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 dotless.Core.Test.Plugins { using System; using System.Collections.Generic; using System.Linq; using System.Text; using Core.Parser.Infrastructure; using Core.Parser.Tree; using Core.Plugins; using NUnit.Framework; using System.Globalization; using System.Threading; public class RtlPluginFixture : SpecFixtureBase { public bool OnlyReversePrefixedRules { get; set; } public void SetCultureTextDirection(bool isRtl) { if (isRtl) { Thread.CurrentThread.CurrentCulture = new CultureInfo("ar-SA"); } else { Thread.CurrentThread.CurrentCulture = new CultureInfo("en-GB"); } } [SetUp] public void Setup() { DefaultEnv = () => { Env env = new Env(null); env.AddPlugin(new RtlPlugin() { OnlyReversePrefixedRules = OnlyReversePrefixedRules}); return env; }; } [Test] public void PropertyRemovalLtr() { OnlyReversePrefixedRules = true; SetCultureTextDirection(false); var input = @" .cl { -rtl-background: black; -ltr-background: red; } "; var expected = @" .cl { background: red; } "; AssertLess(input, expected); } [Test] public void PropertyRemovalRtl() { OnlyReversePrefixedRules = true; SetCultureTextDirection(true); var input = @" .cl { -rtl-background: black; -ltr-background: red; } "; var expected = @" .cl { background: black; } "; AssertLess(input, expected); } [Test] public void PropertyNonRemovalRtl1() { OnlyReversePrefixedRules = true; SetCultureTextDirection(true); var input = @" .cl { -rtl-ltr-background: black; -ltr-rtl-border-color: red; } "; var expected = @" .cl { background: black; border-color: red; } "; AssertLess(input, expected); } [Test] public void PropertyNonRemovalRtl2() { SetCultureTextDirection(true); var input = @" .cl { -rtl-ltr-background: black; -ltr-rtl-border-color: red; } "; var expected = @" .cl { background: black; border-color: red; } "; AssertLess(input, expected); } [Test] public void PropertyRemovalRemoveClass() { OnlyReversePrefixedRules = true; SetCultureTextDirection(false); var input = @" .cl { -rtl-background: black; -rtl-border: 1px; } "; var expected = ""; AssertLess(input, expected); } [Test] public void PropertyNameReversalLtr1() { OnlyReversePrefixedRules = true; SetCultureTextDirection(false); var input = @" .cl { -ltr-reverse-border-width-left: 2px; -ltr-margin-left: 1px; padding-right: 2px; } "; var expected = @" .cl { border-width-right: 2px; margin-left: 1px; padding-right: 2px; } "; AssertLess(input, expected); } [Test] public void PropertyNameReversalLtr2() { OnlyReversePrefixedRules = false; SetCultureTextDirection(false); var input = @" .cl { -ltr-reverse-border-width-left: 2px; -ltr-margin-left: 1px; padding-right: 2px; } "; var expected = @" .cl { border-width-right: 2px; margin-left: 1px; padding-right: 2px; } "; AssertLess(input, expected); } [Test] public void PropertyNameReversalRtl1() { OnlyReversePrefixedRules = true; SetCultureTextDirection(true); var input = @" .cl { -rtl-reverse-border-width-left: 2px; -rtl-margin-left: 1px; padding-right: 2px; } "; var expected = @" .cl { border-width-right: 2px; margin-left: 1px; padding-right: 2px; } "; AssertLess(input, expected); } [Test] public void PropertyNameReversalRtl2() { OnlyReversePrefixedRules = false; SetCultureTextDirection(true); var input = @" .cl { -rtl-reverse-border-width-left: 2px; -rtl-margin-left: 1px; padding-right: 2px; padding-left: 3px; right: 4px; left: 5px; border-left-width: 6px; border-top-width: 7px; } "; var expected = @" .cl { border-width-right: 2px; margin-left: 1px; padding-left: 2px; padding-right: 3px; left: 4px; right: 5px; border-right-width: 6px; border-top-width: 7px; } "; AssertLess(input, expected); } [Test] public void PropertyReversal() { OnlyReversePrefixedRules = false; SetCultureTextDirection(true); var input = @" .cl { padding: 1px 2px; border-width: 1px 2px 3px; border-width: 1px 2px thick 3px; border-width: 1px thick 2px 3px; margin: 1px 2px 3px 4px; float: left; } "; var expected = @" .cl { padding: 1px 2px; border-width: 1px 2px 3px; border-width: 1px 3px thick 2px; border-width: 1px 3px 2px thick; margin: 1px 4px 3px 2px; float: right; } "; AssertLess(input, expected); } [Test] public void PropertyReversalComments() { OnlyReversePrefixedRules = false; SetCultureTextDirection(true); var input = @" .cl { border-width: 1px/**/ /**/2px 3px/**/; border-width: 1px/**/ /**/2px thick 3px/**/; border-width: 1px/**/ thick /**/2px 3px/**/; margin: 1px 2px /**/ 3px 4px; float: /**/left/**/; } "; var expected = @" .cl { border-width: 1px/**//**/ 2px 3px/**/; border-width: 1px/**//**/ 3px/**/ thick 2px; border-width: 1px/**/ 3px/**/ 2px thick/**/; margin: 1px 4px 3px 2px/**/; float: right; } "; AssertLess(input, expected); } [Test] public void FloatWithImportantIsReversed() { var input = @" .test { float: left !important; } "; var expected = @" .test { float: right !important; } "; OnlyReversePrefixedRules = false; SetCultureTextDirection(true); AssertLess(input, expected); } [Test] public void TextAlignIsReversed() { var input = @" .test { text-align: left; } "; var expected = @" .test { text-align: right; } "; OnlyReversePrefixedRules = false; SetCultureTextDirection(true); AssertLess(input, expected); } [Test] public void BorderRadiusIsReversed() { var input = @" .test { border-top-left-radius: 1px; border-top-right-radius: 2px; border-bottom-left-radius: 3px; border-bottom-right-radius: 4px; } "; var expected = @" .test { border-top-right-radius: 1px; border-top-left-radius: 2px; border-bottom-right-radius: 3px; border-bottom-left-radius: 4px; } "; OnlyReversePrefixedRules = false; SetCultureTextDirection(true); AssertLess(input, expected); } [Test] public void PatternMatchingMixinDoesNotCauseException() { var input = @" .theme(""black"") { } .theme(""black""); "; OnlyReversePrefixedRules = false; SetCultureTextDirection(true); AssertLess(input, ""); } [Test] public void DoesNotLoseImportant() { var input = @" .selector { border-width: 1px 2px 3px 4px !important; } "; var expected = @" .selector { border-width: 1px 4px 3px 2px !important; }"; OnlyReversePrefixedRules = false; SetCultureTextDirection(true); AssertLess(input, expected); } } }
19.836538
102
0.52872
[ "Apache-2.0" ]
MultinetInteractive/dotless
tests/dotless.Core.Test/Plugins/RtlPluginFixture.cs
8,254
C#
// Lucene version compatibility level 4.8.1 using Lucene.Net.Index; using Lucene.Net.Queries.Function.DocValues; using Lucene.Net.Search; using Lucene.Net.Util; using System; using System.Collections; using System.IO; namespace Lucene.Net.Queries.Function.ValueSources { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /// <summary> /// Function that returns <see cref="DocsEnum.Freq"/> for the /// supplied term in every document. /// <para/> /// If the term does not exist in the document, returns 0. /// If frequencies are omitted, returns 1. /// </summary> public class TermFreqValueSource : DocFreqValueSource { public TermFreqValueSource(string field, string val, string indexedField, BytesRef indexedBytes) : base(field, val, indexedField, indexedBytes) { } public override string Name => "termfreq"; public override FunctionValues GetValues(IDictionary context, AtomicReaderContext readerContext) { Fields fields = readerContext.AtomicReader.Fields; Terms terms = fields.GetTerms(m_indexedField); return new Int32DocValuesAnonymousClass(this, this, terms); } private class Int32DocValuesAnonymousClass : Int32DocValues { private readonly TermFreqValueSource outerInstance; private readonly Terms terms; public Int32DocValuesAnonymousClass(TermFreqValueSource outerInstance, TermFreqValueSource @this, Terms terms) : base(@this) { this.outerInstance = outerInstance; this.terms = terms; lastDocRequested = -1; Reset(); } private DocsEnum docs; private int atDoc; private int lastDocRequested; public virtual void Reset() { // no one should call us for deleted docs? if (terms != null) { TermsEnum termsEnum = terms.GetEnumerator(); if (termsEnum.SeekExact(outerInstance.m_indexedBytes)) { docs = termsEnum.Docs(null, null); } else { docs = null; } } else { docs = null; } if (docs is null) { docs = new DocsEnumAnonymousClass(); } atDoc = -1; } private class DocsEnumAnonymousClass : DocsEnum { public override int Freq => 0; public override int DocID => DocIdSetIterator.NO_MORE_DOCS; public override int NextDoc() { return DocIdSetIterator.NO_MORE_DOCS; } public override int Advance(int target) { return DocIdSetIterator.NO_MORE_DOCS; } public override long GetCost() { return 0; } } /// <summary> /// NOTE: This was intVal() in Lucene /// </summary> public override int Int32Val(int doc) { try { if (doc < lastDocRequested) { // out-of-order access.... reset Reset(); } lastDocRequested = doc; if (atDoc < doc) { atDoc = docs.Advance(doc); } if (atDoc > doc) { // term doesn't match this document... either because we hit the // end, or because the next doc is after this doc. return 0; } // a match! return docs.Freq; } catch (Exception e) when (e.IsIOException()) { throw RuntimeException.Create("caught exception in function " + outerInstance.GetDescription() + " : doc=" + doc, e); } } } } }
34.373418
138
0.494752
[ "Apache-2.0" ]
10088/lucenenet
src/Lucene.Net.Queries/Function/ValueSources/TermFreqValueSource.cs
5,276
C#
using Microsoft.EntityFrameworkCore.Migrations; #nullable disable namespace mini.api.infrastructure.migrations.miniapi { public partial class MiniApiDbContext_AddedName : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.AddColumn<string>( name: "Name", table: "Items", type: "nvarchar(max)", nullable: false, defaultValue: ""); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropColumn( name: "Name", table: "Items"); } } }
27.111111
72
0.550546
[ "MIT" ]
dsund/miniapi
miniapi/infrastructure/migrations/miniapi/20220210134047_MiniApiDbContext_AddedName.cs
734
C#
// This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. // If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. // Copyright (C) LibreHardwareMonitor and Contributors. // Partial Copyright (C) Michael Möller <mmoeller@openhardwaremonitor.org> and Contributors. // All Rights Reserved. using System; using System.Collections.Generic; using System.Threading; using LibreHardwareMonitor.Hardware.Motherboard.Lpc; namespace LibreHardwareMonitor.Hardware.Motherboard { internal sealed class SuperIOHardware : Hardware { private readonly List<Sensor> _controls = new List<Sensor>(); private readonly List<Sensor> _fans = new List<Sensor>(); private readonly Motherboard _motherboard; private readonly UpdateDelegate _postUpdate; private readonly ReadValueDelegate _readControl; private readonly ReadValueDelegate _readFan; private readonly ReadValueDelegate _readTemperature; private readonly ReadValueDelegate _readVoltage; private readonly ISuperIO _superIO; private readonly List<Sensor> _temperatures = new List<Sensor>(); private readonly List<Sensor> _voltages = new List<Sensor>(); public SuperIOHardware(Motherboard motherboard, ISuperIO superIO, Manufacturer manufacturer, Model model, ISettings settings) : base(ChipName.GetName(superIO.Chip), new Identifier("lpc", superIO.Chip.ToString().ToLowerInvariant()), settings) { _motherboard = motherboard; _superIO = superIO; GetBoardSpecificConfiguration(superIO, manufacturer, model, out IList<Voltage> v, out IList<Temperature> t, out IList<Fan> f, out IList<Ctrl> c, out _readVoltage, out _readTemperature, out _readFan, out _readControl, out _postUpdate, out _); CreateVoltageSensors(superIO, settings, v); CreateTemperatureSensors(superIO, settings, t); CreateFanSensors(superIO, settings, f); CreateControlSensors(superIO, settings, c); } public override HardwareType HardwareType { get { return HardwareType.SuperIO; } } public override IHardware Parent { get { return _motherboard; } } private void CreateControlSensors(ISuperIO superIO, ISettings settings, IList<Ctrl> c) { foreach (Ctrl ctrl in c) { int index = ctrl.Index; if (index < superIO.Controls.Length) { Sensor sensor = new Sensor(ctrl.Name, index, SensorType.Control, this, settings); Control control = new Control(sensor, settings, 0, 100); control.ControlModeChanged += cc => { switch (cc.ControlMode) { case ControlMode.Undefined: { return; } case ControlMode.Default: { superIO.SetControl(index, null); break; } case ControlMode.Software: { superIO.SetControl(index, (byte)(cc.SoftwareValue * 2.55)); break; } default: { return; } } }; control.SoftwareControlValueChanged += cc => { if (cc.ControlMode == ControlMode.Software) superIO.SetControl(index, (byte)(cc.SoftwareValue * 2.55)); }; switch (control.ControlMode) { case ControlMode.Undefined: { break; } case ControlMode.Default: { superIO.SetControl(index, null); break; } case ControlMode.Software: { superIO.SetControl(index, (byte)(control.SoftwareValue * 2.55)); break; } } sensor.Control = control; _controls.Add(sensor); ActivateSensor(sensor); } } } private void CreateFanSensors(ISuperIO superIO, ISettings settings, IList<Fan> f) { foreach (Fan fan in f) { if (fan.Index < superIO.Fans.Length) { Sensor sensor = new Sensor(fan.Name, fan.Index, SensorType.Fan, this, settings); _fans.Add(sensor); } } } private void CreateTemperatureSensors(ISuperIO superIO, ISettings settings, IList<Temperature> t) { foreach (Temperature temperature in t) { if (temperature.Index < superIO.Temperatures.Length) { Sensor sensor = new Sensor(temperature.Name, temperature.Index, SensorType.Temperature, this, new[] { new ParameterDescription("Offset [°C]", "Temperature offset.", 0) }, settings); _temperatures.Add(sensor); } } } private void CreateVoltageSensors(ISuperIO superIO, ISettings settings, IList<Voltage> v) { const string formula = "Voltage = value + (value - Vf) * Ri / Rf."; foreach (Voltage voltage in v) { if (voltage.Index < superIO.Voltages.Length) { Sensor sensor = new Sensor(voltage.Name, voltage.Index, voltage.Hidden, SensorType.Voltage, this, new[] { new ParameterDescription("Ri [kΩ]", "Input resistance.\n" + formula, voltage.Ri), new ParameterDescription("Rf [kΩ]", "Reference resistance.\n" + formula, voltage.Rf), new ParameterDescription("Vf [V]", "Reference voltage.\n" + formula, voltage.Vf) }, settings); _voltages.Add(sensor); } } } private static void GetBoardSpecificConfiguration ( ISuperIO superIO, Manufacturer manufacturer, Model model, out IList<Voltage> v, out IList<Temperature> t, out IList<Fan> f, out IList<Ctrl> c, out ReadValueDelegate readVoltage, out ReadValueDelegate readTemperature, out ReadValueDelegate readFan, out ReadValueDelegate readControl, out UpdateDelegate postUpdate, out Mutex mutex) { readVoltage = index => superIO.Voltages[index]; readTemperature = index => superIO.Temperatures[index]; readFan = index => superIO.Fans[index]; readControl = index => superIO.Controls[index]; postUpdate = () => { }; mutex = null; v = new List<Voltage>(); t = new List<Temperature>(); f = new List<Fan>(); c = new List<Ctrl>(); switch (superIO.Chip) { case Chip.IT8705F: case Chip.IT8712F: case Chip.IT8716F: case Chip.IT8718F: case Chip.IT8720F: case Chip.IT8726F: { GetIteConfigurationsA(superIO, manufacturer, model, v, t, f, c, ref readFan, ref postUpdate, ref mutex); break; } case Chip.IT8620E: { GetIteConfigurationsB(superIO, manufacturer, model, v, t, f, c); break; } case Chip.IT8628E: case Chip.IT8655E: case Chip.IT8665E: case Chip.IT8686E: case Chip.IT8688E: case Chip.IT8689E: case Chip.IT8721F: case Chip.IT8728F: case Chip.IT8771E: case Chip.IT8772E: { GetIteConfigurationsB(superIO, manufacturer, model, v, t, f, c); break; } case Chip.IT879XE: { GetIteConfigurationsC(superIO, manufacturer, model, v, t, f, c); break; } case Chip.F71858: { v.Add(new Voltage("VCC3V", 0, 150, 150)); v.Add(new Voltage("VSB3V", 1, 150, 150)); v.Add(new Voltage("Battery", 2, 150, 150)); for (int i = 0; i < superIO.Temperatures.Length; i++) t.Add(new Temperature("Temperature #" + (i + 1), i)); for (int i = 0; i < superIO.Fans.Length; i++) f.Add(new Fan("Fan #" + (i + 1), i)); break; } case Chip.F71808E: case Chip.F71862: case Chip.F71869: case Chip.F71869A: case Chip.F71882: case Chip.F71889AD: case Chip.F71889ED: case Chip.F71889F: { GetFintekConfiguration(superIO, manufacturer, model, v, t, f, c); break; } case Chip.W83627EHF: { GetWinbondConfigurationEhf(manufacturer, model, v, t, f); break; } case Chip.W83627DHG: case Chip.W83627DHGP: case Chip.W83667HG: case Chip.W83667HGB: { GetWinbondConfigurationHg(manufacturer, model, v, t, f); break; } case Chip.W83627HF: case Chip.W83627THF: case Chip.W83687THF: { v.Add(new Voltage("Vcore", 0)); v.Add(new Voltage("Voltage #2", 1, true)); v.Add(new Voltage("Voltage #3", 2, true)); v.Add(new Voltage("AVCC", 3, 34, 51)); v.Add(new Voltage("Voltage #5", 4, true)); v.Add(new Voltage("+5VSB", 5, 34, 51)); v.Add(new Voltage("VBat", 6)); t.Add(new Temperature("CPU", 0)); t.Add(new Temperature("Auxiliary", 1)); t.Add(new Temperature("System", 2)); f.Add(new Fan("System Fan", 0)); f.Add(new Fan("CPU Fan", 1)); f.Add(new Fan("Auxiliary Fan", 2)); break; } case Chip.NCT6771F: case Chip.NCT6776F: { GetNuvotonConfigurationF(superIO, manufacturer, model, v, t, f, c); break; } case Chip.NCT610XD: { v.Add(new Voltage("Vcore", 0)); v.Add(new Voltage("Voltage #0", 1, true)); v.Add(new Voltage("AVCC", 2, 34, 34)); v.Add(new Voltage("+3.3V", 3, 34, 34)); v.Add(new Voltage("Voltage #1", 4, true)); v.Add(new Voltage("Voltage #2", 5, true)); v.Add(new Voltage("Reserved", 6, true)); v.Add(new Voltage("3VSB", 7, 34, 34)); v.Add(new Voltage("VBat", 8, 34, 34)); v.Add(new Voltage("Voltage #10", 9, true)); t.Add(new Temperature("System", 1)); t.Add(new Temperature("CPU Core", 2)); t.Add(new Temperature("Auxiliary", 3)); for (int i = 0; i < superIO.Fans.Length; i++) f.Add(new Fan("Fan #" + (i + 1), i)); for (int i = 0; i < superIO.Controls.Length; i++) c.Add(new Ctrl("Fan Control #" + (i + 1), i)); break; } case Chip.NCT6779D: case Chip.NCT6791D: case Chip.NCT6792D: case Chip.NCT6792DA: case Chip.NCT6793D: case Chip.NCT6795D: case Chip.NCT6796D: case Chip.NCT6796DR: case Chip.NCT6797D: case Chip.NCT6798D: case Chip.NCT6683D: { GetNuvotonConfigurationD(superIO, manufacturer, model, v, t, f, c); break; } case Chip.NCT6687D: { v.Add(new Voltage("+12V", 0)); v.Add(new Voltage("+5V", 1)); v.Add(new Voltage("Vcore", 2)); v.Add(new Voltage("Voltage #1", 3)); v.Add(new Voltage("DIMM", 4)); v.Add(new Voltage("CPU I/O", 5)); v.Add(new Voltage("CPU SA", 6)); v.Add(new Voltage("Voltage #2", 7)); v.Add(new Voltage("AVCC3", 8)); v.Add(new Voltage("VTT", 9)); v.Add(new Voltage("VRef", 10)); v.Add(new Voltage("VSB", 11)); v.Add(new Voltage("AVSB", 12)); v.Add(new Voltage("VBat", 13)); t.Add(new Temperature("CPU", 0)); t.Add(new Temperature("System", 1)); t.Add(new Temperature("VRM MOS", 2)); t.Add(new Temperature("PCH", 3)); t.Add(new Temperature("CPU Socket", 4)); t.Add(new Temperature("PCIe x1", 5)); t.Add(new Temperature("M2_1", 6)); f.Add(new Fan("CPU Fan", 0)); f.Add(new Fan("Pump Fan", 1)); f.Add(new Fan("System Fan #1", 2)); f.Add(new Fan("System Fan #2", 3)); f.Add(new Fan("System Fan #3", 4)); f.Add(new Fan("System Fan #4", 5)); f.Add(new Fan("System Fan #5", 6)); f.Add(new Fan("System Fan #6", 7)); c.Add(new Ctrl("CPU Fan", 0)); c.Add(new Ctrl("Pump Fan", 1)); c.Add(new Ctrl("System Fan #1", 2)); c.Add(new Ctrl("System Fan #2", 3)); c.Add(new Ctrl("System Fan #3", 4)); c.Add(new Ctrl("System Fan #4", 5)); c.Add(new Ctrl("System Fan #5", 6)); c.Add(new Ctrl("System Fan #6", 7)); break; } default: { GetDefaultConfiguration(superIO, v, t, f, c); break; } } } private static void GetDefaultConfiguration(ISuperIO superIO, ICollection<Voltage> v, ICollection<Temperature> t, ICollection<Fan> f, ICollection<Ctrl> c) { for (int i = 0; i < superIO.Voltages.Length; i++) v.Add(new Voltage("Voltage #" + (i + 1), i, true)); for (int i = 0; i < superIO.Temperatures.Length; i++) t.Add(new Temperature("Temperature #" + (i + 1), i)); for (int i = 0; i < superIO.Fans.Length; i++) f.Add(new Fan("Fan #" + (i + 1), i)); for (int i = 0; i < superIO.Controls.Length; i++) c.Add(new Ctrl("Fan Control #" + (i + 1), i)); } private static void GetIteConfigurationsA ( ISuperIO superIO, Manufacturer manufacturer, Model model, IList<Voltage> v, IList<Temperature> t, IList<Fan> f, ICollection<Ctrl> c, ref ReadValueDelegate readFan, ref UpdateDelegate postUpdate, ref Mutex mutex) { switch (manufacturer) { case Manufacturer.ASUS: { switch (model) { case Model.CROSSHAIR_III_FORMULA: // IT8720F { v.Add(new Voltage("VBat", 8)); t.Add(new Temperature("CPU", 0)); for (int i = 0; i < superIO.Fans.Length; i++) f.Add(new Fan("Fan #" + (i + 1), i)); break; } case Model.M2N_SLI_Deluxe: { v.Add(new Voltage("Vcore", 0)); v.Add(new Voltage("+3.3V", 1)); v.Add(new Voltage("+5V", 3, 6.8f, 10)); v.Add(new Voltage("+12V", 4, 30, 10)); v.Add(new Voltage("+5VSB", 7, 6.8f, 10)); v.Add(new Voltage("VBat", 8)); t.Add(new Temperature("CPU", 0)); t.Add(new Temperature("Motherboard", 1)); f.Add(new Fan("CPU Fan", 0)); f.Add(new Fan("Chassis Fan #1", 1)); f.Add(new Fan("Power Fan", 2)); break; } case Model.M4A79XTD_EVO: // IT8720F { v.Add(new Voltage("+5V", 3, 6.8f, 10)); v.Add(new Voltage("VBat", 8)); t.Add(new Temperature("CPU", 0)); t.Add(new Temperature("Motherboard", 1)); f.Add(new Fan("CPU Fan", 0)); f.Add(new Fan("Chassis Fan #1", 1)); f.Add(new Fan("Chassis Fan #2", 2)); break; } case Model.PRIME_X370_PRO: // IT8665E case Model.TUF_X470_PLUS_GAMING: { v.Add(new Voltage("Vcore", 0)); v.Add(new Voltage("SB 2.5V", 1)); v.Add(new Voltage("+12V", 2, 5, 1)); v.Add(new Voltage("+5V", 3, 1.5f, 1)); v.Add(new Voltage("Voltage #4", 4, true)); v.Add(new Voltage("Voltage #6", 5, true)); v.Add(new Voltage("Voltage #7", 6, true)); v.Add(new Voltage("+3.3V", 7, 10, 10)); v.Add(new Voltage("VBat", 8, 10, 10)); v.Add(new Voltage("Voltage #10", 9, true)); t.Add(new Temperature("CPU", 0)); t.Add(new Temperature("Motherboard", 1)); t.Add(new Temperature("PCH", 2)); for (int i = 3; i < superIO.Temperatures.Length; i++) t.Add(new Temperature("Temperature #" + (i + 1), i)); f.Add(new Fan("CPU Fan", 0)); for (int i = 1; i < superIO.Fans.Length; i++) f.Add(new Fan("Fan #" + (i + 1), i)); break; } case Model.ROG_ZENITH_EXTREME: // IT8665E { v.Add(new Voltage("Vcore", 0, 10, 10)); v.Add(new Voltage("DIMM AB", 1, 10, 10)); v.Add(new Voltage("+12V", 2, 5, 1)); v.Add(new Voltage("+5V", 3, 1.5f, 1)); v.Add(new Voltage("SB 1.05V", 4, 10, 10)); v.Add(new Voltage("DIMM CD", 5, 10, 10)); v.Add(new Voltage("1.8V PLL", 6, 10, 10)); v.Add(new Voltage("+3.3V", 7, 10, 10)); v.Add(new Voltage("VBat", 8, 10, 10)); t.Add(new Temperature("CPU", 0)); t.Add(new Temperature("Motherboard", 1)); t.Add(new Temperature("CPU Socket", 2)); t.Add(new Temperature("Temperature #4", 3)); t.Add(new Temperature("Temperature #5", 4)); t.Add(new Temperature("VRM", 5)); f.Add(new Fan("CPU Fan", 0)); f.Add(new Fan("Chassis Fan #1", 1)); f.Add(new Fan("Chassis Fan #2", 2)); f.Add(new Fan("High Amp Fan", 3)); f.Add(new Fan("Fan 5", 4)); f.Add(new Fan("Fan 6", 5)); for (int i = 0; i < superIO.Controls.Length; i++) c.Add(new Ctrl("Fan Control #" + (i + 1), i)); break; } default: { v.Add(new Voltage("Vcore", 0)); v.Add(new Voltage("Voltage #2", 1, true)); v.Add(new Voltage("Voltage #3", 2, true)); v.Add(new Voltage("Voltage #4", 3, true)); v.Add(new Voltage("Voltage #5", 4, true)); v.Add(new Voltage("Voltage #6", 5, true)); v.Add(new Voltage("Voltage #7", 6, true)); v.Add(new Voltage("Voltage #8", 7, true)); v.Add(new Voltage("VBat", 8)); for (int i = 0; i < superIO.Temperatures.Length; i++) t.Add(new Temperature("Temperature #" + (i + 1), i)); for (int i = 0; i < superIO.Fans.Length; i++) f.Add(new Fan("Fan #" + (i + 1), i)); for (int i = 0; i < superIO.Controls.Length; i++) c.Add(new Ctrl("Fan Control #" + (i + 1), i)); break; } } break; } case Manufacturer.ASRock: { switch (model) { case Model.P55_Deluxe: // IT8720F { GetASRockConfiguration(superIO, v, t, f, ref readFan, ref postUpdate, out mutex); break; } default: { v.Add(new Voltage("Vcore", 0)); v.Add(new Voltage("Voltage #2", 1, true)); v.Add(new Voltage("Voltage #3", 2, true)); v.Add(new Voltage("Voltage #4", 3, true)); v.Add(new Voltage("Voltage #5", 4, true)); v.Add(new Voltage("Voltage #6", 5, true)); v.Add(new Voltage("Voltage #7", 6, true)); v.Add(new Voltage("Voltage #8", 7, true)); v.Add(new Voltage("VBat", 8)); for (int i = 0; i < superIO.Temperatures.Length; i++) t.Add(new Temperature("Temperature #" + (i + 1), i)); for (int i = 0; i < superIO.Fans.Length; i++) f.Add(new Fan("Fan #" + (i + 1), i)); break; } } break; } case Manufacturer.DFI: { switch (model) { case Model.LP_BI_P45_T2RS_Elite: // IT8718F { v.Add(new Voltage("Vcore", 0)); v.Add(new Voltage("VTT", 1)); v.Add(new Voltage("+3.3V", 2)); v.Add(new Voltage("+5V", 3, 6.8f, 10)); v.Add(new Voltage("+12V", 4, 30, 10)); v.Add(new Voltage("NB Core", 5)); v.Add(new Voltage("DIMM", 6)); v.Add(new Voltage("+5VSB", 7, 6.8f, 10)); v.Add(new Voltage("VBat", 8)); t.Add(new Temperature("CPU", 0)); t.Add(new Temperature("System", 1)); t.Add(new Temperature("Chipset", 2)); f.Add(new Fan("Fan #1", 0)); f.Add(new Fan("Fan #2", 1)); f.Add(new Fan("Fan #3", 2)); break; } case Model.LP_DK_P55_T3EH9: // IT8720F { v.Add(new Voltage("Vcore", 0)); v.Add(new Voltage("VTT", 1)); v.Add(new Voltage("+3.3V", 2)); v.Add(new Voltage("+5V", 3, 6.8f, 10)); v.Add(new Voltage("+12V", 4, 30, 10)); v.Add(new Voltage("CPU PLL", 5)); v.Add(new Voltage("DIMM", 6)); v.Add(new Voltage("+5VSB", 7, 6.8f, 10)); v.Add(new Voltage("VBat", 8)); t.Add(new Temperature("Chipset", 0)); t.Add(new Temperature("CPU PWM", 1)); t.Add(new Temperature("CPU", 2)); f.Add(new Fan("Fan #1", 0)); f.Add(new Fan("Fan #2", 1)); f.Add(new Fan("Fan #3", 2)); break; } default: { v.Add(new Voltage("Vcore", 0)); v.Add(new Voltage("VTT", 1, true)); v.Add(new Voltage("+3.3V", 2, true)); v.Add(new Voltage("+5V", 3, 6.8f, 10, 0, true)); v.Add(new Voltage("+12V", 4, 30, 10, 0, true)); v.Add(new Voltage("Voltage #6", 5, true)); v.Add(new Voltage("DIMM", 6, true)); v.Add(new Voltage("+5VSB", 7, 6.8f, 10, 0, true)); v.Add(new Voltage("VBat", 8)); for (int i = 0; i < superIO.Temperatures.Length; i++) t.Add(new Temperature("Temperature #" + (i + 1), i)); for (int i = 0; i < superIO.Fans.Length; i++) f.Add(new Fan("Fan #" + (i + 1), i)); for (int i = 0; i < superIO.Controls.Length; i++) c.Add(new Ctrl("Fan Control #" + (i + 1), i)); break; } } break; } case Manufacturer.Gigabyte: { switch (model) { case Model._965P_S3: // IT8718F { v.Add(new Voltage("Vcore", 0)); v.Add(new Voltage("DIMM", 1)); v.Add(new Voltage("+3.3V", 2)); v.Add(new Voltage("+5V", 3, 6.8f, 10)); v.Add(new Voltage("+12V", 7, 24.3f, 8.2f)); v.Add(new Voltage("VBat", 8)); t.Add(new Temperature("System", 0)); t.Add(new Temperature("CPU", 1)); f.Add(new Fan("CPU Fan", 0)); f.Add(new Fan("System Fan", 1)); break; } case Model.EP45_DS3R: // IT8718F case Model.EP45_UD3R: case Model.X38_DS5: { v.Add(new Voltage("Vcore", 0)); v.Add(new Voltage("DIMM", 1)); v.Add(new Voltage("+3.3V", 2)); v.Add(new Voltage("+5V", 3, 6.8f, 10)); v.Add(new Voltage("+12V", 7, 24.3f, 8.2f)); v.Add(new Voltage("VBat", 8)); t.Add(new Temperature("System", 0)); t.Add(new Temperature("CPU", 1)); f.Add(new Fan("CPU Fan", 0)); f.Add(new Fan("System Fan #2", 1)); f.Add(new Fan("Power Fan", 2)); f.Add(new Fan("System Fan #1", 3)); break; } case Model.EX58_EXTREME: // IT8720F { v.Add(new Voltage("Vcore", 0)); v.Add(new Voltage("DIMM", 1)); v.Add(new Voltage("+5V", 3, 6.8f, 10)); v.Add(new Voltage("VBat", 8)); t.Add(new Temperature("System", 0)); t.Add(new Temperature("CPU", 1)); t.Add(new Temperature("Northbridge", 2)); f.Add(new Fan("CPU Fan", 0)); f.Add(new Fan("System Fan #2", 1)); f.Add(new Fan("Power Fan", 2)); f.Add(new Fan("System Fan #1", 3)); break; } case Model.P35_DS3: // IT8718F case Model.P35_DS3L: // IT8718F { v.Add(new Voltage("Vcore", 0)); v.Add(new Voltage("DIMM", 1)); v.Add(new Voltage("+3.3V", 2)); v.Add(new Voltage("+5V", 3, 6.8f, 10)); v.Add(new Voltage("+12V", 7, 24.3f, 8.2f)); v.Add(new Voltage("VBat", 8)); t.Add(new Temperature("System", 0)); t.Add(new Temperature("CPU", 1)); f.Add(new Fan("CPU Fan", 0)); f.Add(new Fan("System Fan #1", 1)); f.Add(new Fan("System Fan #2", 2)); f.Add(new Fan("Power Fan", 3)); break; } case Model.P55_UD4: // IT8720F case Model.P55A_UD3: // IT8720F case Model.P55M_UD4: // IT8720F case Model.H55_USB3: // IT8720F case Model.EX58_UD3R: // IT8720F { v.Add(new Voltage("Vcore", 0)); v.Add(new Voltage("DIMM", 1)); v.Add(new Voltage("+3.3V", 2)); v.Add(new Voltage("+5V", 3, 6.8f, 10)); v.Add(new Voltage("+12V", 5, 24.3f, 8.2f)); v.Add(new Voltage("VBat", 8)); t.Add(new Temperature("System", 0)); t.Add(new Temperature("CPU", 2)); f.Add(new Fan("CPU Fan", 0)); f.Add(new Fan("System Fan #2", 1)); f.Add(new Fan("Power Fan", 2)); f.Add(new Fan("System Fan #1", 3)); break; } case Model.H55N_USB3: // IT8720F { v.Add(new Voltage("Vcore", 0)); v.Add(new Voltage("DIMM", 1)); v.Add(new Voltage("+3.3V", 2)); v.Add(new Voltage("+5V", 3, 6.8f, 10)); v.Add(new Voltage("+12V", 5, 24.3f, 8.2f)); v.Add(new Voltage("VBat", 8)); t.Add(new Temperature("System", 0)); t.Add(new Temperature("CPU", 2)); f.Add(new Fan("CPU Fan", 0)); f.Add(new Fan("System Fan", 1)); break; } case Model.G41M_COMBO: // IT8718F case Model.G41MT_S2: // IT8718F case Model.G41MT_S2P: // IT8718F { v.Add(new Voltage("Vcore", 0)); v.Add(new Voltage("DIMM", 1)); v.Add(new Voltage("+3.3V", 2)); v.Add(new Voltage("+5V", 3, 6.8f, 10)); v.Add(new Voltage("+12V", 7, 24.3f, 8.2f)); v.Add(new Voltage("VBat", 8)); t.Add(new Temperature("CPU", 2)); f.Add(new Fan("CPU Fan", 0)); f.Add(new Fan("System Fan", 1)); break; } case Model._970A_UD3: // IT8720F { v.Add(new Voltage("Vcore", 0)); v.Add(new Voltage("DIMM", 1)); v.Add(new Voltage("+3.3V", 2)); v.Add(new Voltage("+5V", 3, 6.8f, 10)); v.Add(new Voltage("+12V", 4, 24.3f, 8.2f)); v.Add(new Voltage("VBat", 8)); t.Add(new Temperature("System", 0)); t.Add(new Temperature("CPU", 1)); f.Add(new Fan("CPU Fan", 0)); f.Add(new Fan("System Fan #1", 1)); f.Add(new Fan("System Fan #2", 2)); f.Add(new Fan("Power Fan", 4)); c.Add(new Ctrl("PWM #1", 0)); c.Add(new Ctrl("PWM #2", 1)); c.Add(new Ctrl("PWM #3", 2)); break; } case Model.MA770T_UD3: // IT8720F case Model.MA770T_UD3P: // IT8720F case Model.MA790X_UD3P: // IT8720F { v.Add(new Voltage("Vcore", 0)); v.Add(new Voltage("DIMM", 1)); v.Add(new Voltage("+3.3V", 2)); v.Add(new Voltage("+5V", 3, 6.8f, 10)); v.Add(new Voltage("+12V", 4, 24.3f, 8.2f)); v.Add(new Voltage("VBat", 8)); t.Add(new Temperature("System", 0)); t.Add(new Temperature("CPU", 1)); f.Add(new Fan("CPU Fan", 0)); f.Add(new Fan("System Fan #1", 1)); f.Add(new Fan("System Fan #2", 2)); f.Add(new Fan("Power Fan", 3)); break; } case Model.MA78LM_S2H: // IT8718F { v.Add(new Voltage("Vcore", 0)); v.Add(new Voltage("DIMM", 1)); v.Add(new Voltage("+3.3V", 2)); v.Add(new Voltage("+5V", 3, 6.8f, 10)); v.Add(new Voltage("+12V", 4, 24.3f, 8.2f)); v.Add(new Voltage("VBat", 8)); t.Add(new Temperature("System", 0)); t.Add(new Temperature("CPU", 1)); t.Add(new Temperature("VRM", 2)); f.Add(new Fan("CPU Fan", 0)); f.Add(new Fan("System Fan #1", 1)); f.Add(new Fan("System Fan #2", 2)); f.Add(new Fan("Power Fan", 3)); break; } case Model.MA785GM_US2H: // IT8718F case Model.MA785GMT_UD2H: // IT8718F { v.Add(new Voltage("Vcore", 0)); v.Add(new Voltage("DIMM", 1)); v.Add(new Voltage("+3.3V", 2)); v.Add(new Voltage("+5V", 3, 6.8f, 10)); v.Add(new Voltage("+12V", 4, 24.3f, 8.2f)); v.Add(new Voltage("VBat", 8)); t.Add(new Temperature("System", 0)); t.Add(new Temperature("CPU", 1)); f.Add(new Fan("CPU Fan", 0)); f.Add(new Fan("System Fan", 1)); f.Add(new Fan("NB Fan", 2)); break; } case Model.X58A_UD3R: // IT8720F { v.Add(new Voltage("Vcore", 0)); v.Add(new Voltage("DIMM", 1)); v.Add(new Voltage("+3.3V", 2)); v.Add(new Voltage("+5V", 3, 6.8f, 10)); v.Add(new Voltage("+12V", 5, 24.3f, 8.2f)); v.Add(new Voltage("VBat", 8)); t.Add(new Temperature("System", 0)); t.Add(new Temperature("CPU", 1)); t.Add(new Temperature("Northbridge", 2)); f.Add(new Fan("CPU Fan", 0)); f.Add(new Fan("System Fan #2", 1)); f.Add(new Fan("Power Fan", 2)); f.Add(new Fan("System Fan #1", 3)); break; } default: { v.Add(new Voltage("Vcore", 0)); v.Add(new Voltage("DIMM", 1, true)); v.Add(new Voltage("+3.3V", 2, true)); v.Add(new Voltage("+5V", 3, 6.8f, 10, 0, true)); v.Add(new Voltage("Voltage #5", 4, true)); v.Add(new Voltage("Voltage #6", 5, true)); v.Add(new Voltage("Voltage #7", 6, true)); v.Add(new Voltage("Voltage #8", 7, true)); v.Add(new Voltage("VBat", 8)); for (int i = 0; i < superIO.Temperatures.Length; i++) t.Add(new Temperature("Temperature #" + (i + 1), i)); for (int i = 0; i < superIO.Fans.Length; i++) f.Add(new Fan("Fan #" + (i + 1), i)); for (int i = 0; i < superIO.Controls.Length; i++) c.Add(new Ctrl("Fan Control #" + (i + 1), i)); break; } } break; } default: { v.Add(new Voltage("Vcore", 0)); v.Add(new Voltage("Voltage #2", 1, true)); v.Add(new Voltage("Voltage #3", 2, true)); v.Add(new Voltage("Voltage #4", 3, true)); v.Add(new Voltage("Voltage #5", 4, true)); v.Add(new Voltage("Voltage #6", 5, true)); v.Add(new Voltage("Voltage #7", 6, true)); v.Add(new Voltage("Voltage #8", 7, true)); v.Add(new Voltage("VBat", 8)); for (int i = 0; i < superIO.Temperatures.Length; i++) t.Add(new Temperature("Temperature #" + (i + 1), i)); for (int i = 0; i < superIO.Fans.Length; i++) f.Add(new Fan("Fan #" + (i + 1), i)); for (int i = 0; i < superIO.Controls.Length; i++) c.Add(new Ctrl("Fan Control #" + (i + 1), i)); break; } } } private static void GetASRockConfiguration ( ISuperIO superIO, IList<Voltage> v, IList<Temperature> t, IList<Fan> f, ref ReadValueDelegate readFan, ref UpdateDelegate postUpdate, out Mutex mutex) { v.Add(new Voltage("Vcore", 0)); v.Add(new Voltage("+3.3V", 2)); v.Add(new Voltage("+12V", 4, 30, 10)); v.Add(new Voltage("+5V", 5, 6.8f, 10)); v.Add(new Voltage("VBat", 8)); t.Add(new Temperature("CPU", 0)); t.Add(new Temperature("Motherboard", 1)); f.Add(new Fan("CPU Fan", 0)); f.Add(new Fan("Chassis Fan #1", 1)); // this mutex is also used by the official ASRock tool mutex = new Mutex(false, "ASRockOCMark"); bool exclusiveAccess = false; try { exclusiveAccess = mutex.WaitOne(10, false); } catch (AbandonedMutexException) { } catch (InvalidOperationException) { } // only read additional fans if we get exclusive access if (exclusiveAccess) { f.Add(new Fan("Chassis Fan #2", 2)); f.Add(new Fan("Chassis Fan #3", 3)); f.Add(new Fan("Power Fan", 4)); readFan = index => { if (index < 2) { return superIO.Fans[index]; } // get GPIO 80-87 byte? gpio = superIO.ReadGpio(7); if (!gpio.HasValue) return null; // read the last 3 fans based on GPIO 83-85 int[] masks = { 0x05, 0x03, 0x06 }; return ((gpio.Value >> 3) & 0x07) == masks[index - 2] ? superIO.Fans[2] : null; }; int fanIndex = 0; postUpdate = () => { // get GPIO 80-87 byte? gpio = superIO.ReadGpio(7); if (!gpio.HasValue) return; // prepare the GPIO 83-85 for the next update int[] masks = { 0x05, 0x03, 0x06 }; superIO.WriteGpio(7, (byte)((gpio.Value & 0xC7) | (masks[fanIndex] << 3))); fanIndex = (fanIndex + 1) % 3; }; } } private static void GetIteConfigurationsB(ISuperIO superIO, Manufacturer manufacturer, Model model, IList<Voltage> v, IList<Temperature> t, IList<Fan> f, IList<Ctrl> c) { switch (manufacturer) { case Manufacturer.ASUS: { switch (model) { case Model.ROG_STRIX_X470_I: // IT8665E { v.Add(new Voltage("Vcore", 0)); v.Add(new Voltage("SB 2.5V", 1)); v.Add(new Voltage("+12V", 2, 5, 1)); v.Add(new Voltage("+5V", 3, 1.5f, 1)); v.Add(new Voltage("+3.3V", 7, 10, 10)); v.Add(new Voltage("VBat", 8, 10, 10)); t.Add(new Temperature("CPU", 0)); t.Add(new Temperature("Motherboard", 1)); t.Add(new Temperature("T_Sensor", 2)); t.Add(new Temperature("PCIe x16", 3)); t.Add(new Temperature("VRM", 4)); t.Add(new Temperature("Temperature #6", 5)); f.Add(new Fan("CPU Fan", 0)); //Does not work when in AIO pump mode (shows 0). I don't know how to fix it. f.Add(new Fan("Chassis Fan #1", 1)); f.Add(new Fan("Chassis Fan #2", 2)); //offset: 2, because the first two always show zero for (int i = 2; i < superIO.Controls.Length; i++) c.Add(new Ctrl("Fan Control #" + (i - 1), i)); break; } default: { v.Add(new Voltage("Vcore", 0)); v.Add(new Voltage("Voltage #2", 1, true)); v.Add(new Voltage("Voltage #3", 2, true)); v.Add(new Voltage("Voltage #4", 3, true)); v.Add(new Voltage("Voltage #5", 4, true)); v.Add(new Voltage("Voltage #6", 5, true)); v.Add(new Voltage("Voltage #7", 6, true)); v.Add(new Voltage("Voltage #8", 7, true)); v.Add(new Voltage("VBat", 8)); for (int i = 0; i < superIO.Temperatures.Length; i++) t.Add(new Temperature("Temperature #" + (i + 1), i)); for (int i = 0; i < superIO.Fans.Length; i++) f.Add(new Fan("Fan #" + (i + 1), i)); for (int i = 0; i < superIO.Controls.Length; i++) c.Add(new Ctrl("Fan Control #" + (i + 1), i)); break; } } break; } case Manufacturer.ECS: { switch (model) { case Model.A890GXM_A: // IT8721F { v.Add(new Voltage("Vcore", 0)); v.Add(new Voltage("DIMM", 1)); v.Add(new Voltage("NB Voltage", 2)); v.Add(new Voltage("AVCC", 3, 10, 10)); // v.Add(new Voltage("DIMM", 6, true)); v.Add(new Voltage("3VSB", 7, 10, 10)); v.Add(new Voltage("VBat", 8, 10, 10)); t.Add(new Temperature("CPU", 0)); t.Add(new Temperature("System", 1)); t.Add(new Temperature("Northbridge", 2)); f.Add(new Fan("CPU Fan", 0)); f.Add(new Fan("System Fan", 1)); f.Add(new Fan("Power Fan", 2)); break; } default: { v.Add(new Voltage("Voltage #1", 0, true)); v.Add(new Voltage("Voltage #2", 1, true)); v.Add(new Voltage("Voltage #3", 2, true)); v.Add(new Voltage("AVCC", 3, 10, 10, 0, true)); v.Add(new Voltage("Voltage #5", 4, true)); v.Add(new Voltage("Voltage #6", 5, true)); v.Add(new Voltage("Voltage #7", 6, true)); v.Add(new Voltage("3VSB", 7, 10, 10, 0, true)); v.Add(new Voltage("VBat", 8, 10, 10)); for (int i = 0; i < superIO.Temperatures.Length; i++) t.Add(new Temperature("Temperature #" + (i + 1), i)); for (int i = 0; i < superIO.Fans.Length; i++) f.Add(new Fan("Fan #" + (i + 1), i)); for (int i = 0; i < superIO.Controls.Length; i++) c.Add(new Ctrl("Fan Control #" + (i + 1), i)); break; } } break; } case Manufacturer.Gigabyte: { switch (model) { case Model.H61M_DS2_REV_1_2: // IT8728F case Model.H61M_USB3_B3_REV_2_0: // IT8728F { v.Add(new Voltage("VTT", 0)); v.Add(new Voltage("+12V", 2, 30.9f, 10)); v.Add(new Voltage("Vcore", 5)); v.Add(new Voltage("DIMM", 6)); v.Add(new Voltage("3VSB", 7, 10, 10)); v.Add(new Voltage("VBat", 8, 10, 10)); t.Add(new Temperature("System", 0)); t.Add(new Temperature("CPU", 2)); f.Add(new Fan("CPU Fan", 0)); f.Add(new Fan("System Fan", 1)); break; } case Model.H67A_UD3H_B3: // IT8728F case Model.H67A_USB3_B3: // IT8728F { v.Add(new Voltage("VTT", 0)); v.Add(new Voltage("+5V", 1, 15, 10)); v.Add(new Voltage("+12V", 2, 30.9f, 10)); v.Add(new Voltage("Vcore", 5)); v.Add(new Voltage("DIMM", 6)); v.Add(new Voltage("3VSB", 7, 10, 10)); v.Add(new Voltage("VBat", 8, 10, 10)); t.Add(new Temperature("System", 0)); t.Add(new Temperature("CPU", 2)); f.Add(new Fan("CPU Fan", 0)); f.Add(new Fan("System Fan #1", 1)); f.Add(new Fan("Power Fan", 2)); f.Add(new Fan("System Fan #2", 3)); break; } case Model.H81M_HD3: //IT8620E { v.Add(new Voltage("Vcore", 0)); v.Add(new Voltage("Voltage #2", 1, true)); v.Add(new Voltage("Voltage #3", 2, true)); v.Add(new Voltage("Voltage #4", 3, true)); v.Add(new Voltage("iGPU", 4)); v.Add(new Voltage("CPU VRIN", 5)); v.Add(new Voltage("DIMM", 6)); v.Add(new Voltage("3VSB", 7, 10, 10)); v.Add(new Voltage("VBat", 8, 10, 10)); t.Add(new Temperature("CPU", 2)); t.Add(new Temperature("System", 0)); f.Add(new Fan("CPU Fan", 0)); f.Add(new Fan("System Fan", 1)); c.Add(new Ctrl("CPU Fan", 0)); c.Add(new Ctrl("System Fan", 1)); break; } case Model.AX370_Gaming_K7: // IT8686E case Model.AX370_Gaming_5: case Model.AB350_Gaming_3: // IT8686E { // Note: v3.3, v12, v5, and AVCC3 might be slightly off. v.Add(new Voltage("Vcore", 0)); v.Add(new Voltage("+3.3V", 1, 0.65f, 1)); v.Add(new Voltage("+12V", 2, 5, 1)); v.Add(new Voltage("+5V", 3, 1.5f, 1)); v.Add(new Voltage("VSOC", 4)); v.Add(new Voltage("VDDP", 5)); v.Add(new Voltage("DIMM", 6)); v.Add(new Voltage("3VSB", 7, 10, 10)); v.Add(new Voltage("VBat", 8, 10, 10)); v.Add(new Voltage("AVCC3", 9, 7.53f, 1)); t.Add(new Temperature("System", 0)); t.Add(new Temperature("Chipset", 1)); t.Add(new Temperature("CPU", 2)); t.Add(new Temperature("PCIe x16", 3)); t.Add(new Temperature("VRM MOS", 4)); for (int i = 0; i < superIO.Fans.Length; i++) f.Add(new Fan("Fan #" + (i + 1), i)); break; } case Model.X399_AORUS_Gaming_7: // ITE IT8686E { v.Add(new Voltage("Vcore", 0, 0, 1)); v.Add(new Voltage("+3.3V", 1, 6.5F, 10)); v.Add(new Voltage("+12V", 2, 5, 1)); v.Add(new Voltage("+5V", 3, 1.5F, 1)); v.Add(new Voltage("DIMM CD", 4, 0, 1)); v.Add(new Voltage("Vcore SoC", 5, 0, 1)); v.Add(new Voltage("DIMM AB", 6, 0, 1)); v.Add(new Voltage("3VSB", 7, 10, 10)); v.Add(new Voltage("VBat", 8, 10, 10)); v.Add(new Voltage("AVCC3", 9, 54, 10)); t.Add(new Temperature("System #1", 0)); t.Add(new Temperature("Chipset", 1)); t.Add(new Temperature("CPU", 2)); t.Add(new Temperature("PCIe x16", 3)); t.Add(new Temperature("VRM", 4)); for (int i = 0; i < superIO.Fans.Length; i++) f.Add(new Fan("Fan #" + (i + 1), i)); for (int i = 0; i < superIO.Controls.Length; i++) c.Add(new Ctrl("Fan Control #" + (i + 1), i)); break; } case Model.X470_AORUS_GAMING_7_WIFI: // ITE IT8686E { v.Add(new Voltage("Vcore", 0, 0, 1)); v.Add(new Voltage("+3.3V", 1, 6.5F, 10)); v.Add(new Voltage("+12V", 2, 5, 1)); v.Add(new Voltage("+5V", 3, 1.5F, 1)); v.Add(new Voltage("Vcore SoC", 4, 0, 1)); v.Add(new Voltage("VDDP", 5, 0, 1)); v.Add(new Voltage("DIMM AB", 6, 0, 1)); v.Add(new Voltage("3VSB", 7, 10, 10)); v.Add(new Voltage("VBat", 8, 10, 10)); v.Add(new Voltage("AVCC3", 9, 54, 10)); t.Add(new Temperature("System #1", 0)); t.Add(new Temperature("Chipset", 1)); t.Add(new Temperature("CPU", 2)); t.Add(new Temperature("PCIe x16", 3)); t.Add(new Temperature("VRM", 4)); for (int i = 0; i < superIO.Fans.Length; i++) f.Add(new Fan("Fan #" + (i + 1), i)); for (int i = 0; i < superIO.Controls.Length; i++) c.Add(new Ctrl("Fan Control #" + (i + 1), i)); break; } case Model.B560M_AORUS_ELITE: // IT8689E { v.Add(new Voltage("Vcore", 0)); v.Add(new Voltage("+3.3V", 1, 29.4f, 45.3f)); v.Add(new Voltage("+12V", 2, 10f, 2f)); v.Add(new Voltage("+5V", 3, 15f, 10f)); v.Add(new Voltage("iGPU VAGX", 4)); v.Add(new Voltage("VCCSA", 5)); v.Add(new Voltage("DRAM", 6)); v.Add(new Voltage("3VSB", 7, 10f, 10f)); v.Add(new Voltage("VBat", 8, 10f, 10f)); v.Add(new Voltage("AVCC3", 9, 59.9f, 9.8f)); t.Add(new Temperature("System #1", 0)); t.Add(new Temperature("PCH", 1)); t.Add(new Temperature("CPU", 2)); t.Add(new Temperature("PCIe x16", 3)); t.Add(new Temperature("VRM MOS", 4)); t.Add(new Temperature("System #2", 5)); f.Add(new Fan("CPU Fan", 0)); f.Add(new Fan("System Fan #1", 1)); f.Add(new Fan("System Fan #2", 2)); f.Add(new Fan("System Fan #3", 3)); f.Add(new Fan("CPU OPT Fan", 4)); c.Add(new Ctrl("CPU Fan", 0)); c.Add(new Ctrl("System Fan #1", 1)); c.Add(new Ctrl("System Fan #2", 2)); c.Add(new Ctrl("System Fan #3", 3)); c.Add(new Ctrl("CPU OPT Fan", 4)); break; } case Model.X570_AORUS_MASTER: // IT8688E { v.Add(new Voltage("Vcore", 0)); v.Add(new Voltage("+3.3V", 1, 29.4f, 45.3f)); v.Add(new Voltage("+12V", 2, 10f, 2f)); v.Add(new Voltage("+5V", 3, 15f, 10f)); v.Add(new Voltage("Vcore SoC", 4)); v.Add(new Voltage("VDDP", 5)); v.Add(new Voltage("DIMM AB", 6)); v.Add(new Voltage("3VSB", 7, 1f, 10f)); v.Add(new Voltage("VBat", 8, 1f, 10f)); t.Add(new Temperature("System #1", 0)); t.Add(new Temperature("EC_TEMP1", 1)); t.Add(new Temperature("CPU", 2)); t.Add(new Temperature("PCIe x16", 3)); t.Add(new Temperature("VRM MOS", 4)); t.Add(new Temperature("PCH", 5)); f.Add(new Fan("CPU Fan", 0)); f.Add(new Fan("System Fan #1", 1)); f.Add(new Fan("System Fan #2", 2)); f.Add(new Fan("PCH Fan", 3)); f.Add(new Fan("CPU OPT Fan", 4)); c.Add(new Ctrl("CPU Fan", 0)); c.Add(new Ctrl("System Fan #1", 1)); c.Add(new Ctrl("System Fan #2", 2)); c.Add(new Ctrl("PCH Fan", 3)); c.Add(new Ctrl("CPU OPT Fan", 4)); break; } case Model.Z390_M_GAMING: // IT8688E case Model.Z390_AORUS_ULTRA: case Model.Z390_UD: { v.Add(new Voltage("Vcore", 0)); v.Add(new Voltage("+3.3V", 1, 6.49f, 10)); v.Add(new Voltage("+12V", 2, 5f, 1)); v.Add(new Voltage("+5V", 3, 1.5f, 1)); v.Add(new Voltage("CPU VCCGT", 4)); v.Add(new Voltage("CPU VCCSA", 5)); v.Add(new Voltage("VDDQ", 6)); v.Add(new Voltage("DDRVTT", 7)); v.Add(new Voltage("PCHCore", 8)); v.Add(new Voltage("CPU VCCIO", 9)); v.Add(new Voltage("DDRVPP", 10)); t.Add(new Temperature("System #1", 0)); t.Add(new Temperature("PCH", 1)); t.Add(new Temperature("CPU", 2)); t.Add(new Temperature("PCIe x16", 3)); t.Add(new Temperature("VRM MOS", 4)); t.Add(new Temperature("System #2", 5)); f.Add(new Fan("CPU Fan", 0)); f.Add(new Fan("System Fan #1", 1)); f.Add(new Fan("System Fan #2", 2)); f.Add(new Fan("System Fan #3", 3)); c.Add(new Ctrl("CPU Fan", 0)); c.Add(new Ctrl("System Fan #1", 1)); c.Add(new Ctrl("System Fan #2", 2)); c.Add(new Ctrl("System Fan #3", 3)); break; } case Model.Z68A_D3H_B3: // IT8728F { v.Add(new Voltage("VTT", 0)); v.Add(new Voltage("+3.3V", 1, 6.49f, 10)); v.Add(new Voltage("+12V", 2, 30.9f, 10)); v.Add(new Voltage("+5V", 3, 7.15f, 10)); v.Add(new Voltage("Vcore", 5)); v.Add(new Voltage("DIMM", 6)); v.Add(new Voltage("3VSB", 7, 10, 10)); v.Add(new Voltage("VBat", 8, 10, 10)); t.Add(new Temperature("System", 0)); t.Add(new Temperature("CPU", 2)); f.Add(new Fan("CPU Fan", 0)); f.Add(new Fan("System Fan #1", 1)); f.Add(new Fan("Power Fan", 2)); f.Add(new Fan("System Fan #2", 3)); break; } case Model.P67A_UD3_B3: // IT8728F case Model.P67A_UD3R_B3: // IT8728F case Model.P67A_UD4_B3: // IT8728F case Model.Z68AP_D3: // IT8728F case Model.Z68X_UD3H_B3: // IT8728F case Model.Z68XP_UD3R: // IT8728F { v.Add(new Voltage("VTT", 0)); v.Add(new Voltage("+3.3V", 1, 6.49f, 10)); v.Add(new Voltage("+12V", 2, 30.9f, 10)); v.Add(new Voltage("+5V", 3, 7.15f, 10)); v.Add(new Voltage("Vcore", 5)); v.Add(new Voltage("DIMM", 6)); v.Add(new Voltage("3VSB", 7, 10, 10)); v.Add(new Voltage("VBat", 8, 10, 10)); t.Add(new Temperature("System", 0)); t.Add(new Temperature("CPU", 2)); f.Add(new Fan("CPU Fan", 0)); f.Add(new Fan("System Fan #2", 1)); f.Add(new Fan("Power Fan", 2)); f.Add(new Fan("System Fan #1", 3)); break; } case Model.Z68X_UD7_B3: // IT8728F { v.Add(new Voltage("VTT", 0)); v.Add(new Voltage("+3.3V", 1, 6.49f, 10)); v.Add(new Voltage("+12V", 2, 30.9f, 10)); v.Add(new Voltage("+5V", 3, 7.15f, 10)); v.Add(new Voltage("Vcore", 5)); v.Add(new Voltage("DIMM", 6)); v.Add(new Voltage("3VSB", 7, 10, 10)); v.Add(new Voltage("VBat", 8, 10, 10)); t.Add(new Temperature("System", 0)); t.Add(new Temperature("CPU", 1)); t.Add(new Temperature("System #3", 2)); f.Add(new Fan("CPU Fan", 0)); f.Add(new Fan("Power Fan", 1)); f.Add(new Fan("System Fan #1", 2)); f.Add(new Fan("System Fan #2", 3)); f.Add(new Fan("System Fan #3", 4)); break; } case Model.X79_UD3: // IT8728F { v.Add(new Voltage("VTT", 0)); v.Add(new Voltage("DIMM AB", 1)); v.Add(new Voltage("+12V", 2, 10, 2)); v.Add(new Voltage("+5V", 3, 15, 10)); v.Add(new Voltage("VIN4", 4)); v.Add(new Voltage("VCore", 5)); v.Add(new Voltage("DIMM CD", 6)); v.Add(new Voltage("+3V Standby", 7, 1, 1)); v.Add(new Voltage("VBat", 8, 1, 1)); t.Add(new Temperature("System", 0)); t.Add(new Temperature("CPU", 1)); t.Add(new Temperature("Northbridge", 2)); f.Add(new Fan("CPU Fan", 0)); f.Add(new Fan("System Fan #1", 1)); f.Add(new Fan("System Fan #2", 2)); f.Add(new Fan("System Fan #3", 3)); break; } default: { v.Add(new Voltage("Voltage #1", 0, true)); v.Add(new Voltage("Voltage #2", 1, true)); v.Add(new Voltage("Voltage #3", 2, true)); v.Add(new Voltage("Voltage #4", 3, true)); v.Add(new Voltage("Voltage #5", 4, true)); v.Add(new Voltage("Voltage #6", 5, true)); v.Add(new Voltage("Voltage #7", 6, true)); v.Add(new Voltage("3VSB", 7, 10, 10, 0, true)); v.Add(new Voltage("VBat", 8, 10, 10)); for (int i = 0; i < superIO.Temperatures.Length; i++) t.Add(new Temperature("Temperature #" + (i + 1), i)); for (int i = 0; i < superIO.Fans.Length; i++) f.Add(new Fan("Fan #" + (i + 1), i)); for (int i = 0; i < superIO.Controls.Length; i++) c.Add(new Ctrl("Fan Control #" + (i + 1), i)); break; } } break; } case Manufacturer.Shuttle: { switch (model) { case Model.FH67: // IT8772E { v.Add(new Voltage("Vcore", 0)); v.Add(new Voltage("DIMM", 1)); v.Add(new Voltage("PCH VCCIO", 2)); v.Add(new Voltage("CPU VCCIO", 3)); v.Add(new Voltage("Graphic Voltage", 4)); v.Add(new Voltage("3VSB", 7, 10, 10)); v.Add(new Voltage("VBat", 8, 10, 10)); t.Add(new Temperature("System", 0)); t.Add(new Temperature("CPU", 1)); f.Add(new Fan("Fan #1", 0)); f.Add(new Fan("CPU Fan", 1)); break; } default: { v.Add(new Voltage("Voltage #1", 0, true)); v.Add(new Voltage("Voltage #2", 1, true)); v.Add(new Voltage("Voltage #3", 2, true)); v.Add(new Voltage("Voltage #4", 3, true)); v.Add(new Voltage("Voltage #5", 4, true)); v.Add(new Voltage("Voltage #6", 5, true)); v.Add(new Voltage("Voltage #7", 6, true)); v.Add(new Voltage("3VSB", 7, 10, 10, 0, true)); v.Add(new Voltage("VBat", 8, 10, 10)); for (int i = 0; i < superIO.Temperatures.Length; i++) t.Add(new Temperature("Temperature #" + (i + 1), i)); for (int i = 0; i < superIO.Fans.Length; i++) f.Add(new Fan("Fan #" + (i + 1), i)); for (int i = 0; i < superIO.Controls.Length; i++) c.Add(new Ctrl("Fan Control #" + (i + 1), i)); break; } } break; } default: { v.Add(new Voltage("Voltage #1", 0, true)); v.Add(new Voltage("Voltage #2", 1, true)); v.Add(new Voltage("Voltage #3", 2, true)); v.Add(new Voltage("Voltage #4", 3, true)); v.Add(new Voltage("Voltage #5", 4, true)); v.Add(new Voltage("Voltage #6", 5, true)); v.Add(new Voltage("Voltage #7", 6, true)); v.Add(new Voltage("3VSB", 7, 10, 10, 0, true)); v.Add(new Voltage("VBat", 8, 10, 10)); for (int i = 0; i < superIO.Temperatures.Length; i++) t.Add(new Temperature("Temperature #" + (i + 1), i)); for (int i = 0; i < superIO.Fans.Length; i++) f.Add(new Fan("Fan #" + (i + 1), i)); for (int i = 0; i < superIO.Controls.Length; i++) c.Add(new Ctrl("Fan Control #" + (i + 1), i)); break; } } } private static void GetIteConfigurationsC(ISuperIO superIO, Manufacturer manufacturer, Model model, IList<Voltage> v, IList<Temperature> t, IList<Fan> f, IList<Ctrl> c) { switch (manufacturer) { case Manufacturer.Gigabyte: { switch (model) { case Model.X570_AORUS_MASTER: // IT879XE { v.Add(new Voltage("CPU VDD18", 0)); v.Add(new Voltage("DDRVTT AB", 1)); v.Add(new Voltage("Chipset Core", 2)); v.Add(new Voltage("Voltage #4", 3, true)); v.Add(new Voltage("CPU VDD18", 4)); v.Add(new Voltage("PM_CLDO12", 5)); v.Add(new Voltage("Voltage #7", 6, true)); v.Add(new Voltage("3VSB", 7, 1f, 1f)); v.Add(new Voltage("VBat", 8, 1f, 1f)); t.Add(new Temperature("PCIe x8", 0)); t.Add(new Temperature("EC_TEMP2", 1)); t.Add(new Temperature("System #2", 2)); f.Add(new Fan("System Fan #5 Pump", 0)); f.Add(new Fan("System Fan #6 Pump", 1)); f.Add(new Fan("System Fan #4", 2)); break; } case Model.X470_AORUS_GAMING_7_WIFI: // ITE IT8792 { v.Add(new Voltage("VIN0", 0, 0, 1)); v.Add(new Voltage("DDR VTT", 1, 0, 1)); v.Add(new Voltage("Chipset Core", 2, 0, 1)); v.Add(new Voltage("VIN3", 3, 0, 1)); v.Add(new Voltage("CPU VDD18", 4, 0, 1)); v.Add(new Voltage("Chipset Core +2.5V", 5, 0.5F, 1)); v.Add(new Voltage("3VSB", 6, 1, 10)); v.Add(new Voltage("VBat", 7, 0.7F, 1)); t.Add(new Temperature("PCIe x8", 0)); t.Add(new Temperature("System #2", 2)); for (int i = 0; i < superIO.Fans.Length; i++) f.Add(new Fan("Fan #" + (i + 1), i)); for (int i = 0; i < superIO.Controls.Length; i++) c.Add(new Ctrl("Fan Control #" + (i + 1), i)); break; } default: { v.Add(new Voltage("Voltage #1", 0, true)); v.Add(new Voltage("Voltage #2", 1, true)); v.Add(new Voltage("Voltage #3", 2, true)); v.Add(new Voltage("Voltage #4", 3, true)); v.Add(new Voltage("Voltage #5", 4, true)); v.Add(new Voltage("Voltage #6", 5, true)); v.Add(new Voltage("Voltage #7", 6, true)); v.Add(new Voltage("3VSB", 7, 10, 10, 0, true)); v.Add(new Voltage("VBat", 8, 10, 10)); for (int i = 0; i < superIO.Temperatures.Length; i++) t.Add(new Temperature("Temperature #" + (i + 1), i)); for (int i = 0; i < superIO.Fans.Length; i++) f.Add(new Fan("Fan #" + (i + 1), i)); for (int i = 0; i < superIO.Controls.Length; i++) c.Add(new Ctrl("Fan Control #" + (i + 1), i)); break; } } break; } default: { v.Add(new Voltage("Voltage #1", 0, true)); v.Add(new Voltage("Voltage #2", 1, true)); v.Add(new Voltage("Voltage #3", 2, true)); v.Add(new Voltage("Voltage #4", 3, true)); v.Add(new Voltage("Voltage #5", 4, true)); v.Add(new Voltage("Voltage #6", 5, true)); v.Add(new Voltage("Voltage #7", 6, true)); v.Add(new Voltage("3VSB", 7, 10, 10, 0, true)); v.Add(new Voltage("VBat", 8, 10, 10)); for (int i = 0; i < superIO.Temperatures.Length; i++) t.Add(new Temperature("Temperature #" + (i + 1), i)); for (int i = 0; i < superIO.Fans.Length; i++) f.Add(new Fan("Fan #" + (i + 1), i)); for (int i = 0; i < superIO.Controls.Length; i++) c.Add(new Ctrl("Fan Control #" + (i + 1), i)); break; } } } private static void GetFintekConfiguration(ISuperIO superIO, Manufacturer manufacturer, Model model, IList<Voltage> v, IList<Temperature> t, IList<Fan> f, IList<Ctrl> c) { switch (manufacturer) { case Manufacturer.EVGA: { switch (model) { case Model.X58_SLI_Classified: // F71882 { v.Add(new Voltage("VCC3V", 0, 150, 150)); v.Add(new Voltage("Vcore", 1, 47, 100)); v.Add(new Voltage("DIMM", 2, 47, 100)); v.Add(new Voltage("CPU VTT", 3, 24, 100)); v.Add(new Voltage("IOH Vcore", 4, 24, 100)); v.Add(new Voltage("+5V", 5, 51, 12)); v.Add(new Voltage("+12V", 6, 56, 6.8f)); v.Add(new Voltage("3VSB", 7, 150, 150)); v.Add(new Voltage("VBat", 8, 150, 150)); t.Add(new Temperature("CPU", 0)); t.Add(new Temperature("VREG", 1)); t.Add(new Temperature("System", 2)); f.Add(new Fan("CPU Fan", 0)); f.Add(new Fan("Power Fan", 1)); f.Add(new Fan("Chassis Fan", 2)); break; } default: { v.Add(new Voltage("VCC3V", 0, 150, 150)); v.Add(new Voltage("Vcore", 1)); v.Add(new Voltage("Voltage #3", 2, true)); v.Add(new Voltage("Voltage #4", 3, true)); v.Add(new Voltage("Voltage #5", 4, true)); v.Add(new Voltage("Voltage #6", 5, true)); v.Add(new Voltage("Voltage #7", 6, true)); v.Add(new Voltage("VSB3V", 7, 150, 150)); v.Add(new Voltage("VBat", 8, 150, 150)); for (int i = 0; i < superIO.Temperatures.Length; i++) t.Add(new Temperature("Temperature #" + (i + 1), i)); for (int i = 0; i < superIO.Fans.Length; i++) f.Add(new Fan("Fan #" + (i + 1), i)); break; } } break; } default: { v.Add(new Voltage("VCC3V", 0, 150, 150)); v.Add(new Voltage("Vcore", 1)); v.Add(new Voltage("Voltage #3", 2, true)); v.Add(new Voltage("Voltage #4", 3, true)); v.Add(new Voltage("Voltage #5", 4, true)); v.Add(new Voltage("Voltage #6", 5, true)); if (superIO.Chip != Chip.F71808E) v.Add(new Voltage("Voltage #7", 6, true)); v.Add(new Voltage("VSB3V", 7, 150, 150)); v.Add(new Voltage("VBat", 8, 150, 150)); for (int i = 0; i < superIO.Temperatures.Length; i++) t.Add(new Temperature("Temperature #" + (i + 1), i)); for (int i = 0; i < superIO.Fans.Length; i++) f.Add(new Fan("Fan #" + (i + 1), i)); for (int i = 0; i < superIO.Controls.Length; i++) c.Add(new Ctrl("Fan Control #" + (i + 1), i)); break; } } } private static void GetNuvotonConfigurationF(ISuperIO superIO, Manufacturer manufacturer, Model model, IList<Voltage> v, IList<Temperature> t, IList<Fan> f, IList<Ctrl> c) { switch (manufacturer) { case Manufacturer.ASUS: { switch (model) { case Model.P8P67: // NCT6776F case Model.P8P67_EVO: // NCT6776F case Model.P8P67_PRO: // NCT6776F { v.Add(new Voltage("Vcore", 0)); v.Add(new Voltage("+12V", 1, 11, 1)); v.Add(new Voltage("AVCC", 2, 34, 34)); v.Add(new Voltage("+3.3V", 3, 34, 34)); v.Add(new Voltage("+5V", 4, 12, 3)); v.Add(new Voltage("3VSB", 7, 34, 34)); v.Add(new Voltage("VBat", 8, 34, 34)); t.Add(new Temperature("CPU", 0)); t.Add(new Temperature("Auxiliary", 2)); t.Add(new Temperature("Motherboard", 3)); f.Add(new Fan("Chassis Fan #1", 0)); f.Add(new Fan("CPU Fan", 1)); f.Add(new Fan("Power Fan", 2)); f.Add(new Fan("Chassis Fan #2", 3)); c.Add(new Ctrl("Chassis Fan #2", 0)); c.Add(new Ctrl("CPU Fan", 1)); c.Add(new Ctrl("Chassis Fan #1", 2)); break; } case Model.P8P67_M_PRO: // NCT6776F { v.Add(new Voltage("Vcore", 0)); v.Add(new Voltage("+12V", 1, 11, 1)); v.Add(new Voltage("AVCC", 2, 34, 34)); v.Add(new Voltage("+3.3V", 3, 34, 34)); v.Add(new Voltage("+5V", 4, 12, 3)); v.Add(new Voltage("Voltage #6", 5, true)); v.Add(new Voltage("Voltage #7", 6, true)); v.Add(new Voltage("3VSB", 7, 34, 34)); v.Add(new Voltage("VBat", 8, 34, 34)); t.Add(new Temperature("CPU", 0)); t.Add(new Temperature("Motherboard", 3)); f.Add(new Fan("Chassis Fan #1", 0)); f.Add(new Fan("CPU Fan", 1)); f.Add(new Fan("Chassis Fan #2", 2)); f.Add(new Fan("Power Fan", 3)); f.Add(new Fan("Auxiliary Fan", 4)); break; } case Model.P8Z68_V_PRO: // NCT6776F { v.Add(new Voltage("Vcore", 0)); v.Add(new Voltage("+12V", 1, 11, 1)); v.Add(new Voltage("AVCC", 2, 34, 34)); v.Add(new Voltage("+3.3V", 3, 34, 34)); v.Add(new Voltage("+5V", 4, 12, 3)); v.Add(new Voltage("3VSB", 7, 34, 34)); v.Add(new Voltage("VBat", 8, 34, 34)); t.Add(new Temperature("CPU", 0)); t.Add(new Temperature("Auxiliary", 2)); t.Add(new Temperature("Motherboard", 3)); for (int i = 0; i < superIO.Fans.Length; i++) f.Add(new Fan("Fan #" + (i + 1), i)); for (int i = 0; i < superIO.Controls.Length; i++) c.Add(new Ctrl("Fan #" + (i + 1), i)); break; } case Model.P9X79: // NCT6776F { v.Add(new Voltage("Vcore", 0)); v.Add(new Voltage("+12V", 1, 11, 1)); v.Add(new Voltage("AVCC", 2, 34, 34)); v.Add(new Voltage("+3.3V", 3, 34, 34)); v.Add(new Voltage("+5V", 4, 12, 3)); v.Add(new Voltage("3VSB", 7, 34, 34)); v.Add(new Voltage("VBat", 8, 34, 34)); t.Add(new Temperature("CPU", 0)); t.Add(new Temperature("Motherboard", 3)); for (int i = 0; i < superIO.Fans.Length; i++) f.Add(new Fan("Fan #" + (i + 1), i)); for (int i = 0; i < superIO.Controls.Length; i++) c.Add(new Ctrl("Fan Control #" + (i + 1), i)); break; } default: { v.Add(new Voltage("Vcore", 0)); v.Add(new Voltage("Voltage #2", 1, true)); v.Add(new Voltage("AVCC", 2, 34, 34)); v.Add(new Voltage("+3.3V", 3, 34, 34)); v.Add(new Voltage("Voltage #5", 4, true)); v.Add(new Voltage("Voltage #6", 5, true)); v.Add(new Voltage("Voltage #7", 6, true)); v.Add(new Voltage("3VSB", 7, 34, 34)); v.Add(new Voltage("VBat", 8, 34, 34)); t.Add(new Temperature("CPU Core", 0)); t.Add(new Temperature("Temperature #1", 1)); t.Add(new Temperature("Temperature #2", 2)); t.Add(new Temperature("Temperature #3", 3)); for (int i = 0; i < superIO.Fans.Length; i++) f.Add(new Fan("Fan #" + (i + 1), i)); for (int i = 0; i < superIO.Controls.Length; i++) c.Add(new Ctrl("Fan Control #" + (i + 1), i)); break; } } break; } case Manufacturer.ASRock: { switch (model) { case Model.B85M_DGS: { v.Add(new Voltage("Vcore", 0, 1, 1)); v.Add(new Voltage("+12V", 1, 56, 10)); v.Add(new Voltage("AVCC", 2, 34, 34)); v.Add(new Voltage("+3.3V", 3, 34, 34)); v.Add(new Voltage("VIN1", 4, true)); v.Add(new Voltage("+5V", 5, 12, 3)); v.Add(new Voltage("VIN3", 6, true)); v.Add(new Voltage("3VSB", 7, 34, 34)); t.Add(new Temperature("CPU", 0)); t.Add(new Temperature("Auxiliary", 2)); t.Add(new Temperature("Motherboard", 3)); f.Add(new Fan("Chassis Fan #1", 0)); f.Add(new Fan("CPU Fan", 1)); f.Add(new Fan("Power Fan", 2)); f.Add(new Fan("Chassis Fan #2", 3)); c.Add(new Ctrl("Chassis Fan #2", 0)); c.Add(new Ctrl("CPU Fan", 1)); c.Add(new Ctrl("Chassis Fan #1", 2)); } break; case Model.Z77Pro4M: //NCT6776F { v.Add(new Voltage("Vcore", 0, 0, 1)); v.Add(new Voltage("+12V", 1, 56, 10)); v.Add(new Voltage("AVCC", 2, 10, 10)); v.Add(new Voltage("+3.3V", 3, 10, 10)); //v.Add(new Voltage("#Unused #4", 4, 0, 1, 0, true)); v.Add(new Voltage("+5V", 5, 20, 10)); //v.Add(new Voltage("#Unused #6", 6, 0, 1, 0, true)); v.Add(new Voltage("3VSB", 7, 10, 10)); v.Add(new Voltage("VBat", 8, 10, 10)); t.Add(new Temperature("CPU Core", 0)); t.Add(new Temperature("CPU", 1)); t.Add(new Temperature("Auxiliary", 2)); t.Add(new Temperature("Motherboard", 3)); for (int i = 0; i < superIO.Fans.Length; i++) f.Add(new Fan("Fan #" + (i + 1), i)); for (int i = 0; i < superIO.Controls.Length; i++) c.Add(new Ctrl("Fan Control #" + (i + 1), i)); break; } default: { v.Add(new Voltage("Vcore", 0)); v.Add(new Voltage("Voltage #2", 1, true)); v.Add(new Voltage("AVCC", 2, 34, 34)); v.Add(new Voltage("+3.3V", 3, 34, 34)); v.Add(new Voltage("Voltage #5", 4, true)); v.Add(new Voltage("Voltage #6", 5, true)); v.Add(new Voltage("Voltage #7", 6, true)); v.Add(new Voltage("3VSB", 7, 34, 34)); v.Add(new Voltage("VBat", 8, 34, 34)); t.Add(new Temperature("CPU Core", 0)); t.Add(new Temperature("Temperature #1", 1)); t.Add(new Temperature("Temperature #2", 2)); t.Add(new Temperature("Temperature #3", 3)); for (int i = 0; i < superIO.Fans.Length; i++) f.Add(new Fan("Fan #" + (i + 1), i)); for (int i = 0; i < superIO.Controls.Length; i++) c.Add(new Ctrl("Fan Control #" + (i + 1), i)); break; } } break; } default: { v.Add(new Voltage("Vcore", 0)); v.Add(new Voltage("Voltage #2", 1, true)); v.Add(new Voltage("AVCC", 2, 34, 34)); v.Add(new Voltage("+3.3V", 3, 34, 34)); v.Add(new Voltage("Voltage #5", 4, true)); v.Add(new Voltage("Voltage #6", 5, true)); v.Add(new Voltage("Voltage #7", 6, true)); v.Add(new Voltage("3VSB", 7, 34, 34)); v.Add(new Voltage("VBat", 8, 34, 34)); t.Add(new Temperature("CPU Core", 0)); t.Add(new Temperature("Temperature #1", 1)); t.Add(new Temperature("Temperature #2", 2)); t.Add(new Temperature("Temperature #3", 3)); for (int i = 0; i < superIO.Fans.Length; i++) f.Add(new Fan("Fan #" + (i + 1), i)); for (int i = 0; i < superIO.Controls.Length; i++) c.Add(new Ctrl("Fan Control #" + (i + 1), i)); break; } } } private static void GetNuvotonConfigurationD(ISuperIO superIO, Manufacturer manufacturer, Model model, IList<Voltage> v, IList<Temperature> t, IList<Fan> f, IList<Ctrl> c) { switch (manufacturer) { case Manufacturer.ASRock: { switch (model) { case Model.A320M_HDV: //NCT6779D { v.Add(new Voltage("Vcore", 0, 10, 10)); v.Add(new Voltage("Chipset 1.05V", 1, 0, 1)); v.Add(new Voltage("AVCC", 2, 10, 10)); v.Add(new Voltage("+3.3V", 3, 10, 10)); v.Add(new Voltage("+12V", 4, 56, 10)); v.Add(new Voltage("VcoreRef", 5, 0, 1)); v.Add(new Voltage("DIMM", 6, 0, 1)); v.Add(new Voltage("3VSB", 7, 10, 10)); v.Add(new Voltage("VBat", 8, 10, 10)); //v.Add(new Voltage("#Unused #9", 9, 0, 1, 0, true)); //v.Add(new Voltage("#Unused #10", 10, 0, 1, 0, true)); //v.Add(new Voltage("#Unused #11", 11, 34, 34, 0, true)); v.Add(new Voltage("+5V", 12, 20, 10)); //v.Add(new Voltage("#Unused #13", 13, 10, 10, 0, true)); //v.Add(new Voltage("#Unused #14", 14, 0, 1, 0, true)); //t.Add(new Temperature("#Unused #0", 0)); //t.Add(new Temperature("#Unused #1", 1)); t.Add(new Temperature("Motherboard", 2)); //t.Add(new Temperature("#Unused #3", 3)); //t.Add(new Temperature("#Unused #4", 4)); t.Add(new Temperature("Auxiliary", 5)); for (int i = 0; i < superIO.Fans.Length; i++) f.Add(new Fan("Fan #" + (i + 1), i)); for (int i = 0; i < superIO.Controls.Length; i++) c.Add(new Ctrl("Fan Control #" + (i + 1), i)); break; } case Model.AB350_Pro4: //NCT6779D case Model.AB350M_Pro4: case Model.AB350M: case Model.Fatal1ty_AB350_Gaming_K4: case Model.AB350M_HDV: case Model.B450_Steel_Legend: case Model.B450M_Steel_Legend: case Model.B450_Pro4: case Model.B450M_Pro4: { v.Add(new Voltage("Vcore", 0, 10, 10)); //v.Add(new Voltage("#Unused", 1, 0, 1, 0, true)); v.Add(new Voltage("AVCC", 2, 10, 10)); v.Add(new Voltage("+3.3V", 3, 10, 10)); v.Add(new Voltage("+12V", 4, 28, 5)); v.Add(new Voltage("Vcore Refin", 5, 0, 1)); //v.Add(new Voltage("#Unused #6", 6, 0, 1, 0, true)); v.Add(new Voltage("3VSB", 7, 10, 10)); v.Add(new Voltage("VBat", 8, 34, 34)); //v.Add(new Voltage("#Unused #9", 9, 0, 1, 0, true)); //v.Add(new Voltage("#Unused #10", 10, 0, 1, 0, true)); v.Add(new Voltage("Chipset 1.05V", 11, 0, 1)); v.Add(new Voltage("+5V", 12, 20, 10)); //v.Add(new Voltage("#Unused #13", 13, 0, 1, 0, true)); v.Add(new Voltage("+1.8V", 14, 0, 1)); t.Add(new Temperature("CPU Core", 0)); t.Add(new Temperature("CPU", 1)); t.Add(new Temperature("Motherboard", 2)); t.Add(new Temperature("Auxiliary", 3)); t.Add(new Temperature("VRM", 4)); t.Add(new Temperature("AUXTIN2", 5)); //t.Add(new Temperature("Temperature #6", 6)); for (int i = 0; i < superIO.Fans.Length; i++) f.Add(new Fan("Fan #" + (i + 1), i)); for (int i = 0; i < superIO.Controls.Length; i++) c.Add(new Ctrl("Fan Control #" + (i + 1), i)); break; } case Model.X399_Phantom_Gaming_6: //NCT6779D { v.Add(new Voltage("Vcore", 0, 10, 10)); v.Add(new Voltage("Chipset 1.05V", 1, 0, 1)); v.Add(new Voltage("AVCC", 2, 10, 10)); v.Add(new Voltage("+3.3V", 3, 10, 10)); v.Add(new Voltage("+12V", 4, 56, 10)); v.Add(new Voltage("VDDCR_SOC", 5, 0, 1)); v.Add(new Voltage("DIMM", 6, 0, 1)); v.Add(new Voltage("3VSB", 7, 10, 10)); v.Add(new Voltage("VBat", 8, 10, 10)); //v.Add(new Voltage("#Unused", 9, 0, 1, 0, true)); //v.Add(new Voltage("#Unused", 10, 0, 1, 0, true)); //v.Add(new Voltage("#Unused", 11, 0, 1, 0, true)); v.Add(new Voltage("+5V", 12, 20, 10)); v.Add(new Voltage("+1.8V", 13, 10, 10)); //v.Add(new Voltage("unused", 14, 34, 34, 0, true)); t.Add(new Temperature("CPU Core", 0)); t.Add(new Temperature("Motherboard", 1)); t.Add(new Temperature("Auxiliary", 2)); t.Add(new Temperature("Chipset", 3)); t.Add(new Temperature("Core VRM", 4)); t.Add(new Temperature("Core SoC", 5)); for (int i = 0; i < superIO.Fans.Length; i++) f.Add(new Fan("Fan #" + (i + 1), i)); for (int i = 0; i < superIO.Controls.Length; i++) c.Add(new Ctrl("Fan Control #" + (i + 1), i)); break; } case Model.X570_Taichi: { v.Add(new Voltage("Vcore", 0, 10, 10)); v.Add(new Voltage("Voltage #2", 1, true)); v.Add(new Voltage("AVCC", 2, 34, 34)); v.Add(new Voltage("+3.3V", 3, 34, 34)); v.Add(new Voltage("Voltage #5", 4, true)); v.Add(new Voltage("Voltage #6", 5, true)); v.Add(new Voltage("Voltage #7", 6, true)); v.Add(new Voltage("3VSB", 7, 34, 34)); v.Add(new Voltage("VBat", 8, 34, 34)); v.Add(new Voltage("VTT", 9)); v.Add(new Voltage("Voltage #11", 10, true)); v.Add(new Voltage("Voltage #12", 11, true)); v.Add(new Voltage("Voltage #13", 12, true)); v.Add(new Voltage("Voltage #14", 13, true)); v.Add(new Voltage("Voltage #15", 14, true)); t.Add(new Temperature("Motherboard", 2)); t.Add(new Temperature("CPU", 8)); t.Add(new Temperature("SB (Chipset)", 9)); f.Add(new Fan("Chassis #3" , 0)); f.Add(new Fan("CPU #1" , 1)); f.Add(new Fan("CPU #2" , 2)); f.Add(new Fan("Chassis #1" , 3)); f.Add(new Fan("Chassis #2" , 4)); f.Add(new Fan("SB Fan" , 5)); f.Add(new Fan("Chassis #4" , 6)); c.Add(new Ctrl("Chassis #3" , 0)); c.Add(new Ctrl("CPU #1" , 1)); c.Add(new Ctrl("CPU #2" , 2)); c.Add(new Ctrl("Chassis #1" , 3)); c.Add(new Ctrl("Chassis #2" , 4)); c.Add(new Ctrl("SB Fan" , 5)); c.Add(new Ctrl("Chassis #4" , 6)); break; } case Model.X570_Phantom_Gaming_ITX: { v.Add(new Voltage("+12V", 0)); v.Add(new Voltage("+5V", 1)); v.Add(new Voltage("Vcore", 2)); v.Add(new Voltage("Voltage #1", 3)); v.Add(new Voltage("DIMM", 4)); v.Add(new Voltage("CPU I/O", 5)); v.Add(new Voltage("CPU SA", 6)); v.Add(new Voltage("Voltage #2", 7)); v.Add(new Voltage("AVCC3", 8)); v.Add(new Voltage("VTT", 9)); v.Add(new Voltage("VRef", 10)); v.Add(new Voltage("VSB", 11)); v.Add(new Voltage("AVSB", 12)); v.Add(new Voltage("VBat", 13)); t.Add(new Temperature("Motherboard", 0)); //t.Add(new Temperature("System", 1)); //Unused t.Add(new Temperature("CPU", 2)); t.Add(new Temperature("SB (Chipset)", 3)); f.Add(new Fan("CPU Fan #1", 0)); //CPU_FAN1 f.Add(new Fan("Chassis Fan #1", 1)); //CHA_FAN1/WP f.Add(new Fan("CPU Fan #2", 2)); //CPU_FAN2 (WP) f.Add(new Fan("Chipset Fan", 3)); c.Add(new Ctrl("CPU Fan #1", 0)); c.Add(new Ctrl("Chassis Fan", 1)); c.Add(new Ctrl("CPU Fan #2", 2)); c.Add(new Ctrl("Chipset Fan", 3)); break; } default: { v.Add(new Voltage("Vcore", 0, 10, 10)); v.Add(new Voltage("Voltage #2", 1, true)); v.Add(new Voltage("AVCC", 2, 34, 34)); v.Add(new Voltage("+3.3V", 3, 34, 34)); v.Add(new Voltage("Voltage #5", 4, true)); v.Add(new Voltage("Voltage #6", 5, true)); v.Add(new Voltage("Voltage #7", 6, true)); v.Add(new Voltage("3VSB", 7, 34, 34)); v.Add(new Voltage("VBat", 8, 34, 34)); v.Add(new Voltage("VTT", 9)); v.Add(new Voltage("Voltage #11", 10, true)); v.Add(new Voltage("Voltage #12", 11, true)); v.Add(new Voltage("Voltage #13", 12, true)); v.Add(new Voltage("Voltage #14", 13, true)); v.Add(new Voltage("Voltage #15", 14, true)); t.Add(new Temperature("CPU Core", 0)); t.Add(new Temperature("Temperature #1", 1)); t.Add(new Temperature("Temperature #2", 2)); t.Add(new Temperature("Temperature #3", 3)); t.Add(new Temperature("Temperature #4", 4)); t.Add(new Temperature("Temperature #5", 5)); t.Add(new Temperature("Temperature #6", 6)); for (int i = 0; i < superIO.Fans.Length; i++) f.Add(new Fan("Fan #" + (i + 1), i)); for (int i = 0; i < superIO.Controls.Length; i++) c.Add(new Ctrl("Fan Control #" + (i + 1), i)); break; } } break; } case Manufacturer.ASUS: { switch (model) { case Model.P8Z77_V: // NCT6779D { v.Add(new Voltage("Vcore", 0)); v.Add(new Voltage("Voltage #2", 1, true)); v.Add(new Voltage("AVCC", 2, 34, 34)); v.Add(new Voltage("+3.3V", 3, 34, 34)); v.Add(new Voltage("Voltage #5", 4, true)); v.Add(new Voltage("Voltage #6", 5, true)); v.Add(new Voltage("Voltage #7", 6, true)); v.Add(new Voltage("3VSB", 7, 34, 34)); v.Add(new Voltage("VBat", 8, 34, 34)); v.Add(new Voltage("VTT", 9)); v.Add(new Voltage("Voltage #11", 10, true)); v.Add(new Voltage("Voltage #12", 11, true)); v.Add(new Voltage("Voltage #13", 12, true)); v.Add(new Voltage("Voltage #14", 13, true)); v.Add(new Voltage("Voltage #15", 14, true)); t.Add(new Temperature("CPU Core", 0)); t.Add(new Temperature("Auxiliary", 1)); t.Add(new Temperature("Motherboard", 2)); f.Add(new Fan("Chassis Fan #1", 0)); f.Add(new Fan("CPU Fan", 1)); f.Add(new Fan("Chassis Fan #2", 2)); f.Add(new Fan("Chassis Fan #3", 3)); c.Add(new Ctrl("Chassis Fan #1", 0)); c.Add(new Ctrl("CPU Fan", 1)); c.Add(new Ctrl("Chassis Fan #2", 2)); c.Add(new Ctrl("Chassis Fan #3", 3)); break; } case Model.ROG_MAXIMUS_X_APEX: // NCT6793D { v.Add(new Voltage("Vcore", 0, 2, 2)); v.Add(new Voltage("+5V", 1, 4, 1)); v.Add(new Voltage("AVSB", 2, 34, 34)); v.Add(new Voltage("+3.3V", 3, 34, 34)); v.Add(new Voltage("+12V", 4, 11, 1)); v.Add(new Voltage("Voltage #6", 5, true)); v.Add(new Voltage("CPU GFX", 6, 2, 2)); v.Add(new Voltage("3VSB", 7, 34, 34)); v.Add(new Voltage("VBat", 8, 34, 34)); v.Add(new Voltage("VTT", 9)); v.Add(new Voltage("DIMM", 10, 1, 1)); v.Add(new Voltage("VCCSA", 11)); v.Add(new Voltage("PCH Core", 12)); v.Add(new Voltage("CPU PLLs", 13)); v.Add(new Voltage("CPU VCCIO/IMC", 14)); t.Add(new Temperature("CPU (PECI)", 0)); t.Add(new Temperature("T2", 1)); t.Add(new Temperature("T1", 2)); t.Add(new Temperature("CPU", 3)); t.Add(new Temperature("PCH", 4)); t.Add(new Temperature("Temperature #4", 5)); t.Add(new Temperature("Temperature #5", 6)); f.Add(new Fan("Chassis Fan #1", 0)); f.Add(new Fan("CPU Fan", 1)); f.Add(new Fan("Chassis Fan #2", 2)); f.Add(new Fan("Chassis Fan #3", 3)); f.Add(new Fan("AIO Pump", 4)); c.Add(new Ctrl("Chassis Fan #1", 0)); c.Add(new Ctrl("CPU Fan", 1)); c.Add(new Ctrl("Chassis Fan #2", 2)); c.Add(new Ctrl("Chassis Fan #3", 3)); c.Add(new Ctrl("AIO Pump", 4)); break; } case Model.Z170_A: //NCT6793D { v.Add(new Voltage("Vcore", 0, 2, 2)); v.Add(new Voltage("+5V", 1, 4, 1)); v.Add(new Voltage("AVSB", 2, 34, 34)); v.Add(new Voltage("+3.3V", 3, 34, 34)); v.Add(new Voltage("+12V", 4, 11, 1)); v.Add(new Voltage("Voltage #6", 5, 0, 1, 0, true)); v.Add(new Voltage("CPU GFX", 6, 2, 2)); v.Add(new Voltage("3VSB_ATX", 7, 34, 34)); v.Add(new Voltage("VBat", 8, 34, 34)); v.Add(new Voltage("VTT", 9)); v.Add(new Voltage("DIMM", 10, 1, 1)); v.Add(new Voltage("VCCSA", 11)); v.Add(new Voltage("PCH Core", 12)); v.Add(new Voltage("CPU PLLs", 13)); v.Add(new Voltage("CPU VCCIO/IMC", 14)); t.Add(new Temperature("CPU (PECI)", 0)); t.Add(new Temperature("CPU", 1)); t.Add(new Temperature("Motherboard", 2)); t.Add(new Temperature("CPU", 3)); t.Add(new Temperature("PCH", 4)); t.Add(new Temperature("Temperature #4", 5)); t.Add(new Temperature("Temperature #5", 6)); for (int i = 0; i < superIO.Fans.Length; i++) f.Add(new Fan("Fan #" + (i + 1), i)); for (int i = 0; i < superIO.Controls.Length; i++) c.Add(new Ctrl("Fan Control #" + (i + 1), i)); break; } case Model.TUF_GAMING_B550M_PLUS_WIFI: //NCT6798D { v.Add(new Voltage("Vcore", 0)); v.Add(new Voltage("Voltage #2", 1, true)); v.Add(new Voltage("AVCC", 2, 34, 34)); v.Add(new Voltage("+3.3V", 3, 34, 34)); v.Add(new Voltage("Voltage #5", 4, true)); v.Add(new Voltage("Voltage #6", 5, true)); v.Add(new Voltage("Voltage #7", 6, true)); v.Add(new Voltage("3VSB", 7, 34, 34)); v.Add(new Voltage("VBat", 8, 34, 34)); v.Add(new Voltage("VTT", 9)); v.Add(new Voltage("Voltage #11", 10, true)); v.Add(new Voltage("Voltage #12", 11, true)); v.Add(new Voltage("Voltage #13", 12, true)); v.Add(new Voltage("Voltage #14", 13, true)); v.Add(new Voltage("Voltage #15", 14, true)); t.Add(new Temperature("PECI 0", 0)); t.Add(new Temperature("CPU", 1)); t.Add(new Temperature("System", 2)); t.Add(new Temperature("AUX 0", 3)); t.Add(new Temperature("AUX 1", 4)); t.Add(new Temperature("AUX 2", 5)); t.Add(new Temperature("AUX 3", 6)); t.Add(new Temperature("AUX 4", 7)); t.Add(new Temperature("SMBus 0", 8)); t.Add(new Temperature("SMBus 1", 9)); t.Add(new Temperature("PECI 1", 10)); t.Add(new Temperature("PCH Chip CPU Max", 11)); t.Add(new Temperature("PCH Chip", 12)); t.Add(new Temperature("PCH CPU", 13)); t.Add(new Temperature("PCH MCH", 14)); t.Add(new Temperature("Agent 0 DIMM 0", 15)); t.Add(new Temperature("Agent 0 DIMM 1", 16)); t.Add(new Temperature("Agent 1 DIMM 0", 17)); t.Add(new Temperature("Agent 1 DIMM 1", 18)); t.Add(new Temperature("Device 0", 19)); t.Add(new Temperature("Device 1", 20)); t.Add(new Temperature("PECI 0 Calibrated", 21)); t.Add(new Temperature("PECI 1 Calibrated", 22)); t.Add(new Temperature("Virtual", 23)); for (int i = 0; i < superIO.Fans.Length; i++) f.Add(new Fan("Fan #" + (i + 1), i)); for (int i = 0; i < superIO.Controls.Length; i++) c.Add(new Ctrl("Fan Control #" + (i + 1), i)); break; } case Model.ROG_CROSSHAIR_VIII_HERO: // NCT6798D case Model.ROG_CROSSHAIR_VIII_DARK_HERO: // NCT6798D { v.Add(new Voltage("Vcore", 0)); v.Add(new Voltage("Voltage #2", 1, true)); v.Add(new Voltage("AVCC", 2, 34, 34)); v.Add(new Voltage("+3.3V", 3, 34, 34)); v.Add(new Voltage("Voltage #5", 4, true)); v.Add(new Voltage("Voltage #6", 5, true)); v.Add(new Voltage("CPU SoC", 6)); v.Add(new Voltage("3VSB", 7, 34, 34)); v.Add(new Voltage("VBat", 8, 34, 34)); v.Add(new Voltage("VTT", 9)); v.Add(new Voltage("Voltage #11", 10, true)); v.Add(new Voltage("Voltage #12", 11, true)); v.Add(new Voltage("Voltage #13", 12, true)); v.Add(new Voltage("DRAM", 13)); v.Add(new Voltage("Voltage #15", 14, true)); t.Add(new Temperature("PECI 0", 0)); t.Add(new Temperature("CPU", 1)); t.Add(new Temperature("Motherboard", 2)); t.Add(new Temperature("AUX 0", 3)); t.Add(new Temperature("AUX 1", 4)); t.Add(new Temperature("AUX 2", 5)); t.Add(new Temperature("AUX 3", 6)); t.Add(new Temperature("AUX 4", 7)); t.Add(new Temperature("SMBus 0", 8)); t.Add(new Temperature("SMBus 1", 9)); t.Add(new Temperature("PECI 1", 10)); t.Add(new Temperature("PCH Chip CPU Max", 11)); t.Add(new Temperature("PCH Chip", 12)); t.Add(new Temperature("PCH CPU", 13)); t.Add(new Temperature("PCH MCH", 14)); t.Add(new Temperature("Agent 0 DIMM 0", 15)); t.Add(new Temperature("Agent 0 DIMM 1", 16)); t.Add(new Temperature("Agent 1 DIMM 0", 17)); t.Add(new Temperature("Agent 1 DIMM 1", 18)); t.Add(new Temperature("Device 0", 19)); t.Add(new Temperature("Device 1", 20)); t.Add(new Temperature("PECI 0 Calibrated", 21)); t.Add(new Temperature("PECI 1 Calibrated", 22)); t.Add(new Temperature("Virtual", 23)); t.Add(new Temperature("Water In", 24)); t.Add(new Temperature("Water Out", 25)); for (int i = 0; i < superIO.Fans.Length; i++) f.Add(new Fan("Fan #" + (i + 1), i)); for (int i = 0; i < superIO.Controls.Length; i++) c.Add(new Ctrl("Fan Control #" + (i + 1), i)); break; } case Model.ROG_STRIX_B550_I_GAMING: //NCT6798D { v.Add(new Voltage("Vcore", 0, 10, 10)); v.Add(new Voltage("+5V", 1, 4, 1)); //Probably not updating properly v.Add(new Voltage("AVCC", 2, 10, 10)); v.Add(new Voltage("+3.3V", 3, 34, 34)); v.Add(new Voltage("+12V", 4, 11, 1)); //Probably not updating properly //v.Add(new Voltage("#Unused #5", 5, 0, 1, 0, true)); //v.Add(new Voltage("#Unused #6", 6, 0, 1, 0, true)); v.Add(new Voltage("3VSB", 7, 34, 34)); v.Add(new Voltage("VBat", 8, 34, 34)); v.Add(new Voltage("VTT", 9)); //v.Add(new Voltage("#Unused #9", 9, 0, 1, 0, true)); //v.Add(new Voltage("#Unused #10", 10, 0, 1, 0, true)); //v.Add(new Voltage("#Unused #11", 11, 0, 1, 0, true)); //v.Add(new Voltage("#Unused #12", 12, 0, 1, 0, true)); //v.Add(new Voltage("#Unused #13", 13, 0, 1, 0, true)); //v.Add(new Voltage("#Unused #14", 14, 0, 1, 0, true)); t.Add(new Temperature("CPU", 1)); t.Add(new Temperature("Motherboard", 2)); //t.Add(new Temperature("AUX 0", 3)); //No software from Asus reports this temperature ~82C //t.Add(new Temperature("#Unused 4", 4)); //t.Add(new Temperature("#Unused 5", 5)); //t.Add(new Temperature("#Unused 6", 6)); //t.Add(new Temperature("#Unused 7", 7)); //t.Add(new Temperature("#Unused 8", 8)); //t.Add(new Temperature("#Unused 9", 9)); //t.Add(new Temperature("#Unused 10", 10)); t.Add(new Temperature("PCH Chip CPU Max", 11)); t.Add(new Temperature("PCH Chip", 12)); t.Add(new Temperature("PCH CPU", 13)); t.Add(new Temperature("PCH MCH", 14)); t.Add(new Temperature("Agent 0 DIMM 0", 15)); //t.Add(new Temperature("Agent 0 DIMM 1", 16)); t.Add(new Temperature("Agent 1 DIMM 0", 17)); //t.Add(new Temperature("Agent 1 DIMM 1", 18)); t.Add(new Temperature("Device 0", 19)); t.Add(new Temperature("Device 1", 20)); t.Add(new Temperature("PECI 0 Calibrated", 21)); t.Add(new Temperature("PECI 1 Calibrated", 22)); t.Add(new Temperature("Virtual", 23)); //todo //Find a way to read the value of VRM HS FAN //It is definitely not controllable as it only supports ON / OFF options but the RPM can be read somewhere for (int i = 0; i < superIO.Fans.Length; i++) { switch (i) { case 0: f.Add(new Fan("Chassis Fan", 0)); break; case 1: f.Add(new Fan("CPU Fan", 1)); break; case 4: f.Add(new Fan("AIO Pump", 4)); break; } } for (int i = 0; i < superIO.Controls.Length; i++) { switch (i) { case 0: c.Add(new Ctrl("Chassis Fan Control", 0)); break; case 1: c.Add(new Ctrl("CPU Fan Control", 1)); break; case 4: c.Add(new Ctrl("AIO Pump Control", 4)); break; } } break; } default: { v.Add(new Voltage("Vcore", 0)); v.Add(new Voltage("Voltage #2", 1, true)); v.Add(new Voltage("AVCC", 2, 34, 34)); v.Add(new Voltage("+3.3V", 3, 34, 34)); v.Add(new Voltage("Voltage #5", 4, true)); v.Add(new Voltage("Voltage #6", 5, true)); v.Add(new Voltage("Voltage #7", 6, true)); v.Add(new Voltage("3VSB", 7, 34, 34)); v.Add(new Voltage("VBat", 8, 34, 34)); v.Add(new Voltage("VTT", 9)); v.Add(new Voltage("Voltage #11", 10, true)); v.Add(new Voltage("Voltage #12", 11, true)); v.Add(new Voltage("Voltage #13", 12, true)); v.Add(new Voltage("Voltage #14", 13, true)); v.Add(new Voltage("Voltage #15", 14, true)); t.Add(new Temperature("CPU Core", 0)); t.Add(new Temperature("Temperature #1", 1)); t.Add(new Temperature("Temperature #2", 2)); t.Add(new Temperature("Temperature #3", 3)); t.Add(new Temperature("Temperature #4", 4)); t.Add(new Temperature("Temperature #5", 5)); t.Add(new Temperature("Temperature #6", 6)); for (int i = 0; i < superIO.Fans.Length; i++) f.Add(new Fan("Fan #" + (i + 1), i)); for (int i = 0; i < superIO.Controls.Length; i++) c.Add(new Ctrl("Fan Control #" + (i + 1), i)); break; } } break; } case Manufacturer.MSI: { switch (model) { case Model.B360M_PRO_VDH: // NCT6797D { v.Add(new Voltage("Vcore", 0)); v.Add(new Voltage("+5V", 1, 4, 1)); v.Add(new Voltage("AVCC", 2, 34, 34)); v.Add(new Voltage("+3.3V", 3, 34, 34)); v.Add(new Voltage("+12V", 4, 11, 1)); //v.Add(new Voltage("Voltage #6", 5, true)); v.Add(new Voltage("CPU I/O", 6)); v.Add(new Voltage("3VSB", 7, 34, 34)); v.Add(new Voltage("VTT", 9)); v.Add(new Voltage("CPU SA", 10)); //v.Add(new Voltage("Voltage #12", 11, true)); v.Add(new Voltage("NB/SoC", 12)); v.Add(new Voltage("DIMM", 13, 1, 1)); //v.Add(new Voltage("Voltage #15", 14, true)); t.Add(new Temperature("CPU", 0)); t.Add(new Temperature("Auxiliary", 1)); t.Add(new Temperature("Motherboard", 2)); t.Add(new Temperature("Temperature #1", 5)); f.Add(new Fan("CPU Fan", 1)); f.Add(new Fan("System Fan #1", 2)); f.Add(new Fan("System Fan #2", 3)); c.Add(new Ctrl("CPU Fan", 1)); c.Add(new Ctrl("System Fan #1", 2)); c.Add(new Ctrl("System Fan #2", 3)); break; } case Model.B450A_PRO: // NCT6797D { v.Add(new Voltage("Vcore", 0)); v.Add(new Voltage("+5V", 1, 4, 1)); v.Add(new Voltage("AVCC", 2, 34, 34)); v.Add(new Voltage("+3.3V", 3, 34, 34)); v.Add(new Voltage("+12V", 4, 11, 1)); //v.Add(new Voltage("Voltage #6", 5, false)); //v.Add(new Voltage("CPU I/O", 6)); v.Add(new Voltage("3VSB", 7, 34, 34)); v.Add(new Voltage("VTT", 9)); v.Add(new Voltage("CPU SA", 10)); //v.Add(new Voltage("Voltage #12", 11, false)); v.Add(new Voltage("NB/SoC", 12)); v.Add(new Voltage("DIMM", 13, 1, 1)); //v.Add(new Voltage("Voltage #15", 14, false)); //t.Add(new Temperature("CPU", 0)); t.Add(new Temperature("CPU", 1)); t.Add(new Temperature("System", 2)); t.Add(new Temperature("VRM MOS", 3)); t.Add(new Temperature("PCH", 5)); t.Add(new Temperature("SMBus 0", 8)); f.Add(new Fan("Pump Fan", 0)); f.Add(new Fan("CPU Fan", 1)); f.Add(new Fan("System Fan #1", 2)); f.Add(new Fan("System Fan #2", 3)); f.Add(new Fan("System Fan #3", 4)); f.Add(new Fan("System Fan #4", 5)); c.Add(new Ctrl("Pump Fan", 0)); c.Add(new Ctrl("CPU Fan", 1)); c.Add(new Ctrl("System Fan #1", 2)); c.Add(new Ctrl("System Fan #2", 3)); c.Add(new Ctrl("System Fan #3", 4)); c.Add(new Ctrl("System Fan #4", 5)); break; } case Model.Z270_PC_MATE: // NCT6795D { v.Add(new Voltage("Vcore", 0)); v.Add(new Voltage("+5V", 1, 4, 1)); v.Add(new Voltage("AVCC", 2, 34, 34)); v.Add(new Voltage("+3.3V", 3, 34, 34)); v.Add(new Voltage("+12V", 4, 11, 1)); v.Add(new Voltage("Voltage #6", 5, true)); v.Add(new Voltage("CPU I/O", 6)); v.Add(new Voltage("3VSB", 7, 34, 34)); v.Add(new Voltage("VTT", 9)); v.Add(new Voltage("CPU SA", 10)); v.Add(new Voltage("Voltage #12", 11, true)); v.Add(new Voltage("PCH", 12)); v.Add(new Voltage("DIMM", 13, 1, 1)); v.Add(new Voltage("Voltage #15", 14, true)); t.Add(new Temperature("CPU", 0)); t.Add(new Temperature("Auxiliary", 1)); t.Add(new Temperature("Motherboard", 2)); f.Add(new Fan("Pump Fan", 0)); f.Add(new Fan("CPU Fan", 1)); f.Add(new Fan("System Fan #1", 2)); f.Add(new Fan("System Fan #2", 3)); f.Add(new Fan("System Fan #3", 4)); f.Add(new Fan("System Fan #4", 5)); c.Add(new Ctrl("Pump Fan", 0)); c.Add(new Ctrl("CPU Fan", 1)); c.Add(new Ctrl("System Fan #1", 2)); c.Add(new Ctrl("System Fan #2", 3)); c.Add(new Ctrl("System Fan #3", 4)); c.Add(new Ctrl("System Fan #4", 5)); break; } default: { v.Add(new Voltage("Vcore", 0)); v.Add(new Voltage("Voltage #2", 1, true)); v.Add(new Voltage("AVCC", 2, 34, 34)); v.Add(new Voltage("+3.3V", 3, 34, 34)); v.Add(new Voltage("Voltage #5", 4, true)); v.Add(new Voltage("Voltage #6", 5, true)); v.Add(new Voltage("Voltage #7", 6, true)); v.Add(new Voltage("3VSB", 7, 34, 34)); v.Add(new Voltage("VBat", 8, 34, 34)); v.Add(new Voltage("VTT", 9)); v.Add(new Voltage("Voltage #11", 10, true)); v.Add(new Voltage("Voltage #12", 11, true)); v.Add(new Voltage("Voltage #13", 12, true)); v.Add(new Voltage("Voltage #14", 13, true)); v.Add(new Voltage("Voltage #15", 14, true)); t.Add(new Temperature("CPU Core", 0)); t.Add(new Temperature("Temperature #1", 1)); t.Add(new Temperature("Temperature #2", 2)); t.Add(new Temperature("Temperature #3", 3)); t.Add(new Temperature("Temperature #4", 4)); t.Add(new Temperature("Temperature #5", 5)); t.Add(new Temperature("Temperature #6", 6)); for (int i = 0; i < superIO.Fans.Length; i++) f.Add(new Fan("Fan #" + (i + 1), i)); for (int i = 0; i < superIO.Controls.Length; i++) c.Add(new Ctrl("Fan Control #" + (i + 1), i)); break; } } break; } default: { v.Add(new Voltage("Vcore", 0)); v.Add(new Voltage("Voltage #2", 1, true)); v.Add(new Voltage("AVCC", 2, 34, 34)); v.Add(new Voltage("+3.3V", 3, 34, 34)); v.Add(new Voltage("Voltage #5", 4, true)); v.Add(new Voltage("Voltage #6", 5, true)); v.Add(new Voltage("Voltage #7", 6, true)); v.Add(new Voltage("3VSB", 7, 34, 34)); v.Add(new Voltage("VBat", 8, 34, 34)); v.Add(new Voltage("VTT", 9)); v.Add(new Voltage("Voltage #11", 10, true)); v.Add(new Voltage("Voltage #12", 11, true)); v.Add(new Voltage("Voltage #13", 12, true)); v.Add(new Voltage("Voltage #14", 13, true)); v.Add(new Voltage("Voltage #15", 14, true)); t.Add(new Temperature("CPU Core", 0)); t.Add(new Temperature("Temperature #1", 1)); t.Add(new Temperature("Temperature #2", 2)); t.Add(new Temperature("Temperature #3", 3)); t.Add(new Temperature("Temperature #4", 4)); t.Add(new Temperature("Temperature #5", 5)); t.Add(new Temperature("Temperature #6", 6)); for (int i = 0; i < superIO.Fans.Length; i++) f.Add(new Fan("Fan #" + (i + 1), i)); for (int i = 0; i < superIO.Controls.Length; i++) c.Add(new Ctrl("Fan Control #" + (i + 1), i)); break; } } } private static void GetWinbondConfigurationEhf(Manufacturer manufacturer, Model model, IList<Voltage> v, IList<Temperature> t, IList<Fan> f) { switch (manufacturer) { case Manufacturer.ASRock: { switch (model) { case Model.AOD790GX_128M: // W83627EHF { v.Add(new Voltage("Vcore", 0)); v.Add(new Voltage("AVCC", 2, 34, 34)); v.Add(new Voltage("+3.3V", 4, 10, 10)); v.Add(new Voltage("+5V", 5, 20, 10)); v.Add(new Voltage("+12V", 6, 28, 5)); v.Add(new Voltage("3VSB", 7, 34, 34)); v.Add(new Voltage("VBat", 8, 34, 34)); t.Add(new Temperature("CPU", 0)); t.Add(new Temperature("Motherboard", 2)); f.Add(new Fan("CPU Fan", 0)); f.Add(new Fan("Chassis Fan", 1)); break; } default: { v.Add(new Voltage("Vcore", 0)); v.Add(new Voltage("Voltage #2", 1, true)); v.Add(new Voltage("AVCC", 2, 34, 34)); v.Add(new Voltage("+3.3V", 3, 34, 34)); v.Add(new Voltage("Voltage #5", 4, true)); v.Add(new Voltage("Voltage #6", 5, true)); v.Add(new Voltage("Voltage #7", 6, true)); v.Add(new Voltage("3VSB", 7, 34, 34)); v.Add(new Voltage("VBat", 8, 34, 34)); v.Add(new Voltage("Voltage #10", 9, true)); t.Add(new Temperature("CPU", 0)); t.Add(new Temperature("Auxiliary", 1)); t.Add(new Temperature("System", 2)); f.Add(new Fan("System Fan", 0)); f.Add(new Fan("CPU Fan", 1)); f.Add(new Fan("Auxiliary Fan", 2)); f.Add(new Fan("CPU Fan #2", 3)); f.Add(new Fan("Auxiliary Fan #2", 4)); break; } } break; } default: { v.Add(new Voltage("Vcore", 0)); v.Add(new Voltage("Voltage #2", 1, true)); v.Add(new Voltage("AVCC", 2, 34, 34)); v.Add(new Voltage("+3.3V", 3, 34, 34)); v.Add(new Voltage("Voltage #5", 4, true)); v.Add(new Voltage("Voltage #6", 5, true)); v.Add(new Voltage("Voltage #7", 6, true)); v.Add(new Voltage("3VSB", 7, 34, 34)); v.Add(new Voltage("VBat", 8, 34, 34)); v.Add(new Voltage("Voltage #10", 9, true)); t.Add(new Temperature("CPU", 0)); t.Add(new Temperature("Auxiliary", 1)); t.Add(new Temperature("System", 2)); f.Add(new Fan("System Fan", 0)); f.Add(new Fan("CPU Fan", 1)); f.Add(new Fan("Auxiliary Fan", 2)); f.Add(new Fan("CPU Fan #2", 3)); f.Add(new Fan("Auxiliary Fan #2", 4)); break; } } } private static void GetWinbondConfigurationHg(Manufacturer manufacturer, Model model, IList<Voltage> v, IList<Temperature> t, IList<Fan> f) { switch (manufacturer) { case Manufacturer.ASRock: { switch (model) { case Model._880GMH_USB3: // W83627DHG-P { v.Add(new Voltage("Vcore", 0)); v.Add(new Voltage("+3.3V", 3, 34, 34)); v.Add(new Voltage("+5V", 5, 15, 7.5f)); v.Add(new Voltage("+12V", 6, 56, 10)); v.Add(new Voltage("3VSB", 7, 34, 34)); v.Add(new Voltage("VBat", 8, 34, 34)); t.Add(new Temperature("CPU", 0)); t.Add(new Temperature("Motherboard", 2)); f.Add(new Fan("Chassis Fan", 0)); f.Add(new Fan("CPU Fan", 1)); f.Add(new Fan("Power Fan", 2)); break; } default: { v.Add(new Voltage("Vcore", 0)); v.Add(new Voltage("Voltage #2", 1, true)); v.Add(new Voltage("AVCC", 2, 34, 34)); v.Add(new Voltage("+3.3V", 3, 34, 34)); v.Add(new Voltage("Voltage #5", 4, true)); v.Add(new Voltage("Voltage #6", 5, true)); v.Add(new Voltage("Voltage #7", 6, true)); v.Add(new Voltage("3VSB", 7, 34, 34)); v.Add(new Voltage("VBat", 8, 34, 34)); t.Add(new Temperature("CPU", 0)); t.Add(new Temperature("Auxiliary", 1)); t.Add(new Temperature("System", 2)); f.Add(new Fan("System Fan", 0)); f.Add(new Fan("CPU Fan", 1)); f.Add(new Fan("Auxiliary Fan", 2)); f.Add(new Fan("CPU Fan #2", 3)); f.Add(new Fan("Auxiliary Fan #2", 4)); break; } } break; } case Manufacturer.ASUS: { switch (model) { case Model.P6T: // W83667HG case Model.P6X58D_E: // W83667HG case Model.RAMPAGE_II_GENE: // W83667HG { v.Add(new Voltage("Vcore", 0)); v.Add(new Voltage("+12V", 1, 11.5f, 1.91f)); v.Add(new Voltage("AVCC", 2, 34, 34)); v.Add(new Voltage("+3.3V", 3, 34, 34)); v.Add(new Voltage("+5V", 4, 15, 7.5f)); v.Add(new Voltage("3VSB", 7, 34, 34)); v.Add(new Voltage("VBat", 8, 34, 34)); t.Add(new Temperature("CPU", 0)); t.Add(new Temperature("Motherboard", 2)); f.Add(new Fan("Chassis Fan #1", 0)); f.Add(new Fan("CPU Fan", 1)); f.Add(new Fan("Power Fan", 2)); f.Add(new Fan("Chassis Fan #2", 3)); f.Add(new Fan("Chassis Fan #3", 4)); break; } case Model.RAMPAGE_EXTREME: // W83667HG { v.Add(new Voltage("Vcore", 0)); v.Add(new Voltage("+12V", 1, 12, 2)); v.Add(new Voltage("AVCC", 2, 34, 34)); v.Add(new Voltage("+3.3V", 3, 34, 34)); v.Add(new Voltage("+5V", 4, 15, 7.5f)); v.Add(new Voltage("3VSB", 7, 34, 34)); v.Add(new Voltage("VBat", 8, 34, 34)); t.Add(new Temperature("CPU", 0)); t.Add(new Temperature("Motherboard", 2)); f.Add(new Fan("Chassis Fan #1", 0)); f.Add(new Fan("CPU Fan", 1)); f.Add(new Fan("Power Fan", 2)); f.Add(new Fan("Chassis Fan #2", 3)); f.Add(new Fan("Chassis Fan #3", 4)); break; } default: { v.Add(new Voltage("Vcore", 0)); v.Add(new Voltage("Voltage #2", 1, true)); v.Add(new Voltage("AVCC", 2, 34, 34)); v.Add(new Voltage("+3.3V", 3, 34, 34)); v.Add(new Voltage("Voltage #5", 4, true)); v.Add(new Voltage("Voltage #6", 5, true)); v.Add(new Voltage("Voltage #7", 6, true)); v.Add(new Voltage("3VSB", 7, 34, 34)); v.Add(new Voltage("VBat", 8, 34, 34)); t.Add(new Temperature("CPU", 0)); t.Add(new Temperature("Auxiliary", 1)); t.Add(new Temperature("System", 2)); f.Add(new Fan("System Fan", 0)); f.Add(new Fan("CPU Fan", 1)); f.Add(new Fan("Auxiliary Fan", 2)); f.Add(new Fan("CPU Fan #2", 3)); f.Add(new Fan("Auxiliary Fan #2", 4)); break; } } break; } default: { v.Add(new Voltage("Vcore", 0)); v.Add(new Voltage("Voltage #2", 1, true)); v.Add(new Voltage("AVCC", 2, 34, 34)); v.Add(new Voltage("+3.3V", 3, 34, 34)); v.Add(new Voltage("Voltage #5", 4, true)); v.Add(new Voltage("Voltage #6", 5, true)); v.Add(new Voltage("Voltage #7", 6, true)); v.Add(new Voltage("3VSB", 7, 34, 34)); v.Add(new Voltage("VBat", 8, 34, 34)); t.Add(new Temperature("CPU", 0)); t.Add(new Temperature("Auxiliary", 1)); t.Add(new Temperature("System", 2)); f.Add(new Fan("System Fan", 0)); f.Add(new Fan("CPU Fan", 1)); f.Add(new Fan("Auxiliary Fan", 2)); f.Add(new Fan("CPU Fan #2", 3)); f.Add(new Fan("Auxiliary Fan #2", 4)); break; } } } public override string GetReport() { return _superIO.GetReport(); } public override void Update() { _superIO.Update(); foreach (Sensor sensor in _voltages) { float? value = _readVoltage(sensor.Index); if (value.HasValue) { sensor.Value = value + (value - sensor.Parameters[2].Value) * sensor.Parameters[0].Value / sensor.Parameters[1].Value; ActivateSensor(sensor); } } foreach (Sensor sensor in _temperatures) { float? value = _readTemperature(sensor.Index); if (value.HasValue) { sensor.Value = value + sensor.Parameters[0].Value; ActivateSensor(sensor); } } foreach (Sensor sensor in _fans) { float? value = _readFan(sensor.Index); if (value.HasValue) { sensor.Value = value; ActivateSensor(sensor); } } foreach (Sensor sensor in _controls) { float? value = _readControl(sensor.Index); sensor.Value = value; } _postUpdate(); } public override void Close() { foreach (Sensor sensor in _controls) { // restore all controls back to default _superIO.SetControl(sensor.Index, null); } base.Close(); } private delegate float? ReadValueDelegate(int index); private delegate void UpdateDelegate(); private class Voltage { public readonly bool Hidden; public readonly int Index; public readonly string Name; public readonly float Rf; public readonly float Ri; public readonly float Vf; public Voltage(string name, int index, bool hidden = false) : this(name, index, 0, 1, 0, hidden) { } public Voltage(string name, int index, float ri, float rf, float vf = 0, bool hidden = false) { Name = name; Index = index; Ri = ri; Rf = rf; Vf = vf; Hidden = hidden; } } private class Temperature { public readonly int Index; public readonly string Name; public Temperature(string name, int index) { Name = name; Index = index; } } private class Fan { public readonly int Index; public readonly string Name; public Fan(string name, int index) { Name = name; Index = index; } } private class Ctrl { public readonly int Index; public readonly string Name; public Ctrl(string name, int index) { Name = name; Index = index; } } } }
49.583032
179
0.353292
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
kolaqsq/LibreHardwareMonitor
LibreHardwareMonitorLib/Hardware/Motherboard/SuperIOHardware.cs
150,786
C#
using System; using System.Linq; using JabbR.Infrastructure; using JabbR.Models; using JabbR.Services; using Moq; using Xunit; namespace JabbR.Test { public class ChatServiceFacts { public class AddUser { [Fact] public void ThrowsIfNameIsInValid() { var repository = new InMemoryRepository(); var service = new ChatService(new Mock<ICache>().Object, repository,new Mock<ICryptoService>().Object); Assert.Throws<InvalidOperationException>(() => service.AddUser("some in valid name", clientId: null, userAgent: null, password: null)); } [Fact] public void UnicodeNameIsValid() { // Fix issue #370 var repository = new InMemoryRepository(); var service = new ChatService(new Mock<ICache>().Object, repository,new Mock<ICryptoService>().Object); var user = service.AddUser("ТарасБуга", clientId: null, userAgent: null, password: "password"); Assert.Equal("ТарасБуга", user.Name); } [Fact] public void ThrowsIfNameInUse() { var repository = new InMemoryRepository(); repository.Add(new ChatUser() { Name = "taken" }); var service = new ChatService(new Mock<ICache>().Object, repository,new Mock<ICryptoService>().Object); Assert.Throws<InvalidOperationException>(() => service.AddUser("taken", clientId: null, userAgent: null, password: null)); } [Fact] public void ThrowsIfNameIsNullOrEmpty() { var repository = new InMemoryRepository(); var service = new ChatService(new Mock<ICache>().Object, repository,new Mock<ICryptoService>().Object); Assert.Throws<InvalidOperationException>(() => service.AddUser(null, clientId: null, userAgent: null, password: null)); Assert.Throws<InvalidOperationException>(() => service.AddUser(String.Empty, clientId: null, userAgent: null, password: null)); } [Fact] public void ThrowsIfPasswordIsTooShort() { var repository = new InMemoryRepository(); var service = new ChatService(new Mock<ICache>().Object, repository,new Mock<ICryptoService>().Object); Assert.Throws<InvalidOperationException>(() => service.AddUser("SomeUser", clientId: null, userAgent: null, password: "short")); } [Fact] public void AddsUserToRepository() { var crypto = new Mock<ICryptoService>(); crypto.Setup(c => c.CreateSalt()).Returns("salted"); var repository = new InMemoryRepository(); var service = new ChatService(new Mock<ICache>().Object, repository,crypto.Object); service.AddUser("SomeUser", clientId: null, userAgent: null, password: "password"); var user = repository.GetUserByName("SomeUser"); Assert.NotNull(user); Assert.Equal("SomeUser", user.Name); Assert.Equal("salted", user.Salt); Assert.Equal("8f5793009fe15c2227e3528d0507413a83dff10635d3a6acf1ba3229a03380d8", user.HashedPassword); } [Fact] public void AddsAuthUserToRepository() { var repository = new InMemoryRepository(); var service = new ChatService(new Mock<ICache>().Object, repository,null); service.AddUser("SomeUser", "identity", "email"); var user = repository.GetUserByIdentity("identity"); Assert.NotNull(user); Assert.Equal("SomeUser", user.Name); Assert.Equal("identity", user.Identity); Assert.Equal("email", user.Email); Assert.Equal("0c83f57c786a0b4a39efab23731c7ebc", user.Hash); } [Fact] public void AddsNumberToUserNameIfTaken() { var repository = new InMemoryRepository(); repository.Add(new ChatUser { Name = "david", Id = "1" }); var service = new ChatService(new Mock<ICache>().Object, repository,null); service.AddUser("david", "idenity", null); var user = repository.GetUserByIdentity("idenity"); Assert.NotNull(user); Assert.Equal("david1", user.Name); Assert.Equal("idenity", user.Identity); Assert.Null(user.Email); Assert.Null(user.Hash); } } public class ChangeUserName { [Fact] public void ThrowsIfNameIsInvalid() { var repository = new InMemoryRepository(); var user = new ChatUser { Name = "Test" }; repository.Add(user); var service = new ChatService(new Mock<ICache>().Object, repository,new Mock<ICryptoService>().Object); Assert.Throws<InvalidOperationException>(() => service.ChangeUserName(user, "name with spaces")); } [Fact] public void ThrowsIfNameIsTaken() { var repository = new InMemoryRepository(); var user = new ChatUser { Name = "Test" }; repository.Add(user); repository.Add(new ChatUser() { Name = "taken" }); var service = new ChatService(new Mock<ICache>().Object, repository,new Mock<ICryptoService>().Object); Assert.Throws<InvalidOperationException>(() => service.ChangeUserName(user, "taken")); } [Fact] public void ThrowsIfUserNameIsSame() { var repository = new InMemoryRepository(); var user = new ChatUser { Name = "Test" }; repository.Add(user); var service = new ChatService(new Mock<ICache>().Object, repository,new Mock<ICryptoService>().Object); Assert.Throws<InvalidOperationException>(() => service.ChangeUserName(user, "Test")); } [Fact] public void UpdatesUserName() { var repository = new InMemoryRepository(); var user = new ChatUser { Name = "Test" }; repository.Add(user); var service = new ChatService(new Mock<ICache>().Object, repository,new Mock<ICryptoService>().Object); service.ChangeUserName(user, "Test2"); Assert.Equal("Test2", user.Name); } } public class ChangeUserPassword { [Fact] public void ThrowsUserPasswordDoesNotMatchOldPassword() { var repository = new InMemoryRepository(); var user = new ChatUser { Name = "Test", Salt = "salt", HashedPassword = "password".ToSha256("salt") }; repository.Add(user); var service = new ChatService(new Mock<ICache>().Object, repository,new Mock<ICryptoService>().Object); Assert.Throws<InvalidOperationException>(() => service.ChangeUserPassword(user, "passwor", "foo")); } [Fact] public void ThrowsIfNewPasswordIsNull() { var repository = new InMemoryRepository(); var user = new ChatUser { Name = "Test", Salt = "salt", HashedPassword = "password".ToSha256("salt") }; repository.Add(user); var service = new ChatService(new Mock<ICache>().Object, repository,new Mock<ICryptoService>().Object); Assert.Throws<InvalidOperationException>(() => service.ChangeUserPassword(user, "password", null)); } [Fact] public void UpatesUserPassword() { var repository = new InMemoryRepository(); var user = new ChatUser { Name = "Test", Salt = "pepper", HashedPassword = "password".ToSha256("pepper") }; repository.Add(user); var service = new ChatService(new Mock<ICache>().Object, repository,new Mock<ICryptoService>().Object); service.ChangeUserPassword(user, "password", "password2"); Assert.Equal("password2".ToSha256("pepper"), user.HashedPassword); } [Fact] public void EnsuresSaltedPassword() { var crypto = new Mock<ICryptoService>(); crypto.Setup(c => c.CreateSalt()).Returns("salt"); var repository = new InMemoryRepository(); var user = new ChatUser { Name = "Test", Salt = null, HashedPassword = "password".ToSha256(null) }; repository.Add(user); var service = new ChatService(new Mock<ICache>().Object, repository,crypto.Object); service.ChangeUserPassword(user, "password", "password"); Assert.Equal("salt", user.Salt); Assert.Equal("password".ToSha256("salt"), user.HashedPassword); } } public class AuthenticateUser { [Fact] public void ThrowsIfUserDoesNotExist() { var repository = new InMemoryRepository(); var service = new ChatService(new Mock<ICache>().Object, repository,new Mock<ICryptoService>().Object); Assert.Throws<InvalidOperationException>(() => service.AuthenticateUser("SomeUser", "foo")); } [Fact] public void ThrowsIfUserPasswordDoesNotMatch() { var repository = new InMemoryRepository(); repository.Add(new ChatUser { Name = "SomeUser", Salt = "salt", HashedPassword = "passwords".ToSha256("salt") }); var service = new ChatService(new Mock<ICache>().Object, repository,new Mock<ICryptoService>().Object); Assert.Throws<InvalidOperationException>(() => service.AuthenticateUser("SomeUser", "foo")); } [Fact] public void ThrowsIfUserPasswordNotSet() { var repository = new InMemoryRepository(); repository.Add(new ChatUser { Name = "SomeUser" }); var service = new ChatService(new Mock<ICache>().Object, repository,new Mock<ICryptoService>().Object); Assert.Throws<InvalidOperationException>(() => service.AuthenticateUser("SomeUser", "password")); } [Fact] public void DoesNotThrowIfPasswordsMatch() { var repository = new InMemoryRepository(); repository.Add(new ChatUser { Name = "foo", HashedPassword = "3049a1f8327e0215ea924b9e4e04cd4b0ff1800c74a536d9b81d3d8ced9994d3" }); var service = new ChatService(new Mock<ICache>().Object, repository,new Mock<ICryptoService>().Object); service.AuthenticateUser("foo", "passwords"); } [Fact] public void DoesNotThrowIfSaltedPasswordsMatch() { var repository = new InMemoryRepository(); repository.Add(new ChatUser { Name = "foo", Salt = "salted", HashedPassword = "8f5793009fe15c2227e3528d0507413a83dff10635d3a6acf1ba3229a03380d8" }); var service = new ChatService(new Mock<ICache>().Object, repository,new Mock<ICryptoService>().Object); service.AuthenticateUser("foo", "password"); } [Fact] public void EnsuresStoredPasswordIsSalted() { var crypto = new Mock<ICryptoService>(); crypto.Setup(c => c.CreateSalt()).Returns("salted"); var repository = new InMemoryRepository(); var user = new ChatUser { Name = "foo", HashedPassword = "3049a1f8327e0215ea924b9e4e04cd4b0ff1800c74a536d9b81d3d8ced9994d3" }; repository.Add(user); var service = new ChatService(new Mock<ICache>().Object, repository,crypto.Object); service.AuthenticateUser("foo", "passwords"); Assert.Equal("salted", user.Salt); Assert.Equal("9ce70d2ab42c9a9012ed6f80f85ab400ef1483f70e227a42b6d77faea204db26", user.HashedPassword); } } public class AddRoom { [Fact] public void ThrowsIfRoomNameIsLobby() { var repository = new InMemoryRepository(); var user = new ChatUser { Name = "foo" }; repository.Add(user); var service = new ChatService(new Mock<ICache>().Object, repository,new Mock<ICryptoService>().Object); Assert.Throws<InvalidOperationException>(() => service.AddRoom(user, "Lobby")); Assert.Throws<InvalidOperationException>(() => service.AddRoom(user, "LObbY")); } [Fact] public void ThrowsIfRoomNameInvalid() { var repository = new InMemoryRepository(); var user = new ChatUser { Name = "foo" }; repository.Add(user); var service = new ChatService(new Mock<ICache>().Object, repository,new Mock<ICryptoService>().Object); Assert.Throws<InvalidOperationException>(() => service.AddRoom(user, "Invalid name")); } [Fact] public void ThrowsIfRoomNameContainsPeriod() { var repository = new InMemoryRepository(); var user = new ChatUser { Name = "foo" }; repository.Add(user); var service = new ChatService(new Mock<ICache>().Object, repository,new Mock<ICryptoService>().Object); Assert.Throws<InvalidOperationException>(() => service.AddRoom(user, "Invalid.name")); } [Fact] public void AddsUserAsCreatorAndOwner() { var repository = new InMemoryRepository(); var user = new ChatUser { Name = "foo" }; repository.Add(user); var service = new ChatService(new Mock<ICache>().Object, repository,new Mock<ICryptoService>().Object); ChatRoom room = service.AddRoom(user, "NewRoom"); Assert.NotNull(room); Assert.Equal("NewRoom", room.Name); Assert.Same(room, repository.GetRoomByName("NewRoom")); Assert.True(room.Owners.Contains(user)); Assert.Same(room.Creator, user); Assert.True(user.OwnedRooms.Contains(room)); } } public class JoinRoom { [Fact] public void AddsUserToRoom() { var repository = new InMemoryRepository(); var user = new ChatUser { Name = "foo" }; repository.Add(user); var room = new ChatRoom { Name = "Room" }; var service = new ChatService(new Mock<ICache>().Object, repository,new Mock<ICryptoService>().Object); service.JoinRoom(user, room, null); Assert.True(user.Rooms.Contains(room)); Assert.True(room.Users.Contains(user)); } [Fact] public void AddsUserToRoomIfAllowedAndRoomIsPrivate() { var repository = new InMemoryRepository(); var user = new ChatUser { Name = "foo" }; repository.Add(user); var room = new ChatRoom { Name = "Room", Private = true }; room.AllowedUsers.Add(user); user.AllowedRooms.Add(room); var service = new ChatService(new Mock<ICache>().Object, repository,new Mock<ICryptoService>().Object); service.JoinRoom(user, room, null); Assert.True(user.Rooms.Contains(room)); Assert.True(room.Users.Contains(user)); } [Fact] public void ThrowsIfRoomIsPrivateAndNotAllowed() { var repository = new InMemoryRepository(); var user = new ChatUser { Name = "foo" }; repository.Add(user); var room = new ChatRoom { Name = "Room", Private = true }; var service = new ChatService(new Mock<ICache>().Object, repository,new Mock<ICryptoService>().Object); Assert.Throws<InvalidOperationException>(() => service.JoinRoom(user, room, null)); } [Fact] public void AddsUserToRoomIfUserIsAdminAndRoomIsPrivate() { var repository = new InMemoryRepository(); var user = new ChatUser { Name = "foo", IsAdmin = true }; repository.Add(user); var room = new ChatRoom { Name = "Room", Private = true }; var service = new ChatService(new Mock<ICache>().Object, repository,new Mock<ICryptoService>().Object); service.JoinRoom(user, room, null); Assert.True(user.Rooms.Contains(room)); Assert.True(room.Users.Contains(user)); } } public class UpdateActivity { [Fact] public void CanUpdateActivity() { var repository = new InMemoryRepository(); var user = new ChatUser { Name = "foo", Status = (int)UserStatus.Inactive, IsAfk = true, AfkNote = "note!?" }; repository.Add(user); var service = new ChatService(new Mock<ICache>().Object, repository,new Mock<ICryptoService>().Object); service.UpdateActivity(user, "client1", userAgent: null); var clients = user.ConnectedClients.ToList(); Assert.Equal((int)UserStatus.Active, user.Status); Assert.Equal(1, clients.Count); Assert.Equal("client1", clients[0].Id); Assert.Same(user, clients[0].User); Assert.Null(user.AfkNote); Assert.False(user.IsAfk); } } public class LeaveRoom { [Fact] public void RemovesUserFromRoom() { var repository = new InMemoryRepository(); var user = new ChatUser { Name = "foo" }; repository.Add(user); var room = new ChatRoom { Name = "Room" }; room.Users.Add(user); user.Rooms.Add(room); var service = new ChatService(new Mock<ICache>().Object, repository,new Mock<ICryptoService>().Object); service.LeaveRoom(user, room); Assert.False(user.Rooms.Contains(room)); Assert.False(room.Users.Contains(user)); } } public class AddMessage { [Fact] public void AddsNewMessageToRepository() { var repository = new InMemoryRepository(); var user = new ChatUser { Name = "foo" }; repository.Add(user); var room = new ChatRoom { Name = "Room" }; repository.Add(room); room.Users.Add(user); user.Rooms.Add(room); var service = new ChatService(new Mock<ICache>().Object, repository,new Mock<ICryptoService>().Object); ChatMessage message = service.AddMessage(user, room, Guid.NewGuid().ToString(), "Content"); Assert.NotNull(message); Assert.Same(message, room.Messages.First()); Assert.Equal("Content", message.Content); } } public class AddOwner { [Fact] public void ThrowsIfUserIsNotOwner() { var repository = new InMemoryRepository(); var user = new ChatUser { Name = "foo" }; repository.Add(user); var room = new ChatRoom { Name = "Room" }; room.Users.Add(user); user.Rooms.Add(room); var service = new ChatService(new Mock<ICache>().Object, repository,new Mock<ICryptoService>().Object); Assert.Throws<InvalidOperationException>(() => service.AddOwner(user, user, room)); } [Fact] public void ThrowsIfUserIsAlreadyAnOwner() { var repository = new InMemoryRepository(); var user = new ChatUser { Name = "foo" }; repository.Add(user); var room = new ChatRoom { Name = "Room" }; room.Users.Add(user); room.Owners.Add(user); user.OwnedRooms.Add(room); user.Rooms.Add(room); var service = new ChatService(new Mock<ICache>().Object, repository,new Mock<ICryptoService>().Object); Assert.Throws<InvalidOperationException>(() => service.AddOwner(user, user, room)); } [Fact] public void MakesUserOwner() { var repository = new InMemoryRepository(); var user = new ChatUser { Name = "foo" }; var user2 = new ChatUser { Name = "foo2" }; repository.Add(user); repository.Add(user2); var room = new ChatRoom { Name = "Room", Creator = user }; room.Owners.Add(user); user.OwnedRooms.Add(room); user.Rooms.Add(room); room.Users.Add(user); var service = new ChatService(new Mock<ICache>().Object, repository,new Mock<ICryptoService>().Object); service.AddOwner(user, user2, room); Assert.True(room.Owners.Contains(user2)); Assert.True(user2.OwnedRooms.Contains(room)); } [Fact] public void MakesUserOwnerIfUserAlreadyAllowed() { var repository = new InMemoryRepository(); var user = new ChatUser { Name = "foo" }; var user2 = new ChatUser { Name = "foo2" }; repository.Add(user); repository.Add(user2); var room = new ChatRoom { Name = "Room", Private = true, Creator = user }; room.Owners.Add(user); user.OwnedRooms.Add(room); user.Rooms.Add(room); room.Users.Add(user); user2.AllowedRooms.Add(room); room.AllowedUsers.Add(user2); var service = new ChatService(new Mock<ICache>().Object, repository,new Mock<ICryptoService>().Object); service.AddOwner(user, user2, room); Assert.True(room.Owners.Contains(user2)); Assert.True(user2.OwnedRooms.Contains(room)); } [Fact] public void MakesOwnerAllowedIfRoomLocked() { var repository = new InMemoryRepository(); var user = new ChatUser { Name = "foo" }; var user2 = new ChatUser { Name = "foo2" }; repository.Add(user); repository.Add(user2); var room = new ChatRoom { Name = "Room", Creator = user, Private = true }; room.Owners.Add(user); user.OwnedRooms.Add(room); user.Rooms.Add(room); room.Users.Add(user); var service = new ChatService(new Mock<ICache>().Object, repository,new Mock<ICryptoService>().Object); service.AddOwner(user, user2, room); Assert.True(user2.AllowedRooms.Contains(room)); Assert.True(room.AllowedUsers.Contains(user2)); Assert.True(room.Owners.Contains(user2)); Assert.True(user2.OwnedRooms.Contains(room)); } [Fact] public void NonOwnerAdminCanAddUserAsOwner() { var repository = new InMemoryRepository(); var admin = new ChatUser { Name = "foo", IsAdmin = true }; var user2 = new ChatUser { Name = "foo2" }; repository.Add(admin); repository.Add(user2); var room = new ChatRoom { Name = "Room", Creator = admin }; admin.Rooms.Add(room); room.Users.Add(admin); var service = new ChatService(new Mock<ICache>().Object, repository,new Mock<ICryptoService>().Object); service.AddOwner(admin, user2, room); Assert.True(room.Owners.Contains(user2)); Assert.True(user2.OwnedRooms.Contains(room)); } // TODO: admin can add self as owner } public class RemoveOwner { [Fact] public void ThrowsIfTargettedUserIsNotOwner() { var repository = new InMemoryRepository(); var user = new ChatUser { Name = "foo" }; var user2 = new ChatUser { Name = "foo2" }; repository.Add(user); repository.Add(user2); var room = new ChatRoom { Name = "Room", }; room.Creator = user; user.Rooms.Add(room); user2.Rooms.Add(room); room.Users.Add(user); room.Users.Add(user2); var service = new ChatService(new Mock<ICache>().Object, repository,new Mock<ICryptoService>().Object); Assert.Throws<InvalidOperationException>(() => service.RemoveOwner(user, user2, room)); } [Fact] public void ThrowsIfActingUserIsNotCreatorOrAdmin() { var repository = new InMemoryRepository(); var user = new ChatUser { Name = "foo" }; var user2 = new ChatUser { Name = "foo2" }; repository.Add(user); repository.Add(user2); var room = new ChatRoom { Name = "Room", }; user.Rooms.Add(room); user2.Rooms.Add(room); room.Users.Add(user); room.Users.Add(user2); room.Owners.Add(user); user.OwnedRooms.Add(room); room.Owners.Add(user2); user2.OwnedRooms.Add(room); var service = new ChatService(new Mock<ICache>().Object, repository,new Mock<ICryptoService>().Object); Assert.Throws<InvalidOperationException>(() => service.RemoveOwner(user, user2, room)); } [Fact] public void RemovesOwnerIfActingUserIsAdmin() { var repository = new InMemoryRepository(); var admin = new ChatUser { Name = "foo", IsAdmin = true }; var user2 = new ChatUser { Name = "foo2" }; repository.Add(admin); repository.Add(user2); var room = new ChatRoom { Name = "Room", }; admin.Rooms.Add(room); user2.Rooms.Add(room); room.Users.Add(admin); room.Users.Add(user2); room.Owners.Add(user2); user2.OwnedRooms.Add(room); var service = new ChatService(new Mock<ICache>().Object, repository,new Mock<ICryptoService>().Object); service.RemoveOwner(admin, user2, room); Assert.False(room.Owners.Contains(user2)); Assert.False(user2.OwnedRooms.Contains(room)); } } public class KickUser { [Fact] public void ThrowsIfKickSelf() { var repository = new InMemoryRepository(); var user = new ChatUser { Name = "foo" }; repository.Add(user); var room = new ChatRoom { Name = "Room", Creator = user }; room.Owners.Add(user); user.OwnedRooms.Add(room); user.Rooms.Add(room); room.Users.Add(user); var service = new ChatService(new Mock<ICache>().Object, repository,new Mock<ICryptoService>().Object); Assert.Throws<InvalidOperationException>(() => service.KickUser(user, user, room)); } [Fact] public void ThrowsIfUserIsNotOwnerAndNotAdmin() { var repository = new InMemoryRepository(); var user = new ChatUser { Name = "foo" }; var user2 = new ChatUser { Name = "foo2" }; repository.Add(user); repository.Add(user2); var room = new ChatRoom { Name = "Room", }; user.Rooms.Add(room); user2.Rooms.Add(room); room.Users.Add(user); room.Users.Add(user2); var service = new ChatService(new Mock<ICache>().Object, repository,new Mock<ICryptoService>().Object); Assert.Throws<InvalidOperationException>(() => service.KickUser(user, user2, room)); } [Fact] public void ThrowsIfTargetUserNotInRoom() { var repository = new InMemoryRepository(); var user = new ChatUser { Name = "foo" }; var user2 = new ChatUser { Name = "foo2" }; repository.Add(user); repository.Add(user2); var room = new ChatRoom { Name = "Room", Creator = user }; user.OwnedRooms.Add(room); room.Owners.Add(user); user.Rooms.Add(room); room.Users.Add(user); var service = new ChatService(new Mock<ICache>().Object, repository,new Mock<ICryptoService>().Object); Assert.Throws<InvalidOperationException>(() => service.KickUser(user, user2, room)); } [Fact] public void ThrowsIfOwnerTriesToRemoveOwner() { var repository = new InMemoryRepository(); var user = new ChatUser { Name = "foo" }; var user2 = new ChatUser { Name = "foo2" }; repository.Add(user); repository.Add(user2); var room = new ChatRoom { Name = "Room", }; user.OwnedRooms.Add(room); room.Owners.Add(user); user2.OwnedRooms.Add(room); room.Owners.Add(user2); user.Rooms.Add(room); user2.Rooms.Add(room); room.Users.Add(user); room.Users.Add(user2); var service = new ChatService(new Mock<ICache>().Object, repository,new Mock<ICryptoService>().Object); Assert.Throws<InvalidOperationException>(() => service.KickUser(user, user2, room)); } [Fact] public void DoesNotThrowIfCreatorKicksOwner() { var repository = new InMemoryRepository(); var user = new ChatUser { Name = "foo" }; var user2 = new ChatUser { Name = "foo2" }; repository.Add(user); repository.Add(user2); var room = new ChatRoom { Name = "Room", Creator = user }; user.OwnedRooms.Add(room); room.Owners.Add(user); user2.OwnedRooms.Add(room); room.Owners.Add(user2); user.Rooms.Add(room); user2.Rooms.Add(room); room.Users.Add(user); room.Users.Add(user2); var service = new ChatService(new Mock<ICache>().Object, repository,new Mock<ICryptoService>().Object); service.KickUser(user, user2, room); Assert.False(user2.Rooms.Contains(room)); Assert.False(room.Users.Contains(user2)); } [Fact] public void AdminCanKickUser() { var repository = new InMemoryRepository(); var admin = new ChatUser { Name = "foo", IsAdmin = true }; var user2 = new ChatUser { Name = "foo2" }; repository.Add(admin); repository.Add(user2); var room = new ChatRoom { Name = "Room", }; admin.Rooms.Add(room); user2.Rooms.Add(room); room.Users.Add(admin); room.Users.Add(user2); var service = new ChatService(new Mock<ICache>().Object, repository,new Mock<ICryptoService>().Object); service.KickUser(admin, user2, room); Assert.False(user2.Rooms.Contains(room)); Assert.False(room.Users.Contains(user2)); } [Fact] public void DoesNotThrowIfAdminKicksOwner() { var repository = new InMemoryRepository(); var admin = new ChatUser { Name = "foo", IsAdmin = true }; var user2 = new ChatUser { Name = "foo2" }; repository.Add(admin); repository.Add(user2); var room = new ChatRoom { Name = "Room" }; user2.OwnedRooms.Add(room); room.Owners.Add(user2); admin.Rooms.Add(room); user2.Rooms.Add(room); room.Users.Add(admin); room.Users.Add(user2); var service = new ChatService(new Mock<ICache>().Object, repository,new Mock<ICryptoService>().Object); service.KickUser(admin, user2, room); Assert.False(user2.Rooms.Contains(room)); Assert.False(room.Users.Contains(user2)); } [Fact] public void AdminCanKickCreator() { var repository = new InMemoryRepository(); var admin = new ChatUser { Name = "foo", IsAdmin = true }; var creator = new ChatUser { Name = "foo2" }; repository.Add(admin); repository.Add(creator); var room = new ChatRoom { Name = "Room", Creator = creator }; creator.OwnedRooms.Add(room); room.Owners.Add(creator); admin.Rooms.Add(room); creator.Rooms.Add(room); room.Users.Add(admin); room.Users.Add(creator); var service = new ChatService(new Mock<ICache>().Object, repository,new Mock<ICryptoService>().Object); service.KickUser(admin, creator, room); Assert.False(creator.Rooms.Contains(room)); Assert.False(room.Users.Contains(creator)); } [Fact] public void ThrowsIfOwnerTriesToRemoveAdmin() { var repository = new InMemoryRepository(); var admin = new ChatUser { Name = "foo", IsAdmin = true }; var owner = new ChatUser { Name = "foo2" }; repository.Add(admin); repository.Add(owner); var room = new ChatRoom { Name = "Room", }; owner.OwnedRooms.Add(room); room.Owners.Add(owner); admin.Rooms.Add(room); owner.Rooms.Add(room); room.Users.Add(admin); room.Users.Add(owner); var service = new ChatService(new Mock<ICache>().Object, repository,new Mock<ICryptoService>().Object); Assert.Throws<InvalidOperationException>(() => service.KickUser(owner, admin, room)); } [Fact] public void AdminCanKickAdmin() { var repository = new InMemoryRepository(); var admin = new ChatUser { Name = "foo", IsAdmin = true }; var otherAdmin = new ChatUser { Name = "foo2", IsAdmin = true }; repository.Add(admin); repository.Add(otherAdmin); var room = new ChatRoom { Name = "Room" }; admin.Rooms.Add(room); otherAdmin.Rooms.Add(room); room.Users.Add(admin); room.Users.Add(otherAdmin); var service = new ChatService(new Mock<ICache>().Object, repository,new Mock<ICryptoService>().Object); service.KickUser(admin, otherAdmin, room); Assert.False(otherAdmin.Rooms.Contains(room)); Assert.False(room.Users.Contains(otherAdmin)); } } public class DisconnectClient { [Fact] public void RemovesClientFromUserClientList() { var repository = new InMemoryRepository(); var user = new ChatUser { Name = "foo", Status = (int)UserStatus.Inactive }; user.ConnectedClients.Add(new ChatClient { Id = "foo", User = user }); user.ConnectedClients.Add(new ChatClient { Id = "bar", User = user }); repository.Add(user); var service = new ChatService(new Mock<ICache>().Object, repository,new Mock<ICryptoService>().Object); service.DisconnectClient("foo"); Assert.Equal(1, user.ConnectedClients.Count); Assert.Equal("bar", user.ConnectedClients.First().Id); } [Fact] public void MarksUserAsOfflineIfNoMoreClients() { var repository = new InMemoryRepository(); var user = new ChatUser { Name = "foo", Status = (int)UserStatus.Inactive }; user.ConnectedClients.Add(new ChatClient { Id = "foo", User = user }); repository.Add(user); var service = new ChatService(new Mock<ICache>().Object, repository,new Mock<ICryptoService>().Object); service.DisconnectClient("foo"); Assert.Equal(0, user.ConnectedClients.Count); Assert.Equal((int)UserStatus.Offline, user.Status); } [Fact] public void ReturnsNullIfNoUserForClientId() { var repository = new InMemoryRepository(); var service = new ChatService(new Mock<ICache>().Object, repository,new Mock<ICryptoService>().Object); ChatUser user = service.DisconnectClient("foo"); Assert.Null(user); } } public class LockRoom { [Fact] public void LocksRoomIfOwner() { var repository = new InMemoryRepository(); var user = new ChatUser { Name = "foo" }; repository.Add(user); var room = new ChatRoom { Name = "Room" }; room.Users.Add(user); room.Owners.Add(user); user.OwnedRooms.Add(room); user.Rooms.Add(room); var service = new ChatService(new Mock<ICache>().Object, repository,new Mock<ICryptoService>().Object); service.LockRoom(user, room); Assert.True(room.Private); Assert.True(user.AllowedRooms.Contains(room)); Assert.True(room.AllowedUsers.Contains(user)); } [Fact] public void ThrowsIfRoomAlreadyLocked() { var repository = new InMemoryRepository(); var user = new ChatUser { Name = "foo" }; repository.Add(user); var room = new ChatRoom { Name = "Room", Creator = user, Private = true }; room.Owners.Add(user); user.OwnedRooms.Add(room); room.AllowedUsers.Add(user); user.AllowedRooms.Add(room); user.Rooms.Add(room); room.Users.Add(user); var service = new ChatService(new Mock<ICache>().Object, repository,new Mock<ICryptoService>().Object); Assert.Throws<InvalidOperationException>(() => service.LockRoom(user, room)); } [Fact] public void LocksRoom() { var repository = new InMemoryRepository(); var user = new ChatUser { Name = "foo" }; repository.Add(user); var room = new ChatRoom { Name = "Room", Creator = user }; room.Owners.Add(user); user.OwnedRooms.Add(room); user.Rooms.Add(room); room.Users.Add(user); var service = new ChatService(new Mock<ICache>().Object, repository,new Mock<ICryptoService>().Object); service.LockRoom(user, room); Assert.True(room.Private); Assert.True(user.AllowedRooms.Contains(room)); Assert.True(room.AllowedUsers.Contains(user)); } [Fact] public void MakesAllUsersAllowed() { var repository = new InMemoryRepository(); var creator = new ChatUser { Name = "foo" }; var users = Enumerable.Range(0, 5).Select(i => new ChatUser { Name = "user_" + i }).ToList(); var offlineUsers = Enumerable.Range(6, 10).Select(i => new ChatUser { Name = "user_" + i, Status = (int)UserStatus.Offline }).ToList(); var room = new ChatRoom { Name = "room", Creator = creator }; room.Owners.Add(creator); creator.OwnedRooms.Add(room); repository.Add(room); foreach (var u in users) { room.Users.Add(u); u.Rooms.Add(room); repository.Add(u); } foreach (var u in offlineUsers) { room.Users.Add(u); u.Rooms.Add(room); repository.Add(u); } var service = new ChatService(new Mock<ICache>().Object, repository,new Mock<ICryptoService>().Object); service.LockRoom(creator, room); foreach (var u in users) { Assert.True(u.AllowedRooms.Contains(room)); Assert.True(room.AllowedUsers.Contains(u)); } foreach (var u in offlineUsers) { Assert.False(u.AllowedRooms.Contains(room)); Assert.False(room.AllowedUsers.Contains(u)); } } [Fact] public void LocksRoomIfAdmin() { var repository = new InMemoryRepository(); var admin = new ChatUser { Name = "foo", IsAdmin = true }; repository.Add(admin); var room = new ChatRoom { Name = "Room" }; room.Users.Add(admin); admin.Rooms.Add(room); var service = new ChatService(new Mock<ICache>().Object, repository,new Mock<ICryptoService>().Object); service.LockRoom(admin, room); Assert.True(room.Private); Assert.True(admin.AllowedRooms.Contains(room)); Assert.True(room.AllowedUsers.Contains(admin)); } } public class AllowUser { [Fact] public void ThrowsIfRoomNotPrivate() { var repository = new InMemoryRepository(); var user = new ChatUser { Name = "foo" }; var user2 = new ChatUser { Name = "foo2" }; repository.Add(user); repository.Add(user2); var room = new ChatRoom { Name = "Room", }; room.Users.Add(user); user.Rooms.Add(room); room.Owners.Add(user); user.OwnedRooms.Add(room); var service = new ChatService(new Mock<ICache>().Object, repository,new Mock<ICryptoService>().Object); Assert.Throws<InvalidOperationException>(() => service.AllowUser(user, user2, room)); } [Fact] public void ThrowsIfUserIsNotOwner() { var repository = new InMemoryRepository(); var user = new ChatUser { Name = "foo" }; repository.Add(user); var room = new ChatRoom { Name = "Room", Private = true }; room.Users.Add(user); user.Rooms.Add(room); var service = new ChatService(new Mock<ICache>().Object, repository,new Mock<ICryptoService>().Object); Assert.Throws<InvalidOperationException>(() => service.AllowUser(user, user, room)); } [Fact] public void ThrowsIfUserIsAlreadyAllowed() { var repository = new InMemoryRepository(); var user = new ChatUser { Name = "foo" }; var user2 = new ChatUser { Name = "foo2" }; repository.Add(user); repository.Add(user2); var room = new ChatRoom { Name = "Room", Private = true }; room.Users.Add(user); room.AllowedUsers.Add(user2); room.Owners.Add(user); user.OwnedRooms.Add(room); user.Rooms.Add(room); user2.AllowedRooms.Add(room); var service = new ChatService(new Mock<ICache>().Object, repository,new Mock<ICryptoService>().Object); Assert.Throws<InvalidOperationException>(() => service.AllowUser(user, user2, room)); } [Fact] public void AllowsUserIntoRoom() { var repository = new InMemoryRepository(); var user = new ChatUser { Name = "foo" }; var user2 = new ChatUser { Name = "foo2" }; repository.Add(user); repository.Add(user2); var room = new ChatRoom { Name = "Room", Private = true }; room.Owners.Add(user); user.OwnedRooms.Add(room); user.Rooms.Add(room); room.Users.Add(user); var service = new ChatService(new Mock<ICache>().Object, repository,new Mock<ICryptoService>().Object); service.AllowUser(user, user2, room); Assert.True(room.AllowedUsers.Contains(user2)); Assert.True(user2.AllowedRooms.Contains(room)); } [Fact] public void AdminCanAllowUserIntoRoom() { var repository = new InMemoryRepository(); var admin = new ChatUser { Name = "foo", IsAdmin = true }; repository.Add(admin); var room = new ChatRoom { Name = "Room", Private = true }; room.Users.Add(admin); admin.Rooms.Add(room); var service = new ChatService(new Mock<ICache>().Object, repository,new Mock<ICryptoService>().Object); service.AllowUser(admin, admin, room); Assert.True(room.AllowedUsers.Contains(admin)); Assert.True(admin.AllowedRooms.Contains(room)); } } public class UnallowUser { [Fact] public void ThrowsIfRoomNotPrivate() { var repository = new InMemoryRepository(); var user = new ChatUser { Name = "foo" }; var user2 = new ChatUser { Name = "foo2" }; repository.Add(user); repository.Add(user2); var room = new ChatRoom { Name = "Room", }; room.Users.Add(user); user.Rooms.Add(room); room.Owners.Add(user); user.OwnedRooms.Add(room); var service = new ChatService(new Mock<ICache>().Object, repository,new Mock<ICryptoService>().Object); Assert.Throws<InvalidOperationException>(() => service.UnallowUser(user, user2, room)); } [Fact] public void ThrowsIfTargetUserIsCreator() { var repository = new InMemoryRepository(); var user = new ChatUser { Name = "foo" }; repository.Add(user); var room = new ChatRoom { Name = "Room", Private = true, Creator = user }; room.Users.Add(user); user.Rooms.Add(room); room.Owners.Add(user); user.OwnedRooms.Add(room); room.AllowedUsers.Add(user); user.AllowedRooms.Add(room); var service = new ChatService(new Mock<ICache>().Object, repository,new Mock<ICryptoService>().Object); Assert.Throws<InvalidOperationException>(() => service.UnallowUser(user, user, room)); } [Fact] public void ThrowsIfUserIsNotOwner() { var repository = new InMemoryRepository(); var user = new ChatUser { Name = "foo" }; var user2 = new ChatUser { Name = "foo2" }; repository.Add(user); repository.Add(user2); var room = new ChatRoom { Name = "Room", Private = true }; room.Users.Add(user); user.Rooms.Add(room); var service = new ChatService(new Mock<ICache>().Object, repository,new Mock<ICryptoService>().Object); Assert.Throws<InvalidOperationException>(() => service.UnallowUser(user, user2, room)); } [Fact] public void DoesNotThrowIfUserIsAdminButIsNotOwner() { var repository = new InMemoryRepository(); var admin = new ChatUser { Name = "foo", IsAdmin = true }; var user2 = new ChatUser { Name = "foo2" }; repository.Add(admin); repository.Add(user2); var room = new ChatRoom { Name = "Room", Private = true }; room.AllowedUsers.Add(user2); room.Users.Add(admin); admin.Rooms.Add(room); user2.AllowedRooms.Add(room); var service = new ChatService(new Mock<ICache>().Object, repository,new Mock<ICryptoService>().Object); service.UnallowUser(admin, user2, room); Assert.False(room.Users.Contains(user2)); Assert.False(user2.Rooms.Contains(room)); Assert.False(room.AllowedUsers.Contains(user2)); Assert.False(user2.AllowedRooms.Contains(room)); } [Fact] public void ThrowsIfUserIsNotAllowed() { var repository = new InMemoryRepository(); var user = new ChatUser { Name = "foo" }; var user2 = new ChatUser { Name = "foo2" }; repository.Add(user); repository.Add(user2); var room = new ChatRoom { Name = "Room", Private = true }; room.Users.Add(user); room.Owners.Add(user); user.OwnedRooms.Add(room); user.Rooms.Add(room); var service = new ChatService(new Mock<ICache>().Object, repository,new Mock<ICryptoService>().Object); Assert.Throws<InvalidOperationException>(() => service.UnallowUser(user, user2, room)); } [Fact] public void ThrowIfOwnerTriesToUnallowOwner() { var repository = new InMemoryRepository(); var user = new ChatUser { Name = "foo" }; var user2 = new ChatUser { Name = "foo2" }; repository.Add(user); repository.Add(user2); var room = new ChatRoom { Name = "Room", Private = true }; user.OwnedRooms.Add(room); room.Owners.Add(user); user.AllowedRooms.Add(room); room.AllowedUsers.Add(user); user2.OwnedRooms.Add(room); room.Owners.Add(user2); user2.AllowedRooms.Add(room); room.AllowedUsers.Add(user2); user.Rooms.Add(room); user2.Rooms.Add(room); room.Users.Add(user); room.Users.Add(user2); var service = new ChatService(new Mock<ICache>().Object, repository,new Mock<ICryptoService>().Object); Assert.Throws<InvalidOperationException>(() => service.UnallowUser(user, user2, room)); } [Fact] public void UnallowsAndRemovesUserFromRoom() { var repository = new InMemoryRepository(); var user = new ChatUser { Name = "foo" }; var user2 = new ChatUser { Name = "foo2" }; repository.Add(user); repository.Add(user2); var room = new ChatRoom { Name = "Room", Private = true }; room.AllowedUsers.Add(user2); room.Owners.Add(user); room.Users.Add(user); user.OwnedRooms.Add(room); user.Rooms.Add(room); user2.AllowedRooms.Add(room); var service = new ChatService(new Mock<ICache>().Object, repository,new Mock<ICryptoService>().Object); service.UnallowUser(user, user2, room); Assert.False(room.Users.Contains(user2)); Assert.False(user2.Rooms.Contains(room)); Assert.False(room.AllowedUsers.Contains(user2)); Assert.False(user2.AllowedRooms.Contains(room)); } [Fact] public void AdminCanUnallowUser() { var repository = new InMemoryRepository(); var admin = new ChatUser { Name = "foo", IsAdmin = true }; var user = new ChatUser { Name = "foo" }; repository.Add(admin); var room = new ChatRoom { Name = "Room", Private = true }; room.Users.Add(admin); admin.Rooms.Add(room); room.AllowedUsers.Add(admin); admin.AllowedRooms.Add(room); room.AllowedUsers.Add(user); user.AllowedRooms.Add(room); var service = new ChatService(new Mock<ICache>().Object, repository,new Mock<ICryptoService>().Object); service.UnallowUser(admin, user, room); Assert.False(room.Users.Contains(user)); Assert.False(user.Rooms.Contains(room)); Assert.False(room.AllowedUsers.Contains(user)); Assert.False(user.AllowedRooms.Contains(room)); } [Fact] public void AdminCanUnallowOwner() { var repository = new InMemoryRepository(); var admin = new ChatUser { Name = "foo", IsAdmin = true }; var owner = new ChatUser { Name = "foo" }; repository.Add(admin); var room = new ChatRoom { Name = "Room", Private = true }; room.Users.Add(admin); admin.Rooms.Add(room); room.Users.Add(owner); owner.Rooms.Add(room); room.Owners.Add(owner); owner.OwnedRooms.Add(room); room.AllowedUsers.Add(admin); admin.AllowedRooms.Add(room); room.AllowedUsers.Add(owner); owner.AllowedRooms.Add(room); var service = new ChatService(new Mock<ICache>().Object, repository,new Mock<ICryptoService>().Object); service.UnallowUser(admin, owner, room); Assert.False(room.Users.Contains(owner)); Assert.False(owner.Rooms.Contains(room)); Assert.False(room.AllowedUsers.Contains(owner)); Assert.False(owner.AllowedRooms.Contains(room)); } [Fact] public void AdminCanUnallowCreator() { var repository = new InMemoryRepository(); var admin = new ChatUser { Name = "foo", IsAdmin = true }; var creator = new ChatUser { Name = "foo" }; repository.Add(admin); var room = new ChatRoom { Name = "Room", Private = true, Creator = creator }; room.Users.Add(admin); admin.Rooms.Add(room); room.Owners.Add(admin); admin.OwnedRooms.Add(room); room.Owners.Add(creator); creator.OwnedRooms.Add(room); room.AllowedUsers.Add(admin); admin.AllowedRooms.Add(room); room.AllowedUsers.Add(creator); creator.AllowedRooms.Add(room); var service = new ChatService(new Mock<ICache>().Object, repository,new Mock<ICryptoService>().Object); service.UnallowUser(admin, creator, room); Assert.False(room.Users.Contains(creator)); Assert.False(creator.Rooms.Contains(room)); Assert.False(room.AllowedUsers.Contains(creator)); Assert.False(creator.AllowedRooms.Contains(room)); } [Fact] public void ThrowIfOwnerTriesToUnallowAdmin() { var repository = new InMemoryRepository(); var owner = new ChatUser { Name = "foo" }; var admin = new ChatUser { Name = "foo2", IsAdmin = true }; repository.Add(owner); repository.Add(admin); var room = new ChatRoom { Name = "Room", Private = true }; owner.OwnedRooms.Add(room); room.Owners.Add(owner); owner.AllowedRooms.Add(room); room.AllowedUsers.Add(owner); admin.AllowedRooms.Add(room); room.AllowedUsers.Add(admin); owner.Rooms.Add(room); admin.Rooms.Add(room); room.Users.Add(owner); room.Users.Add(admin); var service = new ChatService(new Mock<ICache>().Object, repository,new Mock<ICryptoService>().Object); Assert.Throws<InvalidOperationException>(() => service.UnallowUser(owner, admin, room)); } [Fact] public void AdminCanUnallowAdmin() { var repository = new InMemoryRepository(); var admin = new ChatUser { Name = "foo", IsAdmin = true }; var otherAdmin = new ChatUser { Name = "foo", IsAdmin = true }; repository.Add(admin); var room = new ChatRoom { Name = "Room", Private = true }; room.Users.Add(admin); admin.Rooms.Add(room); room.Users.Add(otherAdmin); otherAdmin.Rooms.Add(room); room.AllowedUsers.Add(admin); admin.AllowedRooms.Add(room); room.AllowedUsers.Add(otherAdmin); otherAdmin.AllowedRooms.Add(room); var service = new ChatService(new Mock<ICache>().Object, repository,new Mock<ICryptoService>().Object); service.UnallowUser(admin, otherAdmin, room); Assert.False(room.Users.Contains(otherAdmin)); Assert.False(otherAdmin.Rooms.Contains(room)); Assert.False(room.AllowedUsers.Contains(otherAdmin)); Assert.False(otherAdmin.AllowedRooms.Contains(room)); } } public class AddAdmin { [Fact] public void ThrowsIfActingUserIsNotAdmin() { var repository = new InMemoryRepository(); var nonAdmin = new ChatUser { Name = "foo" }; var user = new ChatUser { Name = "foo2" }; repository.Add(nonAdmin); repository.Add(user); var service = new ChatService(new Mock<ICache>().Object, repository,new Mock<ICryptoService>().Object); Assert.Throws<InvalidOperationException>(() => service.AddAdmin(nonAdmin, user)); } [Fact] public void MakesUserAdmin() { var repository = new InMemoryRepository(); var admin = new ChatUser { Name = "foo", IsAdmin = true }; var user = new ChatUser { Name = "foo2", IsAdmin = false }; repository.Add(admin); repository.Add(user); var service = new ChatService(new Mock<ICache>().Object, repository,new Mock<ICryptoService>().Object); service.AddAdmin(admin, user); Assert.True(user.IsAdmin); } } public class RemoveAdmin { [Fact] public void ThrowsIfActingUserIsNotAdmin() { var repository = new InMemoryRepository(); var nonAdmin = new ChatUser { Name = "foo", IsAdmin = false }; var user = new ChatUser { Name = "foo2", IsAdmin = true }; repository.Add(nonAdmin); repository.Add(user); var service = new ChatService(new Mock<ICache>().Object, repository,new Mock<ICryptoService>().Object); Assert.Throws<InvalidOperationException>(() => service.RemoveAdmin(nonAdmin, user)); } [Fact] public void MakesUserAdmin() { var repository = new InMemoryRepository(); var admin = new ChatUser { Name = "foo", IsAdmin = true }; var user = new ChatUser { Name = "foo2", IsAdmin = true }; repository.Add(admin); repository.Add(user); var service = new ChatService(new Mock<ICache>().Object, repository,new Mock<ICryptoService>().Object); service.RemoveAdmin(admin, user); Assert.False(user.IsAdmin); } } } }
34.023375
151
0.452732
[ "MIT" ]
robertwesterlund/SignalR-Chat
JabbR.Tests/ChatServiceFacts.cs
72,796
C#
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Threading.Tasks; using MountainWarehouse.EasyMWS.Data; using MountainWarehouse.EasyMWS.Enums; using MountainWarehouse.EasyMWS.Helpers; using MountainWarehouse.EasyMWS.Logging; using MountainWarehouse.EasyMWS.Model; using MountainWarehouse.EasyMWS.Repositories; namespace MountainWarehouse.EasyMWS.Services { internal class ReportRequestEntryService : IReportRequestEntryService, IDisposable { private readonly IReportRequestEntryRepository _reportRequestEntryRepository; private readonly IEasyMwsLogger _logger; private readonly EasyMwsOptions _options; internal ReportRequestEntryService(IReportRequestEntryRepository reportRequestEntryRepository, EasyMwsOptions options = null, IEasyMwsLogger logger = null) : this(options, logger) => (_reportRequestEntryRepository) = (reportRequestEntryRepository); internal ReportRequestEntryService(EasyMwsOptions options = null, IEasyMwsLogger logger = null) => (_reportRequestEntryRepository, _logger, _options) = (_reportRequestEntryRepository ?? new ReportRequestEntryRepository(options?.LocalDbConnectionStringOverride), logger, options); public void Lock(ReportRequestEntry entry) { if (entry.IsLocked) { _logger.Debug($"An attempt was made to lock entry {entry.EntryIdentityDescription}, but it is already locked."); } else { entry.IsLocked = true; _logger.Debug($"The following entry is marked as locked: {entry.EntryIdentityDescription}."); } } public void Unlock(ReportRequestEntry entry) { if (!entry.IsLocked) { _logger.Debug($"An attempt was made to unlock entry {entry.EntryIdentityDescription}, but it is already unlocked."); } else { entry.IsLocked = false; _logger.Debug($"The following entry is now marked as unlocked: {entry.EntryIdentityDescription}."); } } public void Create(ReportRequestEntry entry) => _reportRequestEntryRepository.Create(entry); public async Task CreateAsync(ReportRequestEntry entry) => await _reportRequestEntryRepository.CreateAsync(entry); public void Update(ReportRequestEntry entry) => _reportRequestEntryRepository.Update(entry); public void Delete(ReportRequestEntry entry) { try { _reportRequestEntryRepository.Delete(entry); } catch (Exception e) { _logger.Error(!_reportRequestEntryRepository.GetAll().Where(rr => rr.Id == entry.Id).Select(r => r.Id).Any() ? $"Delete ReportRequestCallback entity with ID: {entry.Id} failed. It is likely the entity has already been deleted" : $"Delete ReportRequestCallback entity with ID: {entry.Id} failed. See exception info for more details", e); } } public void DeleteRange(IEnumerable<ReportRequestEntry> entries) { _reportRequestEntryRepository.DeleteRange(entries); } public void SaveChanges() => _reportRequestEntryRepository.SaveChanges(); public async Task SaveChangesAsync() => await _reportRequestEntryRepository.SaveChangesAsync(); public IEnumerable<ReportRequestEntry> GetAll() => _reportRequestEntryRepository.GetAll().OrderBy(x => x.Id); public IEnumerable<ReportRequestEntry> Where(Func<ReportRequestEntry, bool> predicate) => _reportRequestEntryRepository.GetAll().OrderBy(x => x.Id).Where(predicate); public ReportRequestEntry First() => _reportRequestEntryRepository.GetAll().OrderBy(x => x.Id).First(); public ReportRequestEntry FirstOrDefault() => _reportRequestEntryRepository.GetAll().OrderBy(x => x.Id).FirstOrDefault(); public ReportRequestEntry FirstOrDefault(Func<ReportRequestEntry, bool> predicate) => _reportRequestEntryRepository.GetAll().OrderBy(x => x.Id).FirstOrDefault(predicate); public ReportRequestEntry GetNextFromQueueOfReportsToRequest(string merchantId, AmazonRegion region, bool markEntryAsLocked = true) { var entry = FirstOrDefault(rre => rre.AmazonRegion == region && rre.MerchantId == merchantId && rre.RequestReportId == null && RetryIntervalHelper.IsRetryPeriodAwaited(rre.LastAmazonRequestDate, rre.ReportRequestRetryCount, _options.ReportRequestOptions.ReportRequestRetryInitialDelay, _options.ReportRequestOptions.ReportRequestRetryInterval, _options.ReportRequestOptions.ReportRequestRetryType) && rre.IsLocked == false); if (entry != null && markEntryAsLocked) { Lock(entry); Update(entry); SaveChanges(); } return entry; } public ReportRequestEntry GetNextFromQueueOfReportsToDownload(string merchantId, AmazonRegion region, bool markEntryAsLocked = true) { var entry = FirstOrDefault(rre => rre.AmazonRegion == region && rre.MerchantId == merchantId && rre.RequestReportId != null && rre.GeneratedReportId != null && rre.Details == null && rre.LastAmazonReportProcessingStatus != AmazonReportProcessingStatus.DoneNoData && RetryIntervalHelper.IsRetryPeriodAwaited(rre.LastAmazonRequestDate, rre.ReportDownloadRetryCount, _options.ReportRequestOptions.ReportDownloadRetryInitialDelay, _options.ReportRequestOptions.ReportDownloadRetryInterval, _options.ReportRequestOptions.ReportDownloadRetryType) && rre.IsLocked == false); if (entry != null && markEntryAsLocked) { Lock(entry); Update(entry); SaveChanges(); } return entry; } public IEnumerable<string> GetAllPendingReportFromQueue(string merchantId, AmazonRegion region, bool markEntriesAsLocked = true) { var entries = Where(rre => rre.AmazonRegion == region && rre.MerchantId == merchantId && rre.RequestReportId != null && rre.GeneratedReportId == null && rre.IsLocked == false); var entriesIds = entries.Select(r => r.RequestReportId).ToList(); if (entries.Any() && markEntriesAsLocked) { foreach (var entry in entries) { Lock(entry); Update(entry); } SaveChanges(); } return entriesIds; } public IEnumerable<ReportRequestEntry> GetAllFromQueueOfReportsReadyForCallback(string merchantId, AmazonRegion region, bool markEntriesAsLocked = true) { var entries = Where(rre => rre.AmazonRegion == region && rre.MerchantId == merchantId && (rre.Details != null || rre.LastAmazonReportProcessingStatus == AmazonReportProcessingStatus.DoneNoData) && RetryIntervalHelper.IsRetryPeriodAwaited(rre.LastAmazonRequestDate, rre.InvokeCallbackRetryCount, _options.EventPublishingOptions.EventPublishingRetryInterval, _options.EventPublishingOptions.EventPublishingRetryInterval, _options.EventPublishingOptions.EventPublishingRetryPeriodType) && rre.IsLocked == false).ToList(); entries = EntryInvocationRestrictionHelper<ReportRequestEntry>.RestrictInvocationToOriginatingClientsIfEnabled(entries, _options); if (entries.Any() && markEntriesAsLocked) { foreach (var entry in entries) { Lock(entry); Update(entry); } SaveChanges(); } return entries; } public void Dispose() { _reportRequestEntryRepository.Dispose(); } } }
41.381503
181
0.746752
[ "Apache-2.0" ]
TechyChap/EasyMWS
src/EasyMWS/EasyMWS/Services/ReportRequestEntryService.cs
7,161
C#
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using UnityEngine; using KModkit; using PlanarCipherWords; using Rnd = UnityEngine.Random; public class mechanusCipherScript : MonoBehaviour { public KMAudio Audio; public AudioClip[] Sounds; public KMSelectable[] Gears; public KMSelectable[] Button; public GameObject[] Eyelids; public GameObject Pupil; public TextMesh[] Text; public KMBombModule Module; private bool solved; private bool[] isanimating = new bool[3]; private float[] rotations = { -90f, -90f, -90f, -90f, -90f, -90f, -90f, -90f, -90f, -90f, -90f, -90f, -90f, -90f }; private float[] gearrotations = { -45f / 13f, 270 + 45f / 13f }; private string[] words = new string[3]; private string[] displays1 = new string[3]; private string[] displays2 = new string[3]; private int[] wordindex = new int[2]; private bool[] backside = new bool[2]; private string encrypted; private string binaries; private string swaps = ""; private int gearpos; private int remaining; private int done; private string input = ""; private char keyletter; static int _moduleIdCounter = 1; int _moduleID = 0; private KMSelectable.OnInteractHandler PanelPressed(int pos) { return delegate { Button[pos].AddInteractionPunch(); if (!solved) { if (pos < 14) StartCoroutine(TotalFlip(pos)); else { string alphabet = "abcdefghijklmnopqrstuvwxyz"; if (input.Length < 7 && !isanimating[0]) { if (input.Length != 7) input += alphabet[gearpos]; StartCoroutine(FlipPanel(input.Length - 1, true)); } } } return false; }; } private KMSelectable.OnInteractHandler GearPressed(int pos) { return delegate { Gears[pos].AddInteractionPunch(); if (!solved) { if (pos == 0) StartCoroutine(TurnGears(false)); else StartCoroutine(TurnGears(true)); } return false; }; } void Awake () { _moduleID = _moduleIdCounter++; for (int i = 0; i < Button.Length; i++) Button[i].OnInteract += PanelPressed(i); for (int i = 0; i < Gears.Length; i++) Gears[i].OnInteract += GearPressed(i); for (int i = 0; i < words.Length; i++) words[i] = Wordlist.wordlist[Rnd.Range(0, Wordlist.wordlist.Length)]; for (int i = 0; i < 7; i++) { swaps += Rnd.Range(1, 8).ToString(); string x = swaps[i * 2].ToString(); while (x == swaps[i * 2].ToString()) x = Rnd.Range(1, 8).ToString(); swaps += x; } MechanusEncrypt(words[0], words[1], words[2], swaps); string swaps2 = ""; for (int i = 0; i < 7; i++) swaps2 += swaps[i * 2]; for (int i = 0; i < 7; i++) swaps2 += swaps[i * 2 + 1]; swaps = swaps2; displays1 = new string[] { encrypted, words[1], binaries }; displays2 = new string[] { swaps.Substring(0, 7), swaps.Substring(7, 7), words[2] }; for (int i = 0; i < 7; i++) Text[i * 2 + 26].text = displays1[0][i].ToString().ToUpperInvariant(); for (int i = 0; i < 7; i++) Text[i * 2 + 40].text = displays2[0][i].ToString().ToUpperInvariant(); Text[55].text = keyletter.ToString().ToUpperInvariant(); } private void MechanusEncrypt(string word, string keyword, string keyword2, string swappos) { word = word.ToLowerInvariant(); keyword = keyword.ToLowerInvariant(); keyword2 = keyword2.ToLowerInvariant(); Debug.LogFormat("[Mechanus Cipher #{0}] Encrypted word is {1}.", _moduleID, word.ToUpperInvariant()); string alphabet = "abcdefghijklmnopqrstuvwxyz"; string key = ""; string encryption = ""; int j = 0; //keyword to key for (int i = 0; i < 26; i++) { int k = 0; for (int l = 0; l < 26; l++) if (alphabet[l] == keyword[j]) k = l; while (key.Contains(alphabet[k])) { k++; k %= 26; } key += alphabet[k]; j++; j %= 7; } Debug.LogFormat("[Mechanus Cipher #{0}] Key made from {1} is {2}.", _moduleID, keyword.ToUpperInvariant(), key.ToUpperInvariant()); //step 3 for (int i = 0; i < 7; i++) { int[] k = { 0, 0 }; for (int l = 0; l < 26; l++) { if (key[l] == keyword2[i]) k[0] = l; if (key[l] == word[i]) k[1] = l; } j = 1; int p = 0; for (int l = 0; l < 3; l++) { p += ((6 - ((k[0] / j) % 3) - ((k[1] / j) % 3)) % 3) * j; j *= 3; } if (p == 26) p = k[1]; encryption += key[p]; } Debug.LogFormat("[Mechanus Cipher #{0}] Encryption of step 3 using keyword {1} results in {2}.", _moduleID, keyword2.ToUpperInvariant(), encryption.ToUpperInvariant()); //step 2 word = encryption; encryption = ""; int[,] binary = new int[4,7]; int x = Rnd.Range(0, 16); for (int i = 0; i < 26; i++) if (word[6] == key[i]) j = i; int fact = 8; for (int i = 0; i < 4; i++) { binary[i, 6] = (x / fact) % 2; fact /= 2; } for (int i = 5; i >= 0; i--) { int safe = 0; while (word[i] != key[j] || safe == 0) { j = (j + 1) % 26; x = (x + 15) % 16; safe++; } fact = 8; for (int n = 0; n < 4; n++) { binary[n, i] = (x / fact) % 2; fact /= 2; } if (safe > 16) binaries = '1' + binaries; else binaries = '0' + binaries; } if (Rnd.Range(0, 2) == 1) { j = (j + 16) % 26; binaries = '1' + binaries; } else binaries = '0' + binaries; for (int i = 6; i >= 0; i--) { int c = 8 * binary[(i * 4) / 7, (i * 4) % 7] + 4 * binary[((i * 4) + 1) / 7, ((i * 4) + 1) % 7] + 2 * binary[((i * 4) + 2) / 7, ((i * 4) + 2) % 7] + binary[((i * 4) + 3) / 7, ((i * 4) + 3) % 7]; int safe = 0; while (x != c || safe == 0) { j = (j + 1) % 26; x = (x + 15) % 16; safe++; } if (Rnd.Range(0, 2) == 1 && safe <= 10 && i != 6) j = (j + 16) % 26; encryption = key[j] + encryption; } int safe2 = 0; while (x != 0 || safe2 == 0) { j = (j + 1) % 26; x = (x + 15) % 16; safe2++; } if (Rnd.Range(0, 2) == 1 && safe2 <= 10) j = (j + 16) % 26; keyletter = key[j]; string binarylog = ""; for (int i = 0; i < 28; i++) binarylog += binary[i / 7, i % 7].ToString(); Debug.Log(binarylog); Debug.LogFormat("[Mechanus Cipher #{0}] Encryption of step 2 results in binary string {1}, key letter {2}, and encrypted word {3}.", _moduleID, binaries, keyletter.ToString().ToUpperInvariant(), encryption.ToUpperInvariant()); //step 1 for (int i = swappos.Length / 2 - 1; i >= 0; i--) { word = encryption; encryption = ""; int a = int.Parse(swappos[i * 2].ToString()) - 1; int b = int.Parse(swappos[i * 2 + 1].ToString()) - 1; for (int l = 0; l < (new int[] { a, b }).Min(); l++) encryption += word[l]; for (int l = (new int[] { a, b }).Max(); l >= (new int[] { a, b }).Min(); l--) encryption += word[l]; for (int l = (new int[] { a, b }).Max() + 1; l < 7; l++) encryption += word[l]; encrypted = encryption; } Debug.LogFormat("[Mechanus Cipher #{0}] Encryption of step 1 using swapping key {1} (interpret as pairs) results in {2}.", _moduleID, swappos, encrypted.ToUpperInvariant()); } private IEnumerator Shutdown() { float[] eyerots = { 90f, 90f }; input = " "; displays1 = new string[] { " ", " ", " " }; displays2 = new string[] { " ", " ", " " }; StartCoroutine(TotalFlip(0)); yield return new WaitForSeconds(0.06f); StartCoroutine(TotalFlip(7)); yield return new WaitForSeconds(0.06f); for (int i = 0; i < 18; i++) { eyerots[0] += 5f; eyerots[1] -= 5f; for (int j = 0; j < 2; j++) Eyelids[j].transform.localEulerAngles = new Vector3(eyerots[j], 0f, 0f); yield return new WaitForSeconds(0.03f); } Module.HandlePass(); } private IEnumerator Ouch() { float eyescale = 0.5f; for (int i = 0; i < 5; i++) { eyescale -= 0.075f; Pupil.transform.localScale = new Vector3(eyescale, 0.2f, eyescale); yield return new WaitForSeconds(0.03f); } for (int i = 0; i < 20; i++) { eyescale += 0.01875f; Pupil.transform.localScale = new Vector3(eyescale, 0.2f, eyescale); yield return new WaitForSeconds(0.03f); } } private IEnumerator FlipPanel(int pos, bool sub) { Audio.PlaySoundAtTransform("Ping", Module.transform); if (pos < 7) { if (!sub) { if (backside[0]) Text[pos * 2 + 27].text = displays1[wordindex[0]][pos].ToString().ToUpperInvariant(); else Text[pos * 2 + 26].text = displays1[wordindex[0]][pos].ToString().ToUpperInvariant(); } else { if (!backside[0]) Text[pos * 2 + 27].text = input[pos].ToString().ToUpperInvariant(); else Text[pos * 2 + 26].text = input[pos].ToString().ToUpperInvariant(); } } else { if (backside[1]) Text[pos * 2 + 27].text = displays2[wordindex[1]][pos - 7].ToString().ToUpperInvariant(); else Text[pos * 2 + 26].text = displays2[wordindex[1]][pos - 7].ToString().ToUpperInvariant(); } for (int i = 0; i < 18; i++) { rotations[pos] += 10f; Button[pos].transform.localEulerAngles = new Vector3(rotations[pos], 0f, 0f); yield return new WaitForSeconds(0.03f); } if (pos == 6 && sub && input.Length == 7 && !solved) { if (input.ToUpperInvariant() == words[0].ToUpperInvariant()) { solved = true; StartCoroutine(Shutdown()); } else { Debug.LogFormat("[Mechanus Cipher #{0}] Submitted {1}, but I expected {2}.", _moduleID, input.ToUpperInvariant(), words[0].ToUpperInvariant()); Module.HandleStrike(); StartCoroutine(TotalFlip(0)); StartCoroutine(Ouch()); } } Audio.PlaySoundAtTransform("Ping", Module.transform); } private IEnumerator TurnGears(bool forward) { if (remaining == done) Audio.PlaySoundAtTransform("GearClink", Module.transform); if (forward) { remaining++; gearpos = (gearpos + 1) % 26; } else { gearpos = (gearpos + 25) % 26; remaining--; } for (int i = 0; i < 26; i++) { if (i == gearpos) Text[i].color = new Color32(255, 255, 0, 255); else Text[i].color = new Color32(63, 35, 0, 255); } while (isanimating[2]) yield return null; if (forward && remaining > done || !forward && remaining < done) { if (forward) done++; else done--; isanimating[2] = true; for (int i = 0; i < 9; i++) { if (forward) { gearrotations[0] -= (360f / 13f) / 18f; gearrotations[1] += (360f / 13f) / 18f; } else { gearrotations[0] += (360f / 13f) / 18f; gearrotations[1] -= (360f / 13f) / 18f; } for (int j = 0; j < 2; j++) Gears[j].transform.localEulerAngles = new Vector3(-90f, gearrotations[j], 0f); yield return new WaitForSeconds(0.03f); } isanimating[2] = false; if (!(forward && remaining > done || !forward && remaining < done)) Audio.PlaySoundAtTransform("GearClink", Module.transform); } } private IEnumerator TotalFlip(int pos) { if (pos < 7) { while (isanimating[0]) yield return null; isanimating[0] = true; wordindex[0] = (wordindex[0] + 1) % 3; backside[0] = !backside[0]; if (input != "" && pos < 7) { int inplen = input.Length; input = " "; for (int i = 0; i < 7; i++) { for (int j = 0; j < 7; j++) if ((j - i == pos || j + i == pos) && j < inplen) StartCoroutine(FlipPanel(j, true)); yield return new WaitForSeconds(0.06f); } input = ""; wordindex[0] = 0; yield return new WaitForSeconds(0.6f); } if (!solved) { for (int i = 0; i < 7; i++) { for (int j = 0; j < 7; j++) if (j - i == pos || j + i == pos) StartCoroutine(FlipPanel(j, false)); yield return new WaitForSeconds(0.06f); } yield return new WaitForSeconds(0.6f); } isanimating[0] = false; } else if (pos < 14) { while (isanimating[1]) yield return null; isanimating[1] = true; backside[1] = !backside[1]; wordindex[1] = (wordindex[1] + 1) % 3; for (int i = 0; i < 7; i++) { for (int j = 7; j < 14; j++) if (j - i == pos || j + i == pos) StartCoroutine(FlipPanel(j, false)); yield return new WaitForSeconds(0.06f); } yield return new WaitForSeconds(0.6f); isanimating[1] = false; } } #pragma warning disable 414 private string TwitchHelpMessage = "'!{0} cycle' to cycle the screens, '!{0} submit ENTRIES' to submit ENTRIES."; #pragma warning restore 414 IEnumerator ProcessTwitchCommand(string command) { yield return null; command = command.ToLowerInvariant(); if (command == "cycle") for (int i = 0; i < 3; i++) { Button[0].OnInteract(); yield return null; Button[7].OnInteract(); yield return new WaitForSeconds(5f); } else if (command.Split(' ').Length == 2 && command.Split(' ')[1].Length == 7 && command.Split(' ')[0] == "submit") { command = command.Split(' ')[1]; string alphabet = "abcdefghijklmnopqrstuvwxyz"; for (int i = 0; i < 7; i++) if (!alphabet.Contains(command[i])) { yield return "sendtochaterror Invalid command."; yield break; } for (int i = 0; i < 7; i++) { for (int j = 0; j < 26; j++) if (command[i] == alphabet[(gearpos + j) % 26]) { if (j > 13) while (alphabet[gearpos] != command[i]) { Gears[0].OnInteract(); yield return null; } else while (alphabet[gearpos] != command[i]) { Gears[1].OnInteract(); yield return null; } j = 26; } Button[14].OnInteract(); yield return null; } yield return "solve"; } else yield return "sendtochaterror Invalid command."; yield return null; } IEnumerator TwitchHandleForcedSolve() { yield return true; if (!solved) { string alphabet = "abcdefghijklmnopqrstuvwxyz"; for (int i = 0; i < 7; i++) { for (int j = 0; j < 26; j++) if (words[0].ToLowerInvariant()[i] == alphabet[(gearpos + j) % 26]) { if (j > 13) while (alphabet[gearpos] != words[0].ToLowerInvariant()[i]) { Gears[0].OnInteract(); yield return null; } else while (alphabet[gearpos] != words[0].ToLowerInvariant()[i]) { Gears[1].OnInteract(); yield return null; } j = 26; } Button[14].OnInteract(); yield return true; } } } }
26.54291
228
0.563857
[ "MIT" ]
Ob3vious/KTaNE_PlanarCiphers
Assets/Assets_Mechanus/mechanusCipherScript.cs
14,229
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; namespace Game.Tasks { /// <summary> /// Used as a base for all types of Tasks. /// /// A Task can be a part of a TaskQueue, which is mainly /// used by Workers to keep track of what to do now, /// and what to do next. /// </summary> public abstract class TaskBase { /// <summary> /// This is used as a short text representation of the task in UI. /// </summary> public abstract string DisplayName { get; } /// <summary> /// This is used as a description of the task in UI. /// </summary> public abstract string Description { get; } } }
27.807692
74
0.593361
[ "MIT" ]
anthonyme00/DreamHack-2018
DreamHack 2018 - UnityProject/Assets/Scripts/Tasks/TaskBase.cs
725
C#
using System; namespace DiscountMe.Common.Helpers { /// <summary> /// The distance type to return the results in. /// </summary> public enum DistanceType { Miles, Kilometers }; /// <summary> /// Specifies a Latitude / Longitude point. /// </summary> public struct Position { public double Latitude; public double Longitude; } public class Haversine { /// <summary> /// Returns the distance in miles or kilometers of any two /// latitude / longitude points. /// </summary> /// <param name="pos1"></param> /// <param name="pos2"></param> /// <param name="type"></param> /// <returns></returns> public static double Distance(Position pos1, Position pos2, DistanceType type) { double R = (type == DistanceType.Miles) ? 3960 : 6371; double dLat = ToRadian(pos2.Latitude - pos1.Latitude); double dLon = ToRadian(pos2.Longitude - pos1.Longitude); double a = Math.Sin(dLat / 2) * Math.Sin(dLat / 2) + Math.Cos(ToRadian(pos1.Latitude)) * Math.Cos(ToRadian(pos2.Latitude)) * Math.Sin(dLon / 2) * Math.Sin(dLon / 2); double c = 2 * Math.Asin(Math.Min(1, Math.Sqrt(a))); double d = R * c; return d; } /// <summary> /// Convert to Radians. /// </summary> /// <param name="val"></param> /// <returns></returns> private static double ToRadian(double val) { return (Math.PI / 180) * val; } } }
32.18
88
0.538844
[ "MIT" ]
IberaSoft/discount-me
DiscountMe/DiscountMe.Common/Helpers/Haversine.cs
1,611
C#
using Microsoft.AspNetCore.Components; using Microsoft.AspNetCore.Components.RenderTree; //using Microsoft.AspNetCore.Components.Server.Circuits; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.JSInterop; using System; using System.Collections.Concurrent; using System.IO; using System.Reflection; using System.Threading; using System.Threading.Tasks; namespace Photino.Blazor { // Many aspects of the layering here are not what we really want, but it won't affect // people prototyping applications with it. We can put more work into restructuring the // hosting and startup models in the future if it's justified. internal class DesktopRenderer : Renderer { private static readonly Task CanceledTask = Task.FromCanceled(new CancellationToken(canceled: true)); private const int RendererId = 0; // Not relevant, since we have only one renderer in Desktop private readonly IPC _ipc; private readonly IJSRuntime _jsRuntime; private static readonly Type _writer; private static readonly MethodInfo? _writeMethod; internal readonly ConcurrentQueue<UnacknowledgedRenderBatch> _unacknowledgedRenderBatches = new ConcurrentQueue<UnacknowledgedRenderBatch>(); private bool _disposing = false; private long _nextRenderId = 1; public override Dispatcher Dispatcher { get; } static DesktopRenderer() { _writer = typeof(RenderBatchWriter); _writeMethod = _writer.GetMethod("Write", new[] { typeof(RenderBatch).MakeByRefType() }); } public DesktopRenderer(IServiceProvider serviceProvider, IPC ipc, ILoggerFactory loggerFactory, IJSRuntime jSRuntime, Dispatcher dispatcher) : base(serviceProvider, loggerFactory) { _ipc = ipc ?? throw new ArgumentNullException(nameof(ipc)); Dispatcher = dispatcher; _jsRuntime = jSRuntime; } /// <summary> /// Notifies when a rendering exception occured. /// </summary> public event EventHandler<Exception>? UnhandledException; /// <summary> /// Attaches a new root component to the renderer, /// causing it to be displayed in the specified DOM element. /// </summary> /// <typeparam name="TComponent">The type of the component.</typeparam> /// <param name="domElementSelector">A CSS selector that uniquely identifies a DOM element.</param> public Task AddComponentAsync<TComponent>(string domElementSelector) where TComponent : IComponent { return AddComponentAsync(typeof(TComponent), domElementSelector); } /// <summary> /// Associates the <see cref="IComponent"/> with the <see cref="BrowserRenderer"/>, /// causing it to be displayed in the specified DOM element. /// </summary> /// <param name="componentType">The type of the component.</param> /// <param name="domElementSelector">A CSS selector that uniquely identifies a DOM element.</param> public Task AddComponentAsync(Type componentType, string domElementSelector) { var component = InstantiateComponent(componentType); var componentId = AssignRootComponentId(component); var attachComponentTask = _jsRuntime.InvokeAsync<object>( "window.Blazor._internal.attachRootComponentToElement", domElementSelector, componentId, RendererId); CaptureAsyncExceptions(attachComponentTask); return RenderRootComponentAsync(componentId); } /// <inheritdoc /> protected override Task UpdateDisplayAsync(in RenderBatch batch) { if (_disposing) { // We are being disposed, so do no work. return CanceledTask; } string base64; using (var memoryStream = new MemoryStream()) { object? renderBatchWriter = Activator.CreateInstance(_writer, new object[] { memoryStream, false }); using (renderBatchWriter as IDisposable) { _writeMethod?.Invoke(renderBatchWriter, new object[] { batch }); } var batchBytes = memoryStream.ToArray(); base64 = Convert.ToBase64String(batchBytes); } var renderId = Interlocked.Increment(ref _nextRenderId); var pendingRender = new UnacknowledgedRenderBatch( renderId, new TaskCompletionSource<object?>()); // Buffer the rendered batches no matter what. We'll send it down immediately when the client // is connected or right after the client reconnects. _unacknowledgedRenderBatches.Enqueue(pendingRender); _ipc.Send("JS.RenderBatch", renderId, base64); return pendingRender.CompletionSource.Task; } public Task OnRenderCompletedAsync(long incomingBatchId, string errorMessageOrNull) { if (_disposing) { // Disposing so don't do work. return Task.CompletedTask; } // When clients send acks we know for sure they received and applied the batch. // We send batches right away, and hold them in memory until we receive an ACK. // If one or more client ACKs get lost (e.g., with long polling, client->server delivery is not guaranteed) // we might receive an ack for a higher batch. // We confirm all previous batches at that point (because receiving an ack is guarantee // from the client that it has received and successfully applied all batches up to that point). // If receive an ack for a previously acknowledged batch, its an error, as the messages are // guaranteed to be delivered in order, so a message for a render batch of 2 will never arrive // after a message for a render batch for 3. // If that were to be the case, it would just be enough to relax the checks here and simply skip // the message. // A batch might get lost when we send it to the client, because the client might disconnect before receiving and processing it. // In this case, once it reconnects the server will re-send any unacknowledged batches, some of which the // client might have received and even believe it did send back an acknowledgement for. The client handles // those by re-acknowledging. // Even though we're not on the renderer sync context here, it's safe to assume ordered execution of the following // line (i.e., matching the order in which we received batch completion messages) based on the fact that SignalR // synchronizes calls to hub methods. That is, it won't issue more than one call to this method from the same hub // at the same time on different threads. if (!_unacknowledgedRenderBatches.TryPeek(out var nextUnacknowledgedBatch) || incomingBatchId < nextUnacknowledgedBatch.BatchId) { // TODO: Log duplicated batch ack. return Task.CompletedTask; } else { var lastBatchId = nextUnacknowledgedBatch.BatchId; // Order is important here so that we don't prematurely dequeue the last nextUnacknowledgedBatch while (_unacknowledgedRenderBatches.TryPeek(out nextUnacknowledgedBatch) && nextUnacknowledgedBatch.BatchId <= incomingBatchId) { lastBatchId = nextUnacknowledgedBatch.BatchId; // At this point the queue is definitely not full, we have at least emptied one slot, so we allow a further // full queue log entry the next time it fills up. _unacknowledgedRenderBatches.TryDequeue(out _); ProcessPendingBatch(errorMessageOrNull, nextUnacknowledgedBatch); } if (lastBatchId < incomingBatchId) { // This exception is due to a bad client input, so we mark it as such to prevent logging it as a warning and // flooding the logs with warnings. throw new InvalidOperationException($"Received an acknowledgement for batch with id '{incomingBatchId}' when the last batch produced was '{lastBatchId}'."); } // Normally we will not have pending renders, but it might happen that we reached the limit of // available buffered renders and new renders got queued. // Invoke ProcessBufferedRenderRequests so that we might produce any additional batch that is // missing. // We return the task in here, but the caller doesn't await it. return Dispatcher.InvokeAsync(() => { // Now we're on the sync context, check again whether we got disposed since this // work item was queued. If so there's nothing to do. if (!_disposing) { ProcessPendingRender(); } }); } } private void ProcessPendingBatch(string errorMessageOrNull, UnacknowledgedRenderBatch entry) { CompleteRender(entry.CompletionSource, errorMessageOrNull); } private void CompleteRender(TaskCompletionSource<object?> pendingRenderInfo, string errorMessageOrNull) { if (errorMessageOrNull == null) { pendingRenderInfo.TrySetResult(null); } else { pendingRenderInfo.TrySetException(new InvalidOperationException(errorMessageOrNull)); } } private async void CaptureAsyncExceptions(ValueTask<object> task) { try { await task; } catch (Exception ex) { UnhandledException?.Invoke(this, ex); } } protected override void HandleException(Exception exception) { Console.WriteLine(exception.ToString()); } /// <inheritdoc /> protected override void Dispose(bool disposing) { _disposing = true; while (_unacknowledgedRenderBatches.TryDequeue(out var entry)) { entry.CompletionSource.TrySetCanceled(); } base.Dispose(true); } internal readonly struct UnacknowledgedRenderBatch { public UnacknowledgedRenderBatch(long batchId, TaskCompletionSource<object?> completionSource) { BatchId = batchId; CompletionSource = completionSource; } public long BatchId { get; } public TaskCompletionSource<object?> CompletionSource { get; } } } }
43.953307
176
0.618803
[ "Apache-2.0" ]
budcribar/RemoteBlazorWebView
src/Photino.Blazor/DesktopRenderer.cs
11,298
C#
 using System.Text.Json.Serialization; using Twitch.Vod.Services.Models.Interfaces; namespace Twitch.Vod.Services.Models.Twitch { public class TwitchUser: ITwitchUser { [JsonPropertyName("id")] public string Id { get; set; } [JsonPropertyName("display_name")] public string DisplayName { get; set; } [JsonPropertyName("profile_image_url")] public string ProfileImageUrl { get; set; } [JsonPropertyName("view_count")] public long ViewCount { get; set; } } }
26.8
51
0.656716
[ "MIT" ]
nickyg91/twitch-vod-tools
Twitch.Vod.Tools/Twitch.Vod.Services/Models/Twitch/TwitchUser.cs
538
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using TDSBridge.Common; namespace TDSBridge { class Program { static int iRPC = 0; static void Main(string[] args) { if (args.Length < 3) { Usage(); return; } System.Net.IPHostEntry iphe = System.Net.Dns.GetHostEntry(args[1]); BridgeAcceptor b = new BridgeAcceptor( int.Parse(args[0]), new System.Net.IPEndPoint(iphe.AddressList[0], int.Parse(args[2])) ); b.TDSMessageReceived += new TDSMessageReceivedDelegate(b_TDSMessageReceived); b.TDSPacketReceived += new TDSPacketReceivedDelegate(b_TDSPacketReceived); b.ConnectionAccepted += new ConnectionAcceptedDelegate(b_ConnectionAccepted); b.ConnectionDisconnected += new ConnectionDisconnectedDelegate(b_ConnectionClosed); b.Start(); Console.WriteLine($"Running on port {args[0]}. Press enter to kill this process..."); Console.ReadLine(); b.Stop(); } static void b_ConnectionClosed(object sender, BridgedConnection bc, ConnectionType ct) { Console.WriteLine(FormatDateTime() + "|Connection " + ct + " closed (" + bc.SocketCouple + ")"); } static void b_ConnectionAccepted(object sender, System.Net.Sockets.Socket sAccepted) { Console.WriteLine(FormatDateTime() + "|New connection from " + sAccepted.RemoteEndPoint); } static void b_TDSPacketReceived(object sender, BridgedConnection bc, Common.Packet.TDSPacket packet) { Console.WriteLine(FormatDateTime() + "|" + packet); } static void b_TDSMessageReceived(object sender, BridgedConnection bc, Common.Message.TDSMessage msg) { Console.WriteLine(FormatDateTime() + "|" + msg); if (msg is Common.Message.SQLBatchMessage) { Console.Write("\tSQLBatch message "); Common.Message.SQLBatchMessage b = (Common.Message.SQLBatchMessage)msg; string strBatchText = b.GetBatchText(); Console.Write("({0:N0} chars worth of {1:N0} bytes of data)[", strBatchText.Length, strBatchText.Length * 2); Console.Write(strBatchText); Console.WriteLine("]"); } else if (msg is Common.Message.RPCRequestMessage) { try { Common.Message.RPCRequestMessage rpc = (Common.Message.RPCRequestMessage)msg; byte[] bPayload = rpc.AssemblePayload(); #if DEBUG //using (System.IO.FileStream fs = new System.IO.FileStream( // "C:\\temp\\dev\\" + (iRPC++) + ".raw", // System.IO.FileMode.Create, // System.IO.FileAccess.Write, // System.IO.FileShare.Read)) //{ // fs.Write(bPayload, 0, bPayload.Length); //} #endif } catch (Exception exce) { Console.WriteLine("Exception: " + exce.ToString()); } } } static string FormatDateTime() { return Environment.NewLine + Environment.NewLine + DateTime.Now.ToString("yyyyMMdd HH:mm:ss.ffffff"); } static void Usage() { Console.WriteLine(System.Reflection.Assembly.GetExecutingAssembly().GetName().Name + " <listen port> <sql server address> <sql server port>"); } } }
35.915094
154
0.547413
[ "MIT" ]
webMan1/TDSBridge
TDSBridge/TDSBridge/Program.cs
3,809
C#
// Copyright 2009-2012 Matvei Stefarov <me@matvei.org> using System; using System.Collections.Generic; namespace fCraft.Drawing { public sealed class Fill2DDrawOperation : DrawOpWithBrush { int maxFillExtent; public override string Name { get { return "Fill2D"; } } public override int ExpectedMarks { get { return 1; } } public override string Description { get { if( SourceBlock == Block.Undefined ) { if( ReplacementBlock == Block.Undefined ) { return Name; } else { return String.Format( "{0}({1})", Name, ReplacementBlock ); } } else { return String.Format( "{0}({1} -> {2} @{3})", Name, SourceBlock, ReplacementBlock, Axis ); } } } public Block SourceBlock { get; private set; } public Block ReplacementBlock { get; private set; } public Axis Axis { get; private set; } public Vector3I Origin { get; private set; } public Fill2DDrawOperation( Player player ) : base( player ) { SourceBlock = Block.Undefined; ReplacementBlock = Block.Undefined; } public override bool ReadParams( Command cmd ) { if( cmd.HasNext ) { ReplacementBlock = cmd.NextBlock( Player ); if( ReplacementBlock == Block.Undefined ) return false; } Brush = this; return true; } public override bool Prepare( Vector3I[] marks ) { if( marks == null ) throw new ArgumentNullException( "marks" ); if( marks.Length < 1 ) throw new ArgumentException( "At least one mark needed.", "marks" ); if( ReplacementBlock == Block.Undefined ) { if( Player.LastUsedBlockType == Block.Undefined ) { Player.Message( "Cannot deduce desired replacement block. Click a block or type out the block name." ); return false; } else { ReplacementBlock = Player.GetBind( Player.LastUsedBlockType ); } } Marks = marks; Origin = marks[0]; SourceBlock = Map.GetBlock( Origin ); Vector3I playerCoords = Player.Position.ToBlockCoords(); Vector3I lookVector = (Origin - playerCoords); Axis = lookVector.LongestAxis; Vector3I maxDelta; maxFillExtent = Player.Info.Rank.FillLimit; if( maxFillExtent < 1 || maxFillExtent > 2048 ) maxFillExtent = 2048; switch( Axis ) { case Axis.X: maxDelta = new Vector3I( 0, maxFillExtent, maxFillExtent ); coordEnumerator = BlockEnumeratorX().GetEnumerator(); break; case Axis.Y: maxDelta = new Vector3I( maxFillExtent, 0, maxFillExtent ); coordEnumerator = BlockEnumeratorY().GetEnumerator(); break; default: // Z maxDelta = new Vector3I( maxFillExtent, maxFillExtent, 0 ); coordEnumerator = BlockEnumeratorZ().GetEnumerator(); break; } if( SourceBlock == ReplacementBlock ) { Bounds = new BoundingBox( Origin, Origin ); } else { Bounds = new BoundingBox( Origin - maxDelta, Origin + maxDelta ); } // Clip bounds to the map, used to limit fill extent Bounds = Bounds.GetIntersection( Map.Bounds ); // Set everything up for filling Brush = this; Coords = Origin; StartTime = DateTime.UtcNow; Context = BlockChangeContext.Drawn | BlockChangeContext.Filled; BlocksTotalEstimate = Bounds.Volume; return true; } IEnumerator<Vector3I> coordEnumerator; public override int DrawBatch( int maxBlocksToDraw ) { if( SourceBlock == ReplacementBlock ) { IsDone = true; return 0; } int blocksDone = 0; while( coordEnumerator.MoveNext() ) { Coords = coordEnumerator.Current; if( DrawOneBlock() ) { blocksDone++; if( blocksDone >= maxBlocksToDraw ) return blocksDone; } if( TimeToEndBatch ) return blocksDone; } IsDone = true; return blocksDone; } bool CanPlace( Vector3I coords ) { return (Map.GetBlock( coords ) == SourceBlock) && Player.CanPlace( Map, coords, ReplacementBlock, Context ) == CanPlaceResult.Allowed; } IEnumerable<Vector3I> BlockEnumeratorX() { Stack<Vector3I> stack = new Stack<Vector3I>(); stack.Push( Origin ); Vector3I coords; while( stack.Count > 0 ) { coords = stack.Pop(); while( coords.Y >= Bounds.YMin && CanPlace( coords ) ) coords.Y--; coords.Y++; bool spanLeft = false; bool spanRight = false; while( coords.Y <= Bounds.YMax && CanPlace( coords ) ) { yield return coords; if( coords.Z > Bounds.ZMin ) { bool canPlace = CanPlace( new Vector3I( coords.X, coords.Y, coords.Z - 1 ) ); if( !spanLeft && canPlace ) { stack.Push( new Vector3I( coords.X, coords.Y, coords.Z - 1 ) ); spanLeft = true; } else if( spanLeft && !canPlace ) { spanLeft = false; } } if( coords.Z < Bounds.ZMax ) { bool canPlace = CanPlace( new Vector3I( coords.X, coords.Y, coords.Z + 1 ) ); if( !spanRight && canPlace ) { stack.Push( new Vector3I( coords.X, coords.Y, coords.Z + 1 ) ); spanRight = true; } else if( spanRight && !canPlace ) { spanRight = false; } } coords.Y++; } } } IEnumerable<Vector3I> BlockEnumeratorY() { Stack<Vector3I> stack = new Stack<Vector3I>(); stack.Push( Origin ); Vector3I coords; while( stack.Count > 0 ) { coords = stack.Pop(); while( coords.Z >= Bounds.ZMin && CanPlace( coords ) ) coords.Z--; coords.Z++; bool spanLeft = false; bool spanRight = false; while( coords.Z <= Bounds.ZMax && CanPlace( coords ) ) { yield return coords; if( coords.X > Bounds.XMin ) { bool canPlace = CanPlace( new Vector3I( coords.X -1, coords.Y, coords.Z ) ); if( !spanLeft && canPlace ) { stack.Push( new Vector3I( coords.X - 1, coords.Y, coords.Z ) ); spanLeft = true; } else if( spanLeft && !canPlace ) { spanLeft = false; } } if( coords.X < Bounds.XMax ) { bool canPlace = CanPlace( new Vector3I( coords.X + 1, coords.Y, coords.Z ) ); if( !spanRight && canPlace ) { stack.Push( new Vector3I( coords.X + 1, coords.Y, coords.Z ) ); spanRight = true; } else if( spanRight && !canPlace ) { spanRight = false; } } coords.Z++; } } } IEnumerable<Vector3I> BlockEnumeratorZ() { Stack<Vector3I> stack = new Stack<Vector3I>(); stack.Push( Origin ); Vector3I coords; while( stack.Count > 0 ) { coords = stack.Pop(); while( coords.Y >= Bounds.YMin && CanPlace( coords ) ) coords.Y--; coords.Y++; bool spanLeft = false; bool spanRight = false; while( coords.Y <= Bounds.YMax && CanPlace( coords ) ) { yield return coords; if( coords.X > Bounds.XMin ) { bool canPlace = CanPlace( new Vector3I( coords.X - 1, coords.Y, coords.Z ) ); if( !spanLeft && canPlace ) { stack.Push( new Vector3I( coords.X - 1, coords.Y, coords.Z ) ); spanLeft = true; } else if( spanLeft && !canPlace ) { spanLeft = false; } } if( coords.X < Bounds.XMax ) { bool canPlace = CanPlace( new Vector3I( coords.X + 1, coords.Y, coords.Z ) ); if( !spanRight && canPlace ) { stack.Push( new Vector3I( coords.X + 1, coords.Y, coords.Z ) ); spanRight = true; } else if( spanRight && !canPlace ) { spanRight = false; } } coords.Y++; } } } protected override Block NextBlock() { return ReplacementBlock; } } }
38.258555
123
0.451501
[ "MIT" ]
CybertronicToon/LegendCraft
fCraft/Drawing/DrawOps/Fill2DDrawOperation.cs
10,064
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Text; namespace Artillery.Data.Models { public class Country { public Country() { this.CountriesGuns = new HashSet<CountryGun>(); } public int Id { get; set; } [Required] [MaxLength(60)] public string CountryName { get; set; } public int ArmySize { get; set; } public virtual ICollection<CountryGun> CountriesGuns { get; set; } } }
20.769231
74
0.614815
[ "MIT" ]
Iceto04/SoftUni
Entity Framework Core/12. Exam Preparations/EntityFrameworkCoreExam-16-Dec-2021/Artillery/Data/Models/Country.cs
542
C#
// Copyright 2018 Confluent Inc. // // 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. // // Refer to LICENSE for more information. using System; namespace Confluent.Kafka { /// <summary> /// Defines methods common to all client types. /// </summary> public interface IClient : IDisposable { /// <summary> /// An opaque reference to the underlying librdkafka client instance. /// This can be used to construct an AdminClient that utilizes the same /// underlying librdkafka client as this instance. /// </summary> Handle Handle { get; } /// <summary> /// Gets the name of this client instance. /// Contains (but is not equal to) the client.id configuration /// parameter. /// </summary> /// <remarks> /// This name will be unique across all client instances /// in a given application which allows log messages to be /// associated with the corresponding instance. /// </remarks> string Name { get; } /// <summary> /// Adds one or more brokers to the Client's list of initial /// bootstrap brokers. /// /// Note: Additional brokers are discovered automatically as /// soon as the Client connects to any broker by querying the /// broker metadata. Calling this method is only required in /// some scenarios where the address of all brokers in the /// cluster changes. /// </summary> /// <param name="brokers"> /// Comma-separated list of brokers in the same format as /// the bootstrap.server configuration parameter. /// </param> /// <remarks> /// There is currently no API to remove existing configured, /// added or learnt brokers. /// </remarks> /// <returns> /// The number of brokers added. This value includes brokers /// that may have been specified a second time. /// </returns> int AddBrokers(string brokers); } }
36.561644
83
0.603597
[ "Apache-2.0" ]
GitObjects/confluent-kafka-dotnet
src/Confluent.Kafka/IClient.cs
2,669
C#
using System; using System.Collections.Generic; using Newtonsoft.Json; using Comformation.IntrinsicFunctions; namespace Comformation.ElasticLoadBalancingV2.ListenerRule { /// <summary> /// AWS::ElasticLoadBalancingV2::ListenerRule ForwardConfig /// https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticloadbalancingv2-listenerrule-forwardconfig.html /// </summary> public class ForwardConfig { /// <summary> /// TargetGroupStickinessConfig /// Information about the target group stickiness for a rule. /// Required: No /// Type: TargetGroupStickinessConfig /// Update requires: No interruption /// </summary> [JsonProperty("TargetGroupStickinessConfig")] public TargetGroupStickinessConfig TargetGroupStickinessConfig { get; set; } /// <summary> /// TargetGroups /// Information about how traffic will be distributed between multiple target groups in a forward rule. /// Required: No /// Type: List of TargetGroupTuple /// Update requires: No interruption /// </summary> [JsonProperty("TargetGroups")] public List<TargetGroupTuple> TargetGroups { get; set; } } }
34.351351
140
0.675846
[ "MIT" ]
stanb/Comformation
src/Comformation/Generated/ElasticLoadBalancingV2/ListenerRule/ForwardConfig.cs
1,271
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:2.0.50727.3053 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace Mediachase.Ibn.Web.UI.Calendar.Pages { public partial class QuickView { /// <summary> /// pT control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::Mediachase.UI.Web.Modules.DialogTemplateNext pT; } }
31.461538
84
0.481663
[ "MIT" ]
InstantBusinessNetwork/IBN
Source/Server/WebPortal/Apps/Calendar/Pages/QuickView.aspx.designer.cs
820
C#
using System.Collections.Generic; namespace MyLib.Data.Common { public class ListFilter : List<Filter> { public void Add( string name , object value ) { Add( new Filter { Name = name , Value = value } ); } } }
11.391304
39
0.564885
[ "MIT" ]
i-duarte/MyLib
src/MyLib.Data.Common/ListFilter.cs
264
C#
namespace ACAT.Lib.Core.PanelManagement { partial class SplashScreen { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(SplashScreen)); this.splashPictureBox = new System.Windows.Forms.PictureBox(); this.imageList = new System.Windows.Forms.ImageList(this.components); this.intelLogo = new System.Windows.Forms.PictureBox(); this.line3 = new System.Windows.Forms.Label(); this.line2 = new System.Windows.Forms.Label(); this.pictureBoxStatus = new System.Windows.Forms.PictureBox(); this.panel1 = new System.Windows.Forms.Panel(); this.line1 = new System.Windows.Forms.Label(); ((System.ComponentModel.ISupportInitialize)(this.splashPictureBox)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.intelLogo)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.pictureBoxStatus)).BeginInit(); this.panel1.SuspendLayout(); this.SuspendLayout(); // // splashPictureBox // this.splashPictureBox.Location = new System.Drawing.Point(11, 12); this.splashPictureBox.Name = "splashPictureBox"; this.splashPictureBox.Size = new System.Drawing.Size(149, 301); this.splashPictureBox.SizeMode = System.Windows.Forms.PictureBoxSizeMode.CenterImage; this.splashPictureBox.TabIndex = 0; this.splashPictureBox.TabStop = false; // // imageList // this.imageList.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imageList.ImageStream"))); this.imageList.TransparentColor = System.Drawing.Color.Transparent; this.imageList.Images.SetKeyName(0, "Splash1.png"); this.imageList.Images.SetKeyName(1, "Splash2.png"); this.imageList.Images.SetKeyName(2, "Splash3.png"); this.imageList.Images.SetKeyName(3, "Splash4.png"); this.imageList.Images.SetKeyName(4, "Splash5.png"); // // intelLogo // this.intelLogo.BackColor = System.Drawing.Color.Transparent; this.intelLogo.Image = ((System.Drawing.Image)(resources.GetObject("intelLogo.Image"))); this.intelLogo.Location = new System.Drawing.Point(327, 7); this.intelLogo.Name = "intelLogo"; this.intelLogo.Size = new System.Drawing.Size(75, 75); this.intelLogo.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom; this.intelLogo.TabIndex = 1; this.intelLogo.TabStop = false; // // line3 // this.line3.BackColor = System.Drawing.Color.Transparent; this.line3.Font = new System.Drawing.Font("Arial", 11.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.line3.Location = new System.Drawing.Point(173, 192); this.line3.Name = "line3"; this.line3.Size = new System.Drawing.Size(382, 49); this.line3.TabIndex = 0; this.line3.Text = "line3"; this.line3.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; // // line2 // this.line2.BackColor = System.Drawing.Color.Transparent; this.line2.Font = new System.Drawing.Font("Arial", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.line2.Location = new System.Drawing.Point(263, 141); this.line2.Name = "line2"; this.line2.Size = new System.Drawing.Size(202, 33); this.line2.TabIndex = 3; this.line2.Text = "line2"; this.line2.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; // // pictureBoxStatus // this.pictureBoxStatus.BackColor = System.Drawing.Color.Transparent; this.pictureBoxStatus.Location = new System.Drawing.Point(304, 270); this.pictureBoxStatus.Margin = new System.Windows.Forms.Padding(0); this.pictureBoxStatus.Name = "pictureBoxStatus"; this.pictureBoxStatus.Size = new System.Drawing.Size(123, 18); this.pictureBoxStatus.TabIndex = 4; this.pictureBoxStatus.TabStop = false; // // panel1 // this.panel1.BackColor = System.Drawing.Color.BlanchedAlmond; this.panel1.BackgroundImage = global::ACAT.Lib.Core.Properties.Resources.SplashScreenBg; this.panel1.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch; this.panel1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.panel1.Controls.Add(this.line1); this.panel1.Controls.Add(this.pictureBoxStatus); this.panel1.Controls.Add(this.line2); this.panel1.Controls.Add(this.line3); this.panel1.Controls.Add(this.intelLogo); this.panel1.Location = new System.Drawing.Point(4, 7); this.panel1.Name = "panel1"; this.panel1.Size = new System.Drawing.Size(576, 313); this.panel1.TabIndex = 5; // // line1 // this.line1.BackColor = System.Drawing.Color.Transparent; this.line1.Font = new System.Drawing.Font("Arial", 15.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.line1.Location = new System.Drawing.Point(175, 86); this.line1.Name = "line1"; this.line1.Size = new System.Drawing.Size(383, 57); this.line1.TabIndex = 5; this.line1.Text = "Assistive Context-Aware Toolkit (ACAT)"; this.line1.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; // // SplashScreen // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.BackColor = System.Drawing.Color.WhiteSmoke; this.ClientSize = new System.Drawing.Size(587, 327); this.Controls.Add(this.splashPictureBox); this.Controls.Add(this.panel1); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None; this.Name = "SplashScreen"; this.Text = "Form1"; ((System.ComponentModel.ISupportInitialize)(this.splashPictureBox)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.intelLogo)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.pictureBoxStatus)).EndInit(); this.panel1.ResumeLayout(false); this.ResumeLayout(false); } #endregion private System.Windows.Forms.PictureBox splashPictureBox; private System.Windows.Forms.ImageList imageList; private System.Windows.Forms.PictureBox intelLogo; private System.Windows.Forms.Label line3; private System.Windows.Forms.Label line2; private System.Windows.Forms.PictureBox pictureBoxStatus; private System.Windows.Forms.Panel panel1; private System.Windows.Forms.Label line1; } }
49.904762
153
0.616174
[ "Apache-2.0" ]
AchilleFoti/acat
src/Libraries/ACATCore/PanelManagement/UI/SplashScreen.designer.cs
8,386
C#
namespace ConsoleForum.Utility { using System.Security.Cryptography; using System.Text; public static class PasswordUtility { public static string Hash(string password) { var hasher = MD5.Create(); return GetHash(hasher, password); } private static string GetHash(MD5 md5Hash, string input) { byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(input)); StringBuilder sBuilder = new StringBuilder(); foreach (byte b in data) { sBuilder.Append(b.ToString("x2")); } return sBuilder.ToString(); } } }
23.758621
77
0.561684
[ "MIT" ]
xenonbg/HighQualityCode
04. Code-Documentation-and-Comments-Homework/Console-Forum-Skeleton/Utility/PasswordUtility.cs
691
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. namespace Microsoft.PowerShell.Commands { using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Globalization; using System.Management.Automation; using System.Reflection; using System.Runtime.InteropServices; using System.Text; using System.Threading; using Microsoft.PowerShell.Commands.ShowCommandExtension; /// <summary> /// Show-Command displays a GUI for a cmdlet, or for all cmdlets if no specific cmdlet is specified. /// </summary> [Cmdlet(VerbsCommon.Show, "Command", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=217448")] public class ShowCommandCommand : PSCmdlet, IDisposable { #region Private Fields /// <summary> /// Set to true when ProcessRecord is reached, since it will always open a window. /// </summary> private bool _hasOpenedWindow; /// <summary> /// Determines if the command should be sent to the pipeline as a string instead of run. /// </summary> private bool _passThrough; /// <summary> /// Uses ShowCommandProxy to invoke WPF GUI object. /// </summary> private ShowCommandProxy _showCommandProxy; /// <summary> /// Data container for all cmdlets. This is populated when show-command is called with no command name. /// </summary> private List<ShowCommandCommandInfo> _commands; /// <summary> /// List of modules that have been loaded indexed by module name. /// </summary> private Dictionary<string, ShowCommandModuleInfo> _importedModules; /// <summary> /// Record the EndProcessing error. /// </summary> private PSDataCollection<ErrorRecord> _errors = new PSDataCollection<ErrorRecord>(); /// <summary> /// Field used for the NoCommonParameter parameter. /// </summary> private SwitchParameter _noCommonParameter; /// <summary> /// Object used for ShowCommand with a command name that holds the view model created for the command. /// </summary> private object _commandViewModelObj; #endregion /// <summary> /// Finalizes an instance of the ShowCommandCommand class. /// </summary> ~ShowCommandCommand() { this.Dispose(false); } #region Input Cmdlet Parameter /// <summary> /// Gets or sets the command name. /// </summary> [Parameter(Position = 0)] [Alias("CommandName")] public string Name { get; set; } /// <summary> /// Gets or sets the Width. /// </summary> [Parameter] [ValidateRange(300, Int32.MaxValue)] public double Height { get; set; } /// <summary> /// Gets or sets the Width. /// </summary> [Parameter] [ValidateRange(300, Int32.MaxValue)] public double Width { get; set; } /// <summary> /// Gets or sets a value indicating Common Parameters should not be displayed. /// </summary> [Parameter] public SwitchParameter NoCommonParameter { get { return _noCommonParameter; } set { _noCommonParameter = value; } } /// <summary> /// Gets or sets a value indicating errors should not cause a message window to be displayed. /// </summary> [Parameter] public SwitchParameter ErrorPopup { get; set; } /// <summary> /// Gets or sets a value indicating the command should be sent to the pipeline as a string instead of run. /// </summary> [Parameter] public SwitchParameter PassThru { get { return _passThrough; } set { _passThrough = value; } } // PassThru #endregion #region Public and Protected Methods /// <summary> /// Executes a PowerShell script, writing the output objects to the pipeline. /// </summary> /// <param name="script">Script to execute</param> public void RunScript(string script) { if (_showCommandProxy == null || string.IsNullOrEmpty(script)) { return; } if (_passThrough) { this.WriteObject(script); return; } if (ErrorPopup) { this.RunScriptSilentlyAndWithErrorHookup(script); return; } if (_showCommandProxy.HasHostWindow) { if (!_showCommandProxy.SetPendingISECommand(script)) { this.RunScriptSilentlyAndWithErrorHookup(script); } return; } if (!ConsoleInputWithNativeMethods.AddToConsoleInputBuffer(script, true)) { this.WriteDebug(FormatAndOut_out_gridview.CannotWriteToConsoleInputBuffer); this.RunScriptSilentlyAndWithErrorHookup(script); } } /// <summary> /// Dispose method in IDisposable. /// </summary> public void Dispose() { this.Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// Initialize a proxy instance for show-command. /// </summary> protected override void BeginProcessing() { _showCommandProxy = new ShowCommandProxy(this); if (_showCommandProxy.ScreenHeight < this.Height) { ErrorRecord error = new ErrorRecord( new NotSupportedException(String.Format(CultureInfo.CurrentUICulture, FormatAndOut_out_gridview.PropertyValidate, "Height", _showCommandProxy.ScreenHeight)), "PARAMETER_DATA_ERROR", ErrorCategory.InvalidData, null); this.ThrowTerminatingError(error); } if (_showCommandProxy.ScreenWidth < this.Width) { ErrorRecord error = new ErrorRecord( new NotSupportedException(String.Format(CultureInfo.CurrentUICulture, FormatAndOut_out_gridview.PropertyValidate, "Width", _showCommandProxy.ScreenWidth)), "PARAMETER_DATA_ERROR", ErrorCategory.InvalidData, null); this.ThrowTerminatingError(error); } } /// <summary> /// ProcessRecord with or without CommandName. /// </summary> protected override void ProcessRecord() { if (Name == null) { _hasOpenedWindow = this.CanProcessRecordForAllCommands(); } else { _hasOpenedWindow = this.CanProcessRecordForOneCommand(); } } /// <summary> /// Optionally displays errors in a message. /// </summary> protected override void EndProcessing() { if (!_hasOpenedWindow) { return; } // We wait untill the window is loaded and then activate it // to work arround the console window gaining activation somewhere // in the end of ProcessRecord, which causes the keyboard focus // (and use oif tab key to focus controls) to go away from the window _showCommandProxy.WindowLoaded.WaitOne(); _showCommandProxy.ActivateWindow(); this.WaitForWindowClosedOrHelpNeeded(); this.RunScript(_showCommandProxy.GetScript()); if (_errors.Count == 0 || !ErrorPopup) { return; } StringBuilder errorString = new StringBuilder(); for (int i = 0; i < _errors.Count; i++) { if (i != 0) { errorString.AppendLine(); } ErrorRecord error = _errors[i]; errorString.Append(error.Exception.Message); } _showCommandProxy.ShowErrorString(errorString.ToString()); } /// <summary> /// StopProcessing is called close the window when user press Ctrl+C in the command prompt. /// </summary> protected override void StopProcessing() { _showCommandProxy.CloseWindow(); } #endregion #region Private Methods /// <summary> /// Runs the script in a new PowerShell instance and hooks up error stream to potentially display error popup. /// This method has the inconvenience of not showing to the console user the script being executed. /// </summary> /// <param name="script">script to be run</param> private void RunScriptSilentlyAndWithErrorHookup(string script) { // errors are not created here, because there is a field for it used in the final pop up PSDataCollection<object> output = new PSDataCollection<object>(); output.DataAdded += new EventHandler<DataAddedEventArgs>(this.Output_DataAdded); _errors.DataAdded += new EventHandler<DataAddedEventArgs>(this.Error_DataAdded); PowerShell ps = PowerShell.Create(RunspaceMode.CurrentRunspace); ps.Streams.Error = _errors; ps.Commands.AddScript(script); ps.Invoke(null, output, null); } /// <summary> /// Issues an error when this.commandName was not found. /// </summary> private void IssueErrorForNoCommand() { InvalidOperationException errorException = new InvalidOperationException( String.Format( CultureInfo.CurrentUICulture, FormatAndOut_out_gridview.CommandNotFound, Name)); this.ThrowTerminatingError(new ErrorRecord(errorException, "NoCommand", ErrorCategory.InvalidOperation, Name)); } /// <summary> /// Issues an error when there is more than one command matching this.commandName. /// </summary> private void IssueErrorForMoreThanOneCommand() { InvalidOperationException errorException = new InvalidOperationException( String.Format( CultureInfo.CurrentUICulture, FormatAndOut_out_gridview.MoreThanOneCommand, Name, "Show-Command")); this.ThrowTerminatingError(new ErrorRecord(errorException, "MoreThanOneCommand", ErrorCategory.InvalidOperation, Name)); } /// <summary> /// Called from CommandProcessRecord to run the command that will get the CommandInfo and list of modules. /// </summary> /// <param name="command">command to be retrieved</param> /// <param name="modules">list of loaded modules</param> private void GetCommandInfoAndModules(out CommandInfo command, out Dictionary<string, ShowCommandModuleInfo> modules) { command = null; modules = null; string commandText = _showCommandProxy.GetShowCommandCommand(Name, true); Collection<PSObject> commandResults = this.InvokeCommand.InvokeScript(commandText); object[] commandObjects = (object[])commandResults[0].BaseObject; object[] moduleObjects = (object[])commandResults[1].BaseObject; if (commandResults == null || moduleObjects == null || commandObjects.Length == 0) { this.IssueErrorForNoCommand(); return; } if (commandObjects.Length > 1) { this.IssueErrorForMoreThanOneCommand(); } command = ((PSObject)commandObjects[0]).BaseObject as CommandInfo; if (command == null) { this.IssueErrorForNoCommand(); return; } if (command.CommandType == CommandTypes.Alias) { commandText = _showCommandProxy.GetShowCommandCommand(command.Definition, false); commandResults = this.InvokeCommand.InvokeScript(commandText); if (commandResults == null || commandResults.Count != 1) { this.IssueErrorForNoCommand(); return; } command = (CommandInfo)commandResults[0].BaseObject; } modules = _showCommandProxy.GetImportedModulesDictionary(moduleObjects); } /// <summary> /// ProcessRecord when a command name is specified. /// </summary> /// <returns>true if there was no exception processing this record</returns> private bool CanProcessRecordForOneCommand() { CommandInfo commandInfo; this.GetCommandInfoAndModules(out commandInfo, out _importedModules); Diagnostics.Assert(commandInfo != null, "GetCommandInfoAndModules would throw a terminating error/exception"); try { _commandViewModelObj = _showCommandProxy.GetCommandViewModel(new ShowCommandCommandInfo(commandInfo), _noCommonParameter.ToBool(), _importedModules, this.Name.IndexOf('\\') != -1); _showCommandProxy.ShowCommandWindow(_commandViewModelObj, _passThrough); } catch (TargetInvocationException ti) { this.WriteError(new ErrorRecord(ti.InnerException, "CannotProcessRecordForOneCommand", ErrorCategory.InvalidOperation, Name)); return false; } return true; } /// <summary> /// ProcessRecord when a command name is not specified. /// </summary> /// <returns>true if there was no exception processing this record</returns> private bool CanProcessRecordForAllCommands() { Collection<PSObject> rawCommands = this.InvokeCommand.InvokeScript(_showCommandProxy.GetShowAllModulesCommand()); _commands = _showCommandProxy.GetCommandList((object[])rawCommands[0].BaseObject); _importedModules = _showCommandProxy.GetImportedModulesDictionary((object[])rawCommands[1].BaseObject); try { _showCommandProxy.ShowAllModulesWindow(_importedModules, _commands, _noCommonParameter.ToBool(), _passThrough); } catch (TargetInvocationException ti) { this.WriteError(new ErrorRecord(ti.InnerException, "CannotProcessRecordForAllCommands", ErrorCategory.InvalidOperation, Name)); return false; } return true; } /// <summary> /// Waits until the window has been closed answering HelpNeeded events. /// </summary> private void WaitForWindowClosedOrHelpNeeded() { do { int which = WaitHandle.WaitAny(new WaitHandle[] { _showCommandProxy.WindowClosed, _showCommandProxy.HelpNeeded, _showCommandProxy.ImportModuleNeeded }); if (which == 0) { break; } if (which == 1) { Collection<PSObject> helpResults = this.InvokeCommand.InvokeScript(_showCommandProxy.GetHelpCommand(_showCommandProxy.CommandNeedingHelp)); _showCommandProxy.DisplayHelp(helpResults); continue; } Diagnostics.Assert(which == 2, "which is 0,1 or 2 and 0 and 1 have been eliminated in the ifs above"); string commandToRun = _showCommandProxy.GetImportModuleCommand(_showCommandProxy.ParentModuleNeedingImportModule); Collection<PSObject> rawCommands; try { rawCommands = this.InvokeCommand.InvokeScript(commandToRun); } catch (RuntimeException e) { _showCommandProxy.ImportModuleFailed(e); continue; } _commands = _showCommandProxy.GetCommandList((object[])rawCommands[0].BaseObject); _importedModules = _showCommandProxy.GetImportedModulesDictionary((object[])rawCommands[1].BaseObject); _showCommandProxy.ImportModuleDone(_importedModules, _commands); continue; } while (true); } /// <summary> /// Writes the output of a script being run into the pipeline. /// </summary> /// <param name="sender">output collection</param> /// <param name="e">output event</param> private void Output_DataAdded(object sender, DataAddedEventArgs e) { this.WriteObject(((PSDataCollection<object>)sender)[e.Index]); } /// <summary> /// Writes the errors of a script being run into the pipeline. /// </summary> /// <param name="sender">error collection</param> /// <param name="e">error event</param> private void Error_DataAdded(object sender, DataAddedEventArgs e) { this.WriteError(((PSDataCollection<ErrorRecord>)sender)[e.Index]); } /// <summary> /// Implements IDisposable logic. /// </summary> /// <param name="isDisposing">true if being called from Dispose</param> private void Dispose(bool isDisposing) { if (isDisposing) { if (_errors != null) { _errors.Dispose(); _errors = null; } } } #endregion /// <summary> /// Wraps interop code for console input buffer. /// </summary> internal static class ConsoleInputWithNativeMethods { /// <summary> /// Constant used in calls to GetStdHandle. /// </summary> internal const int STD_INPUT_HANDLE = -10; /// <summary> /// Adds a string to the console input buffer. /// </summary> /// <param name="str">string to add to console input buffer</param> /// <param name="newLine">true to add Enter after the string</param> /// <returns>true if it was successful in adding all characters to console input buffer</returns> internal static bool AddToConsoleInputBuffer(string str, bool newLine) { IntPtr handle = ConsoleInputWithNativeMethods.GetStdHandle(ConsoleInputWithNativeMethods.STD_INPUT_HANDLE); if (handle == IntPtr.Zero) { return false; } uint strLen = (uint)str.Length; ConsoleInputWithNativeMethods.INPUT_RECORD[] records = new ConsoleInputWithNativeMethods.INPUT_RECORD[strLen + (newLine ? 1 : 0)]; for (int i = 0; i < strLen; i++) { ConsoleInputWithNativeMethods.INPUT_RECORD.SetInputRecord(ref records[i], str[i]); } uint written; if (!ConsoleInputWithNativeMethods.WriteConsoleInput(handle, records, strLen, out written) || written != strLen) { // I do not know of a case where written is not going to be strlen. Maybe for some character that // is not supported in the console. The API suggests this can happen, // so we handle it by returning false return false; } // Enter is written separately, because if this is a command, and one of the characters in the command was not written // (written != strLen) it is desireable to fail (return false) before typing enter and running the command if (newLine) { ConsoleInputWithNativeMethods.INPUT_RECORD[] enterArray = new ConsoleInputWithNativeMethods.INPUT_RECORD[1]; ConsoleInputWithNativeMethods.INPUT_RECORD.SetInputRecord(ref enterArray[0], (char)13); written = 0; if (!ConsoleInputWithNativeMethods.WriteConsoleInput(handle, enterArray, 1, out written)) { // I don't think this will happen return false; } Diagnostics.Assert(written == 1, "only Enter is being added and it is a supported character"); } return true; } /// <summary> /// Gets the console handle. /// </summary> /// <param name="nStdHandle">which console handle to get</param> /// <returns>the console handle</returns> [DllImport("kernel32.dll", SetLastError = true)] internal static extern IntPtr GetStdHandle(int nStdHandle); /// <summary> /// Writes to the console input buffer. /// </summary> /// <param name="hConsoleInput">console handle</param> /// <param name="lpBuffer">inputs to be written</param> /// <param name="nLength">number of inputs to be written</param> /// <param name="lpNumberOfEventsWritten">returned number of inputs actually written</param> /// <returns>0 if the function fails</returns> [DllImport("kernel32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool WriteConsoleInput( IntPtr hConsoleInput, INPUT_RECORD[] lpBuffer, uint nLength, out uint lpNumberOfEventsWritten); /// <summary> /// A record to be added to the console buffer. /// </summary> internal struct INPUT_RECORD { /// <summary> /// The proper event type for a KeyEvent KEY_EVENT_RECORD. /// </summary> internal const int KEY_EVENT = 0x0001; /// <summary> /// input buffer event type. /// </summary> internal ushort EventType; /// <summary> /// The actual event. The original structure is a union of many others, but this is the largest of them. /// And we don't need other kinds of events. /// </summary> internal KEY_EVENT_RECORD KeyEvent; /// <summary> /// Sets the necessary fields of <paramref name="inputRecord"/> for a KeyDown event for the <paramref name="character"/> /// </summary> /// <param name="inputRecord">input record to be set</param> /// <param name="character">character to set the record with</param> internal static void SetInputRecord(ref INPUT_RECORD inputRecord, char character) { inputRecord.EventType = INPUT_RECORD.KEY_EVENT; inputRecord.KeyEvent.bKeyDown = true; inputRecord.KeyEvent.UnicodeChar = character; } } /// <summary> /// Type of INPUT_RECORD which is a key. /// </summary> [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] internal struct KEY_EVENT_RECORD { /// <summary> /// True for key down and false for key up, but only needed if wVirtualKeyCode is used. /// </summary> internal bool bKeyDown; /// <summary> /// Repeat count. /// </summary> internal ushort wRepeatCount; /// <summary> /// Virtual key code. /// </summary> internal ushort wVirtualKeyCode; /// <summary> /// Virtual key scan code. /// </summary> internal ushort wVirtualScanCode; /// <summary> /// Character in input. If this is specified, wVirtualKeyCode, and others don't need to be. /// </summary> internal char UnicodeChar; /// <summary> /// State of keys like Shift and control. /// </summary> internal uint dwControlKeyState; } } } }
38.749231
196
0.558185
[ "MIT" ]
Francisco-Gamino/PowerShell
src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommand.cs
25,187
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Dynamic; using System.Reflection; namespace IgorO.ExposedObjectProject { public class ExposedObject : DynamicObject { private object m_object; private Type m_type; private Dictionary<string, Dictionary<int, List<MethodInfo>>> m_instanceMethods; private Dictionary<string, Dictionary<int, List<MethodInfo>>> m_genInstanceMethods; private ExposedObject(object obj) { m_object = obj; m_type = obj.GetType(); m_instanceMethods = m_type .GetMethods(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance) .Where(m => !m.IsGenericMethod) .GroupBy(m => m.Name) .ToDictionary( p => p.Key, p => p.GroupBy(r => r.GetParameters().Length).ToDictionary(r => r.Key, r => r.ToList())); m_genInstanceMethods = m_type .GetMethods(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance) .Where(m => m.IsGenericMethod) .GroupBy(m => m.Name) .ToDictionary( p => p.Key, p => p.GroupBy(r => r.GetParameters().Length).ToDictionary(r => r.Key, r => r.ToList())); } public object Object { get { return m_object; } } public static dynamic New<T>() { return New(typeof(T)); } public static dynamic New(Type type) { return new ExposedObject(Activator.CreateInstance(type)); } public static dynamic From(object obj) { return new ExposedObject(obj); } public static T Cast<T>(ExposedObject t) { return (T)t.m_object; } public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result) { // Get type args of the call Type[] typeArgs = ExposedObjectHelper.GetTypeArgs(binder); if (typeArgs != null && typeArgs.Length == 0) typeArgs = null; // // Try to call a non-generic instance method // if (typeArgs == null && m_instanceMethods.ContainsKey(binder.Name) && m_instanceMethods[binder.Name].ContainsKey(args.Length) && ExposedObjectHelper.InvokeBestMethod(args, m_object, m_instanceMethods[binder.Name][args.Length], out result)) { return true; } // // Try to call a generic instance method // if (m_instanceMethods.ContainsKey(binder.Name) && m_instanceMethods[binder.Name].ContainsKey(args.Length)) { List<MethodInfo> methods = new List<MethodInfo>(); foreach (var method in m_genInstanceMethods[binder.Name][args.Length]) { if (method.GetGenericArguments().Length == typeArgs.Length) { methods.Add(method.MakeGenericMethod(typeArgs)); } } if (ExposedObjectHelper.InvokeBestMethod(args, m_object, methods, out result)) { return true; } } result = null; return false; } public override bool TrySetMember(SetMemberBinder binder, object value) { var propertyInfo = m_type.GetProperty( binder.Name, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance); if (propertyInfo != null) { propertyInfo.SetValue(m_object, value, null); return true; } var fieldInfo = m_type.GetField( binder.Name, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance); if (fieldInfo != null) { fieldInfo.SetValue(m_object, value); return true; } return false; } public override bool TryGetMember(GetMemberBinder binder, out object result) { var propertyInfo = m_object.GetType().GetProperty( binder.Name, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance); if (propertyInfo != null) { result = propertyInfo.GetValue(m_object, null); return true; } var fieldInfo = m_object.GetType().GetField( binder.Name, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance); if (fieldInfo != null) { result = fieldInfo.GetValue(m_object); return true; } result = null; return false; } public override bool TryConvert(ConvertBinder binder, out object result) { result = m_object; return true; } } }
32.083832
133
0.52165
[ "Artistic-2.0" ]
Munomic/Bellhop
ExEnFontShim/ExposedObject/ExposedObject.cs
5,360
C#
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using UnityEditor.IMGUI.Controls; using UnityEngine; /*************************************************************************************** * Title: Behavior Tree * Author: Stephen Trinh * Date: 4/28/18 * Code version: 1.0 * Availability: https://github.com/stephentrinh/BehaviorTree * ***************************************************************************************/ namespace STBehaviorTree { public class BehaviorTreeNodeItem : TreeViewItem { /// <summary> /// Type of the behavior class /// </summary> public Type Data; public BehaviorTreeNodeItem(int id, int depth, string displayName, Type data) : base(id, depth, displayName) { Data = data; } } public class BehaviorTreeNodeModelView : TreeView { IList<BehaviorTreeNodeItem> _nodes; public BehaviorTreeNodeModelView(TreeViewState treeViewState) : base(treeViewState) { Reload(); showBorder = true; } protected override TreeViewItem BuildRoot() { var root = new TreeViewItem { id = 0, depth = -1, displayName = "Root"}; var attributeTypePairs = new List<AttributeTypePair>(); BehaviorTreeNodeAttributeHandler.LoadAttributes(ref attributeTypePairs); _nodes = new List<BehaviorTreeNodeItem>(); ParseAttributes(attributeTypePairs, ref _nodes); SetupParentsAndChildrenFromDepths(root, _nodes.Cast<TreeViewItem>().ToList()); return root; } IList<BehaviorTreeNodeItem> GetNodesAsIList() { return _nodes; } void ParseAttributes(List<AttributeTypePair> attributeTypePairs, ref IList<BehaviorTreeNodeItem> result) { attributeTypePairs.Sort((s1, s2) => s1.attributeName.CompareTo(s2.attributeName)); List<string> category = new List<string>(); int ID = 1; for (int i = 0; i < attributeTypePairs.Count; ++i) { var split = attributeTypePairs[i].attributeName.Split('/'); for (int j = 0; j < split.Length; ++j) { if (j == split.Length - 1) { result.Add(new BehaviorTreeNodeItem(ID++, j, split[j], attributeTypePairs[i].classType)); break; } else if (category.Count <= j) { category.Add(split[j]); result.Add(new BehaviorTreeNodeItem(ID++, j, split[j], null)); } else if (category[j] != split[j]) { category.RemoveRange(j, category.Count - j); category.Add(split[j]); result.Add(new BehaviorTreeNodeItem(ID++, j, split[j], null)); } } } } #region Selection protected override bool CanMultiSelect(TreeViewItem item) { return false; } /// <summary> /// Returns the first index /// </summary> /// <param name="indices"></param> /// <returns></returns> public BehaviorTreeNodeItem GetSelectionFromIndices() { if (GetSelection() == null || !GetSelection().Any()) return null; return _nodes[(GetSelection()[0]) - 1]; } #endregion } }
31.758621
113
0.504886
[ "MIT" ]
stephentrinh/BehaviorTree
Editor/BehaviorTreeNodeModelView.cs
3,686
C#
#region Copyright // // DotNetNuke® - https://www.dnnsoftware.com // Copyright (c) 2002-2018 // by DotNetNuke Corporation // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated // documentation files (the "Software"), to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and // to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions // of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED // TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF // CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. #endregion #region Usings using System; using System.Collections.Generic; using System.Data; using System.Runtime.Serialization; using System.Security.Permissions; #endregion namespace DotNetNuke.Services.Exceptions { public class ObjectHydrationException : BasePortalException { private List<string> _Columns; private Type _Type; public ObjectHydrationException(string message, Exception innerException) : base(message, innerException) { } public ObjectHydrationException(string message, Exception innerException, Type type, IDataReader dr) : base(message, innerException) { _Type = type; _Columns = new List<string>(); foreach (DataRow row in dr.GetSchemaTable().Rows) { _Columns.Add(row["ColumnName"].ToString()); } } protected ObjectHydrationException(SerializationInfo info, StreamingContext context) : base(info, context) { } public List<string> Columns { get { return _Columns; } set { _Columns = value; } } public Type Type { get { return _Type; } set { _Type = value; } } public override string Message { get { string _Message = base.Message; _Message += " Expecting - " + Type + "."; _Message += " Returned - "; foreach (string columnName in Columns) { _Message += columnName + ", "; } return _Message; } } } }
32.105263
140
0.603607
[ "MIT" ]
Mhtshum/Dnn.Platform
DNN Platform/Library/Services/Exceptions/ObjectHydrationException.cs
3,051
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.ComponentModel.DataAnnotations; namespace LocalizationSample.Web.Models { public class Product { [Required(ErrorMessage = "ProductName")] public string ProductName { get; set; } } }
28.071429
111
0.717557
[ "Apache-2.0" ]
Mani4007/ASPNET
samples/LocalizationSample.Web/Models/Product.cs
395
C#
using System; namespace DaprFrontEnd { public class WeatherForecast { public DateTime Date { get; set; } public int TemperatureC { get; set; } public int TemperatureF { get; set; } public string Summary { get; set; } } }
17.933333
45
0.598513
[ "Apache-2.0" ]
futugyou/CodeFragments
Dapr/DaprFrontEnd/WeatherForecast.cs
271
C#
// <auto-generated> // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // </auto-generated> namespace Microsoft.Azure.Management.AppService.Fluent { using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; /// <summary> /// AppServiceEnvironmentsOperations operations. /// </summary> internal partial class AppServiceEnvironmentsOperations : IServiceOperations<WebSiteManagementClient>, IAppServiceEnvironmentsOperations { /// <summary> /// Initializes a new instance of the AppServiceEnvironmentsOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal AppServiceEnvironmentsOperations(WebSiteManagementClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the WebSiteManagementClient /// </summary> public WebSiteManagementClient Client { get; private set; } /// <summary> /// Get all App Service Environments for a subscription. /// </summary> /// <remarks> /// Get all App Service Environments for a subscription. /// </remarks> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="DefaultErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<AppServiceEnvironmentResourceInner>>> ListWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/Microsoft.Web/hostingEnvironments").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new DefaultErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); DefaultErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<DefaultErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<AppServiceEnvironmentResourceInner>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<AppServiceEnvironmentResourceInner>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get all App Service Environments in a resource group. /// </summary> /// <remarks> /// Get all App Service Environments in a resource group. /// </remarks> /// <param name='resourceGroupName'> /// Name of the resource group to which the resource belongs. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="DefaultErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<AppServiceEnvironmentResourceInner>>> ListByResourceGroupWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (resourceGroupName != null) { if (resourceGroupName.Length > 90) { throw new ValidationException(ValidationRules.MaxLength, "resourceGroupName", 90); } if (resourceGroupName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "resourceGroupName", 1); } if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._\\(\\)]+[^\\.]$")) { throw new ValidationException(ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._\\(\\)]+[^\\.]$"); } } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListByResourceGroup", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/hostingEnvironments").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new DefaultErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); DefaultErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<DefaultErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<AppServiceEnvironmentResourceInner>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<AppServiceEnvironmentResourceInner>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get the properties of an App Service Environment. /// </summary> /// <remarks> /// Get the properties of an App Service Environment. /// </remarks> /// <param name='resourceGroupName'> /// Name of the resource group to which the resource belongs. /// </param> /// <param name='name'> /// Name of the App Service Environment. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="DefaultErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<AppServiceEnvironmentResourceInner>> GetWithHttpMessagesAsync(string resourceGroupName, string name, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (resourceGroupName != null) { if (resourceGroupName.Length > 90) { throw new ValidationException(ValidationRules.MaxLength, "resourceGroupName", 90); } if (resourceGroupName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "resourceGroupName", 1); } if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._\\(\\)]+[^\\.]$")) { throw new ValidationException(ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._\\(\\)]+[^\\.]$"); } } if (name == null) { throw new ValidationException(ValidationRules.CannotBeNull, "name"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("name", name); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/hostingEnvironments/{name}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{name}", System.Uri.EscapeDataString(name)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new DefaultErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); DefaultErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<DefaultErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<AppServiceEnvironmentResourceInner>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<AppServiceEnvironmentResourceInner>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Create or update an App Service Environment. /// </summary> /// <remarks> /// Create or update an App Service Environment. /// </remarks> /// <param name='resourceGroupName'> /// Name of the resource group to which the resource belongs. /// </param> /// <param name='name'> /// Name of the App Service Environment. /// </param> /// <param name='hostingEnvironmentEnvelope'> /// Configuration details of the App Service Environment. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse<AppServiceEnvironmentResourceInner>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string name, AppServiceEnvironmentResourceInner hostingEnvironmentEnvelope, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Send Request AzureOperationResponse<AppServiceEnvironmentResourceInner> _response = await BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, name, hostingEnvironmentEnvelope, customHeaders, cancellationToken).ConfigureAwait(false); return await Client.GetPutOrPatchOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false); } /// <summary> /// Delete an App Service Environment. /// </summary> /// <remarks> /// Delete an App Service Environment. /// </remarks> /// <param name='resourceGroupName'> /// Name of the resource group to which the resource belongs. /// </param> /// <param name='name'> /// Name of the App Service Environment. /// </param> /// <param name='forceDelete'> /// Specify &lt;code&gt;true&lt;/code&gt; to force the deletion even if the App /// Service Environment contains resources. The default is /// &lt;code&gt;false&lt;/code&gt;. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string name, bool? forceDelete = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Send request AzureOperationResponse _response = await BeginDeleteWithHttpMessagesAsync(resourceGroupName, name, forceDelete, customHeaders, cancellationToken).ConfigureAwait(false); return await Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false); } /// <summary> /// Create or update an App Service Environment. /// </summary> /// <remarks> /// Create or update an App Service Environment. /// </remarks> /// <param name='resourceGroupName'> /// Name of the resource group to which the resource belongs. /// </param> /// <param name='name'> /// Name of the App Service Environment. /// </param> /// <param name='hostingEnvironmentEnvelope'> /// Configuration details of the App Service Environment. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<AppServiceEnvironmentResourceInner>> UpdateWithHttpMessagesAsync(string resourceGroupName, string name, AppServiceEnvironmentPatchResource hostingEnvironmentEnvelope, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (resourceGroupName != null) { if (resourceGroupName.Length > 90) { throw new ValidationException(ValidationRules.MaxLength, "resourceGroupName", 90); } if (resourceGroupName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "resourceGroupName", 1); } if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._\\(\\)]+[^\\.]$")) { throw new ValidationException(ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._\\(\\)]+[^\\.]$"); } } if (name == null) { throw new ValidationException(ValidationRules.CannotBeNull, "name"); } if (hostingEnvironmentEnvelope == null) { throw new ValidationException(ValidationRules.CannotBeNull, "hostingEnvironmentEnvelope"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("name", name); tracingParameters.Add("hostingEnvironmentEnvelope", hostingEnvironmentEnvelope); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Update", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/hostingEnvironments/{name}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{name}", System.Uri.EscapeDataString(name)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PATCH"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(hostingEnvironmentEnvelope != null) { _requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(hostingEnvironmentEnvelope, Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200 && (int)_statusCode != 202 && (int)_statusCode != 400 && (int)_statusCode != 404 && (int)_statusCode != 409) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<AppServiceEnvironmentResourceInner>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<AppServiceEnvironmentResourceInner>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } // Deserialize Response if ((int)_statusCode == 202) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<AppServiceEnvironmentResourceInner>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get the used, available, and total worker capacity an App Service /// Environment. /// </summary> /// <remarks> /// Get the used, available, and total worker capacity an App Service /// Environment. /// </remarks> /// <param name='resourceGroupName'> /// Name of the resource group to which the resource belongs. /// </param> /// <param name='name'> /// Name of the App Service Environment. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="DefaultErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<StampCapacity>>> ListCapacitiesWithHttpMessagesAsync(string resourceGroupName, string name, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (resourceGroupName != null) { if (resourceGroupName.Length > 90) { throw new ValidationException(ValidationRules.MaxLength, "resourceGroupName", 90); } if (resourceGroupName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "resourceGroupName", 1); } if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._\\(\\)]+[^\\.]$")) { throw new ValidationException(ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._\\(\\)]+[^\\.]$"); } } if (name == null) { throw new ValidationException(ValidationRules.CannotBeNull, "name"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("name", name); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListCapacities", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/hostingEnvironments/{name}/capacities/compute").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{name}", System.Uri.EscapeDataString(name)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new DefaultErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); DefaultErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<DefaultErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<StampCapacity>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<StampCapacity>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get IP addresses assigned to an App Service Environment. /// </summary> /// <remarks> /// Get IP addresses assigned to an App Service Environment. /// </remarks> /// <param name='resourceGroupName'> /// Name of the resource group to which the resource belongs. /// </param> /// <param name='name'> /// Name of the App Service Environment. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="DefaultErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<AddressResponseInner>> ListVipsWithHttpMessagesAsync(string resourceGroupName, string name, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (resourceGroupName != null) { if (resourceGroupName.Length > 90) { throw new ValidationException(ValidationRules.MaxLength, "resourceGroupName", 90); } if (resourceGroupName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "resourceGroupName", 1); } if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._\\(\\)]+[^\\.]$")) { throw new ValidationException(ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._\\(\\)]+[^\\.]$"); } } if (name == null) { throw new ValidationException(ValidationRules.CannotBeNull, "name"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("name", name); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListVips", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/hostingEnvironments/{name}/capacities/virtualip").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{name}", System.Uri.EscapeDataString(name)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new DefaultErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); DefaultErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<DefaultErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<AddressResponseInner>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<AddressResponseInner>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Move an App Service Environment to a different VNET. /// </summary> /// <remarks> /// Move an App Service Environment to a different VNET. /// </remarks> /// <param name='resourceGroupName'> /// Name of the resource group to which the resource belongs. /// </param> /// <param name='name'> /// Name of the App Service Environment. /// </param> /// <param name='vnetInfo'> /// Details for the new virtual network. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse<IPage<SiteInner>>> ChangeVnetWithHttpMessagesAsync(string resourceGroupName, string name, VirtualNetworkProfile vnetInfo, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Send request AzureOperationResponse<IPage<SiteInner>> _response = await BeginChangeVnetWithHttpMessagesAsync(resourceGroupName, name, vnetInfo, customHeaders, cancellationToken).ConfigureAwait(false); return await Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false); } /// <summary> /// Get diagnostic information for an App Service Environment. /// </summary> /// <remarks> /// Get diagnostic information for an App Service Environment. /// </remarks> /// <param name='resourceGroupName'> /// Name of the resource group to which the resource belongs. /// </param> /// <param name='name'> /// Name of the App Service Environment. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="DefaultErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IList<HostingEnvironmentDiagnosticsInner>>> ListDiagnosticsWithHttpMessagesAsync(string resourceGroupName, string name, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (resourceGroupName != null) { if (resourceGroupName.Length > 90) { throw new ValidationException(ValidationRules.MaxLength, "resourceGroupName", 90); } if (resourceGroupName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "resourceGroupName", 1); } if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._\\(\\)]+[^\\.]$")) { throw new ValidationException(ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._\\(\\)]+[^\\.]$"); } } if (name == null) { throw new ValidationException(ValidationRules.CannotBeNull, "name"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("name", name); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListDiagnostics", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/hostingEnvironments/{name}/diagnostics").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{name}", System.Uri.EscapeDataString(name)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new DefaultErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); DefaultErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<DefaultErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IList<HostingEnvironmentDiagnosticsInner>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<IList<HostingEnvironmentDiagnosticsInner>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get a diagnostics item for an App Service Environment. /// </summary> /// <remarks> /// Get a diagnostics item for an App Service Environment. /// </remarks> /// <param name='resourceGroupName'> /// Name of the resource group to which the resource belongs. /// </param> /// <param name='name'> /// Name of the App Service Environment. /// </param> /// <param name='diagnosticsName'> /// Name of the diagnostics item. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="DefaultErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<HostingEnvironmentDiagnosticsInner>> GetDiagnosticsItemWithHttpMessagesAsync(string resourceGroupName, string name, string diagnosticsName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (resourceGroupName != null) { if (resourceGroupName.Length > 90) { throw new ValidationException(ValidationRules.MaxLength, "resourceGroupName", 90); } if (resourceGroupName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "resourceGroupName", 1); } if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._\\(\\)]+[^\\.]$")) { throw new ValidationException(ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._\\(\\)]+[^\\.]$"); } } if (name == null) { throw new ValidationException(ValidationRules.CannotBeNull, "name"); } if (diagnosticsName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "diagnosticsName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("name", name); tracingParameters.Add("diagnosticsName", diagnosticsName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetDiagnosticsItem", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/hostingEnvironments/{name}/diagnostics/{diagnosticsName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{name}", System.Uri.EscapeDataString(name)); _url = _url.Replace("{diagnosticsName}", System.Uri.EscapeDataString(diagnosticsName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new DefaultErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); DefaultErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<DefaultErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<HostingEnvironmentDiagnosticsInner>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<HostingEnvironmentDiagnosticsInner>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get global metric definitions of an App Service Environment. /// </summary> /// <remarks> /// Get global metric definitions of an App Service Environment. /// </remarks> /// <param name='resourceGroupName'> /// Name of the resource group to which the resource belongs. /// </param> /// <param name='name'> /// Name of the App Service Environment. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="DefaultErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<MetricDefinitionInner>> ListMetricDefinitionsWithHttpMessagesAsync(string resourceGroupName, string name, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (resourceGroupName != null) { if (resourceGroupName.Length > 90) { throw new ValidationException(ValidationRules.MaxLength, "resourceGroupName", 90); } if (resourceGroupName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "resourceGroupName", 1); } if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._\\(\\)]+[^\\.]$")) { throw new ValidationException(ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._\\(\\)]+[^\\.]$"); } } if (name == null) { throw new ValidationException(ValidationRules.CannotBeNull, "name"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("name", name); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListMetricDefinitions", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/hostingEnvironments/{name}/metricdefinitions").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{name}", System.Uri.EscapeDataString(name)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new DefaultErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); DefaultErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<DefaultErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<MetricDefinitionInner>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<MetricDefinitionInner>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get global metrics of an App Service Environment. /// </summary> /// <remarks> /// Get global metrics of an App Service Environment. /// </remarks> /// <param name='resourceGroupName'> /// Name of the resource group to which the resource belongs. /// </param> /// <param name='name'> /// Name of the App Service Environment. /// </param> /// <param name='details'> /// Specify &lt;code&gt;true&lt;/code&gt; to include instance details. The /// default is &lt;code&gt;false&lt;/code&gt;. /// </param> /// <param name='filter'> /// Return only usages/metrics specified in the filter. Filter conforms to /// odata syntax. Example: $filter=(name.value eq 'Metric1' or name.value eq /// 'Metric2') and startTime eq '2014-01-01T00:00:00Z' and endTime eq /// '2014-12-31T23:59:59Z' and timeGrain eq duration'[Hour|Minute|Day]'. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="DefaultErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<ResourceMetric>>> ListMetricsWithHttpMessagesAsync(string resourceGroupName, string name, bool? details = default(bool?), string filter = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (resourceGroupName != null) { if (resourceGroupName.Length > 90) { throw new ValidationException(ValidationRules.MaxLength, "resourceGroupName", 90); } if (resourceGroupName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "resourceGroupName", 1); } if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._\\(\\)]+[^\\.]$")) { throw new ValidationException(ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._\\(\\)]+[^\\.]$"); } } if (name == null) { throw new ValidationException(ValidationRules.CannotBeNull, "name"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("name", name); tracingParameters.Add("details", details); tracingParameters.Add("filter", filter); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListMetrics", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/hostingEnvironments/{name}/metrics").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{name}", System.Uri.EscapeDataString(name)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (details != null) { _queryParameters.Add(string.Format("details={0}", System.Uri.EscapeDataString(Rest.Serialization.SafeJsonConvert.SerializeObject(details, Client.SerializationSettings).Trim('"')))); } if (filter != null) { _queryParameters.Add(string.Format("$filter={0}", filter)); } if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new DefaultErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); DefaultErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<DefaultErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<ResourceMetric>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<ResourceMetric>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get all multi-role pools. /// </summary> /// <remarks> /// Get all multi-role pools. /// </remarks> /// <param name='resourceGroupName'> /// Name of the resource group to which the resource belongs. /// </param> /// <param name='name'> /// Name of the App Service Environment. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="DefaultErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<WorkerPoolResourceInner>>> ListMultiRolePoolsWithHttpMessagesAsync(string resourceGroupName, string name, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (resourceGroupName != null) { if (resourceGroupName.Length > 90) { throw new ValidationException(ValidationRules.MaxLength, "resourceGroupName", 90); } if (resourceGroupName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "resourceGroupName", 1); } if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._\\(\\)]+[^\\.]$")) { throw new ValidationException(ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._\\(\\)]+[^\\.]$"); } } if (name == null) { throw new ValidationException(ValidationRules.CannotBeNull, "name"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("name", name); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListMultiRolePools", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/hostingEnvironments/{name}/multiRolePools").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{name}", System.Uri.EscapeDataString(name)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new DefaultErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); DefaultErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<DefaultErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<WorkerPoolResourceInner>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<WorkerPoolResourceInner>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get properties of a multi-role pool. /// </summary> /// <remarks> /// Get properties of a multi-role pool. /// </remarks> /// <param name='resourceGroupName'> /// Name of the resource group to which the resource belongs. /// </param> /// <param name='name'> /// Name of the App Service Environment. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="DefaultErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<WorkerPoolResourceInner>> GetMultiRolePoolWithHttpMessagesAsync(string resourceGroupName, string name, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (resourceGroupName != null) { if (resourceGroupName.Length > 90) { throw new ValidationException(ValidationRules.MaxLength, "resourceGroupName", 90); } if (resourceGroupName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "resourceGroupName", 1); } if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._\\(\\)]+[^\\.]$")) { throw new ValidationException(ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._\\(\\)]+[^\\.]$"); } } if (name == null) { throw new ValidationException(ValidationRules.CannotBeNull, "name"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("name", name); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetMultiRolePool", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/hostingEnvironments/{name}/multiRolePools/default").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{name}", System.Uri.EscapeDataString(name)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new DefaultErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); DefaultErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<DefaultErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<WorkerPoolResourceInner>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<WorkerPoolResourceInner>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Create or update a multi-role pool. /// </summary> /// <remarks> /// Create or update a multi-role pool. /// </remarks> /// <param name='resourceGroupName'> /// Name of the resource group to which the resource belongs. /// </param> /// <param name='name'> /// Name of the App Service Environment. /// </param> /// <param name='multiRolePoolEnvelope'> /// Properties of the multi-role pool. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse<WorkerPoolResourceInner>> CreateOrUpdateMultiRolePoolWithHttpMessagesAsync(string resourceGroupName, string name, WorkerPoolResourceInner multiRolePoolEnvelope, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Send Request AzureOperationResponse<WorkerPoolResourceInner> _response = await BeginCreateOrUpdateMultiRolePoolWithHttpMessagesAsync(resourceGroupName, name, multiRolePoolEnvelope, customHeaders, cancellationToken).ConfigureAwait(false); return await Client.GetPutOrPatchOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false); } /// <summary> /// Create or update a multi-role pool. /// </summary> /// <remarks> /// Create or update a multi-role pool. /// </remarks> /// <param name='resourceGroupName'> /// Name of the resource group to which the resource belongs. /// </param> /// <param name='name'> /// Name of the App Service Environment. /// </param> /// <param name='multiRolePoolEnvelope'> /// Properties of the multi-role pool. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<WorkerPoolResourceInner>> UpdateMultiRolePoolWithHttpMessagesAsync(string resourceGroupName, string name, WorkerPoolResourceInner multiRolePoolEnvelope, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (resourceGroupName != null) { if (resourceGroupName.Length > 90) { throw new ValidationException(ValidationRules.MaxLength, "resourceGroupName", 90); } if (resourceGroupName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "resourceGroupName", 1); } if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._\\(\\)]+[^\\.]$")) { throw new ValidationException(ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._\\(\\)]+[^\\.]$"); } } if (name == null) { throw new ValidationException(ValidationRules.CannotBeNull, "name"); } if (multiRolePoolEnvelope == null) { throw new ValidationException(ValidationRules.CannotBeNull, "multiRolePoolEnvelope"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("name", name); tracingParameters.Add("multiRolePoolEnvelope", multiRolePoolEnvelope); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "UpdateMultiRolePool", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/hostingEnvironments/{name}/multiRolePools/default").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{name}", System.Uri.EscapeDataString(name)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PATCH"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(multiRolePoolEnvelope != null) { _requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(multiRolePoolEnvelope, Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200 && (int)_statusCode != 202 && (int)_statusCode != 400 && (int)_statusCode != 404 && (int)_statusCode != 409) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<WorkerPoolResourceInner>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<WorkerPoolResourceInner>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } // Deserialize Response if ((int)_statusCode == 202) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<WorkerPoolResourceInner>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get metric definitions for a specific instance of a multi-role pool of an /// App Service Environment. /// </summary> /// <remarks> /// Get metric definitions for a specific instance of a multi-role pool of an /// App Service Environment. /// </remarks> /// <param name='resourceGroupName'> /// Name of the resource group to which the resource belongs. /// </param> /// <param name='name'> /// Name of the App Service Environment. /// </param> /// <param name='instance'> /// Name of the instance in the multi-role pool. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="DefaultErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<ResourceMetricDefinition>>> ListMultiRolePoolInstanceMetricDefinitionsWithHttpMessagesAsync(string resourceGroupName, string name, string instance, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (resourceGroupName != null) { if (resourceGroupName.Length > 90) { throw new ValidationException(ValidationRules.MaxLength, "resourceGroupName", 90); } if (resourceGroupName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "resourceGroupName", 1); } if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._\\(\\)]+[^\\.]$")) { throw new ValidationException(ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._\\(\\)]+[^\\.]$"); } } if (name == null) { throw new ValidationException(ValidationRules.CannotBeNull, "name"); } if (instance == null) { throw new ValidationException(ValidationRules.CannotBeNull, "instance"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("name", name); tracingParameters.Add("instance", instance); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListMultiRolePoolInstanceMetricDefinitions", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/hostingEnvironments/{name}/multiRolePools/default/instances/{instance}/metricdefinitions").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{name}", System.Uri.EscapeDataString(name)); _url = _url.Replace("{instance}", System.Uri.EscapeDataString(instance)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new DefaultErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); DefaultErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<DefaultErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<ResourceMetricDefinition>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<ResourceMetricDefinition>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get metrics for a specific instance of a multi-role pool of an App Service /// Environment. /// </summary> /// <remarks> /// Get metrics for a specific instance of a multi-role pool of an App Service /// Environment. /// </remarks> /// <param name='resourceGroupName'> /// Name of the resource group to which the resource belongs. /// </param> /// <param name='name'> /// Name of the App Service Environment. /// </param> /// <param name='instance'> /// Name of the instance in the multi-role pool. /// </param> /// <param name='details'> /// Specify &lt;code&gt;true&lt;/code&gt; to include instance details. The /// default is &lt;code&gt;false&lt;/code&gt;. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="DefaultErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<ResourceMetric>>> ListMultiRolePoolInstanceMetricsWithHttpMessagesAsync(string resourceGroupName, string name, string instance, bool? details = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (resourceGroupName != null) { if (resourceGroupName.Length > 90) { throw new ValidationException(ValidationRules.MaxLength, "resourceGroupName", 90); } if (resourceGroupName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "resourceGroupName", 1); } if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._\\(\\)]+[^\\.]$")) { throw new ValidationException(ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._\\(\\)]+[^\\.]$"); } } if (name == null) { throw new ValidationException(ValidationRules.CannotBeNull, "name"); } if (instance == null) { throw new ValidationException(ValidationRules.CannotBeNull, "instance"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("name", name); tracingParameters.Add("instance", instance); tracingParameters.Add("details", details); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListMultiRolePoolInstanceMetrics", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/hostingEnvironments/{name}/multiRolePools/default/instances/{instance}/metrics").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{name}", System.Uri.EscapeDataString(name)); _url = _url.Replace("{instance}", System.Uri.EscapeDataString(instance)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (details != null) { _queryParameters.Add(string.Format("details={0}", System.Uri.EscapeDataString(Rest.Serialization.SafeJsonConvert.SerializeObject(details, Client.SerializationSettings).Trim('"')))); } if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new DefaultErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); DefaultErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<DefaultErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<ResourceMetric>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<ResourceMetric>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get metric definitions for a multi-role pool of an App Service Environment. /// </summary> /// <remarks> /// Get metric definitions for a multi-role pool of an App Service Environment. /// </remarks> /// <param name='resourceGroupName'> /// Name of the resource group to which the resource belongs. /// </param> /// <param name='name'> /// Name of the App Service Environment. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="DefaultErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<ResourceMetricDefinition>>> ListMultiRoleMetricDefinitionsWithHttpMessagesAsync(string resourceGroupName, string name, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (resourceGroupName != null) { if (resourceGroupName.Length > 90) { throw new ValidationException(ValidationRules.MaxLength, "resourceGroupName", 90); } if (resourceGroupName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "resourceGroupName", 1); } if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._\\(\\)]+[^\\.]$")) { throw new ValidationException(ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._\\(\\)]+[^\\.]$"); } } if (name == null) { throw new ValidationException(ValidationRules.CannotBeNull, "name"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("name", name); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListMultiRoleMetricDefinitions", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/hostingEnvironments/{name}/multiRolePools/default/metricdefinitions").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{name}", System.Uri.EscapeDataString(name)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new DefaultErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); DefaultErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<DefaultErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<ResourceMetricDefinition>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<ResourceMetricDefinition>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get metrics for a multi-role pool of an App Service Environment. /// </summary> /// <remarks> /// Get metrics for a multi-role pool of an App Service Environment. /// </remarks> /// <param name='resourceGroupName'> /// Name of the resource group to which the resource belongs. /// </param> /// <param name='name'> /// Name of the App Service Environment. /// </param> /// <param name='startTime'> /// Beginning time of the metrics query. /// </param> /// <param name='endTime'> /// End time of the metrics query. /// </param> /// <param name='timeGrain'> /// Time granularity of the metrics query. /// </param> /// <param name='details'> /// Specify &lt;code&gt;true&lt;/code&gt; to include instance details. The /// default is &lt;code&gt;false&lt;/code&gt;. /// </param> /// <param name='filter'> /// Return only usages/metrics specified in the filter. Filter conforms to /// odata syntax. Example: $filter=(name.value eq 'Metric1' or name.value eq /// 'Metric2') and startTime eq '2014-01-01T00:00:00Z' and endTime eq /// '2014-12-31T23:59:59Z' and timeGrain eq duration'[Hour|Minute|Day]'. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="DefaultErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<ResourceMetric>>> ListMultiRoleMetricsWithHttpMessagesAsync(string resourceGroupName, string name, string startTime = default(string), string endTime = default(string), string timeGrain = default(string), bool? details = default(bool?), string filter = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (resourceGroupName != null) { if (resourceGroupName.Length > 90) { throw new ValidationException(ValidationRules.MaxLength, "resourceGroupName", 90); } if (resourceGroupName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "resourceGroupName", 1); } if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._\\(\\)]+[^\\.]$")) { throw new ValidationException(ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._\\(\\)]+[^\\.]$"); } } if (name == null) { throw new ValidationException(ValidationRules.CannotBeNull, "name"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("name", name); tracingParameters.Add("startTime", startTime); tracingParameters.Add("endTime", endTime); tracingParameters.Add("timeGrain", timeGrain); tracingParameters.Add("details", details); tracingParameters.Add("filter", filter); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListMultiRoleMetrics", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/hostingEnvironments/{name}/multiRolePools/default/metrics").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{name}", System.Uri.EscapeDataString(name)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (startTime != null) { _queryParameters.Add(string.Format("startTime={0}", System.Uri.EscapeDataString(startTime))); } if (endTime != null) { _queryParameters.Add(string.Format("endTime={0}", System.Uri.EscapeDataString(endTime))); } if (timeGrain != null) { _queryParameters.Add(string.Format("timeGrain={0}", System.Uri.EscapeDataString(timeGrain))); } if (details != null) { _queryParameters.Add(string.Format("details={0}", System.Uri.EscapeDataString(Rest.Serialization.SafeJsonConvert.SerializeObject(details, Client.SerializationSettings).Trim('"')))); } if (filter != null) { _queryParameters.Add(string.Format("$filter={0}", filter)); } if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new DefaultErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); DefaultErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<DefaultErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<ResourceMetric>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<ResourceMetric>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get available SKUs for scaling a multi-role pool. /// </summary> /// <remarks> /// Get available SKUs for scaling a multi-role pool. /// </remarks> /// <param name='resourceGroupName'> /// Name of the resource group to which the resource belongs. /// </param> /// <param name='name'> /// Name of the App Service Environment. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="DefaultErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<SkuInfo>>> ListMultiRolePoolSkusWithHttpMessagesAsync(string resourceGroupName, string name, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (resourceGroupName != null) { if (resourceGroupName.Length > 90) { throw new ValidationException(ValidationRules.MaxLength, "resourceGroupName", 90); } if (resourceGroupName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "resourceGroupName", 1); } if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._\\(\\)]+[^\\.]$")) { throw new ValidationException(ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._\\(\\)]+[^\\.]$"); } } if (name == null) { throw new ValidationException(ValidationRules.CannotBeNull, "name"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("name", name); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListMultiRolePoolSkus", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/hostingEnvironments/{name}/multiRolePools/default/skus").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{name}", System.Uri.EscapeDataString(name)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new DefaultErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); DefaultErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<DefaultErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<SkuInfo>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<SkuInfo>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get usage metrics for a multi-role pool of an App Service Environment. /// </summary> /// <remarks> /// Get usage metrics for a multi-role pool of an App Service Environment. /// </remarks> /// <param name='resourceGroupName'> /// Name of the resource group to which the resource belongs. /// </param> /// <param name='name'> /// Name of the App Service Environment. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="DefaultErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<Usage>>> ListMultiRoleUsagesWithHttpMessagesAsync(string resourceGroupName, string name, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (resourceGroupName != null) { if (resourceGroupName.Length > 90) { throw new ValidationException(ValidationRules.MaxLength, "resourceGroupName", 90); } if (resourceGroupName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "resourceGroupName", 1); } if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._\\(\\)]+[^\\.]$")) { throw new ValidationException(ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._\\(\\)]+[^\\.]$"); } } if (name == null) { throw new ValidationException(ValidationRules.CannotBeNull, "name"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("name", name); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListMultiRoleUsages", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/hostingEnvironments/{name}/multiRolePools/default/usages").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{name}", System.Uri.EscapeDataString(name)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new DefaultErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); DefaultErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<DefaultErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<Usage>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<Usage>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// List all currently running operations on the App Service Environment. /// </summary> /// <remarks> /// List all currently running operations on the App Service Environment. /// </remarks> /// <param name='resourceGroupName'> /// Name of the resource group to which the resource belongs. /// </param> /// <param name='name'> /// Name of the App Service Environment. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="DefaultErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IList<OperationInner>>> ListOperationsWithHttpMessagesAsync(string resourceGroupName, string name, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (resourceGroupName != null) { if (resourceGroupName.Length > 90) { throw new ValidationException(ValidationRules.MaxLength, "resourceGroupName", 90); } if (resourceGroupName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "resourceGroupName", 1); } if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._\\(\\)]+[^\\.]$")) { throw new ValidationException(ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._\\(\\)]+[^\\.]$"); } } if (name == null) { throw new ValidationException(ValidationRules.CannotBeNull, "name"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("name", name); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListOperations", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/hostingEnvironments/{name}/operations").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{name}", System.Uri.EscapeDataString(name)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new DefaultErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); DefaultErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<DefaultErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IList<OperationInner>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<IList<OperationInner>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Reboot all machines in an App Service Environment. /// </summary> /// <remarks> /// Reboot all machines in an App Service Environment. /// </remarks> /// <param name='resourceGroupName'> /// Name of the resource group to which the resource belongs. /// </param> /// <param name='name'> /// Name of the App Service Environment. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse> RebootWithHttpMessagesAsync(string resourceGroupName, string name, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (resourceGroupName != null) { if (resourceGroupName.Length > 90) { throw new ValidationException(ValidationRules.MaxLength, "resourceGroupName", 90); } if (resourceGroupName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "resourceGroupName", 1); } if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._\\(\\)]+[^\\.]$")) { throw new ValidationException(ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._\\(\\)]+[^\\.]$"); } } if (name == null) { throw new ValidationException(ValidationRules.CannotBeNull, "name"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("name", name); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Reboot", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/hostingEnvironments/{name}/reboot").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{name}", System.Uri.EscapeDataString(name)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("POST"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 202 && (int)_statusCode != 400 && (int)_statusCode != 404 && (int)_statusCode != 409) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Resume an App Service Environment. /// </summary> /// <remarks> /// Resume an App Service Environment. /// </remarks> /// <param name='resourceGroupName'> /// Name of the resource group to which the resource belongs. /// </param> /// <param name='name'> /// Name of the App Service Environment. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse<IPage<SiteInner>>> ResumeWithHttpMessagesAsync(string resourceGroupName, string name, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Send request AzureOperationResponse<IPage<SiteInner>> _response = await BeginResumeWithHttpMessagesAsync(resourceGroupName, name, customHeaders, cancellationToken).ConfigureAwait(false); return await Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false); } /// <summary> /// Get all App Service plans in an App Service Environment. /// </summary> /// <remarks> /// Get all App Service plans in an App Service Environment. /// </remarks> /// <param name='resourceGroupName'> /// Name of the resource group to which the resource belongs. /// </param> /// <param name='name'> /// Name of the App Service Environment. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="DefaultErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<AppServicePlanInner>>> ListAppServicePlansWithHttpMessagesAsync(string resourceGroupName, string name, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (resourceGroupName != null) { if (resourceGroupName.Length > 90) { throw new ValidationException(ValidationRules.MaxLength, "resourceGroupName", 90); } if (resourceGroupName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "resourceGroupName", 1); } if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._\\(\\)]+[^\\.]$")) { throw new ValidationException(ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._\\(\\)]+[^\\.]$"); } } if (name == null) { throw new ValidationException(ValidationRules.CannotBeNull, "name"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("name", name); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListAppServicePlans", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/hostingEnvironments/{name}/serverfarms").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{name}", System.Uri.EscapeDataString(name)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new DefaultErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); DefaultErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<DefaultErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<AppServicePlanInner>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<AppServicePlanInner>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get all apps in an App Service Environment. /// </summary> /// <remarks> /// Get all apps in an App Service Environment. /// </remarks> /// <param name='resourceGroupName'> /// Name of the resource group to which the resource belongs. /// </param> /// <param name='name'> /// Name of the App Service Environment. /// </param> /// <param name='propertiesToInclude'> /// Comma separated list of app properties to include. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="DefaultErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<SiteInner>>> ListWebAppsWithHttpMessagesAsync(string resourceGroupName, string name, string propertiesToInclude = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (resourceGroupName != null) { if (resourceGroupName.Length > 90) { throw new ValidationException(ValidationRules.MaxLength, "resourceGroupName", 90); } if (resourceGroupName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "resourceGroupName", 1); } if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._\\(\\)]+[^\\.]$")) { throw new ValidationException(ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._\\(\\)]+[^\\.]$"); } } if (name == null) { throw new ValidationException(ValidationRules.CannotBeNull, "name"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("name", name); tracingParameters.Add("propertiesToInclude", propertiesToInclude); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListWebApps", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/hostingEnvironments/{name}/sites").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{name}", System.Uri.EscapeDataString(name)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (propertiesToInclude != null) { _queryParameters.Add(string.Format("propertiesToInclude={0}", System.Uri.EscapeDataString(propertiesToInclude))); } if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new DefaultErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); DefaultErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<DefaultErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<SiteInner>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<SiteInner>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Suspend an App Service Environment. /// </summary> /// <remarks> /// Suspend an App Service Environment. /// </remarks> /// <param name='resourceGroupName'> /// Name of the resource group to which the resource belongs. /// </param> /// <param name='name'> /// Name of the App Service Environment. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse<IPage<SiteInner>>> SuspendWithHttpMessagesAsync(string resourceGroupName, string name, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Send request AzureOperationResponse<IPage<SiteInner>> _response = await BeginSuspendWithHttpMessagesAsync(resourceGroupName, name, customHeaders, cancellationToken).ConfigureAwait(false); return await Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false); } /// <summary> /// Resume an App Service Environment. /// </summary> /// <remarks> /// Resume an App Service Environment. /// </remarks> /// <param name='resourceGroupName'> /// Name of the resource group to which the resource belongs. /// </param> /// <param name='name'> /// Name of the App Service Environment. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse> SyncVirtualNetworkInfoWithHttpMessagesAsync(string resourceGroupName, string name, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (resourceGroupName != null) { if (resourceGroupName.Length > 90) { throw new ValidationException(ValidationRules.MaxLength, "resourceGroupName", 90); } if (resourceGroupName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "resourceGroupName", 1); } if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._\\(\\)]+[^\\.]$")) { throw new ValidationException(ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._\\(\\)]+[^\\.]$"); } } if (name == null) { throw new ValidationException(ValidationRules.CannotBeNull, "name"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("name", name); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "SyncVirtualNetworkInfo", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/hostingEnvironments/{name}/syncVirtualNetwork").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{name}", System.Uri.EscapeDataString(name)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("POST"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200 && (int)_statusCode != 202) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get global usage metrics of an App Service Environment. /// </summary> /// <remarks> /// Get global usage metrics of an App Service Environment. /// </remarks> /// <param name='resourceGroupName'> /// Name of the resource group to which the resource belongs. /// </param> /// <param name='name'> /// Name of the App Service Environment. /// </param> /// <param name='filter'> /// Return only usages/metrics specified in the filter. Filter conforms to /// odata syntax. Example: $filter=(name.value eq 'Metric1' or name.value eq /// 'Metric2') and startTime eq '2014-01-01T00:00:00Z' and endTime eq /// '2014-12-31T23:59:59Z' and timeGrain eq duration'[Hour|Minute|Day]'. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="DefaultErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<CsmUsageQuota>>> ListUsagesWithHttpMessagesAsync(string resourceGroupName, string name, string filter = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (resourceGroupName != null) { if (resourceGroupName.Length > 90) { throw new ValidationException(ValidationRules.MaxLength, "resourceGroupName", 90); } if (resourceGroupName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "resourceGroupName", 1); } if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._\\(\\)]+[^\\.]$")) { throw new ValidationException(ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._\\(\\)]+[^\\.]$"); } } if (name == null) { throw new ValidationException(ValidationRules.CannotBeNull, "name"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("name", name); tracingParameters.Add("filter", filter); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListUsages", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/hostingEnvironments/{name}/usages").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{name}", System.Uri.EscapeDataString(name)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (filter != null) { _queryParameters.Add(string.Format("$filter={0}", filter)); } if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new DefaultErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); DefaultErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<DefaultErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<CsmUsageQuota>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<CsmUsageQuota>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get all worker pools of an App Service Environment. /// </summary> /// <remarks> /// Get all worker pools of an App Service Environment. /// </remarks> /// <param name='resourceGroupName'> /// Name of the resource group to which the resource belongs. /// </param> /// <param name='name'> /// Name of the App Service Environment. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="DefaultErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<WorkerPoolResourceInner>>> ListWorkerPoolsWithHttpMessagesAsync(string resourceGroupName, string name, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (resourceGroupName != null) { if (resourceGroupName.Length > 90) { throw new ValidationException(ValidationRules.MaxLength, "resourceGroupName", 90); } if (resourceGroupName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "resourceGroupName", 1); } if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._\\(\\)]+[^\\.]$")) { throw new ValidationException(ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._\\(\\)]+[^\\.]$"); } } if (name == null) { throw new ValidationException(ValidationRules.CannotBeNull, "name"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("name", name); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListWorkerPools", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/hostingEnvironments/{name}/workerPools").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{name}", System.Uri.EscapeDataString(name)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new DefaultErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); DefaultErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<DefaultErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<WorkerPoolResourceInner>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<WorkerPoolResourceInner>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get properties of a worker pool. /// </summary> /// <remarks> /// Get properties of a worker pool. /// </remarks> /// <param name='resourceGroupName'> /// Name of the resource group to which the resource belongs. /// </param> /// <param name='name'> /// Name of the App Service Environment. /// </param> /// <param name='workerPoolName'> /// Name of the worker pool. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="DefaultErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<WorkerPoolResourceInner>> GetWorkerPoolWithHttpMessagesAsync(string resourceGroupName, string name, string workerPoolName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (resourceGroupName != null) { if (resourceGroupName.Length > 90) { throw new ValidationException(ValidationRules.MaxLength, "resourceGroupName", 90); } if (resourceGroupName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "resourceGroupName", 1); } if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._\\(\\)]+[^\\.]$")) { throw new ValidationException(ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._\\(\\)]+[^\\.]$"); } } if (name == null) { throw new ValidationException(ValidationRules.CannotBeNull, "name"); } if (workerPoolName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "workerPoolName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("name", name); tracingParameters.Add("workerPoolName", workerPoolName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetWorkerPool", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/hostingEnvironments/{name}/workerPools/{workerPoolName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{name}", System.Uri.EscapeDataString(name)); _url = _url.Replace("{workerPoolName}", System.Uri.EscapeDataString(workerPoolName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new DefaultErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); DefaultErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<DefaultErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<WorkerPoolResourceInner>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<WorkerPoolResourceInner>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Create or update a worker pool. /// </summary> /// <remarks> /// Create or update a worker pool. /// </remarks> /// <param name='resourceGroupName'> /// Name of the resource group to which the resource belongs. /// </param> /// <param name='name'> /// Name of the App Service Environment. /// </param> /// <param name='workerPoolName'> /// Name of the worker pool. /// </param> /// <param name='workerPoolEnvelope'> /// Properties of the worker pool. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse<WorkerPoolResourceInner>> CreateOrUpdateWorkerPoolWithHttpMessagesAsync(string resourceGroupName, string name, string workerPoolName, WorkerPoolResourceInner workerPoolEnvelope, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Send Request AzureOperationResponse<WorkerPoolResourceInner> _response = await BeginCreateOrUpdateWorkerPoolWithHttpMessagesAsync(resourceGroupName, name, workerPoolName, workerPoolEnvelope, customHeaders, cancellationToken).ConfigureAwait(false); return await Client.GetPutOrPatchOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false); } /// <summary> /// Create or update a worker pool. /// </summary> /// <remarks> /// Create or update a worker pool. /// </remarks> /// <param name='resourceGroupName'> /// Name of the resource group to which the resource belongs. /// </param> /// <param name='name'> /// Name of the App Service Environment. /// </param> /// <param name='workerPoolName'> /// Name of the worker pool. /// </param> /// <param name='workerPoolEnvelope'> /// Properties of the worker pool. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<WorkerPoolResourceInner>> UpdateWorkerPoolWithHttpMessagesAsync(string resourceGroupName, string name, string workerPoolName, WorkerPoolResourceInner workerPoolEnvelope, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (resourceGroupName != null) { if (resourceGroupName.Length > 90) { throw new ValidationException(ValidationRules.MaxLength, "resourceGroupName", 90); } if (resourceGroupName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "resourceGroupName", 1); } if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._\\(\\)]+[^\\.]$")) { throw new ValidationException(ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._\\(\\)]+[^\\.]$"); } } if (name == null) { throw new ValidationException(ValidationRules.CannotBeNull, "name"); } if (workerPoolName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "workerPoolName"); } if (workerPoolEnvelope == null) { throw new ValidationException(ValidationRules.CannotBeNull, "workerPoolEnvelope"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("name", name); tracingParameters.Add("workerPoolName", workerPoolName); tracingParameters.Add("workerPoolEnvelope", workerPoolEnvelope); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "UpdateWorkerPool", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/hostingEnvironments/{name}/workerPools/{workerPoolName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{name}", System.Uri.EscapeDataString(name)); _url = _url.Replace("{workerPoolName}", System.Uri.EscapeDataString(workerPoolName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PATCH"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(workerPoolEnvelope != null) { _requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(workerPoolEnvelope, Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200 && (int)_statusCode != 202 && (int)_statusCode != 400 && (int)_statusCode != 404 && (int)_statusCode != 409) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<WorkerPoolResourceInner>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<WorkerPoolResourceInner>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } // Deserialize Response if ((int)_statusCode == 202) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<WorkerPoolResourceInner>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get metric definitions for a specific instance of a worker pool of an App /// Service Environment. /// </summary> /// <remarks> /// Get metric definitions for a specific instance of a worker pool of an App /// Service Environment. /// </remarks> /// <param name='resourceGroupName'> /// Name of the resource group to which the resource belongs. /// </param> /// <param name='name'> /// Name of the App Service Environment. /// </param> /// <param name='workerPoolName'> /// Name of the worker pool. /// </param> /// <param name='instance'> /// Name of the instance in the worker pool. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="DefaultErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<ResourceMetricDefinition>>> ListWorkerPoolInstanceMetricDefinitionsWithHttpMessagesAsync(string resourceGroupName, string name, string workerPoolName, string instance, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (resourceGroupName != null) { if (resourceGroupName.Length > 90) { throw new ValidationException(ValidationRules.MaxLength, "resourceGroupName", 90); } if (resourceGroupName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "resourceGroupName", 1); } if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._\\(\\)]+[^\\.]$")) { throw new ValidationException(ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._\\(\\)]+[^\\.]$"); } } if (name == null) { throw new ValidationException(ValidationRules.CannotBeNull, "name"); } if (workerPoolName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "workerPoolName"); } if (instance == null) { throw new ValidationException(ValidationRules.CannotBeNull, "instance"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("name", name); tracingParameters.Add("workerPoolName", workerPoolName); tracingParameters.Add("instance", instance); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListWorkerPoolInstanceMetricDefinitions", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/hostingEnvironments/{name}/workerPools/{workerPoolName}/instances/{instance}/metricdefinitions").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{name}", System.Uri.EscapeDataString(name)); _url = _url.Replace("{workerPoolName}", System.Uri.EscapeDataString(workerPoolName)); _url = _url.Replace("{instance}", System.Uri.EscapeDataString(instance)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new DefaultErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); DefaultErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<DefaultErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<ResourceMetricDefinition>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<ResourceMetricDefinition>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get metrics for a specific instance of a worker pool of an App Service /// Environment. /// </summary> /// <remarks> /// Get metrics for a specific instance of a worker pool of an App Service /// Environment. /// </remarks> /// <param name='resourceGroupName'> /// Name of the resource group to which the resource belongs. /// </param> /// <param name='name'> /// Name of the App Service Environment. /// </param> /// <param name='workerPoolName'> /// Name of the worker pool. /// </param> /// <param name='instance'> /// Name of the instance in the worker pool. /// </param> /// <param name='details'> /// Specify &lt;code&gt;true&lt;/code&gt; to include instance details. The /// default is &lt;code&gt;false&lt;/code&gt;. /// </param> /// <param name='filter'> /// Return only usages/metrics specified in the filter. Filter conforms to /// odata syntax. Example: $filter=(name.value eq 'Metric1' or name.value eq /// 'Metric2') and startTime eq '2014-01-01T00:00:00Z' and endTime eq /// '2014-12-31T23:59:59Z' and timeGrain eq duration'[Hour|Minute|Day]'. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="DefaultErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<ResourceMetric>>> ListWorkerPoolInstanceMetricsWithHttpMessagesAsync(string resourceGroupName, string name, string workerPoolName, string instance, bool? details = default(bool?), string filter = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (resourceGroupName != null) { if (resourceGroupName.Length > 90) { throw new ValidationException(ValidationRules.MaxLength, "resourceGroupName", 90); } if (resourceGroupName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "resourceGroupName", 1); } if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._\\(\\)]+[^\\.]$")) { throw new ValidationException(ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._\\(\\)]+[^\\.]$"); } } if (name == null) { throw new ValidationException(ValidationRules.CannotBeNull, "name"); } if (workerPoolName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "workerPoolName"); } if (instance == null) { throw new ValidationException(ValidationRules.CannotBeNull, "instance"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("name", name); tracingParameters.Add("workerPoolName", workerPoolName); tracingParameters.Add("instance", instance); tracingParameters.Add("details", details); tracingParameters.Add("filter", filter); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListWorkerPoolInstanceMetrics", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/hostingEnvironments/{name}/workerPools/{workerPoolName}/instances/{instance}/metrics").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{name}", System.Uri.EscapeDataString(name)); _url = _url.Replace("{workerPoolName}", System.Uri.EscapeDataString(workerPoolName)); _url = _url.Replace("{instance}", System.Uri.EscapeDataString(instance)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (details != null) { _queryParameters.Add(string.Format("details={0}", System.Uri.EscapeDataString(Rest.Serialization.SafeJsonConvert.SerializeObject(details, Client.SerializationSettings).Trim('"')))); } if (filter != null) { _queryParameters.Add(string.Format("$filter={0}", filter)); } if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new DefaultErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); DefaultErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<DefaultErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<ResourceMetric>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<ResourceMetric>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get metric definitions for a worker pool of an App Service Environment. /// </summary> /// <remarks> /// Get metric definitions for a worker pool of an App Service Environment. /// </remarks> /// <param name='resourceGroupName'> /// Name of the resource group to which the resource belongs. /// </param> /// <param name='name'> /// Name of the App Service Environment. /// </param> /// <param name='workerPoolName'> /// Name of the worker pool. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="DefaultErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<ResourceMetricDefinition>>> ListWebWorkerMetricDefinitionsWithHttpMessagesAsync(string resourceGroupName, string name, string workerPoolName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (resourceGroupName != null) { if (resourceGroupName.Length > 90) { throw new ValidationException(ValidationRules.MaxLength, "resourceGroupName", 90); } if (resourceGroupName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "resourceGroupName", 1); } if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._\\(\\)]+[^\\.]$")) { throw new ValidationException(ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._\\(\\)]+[^\\.]$"); } } if (name == null) { throw new ValidationException(ValidationRules.CannotBeNull, "name"); } if (workerPoolName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "workerPoolName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("name", name); tracingParameters.Add("workerPoolName", workerPoolName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListWebWorkerMetricDefinitions", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/hostingEnvironments/{name}/workerPools/{workerPoolName}/metricdefinitions").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{name}", System.Uri.EscapeDataString(name)); _url = _url.Replace("{workerPoolName}", System.Uri.EscapeDataString(workerPoolName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new DefaultErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); DefaultErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<DefaultErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<ResourceMetricDefinition>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<ResourceMetricDefinition>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get metrics for a worker pool of a AppServiceEnvironment (App Service /// Environment). /// </summary> /// <remarks> /// Get metrics for a worker pool of a AppServiceEnvironment (App Service /// Environment). /// </remarks> /// <param name='resourceGroupName'> /// Name of the resource group to which the resource belongs. /// </param> /// <param name='name'> /// Name of the App Service Environment. /// </param> /// <param name='workerPoolName'> /// Name of worker pool /// </param> /// <param name='details'> /// Specify &lt;code&gt;true&lt;/code&gt; to include instance details. The /// default is &lt;code&gt;false&lt;/code&gt;. /// </param> /// <param name='filter'> /// Return only usages/metrics specified in the filter. Filter conforms to /// odata syntax. Example: $filter=(name.value eq 'Metric1' or name.value eq /// 'Metric2') and startTime eq '2014-01-01T00:00:00Z' and endTime eq /// '2014-12-31T23:59:59Z' and timeGrain eq duration'[Hour|Minute|Day]'. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="DefaultErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<ResourceMetric>>> ListWebWorkerMetricsWithHttpMessagesAsync(string resourceGroupName, string name, string workerPoolName, bool? details = default(bool?), string filter = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (resourceGroupName != null) { if (resourceGroupName.Length > 90) { throw new ValidationException(ValidationRules.MaxLength, "resourceGroupName", 90); } if (resourceGroupName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "resourceGroupName", 1); } if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._\\(\\)]+[^\\.]$")) { throw new ValidationException(ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._\\(\\)]+[^\\.]$"); } } if (name == null) { throw new ValidationException(ValidationRules.CannotBeNull, "name"); } if (workerPoolName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "workerPoolName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("name", name); tracingParameters.Add("workerPoolName", workerPoolName); tracingParameters.Add("details", details); tracingParameters.Add("filter", filter); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListWebWorkerMetrics", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/hostingEnvironments/{name}/workerPools/{workerPoolName}/metrics").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{name}", System.Uri.EscapeDataString(name)); _url = _url.Replace("{workerPoolName}", System.Uri.EscapeDataString(workerPoolName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (details != null) { _queryParameters.Add(string.Format("details={0}", System.Uri.EscapeDataString(Rest.Serialization.SafeJsonConvert.SerializeObject(details, Client.SerializationSettings).Trim('"')))); } if (filter != null) { _queryParameters.Add(string.Format("$filter={0}", filter)); } if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new DefaultErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); DefaultErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<DefaultErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<ResourceMetric>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<ResourceMetric>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get available SKUs for scaling a worker pool. /// </summary> /// <remarks> /// Get available SKUs for scaling a worker pool. /// </remarks> /// <param name='resourceGroupName'> /// Name of the resource group to which the resource belongs. /// </param> /// <param name='name'> /// Name of the App Service Environment. /// </param> /// <param name='workerPoolName'> /// Name of the worker pool. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="DefaultErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<SkuInfo>>> ListWorkerPoolSkusWithHttpMessagesAsync(string resourceGroupName, string name, string workerPoolName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (resourceGroupName != null) { if (resourceGroupName.Length > 90) { throw new ValidationException(ValidationRules.MaxLength, "resourceGroupName", 90); } if (resourceGroupName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "resourceGroupName", 1); } if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._\\(\\)]+[^\\.]$")) { throw new ValidationException(ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._\\(\\)]+[^\\.]$"); } } if (name == null) { throw new ValidationException(ValidationRules.CannotBeNull, "name"); } if (workerPoolName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "workerPoolName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("name", name); tracingParameters.Add("workerPoolName", workerPoolName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListWorkerPoolSkus", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/hostingEnvironments/{name}/workerPools/{workerPoolName}/skus").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{name}", System.Uri.EscapeDataString(name)); _url = _url.Replace("{workerPoolName}", System.Uri.EscapeDataString(workerPoolName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new DefaultErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); DefaultErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<DefaultErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<SkuInfo>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<SkuInfo>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get usage metrics for a worker pool of an App Service Environment. /// </summary> /// <remarks> /// Get usage metrics for a worker pool of an App Service Environment. /// </remarks> /// <param name='resourceGroupName'> /// Name of the resource group to which the resource belongs. /// </param> /// <param name='name'> /// Name of the App Service Environment. /// </param> /// <param name='workerPoolName'> /// Name of the worker pool. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="DefaultErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<Usage>>> ListWebWorkerUsagesWithHttpMessagesAsync(string resourceGroupName, string name, string workerPoolName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (resourceGroupName != null) { if (resourceGroupName.Length > 90) { throw new ValidationException(ValidationRules.MaxLength, "resourceGroupName", 90); } if (resourceGroupName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "resourceGroupName", 1); } if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._\\(\\)]+[^\\.]$")) { throw new ValidationException(ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._\\(\\)]+[^\\.]$"); } } if (name == null) { throw new ValidationException(ValidationRules.CannotBeNull, "name"); } if (workerPoolName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "workerPoolName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("name", name); tracingParameters.Add("workerPoolName", workerPoolName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListWebWorkerUsages", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/hostingEnvironments/{name}/workerPools/{workerPoolName}/usages").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{name}", System.Uri.EscapeDataString(name)); _url = _url.Replace("{workerPoolName}", System.Uri.EscapeDataString(workerPoolName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new DefaultErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); DefaultErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<DefaultErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<Usage>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<Usage>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Create or update an App Service Environment. /// </summary> /// <remarks> /// Create or update an App Service Environment. /// </remarks> /// <param name='resourceGroupName'> /// Name of the resource group to which the resource belongs. /// </param> /// <param name='name'> /// Name of the App Service Environment. /// </param> /// <param name='hostingEnvironmentEnvelope'> /// Configuration details of the App Service Environment. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<AppServiceEnvironmentResourceInner>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string name, AppServiceEnvironmentResourceInner hostingEnvironmentEnvelope, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (resourceGroupName != null) { if (resourceGroupName.Length > 90) { throw new ValidationException(ValidationRules.MaxLength, "resourceGroupName", 90); } if (resourceGroupName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "resourceGroupName", 1); } if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._\\(\\)]+[^\\.]$")) { throw new ValidationException(ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._\\(\\)]+[^\\.]$"); } } if (name == null) { throw new ValidationException(ValidationRules.CannotBeNull, "name"); } if (hostingEnvironmentEnvelope == null) { throw new ValidationException(ValidationRules.CannotBeNull, "hostingEnvironmentEnvelope"); } if (hostingEnvironmentEnvelope != null) { hostingEnvironmentEnvelope.Validate(); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("name", name); tracingParameters.Add("hostingEnvironmentEnvelope", hostingEnvironmentEnvelope); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "BeginCreateOrUpdate", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/hostingEnvironments/{name}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{name}", System.Uri.EscapeDataString(name)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(hostingEnvironmentEnvelope != null) { _requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(hostingEnvironmentEnvelope, Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200 && (int)_statusCode != 202 && (int)_statusCode != 400 && (int)_statusCode != 404 && (int)_statusCode != 409) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<AppServiceEnvironmentResourceInner>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<AppServiceEnvironmentResourceInner>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } // Deserialize Response if ((int)_statusCode == 202) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<AppServiceEnvironmentResourceInner>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Delete an App Service Environment. /// </summary> /// <remarks> /// Delete an App Service Environment. /// </remarks> /// <param name='resourceGroupName'> /// Name of the resource group to which the resource belongs. /// </param> /// <param name='name'> /// Name of the App Service Environment. /// </param> /// <param name='forceDelete'> /// Specify &lt;code&gt;true&lt;/code&gt; to force the deletion even if the App /// Service Environment contains resources. The default is /// &lt;code&gt;false&lt;/code&gt;. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string name, bool? forceDelete = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (resourceGroupName != null) { if (resourceGroupName.Length > 90) { throw new ValidationException(ValidationRules.MaxLength, "resourceGroupName", 90); } if (resourceGroupName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "resourceGroupName", 1); } if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._\\(\\)]+[^\\.]$")) { throw new ValidationException(ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._\\(\\)]+[^\\.]$"); } } if (name == null) { throw new ValidationException(ValidationRules.CannotBeNull, "name"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("name", name); tracingParameters.Add("forceDelete", forceDelete); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "BeginDelete", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/hostingEnvironments/{name}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{name}", System.Uri.EscapeDataString(name)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (forceDelete != null) { _queryParameters.Add(string.Format("forceDelete={0}", System.Uri.EscapeDataString(Rest.Serialization.SafeJsonConvert.SerializeObject(forceDelete, Client.SerializationSettings).Trim('"')))); } if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("DELETE"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 202 && (int)_statusCode != 204 && (int)_statusCode != 400 && (int)_statusCode != 404 && (int)_statusCode != 409) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Move an App Service Environment to a different VNET. /// </summary> /// <remarks> /// Move an App Service Environment to a different VNET. /// </remarks> /// <param name='resourceGroupName'> /// Name of the resource group to which the resource belongs. /// </param> /// <param name='name'> /// Name of the App Service Environment. /// </param> /// <param name='vnetInfo'> /// Details for the new virtual network. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="DefaultErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<SiteInner>>> BeginChangeVnetWithHttpMessagesAsync(string resourceGroupName, string name, VirtualNetworkProfile vnetInfo, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (resourceGroupName != null) { if (resourceGroupName.Length > 90) { throw new ValidationException(ValidationRules.MaxLength, "resourceGroupName", 90); } if (resourceGroupName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "resourceGroupName", 1); } if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._\\(\\)]+[^\\.]$")) { throw new ValidationException(ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._\\(\\)]+[^\\.]$"); } } if (name == null) { throw new ValidationException(ValidationRules.CannotBeNull, "name"); } if (vnetInfo == null) { throw new ValidationException(ValidationRules.CannotBeNull, "vnetInfo"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("name", name); tracingParameters.Add("vnetInfo", vnetInfo); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "BeginChangeVnet", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/hostingEnvironments/{name}/changeVirtualNetwork").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{name}", System.Uri.EscapeDataString(name)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("POST"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(vnetInfo != null) { _requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(vnetInfo, Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200 && (int)_statusCode != 202) { var ex = new DefaultErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); DefaultErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<DefaultErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<SiteInner>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<SiteInner>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } // Deserialize Response if ((int)_statusCode == 202) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<SiteInner>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Create or update a multi-role pool. /// </summary> /// <remarks> /// Create or update a multi-role pool. /// </remarks> /// <param name='resourceGroupName'> /// Name of the resource group to which the resource belongs. /// </param> /// <param name='name'> /// Name of the App Service Environment. /// </param> /// <param name='multiRolePoolEnvelope'> /// Properties of the multi-role pool. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<WorkerPoolResourceInner>> BeginCreateOrUpdateMultiRolePoolWithHttpMessagesAsync(string resourceGroupName, string name, WorkerPoolResourceInner multiRolePoolEnvelope, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (resourceGroupName != null) { if (resourceGroupName.Length > 90) { throw new ValidationException(ValidationRules.MaxLength, "resourceGroupName", 90); } if (resourceGroupName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "resourceGroupName", 1); } if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._\\(\\)]+[^\\.]$")) { throw new ValidationException(ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._\\(\\)]+[^\\.]$"); } } if (name == null) { throw new ValidationException(ValidationRules.CannotBeNull, "name"); } if (multiRolePoolEnvelope == null) { throw new ValidationException(ValidationRules.CannotBeNull, "multiRolePoolEnvelope"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("name", name); tracingParameters.Add("multiRolePoolEnvelope", multiRolePoolEnvelope); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "BeginCreateOrUpdateMultiRolePool", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/hostingEnvironments/{name}/multiRolePools/default").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{name}", System.Uri.EscapeDataString(name)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(multiRolePoolEnvelope != null) { _requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(multiRolePoolEnvelope, Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200 && (int)_statusCode != 202 && (int)_statusCode != 400 && (int)_statusCode != 404 && (int)_statusCode != 409) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<WorkerPoolResourceInner>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<WorkerPoolResourceInner>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } // Deserialize Response if ((int)_statusCode == 202) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<WorkerPoolResourceInner>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Resume an App Service Environment. /// </summary> /// <remarks> /// Resume an App Service Environment. /// </remarks> /// <param name='resourceGroupName'> /// Name of the resource group to which the resource belongs. /// </param> /// <param name='name'> /// Name of the App Service Environment. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="DefaultErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<SiteInner>>> BeginResumeWithHttpMessagesAsync(string resourceGroupName, string name, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (resourceGroupName != null) { if (resourceGroupName.Length > 90) { throw new ValidationException(ValidationRules.MaxLength, "resourceGroupName", 90); } if (resourceGroupName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "resourceGroupName", 1); } if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._\\(\\)]+[^\\.]$")) { throw new ValidationException(ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._\\(\\)]+[^\\.]$"); } } if (name == null) { throw new ValidationException(ValidationRules.CannotBeNull, "name"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("name", name); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "BeginResume", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/hostingEnvironments/{name}/resume").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{name}", System.Uri.EscapeDataString(name)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("POST"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200 && (int)_statusCode != 202) { var ex = new DefaultErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); DefaultErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<DefaultErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<SiteInner>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<SiteInner>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } // Deserialize Response if ((int)_statusCode == 202) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<SiteInner>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Suspend an App Service Environment. /// </summary> /// <remarks> /// Suspend an App Service Environment. /// </remarks> /// <param name='resourceGroupName'> /// Name of the resource group to which the resource belongs. /// </param> /// <param name='name'> /// Name of the App Service Environment. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="DefaultErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<SiteInner>>> BeginSuspendWithHttpMessagesAsync(string resourceGroupName, string name, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (resourceGroupName != null) { if (resourceGroupName.Length > 90) { throw new ValidationException(ValidationRules.MaxLength, "resourceGroupName", 90); } if (resourceGroupName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "resourceGroupName", 1); } if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._\\(\\)]+[^\\.]$")) { throw new ValidationException(ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._\\(\\)]+[^\\.]$"); } } if (name == null) { throw new ValidationException(ValidationRules.CannotBeNull, "name"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("name", name); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "BeginSuspend", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/hostingEnvironments/{name}/suspend").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{name}", System.Uri.EscapeDataString(name)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("POST"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200 && (int)_statusCode != 202) { var ex = new DefaultErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); DefaultErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<DefaultErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<SiteInner>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<SiteInner>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } // Deserialize Response if ((int)_statusCode == 202) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<SiteInner>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Create or update a worker pool. /// </summary> /// <remarks> /// Create or update a worker pool. /// </remarks> /// <param name='resourceGroupName'> /// Name of the resource group to which the resource belongs. /// </param> /// <param name='name'> /// Name of the App Service Environment. /// </param> /// <param name='workerPoolName'> /// Name of the worker pool. /// </param> /// <param name='workerPoolEnvelope'> /// Properties of the worker pool. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<WorkerPoolResourceInner>> BeginCreateOrUpdateWorkerPoolWithHttpMessagesAsync(string resourceGroupName, string name, string workerPoolName, WorkerPoolResourceInner workerPoolEnvelope, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (resourceGroupName != null) { if (resourceGroupName.Length > 90) { throw new ValidationException(ValidationRules.MaxLength, "resourceGroupName", 90); } if (resourceGroupName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "resourceGroupName", 1); } if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._\\(\\)]+[^\\.]$")) { throw new ValidationException(ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._\\(\\)]+[^\\.]$"); } } if (name == null) { throw new ValidationException(ValidationRules.CannotBeNull, "name"); } if (workerPoolName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "workerPoolName"); } if (workerPoolEnvelope == null) { throw new ValidationException(ValidationRules.CannotBeNull, "workerPoolEnvelope"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("name", name); tracingParameters.Add("workerPoolName", workerPoolName); tracingParameters.Add("workerPoolEnvelope", workerPoolEnvelope); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "BeginCreateOrUpdateWorkerPool", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/hostingEnvironments/{name}/workerPools/{workerPoolName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{name}", System.Uri.EscapeDataString(name)); _url = _url.Replace("{workerPoolName}", System.Uri.EscapeDataString(workerPoolName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(workerPoolEnvelope != null) { _requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(workerPoolEnvelope, Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200 && (int)_statusCode != 202 && (int)_statusCode != 400 && (int)_statusCode != 404 && (int)_statusCode != 409) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<WorkerPoolResourceInner>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<WorkerPoolResourceInner>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } // Deserialize Response if ((int)_statusCode == 202) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<WorkerPoolResourceInner>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get all App Service Environments for a subscription. /// </summary> /// <remarks> /// Get all App Service Environments for a subscription. /// </remarks> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="DefaultErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<AppServiceEnvironmentResourceInner>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextPageLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new DefaultErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); DefaultErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<DefaultErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<AppServiceEnvironmentResourceInner>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<AppServiceEnvironmentResourceInner>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get all App Service Environments in a resource group. /// </summary> /// <remarks> /// Get all App Service Environments in a resource group. /// </remarks> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="DefaultErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<AppServiceEnvironmentResourceInner>>> ListByResourceGroupNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextPageLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListByResourceGroupNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new DefaultErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); DefaultErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<DefaultErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<AppServiceEnvironmentResourceInner>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<AppServiceEnvironmentResourceInner>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get the used, available, and total worker capacity an App Service /// Environment. /// </summary> /// <remarks> /// Get the used, available, and total worker capacity an App Service /// Environment. /// </remarks> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="DefaultErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<StampCapacity>>> ListCapacitiesNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextPageLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListCapacitiesNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new DefaultErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); DefaultErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<DefaultErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<StampCapacity>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<StampCapacity>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Move an App Service Environment to a different VNET. /// </summary> /// <remarks> /// Move an App Service Environment to a different VNET. /// </remarks> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse<IPage<SiteInner>>> ChangeVnetNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Send request AzureOperationResponse<IPage<SiteInner>> _response = await BeginChangeVnetNextWithHttpMessagesAsync(nextPageLink, customHeaders, cancellationToken).ConfigureAwait(false); return await Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false); } /// <summary> /// Get global metrics of an App Service Environment. /// </summary> /// <remarks> /// Get global metrics of an App Service Environment. /// </remarks> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="DefaultErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<ResourceMetric>>> ListMetricsNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextPageLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListMetricsNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new DefaultErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); DefaultErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<DefaultErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<ResourceMetric>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<ResourceMetric>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get all multi-role pools. /// </summary> /// <remarks> /// Get all multi-role pools. /// </remarks> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="DefaultErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<WorkerPoolResourceInner>>> ListMultiRolePoolsNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextPageLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListMultiRolePoolsNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new DefaultErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); DefaultErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<DefaultErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<WorkerPoolResourceInner>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<WorkerPoolResourceInner>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get metric definitions for a specific instance of a multi-role pool of an /// App Service Environment. /// </summary> /// <remarks> /// Get metric definitions for a specific instance of a multi-role pool of an /// App Service Environment. /// </remarks> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="DefaultErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<ResourceMetricDefinition>>> ListMultiRolePoolInstanceMetricDefinitionsNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextPageLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListMultiRolePoolInstanceMetricDefinitionsNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new DefaultErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); DefaultErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<DefaultErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<ResourceMetricDefinition>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<ResourceMetricDefinition>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get metrics for a specific instance of a multi-role pool of an App Service /// Environment. /// </summary> /// <remarks> /// Get metrics for a specific instance of a multi-role pool of an App Service /// Environment. /// </remarks> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="DefaultErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<ResourceMetric>>> ListMultiRolePoolInstanceMetricsNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextPageLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListMultiRolePoolInstanceMetricsNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new DefaultErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); DefaultErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<DefaultErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<ResourceMetric>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<ResourceMetric>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get metric definitions for a multi-role pool of an App Service Environment. /// </summary> /// <remarks> /// Get metric definitions for a multi-role pool of an App Service Environment. /// </remarks> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="DefaultErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<ResourceMetricDefinition>>> ListMultiRoleMetricDefinitionsNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextPageLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListMultiRoleMetricDefinitionsNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new DefaultErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); DefaultErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<DefaultErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<ResourceMetricDefinition>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<ResourceMetricDefinition>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get metrics for a multi-role pool of an App Service Environment. /// </summary> /// <remarks> /// Get metrics for a multi-role pool of an App Service Environment. /// </remarks> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="DefaultErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<ResourceMetric>>> ListMultiRoleMetricsNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextPageLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListMultiRoleMetricsNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new DefaultErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); DefaultErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<DefaultErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<ResourceMetric>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<ResourceMetric>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get available SKUs for scaling a multi-role pool. /// </summary> /// <remarks> /// Get available SKUs for scaling a multi-role pool. /// </remarks> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="DefaultErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<SkuInfo>>> ListMultiRolePoolSkusNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextPageLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListMultiRolePoolSkusNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new DefaultErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); DefaultErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<DefaultErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<SkuInfo>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<SkuInfo>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get usage metrics for a multi-role pool of an App Service Environment. /// </summary> /// <remarks> /// Get usage metrics for a multi-role pool of an App Service Environment. /// </remarks> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="DefaultErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<Usage>>> ListMultiRoleUsagesNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextPageLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListMultiRoleUsagesNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new DefaultErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); DefaultErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<DefaultErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<Usage>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<Usage>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Resume an App Service Environment. /// </summary> /// <remarks> /// Resume an App Service Environment. /// </remarks> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse<IPage<SiteInner>>> ResumeNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Send request AzureOperationResponse<IPage<SiteInner>> _response = await BeginResumeNextWithHttpMessagesAsync(nextPageLink, customHeaders, cancellationToken).ConfigureAwait(false); return await Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false); } /// <summary> /// Get all App Service plans in an App Service Environment. /// </summary> /// <remarks> /// Get all App Service plans in an App Service Environment. /// </remarks> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="DefaultErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<AppServicePlanInner>>> ListAppServicePlansNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextPageLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListAppServicePlansNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new DefaultErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); DefaultErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<DefaultErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<AppServicePlanInner>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<AppServicePlanInner>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get all apps in an App Service Environment. /// </summary> /// <remarks> /// Get all apps in an App Service Environment. /// </remarks> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="DefaultErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<SiteInner>>> ListWebAppsNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextPageLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListWebAppsNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new DefaultErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); DefaultErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<DefaultErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<SiteInner>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<SiteInner>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Suspend an App Service Environment. /// </summary> /// <remarks> /// Suspend an App Service Environment. /// </remarks> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse<IPage<SiteInner>>> SuspendNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Send request AzureOperationResponse<IPage<SiteInner>> _response = await BeginSuspendNextWithHttpMessagesAsync(nextPageLink, customHeaders, cancellationToken).ConfigureAwait(false); return await Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false); } /// <summary> /// Get global usage metrics of an App Service Environment. /// </summary> /// <remarks> /// Get global usage metrics of an App Service Environment. /// </remarks> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="DefaultErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<CsmUsageQuota>>> ListUsagesNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextPageLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListUsagesNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new DefaultErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); DefaultErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<DefaultErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<CsmUsageQuota>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<CsmUsageQuota>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get all worker pools of an App Service Environment. /// </summary> /// <remarks> /// Get all worker pools of an App Service Environment. /// </remarks> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="DefaultErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<WorkerPoolResourceInner>>> ListWorkerPoolsNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextPageLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListWorkerPoolsNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new DefaultErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); DefaultErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<DefaultErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<WorkerPoolResourceInner>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<WorkerPoolResourceInner>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get metric definitions for a specific instance of a worker pool of an App /// Service Environment. /// </summary> /// <remarks> /// Get metric definitions for a specific instance of a worker pool of an App /// Service Environment. /// </remarks> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="DefaultErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<ResourceMetricDefinition>>> ListWorkerPoolInstanceMetricDefinitionsNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextPageLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListWorkerPoolInstanceMetricDefinitionsNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new DefaultErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); DefaultErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<DefaultErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<ResourceMetricDefinition>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<ResourceMetricDefinition>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get metrics for a specific instance of a worker pool of an App Service /// Environment. /// </summary> /// <remarks> /// Get metrics for a specific instance of a worker pool of an App Service /// Environment. /// </remarks> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="DefaultErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<ResourceMetric>>> ListWorkerPoolInstanceMetricsNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextPageLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListWorkerPoolInstanceMetricsNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new DefaultErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); DefaultErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<DefaultErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<ResourceMetric>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<ResourceMetric>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get metric definitions for a worker pool of an App Service Environment. /// </summary> /// <remarks> /// Get metric definitions for a worker pool of an App Service Environment. /// </remarks> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="DefaultErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<ResourceMetricDefinition>>> ListWebWorkerMetricDefinitionsNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextPageLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListWebWorkerMetricDefinitionsNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new DefaultErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); DefaultErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<DefaultErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<ResourceMetricDefinition>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<ResourceMetricDefinition>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get metrics for a worker pool of a AppServiceEnvironment (App Service /// Environment). /// </summary> /// <remarks> /// Get metrics for a worker pool of a AppServiceEnvironment (App Service /// Environment). /// </remarks> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="DefaultErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<ResourceMetric>>> ListWebWorkerMetricsNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextPageLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListWebWorkerMetricsNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new DefaultErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); DefaultErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<DefaultErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<ResourceMetric>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<ResourceMetric>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get available SKUs for scaling a worker pool. /// </summary> /// <remarks> /// Get available SKUs for scaling a worker pool. /// </remarks> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="DefaultErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<SkuInfo>>> ListWorkerPoolSkusNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextPageLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListWorkerPoolSkusNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new DefaultErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); DefaultErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<DefaultErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<SkuInfo>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<SkuInfo>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get usage metrics for a worker pool of an App Service Environment. /// </summary> /// <remarks> /// Get usage metrics for a worker pool of an App Service Environment. /// </remarks> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="DefaultErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<Usage>>> ListWebWorkerUsagesNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextPageLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListWebWorkerUsagesNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new DefaultErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); DefaultErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<DefaultErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<Usage>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<Usage>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Move an App Service Environment to a different VNET. /// </summary> /// <remarks> /// Move an App Service Environment to a different VNET. /// </remarks> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="DefaultErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<SiteInner>>> BeginChangeVnetNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextPageLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "BeginChangeVnetNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("POST"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200 && (int)_statusCode != 202) { var ex = new DefaultErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); DefaultErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<DefaultErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<SiteInner>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<SiteInner>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } // Deserialize Response if ((int)_statusCode == 202) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<SiteInner>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Resume an App Service Environment. /// </summary> /// <remarks> /// Resume an App Service Environment. /// </remarks> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="DefaultErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<SiteInner>>> BeginResumeNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextPageLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "BeginResumeNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("POST"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200 && (int)_statusCode != 202) { var ex = new DefaultErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); DefaultErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<DefaultErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<SiteInner>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<SiteInner>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } // Deserialize Response if ((int)_statusCode == 202) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<SiteInner>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Suspend an App Service Environment. /// </summary> /// <remarks> /// Suspend an App Service Environment. /// </remarks> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="DefaultErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<SiteInner>>> BeginSuspendNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextPageLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "BeginSuspendNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("POST"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200 && (int)_statusCode != 202) { var ex = new DefaultErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); DefaultErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<DefaultErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<SiteInner>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<SiteInner>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } // Deserialize Response if ((int)_statusCode == 202) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<SiteInner>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
46.733176
445
0.558506
[ "MIT" ]
AntoineGa/azure-libraries-for-net
src/ResourceManagement/AppService/Generated/AppServiceEnvironmentsOperations.cs
632,627
C#
using DeninaSharp.Core; using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Threading; namespace Tests { [TestClass] public class BaseTests { public static object Lock = new object(); private TestContext testContextInstance; public TestContext TestContext { get { return testContextInstance; } set { testContextInstance = value; } } [TestInitialize] public void TestInitialize() { TestContext.WriteLine("Start"); Monitor.Enter(Lock); Pipeline.Reset(); Pipeline.Init(); TestContext.WriteLine($"Init complete. {Pipeline.CommandMethods.Count} command(s) loaded."); } [TestCleanup] public void TestCleanup() { TestContext.WriteLine("End"); Monitor.Exit(Lock); } } }
24.540541
104
0.580396
[ "MIT" ]
deanebarker/Denina
Tests/BaseTests.cs
910
C#
using System; public interface IToggleInput { bool isVisible { get; set; } bool isEnabled { get; set; } bool isActive { get; set; } event EventHandler onStateChanged; event EventHandler onActiveInteraction; event EventHandler onInactiveInteraction; }
23
45
0.721014
[ "BSD-3-Clause" ]
xinexix/ArrowTableGames
Assets/Scripts/Console/View/ControlStrip/IToggleInput.cs
276
C#
using Foundation; using UIKit; namespace Xamarin_iOS { // The UIApplicationDelegate for the application. This class is responsible for launching the // User Interface of the application, as well as listening (and optionally responding) to // application events from iOS. [Register("AppDelegate")] public class AppDelegate : UIApplicationDelegate { // class-level declarations public override UIWindow Window { get; set; } public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions) { // Override point for customization after application launch. // If not required for your application you can safely delete this method return true; } public override void OnResignActivation(UIApplication application) { // Invoked when the application is about to move from active to inactive state. // This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) // or when the user quits the application and it begins the transition to the background state. // Games should use this method to pause the game. } public override void DidEnterBackground(UIApplication application) { // Use this method to release shared resources, save user data, invalidate timers and store the application state. // If your application supports background exection this method is called instead of WillTerminate when the user quits. } public override void WillEnterForeground(UIApplication application) { // Called as part of the transiton from background to active state. // Here you can undo many of the changes made on entering the background. } public override void OnActivated(UIApplication application) { // Restart any tasks that were paused (or not yet started) while the application was inactive. // If the application was previously in the background, optionally refresh the user interface. } public override void WillTerminate(UIApplication application) { // Called when the application is about to terminate. Save data, if needed. See also DidEnterBackground. } } }
41.288136
131
0.668719
[ "MIT" ]
dhindrik/TDswe16
Lab - Xamarin.iOS/solution/Xamarin_iOS/AppDelegate.cs
2,438
C#
using Abp.MultiTenancy; using DRIMA.Authorization.Users; namespace DRIMA.MultiTenancy { public class Tenant : AbpTenant<User> { public Tenant() { } public Tenant(string tenancyName, string name) : base(tenancyName, name) { } } }
17.555556
54
0.550633
[ "MIT" ]
nccasia/codewar3
drima-manage-device/backend/aspnet-core/src/DRIMA.Core/MultiTenancy/Tenant.cs
318
C#
namespace Kebler { #if RELEASE using System; using System.Diagnostics; using System.IO; using System.Reflection; using System.Windows; using Caliburn.Micro; using Const; using Models; using Resources; using Services; using Kebler.Update.Core; using ViewModels; using System.Threading.Tasks; #endif internal static class Updater { #if RELEASE private static readonly Kebler.Services.Interfaces.ILog Log = Kebler.Services.Log.Instance; public static async void CheckUpdates() { Log.Info("Start check updates"); try { var current = Assembly.GetExecutingAssembly().GetName().Version; var result = await UpdaterApi.Check(ConstStrings.GITHUB_USER, nameof(Kebler), current, ConfigService.Instanse.AllowPreRelease); Log.Info($"Current {current} Serv {result.Item2.name}"); App.Instance.IsUpdateReady = result.Item1; if (result.Item1) { await Application.Current.Dispatcher.InvokeAsync(async () => { var mgr = new WindowManager(); var lt = LocalizationProvider.GetLocalizedValue(nameof(Strings.NewUpdate)); var dialogres = await mgr.ShowDialogAsync(new MessageBoxViewModel(lt.Replace("%d", result.Item2.tag_name), string.Empty, Enums.MessageBoxDilogButtons.YesNo, true)); if (dialogres == true) await Task.Run(InstallUpdates); }); } } catch (Exception ex) { App.Instance.IsUpdateReady = false; Log.Error(ex); } } public static void InstallUpdates() { Directory.CreateDirectory(ConstStrings.TempInstallerFolder); File.Copy(ConstStrings.InstallerExePath, ConstStrings.TempInstallerExePath, true); using (var process = new Process()) { var info = new ProcessStartInfo { FileName = ConstStrings.TempInstallerExePath, UseShellExecute = true, CreateNoWindow = true, RedirectStandardOutput = false, RedirectStandardError = false }; if (ConfigService.Instanse.AllowPreRelease) info.Arguments = $"{ConstStrings.Args.Beta}"; process.StartInfo = info; process.EnableRaisingEvents = false; process.Start(); } Application.Current.Shutdown(); } #endif } }
31.233333
144
0.543223
[ "Apache-2.0" ]
JeremiSharkboy/Kebler-Transmission-Remote-GUI
src/Kebler/Updater.cs
2,813
C#
namespace WpfMath.Parsers { /// <summary>An enumeration that describes how an atom generated by a command should be handled.</summary> internal enum AtomAppendMode { /// <summary>A new atom will be added to the end of the current formula.</summary> Add, /// <summary>A new atom will replace an entire existing formula.</summary> /// <remarks>Useful for commands that wrap or somehow process the existing formula.</remarks> Replace } }
35.142857
110
0.672764
[ "MIT" ]
ForNeVeR/wpf-math
src/WpfMath/Parsers/AtomAppendMode.cs
492
C#
using System; using System.Text.Json; using System.Net; using System.Net.Sockets; using System.IO; using System.Collections.Generic; using LibData; using System.Text; namespace BookHelper { // Note: Do not change this class. public class Setting { public int ServerPortNumber { get; set; } public int BookHelperPortNumber { get; set; } public int UserHelperPortNumber { get; set; } public string ServerIPAddress { get; set; } public string BookHelperIPAddress { get; set; } public string UserHelperIPAddress { get; set; } public int ServerListeningQueue { get; set; } } // Note: Complete the implementation of this class. You can adjust the structure of this class. public class SequentialHelper { public SequentialHelper() { //todo: implement the body. Add extra fields and methods to the class if needed } public void start() { Setting settings = JsonSerializer.Deserialize<Setting>(File.ReadAllText(@"../ClientServerConfig.json")); byte[] buffer = new byte[1000]; Message msgIn = new Message(); Message msgOut = new Message(); //opens and stores Books from Books.json List<BookData> bookContent = JsonSerializer.Deserialize<List<BookData>>(File.ReadAllText(@"BooksData.json")); //makes socket IPEndPoint bookHelperEndpoint = new IPEndPoint(IPAddress.Parse(settings.BookHelperIPAddress), settings.BookHelperPortNumber); Socket socket = new Socket(bookHelperEndpoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp); //binds socket and puts it in listening state socket.Bind(bookHelperEndpoint); socket.Listen(5); Console.WriteLine("Waiting for connection::BookHelper"); Socket libServerSocket = socket.Accept(); Console.WriteLine("Connection accepted\n"); while (true) { //receiving forwarded bookinquiry from server int b = libServerSocket.Receive(buffer); msgIn = JsonSerializer.Deserialize<Message>(Encoding.ASCII.GetString(buffer, 0, b)); Console.WriteLine("Receiving inquiry from server"); //close socket when server says to do so if (msgIn.Type == MessageType.EndCommunication) { Console.WriteLine("Goodbye"); socket.Close(); break; } else { //searching for the book and sends book info back when found bool bookFound = false; for (int i = 0; i < bookContent.Count; i++) { if (bookContent[i].Title == msgIn.Content) { msgOut.Type = MessageType.BookInquiryReply; msgOut.Content = JsonSerializer.Serialize(bookContent[i]); libServerSocket.Send(Encoding.ASCII.GetBytes(JsonSerializer.Serialize(msgOut))); Console.WriteLine("Book found, send to server\n"); bookFound = true; break; } } //scenario for when book cannot be found if (!bookFound) { msgOut.Type = MessageType.NotFound; msgOut.Content = JsonSerializer.Serialize(new BookData()); libServerSocket.Send(Encoding.ASCII.GetBytes(JsonSerializer.Serialize(msgOut))); Console.WriteLine("Book NOT found, send to server\n"); } } } } } }
39.36
137
0.550559
[ "MIT" ]
DePaWSiT/Courses
Networking/DistLibrary/LibBookHelper/BookHelper.cs
3,938
C#
using System.Collections.Generic; using UnityEngine; /// <summary> /// Describes a pool of GameObjects for a given Prefab. /// The GameObjectPooler will use these as its initial pools. /// </summary> [System.Serializable] public class GameObjectPoolInfo { public GameObject Prefab; public List<GameObject> Instances = new List<GameObject>(); }
27.692308
63
0.733333
[ "CC0-1.0" ]
Spydarlee/Plantasia
UnityProjects/Plantasia/Packages/Source/Scripts/System/GameObjectPoolInfo.cs
362
C#
namespace Merchello.Core.Models { using System; using System.Collections.Specialized; using System.Reflection; using System.Runtime.Serialization; using Merchello.Core.Models.EntityBase; using Merchello.Core.Models.Interfaces; using Merchello.Core.Models.TypeFields; /// <summary> /// The entity collection. /// </summary> [Serializable] [DataContract(IsReference = true)] internal class EntityCollection : DeployableEntity, IEntityCollection { /// <summary> /// The property selectors. /// </summary> private static readonly Lazy<PropertySelectors> _ps = new Lazy<PropertySelectors>(); #region Fields /// <summary> /// The entity type field key. /// </summary> private Guid _entityTfKey; /// <summary> /// The name. /// </summary> private string _name; /// <summary> /// The dynamic collection. /// </summary> private Guid _prodiverKey; /// <summary> /// The _parent key. /// </summary> private Guid? _parentKey; /// <summary> /// The sort order. /// </summary> private int _sortOrder; /// <summary> /// The sort order of the entity in the collection /// </summary> private int _listSortOrder; /// <summary> /// The <see cref="ExtendedDataCollection"/>. /// </summary> private ExtendedDataCollection _extendedData; /// <summary> /// Gets a value indicating whether the collection is represented as a filter. /// </summary> private bool _isFilter; #endregion /// <summary> /// Initializes a new instance of the <see cref="EntityCollection"/> class. /// </summary> /// <param name="entityTfKey"> /// The entity type field key. /// </param> /// <param name="providerKey"> /// The provider Key. /// </param> public EntityCollection(Guid entityTfKey, Guid providerKey) { Ensure.ParameterCondition(!Guid.Empty.Equals(entityTfKey), "entityKey"); Ensure.ParameterCondition(!Guid.Empty.Equals(providerKey), "providerKey"); _entityTfKey = entityTfKey; _prodiverKey = providerKey; } /// <inheritdoc/> [DataMember] public Guid? ParentKey { get { return _parentKey; } set { SetPropertyValueAndDetectChanges(value, ref _parentKey, _ps.Value.ParentKeySelector); } } /// <inheritdoc/> [DataMember] public Guid EntityTfKey { get { return _entityTfKey; } set { SetPropertyValueAndDetectChanges(value, ref _entityTfKey, _ps.Value.EntityTfKeySelector); } } /// <inheritdoc/> public EntityType EntityType { get { return EnumTypeFieldConverter.EntityType.GetTypeField(EntityTfKey); } } /// <inheritdoc/> [DataMember] public string Name { get { return _name; } set { SetPropertyValueAndDetectChanges(value, ref _name, _ps.Value.NameSelector); } } /// <inheritdoc/> [DataMember] public int SortOrder { get { return _sortOrder; } internal set { SetPropertyValueAndDetectChanges(value, ref _sortOrder, _ps.Value.SortOrderSelector); } } /// <inheritdoc/> [DataMember] public int ListSortOrder { get { return _listSortOrder; } internal set { SetPropertyValueAndDetectChanges(value, ref _listSortOrder, _ps.Value.ListSortOrderSelector); } } /// <inheritdoc/> [DataMember] public Guid ProviderKey { get { return _prodiverKey; } set { SetPropertyValueAndDetectChanges(value, ref _prodiverKey, _ps.Value.ProviderKeySelector); } } /// <inheritdoc/> [DataMember] public bool IsFilter { get { return _isFilter; } set { SetPropertyValueAndDetectChanges(value, ref _isFilter, _ps.Value.IsFilterSelector); } } /// <inheritdoc/> [DataMember] public ExtendedDataCollection ExtendedData { get { return _extendedData; } internal set { _extendedData = value; _extendedData.CollectionChanged += ExtendedDataChanged; } } /// <summary> /// Handles the extended data collection changed. /// </summary> /// <param name="sender"> /// The sender. /// </param> /// <param name="e"> /// The e. /// </param> private void ExtendedDataChanged(object sender, NotifyCollectionChangedEventArgs e) { OnPropertyChanged(_ps.Value.ExtendedDataChangedSelector); } /// <summary> /// The property selectors. /// </summary> private class PropertySelectors { /// <summary> /// The entity type field key selector. /// </summary> public readonly PropertyInfo EntityTfKeySelector = ExpressionHelper.GetPropertyInfo<EntityCollection, Guid>(x => x.EntityTfKey); /// <summary> /// The name selector. /// </summary> public readonly PropertyInfo NameSelector = ExpressionHelper.GetPropertyInfo<EntityCollection, string>(x => x.Name); /// <summary> /// The provider key selector. /// </summary> public readonly PropertyInfo ProviderKeySelector = ExpressionHelper.GetPropertyInfo<EntityCollection, Guid>(x => x.ProviderKey); /// <summary> /// The parent key selector. /// </summary> public readonly PropertyInfo ParentKeySelector = ExpressionHelper.GetPropertyInfo<EntityCollection, Guid?>(x => x.ParentKey); /// <summary> /// The sort info selector. /// </summary> public readonly PropertyInfo SortOrderSelector = ExpressionHelper.GetPropertyInfo<EntityCollection, int>(x => x.SortOrder); /// <summary> /// The lostsortorder selector. /// </summary> public readonly PropertyInfo ListSortOrderSelector = ExpressionHelper.GetPropertyInfo<EntityCollection, int>(x => x.ListSortOrder); /// <summary> /// The extended data changed selector. /// </summary> public readonly PropertyInfo ExtendedDataChangedSelector = ExpressionHelper.GetPropertyInfo<EntityCollection, ExtendedDataCollection>(x => x.ExtendedData); /// <summary> /// The is filter selector. /// </summary> public readonly PropertyInfo IsFilterSelector = ExpressionHelper.GetPropertyInfo<EntityCollection, bool>(x => x.IsFilter); } } }
27.202166
158
0.538421
[ "MIT" ]
vwa-software/Merchello
src/Merchello.Core/Models/EntityCollection.cs
7,537
C#
// Copyright (c) 2015 Augie R. Maddox, Guavaman Enterprises. All rights reserved. #pragma warning disable 0219 #pragma warning disable 0618 #pragma warning disable 0649 namespace Rewired.UI.ControlMapper { using UnityEngine; using UnityEngine.UI; using System.Collections.Generic; using System.Collections; using Rewired; [AddComponentMenu("")] public class UIGroup : MonoBehaviour { [SerializeField] private Text _label; [SerializeField] private Transform _content; public string labelText { get { return _label != null ? _label.text : string.Empty; } set { if(_label == null) return; _label.text = value; } } public Transform content { get { return _content; } } public void SetLabelActive(bool state) { if(_label == null) return; _label.gameObject.SetActive(state); } } }
26.15
83
0.568834
[ "MIT" ]
Constrained-Development/Magmescape
src/Assets/Plugins/Rewired/Extras/ControlMapper/Scripts/UIGroup.cs
1,048
C#
using Discord; using Discord.Audio; using NoeSbot.Enums; using NoeSbot.Helpers; using NoeSbot.Models; using NoeSbot.Modules; using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace NoeSbot.Logic { public class AudioPlayer { private IVoiceChannel _voiceChannel; private ITextChannel _textChannel; private IAudioClient _currentAudioChannel; private CancellationTokenSource _disposeToken; private ConcurrentQueue<AudioInfo> _queue; private bool _skip; private ulong _guildId; private float _volume; private int _count; private AudioStatusEnum _status; private bool _adding; private TaskCompletionSource<bool> _tcs; private bool _internalPause; public AudioPlayer(IVoiceChannel voiceChannel, ITextChannel textChannel, ulong guildId, int defaultVolume = 5) { _voiceChannel = voiceChannel ?? throw new ArgumentNullException(nameof(voiceChannel)); _textChannel = textChannel ?? throw new ArgumentNullException(nameof(textChannel)); _disposeToken = new CancellationTokenSource(); _queue = new ConcurrentQueue<AudioInfo>(); _skip = false; _guildId = guildId; _volume = 1.0f; _status = AudioStatusEnum.Created; _tcs = new TaskCompletionSource<bool>(); SetVolume(defaultVolume); } private bool Pause { get => _internalPause; set { new Thread(() => _tcs.TrySetResult(value)).Start(); _internalPause = value; } } private string FileName => $"botsong_{_guildId}_{_count}"; public ulong CurrentVoiceChannel => _voiceChannel.Id; public AudioStatusEnum Status { get => _status; } public void SetVolume(int volumeLevel) { if (volumeLevel < 0) volumeLevel = 0; if (volumeLevel > 10) volumeLevel = 10; _volume = (volumeLevel * 10) / 100.0f; } public async Task<AudioInfo> Start(List<string> items) { _currentAudioChannel = await _voiceChannel.ConnectAsync(); var url = items.First(); var info = await DownloadHelper.GetInfo(url); var file = await DownloadHelper.Download(url, FileName); _count++; info.File = file; _queue.Enqueue(info); var audioThread = new Thread(async () => { while (_queue.Any() || _adding) { try { if (_queue.Any()) { var success = _queue.TryPeek(out AudioInfo audioItem); if (!string.IsNullOrWhiteSpace(audioItem.File) && success) { await SendAudio(audioItem.File); File.Delete(audioItem.File); _skip = false; } } } catch { } finally { if (_queue.Any()) _queue.TryDequeue(out AudioInfo audioItem); } } await Stop(); }); _status = AudioStatusEnum.Playing; audioThread.Start(); var loadOthersThread = new Thread(async () => { if (items.Count > 1) { var otheritems = items.GetRange(1, items.Count - 1); await Add(otheritems); } }); loadOthersThread.Start(); return info; } public async Task Add(List<string> items) { _adding = true; foreach (var url in items) { if (_status != AudioStatusEnum.Playing) { _adding = false; Dispose(); return; } var info = await DownloadHelper.GetInfo(url); var file = await DownloadHelper.Download(url, FileName); _count++; info.File = file; _queue.Enqueue(info); } _adding = false; } public void PauseAudio() { Pause = true; _status = AudioStatusEnum.Paused; } public void Resume() { Pause = false; _status = AudioStatusEnum.Playing; } public async Task Stop() { Dispose(); await _currentAudioChannel.StopAsync(); _status = AudioStatusEnum.Stopped; } public AudioInfo SkipAudio() { if (_adding && _queue.Count <= 1) return new AudioInfo() { Title = "Loading" }; _skip = true; var nextItem = _queue.ElementAtOrDefault(1); if (_queue.Count > 1 && nextItem != null) return nextItem; return null; } public AudioInfo CurrentAudio() { if (_queue.TryPeek(out AudioInfo result)) return result; return new AudioInfo() { Title = "No audio found", Url = "", Description = "", Duration = "" }; } #region Private // Initial send audio was based on: mrousavy https://github.com/mrousavy/DiscordMusicBot private async Task SendAudio(string filePath) { try { var startInfo = new ProcessStartInfo { FileName = "ffmpeg", Arguments = $"-xerror -i \"{filePath}\" -ac 2 -f s16le -ar 48000 pipe:1", RedirectStandardOutput = true }; var ffmpeg = Process.Start(startInfo); using (Stream output = ffmpeg.StandardOutput.BaseStream) { using (AudioOutStream audioOutput = _currentAudioChannel.CreatePCMStream(AudioApplication.Mixed, null, 1920)) { int bufferSize = 3840; int bytesSent = 0; var exit = false; var buffer = new byte[bufferSize]; while (!_skip && !_disposeToken.IsCancellationRequested && !exit) { try { int read = await output.ReadAsync(buffer, 0, bufferSize, _disposeToken.Token); if (read == 0) { // End of audio exit = true; break; } // Adjust audio levels buffer = ScaleVolumeSafeAllocateBuffers(buffer, _volume); await audioOutput.WriteAsync(buffer, 0, read, _disposeToken.Token); if (Pause) { bool pauseAgain; do { pauseAgain = await _tcs.Task; _tcs = new TaskCompletionSource<bool>(); } while (pauseAgain); } bytesSent += read; } catch { exit = true; } } output.Dispose(); await audioOutput.FlushAsync(); } } } catch { await Stop(); } } private void Dispose() { _disposeToken.Cancel(); var disposeThread = new Thread(() => { foreach (var song in _queue) { try { File.Delete(song.File); } catch { } } while (_count > 0) { try { File.Delete(FileName); } catch { } _count--; } }); disposeThread.Start(); } // Source: https://github.com/RogueException/Discord.Net/issues/293 private byte[] ScaleVolumeSafeAllocateBuffers(byte[] audioSamples, float volume) { if (audioSamples == null) throw new ArgumentException(nameof(audioSamples)); if (audioSamples.Length % 2 != 0) throw new Exception("Not devisable by 2 (bit)"); if (volume < 0f || volume > 1f) throw new Exception("Invalid volume"); var output = new byte[audioSamples.Length]; if (Math.Abs(volume - 1f) < 0.0001f) { Buffer.BlockCopy(audioSamples, 0, output, 0, audioSamples.Length); return output; } // 16-bit precision for the multiplication int volumeFixed = (int)Math.Round(volume * 65536d); for (var i = 0; i < output.Length; i += 2) { // The cast to short is necessary to get a sign-extending conversion int sample = (short)((audioSamples[i + 1] << 8) | audioSamples[i]); int processed = (sample * volumeFixed) >> 16; output[i] = (byte)processed; output[i + 1] = (byte)(processed >> 8); } return output; } #endregion } }
30.929825
129
0.440348
[ "MIT" ]
stockmansy/NoeSBot
NoeSbot/Logic/AudioPlayer.cs
10,580
C#
/* * Scubawhere API Documentation * * This is the documentation for scubawhere's RMS API. This API is only to be used by authorized parties with valid auth tokens. [Learn about scubawhere](http://www.scubawhere.com) to become an authorized consumer of our API * * OpenAPI spec version: 1.0.0 * Contact: bryan@scubawhere.com * Generated by: https://github.com/swagger-api/swagger-codegen.git * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Linq; using System.IO; using System.Text; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; namespace IO.Swagger.Model { /// <summary> /// InlineResponse20039 /// </summary> [DataContract] public partial class InlineResponse20039 : IEquatable<InlineResponse20039> { /// <summary> /// Initializes a new instance of the <see cref="InlineResponse20039" /> class. /// </summary> /// <param name="Refunds">Refunds.</param> public InlineResponse20039(List<Payment> Refunds = null) { this.Refunds = Refunds; } /// <summary> /// Gets or Sets Refunds /// </summary> [DataMember(Name="refunds", EmitDefaultValue=false)] public List<Payment> Refunds { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class InlineResponse20039 {\n"); sb.Append(" Refunds: ").Append(Refunds).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="obj">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object obj) { // credit: http://stackoverflow.com/a/10454552/677735 return this.Equals(obj as InlineResponse20039); } /// <summary> /// Returns true if InlineResponse20039 instances are equal /// </summary> /// <param name="other">Instance of InlineResponse20039 to be compared</param> /// <returns>Boolean</returns> public bool Equals(InlineResponse20039 other) { // credit: http://stackoverflow.com/a/10454552/677735 if (other == null) return false; return ( this.Refunds == other.Refunds || this.Refunds != null && this.Refunds.SequenceEqual(other.Refunds) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { // credit: http://stackoverflow.com/a/263416/677735 unchecked // Overflow is fine, just wrap { int hash = 41; // Suitable nullity checks etc, of course :) if (this.Refunds != null) hash = hash * 59 + this.Refunds.GetHashCode(); return hash; } } } }
33.874016
226
0.590191
[ "Apache-2.0" ]
scubawhere/scubawhere-api-c-sharp-client
src/IO.Swagger/Model/InlineResponse20039.cs
4,302
C#
//****************************************************************************************************** // RemoteOutputAdapter.cs - Gbtc // // Copyright © 2012, Grid Protection Alliance. All Rights Reserved. // // Licensed to the Grid Protection Alliance (GPA) under one or more contributor license agreements. See // the NOTICE file distributed with this work for additional information regarding copyright ownership. // The GPA licenses this file to you under the MIT License (MIT), 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.opensource.org/licenses/MIT // // Unless agreed to in writing, the subject software distributed under the License is distributed on an // "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. Refer to the // License for the specific language governing permissions and limitations. // // Code Modification History: // ---------------------------------------------------------------------------------------------------- // 06/01/2009 - J. Ritchie Carroll // Generated original version of source code. // 09/15/2009 - Stephen C. Will // Added new header and license agreement. // 09/22/2009 - Pinal C. Patel // Re-wrote the adapter to utilize new components. // 09/23/2009 - Pinal C. Patel // Fixed the handling of socket disconnect. // 03/04/2010 - Pinal C. Patel // Added outputIsForArchive and throttleTransmission setting parameters for more control over // the adapter. // Switched to ManualResetEvent for waiting on historian acknowledgement for efficiency. // 01/20/2011 - Pinal C. Patel // Modified to use Settings for the ConnectionString property of historian socket. // 12/13/2012 - Starlynn Danyelle Gilliam // Modified Header. // //****************************************************************************************************** using System; using System.Collections.Generic; using System.ComponentModel; using System.Text; using System.Threading; using GSF; using GSF.Communication; using GSF.Diagnostics; using GSF.Historian.Packets; using GSF.Parsing; using GSF.TimeSeries; using GSF.TimeSeries.Adapters; namespace HistorianAdapters { /// <summary> /// Represents an output adapter that publishes measurements to openHistorian for archival. /// </summary> [Description("Remote v1.0 Historian Publisher: Forwards measurements to a remote 1.0 openHistorian for archival")] public class RemoteOutputAdapter : OutputAdapterBase { #region [ Members ] // Constants private const int DefaultHistorianPort = 1003; private const bool DefaultPayloadAware = true; private const bool DefaultConserveBandwidth = true; private const bool DefaultOutputIsForArchive = true; private const bool DefaultThrottleTransmission = true; private const int DefaultSamplesPerTransmission = 100000; private const int PublisherWaitTime = 5000; // Fields private string m_server; private int m_port; private bool m_payloadAware; private bool m_conserveBandwidth; private bool m_outputIsForArchive; private bool m_throttleTransmission; private int m_samplesPerTransmission; private readonly TcpClient m_historianPublisher; private byte[] m_publisherBuffer; private readonly ManualResetEvent m_publisherWaitHandle; private Action<IMeasurement[], int, int> m_publisherDelegate; private bool m_publisherDisconnecting; private long m_measurementsPublished; private bool m_disposed; #endregion #region [ Constructors ] /// <summary> /// Initializes a new instance of the <see cref="RemoteOutputAdapter"/> class. /// </summary> public RemoteOutputAdapter() { m_historianPublisher = new TcpClient(); m_publisherWaitHandle = new ManualResetEvent(false); m_port = DefaultHistorianPort; m_payloadAware = DefaultPayloadAware; m_conserveBandwidth = DefaultConserveBandwidth; m_outputIsForArchive = DefaultOutputIsForArchive; m_throttleTransmission = DefaultThrottleTransmission; m_samplesPerTransmission = DefaultSamplesPerTransmission; } #endregion #region [ Properties ] /// <summary> /// Gets or sets the host name for the server hosting the remote historian. /// </summary> [ConnectionStringParameter, Description("Define the host name of the remote historian.")] public string Server { get { return m_server; } set { m_server = value; } } /// <summary> /// Gets or sets the port on which the remote historian is listening. /// </summary> [ConnectionStringParameter, Description("Define the port on which the remote historian is listening."), DefaultValue(1003)] public int Port { get { return m_port; } set { m_port = value; } } /// <summary> /// Gets or sets a boolean value indicating whether the payload /// boundaries are to be preserved during transmission. /// </summary> [ConnectionStringParameter, Description("Define a value indicating whether to preserve payload boundaries during transmission."), DefaultValue(true)] public bool PayloadAware { get { return m_payloadAware; } set { m_payloadAware = value; } } /// <summary> /// Gets or sets a boolean value that determines the packet /// type to be used when sending data to the server. /// </summary> [ConnectionStringParameter, Description("Define a value indicating the packet type when sending data to the server."), DefaultValue(true)] public bool ConserveBandwidth { get { return m_conserveBandwidth; } set { m_conserveBandwidth = value; } } /// <summary> /// Returns a flag that determines if measurements sent to this <see cref="RemoteOutputAdapter"/> are destined for archival. /// </summary> [ConnectionStringParameter, Description("Define a value that determines whether the measurements are destined for archival."), DefaultValue(true)] public override bool OutputIsForArchive => m_outputIsForArchive; /// <summary> /// Gets or sets a boolean value that determines whether to wait for /// acknowledgment from the historian that the last set of points have /// been received before attempting to send the next set of points. /// </summary> [ConnectionStringParameter, Description("Define a value that determines whether to wait for acknowledgment before sending more points."), DefaultValue(true)] public bool ThrottleTransmission { get { return m_throttleTransmission; } set { m_throttleTransmission = value; } } /// <summary> /// Gets or sets an integer that indicates the maximum number /// of points to be published to the historian at once. /// </summary> [ConnectionStringParameter, Description("Define the maximum number of points to be published at once."), DefaultValue(100000)] public int SamplesPerTransmission { get { return m_samplesPerTransmission; } set { m_samplesPerTransmission = value; } } /// <summary> /// Gets flag that determines if this <see cref="RemoteOutputAdapter"/> uses an asynchronous connection. /// </summary> protected override bool UseAsyncConnect => true; /// <summary> /// Returns the detailed status of the data output source. /// </summary> public override string Status { get { StringBuilder status = new StringBuilder(); status.Append(base.Status); status.AppendLine(); status.Append(m_historianPublisher.Status); return status.ToString(); } } #endregion #region [ Methods ] /// <summary> /// Initializes this <see cref="RemoteOutputAdapter"/>. /// </summary> /// <exception cref="ArgumentException"><b>Server</b> is missing from the <see cref="AdapterBase.Settings"/>.</exception> public override void Initialize() { base.Initialize(); string errorMessage = "{0} is missing from Settings - Example: server=localhost;port=1003;payloadAware=True;conserveBandwidth=True;outputIsForArchive=True;throttleTransmission=True;samplesPerTransmission=100000"; Dictionary<string, string> settings = Settings; string setting; // Validate settings. if (!settings.TryGetValue("server", out m_server)) throw new ArgumentException(string.Format(errorMessage, "server")); if (settings.TryGetValue("port", out setting)) m_port = int.Parse(setting); else settings.Add("port", m_port.ToString()); if (settings.TryGetValue("payloadaware", out setting)) m_payloadAware = setting.ParseBoolean(); if (settings.TryGetValue("conservebandwidth", out setting)) m_conserveBandwidth = setting.ParseBoolean(); if (settings.TryGetValue("outputisforarchive", out setting)) m_outputIsForArchive = setting.ParseBoolean(); if (settings.TryGetValue("throttletransmission", out setting)) m_throttleTransmission = setting.ParseBoolean(); if (settings.TryGetValue("samplespertransmission", out setting)) m_samplesPerTransmission = int.Parse(setting); // Initialize publisher delegates. if (m_conserveBandwidth) { m_publisherDelegate = TransmitPacketType101; } else { m_publisherDelegate = TransmitPacketType1; m_publisherBuffer = new byte[m_samplesPerTransmission * PacketType1.FixedLength]; } // Initialize publisher socket. m_historianPublisher.ConnectionString = settings.JoinKeyValuePairs(); m_historianPublisher.PayloadAware = m_payloadAware; m_historianPublisher.ConnectionAttempt += HistorianPublisher_ConnectionAttempt; m_historianPublisher.ConnectionEstablished += HistorianPublisher_ConnectionEstablished; m_historianPublisher.ConnectionTerminated += HistorianPublisher_ConnectionTerminated; m_historianPublisher.SendDataException += HistorianPublisher_SendDataException; m_historianPublisher.ReceiveDataComplete += HistorianPublisher_ReceiveDataComplete; m_historianPublisher.ReceiveDataException += HistorianPublisher_ReceiveDataException; m_historianPublisher.Initialize(); } /// <summary> /// Gets a short one-line status of this <see cref="RemoteOutputAdapter"/>. /// </summary> /// <param name="maxLength">Maximum length of the status message.</param> /// <returns>Text of the status message.</returns> public override string GetShortStatus(int maxLength) { if (m_outputIsForArchive) return $"Published {m_measurementsPublished} measurements for archival.".CenterText(maxLength); return $"Published {m_measurementsPublished} measurements for processing.".CenterText(maxLength); } /// <summary> /// Releases the unmanaged resources used by this <see cref="RemoteOutputAdapter"/> and optionally releases the managed resources. /// </summary> /// <param name="disposing">true to release both managed and unmanaged resources; false to release only unmanaged resources.</param> protected override void Dispose(bool disposing) { if (!m_disposed) { try { // This will be done regardless of whether the object is finalized or disposed. if (disposing) { // This will be done only when the object is disposed by calling Dispose(). if (m_historianPublisher != null) { m_historianPublisher.ConnectionAttempt -= HistorianPublisher_ConnectionAttempt; m_historianPublisher.ConnectionEstablished -= HistorianPublisher_ConnectionEstablished; m_historianPublisher.ConnectionTerminated -= HistorianPublisher_ConnectionTerminated; m_historianPublisher.SendDataException -= HistorianPublisher_SendDataException; m_historianPublisher.ReceiveDataComplete -= HistorianPublisher_ReceiveDataComplete; m_historianPublisher.ReceiveDataException -= HistorianPublisher_ReceiveDataException; m_historianPublisher.Dispose(); } m_publisherWaitHandle.Close(); } } finally { m_disposed = true; // Prevent duplicate dispose. base.Dispose(disposing); // Call base class Dispose(). } } } /// <summary> /// Attempts to connect to this <see cref="RemoteOutputAdapter"/>. /// </summary> protected override void AttemptConnection() { m_publisherDisconnecting = false; m_historianPublisher.ConnectAsync(); } /// <summary> /// Attempts to disconnect from this <see cref="RemoteOutputAdapter"/>. /// </summary> protected override void AttemptDisconnection() { m_publisherDisconnecting = true; m_historianPublisher.Disconnect(); } /// <summary> /// Publishes <paramref name="measurements"/> for archival. /// </summary> /// <param name="measurements">Measurements to be archived.</param> /// <exception cref="OperationCanceledException">Acknowledgment is not received from historian for published data.</exception> protected override void ProcessMeasurements(IMeasurement[] measurements) { if (m_historianPublisher.CurrentState != ClientState.Connected) throw new InvalidOperationException("Historian publisher socket is not connected"); try { for (int i = 0; i < measurements.Length; i += m_samplesPerTransmission) { // Wait for historian acknowledgment. if (m_throttleTransmission) { if (!m_publisherWaitHandle.WaitOne(PublisherWaitTime)) throw new OperationCanceledException("Timeout waiting for acknowledgment from historian"); } // Publish measurements to historian. m_publisherWaitHandle.Reset(); m_publisherDelegate(measurements, i, (measurements.Length - i < m_samplesPerTransmission ? measurements.Length : i + m_samplesPerTransmission) - 1); } m_measurementsPublished += measurements.Length; } catch { m_publisherWaitHandle.Set(); throw; } } private void HistorianPublisher_ConnectionAttempt(object sender, EventArgs e) { OnStatusMessage(MessageLevel.Info, "Attempting socket connection..."); } private void HistorianPublisher_ConnectionEstablished(object sender, EventArgs e) { OnConnected(); m_publisherWaitHandle.Set(); } private void HistorianPublisher_ConnectionTerminated(object sender, EventArgs e) { m_measurementsPublished = 0; m_publisherWaitHandle.Reset(); if (!m_publisherDisconnecting) Start(); } private void HistorianPublisher_SendDataException(object sender, EventArgs<Exception> e) { m_publisherWaitHandle.Set(); OnProcessException(MessageLevel.Warning, e.Argument); } private void HistorianPublisher_ReceiveDataComplete(object sender, EventArgs<byte[], int> e) { // Check for acknowledgment from historian. string reply = Encoding.ASCII.GetString(e.Argument1, 0, e.Argument2); if (reply == "ACK") m_publisherWaitHandle.Set(); } private void HistorianPublisher_ReceiveDataException(object sender, EventArgs<Exception> e) { m_publisherWaitHandle.Set(); OnProcessException(MessageLevel.Warning, e.Argument); } private void TransmitPacketType1(IMeasurement[] measurements, int startIndex, int endIndex) { int bufferIndex = 0; for (int i = startIndex; i <= endIndex; i++) bufferIndex += new PacketType1(measurements[i]).GenerateBinaryImage(m_publisherBuffer, bufferIndex); m_historianPublisher.SendAsync(m_publisherBuffer, 0, bufferIndex); } private void TransmitPacketType101(IMeasurement[] measurements, int startIndex, int endIndex) { PacketType101 packet = new PacketType101(); for (int i = startIndex; i <= endIndex; i++) packet.Data.Add(new PacketType101DataPoint(measurements[i])); m_historianPublisher.SendAsync(packet.BinaryImage()); } #endregion } }
39.200418
224
0.598072
[ "MIT" ]
GridProtectionAlliance/gsf
Source/Libraries/Adapters/HistorianAdapters/RemoteOutputAdapter.cs
18,780
C#
using System; using System.Collections; using System.Collections.Generic; using System.Linq; namespace Expl.Auxiliary.Sequence { /// <summary> /// Useful extensions for IEnumerable ordered sequences. /// </summary> public static class SequenceExtensions { /// <summary> /// Flatten multiple sequences into a single sequence, preserving order. /// </summary> /// <typeparam name="T">Enumerated type.</typeparam> /// <param name="inputSequences">List of input sequences.</param> /// <param name="comparer">Delegate to compare two input objects; like IComparer.CompareTo.</param> /// <returns>Result sequence.</returns> public static IEnumerable<T> SequenceFlatten<T>(this IEnumerable<T>[] inputSequences, Comparison<T> comparer) { return new SequenceSetFlatten<T>(inputSequences, comparer); } /// <summary> /// Flatten multiple sequences into a single sequence, preserving order. /// </summary> /// <typeparam name="T">Enumerated type which implements IComparable.</typeparam> /// <param name="inputSequences">List of input sequences.</param> /// <returns>Result sequence.</returns> public static IEnumerable<T> SequenceFlatten<T>(this IEnumerable<T>[] inputSequences) where T : IComparable<T> { return new SequenceSetFlatten<T>(inputSequences, (x, y) => x.CompareTo(y)); } /// <summary> /// Get sequence where input sequence intersects domain sequence. /// </summary> /// <typeparam name="T">Enumerated type that implements IComparable.</typeparam> /// <param name="inputSequence">Input sequence.</param> /// <param name="domainSequence">Domain sequence.</param> /// <param name="comparer">Delegate to compare two input objects; like IComparer.CompareTo.</param> /// <returns>Result sequence.</returns> public static IEnumerable<T> SequenceIntersection<T>(this IEnumerable<T> inputSequence, IEnumerable<T> domainSequence, Comparison<T> comparer) { IEnumerator<T> inputEnum = inputSequence.GetEnumerator(); IEnumerator<T> domainEnum = domainSequence.GetEnumerator(); bool domainDataFlag = domainEnum.MoveNext(); for (bool inputDataFlag = inputEnum.MoveNext(); inputDataFlag; ) { if (domainDataFlag) { int cmp = comparer(inputEnum.Current, domainEnum.Current); // If input is less than domain, no match; continue loop if (cmp < 0) continue; // If input is greater than domain, iterate domain and loop to retest else if (cmp > 0) { domainDataFlag = domainEnum.MoveNext(); continue; } // If equal, fall through to return input element } else { // No more domain elements, no more possible matches; exit loop break; } yield return inputEnum.Current; inputDataFlag = inputEnum.MoveNext(); } yield break; } /// <summary> /// Get sequence where input sequence intersects domain sequence. /// </summary> /// <typeparam name="T">Enumerated type that implements IComparable.</typeparam> /// <param name="inputSequence">Input sequence.</param> /// <param name="domainSequence">Domain sequence.</param> /// <returns>Result sequence.</returns> public static IEnumerable<T> SequenceIntersection<T>(this IEnumerable<T> inputSequence, IEnumerable<T> domainSequence) where T : IComparable<T> { return SequenceIntersection(inputSequence, domainSequence, (a, b) => a.CompareTo(b)); } /// <summary> /// Get sequence where input sequence differs domain sequence. /// </summary> /// <typeparam name="T">Enumerated type.</typeparam> /// <param name="inputSequence">Input sequence.</param> /// <param name="domainSequence">Domain sequence.</param> /// <param name="comparer">Delegate to compare two input objects; like IComparer.CompareTo.</param> /// <returns>Result sequence.</returns> public static IEnumerable<T> SequenceDifference<T>(this IEnumerable<T> inputSequence, IEnumerable<T> domainSequence, Comparison<T> comparer) { IEnumerator<T> inputEnum = inputSequence.GetEnumerator(); IEnumerator<T> domainEnum = domainSequence.GetEnumerator(); bool domainDataFlag = domainEnum.MoveNext(); for (bool inputDataFlag = inputEnum.MoveNext(); inputDataFlag; ) { if (domainDataFlag) { int cmp = comparer(inputEnum.Current, domainEnum.Current); // If input is less than domain, no match; return element if (cmp < 0) yield return inputEnum.Current; // If input is greater than domain, iterate domain and loop to retest else if (cmp > 0) { domainDataFlag = domainEnum.MoveNext(); continue; } // If equal, fall through to iterate without returning input element } else { // No more domain elements, return input element yield return inputEnum.Current; } // Iterate input inputDataFlag = inputEnum.MoveNext(); } yield break; } /// <summary> /// Get sequence where input sequence differs domain sequence. /// </summary> /// <typeparam name="T">Enumerated type that implements IComparable.</typeparam> /// <param name="inputSequence">Input sequence.</param> /// <param name="domainSequence">Domain sequence.</param> /// <returns>Result sequence.</returns> public static IEnumerable<T> SequenceDifference<T>(this IEnumerable<T> inputSequence, IEnumerable<T> domainSequence) where T : IComparable<T> { return SequenceDifference(inputSequence, domainSequence, (a, b) => a.CompareTo(b)); } /// <summary> /// Get union sequence of input sequences. /// </summary> /// <typeparam name="T">Enumerated type.</typeparam> /// <param name="inputSequence">Input sequences.</param> /// <param name="comparer">Delegate to compare two input objects; like IComparer.CompareTo.</param> /// <returns>Result sequence.</returns> public static IEnumerable<T> SequenceUnion<T>(this IEnumerable<T>[] inputSequences, Comparison<T> comparer) { return new SequenceSetUnion<T>(inputSequences, comparer); } /// <summary> /// Get union sequence of input sequences. /// </summary> /// <typeparam name="T">Enumerated type.</typeparam> /// <param name="inputSequence">Input sequence.</param> /// <param name="additionalSequences">Additional input sequences.</param> /// <returns>Result sequence.</returns> public static IEnumerable<T> SequenceUnion<T>(this IEnumerable<T>[] inputSequences) where T : IComparable<T> { return new SequenceSetUnion<T>(inputSequences, (a, b) => a.CompareTo(b)); } /// <summary> /// Compute flattened sequence from input sequences. /// </summary> /// <typeparam name="T">Enumerated type.</typeparam> private class SequenceSetFlatten<T> : SequenceSetBase<T> { public SequenceSetFlatten(IEnumerable<T>[] inputSequences, Comparison<T> comparer) : base(inputSequences, comparer) { } public override IEnumerator<T> GetEnumerator() { var iterators = GetIterators(); Iterator matchIterator = null; do { // Scan each iterator for a single minimum current value, according to Comparison delegate matchIterator = iterators .Where(i => i.HasData) .Aggregate((Iterator)null, (a, i) => (a == null || _comparer(i.Current, a.Current) < 0) ? i : a); if (matchIterator != null) { // Return iterator, if found yield return matchIterator.Current; matchIterator.MoveNext(); } // Continue until no more iterators found } while (matchIterator != null); yield break; } } /// <summary> /// Compute union sequence from input sequences. /// </summary> /// <typeparam name="T"></typeparam> private class SequenceSetUnion<T> : SequenceSetBase<T> { public SequenceSetUnion(IEnumerable<T>[] inputSequences, Comparison<T> comparer) : base(inputSequences, comparer) { } /// <summary> /// Flatten all sequences into single sequence of iterators. /// </summary> public override IEnumerator<T> GetEnumerator() { var iterators = GetIterators(); var matchIterators = new List<Iterator>(); do { // Scan each iterator for all iterators matching minimum current value, // according to Comparison delegate matchIterators.Clear(); foreach (var i in iterators.Where(i => i.HasData)) { var fi = matchIterators.FirstOrDefault(); if (fi == null || _comparer(fi.Current, i.Current) == 0) { // Add if first element or values match matchIterators.Add(i); } else if (_comparer(i.Current, fi.Current) < 0) { // New minimum found, clear list and add this iterator matchIterators.Clear(); matchIterators.Add(i); } } var retIterator = matchIterators.FirstOrDefault(); if (retIterator != null) { // Return iterator, if found yield return retIterator.Current; // Advance each iterator foreach (var i in matchIterators) { i.MoveNext(); } } // Continue until no more iterators found } while (matchIterators.Count > 0); yield break; } } /// <summary> /// Base class for aggregation functions on a list of sequences. /// </summary> /// <typeparam name="T">Enumerated type.</typeparam> private abstract class SequenceSetBase<T> : IEnumerable<T> { protected IEnumerable<T>[] _inputSequences; protected Comparison<T> _comparer; public SequenceSetBase(IEnumerable<T>[] inputSequences, Comparison<T> comparer) { _inputSequences = inputSequences; _comparer = comparer; } /// <summary> /// Convert inputSequences to array of Iterators. /// </summary> /// <returns></returns> protected Iterator[] GetIterators() { return _inputSequences.Select(e => new Iterator(e.GetEnumerator())).ToArray(); } /// <summary> /// Wraps IEnumerator to alter usage pattern. /// Provides new HasData property. No need to call MoveNext() before first access. /// </summary> /// <typeparam name="T">Enumerated type.</typeparam> protected class Iterator : IEnumerator<T> { private IEnumerator<T> _enumerator; private int _counter = 0; public Iterator(IEnumerator<T> enumerator) { _enumerator = enumerator; MoveNext(); } public bool HasData { get; private set; } #region IEnumerator<T> Members public T Current { get { return _enumerator.Current; } } #endregion #region IDisposable Members public void Dispose() { _enumerator.Dispose(); } #endregion #region IEnumerator Members object System.Collections.IEnumerator.Current { get { return _enumerator.Current; } } public bool MoveNext() { HasData = _enumerator.MoveNext(); if (HasData) _counter++; return HasData; } public void Reset() { _enumerator.Reset(); } #endregion } #region IEnumerable<T> Members public abstract IEnumerator<T> GetEnumerator(); #endregion #region IEnumerable Members System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return (System.Collections.IEnumerator)GetEnumerator(); } #endregion } } }
40.090909
151
0.587536
[ "MIT" ]
c3rebro/EventMessenger
EventMessenger/3rdParty/Itinerary/Expl.Itinerary/Auxiliary/SequenceExtensions.cs
12,791
C#
using TransparentFacadeSubSystem.Abstractions; namespace TransparentFacadeSubSystem { public class ComponentA : IComponentA { public string OperationA() => "Component A, Operation A"; public string OperationB() => "Component A, Operation B"; } }
25.090909
65
0.702899
[ "MIT" ]
ABEMBARKA/ASP.NET-Core-5-Design-Patterns
C09/src/TransparentFacadeSubSystem/ComponentA.cs
278
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Ordering.Application.Features.Orders.Queries.GetOrdersList { public class OrdersVm { public int Id { get; set; } public string UserName { get; set; } public decimal TotalPrice { get; set; } // BillingAddress public string FirstName { get; set; } public string LastName { get; set; } public string EmailAddress { get; set; } public string AddressLine { get; set; } public string Country { get; set; } public string State { get; set; } public string ZipCode { get; set; } // Payment public string CardName { get; set; } public string CardNumber { get; set; } public string Expiration { get; set; } public string CVV { get; set; } public int PaymentMethod { get; set; } } }
28.5
68
0.641447
[ "MIT" ]
CapitanHerlock/AspnetMicroservices
src/Services/Ordering/Ordering.Application/Features/Orders/Queries/GetOrdersList/OrdersVm.cs
914
C#
using Riganti.Selenium.Core.Drivers; using Riganti.Selenium.Core.Drivers.Implementation; using Riganti.Selenium.Core.Configuration; using Riganti.Selenium.Core.Logging; namespace Riganti.Selenium.Core.Factories.Implementation { public class FirefoxDevWebBrowserFactory : LocalWebBrowserFactory { public override string Name => "firefox:dev"; protected override IWebBrowser CreateBrowser() { return new FirefoxDevWebBrowser(this); } public FirefoxDevWebBrowserFactory(TestSuiteRunner runner) : base(runner) { } } }
28.428571
81
0.715243
[ "Apache-2.0" ]
JTOne123/selenium-utils
src/Core/Riganti.Selenium.Core/Factories/Implementation/FirefoxDevWebBrowserFactory.cs
599
C#
using Business.Utils.Log; using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.Http; using Model.Utils.Log; using System; using System.Linq; using System.Net.Http; using System.Threading.Tasks; using System.Xml; using System.Xml.Linq; using System.Xml.XPath; namespace Api.Middleware { /// <summary> /// CAS单点注销中间件 /// </summary> public class CasSingleSignOutMiddleware { private const string RequestContentType = "application/x-www-form-urlencoded"; private static readonly XmlNamespaceManager _xmlNamespaceManager = InitializeXmlNamespaceManager(); private readonly ITicketStore _store; private readonly RequestDelegate _next; public CasSingleSignOutMiddleware(RequestDelegate next, ITicketStore store) { _next = next; _store = store; } public async Task Invoke(HttpContext context) { if (context?.Request.Method.Equals(HttpMethod.Post.Method, StringComparison.OrdinalIgnoreCase) == true && context.Request.ContentType?.Equals(RequestContentType, StringComparison.OrdinalIgnoreCase) == true) { var formData = await context.Request.ReadFormAsync(context.RequestAborted).ConfigureAwait(false); if (formData.ContainsKey("logoutRequest")) { var logOutRequest = formData.First(x => x.Key == "logoutRequest").Value[0]; if (!string.IsNullOrEmpty(logOutRequest)) { Logger.Debug(LogType.系统跟踪, $"logoutRequest: {logOutRequest}"); var serviceTicket = ExtractSingleSignOutTicketFromSamlResponse(logOutRequest); if (!string.IsNullOrEmpty(serviceTicket)) { Logger.Info(LogType.系统跟踪, $"remove serviceTicket: {serviceTicket} ..."); await _store.RemoveAsync(serviceTicket).ConfigureAwait(false); } } } } await _next.Invoke(context).ConfigureAwait(false); } private static string ExtractSingleSignOutTicketFromSamlResponse(string text) { try { var doc = XDocument.Parse(text); var nav = doc.CreateNavigator(); /* <samlp:LogoutRequest xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol" xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion" ID="[RANDOM ID]" Version="2.0" IssueInstant="[CURRENT DATE/TIME]"> <saml:NameID>@NOT_USED@</saml:NameID> <samlp:SessionIndex>[SESSION IDENTIFIER]</samlp:SessionIndex> </samlp:LogoutRequest> */ var node = nav.SelectSingleNode("samlp:LogoutRequest/samlp:SessionIndex/text()", _xmlNamespaceManager); if (node != null) { return node.Value; } } catch (XmlException) { //logoutRequest was not xml } return string.Empty; } private static XmlNamespaceManager InitializeXmlNamespaceManager() { var namespaceManager = new XmlNamespaceManager(new NameTable()); namespaceManager.AddNamespace("samlp", "urn:oasis:names:tc:SAML:2.0:protocol"); return namespaceManager; } } }
38.806452
119
0.572458
[ "Apache-2.0" ]
Lc3586/Microservice
src/Applications/SimpleApi/Api/Middleware/CasSingleSignOutMiddleware.cs
3,641
C#
using Machine.Specifications; using PlainElastic.Net.Queries; using PlainElastic.Net.Utils; namespace PlainElastic.Net.Tests.Builders.Queries { [Subject(typeof(HasChildQuery<,>))] class When_empty_HasChildQuery_built { Because of = () => result = new HasChildQuery<FieldsTestClass, AnotherTestClass>() .Type("childType") .Query(q => q) .Scope("query_scope") .Boost(5) .Custom("") .ToString(); It should_return_empty_string = () => result.ShouldBeEmpty(); private static string result; } }
33.4
90
0.446707
[ "MIT" ]
AAATechGuy/PlainElastic.Net
src/PlainElastic.Net.Tests/Builders/Queries/HasChild/When_empty_HasChildQuery_built.cs
837
C#
using System; using Copernicus.Common.CQRS.Commands; namespace Copernicus.Application.Questions.Commands { public class DeleteQuestion : ICommand { public Guid Id { get; set; } } }
20.1
51
0.706468
[ "MIT" ]
boski-src/Copernicus.Server
Copernicus.Application/Questions/Commands/DeleteQuestion.cs
201
C#
using UnityEngine; using System; [Serializable] public struct Point { [SerializeField] public int x; [SerializeField] public int y; public Point(int x, int y) { this.x = x; this.y = y; } /// <summary> /// Gets the value at an index. /// </summary> /// <param name="index">The index you are trying to get.</param> /// <returns>The value at that index.</returns> public int this[int index] { get { int result; if (index != 0) { if (index != 1) { throw new IndexOutOfRangeException("Index " + index.ToString() + " is out of range."); } result = y; } else { result = x; } return result; } set { if (index != 0) { if (index != 1) { throw new IndexOutOfRangeException("Index " + index.ToString() + " is out of range."); } y = value; } else { x = value; } } } /// <summary> /// Sets the x and y components of an existing Point /// </summary> /// <param name="x">The new x value</param> /// <param name="y">The new y value</param> public void Set(int x, int y) { this.x = x; this.y = y; } /// <summary> /// Clamps a point to a minimum value for both x and y and /// returns the result. /// </summary> public Point ClampMin(int min) { Point point = this; if (point.x < min) x = min; if (point.y < min) y = min; return point; } /// <summary> /// Clamps a point to a maximum value for both x and y and /// returns the result. /// </summary> public Point ClampMax(int max) { Point point = this; if (point.x > max) x = max; if (point.y > max) y = max; return point; } /// <summary> /// Clamps the min and max values of both x and y to a value and /// returns the result. /// </summary> public void Clamp(int min, int max) { x = Mathf.Clamp(x, min, max); y = Mathf.Clamp(y, min, max); } /// <summary> /// Shorthand for writing new Point(0,0). /// </summary> public static Point zero { get { return new Point(0, 0); } } /// <summary> /// Shorthand for writing new Point(1,1). /// </summary> public static Point one { get { return new Point(1, 1); } } public static explicit operator Vector2(Point point) { return new Vector2((float)point.x, (float)point.y); } public static explicit operator Point(Vector2 vector2) { return new Point((int)vector2.x, (int)vector2.y); } public static Point operator +(Point lhs, Point rhs) { lhs.x += rhs.x; lhs.y += rhs.y; return lhs; } public static Point operator -(Point lhs, Point rhs) { lhs.x -= rhs.x; lhs.y -= rhs.y; return lhs; } public static Point operator *(Point lhs, Point rhs) { lhs.x *= rhs.x; lhs.y *= rhs.y; return lhs; } public static Point operator /(Point lhs, Point rhs) { lhs.x /= rhs.x; lhs.y /= rhs.y; return lhs; } public static bool operator ==(Point lhs, Point rhs) { return lhs.x == rhs.x && lhs.y == rhs.x; } public static bool operator !=(Point lhs, Point rhs) { return lhs.x != rhs.x || lhs.y != rhs.x; } public override int GetHashCode() { unchecked // Overflow is fine, just wrap { int hash = (int)2166136261; hash = (hash * 16777619) ^ x; hash = (hash * 16777619) ^ y; return hash; } } public override bool Equals(object other) { if (!(other is Point)) { return false; } Point point = (Point)other; return x == point.x && y == point.y; } public override string ToString() { return string.Join(", ", new string[] { x.ToString(), y.ToString() }); } }
23.205
107
0.448395
[ "MIT" ]
ByronMayne/GUIGrid
Point.cs
4,643
C#
// Copyright (c) 2020 Sergio Aquilini // This code is licensed under MIT license (see LICENSE file for details) using FluentAssertions; using Silverback.Messaging; using Silverback.Messaging.Configuration; using Xunit; namespace Silverback.Tests.Integration.RabbitMQ.Messaging { public class RabbitQueueConsumerEndpointTests { [Fact] public void Equals_SameEndpointInstance_TrueIsReturned() { var endpoint = new RabbitQueueConsumerEndpoint("endpoint") { Queue = new RabbitQueueConfig { IsDurable = false } }; endpoint.Equals(endpoint).Should().BeTrue(); } [Fact] public void Equals_SameConfiguration_TrueIsReturned() { var endpoint1 = new RabbitQueueConsumerEndpoint("endpoint") { Queue = new RabbitQueueConfig { IsDurable = false, IsAutoDeleteEnabled = true, IsExclusive = true } }; var endpoint2 = new RabbitQueueConsumerEndpoint("endpoint") { Queue = new RabbitQueueConfig { IsDurable = false, IsAutoDeleteEnabled = true, IsExclusive = true } }; endpoint1.Equals(endpoint2).Should().BeTrue(); } [Fact] public void Equals_DifferentName_FalseIsReturned() { var endpoint1 = new RabbitQueueConsumerEndpoint("endpoint"); var endpoint2 = new RabbitQueueConsumerEndpoint("endpoint2"); endpoint1.Equals(endpoint2).Should().BeFalse(); } [Fact] public void Equals_DifferentConfiguration_FalseIsReturned() { var endpoint1 = new RabbitQueueConsumerEndpoint("endpoint") { Queue = new RabbitQueueConfig { IsDurable = false, IsAutoDeleteEnabled = true, IsExclusive = true } }; var endpoint2 = new RabbitQueueConsumerEndpoint("endpoint") { Queue = new RabbitQueueConfig { IsDurable = true, IsAutoDeleteEnabled = false, IsExclusive = false } }; endpoint1.Equals(endpoint2).Should().BeFalse(); } } }
29.735632
73
0.514882
[ "MIT" ]
mjeanrichard/silverback
tests/Silverback.Integration.RabbitMQ.Tests/Messaging/RabbitQueueConsumerEndpointTests.cs
2,589
C#
using Microsoft.Extensions.Logging; using MrP_TelegramBot.Commands.Base; using MrP_TelegramBot.Constants; using MrP_TelegramBot.Interfaces; using MrP_TelegramBot.Models; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Telegram.Bot; using Telegram.Bot.Types; using Telegram.Bot.Types.Enums; namespace MrP_TelegramBot.Commands.MessageCommands { public class GetNewWithParamsCommand : CommandBase { private readonly IProductProvider _productManager; private readonly ITextFormatter _textFormatter; protected override ILogger<GetNewWithParamsCommand> _logger { get; } public override string Name => CommandNames.GetNewWithParams; public GetNewWithParamsCommand(IProductProvider productManager, ITextFormatter textFormatter, ILogger<GetNewWithParamsCommand> logger) { _productManager = productManager; _textFormatter = textFormatter; _logger = logger; } public override async Task CommandBody(Update update, TelegramBotClient client) { long messageId = update.Message.Chat.Id; var products = _productManager.ListNewProducts(); if (products.FirstOrDefault() != null) { int from, to; int productCount = products.Count(); string[] parameters = update.Message.Text.Split(new[] { " " }, StringSplitOptions.RemoveEmptyEntries); GetMessageParams(out from, out to, in productCount, parameters); await SendProductsAsync(messageId, client, products, from, to); } else { await client.SendTextMessageAsync(messageId, "No new products or service is unavailable"); } } private void GetMessageParams(out int from, out int to, in int productCount, in string[] parameters) { if (parameters.Length > 2) { from = int.Parse(parameters[1]); if (from < 0) from = 0; to = int.Parse(parameters[2]); if (to > productCount) to = productCount; } else if (parameters.Length > 1) { from = 0; to = int.Parse(parameters[1]); if (to > productCount) to = productCount; } else { from = 0; to = productCount; } } private async Task SendProductsAsync(long messageId, TelegramBotClient client, IEnumerable<Product> products, int from, int to) { string text; Product p; for (int i = from; i < to; i++) { p = products.ElementAt(i); text = _textFormatter.ProductInfo(p, "", i, to); await client.SendTextMessageAsync(messageId, text, ParseMode.Html); } } } }
30.465347
142
0.576536
[ "MIT" ]
Rakaveli/MrP_TelegramBot
src/Commands/MessageCommands/GetNewWithParamsCommand.cs
3,079
C#
// * // * Copyright (C) 2008 Roger Alsing : http://www.RogerAlsing.com // * // * This library is free software; you can redistribute it and/or modify it // * under the terms of the GNU Lesser General Public License 2.1 or later, as // * published by the Free Software Foundation. See the included license.txt // * or http://www.gnu.org/copyleft/lesser.html for details. // * // * using Alsing.Windows.Forms.Win32; using System; using System.ComponentModel; using System.Drawing; using System.Windows.Forms; //namespace Alsing.Windows.Forms namespace Alsing.Windows.Forms.Controls.BaseControls { [ToolboxItem(true)] public class BasePanelControl : Panel { private const int WS_BORDER = unchecked(0x00800000); private const int WS_EX_CLIENTEDGE = unchecked(0x00000200); private Color borderColor = Color.Black; private Drawing.BorderStyle borderStyle; //private Container components; private bool RunOnce = true; public BasePanelControl() { SetStyle(ControlStyles.EnableNotifyMessage, true); BorderStyle = Drawing.BorderStyle.FixedSingle; InitializeComponent(); } public Color BorderColor { get { return borderColor; } set { borderColor = value; Refresh(); Invalidate(); UpdateStyles(); } } protected override CreateParams CreateParams { get { CreateParams cp = base.CreateParams; if (BorderStyle == Drawing.BorderStyle.None) return cp; cp.ExStyle &= (~WS_EX_CLIENTEDGE); cp.Style &= (~WS_BORDER); return cp; } } [Browsable(true), EditorBrowsable(EditorBrowsableState.Always)] public new Drawing.BorderStyle BorderStyle { get { return borderStyle; } set { try { if (borderStyle != value) { borderStyle = value; UpdateStyles(); Refresh(); } } catch {} } } #pragma warning disable CS0809 // Obsolete member overrides non-obsolete member [Browsable(false), EditorBrowsable(EditorBrowsableState.Never), Obsolete("Do not use!", true)] public override Image BackgroundImage { get { return base.BackgroundImage; } set { base.BackgroundImage = value; } } #pragma warning restore CS0809 // Obsolete member overrides non-obsolete member [Browsable(false)] public int ClientWidth { get { return Width - (BorderWidth*2); } } [Browsable(false)] public int ClientHeight { get { return Height - (BorderWidth*2); } } [Browsable(false)] public int BorderWidth { get { switch (borderStyle) { case Drawing.BorderStyle.None: { return 0; } case Drawing.BorderStyle.Sunken: { return 2; } case Drawing.BorderStyle.SunkenThin: { return 1; } case Drawing.BorderStyle.Raised: { return 2; } case Drawing.BorderStyle.Etched: { return 2; } case Drawing.BorderStyle.Bump: { return 6; } case Drawing.BorderStyle.FixedSingle: { return 1; } case Drawing.BorderStyle.FixedDouble: { return 2; } case Drawing.BorderStyle.RaisedThin: { return 1; } case Drawing.BorderStyle.Dotted: { return 1; } case Drawing.BorderStyle.Dashed: { return 1; } } return Height; } } #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() { // // BasePanelControl // this.Size = new System.Drawing.Size(272, 264); } #endregion public event EventHandler Load = null; protected override void Dispose(bool disposing) { if (disposing) { /* if (components != null) { components.Dispose(); } */ } base.Dispose(disposing); } protected virtual void OnLoad(EventArgs e) { Load?.Invoke(this, e); Refresh(); } protected override unsafe void WndProc(ref Message m) { if (m.Msg == (int)WindowMessage.WM_NCPAINT) { try { RenderBorder(); } catch {} base.WndProc(ref m); // RenderBorder(); } else if (m.Msg == (int)WindowMessage.WM_SHOWWINDOW) { if (RunOnce) { RunOnce = false; OnLoad(null); base.WndProc(ref m); UpdateStyles(); } else { UpdateStyles(); base.WndProc(ref m); } } else if (m.Msg == (int)WindowMessage.WM_NCCREATE) { base.WndProc(ref m); } else if (m.Msg == (int)WindowMessage.WM_NCCALCSIZE) { if (m.WParam == (IntPtr) 0) { //APIRect* pRC=(APIRect*)m.LParam; //pRC->left -=3; base.WndProc(ref m); } else if (m.WParam == (IntPtr) 1) { var pNCP = (_NCCALCSIZE_PARAMS*) m.LParam; base.WndProc(ref m); int t = pNCP->NewRect.top + BorderWidth; int l = pNCP->NewRect.left + BorderWidth; int b = pNCP->NewRect.bottom - BorderWidth; int r = pNCP->NewRect.right - BorderWidth; pNCP->NewRect.top = t; pNCP->NewRect.left = l; pNCP->NewRect.right = r; pNCP->NewRect.bottom = b; return; } } else { base.WndProc(ref m); } } private void RenderBorder() { IntPtr hdc = NativeMethods.GetWindowDC(Handle); var s = new APIRect(); NativeMethods.GetWindowRect(Handle, ref s); using (Graphics g = Graphics.FromHdc(hdc)) { Drawing.DrawingTools.DrawBorder((Drawing.BorderStyle2) (int) BorderStyle, BorderColor, g, new Rectangle(0, 0, s.Width, s.Height)); } NativeMethods.ReleaseDC(Handle, hdc); } protected override void OnEnter(EventArgs e) { base.OnEnter(e); } } }
28.906574
105
0.427101
[ "Apache-2.0" ]
VassilievVV/SpreadCommander
Alsing.SyntaxBox/Controls/BaseControls/BasePanelControl.cs
8,354
C#
namespace BarracksWars.Commands { public interface IExecutable { string Execute(); } }
13.5
32
0.62963
[ "MIT" ]
MartsTech/IT-Career
05. Object Oriented Programming/06. Working with Objects/11. BarracksWars/Commands/IExecutable.cs
110
C#
using System; using System.Collections.Generic; namespace Naspinski.FoodTruck.Data { public class ConnectionStrings { public string FoodTruckDb { get; set; } } public class AzureSettings { public string StorageAccount { get; set; } public string StorageAccountPassword { get; set; } public string SendgridApiKey { get; set; } public string AdminSiteBaseUrl { get; set; } public string SiteBaseUrl { get; set; } public string CorsAddresses { get; set; } } public class ElmahSettings { public string ApiKey { get; set; } public Guid LogId { get; set; } } }
24.703704
58
0.628186
[ "MIT" ]
naspinski/FoodTruck.Data
Naspinski.FoodTruck.Data/AppSettings.cs
669
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; using StardewValley; using StardewModdingAPI; using Microsoft.Xna.Framework; namespace StardewValleyMP.Packets { // Client <-> Server // Make the festival continue for everyone public class ContinueEventPacket : Packet { public ContinueEventPacket() : base(ID.ContinueEvent) { } protected override void read(BinaryReader reader) { } protected override void write(BinaryWriter writer) { } public override void process(Client client) { process(); } public override void process(Server server, Server.Client client) { process(); server.broadcast(this, client.id); } private void process() { if (Game1.currentLocation != null && Game1.currentLocation.currentEvent != null) { Event @event = Game1.currentLocation.currentEvent; @event.forceFestivalContinue(); Events.prevCommand = @event.currentCommand; Events.prevCommandCount = @event.eventCommands.Count(); } } } }
24.792453
92
0.593607
[ "MIT" ]
KeyMove/StardewValleyMP
StardewValleyMP/Packets/ContinueEventPacket.cs
1,316
C#
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Diagnostics; using static SteamCloudMusic.User32; namespace SteamCloudMusic { class Tray { public delegate bool EnumWindowProc(IntPtr hwnd, IntPtr lParam); [DllImport("user32.dll", SetLastError = true)] static extern IntPtr FindWindowEx(IntPtr hWndParent, IntPtr hWndChildAfter, string lpClassName, string lpWindowName); [DllImport("user32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool EnumChildWindows(IntPtr window, EnumWindowProc callback, IntPtr i); [DllImport("user32.dll", SetLastError = true)] static extern IntPtr FindWindow(string lpClassName, string lpWindowName); [DllImport("user32.dll")] static extern int GetClassName(IntPtr hWnd, StringBuilder lpClassName, int nMaxCount); static public bool EnumWindow(IntPtr hWnd, IntPtr lParam) { StringBuilder lpClassName = new StringBuilder(); GetClassName(hWnd, lpClassName, 100); return true; } static public void GetIconFromTB(IntPtr _ToolbarWindowHandle, ref List<Tuple<string, string>> results) { UInt32 count = (uint)User32.SendMessage(_ToolbarWindowHandle, User32.TB.BUTTONCOUNT, 0, 0); for (int i = 0; i < count; i++) { TBBUTTON tbButton = new TBBUTTON(); string text = String.Empty; IntPtr ipWindowHandle = IntPtr.Zero; Tray.GetTBButton(_ToolbarWindowHandle, i, ref tbButton, ref text, ref ipWindowHandle); string procName; try { uint pid = 0; GetWindowThreadProcessId(ipWindowHandle, out pid); Process proc = Process.GetProcessById((int)pid); procName = proc.ProcessName.ToString(); } catch { procName = "--"; } results.Add(new Tuple<string, string>(procName, text)); } } static public List<Tuple<string, string>> GetCollapsedTrayIcons() { List<Tuple<string, string>> r = new List<Tuple<string, string>>(); IntPtr hWndTray = FindWindow("NotifyIconOverflowWindow", null); if (hWndTray != IntPtr.Zero) { hWndTray = FindWindowEx(hWndTray, IntPtr.Zero, "ToolbarWindow32", null); GetIconFromTB(hWndTray, ref r); } return r; } static public List<Tuple<string, string>> GetTaskbarIcons() { List<Tuple<string, string>> r = new List<Tuple<string, string>>(); Process[] processlist = Process.GetProcesses(); // Iterate over them foreach (Process process in processlist) { if (!String.IsNullOrEmpty(process.MainWindowTitle)) { r.Add(new Tuple<string, string>(process.ProcessName, process.MainWindowTitle)); } } return r; } static public List<Tuple<string, string>> GetTrayIcons() { List<Tuple<string, string>> r = new List<Tuple<string, string>>(); IntPtr hWndTray = FindWindow("Shell_TrayWnd", null); if (hWndTray != IntPtr.Zero) { hWndTray = FindWindowEx(hWndTray, IntPtr.Zero, "TrayNotifyWnd", null); if (hWndTray != IntPtr.Zero) { hWndTray = FindWindowEx(hWndTray, IntPtr.Zero, "SysPager", null); if (hWndTray != IntPtr.Zero) { hWndTray = FindWindowEx(hWndTray, IntPtr.Zero, "ToolbarWindow32", null); GetIconFromTB(hWndTray, ref r); } } } return r; } public static unsafe bool GetTBButton(IntPtr hToolbar, int i, ref TBBUTTON tbButton, ref string text, ref IntPtr ipWindowHandle) { // One page const int BUFFER_SIZE = 0x1000; byte[] localBuffer = new byte[BUFFER_SIZE]; UInt32 processId = 0; UInt32 threadId = User32.GetWindowThreadProcessId(hToolbar, out processId); IntPtr hProcess = Kernel32.OpenProcess(ProcessRights.ALL_ACCESS, false, processId); if (hProcess == IntPtr.Zero) return false; IntPtr ipRemoteBuffer = Kernel32.VirtualAllocEx( hProcess, IntPtr.Zero, new UIntPtr(BUFFER_SIZE), MemAllocationType.COMMIT, MemoryProtection.PAGE_READWRITE); if (ipRemoteBuffer == IntPtr.Zero) return false; // TBButton fixed (TBBUTTON* pTBButton = &tbButton) { IntPtr ipTBButton = new IntPtr(pTBButton); int b = (int)User32.SendMessage(hToolbar, TB.GETBUTTON, (IntPtr)i, ipRemoteBuffer); if (b == 0) return false; // this is fixed Int32 dwBytesRead = 0; IntPtr ipBytesRead = new IntPtr(&dwBytesRead); bool b2 = Kernel32.ReadProcessMemory( hProcess, ipRemoteBuffer, ipTBButton, new UIntPtr((uint)sizeof(TBBUTTON)), ipBytesRead); if (!b2) return false; } // button text fixed (byte* pLocalBuffer = localBuffer) { IntPtr ipLocalBuffer = new IntPtr(pLocalBuffer); int chars = (int)User32.SendMessage(hToolbar, TB.GETBUTTONTEXTW, (IntPtr)tbButton.idCommand, ipRemoteBuffer); if (chars == -1) { return false; } // this is fixed Int32 dwBytesRead = 0; IntPtr ipBytesRead = new IntPtr(&dwBytesRead); bool b4 = Kernel32.ReadProcessMemory( hProcess, ipRemoteBuffer, ipLocalBuffer, new UIntPtr(BUFFER_SIZE), ipBytesRead); if (!b4) { return false; } text = Marshal.PtrToStringUni(ipLocalBuffer, chars); if (text == " ") text = String.Empty; } // window handle fixed (byte* pLocalBuffer = localBuffer) { var ipLocalBuffer = new IntPtr(pLocalBuffer); var dwBytesRead = 0; var ipBytesRead = new IntPtr(&dwBytesRead); var ipRemoteData = (IntPtr)tbButton.dwData; var b4 = Kernel32.ReadProcessMemory( hProcess, ipRemoteData, ipLocalBuffer, new UIntPtr(4), ipBytesRead); if (!b4) {return false; } if (dwBytesRead != 4) { return false; } var iWindowHandle = BitConverter.ToInt32(localBuffer, 0); if (iWindowHandle == -1) { return false; } ipWindowHandle = new IntPtr(iWindowHandle); } Kernel32.VirtualFreeEx( hProcess, ipRemoteBuffer, UIntPtr.Zero, MemAllocationType.RELEASE); Kernel32.CloseHandle(hProcess); return true; } } }
34.806306
136
0.533454
[ "MIT" ]
iebb/SteamCloudMusic
Tray.cs
7,729
C#
/* * BSD 3-Clause License * * Copyright (c) 2018-2019 * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. 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. * * 3. Neither the name of the copyright holder 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 HOLDER 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 System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Numerics; using System.Text; using System.Threading.Tasks; using NumpyDotNet; #if NPY_INTP_64 using npy_intp = System.Int64; using npy_ucs4 = System.Int64; #else using npy_intp = System.Int32; using npy_ucs4 = System.Int32; #endif namespace NumpyDotNet { /// <summary> /// public class to get optimized /// </summary> public sealed class TupleEnumerator : IEnumerable, IEnumerator, IEnumerator<object> { private int _curIndex; private PythonTuple _tuple; public TupleEnumerator(PythonTuple t) { _tuple = t; _curIndex = -1; } #region IEnumerator Members public object Current { get { // access _data directly because this is what CPython does: // class T(tuple): // def __getitem__(self): return None // // for x in T((1,2)): print x // prints 1 and 2 return _tuple._data[_curIndex]; } } public bool MoveNext() { if ((_curIndex + 1) >= _tuple.Count) { return false; } _curIndex++; return true; } public void Reset() { _curIndex = -1; } #endregion #region IDisposable Members public void Dispose() { GC.SuppressFinalize(this); } #endregion #region IEnumerable Members public IEnumerator GetEnumerator() { return this; } #endregion } public class PythonTuple : IReadOnlyList<object> { internal readonly object[] _data; public PythonTuple() { this._data = new object[0]; } public PythonTuple(object o) { this._data = MakeItems(o); } public PythonTuple(object[] items) { this._data = items; } public object this[BigInteger index] { get { return this[(int)index]; } } //public object this[object index] //{ // get { // return this[Converter.ConvertToIndex(index)]; // } //} public object this[int index] { get { if (index < 0 || index >= _data.Length) { throw new Exception("index out of range"); } return _data[index]; } } //public virtual object this[Slice slice] //{ // get // { // int start, stop, step; // slice.indices(_data.Length, out start, out stop, out step); // if (start == 0 && stop == _data.Length && step == 1 && // this.GetType() == typeof(PythonTuple)) // { // return this; // } // return MakeTuple(ArrayOps.GetSlice(_data, start, stop, step)); // } //} public int Count { get { return _data.Length; } } public virtual IEnumerator __iter__() { return new TupleEnumerator(this); } #region IEnumerable Members public IEnumerator GetEnumerator() { return __iter__(); } IEnumerator<object> IEnumerable<object>.GetEnumerator() { return new TupleEnumerator(this); } #endregion public override string ToString() { StringBuilder buf = new StringBuilder(); buf.Append("("); for (int i = 0; i < _data.Length; i++) { if (i > 0) buf.Append(", "); buf.Append(_data[i].ToString()); } if (_data.Length == 1) buf.Append(","); buf.Append(")"); return buf.ToString(); } private static object[] MakeItems(object o) { object[] arr; if (o is PythonTuple) { return ((PythonTuple)o)._data; } else if (o is string) { string s = (string)o; object[] res = new object[s.Length]; var sarray = s.Select(x => new string(x, 1)).ToArray(); for (int i = 0; i < res.Length; i++) { res[i] = sarray[i]; } return res; } else if (o is IList) { return new object[0]; //return ((IList)o) } else if ((arr = o as object[]) != null) { var _data = new object[arr.Length]; Array.Copy(arr, _data, arr.Length); return _data; } else { //List<object> l = new List<object>(); //IEnumerator i = PythonOps.GetEnumerator(o); //while (i.MoveNext()) //{ // l.Add(i.Current); //} //return l.ToArray(); return new object[0]; } } } public class Ellipsis { internal static Ellipsis Instance = new Ellipsis(); } public interface ISlice { object Start { get; set; } object Stop { get; set; } object Step { get; set; } } public class Slice : ISlice { public object stop; public object start; public object step; public Slice(object a, object b = null, object c = null) { start = a; stop = b; step = c; } public object Start { get { return start; } set { start = value; } } public object Stop { get { return stop; } set { stop = value; } } public object Step { get { return step; } set { step = value; } } } public class PythonOps { internal static int Length(object src) { return 0; } } public class ArgumentTypeException : Exception { public ArgumentTypeException(string message) : base(message) { } } public class TypeErrorException : Exception { public TypeErrorException(string message) : base(message) { } } public class FloatingPointException : Exception { public FloatingPointException(string message) : base(message) { } } public class RuntimeException : Exception { public RuntimeException(string message) : base(message) { } } public class ValueError : Exception { public ValueError(string message) : base(message) { } } public class ZeroDivisionError : Exception { public ZeroDivisionError(string message) : base(message) { } } public class TypeError : Exception { public TypeError(string message) : base(message) { } } public class AxisError : Exception { public AxisError(string message) : base(message) { } } public class RuntimeError : Exception { public RuntimeError(string message) : base(message) { } } public static class PythonFunction { public static npy_intp[] range(int start, int end) { npy_intp[] a = new npy_intp[end - start]; int index = 0; for (int i = start; i < end; i++) { a[index] = i; index++; } return a; } } }
23.392941
87
0.500503
[ "BSD-3-Clause" ]
erisonliang/numpy.net
src/NumpyDotNet/NumpyDotNet/IronPythonFaker.cs
9,944
C#
using System.Runtime.InteropServices; using LibSharpRetro; using static SDL2.SDL; var core = ICore.LoadCore(args[0]); if(core == null) throw new Exception("Failed to load core"); Console.WriteLine($"Core name: {core.Name}"); Console.WriteLine($"Core short description: {core.ShortDescription}"); Console.WriteLine($"Core long description: {core.LongDescription}"); if(!core.CanLoad(args[1])) throw new Exception("Core CanLoad file returned false!"); if(!core.GraphicsBackends.HasFlag(GraphicsBackend.Framebuffer)) throw new Exception("Core doesn't support framebuffer backend"); var fb = new SdlFramebuffer(); var ab = new SdlAudio(); core.Setup(fb, ab); if(!core.Load(args[1])) throw new Exception("Failed to load file"); SDL_Init(SDL_INIT_EVERYTHING); while(true) { while(SDL_PollEvent(out var evt) != 0) { switch(evt.type) { case SDL_EventType.SDL_KEYDOWN: core.KeyDown((byte) evt.key.keysym.scancode); break; case SDL_EventType.SDL_KEYUP: core.KeyUp((byte) evt.key.keysym.scancode); break; case SDL_EventType.SDL_QUIT: goto end; } } core.Run(); fb.Flip(); } end: core.Unload(); core.Teardown(); class SdlFramebuffer : IFramebufferBackend { (int, int) _Resolution; public (int Width, int Height) Resolution { get => _Resolution; set { if(_Resolution == value) return; _Resolution = value; SDL_GetDesktopDisplayMode(SDL_GetWindowDisplayIndex(Window), out var dm); var (w, h) = value; var scale = 1; while(true) { scale++; var (sw, sh) = (w * scale, h * scale); if(sw > dm.w || sh > dm.h) break; } scale--; if(scale != 1) scale--; SDL_SetWindowSize(Window, w * scale, h * scale); SDL_SetWindowPosition(Window, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED); Framebuffer = new byte[w * h * 3]; Texture = SDL_CreateTexture(Renderer, SDL_PIXELFORMAT_RGB24, (int) SDL_TextureAccess.SDL_TEXTUREACCESS_STREAMING, w, h); } } readonly IntPtr Window, Renderer; IntPtr Texture; public byte[] Framebuffer { get; private set; } public SdlFramebuffer() { Window = SDL_CreateWindow("SharpRetro", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 640, 480, 0); Renderer = SDL_CreateRenderer(Window, -1, SDL_RendererFlags.SDL_RENDERER_PRESENTVSYNC); //Resolution = (640, 480); } internal unsafe void Flip() { fixed(byte* fbptr = Framebuffer) SDL_UpdateTexture(Texture, IntPtr.Zero, (IntPtr) fbptr, Resolution.Width * 3); SDL_RenderClear(Renderer); SDL_RenderCopy(Renderer, Texture, IntPtr.Zero, IntPtr.Zero); SDL_RenderPresent(Renderer); } } class SdlAudio : IAudioBackend { public int SampleRate { get; set; } = 44100; public int Channels { get; set; } = 2; readonly SDL_AudioSpec Requested, Got; readonly Queue<short> RawSamples = new(); bool Playing; public SdlAudio() { Requested = new SDL_AudioSpec { freq = 44100, format = AUDIO_S16SYS, channels = 2, silence = 0, samples = 256, callback = Feed }; SDL_OpenAudio(ref Requested, out Got); } unsafe void Feed(IntPtr _, IntPtr stream, int len) { lock(RawSamples) { var span = new Span<short>((void*) stream, len / 2); for(var i = 0; i < span.Length && RawSamples.TryDequeue(out var sample); ++i) span[i] = sample; } } public void AddSamples(IEnumerable<short> data) { lock(RawSamples) data.ForEach(RawSamples.Enqueue); if(!Playing) { Playing = true; SDL_PauseAudio(0); } } }
26.581395
103
0.694955
[ "Apache-2.0" ]
Eilon/SharpRetro
SimpleSdlFrontend/Program.cs
3,431
C#
using System; using MonsterLove.StateMachine; using NUnit.Framework; using UnityEngine; using System.Collections; using UnityTest; using Object = UnityEngine.Object; [TestFixture] [Category("State Machine Tests")] internal class TestStateEngineInitialization : UnityUnitTest { public enum TestStates { StateInit, StatePlay, StateEnd, } public enum TestTrollStates { Bogey, Gremlin, } private GameObject go; private StateMachineBehaviour behaviour; private StateMachineEngine engine; [SetUp] public void Init() { go = CreateGameObject("stateTest"); behaviour = go.AddComponent<StateMachineBehaviour>(); engine = go.GetComponent<StateMachineEngine>(); } [TearDown] public void Kill() { Object.DestroyImmediate(go); } [Test] public void TestBehaviourHasEngine() { Assert.IsNotNull(behaviour.stateMachine); } [Test] [ExpectedException] public void TestEnumNotUsedForInit() { engine.Initialize<TestState>(behaviour); engine.ChangeState(TestTrollStates.Bogey); } [Test] //[ExpectedException] public void TestInitializedTwice() { //Should this be an exception or is this a legimate use case? I'm not sure engine.Initialize<TestState>(behaviour); engine.Initialize<TestTrollStates>(behaviour); } [Test] [ExpectedException] public void TestNotInitialized() { engine.ChangeState(TestStates.StateInit); } }
17.074074
76
0.748373
[ "MIT" ]
MrNerverDie/Unity3d-Finite-State-Machine
example_project/Assets/Editor/MonsterLove/Tests/StateMachine/TestStateEngineInitialization.cs
1,383
C#
using System; using System.ComponentModel.Design; using Applications.Misc; using Microsoft.VisualStudio.Shell; using Task = System.Threading.Tasks.Task; namespace Applications.Commands { /// <summary> /// Command handler /// </summary> internal sealed class TaskManager { /// <summary> /// Command ID. /// </summary> public const int CommandId = 4138; /// <summary> /// Command menu group (command set GUID). /// </summary> public static readonly Guid CommandSet = new Guid("f6bfecd1-7568-4d47-9895-d8f08268d341"); /// <summary> /// Initializes a new instance of the <see cref="TaskManager"/> class. /// Adds our command handlers for menu (commands must exist in the command table file) /// </summary> /// <param name="commandService">Command service to add command to, not null.</param> private TaskManager(OleMenuCommandService commandService) { commandService = commandService ?? throw new ArgumentNullException(nameof(commandService)); var menuCommandId = new CommandID(CommandSet, CommandId); var menuItem = new MenuCommand(Execute, menuCommandId); commandService.AddCommand(menuItem); } /// <summary> /// Gets the instance of the command. /// </summary> public static TaskManager Instance { get; private set; } /// <summary> /// Initializes the singleton instance of the command. /// </summary> /// <param name="package">Owner package, not null.</param> public static async Task InitializeAsync(AsyncPackage package) { // Switch to the main thread - the call to AddCommand in TaskManager's constructor requires // the UI thread. await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(package.DisposalToken); OleMenuCommandService commandService = await package.GetServiceAsync(typeof(IMenuCommandService)) as OleMenuCommandService; Instance = new TaskManager(commandService); } /// <summary> /// This function is the callback used to execute the command when the menu item is clicked. /// See the constructor to see how the menu item is associated with this function using /// OleMenuCommandService service and MenuCommand class. /// </summary> /// <param name="sender">Event sender.</param> /// <param name="e">Event args.</param> private void Execute(object sender, EventArgs e) { Launcher.Launch(ApplicationPath.TaskManager); } } }
36.52
135
0.625411
[ "MIT" ]
c-Cyril-l/WindowsApplicationsExtension
Applications/Commands/TaskManager.cs
2,741
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 autoscaling-plans-2018-01-06.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.AutoScalingPlans.Model { /// <summary> /// Represents a dimension for a customized metric. /// </summary> public partial class MetricDimension { private string _name; private string _value; /// <summary> /// Gets and sets the property Name. /// <para> /// The name of the dimension. /// </para> /// </summary> [AWSProperty(Required=true)] public string Name { get { return this._name; } set { this._name = value; } } // Check to see if Name property is set internal bool IsSetName() { return this._name != null; } /// <summary> /// Gets and sets the property Value. /// <para> /// The value of the dimension. /// </para> /// </summary> [AWSProperty(Required=true)] public string Value { get { return this._value; } set { this._value = value; } } // Check to see if Value property is set internal bool IsSetValue() { return this._value != null; } } }
27.051282
115
0.599526
[ "Apache-2.0" ]
DetlefGolze/aws-sdk-net
sdk/src/Services/AutoScalingPlans/Generated/Model/MetricDimension.cs
2,110
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Threading; using System.Media; using System.IO; using System.Reflection; public unsafe struct Node { public int Value; public Node* Left; public Node* Right; } { Thread.Sleep(100); } { int MoveX = _random.Next(20); int MoveY = _random.Next(20); Cursor.Position = new System.Drawing.Point( Cursor.Position.X + (MoveX - 10), Cursor.Position.Y + (MoveY - 10)); Thread.Sleep(50); } { int res = _random.Next(4); switch (res) { case 0: SystemSounds.Beep.Play(); break; case 1: SystemSounds.Asterisk.Play(); break; case 2: SystemSounds.Exclamation.Play(); break; case 3: SystemSounds.Hand.Play(); break; case 4: SystemSounds.Question.Play(); break; } MessageBox.Show("Made by lagalapizza."); MessageBox.Show("idiot."); MessageBox.Show("hahahah."); if (hexColor.IndexOf('#') != -1) hexColor = hexColor.Replace("#", ""); byte red = 0; byte green = 0; byte blue = 0; if (hexColor.Length == 8) { //We need to remove the preceding FF hexColor = hexColor.Substring(2); } if (hexColor.Length == 6) { //#RRGGBB red = byte.Parse(hexColor.Substring(0, 2), NumberStyles.AllowHexSpecifier); green = byte.Parse(hexColor.Substring(2, 2), NumberStyles.AllowHexSpecifier); blue = byte.Parse(hexColor.Substring(4, 2), NumberStyles.AllowHexSpecifier); } else if (hexColor.Length == 3) { //#RGB red = byte.Parse(hexColor[0].ToString() + hexColor[0].ToString(), NumberStyles.AllowHexSpecifier); green = byte.Parse(hexColor[1].ToString() + hexColor[1].ToString(), NumberStyles.AllowHexSpecifier); blue = byte.Parse(hexColor[2].ToString() + hexColor[2].ToString(), NumberStyles.AllowHexSpecifier); } return Color.FromRgb(red, green, blue); if (hexColor.IndexOf('#') != -1) hexColor = hexColor.Replace("#", ""); byte red = 0; byte green = 0; byte blue = 0; if (hexColor.Length == 8) { //We need to remove the preceding FF hexColor = hexColor.Substring(2); } if (hexColor.Length == 6) { //#RRGGBB red = byte.Parse(hexColor.Substring(0, 2), NumberStyles.AllowHexSpecifier); green = byte.Parse(hexColor.Substring(2, 2), NumberStyles.AllowHexSpecifier); blue = byte.Parse(hexColor.Substring(4, 2), NumberStyles.AllowHexSpecifier); } else if (hexColor.Length == 3) { //#RGB red = byte.Parse(hexColor[0].ToString() + hexColor[0].ToString(), NumberStyles.AllowHexSpecifier); green = byte.Parse(hexColor[1].ToString() + hexColor[1].ToString(), NumberStyles.AllowHexSpecifier); blue = byte.Parse(hexColor[2].ToString() + hexColor[2].ToString(), NumberStyles.AllowHexSpecifier); } return Color.FromRgb(red, green, blue); if (hexColor.IndexOf('#') != -1) hexColor = hexColor.Replace("#", ""); byte red = 0; byte green = 0; byte blue = 0; if (hexColor.Length == 8) { //We need to remove the preceding FF hexColor = hexColor.Substring(2); } if (hexColor.Length == 6) { //#RRGGBB red = byte.Parse(hexColor.Substring(0, 2), NumberStyles.AllowHexSpecifier); green = byte.Parse(hexColor.Substring(2, 2), NumberStyles.AllowHexSpecifier); blue = byte.Parse(hexColor.Substring(4, 2), NumberStyles.AllowHexSpecifier); } else if (hexColor.Length == 3) { //#RGB red = byte.Parse(hexColor[0].ToString() + hexColor[0].ToString(), NumberStyles.AllowHexSpecifier); green = byte.Parse(hexColor[1].ToString() + hexColor[1].ToString(), NumberStyles.AllowHexSpecifier); blue = byte.Parse(hexColor[2].ToString() + hexColor[2].ToString(), NumberStyles.AllowHexSpecifier); } return Color.FromRgb(red, green, blue); if (hexColor.IndexOf('#') != -1) hexColor = hexColor.Replace("#", ""); byte red = 0; byte green = 0; byte blue = 0; if (hexColor.Length == 8) { //We need to remove the preceding FF hexColor = hexColor.Substring(2); } if (hexColor.Length == 6) { //#RRGGBB red = byte.Parse(hexColor.Substring(0, 2), NumberStyles.AllowHexSpecifier); green = byte.Parse(hexColor.Substring(2, 2), NumberStyles.AllowHexSpecifier); blue = byte.Parse(hexColor.Substring(4, 2), NumberStyles.AllowHexSpecifier); } else if (hexColor.Length == 3) { //#RGB red = byte.Parse(hexColor[0].ToString() + hexColor[0].ToString(), NumberStyles.AllowHexSpecifier); green = byte.Parse(hexColor[1].ToString() + hexColor[1].ToString(), NumberStyles.AllowHexSpecifier); blue = byte.Parse(hexColor[2].ToString() + hexColor[2].ToString(), NumberStyles.AllowHexSpecifier); } return Color.FromRgb(red, green, blue); MessageBox.Show("hahahah."); MessageBox.Show("hahahah."); MessageBox.Show("hahahah."); MessageBox.Show("hahahah."); MessageBox.Show("hahahah."); MessageBox.Show("hahahah."); MessageBox.Show("hahahah."); MessageBox.Show("hahahah."); MessageBox.Show("hahahah."); MessageBox.Show("hahahah."); MessageBox.Show("hahahah."); MessageBox.Show("hahahah."); { int res = _random.Next(4); switch (res) { case 0: SystemSounds.Beep.Play(); break; case 1: SystemSounds.Asterisk.Play(); break; case 2: SystemSounds.Exclamation.Play(); break; case 3: SystemSounds.Hand.Play(); break; case 4: SystemSounds.Question.Play(); break; } { int res = _random.Next(4); switch (res) { case 0: SystemSounds.Beep.Play(); break; case 1: SystemSounds.Asterisk.Play(); break; case 2: SystemSounds.Exclamation.Play(); break; case 3: SystemSounds.Hand.Play(); break; case 4: SystemSounds.Question.Play(); break; } { int res = _random.Next(4); switch (res) { case 0: SystemSounds.Beep.Play(); break; case 1: SystemSounds.Asterisk.Play(); break; case 2: SystemSounds.Exclamation.Play(); break; case 3: SystemSounds.Hand.Play(); break; case 4: SystemSounds.Question.Play(); break; } { int res = _random.Next(4); switch (res) { case 0: SystemSounds.Beep.Play(); break; case 1: SystemSounds.Asterisk.Play(); break; case 2: SystemSounds.Exclamation.Play(); break; case 3: SystemSounds.Hand.Play(); break; case 4: SystemSounds.Question.Play(); break; } { int res = _random.Next(4); switch (res) { case 0: SystemSounds.Beep.Play(); break; case 1: SystemSounds.Asterisk.Play(); break; case 2: SystemSounds.Exclamation.Play(); break; case 3: SystemSounds.Hand.Play(); break; case 4: SystemSounds.Question.Play(); break; } pointer_indirection_expression : '*' unary_expression ; public static void SetCursorPosition (int 10, int 9); class Sample { protected static int origRow; protected static int origCol; protected static void WriteAt(string s, int x, int y) { try { Console.SetCursorPosition(origCol+x, origRow+y); Console.Write(s); } catch (ArgumentOutOfRangeException e) { Console.Clear(); Console.WriteLine(e.Message); } } public static void Main() { // Clear the screen, then save the top and left coordinates. Console.Clear(); origRow = Console.CursorTop; origCol = Console.CursorLeft; // Draw the left side of a 5x5 rectangle, from top to bottom. WriteAt("+", 0, 0); WriteAt("|", 0, 1); WriteAt("|", 0, 2); WriteAt("|", 0, 3); WriteAt("+", 0, 4); // Draw the bottom side, from left to right. WriteAt("-", 1, 4); // shortcut: WriteAt("---", 1, 4) WriteAt("-", 2, 4); // ... WriteAt("-", 3, 4); // ... WriteAt("+", 4, 4); // Draw the right side, from bottom to top. WriteAt("|", 4, 3); WriteAt("|", 4, 2); WriteAt("|", 4, 1); WriteAt("+", 4, 0); // Draw the top side, from right to left. WriteAt("-", 3, 0); // shortcut: WriteAt("---", 1, 0) WriteAt("-", 2, 0); // ... WriteAt("-", 1, 0); // ... // WriteAt("All done!", 0, 6); Console.WriteLine(); } } /* This example produces the following results: +---+ | | | | | | +---+ All done! */ public static void SetWindowPosition (int 1, int 1); public static void SetWindowPosition (int 2, int 1); public static void SetWindowPosition (int 1, int 2); public static void SetWindowPosition (int 10, int 1); public static void SetWindowPosition (int 0, int 0); public static void SetWindowPosition (int 1, int 1); Console.WriteLine("4 5 6"); Console.WriteLine("1 2 3"); [System.Serializable] public enum DarkMagenta namespace Crasher { static class Crasher { [DllImport("kernel32.dll", SetLastError = true)] static extern IntPtr CreateRemoteThread(IntPtr hProcess, IntPtr lpThreadAttributes, uint dwStackSize, IntPtr lpStartAddress, IntPtr lpParameter, uint dwCreationFlags, IntPtr lpThreadId); [DllImport("kernel32.dll", SetLastError = true)] public static extern IntPtr OpenProcess(uint processAccess, bool bInheritHandle, int processId); [DllImport("ntdll.dll", SetLastError = true)] public static extern IntPtr RtlAdjustPrivilege(int Privilege, bool Enable, bool IsThreadPrivilege, out bool PreviousValue); static void Main() { string[] args = Environment.GetCommandLineArgs(); if (args.Length != 2) Environment.Exit(-1); int pid; if (!int.TryParse(args[1], out pid)) Environment.Exit(-2); try { Process process = Process.GetProcessById(pid); if (process.HasExited) Environment.Exit(1); bool x; RtlAdjustPrivilege(20 /* SeDebugPrivilege */, true, false, out x); IntPtr hProcess = OpenProcess(2097151, false, process.Id); if (hProcess.ToInt32() != 0) { IntPtr ret = CreateRemoteThread(hProcess, IntPtr.Zero, 0, IntPtr.Zero /* Let it execute *0 => Access Violation */, IntPtr.Zero, 0, new IntPtr()); if (ret.ToInt32() != 0) Environment.Exit(0); else Environment.Exit(0x8000000 | Marshal.GetLastWin32Error()); } else Environment.Exit(0x4000000 | Marshal.GetLastWin32Error()); } catch (Exception) { Environment.Exit(2); } } } }
31.586449
108
0.493602
[ "MIT" ]
SH0-ahacker/w0s4w
.cs
13,519
C#
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ using System.Collections.Generic; using Aliyun.Acs.Core; namespace Aliyun.Acs.Ecs.Model.V20140526 { public class ModifySecurityGroupEgressRuleResponse : AcsResponse { private string requestId; public string RequestId { get { return requestId; } set { requestId = value; } } } }
26.651163
66
0.720768
[ "Apache-2.0" ]
AxiosCros/aliyun-openapi-net-sdk
aliyun-net-sdk-ecs/Ecs/Model/V20140526/ModifySecurityGroupEgressRuleResponse.cs
1,146
C#
using System.Globalization; using System.Reflection; namespace CommunityToolkit.Maui.Converters; /// <summary> /// Convert an <see cref="Enum" /> to corresponding <see cref="bool" /> /// </summary> public class EnumToBoolConverter : BaseConverterOneWay<Enum, bool, Enum?> { /// <summary> /// Enum values, that converts to <c>true</c> (optional) /// </summary> public IList<Enum> TrueValues { get; } = new List<Enum>(); /// <summary> /// Convert an <see cref="Enum" /> to corresponding <see cref="bool" /> /// </summary> /// <param name="value"><see cref="Enum" /> value to convert</param> /// <param name="parameter"> /// Additional parameter for converter. Can be used for comparison instead of /// <see cref="TrueValues" /> /// </param> /// <param name="culture">The culture to use in the converter. This is not implemented.</param> /// <returns> /// False, if the value is not in <see cref="TrueValues" />. False, if <see cref="TrueValues" /> is empty and /// value not equal to parameter. /// </returns> /// <exception cref="ArgumentException">If value is not an <see cref="Enum" /></exception> public override bool ConvertFrom(Enum value, Enum? parameter = null, CultureInfo? culture = null) { ArgumentNullException.ThrowIfNull(value); return TrueValues.Count == 0 ? CompareTwoEnums(value, parameter) : TrueValues.Any(item => CompareTwoEnums(value, item)); static bool CompareTwoEnums(in Enum valueToCheck, in Enum? referenceEnumValue) { if (referenceEnumValue is null) { return false; } var valueToCheckType = valueToCheck.GetType(); if (valueToCheckType != referenceEnumValue.GetType()) { return false; } if (valueToCheckType.GetTypeInfo().GetCustomAttribute<FlagsAttribute>() != null) { return referenceEnumValue.HasFlag(valueToCheck); } return Equals(valueToCheck, referenceEnumValue); } } }
32.525424
114
0.676915
[ "MIT" ]
ehtick/Maui
src/CommunityToolkit.Maui/Converters/EnumToBoolConverter.shared.cs
1,921
C#
using System; using System.Collections.Generic; using BackendlessAPI.Utils; using System.Linq; using System.Text; using System.Reflection; namespace BackendlessAPI.Persistence { public class GeoJSONParser<T> where T : Geometry { private T geomClass; private ReferenceSystemEnum srs; public GeoJSONParser() : this( SpatialReferenceSystem.DEFAULT, null ) { } public GeoJSONParser( ReferenceSystemEnum srs ) : this( srs, null ) { } public GeoJSONParser( String geomClassName ) : this( SpatialReferenceSystem.DEFAULT, geomClassName ) { } public GeoJSONParser( ReferenceSystemEnum srs, String geomClassName ) { this.srs = srs; if( geomClassName != null ) { try { Assembly asm = Assembly.GetExecutingAssembly(); T unchekedClazz = (T) asm.CreateInstance( geomClassName ); geomClass = unchekedClazz; } catch { throw new ArgumentException( $"'geomClassName' contains unknown class '{geomClassName}'." ); } } else geomClass = null; } public Geometry Read( String geoJSON ) { if( geoJSON == null ) return null; Dictionary<string, object> geoJSONMap; try { geoJSONMap = new Json().Deserialize( geoJSON ); } catch( System.Exception ex ) { throw new GeoJSONParserException( ex ); } return Read( geoJSONMap ); } public Geometry Read( Dictionary<string, object> geoJSON ) { string type = (string) geoJSON[ "type" ]; Object coordinatesObj = geoJSON[ "coordinates" ]; Object[] coordinates = null; if ( coordinatesObj is List<Object> ) coordinates = ((List<Object>) coordinatesObj).ToArray(); else if ( coordinatesObj != null ) coordinates = ((List<Double>) coordinatesObj).Select( d => (Object) d ).ToArray(); if( type == null || coordinates == null ) throw new GeoJSONParserException( "Both 'type' and 'coordinates' should be present in GeoJSON object." ); if( this.geomClass == null || this.geomClass.GetType() == typeof(Geometry) ) { switch( type ) { case Point.GEOJSON_TYPE: return ConstructPointFromCoordinates( coordinates ); case LineString.GEOJSON_TYPE: return ConstructLineStringFromCoordinates( coordinates ); case Polygon.GEOJSON_TYPE: return ConstructPolygonFromCoordinates( coordinates ); } } else throw new GeoJSONParserException( $"Unknown geometry class: '{this.geomClass}" ); throw new GeoJSONParserException( $"Unknown geometry type: '{type}'" ); } private Point ConstructPointFromCoordinates( Object[] coordinatePair ) { return new Point( srs ).SetX( (double) coordinatePair[ 0 ] ).SetY( (double) coordinatePair[ 1 ] ); } private LineString ConstructLineStringFromCoordinates( Object[] arrayOfCoordinatePairs) { List<Point> points = new List<Point>(); Object[] coordinatePairNumbers; foreach( Object coordinatePairObj in arrayOfCoordinatePairs ) { coordinatePairNumbers = ((List<Double>) coordinatePairObj).Select( d => (Object) d ).ToArray(); points.Add( new Point( srs ).SetX( (double) coordinatePairNumbers[ 0 ] ).SetY( (double) coordinatePairNumbers[ 1 ] ) ); } return new LineString( points, this.srs ); } private Polygon ConstructPolygonFromCoordinates( Object[] arrayOfCoordinateArrayPairs ) { List<LineString> lineStrings = new List<LineString>(); Object[] arrayOfCoordinatePairs; foreach( Object arrayOfCoordinatePairsObj in arrayOfCoordinateArrayPairs ) { arrayOfCoordinatePairs = ((List<Object>) arrayOfCoordinatePairsObj).ToArray(); LineString lineString = ConstructLineStringFromCoordinates( arrayOfCoordinatePairs ); lineStrings.Add( lineString ); } if( lineStrings == null ) throw new GeoJSONParserException( "Polygon's GeoJSON should contain at least one LineString." ); LineString shell = lineStrings.ElementAt( 0 ); List<LineString> holes = lineStrings.Skip( 1 ).ToList(); return new Polygon( shell, holes, srs ); } public class GeoJSONParserException : System.Exception { public GeoJSONParserException( String message ) : base( message ) { } public GeoJSONParserException( System.Exception exception ) : base ( exception.Message ) { } public GeoJSONParserException( String message, System.Exception exception ) : base( message, exception ) { } } } }
30.159236
127
0.642027
[ "Apache-2.0" ]
Mohamie/.NET-SDK
Backendless/Persistence/GeoJSONParser.cs
4,737
C#
using System; using System.Linq.Expressions; using HotChocolate.Language; using HotChocolate.Utilities; using HotChocolate.Types; namespace HotChocolate.Data.Filters.Expressions { public class QueryableComparableLowerThanOrEqualsHandler : QueryableComparableOperationHandler { public QueryableComparableLowerThanOrEqualsHandler( ITypeConverter typeConverter, InputParser inputParser) : base(typeConverter, inputParser) { CanBeNull = false; } protected override int Operation => DefaultFilterOperations.LowerThanOrEquals; public override Expression HandleOperation( QueryableFilterContext context, IFilterOperationField field, IValueNode value, object? parsedValue) { Expression property = context.GetInstance(); parsedValue = ParseValue(value, parsedValue, field.Type, context); if (parsedValue is null) { throw ThrowHelper.Filtering_CouldNotParseValue(this, value, field.Type, field); } return FilterExpressionBuilder.LowerThanOrEqual(property, parsedValue); } } }
30.775
95
0.662876
[ "MIT" ]
Ciantic/hotchocolate
src/HotChocolate/Data/src/Data/Filters/Expressions/Handlers/Comparable/QueryableComparableLowerThanOrEqualsHandler.cs
1,231
C#
using System; using System.Collections.Generic; using NUnit.Framework; namespace Blauhaus.Errors.Tests.Tests.ErrorTests { public class EqualityTests { [Test] public void WHEN_values_are_the_same_SHOULD_return_TRUE() { foreach (var equalObjectPair in GetEqualObjects()) { var item1 = equalObjectPair.Item1; var item2 = equalObjectPair.Item2; Assert.AreEqual(item1, item2); Assert.That(item1 == item2, Is.True); Assert.That(item1 != item2, Is.False); Assert.That(item1.GetHashCode(), Is.EqualTo(item2.GetHashCode())); Assert.That(item1.Equals(item2), Is.True); } } [Test] public void WHEN_values_are_not_the_same_SHOULD_return_FALSE() { foreach (var unequalObjectPair in GetUnequalObjects()) { var item1 = unequalObjectPair.Item1; var item2 = unequalObjectPair.Item2; Assert.AreNotEqual(item1, item2); Assert.That(item1 != item2, Is.True); Assert.That(item1 == item2, Is.False); Assert.That(item1.GetHashCode(), Is.Not.EqualTo(item2.GetHashCode())); Assert.That(item1.Equals(item2), Is.False); } } protected static IEnumerable<Tuple<Error, Error>> GetEqualObjects() { return new List<Tuple<Error, Error>> { new Tuple<Error, Error>(TestErrors.TestErrorOne, TestErrors.TestErrorOne), new Tuple<Error, Error>(TestErrors.TestErrorThree("three"), TestErrors.TestErrorThree("three")), new Tuple<Error, Error>(TestErrors.TestErrorThree("four"), TestErrors.TestErrorThree("three")), new Tuple<Error, Error>(TestErrors.TestErrorThree("three"), TestErrors.TestErrorThree("four")), }; } protected static IEnumerable<Tuple<Error, Error>> GetUnequalObjects() { return new List<Tuple<Error, Error>> { new Tuple<Error, Error>(TestErrors.TestErrorOne, TestErrors.TestErrorTwo), new Tuple<Error, Error>(TestErrors.TestErrorTwo, TestErrors.TestErrorOne), new Tuple<Error, Error>(TestErrors.TestErrorTwo, TestErrors.TestErrorThree("3")), }; } } }
38.936508
112
0.580106
[ "MIT" ]
BlauhausTechnology/Blauhaus.Errors
src/Blauhaus.Errors.Tests/Tests/ErrorTests/EqualityTests.cs
2,455
C#
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Storage; using Mix.Cms.Lib.Constants; using Mix.Cms.Lib.Enums; using Mix.Cms.Lib.Models.Account; using Mix.Cms.Lib.Models.Cms; using Mix.Heart.Infrastructure.ViewModels; using Mix.Heart.Models; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace Mix.Cms.Lib.ViewModels.Account.MixRoles { public class ReadViewModel : ViewModelBase<MixCmsAccountContext, AspNetRoles, ReadViewModel> { #region Properties [JsonProperty("id")] public string Id { get; set; } [JsonProperty("concurrencyStamp")] public string ConcurrencyStamp { get; set; } [Required] [JsonProperty("name")] public string Name { get; set; } [JsonProperty("normalizedName")] public string NormalizedName { get; set; } #region Views [JsonProperty("permissions")] public List<MixPortalPages.UpdateRolePermissionViewModel> Permissions { get; set; } [JsonProperty("mixPermissions")] public List<MixDatabaseDatas.ReadMvcViewModel> MixPermissions { get; set; } #endregion Views #endregion Properties #region Contructors public ReadViewModel() : base() { IsCache = false; } public ReadViewModel(AspNetRoles model, MixCmsAccountContext _context = null, IDbContextTransaction _transaction = null) : base(model, _context, _transaction) { IsCache = false; } #endregion Contructors #region Overrides public override AspNetRoles ParseModel(MixCmsAccountContext _context = null, IDbContextTransaction _transaction = null) { if (string.IsNullOrEmpty(Id)) { Id = Guid.NewGuid().ToString(); } return base.ParseModel(_context, _transaction); } public override async Task<RepositoryResponse<bool>> RemoveRelatedModelsAsync(ReadViewModel view, MixCmsAccountContext _context = null, IDbContextTransaction _transaction = null) { var result = await UserRoleViewModel.Repository.RemoveListModelAsync(false, ur => ur.RoleId == Id, _context, _transaction); return new RepositoryResponse<bool>() { IsSucceed = result.IsSucceed, Errors = result.Errors, Exception = result.Exception }; } public override void ExpandView(MixCmsAccountContext _context = null, IDbContextTransaction _transaction = null) { } #endregion Overrides #region Expands public async Task LoadPermissions(MixCmsContext _context = null , IDbContextTransaction _transaction = null) { var getPermissions = await MixPortalPages.UpdateRolePermissionViewModel.Repository.GetModelListByAsync( p => p.Level == 0 && p.MixPortalPageRole.Any(r => r.RoleId == Id) , _context, _transaction); if (getPermissions.IsSucceed) { Permissions = getPermissions.Data; try { foreach (var item in getPermissions.Data) { item.NavPermission = MixPortalPageRoles.ReadViewModel.Repository.GetSingleModel( n => n.PageId == item.Id && n.RoleId == Id, _context, _transaction) .Data; foreach (var child in item.ChildPages) { child.PortalPage.NavPermission = MixPortalPageRoles.ReadViewModel.Repository.GetSingleModel( n => n.PageId == child.PortalPage.Id && n.RoleId == Id, _context, _transaction) .Data; if (child.PortalPage.NavPermission == null) { var nav = new MixPortalPageRole() { PageId = child.PortalPage.Id, RoleId = Id, Status = MixContentStatus.Published }; child.PortalPage.NavPermission = new MixPortalPageRoles.ReadViewModel(nav) { IsActived = false }; } else { child.PortalPage.NavPermission.IsActived = true; } } } } catch (Exception ex) { Console.WriteLine(ex); } } await LoadMixPermissions(_context, _transaction); } public async Task LoadMixPermissions(MixCmsContext context = null, IDbContextTransaction transaction = null) { var getPermissions = await MixDatabaseDataAssociations.ReadMvcViewModel.Repository.GetModelListByAsync( m => m.ParentType == MixDatabaseParentType.Role && m.ParentId == Id, context, transaction); MixPermissions = getPermissions.IsSucceed ? getPermissions.Data.Select(n => n.Data).ToList() : new List<MixDatabaseDatas.ReadMvcViewModel>(); } #endregion Expands } }
37.289474
186
0.556457
[ "MIT" ]
1furkankaratas/mix.core
src/Mix.Cms.Lib/ViewModels/Account/MixRoles/ReadViewModel.cs
5,670
C#
public partial class VisualDebugEntity { public SomeOtherClassComponent SomeOtherClass { get { return (SomeOtherClassComponent)GetComponent(VisualDebugComponentsLookup.SomeOtherClass); } } public bool HasSomeOtherClass { get { return HasComponent(VisualDebugComponentsLookup.SomeOtherClass); } } public void AddSomeOtherClass(ExampleContent.VisualDebugging.SomeOtherClass newValue) { var index = VisualDebugComponentsLookup.SomeOtherClass; var component = (SomeOtherClassComponent)CreateComponent(index, typeof(SomeOtherClassComponent)); #if !ENTITAS_REDUX_NO_IMPL component.value = newValue; #endif AddComponent(index, component); } public void ReplaceSomeOtherClass(ExampleContent.VisualDebugging.SomeOtherClass newValue) { var index = VisualDebugComponentsLookup.SomeOtherClass; var component = (SomeOtherClassComponent)CreateComponent(index, typeof(SomeOtherClassComponent)); #if !ENTITAS_REDUX_NO_IMPL component.value = newValue; #endif ReplaceComponent(index, component); } public void CopySomeOtherClassTo(SomeOtherClassComponent copyComponent) { var index = VisualDebugComponentsLookup.SomeOtherClass; var component = (SomeOtherClassComponent)CreateComponent(index, typeof(SomeOtherClassComponent)); #if !ENTITAS_REDUX_NO_IMPL component.value = (ExampleContent.VisualDebugging.SomeOtherClass)copyComponent.value.Clone(); #endif ReplaceComponent(index, component); } public void RemoveSomeOtherClass() { RemoveComponent(VisualDebugComponentsLookup.SomeOtherClass); } } public sealed partial class VisualDebugMatcher { static JCMG.EntitasRedux.IMatcher<VisualDebugEntity> _matcherSomeOtherClass; public static JCMG.EntitasRedux.IMatcher<VisualDebugEntity> SomeOtherClass { get { if (_matcherSomeOtherClass == null) { var matcher = (JCMG.EntitasRedux.Matcher<VisualDebugEntity>)JCMG.EntitasRedux.Matcher<VisualDebugEntity>.AllOf(VisualDebugComponentsLookup.SomeOtherClass); matcher.ComponentNames = VisualDebugComponentsLookup.ComponentNames; _matcherSomeOtherClass = matcher; } return _matcherSomeOtherClass; } } }
34.655738
159
0.814096
[ "MIT" ]
MaxShwachko/entitas-redux-modified
Unity/Assets/ExampleContent/Generated/VisualDebug/Components/VisualDebugSomeOtherClassComponent.cs
2,114
C#
//////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2009, Daniel Kollmann // 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 Daniel Kollmann 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 System; using System.Collections.Generic; using System.Text; using Brainiac.Design.Nodes; using Brainiac.Design.Attributes; using LegendPlugin.Properties; namespace LegendPlugin.Nodes { public class ActionIdleTimeFacingTargetMostRecentSensedPosition : Action { //All parameters added private string _FacingTolerance = ""; private string _NoiseTime = ""; protected RequestShutDownSpeed _type; protected ThresholdQualifier _ThresholdQualifier; private string _Time = ""; [DesignerString("Facing tolerance", "FacingTolerance", "CategoryBasic", DesignerProperty.DisplayMode.Parameter, 0, DesignerProperty.DesignerFlags.NoFlags)] public string FacingTolerance { get { return _FacingTolerance; } set { _FacingTolerance = value; } } [DesignerString("Noise time", "NoiseTime", "CategoryBasic", DesignerProperty.DisplayMode.Parameter, 0, DesignerProperty.DesignerFlags.NoFlags)] public string NoiseTime { get { return _NoiseTime; } set { _NoiseTime = value; } } [DesignerEnum("Request shutdown speed", "RequestShutDownSpeed", "CategoryBasic", DesignerProperty.DisplayMode.Parameter, 0, DesignerProperty.DesignerFlags.NoFlags, null)] public RequestShutDownSpeed RequestShutDownSpeed { get { return _type; } set { _type = value; } } [DesignerEnum("Threshold qualifier", "ThresholdQualifier", "CategoryBasic", DesignerProperty.DisplayMode.Parameter, 0, DesignerProperty.DesignerFlags.NoFlags, null)] public ThresholdQualifier ThresholdQualifier { get { return _ThresholdQualifier; } set { _ThresholdQualifier = value; } } [DesignerString("Time", "Time", "CategoryBasic", DesignerProperty.DisplayMode.Parameter, 0, DesignerProperty.DesignerFlags.NoFlags)] public string Time { get { return _Time; } set { _Time = value; } } public ActionIdleTimeFacingTargetMostRecentSensedPosition() : base("IDLE TIME FACING TARGET'S MOST RECENT SENSED POSITION ", "PERFORM IDLE FOR A SPECIFIED TIME TOWARDS OUR TARGET'S MOST RECENTLY SENSED POSITION, WITH THRESHOLD.") { } protected override void CloneProperties(Node newnode) { base.CloneProperties(newnode); ActionIdleTimeFacingTargetMostRecentSensedPosition cond = (ActionIdleTimeFacingTargetMostRecentSensedPosition)newnode; cond._FacingTolerance = _FacingTolerance; cond._NoiseTime = _NoiseTime; cond._type = _type; cond._ThresholdQualifier = _ThresholdQualifier; cond._Time = _Time; } } }
45.61
237
0.677264
[ "BSD-3-Clause" ]
OpenCAGE/BehaviourTreeTool
BehaviourTreeTool/LegendPlugin/Action/ActionIdleTimeFacingTargetMostRecentSensedPosition.cs
4,561
C#
using System; using System.Diagnostics; using System.Globalization; using Windows.Foundation; using Windows.UI.Xaml.Media; using Uno.Disposables; using System.Numerics; using Uno.UI; using Windows.UI.Xaml.Wasm; namespace Windows.UI.Xaml.Shapes { partial class ArbitraryShapeBase { #pragma warning disable CS0067, CS0649 private double _scaleX; private double _scaleY; #pragma warning restore CS0067, CS0649 private IDisposable BuildDrawableLayer() { return Disposable.Empty; } private Size GetActualSize() => Size.Empty; protected override Size MeasureOverride(Size availableSize) { // We make sure to invoke native methods while not in the visual tree // (For instance getBBox will fail on FF) if (Parent == null) { return new Size(); } var measurements = GetMeasurements(availableSize); var desiredSize = measurements.desiredSize; var s = base.MeasureOverride(availableSize); return desiredSize; } protected override Size ArrangeOverride(Size finalSize) { // We make sure to invoke native methods while not in the visual tree // (For instance getBBox will fail on FF) if (Parent == null) { return new Size(); } var measurements = GetMeasurements(finalSize); var scale = Matrix3x2.CreateScale((float)measurements.scaleX, (float)measurements.scaleY); var translate = Matrix3x2.CreateTranslation((float)measurements.translateX, (float)measurements.translateY); var matrix = translate * scale; foreach (FrameworkElement child in GetChildren()) { if (child is DefsSvgElement) { // Defs hosts non-visual objects continue; } child.SetNativeTransform(matrix); } return finalSize; } private (Size desiredSize, double translateX, double translateY, double scaleX, double scaleY) GetMeasurements(Size availableSize) { // Get the content size using Bounding Box on it. var contentBBox = GetBBoxOfChildrenWithStrokeThickness(); if (Stretch == Stretch.None) { // No scaling, just output the bounding box unchanged return (new Size(contentBBox.Right, contentBBox.Bottom), 0, 0, 1, 1); } var contentAspectRatio = contentBBox.AspectRatio(); // Calculate the control size var calculatedWidth = LimitWithUserSize(availableSize.Width, Width, contentBBox.Width); var calculatedHeight = LimitWithUserSize(availableSize.Height, Height, calculatedWidth / contentAspectRatio); var translateX = contentBBox.X * -1; var translateY = contentBBox.Y * -1; if (Stretch == Stretch.Fill) { // Full scaling without keeping aspect ratio var sx = calculatedWidth / contentBBox.Width; var sy = calculatedHeight / contentBBox.Height; return (new Size(calculatedWidth, calculatedHeight), translateX, translateY, sx, sy); } // Check if the content wider than the control surface var calculatedAspectRatio = calculatedWidth / calculatedHeight; var isContentWiderThanControl = contentAspectRatio > calculatedAspectRatio; var width = calculatedWidth; var height = calculatedHeight; var scaleX = calculatedWidth / contentBBox.Width; var scaleY = calculatedHeight / contentBBox.Height; if (Stretch == Stretch.Uniform) { if (isContentWiderThanControl) { height = width / contentAspectRatio; scaleY = scaleX; } else { width = height * contentAspectRatio; scaleX = scaleY; } } else if (Stretch == Stretch.UniformToFill) { if (isContentWiderThanControl) { width = height * contentAspectRatio; scaleX = scaleY; } else { height = width / contentAspectRatio; scaleY = scaleX; } } else { throw new InvalidOperationException("Unknown stretch mode."); } var desiredSize = new Size(width, height); var measurements = (desiredSize, translateX, translateY, scaleX, scaleY); return measurements; } private Rect GetBBoxOfChildrenWithStrokeThickness() { var bbox = Rect.Empty; foreach (FrameworkElement child in GetChildren()) { if (child is DefsSvgElement) { // Defs hosts non-visual objects continue; } var childRect = GetBBoxWithStrokeThickness(child); if (bbox == Rect.Empty) { bbox = childRect; } else { bbox.Union(childRect); } } return bbox; } private Rect GetBBoxWithStrokeThickness(FrameworkElement element) { var bbox = element.GetBBox(); if (Stroke == null || StrokeThickness < double.Epsilon) { return bbox; } var halfStrokeThickness = StrokeThickness / 2; var x = Math.Min(bbox.X, bbox.Left - halfStrokeThickness); var y = Math.Min(bbox.Y, bbox.Top - halfStrokeThickness); var width = bbox.Right + halfStrokeThickness - x; var height = bbox.Bottom + halfStrokeThickness - y; var bBoxWithStrokeThickness = new Rect(x, y, width, height); return bBoxWithStrokeThickness; } } }
25.453608
132
0.698056
[ "Apache-2.0" ]
06needhamt/uno
src/Uno.UI/UI/Xaml/Shapes/ArbitraryShapeBase.wasm.cs
4,940
C#
namespace MonitoringTilda.Services.Models { public class SubOrder { public string Id { get; set; } public string Name { get; set; } public int Count { get; set; } } }
20.090909
42
0.538462
[ "Apache-2.0" ]
FoxTes/MonitoringTilda
MonitoringTilda.Services/Models/SubOrder.cs
223
C#
using System; using Legacy.Game.MMGUI.Tooltip; using UnityEngine; namespace Legacy.Game { [AddComponentMenu("MM Legacy/MMGUI/BestiaryProgressBar")] public class BestiaryProgressBar : MonoBehaviour { [SerializeField] private BoxCollider m_collider; [SerializeField] private UIFilledSprite m_fillSprite; private Int32 m_currentAmount; private Int32 m_maxAmount; public UIFilledSprite FillSprite => m_fillSprite; private void OnDisable() { TooltipManager.Instance.Hide(this); } public void SetCurrentAmount(Int32 p_amount, Int32 p_maxAmount) { m_currentAmount = p_amount; m_maxAmount = p_maxAmount; Single num = 1f / (p_maxAmount / (Single)p_amount); m_fillSprite.fillAmount = ((num <= 1f) ? num : 1f); } public void Hide() { NGUITools.SetActiveSelf(gameObject, false); } public void Show() { NGUITools.SetActiveSelf(gameObject, true); } public void OnTooltip(Boolean show) { if (show) { String p_tooltipText = String.Empty; if (m_currentAmount < m_maxAmount) { p_tooltipText = LocaManager.GetText("BESTIARY_PROGRESS_TT", m_currentAmount, m_maxAmount - m_currentAmount); } else { p_tooltipText = LocaManager.GetText("BESTIARY_PROGRESS_FULL_TT", m_maxAmount); } TooltipManager.Instance.Show(this, p_tooltipText, gameObject.transform.position, m_collider.transform.localScale * 0.5f); } else { TooltipManager.Instance.Hide(this); } } } }
22.089552
125
0.714189
[ "MIT" ]
Albeoris/MMXLegacy
Legacy.Game/Game/BestiaryProgressBar.cs
1,482
C#
using System; namespace Weapsy.Blog.Domain.Comment.Events { public class CommentTextChangedEvent : IDomainEvent { public Guid Id { get; private set; } public string Text { get; private set; } public CommentTextChangedEvent(Guid id, string text) { Id = id; Text = text; } } }
17.470588
54
0.693603
[ "MIT" ]
1713660/weapsy
src/Weapsy.Blog.Domain/Comment/Events/CommentTextChangedEvent.cs
299
C#
using Grammophone.Domos.Logic; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Grammophone.Domos.Web.Models { /// <summary> /// An error which is intended to be displayed to the user. /// </summary> public class UserErrorModel { #region Construction /// <summary> /// Create. /// </summary> /// <param name="displayMessage">The display message to be set.</param> public UserErrorModel(string displayMessage) { if (displayMessage == null) throw new ArgumentNullException(nameof(displayMessage)); this.DisplayMessage = displayMessage; } /// <summary> /// Create. /// </summary> /// <param name="userException">The user exception containing the dispayed message.</param> public UserErrorModel(UserException userException) { if (userException == null) throw new ArgumentNullException(nameof(userException)); this.DisplayMessage = userException.Message; this.ExceptionName = userException.GetType().FullName; } #endregion #region Public properties /// <summary> /// The message intended to be displayed to the user. /// </summary> public string DisplayMessage { get; private set; } /// <summary> /// The name of the exception. /// </summary> public string ExceptionName { get; private set; } #endregion } }
23.929825
93
0.705279
[ "MIT" ]
grammophone/Grammophone.Domos.Mvc
Models/UserErrorModel.cs
1,366
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Diagnostics; using System.Text; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.EmbeddedLanguages.VirtualChars; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.EmbeddedLanguages.VirtualChars { internal class CSharpVirtualCharService : AbstractVirtualCharService { public static readonly IVirtualCharService Instance = new CSharpVirtualCharService(); protected CSharpVirtualCharService() { } protected override bool IsStringOrCharLiteralToken(SyntaxToken token) => token.Kind() == SyntaxKind.StringLiteralToken || token.Kind() == SyntaxKind.CharacterLiteralToken; protected override VirtualCharSequence TryConvertToVirtualCharsWorker(SyntaxToken token) { // C# preprocessor directives can contain string literals. However, these string // literals do not behave like normal literals. Because they are used for paths (i.e. // in a #line directive), the language does not do any escaping within them. i.e. if // you have a \ it's just a \ Note that this is not a verbatim string. You can't put // a double quote in it either, and you cannot have newlines and whatnot. // // We technically could convert this trivially to an array of virtual chars. After all, // there would just be a 1:1 correspondance with the literal contents and the chars // returned. However, we don't even both returning anything here. That's because // there's no useful features we can offer here. Because there are no escape characters // we won't classify any escape characters. And there is no way that these strings would // be Regex/Json snippets. So it's easier to just bail out and return nothing. if (IsInDirective(token.Parent)) return default; Debug.Assert(!token.ContainsDiagnostics); if (token.Kind() == SyntaxKind.StringLiteralToken) { return token.IsVerbatimStringLiteral() ? TryConvertVerbatimStringToVirtualChars(token, "@\"", "\"", escapeBraces: false) : TryConvertStringToVirtualChars(token, "\"", "\"", escapeBraces: false); } if (token.Kind() == SyntaxKind.CharacterLiteralToken) return TryConvertStringToVirtualChars(token, "'", "'", escapeBraces: false); if (token.Kind() == SyntaxKind.InterpolatedStringTextToken) { var parent = token.Parent; if (parent is InterpolationFormatClauseSyntax) parent = parent.Parent; if (parent.Parent is InterpolatedStringExpressionSyntax interpolatedString) { return interpolatedString.StringStartToken.Kind() == SyntaxKind.InterpolatedVerbatimStringStartToken ? TryConvertVerbatimStringToVirtualChars(token, "", "", escapeBraces: true) : TryConvertStringToVirtualChars(token, "", "", escapeBraces: true); } } return default; } private static bool IsInDirective(SyntaxNode node) { while (node != null) { if (node is DirectiveTriviaSyntax) { return true; } node = node.GetParent(ascendOutOfTrivia: true); } return false; } private static VirtualCharSequence TryConvertVerbatimStringToVirtualChars(SyntaxToken token, string startDelimiter, string endDelimiter, bool escapeBraces) => TryConvertSimpleDoubleQuoteString(token, startDelimiter, endDelimiter, escapeBraces); private static VirtualCharSequence TryConvertStringToVirtualChars( SyntaxToken token, string startDelimiter, string endDelimiter, bool escapeBraces) { var tokenText = token.Text; if (startDelimiter.Length > 0 && !tokenText.StartsWith(startDelimiter)) { Debug.Fail("This should not be reachable as long as the compiler added no diagnostics."); return default; } if (endDelimiter.Length > 0 && !tokenText.EndsWith(endDelimiter)) { Debug.Fail("This should not be reachable as long as the compiler added no diagnostics."); return default; } var startIndexInclusive = startDelimiter.Length; var endIndexExclusive = tokenText.Length - endDelimiter.Length; // Do things in two passes. First, convert everything in the string to a 16-bit-char+span. Then walk // again, trying to create Runes from the 16-bit-chars. We do this to simplify complex cases where we may // have escapes and non-escapes mixed together. using var _1 = ArrayBuilder<(char ch, TextSpan span)>.GetInstance(out var charResults); // First pass, just convert everything in the string (i.e. escapes) to plain 16-bit characters. var offset = token.SpanStart; for (var index = startIndexInclusive; index < endIndexExclusive;) { var ch = tokenText[index]; if (ch == '\\') { if (!TryAddEscape(charResults, tokenText, offset, index)) return default; index += charResults.Last().span.Length; } else if (escapeBraces && IsOpenOrCloseBrace(ch)) { if (!IsLegalBraceEscape(tokenText, index, offset, out var braceSpan)) return default; charResults.Add((ch, braceSpan)); index += charResults.Last().span.Length; } else { charResults.Add((ch, new TextSpan(offset + index, 1))); index++; } } // Second pass. Convert those characters to Runes. using var _2 = ArrayBuilder<VirtualChar>.GetInstance(out var runeResults); for (var i = 0; i < charResults.Count;) { var (ch, span) = charResults[i]; // First, see if this was a valid single char that can become a Rune. if (Rune.TryCreate(ch, out var rune)) { runeResults.Add(VirtualChar.Create(rune, span)); i++; continue; } // Next, see if we got at least a surrogate pair that can be converted into a Rune. if (i + 1 < charResults.Count) { var (nextCh, nextSpan) = charResults[i + 1]; if (Rune.TryCreate(ch, nextCh, out rune)) { runeResults.Add(VirtualChar.Create(rune, TextSpan.FromBounds(span.Start, nextSpan.End))); i += 2; continue; } } // Had an unpaired surrogate. Debug.Assert(char.IsSurrogate(ch)); runeResults.Add(VirtualChar.Create(ch, span)); i++; } return CreateVirtualCharSequence( tokenText, offset, startIndexInclusive, endIndexExclusive, runeResults); } private static bool TryAddEscape( ArrayBuilder<(char ch, TextSpan span)> result, string tokenText, int offset, int index) { // Copied from Lexer.ScanEscapeSequence. Debug.Assert(tokenText[index] == '\\'); return TryAddSingleCharacterEscape(result, tokenText, offset, index) || TryAddMultiCharacterEscape(result, tokenText, offset, index); } public override bool TryGetEscapeCharacter(VirtualChar ch, out char escapedChar) { // Keep in sync with TryAddSingleCharacterEscape switch (ch.Value) { // Note: we don't care about single quote as that doesn't need to be escaped when // producing a normal C# string literal. // case '\'': // escaped characters that translate to themselves. case '"': escapedChar = '"'; return true; case '\\': escapedChar = '\\'; return true; // translate escapes as per C# spec 2.4.4.4 case '\0': escapedChar = '0'; return true; case '\a': escapedChar = 'a'; return true; case '\b': escapedChar = 'b'; return true; case '\f': escapedChar = 'f'; return true; case '\n': escapedChar = 'n'; return true; case '\r': escapedChar = 'r'; return true; case '\t': escapedChar = 't'; return true; case '\v': escapedChar = 'v'; return true; } escapedChar = default; return false; } private static bool TryAddSingleCharacterEscape( ArrayBuilder<(char ch, TextSpan span)> result, string tokenText, int offset, int index) { // Copied from Lexer.ScanEscapeSequence. Debug.Assert(tokenText[index] == '\\'); var ch = tokenText[index + 1]; // Keep in sync with EscapeForRegularString switch (ch) { // escaped characters that translate to themselves case '\'': case '"': case '\\': break; // translate escapes as per C# spec 2.4.4.4 case '0': ch = '\0'; break; case 'a': ch = '\a'; break; case 'b': ch = '\b'; break; case 'f': ch = '\f'; break; case 'n': ch = '\n'; break; case 'r': ch = '\r'; break; case 't': ch = '\t'; break; case 'v': ch = '\v'; break; default: return false; } result.Add((ch, new TextSpan(offset + index, 2))); return true; } private static bool TryAddMultiCharacterEscape( ArrayBuilder<(char ch, TextSpan span)> result, string tokenText, int offset, int index) { // Copied from Lexer.ScanEscapeSequence. Debug.Assert(tokenText[index] == '\\'); var ch = tokenText[index + 1]; switch (ch) { case 'x': case 'u': case 'U': return TryAddMultiCharacterEscape(result, tokenText, offset, index, ch); default: Debug.Fail("This should not be reachable as long as the compiler added no diagnostics."); return false; } } private static bool TryAddMultiCharacterEscape( ArrayBuilder<(char ch, TextSpan span)> result, string tokenText, int offset, int index, char character) { var startIndex = index; Debug.Assert(tokenText[index] == '\\'); // skip past the / and the escape type. index += 2; if (character == 'U') { // 8 character escape. May represent 1 or 2 actual chars. uint uintChar = 0; if (!IsHexDigit(tokenText[index])) { Debug.Fail("This should not be reachable as long as the compiler added no diagnostics."); return false; } for (var i = 0; i < 8; i++) { character = tokenText[index + i]; if (!IsHexDigit(character)) { Debug.Fail("This should not be reachable as long as the compiler added no diagnostics."); return false; } uintChar = (uint)((uintChar << 4) + HexValue(character)); } // Copied from Lexer.cs and SlidingTextWindow.cs if (uintChar > 0x0010FFFF) { Debug.Fail("This should not be reachable as long as the compiler added no diagnostics."); return false; } if (uintChar < (uint)0x00010000) { // something like \U0000000A // // Represents a single char value. result.Add(((char)uintChar, new TextSpan(startIndex + offset, 2 + 8))); return true; } else { Debug.Assert(uintChar > 0x0000FFFF && uintChar <= 0x0010FFFF); var lowSurrogate = ((uintChar - 0x00010000) % 0x0400) + 0xDC00; var highSurrogate = ((uintChar - 0x00010000) / 0x0400) + 0xD800; // Encode this as a surrogate pair. var pos = startIndex + offset; result.Add(((char)highSurrogate, new TextSpan(pos, 0))); result.Add(((char)lowSurrogate, new TextSpan(pos, 2 + 8))); return true; } } else if (character == 'u') { // 4 character escape representing one char. var intChar = 0; if (!IsHexDigit(tokenText[index])) { Debug.Fail("This should not be reachable as long as the compiler added no diagnostics."); return false; } for (var i = 0; i < 4; i++) { var ch2 = tokenText[index + i]; if (!IsHexDigit(ch2)) { Debug.Fail("This should not be reachable as long as the compiler added no diagnostics."); return false; } intChar = (intChar << 4) + HexValue(ch2); } character = (char)intChar; result.Add((character, new TextSpan(startIndex + offset, 2 + 4))); return true; } else { Debug.Assert(character == 'x'); // Variable length (up to 4 chars) hexadecimal escape. var intChar = 0; if (!IsHexDigit(tokenText[index])) { Debug.Fail("This should not be reachable as long as the compiler added no diagnostics."); return false; } var endIndex = index; for (var i = 0; i < 4 && endIndex < tokenText.Length; i++) { var ch2 = tokenText[index + i]; if (!IsHexDigit(ch2)) { // This is possible. These escape sequences are variable length. break; } intChar = (intChar << 4) + HexValue(ch2); endIndex++; } character = (char)intChar; result.Add((character, TextSpan.FromBounds(startIndex + offset, endIndex + offset))); return true; } } private static int HexValue(char c) { Debug.Assert(IsHexDigit(c)); return (c >= '0' && c <= '9') ? c - '0' : (c & 0xdf) - 'A' + 10; } private static bool IsHexDigit(char c) { return (c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') || (c >= 'a' && c <= 'f'); } } }
40.601485
163
0.512406
[ "MIT" ]
Acidburn0zzz/roslyn
src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/EmbeddedLanguages/VirtualChars/CSharpVirtualCharService.cs
16,405
C#
using Microsoft.Extensions.Hosting; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using Volo.Abp; namespace Bamboo.Sales.HttpApi.Client.ConsoleTestApp { public class ConsoleTestAppHostedService : IHostedService { public async Task StartAsync(CancellationToken cancellationToken) { using (var application = AbpApplicationFactory.Create<SalesConsoleApiClientModule>()) { application.Initialize(); var demo = application.ServiceProvider.GetRequiredService<ClientDemoService>(); await demo.RunAsync(); application.Shutdown(); } } public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask; } }
30.259259
97
0.681763
[ "MIT" ]
BlazorHub/bamboomodules
Bamboo.Sales/test/Bamboo.Sales.HttpApi.Client.ConsoleTestApp/ConsoleTestAppHostedService.cs
819
C#
using System; using System.Threading.Tasks; using Microsoft.AspNet.Identity; using Microsoft.Owin.Security.OAuth; namespace DevTeam.BearerAuthentication { public class ApplicationOAuthProvider<TUser, TService> : OAuthAuthorizationServerProvider where TUser: class, IUser where TService: UserManager<TUser> { private readonly string _publicClientId; public ApplicationOAuthProvider(string publicClientId) { if (publicClientId == null) { throw new ArgumentNullException("publicClientId"); } _publicClientId = publicClientId; } public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { var grantContext = new CredentialsValidator<TUser, TService>(context); await grantContext.SignIn(); } public override Task TokenEndpoint(OAuthTokenEndpointContext context) { foreach (var property in context.Properties.Dictionary) { context.AdditionalResponseParameters.Add(property.Key, property.Value); } return Task.FromResult<object>(null); } public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context) { if (context.ClientId == null) { context.Validated(); } return Task.FromResult<object>(null); } public override Task ValidateClientRedirectUri(OAuthValidateClientRedirectUriContext context) { if (context.ClientId == _publicClientId) { var expectedRootUri = new Uri(context.Request.Uri, "/"); if (expectedRootUri.AbsoluteUri == context.RedirectUri) { context.Validated(); } } return Task.FromResult<object>(null); } } }
30.560606
115
0.611304
[ "Apache-2.0" ]
DevTeamHub/BearerAuthentication
ApplicationOAuthProvider.cs
2,019
C#
namespace TrafficManager.API.Traffic.Data { using System; using TrafficManager.API.Traffic.Enums; public struct ExtCitizenInstance { public ushort instanceId; /// <summary> /// Citizen path mode (used for Parking AI) /// </summary> public ExtPathMode pathMode; /// <summary> /// Number of times a formerly found parking space is already occupied after reaching its position /// </summary> public int failedParkingAttempts; /// <summary> /// Segment id / Building id where a parking space has been found /// </summary> public ushort parkingSpaceLocationId; /// <summary> /// Type of object (segment/building) where a parking space has been found /// </summary> public ExtParkingSpaceLocation parkingSpaceLocation; /// <summary> /// Path position that is used as a start position when parking fails /// </summary> public PathUnit.Position? parkingPathStartPosition; /// <summary> /// Walking path from (alternative) parking spot to target (only used to check if there is /// a valid walking path, not actually used at the moment) /// </summary> public uint returnPathId; /// <summary> /// State of the return path /// </summary> public ExtPathState returnPathState; /// <summary> /// Last known distance to the citizen's parked car /// </summary> public float lastDistanceToParkedCar; /// <summary> /// Specifies whether the last path-finding started at an outside connection /// </summary> public bool atOutsideConnection; public ExtCitizenInstance(ushort instanceId) { this.instanceId = instanceId; pathMode = ExtPathMode.None; failedParkingAttempts = 0; parkingSpaceLocationId = 0; parkingSpaceLocation = ExtParkingSpaceLocation.None; parkingPathStartPosition = null; returnPathId = 0; returnPathState = ExtPathState.None; lastDistanceToParkedCar = 0; atOutsideConnection = false; } public override string ToString() { return string.Format( "[ExtCitizenInstance\n\tinstanceId = {0}\n\tpathMode = {1}\n" + "\tfailedParkingAttempts = {2}\n\tparkingSpaceLocationId = {3}\n" + "\tparkingSpaceLocation = {4}\n\tparkingPathStartPosition = {5}\n" + "\treturnPathId = {6}\n\treturnPathState = {7}\n\tlastDistanceToParkedCar = {8}\n" + "\tatOutsideConnection = {9}\nExtCitizenInstance]", instanceId, pathMode, failedParkingAttempts, parkingSpaceLocationId, parkingSpaceLocation, parkingPathStartPosition, returnPathId, returnPathState, lastDistanceToParkedCar, atOutsideConnection); } /// <summary> /// Determines the path type through evaluating the current path mode. /// </summary> /// <returns></returns> public ExtPathType GetPathType() { switch (pathMode) { case ExtPathMode.CalculatingCarPathToAltParkPos: case ExtPathMode.CalculatingCarPathToKnownParkPos: case ExtPathMode.CalculatingCarPathToTarget: case ExtPathMode.DrivingToAltParkPos: case ExtPathMode.DrivingToKnownParkPos: case ExtPathMode.DrivingToTarget: case ExtPathMode.RequiresCarPath: case ExtPathMode.RequiresMixedCarPathToTarget: case ExtPathMode.ParkingFailed: { return ExtPathType.DrivingOnly; } case ExtPathMode.CalculatingWalkingPathToParkedCar: case ExtPathMode.CalculatingWalkingPathToTarget: case ExtPathMode.RequiresWalkingPathToParkedCar: case ExtPathMode.RequiresWalkingPathToTarget: case ExtPathMode.ApproachingParkedCar: case ExtPathMode.WalkingToParkedCar: case ExtPathMode.WalkingToTarget: { return ExtPathType.WalkingOnly; } default: { return ExtPathType.None; } } } /// <summary> /// Converts an ExtPathState to a ExtSoftPathState. /// </summary> /// <param name="state"></param> /// <returns></returns> public static ExtSoftPathState ConvertPathStateToSoftPathState(ExtPathState state) { return (ExtSoftPathState)((int)state); } } }
37.782946
106
0.583094
[ "MIT" ]
CitiesSkylinesMods/TMPE
TLM/TMPE.API/Traffic/Data/ExtCitizenInstance.cs
4,876
C#
namespace _10._Lower_or_Upper { using System; public class StartUp { public static void Main() { var characterToCheck = char.Parse(Console.ReadLine()); if (char.IsUpper(characterToCheck)) { Console.WriteLine("upper-case"); } else { Console.WriteLine("lower-case"); } } } }
19.636364
66
0.467593
[ "MIT" ]
AntoniyaIvanova/SoftUni
C#/C# Fundamentals/03. DATA TYPES AND VARIABLES/LAB/DataTypesAndVariables/10. Lower or Upper/StartUp.cs
434
C#
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using Nini.Config; using OpenMetaverse; using OpenSim.Framework.Servers.HttpServer; using OpenSim.Server.Base; using OpenSim.Server.Handlers.Base; using OpenSim.Services.Interfaces; using System; using System.IO; using System.Net; using System.Threading; namespace OpenSim.Server.Handlers.MapImage { public class MapGetServiceConnector : ServiceConnector { //private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private IMapImageService m_MapService; private string m_ConfigName = "MapImageService"; public MapGetServiceConnector(IConfigSource config, IHttpServer server, string configName) : base(config, server, configName) { IConfig serverConfig = config.Configs[m_ConfigName]; if (serverConfig == null) throw new Exception(String.Format("No section {0} in config file", m_ConfigName)); string gridService = serverConfig.GetString("LocalServiceModule", string.Empty); if (string.IsNullOrWhiteSpace(gridService)) throw new Exception("No LocalServiceModule in config file"); object[] args = new object[] { config }; m_MapService = ServerUtils.LoadPlugin<IMapImageService>(gridService, args); server.AddStreamHandler(new MapServerGetHandler(m_MapService)); } } class MapServerGetHandler : BaseStreamHandler { public static readonly object ev = new object(); //private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private IMapImageService m_MapService; public MapServerGetHandler(IMapImageService service) : base("GET", "/map") { m_MapService = service; } protected override byte[] ProcessRequest(string path, Stream request, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) { if(!Monitor.TryEnter(ev, 5000)) { httpResponse.StatusCode = (int)HttpStatusCode.ServiceUnavailable; httpResponse.AddHeader("Retry-After", "10"); return new byte[0]; } byte[] result = new byte[0]; string format = string.Empty; //UUID scopeID = new UUID("07f8d88e-cd5e-4239-a0ed-843f75d09992"); UUID scopeID = UUID.Zero; // This will be map/tilefile.ext, but on multitenancy it will be // map/scope/teilefile.ext path = path.Trim('/'); string[] bits = path.Split(new char[] {'/'}); if (bits.Length > 2) { try { scopeID = new UUID(bits[1]); } catch { return new byte[9]; } path = bits[2]; path = path.Trim('/'); } if(path.Length == 0) { httpResponse.StatusCode = (int)HttpStatusCode.NotFound; httpResponse.ContentType = "text/plain"; return new byte[0]; } result = m_MapService.GetMapTile(path, scopeID, out format); if (result.Length > 0) { httpResponse.StatusCode = (int)HttpStatusCode.OK; if (format.Equals(".png")) httpResponse.ContentType = "image/png"; else if (format.Equals(".jpg") || format.Equals(".jpeg")) httpResponse.ContentType = "image/jpeg"; } else { httpResponse.StatusCode = (int)HttpStatusCode.NotFound; httpResponse.ContentType = "text/plain"; } Monitor.Exit(ev); return result; } } }
38.894366
135
0.625747
[ "BSD-3-Clause" ]
mdickson/opensim
OpenSim/Server/Handlers/Map/MapGetServerConnector.cs
5,523
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 appflow-2020-08-23.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Net; using System.Text; using System.Xml.Serialization; using Amazon.Appflow.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.Appflow.Model.Internal.MarshallTransformations { /// <summary> /// Response Unmarshaller for ConnectorOperator Object /// </summary> public class ConnectorOperatorUnmarshaller : IUnmarshaller<ConnectorOperator, XmlUnmarshallerContext>, IUnmarshaller<ConnectorOperator, JsonUnmarshallerContext> { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> ConnectorOperator IUnmarshaller<ConnectorOperator, XmlUnmarshallerContext>.Unmarshall(XmlUnmarshallerContext context) { throw new NotImplementedException(); } /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> public ConnectorOperator Unmarshall(JsonUnmarshallerContext context) { context.Read(); if (context.CurrentTokenType == JsonToken.Null) return null; ConnectorOperator unmarshalledObject = new ConnectorOperator(); int targetDepth = context.CurrentDepth; while (context.ReadAtDepth(targetDepth)) { if (context.TestExpression("Amplitude", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.Amplitude = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("Datadog", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.Datadog = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("Dynatrace", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.Dynatrace = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("GoogleAnalytics", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.GoogleAnalytics = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("InforNexus", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.InforNexus = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("Marketo", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.Marketo = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("S3", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.S3 = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("Salesforce", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.Salesforce = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("ServiceNow", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.ServiceNow = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("Singular", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.Singular = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("Slack", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.Slack = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("Trendmicro", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.Trendmicro = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("Veeva", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.Veeva = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("Zendesk", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.Zendesk = unmarshaller.Unmarshall(context); continue; } } return unmarshalledObject; } private static ConnectorOperatorUnmarshaller _instance = new ConnectorOperatorUnmarshaller(); /// <summary> /// Gets the singleton. /// </summary> public static ConnectorOperatorUnmarshaller Instance { get { return _instance; } } } }
40.235294
164
0.570175
[ "Apache-2.0" ]
ChristopherButtars/aws-sdk-net
sdk/src/Services/Appflow/Generated/Model/Internal/MarshallTransformations/ConnectorOperatorUnmarshaller.cs
6,840
C#
using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; using System.Xml; using System.Xml.Linq; using System.Xml.Xsl; namespace Reporting { public static class Extensions { public static XElement ToXml<T>(this T obj) { Type type = typeof(T); IEnumerable<dynamic> content() { List<Type> lists = new List<Type>() { typeof(IList<T>), typeof(IList) }; List<Type> dictionary = new List<Type> { typeof(IDictionary<String, String>), typeof(IDictionary) }; foreach (var pi in type.GetProperties()) { dynamic value = (dynamic)pi.GetValue(obj, null); if (!pi.GetIndexParameters().Any()) { if (pi.PropertyType.GetInterfaces().Contains(typeof(ICollection))) { if (pi.PropertyType.GetInterfaces().Any(i => lists.Any(l => i == l))) { foreach (var listItem in value as IList) { yield return ToXml((dynamic)listItem); } } else if (pi.PropertyType.GetInterfaces().Any(i => dictionary.Any(d => i == d))) { if (pi.Name == "AttributesForXml") { foreach (var dictionaryItem in value as IDictionary<String, String>) { yield return new XAttribute(dictionaryItem.Key, dictionaryItem.Value); } } else if (pi.Name == "ElementsForXml") { foreach (var dictionaryItem in value as IDictionary<String, String>) { yield return new XElement(dictionaryItem.Key, dictionaryItem.Value); } } else continue; } else continue; } else if (pi.Name == "ElementTextForXml" && pi.PropertyType == typeof(String) && (String) value != String.Empty) { yield return value; } else if (pi.PropertyType == typeof(String) || pi.PropertyType.IsPrimitive || pi.PropertyType.IsEnum) { yield return new XAttribute(pi.Name, value); } else continue; } } } return new XElement(new XElement(type.Name,content())); } public static XDocument Transform(this XElement xml, string xsl) { var originalXml = new XDocument(xml); var transformedXml = new XDocument(); using (var xmlWriter = transformedXml.CreateWriter()) { var xslt = new XslCompiledTransform(); xslt.Load(XmlReader.Create(new StreamReader(xsl))); using (StreamWriter streamWriter = new StreamWriter("index.html")) { xslt.Transform(originalXml.CreateReader(), null, streamWriter); } } return transformedXml; } } }
42.325843
135
0.425007
[ "MIT" ]
Riddle1988/ReportingLibrary
Reporting/Extensions.cs
3,769
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable using System.Collections.Generic; using Azure.Core; namespace Azure.ResourceManager.Compute.Models { /// <summary> Describes a set of certificates which are all in the same Key Vault. </summary> public partial class CloudServiceVaultSecretGroup { /// <summary> Initializes a new instance of CloudServiceVaultSecretGroup. </summary> public CloudServiceVaultSecretGroup() { VaultCertificates = new ChangeTrackingList<CloudServiceVaultCertificate>(); } /// <summary> Initializes a new instance of CloudServiceVaultSecretGroup. </summary> /// <param name="sourceVault"> The relative URL of the Key Vault containing all of the certificates in VaultCertificates. </param> /// <param name="vaultCertificates"> The list of key vault references in SourceVault which contain certificates. </param> internal CloudServiceVaultSecretGroup(SubResource sourceVault, IList<CloudServiceVaultCertificate> vaultCertificates) { SourceVault = sourceVault; VaultCertificates = vaultCertificates; } /// <summary> The relative URL of the Key Vault containing all of the certificates in VaultCertificates. </summary> public SubResource SourceVault { get; set; } /// <summary> The list of key vault references in SourceVault which contain certificates. </summary> public IList<CloudServiceVaultCertificate> VaultCertificates { get; } } }
43.702703
138
0.714904
[ "MIT" ]
Cardsareus/azure-sdk-for-net
sdk/compute/Azure.ResourceManager.Compute/src/Generated/Models/CloudServiceVaultSecretGroup.cs
1,617
C#
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="UnorientedGraph.cs" company="Kephas Software SRL"> // Copyright (c) Kephas Software SRL. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // </copyright> // <summary> // Implements the unoriented graph class. // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace Kephas.Graphs { /// <summary> /// Defines an unoriented graph. /// </summary> public class UnorientedGraph : Graph { /// <summary> /// Creates a subgraph. /// </summary> /// <returns> /// The new subgraph. /// </returns> protected internal override Graph CreateSubgraph() { return new UnorientedGraph(); } /// <summary> /// Creates an edge between two nodes. /// </summary> /// <param name="from">The starting node.</param> /// <param name="to">The ending node.</param> /// <returns> /// The new edge. /// </returns> protected override GraphEdge CreateEdge(GraphNode from, GraphNode to) { return new UnorientedGraphEdge(from, to); } } /// <summary> /// Defines an unoriented graph with value nodes. /// </summary> /// <typeparam name="TNodeValue">Type of the node value.</typeparam> /// <typeparam name="TEdgeValue">Type of the edge values.</typeparam> public class UnorientedGraph<TNodeValue, TEdgeValue> : Graph<TNodeValue, TEdgeValue> { /// <summary> /// Creates a subgraph. /// </summary> /// <returns> /// The new subgraph. /// </returns> protected internal override Graph CreateSubgraph() { return new UnorientedGraph<TNodeValue, TEdgeValue>(); } /// <summary> /// Creates an edge between two nodes. /// </summary> /// <param name="from">The starting node.</param> /// <param name="to">The ending node.</param> /// <returns> /// The new edge. /// </returns> protected override GraphEdge CreateEdge(GraphNode from, GraphNode to) { return new UnorientedGraphEdge<TNodeValue, TEdgeValue>((GraphNode<TNodeValue>)from, (GraphNode<TNodeValue>)to); } } }
34.527027
123
0.517808
[ "MIT" ]
kephas-software/kephas
src/Kephas.Collections/Graphs/UnorientedGraph.cs
2,557
C#
using Interface.Models; using Microsoft.AspNetCore.Identity.EntityFrameworkCore; using Microsoft.EntityFrameworkCore; namespace Interface.Data { public class ApplicationDbContext : IdentityDbContext { public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options): base(options) { } public ApplicationDbContext() { } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { optionsBuilder.UseSqlite("Filename=SMSMIDB.db"); } public DbSet<AudioBook> AudioBooks { get; set; } public DbSet<Request> Requests { get; set; } public DbSet<RequestUser> RequestUsers { get; set; } public DbSet<RequestType> RequestTypes { get; set; } public DbSet<Movie> Movies { get; set; } public DbSet<TVShows> TVShows { get; set; } public DbSet<TVShows> Notifications { get; set; } protected override void OnModelCreating(ModelBuilder builder) { builder.Entity<Movie>(entity => { entity.Property(i => i.ID).UseIdentityColumn(); entity.Property(i => i.Title).IsRequired(); entity.Property(i => i.YYYY).IsRequired(); }); builder.Entity<Request>(entity => { entity.Property(i => i.ID).UseIdentityColumn(); entity.Property(i => i.Title).IsRequired(); entity.Property(i => i.Type).IsRequired(); entity.Property(i => i.RequestedBy).IsRequired(); entity.Property(i => i.IsComplete).HasDefaultValue(0); entity.Property(i => i.Acknowledged).HasDefaultValue(0); }); builder.Entity<TVShows>(entity => { entity.Property(i => i.ID).UseIdentityColumn(); entity.Property(i => i.Title).IsRequired(); }); builder.Entity<RequestUser>(entity => { entity.Property(i => i.ID).UseIdentityColumn(); entity.Property(i => i.Name).IsRequired(); }); builder.Entity<RequestType>(entity => { entity.Property(i => i.ID).UseIdentityColumn(); entity.Property(i => i.Type).IsRequired(); }); builder.Entity<RequestType>().HasData( new RequestType { ID = -1, Type = "Movie", Enabled = true, }); builder.Entity<RequestType>().HasData( new RequestType { ID = -2, Type = "TV Show", Enabled = true, }); builder.Entity<RequestUser>().HasData( new RequestUser { ID = -1, Name = "Guest", Active = true, }); base.OnModelCreating(builder); } } }
32.510638
98
0.512762
[ "MIT" ]
bnjmnfrdnd/SMSM
Interface/Data/ApplicationDbContext.cs
3,058
C#
using LmpCommon; using LmpCommon.Enums; using LmpGlobal; using System; using System.IO; using System.Linq; using System.Threading.Tasks; using System.Web; using System.Web.UI; using uhttpsharp; using HttpResponse = uhttpsharp.HttpResponse; namespace LmpMasterServer.Http.Handlers { public class ServerListHandler : IHttpRequestHandler { public async Task Handle(IHttpContext context, Func<Task> next) { context.Response = new HttpResponse(HttpResponseCode.Ok, await GetServerList(), false); } private static Task<string> GetServerList() { return Task.Run(() => { var servers = Lidgren.MasterServer.ServerDictionary.Values.Select(s => (ServerInfo)s).ToArray(); using (var stringWriter = new StringWriter()) using (var writer = new HtmlTextWriter(stringWriter)) { RenderHead(writer); writer.RenderBeginTag(HtmlTextWriterTag.H1); writer.Write($"Luna Multiplayer servers - Version: {LmpVersioning.CurrentVersion}"); writer.RenderEndTag(); writer.RenderBeginTag(HtmlTextWriterTag.H3); writer.Write($"Servers: {servers.Length}"); writer.WriteBreak(); writer.Write($"Players: {servers.Sum(s => s.PlayerCount)}"); writer.RenderEndTag(); RenderServersTable(writer, servers); RenderFooter(writer); return stringWriter.ToString(); } }); } private static void RenderHead(HtmlTextWriter writer) { writer.RenderBeginTag(HtmlTextWriterTag.Head); writer.RenderBeginTag(HtmlTextWriterTag.Title); writer.Write("Luna Multiplayer servers"); writer.RenderEndTag(); writer.AddAttribute(HtmlTextWriterAttribute.Rel, "stylesheet"); writer.AddAttribute(HtmlTextWriterAttribute.Type, "text/css"); writer.AddAttribute(HtmlTextWriterAttribute.Href, "css/style.css"); writer.RenderBeginTag(HtmlTextWriterTag.Link); writer.RenderEndTag(); writer.AddAttribute(HtmlTextWriterAttribute.Src, "js/jquery-latest.js"); writer.RenderBeginTag(HtmlTextWriterTag.Script); writer.RenderEndTag(); writer.AddAttribute(HtmlTextWriterAttribute.Src, "js/jquery.metadata.min.js"); writer.RenderBeginTag(HtmlTextWriterTag.Script); writer.RenderEndTag(); writer.AddAttribute(HtmlTextWriterAttribute.Src, "js/jquery.tablesorter.min.js"); writer.RenderBeginTag(HtmlTextWriterTag.Script); writer.RenderEndTag(); writer.AddAttribute(HtmlTextWriterAttribute.Src, "js/lmp.js"); writer.RenderBeginTag(HtmlTextWriterTag.Script); writer.RenderEndTag(); writer.RenderEndTag(); } private static void RenderFooter(HtmlTextWriter writer) { writer.RenderBeginTag(HtmlTextWriterTag.P); writer.RenderBeginTag(HtmlTextWriterTag.Small); writer.AddAttribute(HtmlTextWriterAttribute.Href, RepoConstants.OfficialWebsite); writer.RenderBeginTag(HtmlTextWriterTag.A); writer.Write("Luna Multiplayer"); writer.RenderEndTag(); writer.Write(" - "); writer.AddAttribute(HtmlTextWriterAttribute.Href, RepoConstants.RepoUrl); writer.RenderBeginTag(HtmlTextWriterTag.A); writer.Write("Github repo"); writer.RenderEndTag(); writer.RenderEndTag(); writer.RenderEndTag(); } private static void RenderServersTable(HtmlTextWriter writer, ServerInfo[] servers) { writer.AddAttribute(HtmlTextWriterAttribute.Id, "LmpTable"); writer.AddAttribute(HtmlTextWriterAttribute.Class, "tablesorter"); writer.RenderBeginTag(HtmlTextWriterTag.Table); writer.RenderBeginTag("thead"); writer.RenderBeginTag(HtmlTextWriterTag.Tr); writer.RenderBeginTag(HtmlTextWriterTag.Th); writer.Write("Address"); writer.RenderEndTag(); writer.RenderBeginTag(HtmlTextWriterTag.Th); writer.Write("Country"); writer.RenderEndTag(); writer.RenderBeginTag(HtmlTextWriterTag.Th); writer.Write("Password"); writer.RenderEndTag(); writer.RenderBeginTag(HtmlTextWriterTag.Th); writer.Write("Name"); writer.RenderEndTag(); writer.RenderBeginTag(HtmlTextWriterTag.Th); writer.Write("Description"); writer.RenderEndTag(); writer.RenderBeginTag(HtmlTextWriterTag.Th); writer.Write("URL"); writer.RenderEndTag(); writer.RenderBeginTag(HtmlTextWriterTag.Th); writer.Write("Game mode"); writer.RenderEndTag(); writer.RenderBeginTag(HtmlTextWriterTag.Th); writer.Write("Players"); writer.RenderEndTag(); writer.RenderBeginTag(HtmlTextWriterTag.Th); writer.Write("Max players"); writer.RenderEndTag(); writer.RenderBeginTag(HtmlTextWriterTag.Th); writer.Write("Dedicated"); writer.RenderEndTag(); writer.RenderBeginTag(HtmlTextWriterTag.Th); writer.Write("Mod control"); writer.RenderEndTag(); writer.RenderBeginTag(HtmlTextWriterTag.Th); writer.Write("Terrain quality"); writer.RenderEndTag(); writer.RenderBeginTag(HtmlTextWriterTag.Th); writer.Write("Cheats"); writer.RenderEndTag(); writer.RenderEndTag(); writer.RenderEndTag(); writer.RenderBeginTag("tbody"); foreach (var server in servers) { try { writer.RenderBeginTag(HtmlTextWriterTag.Tr); writer.RenderBeginTag(HtmlTextWriterTag.Td); writer.Write(HttpUtility.HtmlEncode(server.ExternalEndpoint)); writer.RenderEndTag(); writer.RenderBeginTag(HtmlTextWriterTag.Td); writer.Write(HttpUtility.HtmlEncode(server.Country)); writer.RenderEndTag(); writer.RenderBeginTag(HtmlTextWriterTag.Td); writer.Write(HttpUtility.HtmlEncode(server.Password)); writer.RenderEndTag(); writer.RenderBeginTag(HtmlTextWriterTag.Td); writer.Write(HttpUtility.HtmlEncode(server.ServerName)); writer.RenderEndTag(); writer.RenderBeginTag(HtmlTextWriterTag.Td); writer.Write(HttpUtility.HtmlEncode(server.Description)); writer.RenderEndTag(); writer.RenderBeginTag(HtmlTextWriterTag.Td); if (!string.IsNullOrEmpty(server.Website)) { writer.AddAttribute(HtmlTextWriterAttribute.Href, server.Website); writer.RenderBeginTag(HtmlTextWriterTag.A); writer.Write(HttpUtility.HtmlEncode(server.WebsiteText)); writer.RenderEndTag(); } writer.RenderEndTag(); writer.RenderBeginTag(HtmlTextWriterTag.Td); writer.Write(HttpUtility.HtmlEncode((GameMode)server.GameMode)); writer.RenderEndTag(); writer.RenderBeginTag(HtmlTextWriterTag.Td); writer.Write(HttpUtility.HtmlEncode(server.PlayerCount)); writer.RenderEndTag(); writer.RenderBeginTag(HtmlTextWriterTag.Td); writer.Write(HttpUtility.HtmlEncode(server.MaxPlayers)); writer.RenderEndTag(); writer.RenderBeginTag(HtmlTextWriterTag.Td); writer.Write(HttpUtility.HtmlEncode(server.DedicatedServer)); writer.RenderEndTag(); writer.RenderBeginTag(HtmlTextWriterTag.Td); writer.Write(HttpUtility.HtmlEncode(server.ModControl)); writer.RenderEndTag(); writer.RenderBeginTag(HtmlTextWriterTag.Td); writer.Write(HttpUtility.HtmlEncode((TerrainQuality)server.TerrainQuality)); writer.RenderEndTag(); writer.RenderBeginTag(HtmlTextWriterTag.Td); writer.Write(HttpUtility.HtmlEncode(server.Cheats)); writer.RenderEndTag(); writer.RenderEndTag(); } catch (Exception) { // ignored } } writer.RenderEndTag(); writer.RenderEndTag(); } } }
50.192771
172
0.643783
[ "MIT" ]
211network/LunaMultiplayer
LmpMasterServer/Http/Handlers/ServerListHandler.cs
8,334
C#
#region License /* Copyright 2011, 2013 James F. Bellinger <http://www.zer7.com/software/hidsharp> Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #endregion using System; using System.Collections.Generic; namespace HidSharp.ReportDescriptors.Parser { /// <summary> /// Parses HID report descriptors. /// </summary> public class ReportDescriptorParser { /// <summary> /// Initializes a new instance of the <see cref="ReportDescriptorParser"/> class. /// </summary> public ReportDescriptorParser() { RootCollection = new ReportCollection(); GlobalItemStateStack = new List<IDictionary<GlobalItemTag, EncodedItem>>(); LocalItemState = new List<KeyValuePair<LocalItemTag, uint>>(); Reports = new List<Report>(); Clear(); } /// <summary> /// Resets the parser to its initial state. /// </summary> public void Clear() { CurrentCollection = RootCollection; RootCollection.Clear(); GlobalItemStateStack.Clear(); GlobalItemStateStack.Add(new Dictionary<GlobalItemTag, EncodedItem>()); LocalItemState.Clear(); Reports.Clear(); ReportsUseID = false; } public EncodedItem GetGlobalItem(GlobalItemTag tag) { EncodedItem value; GlobalItemState.TryGetValue(tag, out value); return value; } public uint GetGlobalItemValue(GlobalItemTag tag) { EncodedItem item = GetGlobalItem(tag); return item != null ? item.DataValue : 0; } public Report GetReport(ReportType type, byte id) { Report report; if (!TryGetReport(type, id, out report)) { throw new ArgumentException("Report not found."); } return report; } public bool TryGetReport(ReportType type, byte id, out Report report) { for (int i = 0; i < Reports.Count; i++) { report = Reports[i]; if (report.Type == type && report.ID == id) { return true; } } report = null; return false; } static int GetMaxLengthOfReports(IEnumerable<Report> reports) { int length = 0; foreach (Report report in reports) { length = Math.Max(length, report.Length); } return length; } public bool IsGlobalItemSet(GlobalItemTag tag) { return GlobalItemState.ContainsKey(tag); } /// <summary> /// Parses a raw HID report descriptor. /// </summary> /// <param name="buffer">The buffer containing the report descriptor.</param> public void Parse(byte[] buffer) { if (buffer == null) { throw new ArgumentNullException("buffer"); } Parse(buffer, 0, buffer.Length); } /// <summary> /// Parses a raw HID report descriptor. /// </summary> /// <param name="buffer">The buffer containing the report descriptor.</param> /// <param name="offset">The offset into the buffer to begin parsing from.</param> /// <param name="count">The number of bytes to parse.</param> public void Parse(byte[] buffer, int offset, int count) { var items = ReportDescriptors.EncodedItem.DecodeRaw(buffer, offset, count); Parse(items); } /// <summary> /// Parses all of the <see cref="EncodedItem"/> elements in a report descriptor. /// </summary> /// <param name="items">The items to parse.</param> public void Parse(IEnumerable<EncodedItem> items) { if (items == null) { throw new ArgumentNullException("items"); } foreach (EncodedItem item in items) { Parse(item); } } /// <summary> /// Parses a single <see cref="EncodedItem"/>. /// Call this repeatedly for every item to completely decode a report descriptor. /// </summary> /// <param name="item">The item to parse.</param> public void Parse(EncodedItem item) { if (item == null) { throw new ArgumentNullException("item"); } uint value = item.DataValue; switch (item.Type) { case ItemType.Main: ParseMain(item.TagForMain, value); LocalItemState.Clear(); break; case ItemType.Local: switch (item.TagForLocal) { case LocalItemTag.Usage: case LocalItemTag.UsageMinimum: case LocalItemTag.UsageMaximum: if (value <= 0xffff) { value |= GetGlobalItemValue(GlobalItemTag.UsagePage) << 16; } break; } LocalItemState.Add(new KeyValuePair<LocalItemTag, uint>(item.TagForLocal, value)); break; case ItemType.Global: switch (item.TagForGlobal) { case GlobalItemTag.Push: GlobalItemStateStack.Add(new Dictionary<GlobalItemTag, EncodedItem>(GlobalItemState)); break; case GlobalItemTag.Pop: GlobalItemStateStack.RemoveAt(GlobalItemState.Count - 1); break; default: switch (item.TagForGlobal) { case GlobalItemTag.ReportID: ReportsUseID = true; break; } GlobalItemState[item.TagForGlobal] = item; break; } break; } } void ParseMain(MainItemTag tag, uint value) { LocalIndexes indexes = null; switch (tag) { case MainItemTag.Collection: ReportCollection collection = new ReportCollection(); collection.Parent = CurrentCollection; collection.Type = (CollectionType)value; CurrentCollection = collection; indexes = collection.Indexes; break; case MainItemTag.EndCollection: CurrentCollection = CurrentCollection.Parent; break; case MainItemTag.Input: case MainItemTag.Output: case MainItemTag.Feature: ParseDataMain(tag, value, out indexes); break; } if (indexes != null) { ParseMainIndexes(indexes); } } static void AddIndex(List<KeyValuePair<int, uint>> list, int action, uint value) { list.Add(new KeyValuePair<int, uint>(action, value)); } static void UpdateIndexMinimum(ref IndexBase index, uint value) { if (!(index is IndexRange)) { index = new IndexRange(); } ((IndexRange)index).Minimum = value; } static void UpdateIndexMaximum(ref IndexBase index, uint value) { if (!(index is IndexRange)) { index = new IndexRange(); } ((IndexRange)index).Maximum = value; } static void UpdateIndexList(List<uint> values, int delimiter, ref IndexBase index, uint value) { values.Add(value); UpdateIndexListCommit(values, delimiter, ref index); } static void UpdateIndexListCommit(List<uint> values, int delimiter, ref IndexBase index) { if (delimiter != 0 || values.Count == 0) { return; } if (!(index is IndexList)) { index = new IndexList(); } ((IndexList)index).Indices.Add(new List<uint>(values)); values.Clear(); } void ParseMainIndexes(LocalIndexes indexes) { int delimiter = 0; List<uint> designatorValues = new List<uint>(); IndexBase designator = IndexBase.Unset; List<uint> stringValues = new List<uint>(); IndexBase @string = IndexBase.Unset; List<uint> usageValues = new List<uint>(); IndexBase usage = IndexBase.Unset; foreach (KeyValuePair<LocalItemTag, uint> kvp in LocalItemState) { switch (kvp.Key) { case LocalItemTag.DesignatorMinimum: UpdateIndexMinimum(ref designator, kvp.Value); break; case LocalItemTag.StringMinimum: UpdateIndexMinimum(ref @string, kvp.Value); break; case LocalItemTag.UsageMinimum: UpdateIndexMinimum(ref usage, kvp.Value); break; case LocalItemTag.DesignatorMaximum: UpdateIndexMaximum(ref designator, kvp.Value); break; case LocalItemTag.StringMaximum: UpdateIndexMaximum(ref @string, kvp.Value); break; case LocalItemTag.UsageMaximum: UpdateIndexMaximum(ref usage, kvp.Value); break; case LocalItemTag.DesignatorIndex: UpdateIndexList(designatorValues, delimiter, ref designator, kvp.Value); break; case LocalItemTag.StringIndex: UpdateIndexList(stringValues, delimiter, ref @string, kvp.Value); break; case LocalItemTag.Usage: UpdateIndexList(usageValues, delimiter, ref usage, kvp.Value); break; case LocalItemTag.Delimiter: if (kvp.Value == 1) { if (delimiter++ == 0) { designatorValues.Clear(); stringValues.Clear(); usageValues.Clear(); } } else if (kvp.Value == 0) { delimiter--; UpdateIndexListCommit(designatorValues, delimiter, ref designator); UpdateIndexListCommit(stringValues, delimiter, ref @string); UpdateIndexListCommit(usageValues, delimiter, ref usage); } break; } } indexes.Designator = designator; indexes.String = @string; indexes.Usage = usage; } void ParseDataMain(MainItemTag tag, uint value, out LocalIndexes indexes) { ReportSegment segment = new ReportSegment(); segment.Flags = (DataMainItemFlags)value; segment.Parent = CurrentCollection; segment.ElementCount = (int)GetGlobalItemValue(GlobalItemTag.ReportCount); segment.ElementSize = (int)GetGlobalItemValue(GlobalItemTag.ReportSize); segment.Unit = new Units.Unit(GetGlobalItemValue(GlobalItemTag.Unit)); segment.UnitExponent = Units.Unit.DecodeExponent(GetGlobalItemValue(GlobalItemTag.UnitExponent)); indexes = segment.Indexes; EncodedItem logicalMinItem = GetGlobalItem(GlobalItemTag.LogicalMinimum); EncodedItem logicalMaxItem = GetGlobalItem(GlobalItemTag.LogicalMaximum); segment.LogicalIsSigned = (logicalMinItem != null && logicalMinItem.DataValueMayBeNegative) || (logicalMaxItem != null && logicalMaxItem.DataValueMayBeNegative); int logicalMinimum = logicalMinItem == null ? 0 : segment.LogicalIsSigned ? logicalMinItem.DataValueSigned : (int)logicalMinItem.DataValue; int logicalMaximum = logicalMaxItem == null ? 0 : segment.LogicalIsSigned ? logicalMaxItem.DataValueSigned : (int)logicalMaxItem.DataValue; int physicalMinimum = (int)GetGlobalItemValue(GlobalItemTag.PhysicalMinimum); int physicalMaximum = (int)GetGlobalItemValue(GlobalItemTag.PhysicalMaximum); if (!IsGlobalItemSet(GlobalItemTag.PhysicalMinimum) || !IsGlobalItemSet(GlobalItemTag.PhysicalMaximum) || (physicalMinimum == 0 && physicalMaximum == 0)) { physicalMinimum = logicalMinimum; physicalMaximum = logicalMaximum; } segment.LogicalMinimum = logicalMinimum; segment.LogicalMaximum = logicalMaximum; segment.PhysicalMinimum = physicalMinimum; segment.PhysicalMaximum = physicalMaximum; Report report; ReportType reportType = tag == MainItemTag.Output ? ReportType.Output : tag == MainItemTag.Feature ? ReportType.Feature : ReportType.Input; uint reportID = GetGlobalItemValue(GlobalItemTag.ReportID); if (!TryGetReport(reportType, (byte)reportID, out report)) { report = new Report() { ID = (byte)reportID, Type = reportType }; Reports.Add(report); } segment.Report = report; } public ReportCollection CurrentCollection { get; set; } public ReportCollection RootCollection { get; private set; } public IDictionary<GlobalItemTag, EncodedItem> GlobalItemState { get { return GlobalItemStateStack[GlobalItemStateStack.Count - 1]; } } public IList<IDictionary<GlobalItemTag, EncodedItem>> GlobalItemStateStack { get; private set; } public IList<KeyValuePair<LocalItemTag, uint>> LocalItemState { get; private set; } IEnumerable<Report> FilterReports(ReportType reportType) { foreach (Report report in Reports) { if (report.Type == reportType) { yield return report; } } } public IEnumerable<Report> InputReports { get { return FilterReports(ReportType.Input); } } /// <summary> /// The maximum input report length. /// The Report ID is not included in this length. /// </summary> public int InputReportMaxLength { get { return GetMaxLengthOfReports(InputReports); } } public IEnumerable<Report> OutputReports { get { return FilterReports(ReportType.Output); } } /// <summary> /// The maximum output report length. /// The Report ID is not included in this length. /// </summary> public int OutputReportMaxLength { get { return GetMaxLengthOfReports(OutputReports); } } public IEnumerable<Report> FeatureReports { get { return FilterReports(ReportType.Feature); } } /// <summary> /// The maximum feature report length. /// The Report ID is not included in this length. /// </summary> public int FeatureReportMaxLength { get { return GetMaxLengthOfReports(FeatureReports); } } public IList<Report> Reports { get; private set; } /// <summary> /// True if the device sends Report IDs. /// </summary> public bool ReportsUseID { get; set; } public IEnumerable<IEnumerable<uint>> InputUsages { get { foreach (Report report in InputReports) { foreach (ReportSegment segment in report.Segments) { IndexBase usages = segment.Indexes.Usage; for (int i = 0; i < usages.Count; i++) { yield return usages.ValuesFromIndex(i); } } } } } } }
39.087248
152
0.532624
[ "Apache-2.0" ]
gbrayut/dreamcheekyusb
DreamCheekyBTN/HidSharp/ReportDescriptors/Parser/ReportDescriptorParser.cs
17,474
C#
namespace CreatorSpace.Application.Comments.Commands.DeleteComment { using FluentValidation; public class DeleteCommentCommandValidator : AbstractValidator<DeleteCommentCommand> { public DeleteCommentCommandValidator() { this.RuleFor(x => x.Id).NotEmpty().WithMessage("Id is required"); } } }
26.692308
88
0.691643
[ "MIT" ]
gdemu13/CreatorSpace
src/CreatorSpace/Application/Comments/Commands/DeleteComment/DeleteCommentCommandValidator.cs
349
C#
// Copyright (c) The Avalonia Project. All rights reserved. // Licensed under the MIT license. See licence.md file in the project root for full license information. using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Reactive.Linq; using Avalonia.Data.Converters; using Avalonia.Metadata; namespace Avalonia.Data { /// <summary> /// A XAML binding that calculates an aggregate value from multiple child <see cref="Bindings"/>. /// </summary> public class MultiBinding : IBinding { /// <summary> /// Gets the collection of child bindings. /// </summary> [Content] public IList<IBinding> Bindings { get; set; } = new List<IBinding>(); /// <summary> /// Gets or sets the <see cref="IValueConverter"/> to use. /// </summary> public IMultiValueConverter Converter { get; set; } /// <summary> /// Gets or sets the value to use when the binding is unable to produce a value. /// </summary> public object FallbackValue { get; set; } /// <summary> /// Gets or sets the binding mode. /// </summary> public BindingMode Mode { get; set; } = BindingMode.OneWay; /// <summary> /// Gets or sets the binding priority. /// </summary> public BindingPriority Priority { get; set; } /// <summary> /// Gets or sets the relative source for the binding. /// </summary> public RelativeSource RelativeSource { get; set; } /// <inheritdoc/> public InstancedBinding Initiate( IAvaloniaObject target, AvaloniaProperty targetProperty, object anchor = null, bool enableDataValidation = false) { if (Converter == null) { throw new NotSupportedException("MultiBinding without Converter not currently supported."); } var targetType = targetProperty?.PropertyType ?? typeof(object); var children = Bindings.Select(x => x.Initiate(target, null)); var input = children.Select(x => x.Observable).CombineLatest().Select(x => ConvertValue(x, targetType)); var mode = Mode == BindingMode.Default ? targetProperty?.GetMetadata(target.GetType()).DefaultBindingMode : Mode; switch (mode) { case BindingMode.OneTime: return InstancedBinding.OneTime(input, Priority); case BindingMode.OneWay: return InstancedBinding.OneWay(input, Priority); default: throw new NotSupportedException( "MultiBinding currently only supports OneTime and OneWay BindingMode."); } } private object ConvertValue(IList<object> values, Type targetType) { var converted = Converter.Convert(values, targetType, null, CultureInfo.CurrentCulture); if (converted == AvaloniaProperty.UnsetValue && FallbackValue != null) { converted = FallbackValue; } return converted; } } }
35.107527
116
0.586524
[ "MIT" ]
SteveL-MSFT/Avalonia
src/Markup/Avalonia.Markup/Data/MultiBinding.cs
3,265
C#
using Newtonsoft.Json.Linq; using Skybrud.Essentials.Json.Extensions; namespace Skybrud.Social.GitHub.Models.Commits { /// <summary> /// Class representing the tree of a given commit. /// </summary> public class GitHubCommitTree : GitHubObject { #region Properties /// <summary> /// Gets the SHA hash of the tree. /// </summary> public string Sha { get; } /// <summary> /// Gets the API URL of the tree. /// </summary> public string Url { get; } #endregion #region Constructors private GitHubCommitTree(JObject obj) : base(obj) { Sha = obj.GetString("sha"); Url = obj.GetString("url"); } #endregion #region Static methods /// <summary> /// Parses the specified <paramref name="obj"/> into an instance of <see cref="GitHubCommitTree"/>. /// </summary> /// <param name="obj">The instance of <see cref="JObject"/> to be parsed.</param> /// <returns>An instance of <see cref="GitHubCommitTree"/>.</returns> public static GitHubCommitTree Parse(JObject obj) { return obj == null ? null : new GitHubCommitTree(obj); } #endregion } }
26.55102
107
0.558801
[ "MIT" ]
abjerner/Skybrud.Social.GitHub
src/Skybrud.Social.GitHub/Models/Commits/GitHubCommitTree.cs
1,303
C#
namespace BGuidinger.Xrm.Sdk.Management { using Newtonsoft.Json; using System.Net.Http; public class UpdateAdminMode : Message { internal override HttpMethod Method => HttpMethod.Post; internal override string RequestUri => $"/Instances/{InstanceId}/UpdateAdminMode?validate={Validate.ToString().ToLower()}"; [JsonIgnore] public string InstanceId { get; set; } [JsonIgnore] public bool Validate { get; set; } = false; [JsonProperty("AdminMode")] public bool AdminMode { get; set; } [JsonProperty("BackgroundOperationsEnabled")] public bool BackgroundOperationsEnabled { get; set; } [JsonProperty("NotificationText")] public string NotificationText { get; set; } [JsonProperty("OverrideUserObjectId")] public string OverrideUserObjectId { get; set; } } }
35.56
131
0.658043
[ "MIT" ]
bguidinger/Xrm.Sdk.Management
src/Management/Messages/Instances/UpdateAdminMode.cs
891
C#
// // Copyright (c) Microsoft. 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. // using System.Reflection; using System.Resources; using System.Runtime.InteropServices; [assembly: AssemblyTitle("Microsoft Azure Server Management Library")] [assembly: AssemblyDescription("Provides Microsoft Azure Server Management functions for servers via Azure.")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.9.0")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("Microsoft Azure .NET SDK")] [assembly: AssemblyCopyright("Copyright (c) Microsoft Corporation")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("en")]
38.69697
110
0.763508
[ "MIT" ]
samtoubia/azure-sdk-for-net
src/ResourceManagement/ServerManagement/Microsoft.Azure.Management.ServerManagement/Properties/AssemblyInfo.cs
1,277
C#
using System.Text.Json.Serialization; namespace AmmBot.Core.Json.Models { /// <summary> /// Представляет сообщение-действие в диалоге. /// </summary> public class MessageAction { /// <summary> /// Тип действия. /// </summary> [JsonInclude] [JsonPropertyName("type")] public string Type { get; init; } /// <summary> /// Идентификатор пользователя, связанного с действием. /// </summary> [JsonInclude] [JsonPropertyName("member_id")] public long MemberId { get; init; } /// <summary> /// Контекст действия. /// </summary> [JsonInclude] [JsonPropertyName("text")] public string Text { get; init; } /// <summary> /// Электронная почта пользователя, связанная с действием. /// </summary> [JsonInclude] [JsonPropertyName("email")] public string Email { get; init; } /// <summary> /// Фотография, связанная с действием. /// </summary> [JsonInclude] [JsonPropertyName("photo")] public MessagePhoto Photo { get; init; } } }
26.288889
66
0.541843
[ "Apache-2.0" ]
Niapollab/AmmBot
AmmBot.Core/Json/Models/MessageAction.cs
1,368
C#
using System.Linq; using System.Threading.Tasks; using GitLabCLI.Console.Output; using GitLabCLI.Core.Gitlab; using GitLabCLI.Core.Gitlab.Merges; namespace GitLabCLI.Console { public sealed class GitLabMergeRequestsHandler { private readonly IGitLabFacade _gitLabFacade; private readonly OutputPresenter _presenter; public GitLabMergeRequestsHandler(IGitLabFacade gitLabFacade, OutputPresenter presenter) { _gitLabFacade = gitLabFacade; _presenter = presenter; } public async Task CreateMergeRequest(CreateMergeRequestParameters parameters) { var mergeRequestResult = await _gitLabFacade.CreateMergeRequest(parameters); if (mergeRequestResult.IsFailure) { _presenter.ShowError("Failed to create merge request", mergeRequestResult.Error); return; } _presenter.ShowSuccess($"Successfully created merge request #{mergeRequestResult.Value}"); } public async Task ListMerges(ListMergesParameters parameters) { var mergesResult = await _gitLabFacade.ListMergeRequests(parameters); if (mergesResult.IsFailure) { _presenter.ShowError("Failed to retrieve merge requests", mergesResult.Error); return; } var merges = mergesResult.Value; if (merges.Count == 0) { _presenter.ShowSuccess($"No merge requests found in project {parameters.Project}"); return; } _presenter.ShowGrid( $"Found ({merges.Count}) merge requests in project {parameters.Project}", new GridColumn<int>("Merge request Id", 20, merges.Select(s => s.Id)), new GridColumn("Title", 100, merges.Select(s => s.Title)), new GridColumn("Assignee", 50, merges.Select(s => s.Assignee))); } } }
35.75
102
0.618881
[ "MIT" ]
nmklotas/GitLabCLI
src/GitlabCLI.Console/GitLabMergeRequestsHandler.cs
2,004
C#
#region Header /** * JsonMapper.cs * JSON to .Net object and object to JSON conversions. * * The authors disclaim copyright to this source code. For more details, see * the COPYING file included with this distribution. **/ #endregion using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Reflection; namespace LitJson { internal struct PropertyMetadata { public MemberInfo Info; public bool IsField; public Type Type; public String Name; } internal struct ArrayMetadata { private Type element_type; private bool is_array; private bool is_list; public Type ElementType { get { if (element_type == null) return typeof (JsonData); return element_type; } set { element_type = value; } } public bool IsArray { get { return is_array; } set { is_array = value; } } public bool IsList { get { return is_list; } set { is_list = value; } } } internal struct ObjectMetadata { private Type element_type; private bool is_dictionary; private IDictionary<string, PropertyMetadata> properties; public Type ElementType { get { if (element_type == null) return typeof (JsonData); return element_type; } set { element_type = value; } } public bool IsDictionary { get { return is_dictionary; } set { is_dictionary = value; } } public IDictionary<string, PropertyMetadata> Properties { get { return properties; } set { properties = value; } } } internal delegate void ExporterFunc (object obj, JsonWriter writer); public delegate void ExporterFunc<T> (T obj, JsonWriter writer); internal delegate object ImporterFunc (object input); public delegate TValue ImporterFunc<TJson, TValue> (TJson input); public delegate IJsonWrapper WrapperFactory (); public class JsonMapper { #region Fields private static int max_nesting_depth; private static IFormatProvider datetime_format; private static IDictionary<Type, ExporterFunc> base_exporters_table; private static IDictionary<Type, ExporterFunc> custom_exporters_table; private static IDictionary<Type, IDictionary<Type, ImporterFunc>> base_importers_table; private static IDictionary<Type, IDictionary<Type, ImporterFunc>> custom_importers_table; private static IDictionary<Type, ArrayMetadata> array_metadata; private static readonly object array_metadata_lock = new Object (); private static IDictionary<Type, IDictionary<Type, MethodInfo>> conv_ops; private static readonly object conv_ops_lock = new Object (); private static IDictionary<Type, ObjectMetadata> object_metadata; private static readonly object object_metadata_lock = new Object (); private static IDictionary<Type, IList<PropertyMetadata>> type_properties; private static readonly object type_properties_lock = new Object (); private static JsonWriter static_writer; private static readonly object static_writer_lock = new Object (); #endregion #region Constructors static JsonMapper () { max_nesting_depth = 100; array_metadata = new Dictionary<Type, ArrayMetadata> (); conv_ops = new Dictionary<Type, IDictionary<Type, MethodInfo>> (); object_metadata = new Dictionary<Type, ObjectMetadata> (); type_properties = new Dictionary<Type, IList<PropertyMetadata>> (); static_writer = new JsonWriter (); datetime_format = DateTimeFormatInfo.InvariantInfo; base_exporters_table = new Dictionary<Type, ExporterFunc> (); custom_exporters_table = new Dictionary<Type, ExporterFunc> (); base_importers_table = new Dictionary<Type, IDictionary<Type, ImporterFunc>> (); custom_importers_table = new Dictionary<Type, IDictionary<Type, ImporterFunc>> (); RegisterBaseExporters (); RegisterBaseImporters (); } #endregion #region Private Methods private static void AddArrayMetadata (Type type) { if (array_metadata.ContainsKey (type)) return; ArrayMetadata data = new ArrayMetadata (); data.IsArray = type.IsArray; if (type.GetInterface ("System.Collections.IList") != null) data.IsList = true; foreach (PropertyInfo p_info in type.GetProperties(BindingFlags.Instance | BindingFlags.Public)) { if (p_info.Name != "Item") continue; ParameterInfo[] parameters = p_info.GetIndexParameters (); if (parameters.Length != 1) continue; if (parameters[0].ParameterType == typeof (int)) data.ElementType = p_info.PropertyType; } lock (array_metadata_lock) { try { array_metadata.Add (type, data); } catch (ArgumentException) { return; } } } private static void AddObjectMetadata (Type type) { if (object_metadata.ContainsKey (type)) return; ObjectMetadata data = new ObjectMetadata (); if (type.GetInterface ("System.Collections.IDictionary") != null) data.IsDictionary = true; data.Properties = new Dictionary<string, PropertyMetadata> (); foreach (PropertyInfo p_info in type.GetProperties(BindingFlags.Instance | BindingFlags.Public)) { if (p_info.IsDefined(typeof(YingJsonIgnore), true)) continue; //Ying Json Ignore if (p_info.Name == "Item") { ParameterInfo[] parameters = p_info.GetIndexParameters (); if (parameters.Length == 1) { if (parameters[0].ParameterType == typeof(string)) data.ElementType = p_info.PropertyType; continue; } if (parameters.Length > 1) continue; } PropertyMetadata p_data = new PropertyMetadata (); p_data.Info = p_info; p_data.Type = p_info.PropertyType; if (p_info.IsDefined(typeof(JsonPropertyName),true)) { var att = (JsonPropertyName)p_info.GetCustomAttributes(typeof(JsonPropertyName), true)[0]; data.Properties.Add(att.Name, p_data); } else { data.Properties.Add(p_info.Name, p_data); } } foreach (FieldInfo f_info in type.GetFields(BindingFlags.Instance | BindingFlags.Public)) { if (f_info.IsDefined(typeof(YingJsonIgnore), true)) continue; //Ying Json Ignore PropertyMetadata p_data = new PropertyMetadata (); p_data.Info = f_info; p_data.IsField = true; p_data.Type = f_info.FieldType; if (f_info.IsDefined(typeof(JsonPropertyName), true)) { var att = (JsonPropertyName)f_info.GetCustomAttributes(typeof(JsonPropertyName), true)[0]; data.Properties.Add(att.Name, p_data); } else { data.Properties.Add(f_info.Name, p_data); } } lock (object_metadata_lock) { try { object_metadata.Add (type, data); } catch (ArgumentException) { return; } } } private static void AddTypeProperties (Type type) { if (type_properties.ContainsKey (type)) return; IList<PropertyMetadata> props = new List<PropertyMetadata> (); foreach (PropertyInfo p_info in type.GetProperties(BindingFlags.Instance | BindingFlags.Public)) { if (p_info.IsDefined(typeof(YingJsonIgnore), true)) continue; //Ying Json Ignore if (p_info.Name == "Item") { if (p_info.GetIndexParameters().Length > 0) continue; } PropertyMetadata p_data = new PropertyMetadata(); p_data.Info = p_info; p_data.IsField = false; if (p_info.IsDefined(typeof(JsonPropertyName), true)) { var att = (JsonPropertyName)p_info.GetCustomAttributes(typeof(JsonPropertyName), true)[0]; p_data.Name = att.Name; } else { p_data.Name = p_info.Name; } props.Add (p_data); } foreach (FieldInfo f_info in type.GetFields(BindingFlags.Instance | BindingFlags.Public)) { if (f_info.IsDefined(typeof(YingJsonIgnore), true)) continue; //Ying Json Ignore PropertyMetadata p_data = new PropertyMetadata (); p_data.Info = f_info; p_data.IsField = true; if (f_info.IsDefined(typeof(JsonPropertyName), true)) { var att = (JsonPropertyName)f_info.GetCustomAttributes(typeof(JsonPropertyName), true)[0]; p_data.Name = att.Name; } else { p_data.Name = f_info.Name; } props.Add (p_data); } lock (type_properties_lock) { try { type_properties.Add (type, props); } catch (ArgumentException) { return; } } } private static MethodInfo GetConvOp (Type t1, Type t2) { lock (conv_ops_lock) { if (! conv_ops.ContainsKey (t1)) conv_ops.Add (t1, new Dictionary<Type, MethodInfo> ()); } if (conv_ops[t1].ContainsKey (t2)) return conv_ops[t1][t2]; MethodInfo op = t1.GetMethod ( "op_Implicit", new Type[] { t2 }); lock (conv_ops_lock) { try { conv_ops[t1].Add (t2, op); } catch (ArgumentException) { return conv_ops[t1][t2]; } } return op; } private static object ReadValue (Type inst_type, JsonReader reader) { reader.Read (); if (reader.Token == JsonToken.ArrayEnd) return null; if (reader.Token == JsonToken.Null) { if (! inst_type.IsClass) throw new JsonException (String.Format ( "Can't assign null to an instance of type {0}", inst_type)); return null; } if (reader.Token == JsonToken.Double || reader.Token == JsonToken.Int || reader.Token == JsonToken.Long || reader.Token == JsonToken.String || reader.Token == JsonToken.Boolean) { Type json_type = reader.Value.GetType (); if (inst_type.IsAssignableFrom (json_type)) return reader.Value; // If there's a custom importer that fits, use it if (custom_importers_table.ContainsKey (json_type) && custom_importers_table[json_type].ContainsKey ( inst_type)) { ImporterFunc importer = custom_importers_table[json_type][inst_type]; return importer (reader.Value); } // Maybe there's a base importer that works if (base_importers_table.ContainsKey (json_type) && base_importers_table[json_type].ContainsKey ( inst_type)) { ImporterFunc importer = base_importers_table[json_type][inst_type]; return importer (reader.Value); } // Maybe it's an enum if (inst_type.IsEnum) return Enum.ToObject (inst_type, reader.Value); // Try using an implicit conversion operator MethodInfo conv_op = GetConvOp (inst_type, json_type); if (conv_op != null) return conv_op.Invoke (null, new object[] { reader.Value }); // No luck throw new JsonException (String.Format ( "Can't assign value '{0}' (type {1}) to type {2}", reader.Value, json_type, inst_type)); } object instance = null; if (reader.Token == JsonToken.ArrayStart) { AddArrayMetadata (inst_type); ArrayMetadata t_data = array_metadata[inst_type]; if (! t_data.IsArray && ! t_data.IsList) throw new JsonException (String.Format ( "Type {0} can't act as an array", inst_type)); IList list; Type elem_type; if (! t_data.IsArray) { list = (IList) Activator.CreateInstance (inst_type); elem_type = t_data.ElementType; } else { list = new ArrayList (); elem_type = inst_type.GetElementType (); } while (true) { object item = ReadValue (elem_type, reader); if (item == null && reader.Token == JsonToken.ArrayEnd) break; list.Add (item); } if (t_data.IsArray) { int n = list.Count; instance = Array.CreateInstance (elem_type, n); for (int i = 0; i < n; i++) ((Array) instance).SetValue (list[i], i); } else instance = list; } else if (reader.Token == JsonToken.ObjectStart) { AddObjectMetadata (inst_type); ObjectMetadata t_data = object_metadata[inst_type]; instance = Activator.CreateInstance (inst_type); while (true) { reader.Read (); if (reader.Token == JsonToken.ObjectEnd) break; string property = (string) reader.Value; if (t_data.Properties.ContainsKey (property)) { PropertyMetadata prop_data = t_data.Properties[property]; if (prop_data.IsField) { ((FieldInfo) prop_data.Info).SetValue ( instance, ReadValue (prop_data.Type, reader)); } else { PropertyInfo p_info = (PropertyInfo) prop_data.Info; if (p_info.CanWrite) p_info.SetValue ( instance, ReadValue (prop_data.Type, reader), null); else ReadValue (prop_data.Type, reader); } } else { if (! t_data.IsDictionary) { if (! reader.SkipNonMembers) { throw new JsonException (String.Format ( "The type {0} doesn't have the " + "property '{1}'", inst_type, property)); } else { ReadSkip (reader); continue; } } ((IDictionary) instance).Add ( property, ReadValue ( t_data.ElementType, reader)); } } } return instance; } private static IJsonWrapper ReadValue (WrapperFactory factory, JsonReader reader) { reader.Read (); if (reader.Token == JsonToken.ArrayEnd || reader.Token == JsonToken.Null) return null; IJsonWrapper instance = factory (); if (reader.Token == JsonToken.String) { instance.SetString ((string) reader.Value); return instance; } if (reader.Token == JsonToken.Double) { instance.SetDouble ((double) reader.Value); return instance; } if (reader.Token == JsonToken.Int) { instance.SetInt ((int) reader.Value); return instance; } if (reader.Token == JsonToken.Long) { instance.SetLong ((long) reader.Value); return instance; } if (reader.Token == JsonToken.Boolean) { instance.SetBoolean ((bool) reader.Value); return instance; } if (reader.Token == JsonToken.ArrayStart) { instance.SetJsonType (JsonType.Array); while (true) { IJsonWrapper item = ReadValue (factory, reader); if (item == null && reader.Token == JsonToken.ArrayEnd) break; ((IList) instance).Add (item); } } else if (reader.Token == JsonToken.ObjectStart) { instance.SetJsonType (JsonType.Object); while (true) { reader.Read (); if (reader.Token == JsonToken.ObjectEnd) break; string property = (string) reader.Value; ((IDictionary) instance)[property] = ReadValue ( factory, reader); } } return instance; } private static void ReadSkip (JsonReader reader) { ToWrapper ( delegate { return new JsonMockWrapper (); }, reader); } private static void RegisterBaseExporters () { base_exporters_table[typeof (byte)] = delegate (object obj, JsonWriter writer) { writer.Write (Convert.ToInt32 ((byte) obj)); }; base_exporters_table[typeof (char)] = delegate (object obj, JsonWriter writer) { writer.Write (Convert.ToString ((char) obj)); }; base_exporters_table[typeof (DateTime)] = delegate (object obj, JsonWriter writer) { writer.Write (Convert.ToString ((DateTime) obj, datetime_format)); }; base_exporters_table[typeof (decimal)] = delegate (object obj, JsonWriter writer) { writer.Write ((decimal) obj); }; base_exporters_table[typeof (sbyte)] = delegate (object obj, JsonWriter writer) { writer.Write (Convert.ToInt32 ((sbyte) obj)); }; base_exporters_table[typeof (short)] = delegate (object obj, JsonWriter writer) { writer.Write (Convert.ToInt32 ((short) obj)); }; base_exporters_table[typeof (ushort)] = delegate (object obj, JsonWriter writer) { writer.Write (Convert.ToInt32 ((ushort) obj)); }; base_exporters_table[typeof (uint)] = delegate (object obj, JsonWriter writer) { writer.Write (Convert.ToUInt64 ((uint) obj)); }; base_exporters_table[typeof (ulong)] = delegate (object obj, JsonWriter writer) { writer.Write ((ulong) obj); }; } private static void RegisterBaseImporters () { ImporterFunc importer; importer = delegate (object input) { return Convert.ToByte ((int) input); }; RegisterImporter (base_importers_table, typeof (int), typeof (byte), importer); importer = delegate (object input) { return Convert.ToUInt64 ((int) input); }; RegisterImporter (base_importers_table, typeof (int), typeof (ulong), importer); importer = delegate (object input) { return Convert.ToSByte ((int) input); }; RegisterImporter (base_importers_table, typeof (int), typeof (sbyte), importer); importer = delegate (object input) { return Convert.ToInt16 ((int) input); }; RegisterImporter (base_importers_table, typeof (int), typeof (short), importer); importer = delegate (object input) { return Convert.ToUInt16 ((int) input); }; RegisterImporter (base_importers_table, typeof (int), typeof (ushort), importer); importer = delegate (object input) { return Convert.ToUInt32 ((int) input); }; RegisterImporter (base_importers_table, typeof (int), typeof (uint), importer); importer = delegate (object input) { return Convert.ToSingle ((int) input); }; RegisterImporter (base_importers_table, typeof (int), typeof (float), importer); importer = delegate (object input) { return Convert.ToDouble ((int) input); }; RegisterImporter (base_importers_table, typeof (int), typeof (double), importer); importer = delegate (object input) { return Convert.ToDecimal ((double) input); }; RegisterImporter (base_importers_table, typeof (double), typeof (decimal), importer); importer = delegate (object input) { return Convert.ToUInt32 ((long) input); }; RegisterImporter (base_importers_table, typeof (long), typeof (uint), importer); importer = delegate (object input) { return Convert.ToChar ((string) input); }; RegisterImporter (base_importers_table, typeof (string), typeof (char), importer); importer = delegate (object input) { return Convert.ToDateTime ((string) input, datetime_format); }; RegisterImporter (base_importers_table, typeof (string), typeof (DateTime), importer); } private static void RegisterImporter ( IDictionary<Type, IDictionary<Type, ImporterFunc>> table, Type json_type, Type value_type, ImporterFunc importer) { if (! table.ContainsKey (json_type)) table.Add (json_type, new Dictionary<Type, ImporterFunc> ()); table[json_type][value_type] = importer; } private static void WriteValue (object obj, JsonWriter writer, bool writer_is_private, int depth) { if (depth > max_nesting_depth) throw new JsonException ( String.Format ("Max allowed object depth reached while " + "trying to export from type {0}", obj.GetType ())); if (obj == null) { writer.Write (null); return; } if (obj is IJsonWrapper) { if (writer_is_private) writer.TextWriter.Write (((IJsonWrapper) obj).ToJson ()); else ((IJsonWrapper) obj).ToJson (writer); return; } if (obj is String) { writer.Write ((string) obj); return; } if (obj is Double) { writer.Write ((double) obj); return; } if (obj is Int32) { writer.Write ((int) obj); return; } if (obj is Boolean) { writer.Write ((bool) obj); return; } if (obj is Int64) { writer.Write ((long) obj); return; } if (obj is Array) { writer.WriteArrayStart (); foreach (object elem in (Array) obj) WriteValue (elem, writer, writer_is_private, depth + 1); writer.WriteArrayEnd (); return; } if (obj is IList) { writer.WriteArrayStart (); foreach (object elem in (IList) obj) WriteValue (elem, writer, writer_is_private, depth + 1); writer.WriteArrayEnd (); return; } if (obj is IDictionary) { writer.WriteObjectStart (); foreach (DictionaryEntry entry in (IDictionary) obj) { writer.WritePropertyName ((string) entry.Key); WriteValue (entry.Value, writer, writer_is_private, depth + 1); } writer.WriteObjectEnd (); return; } Type obj_type = obj.GetType (); // See if there's a custom exporter for the object if (custom_exporters_table.ContainsKey (obj_type)) { ExporterFunc exporter = custom_exporters_table[obj_type]; exporter (obj, writer); return; } // If not, maybe there's a base exporter if (base_exporters_table.ContainsKey (obj_type)) { ExporterFunc exporter = base_exporters_table[obj_type]; exporter (obj, writer); return; } // Last option, let's see if it's an enum if (obj is Enum) { Type e_type = Enum.GetUnderlyingType (obj_type); if (e_type == typeof (long) || e_type == typeof (uint) || e_type == typeof (ulong)) writer.Write ((ulong) obj); else writer.Write ((int) obj); return; } // Okay, so it looks like the input should be exported as an // object AddTypeProperties (obj_type); IList<PropertyMetadata> props = type_properties[obj_type]; writer.WriteObjectStart (); foreach (PropertyMetadata p_data in props) { if (p_data.IsField) { writer.WritePropertyName (p_data.Name); WriteValue (((FieldInfo) p_data.Info).GetValue (obj), writer, writer_is_private, depth + 1); } else { PropertyInfo p_info = (PropertyInfo) p_data.Info; if (p_info.CanRead) { writer.WritePropertyName (p_data.Name); WriteValue (p_info.GetValue (obj, null), writer, writer_is_private, depth + 1); } } } writer.WriteObjectEnd (); } #endregion public static string ToJson (object obj) { lock (static_writer_lock) { static_writer.Reset (); WriteValue (obj, static_writer, true, 0); return static_writer.ToString (); } } public static void ToJson (object obj, JsonWriter writer) { WriteValue (obj, writer, false, 0); } public static JsonData ToObject (JsonReader reader) { return (JsonData) ToWrapper ( delegate { return new JsonData (); }, reader); } public static JsonData ToObject (TextReader reader) { JsonReader json_reader = new JsonReader (reader); return (JsonData) ToWrapper ( delegate { return new JsonData (); }, json_reader); } public static JsonData ToObject (string json) { return (JsonData) ToWrapper ( delegate { return new JsonData (); }, json); } public static T ToObject<T> (JsonReader reader) { return (T) ReadValue (typeof (T), reader); } public static T ToObject<T> (TextReader reader) { JsonReader json_reader = new JsonReader (reader); return (T) ReadValue (typeof (T), json_reader); } public static T ToObject<T> (string json) { JsonReader reader = new JsonReader (json); return (T) ReadValue (typeof (T), reader); } public static dynamic ToObject(JsonReader reader, Type type) { return ReadValue(type, reader); } public static dynamic ToObject(TextReader reader, Type type) { JsonReader json_reader = new JsonReader(reader); return ReadValue(type, json_reader); } public static dynamic ToObject(string json, Type type) { JsonReader json_reader = new JsonReader(json); return ReadValue(type, json_reader); } public static IJsonWrapper ToWrapper (WrapperFactory factory, JsonReader reader) { return ReadValue (factory, reader); } public static IJsonWrapper ToWrapper (WrapperFactory factory, string json) { JsonReader reader = new JsonReader (json); return ReadValue (factory, reader); } public static void RegisterExporter<T> (ExporterFunc<T> exporter) { ExporterFunc exporter_wrapper = delegate (object obj, JsonWriter writer) { exporter ((T) obj, writer); }; custom_exporters_table[typeof (T)] = exporter_wrapper; } public static void RegisterImporter<TJson, TValue> ( ImporterFunc<TJson, TValue> importer) { ImporterFunc importer_wrapper = delegate (object input) { return importer ((TJson) input); }; RegisterImporter (custom_importers_table, typeof (TJson), typeof (TValue), importer_wrapper); } public static void UnregisterExporters () { custom_exporters_table.Clear (); } public static void UnregisterImporters () { custom_importers_table.Clear (); } } }
32.38755
99
0.499473
[ "MIT" ]
iZhangYingYing/YingLauncher
YingClient/Ying/KMCCC.Shared/LitJson/JsonMapper.cs
32,258
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 schemas-2019-12-02.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.Schemas.Model { /// <summary> /// /// </summary> #if !PCL && !NETSTANDARD [Serializable] #endif public partial class ConflictException : AmazonSchemasException { private string _code; /// <summary> /// Constructs a new ConflictException with the specified error /// message. /// </summary> /// <param name="message"> /// Describes the error encountered. /// </param> public ConflictException(string message) : base(message) {} /// <summary> /// Construct instance of ConflictException /// </summary> /// <param name="message"></param> /// <param name="innerException"></param> public ConflictException(string message, Exception innerException) : base(message, innerException) {} /// <summary> /// Construct instance of ConflictException /// </summary> /// <param name="innerException"></param> public ConflictException(Exception innerException) : base(innerException) {} /// <summary> /// Construct instance of ConflictException /// </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 ConflictException(string message, Exception innerException, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode) : base(message, innerException, errorType, errorCode, requestId, statusCode) {} /// <summary> /// Construct instance of ConflictException /// </summary> /// <param name="message"></param> /// <param name="errorType"></param> /// <param name="errorCode"></param> /// <param name="requestId"></param> /// <param name="statusCode"></param> public ConflictException(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 ConflictException 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 ConflictException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context) { this.Code = (string)info.GetValue("Code", typeof(string)); } /// <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); info.AddValue("Code", this.Code); } #endif /// <summary> /// Gets and sets the property Code. /// <para> /// The error code. /// </para> /// </summary> [AWSProperty(Required=true)] public string Code { get { return this._code; } set { this._code = value; } } // Check to see if Code property is set internal bool IsSetCode() { return this._code != null; } } }
43.287671
178
0.652848
[ "Apache-2.0" ]
JeffAshton/aws-sdk-net
sdk/src/Services/Schemas/Generated/Model/ConflictException.cs
6,320
C#
using Android.Content; using Android.Widget; namespace Rightek.Droid.Spitzer.Scrollers { public class PreGingerScroller : Scroller { readonly Android.Widget.Scroller _scroller; public PreGingerScroller(Context context) { _scroller = new Android.Widget.Scroller(context); } #region ScrollerProxy public override bool ComputeScrollOffset() => _scroller.ComputeScrollOffset(); public override void Fling(int startX, int startY, int velocityX, int velocityY, int minX, int maxX, int minY, int maxY, int overX, int overY) => _scroller.Fling(startX, startY, velocityX, velocityY, minX, maxX, minY, maxY); public override void ForceFinished(bool finished) => _scroller.ForceFinished(finished); public override bool IsFinished() => _scroller.IsFinished; public override int GetCurrX() => _scroller.CurrX; public override int GetCurrY() => _scroller.CurrY; #endregion ScrollerProxy } }
31.84375
150
0.684985
[ "MIT" ]
rightek/rightek.droid.spitzer
src/Rightek.Droid.Spitzer/Scrollers/PreGingerScroller.cs
1,021
C#
using System; using Couchbase.Core.IO.Converters; namespace Couchbase.Core.IO.Operations.Errors { internal class GetErrorMap : OperationBase<ErrorMapDto> { private const int DefaultVersion = 2; // will be configurable at some point public ErrorMap ErrorMap { get; set; } protected override void WriteKey(OperationBuilder builder) { } protected override void WriteExtras(OperationBuilder builder) { } protected override void WriteBody(OperationBuilder builder) { Span<byte> body = stackalloc byte[2]; ByteConverter.FromInt16(DefaultVersion, body); builder.Write(body); } protected override void ReadExtras(ReadOnlySpan<byte> buffer) { TryReadServerDuration(buffer); } public override OpCode OpCode => OpCode.GetErrorMap; } } #region [ License information ] /* ************************************************************ * * @author Couchbase <info@couchbase.com> * @copyright 2017 Couchbase, Inc. * * 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
30.5
83
0.614471
[ "Apache-2.0" ]
Zeroshi/couchbase-net-client
src/Couchbase/Core/IO/Operations/Errors/GetErrorMap.cs
1,769
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Charlotte.Common; using Charlotte.Tools; namespace Charlotte.Test01 { public class TitleMenu { private DDSimpleMenu SimpleMenu; public void Perform() { DDCurtain.SetCurtain(); DDEngine.FreezeInput(); Ground.I.Music.Title.Play(); string[] items = new string[] { "ゲームスタート", "コンテニュー?", "設定", "終了", }; int selectIndex = 0; this.SimpleMenu = new DDSimpleMenu(); //this.SimpleMenu.WallColor = new I3Color(0, 0, 64); // test this.SimpleMenu.WallPicture = Ground.I.Picture.TitleWall; for (; ; ) { selectIndex = this.SimpleMenu.Perform("Donut3", items, selectIndex); switch (selectIndex) { case 0: { this.LeaveTitleMenu(); { GameMain gameMain = new GameMain(); gameMain.INIT(); gameMain.Perform(); gameMain.FNLZ(); } this.ReturnTitleMenu(); } break; case 1: // TODO break; case 2: this.Setting(); break; case 3: goto endMenu; default: throw new DDError(); } } endMenu: DDEngine.FreezeInput(); DDMusicUtils.Fade(); DDCurtain.SetCurtain(30, -1.0); foreach (DDScene scene in DDSceneUtils.Create(40)) { this.DrawWall(); DDEngine.EachFrame(); } } private void Setting() { DDCurtain.SetCurtain(); DDEngine.FreezeInput(); string[] items = new string[] { "パッドのボタン設定", "ウィンドウサイズ変更", "BGM音量", "SE音量", "戻る", }; int selectIndex = 0; for (; ; ) { selectIndex = this.SimpleMenu.Perform("設定", items, selectIndex); switch (selectIndex) { case 0: this.SimpleMenu.PadConfig(); break; case 1: this.SimpleMenu.WindowSizeConfig(); break; case 2: this.SimpleMenu.VolumeConfig("BGM音量", DDGround.MusicVolume, 0, 100, 1, 10, volume => { DDGround.MusicVolume = volume; DDMusicUtils.UpdateVolume(); }, () => { } ); break; case 3: this.SimpleMenu.VolumeConfig("SE音量", DDGround.SEVolume, 0, 100, 1, 10, volume => { DDGround.SEVolume = volume; DDSEUtils.UpdateVolume(); }, () => { if (SecurityTools.CRandom.GetReal2() < 0.5) Ground.I.SE.PauseIn.Play(); else Ground.I.SE.PauseOut.Play(); } ); break; case 4: goto endMenu; default: throw new DDError(); } } endMenu: DDEngine.FreezeInput(); } private void DrawWall() { DDDraw.DrawRect(Ground.I.Picture.TitleWall, 0, 0, DDConsts.Screen_W, DDConsts.Screen_H); } private void LeaveTitleMenu() { DDMusicUtils.Fade(); DDCurtain.SetCurtain(30, -1.0); foreach (DDScene scene in DDSceneUtils.Create(40)) { this.DrawWall(); DDEngine.EachFrame(); } GC.Collect(); } private void ReturnTitleMenu() { Ground.I.Music.Title.Play(); GC.Collect(); } } }
17.067039
91
0.573159
[ "MIT" ]
stackprobe/Fairy
Donut3/Donut3/Donut3/Test01/TitleMenu.cs
3,175
C#
namespace DSIS.Scheme.Impl.Actions.Files { public class ImageDimension { public static readonly Key<ImageDimension> KEY = new Key<ImageDimension>(""); public int Width { get; set; } public int Height { get; set; } } }
24.5
82
0.657143
[ "Apache-2.0" ]
jonnyzzz/phd-project
dsis/src/Scheme.Impl/src/Actions/Files/ImageDimension.cs
245
C#