context
stringlengths 2.52k
185k
| gt
stringclasses 1
value |
---|---|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Microsoft.Xna.Framework.Graphics;
using Pathoschild.Stardew.Common;
using Pathoschild.Stardew.Common.Patching;
using Pathoschild.Stardew.SmallBeachFarm.Framework;
using Pathoschild.Stardew.SmallBeachFarm.Framework.Config;
using Pathoschild.Stardew.SmallBeachFarm.Patches;
using StardewModdingAPI;
using StardewModdingAPI.Events;
using StardewModdingAPI.Utilities;
using StardewValley;
using StardewValley.GameData;
using StardewValley.Locations;
using StardewValley.Objects;
using xTile;
using xTile.Dimensions;
using xTile.Tiles;
using Rectangle = Microsoft.Xna.Framework.Rectangle;
namespace Pathoschild.Stardew.SmallBeachFarm
{
/// <summary>The mod entry class loaded by SMAPI.</summary>
public class ModEntry : Mod, IAssetEditor, IAssetLoader
{
/*********
** Fields
*********/
/// <summary>The MD5 hash for the default data.json file.</summary>
private const string DataFileHash = "641585fd329fac69e377cb911cf70862";
/// <summary>The relative path to the folder containing tilesheet variants.</summary>
private readonly string TilesheetsPath = Path.Combine("assets", "tilesheets");
/// <summary>The mod configuration.</summary>
private ModConfig Config;
/// <summary>The mod's hardcoded data.</summary>
private ModData Data;
/// <summary>A fake asset key prefix from which to load tilesheets.</summary>
private string FakeAssetPrefix => PathUtilities.NormalizeAssetName($"Mods/{this.ModManifest.UniqueID}");
/*********
** Public methods
*********/
/// <inheritdoc />
public override void Entry(IModHelper helper)
{
I18n.Init(helper.Translation);
// read data
this.Data = this.Helper.Data.ReadJsonFile<ModData>("assets/data.json");
{
string dataPath = Path.Combine(this.Helper.DirectoryPath, "assets", "data.json");
if (this.Data == null || !File.Exists(dataPath))
{
this.Monitor.Log("The mod's 'assets/data.json' file is missing, so this mod can't work correctly. Please reinstall the mod to fix this.", LogLevel.Error);
return;
}
if (CommonHelper.GetFileHash(dataPath) != ModEntry.DataFileHash)
this.Monitor.Log("Found edits to 'assets/data.json'.");
}
// read config
this.Config = this.Helper.ReadConfig<ModConfig>();
// hook events
helper.Events.GameLoop.SaveLoaded += this.OnSaveLoaded;
helper.Events.GameLoop.DayEnding += this.DayEnding;
helper.Events.GameLoop.GameLaunched += this.OnGameLaunched;
// hook Harmony patch
HarmonyPatcher.Apply(this,
new FarmPatcher(
this.Monitor,
config: this.Config,
isSmallBeachFarm: location => this.IsSmallBeachFarm(location, out _),
getFishType: this.GetFishType
)
);
}
/// <inheritdoc />
public bool CanEdit<T>(IAssetInfo asset)
{
return
asset.AssetNameEquals("Data/AdditionalFarms")
|| asset.AssetNameEquals("Strings/UI");
}
/// <inheritdoc />
public void Edit<T>(IAssetData asset)
{
// add farm type
if (asset.AssetNameEquals("Data/AdditionalFarms"))
{
var data = (List<ModFarmType>)asset.Data;
data.Add(new()
{
ID = this.ModManifest.UniqueID,
TooltipStringPath = "Strings/UI:Pathoschild_BeachFarm_Description",
MapName = "Pathoschild_SmallBeachFarm"
});
}
// add farm description
else if (asset.AssetNameEquals("Strings/UI"))
{
var data = asset.AsDictionary<string, string>().Data;
data["Pathoschild_BeachFarm_Description"] = $"{I18n.Farm_Name()}_{I18n.Farm_Description()}";
}
}
/// <inheritdoc />
public bool CanLoad<T>(IAssetInfo asset)
{
return
asset.AssetNameEquals("Maps/Pathoschild_SmallBeachFarm")
|| asset.AssetName.StartsWith(this.FakeAssetPrefix);
}
/// <inheritdoc />
public T Load<T>(IAssetInfo asset)
{
// load map
if (asset.AssetNameEquals("Maps/Pathoschild_SmallBeachFarm"))
{
// load map
Map map = this.Helper.Content.Load<Map>("assets/farm.tmx");
// add islands
if (this.Config.EnableIslands)
{
Map islands = this.Helper.Content.Load<Map>("assets/islands.tmx");
this.Helper.Content.GetPatchHelper(map)
.AsMap()
.PatchMap(source: islands, targetArea: new Rectangle(0, 26, 56, 49));
}
// add campfire
if (this.Config.AddCampfire)
{
var buildingsLayer = map.GetLayer("Buildings");
buildingsLayer.Tiles[65, 23] = new StaticTile(buildingsLayer, map.GetTileSheet("zbeach"), BlendMode.Alpha, 157); // driftwood pile
buildingsLayer.Tiles[64, 22] = new StaticTile(buildingsLayer, map.GetTileSheet("untitled tile sheet"), BlendMode.Alpha, 242); // campfire
}
// apply tilesheet recolors
string internalRootKey = this.Helper.Content.GetActualAssetKey($"{this.TilesheetsPath}/_default");
foreach (TileSheet tilesheet in map.TileSheets)
{
if (tilesheet.ImageSource.StartsWith(internalRootKey + PathUtilities.PreferredAssetSeparator))
tilesheet.ImageSource = this.Helper.Content.GetActualAssetKey($"{this.FakeAssetPrefix}/{Path.GetFileNameWithoutExtension(tilesheet.ImageSource)}", ContentSource.GameContent);
}
return (T)(object)map;
}
// load tilesheet
if (asset.AssetName.StartsWith(this.FakeAssetPrefix))
{
string filename = Path.GetFileName(asset.AssetName);
if (!Path.HasExtension(filename))
filename += ".png";
// get relative path to load
string relativePath = new DirectoryInfo(this.GetFullPath(this.TilesheetsPath))
.EnumerateDirectories()
.FirstOrDefault(p => p.Name != "_default" && this.Helper.ModRegistry.IsLoaded(p.Name))
?.Name;
relativePath = Path.Combine(this.TilesheetsPath, relativePath ?? "_default", filename);
// load asset
Texture2D tilesheet = this.Helper.Content.Load<Texture2D>(relativePath);
return (T)(object)tilesheet;
}
// unknown asset
throw new NotSupportedException($"Unexpected asset '{asset.AssetName}'.");
}
/*********
** Private methods
*********/
/// <inheritdoc cref="IGameLoopEvents.GameLaunched"/>
/// <param name="sender">The event sender.</param>
/// <param name="e">The event data.</param>
private void OnGameLaunched(object sender, GameLaunchedEventArgs e)
{
// add Generic Mod Config Menu integration
new GenericModConfigMenuIntegrationForSmallBeachFarm(
getConfig: () => this.Config,
reset: () =>
{
this.Config = new ModConfig();
this.Helper.WriteConfig(this.Config);
},
saveAndApply: () => this.Helper.WriteConfig(this.Config),
modRegistry: this.Helper.ModRegistry,
monitor: this.Monitor,
manifest: this.ModManifest
).Register();
}
/// <inheritdoc cref="IGameLoopEvents.SaveLoaded"/>
/// <param name="sender">The event sender.</param>
/// <param name="e">The event data.</param>
private void OnSaveLoaded(object sender, SaveLoadedEventArgs e)
{
// when the player first loads the save, fix the broken TV if needed
if (Context.IsMainPlayer && Game1.currentLocation is FarmHouse farmhouse && Game1.dayOfMonth == 1 && Game1.currentSeason == "spring" && Game1.year == 1)
{
var brokenTvs = farmhouse.furniture
.Where(furniture => furniture.ParentSheetIndex == 1680 && furniture is not TV)
.ToArray();
foreach (var tv in brokenTvs)
{
farmhouse.furniture.Remove(tv);
farmhouse.furniture.Add(new TV(1680, tv.TileLocation));
}
}
}
/// <inheritdoc cref="IGameLoopEvents.DayEnding"/>
/// <param name="sender">The event sender.</param>
/// <param name="e">The event data.</param>
private void DayEnding(object sender, DayEndingEventArgs e)
{
if (!this.IsSmallBeachFarm(Game1.getFarm(), out Farm farm))
return;
// update ocean crab pots before the game does
GameLocation beach = Game1.getLocationFromName("Beach");
foreach (CrabPot pot in farm.objects.Values.OfType<CrabPot>())
{
if (this.GetFishType(farm, (int)pot.TileLocation.X, (int)pot.TileLocation.Y) == FishType.Ocean)
pot.DayUpdate(beach);
}
}
/// <summary>Get the full path for a relative path.</summary>
/// <param name="relative">The relative path.</param>
private string GetFullPath(string relative)
{
return Path.Combine(this.Helper.DirectoryPath, relative);
}
/// <summary>Get whether the given location is the Small Beach Farm.</summary>
/// <param name="location">The location to check.</param>
/// <param name="farm">The farm instance.</param>
private bool IsSmallBeachFarm(GameLocation location, out Farm farm)
{
if (Game1.whichModFarm?.ID == this.ModManifest.UniqueID && location is Farm { Name: "Farm" } farmInstance)
{
farm = farmInstance;
return true;
}
farm = null;
return false;
}
/// <summary>Get the fish that should be available from the given tile.</summary>
/// <param name="farm">The farm instance.</param>
/// <param name="x">The tile X position.</param>
/// <param name="y">The tile Y position.</param>
private FishType GetFishType(Farm farm, int x, int y)
{
// not water
if (farm.doesTileHaveProperty(x, y, "Water", "Back") == null)
return FishType.Default;
// mixed fish area
if (this.Data.MixedFishAreas.Any(p => p.Contains(x, y)))
{
return Game1.random.Next(2) == 1
? FishType.Ocean
: FishType.River;
}
// ocean or river
string tilesheetId = farm.map
?.GetLayer("Back")
?.PickTile(new Location(x * Game1.tileSize, y * Game1.tileSize), Game1.viewport.Size)
?.TileSheet
?.Id;
return tilesheetId is "zbeach" or "zbeach_farm"
? FishType.Ocean
: FishType.River;
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp.CodeFixes.FullyQualify;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Diagnostics;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.FullyQualify
{
public class FullyQualifyTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest
{
internal override Tuple<DiagnosticAnalyzer, CodeFixProvider> CreateDiagnosticProviderAndFixer(Workspace workspace)
{
return Tuple.Create<DiagnosticAnalyzer, CodeFixProvider>(null, new CSharpFullyQualifyCodeFixProvider());
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestTypeFromMultipleNamespaces1()
{
await TestAsync(
@"class Class { [|IDictionary|] Method() { Foo(); } }",
@"class Class { System.Collections.IDictionary Method() { Foo(); } }");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestTypeFromMultipleNamespaces2()
{
await TestAsync(
@"class Class { [|IDictionary|] Method() { Foo(); } }",
@"class Class { System.Collections.Generic.IDictionary Method() { Foo(); } }",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestGenericWithNoArgs()
{
await TestAsync(
@"class Class { [|List|] Method() { Foo(); } }",
@"class Class { System.Collections.Generic.List Method() { Foo(); } }");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestGenericWithCorrectArgs()
{
await TestAsync(
@"class Class { [|List<int>|] Method() { Foo(); } }",
@"class Class { System.Collections.Generic.List<int> Method() { Foo(); } }");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestSmartTagDisplayText()
{
await TestSmartTagTextAsync(
@"class Class { [|List<int>|] Method() { Foo(); } }",
"System.Collections.Generic.List");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestGenericWithWrongArgs()
{
await TestMissingAsync(
@"class Class { [|List<int,string>|] Method() { Foo(); } }");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestGenericInLocalDeclaration()
{
await TestAsync(
@"class Class { void Foo() { [|List<int>|] a = new List<int>(); } }",
@"class Class { void Foo() { System.Collections.Generic.List<int> a = new List<int>(); } }");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestGenericItemType()
{
await TestAsync(
@"using System.Collections.Generic; class Class { List<[|Int32|]> l; }",
@"using System.Collections.Generic; class Class { List<System.Int32> l; }");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestGenerateWithExistingUsings()
{
await TestAsync(
@"using System; class Class { [|List<int>|] Method() { Foo(); } }",
@"using System; class Class { System.Collections.Generic.List<int> Method() { Foo(); } }");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestGenerateInNamespace()
{
await TestAsync(
@"namespace N { class Class { [|List<int>|] Method() { Foo(); } } }",
@"namespace N { class Class { System.Collections.Generic.List<int> Method() { Foo(); } } }");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestGenerateInNamespaceWithUsings()
{
await TestAsync(
@"namespace N { using System; class Class { [|List<int>|] Method() { Foo(); } } }",
@"namespace N { using System; class Class { System.Collections.Generic.List<int> Method() { Foo(); } } }");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestExistingUsing()
{
await TestActionCountAsync(
@"using System.Collections.Generic; class Class { [|IDictionary|] Method() { Foo(); } }",
count: 2);
await TestAsync(
@"using System.Collections.Generic; class Class { [|IDictionary|] Method() { Foo(); } }",
@"using System.Collections.Generic; class Class { System.Collections.IDictionary Method() { Foo(); } }");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestMissingIfUniquelyBound()
{
await TestMissingAsync(
@"using System; class Class { [|String|] Method() { Foo(); } }");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestMissingIfUniquelyBoundGeneric()
{
await TestMissingAsync(
@"using System.Collections.Generic; class Class { [|List<int>|] Method() { Foo(); } }");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestOnEnum()
{
await TestAsync(
@"class Class { void Foo() { var a = [|Colors|].Red; } } namespace A { enum Colors {Red, Green, Blue} }",
@"class Class { void Foo() { var a = A.Colors.Red; } } namespace A { enum Colors {Red, Green, Blue} }");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestOnClassInheritance()
{
await TestAsync(
@"class Class : [|Class2|] { } namespace A { class Class2 { } }",
@"class Class : A.Class2 { } namespace A { class Class2 { } }");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestOnImplementedInterface()
{
await TestAsync(
@"class Class : [|IFoo|] { } namespace A { interface IFoo { } }",
@"class Class : A.IFoo { } namespace A { interface IFoo { } }");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestAllInBaseList()
{
await TestAsync(
@"class Class : [|IFoo|], Class2 { } namespace A { class Class2 { } } namespace B { interface IFoo { } } ",
@"class Class : B.IFoo, Class2 { } namespace A { class Class2 { } } namespace B { interface IFoo { } }");
await TestAsync(
@"class Class : B.IFoo, [|Class2|] { } namespace A { class Class2 { } } namespace B { interface IFoo { } } ",
@"class Class : B.IFoo, A.Class2 { } namespace A { class Class2 { } } namespace B { interface IFoo { } }");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestAttributeUnexpanded()
{
await TestAsync(
@"[[|Obsolete|]]class Class { }",
@"[System.Obsolete]class Class { }");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestAttributeExpanded()
{
await TestAsync(
@"[[|ObsoleteAttribute|]]class Class { }",
@"[System.ObsoleteAttribute]class Class { }");
}
[WorkItem(527360, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527360")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestExtensionMethods()
{
await TestMissingAsync(
@"using System.Collections.Generic; class Foo { void Bar() { var values = new List<int>() { 1, 2, 3 }; values.[|Where|](i => i > 1); } }");
}
[WorkItem(538018, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538018")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestAfterNew()
{
await TestAsync(
@"class Class { void Foo() { List<int> l; l = new [|List<int>|](); } }",
@"class Class { void Foo() { List<int> l; l = new System.Collections.Generic.List<int>(); } }");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestArgumentsInMethodCall()
{
await TestAsync(
@"class Class { void Test() { Console.WriteLine([|DateTime|].Today); } }",
@"class Class { void Test() { Console.WriteLine(System.DateTime.Today); } }");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestCallSiteArgs()
{
await TestAsync(
@"class Class { void Test([|DateTime|] dt) { } }",
@"class Class { void Test(System.DateTime dt) { } }");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestUsePartialClass()
{
await TestAsync(
@"namespace A { public class Class { [|PClass|] c; } } namespace B{ public partial class PClass { } }",
@"namespace A { public class Class { B.PClass c; } } namespace B{ public partial class PClass { } }");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestGenericClassInNestedNamespace()
{
await TestAsync(
@"namespace A { namespace B { class GenericClass<T> { } } } namespace C { class Class { [|GenericClass<int>|] c; } }",
@"namespace A { namespace B { class GenericClass<T> { } } } namespace C { class Class { A.B.GenericClass<int> c; } }");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestBeforeStaticMethod()
{
await TestAsync(
@"class Class { void Test() { [|Math|].Sqrt(); }",
@"class Class { void Test() { System.Math.Sqrt(); }");
}
[WorkItem(538136, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538136")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestBeforeNamespace()
{
await TestAsync(
@"namespace A { class Class { [|C|].Test t; } } namespace B { namespace C { class Test { } } }",
@"namespace A { class Class { B.C.Test t; } } namespace B { namespace C { class Test { } } }");
}
[WorkItem(527395, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527395")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestSimpleNameWithLeadingTrivia()
{
await TestAsync(
@"class Class { void Test() { /*foo*/[|Int32|] i; } }",
@"class Class { void Test() { /*foo*/System.Int32 i; } }",
compareTokens: false);
}
[WorkItem(527395, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527395")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestGenericNameWithLeadingTrivia()
{
await TestAsync(
@"class Class { void Test() { /*foo*/[|List<int>|] l; } }",
@"class Class { void Test() { /*foo*/System.Collections.Generic.List<int> l; } }",
compareTokens: false);
}
[WorkItem(538740, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538740")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestFullyQualifyTypeName()
{
await TestAsync(
@"public class Program { public class Inner { } } class Test { [|Inner|] i; }",
@"public class Program { public class Inner { } } class Test { Program.Inner i; }");
}
[WorkItem(538740, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538740")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestFullyQualifyTypeName_NotForGenericType()
{
await TestMissingAsync(
@"class Program<T> { public class Inner { } } class Test { [|Inner|] i; }");
}
[WorkItem(538764, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538764")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestFullyQualifyThroughAlias()
{
await TestAsync(
@"using Alias = System; class C { [|Int32|] i; }",
@"using Alias = System; class C { Alias.Int32 i; }");
}
[WorkItem(538763, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538763")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestFullyQualifyPrioritizeTypesOverNamespaces1()
{
await TestAsync(
@"namespace Outer { namespace C { class C { } } } class Test { [|C|] c; }",
@"namespace Outer { namespace C { class C { } } } class Test { Outer.C.C c; }");
}
[WorkItem(538763, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538763")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestFullyQualifyPrioritizeTypesOverNamespaces2()
{
await TestAsync(
@"namespace Outer { namespace C { class C { } } } class Test { [|C|] c; }",
@"namespace Outer { namespace C { class C { } } } class Test { Outer.C c; }",
index: 1);
}
[WorkItem(539853, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539853")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task BugFix5950()
{
await TestAsync(
@"using System.Console; WriteLine([|Expression|].Constant(123));",
@"using System.Console; WriteLine(System.Linq.Expressions.Expression.Constant(123));",
parseOptions: GetScriptOptions());
}
[WorkItem(540318, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540318")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestAfterAlias()
{
await TestMissingAsync(
@"using System ; using System . Collections . Generic ; using System . Linq ; class Program { static void Main ( string [ ] args ) { System :: [|Console|] :: WriteLine ( ""TEST"" ) ; } } ");
}
[WorkItem(540942, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540942")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestMissingOnIncompleteStatement()
{
await TestMissingAsync(
@"using System ; using System . IO ; class C { static void Main ( string [ ] args ) { [|Path|] } } ");
}
[WorkItem(542643, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542643")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestAssemblyAttribute()
{
await TestAsync(
@"[ assembly : [|InternalsVisibleTo|] ( ""Project"" ) ] ",
@"[ assembly : System . Runtime . CompilerServices . InternalsVisibleTo ( ""Project"" ) ] ");
}
[WorkItem(543388, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543388")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestMissingOnAliasName()
{
await TestMissingAsync(
@"using [|GIBBERISH|] = Foo . GIBBERISH ; class Program { static void Main ( string [ ] args ) { GIBBERISH x ; } } namespace Foo { public class GIBBERISH { } } ");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestMissingOnAttributeOverloadResolutionError()
{
await TestMissingAsync(
@"using System . Runtime . InteropServices ; class M { [ [|DllImport|] ( ) ] static extern int ? My ( ) ; } ");
}
[WorkItem(544950, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544950")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestNotOnAbstractConstructor()
{
await TestMissingAsync(
@"using System . IO ; class Program { static void Main ( string [ ] args ) { var s = new [|Stream|] ( ) ; } } ");
}
[WorkItem(545774, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545774")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestAttribute()
{
var input = @"[ assembly : [|Guid|] ( ""9ed54f84-a89d-4fcd-a854-44251e925f09"" ) ] ";
await TestActionCountAsync(input, 1);
await TestAsync(
input,
@"[ assembly : System . Runtime . InteropServices . Guid ( ""9ed54f84-a89d-4fcd-a854-44251e925f09"" ) ] ");
}
[WorkItem(546027, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546027")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestGeneratePropertyFromAttribute()
{
await TestMissingAsync(
@"using System ; [ AttributeUsage ( AttributeTargets . Class ) ] class MyAttrAttribute : Attribute { } [ MyAttr ( 123 , [|Version|] = 1 ) ] class D { } ");
}
[WorkItem(775448, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/775448")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task ShouldTriggerOnCS0308()
{
// CS0308: The non-generic type 'A' cannot be used with type arguments
await TestAsync(
@"using System.Collections;
class Test
{
static void Main(string[] args)
{
[|IEnumerable<int>|] f;
}
}",
@"using System.Collections;
class Test
{
static void Main(string[] args)
{
System.Collections.Generic.IEnumerable<int> f;
}
}");
}
[WorkItem(947579, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/947579")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task AmbiguousTypeFix()
{
await TestAsync(
@"using n1;
using n2;
class B { void M1() { [|var a = new A();|] }}
namespace n1 { class A { }}
namespace n2 { class A { }}",
@"using n1;
using n2;
class B { void M1() { var a = new n1.A(); }}
namespace n1 { class A { }}
namespace n2 { class A { }}");
}
[WorkItem(995857, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/995857")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task NonPublicNamespaces()
{
await TestAsync(
@"namespace MS.Internal.Xaml { private class A { } }
namespace System.Xaml { public class A { } }
public class Program { static void M() { [|Xaml|] } }",
@"namespace MS.Internal.Xaml { private class A { } }
namespace System.Xaml { public class A { } }
public class Program { static void M() { System.Xaml } }");
await TestAsync(
@"namespace MS.Internal.Xaml { public class A { } }
namespace System.Xaml { public class A { } }
public class Program { static void M() { [|Xaml|] } }",
@"namespace MS.Internal.Xaml { public class A { } }
namespace System.Xaml { public class A { } }
public class Program { static void M() { MS.Internal.Xaml } }");
}
[WorkItem(11071, "https://github.com/dotnet/roslyn/issues/11071")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task AmbiguousFixOrdering()
{
await TestAsync(
@"using n1;
using n2;
[[|Inner|].C]
class B { }
namespace n1 { namespace Inner { } }
namespace n2 { namespace Inner { class CAttribute { } } }",
@"using n1;
using n2;
[n2.Inner.C]
class B { }
namespace n1 { namespace Inner { } }
namespace n2 { namespace Inner { class CAttribute { } } }");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TupleTest()
{
await TestAsync(
@"class Class { ([|IDictionary|], string) Method() { Foo(); } }",
@"class Class { (System.Collections.IDictionary, string) Method() { Foo(); } }",
parseOptions: TestOptions.Regular.WithTuplesFeature(),
withScriptOption: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TupleWithOneName()
{
await TestAsync(
@"class Class { ([|IDictionary|] a, string) Method() { Foo(); } }",
@"class Class { (System.Collections.IDictionary a, string) Method() { Foo(); } }",
parseOptions: TestOptions.Regular.WithTuplesFeature(),
withScriptOption: true);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Win32.SafeHandles;
using CURLAUTH = Interop.Http.CURLAUTH;
using CURLcode = Interop.Http.CURLcode;
using CURLINFO = Interop.Http.CURLINFO;
using CURLMcode = Interop.Http.CURLMcode;
using CURLMSG = Interop.Http.CURLMSG;
using CURLoption = Interop.Http.CURLoption;
using SafeCurlMultiHandle = Interop.Http.SafeCurlMultiHandle;
using CurlSeekResult = Interop.Http.CurlSeekResult;
namespace System.Net.Http
{
internal partial class CurlHandler : HttpMessageHandler
{
/// <summary>Provides a multi handle and the associated processing for all requests on the handle.</summary>
private sealed class MultiAgent
{
/// <summary>
/// Amount of time in milliseconds to keep a multiagent worker alive when there's no work to be done.
/// Increasing this value makes it more likely that a worker will end up getting reused for subsequent
/// requests, saving on the costs associated with spinning up a new worker, but at the same time it
/// burns a thread for that period of time.
/// </summary>
private const int KeepAliveMilliseconds = 50;
private static readonly Interop.Http.ReadWriteCallback s_receiveHeadersCallback = CurlReceiveHeadersCallback;
private static readonly Interop.Http.ReadWriteCallback s_sendCallback = CurlSendCallback;
private static readonly Interop.Http.SeekCallback s_seekCallback = CurlSeekCallback;
private static readonly Interop.Http.ReadWriteCallback s_receiveBodyCallback = CurlReceiveBodyCallback;
private static readonly Interop.Http.DebugCallback s_debugCallback = CurlDebugFunction;
/// <summary>CurlHandler that owns this MultiAgent.</summary>
private readonly CurlHandler _associatedHandler;
/// <summary>
/// A collection of not-yet-processed incoming requests for work to be done
/// by this multi agent. This can include making new requests, canceling
/// active requests, or unpausing active requests.
/// Protected by a lock on <see cref="_incomingRequests"/>.
/// </summary>
private readonly Queue<IncomingRequest> _incomingRequests = new Queue<IncomingRequest>();
/// <summary>Map of activeOperations, indexed by a GCHandle ptr.</summary>
private readonly Dictionary<IntPtr, ActiveRequest> _activeOperations = new Dictionary<IntPtr, ActiveRequest>();
/// <summary>
/// Special file descriptor used to wake-up curl_multi_wait calls. This is the read
/// end of a pipe, with the write end written to when work is queued or when cancellation
/// is requested. This is only valid while the worker is executing.
/// </summary>
private SafeFileHandle _wakeupRequestedPipeFd;
/// <summary>
/// Write end of the pipe connected to <see cref="_wakeupRequestedPipeFd"/>.
/// This is only valid while the worker is executing.
/// </summary>
private SafeFileHandle _requestWakeupPipeFd;
/// <summary>
/// Task for the currently running worker, or null if there is no current worker.
/// Protected by a lock on <see cref="_incomingRequests"/>.
/// </summary>
private Task _runningWorker;
/// <summary>Initializes the MultiAgent.</summary>
/// <param name="handler">The handler that owns this agent.</param>
public MultiAgent(CurlHandler handler)
{
Debug.Assert(handler != null, "Expected non-null handler");
_associatedHandler = handler;
}
/// <summary>Queues a request for the multi handle to process.</summary>
public void Queue(IncomingRequest request)
{
lock (_incomingRequests)
{
// Add the request, then initiate processing.
_incomingRequests.Enqueue(request);
EnsureWorkerIsRunning();
}
}
/// <summary>Gets the ID of the currently running worker, or null if there isn't one.</summary>
internal int? RunningWorkerId { get { return _runningWorker != null ? (int?)_runningWorker.Id : null; } }
/// <summary>Schedules the processing worker if one hasn't already been scheduled.</summary>
private void EnsureWorkerIsRunning()
{
Debug.Assert(Monitor.IsEntered(_incomingRequests), "Needs to be called under _incomingRequests lock");
if (_runningWorker == null)
{
EventSourceTrace("MultiAgent worker queueing");
// Create pipe used to forcefully wake up curl_multi_wait calls when something important changes.
// This is created here rather than in Process so that the pipe is available immediately
// for subsequent queue calls to use.
Debug.Assert(_wakeupRequestedPipeFd == null, "Read pipe should have been cleared");
Debug.Assert(_requestWakeupPipeFd == null, "Write pipe should have been cleared");
unsafe
{
int* fds = stackalloc int[2];
Interop.CheckIo(Interop.Sys.Pipe(fds));
_wakeupRequestedPipeFd = new SafeFileHandle((IntPtr)fds[Interop.Sys.ReadEndOfPipe], true);
_requestWakeupPipeFd = new SafeFileHandle((IntPtr)fds[Interop.Sys.WriteEndOfPipe], true);
}
// Kick off the processing task. It's "DenyChildAttach" to avoid any surprises if
// code happens to create attached tasks, and it's LongRunning because this thread
// is likely going to sit around for a while in a wait loop (and the more requests
// are concurrently issued to the same agent, the longer the thread will be around).
const TaskCreationOptions Options = TaskCreationOptions.DenyChildAttach | TaskCreationOptions.LongRunning;
_runningWorker = new Task(s =>
{
var thisRef = (MultiAgent)s;
try
{
// Do the actual processing
thisRef.EventSourceTrace("MultiAgent worker running");
thisRef.WorkerLoop();
}
catch (Exception exc)
{
thisRef.EventSourceTrace("Unexpected worker failure: {0}", exc);
Debug.Fail("Unexpected exception from processing loop: " + exc.ToString());
}
finally
{
thisRef.EventSourceTrace("MultiAgent worker shutting down");
lock (thisRef._incomingRequests)
{
// Close our wakeup pipe (ignore close errors).
// This is done while holding the lock to prevent
// subsequent Queue calls to see an improperly configured
// set of descriptors.
thisRef._wakeupRequestedPipeFd.Dispose();
thisRef._wakeupRequestedPipeFd = null;
thisRef._requestWakeupPipeFd.Dispose();
thisRef._requestWakeupPipeFd = null;
// In the time between we stopped processing and now,
// more requests could have been added. If they were
// kick off another processing loop.
thisRef._runningWorker = null;
if (thisRef._incomingRequests.Count > 0)
{
thisRef.EnsureWorkerIsRunning();
}
}
}
}, this, CancellationToken.None, Options);
_runningWorker.Start(TaskScheduler.Default); // started after _runningWorker field set to avoid race conditions
}
else // _workerRunning == true
{
// The worker is already running. If there are already queued requests, we're done.
// However, if there aren't any queued requests, Process could be blocked inside of
// curl_multi_wait, and we want to make sure it wakes up to see that there additional
// requests waiting to be handled. So we write to the wakeup pipe.
Debug.Assert(_incomingRequests.Count >= 1, "We just queued a request, so the count should be at least 1");
if (_incomingRequests.Count == 1)
{
RequestWakeup();
}
}
}
/// <summary>Write a byte to the wakeup pipe.</summary>
private void RequestWakeup()
{
unsafe
{
EventSourceTrace(null);
byte b = 1;
Interop.CheckIo(Interop.Sys.Write(_requestWakeupPipeFd, &b, 1));
}
}
/// <summary>Clears data from the wakeup pipe.</summary>
/// <remarks>
/// This must only be called when we know there's data to be read.
/// The MultiAgent could easily deadlock if it's called when there's no data in the pipe.
/// </remarks>
private unsafe void ReadFromWakeupPipeWhenKnownToContainData()
{
// It's possible but unlikely that there will be tons of extra data in the pipe,
// more than we end up reading out here (it's unlikely because we only write a byte to the pipe when
// transitioning from 0 to 1 incoming request). In that unlikely event, the worst
// case will be that the next one or more waits will wake up immediately, with each one
// subsequently clearing out more of the pipe.
const int ClearBufferSize = 64; // sufficiently large to clear the pipe in any normal case
byte* clearBuf = stackalloc byte[ClearBufferSize];
Interop.CheckIo(Interop.Sys.Read(_wakeupRequestedPipeFd, clearBuf, ClearBufferSize));
}
/// <summary>Requests that libcurl unpause the connection associated with this request.</summary>
internal void RequestUnpause(EasyRequest easy)
{
EventSourceTrace(null, easy: easy);
Queue(new IncomingRequest { Easy = easy, Type = IncomingRequestType.Unpause });
}
/// <summary>Creates and configures a new multi handle.</summary>
private SafeCurlMultiHandle CreateAndConfigureMultiHandle()
{
// Create the new handle
SafeCurlMultiHandle multiHandle = Interop.Http.MultiCreate();
if (multiHandle.IsInvalid)
{
throw CreateHttpRequestException(new CurlException((int)CURLcode.CURLE_FAILED_INIT, isMulti: false));
}
// In support of HTTP/2, enable HTTP/2 connections to be multiplexed if possible.
// We must only do this if the version of libcurl being used supports HTTP/2 multiplexing.
// Due to a change in a libcurl signature, if we try to make this call on an older libcurl,
// we'll end up accidentally and unconditionally enabling HTTP 1.1 pipelining.
if (s_supportsHttp2Multiplexing)
{
ThrowIfCURLMError(Interop.Http.MultiSetOptionLong(multiHandle,
Interop.Http.CURLMoption.CURLMOPT_PIPELINING,
(long)Interop.Http.CurlPipe.CURLPIPE_MULTIPLEX));
}
// Configure max connections per host if it was changed from the default
if (_associatedHandler.MaxConnectionsPerServer < int.MaxValue) // int.MaxValue considered infinite, mapping to libcurl default of 0
{
CURLMcode code = Interop.Http.MultiSetOptionLong(multiHandle,
Interop.Http.CURLMoption.CURLMOPT_MAX_HOST_CONNECTIONS,
_associatedHandler.MaxConnectionsPerServer);
// This should always succeed, as we already verified we can set this option
// with this value. Treat any failure then as non-fatal in release; worst case
// is we employ more connections than desired.
Debug.Assert(code == CURLMcode.CURLM_OK, $"Expected OK, got {code}");
}
return multiHandle;
}
private void WorkerLoop()
{
Debug.Assert(!Monitor.IsEntered(_incomingRequests), "No locks should be held while invoking Process");
Debug.Assert(_runningWorker != null && _runningWorker.Id == Task.CurrentId, "This is the worker, so it must be running");
Debug.Assert(_wakeupRequestedPipeFd != null && !_wakeupRequestedPipeFd.IsInvalid, "Should have a valid pipe for wake ups");
// Create the multi handle to use for this round of processing. This one handle will be used
// to service all easy requests currently available and all those that come in while
// we're processing other requests. Once the work quiesces and there are no more requests
// to process, this multi handle will be released as the worker goes away. The next
// time a request arrives and a new worker is spun up, a new multi handle will be created.
SafeCurlMultiHandle multiHandle = CreateAndConfigureMultiHandle();
// Clear our active operations table. This should already be clear, either because
// all previous operations completed without unexpected exception, or in the case of an
// unexpected exception we should have cleaned up gracefully anyway. But just in case...
Debug.Assert(_activeOperations.Count == 0, "We shouldn't have any active operations when starting processing.");
_activeOperations.Clear();
Exception eventLoopError = null;
try
{
// Continue processing as long as there are any active operations
while (true)
{
// First handle any requests in the incoming requests queue.
while (true)
{
IncomingRequest request;
lock (_incomingRequests)
{
if (_incomingRequests.Count == 0) break;
request = _incomingRequests.Dequeue();
}
HandleIncomingRequest(multiHandle, request);
}
// If we have no active operations, there's no work to do right now.
if (_activeOperations.Count == 0)
{
// Setting up a mutiagent processing loop involves creating a new MultiAgent, creating a task
// and a thread to process it, creating a new pipe, etc., which has non-trivial cost associated
// with it. Thus, to avoid repeatedly spinning up and down these workers, we can keep this worker
// alive for a little while longer in case another request comes in within some reasonably small
// amount of time. This helps with the case where a sequence of requests is made serially rather
// than in parallel, avoiding the likely case of spinning up a new multiagent for each.
Interop.Sys.PollEvents triggered;
Interop.Error pollRv = Interop.Sys.Poll(_wakeupRequestedPipeFd, Interop.Sys.PollEvents.POLLIN, KeepAliveMilliseconds, out triggered);
if (pollRv == Interop.Error.SUCCESS && (triggered & Interop.Sys.PollEvents.POLLIN) != 0)
{
// Another request came in while we were waiting. Clear the pipe and loop around to continue processing.
ReadFromWakeupPipeWhenKnownToContainData();
continue;
}
// We're done. Exit the multiagent.
return;
}
// We have one or more active operations. Run any work that needs to be run.
CURLMcode performResult;
while ((performResult = Interop.Http.MultiPerform(multiHandle)) == CURLMcode.CURLM_CALL_MULTI_PERFORM);
ThrowIfCURLMError(performResult);
// Complete and remove any requests that have finished being processed.
CURLMSG message;
IntPtr easyHandle;
CURLcode result;
while (Interop.Http.MultiInfoRead(multiHandle, out message, out easyHandle, out result))
{
Debug.Assert(message == CURLMSG.CURLMSG_DONE, "CURLMSG_DONE is supposed to be the only message type");
if (message == CURLMSG.CURLMSG_DONE)
{
IntPtr gcHandlePtr;
CURLcode getInfoResult = Interop.Http.EasyGetInfoPointer(easyHandle, CURLINFO.CURLINFO_PRIVATE, out gcHandlePtr);
Debug.Assert(getInfoResult == CURLcode.CURLE_OK, "Failed to get info on a completing easy handle");
if (getInfoResult == CURLcode.CURLE_OK)
{
ActiveRequest completedOperation;
bool gotActiveOp = _activeOperations.TryGetValue(gcHandlePtr, out completedOperation);
Debug.Assert(gotActiveOp, "Expected to find GCHandle ptr in active operations table");
if (gotActiveOp)
{
DeactivateActiveRequest(multiHandle, completedOperation.Easy, gcHandlePtr, completedOperation.CancellationRegistration);
FinishRequest(completedOperation.Easy, result);
}
}
}
}
// Wait for more things to do.
bool isWakeupRequestedPipeActive;
bool isTimeout;
ThrowIfCURLMError(Interop.Http.MultiWait(multiHandle, _wakeupRequestedPipeFd, out isWakeupRequestedPipeActive, out isTimeout));
if (isWakeupRequestedPipeActive)
{
// We woke up (at least in part) because a wake-up was requested.
// Read the data out of the pipe to clear it.
Debug.Assert(!isTimeout, "should not have timed out if isExtraFileDescriptorActive");
EventSourceTrace("Wait wake-up");
ReadFromWakeupPipeWhenKnownToContainData();
}
if (isTimeout)
{
EventSourceTrace("Wait timeout");
}
// PERF NOTE: curl_multi_wait uses poll (assuming it's available), which is O(N) in terms of the number of fds
// being waited on. If this ends up being a scalability bottleneck, we can look into using the curl_multi_socket_*
// APIs, which would let us switch to using epoll by being notified when sockets file descriptors are added or
// removed and configuring the epoll context with EPOLL_CTL_ADD/DEL, which at the expense of a lot of additional
// complexity would let us turn the O(N) operation into an O(1) operation. The additional complexity would come
// not only in the form of additional callbacks and managing the socket collection, but also in the form of timer
// management, which is necessary when using the curl_multi_socket_* APIs and which we avoid by using just
// curl_multi_wait/perform.
}
}
catch (Exception exc)
{
eventLoopError = exc;
throw;
}
finally
{
// If we got an unexpected exception, something very bad happened. We may have some
// operations that we initiated but that weren't completed. Make sure to clean up any
// such operations, failing them and releasing their resources.
if (_activeOperations.Count > 0)
{
Debug.Assert(eventLoopError != null, "We should only have remaining operations if we got an unexpected exception");
foreach (KeyValuePair<IntPtr, ActiveRequest> pair in _activeOperations)
{
ActiveRequest failingOperation = pair.Value;
IntPtr failingOperationGcHandle = pair.Key;
DeactivateActiveRequest(multiHandle, failingOperation.Easy, failingOperationGcHandle, failingOperation.CancellationRegistration);
// Complete the operation's task and clean up any of its resources
failingOperation.Easy.FailRequest(CreateHttpRequestException(eventLoopError));
failingOperation.Easy.Cleanup(); // no active processing remains, so cleanup
}
// Clear the table.
_activeOperations.Clear();
}
// Finally, dispose of the multi handle.
multiHandle.Dispose();
}
}
private void HandleIncomingRequest(SafeCurlMultiHandle multiHandle, IncomingRequest request)
{
Debug.Assert(!Monitor.IsEntered(_incomingRequests), "Incoming requests lock should only be held while accessing the queue");
EventSourceTrace("Type: {0}", request.Type, easy: request.Easy);
EasyRequest easy = request.Easy;
switch (request.Type)
{
case IncomingRequestType.New:
ActivateNewRequest(multiHandle, easy);
break;
case IncomingRequestType.Cancel:
Debug.Assert(easy._associatedMultiAgent == this, "Should only cancel associated easy requests");
Debug.Assert(easy._cancellationToken.IsCancellationRequested, "Cancellation should have been requested");
FindAndFailActiveRequest(multiHandle, easy, new OperationCanceledException(easy._cancellationToken));
break;
case IncomingRequestType.Unpause:
Debug.Assert(easy._associatedMultiAgent == this, "Should only unpause associated easy requests");
if (!easy._easyHandle.IsClosed)
{
IntPtr gcHandlePtr;
ActiveRequest ar;
Debug.Assert(FindActiveRequest(easy, out gcHandlePtr, out ar), "Couldn't find active request for unpause");
CURLcode unpauseResult = Interop.Http.EasyUnpause(easy._easyHandle);
try
{
ThrowIfCURLEError(unpauseResult);
}
catch (Exception exc)
{
FindAndFailActiveRequest(multiHandle, easy, exc);
}
}
break;
default:
Debug.Fail("Invalid request type: " + request.Type);
break;
}
}
private void ActivateNewRequest(SafeCurlMultiHandle multiHandle, EasyRequest easy)
{
Debug.Assert(easy != null, "We should never get a null request");
Debug.Assert(easy._associatedMultiAgent == null, "New requests should not be associated with an agent yet");
// If cancellation has been requested, complete the request proactively
if (easy._cancellationToken.IsCancellationRequested)
{
easy.FailRequest(new OperationCanceledException(easy._cancellationToken));
easy.Cleanup(); // no active processing remains, so cleanup
return;
}
// Otherwise, configure it. Most of the configuration was already done when the EasyRequest
// was created, but there's additional configuration we need to do specific to this
// multi agent, specifically telling the easy request about its own GCHandle and setting
// up callbacks for data processing. Once it's configured, add it to the multi handle.
GCHandle gcHandle = GCHandle.Alloc(easy);
IntPtr gcHandlePtr = GCHandle.ToIntPtr(gcHandle);
try
{
easy._associatedMultiAgent = this;
easy.SetCurlOption(CURLoption.CURLOPT_PRIVATE, gcHandlePtr);
easy.SetCurlCallbacks(gcHandlePtr, s_receiveHeadersCallback, s_sendCallback, s_seekCallback, s_receiveBodyCallback, s_debugCallback);
ThrowIfCURLMError(Interop.Http.MultiAddHandle(multiHandle, easy._easyHandle));
}
catch (Exception exc)
{
gcHandle.Free();
easy.FailRequest(exc);
easy.Cleanup(); // no active processing remains, so cleanup
return;
}
// And if cancellation can be requested, hook up a cancellation callback.
// This callback will put the easy request back into the queue, which will
// ensure that a wake-up request has been issued. When we pull
// the easy request out of the request queue, we'll see that it's already
// associated with this agent, meaning that it's a cancellation request,
// and we'll deal with it appropriately.
var cancellationReg = default(CancellationTokenRegistration);
if (easy._cancellationToken.CanBeCanceled)
{
cancellationReg = easy._cancellationToken.Register(s =>
{
var state = (Tuple<MultiAgent, EasyRequest>)s;
state.Item1.Queue(new IncomingRequest { Easy = state.Item2, Type = IncomingRequestType.Cancel });
}, Tuple.Create<MultiAgent, EasyRequest>(this, easy));
}
// Finally, add it to our map.
_activeOperations.Add(
gcHandlePtr,
new ActiveRequest { Easy = easy, CancellationRegistration = cancellationReg });
}
private void DeactivateActiveRequest(
SafeCurlMultiHandle multiHandle, EasyRequest easy,
IntPtr gcHandlePtr, CancellationTokenRegistration cancellationRegistration)
{
// Remove the operation from the multi handle so we can shut down the multi handle cleanly
CURLMcode removeResult = Interop.Http.MultiRemoveHandle(multiHandle, easy._easyHandle);
Debug.Assert(removeResult == CURLMcode.CURLM_OK, "Failed to remove easy handle"); // ignore cleanup errors in release
// Release the associated GCHandle so that it's not kept alive forever
if (gcHandlePtr != IntPtr.Zero)
{
try
{
GCHandle.FromIntPtr(gcHandlePtr).Free();
_activeOperations.Remove(gcHandlePtr);
}
catch (InvalidOperationException)
{
Debug.Fail("Couldn't get/free the GCHandle for an active operation while shutting down due to failure");
}
}
// Undo cancellation registration
cancellationRegistration.Dispose();
}
private bool FindActiveRequest(EasyRequest easy, out IntPtr gcHandlePtr, out ActiveRequest activeRequest)
{
// We maintain an IntPtr=>ActiveRequest mapping, which makes it cheap to look-up by GCHandle ptr but
// expensive to look up by EasyRequest. If we find this becoming a bottleneck, we can add a reverse
// map that stores the other direction as well.
foreach (KeyValuePair<IntPtr, ActiveRequest> pair in _activeOperations)
{
if (pair.Value.Easy == easy)
{
gcHandlePtr = pair.Key;
activeRequest = pair.Value;
return true;
}
}
gcHandlePtr = IntPtr.Zero;
activeRequest = default(ActiveRequest);
return false;
}
private void FindAndFailActiveRequest(SafeCurlMultiHandle multiHandle, EasyRequest easy, Exception error)
{
EventSourceTrace("Error: {0}", error, easy: easy);
IntPtr gcHandlePtr;
ActiveRequest activeRequest;
if (FindActiveRequest(easy, out gcHandlePtr, out activeRequest))
{
DeactivateActiveRequest(multiHandle, easy, gcHandlePtr, activeRequest.CancellationRegistration);
easy.FailRequest(error);
easy.Cleanup(); // no active processing remains, so we can cleanup
}
else
{
Debug.Assert(easy.Task.IsCompleted, "We should only not be able to find the request if it failed or we started to send back the response.");
}
}
private void FinishRequest(EasyRequest completedOperation, CURLcode messageResult)
{
EventSourceTrace("Curl result: {0}", messageResult, easy: completedOperation);
if (completedOperation._responseMessage.StatusCode != HttpStatusCode.Unauthorized)
{
// If preauthentication is enabled, then we want to transfer credentials to the handler's credential cache.
// That entails asking the easy operation which auth types are supported, and then giving that info to the
// handler, which along with the request URI and its server credentials will populate the cache appropriately.
if (completedOperation._handler.PreAuthenticate)
{
long authAvailable;
if (Interop.Http.EasyGetInfoLong(completedOperation._easyHandle, CURLINFO.CURLINFO_HTTPAUTH_AVAIL, out authAvailable) == CURLcode.CURLE_OK)
{
completedOperation._handler.TransferCredentialsToCache(
completedOperation._requestMessage.RequestUri, (CURLAUTH)authAvailable);
}
// Ignore errors: no need to fail for the sake of putting the credentials into the cache
}
}
// Complete or fail the request
try
{
bool unsupportedProtocolRedirect = messageResult == CURLcode.CURLE_UNSUPPORTED_PROTOCOL && completedOperation._isRedirect;
if (!unsupportedProtocolRedirect)
{
ThrowIfCURLEError(messageResult);
}
completedOperation.EnsureResponseMessagePublished();
}
catch (Exception exc)
{
completedOperation.FailRequest(exc);
}
// At this point, we've completed processing the entire request, either due to error
// or due to completing the entire response.
completedOperation.Cleanup();
}
private static void CurlDebugFunction(IntPtr curl, Interop.Http.CurlInfoType type, IntPtr data, ulong size, IntPtr context)
{
EasyRequest easy;
TryGetEasyRequestFromContext(context, out easy);
try
{
switch (type)
{
case Interop.Http.CurlInfoType.CURLINFO_TEXT:
case Interop.Http.CurlInfoType.CURLINFO_HEADER_IN:
case Interop.Http.CurlInfoType.CURLINFO_HEADER_OUT:
string text = Marshal.PtrToStringAnsi(data, (int)size).Trim();
if (text.Length > 0)
{
CurlHandler.EventSourceTrace("{0}: {1}", type, text, 0, easy: easy);
}
break;
default:
CurlHandler.EventSourceTrace("{0}: {1} bytes", type, size, 0, easy: easy);
break;
}
}
catch (Exception exc)
{
CurlHandler.EventSourceTrace("Error: {0}", exc, easy: easy);
}
}
private static ulong CurlReceiveHeadersCallback(IntPtr buffer, ulong size, ulong nitems, IntPtr context)
{
// The callback is invoked once per header; multi-line headers get merged into a single line.
size *= nitems;
Debug.Assert(size <= Interop.Http.CURL_MAX_HTTP_HEADER, $"Expected header size <= {Interop.Http.CURL_MAX_HTTP_HEADER}, got {size}");
if (size == 0)
{
return 0;
}
EasyRequest easy;
if (TryGetEasyRequestFromContext(context, out easy))
{
CurlHandler.EventSourceTrace("Size: {0}", size, easy: easy);
try
{
CurlResponseMessage response = easy._responseMessage;
CurlResponseHeaderReader reader = new CurlResponseHeaderReader(buffer, size);
// Validate that we haven't received too much header data.
ulong headerBytesReceived = response._headerBytesReceived + size;
if (headerBytesReceived > (ulong)easy._handler.MaxResponseHeadersLength)
{
throw new HttpRequestException(
SR.Format(SR.net_http_response_headers_exceeded_length, easy._handler.MaxResponseHeadersLength));
}
response._headerBytesReceived = (uint)headerBytesReceived;
// Parse the header
if (reader.ReadStatusLine(response))
{
// Clear the headers when the status line is received. This may happen multiple times if there are multiple response headers (like in redirection).
response.Headers.Clear();
response.Content.Headers.Clear();
response._headerBytesReceived = (uint)size;
easy._isRedirect = easy._handler.AutomaticRedirection &&
(response.StatusCode == HttpStatusCode.Moved || // 301
response.StatusCode == HttpStatusCode.Redirect || // 302
response.StatusCode == HttpStatusCode.RedirectMethod || // 303
response.StatusCode == HttpStatusCode.RedirectKeepVerb); // 307
}
else
{
string headerName;
string headerValue;
if (reader.ReadHeader(out headerName, out headerValue))
{
if (!response.Headers.TryAddWithoutValidation(headerName, headerValue))
{
response.Content.Headers.TryAddWithoutValidation(headerName, headerValue);
}
else if (easy._isRedirect && string.Equals(headerName, HttpKnownHeaderNames.Location, StringComparison.OrdinalIgnoreCase))
{
HandleRedirectLocationHeader(easy, headerValue);
}
else if (string.Equals(headerName, HttpKnownHeaderNames.SetCookie, StringComparison.OrdinalIgnoreCase))
{
easy._handler.AddResponseCookies(easy, headerValue);
}
}
}
return size;
}
catch (Exception ex)
{
easy.FailRequest(ex); // cleanup will be handled by main processing loop
}
}
// Returning a value other than size fails the callback and forces
// request completion with an error
CurlHandler.EventSourceTrace("Aborting request", easy: easy);
return size - 1;
}
private static ulong CurlReceiveBodyCallback(
IntPtr buffer, ulong size, ulong nitems, IntPtr context)
{
size *= nitems;
EasyRequest easy;
if (TryGetEasyRequestFromContext(context, out easy))
{
CurlHandler.EventSourceTrace("Size: {0}", size, easy: easy);
try
{
if (!(easy.Task.IsCanceled || easy.Task.IsFaulted))
{
// Complete the task if it hasn't already been. This will make the
// stream available to consumers. A previous write callback
// may have already completed the task to publish the response.
easy.EnsureResponseMessagePublished();
// Try to transfer the data to a reader. This will return either the
// amount of data transferred (equal to the amount requested
// to be transferred), or it will return a pause request.
return easy._responseMessage.ResponseStream.TransferDataToStream(buffer, (long)size);
}
}
catch (Exception ex)
{
easy.FailRequest(ex); // cleanup will be handled by main processing loop
}
}
// Returning a value other than size fails the callback and forces
// request completion with an error.
CurlHandler.EventSourceTrace("Aborting request", easy: easy);
return (size > 0) ? size - 1 : 1;
}
private static ulong CurlSendCallback(IntPtr buffer, ulong size, ulong nitems, IntPtr context)
{
int length = checked((int)(size * nitems));
Debug.Assert(length <= RequestBufferSize, "length " + length + " should not be larger than RequestBufferSize " + RequestBufferSize);
if (length == 0)
{
return 0;
}
EasyRequest easy;
if (TryGetEasyRequestFromContext(context, out easy))
{
CurlHandler.EventSourceTrace("Size: {0}", length, easy: easy);
Debug.Assert(easy._requestContentStream != null, "We should only be in the send callback if we have a request content stream");
Debug.Assert(easy._associatedMultiAgent != null, "The request should be associated with a multi agent.");
try
{
// Transfer data from the request's content stream to libcurl
return TransferDataFromRequestStream(buffer, length, easy);
}
catch (Exception ex)
{
easy.FailRequest(ex); // cleanup will be handled by main processing loop
}
}
// Something went wrong.
CurlHandler.EventSourceTrace("Aborting request", easy: easy);
return Interop.Http.CURL_READFUNC_ABORT;
}
/// <summary>
/// Transfers up to <paramref name="length"/> data from the <paramref name="easy"/>'s
/// request content (non-memory) stream to the buffer.
/// </summary>
/// <returns>The number of bytes transferred.</returns>
private static ulong TransferDataFromRequestStream(IntPtr buffer, int length, EasyRequest easy)
{
CurlHandler.EventSourceTrace("Length: {0}", length, easy: easy);
MultiAgent multi = easy._associatedMultiAgent;
// First check to see whether there's any data available from a previous asynchronous read request.
// If there is, the transfer state's Task field will be non-null, with its Result representing
// the number of bytes read. The Buffer will then contain all of that read data. If the Count
// is 0, then this is the first time we're checking that Task, and so we populate the Count
// from that read result. After that, we can transfer as much data remains between Offset and
// Count. Multiple callbacks may pull from that one read.
EasyRequest.SendTransferState sts = easy._sendTransferState;
if (sts != null)
{
// Is there a previous read that may still have data to be consumed?
if (sts._task != null)
{
if (!sts._task.IsCompleted)
{
// We have a previous read that's not yet completed. This should be quite rare, but it can
// happen when we're unpaused prematurely, potentially due to the request still finishing
// being sent as the server starts to send a response. Since we still have the outstanding
// read, we simply re-pause. When the task completes (which could have happened immediately
// after the check). the continuation we previously created will fire and queue an unpause.
// Since all of this processing is single-threaded on the current thread, that unpause request
// is guaranteed to happen after this re-pause.
multi.EventSourceTrace("Re-pausing reading after a spurious un-pause", easy: easy);
return Interop.Http.CURL_READFUNC_PAUSE;
}
// Determine how many bytes were read on the last asynchronous read.
// If nothing was read, then we're done and can simply return 0 to indicate
// the end of the stream.
int bytesRead = sts._task.GetAwaiter().GetResult(); // will throw if read failed
Debug.Assert(bytesRead >= 0 && bytesRead <= sts._buffer.Length, "ReadAsync returned an invalid result length: " + bytesRead);
if (bytesRead == 0)
{
sts.SetTaskOffsetCount(null, 0, 0);
return 0;
}
// If Count is still 0, then this is the first time after the task completed
// that we're examining the data: transfer the bytesRead to the Count.
if (sts._count == 0)
{
multi.EventSourceTrace("ReadAsync completed with bytes: {0}", bytesRead, easy: easy);
sts._count = bytesRead;
}
// Now Offset and Count are both accurate. Determine how much data we can copy to libcurl...
int availableData = sts._count - sts._offset;
Debug.Assert(availableData > 0, "There must be some data still available.");
// ... and copy as much of that as libcurl will allow.
int bytesToCopy = Math.Min(availableData, length);
Marshal.Copy(sts._buffer, sts._offset, buffer, bytesToCopy);
multi.EventSourceTrace("Copied {0} bytes from request stream", bytesToCopy, easy: easy);
// Update the offset. If we've gone through all of the data, reset the state
// so that the next time we're called back we'll do a new read.
sts._offset += bytesToCopy;
Debug.Assert(sts._offset <= sts._count, "Offset should never exceed count");
if (sts._offset == sts._count)
{
sts.SetTaskOffsetCount(null, 0, 0);
}
// Return the amount of data copied
Debug.Assert(bytesToCopy > 0, "We should never return 0 bytes here.");
return (ulong)bytesToCopy;
}
// sts was non-null but sts.Task was null, meaning there was no previous task/data
// from which to satisfy any of this request.
}
else // sts == null
{
// Allocate a transfer state object to use for the remainder of this request.
easy._sendTransferState = sts = new EasyRequest.SendTransferState();
}
Debug.Assert(sts != null, "By this point we should have a transfer object");
Debug.Assert(sts._task == null, "There shouldn't be a task now.");
Debug.Assert(sts._count == 0, "Count should be zero.");
Debug.Assert(sts._offset == 0, "Offset should be zero.");
// If we get here, there was no previously read data available to copy.
// Initiate a new asynchronous read.
Task<int> asyncRead = easy._requestContentStream.ReadAsyncInternal(
sts._buffer, 0, Math.Min(sts._buffer.Length, length), easy._cancellationToken);
Debug.Assert(asyncRead != null, "Badly implemented stream returned a null task from ReadAsync");
// Even though it's "Async", it's possible this read could complete synchronously or extremely quickly.
// Check to see if it did, in which case we can also satisfy the libcurl request synchronously in this callback.
if (asyncRead.IsCompleted)
{
// Get the amount of data read.
int bytesRead = asyncRead.GetAwaiter().GetResult(); // will throw if read failed
if (bytesRead == 0)
{
return 0;
}
// Copy as much as we can.
int bytesToCopy = Math.Min(bytesRead, length);
Debug.Assert(bytesToCopy > 0 && bytesToCopy <= sts._buffer.Length, "ReadAsync quickly returned an invalid result length: " + bytesToCopy);
Marshal.Copy(sts._buffer, 0, buffer, bytesToCopy);
// If we read more than we were able to copy, stash it away for the next read.
if (bytesToCopy < bytesRead)
{
sts.SetTaskOffsetCount(asyncRead, bytesToCopy, bytesRead);
}
// Return the number of bytes read.
return (ulong)bytesToCopy;
}
// Otherwise, the read completed asynchronously. Store the task, and hook up a continuation
// such that the connection will be unpaused once the task completes.
sts.SetTaskOffsetCount(asyncRead, 0, 0);
asyncRead.ContinueWith((t, s) =>
{
EasyRequest easyRef = (EasyRequest)s;
easyRef._associatedMultiAgent.RequestUnpause(easyRef);
}, easy, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
// Then pause the connection.
multi.EventSourceTrace("Pausing the connection.", easy: easy);
return Interop.Http.CURL_READFUNC_PAUSE;
}
private static CurlSeekResult CurlSeekCallback(IntPtr context, long offset, int origin)
{
CurlHandler.EventSourceTrace("Offset: {0}, Origin: {1}", offset, origin, 0);
EasyRequest easy;
if (TryGetEasyRequestFromContext(context, out easy))
{
try
{
// If libcul is requesting we seek back to the beginning and if the request
// content stream is in a position to reset itself, reset and let libcurl
// know we did the seek; otherwise, let it know we can't seek.
if (offset == 0 && origin == (int)SeekOrigin.Begin &&
easy._requestContentStream != null && easy._requestContentStream.TryReset())
{
// Dump any state associated with the old stream's position
if (easy._sendTransferState != null)
{
easy._sendTransferState.SetTaskOffsetCount(null, 0, 0);
}
// Restart the transfer
easy._requestContentStream.Run();
return CurlSeekResult.CURL_SEEKFUNC_OK;
}
else
{
return CurlSeekResult.CURL_SEEKFUNC_CANTSEEK;
}
}
catch (Exception ex)
{
easy.FailRequest(ex); // cleanup will be handled by main processing loop
}
}
// Something went wrong
return CurlSeekResult.CURL_SEEKFUNC_FAIL;
}
private static bool TryGetEasyRequestFromContext(IntPtr context, out EasyRequest easy)
{
// Get the EasyRequest from the context
try
{
GCHandle handle = GCHandle.FromIntPtr(context);
easy = (EasyRequest)handle.Target;
Debug.Assert(easy != null, "Expected non-null EasyRequest in GCHandle");
return easy != null;
}
catch (InvalidCastException)
{
Debug.Fail("EasyRequest wasn't the GCHandle's Target");
}
catch (InvalidOperationException)
{
Debug.Fail("Invalid GCHandle");
}
easy = null;
return false;
}
private void EventSourceTrace<TArg0>(string formatMessage, TArg0 arg0, EasyRequest easy = null, [CallerMemberName] string memberName = null)
{
CurlHandler.EventSourceTrace(formatMessage, arg0, this, easy, memberName);
}
private void EventSourceTrace(string message, EasyRequest easy = null, [CallerMemberName] string memberName = null)
{
CurlHandler.EventSourceTrace(message, this, easy, memberName);
}
/// <summary>Represents an active request currently being processed by the agent.</summary>
private struct ActiveRequest
{
public EasyRequest Easy;
public CancellationTokenRegistration CancellationRegistration;
}
/// <summary>Represents an incoming request to be processed by the agent.</summary>
internal struct IncomingRequest
{
public IncomingRequestType Type;
public EasyRequest Easy;
}
/// <summary>The type of an incoming request to be processed by the agent.</summary>
internal enum IncomingRequestType : byte
{
/// <summary>A new request that's never been submitted to an agent.</summary>
New,
/// <summary>A request to cancel a request previously submitted to the agent.</summary>
Cancel,
/// <summary>A request to unpause the connection associated with a request previously submitted to the agent.</summary>
Unpause
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.IO;
using System.Security.Cryptography;
using System.Threading;
using System.Threading.Tasks;
using Azure.Core.Cryptography;
using Azure.Storage.Cryptography.Models;
namespace Azure.Storage.Cryptography
{
internal class ClientSideDecryptor
{
/// <summary>
/// Clients that can upload data have a key encryption key stored on them. Checking if
/// a cached key exists and matches a given <see cref="EncryptionData"/> saves a call
/// to the external key resolver implementation when available.
/// </summary>
private readonly IKeyEncryptionKey _potentialCachedIKeyEncryptionKey;
/// <summary>
/// Resolver to fetch the key encryption key.
/// </summary>
private readonly IKeyEncryptionKeyResolver _keyResolver;
public ClientSideDecryptor(ClientSideEncryptionOptions options)
{
_potentialCachedIKeyEncryptionKey = options.KeyEncryptionKey;
_keyResolver = options.KeyResolver;
}
/// <summary>
/// Decrypts the given stream if decryption information is provided.
/// Does not shave off unwanted start/end bytes, but will shave off padding.
/// </summary>
/// <param name="ciphertext">Stream to decrypt.</param>
/// <param name="encryptionData">
/// Encryption metadata and wrapped content encryption key.
/// </param>
/// <param name="ivInStream">
/// Whether to use the first block of the stream for the IV instead of the value in
/// <paramref name="encryptionData"/>. Generally for partial blob downloads where the
/// previous block of the ciphertext is the IV for the next.
/// </param>
/// <param name="noPadding">
/// Whether to ignore padding. Generally for partial blob downloads where the end of
/// the blob (where the padding occurs) was not downloaded.
/// </param>
/// <param name="async">Whether to perform this function asynchronously.</param>
/// <param name="cancellationToken"></param>
/// <returns>
/// Decrypted plaintext.
/// </returns>
/// <exception cref="Exception">
/// Exceptions thrown based on implementations of <see cref="IKeyEncryptionKey"/> and
/// <see cref="IKeyEncryptionKeyResolver"/>.
/// </exception>
public async Task<Stream> DecryptInternal(
Stream ciphertext,
EncryptionData encryptionData,
bool ivInStream,
bool noPadding,
bool async,
CancellationToken cancellationToken)
{
switch (encryptionData.EncryptionAgent.EncryptionVersion)
{
case ClientSideEncryptionVersion.V1_0:
return await DecryptInternalV1_0(
ciphertext,
encryptionData,
ivInStream,
noPadding,
async,
cancellationToken).ConfigureAwait(false);
default:
throw Errors.ClientSideEncryption.BadEncryptionAgent(encryptionData.EncryptionAgent.EncryptionVersion.ToString());
}
}
/// <summary>
/// Decrypts the given stream if decryption information is provided.
/// Does not shave off unwanted start/end bytes, but will shave off padding.
/// </summary>
/// <param name="ciphertext">Stream to decrypt.</param>
/// <param name="encryptionData">
/// Encryption metadata and wrapped content encryption key.
/// </param>
/// <param name="ivInStream">
/// Whether to use the first block of the stream for the IV instead of the value in
/// <paramref name="encryptionData"/>. Generally for partial blob downloads where the
/// previous block of the ciphertext is the IV for the next.
/// </param>
/// <param name="noPadding">
/// Whether to ignore padding. Generally for partial blob downloads where the end of
/// the blob (where the padding occurs) was not downloaded.
/// </param>
/// <param name="async">Whether to perform this function asynchronously.</param>
/// <param name="cancellationToken"></param>
/// <returns>
/// Decrypted plaintext.
/// </returns>
/// <exception cref="Exception">
/// Exceptions thrown based on implementations of <see cref="IKeyEncryptionKey"/> and
/// <see cref="IKeyEncryptionKeyResolver"/>.
/// </exception>
private async Task<Stream> DecryptInternalV1_0(
Stream ciphertext,
EncryptionData encryptionData,
bool ivInStream,
bool noPadding,
bool async,
CancellationToken cancellationToken)
{
var contentEncryptionKey = await GetContentEncryptionKeyAsync(
encryptionData,
async,
cancellationToken).ConfigureAwait(false);
Stream plaintext;
//int read = 0;
if (encryptionData != default)
{
byte[] IV;
if (!ivInStream)
{
IV = encryptionData.ContentEncryptionIV;
}
else
{
IV = new byte[Constants.ClientSideEncryption.EncryptionBlockSize];
if (async)
{
await ciphertext.ReadAsync(IV, 0, IV.Length, cancellationToken).ConfigureAwait(false);
}
else
{
ciphertext.Read(IV, 0, IV.Length);
}
//read = IV.Length;
}
plaintext = WrapStream(
ciphertext,
contentEncryptionKey.ToArray(),
encryptionData,
IV,
noPadding);
}
else
{
plaintext = ciphertext;
}
return plaintext;
}
#pragma warning disable CS1587 // XML comment is not placed on a valid language element
/// <summary>
/// Returns the content encryption key for blob. First tries to get the key encryption key from KeyResolver,
/// then falls back to IKey stored on this EncryptionPolicy. Unwraps the content encryption key with the
/// correct key wrapper.
/// </summary>
/// <param name="encryptionData">The encryption data.</param>
/// <param name="async">Whether to perform asynchronously.</param>
/// <param name="cancellationToken"></param>
/// <returns>
/// Encryption key as a byte array.
/// </returns>
/// <exception cref="Exception">
/// Exceptions thrown based on implementations of <see cref="IKeyEncryptionKey"/> and
/// <see cref="IKeyEncryptionKeyResolver"/>.
/// </exception>
private async Task<Memory<byte>> GetContentEncryptionKeyAsync(
#pragma warning restore CS1587 // XML comment is not placed on a valid language element
EncryptionData encryptionData,
bool async,
CancellationToken cancellationToken)
{
IKeyEncryptionKey key = default;
// If we already have a local key and it is the correct one, use that.
if (encryptionData.WrappedContentKey.KeyId == _potentialCachedIKeyEncryptionKey?.KeyId)
{
key = _potentialCachedIKeyEncryptionKey;
}
// Otherwise, use the resolver.
else if (_keyResolver != null)
{
key = async
? await _keyResolver.ResolveAsync(encryptionData.WrappedContentKey.KeyId, cancellationToken).ConfigureAwait(false)
: _keyResolver.Resolve(encryptionData.WrappedContentKey.KeyId, cancellationToken);
}
// We throw for every other reason that decryption couldn't happen. Throw a reasonable
// exception here instead of nullref.
if (key == default)
{
throw Errors.ClientSideEncryption.KeyNotFound(encryptionData.WrappedContentKey.KeyId);
}
return async
? await key.UnwrapKeyAsync(
encryptionData.WrappedContentKey.Algorithm,
encryptionData.WrappedContentKey.EncryptedKey,
cancellationToken).ConfigureAwait(false)
: key.UnwrapKey(
encryptionData.WrappedContentKey.Algorithm,
encryptionData.WrappedContentKey.EncryptedKey,
cancellationToken);
}
/// <summary>
/// Wraps a stream of ciphertext to stream plaintext.
/// </summary>
/// <param name="contentStream"></param>
/// <param name="contentEncryptionKey"></param>
/// <param name="encryptionData"></param>
/// <param name="iv"></param>
/// <param name="noPadding"></param>
/// <returns></returns>
private static Stream WrapStream(
Stream contentStream,
byte[] contentEncryptionKey,
EncryptionData encryptionData,
byte[] iv,
bool noPadding)
{
if (encryptionData.EncryptionAgent.EncryptionAlgorithm == ClientSideEncryptionAlgorithm.AesCbc256)
{
using (AesCryptoServiceProvider aesProvider = new AesCryptoServiceProvider())
{
aesProvider.IV = iv ?? encryptionData.ContentEncryptionIV;
aesProvider.Key = contentEncryptionKey;
if (noPadding)
{
aesProvider.Padding = PaddingMode.None;
}
return new CryptoStream(contentStream, aesProvider.CreateDecryptor(), CryptoStreamMode.Read);
}
}
throw Errors.ClientSideEncryption.BadEncryptionAlgorithm(encryptionData.EncryptionAgent.EncryptionAlgorithm.ToString());
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Text;
namespace System.IO
{
public static partial class Path
{
public static char[] GetInvalidFileNameChars() => new char[]
{
'\"', '<', '>', '|', '\0',
(char)1, (char)2, (char)3, (char)4, (char)5, (char)6, (char)7, (char)8, (char)9, (char)10,
(char)11, (char)12, (char)13, (char)14, (char)15, (char)16, (char)17, (char)18, (char)19, (char)20,
(char)21, (char)22, (char)23, (char)24, (char)25, (char)26, (char)27, (char)28, (char)29, (char)30,
(char)31, ':', '*', '?', '\\', '/'
};
public static char[] GetInvalidPathChars() => new char[]
{
'|', '\0',
(char)1, (char)2, (char)3, (char)4, (char)5, (char)6, (char)7, (char)8, (char)9, (char)10,
(char)11, (char)12, (char)13, (char)14, (char)15, (char)16, (char)17, (char)18, (char)19, (char)20,
(char)21, (char)22, (char)23, (char)24, (char)25, (char)26, (char)27, (char)28, (char)29, (char)30,
(char)31
};
// Expands the given path to a fully qualified path.
public static string GetFullPath(string path)
{
if (path == null)
throw new ArgumentNullException(nameof(path));
// If the path would normalize to string empty, we'll consider it empty
if (PathInternal.IsEffectivelyEmpty(path))
throw new ArgumentException(SR.Arg_PathEmpty, nameof(path));
// Embedded null characters are the only invalid character case we trully care about.
// This is because the nulls will signal the end of the string to Win32 and therefore have
// unpredictable results.
if (path.IndexOf('\0') != -1)
throw new ArgumentException(SR.Argument_InvalidPathChars, nameof(path));
if (PathInternal.IsExtended(path))
{
// \\?\ paths are considered normalized by definition. Windows doesn't normalize \\?\
// paths and neither should we. Even if we wanted to GetFullPathName does not work
// properly with device paths. If one wants to pass a \\?\ path through normalization
// one can chop off the prefix, pass it to GetFullPath and add it again.
return path;
}
return PathHelper.Normalize(path);
}
public static string GetFullPath(string path, string basePath)
{
if (path == null)
throw new ArgumentNullException(nameof(path));
if (basePath == null)
throw new ArgumentNullException(nameof(basePath));
if (!IsPathFullyQualified(basePath))
throw new ArgumentException(SR.Arg_BasePathNotFullyQualified, nameof(basePath));
if (basePath.Contains('\0') || path.Contains('\0'))
throw new ArgumentException(SR.Argument_InvalidPathChars);
if (IsPathFullyQualified(path))
return GetFullPath(path);
if (PathInternal.IsEffectivelyEmpty(path))
return basePath;
int length = path.Length;
string combinedPath = null;
if ((length >= 1 && PathInternal.IsDirectorySeparator(path[0])))
{
// Path is current drive rooted i.e. starts with \:
// "\Foo" and "C:\Bar" => "C:\Foo"
// "\Foo" and "\\?\C:\Bar" => "\\?\C:\Foo"
combinedPath = Join(GetPathRoot(basePath.AsSpan()), path.AsSpan(1)); // Cut the separator to ensure we don't end up with two separators when joining with the root.
}
else if (length >= 2 && PathInternal.IsValidDriveChar(path[0]) && path[1] == PathInternal.VolumeSeparatorChar)
{
// Drive relative paths
Debug.Assert(length == 2 || !PathInternal.IsDirectorySeparator(path[2]));
if (GetVolumeName(path).EqualsOrdinal(GetVolumeName(basePath)))
{
// Matching root
// "C:Foo" and "C:\Bar" => "C:\Bar\Foo"
// "C:Foo" and "\\?\C:\Bar" => "\\?\C:\Bar\Foo"
combinedPath = Join(basePath, path.AsSpan(2));
}
else
{
// No matching root, root to specified drive
// "D:Foo" and "C:\Bar" => "D:Foo"
// "D:Foo" and "\\?\C:\Bar" => "\\?\D:\Foo"
combinedPath = !PathInternal.IsDevice(basePath)
? path.Insert(2, @"\")
: length == 2
? JoinInternal(basePath.AsSpan(0, 4), path, @"\")
: JoinInternal(basePath.AsSpan(0, 4), path.AsSpan(0, 2), @"\", path.AsSpan(2));
}
}
else
{
// "Simple" relative path
// "Foo" and "C:\Bar" => "C:\Bar\Foo"
// "Foo" and "\\?\C:\Bar" => "\\?\C:\Bar\Foo"
combinedPath = JoinInternal(basePath, path);
}
// Device paths are normalized by definition, so passing something of this format (i.e. \\?\C:\.\tmp, \\.\C:\foo)
// to Windows APIs won't do anything by design. Additionally, GetFullPathName() in Windows doesn't root
// them properly. As such we need to manually remove segments and not use GetFullPath().
return PathInternal.IsDevice(combinedPath)
? PathInternal.RemoveRelativeSegments(combinedPath, PathInternal.GetRootLength(combinedPath))
: GetFullPath(combinedPath);
}
public static string GetTempPath()
{
Span<char> initialBuffer = stackalloc char[PathInternal.MaxShortPath];
var builder = new ValueStringBuilder(initialBuffer);
GetTempPath(ref builder);
string path = PathHelper.Normalize(ref builder);
builder.Dispose();
return path;
}
private static void GetTempPath(ref ValueStringBuilder builder)
{
uint result = 0;
while ((result = Interop.Kernel32.GetTempPathW(builder.Capacity, ref builder.GetPinnableReference())) > builder.Capacity)
{
// Reported size is greater than the buffer size. Increase the capacity.
builder.EnsureCapacity(checked((int)result));
}
if (result == 0)
throw Win32Marshal.GetExceptionForLastWin32Error();
builder.Length = (int)result;
}
// Returns a unique temporary file name, and creates a 0-byte file by that
// name on disk.
public static string GetTempFileName()
{
Span<char> initialTempPathBuffer = stackalloc char[PathInternal.MaxShortPath];
ValueStringBuilder tempPathBuilder = new ValueStringBuilder(initialTempPathBuffer);
GetTempPath(ref tempPathBuilder);
Span<char> initialBuffer = stackalloc char[PathInternal.MaxShortPath];
var builder = new ValueStringBuilder(initialBuffer);
uint result = Interop.Kernel32.GetTempFileNameW(
ref tempPathBuilder.GetPinnableReference(), "tmp", 0, ref builder.GetPinnableReference());
tempPathBuilder.Dispose();
if (result == 0)
throw Win32Marshal.GetExceptionForLastWin32Error();
builder.Length = builder.RawChars.IndexOf('\0');
string path = PathHelper.Normalize(ref builder);
builder.Dispose();
return path;
}
// Tests if the given path contains a root. A path is considered rooted
// if it starts with a backslash ("\") or a valid drive letter and a colon (":").
public static bool IsPathRooted(string path)
{
return path != null && IsPathRooted(path.AsSpan());
}
public static bool IsPathRooted(ReadOnlySpan<char> path)
{
int length = path.Length;
return (length >= 1 && PathInternal.IsDirectorySeparator(path[0]))
|| (length >= 2 && PathInternal.IsValidDriveChar(path[0]) && path[1] == PathInternal.VolumeSeparatorChar);
}
// Returns the root portion of the given path. The resulting string
// consists of those rightmost characters of the path that constitute the
// root of the path. Possible patterns for the resulting string are: An
// empty string (a relative path on the current drive), "\" (an absolute
// path on the current drive), "X:" (a relative path on a given drive,
// where X is the drive letter), "X:\" (an absolute path on a given drive),
// and "\\server\share" (a UNC path for a given server and share name).
// The resulting string is null if path is null. If the path is empty or
// only contains whitespace characters an ArgumentException gets thrown.
public static string GetPathRoot(string path)
{
if (PathInternal.IsEffectivelyEmpty(path))
return null;
ReadOnlySpan<char> result = GetPathRoot(path.AsSpan());
if (path.Length == result.Length)
return PathInternal.NormalizeDirectorySeparators(path);
return PathInternal.NormalizeDirectorySeparators(new string(result));
}
/// <remarks>
/// Unlike the string overload, this method will not normalize directory separators.
/// </remarks>
public static ReadOnlySpan<char> GetPathRoot(ReadOnlySpan<char> path)
{
if (PathInternal.IsEffectivelyEmpty(path))
return ReadOnlySpan<char>.Empty;
int pathRoot = PathInternal.GetRootLength(path);
return pathRoot <= 0 ? ReadOnlySpan<char>.Empty : path.Slice(0, pathRoot);
}
/// <summary>Gets whether the system is case-sensitive.</summary>
internal static bool IsCaseSensitive { get { return false; } }
/// <summary>
/// Returns the volume name for dos, UNC and device paths.
/// </summary>
internal static ReadOnlySpan<char> GetVolumeName(ReadOnlySpan<char> path)
{
// 3 cases: UNC ("\\server\share"), Device ("\\?\C:\"), or Dos ("C:\")
ReadOnlySpan<char> root = GetPathRoot(path);
if (root.Length == 0)
return root;
int offset = GetUncRootLength(path);
if (offset >= 0)
{
// Cut from "\\?\UNC\Server\Share" to "Server\Share"
// Cut from "\\Server\Share" to "Server\Share"
return TrimEndingDirectorySeparator(root.Slice(offset));
}
else if (PathInternal.IsDevice(path))
{
return TrimEndingDirectorySeparator(root.Slice(4)); // Cut from "\\?\C:\" to "C:"
}
return TrimEndingDirectorySeparator(root); // e.g. "C:"
}
/// <summary>
/// Trims the ending directory separator if present.
/// </summary>
/// <param name="path"></param>
internal static ReadOnlySpan<char> TrimEndingDirectorySeparator(ReadOnlySpan<char> path) =>
PathInternal.EndsInDirectorySeparator(path) ?
path.Slice(0, path.Length - 1) :
path;
/// <summary>
/// Returns offset as -1 if the path is not in Unc format, otherwise returns the root length.
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
internal static int GetUncRootLength(ReadOnlySpan<char> path)
{
bool isDevice = PathInternal.IsDevice(path);
if (!isDevice && path.Slice(0, 2).EqualsOrdinal(@"\\") )
return 2;
else if (isDevice && path.Length >= 8
&& (path.Slice(0, 8).EqualsOrdinal(PathInternal.UncExtendedPathPrefix)
|| path.Slice(5, 4).EqualsOrdinal(@"UNC\")))
return 8;
return -1;
}
}
}
| |
//
// CollectionIndexer.cs
//
// Author:
// Aaron Bockover <abockover@novell.com>
//
// Copyright (C) 2008 Novell, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Xml;
using System.Threading;
using System.Collections.Generic;
using Hyena;
using Banshee.Base;
using Banshee.Sources;
using Banshee.Library;
using Banshee.ServiceStack;
using Banshee.Collection;
using Banshee.Collection.Database;
namespace Banshee.Collection.Indexer
{
[DBusExportable (ServiceName = "CollectionIndexer")]
public class CollectionIndexer : ICollectionIndexer, IService, IDBusExportable, IDisposable
{
private static int instance_count = 0;
private CollectionIndexerService service;
private List<CachedList<DatabaseTrackInfo>> model_caches = new List<CachedList<DatabaseTrackInfo>> ();
private string [] export_fields;
private event ActionHandler indexing_finished;
event ActionHandler ICollectionIndexer.IndexingFinished {
add { indexing_finished += value; }
remove { indexing_finished -= value; }
}
private event SaveToXmlFinishedHandler save_to_xml_finished;
event SaveToXmlFinishedHandler ICollectionIndexer.SaveToXmlFinished {
add { save_to_xml_finished += value; }
remove { save_to_xml_finished -= value; }
}
public event EventHandler IndexingFinished;
internal CollectionIndexer (CollectionIndexerService service)
{
this.service = service;
}
public void Dispose ()
{
lock (this) {
DisposeModels ();
if (service != null) {
service.DisposeIndexer (this);
}
}
}
private void DisposeModels ()
{
foreach (CachedList<DatabaseTrackInfo> model in model_caches) {
model.Dispose ();
}
model_caches.Clear ();
}
public void SetExportFields (string [] fields)
{
lock (this) {
export_fields = fields;
}
}
public void Index ()
{
lock (this) {
DisposeModels ();
foreach (Source source in ServiceManager.SourceManager.Sources) {
LibrarySource library = source as LibrarySource;
if (library != null && library.Indexable) {
model_caches.Add (CachedList<DatabaseTrackInfo>.CreateFromSourceModel (
(DatabaseTrackListModel)library.TrackModel));
}
}
}
OnIndexingFinished ();
}
void ICollectionIndexer.Index ()
{
ThreadPool.QueueUserWorkItem (delegate { Index (); });
}
public void SaveToXml (string path)
{
lock (this) {
uint timer_id = Hyena.Log.DebugTimerStart ();
bool success = false;
try {
XmlTextWriter writer = new XmlTextWriter (path, System.Text.Encoding.UTF8);
writer.Formatting = Formatting.Indented;
writer.Indentation = 2;
writer.IndentChar = ' ';
writer.WriteStartDocument (true);
writer.WriteStartElement ("banshee-collection");
writer.WriteStartAttribute ("version");
writer.WriteString (TrackInfo.ExportVersion);
writer.WriteEndAttribute ();
for (int i = 0; i < model_caches.Count; i++) {
CachedList<DatabaseTrackInfo> model = model_caches[i];
if (model.Count <= 0) {
continue;
}
writer.WriteStartElement ("model");
for (int j = 0; j < model.Count; j++) {
writer.WriteStartElement ("item");
foreach (KeyValuePair<string, object> item in model[j].GenerateExportable (export_fields)) {
string type = "string";
if (item.Value is Boolean) type = "bool";
else if (item.Value is Byte) type = "byte";
else if (item.Value is SByte) type = "sbyte";
else if (item.Value is Int16) type = "short";
else if (item.Value is UInt16) type = "ushort";
else if (item.Value is Int32) type = "int";
else if (item.Value is UInt32) type = "uint";
else if (item.Value is Int64) type = "long";
else if (item.Value is UInt64) type = "ulong";
else if (item.Value is Char) type = "char";
else if (item.Value is Double) type = "double";
else if (item.Value is Single) type = "float";
writer.WriteStartElement (item.Key);
writer.WriteStartAttribute ("type");
writer.WriteString (type);
writer.WriteEndAttribute ();
writer.WriteString (item.Value.ToString ());
writer.WriteEndElement ();
}
writer.WriteEndElement ();
}
writer.WriteEndElement ();
}
writer.WriteEndElement ();
writer.WriteEndDocument ();
writer.Close ();
success = true;
} catch (Exception e) {
Log.Exception (e);
}
Hyena.Log.DebugTimerPrint (timer_id, "CollectionIndexer.SaveToXml: {0}");
SaveToXmlFinishedHandler handler = save_to_xml_finished;
if (handler != null) {
handler (success, path);
}
}
}
void ICollectionIndexer.SaveToXml (string path)
{
ThreadPool.QueueUserWorkItem (delegate { SaveToXml (path); });
}
public IDictionary<string, object> GetResult (int modelIndex, int itemIndex)
{
lock (this) {
if (modelIndex < 0 || modelIndex >= model_caches.Count) {
throw new IndexOutOfRangeException ("modelIndex");
}
CachedList<DatabaseTrackInfo> model = model_caches[modelIndex];
if (itemIndex < 0 || itemIndex >= model.Count) {
throw new IndexOutOfRangeException ("itemIndex");
}
return model[itemIndex].GenerateExportable (export_fields);
}
}
public int GetModelCounts ()
{
lock (this) {
return model_caches.Count;
}
}
public int GetModelResultsCount (int modelIndex)
{
lock (this) {
if (modelIndex < 0 || modelIndex >= model_caches.Count) {
return -1;
}
return model_caches[modelIndex].Count;
}
}
protected virtual void OnIndexingFinished ()
{
EventHandler handler = IndexingFinished;
if (handler != null) {
handler (this, EventArgs.Empty);
}
ActionHandler dbus_handler = indexing_finished;
if (dbus_handler != null) {
dbus_handler ();
}
}
private string service_name = String.Format ("CollectionIndexer_{0}", instance_count++);
string IService.ServiceName {
get { return service_name; }
}
IDBusExportable IDBusExportable.Parent {
get { return service; }
}
}
}
| |
using System;
using ASMDM;
using ASMMath;
using System.Threading;
using System.Collections;
namespace RemoteMachine
{
public delegate void GetMatrixFromFar(int loc);
public class ASMProcessorRS
{
//public ProgramThread currentthread;
public ProgramCode currentcode;
public RaiseError raiseerror;
private GetMatrixFromFar GetMatrixIntoMemory;
private ASMProcessorOperation[] ASMOperations = new ASMProcessorOperation[49];
public ASMProcessorRS(GetMatrixFromFar dgetmatrix)
{
GetMatrixIntoMemory = dgetmatrix;
ASMOperations[(int)ASMPROCESSOR_OPERATIONS.GETCONSTANT] = new ASMProcessorOperation(this.ASM_GetConstant);
ASMOperations[(int)ASMPROCESSOR_OPERATIONS.GETMEMORY] = new ASMProcessorOperation(this.ASM_GetMemory);
ASMOperations[(int)ASMPROCESSOR_OPERATIONS.STORE] = new ASMProcessorOperation(this.ASM_Store);
ASMOperations[(int)ASMPROCESSOR_OPERATIONS.ADD] = new ASMProcessorOperation(this.ASM_Add);
ASMOperations[(int)ASMPROCESSOR_OPERATIONS.PRINT] = new ASMProcessorOperation(this.ASM_Print);
ASMOperations[(int)ASMPROCESSOR_OPERATIONS.DIVIDE] = new ASMProcessorOperation(this.ASM_Divide);
ASMOperations[(int)ASMPROCESSOR_OPERATIONS.MULTIPLY] = new ASMProcessorOperation(this.ASM_Multiply);
ASMOperations[(int)ASMPROCESSOR_OPERATIONS.SUBTRACT] = new ASMProcessorOperation(this.ASM_Subtract);
ASMOperations[(int)ASMPROCESSOR_OPERATIONS.EXPONENT] = new ASMProcessorOperation(this.ASM_Exponent);
ASMOperations[(int)ASMPROCESSOR_OPERATIONS.MOD] = new ASMProcessorOperation(this.ASM_Mod);
ASMOperations[(int)ASMPROCESSOR_OPERATIONS.PUSHSTACK] = new ASMProcessorOperation(this.ASM_PushStack);
ASMOperations[(int)ASMPROCESSOR_OPERATIONS.NEWMATRIX] = new ASMProcessorOperation(this.ASM_NewMatrix);
ASMOperations[(int)ASMPROCESSOR_OPERATIONS.STOREMATRIX] = new ASMProcessorOperation(this.ASM_StoreMatrix);
ASMOperations[(int)ASMPROCESSOR_OPERATIONS.GETMATRIXELEMENT] = new ASMProcessorOperation(this.ASM_GetMatrixElement);
ASMOperations[(int)ASMPROCESSOR_OPERATIONS.NEGATIVE] = new ASMProcessorOperation(this.ASM_Negative);
ASMOperations[(int)ASMPROCESSOR_OPERATIONS.ISEQUAL] = new ASMProcessorOperation(this.ASM_IsEqual);
ASMOperations[(int)ASMPROCESSOR_OPERATIONS.ISNOTEQUAL] = new ASMProcessorOperation(this.ASM_IsNotEqual);
ASMOperations[(int)ASMPROCESSOR_OPERATIONS.ISGREATERTHAN] = new ASMProcessorOperation(this.ASM_IsGreaterThan);
ASMOperations[(int)ASMPROCESSOR_OPERATIONS.ISLESSTHAN] = new ASMProcessorOperation(this.ASM_IsLessThan);
ASMOperations[(int)ASMPROCESSOR_OPERATIONS.ISGREATERTHANEQUAL] = new ASMProcessorOperation(this.ASM_IsGreaterThanEqual);
ASMOperations[(int)ASMPROCESSOR_OPERATIONS.ISLESSTHANEQUAL] = new ASMProcessorOperation(this.ASM_IsLessThanEqual);
ASMOperations[(int)ASMPROCESSOR_OPERATIONS.LOGICALAND] = new ASMProcessorOperation(this.ASM_LogicalAnd);
ASMOperations[(int)ASMPROCESSOR_OPERATIONS.LOGICALOR] = new ASMProcessorOperation(this.ASM_LogicalOR);
ASMOperations[(int)ASMPROCESSOR_OPERATIONS.LOGICALNOT] = new ASMProcessorOperation(this.ASM_LogicalNot);
ASMOperations[(int)ASMPROCESSOR_OPERATIONS.STOREEXTRA] = new ASMProcessorOperation(this.ASM_StoreExtra);
ASMOperations[(int)ASMPROCESSOR_OPERATIONS.JMP] = new ASMProcessorOperation(this.ASM_Jmp);
ASMOperations[(int)ASMPROCESSOR_OPERATIONS.JMPCMP] = new ASMProcessorOperation(this.ASM_JmpCmp);
ASMOperations[(int)ASMPROCESSOR_OPERATIONS.JMPCMP2] = new ASMProcessorOperation(this.ASM_JmpCmp2);
ASMOperations[(int)ASMPROCESSOR_OPERATIONS.STARTMATRIX] = new ASMProcessorOperation(this.ASM_StartMatrix);
ASMOperations[(int)ASMPROCESSOR_OPERATIONS.TRANSPOSE] = new ASMProcessorOperation(this.ASM_Transpose);
ASMOperations[(int)ASMPROCESSOR_OPERATIONS.ADJOINT] = new ASMProcessorOperation(this.ASM_Adjoint);
ASMOperations[(int)ASMPROCESSOR_OPERATIONS.COS] = new ASMProcessorOperation(this.ASM_Cos);
ASMOperations[(int)ASMPROCESSOR_OPERATIONS.SIN] = new ASMProcessorOperation(this.ASM_Sin);
ASMOperations[(int)ASMPROCESSOR_OPERATIONS.TAN] = new ASMProcessorOperation(this.ASM_Tan);
ASMOperations[(int)ASMPROCESSOR_OPERATIONS.ARCCOS] = new ASMProcessorOperation(this.ASM_ArcCos);
ASMOperations[(int)ASMPROCESSOR_OPERATIONS.ARCSIN] = new ASMProcessorOperation(this.ASM_ArcSin);
ASMOperations[(int)ASMPROCESSOR_OPERATIONS.ARCTAN] = new ASMProcessorOperation(this.ASM_ArcTan);
ASMOperations[(int)ASMPROCESSOR_OPERATIONS.NEWIDENTITYMATRIX] = new ASMProcessorOperation(this.ASM_NewIdentityMatrix);
ASMOperations[(int)ASMPROCESSOR_OPERATIONS.PARALLELSTART] = new ASMProcessorOperation(this.ASM_ParallelStart);
ASMOperations[(int)ASMPROCESSOR_OPERATIONS.INPUTNUMBER] = new ASMProcessorOperation(this.ASM_InputNumber);
ASMOperations[(int)ASMPROCESSOR_OPERATIONS.WAITFORDEVICE] = new ASMProcessorOperation(this.ASM_WaitForDevice);
ASMOperations[(int)ASMPROCESSOR_OPERATIONS.SETMATRIXTODEVICE] = new ASMProcessorOperation(this.ASM_SetMatrixToDevice);
ASMOperations[(int)ASMPROCESSOR_OPERATIONS.GETMATRIXFROMDEVICE] = new ASMProcessorOperation(this.ASM_GetMatrixFromDevice);
ASMOperations[(int)ASMPROCESSOR_OPERATIONS.ISMATRIX] = new ASMProcessorOperation(this.ASM_IsMatrix);
ASMOperations[(int)ASMPROCESSOR_OPERATIONS.GETROWS] = new ASMProcessorOperation(this.ASM_GetRows);
ASMOperations[(int)ASMPROCESSOR_OPERATIONS.GETCOLUMNS] = new ASMProcessorOperation(this.ASM_GetColumns);
ASMOperations[(int)ASMPROCESSOR_OPERATIONS.GETPRIMES] = new ASMProcessorOperation(this.ASM_GetPrimes);
ASMOperations[(int)ASMPROCESSOR_OPERATIONS.GETPRIMESUPTO] = new ASMProcessorOperation(this.ASM_GetPrimesUpto);
ASMOperations[(int)ASMPROCESSOR_OPERATIONS.SQRT] = new ASMProcessorOperation(this.ASM_Sqrt);
}
/*private void PushStack(ref ProgramThread currentthread,double pvalue,MEMTYPECONSTANTS ptype){
//lock(this)
//{
currentthread.stackpointer++;
currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.DATA] = pvalue;
currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.TYPE] = (double)ptype;
//}
}*/
/*private void PopStack(ref ProgramThread currentthread)
{
//lock(this)
//{
currentthread.stackpointer--;
//}
}*/
private int PlaceMatrix(Matrix matrix)
{
lock(this)
{
for(int a=0;a<currentcode.matrixstate.Length;a++)
if(currentcode.matrixstate[a]==MatrixState.UNUSED)
{
currentcode.matrixmemory[a] = matrix;
currentcode.matrixstate[a] = MatrixState.NEWMATRIX;
return a;
}
else if(currentcode.matrixstate[a]==MatrixState.REMOVED){
currentcode.matrixmemory[a] = matrix;
currentcode.matrixstate[a] = MatrixState.OVERWITTEN;
return a;
}
}
throw new Exception("Not enough Matrix Memory.");
}
private void FreeMatrixMemory(int loc){
currentcode.matrixmemory[loc]= null;
if(currentcode.matrixstate[loc]==MatrixState.OVERWITTEN ||
currentcode.matrixstate[loc]==MatrixState.AVAILABLE ||
currentcode.matrixstate[loc]==MatrixState.MODIFIED ||
currentcode.matrixstate[loc]==MatrixState.NOTAVAILABLE)
currentcode.matrixstate[loc] = MatrixState.REMOVED;
else
currentcode.matrixstate[loc] = MatrixState.UNUSED;
}
private void MatrixStateModified(int loc){
if(currentcode.matrixstate[loc]==MatrixState.AVAILABLE)
currentcode.matrixstate[loc] = MatrixState.MODIFIED;
}
private void GetMatrix(int loc){
if(currentcode.matrixstate[loc]==MatrixState.NOTAVAILABLE)
GetMatrixIntoMemory(loc);
}
public void Process(ref ProgramThread currentthread)
{
while(currentthread.inspointer<=currentthread.endthread)
{
ASMOperations[currentcode.instructions[currentthread.inspointer]](ref currentthread);
currentthread.inspointer++;
}
}
private void ASM_PushStack(ref ProgramThread currentthread)
{
currentthread.inspointer++;
ushort tempvar = currentcode.instructions[currentthread.inspointer];
currentthread.inspointer++;
ushort tempvar2 = currentcode.instructions[currentthread.inspointer];
//PushStack(ref currentthread,tempvar,(MEMTYPECONSTANTS)tempvar2);
//PushStack Start
currentthread.stackpointer++;
currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.DATA] = tempvar;
currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.TYPE] = tempvar2;
//PushStack End
}
private void ASM_Jmp(ref ProgramThread currentthread)
{
currentthread.inspointer++;
currentthread.inspointer += ((int)currentcode.numconstants[currentcode.instructions [currentthread.inspointer]]);
}
private void ASM_JmpCmp(ref ProgramThread currentthread)
{
currentthread.inspointer++;
if(!currentthread.cmpflag)currentthread.inspointer += ((int)currentcode.numconstants[currentcode.instructions [currentthread.inspointer]]);
}
private void ASM_JmpCmp2(ref ProgramThread currentthread)
{
currentthread.inspointer++;
if(currentthread.cmpflag)currentthread.inspointer += ((int)currentcode.numconstants[currentcode.instructions [currentthread.inspointer]]);
}
private void ASM_GetConstant(ref ProgramThread currentthread)
{
currentthread.inspointer++;
//PushStack(ref currentthread,currentcode.numconstants [
// currentcode.instructions [currentthread.inspointer]
// ],MEMTYPECONSTANTS.VALUE);
//PushStack Start
currentthread.stackpointer++;
currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.DATA] =
currentcode.numconstants [currentcode.instructions
[currentthread.inspointer]];
currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.TYPE] = (double)MEMTYPECONSTANTS.VALUE;
//PushStack End
}
private void ASM_GetMemory(ref ProgramThread currentthread)
{
ushort tempvar;
currentthread.inspointer++;
tempvar = currentcode.instructions [currentthread.inspointer];
//PushStack(ref currentthread,currentcode.memory[tempvar,(int)MEMCONSTANTS.DATA],
// (MEMTYPECONSTANTS)currentcode.memory[tempvar,(int)MEMCONSTANTS.TYPE]);
//PushStack Start
currentthread.stackpointer++;
currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.DATA] = currentcode.memory[tempvar,(int)MEMCONSTANTS.DATA];
currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.TYPE] = currentcode.memory[tempvar,(int)MEMCONSTANTS.TYPE];
//PushStack End
}
private void ASM_Add(ref ProgramThread currentthread)
{
double tempvar1,tempvar2;
MEMTYPECONSTANTS tempvar1type,tempvar2type;
tempvar1 = currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.DATA];
tempvar1type =(MEMTYPECONSTANTS)currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.TYPE];
currentthread.stackpointer--;
tempvar2 = currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.DATA];
tempvar2type =(MEMTYPECONSTANTS)currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.TYPE];
currentthread.stackpointer--;
if(tempvar1type==MEMTYPECONSTANTS.VALUE && tempvar2type==MEMTYPECONSTANTS.VALUE)
tempvar1 = tempvar1+tempvar2;
else if(tempvar1type==MEMTYPECONSTANTS.VALUE && (tempvar2type==MEMTYPECONSTANTS.REFERENCE || tempvar2type==MEMTYPECONSTANTS.TEMPREFERENCE))
{
GetMatrix((int)tempvar2);
Matrix temp = currentcode.matrixmemory[(int)tempvar2];
temp = temp + tempvar1;
if(tempvar2type==MEMTYPECONSTANTS.TEMPREFERENCE)
{
currentcode.matrixmemory[(int)tempvar2] = temp;
MatrixStateModified((int)tempvar2);
tempvar1 = tempvar2;
tempvar1type = MEMTYPECONSTANTS.TEMPREFERENCE;
}
else
{
tempvar1 = PlaceMatrix(temp);
tempvar1type = MEMTYPECONSTANTS.TEMPREFERENCE;
}
}
else if(tempvar2type==MEMTYPECONSTANTS.VALUE && (tempvar1type==MEMTYPECONSTANTS.REFERENCE || tempvar1type==MEMTYPECONSTANTS.TEMPREFERENCE))
{
GetMatrix((int)tempvar1);
Matrix temp = currentcode.matrixmemory[(int)tempvar1];
temp = temp + tempvar2;
if(tempvar1type==MEMTYPECONSTANTS.TEMPREFERENCE)
{
currentcode.matrixmemory[(int)tempvar1] = temp;
MatrixStateModified((int)tempvar1);
}
else
{
tempvar1 = PlaceMatrix(temp);
tempvar1type = MEMTYPECONSTANTS.TEMPREFERENCE;
}
}
else if((tempvar2type==MEMTYPECONSTANTS.REFERENCE || tempvar2type==MEMTYPECONSTANTS.TEMPREFERENCE) && (tempvar1type==MEMTYPECONSTANTS.REFERENCE || tempvar1type==MEMTYPECONSTANTS.TEMPREFERENCE))
{
GetMatrix((int)tempvar2);
GetMatrix((int)tempvar1);
Matrix temp1 = currentcode.matrixmemory[(int)tempvar1];
Matrix temp2 = currentcode.matrixmemory[(int)tempvar2];
temp1 = temp1+temp2;
if(tempvar1type==MEMTYPECONSTANTS.TEMPREFERENCE)
{
currentcode.matrixmemory[(int)tempvar1] = temp1;
MatrixStateModified((int)tempvar1);
if(tempvar2type==MEMTYPECONSTANTS.TEMPREFERENCE)FreeMatrixMemory((int)tempvar2);
}
else if(tempvar2type==MEMTYPECONSTANTS.TEMPREFERENCE)
{
currentcode.matrixmemory[(int)tempvar2] = temp1;
MatrixStateModified((int)tempvar2);
tempvar1 = tempvar2;
tempvar1type = MEMTYPECONSTANTS.TEMPREFERENCE;
}
else
{
tempvar1 = PlaceMatrix(temp1);
tempvar1type = MEMTYPECONSTANTS.TEMPREFERENCE;
}
}
else
throw new Exception("Type mismatch");
//PushStack(ref currentthread,tempvar1,tempvar1type);
//PushStack Start
currentthread.stackpointer++;
currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.DATA] =tempvar1;
currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.TYPE] =(double)tempvar1type;
//PushStack End
}
private void ASM_Multiply(ref ProgramThread currentthread)
{
double tempvar1,tempvar2;
MEMTYPECONSTANTS tempvar1type,tempvar2type;
tempvar1 = currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.DATA];
tempvar1type =(MEMTYPECONSTANTS)currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.TYPE];
currentthread.stackpointer--;
tempvar2 = currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.DATA];
tempvar2type =(MEMTYPECONSTANTS)currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.TYPE];
currentthread.stackpointer--;
if(tempvar1type==MEMTYPECONSTANTS.VALUE && tempvar2type==MEMTYPECONSTANTS.VALUE)
tempvar1 = tempvar1*tempvar2;
else if(tempvar1type==MEMTYPECONSTANTS.VALUE && (tempvar2type==MEMTYPECONSTANTS.REFERENCE || tempvar2type==MEMTYPECONSTANTS.TEMPREFERENCE))
{
GetMatrix((int)tempvar2);
Matrix temp = currentcode.matrixmemory[(int)tempvar2];
temp = temp * tempvar1;
if(tempvar2type==MEMTYPECONSTANTS.TEMPREFERENCE)
{
currentcode.matrixmemory[(int)tempvar2] = temp;
MatrixStateModified((int)tempvar2);
tempvar1 = tempvar2;
tempvar1type = MEMTYPECONSTANTS.TEMPREFERENCE;
}
else
{
tempvar1 = PlaceMatrix(temp);
tempvar1type = MEMTYPECONSTANTS.TEMPREFERENCE;
}
}
else if(tempvar2type==MEMTYPECONSTANTS.VALUE && (tempvar1type==MEMTYPECONSTANTS.REFERENCE || tempvar1type==MEMTYPECONSTANTS.TEMPREFERENCE))
{
GetMatrix((int)tempvar1);
Matrix temp = currentcode.matrixmemory[(int)tempvar1];
temp = temp * tempvar2;
if(tempvar1type==MEMTYPECONSTANTS.TEMPREFERENCE)
{
currentcode.matrixmemory[(int)tempvar1] = temp;
MatrixStateModified((int)tempvar2);
}
else
{
tempvar1 = PlaceMatrix(temp);
tempvar1type = MEMTYPECONSTANTS.TEMPREFERENCE;
}
}
else if((tempvar2type==MEMTYPECONSTANTS.REFERENCE || tempvar2type==MEMTYPECONSTANTS.TEMPREFERENCE) && (tempvar1type==MEMTYPECONSTANTS.REFERENCE || tempvar1type==MEMTYPECONSTANTS.TEMPREFERENCE))
{
GetMatrix((int)tempvar2);
GetMatrix((int)tempvar1);
Matrix temp1 = currentcode.matrixmemory[(int)tempvar1];
Matrix temp2 = currentcode.matrixmemory[(int)tempvar2];
temp1 = temp1*temp2;
if(tempvar1type==MEMTYPECONSTANTS.TEMPREFERENCE)
{
currentcode.matrixmemory[(int)tempvar1] = temp1;
MatrixStateModified((int)tempvar1);
if(tempvar2type==MEMTYPECONSTANTS.TEMPREFERENCE)FreeMatrixMemory((int)tempvar2);;
}
else if(tempvar2type==MEMTYPECONSTANTS.TEMPREFERENCE)
{
currentcode.matrixmemory[(int)tempvar2] = temp1;
MatrixStateModified((int)tempvar2);
tempvar1 = tempvar2;
tempvar1type = MEMTYPECONSTANTS.TEMPREFERENCE;
}
else
{
tempvar1 = PlaceMatrix(temp1);
tempvar1type = MEMTYPECONSTANTS.TEMPREFERENCE;
}
}
else
throw new Exception("Type mismatch");
//PushStack(ref currentthread,tempvar1,tempvar1type);
//PushStack Start
currentthread.stackpointer++;
currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.DATA] =tempvar1;
currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.TYPE] =(double)tempvar1type;
//PushStack End
}
private void ASM_Subtract(ref ProgramThread currentthread)
{
double tempvar1,tempvar2;
MEMTYPECONSTANTS tempvar1type,tempvar2type;
tempvar1 = currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.DATA];
tempvar1type =(MEMTYPECONSTANTS)currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.TYPE];
currentthread.stackpointer--;
tempvar2 = currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.DATA];
tempvar2type =(MEMTYPECONSTANTS)currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.TYPE];
currentthread.stackpointer--;
if(tempvar1type==MEMTYPECONSTANTS.VALUE && tempvar2type==MEMTYPECONSTANTS.VALUE)
tempvar1 = tempvar1-tempvar2;
else if(tempvar2type==MEMTYPECONSTANTS.VALUE && (tempvar1type==MEMTYPECONSTANTS.REFERENCE || tempvar1type==MEMTYPECONSTANTS.TEMPREFERENCE))
{
GetMatrix((int)tempvar1);
Matrix temp = currentcode.matrixmemory[(int)tempvar1];
temp = temp - tempvar2;
if(tempvar1type==MEMTYPECONSTANTS.TEMPREFERENCE)
{
MatrixStateModified((int)tempvar1);
currentcode.matrixmemory[(int)tempvar1] = temp;
}
else
{
tempvar1 = PlaceMatrix(temp);
tempvar1type = MEMTYPECONSTANTS.TEMPREFERENCE;
}
}
else if(tempvar1type==MEMTYPECONSTANTS.VALUE && (tempvar2type==MEMTYPECONSTANTS.REFERENCE || tempvar2type==MEMTYPECONSTANTS.TEMPREFERENCE))
{
GetMatrix((int)tempvar2);
if(tempvar2type==MEMTYPECONSTANTS.TEMPREFERENCE)
{
currentcode.matrixmemory[(int)tempvar2].InvSub(tempvar1);
MatrixStateModified((int)tempvar2);
tempvar1 = tempvar2;
}
else
{
Matrix temp = currentcode.matrixmemory[(int)tempvar2];
temp = temp.ReturnInvSub(tempvar1);
tempvar1 = PlaceMatrix(temp);
}
tempvar1type = MEMTYPECONSTANTS.TEMPREFERENCE;
}
else if((tempvar2type==MEMTYPECONSTANTS.REFERENCE || tempvar2type==MEMTYPECONSTANTS.TEMPREFERENCE) && (tempvar1type==MEMTYPECONSTANTS.REFERENCE || tempvar1type==MEMTYPECONSTANTS.TEMPREFERENCE))
{
GetMatrix((int)tempvar1);
GetMatrix((int)tempvar2);
Matrix temp1 = currentcode.matrixmemory[(int)tempvar1];
Matrix temp2 = currentcode.matrixmemory[(int)tempvar2];
temp1 = temp1-temp2;
if(tempvar1type==MEMTYPECONSTANTS.TEMPREFERENCE)
{
MatrixStateModified((int)tempvar1);
currentcode.matrixmemory[(int)tempvar1] = temp1;
if(tempvar2type==MEMTYPECONSTANTS.TEMPREFERENCE)FreeMatrixMemory((int)tempvar2);
}
else if(tempvar2type==MEMTYPECONSTANTS.TEMPREFERENCE)
{
MatrixStateModified((int)tempvar2);
currentcode.matrixmemory[(int)tempvar2] = temp1;
tempvar1 = tempvar2;
tempvar1type = MEMTYPECONSTANTS.TEMPREFERENCE;
}
else
{
tempvar1 = PlaceMatrix(temp1);
tempvar1type = MEMTYPECONSTANTS.TEMPREFERENCE;
}
}
else
throw new Exception("Type mismatch");
//PushStack(ref currentthread,tempvar1,tempvar1type);
//PushStack Start
currentthread.stackpointer++;
currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.DATA] =tempvar1;
currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.TYPE] =(double)tempvar1type;
//PushStack End
}
private void ASM_Divide(ref ProgramThread currentthread)
{
double tempvar1,tempvar2;
MEMTYPECONSTANTS tempvar1type,tempvar2type;
tempvar1 = currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.DATA];
tempvar1type =(MEMTYPECONSTANTS)currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.TYPE];
currentthread.stackpointer--;
tempvar2 = currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.DATA];
tempvar2type =(MEMTYPECONSTANTS)currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.TYPE];
currentthread.stackpointer--;
if(tempvar1type==MEMTYPECONSTANTS.VALUE && tempvar2type==MEMTYPECONSTANTS.VALUE)
tempvar1 = tempvar1/tempvar2;
else if(tempvar2type==MEMTYPECONSTANTS.VALUE && (tempvar1type==MEMTYPECONSTANTS.REFERENCE || tempvar1type==MEMTYPECONSTANTS.TEMPREFERENCE))
{
GetMatrix((int)tempvar1);
Matrix temp = currentcode.matrixmemory[(int)tempvar1];
temp = temp / tempvar2;
if(tempvar1type==MEMTYPECONSTANTS.TEMPREFERENCE)
{
currentcode.matrixmemory[(int)tempvar1] = temp;
MatrixStateModified((int)tempvar1);
}
else
{
tempvar1 = PlaceMatrix(temp);
tempvar1type = MEMTYPECONSTANTS.TEMPREFERENCE;
}
}
else if(tempvar1type==MEMTYPECONSTANTS.VALUE && (tempvar2type==MEMTYPECONSTANTS.REFERENCE || tempvar2type==MEMTYPECONSTANTS.TEMPREFERENCE))
{
GetMatrix((int)tempvar2);
if(tempvar2type==MEMTYPECONSTANTS.TEMPREFERENCE)
{
currentcode.matrixmemory[(int)tempvar2].InvDiv(tempvar1);
MatrixStateModified((int)tempvar2);
tempvar1 = tempvar2;
}
else
{
Matrix temp = currentcode.matrixmemory[(int)tempvar2];
temp = temp.ReturnInvDiv(tempvar1);
tempvar1 = PlaceMatrix(temp);
}
tempvar1type = MEMTYPECONSTANTS.TEMPREFERENCE;
}
else if((tempvar2type==MEMTYPECONSTANTS.REFERENCE || tempvar2type==MEMTYPECONSTANTS.TEMPREFERENCE) && (tempvar1type==MEMTYPECONSTANTS.REFERENCE || tempvar1type==MEMTYPECONSTANTS.TEMPREFERENCE))
{
GetMatrix((int)tempvar1);
GetMatrix((int)tempvar2);
Matrix temp1 = currentcode.matrixmemory[(int)tempvar1];
Matrix temp2 = currentcode.matrixmemory[(int)tempvar2];
temp1 = temp1/temp2;
if(tempvar1type==MEMTYPECONSTANTS.TEMPREFERENCE)
{
currentcode.matrixmemory[(int)tempvar1] = temp1;
MatrixStateModified((int)tempvar1);
if(tempvar2type==MEMTYPECONSTANTS.TEMPREFERENCE)FreeMatrixMemory((int)tempvar2);
}
else if(tempvar2type==MEMTYPECONSTANTS.TEMPREFERENCE)
{
currentcode.matrixmemory[(int)tempvar2] = temp1;
MatrixStateModified((int)tempvar2);
tempvar1 = tempvar2;
tempvar1type = MEMTYPECONSTANTS.TEMPREFERENCE;
}
else
{
tempvar1 = PlaceMatrix(temp1);
tempvar1type = MEMTYPECONSTANTS.TEMPREFERENCE;
}
}
else
throw new Exception("Type mismatch");
//PushStack(ref currentthread,tempvar1,tempvar1type);
//PushStack Start
currentthread.stackpointer++;
currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.DATA] =tempvar1;
currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.TYPE] =(double)tempvar1type;
//PushStack End
}
private void ASM_Exponent(ref ProgramThread currentthread)
{
double tempvar1,tempvar2;
MEMTYPECONSTANTS tempvar1type,tempvar2type;
tempvar1 = currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.DATA];
tempvar1type =(MEMTYPECONSTANTS)currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.TYPE];
currentthread.stackpointer--;
tempvar2 = currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.DATA];
tempvar2type =(MEMTYPECONSTANTS)currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.TYPE];
currentthread.stackpointer--;
if(tempvar1type==MEMTYPECONSTANTS.VALUE && tempvar2type==MEMTYPECONSTANTS.VALUE)
tempvar1 = Math.Pow(tempvar1,tempvar2);
else if(tempvar2type==MEMTYPECONSTANTS.VALUE && (tempvar1type==MEMTYPECONSTANTS.REFERENCE || tempvar1type==MEMTYPECONSTANTS.TEMPREFERENCE))
{
GetMatrix((int)tempvar1);
Matrix temp = currentcode.matrixmemory[(int)tempvar1];
temp = temp ^ tempvar2;
if(tempvar1type==MEMTYPECONSTANTS.TEMPREFERENCE)
{
currentcode.matrixmemory[(int)tempvar1] = temp;
MatrixStateModified( (int)tempvar1);
}
else
{
tempvar1 = PlaceMatrix(temp);
tempvar1type = MEMTYPECONSTANTS.TEMPREFERENCE;
}
}
else if(tempvar1type==MEMTYPECONSTANTS.VALUE && (tempvar2type==MEMTYPECONSTANTS.REFERENCE || tempvar2type==MEMTYPECONSTANTS.TEMPREFERENCE))
{
GetMatrix((int)tempvar2);
if(tempvar2type==MEMTYPECONSTANTS.TEMPREFERENCE)
{
currentcode.matrixmemory[(int)tempvar2].InvExp(tempvar1);
MatrixStateModified( (int)tempvar2);
tempvar1 = tempvar2;
}
else
{
Matrix temp = currentcode.matrixmemory[(int)tempvar2];
temp = temp.ReturnInvExp(tempvar1);
tempvar1 = PlaceMatrix(temp);
}
tempvar1type = MEMTYPECONSTANTS.TEMPREFERENCE;
}
else if((tempvar2type==MEMTYPECONSTANTS.REFERENCE || tempvar2type==MEMTYPECONSTANTS.TEMPREFERENCE) && (tempvar1type==MEMTYPECONSTANTS.REFERENCE || tempvar1type==MEMTYPECONSTANTS.TEMPREFERENCE))
{
GetMatrix((int)tempvar1);
GetMatrix( (int)tempvar2);
Matrix temp1 = currentcode.matrixmemory[(int)tempvar1];
Matrix temp2 = currentcode.matrixmemory[(int)tempvar2];
temp1 = temp1^temp2;
if(tempvar1type==MEMTYPECONSTANTS.TEMPREFERENCE)
{
currentcode.matrixmemory[(int)tempvar1] = temp1;
MatrixStateModified( (int)tempvar1);
if(tempvar2type==MEMTYPECONSTANTS.TEMPREFERENCE)FreeMatrixMemory((int)tempvar2);
}
else if(tempvar2type==MEMTYPECONSTANTS.TEMPREFERENCE)
{
currentcode.matrixmemory[(int)tempvar2] = temp1;
MatrixStateModified((int)tempvar2);
tempvar1 = tempvar2;
tempvar1type = MEMTYPECONSTANTS.TEMPREFERENCE;
}
else
{
tempvar1 = PlaceMatrix(temp1);
tempvar1type = MEMTYPECONSTANTS.TEMPREFERENCE;
}
}
else
throw new Exception("Type mismatch");
//PushStack(ref currentthread,tempvar1,tempvar1type);
//PushStack Start
currentthread.stackpointer++;
currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.DATA] =tempvar1;
currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.TYPE] =(double)tempvar1type;
//PushStack End
}
private void ASM_Mod(ref ProgramThread currentthread)
{
double tempvar1,tempvar2;
MEMTYPECONSTANTS tempvar1type,tempvar2type;
tempvar1 = currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.DATA];
tempvar1type =(MEMTYPECONSTANTS)currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.TYPE];
currentthread.stackpointer--;
tempvar2 = currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.DATA];
tempvar2type =(MEMTYPECONSTANTS)currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.TYPE];
currentthread.stackpointer--;
if(tempvar1type==MEMTYPECONSTANTS.VALUE && tempvar2type==MEMTYPECONSTANTS.VALUE)
tempvar1 = tempvar1 % tempvar2;
else if(tempvar2type==MEMTYPECONSTANTS.VALUE && (tempvar1type==MEMTYPECONSTANTS.REFERENCE || tempvar1type==MEMTYPECONSTANTS.TEMPREFERENCE))
{
GetMatrix((int)tempvar1);
Matrix temp = currentcode.matrixmemory[(int)tempvar1];
temp = temp % tempvar2;
if(tempvar1type==MEMTYPECONSTANTS.TEMPREFERENCE)
{
currentcode.matrixmemory[(int)tempvar1] = temp;
MatrixStateModified( (int)tempvar1);
}
else
{
tempvar1 = PlaceMatrix(temp);
tempvar1type = MEMTYPECONSTANTS.TEMPREFERENCE;
}
}
else if(tempvar1type==MEMTYPECONSTANTS.VALUE && (tempvar2type==MEMTYPECONSTANTS.REFERENCE || tempvar2type==MEMTYPECONSTANTS.TEMPREFERENCE))
{
GetMatrix((int)tempvar2);
if(tempvar2type==MEMTYPECONSTANTS.TEMPREFERENCE)
{
currentcode.matrixmemory[(int)tempvar2].InvMod(tempvar1);
MatrixStateModified( (int)tempvar2);
tempvar1 = tempvar2;
}
else
{
Matrix temp = currentcode.matrixmemory[(int)tempvar2];
temp = temp.ReturnInvMod(tempvar1);
tempvar1 = PlaceMatrix(temp);
}
tempvar1type = MEMTYPECONSTANTS.TEMPREFERENCE;
}
else if((tempvar2type==MEMTYPECONSTANTS.REFERENCE || tempvar2type==MEMTYPECONSTANTS.TEMPREFERENCE) && (tempvar1type==MEMTYPECONSTANTS.REFERENCE || tempvar1type==MEMTYPECONSTANTS.TEMPREFERENCE))
{
GetMatrix((int)tempvar1);
GetMatrix((int)tempvar2);
Matrix temp1 = currentcode.matrixmemory[(int)tempvar1];
Matrix temp2 = currentcode.matrixmemory[(int)tempvar2];
temp1 = temp1%temp2;
if(tempvar1type==MEMTYPECONSTANTS.TEMPREFERENCE)
{
currentcode.matrixmemory[(int)tempvar1] = temp1;
MatrixStateModified( (int)tempvar1);
if(tempvar2type==MEMTYPECONSTANTS.TEMPREFERENCE)FreeMatrixMemory((int)tempvar2);
}
else if(tempvar2type==MEMTYPECONSTANTS.TEMPREFERENCE)
{
currentcode.matrixmemory[(int)tempvar2] = temp1;
MatrixStateModified( (int)tempvar2);
tempvar1 = tempvar2;
tempvar1type = MEMTYPECONSTANTS.TEMPREFERENCE;
}
else
{
tempvar1 = PlaceMatrix(temp1);
tempvar1type = MEMTYPECONSTANTS.TEMPREFERENCE;
}
}
else
throw new Exception("Type mismatch");
//PushStack(ref currentthread,tempvar1,tempvar1type);
//PushStack Start
currentthread.stackpointer++;
currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.DATA] =tempvar1;
currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.TYPE] =(double)tempvar1type;
//PushStack End
}
private void ASM_Negative(ref ProgramThread currentthread)
{
double tempvar1;
MEMTYPECONSTANTS tempvar1type;
tempvar1 = currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.DATA];
tempvar1type =(MEMTYPECONSTANTS)currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.TYPE];
currentthread.stackpointer--;
if(tempvar1type==MEMTYPECONSTANTS.VALUE)
tempvar1 = -(tempvar1);
else if(tempvar1type==MEMTYPECONSTANTS.REFERENCE || tempvar1type==MEMTYPECONSTANTS.TEMPREFERENCE)
{
GetMatrix((int)tempvar1);
Matrix temp = currentcode.matrixmemory[(int)tempvar1];
temp = temp.ReturnNegative();
if(tempvar1type==MEMTYPECONSTANTS.TEMPREFERENCE)
{
currentcode.matrixmemory[(int)tempvar1] = temp;
MatrixStateModified((int)tempvar1);
}
else
{
tempvar1 = PlaceMatrix(temp);
tempvar1type = MEMTYPECONSTANTS.TEMPREFERENCE;
}
}
else
throw new Exception("Type mismatch");
//PushStack(ref currentthread,tempvar1,tempvar1type);
//PushStack Start
currentthread.stackpointer++;
currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.DATA] =tempvar1;
currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.TYPE] =(double)tempvar1type;
//PushStack End
}
private void ASM_Store(ref ProgramThread currentthread)
{
ushort tempvar;
int rmm=-2;
currentthread.inspointer++;
if((MEMTYPECONSTANTS)currentcode.memory[currentcode.instructions [
currentthread.inspointer],(int)MEMCONSTANTS.TYPE]==
MEMTYPECONSTANTS.REFERENCE ||(MEMTYPECONSTANTS)currentcode.memory[
currentcode.instructions[currentthread.inspointer],
(int)MEMCONSTANTS.TYPE]==MEMTYPECONSTANTS.TEMPREFERENCE)
rmm =(int)currentcode.memory[currentcode.instructions
[currentthread.inspointer],(int)MEMCONSTANTS.DATA];
tempvar =(ushort)currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.TYPE];
if(tempvar==(ushort)MEMTYPECONSTANTS.VALUE)
{
tempvar = currentcode.instructions [currentthread.inspointer];
currentcode.memory[tempvar,(int)MEMCONSTANTS.DATA] = currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.DATA];
currentcode.memory[tempvar,(int)MEMCONSTANTS.TYPE] = (double)MEMTYPECONSTANTS.VALUE;
}
else if(tempvar==(ushort)MEMTYPECONSTANTS.REFERENCE)
{
tempvar = currentcode.instructions [currentthread.inspointer];
GetMatrix((int)currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.DATA]);
Matrix temp = currentcode.matrixmemory[(int)currentthread.pstack
[currentthread.stackpointer,(int)MEMCONSTANTS.DATA]].ReturnClone();
currentcode.memory[tempvar,(int)MEMCONSTANTS.DATA]= PlaceMatrix(temp);
currentcode.memory[tempvar,(int)MEMCONSTANTS.TYPE] = (double)MEMTYPECONSTANTS.REFERENCE;
}
else if(tempvar==(ushort)MEMTYPECONSTANTS.TEMPREFERENCE)
{
tempvar = currentcode.instructions [currentthread.inspointer];
currentcode.memory[tempvar,(int)MEMCONSTANTS.DATA]= currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.DATA];
currentcode.memory[tempvar,(int)MEMCONSTANTS.TYPE] = (double)MEMTYPECONSTANTS.REFERENCE;
}
currentthread.stackpointer--;
if(rmm>=0)
FreeMatrixMemory(rmm);
}
private void ASM_Print(ref ProgramThread currentthread)
{
double tempvar1;
MEMTYPECONSTANTS tempvar1type;
string output="";
currentthread.inspointer++;
ushort argcount = currentcode.instructions[
currentthread.inspointer];
for(ushort tmp=1;tmp<=argcount;tmp++)
{
tempvar1 = currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.DATA];
tempvar1type =(MEMTYPECONSTANTS)currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.TYPE];
currentthread.stackpointer--;
if(tempvar1type == MEMTYPECONSTANTS.VALUE)
output += tempvar1.ToString()+" ";
else if(tempvar1type == MEMTYPECONSTANTS.REFERENCE || tempvar1type == MEMTYPECONSTANTS.TEMPREFERENCE)
{
GetMatrix((int)tempvar1);
output += currentcode.matrixmemory[(int)tempvar1].Display()+" ";
if(tempvar1type == MEMTYPECONSTANTS.TEMPREFERENCE)FreeMatrixMemory((int)tempvar1);
}
else if(tempvar1type == MEMTYPECONSTANTS.LITERAL)
output += currentcode.literals[(int)tempvar1]+" ";
else
throw new Exception("Type mismatch");
}
currentcode.bus.Out.Output(output);
currentcode.bus.Out.Output("\r\n");
}
private void ASM_InputNumber(ref ProgramThread currentthread)
{
double tempvar1;
MEMTYPECONSTANTS tempvar1type;
string output="";
currentthread.inspointer++;
ushort argcount = currentcode.instructions[
currentthread.inspointer];
for(ushort tmp=1;tmp<=argcount;tmp++)
{
tempvar1 = currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.DATA];
tempvar1type =(MEMTYPECONSTANTS)currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.TYPE];
currentthread.stackpointer--;
if(tempvar1type == MEMTYPECONSTANTS.VALUE)
output += tempvar1.ToString();
else if(tempvar1type == MEMTYPECONSTANTS.REFERENCE || tempvar1type == MEMTYPECONSTANTS.TEMPREFERENCE)
{
GetMatrix((int)tempvar1);
output += currentcode.matrixmemory[(int)tempvar1].Display();
if(tempvar1type == MEMTYPECONSTANTS.TEMPREFERENCE)currentcode.matrixmemory[(int)tempvar1]= null;
}
else if(tempvar1type == MEMTYPECONSTANTS.LITERAL)
output += currentcode.literals[(int)tempvar1];
else
throw new Exception("Type mismatch");
}
lock(this)
{
//currentcode.bus.Out.Output(output);
//PushStack Start
currentthread.stackpointer++;
currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.DATA] =currentcode.bus.In.Input(output);
currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.TYPE] =(double)MEMTYPECONSTANTS.VALUE;
//PushStack End
}
}
private void ASM_NewMatrix(ref ProgramThread currentthread)
{
double tempvar1,tempvar2;
MEMTYPECONSTANTS tempvar1type,tempvar2type;
tempvar1 = currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.DATA];
tempvar1type =(MEMTYPECONSTANTS)currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.TYPE];
currentthread.stackpointer--;
tempvar2 = currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.DATA];
tempvar2type =(MEMTYPECONSTANTS)currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.TYPE];
currentthread.stackpointer--;
if(tempvar1type != MEMTYPECONSTANTS.VALUE || tempvar2type != MEMTYPECONSTANTS.VALUE)throw new Exception("Type mismatch");
tempvar1 = PlaceMatrix(new Matrix((int)tempvar1,(int)tempvar2));
tempvar1type = MEMTYPECONSTANTS.TEMPREFERENCE;
//PushStack(ref currentthread,tempvar1,tempvar1type);
//PushStack Start
currentthread.stackpointer++;
currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.DATA] =tempvar1;
currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.TYPE] =(double)tempvar1type;
//PushStack End
}
private void ASM_StartMatrix(ref ProgramThread currentthread)
{
currentthread.inspointer++;
int rws = currentcode.instructions[currentthread.inspointer];
currentthread.inspointer++;
int cols = (int)currentcode.numconstants[currentcode.instructions[currentthread.inspointer]];
Matrix temp = new Matrix(rws,cols);
for(int rw=0;rw<rws;rw++)
{
currentthread.inspointer++;
if((ASMPROCESSOR_OPERATIONS)currentcode.instructions[currentthread.inspointer]==ASMPROCESSOR_OPERATIONS.ROWDEFINEDBYVALUES)
for(int cl=0;cl<cols;cl++)
{
currentthread.inspointer++;
temp.m_MatArr[rw,cl] = currentcode.numconstants[currentcode.instructions[currentthread.inspointer]];
}
else
{
double st,inc;
currentthread.inspointer++;
st = currentcode.numconstants[currentcode.instructions[currentthread.inspointer]];
currentthread.inspointer++;
inc = currentcode.numconstants[currentcode.instructions[currentthread.inspointer]];
double tmp=st;
for(int cl=0;cl<cols;cl++)
{
temp.m_MatArr[rw,cl] = tmp;
tmp=tmp+inc;
}
}
}
//PushStack(ref currentthread,PlaceMatrix(temp),MEMTYPECONSTANTS.TEMPREFERENCE);
//PushStack Start
currentthread.stackpointer++;
currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.DATA] =PlaceMatrix(temp);
currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.TYPE] =(double)MEMTYPECONSTANTS.TEMPREFERENCE;
//PushStack End
}
private void ASM_StoreMatrix(ref ProgramThread currentthread)
{
double tempvar1,tempvar2,tempvar3,tempvar4;
MEMTYPECONSTANTS tempvar1type,tempvar2type,tempvar3type,tempvar4type;
tempvar1 = currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.DATA];
tempvar1type =(MEMTYPECONSTANTS)currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.TYPE];
currentthread.stackpointer--;
tempvar2 = currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.DATA];
tempvar2type =(MEMTYPECONSTANTS)currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.TYPE];
currentthread.stackpointer--;
tempvar3 = currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.DATA];
tempvar3type =(MEMTYPECONSTANTS)currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.TYPE];
currentthread.stackpointer--;
tempvar4 = currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.DATA];
tempvar4type =(MEMTYPECONSTANTS)currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.TYPE];
currentthread.stackpointer--;
if(tempvar1type != MEMTYPECONSTANTS.REFERENCE )throw new Exception("Type mismatch");
if(tempvar2type != MEMTYPECONSTANTS.VALUE )throw new Exception("Type mismatch");
if(tempvar3type != MEMTYPECONSTANTS.VALUE )throw new Exception("Type mismatch");
if(tempvar4type != MEMTYPECONSTANTS.VALUE )throw new Exception("Type mismatch");
GetMatrix((int)tempvar1);
currentcode.matrixmemory[(int)tempvar1].SetValue((int)tempvar2,(int)tempvar3,tempvar4);
MatrixStateModified((int)tempvar1);
}
private void ASM_GetMatrixElement(ref ProgramThread currentthread)
{
double tempvar1,tempvar2,tempvar3;
MEMTYPECONSTANTS tempvar1type,tempvar2type,tempvar3type;
tempvar1 = currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.DATA];
tempvar1type =(MEMTYPECONSTANTS)currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.TYPE];
currentthread.stackpointer--;
tempvar2 = currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.DATA];
tempvar2type =(MEMTYPECONSTANTS)currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.TYPE];
currentthread.stackpointer--;
tempvar3 = currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.DATA];
tempvar3type =(MEMTYPECONSTANTS)currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.TYPE];
currentthread.stackpointer--;
if(tempvar1type != MEMTYPECONSTANTS.REFERENCE )throw new Exception("Type mismatch");
if(tempvar2type != MEMTYPECONSTANTS.VALUE )throw new Exception("Type mismatch");
if(tempvar3type != MEMTYPECONSTANTS.VALUE )throw new Exception("Type mismatch");
//PushStack(ref currentthread,currentcode.matrixmemory[(int)tempvar1].GetValue((int)tempvar2,(int)tempvar3),MEMTYPECONSTANTS.VALUE);
//PushStack Start
currentthread.stackpointer++;
GetMatrix((int)tempvar1);
currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.DATA] =currentcode.matrixmemory[(int)tempvar1].GetValue((int)tempvar2,(int)tempvar3);
currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.TYPE] =(double)MEMTYPECONSTANTS.VALUE;
//PushStack End
}
private void ASM_IsEqual(ref ProgramThread currentthread)
{
double tempvar1,tempvar2;
MEMTYPECONSTANTS tempvar1type,tempvar2type;
tempvar1 = currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.DATA];
tempvar1type =(MEMTYPECONSTANTS)currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.TYPE];
currentthread.stackpointer--;
tempvar2 = currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.DATA];
tempvar2type =(MEMTYPECONSTANTS)currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.TYPE];
currentthread.stackpointer--;
if(tempvar1type==MEMTYPECONSTANTS.VALUE && tempvar2type==MEMTYPECONSTANTS.VALUE)
currentthread.cmpflag = (tempvar1 == tempvar2);
else if((tempvar1type==MEMTYPECONSTANTS.REFERENCE || tempvar1type==MEMTYPECONSTANTS.TEMPREFERENCE) && (tempvar2type==MEMTYPECONSTANTS.REFERENCE || tempvar2type==MEMTYPECONSTANTS.TEMPREFERENCE))
{
GetMatrix((int)tempvar1);GetMatrix((int)tempvar2);
currentthread.cmpflag = (currentcode.matrixmemory[(int)tempvar1] == currentcode.matrixmemory[(int)tempvar2]);
if(tempvar1type == MEMTYPECONSTANTS.TEMPREFERENCE)FreeMatrixMemory((int)tempvar1);
if(tempvar2type == MEMTYPECONSTANTS.TEMPREFERENCE)FreeMatrixMemory((int)tempvar2);
}
else
throw new Exception("Type mismatch");
}
private void ASM_IsNotEqual(ref ProgramThread currentthread)
{
double tempvar1,tempvar2;
MEMTYPECONSTANTS tempvar1type,tempvar2type;
tempvar1 = currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.DATA];
tempvar1type =(MEMTYPECONSTANTS)currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.TYPE];
currentthread.stackpointer--;
tempvar2 = currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.DATA];
tempvar2type =(MEMTYPECONSTANTS)currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.TYPE];
currentthread.stackpointer--;
if(tempvar1type==MEMTYPECONSTANTS.VALUE && tempvar2type==MEMTYPECONSTANTS.VALUE)
currentthread.cmpflag = (tempvar1 != tempvar2);
else if((tempvar1type==MEMTYPECONSTANTS.REFERENCE || tempvar1type==MEMTYPECONSTANTS.TEMPREFERENCE) && (tempvar2type==MEMTYPECONSTANTS.REFERENCE || tempvar2type==MEMTYPECONSTANTS.TEMPREFERENCE))
{
GetMatrix((int)tempvar1);GetMatrix((int)tempvar2);
currentthread.cmpflag = (currentcode.matrixmemory[(int)tempvar1] != currentcode.matrixmemory[(int)tempvar2]);
if(tempvar1type == MEMTYPECONSTANTS.TEMPREFERENCE)FreeMatrixMemory((int)tempvar1);
if(tempvar2type == MEMTYPECONSTANTS.TEMPREFERENCE)FreeMatrixMemory((int)tempvar2);
}
else
throw new Exception("Type mismatch");
}
private void ASM_IsGreaterThan(ref ProgramThread currentthread)
{
double tempvar1,tempvar2;
MEMTYPECONSTANTS tempvar1type,tempvar2type;
tempvar1 = currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.DATA];
tempvar1type =(MEMTYPECONSTANTS)currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.TYPE];
currentthread.stackpointer--;
tempvar2 = currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.DATA];
tempvar2type =(MEMTYPECONSTANTS)currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.TYPE];
currentthread.stackpointer--;
if(tempvar1type==MEMTYPECONSTANTS.VALUE && tempvar2type==MEMTYPECONSTANTS.VALUE)
currentthread.cmpflag = (tempvar1 > tempvar2);
else
throw new Exception("Type mismatch");
}
private void ASM_IsLessThan(ref ProgramThread currentthread)
{
double tempvar1,tempvar2;
MEMTYPECONSTANTS tempvar1type,tempvar2type;
tempvar1 = currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.DATA];
tempvar1type =(MEMTYPECONSTANTS)currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.TYPE];
currentthread.stackpointer--;
tempvar2 = currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.DATA];
tempvar2type =(MEMTYPECONSTANTS)currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.TYPE];
currentthread.stackpointer--;
if(tempvar1type==MEMTYPECONSTANTS.VALUE && tempvar2type==MEMTYPECONSTANTS.VALUE)
currentthread.cmpflag = (tempvar1 < tempvar2);
else
throw new Exception("Type mismatch");
}
private void ASM_IsGreaterThanEqual(ref ProgramThread currentthread)
{
double tempvar1,tempvar2;
MEMTYPECONSTANTS tempvar1type,tempvar2type;
tempvar1 = currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.DATA];
tempvar1type =(MEMTYPECONSTANTS)currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.TYPE];
currentthread.stackpointer--;
tempvar2 = currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.DATA];
tempvar2type =(MEMTYPECONSTANTS)currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.TYPE];
currentthread.stackpointer--;
if(tempvar1type==MEMTYPECONSTANTS.VALUE && tempvar2type==MEMTYPECONSTANTS.VALUE)
currentthread.cmpflag = (tempvar1 >= tempvar2);
else
throw new Exception("Type mismatch");
}
private void ASM_IsLessThanEqual(ref ProgramThread currentthread)
{
double tempvar1,tempvar2;
MEMTYPECONSTANTS tempvar1type,tempvar2type;
tempvar1 = currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.DATA];
tempvar1type =(MEMTYPECONSTANTS)currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.TYPE];
currentthread.stackpointer--;
tempvar2 = currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.DATA];
tempvar2type =(MEMTYPECONSTANTS)currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.TYPE];
currentthread.stackpointer--;
if(tempvar1type==MEMTYPECONSTANTS.VALUE && tempvar2type==MEMTYPECONSTANTS.VALUE)
currentthread.cmpflag = (tempvar1 <= tempvar2);
else
throw new Exception("Type mismatch");
}
private void ASM_StoreExtra(ref ProgramThread currentthread)
{
if(currentthread.cmpflag)
{
//PushStack(ref currentthread,1,MEMTYPECONSTANTS.VALUE);
//PushStack Start
currentthread.stackpointer++;
currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.DATA] =1;
currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.TYPE] =(double)MEMTYPECONSTANTS.VALUE;
//PushStack End
}
else
{
//PushStack(ref currentthread,0,MEMTYPECONSTANTS.VALUE);
//PushStack Start
currentthread.stackpointer++;
currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.DATA] =0;
currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.TYPE] =(double)MEMTYPECONSTANTS.VALUE;
//PushStack End
}
}
private void ASM_LogicalAnd(ref ProgramThread currentthread)
{
bool extraflag;
if(currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.DATA]==1)
extraflag = true;
else
extraflag = false;
currentthread.stackpointer--;
currentthread.cmpflag = (currentthread.cmpflag && extraflag);
}
private void ASM_LogicalOR(ref ProgramThread currentthread)
{
bool extraflag;
if(currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.DATA]==1)
extraflag = true;
else
extraflag = false;
currentthread.stackpointer--;
currentthread.cmpflag = (currentthread.cmpflag || extraflag);
}
private void ASM_LogicalNot(ref ProgramThread currentthread)
{
currentthread.cmpflag = !(currentthread.cmpflag);
}
private void ASM_Transpose(ref ProgramThread currentthread)
{
double tempvar1;
MEMTYPECONSTANTS tempvar1type;
tempvar1 = currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.DATA];
tempvar1type =(MEMTYPECONSTANTS)currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.TYPE];
currentthread.stackpointer--;
if(tempvar1type == MEMTYPECONSTANTS.REFERENCE)
{
GetMatrix((int)tempvar1);
tempvar1 = PlaceMatrix(currentcode.matrixmemory[(int)tempvar1].ReturnTranspose());
tempvar1type = MEMTYPECONSTANTS.TEMPREFERENCE;
}
else if(tempvar1type == MEMTYPECONSTANTS.TEMPREFERENCE )
{
GetMatrix((int)tempvar1);
currentcode.matrixmemory[(int)tempvar1].Transpose();
MatrixStateModified((int)tempvar1);
}
else
throw new Exception("Type mismatch");
//PushStack(ref currentthread,tempvar1,tempvar1type);
//PushStack Start
currentthread.stackpointer++;
currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.DATA] =tempvar1;
currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.TYPE] =(double)tempvar1type;
//PushStack End
}
private void ASM_Adjoint(ref ProgramThread currentthread)
{
double tempvar1;
MEMTYPECONSTANTS tempvar1type;
tempvar1 = currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.DATA];
tempvar1type =(MEMTYPECONSTANTS)currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.TYPE];
currentthread.stackpointer--;
if(tempvar1type == MEMTYPECONSTANTS.REFERENCE)
{
GetMatrix((int)tempvar1);
tempvar1 = PlaceMatrix(currentcode.matrixmemory[(int)tempvar1].ReturnAdjoint());
tempvar1type = MEMTYPECONSTANTS.TEMPREFERENCE;
}
else if(tempvar1type == MEMTYPECONSTANTS.TEMPREFERENCE )
{
GetMatrix((int)tempvar1);
currentcode.matrixmemory[(int)tempvar1]=currentcode.matrixmemory[(int)tempvar1].ReturnAdjoint();
MatrixStateModified((int)tempvar1);
}
else
throw new Exception("Type mismatch");
//PushStack(ref currentthread,tempvar1,tempvar1type);
//PushStack Start
currentthread.stackpointer++;
currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.DATA] =tempvar1;
currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.TYPE] =(double)tempvar1type;
//PushStack End
}
private void ASM_Cos(ref ProgramThread currentthread)
{
double tempvar1;
MEMTYPECONSTANTS tempvar1type;
tempvar1 = currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.DATA];
tempvar1type =(MEMTYPECONSTANTS)currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.TYPE];
currentthread.stackpointer--;
if(tempvar1type == MEMTYPECONSTANTS.REFERENCE)
{
GetMatrix((int)tempvar1);
tempvar1 = PlaceMatrix(currentcode.matrixmemory[(int)tempvar1].ReturnCos());
tempvar1type = MEMTYPECONSTANTS.TEMPREFERENCE;
}
else if(tempvar1type == MEMTYPECONSTANTS.TEMPREFERENCE )
{
currentcode.matrixmemory[(int)tempvar1].Cos();
MatrixStateModified((int)tempvar1);
}
else if(tempvar1type == MEMTYPECONSTANTS.VALUE )
{
tempvar1 = Math.Cos(tempvar1);
}
else
throw new Exception("Type mismatch");
//PushStack(ref currentthread,tempvar1,tempvar1type);
//PushStack Start
currentthread.stackpointer++;
currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.DATA] =tempvar1;
currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.TYPE] =(double)tempvar1type;
//PushStack End
}
private void ASM_Sin(ref ProgramThread currentthread)
{
double tempvar1;
MEMTYPECONSTANTS tempvar1type;
tempvar1 = currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.DATA];
tempvar1type =(MEMTYPECONSTANTS)currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.TYPE];
currentthread.stackpointer--;
if(tempvar1type == MEMTYPECONSTANTS.REFERENCE)
{
GetMatrix((int)tempvar1);
tempvar1 = PlaceMatrix(currentcode.matrixmemory[(int)tempvar1].ReturnSin());
tempvar1type = MEMTYPECONSTANTS.TEMPREFERENCE;
}
else if(tempvar1type == MEMTYPECONSTANTS.TEMPREFERENCE )
{
currentcode.matrixmemory[(int)tempvar1].Sin();
MatrixStateModified((int)tempvar1);
}
else if(tempvar1type == MEMTYPECONSTANTS.VALUE )
{
tempvar1 = Math.Sin(tempvar1);
}
else
throw new Exception("Type mismatch");
//PushStack(ref currentthread,tempvar1,tempvar1type);
//PushStack Start
currentthread.stackpointer++;
currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.DATA] =tempvar1;
currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.TYPE] =(double)tempvar1type;
//PushStack End
}
private void ASM_Tan(ref ProgramThread currentthread)
{
double tempvar1;
MEMTYPECONSTANTS tempvar1type;
tempvar1 = currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.DATA];
tempvar1type =(MEMTYPECONSTANTS)currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.TYPE];
currentthread.stackpointer--;
if(tempvar1type == MEMTYPECONSTANTS.REFERENCE)
{
GetMatrix((int)tempvar1);
tempvar1 = PlaceMatrix(currentcode.matrixmemory[(int)tempvar1].ReturnTan());
tempvar1type = MEMTYPECONSTANTS.TEMPREFERENCE;
}
else if(tempvar1type == MEMTYPECONSTANTS.TEMPREFERENCE )
{
currentcode.matrixmemory[(int)tempvar1].Tan();
MatrixStateModified((int)tempvar1);
}
else if(tempvar1type == MEMTYPECONSTANTS.VALUE )
{
tempvar1 = Math.Tan(tempvar1);
}
else
throw new Exception("Type mismatch");
//PushStack(ref currentthread,tempvar1,tempvar1type);
//PushStack Start
currentthread.stackpointer++;
currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.DATA] =tempvar1;
currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.TYPE] =(double)tempvar1type;
//PushStack End
}
private void ASM_ArcCos(ref ProgramThread currentthread)
{
double tempvar1;
MEMTYPECONSTANTS tempvar1type;
tempvar1 = currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.DATA];
tempvar1type =(MEMTYPECONSTANTS)currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.TYPE];
currentthread.stackpointer--;
if(tempvar1type == MEMTYPECONSTANTS.REFERENCE)
{
GetMatrix((int)tempvar1);
tempvar1 = PlaceMatrix(currentcode.matrixmemory[(int)tempvar1].ReturnArcCos());
tempvar1type = MEMTYPECONSTANTS.TEMPREFERENCE;
}
else if(tempvar1type == MEMTYPECONSTANTS.TEMPREFERENCE )
{
currentcode.matrixmemory[(int)tempvar1].ArcCos();
MatrixStateModified((int)tempvar1);
}
else if(tempvar1type == MEMTYPECONSTANTS.VALUE )
{
tempvar1 = Math.Acos(tempvar1);
}
else
throw new Exception("Type mismatch");
//PushStack(ref currentthread,tempvar1,tempvar1type);
//PushStack Start
currentthread.stackpointer++;
currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.DATA] =tempvar1;
currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.TYPE] =(double)tempvar1type;
//PushStack End
}
private void ASM_ArcSin(ref ProgramThread currentthread)
{
double tempvar1;
MEMTYPECONSTANTS tempvar1type;
tempvar1 = currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.DATA];
tempvar1type =(MEMTYPECONSTANTS)currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.TYPE];
currentthread.stackpointer--;
if(tempvar1type == MEMTYPECONSTANTS.REFERENCE)
{
GetMatrix((int)tempvar1);
tempvar1 = PlaceMatrix(currentcode.matrixmemory[(int)tempvar1].ReturnArcSin());
tempvar1type = MEMTYPECONSTANTS.TEMPREFERENCE;
}
else if(tempvar1type == MEMTYPECONSTANTS.TEMPREFERENCE )
{
currentcode.matrixmemory[(int)tempvar1].ArcSin();
MatrixStateModified((int)tempvar1);
}
else if(tempvar1type == MEMTYPECONSTANTS.VALUE )
{
tempvar1 = Math.Asin(tempvar1);
}
else
throw new Exception("Type mismatch");
//PushStack(ref currentthread,tempvar1,tempvar1type);
//PushStack Start
currentthread.stackpointer++;
currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.DATA] =tempvar1;
currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.TYPE] =(double)tempvar1type;
//PushStack End
}
private void ASM_ArcTan(ref ProgramThread currentthread)
{
double tempvar1;
MEMTYPECONSTANTS tempvar1type;
tempvar1 = currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.DATA];
tempvar1type =(MEMTYPECONSTANTS)currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.TYPE];
currentthread.stackpointer--;
if(tempvar1type == MEMTYPECONSTANTS.REFERENCE)
{
GetMatrix((int)tempvar1);
tempvar1 = PlaceMatrix(currentcode.matrixmemory[(int)tempvar1].ReturnArcTan());
tempvar1type = MEMTYPECONSTANTS.TEMPREFERENCE;
}
else if(tempvar1type == MEMTYPECONSTANTS.TEMPREFERENCE )
{
currentcode.matrixmemory[(int)tempvar1].ArcTan();
MatrixStateModified((int)tempvar1);
}
else if(tempvar1type == MEMTYPECONSTANTS.VALUE )
{
tempvar1 = Math.Atan(tempvar1);
}
else
throw new Exception("Type mismatch");
//PushStack(ref currentthread,tempvar1,tempvar1type);
//PushStack Start
currentthread.stackpointer++;
currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.DATA] =tempvar1;
currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.TYPE] =(double)tempvar1type;
//PushStack End
}
private void ASM_Sqrt(ref ProgramThread currentthread)
{
double tempvar1;
MEMTYPECONSTANTS tempvar1type;
tempvar1 = currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.DATA];
tempvar1type =(MEMTYPECONSTANTS)currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.TYPE];
currentthread.stackpointer--;
if(tempvar1type == MEMTYPECONSTANTS.REFERENCE)
{
GetMatrix((int)tempvar1);
tempvar1 = PlaceMatrix(currentcode.matrixmemory[(int)tempvar1].ReturnSquareRoot());
tempvar1type = MEMTYPECONSTANTS.TEMPREFERENCE;
}
else if(tempvar1type == MEMTYPECONSTANTS.TEMPREFERENCE )
{
GetMatrix((int)tempvar1);
currentcode.matrixmemory[(int)tempvar1].SquareRoot();
}
else if(tempvar1type == MEMTYPECONSTANTS.VALUE )
{
tempvar1 = Math.Sqrt(tempvar1);
}
else
throw new Exception("Type mismatch");
//PushStack(ref currentthread,tempvar1,tempvar1type);
//PushStack Start
currentthread.stackpointer++;
currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.DATA] =tempvar1;
currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.TYPE] =(double)tempvar1type;
//PushStack End
}
private void ASM_NewIdentityMatrix(ref ProgramThread currentthread)
{
double tempvar1;
MEMTYPECONSTANTS tempvar1type;
tempvar1 = currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.DATA];
tempvar1type =(MEMTYPECONSTANTS)currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.TYPE];
currentthread.stackpointer--;
if(tempvar1type == MEMTYPECONSTANTS.VALUE)
{
tempvar1 = PlaceMatrix(Matrix.NewIdentityMatrix((int)tempvar1));
tempvar1type = MEMTYPECONSTANTS.TEMPREFERENCE;
}
else
throw new Exception("Type mismatch");
//PushStack(ref currentthread,tempvar1,tempvar1type);
//PushStack Start
currentthread.stackpointer++;
currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.DATA] =tempvar1;
currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.TYPE] =(double)tempvar1type;
//PushStack End
}
private void ASM_WaitForDevice(ref ProgramThread currentthread)
{
int tempvar1;
MEMTYPECONSTANTS tempvar1type;
tempvar1 = (int)currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.DATA];
tempvar1type =(MEMTYPECONSTANTS)currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.TYPE];
currentthread.stackpointer--;
if(tempvar1type != MEMTYPECONSTANTS.VALUE)
throw new Exception("Type mismatch");
//PushStack Start
currentthread.stackpointer++;
try
{
currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.DATA] =
currentcode.bus.ExternalDevices[tempvar1].WaitForDevice();
}
catch(Exception e)
{
currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.DATA] =-1;
}
currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.TYPE] =(double)MEMTYPECONSTANTS.VALUE;
//PushStack End
}
private void ASM_GetMatrixFromDevice(ref ProgramThread currentthread)
{
int tempvar1;
MEMTYPECONSTANTS tempvar1type;
tempvar1 = (int)currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.DATA];
tempvar1type =(MEMTYPECONSTANTS)currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.TYPE];
currentthread.stackpointer--;
if(tempvar1type != MEMTYPECONSTANTS.VALUE)
throw new Exception("Type mismatch");
currentthread.stackpointer++;
try
{
if(currentcode.bus.ExternalDevices[tempvar1].IsConnected)
{
Matrix tempmat = currentcode.bus.ExternalDevices
[tempvar1].GetMatrix();
if(Object.ReferenceEquals(tempmat,null))
{
currentthread.pstack[currentthread.stackpointer,
(int)MEMCONSTANTS.DATA] =0;
currentthread.pstack[currentthread.stackpointer,
(int)MEMCONSTANTS.TYPE] =(double)MEMTYPECONSTANTS.VALUE;
}
else
{
currentthread.pstack[currentthread.stackpointer,
(int)MEMCONSTANTS.DATA] = PlaceMatrix(tempmat);
currentthread.pstack[currentthread.stackpointer,
(int)MEMCONSTANTS.TYPE] =(double)MEMTYPECONSTANTS.TEMPREFERENCE;
}
}
else
{
currentthread.pstack[currentthread.stackpointer,
(int)MEMCONSTANTS.DATA] =-2;
currentthread.pstack[currentthread.stackpointer,
(int)MEMCONSTANTS.TYPE] =(double)MEMTYPECONSTANTS.VALUE;
}
}
catch(Exception e)
{
currentthread.pstack[currentthread.stackpointer,
(int)MEMCONSTANTS.DATA] =-1;
currentthread.pstack[currentthread.stackpointer,
(int)MEMCONSTANTS.TYPE] =(double)MEMTYPECONSTANTS.VALUE;
}
}
private void ASM_SetMatrixToDevice(ref ProgramThread currentthread)
{
int tempvar1,tempvar2;
MEMTYPECONSTANTS tempvar1type,tempvar2type;
tempvar1 = (int)currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.DATA];
tempvar1type =(MEMTYPECONSTANTS)currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.TYPE];
currentthread.stackpointer--;
tempvar2 = (int)currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.DATA];
tempvar2type =(MEMTYPECONSTANTS)currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.TYPE];
currentthread.stackpointer--;
if(tempvar1type != MEMTYPECONSTANTS.VALUE || (tempvar2type !=
MEMTYPECONSTANTS.REFERENCE && tempvar2type !=
MEMTYPECONSTANTS.TEMPREFERENCE))
throw new Exception("Type mismatch");
currentthread.stackpointer++;
try
{
if(currentcode.bus.ExternalDevices[tempvar1].IsConnected)
{
GetMatrix(tempvar2);
currentcode.bus.ExternalDevices[tempvar1].PutMatrix(
currentcode.matrixmemory[tempvar2]);
currentthread.pstack[currentthread.stackpointer,
(int)MEMCONSTANTS.DATA] = 1;
currentthread.pstack[currentthread.stackpointer,
(int)MEMCONSTANTS.TYPE] =(double)MEMTYPECONSTANTS.VALUE;
}
else
{
currentthread.pstack[currentthread.stackpointer,
(int)MEMCONSTANTS.DATA] =-2;
currentthread.pstack[currentthread.stackpointer,
(int)MEMCONSTANTS.TYPE] =(double)MEMTYPECONSTANTS.VALUE;
}
}
catch(Exception e)
{
currentthread.pstack[currentthread.stackpointer,
(int)MEMCONSTANTS.DATA] =-1;
currentthread.pstack[currentthread.stackpointer,
(int)MEMCONSTANTS.TYPE] =(double)MEMTYPECONSTANTS.VALUE;
}
if(tempvar2type == MEMTYPECONSTANTS.TEMPREFERENCE)
FreeMatrixMemory(tempvar2);
}
private void ASM_IsMatrix(ref ProgramThread currentthread)
{
int tempvar1;
MEMTYPECONSTANTS tempvar1type;
tempvar1 = (int)currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.DATA];
tempvar1type =(MEMTYPECONSTANTS)currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.TYPE];
currentthread.stackpointer--;
currentthread.stackpointer++;
if(tempvar1type == MEMTYPECONSTANTS.REFERENCE
|| tempvar1type == MEMTYPECONSTANTS.TEMPREFERENCE)
currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.DATA] =1;
else
currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.DATA] =0;
currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.TYPE] =(double)MEMTYPECONSTANTS.VALUE;
if(tempvar1type == MEMTYPECONSTANTS.TEMPREFERENCE)
FreeMatrixMemory(tempvar1);
}
private void ASM_GetRows(ref ProgramThread currentthread)
{
int tempvar1;
MEMTYPECONSTANTS tempvar1type;
tempvar1 = (int)currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.DATA];
tempvar1type =(MEMTYPECONSTANTS)currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.TYPE];
currentthread.stackpointer--;
if(tempvar1type != MEMTYPECONSTANTS.REFERENCE
&& tempvar1type != MEMTYPECONSTANTS.TEMPREFERENCE)
throw new Exception("Type mismatch");
GetMatrix(tempvar1);
currentthread.stackpointer++;
currentthread.pstack[currentthread.stackpointer,
(int)MEMCONSTANTS.DATA] =currentcode.matrixmemory[tempvar1].Rows;
currentthread.pstack[currentthread.stackpointer,
(int)MEMCONSTANTS.TYPE] =(double)MEMTYPECONSTANTS.VALUE;
if(tempvar1type == MEMTYPECONSTANTS.TEMPREFERENCE)
FreeMatrixMemory(tempvar1);
}
private void ASM_GetColumns(ref ProgramThread currentthread)
{
int tempvar1;
MEMTYPECONSTANTS tempvar1type;
tempvar1 = (int)currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.DATA];
tempvar1type =(MEMTYPECONSTANTS)currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.TYPE];
currentthread.stackpointer--;
if(tempvar1type != MEMTYPECONSTANTS.REFERENCE
&& tempvar1type != MEMTYPECONSTANTS.TEMPREFERENCE)
throw new Exception("Type mismatch");
GetMatrix(tempvar1);
currentthread.stackpointer++;
currentthread.pstack[currentthread.stackpointer,
(int)MEMCONSTANTS.DATA] =currentcode.matrixmemory[tempvar1].Columns;
currentthread.pstack[currentthread.stackpointer,
(int)MEMCONSTANTS.TYPE] =(double)MEMTYPECONSTANTS.VALUE;
if(tempvar1type == MEMTYPECONSTANTS.TEMPREFERENCE)
FreeMatrixMemory(tempvar1);
}
private void ASM_GetPrimes(ref ProgramThread currentthread)
{
int tempvar1;
MEMTYPECONSTANTS tempvar1type;
tempvar1 = (int)currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.DATA];
tempvar1type =(MEMTYPECONSTANTS)currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.TYPE];
currentthread.stackpointer--;
if(tempvar1type != MEMTYPECONSTANTS.VALUE)
throw new Exception("Type mismatch");
if(tempvar1 <= 0)
throw new Exception("Supplied argument cannot be less than or equal to zero.");
long num =1;
Matrix tempmat = new Matrix(1,tempvar1);
for(int lpvar=1;lpvar<=tempvar1;lpvar++)
{
bool primeflag = false;
while(!primeflag)
{
long k=1;
for (int lpvar2=2;lpvar2<=num/2;lpvar2++)
{
k=num%lpvar2;
if(k==0)
break;
}
if(k!=0)
{
tempmat.m_MatArr[0,lpvar-1] = num;
primeflag=true;
}
num++;
}
}
currentthread.stackpointer++;
currentthread.pstack[currentthread.stackpointer,
(int)MEMCONSTANTS.DATA] =PlaceMatrix(tempmat);;
currentthread.pstack[currentthread.stackpointer,
(int)MEMCONSTANTS.TYPE] =(double)MEMTYPECONSTANTS.TEMPREFERENCE;
}
private void ASM_GetPrimesUpto(ref ProgramThread currentthread)
{
int tempvar1;
MEMTYPECONSTANTS tempvar1type;
tempvar1 = (int)currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.DATA];
tempvar1type =(MEMTYPECONSTANTS)currentthread.pstack[currentthread.stackpointer,(int)MEMCONSTANTS.TYPE];
currentthread.stackpointer--;
if(tempvar1type != MEMTYPECONSTANTS.VALUE)
throw new Exception("Type mismatch");
if(tempvar1 <= 0)
throw new Exception("Supplied argument cannot be less than or equal to zero.");
ArrayList templist = new ArrayList();
for(int lpvar=1;lpvar<=tempvar1;lpvar++)
{
long k=1;
for (int lpvar2=2;lpvar2<=lpvar/2;lpvar2++)
{
k=lpvar%lpvar2;
if(k==0)
break;
}
if(k!=0)
templist.Add(lpvar);
}
Matrix tempmat = new Matrix(1,templist.Count);
int lpvar3=0;
foreach(object tmp in templist)
{
tempmat.m_MatArr[0,lpvar3] =long.Parse(tmp.ToString());
lpvar3++;
}
currentthread.stackpointer++;
currentthread.pstack[currentthread.stackpointer,
(int)MEMCONSTANTS.DATA] =PlaceMatrix(tempmat);;
currentthread.pstack[currentthread.stackpointer,
(int)MEMCONSTANTS.TYPE] =(double)MEMTYPECONSTANTS.TEMPREFERENCE;
}
/*private void ASM_ParallelStart(ref ProgramThread currentthread)
{
currentthread.inspointer++;
currentthread.inspointer = (int)currentcode.numconstants[
currentcode.instructions[currentthread.inspointer]];
WrappedThreadObject tempthread = new WrappedThreadObject(this);
ArrayList threads= new ArrayList();
while(currentcode.instructions[currentthread.inspointer]==(ushort)ASMPROCESSOR_OPERATIONS.CREATETHREAD)
{
currentthread.inspointer++;
tempthread.mthread.inspointer = (int)currentcode.numconstants[
currentcode.instructions[currentthread.inspointer]];
currentthread.inspointer++;
tempthread.mthread.endthread = (int)currentcode.numconstants[
currentcode.instructions[currentthread.inspointer]];
currentthread.inspointer++;
threads.Add(tempthread);
tempthread.Start();
tempthread = new WrappedThreadObject(this);
}
foreach(WrappedThreadObject temp in threads)
temp.thread.Join();
//threads = null;
}*/
private void ASM_ParallelStart(ref ProgramThread currentthread)
{
currentthread.inspointer++;
int paralleloffset= currentthread.inspointer;
currentthread.inspointer += (int)currentcode.numconstants[
currentcode.instructions[currentthread.inspointer]];
WrappedThreadObjectRS tempthread = new WrappedThreadObjectRS(this);
ArrayList threads= new ArrayList();
while(currentcode.instructions[currentthread.inspointer]==(ushort)ASMPROCESSOR_OPERATIONS.CREATETHREAD)
{
currentthread.inspointer++;
tempthread.mthread.inspointer =paralleloffset + (int)currentcode.numconstants[
currentcode.instructions[currentthread.inspointer]];
currentthread.inspointer++;
tempthread.mthread.endthread =paralleloffset + (int)currentcode.numconstants[
currentcode.instructions[currentthread.inspointer]];
currentthread.inspointer++;
currentthread.inspointer += (currentcode.instructions[currentthread.inspointer]+1);
threads.Add(tempthread);
tempthread.Start();
tempthread = new WrappedThreadObjectRS(this);
}
foreach(WrappedThreadObjectRS temp in threads)
temp.thread.Join();
//threads = null;
}
}
public class WrappedThreadObjectRS
{
public ProgramThread mthread;
ASMProcessorRS threadprocessor;
public Thread thread;
public WrappedThreadObjectRS(ASMProcessorRS threadprocessor)
{
this.mthread = new ProgramThread();
this.mthread.pstack = new double[RemoteMachine.threadstacksize,2];
this.mthread.stackpointer = -1;
this.threadprocessor = threadprocessor;
}
public void Start()
{
thread = new Thread(new ThreadStart(this.ThreadProc));
thread.Start();
}
public void ThreadProc()
{
try
{
threadprocessor.Process(ref mthread);
}
catch(Exception ee)
{
//System.Windows.Forms.MessageBox.Show("Thread - " + mthread.inspointer
// + " -> " + mthread.endthread + " :" + ee.Message);
//Console.WriteLine("Thread - " + mthread.inspointer
// + " -> " + mthread.endthread + " :" + ee.Message);
threadprocessor.raiseerror(ee.Message);
}
}
}
}
| |
/// This code was generated by
/// \ / _ _ _| _ _
/// | (_)\/(_)(_|\/| |(/_ v1.0.0
/// / /
using NSubstitute;
using NSubstitute.ExceptionExtensions;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using Twilio.Clients;
using Twilio.Converters;
using Twilio.Exceptions;
using Twilio.Http;
using Twilio.Rest.Preview.DeployedDevices.Fleet;
namespace Twilio.Tests.Rest.Preview.DeployedDevices.Fleet
{
[TestFixture]
public class DeploymentTest : TwilioTest
{
[Test]
public void TestFetchRequest()
{
var twilioRestClient = Substitute.For<ITwilioRestClient>();
var request = new Request(
HttpMethod.Get,
Twilio.Rest.Domain.Preview,
"/DeployedDevices/Fleets/FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Deployments/DLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
""
);
twilioRestClient.Request(request).Throws(new ApiException("Server Error, no content"));
try
{
DeploymentResource.Fetch("FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", "DLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", client: twilioRestClient);
Assert.Fail("Expected TwilioException to be thrown for 500");
}
catch (ApiException) {}
twilioRestClient.Received().Request(request);
}
[Test]
public void TestFetchResponse()
{
var twilioRestClient = Substitute.For<ITwilioRestClient>();
twilioRestClient.AccountSid.Returns("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
twilioRestClient.Request(Arg.Any<Request>())
.Returns(new Response(
System.Net.HttpStatusCode.OK,
"{\"sid\": \"DLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"friendly_name\": \"friendly_name\",\"account_sid\": \"ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"fleet_sid\": \"FLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"sync_service_sid\": \"ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"date_created\": \"2016-07-30T20:00:00Z\",\"date_updated\": \"2016-07-30T20:00:00Z\",\"url\": \"https://preview.twilio.com/DeployedDevices/Fleets/FLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Deployments/DLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"}"
));
var response = DeploymentResource.Fetch("FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", "DLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", client: twilioRestClient);
Assert.NotNull(response);
}
[Test]
public void TestDeleteRequest()
{
var twilioRestClient = Substitute.For<ITwilioRestClient>();
var request = new Request(
HttpMethod.Delete,
Twilio.Rest.Domain.Preview,
"/DeployedDevices/Fleets/FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Deployments/DLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
""
);
twilioRestClient.Request(request).Throws(new ApiException("Server Error, no content"));
try
{
DeploymentResource.Delete("FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", "DLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", client: twilioRestClient);
Assert.Fail("Expected TwilioException to be thrown for 500");
}
catch (ApiException) {}
twilioRestClient.Received().Request(request);
}
[Test]
public void TestDeleteResponse()
{
var twilioRestClient = Substitute.For<ITwilioRestClient>();
twilioRestClient.AccountSid.Returns("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
twilioRestClient.Request(Arg.Any<Request>())
.Returns(new Response(
System.Net.HttpStatusCode.NoContent,
"null"
));
var response = DeploymentResource.Delete("FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", "DLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", client: twilioRestClient);
Assert.NotNull(response);
}
[Test]
public void TestCreateRequest()
{
var twilioRestClient = Substitute.For<ITwilioRestClient>();
var request = new Request(
HttpMethod.Post,
Twilio.Rest.Domain.Preview,
"/DeployedDevices/Fleets/FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Deployments",
""
);
twilioRestClient.Request(request).Throws(new ApiException("Server Error, no content"));
try
{
DeploymentResource.Create("FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", client: twilioRestClient);
Assert.Fail("Expected TwilioException to be thrown for 500");
}
catch (ApiException) {}
twilioRestClient.Received().Request(request);
}
[Test]
public void TestCreateResponse()
{
var twilioRestClient = Substitute.For<ITwilioRestClient>();
twilioRestClient.AccountSid.Returns("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
twilioRestClient.Request(Arg.Any<Request>())
.Returns(new Response(
System.Net.HttpStatusCode.Created,
"{\"sid\": \"DLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"friendly_name\": \"friendly_name\",\"account_sid\": \"ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"fleet_sid\": \"FLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"sync_service_sid\": \"ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"date_created\": \"2016-07-30T20:00:00Z\",\"date_updated\": \"2016-07-30T20:00:00Z\",\"url\": \"https://preview.twilio.com/DeployedDevices/Fleets/FLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Deployments/DLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"}"
));
var response = DeploymentResource.Create("FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", client: twilioRestClient);
Assert.NotNull(response);
}
[Test]
public void TestReadRequest()
{
var twilioRestClient = Substitute.For<ITwilioRestClient>();
var request = new Request(
HttpMethod.Get,
Twilio.Rest.Domain.Preview,
"/DeployedDevices/Fleets/FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Deployments",
""
);
twilioRestClient.Request(request).Throws(new ApiException("Server Error, no content"));
try
{
DeploymentResource.Read("FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", client: twilioRestClient);
Assert.Fail("Expected TwilioException to be thrown for 500");
}
catch (ApiException) {}
twilioRestClient.Received().Request(request);
}
[Test]
public void TestReadEmptyResponse()
{
var twilioRestClient = Substitute.For<ITwilioRestClient>();
twilioRestClient.AccountSid.Returns("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
twilioRestClient.Request(Arg.Any<Request>())
.Returns(new Response(
System.Net.HttpStatusCode.OK,
"{\"deployments\": [],\"meta\": {\"first_page_url\": \"https://preview.twilio.com/DeployedDevices/Fleets/FLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Deployments?PageSize=50&Page=0\",\"key\": \"deployments\",\"next_page_url\": null,\"page\": 0,\"page_size\": 50,\"previous_page_url\": null,\"url\": \"https://preview.twilio.com/DeployedDevices/Fleets/FLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Deployments?PageSize=50&Page=0\"}}"
));
var response = DeploymentResource.Read("FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", client: twilioRestClient);
Assert.NotNull(response);
}
[Test]
public void TestReadFullResponse()
{
var twilioRestClient = Substitute.For<ITwilioRestClient>();
twilioRestClient.AccountSid.Returns("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
twilioRestClient.Request(Arg.Any<Request>())
.Returns(new Response(
System.Net.HttpStatusCode.OK,
"{\"deployments\": [{\"sid\": \"DLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"friendly_name\": \"friendly_name\",\"account_sid\": \"ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"fleet_sid\": \"FLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"sync_service_sid\": \"ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"date_created\": \"2016-07-30T20:00:00Z\",\"date_updated\": \"2016-07-30T20:00:00Z\",\"url\": \"https://preview.twilio.com/DeployedDevices/Fleets/FLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Deployments/DLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"}],\"meta\": {\"first_page_url\": \"https://preview.twilio.com/DeployedDevices/Fleets/FLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Deployments?PageSize=50&Page=0\",\"key\": \"deployments\",\"next_page_url\": null,\"page\": 0,\"page_size\": 50,\"previous_page_url\": null,\"url\": \"https://preview.twilio.com/DeployedDevices/Fleets/FLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Deployments?PageSize=50&Page=0\"}}"
));
var response = DeploymentResource.Read("FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", client: twilioRestClient);
Assert.NotNull(response);
}
[Test]
public void TestUpdateRequest()
{
var twilioRestClient = Substitute.For<ITwilioRestClient>();
var request = new Request(
HttpMethod.Post,
Twilio.Rest.Domain.Preview,
"/DeployedDevices/Fleets/FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Deployments/DLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
""
);
twilioRestClient.Request(request).Throws(new ApiException("Server Error, no content"));
try
{
DeploymentResource.Update("FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", "DLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", client: twilioRestClient);
Assert.Fail("Expected TwilioException to be thrown for 500");
}
catch (ApiException) {}
twilioRestClient.Received().Request(request);
}
[Test]
public void TestUpdateResponse()
{
var twilioRestClient = Substitute.For<ITwilioRestClient>();
twilioRestClient.AccountSid.Returns("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
twilioRestClient.Request(Arg.Any<Request>())
.Returns(new Response(
System.Net.HttpStatusCode.OK,
"{\"sid\": \"DLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"friendly_name\": \"friendly_name\",\"account_sid\": \"ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"fleet_sid\": \"FLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"sync_service_sid\": \"ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"date_created\": \"2016-07-30T20:00:00Z\",\"date_updated\": \"2016-07-30T20:00:00Z\",\"url\": \"https://preview.twilio.com/DeployedDevices/Fleets/FLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Deployments/DLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"}"
));
var response = DeploymentResource.Update("FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", "DLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", client: twilioRestClient);
Assert.NotNull(response);
}
}
}
| |
/*
* 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 System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using log4net;
using log4net.Appender;
using log4net.Core;
using log4net.Repository;
using Nini.Config;
using OpenSim.Framework.Console;
using OpenSim.Framework.Monitoring;
namespace OpenSim.Framework.Servers
{
public class ServerBase
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public IConfigSource Config { get; protected set; }
/// <summary>
/// Console to be used for any command line output. Can be null, in which case there should be no output.
/// </summary>
protected ICommandConsole m_console;
protected OpenSimAppender m_consoleAppender;
protected FileAppender m_logFileAppender;
protected DateTime m_startuptime;
protected string m_startupDirectory = Environment.CurrentDirectory;
protected string m_pidFile = String.Empty;
protected ServerStatsCollector m_serverStatsCollector;
/// <summary>
/// Server version information. Usually VersionInfo + information about git commit, operating system, etc.
/// </summary>
protected string m_version;
public ServerBase()
{
m_startuptime = DateTime.Now;
m_version = VersionInfo.Version;
EnhanceVersionInformation();
}
protected void CreatePIDFile(string path)
{
if (File.Exists(path))
m_log.ErrorFormat(
"[SERVER BASE]: Previous pid file {0} still exists on startup. Possibly previously unclean shutdown.",
path);
try
{
string pidstring = System.Diagnostics.Process.GetCurrentProcess().Id.ToString();
using (FileStream fs = File.Create(path))
{
Byte[] buf = Encoding.ASCII.GetBytes(pidstring);
fs.Write(buf, 0, buf.Length);
}
m_pidFile = path;
m_log.InfoFormat("[SERVER BASE]: Created pid file {0}", m_pidFile);
}
catch (Exception e)
{
m_log.Warn(string.Format("[SERVER BASE]: Could not create PID file at {0} ", path), e);
}
}
protected void RemovePIDFile()
{
if (m_pidFile != String.Empty)
{
try
{
File.Delete(m_pidFile);
}
catch (Exception e)
{
m_log.Error(string.Format("[SERVER BASE]: Error whilst removing {0} ", m_pidFile), e);
}
m_pidFile = String.Empty;
}
}
/// <summary>
/// Log information about the circumstances in which we're running (OpenSimulator version number, CLR details,
/// etc.).
/// </summary>
public void LogEnvironmentInformation()
{
// FIXME: This should be done down in ServerBase but we need to sort out and refactor the log4net
// XmlConfigurator calls first accross servers.
m_log.InfoFormat("[SERVER BASE]: Starting in {0}", m_startupDirectory);
m_log.InfoFormat("[SERVER BASE]: OpenSimulator version: {0}", m_version);
// clr version potentially is more confusing than helpful, since it doesn't tell us if we're running under Mono/MS .NET and
// the clr version number doesn't match the project version number under Mono.
//m_log.Info("[STARTUP]: Virtual machine runtime version: " + Environment.Version + Environment.NewLine);
m_log.InfoFormat(
"[SERVER BASE]: Operating system version: {0}, .NET platform {1}, {2}-bit",
Environment.OSVersion, Environment.OSVersion.Platform, Util.Is64BitProcess() ? "64" : "32");
}
public void RegisterCommonAppenders(IConfig startupConfig)
{
ILoggerRepository repository = LogManager.GetRepository();
IAppender[] appenders = repository.GetAppenders();
foreach (IAppender appender in appenders)
{
if (appender.Name == "Console")
{
m_consoleAppender = (OpenSimAppender)appender;
}
else if (appender.Name == "LogFileAppender")
{
m_logFileAppender = (FileAppender)appender;
}
}
if (null == m_consoleAppender)
{
Notice("No appender named Console found (see the log4net config file for this executable)!");
}
else
{
// FIXME: This should be done through an interface rather than casting.
m_consoleAppender.Console = (ConsoleBase)m_console;
// If there is no threshold set then the threshold is effectively everything.
if (null == m_consoleAppender.Threshold)
m_consoleAppender.Threshold = Level.All;
Notice(String.Format("Console log level is {0}", m_consoleAppender.Threshold));
}
if (m_logFileAppender != null && startupConfig != null)
{
string cfgFileName = startupConfig.GetString("LogFile", null);
if (cfgFileName != null)
{
m_logFileAppender.File = cfgFileName;
m_logFileAppender.ActivateOptions();
}
m_log.InfoFormat("[SERVER BASE]: Logging started to file {0}", m_logFileAppender.File);
}
}
/// <summary>
/// Register common commands once m_console has been set if it is going to be set
/// </summary>
public void RegisterCommonCommands()
{
if (m_console == null)
return;
m_console.Commands.AddCommand(
"General", false, "show info", "show info", "Show general information about the server", HandleShow);
m_console.Commands.AddCommand(
"General", false, "show version", "show version", "Show server version", HandleShow);
m_console.Commands.AddCommand(
"General", false, "show uptime", "show uptime", "Show server uptime", HandleShow);
m_console.Commands.AddCommand(
"General", false, "get log level", "get log level", "Get the current console logging level",
(mod, cmd) => ShowLogLevel());
m_console.Commands.AddCommand(
"General", false, "set log level", "set log level <level>",
"Set the console logging level for this session.", HandleSetLogLevel);
m_console.Commands.AddCommand(
"General", false, "config set",
"config set <section> <key> <value>",
"Set a config option. In most cases this is not useful since changed parameters are not dynamically reloaded. Neither do changed parameters persist - you will have to change a config file manually and restart.", HandleConfig);
m_console.Commands.AddCommand(
"General", false, "config get",
"config get [<section>] [<key>]",
"Synonym for config show",
HandleConfig);
m_console.Commands.AddCommand(
"General", false, "config show",
"config show [<section>] [<key>]",
"Show config information",
"If neither section nor field are specified, then the whole current configuration is printed." + Environment.NewLine
+ "If a section is given but not a field, then all fields in that section are printed.",
HandleConfig);
m_console.Commands.AddCommand(
"General", false, "config save",
"config save <path>",
"Save current configuration to a file at the given path", HandleConfig);
m_console.Commands.AddCommand(
"General", false, "command-script",
"command-script <script>",
"Run a command script from file", HandleScript);
m_console.Commands.AddCommand(
"General", false, "show threads",
"show threads",
"Show thread status", HandleShow);
m_console.Commands.AddCommand(
"Debug", false, "threads abort",
"threads abort <thread-id>",
"Abort a managed thread. Use \"show threads\" to find possible threads.", HandleThreadsAbort);
m_console.Commands.AddCommand(
"General", false, "threads show",
"threads show",
"Show thread status. Synonym for \"show threads\"",
(string module, string[] args) => Notice(GetThreadsReport()));
m_console.Commands.AddCommand (
"Debug", false, "debug comms set",
"debug comms set serialosdreq true|false",
"Set comms parameters. For debug purposes.",
HandleDebugCommsSet);
m_console.Commands.AddCommand (
"Debug", false, "debug comms status",
"debug comms status",
"Show current debug comms parameters.",
HandleDebugCommsStatus);
m_console.Commands.AddCommand (
"Debug", false, "debug threadpool set",
"debug threadpool set worker|iocp min|max <n>",
"Set threadpool parameters. For debug purposes.",
HandleDebugThreadpoolSet);
m_console.Commands.AddCommand (
"Debug", false, "debug threadpool status",
"debug threadpool status",
"Show current debug threadpool parameters.",
HandleDebugThreadpoolStatus);
m_console.Commands.AddCommand(
"Debug", false, "debug threadpool level",
"debug threadpool level 0.." + Util.MAX_THREADPOOL_LEVEL,
"Turn on logging of activity in the main thread pool.",
"Log levels:\n"
+ " 0 = no logging\n"
+ " 1 = only first line of stack trace; don't log common threads\n"
+ " 2 = full stack trace; don't log common threads\n"
+ " 3 = full stack trace, including common threads\n",
HandleDebugThreadpoolLevel);
m_console.Commands.AddCommand(
"Debug", false, "show threadpool calls active",
"show threadpool calls active",
"Show details about threadpool calls that are still active (currently waiting or in progress)",
HandleShowThreadpoolCallsActive);
m_console.Commands.AddCommand(
"Debug", false, "show threadpool calls complete",
"show threadpool calls complete",
"Show details about threadpool calls that have been completed.",
HandleShowThreadpoolCallsComplete);
m_console.Commands.AddCommand(
"Debug", false, "force gc",
"force gc",
"Manually invoke runtime garbage collection. For debugging purposes",
HandleForceGc);
m_console.Commands.AddCommand(
"General", false, "quit",
"quit",
"Quit the application", (mod, args) => Shutdown());
m_console.Commands.AddCommand(
"General", false, "shutdown",
"shutdown",
"Quit the application", (mod, args) => Shutdown());
ChecksManager.RegisterConsoleCommands(m_console);
StatsManager.RegisterConsoleCommands(m_console);
}
public void RegisterCommonComponents(IConfigSource configSource)
{
IConfig networkConfig = configSource.Configs["Network"];
if (networkConfig != null)
{
WebUtil.SerializeOSDRequestsPerEndpoint = networkConfig.GetBoolean("SerializeOSDRequests", false);
}
m_serverStatsCollector = new ServerStatsCollector();
m_serverStatsCollector.Initialise(configSource);
m_serverStatsCollector.Start();
}
private void HandleDebugCommsStatus(string module, string[] args)
{
Notice("serialosdreq is {0}", WebUtil.SerializeOSDRequestsPerEndpoint);
}
private void HandleDebugCommsSet(string module, string[] args)
{
if (args.Length != 5)
{
Notice("Usage: debug comms set serialosdreq true|false");
return;
}
if (args[3] != "serialosdreq")
{
Notice("Usage: debug comms set serialosdreq true|false");
return;
}
bool setSerializeOsdRequests;
if (!ConsoleUtil.TryParseConsoleBool(m_console, args[4], out setSerializeOsdRequests))
return;
WebUtil.SerializeOSDRequestsPerEndpoint = setSerializeOsdRequests;
Notice("serialosdreq is now {0}", setSerializeOsdRequests);
}
private void HandleShowThreadpoolCallsActive(string module, string[] args)
{
List<KeyValuePair<string, int>> calls = Util.GetFireAndForgetCallsInProgress().ToList();
calls.Sort((kvp1, kvp2) => kvp2.Value.CompareTo(kvp1.Value));
int namedCalls = 0;
ConsoleDisplayList cdl = new ConsoleDisplayList();
foreach (KeyValuePair<string, int> kvp in calls)
{
if (kvp.Value > 0)
{
cdl.AddRow(kvp.Key, kvp.Value);
namedCalls += kvp.Value;
}
}
cdl.AddRow("TOTAL NAMED", namedCalls);
long allQueuedCalls = Util.TotalQueuedFireAndForgetCalls;
long allRunningCalls = Util.TotalRunningFireAndForgetCalls;
cdl.AddRow("TOTAL QUEUED", allQueuedCalls);
cdl.AddRow("TOTAL RUNNING", allRunningCalls);
cdl.AddRow("TOTAL ANONYMOUS", allQueuedCalls + allRunningCalls - namedCalls);
cdl.AddRow("TOTAL ALL", allQueuedCalls + allRunningCalls);
MainConsole.Instance.Output(cdl.ToString());
}
private void HandleShowThreadpoolCallsComplete(string module, string[] args)
{
List<KeyValuePair<string, int>> calls = Util.GetFireAndForgetCallsMade().ToList();
calls.Sort((kvp1, kvp2) => kvp2.Value.CompareTo(kvp1.Value));
int namedCallsMade = 0;
ConsoleDisplayList cdl = new ConsoleDisplayList();
foreach (KeyValuePair<string, int> kvp in calls)
{
cdl.AddRow(kvp.Key, kvp.Value);
namedCallsMade += kvp.Value;
}
cdl.AddRow("TOTAL NAMED", namedCallsMade);
long allCallsMade = Util.TotalFireAndForgetCallsMade;
cdl.AddRow("TOTAL ANONYMOUS", allCallsMade - namedCallsMade);
cdl.AddRow("TOTAL ALL", allCallsMade);
MainConsole.Instance.Output(cdl.ToString());
}
private void HandleDebugThreadpoolStatus(string module, string[] args)
{
int workerThreads, iocpThreads;
ThreadPool.GetMinThreads(out workerThreads, out iocpThreads);
Notice("Min worker threads: {0}", workerThreads);
Notice("Min IOCP threads: {0}", iocpThreads);
ThreadPool.GetMaxThreads(out workerThreads, out iocpThreads);
Notice("Max worker threads: {0}", workerThreads);
Notice("Max IOCP threads: {0}", iocpThreads);
ThreadPool.GetAvailableThreads(out workerThreads, out iocpThreads);
Notice("Available worker threads: {0}", workerThreads);
Notice("Available IOCP threads: {0}", iocpThreads);
}
private void HandleDebugThreadpoolSet(string module, string[] args)
{
if (args.Length != 6)
{
Notice("Usage: debug threadpool set worker|iocp min|max <n>");
return;
}
int newThreads;
if (!ConsoleUtil.TryParseConsoleInt(m_console, args[5], out newThreads))
return;
string poolType = args[3];
string bound = args[4];
bool fail = false;
int workerThreads, iocpThreads;
if (poolType == "worker")
{
if (bound == "min")
{
ThreadPool.GetMinThreads(out workerThreads, out iocpThreads);
if (!ThreadPool.SetMinThreads(newThreads, iocpThreads))
fail = true;
}
else
{
ThreadPool.GetMaxThreads(out workerThreads, out iocpThreads);
if (!ThreadPool.SetMaxThreads(newThreads, iocpThreads))
fail = true;
}
}
else
{
if (bound == "min")
{
ThreadPool.GetMinThreads(out workerThreads, out iocpThreads);
if (!ThreadPool.SetMinThreads(workerThreads, newThreads))
fail = true;
}
else
{
ThreadPool.GetMaxThreads(out workerThreads, out iocpThreads);
if (!ThreadPool.SetMaxThreads(workerThreads, newThreads))
fail = true;
}
}
if (fail)
{
Notice("ERROR: Could not set {0} {1} threads to {2}", poolType, bound, newThreads);
}
else
{
int minWorkerThreads, maxWorkerThreads, minIocpThreads, maxIocpThreads;
ThreadPool.GetMinThreads(out minWorkerThreads, out minIocpThreads);
ThreadPool.GetMaxThreads(out maxWorkerThreads, out maxIocpThreads);
Notice("Min worker threads now {0}", minWorkerThreads);
Notice("Min IOCP threads now {0}", minIocpThreads);
Notice("Max worker threads now {0}", maxWorkerThreads);
Notice("Max IOCP threads now {0}", maxIocpThreads);
}
}
private static void HandleDebugThreadpoolLevel(string module, string[] cmdparams)
{
if (cmdparams.Length < 4)
{
MainConsole.Instance.Output("Usage: debug threadpool level 0.." + Util.MAX_THREADPOOL_LEVEL);
return;
}
string rawLevel = cmdparams[3];
int newLevel;
if (!int.TryParse(rawLevel, out newLevel))
{
MainConsole.Instance.OutputFormat("{0} is not a valid debug level", rawLevel);
return;
}
if (newLevel < 0 || newLevel > Util.MAX_THREADPOOL_LEVEL)
{
MainConsole.Instance.OutputFormat("{0} is outside the valid debug level range of 0.." + Util.MAX_THREADPOOL_LEVEL, newLevel);
return;
}
Util.LogThreadPool = newLevel;
MainConsole.Instance.OutputFormat("LogThreadPool set to {0}", newLevel);
}
private void HandleForceGc(string module, string[] args)
{
Notice("Manually invoking runtime garbage collection");
GC.Collect();
}
public virtual void HandleShow(string module, string[] cmd)
{
List<string> args = new List<string>(cmd);
args.RemoveAt(0);
string[] showParams = args.ToArray();
switch (showParams[0])
{
case "info":
ShowInfo();
break;
case "version":
Notice(GetVersionText());
break;
case "uptime":
Notice(GetUptimeReport());
break;
case "threads":
Notice(GetThreadsReport());
break;
}
}
/// <summary>
/// Change and load configuration file data.
/// </summary>
/// <param name="module"></param>
/// <param name="cmd"></param>
private void HandleConfig(string module, string[] cmd)
{
List<string> args = new List<string>(cmd);
args.RemoveAt(0);
string[] cmdparams = args.ToArray();
if (cmdparams.Length > 0)
{
string firstParam = cmdparams[0].ToLower();
switch (firstParam)
{
case "set":
if (cmdparams.Length < 4)
{
Notice("Syntax: config set <section> <key> <value>");
Notice("Example: config set ScriptEngine.DotNetEngine NumberOfScriptThreads 5");
}
else
{
IConfig c;
IConfigSource source = new IniConfigSource();
c = source.AddConfig(cmdparams[1]);
if (c != null)
{
string _value = String.Join(" ", cmdparams, 3, cmdparams.Length - 3);
c.Set(cmdparams[2], _value);
Config.Merge(source);
Notice("In section [{0}], set {1} = {2}", c.Name, cmdparams[2], _value);
}
}
break;
case "get":
case "show":
if (cmdparams.Length == 1)
{
foreach (IConfig config in Config.Configs)
{
Notice("[{0}]", config.Name);
string[] keys = config.GetKeys();
foreach (string key in keys)
Notice(" {0} = {1}", key, config.GetString(key));
}
}
else if (cmdparams.Length == 2 || cmdparams.Length == 3)
{
IConfig config = Config.Configs[cmdparams[1]];
if (config == null)
{
Notice("Section \"{0}\" does not exist.",cmdparams[1]);
break;
}
else
{
if (cmdparams.Length == 2)
{
Notice("[{0}]", config.Name);
foreach (string key in config.GetKeys())
Notice(" {0} = {1}", key, config.GetString(key));
}
else
{
Notice(
"config get {0} {1} : {2}",
cmdparams[1], cmdparams[2], config.GetString(cmdparams[2]));
}
}
}
else
{
Notice("Syntax: config {0} [<section>] [<key>]", firstParam);
Notice("Example: config {0} ScriptEngine.DotNetEngine NumberOfScriptThreads", firstParam);
}
break;
case "save":
if (cmdparams.Length < 2)
{
Notice("Syntax: config save <path>");
return;
}
string path = cmdparams[1];
Notice("Saving configuration file: {0}", path);
if (Config is IniConfigSource)
{
IniConfigSource iniCon = (IniConfigSource)Config;
iniCon.Save(path);
}
else if (Config is XmlConfigSource)
{
XmlConfigSource xmlCon = (XmlConfigSource)Config;
xmlCon.Save(path);
}
break;
}
}
}
private void HandleSetLogLevel(string module, string[] cmd)
{
if (cmd.Length != 4)
{
Notice("Usage: set log level <level>");
return;
}
if (null == m_consoleAppender)
{
Notice("No appender named Console found (see the log4net config file for this executable)!");
return;
}
string rawLevel = cmd[3];
ILoggerRepository repository = LogManager.GetRepository();
Level consoleLevel = repository.LevelMap[rawLevel];
if (consoleLevel != null)
m_consoleAppender.Threshold = consoleLevel;
else
Notice(
"{0} is not a valid logging level. Valid logging levels are ALL, DEBUG, INFO, WARN, ERROR, FATAL, OFF",
rawLevel);
ShowLogLevel();
}
private void ShowLogLevel()
{
Notice("Console log level is {0}", m_consoleAppender.Threshold);
}
protected virtual void HandleScript(string module, string[] parms)
{
if (parms.Length != 2)
{
Notice("Usage: command-script <path-to-script");
return;
}
RunCommandScript(parms[1]);
}
/// <summary>
/// Run an optional startup list of commands
/// </summary>
/// <param name="fileName"></param>
protected void RunCommandScript(string fileName)
{
if (m_console == null)
return;
if (File.Exists(fileName))
{
m_log.Info("[SERVER BASE]: Running " + fileName);
using (StreamReader readFile = File.OpenText(fileName))
{
string currentCommand;
while ((currentCommand = readFile.ReadLine()) != null)
{
currentCommand = currentCommand.Trim();
if (!(currentCommand == ""
|| currentCommand.StartsWith(";")
|| currentCommand.StartsWith("//")
|| currentCommand.StartsWith("#")))
{
m_log.Info("[SERVER BASE]: Running '" + currentCommand + "'");
m_console.RunCommand(currentCommand);
}
}
}
}
}
/// <summary>
/// Return a report about the uptime of this server
/// </summary>
/// <returns></returns>
protected string GetUptimeReport()
{
StringBuilder sb = new StringBuilder(String.Format("Time now is {0}\n", DateTime.Now));
sb.Append(String.Format("Server has been running since {0}, {1}\n", m_startuptime.DayOfWeek, m_startuptime));
sb.Append(String.Format("That is an elapsed time of {0}\n", DateTime.Now - m_startuptime));
return sb.ToString();
}
protected void ShowInfo()
{
Notice(GetVersionText());
Notice("Startup directory: " + m_startupDirectory);
if (null != m_consoleAppender)
Notice(String.Format("Console log level: {0}", m_consoleAppender.Threshold));
}
/// <summary>
/// Enhance the version string with extra information if it's available.
/// </summary>
protected void EnhanceVersionInformation()
{
string buildVersion = string.Empty;
// The subversion information is deprecated and will be removed at a later date
// Add subversion revision information if available
// Try file "svn_revision" in the current directory first, then the .svn info.
// This allows to make the revision available in simulators not running from the source tree.
// FIXME: Making an assumption about the directory we're currently in - we do this all over the place
// elsewhere as well
string gitDir = "../.git/";
string gitRefPointerPath = gitDir + "HEAD";
string svnRevisionFileName = "svn_revision";
string svnFileName = ".svn/entries";
string manualVersionFileName = ".version";
string inputLine;
int strcmp;
if (File.Exists(manualVersionFileName))
{
using (StreamReader CommitFile = File.OpenText(manualVersionFileName))
buildVersion = CommitFile.ReadLine();
m_version += buildVersion ?? "";
}
else if (File.Exists(gitRefPointerPath))
{
// m_log.DebugFormat("[SERVER BASE]: Found {0}", gitRefPointerPath);
string rawPointer = "";
using (StreamReader pointerFile = File.OpenText(gitRefPointerPath))
rawPointer = pointerFile.ReadLine();
// m_log.DebugFormat("[SERVER BASE]: rawPointer [{0}]", rawPointer);
Match m = Regex.Match(rawPointer, "^ref: (.+)$");
if (m.Success)
{
// m_log.DebugFormat("[SERVER BASE]: Matched [{0}]", m.Groups[1].Value);
string gitRef = m.Groups[1].Value;
string gitRefPath = gitDir + gitRef;
if (File.Exists(gitRefPath))
{
// m_log.DebugFormat("[SERVER BASE]: Found gitRefPath [{0}]", gitRefPath);
using (StreamReader refFile = File.OpenText(gitRefPath))
{
string gitHash = refFile.ReadLine();
m_version += gitHash.Substring(0, 7);
}
}
}
}
else
{
// Remove the else logic when subversion mirror is no longer used
if (File.Exists(svnRevisionFileName))
{
StreamReader RevisionFile = File.OpenText(svnRevisionFileName);
buildVersion = RevisionFile.ReadLine();
buildVersion.Trim();
RevisionFile.Close();
}
if (string.IsNullOrEmpty(buildVersion) && File.Exists(svnFileName))
{
StreamReader EntriesFile = File.OpenText(svnFileName);
inputLine = EntriesFile.ReadLine();
while (inputLine != null)
{
// using the dir svn revision at the top of entries file
strcmp = String.Compare(inputLine, "dir");
if (strcmp == 0)
{
buildVersion = EntriesFile.ReadLine();
break;
}
else
{
inputLine = EntriesFile.ReadLine();
}
}
EntriesFile.Close();
}
m_version += string.IsNullOrEmpty(buildVersion) ? " " : ("." + buildVersion + " ").Substring(0, 6);
}
}
protected string GetVersionText()
{
return String.Format("Version: {0} (interface version {1})", m_version, VersionInfo.MajorInterfaceVersion);
}
/// <summary>
/// Get a report about the registered threads in this server.
/// </summary>
protected string GetThreadsReport()
{
// This should be a constant field.
string reportFormat = "{0,6} {1,35} {2,16} {3,13} {4,10} {5,30}";
StringBuilder sb = new StringBuilder();
Watchdog.ThreadWatchdogInfo[] threads = Watchdog.GetThreadsInfo();
sb.Append(threads.Length + " threads are being tracked:" + Environment.NewLine);
int timeNow = Environment.TickCount & Int32.MaxValue;
sb.AppendFormat(reportFormat, "ID", "NAME", "LAST UPDATE (MS)", "LIFETIME (MS)", "PRIORITY", "STATE");
sb.Append(Environment.NewLine);
foreach (Watchdog.ThreadWatchdogInfo twi in threads)
{
Thread t = twi.Thread;
sb.AppendFormat(
reportFormat,
t.ManagedThreadId,
t.Name,
timeNow - twi.LastTick,
timeNow - twi.FirstTick,
t.Priority,
t.ThreadState);
sb.Append("\n");
}
sb.Append("\n");
// For some reason mono 2.6.7 returns an empty threads set! Not going to confuse people by reporting
// zero active threads.
int totalThreads = Process.GetCurrentProcess().Threads.Count;
if (totalThreads > 0)
sb.AppendFormat("Total threads active: {0}\n\n", totalThreads);
sb.Append("Main threadpool (excluding script engine pools)\n");
sb.Append(GetThreadPoolReport());
return sb.ToString();
}
/// <summary>
/// Get a thread pool report.
/// </summary>
/// <returns></returns>
public static string GetThreadPoolReport()
{
string threadPoolUsed = null;
int maxThreads = 0;
int minThreads = 0;
int allocatedThreads = 0;
int inUseThreads = 0;
int waitingCallbacks = 0;
int completionPortThreads = 0;
StringBuilder sb = new StringBuilder();
if (Util.FireAndForgetMethod == FireAndForgetMethod.SmartThreadPool)
{
STPInfo stpi = Util.GetSmartThreadPoolInfo();
// ROBUST currently leaves this the FireAndForgetMethod but never actually initializes the threadpool.
if (stpi != null)
{
threadPoolUsed = "SmartThreadPool";
maxThreads = stpi.MaxThreads;
minThreads = stpi.MinThreads;
inUseThreads = stpi.InUseThreads;
allocatedThreads = stpi.ActiveThreads;
waitingCallbacks = stpi.WaitingCallbacks;
}
}
else if (
Util.FireAndForgetMethod == FireAndForgetMethod.QueueUserWorkItem
|| Util.FireAndForgetMethod == FireAndForgetMethod.UnsafeQueueUserWorkItem)
{
threadPoolUsed = "BuiltInThreadPool";
ThreadPool.GetMaxThreads(out maxThreads, out completionPortThreads);
ThreadPool.GetMinThreads(out minThreads, out completionPortThreads);
int availableThreads;
ThreadPool.GetAvailableThreads(out availableThreads, out completionPortThreads);
inUseThreads = maxThreads - availableThreads;
allocatedThreads = -1;
waitingCallbacks = -1;
}
if (threadPoolUsed != null)
{
sb.AppendFormat("Thread pool used : {0}\n", threadPoolUsed);
sb.AppendFormat("Max threads : {0}\n", maxThreads);
sb.AppendFormat("Min threads : {0}\n", minThreads);
sb.AppendFormat("Allocated threads : {0}\n", allocatedThreads < 0 ? "not applicable" : allocatedThreads.ToString());
sb.AppendFormat("In use threads : {0}\n", inUseThreads);
sb.AppendFormat("Work items waiting : {0}\n", waitingCallbacks < 0 ? "not available" : waitingCallbacks.ToString());
}
else
{
sb.AppendFormat("Thread pool not used\n");
}
return sb.ToString();
}
public virtual void HandleThreadsAbort(string module, string[] cmd)
{
if (cmd.Length != 3)
{
MainConsole.Instance.Output("Usage: threads abort <thread-id>");
return;
}
int threadId;
if (!int.TryParse(cmd[2], out threadId))
{
MainConsole.Instance.Output("ERROR: Thread id must be an integer");
return;
}
if (Watchdog.AbortThread(threadId))
MainConsole.Instance.OutputFormat("Aborted thread with id {0}", threadId);
else
MainConsole.Instance.OutputFormat("ERROR - Thread with id {0} not found in managed threads", threadId);
}
/// <summary>
/// Console output is only possible if a console has been established.
/// That is something that cannot be determined within this class. So
/// all attempts to use the console MUST be verified.
/// </summary>
/// <param name="msg"></param>
protected void Notice(string msg)
{
if (m_console != null)
{
m_console.Output(msg);
}
}
/// <summary>
/// Console output is only possible if a console has been established.
/// That is something that cannot be determined within this class. So
/// all attempts to use the console MUST be verified.
/// </summary>
/// <param name="format"></param>
/// <param name="components"></param>
protected void Notice(string format, params object[] components)
{
if (m_console != null)
m_console.OutputFormat(format, components);
}
public virtual void Shutdown()
{
m_serverStatsCollector.Close();
ShutdownSpecific();
}
/// <summary>
/// Should be overriden and referenced by descendents if they need to perform extra shutdown processing
/// </summary>
protected virtual void ShutdownSpecific() {}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections;
using System.IO;
using System.Runtime.InteropServices;
using Xunit;
namespace System.Tests
{
public class GetEnvironmentVariable
{
[Fact]
public void InvalidArguments_ThrowsExceptions()
{
Assert.Throws<ArgumentNullException>("variable", () => Environment.GetEnvironmentVariable(null));
Assert.Throws<ArgumentNullException>("variable", () => Environment.SetEnvironmentVariable(null, "test"));
Assert.Throws<ArgumentException>("variable", () => Environment.SetEnvironmentVariable("", "test"));
Assert.Throws<ArgumentException>("value", () => Environment.SetEnvironmentVariable("test", new string('s', 65 * 1024)));
Assert.Throws<ArgumentException>("variable", () => Environment.SetEnvironmentVariable("", "test", EnvironmentVariableTarget.Machine));
Assert.Throws<ArgumentNullException>("variable", () => Environment.SetEnvironmentVariable(null, "test", EnvironmentVariableTarget.User));
Assert.Throws<ArgumentNullException>("variable", () => Environment.GetEnvironmentVariable(null, EnvironmentVariableTarget.Process));
Assert.Throws<ArgumentOutOfRangeException>("target", () => Environment.GetEnvironmentVariable("test", (EnvironmentVariableTarget)42));
Assert.Throws<ArgumentOutOfRangeException>("target", () => Environment.SetEnvironmentVariable("test", "test", (EnvironmentVariableTarget)(-1)));
Assert.Throws<ArgumentOutOfRangeException>("target", () => Environment.GetEnvironmentVariables((EnvironmentVariableTarget)(3)));
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
Assert.Throws<ArgumentException>("variable", () => Environment.SetEnvironmentVariable(new string('s', 256), "value", EnvironmentVariableTarget.User));
}
}
[Fact]
public void EmptyVariableReturnsNull()
{
Assert.Null(Environment.GetEnvironmentVariable(String.Empty));
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // GetEnvironmentVariable by design doesn't respect changes via setenv
public void RandomLongVariableNameCanRoundTrip()
{
// NOTE: The limit of 32766 characters enforced by desktop
// SetEnvironmentVariable is antiquated. I was
// able to create ~1GB names and values on my Windows 8.1 box. On
// desktop, GetEnvironmentVariable throws OOM during its attempt to
// demand huge EnvironmentPermission well before that. Also, the old
// test for long name case wasn't very good: it just checked that an
// arbitrary long name > 32766 characters returned null (not found), but
// that had nothing to do with the limit, the variable was simply not
// found!
string variable = "LongVariable_" + new string('@', 33000);
const string value = "TestValue";
try
{
SetEnvironmentVariableWithPInvoke(variable, value);
Assert.Equal(value, Environment.GetEnvironmentVariable(variable));
}
finally
{
SetEnvironmentVariableWithPInvoke(variable, null);
}
}
[Fact]
public void RandomVariableThatDoesNotExistReturnsNull()
{
string variable = "TestVariable_SurelyThisDoesNotExist";
Assert.Null(Environment.GetEnvironmentVariable(variable));
}
[Fact]
public void VariableNamesAreCaseInsensitiveAsAppropriate()
{
string value = "TestValue";
try
{
Environment.SetEnvironmentVariable("ThisIsATestEnvironmentVariable", value);
Assert.Equal(value, Environment.GetEnvironmentVariable("ThisIsATestEnvironmentVariable"));
if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
value = null;
}
Assert.Equal(value, Environment.GetEnvironmentVariable("thisisatestenvironmentvariable"));
Assert.Equal(value, Environment.GetEnvironmentVariable("THISISATESTENVIRONMENTVARIABLE"));
Assert.Equal(value, Environment.GetEnvironmentVariable("ThISISATeSTENVIRoNMEnTVaRIABLE"));
}
finally
{
Environment.SetEnvironmentVariable("ThisIsATestEnvironmentVariable", null);
}
}
[Fact]
public void CanGetAllVariablesIndividually()
{
Random r = new Random();
string envVar1 = "TestVariable_CanGetVariablesIndividually_" + r.Next().ToString();
string envVar2 = "TestVariable_CanGetVariablesIndividually_" + r.Next().ToString();
try
{
Environment.SetEnvironmentVariable(envVar1, envVar1);
Environment.SetEnvironmentVariable(envVar2, envVar2);
IDictionary envBlock = Environment.GetEnvironmentVariables();
// Make sure the environment variables we set are part of the dictionary returned.
Assert.True(envBlock.Contains(envVar1));
Assert.True(envBlock.Contains(envVar1));
// Make sure the values match the expected ones.
Assert.Equal(envVar1, envBlock[envVar1]);
Assert.Equal(envVar2, envBlock[envVar2]);
// Make sure we can read the individual variables as well
Assert.Equal(envVar1, Environment.GetEnvironmentVariable(envVar1));
Assert.Equal(envVar2, Environment.GetEnvironmentVariable(envVar2));
}
finally
{
// Clear the variables we just set
Environment.SetEnvironmentVariable(envVar1, null);
Environment.SetEnvironmentVariable(envVar2, null);
}
}
public void EnumerateYieldsDictionaryEntryFromIEnumerable()
{
// GetEnvironmentVariables has always yielded DictionaryEntry from IEnumerable
IDictionary vars = Environment.GetEnvironmentVariables();
IEnumerator enumerator = ((IEnumerable)vars).GetEnumerator();
if (enumerator.MoveNext())
{
Assert.IsType<DictionaryEntry>(enumerator.Current);
}
else
{
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
}
}
public void EnvironmentVariablesAreHashtable()
{
// On NetFX, the type returned was always Hashtable
Assert.IsType<Hashtable>(Environment.GetEnvironmentVariables());
}
[Theory]
[InlineData(EnvironmentVariableTarget.Process)]
[InlineData(EnvironmentVariableTarget.Machine)]
[InlineData(EnvironmentVariableTarget.User)]
public void EnvironmentVariablesAreHashtable(EnvironmentVariableTarget target)
{
// On NetFX, the type returned was always Hashtable
Assert.IsType<Hashtable>(Environment.GetEnvironmentVariables(target));
}
[Theory]
[InlineData(EnvironmentVariableTarget.Process)]
[InlineData(EnvironmentVariableTarget.Machine)]
[InlineData(EnvironmentVariableTarget.User)]
public void EnumerateYieldsDictionaryEntryFromIEnumerable(EnvironmentVariableTarget target)
{
// GetEnvironmentVariables has always yielded DictionaryEntry from IEnumerable
IDictionary vars = Environment.GetEnvironmentVariables(target);
IEnumerator enumerator = ((IEnumerable)vars).GetEnumerator();
if (enumerator.MoveNext())
{
Assert.IsType<DictionaryEntry>(enumerator.Current);
}
else
{
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
}
}
[Theory]
[InlineData(EnvironmentVariableTarget.Process)]
[InlineData(EnvironmentVariableTarget.Machine)]
[InlineData(EnvironmentVariableTarget.User)]
public void EnumerateEnvironmentVariables(EnvironmentVariableTarget target)
{
bool lookForSetValue = (target == EnvironmentVariableTarget.Process) || PlatformDetection.IsWindowsAndElevated;
const string key = "EnumerateEnvironmentVariables";
string value = Path.GetRandomFileName();
try
{
if (lookForSetValue)
{
Environment.SetEnvironmentVariable(key, value, target);
Assert.Equal(value, Environment.GetEnvironmentVariable(key, target));
}
IDictionary results = Environment.GetEnvironmentVariables(target);
// Ensure we can walk through the results
IDictionaryEnumerator enumerator = results.GetEnumerator();
while (enumerator.MoveNext())
{
Assert.NotNull(enumerator.Entry);
}
if (lookForSetValue)
{
// Ensure that we got our flagged value out
Assert.Equal(value, results[key]);
}
}
finally
{
if (lookForSetValue)
{
Environment.SetEnvironmentVariable(key, null, target);
Assert.Null(Environment.GetEnvironmentVariable(key, target));
}
}
}
private static void SetEnvironmentVariableWithPInvoke(string name, string value)
{
bool success =
RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ?
SetEnvironmentVariable(name, value) :
(value != null ? setenv(name, value, 1) : unsetenv(name)) == 0;
Assert.True(success);
}
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern bool SetEnvironmentVariable(string lpName, string lpValue);
[DllImport("libc")]
private static extern int setenv(string name, string value, int overwrite);
[DllImport("libc")]
private static extern int unsetenv(string name);
}
}
| |
//---------------------------------------------------------------------
// This file is part of the CLR Managed Debugger (mdbg) Sample.
//
// Copyright (C) Microsoft Corporation. All rights reserved.
//---------------------------------------------------------------------
using System;
using System.Threading;
using System.Diagnostics;
using System.Collections;
using System.Reflection;
using System.IO;
using Microsoft.Samples.Debugging.CorDebug;
using Microsoft.Samples.Debugging.CorDebug.NativeApi;
using Microsoft.Samples.Debugging.CorMetadata;
using System.Runtime.Remoting;
namespace Microsoft.Samples.Debugging.MdbgEngine
{
/// <summary>
/// This represents a Collection of MDbg Debugger Variables.
/// </summary>
public sealed class MDbgDebuggerVarCollection : MarshalByRefObject,IEnumerable
{
internal MDbgDebuggerVarCollection(MDbgProcess process)
{
m_process = process;
}
IEnumerator IEnumerable.GetEnumerator()
{
MDbgDebuggerVar[] ret = new MDbgDebuggerVar[m_debuggerVars.Count+g_specialVars.Length];
m_debuggerVars.Values.CopyTo(ret,0);
for(int i=0;i<g_specialVars.Length;++i)
{
MDbgDebuggerVar d = RetrieveSpecialVar(g_specialVars[i]);
Debug.Assert(d!=null); // RetrieveSpecialVar needs to succedd for every var in g_specialVars
ret[m_debuggerVars.Count+i] = d;
}
Array.Sort(ret);
return ret.GetEnumerator();
}
/// <summary>
/// Indexer allowing the Variable Collection to be accessed using array syntax.
/// </summary>
/// <param name="varName">The variable name that you want to access.</param>
/// <returns>The variable.</returns>
public MDbgDebuggerVar this[string varName]
{
get
{
Debug.Assert(varName!=null && varName.StartsWith("$"));
if( varName==null || !varName.StartsWith("$") )
throw new ArgumentException("Wrong name of debugger variable.");
// handle special read-only debugger vars
MDbgDebuggerVar dv;
dv = RetrieveSpecialVar(varName);
if( dv!=null )
return dv;
string istr =String.Intern(varName);
if(m_debuggerVars.Contains(istr))
return (MDbgDebuggerVar) m_debuggerVars[istr];
else
{
dv = new MDbgDebuggerVar(varName);
m_debuggerVars.Add(istr,dv);
return dv;
}
}
}
/// <summary>
/// Indicates if a variable name is in the collection.
/// </summary>
/// <param name="variableName">The variable name to look up.</param>
/// <returns>Returns true if the variable is in the collection and false if it is not.</returns>
public bool HaveVariable(string variableName)
{
return ( RetrieveSpecialVar(variableName)!=null
||m_debuggerVars.Contains(String.Intern(variableName)) );
}
private static string[] g_specialVars = new string[]{"$ex","$thread"};
private MDbgDebuggerVar RetrieveSpecialVar(string variableName)
{
switch(variableName)
{
case "$ex":
case "$exception":
return new MDbgDebuggerVar("$ex",m_process.Threads.Active.CurrentException.CorValue);
case "$thread":
return new MDbgDebuggerVar("$thread", m_process.Threads.Active.CorThread.ThreadVariable);
default:
return null; // we don't know this special variable
}
}
/// <summary>
/// Removes a variable from the collection.
/// </summary>
/// <param name="variableName">The name of the variable to remove.</param>
public void DeleteVariable(string variableName)
{
Debug.Assert(variableName!=null);
m_debuggerVars.Remove(String.Intern(variableName));
}
/// <summary>
/// Sets the EvalResult to the specified CorValue
/// </summary>
/// <param name="evalValue">What value to set the Result to.</param>
/// <returns>Returns true on success else false.</returns>
public bool SetEvalResult(CorValue evalValue)
{
Debug.Assert(evalValue!=null);
if( evalValue==null )
throw new ArgumentException();
this["$result"].Value = evalValue;
return true;
}
private Hashtable m_debuggerVars = new Hashtable();
private MDbgProcess m_process;
}
/// <summary>
/// MDbg Debugger Variable class.
/// </summary>
public sealed class MDbgDebuggerVar : MarshalByRefObject, IComparable
{
internal MDbgDebuggerVar(string variableName)
{
Debug.Assert(variableName!=null);
m_name = variableName;
}
internal MDbgDebuggerVar(string variableName, CorValue corValue)
{
// corValue can be null meaning that the variable is not available
Debug.Assert(variableName!=null);
m_name = variableName;
m_corValue = corValue;
}
/// <summary>
/// Gets or sets the CorValue. Can be either CorReferenceValue or CorHeapValue
/// </summary>
/// <value></value>
public CorValue Value
{
get
{
return m_corValue;
}
set
{
Debug.Assert(value!=null);
if(value!=null)
{
CorHeapValue hv = value.CastToHeapValue();
if( hv==null )
{
// Check if it's a reference value.
CorReferenceValue cv = value.CastToReferenceValue();
if ((cv != null) && !cv.IsNull)
{
CorValue v2 = null;
try
{
v2 = cv.Dereference();
Debug.Assert(v2 != null, "Should always be able to dereference a reference value.");
hv = v2.CastToHeapValue();
}
catch(System.Runtime.InteropServices.COMException)
{
// If dereference failed because it was a bad value, then we won't try to make a strong
// reference to it.
}
}
}
if( hv!=null )
{
m_corValue = hv.CreateHandle(CorDebugHandleType.HANDLE_STRONG);
}
else
{
// this is not a GC collectable object, we might store the reference directly
m_corValue = value;
}
}
else
m_corValue = null;
}
}
/// <summary>
/// Get the CorValue for Variable.
/// </summary>
/// <value>The CorValue.</value>
public CorValue CorValue
{
get
{
return m_corValue;
}
}
/// <summary>
/// Get the Name for the Variable.
/// </summary>
/// <value>The Name.</value>
public string Name
{
get
{
return m_name;
}
}
int IComparable.CompareTo(object obj)
{
MDbgDebuggerVar other= obj as MDbgDebuggerVar;
return String.Compare( this.Name, other.Name );
}
private CorValue m_corValue=null;
private string m_name;
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Hyak.Common;
using Microsoft.Azure;
using Microsoft.Azure.Management.Sql.LegacySdk;
using Microsoft.Azure.Management.Sql.LegacySdk.Models;
using Newtonsoft.Json.Linq;
namespace Microsoft.Azure.Management.Sql.LegacySdk
{
/// <summary>
/// Represents all the operations for operating on Azure SQL Job Accounts.
/// Contains operations to: Create, Retrieve, Update, and Delete Job
/// Accounts
/// </summary>
internal partial class JobAccountOperations : IServiceOperations<SqlManagementClient>, IJobAccountOperations
{
/// <summary>
/// Initializes a new instance of the JobAccountOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal JobAccountOperations(SqlManagementClient client)
{
this._client = client;
}
private SqlManagementClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.Azure.Management.Sql.LegacySdk.SqlManagementClient.
/// </summary>
public SqlManagementClient Client
{
get { return this._client; }
}
/// <summary>
/// Begins creating a new Azure SQL Job Account or updating an existing
/// Azure SQL Job Account. To determine the status of the operation
/// call GetJobAccountOperationStatus.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the Azure SQL
/// Database Server belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Database Server that the Job
/// Account is hosted in.
/// </param>
/// <param name='jobAccountName'>
/// Required. The name of the Azure SQL Job Account to be created or
/// updated.
/// </param>
/// <param name='parameters'>
/// Required. The required parameters for creating or updating a Job
/// Account.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Response for long running Azure Sql Job Account operations.
/// </returns>
public async Task<JobAccountOperationResponse> BeginCreateOrUpdateAsync(string resourceGroupName, string serverName, string jobAccountName, JobAccountCreateOrUpdateParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (serverName == null)
{
throw new ArgumentNullException("serverName");
}
if (jobAccountName == null)
{
throw new ArgumentNullException("jobAccountName");
}
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
if (parameters.Properties == null)
{
throw new ArgumentNullException("parameters.Properties");
}
if (parameters.Properties.DatabaseId == null)
{
throw new ArgumentNullException("parameters.Properties.DatabaseId");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serverName", serverName);
tracingParameters.Add("jobAccountName", jobAccountName);
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "BeginCreateOrUpdateAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.Sql";
url = url + "/servers/";
url = url + Uri.EscapeDataString(serverName);
url = url + "/jobAccounts/";
url = url + Uri.EscapeDataString(jobAccountName);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-05-01-preview");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Put;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = null;
JToken requestDoc = null;
JObject jobAccountCreateOrUpdateParametersValue = new JObject();
requestDoc = jobAccountCreateOrUpdateParametersValue;
JObject propertiesValue = new JObject();
jobAccountCreateOrUpdateParametersValue["properties"] = propertiesValue;
propertiesValue["databaseId"] = parameters.Properties.DatabaseId;
if (parameters.Location != null)
{
jobAccountCreateOrUpdateParametersValue["location"] = parameters.Location;
}
if (parameters.Tags != null)
{
JObject tagsDictionary = new JObject();
foreach (KeyValuePair<string, string> pair in parameters.Tags)
{
string tagsKey = pair.Key;
string tagsValue = pair.Value;
tagsDictionary[tagsKey] = tagsValue;
}
jobAccountCreateOrUpdateParametersValue["tags"] = tagsDictionary;
}
requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented);
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Created && statusCode != HttpStatusCode.Accepted)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
JobAccountOperationResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK || statusCode == HttpStatusCode.Created || statusCode == HttpStatusCode.Accepted)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new JobAccountOperationResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
ErrorResponse errorInstance = new ErrorResponse();
result.Error = errorInstance;
JToken codeValue = responseDoc["code"];
if (codeValue != null && codeValue.Type != JTokenType.Null)
{
string codeInstance = ((string)codeValue);
errorInstance.Code = codeInstance;
}
JToken messageValue = responseDoc["message"];
if (messageValue != null && messageValue.Type != JTokenType.Null)
{
string messageInstance = ((string)messageValue);
errorInstance.Message = messageInstance;
}
JToken targetValue = responseDoc["target"];
if (targetValue != null && targetValue.Type != JTokenType.Null)
{
string targetInstance = ((string)targetValue);
errorInstance.Target = targetInstance;
}
JobAccount jobAccountInstance = new JobAccount();
result.JobAccount = jobAccountInstance;
JToken propertiesValue2 = responseDoc["properties"];
if (propertiesValue2 != null && propertiesValue2.Type != JTokenType.Null)
{
JobAccountProperties propertiesInstance = new JobAccountProperties();
jobAccountInstance.Properties = propertiesInstance;
JToken databaseIdValue = propertiesValue2["databaseId"];
if (databaseIdValue != null && databaseIdValue.Type != JTokenType.Null)
{
string databaseIdInstance = ((string)databaseIdValue);
propertiesInstance.DatabaseId = databaseIdInstance;
}
}
JToken idValue = responseDoc["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
jobAccountInstance.Id = idInstance;
}
JToken nameValue = responseDoc["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
jobAccountInstance.Name = nameInstance;
}
JToken typeValue = responseDoc["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
string typeInstance = ((string)typeValue);
jobAccountInstance.Type = typeInstance;
}
JToken locationValue = responseDoc["location"];
if (locationValue != null && locationValue.Type != JTokenType.Null)
{
string locationInstance = ((string)locationValue);
jobAccountInstance.Location = locationInstance;
}
JToken tagsSequenceElement = ((JToken)responseDoc["tags"]);
if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null)
{
foreach (JProperty property in tagsSequenceElement)
{
string tagsKey2 = ((string)property.Name);
string tagsValue2 = ((string)property.Value);
jobAccountInstance.Tags.Add(tagsKey2, tagsValue2);
}
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("Location"))
{
result.OperationStatusLink = httpResponse.Headers.GetValues("Location").FirstOrDefault();
}
if (httpResponse.Headers.Contains("Retry-After"))
{
result.RetryAfter = int.Parse(httpResponse.Headers.GetValues("Retry-After").FirstOrDefault(), CultureInfo.InvariantCulture);
}
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (statusCode == HttpStatusCode.Created)
{
result.Status = OperationStatus.Succeeded;
}
if (statusCode == HttpStatusCode.OK)
{
result.Status = OperationStatus.Succeeded;
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Begins deleting the Azure SQL Job Account with the given name. To
/// determine the status of the operation call
/// GetJobAccountOperationStatus.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the Azure SQL
/// Database Server belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Database Server that the Job
/// Account is hosted in.
/// </param>
/// <param name='jobAccountName'>
/// Required. The name of the Azure SQL Job Account to be deleted.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Response for long running Azure Sql Job Account operations.
/// </returns>
public async Task<JobAccountOperationResponse> BeginDeleteAsync(string resourceGroupName, string serverName, string jobAccountName, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (serverName == null)
{
throw new ArgumentNullException("serverName");
}
if (jobAccountName == null)
{
throw new ArgumentNullException("jobAccountName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serverName", serverName);
tracingParameters.Add("jobAccountName", jobAccountName);
TracingAdapter.Enter(invocationId, this, "BeginDeleteAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.Sql";
url = url + "/servers/";
url = url + Uri.EscapeDataString(serverName);
url = url + "/jobAccounts/";
url = url + Uri.EscapeDataString(jobAccountName);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-05-01-preview");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Delete;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Accepted && statusCode != HttpStatusCode.NoContent)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
JobAccountOperationResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK || statusCode == HttpStatusCode.Accepted || statusCode == HttpStatusCode.NoContent)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new JobAccountOperationResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
ErrorResponse errorInstance = new ErrorResponse();
result.Error = errorInstance;
JToken codeValue = responseDoc["code"];
if (codeValue != null && codeValue.Type != JTokenType.Null)
{
string codeInstance = ((string)codeValue);
errorInstance.Code = codeInstance;
}
JToken messageValue = responseDoc["message"];
if (messageValue != null && messageValue.Type != JTokenType.Null)
{
string messageInstance = ((string)messageValue);
errorInstance.Message = messageInstance;
}
JToken targetValue = responseDoc["target"];
if (targetValue != null && targetValue.Type != JTokenType.Null)
{
string targetInstance = ((string)targetValue);
errorInstance.Target = targetInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("Location"))
{
result.OperationStatusLink = httpResponse.Headers.GetValues("Location").FirstOrDefault();
}
if (httpResponse.Headers.Contains("Retry-After"))
{
result.RetryAfter = int.Parse(httpResponse.Headers.GetValues("Retry-After").FirstOrDefault(), CultureInfo.InvariantCulture);
}
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (statusCode == HttpStatusCode.NoContent)
{
result.Status = OperationStatus.Succeeded;
}
if (statusCode == HttpStatusCode.OK)
{
result.Status = OperationStatus.Succeeded;
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Creates a new Azure SQL Job Account or updates an existing Azure
/// SQL Job Account.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the server
/// belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Job Database Server that the
/// Job Account is hosted in.
/// </param>
/// <param name='jobAccountName'>
/// Required. The name of the Azure SQL Job Account to be created or
/// updated.
/// </param>
/// <param name='parameters'>
/// Required. The required parameters for creating or updating a Job
/// Account.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Response for long running Azure Sql Job Account operations.
/// </returns>
public async Task<JobAccountOperationResponse> CreateOrUpdateAsync(string resourceGroupName, string serverName, string jobAccountName, JobAccountCreateOrUpdateParameters parameters, CancellationToken cancellationToken)
{
SqlManagementClient client = this.Client;
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serverName", serverName);
tracingParameters.Add("jobAccountName", jobAccountName);
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "CreateOrUpdateAsync", tracingParameters);
}
cancellationToken.ThrowIfCancellationRequested();
JobAccountOperationResponse response = await client.JobAccounts.BeginCreateOrUpdateAsync(resourceGroupName, serverName, jobAccountName, parameters, cancellationToken).ConfigureAwait(false);
if (response.Status == OperationStatus.Succeeded)
{
return response;
}
cancellationToken.ThrowIfCancellationRequested();
JobAccountOperationResponse result = await client.JobAccounts.GetJobAccountOperationStatusAsync(response.OperationStatusLink, cancellationToken).ConfigureAwait(false);
int delayInSeconds = response.RetryAfter;
if (delayInSeconds == 0)
{
delayInSeconds = 30;
}
if (client.LongRunningOperationInitialTimeout >= 0)
{
delayInSeconds = client.LongRunningOperationInitialTimeout;
}
while (result.Status == OperationStatus.InProgress)
{
cancellationToken.ThrowIfCancellationRequested();
await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
result = await client.JobAccounts.GetJobAccountOperationStatusAsync(response.OperationStatusLink, cancellationToken).ConfigureAwait(false);
delayInSeconds = result.RetryAfter;
if (delayInSeconds == 0)
{
delayInSeconds = 15;
}
if (client.LongRunningOperationRetryTimeout >= 0)
{
delayInSeconds = client.LongRunningOperationRetryTimeout;
}
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
/// <summary>
/// Creates a new Azure SQL Job Account or updates an existing Azure
/// SQL Job Account.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the server
/// belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Job Database Server that the
/// Job Account is hosted in.
/// </param>
/// <param name='jobAccountName'>
/// Required. The name of the Azure SQL Job Account to be created or
/// updated.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Response for long running Azure Sql Job Account operations.
/// </returns>
public async Task<JobAccountOperationResponse> DeleteAsync(string resourceGroupName, string serverName, string jobAccountName, CancellationToken cancellationToken)
{
SqlManagementClient client = this.Client;
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serverName", serverName);
tracingParameters.Add("jobAccountName", jobAccountName);
TracingAdapter.Enter(invocationId, this, "DeleteAsync", tracingParameters);
}
cancellationToken.ThrowIfCancellationRequested();
JobAccountOperationResponse response = await client.JobAccounts.BeginDeleteAsync(resourceGroupName, serverName, jobAccountName, cancellationToken).ConfigureAwait(false);
if (response.Status == OperationStatus.Succeeded)
{
return response;
}
cancellationToken.ThrowIfCancellationRequested();
JobAccountOperationResponse result = await client.JobAccounts.GetJobAccountOperationStatusAsync(response.OperationStatusLink, cancellationToken).ConfigureAwait(false);
int delayInSeconds = response.RetryAfter;
if (delayInSeconds == 0)
{
delayInSeconds = 30;
}
if (client.LongRunningOperationInitialTimeout >= 0)
{
delayInSeconds = client.LongRunningOperationInitialTimeout;
}
while (result.Status == OperationStatus.InProgress)
{
cancellationToken.ThrowIfCancellationRequested();
await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
result = await client.JobAccounts.GetJobAccountOperationStatusAsync(response.OperationStatusLink, cancellationToken).ConfigureAwait(false);
delayInSeconds = result.RetryAfter;
if (delayInSeconds == 0)
{
delayInSeconds = 15;
}
if (client.LongRunningOperationRetryTimeout >= 0)
{
delayInSeconds = client.LongRunningOperationRetryTimeout;
}
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
/// <summary>
/// Returns information about an Azure SQL Job Account.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the server
/// belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Database Server that the Job
/// Account is hosted in.
/// </param>
/// <param name='jobAccountName'>
/// Required. The name of the Azure SQL Job Account to be retrieved.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Represents the response to a Get Azure Sql Job Account request.
/// </returns>
public async Task<JobAccountGetResponse> GetAsync(string resourceGroupName, string serverName, string jobAccountName, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (serverName == null)
{
throw new ArgumentNullException("serverName");
}
if (jobAccountName == null)
{
throw new ArgumentNullException("jobAccountName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serverName", serverName);
tracingParameters.Add("jobAccountName", jobAccountName);
TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.Sql";
url = url + "/servers/";
url = url + Uri.EscapeDataString(serverName);
url = url + "/jobAccounts/";
url = url + Uri.EscapeDataString(jobAccountName);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-05-01-preview");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
JobAccountGetResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new JobAccountGetResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
JobAccount jobAccountInstance = new JobAccount();
result.JobAccount = jobAccountInstance;
JToken propertiesValue = responseDoc["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
JobAccountProperties propertiesInstance = new JobAccountProperties();
jobAccountInstance.Properties = propertiesInstance;
JToken databaseIdValue = propertiesValue["databaseId"];
if (databaseIdValue != null && databaseIdValue.Type != JTokenType.Null)
{
string databaseIdInstance = ((string)databaseIdValue);
propertiesInstance.DatabaseId = databaseIdInstance;
}
}
JToken idValue = responseDoc["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
jobAccountInstance.Id = idInstance;
}
JToken nameValue = responseDoc["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
jobAccountInstance.Name = nameInstance;
}
JToken typeValue = responseDoc["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
string typeInstance = ((string)typeValue);
jobAccountInstance.Type = typeInstance;
}
JToken locationValue = responseDoc["location"];
if (locationValue != null && locationValue.Type != JTokenType.Null)
{
string locationInstance = ((string)locationValue);
jobAccountInstance.Location = locationInstance;
}
JToken tagsSequenceElement = ((JToken)responseDoc["tags"]);
if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null)
{
foreach (JProperty property in tagsSequenceElement)
{
string tagsKey = ((string)property.Name);
string tagsValue = ((string)property.Value);
jobAccountInstance.Tags.Add(tagsKey, tagsValue);
}
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Gets the status of an Azure Sql Job Account create or update
/// operation.
/// </summary>
/// <param name='operationStatusLink'>
/// Required. Location value returned by the Begin operation
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Response for long running Azure Sql Job Account operations.
/// </returns>
public async Task<JobAccountOperationResponse> GetJobAccountOperationStatusAsync(string operationStatusLink, CancellationToken cancellationToken)
{
// Validate
if (operationStatusLink == null)
{
throw new ArgumentNullException("operationStatusLink");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("operationStatusLink", operationStatusLink);
TracingAdapter.Enter(invocationId, this, "GetJobAccountOperationStatusAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + operationStatusLink;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Created && statusCode != HttpStatusCode.Accepted && statusCode != HttpStatusCode.NoContent)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
JobAccountOperationResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK || statusCode == HttpStatusCode.Created || statusCode == HttpStatusCode.Accepted || statusCode == HttpStatusCode.NoContent)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new JobAccountOperationResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
ErrorResponse errorInstance = new ErrorResponse();
result.Error = errorInstance;
JToken codeValue = responseDoc["code"];
if (codeValue != null && codeValue.Type != JTokenType.Null)
{
string codeInstance = ((string)codeValue);
errorInstance.Code = codeInstance;
}
JToken messageValue = responseDoc["message"];
if (messageValue != null && messageValue.Type != JTokenType.Null)
{
string messageInstance = ((string)messageValue);
errorInstance.Message = messageInstance;
}
JToken targetValue = responseDoc["target"];
if (targetValue != null && targetValue.Type != JTokenType.Null)
{
string targetInstance = ((string)targetValue);
errorInstance.Target = targetInstance;
}
JobAccount jobAccountInstance = new JobAccount();
result.JobAccount = jobAccountInstance;
JToken propertiesValue = responseDoc["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
JobAccountProperties propertiesInstance = new JobAccountProperties();
jobAccountInstance.Properties = propertiesInstance;
JToken databaseIdValue = propertiesValue["databaseId"];
if (databaseIdValue != null && databaseIdValue.Type != JTokenType.Null)
{
string databaseIdInstance = ((string)databaseIdValue);
propertiesInstance.DatabaseId = databaseIdInstance;
}
}
JToken idValue = responseDoc["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
jobAccountInstance.Id = idInstance;
}
JToken nameValue = responseDoc["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
jobAccountInstance.Name = nameInstance;
}
JToken typeValue = responseDoc["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
string typeInstance = ((string)typeValue);
jobAccountInstance.Type = typeInstance;
}
JToken locationValue = responseDoc["location"];
if (locationValue != null && locationValue.Type != JTokenType.Null)
{
string locationInstance = ((string)locationValue);
jobAccountInstance.Location = locationInstance;
}
JToken tagsSequenceElement = ((JToken)responseDoc["tags"]);
if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null)
{
foreach (JProperty property in tagsSequenceElement)
{
string tagsKey = ((string)property.Name);
string tagsValue = ((string)property.Value);
jobAccountInstance.Tags.Add(tagsKey, tagsValue);
}
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (statusCode == HttpStatusCode.NoContent)
{
result.Status = OperationStatus.Succeeded;
}
if (statusCode == HttpStatusCode.Created)
{
result.Status = OperationStatus.Succeeded;
}
if (statusCode == HttpStatusCode.OK)
{
result.Status = OperationStatus.Succeeded;
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Returns information about Azure SQL Job Accounts.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the server
/// belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Database Server that the Job
/// Accounts are hosted in.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Represents the response to a List Azure Sql Job Accounts request.
/// </returns>
public async Task<JobAccountListResponse> ListAsync(string resourceGroupName, string serverName, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (serverName == null)
{
throw new ArgumentNullException("serverName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serverName", serverName);
TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.Sql";
url = url + "/servers/";
url = url + Uri.EscapeDataString(serverName);
url = url + "/jobAccounts";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-05-01-preview");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
JobAccountListResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new JobAccountListResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
JToken valueArray = responseDoc["value"];
if (valueArray != null && valueArray.Type != JTokenType.Null)
{
foreach (JToken valueValue in ((JArray)valueArray))
{
JobAccount jobAccountInstance = new JobAccount();
result.JobAccounts.Add(jobAccountInstance);
JToken propertiesValue = valueValue["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
JobAccountProperties propertiesInstance = new JobAccountProperties();
jobAccountInstance.Properties = propertiesInstance;
JToken databaseIdValue = propertiesValue["databaseId"];
if (databaseIdValue != null && databaseIdValue.Type != JTokenType.Null)
{
string databaseIdInstance = ((string)databaseIdValue);
propertiesInstance.DatabaseId = databaseIdInstance;
}
}
JToken idValue = valueValue["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
jobAccountInstance.Id = idInstance;
}
JToken nameValue = valueValue["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
jobAccountInstance.Name = nameInstance;
}
JToken typeValue = valueValue["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
string typeInstance = ((string)typeValue);
jobAccountInstance.Type = typeInstance;
}
JToken locationValue = valueValue["location"];
if (locationValue != null && locationValue.Type != JTokenType.Null)
{
string locationInstance = ((string)locationValue);
jobAccountInstance.Location = locationInstance;
}
JToken tagsSequenceElement = ((JToken)valueValue["tags"]);
if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null)
{
foreach (JProperty property in tagsSequenceElement)
{
string tagsKey = ((string)property.Name);
string tagsValue = ((string)property.Value);
jobAccountInstance.Tags.Add(tagsKey, tagsValue);
}
}
}
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Web.Http.Description;
using System.Xml.Linq;
using Newtonsoft.Json;
namespace RedBox.Web.Areas.HelpPage.SampleGeneration
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>>
{
DefaultSampleObjectFactory,
};
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order,
/// stopping when the factory successfully returns a non-<see langref="null"/> object.
/// </summary>
/// <remarks>
/// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use
/// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and
/// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",
Justification = "This is an appropriate nesting of generic types")]
public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames.
// If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames.
// If still not found, try to get the sample provided for the specified mediaType and type.
// Finally, try to get the sample provided for the specified mediaType.
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create
/// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other
/// factories in <see cref="SampleObjectFactories"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")]
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// No specific object available, try our factories.
foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories)
{
if (factory == null)
{
continue;
}
try
{
sampleObject = factory(this, type);
if (sampleObject != null)
{
break;
}
}
catch
{
// Ignore any problems encountered in the factory; go on to the next one (if any).
}
}
}
return sampleObject;
}
/// <summary>
/// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The type.</returns>
public virtual Type ResolveHttpRequestMessageType(ApiDescription api)
{
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters);
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
UnwrapException(e).Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
internal static Exception UnwrapException(Exception exception)
{
AggregateException aggregateException = exception as AggregateException;
if (aggregateException != null)
{
return aggregateException.Flatten().InnerException;
}
return exception;
}
// Default factory for sample objects
private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type)
{
// Try to create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
// Copyright (c) 2007-2008 Adrian Kuhn <akuhn(a)iam.unibe.ch>
//
// This file is part of 'Fame (for .NET)'.
//
// 'Fame (for .NET)' is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or (at your
// option) any later version.
//
// 'Fame (for .NET)' is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
// License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with 'Fame (for .NET)'. If not, see <http://www.gnu.org/licenses/>.
namespace Fame
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using Common;
using Dsl;
using Fm3;
using Internal;
using Parser;
/// <inheritdoc />
/// <summary>
/// A meta-model (ie elements conforming to FM3).
/// </summary>
public class MetaRepository : Repository
{
private readonly Dictionary<string, Element> _bindings;
private readonly Dictionary<Type, MetaDescription> _classes;
private bool _immutable;
public static MetaRepository CreateFm3()
{
MetaRepository mse = new MetaRepository(null);
mse.With(typeof(MetaDescription));
mse.With(typeof(Element));
mse.With(typeof(PackageDescription));
mse.With(typeof(PropertyDescription));
mse.AddAll(mse._bindings.Values.ToArray());
mse.SetImmutable();
return mse;
}
public static bool IsValidElementName(string name)
{
if (string.IsNullOrEmpty(name))
return false;
bool expectStart = true;
foreach (char ch in name)
{
if (expectStart)
{
if (char.IsLetter(ch))
{
expectStart = false;
}
else
{
return false;
}
}
else
{
if (ch == '.')
{
expectStart = true;
}
else
{
if (!char.IsLetterOrDigit(ch) && ch != '_')
return false;
}
}
}
return !expectStart;
}
public static bool IsValidName(string name)
{
return !string.IsNullOrEmpty(name) && char.IsLetter(name[0]); // && isAlphanumeric(string); //TODO: see utils
}
public MetaRepository() : this (CreateFm3())
{
}
public MetaRepository(MetaRepository metamodel) : base(metamodel)
{
_classes = new Dictionary<Type, MetaDescription>();
_bindings = new Dictionary<string, Element>();
}
public override void Add(object element)
{
Debug.Assert(!_immutable);
Debug.Assert(element is Element, element.GetType().ToString());
if (element is MetaDescription)
{
MetaDescription meta = (MetaDescription)element;
if (meta.IsPrimitive() || meta.IsRoot()) return;
}
base.Add(element);
if (!_bindings.ContainsKey(((Element)element).Fullname))
_bindings.Add(((Element)element).Fullname, (Element)element);
}
public void AddClassDescription(Type cls, MetaDescription desc)
{
_classes.Add(cls, desc);
}
public ICollection<MetaDescription> AllClassDescriptions()
{
return All<MetaDescription>();
}
public ICollection<PackageDescription> AllPackageDescriptions()
{
return All<PackageDescription>();
}
public ICollection<PropertyDescription> AllPropertyDescriptions()
{
return All<PropertyDescription>();
}
public MetamodelBuilder Builder()
{
IParseClient client = new Importer(GetMetamodel(), this);
client = new DebugClient(client);
client = new ProtocolChecker(client);
return new MetamodelBuilder(client);
}
public Warnings CheckConstraints()
{
Warnings warnings = new Warnings();
foreach (object each in GetElements())
{
((Element)each).CheckConstraints(warnings);
}
return warnings;
}
public MetaDescription DescriptionNamed(string fullname)
{
object found = Get<Element>(fullname);
if (found is MetaDescription)
return (MetaDescription)found;
return null;
}
/// <summary>
/// Returns the Fame-class to which the given C#-class is connected in this metammodel.
///
/// throws Exception if the C#-class is not connected to any Fame-class in this metammodel.
/// see #with(Class)
/// </summary>
/// <param name="jclass">a causally connected C#-class.</param>
/// <returns>return a causally connected Fame-class.</returns>
public MetaDescription GetDescription(Type jclass)
{
MetaDescription m = LookupPrimitive(jclass);
if (m != null) return m;
for (Type curr = jclass; curr != null; curr = curr.BaseType)
{
m = LookupClass(curr);
if (m != null) return m;
}
throw new Exception("Class not metadescribed: " + jclass);
//throw new ClassNotMetadescribedException(jclass);
}
private MetaDescription LookupPrimitive(Type jclass)
{
if (jclass.IsPrimitive)
{
return typeof(bool) == jclass ? MetaDescription.BOOLEAN : MetaDescription.NUMBER;
}
if (jclass.IsNumber())
{
return MetaDescription.NUMBER;
}
if (typeof(bool) == jclass)
{
return MetaDescription.BOOLEAN;
}
if (typeof(string) == jclass)
{
return MetaDescription.STRING;
}
if (typeof(char[]) == jclass)
{
return MetaDescription.STRING;
}
if (typeof(object) == jclass)
{
return MetaDescription.OBJECT;
}
return null;
}
public PackageDescription InitializePackageNamed(string name)
{
PackageDescription description = Get<PackageDescription>(name);
if (description == null)
{
description = new PackageDescription(name);
_bindings.Add(name, description);
}
return description;
}
public bool IsSelfDescribed()
{
return GetMetamodel() == this;
}
private MetaDescription LookupClass(Type jclass)
{
if (_classes.ContainsKey(jclass))
return _classes[jclass];
return null;
}
private MetaDescription LookupFull(Type jclass)
{
MetaDescription m = LookupPrimitive(jclass);
if (m == null) m = LookupClass(jclass);
return m;
}
public void SetImmutable()
{
_immutable = true;
}
/// <summary>
/// Processes the annotations of the given Java-class, creates an according
/// Fame-class and establishes a Scenario-II connection between both. If such
/// a connection is already present, nothing is done.
///
/// @see FameDescription
/// @see FamePackage
/// @see FameProperty
/// @throws AssertionError if the Java-class is not annotated.
/// </summary>
/// <param name="annotatedType">an annotated C#-class</param>
public void With(Type annotatedType)
{
MetaDescription m = LookupFull(annotatedType);
if (m == null)
{
MetaDescriptionFactory factory = new MetaDescriptionFactory(annotatedType, this);
if (factory.AnnotationPresent)
{
m = factory.CreateInstance();
_classes.Add(annotatedType, m);
factory.InitializeInstance();
_bindings.Add(m.Fullname, m);
}
if (!IsSelfDescribed())
{
// TODO explain? breaks meta-loop!
Add(m);
}
}
Debug.Assert(m != null, annotatedType.ToString());
}
/// <summary>
/// Processes all given Java-classes.
///
/// @see #with(Class)
/// @throws AssertionError if any o fthe C#-classes is not annotated.
///
/// </summary>
/// <param name="jclasses">some annotated C#-classes.</param>
public void WithAll(params Type[] jclasses)
{
foreach (Type jclass in jclasses)
{
With(jclass);
}
}
public T Get<T>(string fullname) where T : Element
{
if (_bindings.ContainsKey(fullname))
return (T)_bindings[fullname];
return default(T);
}
}
}
| |
//----------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace System.ServiceModel.Security
{
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IdentityModel.Policy;
using System.IdentityModel.Selectors;
using System.IdentityModel.Tokens;
using System.Runtime;
using System.Runtime.Diagnostics;
using System.Security.Cryptography;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
using System.ServiceModel.Diagnostics;
using System.ServiceModel.Diagnostics.Application;
using System.ServiceModel.Security.Tokens;
using System.Xml;
using Reference = System.IdentityModel.Reference;
using SignedInfo = System.IdentityModel.SignedInfo;
using SignedXml = System.IdentityModel.SignedXml;
using StandardSignedInfo = System.IdentityModel.StandardSignedInfo;
class WSSecurityOneDotZeroReceiveSecurityHeader : ReceiveSecurityHeader
{
WrappedKeySecurityToken pendingDecryptionToken;
ReferenceList pendingReferenceList;
SignedXml pendingSignature;
List<string> earlyDecryptedDataReferences;
public WSSecurityOneDotZeroReceiveSecurityHeader(Message message, string actor, bool mustUnderstand, bool relay,
SecurityStandardsManager standardsManager,
SecurityAlgorithmSuite algorithmSuite,
int headerIndex,
MessageDirection transferDirection)
: base(message, actor, mustUnderstand, relay, standardsManager, algorithmSuite, headerIndex, transferDirection)
{
}
protected static SymmetricAlgorithm CreateDecryptionAlgorithm(SecurityToken token, string encryptionMethod, SecurityAlgorithmSuite suite)
{
if (encryptionMethod == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(
SR.GetString(SR.EncryptionMethodMissingInEncryptedData)));
}
suite.EnsureAcceptableEncryptionAlgorithm(encryptionMethod);
SymmetricSecurityKey symmetricSecurityKey = SecurityUtils.GetSecurityKey<SymmetricSecurityKey>(token);
if (symmetricSecurityKey == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(
SR.GetString(SR.TokenCannotCreateSymmetricCrypto, token)));
}
suite.EnsureAcceptableDecryptionSymmetricKeySize(symmetricSecurityKey, token);
SymmetricAlgorithm algorithm = symmetricSecurityKey.GetSymmetricAlgorithm(encryptionMethod);
if (algorithm == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(
SR.GetString(SR.UnableToCreateSymmetricAlgorithmFromToken, encryptionMethod)));
}
return algorithm;
}
void DecryptBody(XmlDictionaryReader bodyContentReader, SecurityToken token)
{
EncryptedData bodyXml = new EncryptedData();
bodyXml.ShouldReadXmlReferenceKeyInfoClause = this.MessageDirection == MessageDirection.Output;
bodyXml.SecurityTokenSerializer = this.StandardsManager.SecurityTokenSerializer;
bodyXml.ReadFrom(bodyContentReader, MaxReceivedMessageSize);
if (!bodyContentReader.EOF && bodyContentReader.NodeType != XmlNodeType.EndElement)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(SR.GetString(SR.BadEncryptedBody)));
}
if (token == null)
{
token = ResolveKeyIdentifier(bodyXml.KeyIdentifier, this.PrimaryTokenResolver, false);
}
RecordEncryptionToken(token);
using (SymmetricAlgorithm algorithm = CreateDecryptionAlgorithm(token, bodyXml.EncryptionMethod, this.AlgorithmSuite))
{
bodyXml.SetUpDecryption(algorithm);
this.SecurityVerifiedMessage.SetDecryptedBody(bodyXml.GetDecryptedBuffer());
}
}
protected virtual DecryptedHeader DecryptHeader(XmlDictionaryReader reader, WrappedKeySecurityToken wrappedKeyToken)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new MessageSecurityException(SR.GetString(SR.HeaderDecryptionNotSupportedInWsSecurityJan2004)));
}
protected override byte[] DecryptSecurityHeaderElement(
EncryptedData encryptedData, WrappedKeySecurityToken wrappedKeyToken, out SecurityToken encryptionToken)
{
if ((encryptedData.KeyIdentifier != null) || (wrappedKeyToken == null))
{
// The EncryptedData might have a KeyInfo inside it. Try resolving the SecurityKeyIdentifier.
encryptionToken = ResolveKeyIdentifier(encryptedData.KeyIdentifier, this.CombinedPrimaryTokenResolver, false);
if (wrappedKeyToken != null && wrappedKeyToken.ReferenceList != null && encryptedData.HasId && wrappedKeyToken.ReferenceList.ContainsReferredId(encryptedData.Id) && (wrappedKeyToken != encryptionToken))
{
// We have a EncryptedKey with a ReferenceList inside it. This would mean that
// all the EncryptedData pointed by the ReferenceList should be encrypted only
// by this key. The individual EncryptedData elements if containing a KeyInfo
// clause should point back to the same EncryptedKey token.
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(SR.GetString(SR.EncryptedKeyWasNotEncryptedWithTheRequiredEncryptingToken, wrappedKeyToken)));
}
}
else
{
encryptionToken = wrappedKeyToken;
}
using (SymmetricAlgorithm algorithm = CreateDecryptionAlgorithm(encryptionToken, encryptedData.EncryptionMethod, this.AlgorithmSuite))
{
encryptedData.SetUpDecryption(algorithm);
return encryptedData.GetDecryptedBuffer();
}
}
protected override WrappedKeySecurityToken DecryptWrappedKey(XmlDictionaryReader reader)
{
if (TD.WrappedKeyDecryptionStartIsEnabled())
{
TD.WrappedKeyDecryptionStart(this.EventTraceActivity);
}
WrappedKeySecurityToken token = (WrappedKeySecurityToken)this.StandardsManager.SecurityTokenSerializer.ReadToken(
reader, this.PrimaryTokenResolver);
this.AlgorithmSuite.EnsureAcceptableKeyWrapAlgorithm(token.WrappingAlgorithm, token.WrappingSecurityKey is AsymmetricSecurityKey);
if (TD.WrappedKeyDecryptionSuccessIsEnabled())
{
TD.WrappedKeyDecryptionSuccess(this.EventTraceActivity);
}
return token;
}
bool EnsureDigestValidityIfIdMatches(
SignedInfo signedInfo,
string id, XmlDictionaryReader reader, bool doSoapAttributeChecks,
MessagePartSpecification signatureParts, MessageHeaderInfo info, bool checkForTokensAtHeaders)
{
if (signedInfo == null)
{
return false;
}
if (doSoapAttributeChecks)
{
VerifySoapAttributeMatchForHeader(info, signatureParts, reader);
}
bool signed = false;
bool isRecognizedSecurityToken = checkForTokensAtHeaders && this.StandardsManager.SecurityTokenSerializer.CanReadToken(reader);
try
{
signed = signedInfo.EnsureDigestValidityIfIdMatches(id, reader);
}
catch (CryptographicException exception)
{
//
// Wrap the crypto exception here so that the perf couter can be updated correctly
//
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(SR.GetString(SR.FailedSignatureVerification), exception));
}
if (signed && isRecognizedSecurityToken)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(SR.GetString(SR.SecurityTokenFoundOutsideSecurityHeader, info.Namespace, info.Name)));
}
return signed;
}
protected override void ExecuteMessageProtectionPass(bool hasAtLeastOneSupportingTokenExpectedToBeSigned)
{
SignatureTargetIdManager idManager = this.StandardsManager.IdManager;
MessagePartSpecification encryptionParts = this.RequiredEncryptionParts ?? MessagePartSpecification.NoParts;
MessagePartSpecification signatureParts = this.RequiredSignatureParts ?? MessagePartSpecification.NoParts;
bool checkForTokensAtHeaders = hasAtLeastOneSupportingTokenExpectedToBeSigned;
bool doSoapAttributeChecks = !signatureParts.IsBodyIncluded;
bool encryptBeforeSign = this.EncryptBeforeSignMode;
SignedInfo signedInfo = this.pendingSignature != null ? this.pendingSignature.Signature.SignedInfo : null;
SignatureConfirmations signatureConfirmations = this.GetSentSignatureConfirmations();
if (signatureConfirmations != null && signatureConfirmations.Count > 0 && signatureConfirmations.IsMarkedForEncryption)
{
// If Signature Confirmations are encrypted then the signature should
// be encrypted as well.
this.VerifySignatureEncryption();
}
MessageHeaders headers = this.SecurityVerifiedMessage.Headers;
XmlDictionaryReader reader = this.SecurityVerifiedMessage.GetReaderAtFirstHeader();
bool atLeastOneHeaderOrBodyEncrypted = false;
for (int i = 0; i < headers.Count; i++)
{
if (reader.NodeType != XmlNodeType.Element)
{
reader.MoveToContent();
}
if (i == this.HeaderIndex)
{
reader.Skip();
continue;
}
bool isHeaderEncrypted = false;
string id = idManager.ExtractId(reader);
if (id != null)
{
isHeaderEncrypted = TryDeleteReferenceListEntry(id);
}
if (!isHeaderEncrypted && reader.IsStartElement(SecurityXXX2005Strings.EncryptedHeader, SecurityXXX2005Strings.Namespace))
{
XmlDictionaryReader localreader = headers.GetReaderAtHeader(i);
localreader.ReadStartElement(SecurityXXX2005Strings.EncryptedHeader, SecurityXXX2005Strings.Namespace);
if (localreader.IsStartElement(EncryptedData.ElementName, XD.XmlEncryptionDictionary.Namespace))
{
string encryptedDataId = localreader.GetAttribute(XD.XmlEncryptionDictionary.Id, null);
if (encryptedDataId != null && TryDeleteReferenceListEntry(encryptedDataId))
{
isHeaderEncrypted = true;
}
}
}
this.ElementManager.VerifyUniquenessAndSetHeaderId(id, i);
MessageHeaderInfo info = headers[i];
if (!isHeaderEncrypted && encryptionParts.IsHeaderIncluded(info.Name, info.Namespace))
{
this.SecurityVerifiedMessage.OnUnencryptedPart(info.Name, info.Namespace);
}
bool headerSigned;
if ((!isHeaderEncrypted || encryptBeforeSign) && id != null)
{
headerSigned = EnsureDigestValidityIfIdMatches(signedInfo, id, reader, doSoapAttributeChecks, signatureParts, info, checkForTokensAtHeaders);
}
else
{
headerSigned = false;
}
if (isHeaderEncrypted)
{
XmlDictionaryReader decryptionReader = headerSigned ? headers.GetReaderAtHeader(i) : reader;
DecryptedHeader decryptedHeader = DecryptHeader(decryptionReader, this.pendingDecryptionToken);
info = decryptedHeader;
id = decryptedHeader.Id;
this.ElementManager.VerifyUniquenessAndSetDecryptedHeaderId(id, i);
headers.ReplaceAt(i, decryptedHeader);
if (!ReferenceEquals(decryptionReader, reader))
{
decryptionReader.Close();
}
if (!encryptBeforeSign && id != null)
{
XmlDictionaryReader decryptedHeaderReader = decryptedHeader.GetHeaderReader();
headerSigned = EnsureDigestValidityIfIdMatches(signedInfo, id, decryptedHeaderReader, doSoapAttributeChecks, signatureParts, info, checkForTokensAtHeaders);
decryptedHeaderReader.Close();
}
}
if (!headerSigned && signatureParts.IsHeaderIncluded(info.Name, info.Namespace))
{
this.SecurityVerifiedMessage.OnUnsignedPart(info.Name, info.Namespace);
}
if (headerSigned && isHeaderEncrypted)
{
// We have a header that is signed and encrypted. So the accompanying primary signature
// should be encrypted as well.
this.VerifySignatureEncryption();
}
if (isHeaderEncrypted && !headerSigned)
{
// We require all encrypted headers (outside the security header) to be signed.
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(SR.GetString(SR.EncryptedHeaderNotSigned, info.Name, info.Namespace)));
}
if (!headerSigned && !isHeaderEncrypted)
{
reader.Skip();
}
atLeastOneHeaderOrBodyEncrypted |= isHeaderEncrypted;
}
reader.ReadEndElement();
if (reader.NodeType != XmlNodeType.Element)
{
reader.MoveToContent();
}
string bodyId = idManager.ExtractId(reader);
this.ElementManager.VerifyUniquenessAndSetBodyId(bodyId);
this.SecurityVerifiedMessage.SetBodyPrefixAndAttributes(reader);
bool expectBodyEncryption = encryptionParts.IsBodyIncluded || HasPendingDecryptionItem();
bool bodySigned;
if ((!expectBodyEncryption || encryptBeforeSign) && bodyId != null)
{
bodySigned = EnsureDigestValidityIfIdMatches(signedInfo, bodyId, reader, false, null, null, false);
}
else
{
bodySigned = false;
}
bool bodyEncrypted;
if (expectBodyEncryption)
{
XmlDictionaryReader bodyReader = bodySigned ? this.SecurityVerifiedMessage.CreateFullBodyReader() : reader;
bodyReader.ReadStartElement();
string bodyContentId = idManager.ExtractId(bodyReader);
this.ElementManager.VerifyUniquenessAndSetBodyContentId(bodyContentId);
bodyEncrypted = bodyContentId != null && TryDeleteReferenceListEntry(bodyContentId);
if (bodyEncrypted)
{
DecryptBody(bodyReader, this.pendingDecryptionToken);
}
if (!ReferenceEquals(bodyReader, reader))
{
bodyReader.Close();
}
if (!encryptBeforeSign && signedInfo != null && signedInfo.HasUnverifiedReference(bodyId))
{
bodyReader = this.SecurityVerifiedMessage.CreateFullBodyReader();
bodySigned = EnsureDigestValidityIfIdMatches(signedInfo, bodyId, bodyReader, false, null, null, false);
bodyReader.Close();
}
}
else
{
bodyEncrypted = false;
}
if (bodySigned && bodyEncrypted)
{
this.VerifySignatureEncryption();
}
reader.Close();
if (this.pendingSignature != null)
{
this.pendingSignature.CompleteSignatureVerification();
this.pendingSignature = null;
}
this.pendingDecryptionToken = null;
atLeastOneHeaderOrBodyEncrypted |= bodyEncrypted;
if (!bodySigned && signatureParts.IsBodyIncluded)
{
this.SecurityVerifiedMessage.OnUnsignedPart(XD.MessageDictionary.Body.Value, this.Version.Envelope.Namespace);
}
if (!bodyEncrypted && encryptionParts.IsBodyIncluded)
{
this.SecurityVerifiedMessage.OnUnencryptedPart(XD.MessageDictionary.Body.Value, this.Version.Envelope.Namespace);
}
this.SecurityVerifiedMessage.OnMessageProtectionPassComplete(atLeastOneHeaderOrBodyEncrypted);
}
protected override bool IsReaderAtEncryptedData(XmlDictionaryReader reader)
{
bool encrypted = reader.IsStartElement(EncryptedData.ElementName, XD.XmlEncryptionDictionary.Namespace);
if (encrypted == true)
this.HasAtLeastOneItemInsideSecurityHeaderEncrypted = true;
return encrypted;
}
protected override bool IsReaderAtEncryptedKey(XmlDictionaryReader reader)
{
return reader.IsStartElement(EncryptedKey.ElementName, XD.XmlEncryptionDictionary.Namespace);
}
protected override bool IsReaderAtReferenceList(XmlDictionaryReader reader)
{
return reader.IsStartElement(ReferenceList.ElementName, ReferenceList.NamespaceUri);
}
protected override bool IsReaderAtSignature(XmlDictionaryReader reader)
{
return reader.IsStartElement(XD.XmlSignatureDictionary.Signature, XD.XmlSignatureDictionary.Namespace);
}
protected override bool IsReaderAtSecurityTokenReference(XmlDictionaryReader reader)
{
return reader.IsStartElement(XD.SecurityJan2004Dictionary.SecurityTokenReference, XD.SecurityJan2004Dictionary.Namespace);
}
protected override void ProcessReferenceListCore(ReferenceList referenceList, WrappedKeySecurityToken wrappedKeyToken)
{
this.pendingReferenceList = referenceList;
this.pendingDecryptionToken = wrappedKeyToken;
}
protected override ReferenceList ReadReferenceListCore(XmlDictionaryReader reader)
{
ReferenceList referenceList = new ReferenceList();
referenceList.ReadFrom(reader);
return referenceList;
}
protected override EncryptedData ReadSecurityHeaderEncryptedItem(XmlDictionaryReader reader, bool readXmlreferenceKeyInfoClause)
{
EncryptedData encryptedData = new EncryptedData();
encryptedData.ShouldReadXmlReferenceKeyInfoClause = readXmlreferenceKeyInfoClause;
encryptedData.SecurityTokenSerializer = this.StandardsManager.SecurityTokenSerializer;
encryptedData.ReadFrom(reader);
return encryptedData;
}
protected override SignedXml ReadSignatureCore(XmlDictionaryReader signatureReader)
{
SignedXml signedXml = new SignedXml(ServiceModelDictionaryManager.Instance, this.StandardsManager.SecurityTokenSerializer);
signedXml.Signature.SignedInfo.ResourcePool = this.ResourcePool;
signedXml.ReadFrom(signatureReader);
return signedXml;
}
protected static bool TryResolveKeyIdentifier(
SecurityKeyIdentifier keyIdentifier, SecurityTokenResolver resolver, bool isFromSignature, out SecurityToken token)
{
if (keyIdentifier == null)
{
if (isFromSignature)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(SR.GetString(SR.NoKeyInfoInSignatureToFindVerificationToken)));
}
else
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(SR.GetString(SR.NoKeyInfoInEncryptedItemToFindDecryptingToken)));
}
}
return resolver.TryResolveToken(keyIdentifier, out token);
}
protected static SecurityToken ResolveKeyIdentifier(SecurityKeyIdentifier keyIdentifier, SecurityTokenResolver resolver, bool isFromSignature)
{
SecurityToken token;
if (!TryResolveKeyIdentifier(keyIdentifier, resolver, isFromSignature, out token))
{
if (isFromSignature)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(
SR.GetString(SR.UnableToResolveKeyInfoForVerifyingSignature, keyIdentifier, resolver)));
}
else
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(
SR.GetString(SR.UnableToResolveKeyInfoForDecryption, keyIdentifier, resolver)));
}
}
return token;
}
SecurityToken ResolveSignatureToken(SecurityKeyIdentifier keyIdentifier, SecurityTokenResolver resolver, bool isPrimarySignature)
{
SecurityToken token;
TryResolveKeyIdentifier(keyIdentifier, resolver, true, out token);
if (token == null && !isPrimarySignature)
{
// check if there is a rsa key token authenticator
if (keyIdentifier.Count == 1)
{
RsaKeyIdentifierClause rsaClause;
if (keyIdentifier.TryFind<RsaKeyIdentifierClause>(out rsaClause))
{
RsaSecurityTokenAuthenticator rsaAuthenticator = FindAllowedAuthenticator<RsaSecurityTokenAuthenticator>(false);
if (rsaAuthenticator != null)
{
token = new RsaSecurityToken(rsaClause.Rsa);
ReadOnlyCollection<IAuthorizationPolicy> authorizationPolicies = rsaAuthenticator.ValidateToken(token);
SupportingTokenAuthenticatorSpecification spec;
TokenTracker rsaTracker = GetSupportingTokenTracker(rsaAuthenticator, out spec);
if (rsaTracker == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new MessageSecurityException(SR.GetString(SR.UnknownTokenAuthenticatorUsedInTokenProcessing, rsaAuthenticator)));
}
rsaTracker.RecordToken(token);
SecurityTokenAuthorizationPoliciesMapping.Add(token, authorizationPolicies);
}
}
}
}
if (token == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(
SR.GetString(SR.UnableToResolveKeyInfoForVerifyingSignature, keyIdentifier, resolver)));
}
return token;
}
protected override void ReadSecurityTokenReference(XmlDictionaryReader reader)
{
string strId = reader.GetAttribute(XD.UtilityDictionary.IdAttribute, XD.UtilityDictionary.Namespace);
SecurityKeyIdentifierClause strClause = this.StandardsManager.SecurityTokenSerializer.ReadKeyIdentifierClause(reader);
if (String.IsNullOrEmpty(strClause.Id))
{
strClause.Id = strId;
}
if (!String.IsNullOrEmpty(strClause.Id))
{
this.ElementManager.AppendSecurityTokenReference(strClause, strClause.Id);
}
}
bool HasPendingDecryptionItem()
{
return this.pendingReferenceList != null && this.pendingReferenceList.DataReferenceCount > 0;
}
protected override bool TryDeleteReferenceListEntry(string id)
{
return this.pendingReferenceList != null && this.pendingReferenceList.TryRemoveReferredId(id);
}
protected override void EnsureDecryptionComplete()
{
if (this.earlyDecryptedDataReferences != null)
{
for (int i = 0; i < this.earlyDecryptedDataReferences.Count; i++)
{
if (!TryDeleteReferenceListEntry(this.earlyDecryptedDataReferences[i]))
{
throw TraceUtility.ThrowHelperError(new MessageSecurityException(SR.GetString(SR.UnexpectedEncryptedElementInSecurityHeader)), this.Message);
}
}
}
if (HasPendingDecryptionItem())
{
throw TraceUtility.ThrowHelperError(
new MessageSecurityException(SR.GetString(SR.UnableToResolveDataReference, this.pendingReferenceList.GetReferredId(0))), this.Message);
}
}
protected override void OnDecryptionOfSecurityHeaderItemRequiringReferenceListEntry(string id)
{
if (!TryDeleteReferenceListEntry(id))
{
if (this.earlyDecryptedDataReferences == null)
{
this.earlyDecryptedDataReferences = new List<string>(4);
}
this.earlyDecryptedDataReferences.Add(id);
}
}
protected override SecurityToken VerifySignature(SignedXml signedXml, bool isPrimarySignature,
SecurityHeaderTokenResolver resolver, object signatureTarget, string id)
{
if (TD.SignatureVerificationStartIsEnabled())
{
TD.SignatureVerificationStart(this.EventTraceActivity);
}
SecurityToken token = ResolveSignatureToken(signedXml.Signature.KeyIdentifier, resolver, isPrimarySignature);
if (isPrimarySignature)
{
RecordSignatureToken(token);
}
ReadOnlyCollection<SecurityKey> keys = token.SecurityKeys;
SecurityKey securityKey = (keys != null && keys.Count > 0) ? keys[0] : null;
if (securityKey == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(
SR.GetString(SR.UnableToCreateICryptoFromTokenForSignatureVerification, token)));
}
this.AlgorithmSuite.EnsureAcceptableSignatureKeySize(securityKey, token);
this.AlgorithmSuite.EnsureAcceptableSignatureAlgorithm(securityKey, signedXml.Signature.SignedInfo.SignatureMethod);
signedXml.StartSignatureVerification(securityKey);
StandardSignedInfo signedInfo = (StandardSignedInfo)signedXml.Signature.SignedInfo;
ValidateDigestsOfTargetsInSecurityHeader(signedInfo, this.Timestamp, isPrimarySignature, signatureTarget, id);
if (!isPrimarySignature)
{
if ((!this.RequireMessageProtection) && (securityKey is AsymmetricSecurityKey) && (this.Version.Addressing != AddressingVersion.None))
{
// For Transport Security using Asymmetric Keys verify that
// the 'To' header is signed.
int headerIndex = this.Message.Headers.FindHeader(XD.AddressingDictionary.To.Value, this.Message.Version.Addressing.Namespace);
if (headerIndex == -1)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(SR.GetString(SR.TransportSecuredMessageMissingToHeader)));
XmlDictionaryReader toHeaderReader = this.Message.Headers.GetReaderAtHeader(headerIndex);
id = toHeaderReader.GetAttribute(XD.UtilityDictionary.IdAttribute, XD.UtilityDictionary.Namespace);
if (id == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(SR.GetString(SR.UnsignedToHeaderInTransportSecuredMessage)));
signedXml.EnsureDigestValidity(id, toHeaderReader);
}
signedXml.CompleteSignatureVerification();
return token;
}
this.pendingSignature = signedXml;
if (TD.SignatureVerificationSuccessIsEnabled())
{
TD.SignatureVerificationSuccess(this.EventTraceActivity);
}
return token;
}
void ValidateDigestsOfTargetsInSecurityHeader(StandardSignedInfo signedInfo, SecurityTimestamp timestamp, bool isPrimarySignature, object signatureTarget, string id)
{
Fx.Assert(!isPrimarySignature || (isPrimarySignature && (signatureTarget == null)), "For primary signature we try to validate all the references.");
for (int i = 0; i < signedInfo.ReferenceCount; i++)
{
Reference reference = signedInfo[i];
this.AlgorithmSuite.EnsureAcceptableDigestAlgorithm(reference.DigestMethod);
string referredId = reference.ExtractReferredId();
if (isPrimarySignature || (id == referredId))
{
if (timestamp != null && timestamp.Id == referredId && !reference.TransformChain.NeedsInclusiveContext &&
timestamp.DigestAlgorithm == reference.DigestMethod && timestamp.GetDigest() != null)
{
reference.EnsureDigestValidity(referredId, timestamp.GetDigest());
this.ElementManager.SetTimestampSigned(referredId);
}
else
{
if (signatureTarget != null)
reference.EnsureDigestValidity(id, signatureTarget);
else
{
int tokenIndex = -1;
XmlDictionaryReader reader = null;
if (reference.IsStrTranform())
{
if (this.ElementManager.TryGetTokenElementIndexFromStrId(referredId, out tokenIndex))
{
ReceiveSecurityHeaderEntry entry;
this.ElementManager.GetElementEntry(tokenIndex, out entry);
bool isSignedToken = (entry.bindingMode == ReceiveSecurityHeaderBindingModes.Signed)
|| (entry.bindingMode == ReceiveSecurityHeaderBindingModes.SignedEndorsing);
// This means it is a protected(signed)primary token.
if (!this.ElementManager.IsPrimaryTokenSigned)
{
this.ElementManager.IsPrimaryTokenSigned = entry.bindingMode == ReceiveSecurityHeaderBindingModes.Primary &&
entry.elementCategory == ReceiveSecurityHeaderElementCategory.Token;
}
this.ElementManager.SetSigned(tokenIndex);
// We pass true if it is a signed supporting token, signed primary token or a SignedEndorsing token. We pass false if it is a SignedEncrypted Token.
reader = this.ElementManager.GetReader(tokenIndex, isSignedToken);
}
}
else
reader = this.ElementManager.GetSignatureVerificationReader(referredId, this.EncryptBeforeSignMode);
if (reader != null)
{
reference.EnsureDigestValidity(referredId, reader);
reader.Close();
}
}
}
if (!isPrimarySignature)
{
// We were given an id to verify and we have verified it. So just break out
// of the loop.
break;
}
}
}
// This check makes sure that if RequireSignedPrimaryToken is true (ProtectTokens is enabled on sbe) then the incoming message
// should have the primary signature over the primary(signing)token.
if (isPrimarySignature && this.RequireSignedPrimaryToken && !this.ElementManager.IsPrimaryTokenSigned)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(SR.GetString(SR.SupportingTokenIsNotSigned, new IssuedSecurityTokenParameters())));
}
// NOTE: On both client and server side, WCF quietly consumes protected tokens even if protect token is not enabled on sbe.
// To change this behaviour add another check below and throw appropriate exception message.
}
void VerifySoapAttributeMatchForHeader(MessageHeaderInfo info, MessagePartSpecification signatureParts, XmlDictionaryReader reader)
{
if (!signatureParts.IsHeaderIncluded(info.Name, info.Namespace))
{
return;
}
EnvelopeVersion currentVersion = this.Version.Envelope;
EnvelopeVersion otherVersion = currentVersion == EnvelopeVersion.Soap11 ? EnvelopeVersion.Soap12 : EnvelopeVersion.Soap11;
bool presentInCurrentVersion;
bool presentInOtherVersion;
presentInCurrentVersion = null != reader.GetAttribute(XD.MessageDictionary.MustUnderstand, currentVersion.DictionaryNamespace);
presentInOtherVersion = null != reader.GetAttribute(XD.MessageDictionary.MustUnderstand, otherVersion.DictionaryNamespace);
if (presentInOtherVersion && !presentInCurrentVersion)
{
throw TraceUtility.ThrowHelperError(
new MessageSecurityException(SR.GetString(
SR.InvalidAttributeInSignedHeader, info.Name, info.Namespace,
XD.MessageDictionary.MustUnderstand, otherVersion.DictionaryNamespace,
XD.MessageDictionary.MustUnderstand, currentVersion.DictionaryNamespace)), this.SecurityVerifiedMessage);
}
presentInCurrentVersion = null != reader.GetAttribute(currentVersion.DictionaryActor, currentVersion.DictionaryNamespace);
presentInOtherVersion = null != reader.GetAttribute(otherVersion.DictionaryActor, otherVersion.DictionaryNamespace);
if (presentInOtherVersion && !presentInCurrentVersion)
{
throw TraceUtility.ThrowHelperError(
new MessageSecurityException(SR.GetString(
SR.InvalidAttributeInSignedHeader, info.Name, info.Namespace,
otherVersion.DictionaryActor, otherVersion.DictionaryNamespace,
currentVersion.DictionaryActor, currentVersion.DictionaryNamespace)), this.SecurityVerifiedMessage);
}
}
}
}
| |
//---------------------------------------------------------------------------
//
// <copyright file="ClientEventManager.cs" company="Microsoft">
// Copyright (C) Microsoft Corporation. All rights reserved.
// </copyright>
//
//
// Description: Manages the listeners for one accessibility aid or test application.
//
// History:
// 06/17/2003 : BrendanM Ported to WCP
//
//---------------------------------------------------------------------------
using System.Windows;
using System.Collections;
using System.Diagnostics;
using System.Windows.Automation;
using System.Windows.Automation.Provider;
using MS.Win32;
using System;
// PRESHARP: In order to avoid generating warnings about unkown message numbers and unknown pragmas.
#pragma warning disable 1634, 1691
namespace MS.Internal.Automation
{
// Manages the listeners for one accessibility aid or test application. Locking
// is used in all public methods to allow for multiple threads in a client process.
internal static class ClientEventManager
{
//------------------------------------------------------
//
// Constructors
//
//------------------------------------------------------
#region Constructors
// Static class, no ctor
#endregion Constructors
//------------------------------------------------------
//
// Internal Methods
//
//------------------------------------------------------
#region Internal Methods
// AddFocusListener - Adds a focus listener for this client.
internal static void AddFocusListener(Delegate eventCallback, EventListener l)
{
AddRootListener(Tracker.Focus, eventCallback, l);
}
// RemoveFocusListener - Removes a focus change listener from this client
// and notifies the UIAccess server
internal static void RemoveFocusListener(Delegate eventCallback)
{
RemoveRootListener(AutomationElement.AutomationFocusChangedEvent, Tracker.Focus, eventCallback);
}
// AddListener - Adds a listener for this client and notifies the UIA server. All event
// handler additions call through to this method.
internal static void AddListener(AutomationElement rawEl, Delegate eventCallback, EventListener l)
{
lock (_classLock)
{
// If we are adding a listener then a proxy could be created as a result of an event so make sure they are loaded
ProxyManager.LoadDefaultProxies();
if (_listeners == null)
{
// enough space for 16 AddXxxListeners (100 bytes)
_listeners = new ArrayList(16);
}
// Start the callback queue that gets us off the server's
// UI thread when events arrive cross-proc
CheckStartCallbackQueueing();
//
// The framework handles some events on behalf of providers; do those here
//
// If listening for BoundingRectangleProperty then may need to start listening on the
// client-side for LocationChange WinEvent (only use *one* BoundingRectTracker instance).
if (_winEventTrackers[(int)Tracker.BoundingRect] == null && HasProperty(AutomationElement.BoundingRectangleProperty, l.Properties))
{
//
AddWinEventListener(Tracker.BoundingRect, new BoundingRectTracker());
}
// Start listening for menu event in order to raise MenuOpened/Closed events.
if ( _winEventTrackers [(int)Tracker.MenuOpenedOrClosed] == null && (l.EventId == AutomationElement.MenuOpenedEvent || l.EventId == AutomationElement.MenuClosedEvent) )
{
AddWinEventListener( Tracker.MenuOpenedOrClosed, new MenuTracker( new MenuHandler( OnMenuEvent ) ) );
}
// Begin watching for hwnd open/close/show/hide so can advise of what events are being listened for.
// Only advise UI contexts of events being added if the event might be raised by a provider.
// TopLevelWindow event is raised by UI Automation framework so no need to track new UI.
//
if (_winEventTrackers[(int)Tracker.WindowShowOrOpen] == null )
{
AddWinEventListener( Tracker.WindowShowOrOpen, new WindowShowOrOpenTracker( new WindowShowOrOpenHandler( OnWindowShowOrOpen ) ) );
AddWinEventListener( Tracker.WindowHideOrClose, new WindowHideOrCloseTracker( new WindowHideOrCloseHandler( OnWindowHideOrClose ) ) );
}
// If listening for WindowInteractionStateProperty then may need to start listening on the
// client-side for ObjectStateChange WinEvent.
if (_winEventTrackers[(int)Tracker.WindowInteractionState] == null && HasProperty(WindowPattern.WindowInteractionStateProperty, l.Properties))
{
AddWinEventListener(Tracker.WindowInteractionState, new WindowInteractionStateTracker());
}
// If listening for WindowVisualStateProperty then may need to start listening on the
// client-side for ObjectLocationChange WinEvent.
if (_winEventTrackers[(int)Tracker.WindowVisualState] == null && HasProperty(WindowPattern.WindowVisualStateProperty, l.Properties))
{
AddWinEventListener(Tracker.WindowVisualState, new WindowVisualStateTracker());
}
// Wrap and store this record on the client...
EventListenerClientSide ec = new EventListenerClientSide(rawEl, eventCallback, l);
_listeners.Add(ec);
// Only advise UI contexts of events being added if the event might be raised by
// a provider. TopLevelWindow event is raised by UI Automation framework.
if (ShouldAdviseProviders( l.EventId ))
{
// .. then let the server know about this listener
ec.EventHandle = UiaCoreApi.UiaAddEvent(rawEl.RawNode, l.EventId.Id, ec.CallbackDelegate, l.TreeScope, PropertyArrayToIntArray(l.Properties), l.CacheRequest);
}
}
}
private static int[] PropertyArrayToIntArray(AutomationProperty[] properties)
{
if (properties == null)
return null;
int[] propertiesAsInts = new int[properties.Length];
for (int i = 0; i < properties.Length; i++)
{
propertiesAsInts[i] = properties[i].Id;
}
return propertiesAsInts;
}
// RemoveListener - Removes a listener from this client and notifies the UIAutomation server-side
internal static void RemoveListener( AutomationEvent eventId, AutomationElement el, Delegate eventCallback )
{
lock( _classLock )
{
if( _listeners != null )
{
bool boundingRectListeners = false; // if not removing BoundingRect listeners no need to do check below
bool menuListeners = false; // if not removing MenuOpenedOrClosed listeners no need to do check below
bool windowInteracationListeners = false; // if not removing WindowsIntercation listeners no need to do check below
bool windowVisualListeners = false; // if not removing WindowsVisual listeners no need to do check below
for (int i = _listeners.Count - 1; i >= 0; i--)
{
EventListenerClientSide ec = (EventListenerClientSide)_listeners[i];
if( ec.IsListeningFor( eventId, el, eventCallback ) )
{
EventListener l = ec.EventListener;
// Only advise UI contexts of events being removed if the event might be raised by
// a provider. TopLevelWindow event is raised by UI Automation framework.
if ( ShouldAdviseProviders(eventId) )
{
// Notify the server-side that this event is no longer interesting
try
{
ec.EventHandle.Dispose(); // Calls UiaCoreApi.UiaRemoveEvent
}
// PRESHARP: Warning - Catch statements should not have empty bodies
#pragma warning disable 6502
catch (ElementNotAvailableException)
{
// the element is gone already; continue on and remove the listener
}
#pragma warning restore 6502
finally
{
ec.Dispose();
}
}
// before removing, check if this delegate was listening for the below events
// and see if we can stop clientside WinEvent trackers.
if (HasProperty(AutomationElement.BoundingRectangleProperty, l.Properties))
{
boundingRectListeners = true;
}
if( eventId == AutomationElement.MenuOpenedEvent || eventId == AutomationElement.MenuClosedEvent )
{
menuListeners = true;
}
if (HasProperty(WindowPattern.WindowInteractionStateProperty, l.Properties))
{
windowInteracationListeners = true;
}
if (HasProperty(WindowPattern.WindowVisualStateProperty, l.Properties))
{
windowVisualListeners = true;
}
// delete this one
_listeners.RemoveAt( i );
}
}
// Check listeners bools to see if clientside listeners can be removed
if (boundingRectListeners)
{
RemovePropertyTracker(AutomationElement.BoundingRectangleProperty, Tracker.BoundingRect);
}
if (menuListeners)
{
RemoveMenuListeners();
}
if (windowInteracationListeners)
{
RemovePropertyTracker(WindowPattern.WindowInteractionStateProperty, Tracker.WindowInteractionState);
}
if (windowVisualListeners)
{
RemovePropertyTracker(WindowPattern.WindowVisualStateProperty, Tracker.WindowVisualState);
}
// See if we can cleanup completely
if (_listeners.Count == 0)
{
// as long as OnWindowShowOrOpen is static can just use new here and get same object instance
// (if there's no WindowShowOrOpen listener, this method just returns)
RemoveWinEventListener(Tracker.WindowShowOrOpen, new WindowShowOrOpenHandler(OnWindowShowOrOpen));
RemoveWinEventListener( Tracker.WindowHideOrClose, new WindowHideOrCloseHandler( OnWindowHideOrClose ) );
_listeners = null;
}
}
}
}
private static void RemovePropertyTracker(AutomationProperty property, Tracker tracker)
{
bool foundListener = false; // assume none
foreach (EventListenerClientSide l in _listeners)
{
if (HasProperty(property, l.EventListener.Properties))
{
foundListener = true; // delegate is still interested so can't
break; // stop the WinEvent tracking
}
}
if (!foundListener)
{
RemoveWinEventListener(tracker, null);
}
}
private static void RemoveMenuListeners()
{
bool menuListeners = false; // assume none
foreach (EventListenerClientSide l in _listeners)
{
if (l.EventListener.EventId == AutomationElement.MenuOpenedEvent || l.EventListener.EventId == AutomationElement.MenuClosedEvent)
{
menuListeners = true; // delegate is still interested so can't
break; // stop the WinEvent tracking
}
}
if (!menuListeners)
{
// as long as OnMenuEvent is static can just use new here and get same object instance
RemoveWinEventListener(Tracker.MenuOpenedOrClosed, new MenuHandler(OnMenuEvent));
}
}
// RemoveAllListeners - Removes all listeners from this client and notifies the
// UIAccess server
internal static void RemoveAllListeners()
{
lock (_classLock)
{
if (_listeners == null)
return;
// Stop all WinEvent tracking
StopWinEventTracking();
// Must remove from back to front when calling RemoveAt because ArrayList
// elements are compressed after each RemoveAt.
for (int i = _listeners.Count - 1; i >= 0; i--)
{
EventListenerClientSide ec = (EventListenerClientSide)_listeners[i];
// Notify the server-side UIAccess that this event is no longer interesting
EventListener l = ec.EventListener;
// Only advise UI contexts of events being removed if the event might be raised by
// a provider. TopLevelWindow event is raised by UI Automation framework.
if ( ShouldAdviseProviders(l.EventId) )
{
ec.EventHandle.Dispose(); // Calls RemoveEvent
}
// delete this one
_listeners.RemoveAt(i);
}
_listeners = null;
CheckStopCallbackQueueing();
}
}
#endregion Internal Methods
//------------------------------------------------------
//
// Internal Properties
//
//------------------------------------------------------
#region Internal Properties
// return the queue class instance
internal static QueueProcessor CBQ
{
get
{
return _callbackQueue;
}
}
#endregion Internal Properties
//------------------------------------------------------
//
// Private Methods
//
//------------------------------------------------------
#region Private Methods
// check queue is started, or start if necessary (always called w/in a lock)
private static void CheckStartCallbackQueueing()
{
if (!_isBkgrdThreadRunning)
{
_isBkgrdThreadRunning = true;
_callbackQueue = new QueueProcessor();
_callbackQueue.StartOnThread();
}
}
// check if queue is still needed, stop if necessary (always called w/in a lock)
private static void CheckStopCallbackQueueing()
{
// anything to stop?
if (!_isBkgrdThreadRunning)
return;
// if there are listeners then can't stop
if (_listeners != null)
return;
// Are any WinEvents currently being tracked for this client?
foreach (WinEventWrap eventWrapper in _winEventTrackers)
{
if (eventWrapper != null)
{
return;
}
}
// OK to stop the queue now
_isBkgrdThreadRunning = false;
_callbackQueue.PostQuit();
// Intentionally not setting _callbackQueue null here; don't want to mess with it from this thread.
}
// StopWinEventTracking is called when we just want to quit (RemoveAllListeners)
private static void StopWinEventTracking()
{
int i;
for (i=0; i<(int)Tracker.NumEventTrackers; i++)
{
WinEventWrap eventWrapper = _winEventTrackers[i];
if (eventWrapper != null)
{
eventWrapper.StopListening();
_winEventTrackers[i] = null;
}
}
}
// Raise events for rawEl
internal static void RaiseEventInThisClientOnly(AutomationEvent eventId, AutomationElement rawEl, AutomationEventArgs e)
{
// This version of RaiseEventInThisClientOnly can be called with a local (proxied) or remote (native)AutomationElement
lock (_classLock)
{
if ( _listeners == null )
return;
AutomationElement el = rawEl;
foreach (EventListenerClientSide listener in _listeners)
{
// Is this event a type this listener is interested in?
if (listener.EventListener.EventId == eventId)
{
// Did this event happen on an element this listener is interested in?
if (rawEl == null || listener.WithinScope( rawEl ))
{
UiaCoreApi.UiaCacheRequest cacheRequest = listener.EventListener.CacheRequest;
CBQ.PostWorkItem(new ClientSideQueueItem(listener.ClientCallback, el, cacheRequest, e));
}
}
}
}
}
// Raise events for the element that has RuntimeId == rid (special case for events where the element is no longer available)
internal static void RaiseEventInThisClientOnly( AutomationEvent eventId, int [] rid, AutomationEventArgs e)
{
// This version of RaiseEventInThisClientOnly can be called with a local (proxied) or remote (native)AutomationElement
lock ( _classLock )
{
if ( _listeners == null )
return;
foreach ( EventListenerClientSide listener in _listeners )
{
// Is this event a type this listener is interested in?
if ( listener.EventListener.EventId == eventId )
{
// Did this event happen on an element this listener is interested in?
if ( listener.WithinScope( rid ) )
{
CBQ.PostWorkItem(new ClientSideQueueItem(listener.ClientCallback, null, null, e));
}
}
}
}
}
// GetNewRootTracker - Returns a new WinEvent wrapped object for events that are
// always based on the RootElement (e.g. AutomationFocusChanged or TopWindow events)
private static WinEventWrap GetNewRootTracker(Tracker idx)
{
if (idx == Tracker.Focus)
{
return new FocusTracker();
}
Debug.Assert(false, "GetNewRootTracker internal error: Unexpected Tracker value!");
return null;
}
// AddRootListener - Add a listener for an event whose reference is always the
// root and scope is all elements
private static void AddRootListener(Tracker idx, Delegate eventCallback, EventListener l)
{
lock ( _classLock )
{
// Add this listener to client-side store of listeners and give the server
// a chance to enable accessibility for this event
AddListener( AutomationElement.RootElement, eventCallback, l );
// Track WinEvents
WinEventWrap eventWrapper = _winEventTrackers[(int)idx];
if ( eventWrapper == null )
{
// First time create a WinEvent tracker and start listening
AddWinEventListener( idx, GetNewRootTracker( idx ) );
}
else
{
// Subsequent times just add the callback to the existing WinEvent
eventWrapper.AddCallback( eventCallback );
}
}
}
// RemoveRootListener - Remove a listener for an event whose reference is always
// the root and scope is all elements
private static void RemoveRootListener(AutomationEvent eventId, Tracker idx, Delegate eventCallback)
{
lock (_classLock)
{
RemoveListener(eventId, AutomationElement.RootElement, eventCallback);
RemoveWinEventListener(idx, eventCallback);
}
}
// AddWinEventListener - add an event callback for a global listener
private static void AddWinEventListener(Tracker idx, WinEventWrap eventWrapper)
{
// make sure we can queue items
CheckStartCallbackQueueing();
_winEventTrackers[(int)idx] = eventWrapper;
_callbackQueue.PostSyncWorkItem(new WinEventQueueItem(eventWrapper, WinEventQueueItem.StartListening));
}
// RemoveWinEventListener - remove an event callback for a global listener
private static void RemoveWinEventListener(Tracker idx, Delegate eventCallback)
{
WinEventWrap eventWrapper = _winEventTrackers[(int)idx];
if (eventWrapper == null)
return;
bool fRemovedLastListener = eventWrapper.RemoveCallback(eventCallback);
if (fRemovedLastListener)
{
_callbackQueue.PostSyncWorkItem(new WinEventQueueItem(eventWrapper, WinEventQueueItem.StopListening));
_winEventTrackers[(int)idx] = null;
CheckStopCallbackQueueing();
}
}
// HasProperty - helper to check for a property in an AutomationProperty array
private static bool HasProperty(AutomationProperty p, AutomationProperty [] properties)
{
if (properties == null)
return false;
foreach (AutomationProperty p1 in properties)
{
if (p1 == p)
{
return true;
}
}
return false;
}
// OnWindowHideOrClose - Called by the WindowHideOrCloseTracker class when UI is hidden or destroyed
private static void OnWindowHideOrClose( IntPtr hwnd, AutomationElement rawEl, int [] runtimeId )
{
bool doWindowClosedEvent = false;
bool doStructureChangedEvent = false;
lock ( _classLock )
{
if (_listeners != null)
{
// if an hwnd is hidden or closed remove event listeners for the window's provider
for (int i = 0; i < _listeners.Count; i++)
{
EventListenerClientSide ec = (EventListenerClientSide)_listeners[i];
EventListener l = ec.EventListener;
if ( l.EventId == WindowPattern.WindowClosedEvent )
doWindowClosedEvent = true;
if ( l.EventId == AutomationElement.StructureChangedEvent )
doStructureChangedEvent = true;
// Only advise UI contexts if the provider still exists
// (but keep looking to see if need to do a WindowClosedEvent)
if (rawEl == null)
continue;
// Only advise UI contexts if the provider might raise that event.
if (!ShouldAdviseProviders(l.EventId))
continue;
// Only advise UI contexts if the element is w/in scope of the reference element
if (!ec.WithinScope(rawEl))
continue;
// Notify the server-side that this event is no longer interesting
UiaCoreApi.UiaEventRemoveWindow(ec.EventHandle, hwnd);
}
}
}
// Piggy-back on the listener for Windows hiding or closing to raise WindowClosed and StructureChanged events.
// When the hwnd behind rawEl is being destroyed, it can't be determined that rawEl once had the
// WindowPattern interface. Therefore raise an event for any window close.
if ( doWindowClosedEvent )
{
// When the hwnd is just hidden, rawEl will not be null, so can test if this would support WindowPattern
// and throw this event away if the window doesn't support that CP
if ( rawEl != null && !HwndProxyElementProvider.IsWindowPatternWindow( NativeMethods.HWND.Cast( hwnd ) ) )
return;
// Go ahead and raise a client-side only WindowClosedEvent (if anyone is listening)
WindowClosedEventArgs e = new WindowClosedEventArgs( runtimeId );
RaiseEventInThisClientOnly(WindowPattern.WindowClosedEvent, runtimeId, e);
}
if ( doStructureChangedEvent )
{
// Raise an event for structure changed. This element has essentially gone away so there isn't an
// opportunity to do filtering here. So, just like WindowClosed, this event will be very noisy.
StructureChangedEventArgs e = new StructureChangedEventArgs( StructureChangeType.ChildRemoved, runtimeId );
RaiseEventInThisClientOnly(AutomationElement.StructureChangedEvent, runtimeId, e);
}
}
// OnWindowShowOrOpen - Called by the WindowShowOrOpenTracker class when UI is shown or created
private static void OnWindowShowOrOpen( IntPtr hwnd, AutomationElement rawEl )
{
bool doWindowOpenedEvent = false;
bool doStructureChangedEvent = false;
lock ( _classLock )
{
if (_listeners != null)
{
// if rawEl is w/in the scope of any listeners then register for events in the new UI
for (int i = 0; i < _listeners.Count; i++)
{
EventListenerClientSide ec = (EventListenerClientSide)_listeners[i];
EventListener l = ec.EventListener;
if ( l.EventId == WindowPattern.WindowOpenedEvent )
doWindowOpenedEvent = true;
if ( l.EventId == AutomationElement.StructureChangedEvent )
doStructureChangedEvent = true;
// Only advise UI contexts if the provider might raise that event.
if (!ShouldAdviseProviders( l.EventId ))
continue;
// Only advise UI contexts if the element is w/in scope of the reference element
if (!ec.WithinScope( rawEl ))
continue;
// Notify the server side
UiaCoreApi.UiaEventAddWindow(ec.EventHandle, hwnd);
}
}
}
// Piggy-back on the listener for Windows hiding or closing to raise WindowClosed and StructureChanged events.
if ( doWindowOpenedEvent )
{
if ( HwndProxyElementProvider.IsWindowPatternWindow( NativeMethods.HWND.Cast( hwnd ) ) )
{
// Go ahead and raise a client-side only WindowOpenedEvent (if anyone is listening)
AutomationEventArgs e = new AutomationEventArgs( WindowPattern.WindowOpenedEvent );
RaiseEventInThisClientOnly( WindowPattern.WindowOpenedEvent, rawEl, e);
}
}
if ( doStructureChangedEvent )
{
// Filter on the control elements. Otherwise, this is extremely noisy. Consider not filtering if there is feedback.
//ControlType ct = (ControlType)rawEl.GetPropertyValue( AutomationElement.ControlTypeProperty );
//if ( ct != null )
{
// Last,raise an event for structure changed
StructureChangedEventArgs e = new StructureChangedEventArgs( StructureChangeType.ChildAdded, rawEl.GetRuntimeId() );
RaiseEventInThisClientOnly(AutomationElement.StructureChangedEvent, rawEl, e);
}
}
}
// OnMenuEvent - Called by MenuTracker class
private static void OnMenuEvent( AutomationElement rawEl, bool menuHasOpened )
{
AutomationEvent eventId = menuHasOpened ? AutomationElement.MenuOpenedEvent : AutomationElement.MenuClosedEvent;
AutomationEventArgs e = new AutomationEventArgs( eventId );
RaiseEventInThisClientOnly(eventId, rawEl, e);
}
private static bool ShouldAdviseProviders( AutomationEvent eventId )
{
foreach (AutomationEvent ev in _doNotShouldAdviseProviders)
{
if (ev == eventId)
return false;
}
return true;
}
#endregion Private Methods
//------------------------------------------------------
//
// Private Fields
//
//------------------------------------------------------
#region Private Fields
// Indices into ClientEventManager._winEventTrackers. How wrapped WinEvents are added
// and removed is common code; using an array makes it easier to add, remove and do
// cleanup on client exit.
private enum Tracker
{
Focus = 0,
WindowShowOrOpen,
WindowHideOrClose,
BoundingRect,
MenuOpenedOrClosed,
WindowInteractionState,
WindowVisualState,
// insert additional indices here...
NumEventTrackers,
}
//
private static AutomationEvent[] _doNotShouldAdviseProviders = new AutomationEvent[] {
WindowPattern.WindowOpenedEvent, WindowPattern.WindowClosedEvent
};
private static WinEventWrap [] _winEventTrackers = new WinEventWrap[(int)Tracker.NumEventTrackers];
private static QueueProcessor _callbackQueue; // callbacks are queued on this class to avoid deadlocks
private static bool _isBkgrdThreadRunning = false; // is there a background thread for queueing and recieving WinEvents?
private static ArrayList _listeners; // data representing events the client is listening for
private static object _classLock = new object(); // use lock object vs typeof(class) for perf reasons
#endregion Private Fields
}
}
| |
namespace au.util.comctl
{
partial class SimpleCalcForm
{
/// <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()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(SimpleCalcForm));
this._txtNumber = new System.Windows.Forms.TextBox();
this._btnClear = new System.Windows.Forms.Button();
this._btnDivide = new System.Windows.Forms.Button();
this._btnMultiply = new System.Windows.Forms.Button();
this._btnSubtract = new System.Windows.Forms.Button();
this._btn7 = new System.Windows.Forms.Button();
this._btn8 = new System.Windows.Forms.Button();
this._btn9 = new System.Windows.Forms.Button();
this._btnAdd = new System.Windows.Forms.Button();
this._btn4 = new System.Windows.Forms.Button();
this._btn5 = new System.Windows.Forms.Button();
this._btn6 = new System.Windows.Forms.Button();
this._btn1 = new System.Windows.Forms.Button();
this._btn2 = new System.Windows.Forms.Button();
this._btn3 = new System.Windows.Forms.Button();
this._btnEquals = new System.Windows.Forms.Button();
this._btn0 = new System.Windows.Forms.Button();
this._btnDecimal = new System.Windows.Forms.Button();
this._btnOK = new System.Windows.Forms.Button();
this._btnCancel = new System.Windows.Forms.Button();
this._picCalc = new System.Windows.Forms.PictureBox();
((System.ComponentModel.ISupportInitialize)(this._picCalc)).BeginInit();
this.SuspendLayout();
//
// _txtNumber
//
resources.ApplyResources(this._txtNumber, "_txtNumber");
this._txtNumber.Name = "_txtNumber";
this._txtNumber.TabStop = false;
//
// _btnClear
//
resources.ApplyResources(this._btnClear, "_btnClear");
this._btnClear.Name = "_btnClear";
this._btnClear.TabStop = false;
this._btnClear.UseVisualStyleBackColor = true;
this._btnClear.Click += new System.EventHandler(this._btnClear_Click);
//
// _btnDivide
//
resources.ApplyResources(this._btnDivide, "_btnDivide");
this._btnDivide.Name = "_btnDivide";
this._btnDivide.TabStop = false;
this._btnDivide.UseVisualStyleBackColor = true;
this._btnDivide.Click += new System.EventHandler(this._btnDivide_Click);
//
// _btnMultiply
//
resources.ApplyResources(this._btnMultiply, "_btnMultiply");
this._btnMultiply.Name = "_btnMultiply";
this._btnMultiply.TabStop = false;
this._btnMultiply.UseVisualStyleBackColor = true;
this._btnMultiply.Click += new System.EventHandler(this._btnMultiply_Click);
//
// _btnSubtract
//
resources.ApplyResources(this._btnSubtract, "_btnSubtract");
this._btnSubtract.Name = "_btnSubtract";
this._btnSubtract.TabStop = false;
this._btnSubtract.UseVisualStyleBackColor = true;
this._btnSubtract.Click += new System.EventHandler(this._btnSubtract_Click);
//
// _btn7
//
resources.ApplyResources(this._btn7, "_btn7");
this._btn7.Name = "_btn7";
this._btn7.TabStop = false;
this._btn7.UseVisualStyleBackColor = true;
this._btn7.Click += new System.EventHandler(this._btn7_Click);
//
// _btn8
//
resources.ApplyResources(this._btn8, "_btn8");
this._btn8.Name = "_btn8";
this._btn8.TabStop = false;
this._btn8.UseVisualStyleBackColor = true;
this._btn8.Click += new System.EventHandler(this._btn8_Click);
//
// _btn9
//
resources.ApplyResources(this._btn9, "_btn9");
this._btn9.Name = "_btn9";
this._btn9.TabStop = false;
this._btn9.UseVisualStyleBackColor = true;
this._btn9.Click += new System.EventHandler(this._btn9_Click);
//
// _btnAdd
//
resources.ApplyResources(this._btnAdd, "_btnAdd");
this._btnAdd.Name = "_btnAdd";
this._btnAdd.TabStop = false;
this._btnAdd.UseVisualStyleBackColor = true;
this._btnAdd.Click += new System.EventHandler(this._btnAdd_Click);
//
// _btn4
//
resources.ApplyResources(this._btn4, "_btn4");
this._btn4.Name = "_btn4";
this._btn4.TabStop = false;
this._btn4.UseVisualStyleBackColor = true;
this._btn4.Click += new System.EventHandler(this._btn4_Click);
//
// _btn5
//
resources.ApplyResources(this._btn5, "_btn5");
this._btn5.Name = "_btn5";
this._btn5.TabStop = false;
this._btn5.UseVisualStyleBackColor = true;
this._btn5.Click += new System.EventHandler(this._btn5_Click);
//
// _btn6
//
resources.ApplyResources(this._btn6, "_btn6");
this._btn6.Name = "_btn6";
this._btn6.TabStop = false;
this._btn6.UseVisualStyleBackColor = true;
this._btn6.Click += new System.EventHandler(this._btn6_Click);
//
// _btn1
//
resources.ApplyResources(this._btn1, "_btn1");
this._btn1.Name = "_btn1";
this._btn1.TabStop = false;
this._btn1.UseVisualStyleBackColor = true;
this._btn1.Click += new System.EventHandler(this._btn1_Click);
//
// _btn2
//
resources.ApplyResources(this._btn2, "_btn2");
this._btn2.Name = "_btn2";
this._btn2.TabStop = false;
this._btn2.UseVisualStyleBackColor = true;
this._btn2.Click += new System.EventHandler(this._btn2_Click);
//
// _btn3
//
resources.ApplyResources(this._btn3, "_btn3");
this._btn3.Name = "_btn3";
this._btn3.TabStop = false;
this._btn3.UseVisualStyleBackColor = true;
this._btn3.Click += new System.EventHandler(this._btn3_Click);
//
// _btnEquals
//
resources.ApplyResources(this._btnEquals, "_btnEquals");
this._btnEquals.Name = "_btnEquals";
this._btnEquals.TabStop = false;
this._btnEquals.UseVisualStyleBackColor = true;
this._btnEquals.Click += new System.EventHandler(this._btnEquals_Click);
//
// _btn0
//
resources.ApplyResources(this._btn0, "_btn0");
this._btn0.Name = "_btn0";
this._btn0.TabStop = false;
this._btn0.UseVisualStyleBackColor = true;
this._btn0.Click += new System.EventHandler(this._btn0_Click);
//
// _btnDecimal
//
resources.ApplyResources(this._btnDecimal, "_btnDecimal");
this._btnDecimal.Name = "_btnDecimal";
this._btnDecimal.TabStop = false;
this._btnDecimal.UseVisualStyleBackColor = true;
this._btnDecimal.Click += new System.EventHandler(this._btnDecimal_Click);
//
// _btnOK
//
this._btnOK.DialogResult = System.Windows.Forms.DialogResult.OK;
resources.ApplyResources(this._btnOK, "_btnOK");
this._btnOK.Name = "_btnOK";
this._btnOK.UseVisualStyleBackColor = true;
this._btnOK.Click += new System.EventHandler(this._btnOK_Click);
//
// _btnCancel
//
this._btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
resources.ApplyResources(this._btnCancel, "_btnCancel");
this._btnCancel.Name = "_btnCancel";
this._btnCancel.UseVisualStyleBackColor = true;
this._btnCancel.Click += new System.EventHandler(this._btnCancel_Click);
//
// _picCalc
//
this._picCalc.Image = global::au.util.comctl.Properties.Resources.calcLarge;
this._picCalc.InitialImage = global::au.util.comctl.Properties.Resources.calcLarge;
resources.ApplyResources(this._picCalc, "_picCalc");
this._picCalc.Name = "_picCalc";
this._picCalc.TabStop = false;
//
// SimpleCalcForm
//
this.AcceptButton = this._btnEquals;
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Inherit;
resources.ApplyResources(this, "$this");
this.Controls.Add(this._picCalc);
this.Controls.Add(this._btnCancel);
this.Controls.Add(this._btnOK);
this.Controls.Add(this._btnDecimal);
this.Controls.Add(this._btn3);
this.Controls.Add(this._btn2);
this.Controls.Add(this._btn0);
this.Controls.Add(this._btn1);
this.Controls.Add(this._btn6);
this.Controls.Add(this._btn5);
this.Controls.Add(this._btn4);
this.Controls.Add(this._btnEquals);
this.Controls.Add(this._btnAdd);
this.Controls.Add(this._btn9);
this.Controls.Add(this._btn8);
this.Controls.Add(this._btn7);
this.Controls.Add(this._btnSubtract);
this.Controls.Add(this._btnMultiply);
this.Controls.Add(this._btnDivide);
this.Controls.Add(this._btnClear);
this.Controls.Add(this._txtNumber);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.KeyPreview = true;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "SimpleCalcForm";
this.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.SimpleCalcForm_KeyPress);
((System.ComponentModel.ISupportInitialize)(this._picCalc)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.TextBox _txtNumber;
private System.Windows.Forms.Button _btnClear;
private System.Windows.Forms.Button _btnDivide;
private System.Windows.Forms.Button _btnMultiply;
private System.Windows.Forms.Button _btnSubtract;
private System.Windows.Forms.Button _btn7;
private System.Windows.Forms.Button _btn8;
private System.Windows.Forms.Button _btn9;
private System.Windows.Forms.Button _btnAdd;
private System.Windows.Forms.Button _btn4;
private System.Windows.Forms.Button _btn5;
private System.Windows.Forms.Button _btn6;
private System.Windows.Forms.Button _btn1;
private System.Windows.Forms.Button _btn2;
private System.Windows.Forms.Button _btn3;
private System.Windows.Forms.Button _btnEquals;
private System.Windows.Forms.Button _btn0;
private System.Windows.Forms.Button _btnDecimal;
private System.Windows.Forms.Button _btnOK;
private System.Windows.Forms.Button _btnCancel;
private System.Windows.Forms.PictureBox _picCalc;
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System.Threading.Tasks;
using Azure.Core.TestFramework;
using NUnit.Framework;
using Azure.ResourceManager.Dns.Models;
using Azure.ResourceManager.Dns.Tests;
using System.Collections.Generic;
using Azure.Core;
namespace Azure.Management.Dns.Tests
{
[TestFixture]
[Ignore("These tests will work once the conversion to new track 2 is complete")]
public class ScenarioTestsRecordSets : DnsManagementClientBase
{
private string location;
private string resourceGroup;
private string zoneNameForList;
private ChangeTrackingList<AaaaRecord> dummyAaaaRecords;
private ChangeTrackingList<ARecord> dummyARecords;
private ChangeTrackingList<MxRecord> dummyMxRecords;
private ChangeTrackingList<NsRecord> dummyNsRecords;
private ChangeTrackingList<PtrRecord> dummyPtrRecords;
private ChangeTrackingList<SrvRecord> dummySrvRecords;
private ChangeTrackingList<TxtRecord> dummyTxtRecords;
private ChangeTrackingList<CaaRecord> dummyCaaRecords;
private Dictionary<string, string> metadata;
private bool setupRun = false;
public ScenarioTestsRecordSets()
: base(true)
{
resourceGroup = null;
location = "West US";
zoneNameForList = "azure.ameredmond.dns";
dummyAaaaRecords = new ChangeTrackingList<AaaaRecord>();
dummyARecords = new ChangeTrackingList<ARecord>();
dummyMxRecords = new ChangeTrackingList<MxRecord>();
dummyNsRecords = new ChangeTrackingList<NsRecord>();
dummyPtrRecords = new ChangeTrackingList<PtrRecord>();
dummySrvRecords = new ChangeTrackingList<SrvRecord>();
dummyTxtRecords = new ChangeTrackingList<TxtRecord>();
dummyCaaRecords = new ChangeTrackingList<CaaRecord>();
metadata = new Dictionary<string, string>
{
{"tag1", "value1"}
};
}
[SetUp]
public async Task ClearChallengeCacheforRecord()
{
if ((Mode == RecordedTestMode.Record || Mode == RecordedTestMode.Playback) && !setupRun)
{
await InitializeClients();
this.resourceGroup = Recording.GenerateAssetName("Default-Dns-");
await Helper.TryRegisterResourceGroupAsync(ResourceGroupsOperations, this.location, this.resourceGroup);
var aZone = new Zone("Global");
await ZonesOperations.CreateOrUpdateAsync(this.resourceGroup, this.zoneNameForList, aZone);
setupRun = true;
}
else if (setupRun)
{
await initNewRecord();
}
}
[OneTimeTearDown]
public async Task CleanupResourceGroup()
{
await CleanupResourceGroupsAsync();
}
[TestCase]
public async Task DnsCreateARecordDelete()
{
var namespaceName = Recording.GenerateAssetName("sdk-RecordSet");
var aRecords = new ChangeTrackingList<ARecord>
{
new ARecord {Ipv4Address = "127.0.0.1"}
};
var recordName = "a_record";
var testARecordSet = new RecordSet("test_id", recordName, "A", null, this.metadata, 3600, null, null, null, aRecords, this.dummyAaaaRecords, this.dummyMxRecords,
this.dummyNsRecords, this.dummyPtrRecords, this.dummySrvRecords, this.dummyTxtRecords, null, null, this.dummyCaaRecords);
var createRecordSetResponse = await RecordSetsOperations.CreateOrUpdateAsync(this.resourceGroup, zoneNameForList, recordName, RecordType.A, testARecordSet);
Assert.NotNull(createRecordSetResponse);
Assert.AreEqual(createRecordSetResponse.Value.Name, recordName);
var deleteRecordSetResponse = await RecordSetsOperations.DeleteAsync(this.resourceGroup, zoneNameForList, recordName, RecordType.A);
Assert.NotNull(deleteRecordSetResponse);
}
[TestCase]
public async Task DnsMultiRecordCreateDelete()
{
var namespaceName = Recording.GenerateAssetName("sdk-RecordSet");
var AaaaRecords = new ChangeTrackingList<AaaaRecord>
{
new AaaaRecord {Ipv6Address = "1:1:1:1:1:ffff:783f:e6dc"},
new AaaaRecord {Ipv6Address = "0:0:0:0:0:ffff:403:201"},
};
var recordName = "aaaa_multi_record";
var testARecordSet = new RecordSet("test_id", recordName, "Aaaa", null, this.metadata, 3600, null, null, null, this.dummyARecords, AaaaRecords,
this.dummyMxRecords, this.dummyNsRecords, this.dummyPtrRecords, this.dummySrvRecords, this.dummyTxtRecords, null, null, this.dummyCaaRecords);
var createRecordSetResponse = await RecordSetsOperations.CreateOrUpdateAsync(resourceGroup, this.zoneNameForList, recordName, RecordType.Aaaa, testARecordSet);
Assert.NotNull(createRecordSetResponse);
Assert.AreEqual(createRecordSetResponse.Value.Name, recordName);
var deleteRecordSetResponse = await RecordSetsOperations.DeleteAsync(resourceGroup, this.zoneNameForList, recordName, RecordType.A);
Assert.NotNull(deleteRecordSetResponse);
}
[TestCase]
public async Task DnsRecordSetListByResourceGroup()
{
var namespaceName = Recording.GenerateAssetName("sdk-RecordSet");
var aZone = new Zone("Global");
var zoneName = "azure.ameredmondlocal2.dns";
await ZonesOperations.CreateOrUpdateAsync(resourceGroup, zoneName, aZone);
var ipv6Addr = "1:1:1:1:1:ffff:783f:e6dc";
var AaaaRecords = new ChangeTrackingList<AaaaRecord>
{
new AaaaRecord {Ipv6Address = ipv6Addr},
};
var recordName = "aaaa_record";
var testARecordSet = new RecordSet("test_id", recordName, "Aaaa", null, this.metadata, 3600, null, null, null, this.dummyARecords, AaaaRecords, this.dummyMxRecords,
this.dummyNsRecords, this.dummyPtrRecords, this.dummySrvRecords, this.dummyTxtRecords, null, null, this.dummyCaaRecords);
var createRecordSetResponse = await RecordSetsOperations.CreateOrUpdateAsync(this.resourceGroup, zoneName, recordName, RecordType.Aaaa, testARecordSet);
Assert.NotNull(createRecordSetResponse);
var listResponse = RecordSetsOperations.ListAllByDnsZoneAsync(this.resourceGroup, zoneName);
Assert.NotNull(listResponse);
var allResults = await listResponse.ToEnumerableAsync();
Assert.True(allResults.Count == 3); //SOA and NS record should exist
RecordSet aaaaRecord = null;
foreach (var arecord in allResults)
{
if (arecord.Type == "Microsoft.Network/dnszones/AAAA")
{
aaaaRecord = arecord;
break;
}
}
Assert.NotNull(aaaaRecord); ;
Assert.AreEqual(aaaaRecord.AaaaRecords[0].Ipv6Address, ipv6Addr);
var deleteRecordSetResponse = await RecordSetsOperations.DeleteAsync(this.resourceGroup, zoneName, recordName, RecordType.A);
var deleteZoneResponse = await ZonesOperations.StartDeleteAsync(resourceGroup, zoneName);
Assert.NotNull(deleteZoneResponse);
}
[TestCase]
public async Task DnsRecordSetListByResourceGroupTop()
{
var namespaceName = Recording.GenerateAssetName("sdk-RecordSet");
var aZone = new Zone("Global");
var zoneName = "azure.ameredmondlocaltoptest.dns";
await ZonesOperations.CreateOrUpdateAsync(resourceGroup, zoneName, aZone);
//var ipv6Addr = "1:1:1:1:1:ffff:783f:e6dc";
var AaaaRecords = new ChangeTrackingList<AaaaRecord>
{
new AaaaRecord {Ipv6Address = "1:1:1:1:1:ffff:783f:e6dc"},
new AaaaRecord {Ipv6Address = "0:0:0:0:0:ffff:403:201"},
};
var recordName = "aaaa_record666";
var testARecordSet = new RecordSet("test_id1", recordName, "Aaaa", null, this.metadata, 3600, null, null, null, this.dummyARecords, AaaaRecords, this.dummyMxRecords,
this.dummyNsRecords, this.dummyPtrRecords, this.dummySrvRecords, this.dummyTxtRecords, null, null, this.dummyCaaRecords);
var createRecordSetResponse = await RecordSetsOperations.CreateOrUpdateAsync(this.resourceGroup, zoneName, recordName, RecordType.Aaaa, testARecordSet);
Assert.NotNull(createRecordSetResponse);
recordName = "aaaa_record2";
testARecordSet = new RecordSet("test_id2", recordName, "Aaaa", null, this.metadata, 3600, null, null, null, this.dummyARecords, AaaaRecords, this.dummyMxRecords,
this.dummyNsRecords, this.dummyPtrRecords, this.dummySrvRecords, this.dummyTxtRecords, null, null, this.dummyCaaRecords);
createRecordSetResponse = await RecordSetsOperations.CreateOrUpdateAsync(this.resourceGroup, zoneName, recordName, RecordType.Aaaa, testARecordSet);
var listResponse = RecordSetsOperations.ListByDnsZoneAsync(this.resourceGroup, zoneName, 1);
var t = listResponse.AsPages();
var pageResults = await t.ToEnumerableAsync();
Assert.True(pageResults.Count > 1);
var deleteRecordSetResponse = await RecordSetsOperations.DeleteAsync(this.resourceGroup, zoneName, recordName, RecordType.A);
var deleteZoneResponse = await ZonesOperations.StartDeleteAsync(resourceGroup, zoneName);
Assert.NotNull(deleteZoneResponse);
}
[TestCase]
public async Task DnsRecordSetListByResourceGroupNoTop()
{
var namespaceName = Recording.GenerateAssetName("sdk-RecordSet");
var aZone = new Zone("Global");
var zoneName = "azure.ameredmondlocalNotoptest.dns";
await ZonesOperations.CreateOrUpdateAsync(resourceGroup, zoneName, aZone);
var AaaaRecords = new ChangeTrackingList<AaaaRecord>
{
new AaaaRecord {Ipv6Address = "1:1:1:1:1:ffff:783f:e6dc"},
new AaaaRecord {Ipv6Address = "0:0:0:0:0:ffff:403:201"},
};
var recordName = "aaaa_record66";
var testARecordSet = new RecordSet("test_id1", recordName, "Aaaa", null, this.metadata, 3600, null, null, null, this.dummyARecords, AaaaRecords, this.dummyMxRecords,
this.dummyNsRecords, this.dummyPtrRecords, this.dummySrvRecords, this.dummyTxtRecords, null, null, this.dummyCaaRecords);
var createRecordSetResponse = await RecordSetsOperations.CreateOrUpdateAsync(this.resourceGroup, zoneName, recordName, RecordType.Aaaa, testARecordSet);
Assert.NotNull(createRecordSetResponse);
recordName = "aaaa_record2";
testARecordSet = new RecordSet("test_id2", recordName, "Aaaa", null, this.metadata, 3600, null, null, null, this.dummyARecords, AaaaRecords, this.dummyMxRecords,
this.dummyNsRecords, this.dummyPtrRecords, this.dummySrvRecords, this.dummyTxtRecords, null, null, this.dummyCaaRecords);
createRecordSetResponse = await RecordSetsOperations.CreateOrUpdateAsync(this.resourceGroup, zoneName, recordName, RecordType.Aaaa, testARecordSet);
var listResponse = RecordSetsOperations.ListByDnsZoneAsync(this.resourceGroup, zoneName);
var t = listResponse.AsPages();
var pageResults = await t.ToEnumerableAsync();
Assert.True(pageResults.Count == 1);
var deleteRecordSetResponse = await RecordSetsOperations.DeleteAsync(this.resourceGroup, zoneName, recordName, RecordType.A);
var deleteZoneResponse = await ZonesOperations.StartDeleteAsync(resourceGroup, zoneName);
Assert.NotNull(deleteZoneResponse);
}
[TestCase]
public async Task DnsRecordSetUpdateSoa()
{
var namespaceName = Recording.GenerateAssetName("sdk-RecordSet");
var ipv6Addr = "1:1:1:1:1:ffff:783f:e6dc";
var AaaaRecords = new ChangeTrackingList<AaaaRecord>
{
new AaaaRecord {Ipv6Address = ipv6Addr},
};
var recordName = "soa_record";
var testARecordSet = new RecordSet("test_id", recordName, "Aaaa", null, this.metadata, 3600, null, null, null, this.dummyARecords, AaaaRecords, this.dummyMxRecords,
this.dummyNsRecords, this.dummyPtrRecords, this.dummySrvRecords, this.dummyTxtRecords, null, null, this.dummyCaaRecords);
var createRecordSetResponse = await RecordSetsOperations.CreateOrUpdateAsync(resourceGroup, this.zoneNameForList, recordName, RecordType.Aaaa, testARecordSet);
Assert.NotNull(createRecordSetResponse);
var getResponseSoa = await RecordSetsOperations.GetAsync(this.resourceGroup, this.zoneNameForList, "@", RecordType.SOA);
var soaRecord = getResponseSoa.Value;
soaRecord.SoaRecord.ExpireTime = 123;
soaRecord.SoaRecord.MinimumTtl = 1234;
soaRecord.SoaRecord.RefreshTime = 12345;
soaRecord.SoaRecord.RetryTime = 123456;
var updateResponse = await RecordSetsOperations.CreateOrUpdateAsync(this.resourceGroup, this.zoneNameForList, "@", RecordType.SOA, soaRecord);
Assert.True(Helper.AreEqual(updateResponse, soaRecord, ignoreEtag: true));
var deleteRecordSetResponse = await RecordSetsOperations.DeleteAsync(resourceGroup, this.zoneNameForList, recordName, RecordType.A);
}
[TestCase]
public async Task DnsUpdateARecord()
{
var namespaceName = Recording.GenerateAssetName("sdk-RecordSet");
var aRecords = new ChangeTrackingList<ARecord>
{
new ARecord {Ipv4Address = "123.32.1.0"}
};
var recordName = "a_update_record";
var testARecordSet = new RecordSet("test_id", recordName, "A", null, this.metadata, 60, null, null, null, aRecords, this.dummyAaaaRecords, this.dummyMxRecords,
this.dummyNsRecords, this.dummyPtrRecords, this.dummySrvRecords, this.dummyTxtRecords, null, null, this.dummyCaaRecords);
var createRecordSetResponse = await RecordSetsOperations.CreateOrUpdateAsync(resourceGroup, this.zoneNameForList, recordName, RecordType.A, testARecordSet);
Assert.True(Helper.AreEqual(createRecordSetResponse, testARecordSet, ignoreEtag: true));
var getResponseARecord = await RecordSetsOperations.GetAsync(this.resourceGroup, this.zoneNameForList, recordName, RecordType.A);
var aRecord = getResponseARecord.Value;
aRecord.TTL = 120; //update TTL from 60 to 120
var updateResponse = await RecordSetsOperations.CreateOrUpdateAsync(this.resourceGroup, this.zoneNameForList, recordName, RecordType.A, aRecord);
Assert.AreEqual(updateResponse.Value.TTL, 120);
var deleteRecordSetResponse = await RecordSetsOperations.DeleteAsync(resourceGroup, this.zoneNameForList, recordName, RecordType.A);
Assert.NotNull(deleteRecordSetResponse);
}
[TestCase]
public async Task CreateGetMx()
{
var mxRecords = new ChangeTrackingList<MxRecord>
{
new MxRecord {Exchange = "mail1.scsfsm.com", Preference = 1},
new MxRecord {Exchange = "mail2.scsfsm.com", Preference = 2},
};
var recordName = "mx_record";
var testMxRecordSet = new RecordSet("test_id", recordName, "MX", null, this.metadata, 60, null, null, null, this.dummyARecords, this.dummyAaaaRecords, mxRecords,
this.dummyNsRecords, this.dummyPtrRecords, this.dummySrvRecords, this.dummyTxtRecords, null, null, this.dummyCaaRecords);
var createRecordSetResponse = await RecordSetsOperations.CreateOrUpdateAsync(resourceGroup, this.zoneNameForList, recordName, RecordType.MX, testMxRecordSet);
Assert.True(Helper.AreEqual(createRecordSetResponse, testMxRecordSet, ignoreEtag: true));
}
[TestCase]
public async Task CreateGetNs()
{
var nsRecords = new ChangeTrackingList<NsRecord>
{
new NsRecord {Nsdname = "ns1.scsfsm.com"},
new NsRecord {Nsdname = "ns2.scsfsm.com"},
};
var recordName = "ns_record";
var testNsecordSet = new RecordSet("test_id", recordName, "NS", null, this.metadata, 60, null, null, null, this.dummyARecords, this.dummyAaaaRecords, this.dummyMxRecords,
nsRecords, this.dummyPtrRecords, this.dummySrvRecords, this.dummyTxtRecords, null, null, this.dummyCaaRecords);
var createRecordSetResponse = await RecordSetsOperations.CreateOrUpdateAsync(resourceGroup, this.zoneNameForList, recordName, RecordType.NS, testNsecordSet);
Assert.True(Helper.AreEqual(createRecordSetResponse, testNsecordSet, ignoreEtag: true));
}
[TestCase]
public async Task CreateGetPtr()
{
var ptrRecords = new ChangeTrackingList<PtrRecord>
{
new PtrRecord {Ptrdname = "www1.scsfsm.com"},
new PtrRecord {Ptrdname = "www2.scsfsm.com"},
};
var recordName = "ptr_record";
var testPtrRecordSet = new RecordSet("test_id", recordName, "PTR", null, this.metadata, 60, null, null, null, this.dummyARecords, this.dummyAaaaRecords, this.dummyMxRecords,
this.dummyNsRecords, ptrRecords, this.dummySrvRecords, this.dummyTxtRecords, null, null, this.dummyCaaRecords);
var createRecordSetResponse = await RecordSetsOperations.CreateOrUpdateAsync(resourceGroup, this.zoneNameForList, recordName, RecordType.PTR, testPtrRecordSet);
Assert.True(Helper.AreEqual(createRecordSetResponse, testPtrRecordSet, ignoreEtag: true));
}
[TestCase]
public async Task CreateGetSrv()
{
var srvRecords = new ChangeTrackingList<SrvRecord>
{
new SrvRecord
{
Target = "bt2.scsfsm.com",
Priority = 0,
Weight = 2,
Port = 44
},
new SrvRecord
{
Target = "bt1.scsfsm.com",
Priority = 1,
Weight = 1,
Port = 45
},
};
var recordName = "srv_record";
var testSrvRecordSet = new RecordSet("test_id", recordName, "SRV", null, this.metadata, 60, null, null, null, this.dummyARecords, this.dummyAaaaRecords, this.dummyMxRecords,
this.dummyNsRecords, this.dummyPtrRecords, srvRecords, this.dummyTxtRecords, null, null, this.dummyCaaRecords);
var createRecordSetResponse = await RecordSetsOperations.CreateOrUpdateAsync(resourceGroup, this.zoneNameForList, recordName, RecordType.SRV, testSrvRecordSet);
Assert.True(Helper.AreEqual(createRecordSetResponse, testSrvRecordSet, ignoreEtag: true));
}
[TestCase]
public async Task CreateGetTxt()
{
var txtRecords = new ChangeTrackingList<TxtRecord>
{
new TxtRecord(new List<string>{"lorem"}),
new TxtRecord(new List<string>{"ipsum"}),
};
var recordName = "txt_record";
var testTxtRecordSet = new RecordSet("test_id", recordName, "TXT", null, this.metadata, 60, null, null, null, this.dummyARecords, this.dummyAaaaRecords, this.dummyMxRecords,
this.dummyNsRecords, this.dummyPtrRecords, this.dummySrvRecords, txtRecords, null, null, this.dummyCaaRecords);
var createRecordSetResponse = await RecordSetsOperations.CreateOrUpdateAsync(resourceGroup, this.zoneNameForList, recordName, RecordType.TXT, testTxtRecordSet);
Assert.True(Helper.AreEqual(createRecordSetResponse, testTxtRecordSet, ignoreEtag: true));
}
[TestCase]
public async Task DnsUpdateARecordMultiRecord()
{
var namespaceName = Recording.GenerateAssetName("sdk-RecordSet");
var aRecords = new ChangeTrackingList<ARecord>
{
new ARecord {Ipv4Address = "123.32.1.0"}
};
var recordName = "a_multi_record";
var testARecordSet = new RecordSet("test_id", recordName, "A", null, this.metadata, 60, null, null, null, aRecords, this.dummyAaaaRecords, this.dummyMxRecords,
this.dummyNsRecords, this.dummyPtrRecords, this.dummySrvRecords, this.dummyTxtRecords, null, null, this.dummyCaaRecords);
var createRecordSetResponse = await RecordSetsOperations.CreateOrUpdateAsync(resourceGroup, this.zoneNameForList, recordName, RecordType.A, testARecordSet);
Assert.True(Helper.AreEqual(createRecordSetResponse, testARecordSet, ignoreEtag: true));
var getResponseARecord = await RecordSetsOperations.GetAsync(this.resourceGroup, this.zoneNameForList, recordName, RecordType.A);
var aRecord = getResponseARecord.Value;
aRecord.TTL = 120; //update TTL from 60 to 120
aRecord.ARecords.Clear();
var aList = new List<ARecord>
{
new ARecord {Ipv4Address = "123.32.1.0"},
new ARecord {Ipv4Address = "101.10.0.1"},
new ARecord {Ipv4Address = "22.33.44.55"},
};
((List<ARecord>)aRecord.ARecords).AddRange(aList);
var updateResponse = await RecordSetsOperations.CreateOrUpdateAsync(this.resourceGroup, this.zoneNameForList, recordName, RecordType.A, aRecord);
var updatedRecords = updateResponse.Value;
Assert.AreEqual(updatedRecords.TTL, 120);
for (int i = 0; i < aList.Count; i++)
{
Assert.True(updatedRecords.ARecords[i].Ipv4Address == aList[i].Ipv4Address);
}
Assert.False(string.IsNullOrWhiteSpace(updatedRecords.Etag));
var deleteRecordSetResponse = await RecordSetsOperations.DeleteAsync(resourceGroup, this.zoneNameForList, recordName, RecordType.A);
Assert.NotNull(deleteRecordSetResponse);
}
[TestCase]
public async Task UpdateRecordSetPreconditionFailed()
{
var namespaceName = Recording.GenerateAssetName("sdk-RecordSet");
var cnameRecord = new CnameRecord { Cname = "www.contoso.example.com" };
var recordName = "cname_record";
var testCnameRecordSet = new RecordSet("test_id", recordName, "Cname", null, this.metadata, 60, null, null, null, this.dummyARecords, this.dummyAaaaRecords, this.dummyMxRecords,
this.dummyNsRecords, this.dummyPtrRecords, this.dummySrvRecords, this.dummyTxtRecords, cnameRecord, null, this.dummyCaaRecords);
var createRecordSetResponse = await RecordSetsOperations.CreateOrUpdateAsync(resourceGroup, this.zoneNameForList, recordName, RecordType.Cname, testCnameRecordSet);
bool exceptionCaught = false;
try
{
await RecordSetsOperations.CreateOrUpdateAsync(
this.resourceGroup,
this.zoneNameForList,
recordName,
RecordType.Cname,
ifMatch: "somegibberish",
ifNoneMatch: null,
parameters: testCnameRecordSet);
}
catch (Azure.RequestFailedException)
{
exceptionCaught = true;
}
finally
{
Assert.True(exceptionCaught);
}
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="XmlLoader.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <owner current="true" primary="true">[....]</owner>
//------------------------------------------------------------------------------
namespace System.Xml {
using System.IO;
using System.Collections;
using System.Diagnostics;
using System.Text;
using System.Xml.Schema;
using System.Globalization;
internal class XmlLoader {
XmlDocument doc;
XmlReader reader;
bool preserveWhitespace;
public XmlLoader() {
}
internal void Load(XmlDocument doc, XmlReader reader, bool preserveWhitespace ) {
this.doc = doc;
// perf: unwrap XmlTextReader if no one derived from it
if ( reader.GetType() == typeof( System.Xml.XmlTextReader ) ) {
this.reader = ((XmlTextReader)reader).Impl;
}
else {
this.reader = reader;
}
this.preserveWhitespace = preserveWhitespace;
if (doc == null)
throw new ArgumentException(Res.GetString(Res.Xdom_Load_NoDocument));
if (reader == null)
throw new ArgumentException(Res.GetString(Res.Xdom_Load_NoReader));
doc.SetBaseURI( reader.BaseURI );
if (reader.Settings != null
&& reader.Settings.ValidationType == ValidationType.Schema) {
doc.Schemas = reader.Settings.Schemas;
}
if ( this.reader.ReadState != ReadState.Interactive ) {
if ( !this.reader.Read() )
return;
}
LoadDocSequence( doc);
}
//The function will start loading the document from where current XmlReader is pointing at.
private void LoadDocSequence( XmlDocument parentDoc ) {
Debug.Assert( this.reader != null );
Debug.Assert( parentDoc != null );
XmlNode node = null;
while ( ( node = LoadNode(true) ) != null ) {
parentDoc.AppendChildForLoad( node, parentDoc );
if ( !this.reader.Read() )
return;
}
}
internal XmlNode ReadCurrentNode(XmlDocument doc, XmlReader reader) {
this.doc = doc;
this.reader = reader;
// WS are optional only for loading (see XmlDocument.PreserveWhitespace)
this.preserveWhitespace = true;
if (doc == null)
throw new ArgumentException(Res.GetString(Res.Xdom_Load_NoDocument));
if (reader == null)
throw new ArgumentException(Res.GetString(Res.Xdom_Load_NoReader));
if( reader.ReadState == ReadState.Initial ) {
reader.Read();
}
if( reader.ReadState == ReadState.Interactive ) {
XmlNode n = LoadNode(true);
// Move to the next node
if ( n.NodeType != XmlNodeType.Attribute )
reader.Read();
return n;
}
return null;
}
private XmlNode LoadNode(bool skipOverWhitespace) {
XmlReader r = this.reader;
XmlNode parent = null;
XmlElement element;
IXmlSchemaInfo schemaInfo;
do {
XmlNode node = null;
switch ( r.NodeType ) {
case XmlNodeType.Element:
bool fEmptyElement = r.IsEmptyElement;
element = doc.CreateElement( r.Prefix, r.LocalName, r.NamespaceURI );
element.IsEmpty = fEmptyElement;
if ( r.MoveToFirstAttribute() ) {
XmlAttributeCollection attributes = element.Attributes;
do {
XmlAttribute attr = LoadAttributeNode();
attributes.Append( attr ); // special case for load
}
while( r.MoveToNextAttribute() );
r.MoveToElement();
}
// recursively load all children.
if ( !fEmptyElement ) {
if ( parent != null ) {
parent.AppendChildForLoad( element, doc );
}
parent = element;
continue;
}
else {
schemaInfo = r.SchemaInfo;
if (schemaInfo != null) {
element.XmlName = doc.AddXmlName(element.Prefix, element.LocalName, element.NamespaceURI, schemaInfo);
}
node = element;
break;
}
case XmlNodeType.EndElement:
if ( parent == null ) {
return null;
}
Debug.Assert( parent.NodeType == XmlNodeType.Element );
schemaInfo = r.SchemaInfo;
if (schemaInfo != null) {
element = parent as XmlElement;
if (element != null) {
element.XmlName = doc.AddXmlName(element.Prefix, element.LocalName, element.NamespaceURI, schemaInfo);
}
}
if ( parent.ParentNode == null ) {
return parent;
}
parent = parent.ParentNode;
continue;
case XmlNodeType.EntityReference:
node = LoadEntityReferenceNode( false );
break;
case XmlNodeType.EndEntity:
Debug.Assert( parent == null );
return null;
case XmlNodeType.Attribute:
node = LoadAttributeNode();
break;
case XmlNodeType.Text:
node = doc.CreateTextNode( r.Value );
break;
case XmlNodeType.SignificantWhitespace:
node = doc.CreateSignificantWhitespace( r.Value );
break;
case XmlNodeType.Whitespace:
if ( preserveWhitespace ) {
node = doc.CreateWhitespace( r.Value );
break;
}
else if (parent == null && !skipOverWhitespace) {
// if called from LoadEntityReferenceNode, just return null
return null;
}
else {
continue;
}
case XmlNodeType.CDATA:
node = doc.CreateCDataSection( r.Value );
break;
case XmlNodeType.XmlDeclaration:
node = LoadDeclarationNode();
break;
case XmlNodeType.ProcessingInstruction:
node = doc.CreateProcessingInstruction( r.Name, r.Value );
break;
case XmlNodeType.Comment:
node = doc.CreateComment( r.Value );
break;
case XmlNodeType.DocumentType:
node = LoadDocumentTypeNode();
break;
default:
throw UnexpectedNodeType( r.NodeType );
}
Debug.Assert( node != null );
if ( parent != null ) {
parent.AppendChildForLoad( node, doc );
}
else {
return node;
}
}
while ( r.Read());
// when the reader ended before full subtree is read, return whatever we have created so far
if ( parent != null ) {
while ( parent.ParentNode != null ) {
parent = parent.ParentNode;
}
}
return parent;
}
private XmlAttribute LoadAttributeNode() {
Debug.Assert(reader.NodeType == XmlNodeType.Attribute);
XmlReader r = reader;
if (r.IsDefault) {
return LoadDefaultAttribute();
}
XmlAttribute attr = doc.CreateAttribute(r.Prefix, r.LocalName, r.NamespaceURI);
IXmlSchemaInfo schemaInfo = r.SchemaInfo;
if (schemaInfo != null) {
attr.XmlName = doc.AddAttrXmlName(attr.Prefix, attr.LocalName, attr.NamespaceURI, schemaInfo);
}
while ( r.ReadAttributeValue() ) {
XmlNode node;
switch (r.NodeType) {
case XmlNodeType.Text:
node = doc.CreateTextNode( r.Value );
break;
case XmlNodeType.EntityReference:
node = doc.CreateEntityReference( r.LocalName );
if ( r.CanResolveEntity ) {
r.ResolveEntity();
LoadAttributeValue( node, false );
// Code internally relies on the fact that an EntRef nodes has at least one child (even an empty text node). Ensure that this holds true,
// if the reader does not present any children for the ent-ref
if ( node.FirstChild == null ) {
node.AppendChildForLoad( doc.CreateTextNode(string.Empty), doc );
}
}
break;
default:
throw UnexpectedNodeType( r.NodeType );
}
Debug.Assert( node != null );
attr.AppendChildForLoad( node, doc );
}
return attr;
}
private XmlAttribute LoadDefaultAttribute() {
Debug.Assert( reader.IsDefault );
XmlReader r = reader;
XmlAttribute attr = doc.CreateDefaultAttribute( r.Prefix, r.LocalName, r.NamespaceURI );
IXmlSchemaInfo schemaInfo = r.SchemaInfo;
if (schemaInfo != null) {
attr.XmlName = doc.AddAttrXmlName(attr.Prefix, attr.LocalName, attr.NamespaceURI, schemaInfo);
}
LoadAttributeValue( attr, false );
XmlUnspecifiedAttribute defAttr = attr as XmlUnspecifiedAttribute;
// If user overrides CreateDefaultAttribute, then attr will NOT be a XmlUnspecifiedAttribute instance.
if ( defAttr != null )
defAttr.SetSpecified( false );
return attr;
}
private void LoadAttributeValue( XmlNode parent, bool direct ) {
XmlReader r = reader;
while ( r.ReadAttributeValue() ) {
XmlNode node;
switch ( r.NodeType ) {
case XmlNodeType.Text:
node = direct ? new XmlText( r.Value, doc ) : doc.CreateTextNode( r.Value );
break;
case XmlNodeType.EndEntity:
return;
case XmlNodeType.EntityReference:
node = direct ? new XmlEntityReference( reader.LocalName, doc ) : doc.CreateEntityReference( reader.LocalName );
if ( r.CanResolveEntity ) {
r.ResolveEntity();
LoadAttributeValue( node, direct );
// Code internally relies on the fact that an EntRef nodes has at least one child (even an empty text node). Ensure that this holds true,
// if the reader does not present any children for the ent-ref
if ( node.FirstChild == null ) {
node.AppendChildForLoad( direct ? new XmlText( string.Empty ) : doc.CreateTextNode( string.Empty ), doc );
}
}
break;
default:
throw UnexpectedNodeType( r.NodeType );
}
Debug.Assert( node != null );
parent.AppendChildForLoad( node, doc );
}
return;
}
private XmlEntityReference LoadEntityReferenceNode( bool direct ) {
Debug.Assert( reader.NodeType == XmlNodeType.EntityReference );
XmlEntityReference eref = direct ? new XmlEntityReference( reader.Name, this.doc ) : doc.CreateEntityReference( reader.Name );
if ( reader.CanResolveEntity ) {
reader.ResolveEntity();
while ( reader.Read() && reader.NodeType != XmlNodeType.EndEntity ) {
XmlNode node = direct ? LoadNodeDirect() : LoadNode(false);
if ( node != null ) {
eref.AppendChildForLoad( node, doc );
}
}
// Code internally relies on the fact that an EntRef nodes has at least one child (even an empty text node). Ensure that this holds true,
// if the reader does not present any children for the ent-ref
if ( eref.LastChild == null )
eref.AppendChildForLoad( doc.CreateTextNode(string.Empty), doc );
}
return eref;
}
private XmlDeclaration LoadDeclarationNode() {
Debug.Assert( reader.NodeType == XmlNodeType.XmlDeclaration );
//parse data
string version = null;
string encoding = null;
string standalone = null;
// Try first to use the reader to get the xml decl "attributes". Since not all readers are required to support this, it is possible to have
// implementations that do nothing
while(reader.MoveToNextAttribute()) {
switch (reader.Name) {
case "version":
version = reader.Value;
break;
case "encoding":
encoding = reader.Value;
break;
case "standalone":
standalone = reader.Value;
break;
default:
Debug.Assert( false );
break;
}
}
// For readers that do not break xml decl into attributes, we must parse the xml decl ourselfs. We use version attr, b/c xml decl MUST contain
// at least version attr, so if the reader implements them as attr, then version must be present
if ( version == null )
ParseXmlDeclarationValue( reader.Value, out version, out encoding, out standalone );
return doc.CreateXmlDeclaration( version, encoding, standalone );
}
private XmlDocumentType LoadDocumentTypeNode() {
Debug.Assert( reader.NodeType == XmlNodeType.DocumentType );
String publicId = null;
String systemId = null;
String internalSubset = reader.Value;
String localName = reader.LocalName;
while (reader.MoveToNextAttribute()) {
switch (reader.Name) {
case "PUBLIC" :
publicId = reader.Value;
break;
case "SYSTEM":
systemId = reader.Value;
break;
}
}
XmlDocumentType dtNode = doc.CreateDocumentType( localName, publicId, systemId, internalSubset );
IDtdInfo dtdInfo = reader.DtdInfo;
if ( dtdInfo != null )
LoadDocumentType( dtdInfo, dtNode );
else {
//construct our own XmlValidatingReader to parse the DocumentType node so we could get Entities and notations information
ParseDocumentType( dtNode );
}
return dtNode;
}
// LoadNodeDirect does not use creator functions on XmlDocument. It is used loading nodes that are children of entity nodes,
// becaouse we do not want to let users extend these (if we would allow this, XmlDataDocument would have a problem, becaouse
// they do not know that those nodes should not be mapped). It can be also used for an optimized load path when if the
// XmlDocument is not extended if XmlDocumentType and XmlDeclaration handling is added.
private XmlNode LoadNodeDirect() {
XmlReader r = this.reader;
XmlNode parent = null;
do {
XmlNode node = null;
switch ( r.NodeType ) {
case XmlNodeType.Element:
bool fEmptyElement = reader.IsEmptyElement;
XmlElement element = new XmlElement( reader.Prefix, reader.LocalName, reader.NamespaceURI, this.doc );
element.IsEmpty = fEmptyElement;
if ( reader.MoveToFirstAttribute() ) {
XmlAttributeCollection attributes = element.Attributes;
do {
XmlAttribute attr = LoadAttributeNodeDirect();
attributes.Append( attr ); // special case for load
} while( r.MoveToNextAttribute() );
}
// recursively load all children.
if ( !fEmptyElement ) {
parent.AppendChildForLoad( element, doc );
parent = element;
continue;
}
else {
node = element;
break;
}
case XmlNodeType.EndElement:
Debug.Assert( parent.NodeType == XmlNodeType.Element );
if ( parent.ParentNode == null ) {
return parent;
}
parent = parent.ParentNode;
continue;
case XmlNodeType.EntityReference:
node = LoadEntityReferenceNode( true );
break;
case XmlNodeType.EndEntity:
continue;
case XmlNodeType.Attribute:
node = LoadAttributeNodeDirect();
break;
case XmlNodeType.SignificantWhitespace:
node = new XmlSignificantWhitespace( reader.Value, this.doc );
break;
case XmlNodeType.Whitespace:
if ( preserveWhitespace ) {
node = new XmlWhitespace( reader.Value, this.doc );
}
else {
continue;
}
break;
case XmlNodeType.Text:
node = new XmlText( reader.Value, this.doc );
break;
case XmlNodeType.CDATA:
node = new XmlCDataSection( reader.Value, this.doc );
break;
case XmlNodeType.ProcessingInstruction:
node = new XmlProcessingInstruction( reader.Name, reader.Value, this.doc );
break;
case XmlNodeType.Comment:
node = new XmlComment( reader.Value, this.doc );
break;
default:
throw UnexpectedNodeType( reader.NodeType );
}
Debug.Assert( node != null );
if ( parent != null ) {
parent.AppendChildForLoad( node, doc );
}
else {
return node;
}
}
while ( r.Read());
return null;
}
private XmlAttribute LoadAttributeNodeDirect() {
XmlReader r = reader;
XmlAttribute attr;
if ( r.IsDefault ) {
XmlUnspecifiedAttribute defattr = new XmlUnspecifiedAttribute( r.Prefix, r.LocalName, r.NamespaceURI, this.doc );
LoadAttributeValue( defattr, true );
defattr.SetSpecified( false );
return defattr;
}
else {
attr = new XmlAttribute( r.Prefix, r.LocalName, r.NamespaceURI, this.doc );
LoadAttributeValue( attr, true );
return attr;
}
}
internal void ParseDocumentType ( XmlDocumentType dtNode ) {
XmlDocument doc = dtNode.OwnerDocument;
//if xmlresolver is set on doc, use that one, otherwise use the default one being created by xmlvalidatingreader
if ( doc.HasSetResolver )
ParseDocumentType( dtNode, true, doc.GetResolver() );
else
ParseDocumentType( dtNode, false, null );
}
private void ParseDocumentType ( XmlDocumentType dtNode, bool bUseResolver, XmlResolver resolver ) {
this.doc = dtNode.OwnerDocument;
XmlParserContext pc = new XmlParserContext(null, new XmlNamespaceManager( this.doc.NameTable ), null, null, null, null, this.doc.BaseURI, string.Empty, XmlSpace.None);
XmlTextReaderImpl tr = new XmlTextReaderImpl("", XmlNodeType.Element, pc);
tr.Namespaces = dtNode.ParseWithNamespaces;
if (bUseResolver) {
tr.XmlResolver = resolver;
}
IDtdParser dtdParser = DtdParser.Create();
XmlTextReaderImpl.DtdParserProxy proxy = new XmlTextReaderImpl.DtdParserProxy(tr);
IDtdInfo dtdInfo = dtdParser.ParseFreeFloatingDtd(this.doc.BaseURI, dtNode.Name, dtNode.PublicId, dtNode.SystemId, dtNode.InternalSubset, proxy );
LoadDocumentType( dtdInfo, dtNode );
}
private void LoadDocumentType( IDtdInfo dtdInfo, XmlDocumentType dtNode ) {
SchemaInfo schInfo = dtdInfo as SchemaInfo;
if (schInfo == null) {
throw new XmlException(Res.Xml_InternalError, string.Empty);
}
dtNode.DtdSchemaInfo = schInfo;
if (schInfo != null) {
//set the schema information into the document
doc.DtdSchemaInfo = schInfo;
// Notation hashtable
if (schInfo.Notations != null) {
foreach( SchemaNotation scNot in schInfo.Notations.Values ) {
dtNode.Notations.SetNamedItem(new XmlNotation( scNot.Name.Name, scNot.Pubid, scNot.SystemLiteral, doc ));
}
}
// Entity hashtables
if (schInfo.GeneralEntities != null) {
foreach( SchemaEntity scEnt in schInfo.GeneralEntities.Values ) {
XmlEntity ent = new XmlEntity( scEnt.Name.Name, scEnt.Text, scEnt.Pubid, scEnt.Url, scEnt.NData.IsEmpty ? null : scEnt.NData.Name, doc );
ent.SetBaseURI( scEnt.DeclaredURI );
dtNode.Entities.SetNamedItem( ent );
}
}
if (schInfo.ParameterEntities != null) {
foreach( SchemaEntity scEnt in schInfo.ParameterEntities.Values ) {
XmlEntity ent = new XmlEntity( scEnt.Name.Name, scEnt.Text, scEnt.Pubid, scEnt.Url, scEnt.NData.IsEmpty ? null : scEnt.NData.Name, doc );
ent.SetBaseURI( scEnt.DeclaredURI );
dtNode.Entities.SetNamedItem( ent );
}
}
doc.Entities = dtNode.Entities;
//extract the elements which has attribute defined as ID from the element declarations
IDictionaryEnumerator elementDecls = schInfo.ElementDecls.GetEnumerator();
if (elementDecls != null) {
elementDecls.Reset();
while (elementDecls.MoveNext()) {
SchemaElementDecl elementDecl = (SchemaElementDecl)elementDecls.Value;
if (elementDecl.AttDefs != null) {
IDictionaryEnumerator attDefs = elementDecl.AttDefs.GetEnumerator();
while (attDefs.MoveNext()) {
SchemaAttDef attdef = (SchemaAttDef)attDefs.Value;
if (attdef.Datatype.TokenizedType == XmlTokenizedType.ID) {
//we only register the XmlElement based on their Prefix/LocalName and skip the namespace
doc.AddIdInfo(
doc.AddXmlName(elementDecl.Prefix, elementDecl.Name.Name, string.Empty, null),
doc.AddAttrXmlName(attdef.Prefix, attdef.Name.Name, string.Empty, null));
break;
}
}
}
}
}
}
}
#pragma warning restore 618
private XmlParserContext GetContext ( XmlNode node ) {
String lang = null;
XmlSpace spaceMode = XmlSpace.None;
XmlDocumentType docType = this.doc.DocumentType;
String baseURI = this.doc.BaseURI;
//constructing xmlnamespace
Hashtable prefixes = new Hashtable();
XmlNameTable nt = this.doc.NameTable;
XmlNamespaceManager mgr = new XmlNamespaceManager( nt );
bool bHasDefXmlnsAttr = false;
// Process all xmlns, xmlns:prefix, xml:space and xml:lang attributes
while ( node != null && node != doc ) {
if ( node is XmlElement && ((XmlElement)node).HasAttributes ) {
mgr.PushScope();
foreach( XmlAttribute attr in ((XmlElement)node).Attributes ) {
if ( attr.Prefix == doc.strXmlns && prefixes.Contains( attr.LocalName ) == false ) {
// Make sure the next time we will not add this prefix
prefixes.Add( attr.LocalName, attr.LocalName );
mgr.AddNamespace( attr.LocalName, attr.Value );
}
else if ( !bHasDefXmlnsAttr && attr.Prefix.Length == 0 && attr.LocalName == doc.strXmlns ) {
// Save the case xmlns="..." where xmlns is the LocalName
mgr.AddNamespace( String.Empty, attr.Value );
bHasDefXmlnsAttr = true;
}
else if ( spaceMode == XmlSpace.None && attr.Prefix == doc.strXml && attr.LocalName == doc.strSpace ) {
// Save xml:space context
if ( attr.Value=="default" )
spaceMode = XmlSpace.Default;
else if (attr.Value=="preserve")
spaceMode = XmlSpace.Preserve;
}
else if ( lang == null && attr.Prefix == doc.strXml && attr.LocalName == doc.strLang ) {
// Save xml:lag context
lang = attr.Value;
}
}
}
node = node.ParentNode;
}
return new XmlParserContext(
nt,
mgr,
( docType == null ) ? null : docType.Name,
( docType == null ) ? null : docType.PublicId,
( docType == null ) ? null : docType.SystemId,
( docType == null ) ? null : docType.InternalSubset,
baseURI,
lang,
spaceMode
);
}
internal XmlNamespaceManager ParsePartialContent( XmlNode parentNode, string innerxmltext, XmlNodeType nt) {
//the function shouldn't be used to set innerxml for XmlDocument node
Debug.Assert( parentNode.NodeType != XmlNodeType.Document );
this.doc = parentNode.OwnerDocument;
Debug.Assert( this.doc != null );
XmlParserContext pc = GetContext( parentNode );
this.reader = CreateInnerXmlReader( innerxmltext, nt, pc, this.doc );
try {
this.preserveWhitespace = true;
bool bOrigLoading = doc.IsLoading;
doc.IsLoading = true;
if ( nt == XmlNodeType.Entity ) {
XmlNode node = null;
while ( reader.Read() && ( node = LoadNodeDirect() ) != null ) {
parentNode.AppendChildForLoad( node, doc );
}
}
else {
XmlNode node = null;
while ( reader.Read() && ( node = LoadNode(true) ) != null ) {
parentNode.AppendChildForLoad( node, doc );
}
}
doc.IsLoading = bOrigLoading;
}
finally {
this.reader.Close();
}
return pc.NamespaceManager;
}
internal void LoadInnerXmlElement(XmlElement node, string innerxmltext ) {
//construct a tree underneth the node
XmlNamespaceManager mgr = ParsePartialContent( node, innerxmltext, XmlNodeType.Element );
//remove the duplicate namesapce
if ( node.ChildNodes.Count > 0 )
RemoveDuplicateNamespace( (XmlElement) node, mgr, false );
}
internal void LoadInnerXmlAttribute(XmlAttribute node, string innerxmltext ) {
ParsePartialContent( node, innerxmltext, XmlNodeType.Attribute );
}
private void RemoveDuplicateNamespace( XmlElement elem, XmlNamespaceManager mgr, bool fCheckElemAttrs ) {
//remove the duplicate attributes on current node first
mgr.PushScope();
XmlAttributeCollection attrs = elem.Attributes;
int cAttrs = attrs.Count;
if ( fCheckElemAttrs && cAttrs > 0 ) {
for ( int i = cAttrs - 1; i >= 0; --i ) {
XmlAttribute attr = attrs[i];
if ( attr.Prefix == doc.strXmlns ) {
string nsUri = mgr.LookupNamespace(attr.LocalName);
if ( nsUri != null ) {
if ( attr.Value == nsUri )
elem.Attributes.RemoveNodeAt(i);
}
else {
// Add this namespace, so it we will behave corectly when setting "<bar xmlns:p="BAR"><foo2 xmlns:p="FOO"/></bar>" as
// InnerXml on this foo elem where foo is like this "<foo xmlns:p="FOO"></foo>"
// If do not do this, then we will remove the inner p prefix definition and will let the 1st p to be in scope for
// the subsequent InnerXml_set or setting an EntRef inside.
mgr.AddNamespace( attr.LocalName, attr.Value );
}
}
else if ( attr.Prefix.Length == 0 && attr.LocalName == doc.strXmlns ) {
string nsUri = mgr.DefaultNamespace;
if ( nsUri != null ) {
if ( attr.Value == nsUri )
elem.Attributes.RemoveNodeAt(i);
}
else {
// Add this namespace, so it we will behave corectly when setting "<bar xmlns:p="BAR"><foo2 xmlns:p="FOO"/></bar>" as
// InnerXml on this foo elem where foo is like this "<foo xmlns:p="FOO"></foo>"
// If do not do this, then we will remove the inner p prefix definition and will let the 1st p to be in scope for
// the subsequent InnerXml_set or setting an EntRef inside.
mgr.AddNamespace( attr.LocalName, attr.Value );
}
}
}
}
//now recursively remove the duplicate attributes on the children
XmlNode child = elem.FirstChild;
while ( child != null ) {
XmlElement childElem = child as XmlElement;
if ( childElem != null )
RemoveDuplicateNamespace( childElem, mgr, true );
child = child.NextSibling;
}
mgr.PopScope();
}
private String EntitizeName(String name) {
return "&"+name+";";
}
//The function is called when expanding the entity when its children being asked
internal void ExpandEntity(XmlEntity ent) {
ParsePartialContent( ent, EntitizeName(ent.Name), XmlNodeType.Entity );
}
//The function is called when expanding the entity ref. ( inside XmlEntityReference.SetParent )
internal void ExpandEntityReference(XmlEntityReference eref)
{
//when the ent ref is not associated w/ an entity, append an empty string text node as child
this.doc = eref.OwnerDocument;
bool bOrigLoadingState = doc.IsLoading;
doc.IsLoading = true;
switch ( eref.Name ) {
case "lt":
eref.AppendChildForLoad( doc.CreateTextNode( "<" ), doc );
doc.IsLoading = bOrigLoadingState;
return;
case "gt":
eref.AppendChildForLoad( doc.CreateTextNode( ">" ), doc );
doc.IsLoading = bOrigLoadingState;
return;
case "amp":
eref.AppendChildForLoad( doc.CreateTextNode( "&" ), doc );
doc.IsLoading = bOrigLoadingState;
return;
case "apos":
eref.AppendChildForLoad( doc.CreateTextNode( "'" ), doc );
doc.IsLoading = bOrigLoadingState;
return;
case "quot":
eref.AppendChildForLoad( doc.CreateTextNode( "\"" ), doc );
doc.IsLoading = bOrigLoadingState;
return;
}
XmlNamedNodeMap entities = doc.Entities;
foreach ( XmlEntity ent in entities ) {
if ( Ref.Equal( ent.Name, eref.Name ) ) {
ParsePartialContent( eref, EntitizeName(eref.Name), XmlNodeType.EntityReference );
return;
}
}
//no fit so far
if( !( doc.ActualLoadingStatus ) ) {
eref.AppendChildForLoad( doc.CreateTextNode( "" ), doc );
doc.IsLoading = bOrigLoadingState;
}
else {
doc.IsLoading = bOrigLoadingState;
throw new XmlException( Res.Xml_UndeclaredParEntity, eref.Name );
}
}
#pragma warning disable 618
// Creates a XmlValidatingReader suitable for parsing InnerXml strings
private XmlReader CreateInnerXmlReader( String xmlFragment, XmlNodeType nt, XmlParserContext context, XmlDocument doc ) {
XmlNodeType contentNT = nt;
if ( contentNT == XmlNodeType.Entity || contentNT == XmlNodeType.EntityReference )
contentNT = XmlNodeType.Element;
XmlTextReaderImpl tr = new XmlTextReaderImpl( xmlFragment, contentNT, context );
tr.XmlValidatingReaderCompatibilityMode = true;
if ( doc.HasSetResolver ) {
tr.XmlResolver = doc.GetResolver();
}
if( !( doc.ActualLoadingStatus ) ) {
tr.DisableUndeclaredEntityCheck = true;
}
Debug.Assert( tr.EntityHandling == EntityHandling.ExpandCharEntities );
XmlDocumentType dtdNode = doc.DocumentType;
if ( dtdNode != null ) {
tr.Namespaces = dtdNode.ParseWithNamespaces;
if ( dtdNode.DtdSchemaInfo != null ) {
tr.SetDtdInfo( dtdNode.DtdSchemaInfo );
}
else {
IDtdParser dtdParser = DtdParser.Create();
XmlTextReaderImpl.DtdParserProxy proxy = new XmlTextReaderImpl.DtdParserProxy(tr);
IDtdInfo dtdInfo = dtdParser.ParseFreeFloatingDtd(context.BaseURI, context.DocTypeName, context.PublicId, context.SystemId, context.InternalSubset, proxy);
//
dtdNode.DtdSchemaInfo = dtdInfo as SchemaInfo;
tr.SetDtdInfo( dtdInfo );
}
}
if ( nt == XmlNodeType.Entity || nt == XmlNodeType.EntityReference ) {
tr.Read(); //this will skip the first element "wrapper"
tr.ResolveEntity();
}
return tr;
}
#pragma warning restore 618
internal static void ParseXmlDeclarationValue( string strValue, out string version, out string encoding, out string standalone ) {
version = null;
encoding = null;
standalone = null;
XmlTextReaderImpl tempreader = new XmlTextReaderImpl( strValue, (XmlParserContext)null);
try {
tempreader.Read();
//get version info.
if (tempreader.MoveToAttribute( "version" ))
version = tempreader.Value;
//get encoding info
if (tempreader.MoveToAttribute( "encoding" ))
encoding = tempreader.Value;
//get standalone info
if (tempreader.MoveToAttribute( "standalone" ))
standalone = tempreader.Value;
}
finally {
tempreader.Close();
}
}
static internal Exception UnexpectedNodeType( XmlNodeType nodetype ) {
return new InvalidOperationException( string.Format( CultureInfo.InvariantCulture, Res.GetString(Res.Xml_UnexpectedNodeType), nodetype.ToString()));
}
}
}
| |
/*
* DateTime.cs - Implementation of the "System.DateTime" class.
*
* Copyright (C) 2001 Southern Storm Software, Pty Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
namespace System
{
using System.Globalization;
using System.Runtime.InteropServices;
using Platform;
using System.Private.DateTimeFormat;
// ECMA requires that this have "auto" layout.
#if CONFIG_RUNTIME_INFRA
[StructLayout(LayoutKind.Auto)]
#endif
public struct DateTime : IComparable, IFormattable
#if !ECMA_COMPAT
, IConvertible
#endif
{
private long value_;
// Days in each month in regular years.
internal static readonly int[] daysForEachMonth
= {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
// Days before each month in regular years.
internal static readonly int[] daysBeforeMonth
= {0,
31,
31 + 28,
31 + 28 + 31,
31 + 28 + 31 + 30,
31 + 28 + 31 + 30 + 31,
31 + 28 + 31 + 30 + 31 + 30,
31 + 28 + 31 + 30 + 31 + 30 + 31,
31 + 28 + 31 + 30 + 31 + 30 + 31 + 31,
31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30,
31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31,
31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31 + 30};
// Internal useful constants.
private const long ticksPerDay = (10000000L * 60L * 60L * 24L);
// Maximum microseconds value.
private static readonly long maxTicks =
(DateToTicks(9999, 12, 31) + ticksPerDay - 1);
// Public constants.
public static readonly DateTime MinValue = new DateTime(0);
public static readonly DateTime MaxValue = new DateTime(maxTicks);
// Convert a year into a number of ticks.
private static long YearToTicks(int year)
{
--year;
return (long)(year * 365 + year / 4 -
year / 100 + year / 400) * ticksPerDay;
}
// Convert a YMD date into a number of ticks.
private static long DateToTicks(int year, int month, int day)
{
int daysInMonth;
long result;
bool isLeap;
if(year >= 1 && year <= 9999 &&
month >= 1 && month <= 12)
{
isLeap = IsLeapYear(year);
daysInMonth = daysForEachMonth[month - 1];
if(month == 2 && isLeap)
{
++daysInMonth;
}
if(day >= 1 && day <= daysInMonth)
{
unchecked
{
result = (YearToTicks(year) / ticksPerDay);
result += (long)(daysBeforeMonth[month - 1]);
if(month > 2 && isLeap)
{
++result;
}
return (result + (long)(day - 1)) * ticksPerDay;
}
}
}
throw new ArgumentOutOfRangeException(_("ArgRange_YMD"));
}
// Convert a time into a number of ticks.
internal static long TimeToTicks(int hour, int minute, int second)
{
if(hour >= 0 && hour <= 23 &&
minute >= 0 && minute <= 59 &&
second >= 0 && minute <= 59)
{
unchecked
{
return ((long)(hour * 3600 + minute * 60 + second))
* 10000000L;
}
}
throw new ArgumentOutOfRangeException(_("ArgRange_HMS"));
}
// Constructors.
public DateTime(long ticks)
{
if(ticks >= 0 && ticks <= maxTicks)
{
value_ = ticks;
}
else
{
throw new ArgumentOutOfRangeException
("ticks", _("ArgRange_DateTimeTicks"));
}
}
public DateTime(int year, int month, int day)
{
value_ = DateToTicks(year, month, day);
}
public DateTime(int year, int month, int day,
int hour, int minute, int second)
{
value_ = DateToTicks(year, month, day) +
TimeToTicks(hour, minute, second);
}
public DateTime(int year, int month, int day,
int hour, int minute, int second, int millisecond)
{
unchecked
{
value_ = DateToTicks(year, month, day) +
TimeToTicks(hour, minute, second) +
((long)millisecond) * 10000L;
if(value_ < 0 || value_ > maxTicks)
{
throw new ArgumentException(_("Arg_DateTimeRange"));
}
}
}
#if !ECMA_COMPAT
// Non-ECMA constructors.
public DateTime(int year, int month, int day,
int hour, int minute, int second, Calendar calendar)
: this(year, month, day, hour, minute, second, 0, calendar)
{
// Nothing to do here
}
public DateTime(int year, int month, int day, Calendar calendar)
: this(year, month, day, 0, 0, 0, 0, calendar)
{
// Nothing to do here
}
public DateTime(int year, int month, int day,
int hour, int minute, int second, int millisecond,
Calendar calendar)
{
if(calendar == null)
{
throw new ArgumentNullException("calendar");
}
value_ = calendar.ToDateTime(year, month, day, hour,
minute, second, millisecond,
Calendar.CurrentEra)
.Ticks;
}
#endif // !ECMA_COMPAT
// Determine if a year is a leap year.
public static bool IsLeapYear(int year)
{
return ((year % 4) == 0 &&
((year % 100) != 0 || (year % 400) == 0));
}
// Determine the number of days in a month.
public static int DaysInMonth(int year, int month)
{
if(year < 1 || year > 9999)
{
throw new ArgumentOutOfRangeException
("year", _("ArgRange_Year"));
}
if(month < 1 || month > 12)
{
throw new ArgumentOutOfRangeException
("month", _("ArgRange_Month"));
}
if(IsLeapYear(year) && month == 2)
{
return 29;
}
else
{
return daysForEachMonth[month - 1];
}
}
#if !ECMA_COMPAT
// The base time for Windows file time values (Midnight, Jan 1, 1601).
private static readonly DateTime FileTimeBase = new DateTime(1601, 1, 1);
// Convert a Windows file time into a DateTime value.
public static DateTime FromFileTime(long fileTime)
{
return FromFileTimeUtc(fileTime).ToLocalTime();
}
// Convert a DateTime value into a Windows file time.
public long ToFileTime()
{
return ToUniversalTime().ToFileTimeUtc();
}
// Convert a UTC file time value into a DateTime value.
public static DateTime FromFileTimeUtc(long fileTime)
{
checked
{
try
{
return new DateTime(fileTime + FileTimeBase.Ticks);
}
catch(OverflowException)
{
throw new ArgumentOutOfRangeException
("fileTime", _("ArgRange_DateTimeRange"));
}
}
}
// Convert a DateTime value into a UTC file time value.
public long ToFileTimeUtc()
{
long time = value_ - FileTimeBase.Ticks;
if(time < 0)
{
throw new ArgumentOutOfRangeException
("this", _("ArgRange_DateTimeRange"));
}
else
{
return time;
}
}
// Base time for OLE Automation values (Midnight, Dec 30, 1899).
private static readonly DateTime OLEBaseTime = new DateTime(1899, 12, 30);
// Convert an OLE Automation date into a DateTime value.
public static DateTime FromOADate(double d)
{
// Convert the value into ticks, while checking for overflow.
long ticks;
checked
{
try
{
ticks = ((long)(d * (double)TimeSpan.TicksPerDay)) +
OLEBaseTime.Ticks;
}
catch(OverflowException)
{
throw new ArgumentOutOfRangeException
("d", _("ArgRange_DateTimeRange"));
}
}
// Convert the ticks into a DateTime value, which will
// perform additional range checking.
return new DateTime(ticks);
}
// Convert this DateTime value into an OLE Automation date.
public double ToOADate()
{
if(value_ == 0)
{
// Special case for uninitialized DateTime values.
return 0.0;
}
else
{
return (((double)value_) / ((double)TimeSpan.TicksPerDay))
- ((double)OLEBaseTime.Ticks);
}
}
#endif // !ECMA_COMPAT
// Get a hash code for this DateTime value.
public override int GetHashCode()
{
unchecked
{
return (int)(value_ ^ (value_ >> 32));
}
}
// Compare DateTime values for equality.
public override bool Equals(Object value)
{
if(value is DateTime)
{
return (value_ == ((DateTime)value).value_);
}
else
{
return false;
}
}
public static bool Equals(DateTime d1, DateTime d2)
{
return (d1.value_ == d2.value_);
}
// String conversion.
public override String ToString()
{
return DateTimeFormatter.Format(this, "G", null);
}
public String ToString(String format)
{
return DateTimeFormatter.Format(this, format, null);
}
public String ToString(IFormatProvider provider)
{
return DateTimeFormatter.Format(this, "G", provider);
}
public String ToString(String format, IFormatProvider provider)
{
return DateTimeFormatter.Format(this, format, provider);
}
// Parsing methods.
public static DateTime Parse(String s)
{
return DateTimeParser.Parse
(s, null, DateTimeStyles.AllowWhiteSpaces);
}
public static DateTime Parse(String s, IFormatProvider provider)
{
return DateTimeParser.Parse
(s, provider, DateTimeStyles.AllowWhiteSpaces);
}
public static DateTime Parse(String s, IFormatProvider provider,
DateTimeStyles style)
{
return DateTimeParser.Parse(s, provider, style);
}
public static DateTime ParseExact(String s, String format,
IFormatProvider provider)
{
if(format == null)
{
throw new ArgumentNullException("format");
}
return DateTimeParser.ParseExact
(s, new String[] {format}, provider,
DateTimeStyles.AllowWhiteSpaces);
}
public static DateTime ParseExact(String s, String format,
IFormatProvider provider,
DateTimeStyles style)
{
if(format == null)
{
throw new ArgumentNullException("format");
}
return DateTimeParser.ParseExact
(s, new String[] {format}, provider, style);
}
public static DateTime ParseExact(String s, String[] formats,
IFormatProvider provider,
DateTimeStyles style)
{
return DateTimeParser.ParseExact
(s, formats, provider, style);
}
public static int Compare(DateTime t1, DateTime t2)
{
if(t1.value_ < t2.value_)
{
return -1;
}
else if(t1.value_ > t2.value_)
{
return 1;
}
else
{
return 0;
}
}
// Implementation of the IComparable interface.
public int CompareTo(Object value)
{
if(value != null)
{
if(!(value is DateTime))
{
throw new ArgumentException(_("Arg_MustBeDateTime"));
}
long value2 = ((DateTime)value).value_;
if(value_ < value2)
{
return -1;
}
else if(value_ > value2)
{
return 1;
}
else
{
return 0;
}
}
else
{
return 1;
}
}
#if !ECMA_COMPAT
// Implementation of IConvertible interface.
public TypeCode GetTypeCode()
{
return TypeCode.DateTime;
}
Object IConvertible.ToType(Type ct, IFormatProvider provider)
{
return Convert.DefaultToType(this, ct, provider, true);
}
Boolean IConvertible.ToBoolean(IFormatProvider provider)
{
throw new InvalidCastException
(String.Format
(_("InvalidCast_FromTo"), "DateTime", "Boolean"));
}
Byte IConvertible.ToByte(IFormatProvider provider)
{
throw new InvalidCastException
(String.Format
(_("InvalidCast_FromTo"), "DateTime", "Byte"));
}
SByte IConvertible.ToSByte(IFormatProvider provider)
{
throw new InvalidCastException
(String.Format
(_("InvalidCast_FromTo"), "DateTime", "SByte"));
}
Int16 IConvertible.ToInt16(IFormatProvider provider)
{
throw new InvalidCastException
(String.Format
(_("InvalidCast_FromTo"), "DateTime", "Int16"));
}
UInt16 IConvertible.ToUInt16(IFormatProvider provider)
{
throw new InvalidCastException
(String.Format
(_("InvalidCast_FromTo"), "DateTime", "UInt16"));
}
Int32 IConvertible.ToInt32(IFormatProvider provider)
{
throw new InvalidCastException
(String.Format
(_("InvalidCast_FromTo"), "DateTime", "Int32"));
}
UInt32 IConvertible.ToUInt32(IFormatProvider provider)
{
throw new InvalidCastException
(String.Format
(_("InvalidCast_FromTo"), "DateTime", "UInt32"));
}
Int64 IConvertible.ToInt64(IFormatProvider provider)
{
throw new InvalidCastException
(String.Format
(_("InvalidCast_FromTo"), "DateTime", "Int64"));
}
UInt64 IConvertible.ToUInt64(IFormatProvider provider)
{
throw new InvalidCastException
(String.Format
(_("InvalidCast_FromTo"), "DateTime", "UInt64"));
}
Char IConvertible.ToChar(IFormatProvider provider)
{
throw new InvalidCastException
(String.Format
(_("InvalidCast_FromTo"), "DateTime", "Char"));
}
Single IConvertible.ToSingle(IFormatProvider provider)
{
throw new InvalidCastException
(String.Format
(_("InvalidCast_FromTo"), "DateTime", "Single"));
}
Double IConvertible.ToDouble(IFormatProvider provider)
{
throw new InvalidCastException
(String.Format
(_("InvalidCast_FromTo"), "DateTime", "Double"));
}
Decimal IConvertible.ToDecimal(IFormatProvider provider)
{
throw new InvalidCastException
(String.Format
(_("InvalidCast_FromTo"), "DateTime", "Decimal"));
}
DateTime IConvertible.ToDateTime(IFormatProvider provider)
{
return this;
}
#endif // !ECMA_COMPAT
// The number of days in 400 years.
private const int DaysPer400Years = (400 * 365 + 97);
// The number of days in 100 years, when the 100th is not a leap year.
private const int DaysPer100Years = (100 * 365 + 24);
// The number of days in 4 years, including the leap day.
private const int DaysPer4Years = (4 * 365 + 1);
// Properties.
public DateTime Date
{
get
{
return new DateTime(value_ - (value_ % ticksPerDay));
}
}
public int Day
{
get
{
// Get the current year.
int year = Year;
// Get the tick offset within the year for the day.
long ticks = value_ - YearToTicks(year);
// Convert the tick offset into days.
int days = unchecked((int)(ticks / TimeSpan.TicksPerDay));
// Adjust for Jan and Feb in leap years.
if(IsLeapYear(year))
{
if(days < 31)
{
return days + 1;
}
else if(days < (31 + 29))
{
return days - 30;
}
--days;
}
// Search for the starting month.
int month = 1;
while(month < 12 && days >= daysBeforeMonth[month])
{
++month;
}
return days - daysBeforeMonth[month - 1] + 1;
}
}
public int Month
{
get
{
// Get the current year.
int year = Year;
// Get the tick offset within the year for the day.
long ticks = value_ - YearToTicks(year);
// Convert the tick offset into days.
int days = unchecked((int)(ticks / TimeSpan.TicksPerDay));
// Adjust for Jan and Feb in leap years.
if(IsLeapYear(year))
{
if(days < 31)
{
return 1;
}
else if(days < (31 + 29))
{
return 2;
}
--days;
}
// Search for the starting month.
int month = 1;
while(month < 12 && days >= daysBeforeMonth[month])
{
++month;
}
return month;
}
}
public int Year
{
get
{
// Note: there is probably a tricky mathematical
// formula for doing this, but this version is a
// lot easier to understand and debug.
// Convert the tick count into a day value.
int days = unchecked((int)(value_ / TimeSpan.TicksPerDay));
// Determine the 400-year cycle that contains the date.
int yearBase = ((days / DaysPer400Years) * 400) + 1;
int yearOffset = days % DaysPer400Years;
// Determine the 100-year cycle that contains the date.
if(yearOffset >= DaysPer100Years * 3)
{
yearBase += 300;
yearOffset -= DaysPer100Years * 3;
if(yearOffset >= DaysPer100Years)
{
// The date is at the end of a 400-year cycle.
return yearBase + 399;
}
}
else if(yearOffset >= DaysPer100Years * 2)
{
yearBase += 200;
yearOffset -= DaysPer100Years * 2;
}
else if(yearOffset >= DaysPer100Years)
{
yearBase += 100;
yearOffset -= DaysPer100Years;
}
// Determine the 4-year cycle that contains the date.
int temp = yearOffset / DaysPer4Years;
yearBase += temp * 4;
yearOffset -= temp * DaysPer4Years;
// Determine the year out of the 4-year cycle.
if(yearOffset >= 365 * 3)
{
return yearBase + 3;
}
else if(yearOffset >= 365 * 2)
{
return yearBase + 2;
}
else if(yearOffset >= 365)
{
return yearBase + 1;
}
else
{
return yearBase;
}
}
}
public int Hour
{
get
{
unchecked
{
return (int)((value_ / (ticksPerDay / 24)) % 24);
}
}
}
public int Minute
{
get
{
unchecked
{
return (int)((value_ / (ticksPerDay / (24 * 60))) % 60);
}
}
}
public int Second
{
get
{
unchecked
{
return (int)((value_ / 10000000L) % 60);
}
}
}
public int Millisecond
{
get
{
unchecked
{
return (int)((value_ / 10000L) % 1000L);
}
}
}
#if ECMA_COMPAT
internal
#else
public
#endif
System.DayOfWeek DayOfWeek
{
get
{
unchecked
{
return (System.DayOfWeek)(((value_ / ticksPerDay) + 1) % 7);
}
}
}
public int DayOfYear
{
get
{
// Get the tick offset within the year for the day.
long ticks = value_ - YearToTicks(Year);
// Convert the tick offset into days.
return unchecked((int)(ticks / TimeSpan.TicksPerDay)) + 1;
}
}
public long Ticks
{
get
{
return value_;
}
}
public TimeSpan TimeOfDay
{
get
{
return new TimeSpan(value_ % TimeSpan.TicksPerDay);
}
}
public static DateTime Now
{
get
{
return new DateTime(TimeMethods.GetCurrentTime());
}
}
public static DateTime UtcNow
{
get
{
return new DateTime(TimeMethods.GetCurrentUtcTime());
}
}
public static DateTime Today
{
get
{
long value = TimeMethods.GetCurrentTime();
return new DateTime(value - (value % ticksPerDay));
}
}
// Operators.
public static bool operator==(DateTime d1, DateTime d2)
{ return (d1.value_ == d2.value_); }
public static bool operator!=(DateTime d1, DateTime d2)
{ return (d1.value_ != d2.value_); }
public static bool operator<(DateTime d1, DateTime d2)
{ return (d1.value_ < d2.value_); }
public static bool operator>(DateTime d1, DateTime d2)
{ return (d1.value_ > d2.value_); }
public static bool operator<=(DateTime d1, DateTime d2)
{ return (d1.value_ <= d2.value_); }
public static bool operator>=(DateTime d1, DateTime d2)
{ return (d1.value_ >= d2.value_); }
public static DateTime operator+(DateTime d, TimeSpan t)
{ return new DateTime(d.value_ + t.value_); }
public static DateTime operator-(DateTime d, TimeSpan t)
{ return new DateTime(d.value_ - t.value_); }
public static TimeSpan operator-(DateTime d1, DateTime d2)
{ return new TimeSpan(d1.value_ - d2.value_); }
// Named operators.
public DateTime Add(TimeSpan t)
{ return new DateTime(value_ + t.value_); }
public DateTime Subtract(TimeSpan t)
{ return new DateTime(value_ - t.value_); }
public TimeSpan Subtract(DateTime d)
{ return new TimeSpan(value_ - d.value_); }
#if CONFIG_EXTENDED_NUMERICS
// Internal version of the "Add*" methods.
private DateTime DoAdd(double value, long multiplier)
{
// Let the runtime engine do the hard work of detecting
// most of the overflow conditions.
checked
{
try
{
return new DateTime
(value_ + ((long)(value * (double)multiplier)));
}
catch(OverflowException)
{
throw new ArgumentException(_("Arg_DateTimeRange"));
}
}
}
// Add certain periods of time to this DateTime value.
public DateTime AddDays(double value)
{
return DoAdd(value, TimeSpan.TicksPerDay);
}
public DateTime AddHours(double value)
{
return DoAdd(value, TimeSpan.TicksPerHour);
}
public DateTime AddMilliseconds(double value)
{
return DoAdd(value, TimeSpan.TicksPerMillisecond);
}
public DateTime AddMinutes(double value)
{
return DoAdd(value, TimeSpan.TicksPerMinute);
}
public DateTime AddSeconds(double value)
{
return DoAdd(value, TimeSpan.TicksPerSecond);
}
#endif // CONFIG_EXTENDED_NUMERICS
public DateTime AddMonths(int months)
{
// Crack open this DateTime value.
int year = Year;
int month = Month;
int day = Day;
long ticks = (value_ % TimeSpan.TicksPerDay);
int hour = (int)(ticks / TimeSpan.TicksPerHour);
int minute = (int)((ticks / TimeSpan.TicksPerMinute) % 60);
int second = (int)((ticks / TimeSpan.TicksPerSecond) % 60);
int fractions = (int)(ticks % TimeSpan.TicksPerSecond);
// Adjust the month and year values and rebuild.
if(months < 0)
{
months = -months;
year -= months / 12;
month -= months % 12;
if(month < 1)
{
--year;
month += 12;
}
}
else
{
year += months / 12;
month += months % 12;
if(month > 12)
{
++year;
month -= 12;
}
}
int daysInMonth = daysForEachMonth[month - 1];
if (day > daysInMonth)
{
day = daysInMonth;
}
return new DateTime(year, month, day,
hour, minute, second, fractions);
}
public DateTime AddTicks(long value)
{
return new DateTime(value_ + value);
}
public DateTime AddYears(int years)
{
// Crack open this DateTime value.
int year = Year;
int month = Month;
int day = Day;
long ticks = (value_ % TimeSpan.TicksPerDay);
int hour = (int)(ticks / TimeSpan.TicksPerHour);
int minute = (int)((ticks / TimeSpan.TicksPerMinute) % 60);
int second = (int)((ticks / TimeSpan.TicksPerSecond) % 60);
int fractions = (int)(ticks % TimeSpan.TicksPerSecond);
// Adjust the year value and rebuild.
return new DateTime(year + years, month, day,
hour, minute, second, fractions);
}
#if !ECMA_COMPAT
// Get this DateTime value in a variety of formats.
private String[] GetDateTimeFormats(DateTimeFormatInfo info,
String[] patterns)
{
String[] results = new String [patterns.Length];
int index;
for(index = 0; index < patterns.Length; ++index)
{
results[index] = DateTimeFormatter.Format
(patterns[index], this, info);
}
return results;
}
public String[] GetDateTimeFormats()
{
DateTimeFormatInfo info =
DateTimeFormatInfo.GetInstance(null);
return GetDateTimeFormats(info, info.GetAllDateTimePatterns());
}
public String[] GetDateTimeFormats(char format)
{
DateTimeFormatInfo info =
DateTimeFormatInfo.GetInstance(null);
return GetDateTimeFormats
(info, info.GetAllDateTimePatterns(format));
}
public String[] GetDateTimeFormats(IFormatProvider provider)
{
DateTimeFormatInfo info =
DateTimeFormatInfo.GetInstance(provider);
return GetDateTimeFormats(info, info.GetAllDateTimePatterns());
}
public String[] GetDateTimeFormats(char format, IFormatProvider provider)
{
DateTimeFormatInfo info =
DateTimeFormatInfo.GetInstance(provider);
return GetDateTimeFormats
(info, info.GetAllDateTimePatterns(format));
}
#endif // !ECMA_COMPAT
// Convert this DateTime value into local time.
public DateTime ToLocalTime()
{
return new DateTime
(value_ - ((long)(TimeMethods.GetTimeZoneAdjust(value_))) *
TimeSpan.TicksPerSecond);
}
// Convert this DateTime value into UTC time.
public DateTime ToUniversalTime()
{
return new DateTime
(value_ + ((long)(TimeMethods.GetTimeZoneAdjust(value_))) *
TimeSpan.TicksPerSecond);
}
// Convert this DateTime value into a long date string.
public String ToLongDateString()
{
return ToString("D", null);
}
// Convert this DateTime value into a long time string.
public String ToLongTimeString()
{
return ToString("T", null);
}
// Convert this DateTime value into a short date string.
public String ToShortDateString()
{
return ToString("d", null);
}
// Convert this DateTime value into a short time string.
public String ToShortTimeString()
{
return ToString("t", null);
}
}; // class DateTime
}; // namespace System
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;
using System.Globalization;
using System.Management.Automation;
namespace Microsoft.PowerShell.Commands.Internal.Format
{
internal static class DisplayCondition
{
internal static bool Evaluate(PSObject obj, PSPropertyExpression ex, out PSPropertyExpressionResult expressionResult)
{
expressionResult = null;
List<PSPropertyExpressionResult> res = ex.GetValues(obj);
if (res.Count == 0)
return false;
if (res[0].Exception != null)
{
expressionResult = res[0];
return false;
}
return LanguagePrimitives.IsTrue(res[0].Result);
}
}
/// <summary>
/// Helper object holding a generic object and the related
/// "applies to" object.
/// It is used in by the inheritance based type match algorithm.
/// </summary>
internal sealed class TypeMatchItem
{
internal TypeMatchItem(object obj, AppliesTo a)
{
Item = obj;
AppliesTo = a;
}
internal TypeMatchItem(object obj, AppliesTo a, PSObject currentObject)
{
Item = obj;
AppliesTo = a;
CurrentObject = currentObject;
}
internal object Item { get; }
internal AppliesTo AppliesTo { get; }
internal PSObject CurrentObject { get; }
}
/// <summary>
/// Algorithm to execute a type match on a list of entities
/// having an "applies to" associated object.
/// </summary>
internal sealed class TypeMatch
{
#region tracer
[TraceSource("TypeMatch", "F&O TypeMatch")]
private static readonly PSTraceSource s_classTracer =
PSTraceSource.GetTracer("TypeMatch", "F&O TypeMatch");
private static PSTraceSource s_activeTracer = null;
private static PSTraceSource ActiveTracer
{
get
{
return s_activeTracer ?? s_classTracer;
}
}
internal static void SetTracer(PSTraceSource t)
{
s_activeTracer = t;
}
internal static void ResetTracer()
{
s_activeTracer = s_classTracer;
}
#endregion tracer
internal TypeMatch(PSPropertyExpressionFactory expressionFactory, TypeInfoDataBase db, Collection<string> typeNames)
{
_expressionFactory = expressionFactory;
_db = db;
_typeNameHierarchy = typeNames;
_useInheritance = true;
}
internal TypeMatch(PSPropertyExpressionFactory expressionFactory, TypeInfoDataBase db, Collection<string> typeNames, bool useInheritance)
{
_expressionFactory = expressionFactory;
_db = db;
_typeNameHierarchy = typeNames;
_useInheritance = useInheritance;
}
internal bool PerfectMatch(TypeMatchItem item)
{
int match = ComputeBestMatch(item.AppliesTo, item.CurrentObject);
if (match == BestMatchIndexUndefined)
return false;
if (_bestMatchIndex == BestMatchIndexUndefined ||
match < _bestMatchIndex)
{
_bestMatchIndex = match;
_bestMatchItem = item;
}
return _bestMatchIndex == BestMatchIndexPerfect;
}
internal object BestMatch
{
get
{
if (_bestMatchItem == null)
return null;
return _bestMatchItem.Item;
}
}
private int ComputeBestMatch(AppliesTo appliesTo, PSObject currentObject)
{
int best = BestMatchIndexUndefined;
foreach (TypeOrGroupReference r in appliesTo.referenceList)
{
PSPropertyExpression ex = null;
if (r.conditionToken != null)
{
ex = _expressionFactory.CreateFromExpressionToken(r.conditionToken);
}
int currentMatch = BestMatchIndexUndefined;
TypeReference tr = r as TypeReference;
if (tr != null)
{
// we have a type
currentMatch = MatchTypeIndex(tr.name, currentObject, ex);
}
else
{
// we have a type group reference
TypeGroupReference tgr = r as TypeGroupReference;
// find the type group definition the reference points to
TypeGroupDefinition tgd = DisplayDataQuery.FindGroupDefinition(_db, tgr.name);
if (tgd != null)
{
// we found the group, see if the group has the type
currentMatch = ComputeBestMatchInGroup(tgd, currentObject, ex);
}
}
if (currentMatch == BestMatchIndexPerfect)
return currentMatch;
if (best == BestMatchIndexUndefined || best < currentMatch)
{
best = currentMatch;
}
}
return best;
}
private int ComputeBestMatchInGroup(TypeGroupDefinition tgd, PSObject currentObject, PSPropertyExpression ex)
{
int best = BestMatchIndexUndefined;
int k = 0;
foreach (TypeReference tr in tgd.typeReferenceList)
{
int currentMatch = MatchTypeIndex(tr.name, currentObject, ex);
if (currentMatch == BestMatchIndexPerfect)
return currentMatch;
if (best == BestMatchIndexUndefined || best < currentMatch)
{
best = currentMatch;
}
k++;
}
return best;
}
private int MatchTypeIndex(string typeName, PSObject currentObject, PSPropertyExpression ex)
{
if (string.IsNullOrEmpty(typeName))
return BestMatchIndexUndefined;
int k = 0;
foreach (string name in _typeNameHierarchy)
{
if (string.Equals(name, typeName, StringComparison.OrdinalIgnoreCase)
&& MatchCondition(currentObject, ex))
{
return k;
}
if (k == 0 && !_useInheritance)
break;
k++;
}
return BestMatchIndexUndefined;
}
private bool MatchCondition(PSObject currentObject, PSPropertyExpression ex)
{
if (ex == null)
return true;
PSPropertyExpressionResult expressionResult;
bool retVal = DisplayCondition.Evaluate(currentObject, ex, out expressionResult);
return retVal;
}
private PSPropertyExpressionFactory _expressionFactory;
private TypeInfoDataBase _db;
private Collection<string> _typeNameHierarchy;
private bool _useInheritance;
private int _bestMatchIndex = BestMatchIndexUndefined;
private TypeMatchItem _bestMatchItem;
private const int BestMatchIndexUndefined = -1;
private const int BestMatchIndexPerfect = 0;
}
internal static class DisplayDataQuery
{
#region tracer
[TraceSource("DisplayDataQuery", "DisplayDataQuery")]
private static readonly PSTraceSource s_classTracer =
PSTraceSource.GetTracer("DisplayDataQuery", "DisplayDataQuery");
private static PSTraceSource s_activeTracer = null;
private static PSTraceSource ActiveTracer
{
get
{
return s_activeTracer ?? s_classTracer;
}
}
internal static void SetTracer(PSTraceSource t)
{
s_activeTracer = t;
}
internal static void ResetTracer()
{
s_activeTracer = s_classTracer;
}
#endregion tracer
internal static EnumerableExpansion GetEnumerableExpansionFromType(PSPropertyExpressionFactory expressionFactory, TypeInfoDataBase db, Collection<string> typeNames)
{
TypeMatch match = new TypeMatch(expressionFactory, db, typeNames);
foreach (EnumerableExpansionDirective expansionDirective in db.defaultSettingsSection.enumerableExpansionDirectiveList)
{
if (match.PerfectMatch(new TypeMatchItem(expansionDirective, expansionDirective.appliesTo)))
{
return expansionDirective.enumerableExpansion;
}
}
if (match.BestMatch != null)
{
return ((EnumerableExpansionDirective)(match.BestMatch)).enumerableExpansion;
}
else
{
Collection<string> typesWithoutPrefix = Deserializer.MaskDeserializationPrefix(typeNames);
if (typesWithoutPrefix != null)
{
EnumerableExpansion result = GetEnumerableExpansionFromType(expressionFactory, db, typesWithoutPrefix);
return result;
}
// return a default value if no matches were found
return EnumerableExpansion.EnumOnly;
}
}
internal static FormatShape GetShapeFromType(PSPropertyExpressionFactory expressionFactory, TypeInfoDataBase db, Collection<string> typeNames)
{
ShapeSelectionDirectives shapeDirectives = db.defaultSettingsSection.shapeSelectionDirectives;
TypeMatch match = new TypeMatch(expressionFactory, db, typeNames);
foreach (FormatShapeSelectionOnType shapeSelOnType in shapeDirectives.formatShapeSelectionOnTypeList)
{
if (match.PerfectMatch(new TypeMatchItem(shapeSelOnType, shapeSelOnType.appliesTo)))
{
return shapeSelOnType.formatShape;
}
}
if (match.BestMatch != null)
{
return ((FormatShapeSelectionOnType)(match.BestMatch)).formatShape;
}
else
{
Collection<string> typesWithoutPrefix = Deserializer.MaskDeserializationPrefix(typeNames);
if (typesWithoutPrefix != null)
{
FormatShape result = GetShapeFromType(expressionFactory, db, typesWithoutPrefix);
return result;
}
// return a default value if no matches were found
return FormatShape.Undefined;
}
}
internal static FormatShape GetShapeFromPropertyCount(TypeInfoDataBase db, int propertyCount)
{
if (propertyCount <= db.defaultSettingsSection.shapeSelectionDirectives.PropertyCountForTable)
return FormatShape.Table;
return FormatShape.List;
}
internal static ViewDefinition GetViewByShapeAndType(PSPropertyExpressionFactory expressionFactory, TypeInfoDataBase db,
FormatShape shape, Collection<string> typeNames, string viewName)
{
if (shape == FormatShape.Undefined)
{
return GetDefaultView(expressionFactory, db, typeNames);
}
// map the FormatShape to a type derived from ViewDefinition
System.Type t = null;
if (shape == FormatShape.Table)
{
t = typeof(TableControlBody);
}
else if (shape == FormatShape.List)
{
t = typeof(ListControlBody);
}
else if (shape == FormatShape.Wide)
{
t = typeof(WideControlBody);
}
else if (shape == FormatShape.Complex)
{
t = typeof(ComplexControlBody);
}
else
{
Diagnostics.Assert(false, "unknown shape: this should never happen unless a new shape is added");
return null;
}
return GetView(expressionFactory, db, t, typeNames, viewName);
}
internal static ViewDefinition GetOutOfBandView(PSPropertyExpressionFactory expressionFactory,
TypeInfoDataBase db, Collection<string> typeNames)
{
TypeMatch match = new TypeMatch(expressionFactory, db, typeNames);
foreach (ViewDefinition vd in db.viewDefinitionsSection.viewDefinitionList)
{
if (!IsOutOfBandView(vd))
continue;
if (match.PerfectMatch(new TypeMatchItem(vd, vd.appliesTo)))
{
return vd;
}
}
// this is the best match we had
ViewDefinition result = match.BestMatch as ViewDefinition;
// we were unable to find a best match so far..try
// to get rid of Deserialization prefix and see if a
// match can be found.
if (result == null)
{
Collection<string> typesWithoutPrefix = Deserializer.MaskDeserializationPrefix(typeNames);
if (typesWithoutPrefix != null)
{
result = GetOutOfBandView(expressionFactory, db, typesWithoutPrefix);
}
}
return result;
}
private static ViewDefinition GetView(PSPropertyExpressionFactory expressionFactory, TypeInfoDataBase db, System.Type mainControlType, Collection<string> typeNames, string viewName)
{
TypeMatch match = new TypeMatch(expressionFactory, db, typeNames);
foreach (ViewDefinition vd in db.viewDefinitionsSection.viewDefinitionList)
{
if (vd == null || mainControlType != vd.mainControl.GetType())
{
ActiveTracer.WriteLine(
"NOT MATCH {0} NAME: {1}",
ControlBase.GetControlShapeName(vd.mainControl), (vd != null ? vd.name : string.Empty));
continue;
}
if (IsOutOfBandView(vd))
{
ActiveTracer.WriteLine(
"NOT MATCH OutOfBand {0} NAME: {1}",
ControlBase.GetControlShapeName(vd.mainControl), vd.name);
continue;
}
if (vd.appliesTo == null)
{
ActiveTracer.WriteLine(
"NOT MATCH {0} NAME: {1} No applicable types",
ControlBase.GetControlShapeName(vd.mainControl), vd.name);
continue;
}
// first make sure we match on name:
// if not, we do not try a match at all
if (viewName != null && !string.Equals(vd.name, viewName, StringComparison.OrdinalIgnoreCase))
{
ActiveTracer.WriteLine(
"NOT MATCH {0} NAME: {1}",
ControlBase.GetControlShapeName(vd.mainControl), vd.name);
continue;
}
// check if we have a perfect match
// if so, we are done
try
{
TypeMatch.SetTracer(ActiveTracer);
if (match.PerfectMatch(new TypeMatchItem(vd, vd.appliesTo)))
{
TraceHelper(vd, true);
return vd;
}
}
finally
{
TypeMatch.ResetTracer();
}
TraceHelper(vd, false);
}
// this is the best match we had
ViewDefinition result = GetBestMatch(match);
// we were unable to find a best match so far..try
// to get rid of Deserialization prefix and see if a
// match can be found.
if (result == null)
{
Collection<string> typesWithoutPrefix = Deserializer.MaskDeserializationPrefix(typeNames);
if (typesWithoutPrefix != null)
{
result = GetView(expressionFactory, db, mainControlType, typesWithoutPrefix, viewName);
}
}
return result;
}
private static void TraceHelper(ViewDefinition vd, bool isMatched)
{
if ((ActiveTracer.Options & PSTraceSourceOptions.WriteLine) != 0)
{
foreach (TypeOrGroupReference togr in vd.appliesTo.referenceList)
{
StringBuilder sb = new StringBuilder();
TypeReference tr = togr as TypeReference;
sb.Append(isMatched ? "MATCH FOUND" : "NOT MATCH");
if (tr != null)
{
sb.AppendFormat(CultureInfo.InvariantCulture, " {0} NAME: {1} TYPE: {2}",
ControlBase.GetControlShapeName(vd.mainControl), vd.name, tr.name);
}
else
{
TypeGroupReference tgr = togr as TypeGroupReference;
sb.AppendFormat(CultureInfo.InvariantCulture, " {0} NAME: {1} GROUP: {2}",
ControlBase.GetControlShapeName(vd.mainControl), vd.name, tgr.name);
}
ActiveTracer.WriteLine(sb.ToString());
}
}
}
private static ViewDefinition GetBestMatch(TypeMatch match)
{
ViewDefinition bestMatchedVD = match.BestMatch as ViewDefinition;
if (bestMatchedVD != null)
{
TraceHelper(bestMatchedVD, true);
}
return bestMatchedVD;
}
private static ViewDefinition GetDefaultView(PSPropertyExpressionFactory expressionFactory, TypeInfoDataBase db, Collection<string> typeNames)
{
TypeMatch match = new TypeMatch(expressionFactory, db, typeNames);
foreach (ViewDefinition vd in db.viewDefinitionsSection.viewDefinitionList)
{
if (vd == null)
continue;
if (IsOutOfBandView(vd))
{
ActiveTracer.WriteLine(
"NOT MATCH OutOfBand {0} NAME: {1}",
ControlBase.GetControlShapeName(vd.mainControl), vd.name);
continue;
}
if (vd.appliesTo == null)
{
ActiveTracer.WriteLine(
"NOT MATCH {0} NAME: {1} No applicable types",
ControlBase.GetControlShapeName(vd.mainControl), vd.name);
continue;
}
try
{
TypeMatch.SetTracer(ActiveTracer);
if (match.PerfectMatch(new TypeMatchItem(vd, vd.appliesTo)))
{
TraceHelper(vd, true);
return vd;
}
}
finally
{
TypeMatch.ResetTracer();
}
TraceHelper(vd, false);
}
// this is the best match we had
ViewDefinition result = GetBestMatch(match);
// we were unable to find a best match so far..try
// to get rid of Deserialization prefix and see if a
// match can be found.
if (result == null)
{
Collection<string> typesWithoutPrefix = Deserializer.MaskDeserializationPrefix(typeNames);
if (typesWithoutPrefix != null)
{
result = GetDefaultView(expressionFactory, db, typesWithoutPrefix);
}
}
return result;
}
private static bool IsOutOfBandView(ViewDefinition vd)
{
return (vd.mainControl is ComplexControlBody || vd.mainControl is ListControlBody) && vd.outOfBand;
}
/// <summary>
/// Given an appliesTo list, it finds all the types that are contained (following type
/// group references)
/// </summary>
/// <param name="db">Database to use.</param>
/// <param name="appliesTo">Object to lookup.</param>
/// <returns></returns>
internal static AppliesTo GetAllApplicableTypes(TypeInfoDataBase db, AppliesTo appliesTo)
{
Hashtable allTypes = new Hashtable(StringComparer.OrdinalIgnoreCase);
foreach (TypeOrGroupReference r in appliesTo.referenceList)
{
// if it is a type reference, just add the type name
TypeReference tr = r as TypeReference;
if (tr != null)
{
if (!allTypes.ContainsKey(tr.name))
allTypes.Add(tr.name, null);
}
else
{
// check if we have a type group reference
TypeGroupReference tgr = r as TypeGroupReference;
if (tgr == null)
continue;
// find the type group definition the reference points to
TypeGroupDefinition tgd = FindGroupDefinition(db, tgr.name);
if (tgd == null)
continue;
// we found the group, go over it
foreach (TypeReference x in tgd.typeReferenceList)
{
if (!allTypes.ContainsKey(x.name))
allTypes.Add(x.name, null);
}
}
}
AppliesTo retVal = new AppliesTo();
foreach (DictionaryEntry x in allTypes)
{
retVal.AddAppliesToType(x.Key as string);
}
return retVal;
}
internal static TypeGroupDefinition FindGroupDefinition(TypeInfoDataBase db, string groupName)
{
foreach (TypeGroupDefinition tgd in db.typeGroupSection.typeGroupDefinitionList)
{
if (string.Equals(tgd.name, groupName, StringComparison.OrdinalIgnoreCase))
return tgd;
}
return null;
}
internal static ControlBody ResolveControlReference(TypeInfoDataBase db, List<ControlDefinition> viewControlDefinitionList,
ControlReference controlReference)
{
// first tri to resolve the reference at the view level
ControlBody controlBody = ResolveControlReferenceInList(controlReference,
viewControlDefinitionList);
if (controlBody != null)
return controlBody;
// fall back to the global definitions
return ResolveControlReferenceInList(controlReference, db.formatControlDefinitionHolder.controlDefinitionList);
}
private static ControlBody ResolveControlReferenceInList(ControlReference controlReference,
List<ControlDefinition> controlDefinitionList)
{
foreach (ControlDefinition x in controlDefinitionList)
{
if (x.controlBody.GetType() != controlReference.controlType)
continue;
if (string.Compare(controlReference.name, x.name, StringComparison.OrdinalIgnoreCase) == 0)
return x.controlBody;
}
return null;
}
}
}
| |
using Microsoft.IdentityModel.S2S.Protocols.OAuth2;
using Microsoft.IdentityModel.Tokens;
using Microsoft.SharePoint.Client;
using System;
using System.Net;
using System.Security.Principal;
using System.Web;
using System.Web.Configuration;
namespace Core.RibbonCommandsWeb
{
/// <summary>
/// Encapsulates all the information from SharePoint.
/// </summary>
public abstract class SharePointContext
{
public const string SPHostUrlKey = "SPHostUrl";
public const string SPAppWebUrlKey = "SPAppWebUrl";
public const string SPLanguageKey = "SPLanguage";
public const string SPClientTagKey = "SPClientTag";
public const string SPProductNumberKey = "SPProductNumber";
protected static readonly TimeSpan AccessTokenLifetimeTolerance = TimeSpan.FromMinutes(5.0);
private readonly Uri spHostUrl;
private readonly Uri spAppWebUrl;
private readonly string spLanguage;
private readonly string spClientTag;
private readonly string spProductNumber;
// <AccessTokenString, UtcExpiresOn>
protected Tuple<string, DateTime> userAccessTokenForSPHost;
protected Tuple<string, DateTime> userAccessTokenForSPAppWeb;
protected Tuple<string, DateTime> appOnlyAccessTokenForSPHost;
protected Tuple<string, DateTime> appOnlyAccessTokenForSPAppWeb;
/// <summary>
/// Gets the SharePoint host url from QueryString of the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The specified HTTP request.</param>
/// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns>
public static Uri GetSPHostUrl(HttpRequestBase httpRequest)
{
if (httpRequest == null)
{
throw new ArgumentNullException("httpRequest");
}
string spHostUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SPHostUrlKey]);
Uri spHostUrl;
if (Uri.TryCreate(spHostUrlString, UriKind.Absolute, out spHostUrl) &&
(spHostUrl.Scheme == Uri.UriSchemeHttp || spHostUrl.Scheme == Uri.UriSchemeHttps))
{
return spHostUrl;
}
return null;
}
/// <summary>
/// Gets the SharePoint host url from QueryString of the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The specified HTTP request.</param>
/// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns>
public static Uri GetSPHostUrl(HttpRequest httpRequest)
{
return GetSPHostUrl(new HttpRequestWrapper(httpRequest));
}
/// <summary>
/// The SharePoint host url.
/// </summary>
public Uri SPHostUrl
{
get { return this.spHostUrl; }
}
/// <summary>
/// The SharePoint app web url.
/// </summary>
public Uri SPAppWebUrl
{
get { return this.spAppWebUrl; }
}
/// <summary>
/// The SharePoint language.
/// </summary>
public string SPLanguage
{
get { return this.spLanguage; }
}
/// <summary>
/// The SharePoint client tag.
/// </summary>
public string SPClientTag
{
get { return this.spClientTag; }
}
/// <summary>
/// The SharePoint product number.
/// </summary>
public string SPProductNumber
{
get { return this.spProductNumber; }
}
/// <summary>
/// The user access token for the SharePoint host.
/// </summary>
public abstract string UserAccessTokenForSPHost
{
get;
}
/// <summary>
/// The user access token for the SharePoint app web.
/// </summary>
public abstract string UserAccessTokenForSPAppWeb
{
get;
}
/// <summary>
/// The app only access token for the SharePoint host.
/// </summary>
public abstract string AppOnlyAccessTokenForSPHost
{
get;
}
/// <summary>
/// The app only access token for the SharePoint app web.
/// </summary>
public abstract string AppOnlyAccessTokenForSPAppWeb
{
get;
}
/// <summary>
/// Constructor.
/// </summary>
/// <param name="spHostUrl">The SharePoint host url.</param>
/// <param name="spAppWebUrl">The SharePoint app web url.</param>
/// <param name="spLanguage">The SharePoint language.</param>
/// <param name="spClientTag">The SharePoint client tag.</param>
/// <param name="spProductNumber">The SharePoint product number.</param>
protected SharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber)
{
if (spHostUrl == null)
{
throw new ArgumentNullException("spHostUrl");
}
if (string.IsNullOrEmpty(spLanguage))
{
throw new ArgumentNullException("spLanguage");
}
if (string.IsNullOrEmpty(spClientTag))
{
throw new ArgumentNullException("spClientTag");
}
if (string.IsNullOrEmpty(spProductNumber))
{
throw new ArgumentNullException("spProductNumber");
}
this.spHostUrl = spHostUrl;
this.spAppWebUrl = spAppWebUrl;
this.spLanguage = spLanguage;
this.spClientTag = spClientTag;
this.spProductNumber = spProductNumber;
}
/// <summary>
/// Creates a user ClientContext for the SharePoint host.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateUserClientContextForSPHost()
{
return CreateClientContext(this.SPHostUrl, this.UserAccessTokenForSPHost);
}
/// <summary>
/// Creates a user ClientContext for the SharePoint app web.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateUserClientContextForSPAppWeb()
{
return CreateClientContext(this.SPAppWebUrl, this.UserAccessTokenForSPAppWeb);
}
/// <summary>
/// Creates app only ClientContext for the SharePoint host.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateAppOnlyClientContextForSPHost()
{
return CreateClientContext(this.SPHostUrl, this.AppOnlyAccessTokenForSPHost);
}
/// <summary>
/// Creates an app only ClientContext for the SharePoint app web.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateAppOnlyClientContextForSPAppWeb()
{
return CreateClientContext(this.SPAppWebUrl, this.AppOnlyAccessTokenForSPAppWeb);
}
/// <summary>
/// Gets the database connection string from SharePoint for autohosted app.
/// </summary>
/// <returns>The database connection string. Returns <c>null</c> if the app is not autohosted or there is no database.</returns>
public string GetDatabaseConnectionString()
{
string dbConnectionString = null;
using (ClientContext clientContext = CreateAppOnlyClientContextForSPHost())
{
if (clientContext != null)
{
var result = AppInstance.RetrieveAppDatabaseConnectionString(clientContext);
clientContext.ExecuteQuery();
dbConnectionString = result.Value;
}
}
if (dbConnectionString == null)
{
const string LocalDBInstanceForDebuggingKey = "LocalDBInstanceForDebugging";
var dbConnectionStringSettings = WebConfigurationManager.ConnectionStrings[LocalDBInstanceForDebuggingKey];
dbConnectionString = dbConnectionStringSettings != null ? dbConnectionStringSettings.ConnectionString : null;
}
return dbConnectionString;
}
/// <summary>
/// Determines if the specified access token is valid.
/// It considers an access token as not valid if it is null, or it has expired.
/// </summary>
/// <param name="accessToken">The access token to verify.</param>
/// <returns>True if the access token is valid.</returns>
protected static bool IsAccessTokenValid(Tuple<string, DateTime> accessToken)
{
return accessToken != null &&
!string.IsNullOrEmpty(accessToken.Item1) &&
accessToken.Item2 > DateTime.UtcNow;
}
/// <summary>
/// Creates a ClientContext with the specified SharePoint site url and the access token.
/// </summary>
/// <param name="spSiteUrl">The site url.</param>
/// <param name="accessToken">The access token.</param>
/// <returns>A ClientContext instance.</returns>
private static ClientContext CreateClientContext(Uri spSiteUrl, string accessToken)
{
if (spSiteUrl != null && !string.IsNullOrEmpty(accessToken))
{
return TokenHelper.GetClientContextWithAccessToken(spSiteUrl.AbsoluteUri, accessToken);
}
return null;
}
}
/// <summary>
/// Redirection status.
/// </summary>
public enum RedirectionStatus
{
Ok,
ShouldRedirect,
CanNotRedirect
}
/// <summary>
/// Provides SharePointContext instances.
/// </summary>
public abstract class SharePointContextProvider
{
private static SharePointContextProvider current;
/// <summary>
/// The current SharePointContextProvider instance.
/// </summary>
public static SharePointContextProvider Current
{
get { return SharePointContextProvider.current; }
}
/// <summary>
/// Initializes the default SharePointContextProvider instance.
/// </summary>
static SharePointContextProvider()
{
if (!TokenHelper.IsHighTrustApp())
{
SharePointContextProvider.current = new SharePointAcsContextProvider();
}
else
{
SharePointContextProvider.current = new SharePointHighTrustContextProvider();
}
}
/// <summary>
/// Registers the specified SharePointContextProvider instance as current.
/// It should be called by Application_Start() in Global.asax.
/// </summary>
/// <param name="provider">The SharePointContextProvider to be set as current.</param>
public static void Register(SharePointContextProvider provider)
{
if (provider == null)
{
throw new ArgumentNullException("provider");
}
SharePointContextProvider.current = provider;
}
/// <summary>
/// Checks if it is necessary to redirect to SharePoint for user to authenticate.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param>
/// <returns>Redirection status.</returns>
public static RedirectionStatus CheckRedirectionStatus(HttpContextBase httpContext, out Uri redirectUrl)
{
if (httpContext == null)
{
throw new ArgumentNullException("httpContext");
}
redirectUrl = null;
if (SharePointContextProvider.Current.GetSharePointContext(httpContext) != null)
{
return RedirectionStatus.Ok;
}
const string SPHasRedirectedToSharePointKey = "SPHasRedirectedToSharePoint";
if (!string.IsNullOrEmpty(httpContext.Request.QueryString[SPHasRedirectedToSharePointKey]))
{
return RedirectionStatus.CanNotRedirect;
}
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
if (spHostUrl == null)
{
return RedirectionStatus.CanNotRedirect;
}
if (StringComparer.OrdinalIgnoreCase.Equals(httpContext.Request.HttpMethod, "POST"))
{
return RedirectionStatus.CanNotRedirect;
}
Uri requestUrl = httpContext.Request.Url;
var queryNameValueCollection = HttpUtility.ParseQueryString(requestUrl.Query);
// Removes the values that are included in {StandardTokens}, as {StandardTokens} will be inserted at the beginning of the query string.
queryNameValueCollection.Remove(SharePointContext.SPHostUrlKey);
queryNameValueCollection.Remove(SharePointContext.SPAppWebUrlKey);
queryNameValueCollection.Remove(SharePointContext.SPLanguageKey);
queryNameValueCollection.Remove(SharePointContext.SPClientTagKey);
queryNameValueCollection.Remove(SharePointContext.SPProductNumberKey);
// Adds SPHasRedirectedToSharePoint=1.
queryNameValueCollection.Add(SPHasRedirectedToSharePointKey, "1");
UriBuilder returnUrlBuilder = new UriBuilder(requestUrl);
returnUrlBuilder.Query = queryNameValueCollection.ToString();
// Inserts StandardTokens.
const string StandardTokens = "{StandardTokens}";
string returnUrlString = returnUrlBuilder.Uri.AbsoluteUri;
returnUrlString = returnUrlString.Insert(returnUrlString.IndexOf("?") + 1, StandardTokens + "&");
// Constructs redirect url.
string redirectUrlString = TokenHelper.GetAppContextTokenRequestUrl(spHostUrl.AbsoluteUri, Uri.EscapeDataString(returnUrlString));
redirectUrl = new Uri(redirectUrlString, UriKind.Absolute);
return RedirectionStatus.ShouldRedirect;
}
/// <summary>
/// Checks if it is necessary to redirect to SharePoint for user to authenticate.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param>
/// <returns>Redirection status.</returns>
public static RedirectionStatus CheckRedirectionStatus(HttpContext httpContext, out Uri redirectUrl)
{
return CheckRedirectionStatus(new HttpContextWrapper(httpContext), out redirectUrl);
}
/// <summary>
/// Creates a SharePointContext instance with the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The HTTP request.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns>
public SharePointContext CreateSharePointContext(HttpRequestBase httpRequest)
{
if (httpRequest == null)
{
throw new ArgumentNullException("httpRequest");
}
// SPHostUrl
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpRequest);
if (spHostUrl == null)
{
return null;
}
// SPAppWebUrl
string spAppWebUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SharePointContext.SPAppWebUrlKey]);
Uri spAppWebUrl;
if (!Uri.TryCreate(spAppWebUrlString, UriKind.Absolute, out spAppWebUrl) ||
!(spAppWebUrl.Scheme == Uri.UriSchemeHttp || spAppWebUrl.Scheme == Uri.UriSchemeHttps))
{
spAppWebUrl = null;
}
// SPLanguage
string spLanguage = httpRequest.QueryString[SharePointContext.SPLanguageKey];
if (string.IsNullOrEmpty(spLanguage))
{
return null;
}
// SPClientTag
string spClientTag = httpRequest.QueryString[SharePointContext.SPClientTagKey];
if (string.IsNullOrEmpty(spClientTag))
{
return null;
}
// SPProductNumber
string spProductNumber = httpRequest.QueryString[SharePointContext.SPProductNumberKey];
if (string.IsNullOrEmpty(spProductNumber))
{
return null;
}
return CreateSharePointContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, httpRequest);
}
/// <summary>
/// Creates a SharePointContext instance with the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The HTTP request.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns>
public SharePointContext CreateSharePointContext(HttpRequest httpRequest)
{
return CreateSharePointContext(new HttpRequestWrapper(httpRequest));
}
/// <summary>
/// Gets a SharePointContext instance associated with the specified HTTP context.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns>
public SharePointContext GetSharePointContext(HttpContextBase httpContext)
{
if (httpContext == null)
{
throw new ArgumentNullException("httpContext");
}
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
if (spHostUrl == null)
{
return null;
}
SharePointContext spContext = LoadSharePointContext(httpContext);
if (spContext == null || !ValidateSharePointContext(spContext, httpContext))
{
spContext = CreateSharePointContext(httpContext.Request);
if (spContext != null)
{
SaveSharePointContext(spContext, httpContext);
}
}
return spContext;
}
/// <summary>
/// Gets a SharePointContext instance associated with the specified HTTP context.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns>
public SharePointContext GetSharePointContext(HttpContext httpContext)
{
return GetSharePointContext(new HttpContextWrapper(httpContext));
}
/// <summary>
/// Creates a SharePointContext instance.
/// </summary>
/// <param name="spHostUrl">The SharePoint host url.</param>
/// <param name="spAppWebUrl">The SharePoint app web url.</param>
/// <param name="spLanguage">The SharePoint language.</param>
/// <param name="spClientTag">The SharePoint client tag.</param>
/// <param name="spProductNumber">The SharePoint product number.</param>
/// <param name="httpRequest">The HTTP request.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns>
protected abstract SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest);
/// <summary>
/// Validates if the given SharePointContext can be used with the specified HTTP context.
/// </summary>
/// <param name="spContext">The SharePointContext.</param>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>True if the given SharePointContext can be used with the specified HTTP context.</returns>
protected abstract bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext);
/// <summary>
/// Loads the SharePointContext instance associated with the specified HTTP context.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if not found.</returns>
protected abstract SharePointContext LoadSharePointContext(HttpContextBase httpContext);
/// <summary>
/// Saves the specified SharePointContext instance associated with the specified HTTP context.
/// <c>null</c> is accepted for clearing the SharePointContext instance associated with the HTTP context.
/// </summary>
/// <param name="spContext">The SharePointContext instance to be saved, or <c>null</c>.</param>
/// <param name="httpContext">The HTTP context.</param>
protected abstract void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext);
}
#region ACS
/// <summary>
/// Encapsulates all the information from SharePoint in ACS mode.
/// </summary>
public class SharePointAcsContext : SharePointContext
{
private readonly string contextToken;
private readonly SharePointContextToken contextTokenObj;
/// <summary>
/// The context token.
/// </summary>
public string ContextToken
{
get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextToken : null; }
}
/// <summary>
/// The context token's "CacheKey" claim.
/// </summary>
public string CacheKey
{
get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.CacheKey : null; }
}
/// <summary>
/// The context token's "refreshtoken" claim.
/// </summary>
public string RefreshToken
{
get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.RefreshToken : null; }
}
public override string UserAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.userAccessTokenForSPHost,
() => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPHostUrl.Authority));
}
}
public override string UserAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb,
() => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPAppWebUrl.Authority));
}
}
public override string AppOnlyAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost,
() => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPHostUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPHostUrl)));
}
}
public override string AppOnlyAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb,
() => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPAppWebUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPAppWebUrl)));
}
}
public SharePointAcsContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, string contextToken, SharePointContextToken contextTokenObj)
: base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber)
{
if (string.IsNullOrEmpty(contextToken))
{
throw new ArgumentNullException("contextToken");
}
if (contextTokenObj == null)
{
throw new ArgumentNullException("contextTokenObj");
}
this.contextToken = contextToken;
this.contextTokenObj = contextTokenObj;
}
/// <summary>
/// Ensures the access token is valid and returns it.
/// </summary>
/// <param name="accessToken">The access token to verify.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
/// <returns>The access token string.</returns>
private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler)
{
RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler);
return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null;
}
/// <summary>
/// Renews the access token if it is not valid.
/// </summary>
/// <param name="accessToken">The access token to renew.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler)
{
if (IsAccessTokenValid(accessToken))
{
return;
}
try
{
OAuth2AccessTokenResponse oAuth2AccessTokenResponse = tokenRenewalHandler();
DateTime expiresOn = oAuth2AccessTokenResponse.ExpiresOn;
if ((expiresOn - oAuth2AccessTokenResponse.NotBefore) > AccessTokenLifetimeTolerance)
{
// Make the access token get renewed a bit earlier than the time when it expires
// so that the calls to SharePoint with it will have enough time to complete successfully.
expiresOn -= AccessTokenLifetimeTolerance;
}
accessToken = Tuple.Create(oAuth2AccessTokenResponse.AccessToken, expiresOn);
}
catch (WebException)
{
}
}
}
/// <summary>
/// Default provider for SharePointAcsContext.
/// </summary>
public class SharePointAcsContextProvider : SharePointContextProvider
{
private const string SPContextKey = "SPContext";
private const string SPCacheKeyKey = "SPCacheKey";
protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest)
{
string contextTokenString = TokenHelper.GetContextTokenFromRequest(httpRequest);
if (string.IsNullOrEmpty(contextTokenString))
{
return null;
}
SharePointContextToken contextToken = null;
try
{
contextToken = TokenHelper.ReadAndValidateContextToken(contextTokenString, httpRequest.Url.Authority);
}
catch (WebException)
{
return null;
}
catch (AudienceUriValidationFailedException)
{
return null;
}
return new SharePointAcsContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, contextTokenString, contextToken);
}
protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
SharePointAcsContext spAcsContext = spContext as SharePointAcsContext;
if (spAcsContext != null)
{
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
string contextToken = TokenHelper.GetContextTokenFromRequest(httpContext.Request);
HttpCookie spCacheKeyCookie = httpContext.Request.Cookies[SPCacheKeyKey];
string spCacheKey = spCacheKeyCookie != null ? spCacheKeyCookie.Value : null;
return spHostUrl == spAcsContext.SPHostUrl &&
!string.IsNullOrEmpty(spAcsContext.CacheKey) &&
spCacheKey == spAcsContext.CacheKey &&
!string.IsNullOrEmpty(spAcsContext.ContextToken) &&
(string.IsNullOrEmpty(contextToken) || contextToken == spAcsContext.ContextToken);
}
return false;
}
protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext)
{
return httpContext.Session[SPContextKey] as SharePointAcsContext;
}
protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
SharePointAcsContext spAcsContext = spContext as SharePointAcsContext;
if (spAcsContext != null)
{
HttpCookie spCacheKeyCookie = new HttpCookie(SPCacheKeyKey)
{
Value = spAcsContext.CacheKey,
Secure = true,
HttpOnly = true
};
httpContext.Response.AppendCookie(spCacheKeyCookie);
}
httpContext.Session[SPContextKey] = spAcsContext;
}
}
#endregion ACS
#region HighTrust
/// <summary>
/// Encapsulates all the information from SharePoint in HighTrust mode.
/// </summary>
public class SharePointHighTrustContext : SharePointContext
{
private readonly WindowsIdentity logonUserIdentity;
/// <summary>
/// The Windows identity for the current user.
/// </summary>
public WindowsIdentity LogonUserIdentity
{
get { return this.logonUserIdentity; }
}
public override string UserAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.userAccessTokenForSPHost,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, this.LogonUserIdentity));
}
}
public override string UserAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, this.LogonUserIdentity));
}
}
public override string AppOnlyAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, null));
}
}
public override string AppOnlyAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, null));
}
}
public SharePointHighTrustContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, WindowsIdentity logonUserIdentity)
: base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber)
{
if (logonUserIdentity == null)
{
throw new ArgumentNullException("logonUserIdentity");
}
this.logonUserIdentity = logonUserIdentity;
}
/// <summary>
/// Ensures the access token is valid and returns it.
/// </summary>
/// <param name="accessToken">The access token to verify.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
/// <returns>The access token string.</returns>
private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler)
{
RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler);
return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null;
}
/// <summary>
/// Renews the access token if it is not valid.
/// </summary>
/// <param name="accessToken">The access token to renew.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler)
{
if (IsAccessTokenValid(accessToken))
{
return;
}
DateTime expiresOn = DateTime.UtcNow.Add(TokenHelper.HighTrustAccessTokenLifetime);
if (TokenHelper.HighTrustAccessTokenLifetime > AccessTokenLifetimeTolerance)
{
// Make the access token get renewed a bit earlier than the time when it expires
// so that the calls to SharePoint with it will have enough time to complete successfully.
expiresOn -= AccessTokenLifetimeTolerance;
}
accessToken = Tuple.Create(tokenRenewalHandler(), expiresOn);
}
}
/// <summary>
/// Default provider for SharePointHighTrustContext.
/// </summary>
public class SharePointHighTrustContextProvider : SharePointContextProvider
{
private const string SPContextKey = "SPContext";
protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest)
{
WindowsIdentity logonUserIdentity = httpRequest.LogonUserIdentity;
if (logonUserIdentity == null || !logonUserIdentity.IsAuthenticated || logonUserIdentity.IsGuest || logonUserIdentity.User == null)
{
return null;
}
return new SharePointHighTrustContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, logonUserIdentity);
}
protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
SharePointHighTrustContext spHighTrustContext = spContext as SharePointHighTrustContext;
if (spHighTrustContext != null)
{
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
WindowsIdentity logonUserIdentity = httpContext.Request.LogonUserIdentity;
return spHostUrl == spHighTrustContext.SPHostUrl &&
logonUserIdentity != null &&
logonUserIdentity.IsAuthenticated &&
!logonUserIdentity.IsGuest &&
logonUserIdentity.User == spHighTrustContext.LogonUserIdentity.User;
}
return false;
}
protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext)
{
return httpContext.Session[SPContextKey] as SharePointHighTrustContext;
}
protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
httpContext.Session[SPContextKey] = spContext as SharePointHighTrustContext;
}
}
#endregion HighTrust
}
| |
/// This code was generated by
/// \ / _ _ _| _ _
/// | (_)\/(_)(_|\/| |(/_ v1.0.0
/// / /
/// <summary>
/// ParticipantResource
/// </summary>
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using Twilio.Base;
using Twilio.Clients;
using Twilio.Converters;
using Twilio.Exceptions;
using Twilio.Http;
using Twilio.Types;
namespace Twilio.Rest.Video.V1.Room
{
public class ParticipantResource : Resource
{
public sealed class StatusEnum : StringEnum
{
private StatusEnum(string value) : base(value) {}
public StatusEnum() {}
public static implicit operator StatusEnum(string value)
{
return new StatusEnum(value);
}
public static readonly StatusEnum Connected = new StatusEnum("connected");
public static readonly StatusEnum Disconnected = new StatusEnum("disconnected");
}
private static Request BuildFetchRequest(FetchParticipantOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Get,
Rest.Domain.Video,
"/v1/Rooms/" + options.PathRoomSid + "/Participants/" + options.PathSid + "",
queryParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// fetch
/// </summary>
/// <param name="options"> Fetch Participant parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Participant </returns>
public static ParticipantResource Fetch(FetchParticipantOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildFetchRequest(options, client));
return FromJson(response.Content);
}
#if !NET35
/// <summary>
/// fetch
/// </summary>
/// <param name="options"> Fetch Participant parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Participant </returns>
public static async System.Threading.Tasks.Task<ParticipantResource> FetchAsync(FetchParticipantOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildFetchRequest(options, client));
return FromJson(response.Content);
}
#endif
/// <summary>
/// fetch
/// </summary>
/// <param name="pathRoomSid"> The SID of the room with the Participant resource to fetch </param>
/// <param name="pathSid"> The SID that identifies the resource to fetch </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Participant </returns>
public static ParticipantResource Fetch(string pathRoomSid, string pathSid, ITwilioRestClient client = null)
{
var options = new FetchParticipantOptions(pathRoomSid, pathSid);
return Fetch(options, client);
}
#if !NET35
/// <summary>
/// fetch
/// </summary>
/// <param name="pathRoomSid"> The SID of the room with the Participant resource to fetch </param>
/// <param name="pathSid"> The SID that identifies the resource to fetch </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Participant </returns>
public static async System.Threading.Tasks.Task<ParticipantResource> FetchAsync(string pathRoomSid,
string pathSid,
ITwilioRestClient client = null)
{
var options = new FetchParticipantOptions(pathRoomSid, pathSid);
return await FetchAsync(options, client);
}
#endif
private static Request BuildReadRequest(ReadParticipantOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Get,
Rest.Domain.Video,
"/v1/Rooms/" + options.PathRoomSid + "/Participants",
queryParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// read
/// </summary>
/// <param name="options"> Read Participant parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Participant </returns>
public static ResourceSet<ParticipantResource> Read(ReadParticipantOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildReadRequest(options, client));
var page = Page<ParticipantResource>.FromJson("participants", response.Content);
return new ResourceSet<ParticipantResource>(page, options, client);
}
#if !NET35
/// <summary>
/// read
/// </summary>
/// <param name="options"> Read Participant parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Participant </returns>
public static async System.Threading.Tasks.Task<ResourceSet<ParticipantResource>> ReadAsync(ReadParticipantOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildReadRequest(options, client));
var page = Page<ParticipantResource>.FromJson("participants", response.Content);
return new ResourceSet<ParticipantResource>(page, options, client);
}
#endif
/// <summary>
/// read
/// </summary>
/// <param name="pathRoomSid"> The SID of the room with the Participant resources to read </param>
/// <param name="status"> Read only the participants with this status </param>
/// <param name="identity"> Read only the Participants with this user identity value </param>
/// <param name="dateCreatedAfter"> Read only Participants that started after this date in UTC ISO 8601 format </param>
/// <param name="dateCreatedBefore"> Read only Participants that started before this date in ISO 8601 format </param>
/// <param name="pageSize"> Page size </param>
/// <param name="limit"> Record limit </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Participant </returns>
public static ResourceSet<ParticipantResource> Read(string pathRoomSid,
ParticipantResource.StatusEnum status = null,
string identity = null,
DateTime? dateCreatedAfter = null,
DateTime? dateCreatedBefore = null,
int? pageSize = null,
long? limit = null,
ITwilioRestClient client = null)
{
var options = new ReadParticipantOptions(pathRoomSid){Status = status, Identity = identity, DateCreatedAfter = dateCreatedAfter, DateCreatedBefore = dateCreatedBefore, PageSize = pageSize, Limit = limit};
return Read(options, client);
}
#if !NET35
/// <summary>
/// read
/// </summary>
/// <param name="pathRoomSid"> The SID of the room with the Participant resources to read </param>
/// <param name="status"> Read only the participants with this status </param>
/// <param name="identity"> Read only the Participants with this user identity value </param>
/// <param name="dateCreatedAfter"> Read only Participants that started after this date in UTC ISO 8601 format </param>
/// <param name="dateCreatedBefore"> Read only Participants that started before this date in ISO 8601 format </param>
/// <param name="pageSize"> Page size </param>
/// <param name="limit"> Record limit </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Participant </returns>
public static async System.Threading.Tasks.Task<ResourceSet<ParticipantResource>> ReadAsync(string pathRoomSid,
ParticipantResource.StatusEnum status = null,
string identity = null,
DateTime? dateCreatedAfter = null,
DateTime? dateCreatedBefore = null,
int? pageSize = null,
long? limit = null,
ITwilioRestClient client = null)
{
var options = new ReadParticipantOptions(pathRoomSid){Status = status, Identity = identity, DateCreatedAfter = dateCreatedAfter, DateCreatedBefore = dateCreatedBefore, PageSize = pageSize, Limit = limit};
return await ReadAsync(options, client);
}
#endif
/// <summary>
/// Fetch the target page of records
/// </summary>
/// <param name="targetUrl"> API-generated URL for the requested results page </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> The target page of records </returns>
public static Page<ParticipantResource> GetPage(string targetUrl, ITwilioRestClient client)
{
client = client ?? TwilioClient.GetRestClient();
var request = new Request(
HttpMethod.Get,
targetUrl
);
var response = client.Request(request);
return Page<ParticipantResource>.FromJson("participants", response.Content);
}
/// <summary>
/// Fetch the next page of records
/// </summary>
/// <param name="page"> current page of records </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> The next page of records </returns>
public static Page<ParticipantResource> NextPage(Page<ParticipantResource> page, ITwilioRestClient client)
{
var request = new Request(
HttpMethod.Get,
page.GetNextPageUrl(Rest.Domain.Video)
);
var response = client.Request(request);
return Page<ParticipantResource>.FromJson("participants", response.Content);
}
/// <summary>
/// Fetch the previous page of records
/// </summary>
/// <param name="page"> current page of records </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> The previous page of records </returns>
public static Page<ParticipantResource> PreviousPage(Page<ParticipantResource> page, ITwilioRestClient client)
{
var request = new Request(
HttpMethod.Get,
page.GetPreviousPageUrl(Rest.Domain.Video)
);
var response = client.Request(request);
return Page<ParticipantResource>.FromJson("participants", response.Content);
}
private static Request BuildUpdateRequest(UpdateParticipantOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Post,
Rest.Domain.Video,
"/v1/Rooms/" + options.PathRoomSid + "/Participants/" + options.PathSid + "",
postParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// update
/// </summary>
/// <param name="options"> Update Participant parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Participant </returns>
public static ParticipantResource Update(UpdateParticipantOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildUpdateRequest(options, client));
return FromJson(response.Content);
}
#if !NET35
/// <summary>
/// update
/// </summary>
/// <param name="options"> Update Participant parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Participant </returns>
public static async System.Threading.Tasks.Task<ParticipantResource> UpdateAsync(UpdateParticipantOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildUpdateRequest(options, client));
return FromJson(response.Content);
}
#endif
/// <summary>
/// update
/// </summary>
/// <param name="pathRoomSid"> The SID of the room with the participant to update </param>
/// <param name="pathSid"> The SID that identifies the resource to update </param>
/// <param name="status"> The new status of the resource </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Participant </returns>
public static ParticipantResource Update(string pathRoomSid,
string pathSid,
ParticipantResource.StatusEnum status = null,
ITwilioRestClient client = null)
{
var options = new UpdateParticipantOptions(pathRoomSid, pathSid){Status = status};
return Update(options, client);
}
#if !NET35
/// <summary>
/// update
/// </summary>
/// <param name="pathRoomSid"> The SID of the room with the participant to update </param>
/// <param name="pathSid"> The SID that identifies the resource to update </param>
/// <param name="status"> The new status of the resource </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Participant </returns>
public static async System.Threading.Tasks.Task<ParticipantResource> UpdateAsync(string pathRoomSid,
string pathSid,
ParticipantResource.StatusEnum status = null,
ITwilioRestClient client = null)
{
var options = new UpdateParticipantOptions(pathRoomSid, pathSid){Status = status};
return await UpdateAsync(options, client);
}
#endif
/// <summary>
/// Converts a JSON string into a ParticipantResource object
/// </summary>
/// <param name="json"> Raw JSON string </param>
/// <returns> ParticipantResource object represented by the provided JSON </returns>
public static ParticipantResource FromJson(string json)
{
// Convert all checked exceptions to Runtime
try
{
return JsonConvert.DeserializeObject<ParticipantResource>(json);
}
catch (JsonException e)
{
throw new ApiException(e.Message, e);
}
}
/// <summary>
/// The unique string that identifies the resource
/// </summary>
[JsonProperty("sid")]
public string Sid { get; private set; }
/// <summary>
/// The SID of the participant's room
/// </summary>
[JsonProperty("room_sid")]
public string RoomSid { get; private set; }
/// <summary>
/// The SID of the Account that created the resource
/// </summary>
[JsonProperty("account_sid")]
public string AccountSid { get; private set; }
/// <summary>
/// The status of the Participant
/// </summary>
[JsonProperty("status")]
[JsonConverter(typeof(StringEnumConverter))]
public ParticipantResource.StatusEnum Status { get; private set; }
/// <summary>
/// The string that identifies the resource's User
/// </summary>
[JsonProperty("identity")]
public string Identity { get; private set; }
/// <summary>
/// The ISO 8601 date and time in GMT when the resource was created
/// </summary>
[JsonProperty("date_created")]
public DateTime? DateCreated { get; private set; }
/// <summary>
/// The ISO 8601 date and time in GMT when the resource was last updated
/// </summary>
[JsonProperty("date_updated")]
public DateTime? DateUpdated { get; private set; }
/// <summary>
/// The time of participant connected to the room in ISO 8601 format
/// </summary>
[JsonProperty("start_time")]
public DateTime? StartTime { get; private set; }
/// <summary>
/// The time when the participant disconnected from the room in ISO 8601 format
/// </summary>
[JsonProperty("end_time")]
public DateTime? EndTime { get; private set; }
/// <summary>
/// Duration of time in seconds the participant was connected
/// </summary>
[JsonProperty("duration")]
public int? Duration { get; private set; }
/// <summary>
/// The absolute URL of the resource
/// </summary>
[JsonProperty("url")]
public Uri Url { get; private set; }
/// <summary>
/// The URLs of related resources
/// </summary>
[JsonProperty("links")]
public Dictionary<string, string> Links { get; private set; }
private ParticipantResource()
{
}
}
}
| |
//
// iterators.cs: Support for implementing iterators
//
// Author:
// Miguel de Icaza (miguel@ximian.com)
// Marek Safar (marek.safar@gmail.com)
//
// Dual licensed under the terms of the MIT X11 or GNU GPL
// Copyright 2003 Ximian, Inc.
// Copyright 2003-2008 Novell, Inc.
// Copyright 2011 Xamarin Inc.
//
using System;
using System.Collections.Generic;
using Mono.CompilerServices.SymbolWriter;
#if STATIC
using IKVM.Reflection.Emit;
#else
using System.Reflection.Emit;
#endif
namespace Mono.CSharp
{
public abstract class YieldStatement<T> : ResumableStatement where T : StateMachineInitializer
{
protected Expression expr;
protected bool unwind_protect;
protected T machine_initializer;
int resume_pc;
protected YieldStatement (Expression expr, Location l)
{
this.expr = expr;
loc = l;
}
public Expression Expr {
get { return this.expr; }
}
protected override void CloneTo (CloneContext clonectx, Statement t)
{
var target = (YieldStatement<T>) t;
target.expr = expr.Clone (clonectx);
}
protected override void DoEmit (EmitContext ec)
{
machine_initializer.InjectYield (ec, expr, resume_pc, unwind_protect, resume_point);
}
public override bool Resolve (BlockContext bc)
{
expr = expr.Resolve (bc);
if (expr == null)
return false;
machine_initializer = bc.CurrentAnonymousMethod as T;
if (!bc.CurrentBranching.CurrentUsageVector.IsUnreachable)
unwind_protect = bc.CurrentBranching.AddResumePoint (this, out resume_pc);
return true;
}
}
public class Yield : YieldStatement<Iterator>
{
public Yield (Expression expr, Location loc)
: base (expr, loc)
{
}
public static bool CheckContext (ResolveContext ec, Location loc)
{
if (!ec.CurrentAnonymousMethod.IsIterator) {
ec.Report.Error (1621, loc,
"The yield statement cannot be used inside anonymous method blocks");
return false;
}
return true;
}
public override bool Resolve (BlockContext bc)
{
if (!CheckContext (bc, loc))
return false;
if (!base.Resolve (bc))
return false;
var otype = bc.CurrentIterator.OriginalIteratorType;
if (expr.Type != otype) {
expr = Convert.ImplicitConversionRequired (bc, expr, otype, loc);
if (expr == null)
return false;
}
return true;
}
public override object Accept (StructuralVisitor visitor)
{
return visitor.Visit (this);
}
}
public class YieldBreak : ExitStatement
{
Iterator iterator;
public YieldBreak (Location l)
{
loc = l;
}
public override void Error_FinallyClause (Report Report)
{
Report.Error (1625, loc, "Cannot yield in the body of a finally clause");
}
protected override void CloneTo (CloneContext clonectx, Statement target)
{
throw new NotSupportedException ();
}
protected override bool DoResolve (BlockContext ec)
{
iterator = ec.CurrentIterator;
return Yield.CheckContext (ec, loc);
}
protected override void DoEmit (EmitContext ec)
{
iterator.EmitYieldBreak (ec, unwind_protect);
}
public override object Accept (StructuralVisitor visitor)
{
return visitor.Visit (this);
}
}
public abstract class StateMachine : AnonymousMethodStorey
{
public enum State
{
Running = -3, // Used only in CurrentPC, never stored into $PC
Uninitialized = -2,
After = -1,
Start = 0
}
Field pc_field;
StateMachineMethod method;
int local_name_idx;
protected StateMachine (ParametersBlock block, TypeDefinition parent, MemberBase host, TypeParameters tparams, string name, MemberKind kind)
: base (block, parent, host, tparams, name, kind)
{
}
#region Properties
public StateMachineMethod StateMachineMethod {
get {
return method;
}
}
public Field PC {
get {
return pc_field;
}
}
#endregion
public void AddEntryMethod (StateMachineMethod method)
{
if (this.method != null)
throw new InternalErrorException ();
this.method = method;
Members.Add (method);
}
protected override bool DoDefineMembers ()
{
pc_field = AddCompilerGeneratedField ("$PC", new TypeExpression (Compiler.BuiltinTypes.Int, Location));
return base.DoDefineMembers ();
}
protected override string GetVariableMangledName (LocalVariable local_info)
{
if (local_info.IsCompilerGenerated)
return base.GetVariableMangledName (local_info);
return "<" + local_info.Name + ">__" + local_name_idx++.ToString ("X");
}
}
class IteratorStorey : StateMachine
{
class GetEnumeratorMethod : StateMachineMethod
{
sealed class GetEnumeratorStatement : Statement
{
readonly IteratorStorey host;
readonly StateMachineMethod host_method;
Expression new_storey;
public GetEnumeratorStatement (IteratorStorey host, StateMachineMethod host_method)
{
this.host = host;
this.host_method = host_method;
loc = host_method.Location;
}
protected override void CloneTo (CloneContext clonectx, Statement target)
{
throw new NotSupportedException ();
}
public override bool Resolve (BlockContext ec)
{
TypeExpression storey_type_expr = new TypeExpression (host.Definition, loc);
List<Expression> init = null;
if (host.hoisted_this != null) {
init = new List<Expression> (host.hoisted_params == null ? 1 : host.HoistedParameters.Count + 1);
HoistedThis ht = host.hoisted_this;
FieldExpr from = new FieldExpr (ht.Field, loc);
from.InstanceExpression = new CompilerGeneratedThis (ec.CurrentType, loc);
init.Add (new ElementInitializer (ht.Field.Name, from, loc));
}
if (host.hoisted_params != null) {
if (init == null)
init = new List<Expression> (host.HoistedParameters.Count);
for (int i = 0; i < host.hoisted_params.Count; ++i) {
HoistedParameter hp = host.hoisted_params [i];
HoistedParameter hp_cp = host.hoisted_params_copy [i];
FieldExpr from = new FieldExpr (hp_cp.Field, loc);
from.InstanceExpression = new CompilerGeneratedThis (ec.CurrentType, loc);
init.Add (new ElementInitializer (hp.Field.Name, from, loc));
}
}
if (init != null) {
new_storey = new NewInitialize (storey_type_expr, null,
new CollectionOrObjectInitializers (init, loc), loc);
} else {
new_storey = new New (storey_type_expr, null, loc);
}
new_storey = new_storey.Resolve (ec);
if (new_storey != null)
new_storey = Convert.ImplicitConversionRequired (ec, new_storey, host_method.MemberType, loc);
ec.CurrentBranching.CurrentUsageVector.Goto ();
return true;
}
protected override void DoEmit (EmitContext ec)
{
Label label_init = ec.DefineLabel ();
ec.EmitThis ();
ec.Emit (OpCodes.Ldflda, host.PC.Spec);
ec.EmitInt ((int) State.Start);
ec.EmitInt ((int) State.Uninitialized);
var m = ec.Module.PredefinedMembers.InterlockedCompareExchange.Resolve (loc);
if (m != null)
ec.Emit (OpCodes.Call, m);
ec.EmitInt ((int) State.Uninitialized);
ec.Emit (OpCodes.Bne_Un_S, label_init);
ec.EmitThis ();
ec.Emit (OpCodes.Ret);
ec.MarkLabel (label_init);
new_storey.Emit (ec);
ec.Emit (OpCodes.Ret);
}
}
GetEnumeratorMethod (IteratorStorey host, FullNamedExpression returnType, MemberName name)
: base (host, null, returnType, Modifiers.DEBUGGER_HIDDEN, name)
{
}
public static GetEnumeratorMethod Create (IteratorStorey host, FullNamedExpression returnType, MemberName name)
{
return Create (host, returnType, name, null);
}
public static GetEnumeratorMethod Create (IteratorStorey host, FullNamedExpression returnType, MemberName name, Statement statement)
{
var m = new GetEnumeratorMethod (host, returnType, name);
var stmt = statement ?? new GetEnumeratorStatement (host, m);
m.block.AddStatement (stmt);
m.block.IsCompilerGenerated = true;
return m;
}
}
class DisposeMethod : StateMachineMethod
{
sealed class DisposeMethodStatement : Statement
{
Iterator iterator;
public DisposeMethodStatement (Iterator iterator)
{
this.iterator = iterator;
this.loc = iterator.Location;
}
protected override void CloneTo (CloneContext clonectx, Statement target)
{
throw new NotSupportedException ();
}
public override bool Resolve (BlockContext ec)
{
return true;
}
protected override void DoEmit (EmitContext ec)
{
ec.CurrentAnonymousMethod = iterator;
iterator.EmitDispose (ec);
}
}
public DisposeMethod (IteratorStorey host)
: base (host, null, new TypeExpression (host.Compiler.BuiltinTypes.Void, host.Location), Modifiers.PUBLIC | Modifiers.DEBUGGER_HIDDEN,
new MemberName ("Dispose", host.Location))
{
host.Members.Add (this);
Block.AddStatement (new DisposeMethodStatement (host.Iterator));
Block.IsCompilerGenerated = true;
}
}
//
// Uses Method as method info
//
class DynamicMethodGroupExpr : MethodGroupExpr
{
readonly Method method;
public DynamicMethodGroupExpr (Method method, Location loc)
: base ((IList<MemberSpec>) null, null, loc)
{
this.method = method;
eclass = ExprClass.Unresolved;
}
protected override Expression DoResolve (ResolveContext ec)
{
Methods = new List<MemberSpec> (1) { method.Spec };
type = method.Parent.Definition;
InstanceExpression = new CompilerGeneratedThis (type, Location);
return base.DoResolve (ec);
}
}
class DynamicFieldExpr : FieldExpr
{
readonly Field field;
public DynamicFieldExpr (Field field, Location loc)
: base (loc)
{
this.field = field;
}
protected override Expression DoResolve (ResolveContext ec)
{
spec = field.Spec;
type = spec.MemberType;
InstanceExpression = new CompilerGeneratedThis (type, Location);
return base.DoResolve (ec);
}
}
public readonly Iterator Iterator;
List<HoistedParameter> hoisted_params_copy;
TypeExpr iterator_type_expr;
Field current_field;
Field disposing_field;
TypeSpec generic_enumerator_type;
TypeSpec generic_enumerable_type;
public IteratorStorey (Iterator iterator)
: base (iterator.Container.ParametersBlock, iterator.Host,
iterator.OriginalMethod as MemberBase, iterator.OriginalMethod.CurrentTypeParameters, "Iterator", MemberKind.Class)
{
this.Iterator = iterator;
}
public Field CurrentField {
get {
return current_field;
}
}
public Field DisposingField {
get {
return disposing_field;
}
}
public IList<HoistedParameter> HoistedParameters {
get { return hoisted_params; }
}
protected override TypeSpec[] ResolveBaseTypes (out FullNamedExpression base_class)
{
var mtype = Iterator.OriginalIteratorType;
if (Mutator != null)
mtype = Mutator.Mutate (mtype);
iterator_type_expr = new TypeExpression (mtype, Location);
var ifaces = new List<TypeSpec> (5);
if (Iterator.IsEnumerable) {
ifaces.Add (Compiler.BuiltinTypes.IEnumerable);
if (Module.PredefinedTypes.IEnumerableGeneric.Define ()) {
generic_enumerable_type = Module.PredefinedTypes.IEnumerableGeneric.TypeSpec.MakeGenericType (Module, new[] { mtype });
ifaces.Add (generic_enumerable_type);
}
}
ifaces.Add (Compiler.BuiltinTypes.IEnumerator);
ifaces.Add (Compiler.BuiltinTypes.IDisposable);
var ienumerator_generic = Module.PredefinedTypes.IEnumeratorGeneric;
if (ienumerator_generic.Define ()) {
generic_enumerator_type = ienumerator_generic.TypeSpec.MakeGenericType (Module, new [] { mtype });
ifaces.Add (generic_enumerator_type);
}
base_class = null;
base_type = Compiler.BuiltinTypes.Object;
return ifaces.ToArray ();
}
protected override bool DoDefineMembers ()
{
current_field = AddCompilerGeneratedField ("$current", iterator_type_expr);
disposing_field = AddCompilerGeneratedField ("$disposing", new TypeExpression (Compiler.BuiltinTypes.Bool, Location));
if (hoisted_params != null) {
//
// Iterators are independent, each GetEnumerator call has to
// create same enumerator therefore we have to keep original values
// around for re-initialization
//
// TODO: Do it for assigned/modified parameters only
//
hoisted_params_copy = new List<HoistedParameter> (hoisted_params.Count);
foreach (HoistedParameter hp in hoisted_params) {
hoisted_params_copy.Add (new HoistedParameter (hp, "<$>" + hp.Field.Name));
}
}
if (generic_enumerator_type != null)
Define_Current (true);
Define_Current (false);
new DisposeMethod (this);
Define_Reset ();
if (Iterator.IsEnumerable) {
FullNamedExpression explicit_iface = new TypeExpression (Compiler.BuiltinTypes.IEnumerable, Location);
var name = new MemberName ("GetEnumerator", null, explicit_iface, Location.Null);
if (generic_enumerator_type != null) {
explicit_iface = new TypeExpression (generic_enumerable_type, Location);
var gname = new MemberName ("GetEnumerator", null, explicit_iface, Location.Null);
Method gget_enumerator = GetEnumeratorMethod.Create (this, new TypeExpression (generic_enumerator_type, Location), gname);
//
// Just call generic GetEnumerator implementation
//
var stmt = new Return (new Invocation (new DynamicMethodGroupExpr (gget_enumerator, Location), null), Location);
Method get_enumerator = GetEnumeratorMethod.Create (this, new TypeExpression (Compiler.BuiltinTypes.IEnumerator, Location), name, stmt);
Members.Add (get_enumerator);
Members.Add (gget_enumerator);
} else {
Members.Add (GetEnumeratorMethod.Create (this, new TypeExpression (Compiler.BuiltinTypes.IEnumerator, Location), name));
}
}
return base.DoDefineMembers ();
}
void Define_Current (bool is_generic)
{
TypeExpr type;
FullNamedExpression explicit_iface;
if (is_generic) {
explicit_iface = new TypeExpression (generic_enumerator_type, Location);
type = iterator_type_expr;
} else {
explicit_iface = new TypeExpression (Module.Compiler.BuiltinTypes.IEnumerator, Location);
type = new TypeExpression (Compiler.BuiltinTypes.Object, Location);
}
var name = new MemberName ("Current", null, explicit_iface, Location);
ToplevelBlock get_block = new ToplevelBlock (Compiler, Location) {
IsCompilerGenerated = true
};
get_block.AddStatement (new Return (new DynamicFieldExpr (CurrentField, Location), Location));
Property current = new Property (this, type, Modifiers.DEBUGGER_HIDDEN | Modifiers.COMPILER_GENERATED, name, null);
current.Get = new Property.GetMethod (current, Modifiers.COMPILER_GENERATED, null, Location);
current.Get.Block = get_block;
Members.Add (current);
}
void Define_Reset ()
{
Method reset = new Method (
this, new TypeExpression (Compiler.BuiltinTypes.Void, Location),
Modifiers.PUBLIC | Modifiers.DEBUGGER_HIDDEN | Modifiers.COMPILER_GENERATED,
new MemberName ("Reset", Location),
ParametersCompiled.EmptyReadOnlyParameters, null);
Members.Add (reset);
reset.Block = new ToplevelBlock (Compiler, Location) {
IsCompilerGenerated = true
};
TypeSpec ex_type = Module.PredefinedTypes.NotSupportedException.Resolve ();
if (ex_type == null)
return;
reset.Block.AddStatement (new Throw (new New (new TypeExpression (ex_type, Location), null, Location), Location));
}
protected override void EmitHoistedParameters (EmitContext ec, List<HoistedParameter> hoisted)
{
base.EmitHoistedParameters (ec, hoisted);
base.EmitHoistedParameters (ec, hoisted_params_copy);
}
}
public class StateMachineMethod : Method
{
readonly StateMachineInitializer expr;
public StateMachineMethod (StateMachine host, StateMachineInitializer expr, FullNamedExpression returnType, Modifiers mod, MemberName name)
: base (host, returnType, mod | Modifiers.COMPILER_GENERATED,
name, ParametersCompiled.EmptyReadOnlyParameters, null)
{
this.expr = expr;
Block = new ToplevelBlock (host.Compiler, ParametersCompiled.EmptyReadOnlyParameters, Location.Null);
}
public override EmitContext CreateEmitContext (ILGenerator ig, SourceMethodBuilder sourceMethod)
{
EmitContext ec = new EmitContext (this, ig, MemberType, sourceMethod);
ec.CurrentAnonymousMethod = expr;
if (expr is AsyncInitializer)
ec.With (BuilderContext.Options.AsyncBody, true);
return ec;
}
}
public abstract class StateMachineInitializer : AnonymousExpression
{
sealed class MoveNextBodyStatement : Statement
{
readonly StateMachineInitializer state_machine;
public MoveNextBodyStatement (StateMachineInitializer stateMachine)
{
this.state_machine = stateMachine;
this.loc = stateMachine.Location;
}
protected override void CloneTo (CloneContext clonectx, Statement target)
{
throw new NotSupportedException ();
}
public override bool Resolve (BlockContext ec)
{
return true;
}
protected override void DoEmit (EmitContext ec)
{
state_machine.EmitMoveNext (ec);
}
public override void Emit (EmitContext ec)
{
// Don't create sequence point
DoEmit (ec);
}
}
public readonly TypeDefinition Host;
protected StateMachine storey;
//
// The state as we generate the machine
//
Label move_next_ok;
Label iterator_body_end;
protected Label move_next_error;
LocalBuilder skip_finally;
protected LocalBuilder current_pc;
protected List<ResumableStatement> resume_points;
protected StateMachineInitializer (ParametersBlock block, TypeDefinition host, TypeSpec returnType)
: base (block, returnType, block.StartLocation)
{
this.Host = host;
}
#region Properties
public Label BodyEnd {
get {
return iterator_body_end;
}
}
public LocalBuilder CurrentPC
{
get {
return current_pc;
}
}
public LocalBuilder SkipFinally {
get {
return skip_finally;
}
}
public override AnonymousMethodStorey Storey {
get {
return storey;
}
}
#endregion
public int AddResumePoint (ResumableStatement stmt)
{
if (resume_points == null)
resume_points = new List<ResumableStatement> ();
resume_points.Add (stmt);
return resume_points.Count;
}
public override Expression CreateExpressionTree (ResolveContext ec)
{
throw new NotSupportedException ("ET");
}
protected virtual BlockContext CreateBlockContext (ResolveContext rc)
{
var ctx = new BlockContext (rc, block, ((BlockContext) rc).ReturnType);
ctx.CurrentAnonymousMethod = this;
return ctx;
}
protected override Expression DoResolve (ResolveContext ec)
{
var ctx = CreateBlockContext (ec);
Block.Resolve (ctx);
//
// Explicit return is required for Task<T> state machine
//
var task_storey = storey as AsyncTaskStorey;
if (task_storey == null || (task_storey.ReturnType != null && !task_storey.ReturnType.IsGenericTask))
ctx.CurrentBranching.CurrentUsageVector.Goto ();
ctx.EndFlowBranching ();
if (!ec.IsInProbingMode) {
var move_next = new StateMachineMethod (storey, this, new TypeExpression (ReturnType, loc), Modifiers.PUBLIC, new MemberName ("MoveNext", loc));
move_next.Block.AddStatement (new MoveNextBodyStatement (this));
storey.AddEntryMethod (move_next);
}
eclass = ExprClass.Value;
return this;
}
public override void Emit (EmitContext ec)
{
//
// Load state machine instance
//
storey.Instance.Emit (ec);
}
void EmitMoveNext_NoResumePoints (EmitContext ec)
{
ec.EmitThis ();
ec.Emit (OpCodes.Ldfld, storey.PC.Spec);
ec.EmitThis ();
ec.EmitInt ((int) IteratorStorey.State.After);
ec.Emit (OpCodes.Stfld, storey.PC.Spec);
// We only care if the PC is zero (start executing) or non-zero (don't do anything)
ec.Emit (OpCodes.Brtrue, move_next_error);
iterator_body_end = ec.DefineLabel ();
block.EmitEmbedded (ec);
ec.MarkLabel (iterator_body_end);
EmitMoveNextEpilogue (ec);
ec.MarkLabel (move_next_error);
if (ReturnType.Kind != MemberKind.Void) {
ec.EmitInt (0);
ec.Emit (OpCodes.Ret);
}
}
void EmitMoveNext (EmitContext ec)
{
move_next_ok = ec.DefineLabel ();
move_next_error = ec.DefineLabel ();
if (resume_points == null) {
EmitMoveNext_NoResumePoints (ec);
return;
}
current_pc = ec.GetTemporaryLocal (ec.BuiltinTypes.UInt);
ec.EmitThis ();
ec.Emit (OpCodes.Ldfld, storey.PC.Spec);
ec.Emit (OpCodes.Stloc, current_pc);
// We're actually in state 'running', but this is as good a PC value as any if there's an abnormal exit
ec.EmitThis ();
ec.EmitInt ((int) IteratorStorey.State.After);
ec.Emit (OpCodes.Stfld, storey.PC.Spec);
Label[] labels = new Label[1 + resume_points.Count];
labels[0] = ec.DefineLabel ();
bool need_skip_finally = false;
for (int i = 0; i < resume_points.Count; ++i) {
ResumableStatement s = resume_points[i];
need_skip_finally |= s is ExceptionStatement;
labels[i + 1] = s.PrepareForEmit (ec);
}
if (need_skip_finally) {
skip_finally = ec.GetTemporaryLocal (ec.BuiltinTypes.Bool);
ec.EmitInt (0);
ec.Emit (OpCodes.Stloc, skip_finally);
}
var async_init = this as AsyncInitializer;
if (async_init != null)
ec.BeginExceptionBlock ();
ec.Emit (OpCodes.Ldloc, current_pc);
ec.Emit (OpCodes.Switch, labels);
ec.Emit (async_init != null ? OpCodes.Leave : OpCodes.Br, move_next_error);
ec.MarkLabel (labels[0]);
iterator_body_end = ec.DefineLabel ();
block.EmitEmbedded (ec);
ec.MarkLabel (iterator_body_end);
if (async_init != null) {
var catch_value = LocalVariable.CreateCompilerGenerated (ec.Module.Compiler.BuiltinTypes.Exception, block, Location);
ec.BeginCatchBlock (catch_value.Type);
catch_value.EmitAssign (ec);
ec.EmitThis ();
ec.EmitInt ((int) IteratorStorey.State.After);
ec.Emit (OpCodes.Stfld, storey.PC.Spec);
((AsyncTaskStorey) async_init.Storey).EmitSetException (ec, new LocalVariableReference (catch_value, Location));
ec.Emit (OpCodes.Leave, move_next_ok);
ec.EndExceptionBlock ();
}
ec.Mark (Block.Original.EndLocation);
ec.EmitThis ();
ec.EmitInt ((int) IteratorStorey.State.After);
ec.Emit (OpCodes.Stfld, storey.PC.Spec);
EmitMoveNextEpilogue (ec);
ec.MarkLabel (move_next_error);
if (ReturnType.Kind != MemberKind.Void) {
ec.EmitInt (0);
ec.Emit (OpCodes.Ret);
}
ec.MarkLabel (move_next_ok);
if (ReturnType.Kind != MemberKind.Void) {
ec.EmitInt (1);
ec.Emit (OpCodes.Ret);
}
}
protected virtual void EmitMoveNextEpilogue (EmitContext ec)
{
}
public void EmitLeave (EmitContext ec, bool unwind_protect)
{
// Return ok
ec.Emit (unwind_protect ? OpCodes.Leave : OpCodes.Br, move_next_ok);
}
//
// Called back from YieldStatement
//
public virtual void InjectYield (EmitContext ec, Expression expr, int resume_pc, bool unwind_protect, Label resume_point)
{
//
// Guard against being disposed meantime
//
Label disposed = ec.DefineLabel ();
var iterator = storey as IteratorStorey;
if (iterator != null) {
ec.EmitThis ();
ec.Emit (OpCodes.Ldfld, iterator.DisposingField.Spec);
ec.Emit (OpCodes.Brtrue_S, disposed);
}
//
// store resume program-counter
//
ec.EmitThis ();
ec.EmitInt (resume_pc);
ec.Emit (OpCodes.Stfld, storey.PC.Spec);
if (iterator != null) {
ec.MarkLabel (disposed);
}
// mark finally blocks as disabled
if (unwind_protect && skip_finally != null) {
ec.EmitInt (1);
ec.Emit (OpCodes.Stloc, skip_finally);
}
}
public void SetStateMachine (StateMachine stateMachine)
{
this.storey = stateMachine;
}
}
//
// Iterators are implemented as state machine blocks
//
public class Iterator : StateMachineInitializer
{
sealed class TryFinallyBlockProxyStatement : Statement
{
TryFinallyBlock block;
Iterator iterator;
public TryFinallyBlockProxyStatement (Iterator iterator, TryFinallyBlock block)
{
this.iterator = iterator;
this.block = block;
}
protected override void CloneTo (CloneContext clonectx, Statement target)
{
throw new NotSupportedException ();
}
protected override void DoEmit (EmitContext ec)
{
//
// Restore redirection for any captured variables
//
ec.CurrentAnonymousMethod = iterator;
using (ec.With (BuilderContext.Options.OmitDebugInfo, !ec.HasMethodSymbolBuilder)) {
block.EmitFinallyBody (ec);
}
}
}
public readonly IMethodData OriginalMethod;
public readonly bool IsEnumerable;
public readonly TypeSpec OriginalIteratorType;
int finally_hosts_counter;
public Iterator (ParametersBlock block, IMethodData method, TypeDefinition host, TypeSpec iterator_type, bool is_enumerable)
: base (block, host, host.Compiler.BuiltinTypes.Bool)
{
this.OriginalMethod = method;
this.OriginalIteratorType = iterator_type;
this.IsEnumerable = is_enumerable;
this.type = method.ReturnType;
}
#region Properties
public ToplevelBlock Container {
get { return OriginalMethod.Block; }
}
public override string ContainerType {
get { return "iterator"; }
}
public override bool IsIterator {
get { return true; }
}
#endregion
public Method CreateFinallyHost (TryFinallyBlock block)
{
var method = new Method (storey, new TypeExpression (storey.Compiler.BuiltinTypes.Void, loc),
Modifiers.COMPILER_GENERATED, new MemberName (CompilerGeneratedContainer.MakeName (null, null, "Finally", finally_hosts_counter++), loc),
ParametersCompiled.EmptyReadOnlyParameters, null);
method.Block = new ToplevelBlock (method.Compiler, method.ParameterInfo, loc);
method.Block.IsCompilerGenerated = true;
method.Block.AddStatement (new TryFinallyBlockProxyStatement (this, block));
// Cannot it add to storey because it'd be emitted before nested
// anonoymous methods which could capture shared variable
return method;
}
public void EmitYieldBreak (EmitContext ec, bool unwind_protect)
{
ec.Emit (unwind_protect ? OpCodes.Leave : OpCodes.Br, move_next_error);
}
public override string GetSignatureForError ()
{
return OriginalMethod.GetSignatureForError ();
}
public override void Emit (EmitContext ec)
{
//
// Load Iterator storey instance
//
storey.Instance.Emit (ec);
//
// Initialize iterator PC when it's unitialized
//
if (IsEnumerable) {
ec.Emit (OpCodes.Dup);
ec.EmitInt ((int)IteratorStorey.State.Uninitialized);
var field = storey.PC.Spec;
if (storey.MemberName.IsGeneric) {
field = MemberCache.GetMember (Storey.Instance.Type, field);
}
ec.Emit (OpCodes.Stfld, field);
}
}
public void EmitDispose (EmitContext ec)
{
if (resume_points == null)
return;
Label end = ec.DefineLabel ();
Label[] labels = null;
for (int i = 0; i < resume_points.Count; ++i) {
ResumableStatement s = resume_points[i];
Label ret = s.PrepareForDispose (ec, end);
if (ret.Equals (end) && labels == null)
continue;
if (labels == null) {
labels = new Label[resume_points.Count + 1];
for (int j = 0; j <= i; ++j)
labels[j] = end;
}
labels[i + 1] = ret;
}
if (labels != null) {
current_pc = ec.GetTemporaryLocal (ec.BuiltinTypes.UInt);
ec.EmitThis ();
ec.Emit (OpCodes.Ldfld, storey.PC.Spec);
ec.Emit (OpCodes.Stloc, current_pc);
}
ec.EmitThis ();
ec.EmitInt (1);
ec.Emit (OpCodes.Stfld, ((IteratorStorey) storey).DisposingField.Spec);
ec.EmitThis ();
ec.EmitInt ((int) IteratorStorey.State.After);
ec.Emit (OpCodes.Stfld, storey.PC.Spec);
if (labels != null) {
//SymbolWriter.StartIteratorDispatcher (ec.ig);
ec.Emit (OpCodes.Ldloc, current_pc);
ec.Emit (OpCodes.Switch, labels);
//SymbolWriter.EndIteratorDispatcher (ec.ig);
foreach (ResumableStatement s in resume_points)
s.EmitForDispose (ec, current_pc, end, true);
}
ec.MarkLabel (end);
}
public override void EmitStatement (EmitContext ec)
{
throw new NotImplementedException ();
}
public override void InjectYield (EmitContext ec, Expression expr, int resume_pc, bool unwind_protect, Label resume_point)
{
// Store the new value into current
var fe = new FieldExpr (((IteratorStorey) storey).CurrentField, loc);
fe.InstanceExpression = new CompilerGeneratedThis (storey.CurrentType, loc);
fe.EmitAssign (ec, expr, false, false);
base.InjectYield (ec, expr, resume_pc, unwind_protect, resume_point);
EmitLeave (ec, unwind_protect);
ec.MarkLabel (resume_point);
}
protected override BlockContext CreateBlockContext (ResolveContext rc)
{
var bc = base.CreateBlockContext (rc);
bc.StartFlowBranching (this, rc.CurrentBranching);
return bc;
}
public static void CreateIterator (IMethodData method, TypeDefinition parent, Modifiers modifiers)
{
bool is_enumerable;
TypeSpec iterator_type;
TypeSpec ret = method.ReturnType;
if (ret == null)
return;
if (!CheckType (ret, parent, out iterator_type, out is_enumerable)) {
parent.Compiler.Report.Error (1624, method.Location,
"The body of `{0}' cannot be an iterator block " +
"because `{1}' is not an iterator interface type",
method.GetSignatureForError (),
TypeManager.CSharpName (ret));
return;
}
ParametersCompiled parameters = method.ParameterInfo;
for (int i = 0; i < parameters.Count; i++) {
Parameter p = parameters [i];
Parameter.Modifier mod = p.ModFlags;
if ((mod & Parameter.Modifier.RefOutMask) != 0) {
parent.Compiler.Report.Error (1623, p.Location,
"Iterators cannot have ref or out parameters");
return;
}
if (p is ArglistParameter) {
parent.Compiler.Report.Error (1636, method.Location,
"__arglist is not allowed in parameter list of iterators");
return;
}
if (parameters.Types [i].IsPointer) {
parent.Compiler.Report.Error (1637, p.Location,
"Iterators cannot have unsafe parameters or yield types");
return;
}
}
if ((modifiers & Modifiers.UNSAFE) != 0) {
parent.Compiler.Report.Error (1629, method.Location, "Unsafe code may not appear in iterators");
}
method.Block = method.Block.ConvertToIterator (method, parent, iterator_type, is_enumerable);
}
static bool CheckType (TypeSpec ret, TypeContainer parent, out TypeSpec original_iterator_type, out bool is_enumerable)
{
original_iterator_type = null;
is_enumerable = false;
if (ret.BuiltinType == BuiltinTypeSpec.Type.IEnumerable) {
original_iterator_type = parent.Compiler.BuiltinTypes.Object;
is_enumerable = true;
return true;
}
if (ret.BuiltinType == BuiltinTypeSpec.Type.IEnumerator) {
original_iterator_type = parent.Compiler.BuiltinTypes.Object;
is_enumerable = false;
return true;
}
InflatedTypeSpec inflated = ret as InflatedTypeSpec;
if (inflated == null)
return false;
var member_definition = inflated.MemberDefinition;
PredefinedType ptype = parent.Module.PredefinedTypes.IEnumerableGeneric;
if (ptype.Define () && ptype.TypeSpec.MemberDefinition == member_definition) {
original_iterator_type = inflated.TypeArguments[0];
is_enumerable = true;
return true;
}
ptype = parent.Module.PredefinedTypes.IEnumeratorGeneric;
if (ptype.Define () && ptype.TypeSpec.MemberDefinition == member_definition) {
original_iterator_type = inflated.TypeArguments[0];
is_enumerable = false;
return true;
}
return false;
}
}
}
| |
using System;
using System.Diagnostics;
using HANDLE = System.IntPtr;
using System.Text;
namespace Community.CsharpSqlite
{
public partial class Sqlite3
{
/*
** 2006 June 7
**
** The author disclaims copyright to this source code. In place of
** a legal notice, here is a blessing:
**
** May you do good and not evil.
** May you find forgiveness for yourself and forgive others.
** May you share freely, never taking more than you give.
**
*************************************************************************
** This file contains code used to dynamically load extensions into
** the SQLite library.
*************************************************************************
** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart
** C#-SQLite is an independent reimplementation of the SQLite software library
**
** SQLITE_SOURCE_ID: 2011-05-19 13:26:54 ed1da510a239ea767a01dc332b667119fa3c908e
**
*************************************************************************
*/
#if !SQLITE_CORE
//#define SQLITE_CORE 1 /* Disable the API redefinition in sqlite3ext.h */
const int SQLITE_CORE = 1;
#endif
//#include "sqlite3ext.h"
//#include "sqliteInt.h"
//#include <string.h>
#if !SQLITE_OMIT_LOAD_EXTENSION
/*
** Some API routines are omitted when various features are
** excluded from a build of SQLite. Substitute a NULL pointer
** for any missing APIs.
*/
#if !SQLITE_ENABLE_COLUMN_METADATA
//# define sqlite3_column_database_name 0
//# define sqlite3_column_database_name16 0
//# define sqlite3_column_table_name 0
//# define sqlite3_column_table_name16 0
//# define sqlite3_column_origin_name 0
//# define sqlite3_column_origin_name16 0
//# define sqlite3_table_column_metadata 0
#endif
#if SQLITE_OMIT_AUTHORIZATION
//# define sqlite3_set_authorizer 0
#endif
#if SQLITE_OMIT_UTF16
//# define sqlite3_bind_text16 0
//# define sqlite3_collation_needed16 0
//# define sqlite3_column_decltype16 0
//# define sqlite3_column_name16 0
//# define sqlite3_column_text16 0
//# define sqlite3_complete16 0
//# define sqlite3_create_collation16 0
//# define sqlite3_create_function16 0
//# define sqlite3_errmsg16 0
static string sqlite3_errmsg16( sqlite3 db )
{
return "";
}
//# define sqlite3_open16 0
//# define sqlite3_prepare16 0
//# define sqlite3_prepare16_v2 0
//# define sqlite3_result_error16 0
//# define sqlite3_result_text16 0
static void sqlite3_result_text16( sqlite3_context pCtx, string z, int n, dxDel xDel )
{
}
//# define sqlite3_result_text16be 0
//# define sqlite3_result_text16le 0
//# define sqlite3_value_text16 0
//# define sqlite3_value_text16be 0
//# define sqlite3_value_text16le 0
//# define sqlite3_column_database_name16 0
//# define sqlite3_column_table_name16 0
//# define sqlite3_column_origin_name16 0
#endif
#if SQLITE_OMIT_COMPLETE
//# define sqlite3_complete 0
//# define sqlite3_complete16 0
#endif
#if SQLITE_OMIT_DECLTYPE
//# define sqlite3_column_decltype16 0
//# define sqlite3_column_decltype 0
#endif
#if SQLITE_OMIT_PROGRESS_CALLBACK
//# define sqlite3_progress_handler 0
static void sqlite3_progress_handler (sqlite3 db, int nOps, dxProgress xProgress, object pArg){}
#endif
#if SQLITE_OMIT_VIRTUALTABLE
//# define sqlite3_create_module 0
//# define sqlite3_create_module_v2 0
//# define sqlite3_declare_vtab 0
#endif
#if SQLITE_OMIT_SHARED_CACHE
//# define sqlite3_enable_shared_cache 0
#endif
#if SQLITE_OMIT_TRACE
//# define sqlite3_profile 0
//# define sqlite3_trace 0
#endif
#if SQLITE_OMIT_GET_TABLE
//# define //sqlite3_free_table 0
static public int sqlite3_free_table(ref string[] pazResult) { pazResult = null; return 0; }
static public int sqlite3_get_table(
sqlite3 db, /* An open database */
string zSql, /* SQL to be evaluated */
ref string[] pazResult, /* Results of the query */
ref int pnRow, /* Number of result rows written here */
object dummy,
ref string pzErrmsg /* Error msg written here */
)
{
int iDummy = 0;
return sqlite3_get_table(db, zSql, ref pazResult, ref pnRow, ref iDummy, ref pzErrmsg);
}
//# define sqlite3_get_table 0
static public int sqlite3_get_table(
sqlite3 db, /* An open database */
string zSql, /* SQL to be evaluated */
ref string[] pazResult, /* Results of the query */
ref int pnRow, /* Number of result rows written here */
ref int pnColumn, /* Number of result columns written here */
ref string pzErrmsg /* Error msg written here */
)
{
return 0;
}
#endif
#if SQLITE_OMIT_INCRBLOB
//#define sqlite3_bind_zeroblob 0
//#define sqlite3_blob_bytes 0
//#define sqlite3_blob_close 0
//#define sqlite3_blob_open 0
//#define sqlite3_blob_read 0
//#define sqlite3_blob_write 0
#endif
/*
** The following structure contains pointers to all SQLite API routines.
** A pointer to this structure is passed into extensions when they are
** loaded so that the extension can make calls back into the SQLite
** library.
**
** When adding new APIs, add them to the bottom of this structure
** in order to preserve backwards compatibility.
**
** Extensions that use newer APIs should first call the
** sqlite3_libversion_number() to make sure that the API they
** intend to use is supported by the library. Extensions should
** also check to make sure that the pointer to the function is
** not NULL before calling it.
*/
public class sqlite3_api_routines
{
public sqlite3 context_db_handle;
};
static sqlite3_api_routines sqlite3Apis = new sqlite3_api_routines();
//{
// sqlite3_aggregate_context,
#if !SQLITE_OMIT_DEPRECATED
/ sqlite3_aggregate_count,
#else
// 0,
#endif
// sqlite3_bind_blob,
// sqlite3_bind_double,
// sqlite3_bind_int,
// sqlite3_bind_int64,
// sqlite3_bind_null,
// sqlite3_bind_parameter_count,
// sqlite3_bind_parameter_index,
// sqlite3_bind_parameter_name,
// sqlite3_bind_text,
// sqlite3_bind_text16,
// sqlite3_bind_value,
// sqlite3_busy_handler,
// sqlite3_busy_timeout,
// sqlite3_changes,
// sqlite3_close,
// sqlite3_collation_needed,
// sqlite3_collation_needed16,
// sqlite3_column_blob,
// sqlite3_column_bytes,
// sqlite3_column_bytes16,
// sqlite3_column_count,
// sqlite3_column_database_name,
// sqlite3_column_database_name16,
// sqlite3_column_decltype,
// sqlite3_column_decltype16,
// sqlite3_column_double,
// sqlite3_column_int,
// sqlite3_column_int64,
// sqlite3_column_name,
// sqlite3_column_name16,
// sqlite3_column_origin_name,
// sqlite3_column_origin_name16,
// sqlite3_column_table_name,
// sqlite3_column_table_name16,
// sqlite3_column_text,
// sqlite3_column_text16,
// sqlite3_column_type,
// sqlite3_column_value,
// sqlite3_commit_hook,
// sqlite3_complete,
// sqlite3_complete16,
// sqlite3_create_collation,
// sqlite3_create_collation16,
// sqlite3_create_function,
// sqlite3_create_function16,
// sqlite3_create_module,
// sqlite3_data_count,
// sqlite3_db_handle,
// sqlite3_declare_vtab,
// sqlite3_enable_shared_cache,
// sqlite3_errcode,
// sqlite3_errmsg,
// sqlite3_errmsg16,
// sqlite3_exec,
#if !SQLITE_OMIT_DEPRECATED
//sqlite3_expired,
#else
//0,
#endif
// sqlite3_finalize,
// //sqlite3_free,
// //sqlite3_free_table,
// sqlite3_get_autocommit,
// sqlite3_get_auxdata,
// sqlite3_get_table,
// 0, /* Was sqlite3_global_recover(), but that function is deprecated */
// sqlite3_interrupt,
// sqlite3_last_insert_rowid,
// sqlite3_libversion,
// sqlite3_libversion_number,
// sqlite3_malloc,
// sqlite3_mprintf,
// sqlite3_open,
// sqlite3_open16,
// sqlite3_prepare,
// sqlite3_prepare16,
// sqlite3_profile,
// sqlite3_progress_handler,
// sqlite3_realloc,
// sqlite3_reset,
// sqlite3_result_blob,
// sqlite3_result_double,
// sqlite3_result_error,
// sqlite3_result_error16,
// sqlite3_result_int,
// sqlite3_result_int64,
// sqlite3_result_null,
// sqlite3_result_text,
// sqlite3_result_text16,
// sqlite3_result_text16be,
// sqlite3_result_text16le,
// sqlite3_result_value,
// sqlite3_rollback_hook,
// sqlite3_set_authorizer,
// sqlite3_set_auxdata,
// sqlite3_snprintf,
// sqlite3_step,
// sqlite3_table_column_metadata,
#if !SQLITE_OMIT_DEPRECATED
//sqlite3_thread_cleanup,
#else
// 0,
#endif
// sqlite3_total_changes,
// sqlite3_trace,
#if !SQLITE_OMIT_DEPRECATED
//sqlite3_transfer_bindings,
#else
// 0,
#endif
// sqlite3_update_hook,
// sqlite3_user_data,
// sqlite3_value_blob,
// sqlite3_value_bytes,
// sqlite3_value_bytes16,
// sqlite3_value_double,
// sqlite3_value_int,
// sqlite3_value_int64,
// sqlite3_value_numeric_type,
// sqlite3_value_text,
// sqlite3_value_text16,
// sqlite3_value_text16be,
// sqlite3_value_text16le,
// sqlite3_value_type,
// sqlite3_vmprintf,
// /*
// ** The original API set ends here. All extensions can call any
// ** of the APIs above provided that the pointer is not NULL. But
// ** before calling APIs that follow, extension should check the
// ** sqlite3_libversion_number() to make sure they are dealing with
// ** a library that is new enough to support that API.
// *************************************************************************
// */
// sqlite3_overload_function,
// /*
// ** Added after 3.3.13
// */
// sqlite3_prepare_v2,
// sqlite3_prepare16_v2,
// sqlite3_clear_bindings,
// /*
// ** Added for 3.4.1
// */
// sqlite3_create_module_v2,
// /*
// ** Added for 3.5.0
// */
// sqlite3_bind_zeroblob,
// sqlite3_blob_bytes,
// sqlite3_blob_close,
// sqlite3_blob_open,
// sqlite3_blob_read,
// sqlite3_blob_write,
// sqlite3_create_collation_v2,
// sqlite3_file_control,
// sqlite3_memory_highwater,
// sqlite3_memory_used,
#if SQLITE_MUTEX_OMIT
// 0,
// 0,
// 0,
// 0,
// 0,
#else
// sqlite3MutexAlloc,
// sqlite3_mutex_enter,
// sqlite3_mutex_free,
// sqlite3_mutex_leave,
// sqlite3_mutex_try,
#endif
// sqlite3_open_v2,
// sqlite3_release_memory,
// sqlite3_result_error_nomem,
// sqlite3_result_error_toobig,
// sqlite3_sleep,
// sqlite3_soft_heap_limit,
// sqlite3_vfs_find,
// sqlite3_vfs_register,
// sqlite3_vfs_unregister,
// /*
// ** Added for 3.5.8
// */
// sqlite3_threadsafe,
// sqlite3_result_zeroblob,
// sqlite3_result_error_code,
// sqlite3_test_control,
// sqlite3_randomness,
// sqlite3_context_db_handle,
// /*
// ** Added for 3.6.0
// */
// sqlite3_extended_result_codes,
// sqlite3_limit,
// sqlite3_next_stmt,
// sqlite3_sql,
// sqlite3_status,
// /*
// ** Added for 3.7.4
// */
// sqlite3_backup_finish,
// sqlite3_backup_init,
// sqlite3_backup_pagecount,
// sqlite3_backup_remaining,
// sqlite3_backup_step,
//#if !SQLITE_OMIT_COMPILEOPTION_DIAGS
// sqlite3_compileoption_get,
// sqlite3_compileoption_used,
//#else
// 0,
// 0,
//#endif
// sqlite3_create_function_v2,
// sqlite3_db_config,
// sqlite3_db_mutex,
// sqlite3_db_status,
// sqlite3_extended_errcode,
// sqlite3_log,
// sqlite3_soft_heap_limit64,
// sqlite3_sourceid,
// sqlite3_stmt_status,
// sqlite3_strnicmp,
//#if SQLITE_ENABLE_UNLOCK_NOTIFY
// sqlite3_unlock_notify,
//#else
// 0,
//#endif
//#if !SQLITE_OMIT_WAL
// sqlite3_wal_autocheckpoint,
// sqlite3_wal_checkpoint,
// sqlite3_wal_hook,
//#else
// 0,
// 0,
// 0,
//#endif
//};
/*
** Attempt to load an SQLite extension library contained in the file
** zFile. The entry point is zProc. zProc may be 0 in which case a
** default entry point name (sqlite3_extension_init) is used. Use
** of the default name is recommended.
**
** Return SQLITE_OK on success and SQLITE_ERROR if something goes wrong.
**
** If an error occurs and pzErrMsg is not 0, then fill pzErrMsg with
** error message text. The calling function should free this memory
** by calling sqlite3DbFree(db, ).
*/
static int sqlite3LoadExtension(
sqlite3 db, /* Load the extension into this database connection */
string zFile, /* Name of the shared library containing extension */
string zProc, /* Entry point. Use "sqlite3_extension_init" if 0 */
ref string pzErrMsg /* Put error message here if not 0 */
)
{
sqlite3_vfs pVfs = db.pVfs;
HANDLE handle;
dxInit xInit; //int (*xInit)(sqlite3*,char**,const sqlite3_api_routines);
StringBuilder zErrmsg = new StringBuilder( 100 );
//object aHandle;
const int nMsg = 300;
if ( pzErrMsg != null )
pzErrMsg = null;
/* Ticket #1863. To avoid a creating security problems for older
** applications that relink against newer versions of SQLite, the
** ability to run load_extension is turned off by default. One
** must call sqlite3_enable_load_extension() to turn on extension
** loading. Otherwise you get the following error.
*/
if ( ( db.flags & SQLITE_LoadExtension ) == 0 )
{
//if( pzErrMsg != null){
pzErrMsg = sqlite3_mprintf( "not authorized" );
//}
return SQLITE_ERROR;
}
if ( zProc == null || zProc == "" )
{
zProc = "sqlite3_extension_init";
}
handle = sqlite3OsDlOpen( pVfs, zFile );
if ( handle == IntPtr.Zero )
{
// if( pzErrMsg ){
pzErrMsg = "";//*pzErrMsg = zErrmsg = sqlite3_malloc(nMsg);
//if( zErrmsg !=null){
sqlite3_snprintf( nMsg, zErrmsg,
"unable to open shared library [%s]", zFile );
sqlite3OsDlError( pVfs, nMsg - 1, zErrmsg.ToString() );
return SQLITE_ERROR;
}
//xInit = (int()(sqlite3*,char**,const sqlite3_api_routines))
// sqlite3OsDlSym(pVfs, handle, zProc);
xInit = (dxInit)sqlite3OsDlSym( pVfs, handle, ref zProc );
Debugger.Break(); // TODO --
//if( xInit==0 ){
// if( pzErrMsg ){
// *pzErrMsg = zErrmsg = sqlite3_malloc(nMsg);
// if( zErrmsg ){
// sqlite3_snprintf(nMsg, zErrmsg,
// "no entry point [%s] in shared library [%s]", zProc,zFile);
// sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
// }
// sqlite3OsDlClose(pVfs, handle);
// }
// return SQLITE_ERROR;
// }else if( xInit(db, ref zErrmsg, sqlite3Apis) ){
//// if( pzErrMsg !=null){
// pzErrMsg = sqlite3_mprintf("error during initialization: %s", zErrmsg);
// //}
// sqlite3DbFree(db,ref zErrmsg);
// sqlite3OsDlClose(pVfs, ref handle);
// return SQLITE_ERROR;
// }
// /* Append the new shared library handle to the db.aExtension array. */
// aHandle = sqlite3DbMallocZero(db, sizeof(handle)*db.nExtension+1);
// if( aHandle==null ){
// return SQLITE_NOMEM;
// }
// if( db.nExtension>0 ){
// memcpy(aHandle, db.aExtension, sizeof(handle)*(db.nExtension));
// }
// sqlite3DbFree(db,ref db.aExtension);
// db.aExtension = aHandle;
// db.aExtension[db.nExtension++] = handle;
return SQLITE_OK;
}
static public int sqlite3_load_extension(
sqlite3 db, /* Load the extension into this database connection */
string zFile, /* Name of the shared library containing extension */
string zProc, /* Entry point. Use "sqlite3_extension_init" if 0 */
ref string pzErrMsg /* Put error message here if not 0 */
)
{
int rc;
sqlite3_mutex_enter( db.mutex );
rc = sqlite3LoadExtension( db, zFile, zProc, ref pzErrMsg );
rc = sqlite3ApiExit( db, rc );
sqlite3_mutex_leave( db.mutex );
return rc;
}
/*
** Call this routine when the database connection is closing in order
** to clean up loaded extensions
*/
static void sqlite3CloseExtensions( sqlite3 db )
{
int i;
Debug.Assert( sqlite3_mutex_held( db.mutex ) );
for ( i = 0; i < db.nExtension; i++ )
{
sqlite3OsDlClose( db.pVfs, (HANDLE)db.aExtension[i] );
}
sqlite3DbFree( db, ref db.aExtension );
}
/*
** Enable or disable extension loading. Extension loading is disabled by
** default so as not to open security holes in older applications.
*/
static public int sqlite3_enable_load_extension( sqlite3 db, int onoff )
{
sqlite3_mutex_enter( db.mutex );
if ( onoff != 0 )
{
db.flags |= SQLITE_LoadExtension;
}
else
{
db.flags &= ~SQLITE_LoadExtension;
}
sqlite3_mutex_leave( db.mutex );
return SQLITE_OK;
}
#endif //* SQLITE_OMIT_LOAD_EXTENSION */
/*
** The auto-extension code added regardless of whether or not extension
** loading is supported. We need a dummy sqlite3Apis pointer for that
** code if regular extension loading is not available. This is that
** dummy pointer.
*/
#if SQLITE_OMIT_LOAD_EXTENSION
const sqlite3_api_routines sqlite3Apis = null;
#endif
/*
** The following object holds the list of automatically loaded
** extensions.
**
** This list is shared across threads. The SQLITE_MUTEX_STATIC_MASTER
** mutex must be held while accessing this list.
*/
//typedef struct sqlite3AutoExtList sqlite3AutoExtList;
public class sqlite3AutoExtList
{
public int nExt = 0; /* Number of entries in aExt[] */
public dxInit[] aExt = null; /* Pointers to the extension init functions */
public sqlite3AutoExtList( int nExt, dxInit[] aExt )
{
this.nExt = nExt;
this.aExt = aExt;
}
}
static sqlite3AutoExtList sqlite3Autoext = new sqlite3AutoExtList( 0, null );
/* The "wsdAutoext" macro will resolve to the autoextension
** state vector. If writable static data is unsupported on the target,
** we have to locate the state vector at run-time. In the more common
** case where writable static data is supported, wsdStat can refer directly
** to the "sqlite3Autoext" state vector declared above.
*/
#if SQLITE_OMIT_WSD
//# define wsdAutoextInit \
sqlite3AutoExtList *x = &GLOBAL(sqlite3AutoExtList,sqlite3Autoext)
//# define wsdAutoext x[0]
#else
//# define wsdAutoextInit
static void wsdAutoextInit()
{
}
//# define wsdAutoext sqlite3Autoext
static sqlite3AutoExtList wsdAutoext = sqlite3Autoext;
#endif
/*
** Register a statically linked extension that is automatically
** loaded by every new database connection.
*/
static int sqlite3_auto_extension( dxInit xInit )
{
int rc = SQLITE_OK;
#if !SQLITE_OMIT_AUTOINIT
rc = sqlite3_initialize();
if ( rc != 0 )
{
return rc;
}
else
#endif
{
int i;
#if SQLITE_THREADSAFE
sqlite3_mutex mutex = sqlite3MutexAlloc( SQLITE_MUTEX_STATIC_MASTER );
#else
sqlite3_mutex mutex = sqlite3MutexAlloc( SQLITE_MUTEX_STATIC_MASTER );
#endif
wsdAutoextInit();
sqlite3_mutex_enter( mutex );
for ( i = 0; i < wsdAutoext.nExt; i++ )
{
if ( wsdAutoext.aExt[i] == xInit )
break;
}
//if( i==wsdAutoext.nExt ){
// int nByte = (wsdAutoext.nExt+1)*sizeof(wsdAutoext.aExt[0]);
// void **aNew;
// aNew = sqlite3_realloc(wsdAutoext.aExt, nByte);
// if( aNew==0 ){
// rc = SQLITE_NOMEM;
// }else{
Array.Resize( ref wsdAutoext.aExt, wsdAutoext.nExt + 1 );// wsdAutoext.aExt = aNew;
wsdAutoext.aExt[wsdAutoext.nExt] = xInit;
wsdAutoext.nExt++;
//}
sqlite3_mutex_leave( mutex );
Debug.Assert( ( rc & 0xff ) == rc );
return rc;
}
}
/*
** Reset the automatic extension loading mechanism.
*/
static void sqlite3_reset_auto_extension()
{
#if !SQLITE_OMIT_AUTOINIT
if ( sqlite3_initialize() == SQLITE_OK )
#endif
{
#if SQLITE_THREADSAFE
sqlite3_mutex mutex = sqlite3MutexAlloc( SQLITE_MUTEX_STATIC_MASTER );
#else
sqlite3_mutex mutex = sqlite3MutexAlloc( SQLITE_MUTEX_STATIC_MASTER );
#endif
wsdAutoextInit();
sqlite3_mutex_enter( mutex );
#if SQLITE_OMIT_WSD
//sqlite3_free( ref wsdAutoext.aExt );
wsdAutoext.aExt = null;
wsdAutoext.nExt = 0;
#else
//sqlite3_free( ref sqlite3Autoext.aExt );
sqlite3Autoext.aExt = null;
sqlite3Autoext.nExt = 0;
#endif
sqlite3_mutex_leave( mutex );
}
}
/*
** Load all automatic extensions.
**
** If anything goes wrong, set an error in the database connection.
*/
static void sqlite3AutoLoadExtensions( sqlite3 db )
{
int i;
bool go = true;
dxInit xInit;//)(sqlite3*,char**,const sqlite3_api_routines);
wsdAutoextInit();
#if SQLITE_OMIT_WSD
if ( wsdAutoext.nExt == 0 )
#else
if ( sqlite3Autoext.nExt == 0 )
#endif
{
/* Common case: early out without every having to acquire a mutex */
return;
}
for ( i = 0; go; i++ )
{
string zErrmsg = "";
#if SQLITE_THREADSAFE
sqlite3_mutex mutex = sqlite3MutexAlloc( SQLITE_MUTEX_STATIC_MASTER );
#else
sqlite3_mutex mutex = sqlite3MutexAlloc( SQLITE_MUTEX_STATIC_MASTER );
#endif
sqlite3_mutex_enter( mutex );
if ( i >= wsdAutoext.nExt )
{
xInit = null;
go = false;
}
else
{
xInit = (dxInit)
wsdAutoext.aExt[i];
}
sqlite3_mutex_leave( mutex );
zErrmsg = "";
if ( xInit != null && xInit( db, ref zErrmsg, (sqlite3_api_routines)sqlite3Apis ) != 0 )
{
sqlite3Error( db, SQLITE_ERROR,
"automatic extension loading failed: %s", zErrmsg );
go = false;
}
sqlite3DbFree( db, ref zErrmsg );
}
}
}
}
| |
// 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.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void SubtractSByte()
{
var test = new SimpleBinaryOpTest__SubtractSByte();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (Avx.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (Avx.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (Avx.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (Avx.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (Avx.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleBinaryOpTest__SubtractSByte
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle inHandle2;
private GCHandle outHandle;
private ulong alignment;
public DataTable(SByte[] inArray1, SByte[] inArray2, SByte[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<SByte>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<SByte>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<SByte>();
if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<SByte, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<SByte, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector256<SByte> _fld1;
public Vector256<SByte> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<SByte>, byte>(ref testStruct._fld1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<SByte>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<SByte>, byte>(ref testStruct._fld2), ref Unsafe.As<SByte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<SByte>>());
return testStruct;
}
public void RunStructFldScenario(SimpleBinaryOpTest__SubtractSByte testClass)
{
var result = Avx2.Subtract(_fld1, _fld2);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleBinaryOpTest__SubtractSByte testClass)
{
fixed (Vector256<SByte>* pFld1 = &_fld1)
fixed (Vector256<SByte>* pFld2 = &_fld2)
{
var result = Avx2.Subtract(
Avx.LoadVector256((SByte*)(pFld1)),
Avx.LoadVector256((SByte*)(pFld2))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 32;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<SByte>>() / sizeof(SByte);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<SByte>>() / sizeof(SByte);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<SByte>>() / sizeof(SByte);
private static SByte[] _data1 = new SByte[Op1ElementCount];
private static SByte[] _data2 = new SByte[Op2ElementCount];
private static Vector256<SByte> _clsVar1;
private static Vector256<SByte> _clsVar2;
private Vector256<SByte> _fld1;
private Vector256<SByte> _fld2;
private DataTable _dataTable;
static SimpleBinaryOpTest__SubtractSByte()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<SByte>, byte>(ref _clsVar1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<SByte>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<SByte>, byte>(ref _clsVar2), ref Unsafe.As<SByte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<SByte>>());
}
public SimpleBinaryOpTest__SubtractSByte()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<SByte>, byte>(ref _fld1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<SByte>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<SByte>, byte>(ref _fld2), ref Unsafe.As<SByte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<SByte>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); }
_dataTable = new DataTable(_data1, _data2, new SByte[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Avx2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Avx2.Subtract(
Unsafe.Read<Vector256<SByte>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<SByte>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Avx2.Subtract(
Avx.LoadVector256((SByte*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((SByte*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Avx2.Subtract(
Avx.LoadAlignedVector256((SByte*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((SByte*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Avx2).GetMethod(nameof(Avx2.Subtract), new Type[] { typeof(Vector256<SByte>), typeof(Vector256<SByte>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<SByte>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<SByte>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<SByte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Avx2).GetMethod(nameof(Avx2.Subtract), new Type[] { typeof(Vector256<SByte>), typeof(Vector256<SByte>) })
.Invoke(null, new object[] {
Avx.LoadVector256((SByte*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((SByte*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<SByte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Avx2).GetMethod(nameof(Avx2.Subtract), new Type[] { typeof(Vector256<SByte>), typeof(Vector256<SByte>) })
.Invoke(null, new object[] {
Avx.LoadAlignedVector256((SByte*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((SByte*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<SByte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Avx2.Subtract(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector256<SByte>* pClsVar1 = &_clsVar1)
fixed (Vector256<SByte>* pClsVar2 = &_clsVar2)
{
var result = Avx2.Subtract(
Avx.LoadVector256((SByte*)(pClsVar1)),
Avx.LoadVector256((SByte*)(pClsVar2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector256<SByte>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector256<SByte>>(_dataTable.inArray2Ptr);
var result = Avx2.Subtract(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = Avx.LoadVector256((SByte*)(_dataTable.inArray1Ptr));
var op2 = Avx.LoadVector256((SByte*)(_dataTable.inArray2Ptr));
var result = Avx2.Subtract(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var op1 = Avx.LoadAlignedVector256((SByte*)(_dataTable.inArray1Ptr));
var op2 = Avx.LoadAlignedVector256((SByte*)(_dataTable.inArray2Ptr));
var result = Avx2.Subtract(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleBinaryOpTest__SubtractSByte();
var result = Avx2.Subtract(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new SimpleBinaryOpTest__SubtractSByte();
fixed (Vector256<SByte>* pFld1 = &test._fld1)
fixed (Vector256<SByte>* pFld2 = &test._fld2)
{
var result = Avx2.Subtract(
Avx.LoadVector256((SByte*)(pFld1)),
Avx.LoadVector256((SByte*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Avx2.Subtract(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector256<SByte>* pFld1 = &_fld1)
fixed (Vector256<SByte>* pFld2 = &_fld2)
{
var result = Avx2.Subtract(
Avx.LoadVector256((SByte*)(pFld1)),
Avx.LoadVector256((SByte*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Avx2.Subtract(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = Avx2.Subtract(
Avx.LoadVector256((SByte*)(&test._fld1)),
Avx.LoadVector256((SByte*)(&test._fld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector256<SByte> op1, Vector256<SByte> op2, void* result, [CallerMemberName] string method = "")
{
SByte[] inArray1 = new SByte[Op1ElementCount];
SByte[] inArray2 = new SByte[Op2ElementCount];
SByte[] outArray = new SByte[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<SByte, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<SByte, byte>(ref inArray2[0]), op2);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<SByte>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "")
{
SByte[] inArray1 = new SByte[Op1ElementCount];
SByte[] inArray2 = new SByte[Op2ElementCount];
SByte[] outArray = new SByte[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector256<SByte>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector256<SByte>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<SByte>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(SByte[] left, SByte[] right, SByte[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if ((sbyte)(left[0] - right[0]) != result[0])
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if ((sbyte)(left[i] - right[i]) != result[i])
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Avx2)}.{nameof(Avx2.Subtract)}<SByte>(Vector256<SByte>, Vector256<SByte>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
/// This code was generated by
/// \ / _ _ _| _ _
/// | (_)\/(_)(_|\/| |(/_ v1.0.0
/// / /
using System;
using System.Collections.Generic;
using Twilio.Base;
using Twilio.Converters;
namespace Twilio.Rest.Preview.Understand.Assistant
{
/// <summary>
/// PLEASE NOTE that this class contains preview products that are subject to change. Use them with caution. If you
/// currently do not have developer preview access, please contact help@twilio.com.
///
/// FetchFieldTypeOptions
/// </summary>
public class FetchFieldTypeOptions : IOptions<FieldTypeResource>
{
/// <summary>
/// The assistant_sid
/// </summary>
public string PathAssistantSid { get; }
/// <summary>
/// The sid
/// </summary>
public string PathSid { get; }
/// <summary>
/// Construct a new FetchFieldTypeOptions
/// </summary>
/// <param name="pathAssistantSid"> The assistant_sid </param>
/// <param name="pathSid"> The sid </param>
public FetchFieldTypeOptions(string pathAssistantSid, string pathSid)
{
PathAssistantSid = pathAssistantSid;
PathSid = pathSid;
}
/// <summary>
/// Generate the necessary parameters
/// </summary>
public List<KeyValuePair<string, string>> GetParams()
{
var p = new List<KeyValuePair<string, string>>();
return p;
}
}
/// <summary>
/// PLEASE NOTE that this class contains preview products that are subject to change. Use them with caution. If you
/// currently do not have developer preview access, please contact help@twilio.com.
///
/// ReadFieldTypeOptions
/// </summary>
public class ReadFieldTypeOptions : ReadOptions<FieldTypeResource>
{
/// <summary>
/// The assistant_sid
/// </summary>
public string PathAssistantSid { get; }
/// <summary>
/// Construct a new ReadFieldTypeOptions
/// </summary>
/// <param name="pathAssistantSid"> The assistant_sid </param>
public ReadFieldTypeOptions(string pathAssistantSid)
{
PathAssistantSid = pathAssistantSid;
}
/// <summary>
/// Generate the necessary parameters
/// </summary>
public override List<KeyValuePair<string, string>> GetParams()
{
var p = new List<KeyValuePair<string, string>>();
if (PageSize != null)
{
p.Add(new KeyValuePair<string, string>("PageSize", PageSize.ToString()));
}
return p;
}
}
/// <summary>
/// PLEASE NOTE that this class contains preview products that are subject to change. Use them with caution. If you
/// currently do not have developer preview access, please contact help@twilio.com.
///
/// CreateFieldTypeOptions
/// </summary>
public class CreateFieldTypeOptions : IOptions<FieldTypeResource>
{
/// <summary>
/// The assistant_sid
/// </summary>
public string PathAssistantSid { get; }
/// <summary>
/// A user-provided string that uniquely identifies this resource as an alternative to the sid. Unique up to 64 characters long.
/// </summary>
public string UniqueName { get; }
/// <summary>
/// A user-provided string that identifies this resource. It is non-unique and can up to 255 characters long.
/// </summary>
public string FriendlyName { get; set; }
/// <summary>
/// Construct a new CreateFieldTypeOptions
/// </summary>
/// <param name="pathAssistantSid"> The assistant_sid </param>
/// <param name="uniqueName"> A user-provided string that uniquely identifies this resource as an alternative to the
/// sid. Unique up to 64 characters long. </param>
public CreateFieldTypeOptions(string pathAssistantSid, string uniqueName)
{
PathAssistantSid = pathAssistantSid;
UniqueName = uniqueName;
}
/// <summary>
/// Generate the necessary parameters
/// </summary>
public List<KeyValuePair<string, string>> GetParams()
{
var p = new List<KeyValuePair<string, string>>();
if (UniqueName != null)
{
p.Add(new KeyValuePair<string, string>("UniqueName", UniqueName));
}
if (FriendlyName != null)
{
p.Add(new KeyValuePair<string, string>("FriendlyName", FriendlyName));
}
return p;
}
}
/// <summary>
/// PLEASE NOTE that this class contains preview products that are subject to change. Use them with caution. If you
/// currently do not have developer preview access, please contact help@twilio.com.
///
/// UpdateFieldTypeOptions
/// </summary>
public class UpdateFieldTypeOptions : IOptions<FieldTypeResource>
{
/// <summary>
/// The assistant_sid
/// </summary>
public string PathAssistantSid { get; }
/// <summary>
/// The sid
/// </summary>
public string PathSid { get; }
/// <summary>
/// A user-provided string that identifies this resource. It is non-unique and can up to 255 characters long.
/// </summary>
public string FriendlyName { get; set; }
/// <summary>
/// A user-provided string that uniquely identifies this resource as an alternative to the sid. Unique up to 64 characters long.
/// </summary>
public string UniqueName { get; set; }
/// <summary>
/// Construct a new UpdateFieldTypeOptions
/// </summary>
/// <param name="pathAssistantSid"> The assistant_sid </param>
/// <param name="pathSid"> The sid </param>
public UpdateFieldTypeOptions(string pathAssistantSid, string pathSid)
{
PathAssistantSid = pathAssistantSid;
PathSid = pathSid;
}
/// <summary>
/// Generate the necessary parameters
/// </summary>
public List<KeyValuePair<string, string>> GetParams()
{
var p = new List<KeyValuePair<string, string>>();
if (FriendlyName != null)
{
p.Add(new KeyValuePair<string, string>("FriendlyName", FriendlyName));
}
if (UniqueName != null)
{
p.Add(new KeyValuePair<string, string>("UniqueName", UniqueName));
}
return p;
}
}
/// <summary>
/// PLEASE NOTE that this class contains preview products that are subject to change. Use them with caution. If you
/// currently do not have developer preview access, please contact help@twilio.com.
///
/// DeleteFieldTypeOptions
/// </summary>
public class DeleteFieldTypeOptions : IOptions<FieldTypeResource>
{
/// <summary>
/// The assistant_sid
/// </summary>
public string PathAssistantSid { get; }
/// <summary>
/// The sid
/// </summary>
public string PathSid { get; }
/// <summary>
/// Construct a new DeleteFieldTypeOptions
/// </summary>
/// <param name="pathAssistantSid"> The assistant_sid </param>
/// <param name="pathSid"> The sid </param>
public DeleteFieldTypeOptions(string pathAssistantSid, string pathSid)
{
PathAssistantSid = pathAssistantSid;
PathSid = pathSid;
}
/// <summary>
/// Generate the necessary parameters
/// </summary>
public List<KeyValuePair<string, string>> GetParams()
{
var p = new List<KeyValuePair<string, string>>();
return p;
}
}
}
| |
using System;
using System.Data.Odbc;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Blob;
using MoreLinq;
using NuGet;
using MemoryCache = System.Runtime.Caching.MemoryCache;
namespace Mandro.NuGet.Core
{
public class AzureBlobPackageRepository : IPackageRepository
{
private readonly Lazy<MemoryCache> _lazyMemoryCache;
private readonly Lazy<CloudBlobContainer> _blogFilesContainer;
private readonly string _packagesBlob;
private readonly string _connectionString;
public AzureBlobPackageRepository(string containerName, string connectionString)
{
_packagesBlob = containerName;
_connectionString = connectionString;
_blogFilesContainer = new Lazy<CloudBlobContainer>(
() =>
{
var container = CloudStorageAccount.Parse(_connectionString)
.CreateCloudBlobClient()
.GetContainerReference(_packagesBlob);
if (container.CreateIfNotExists())
{
var permissions = container.GetPermissions();
permissions.PublicAccess = BlobContainerPublicAccessType.Container;
container.SetPermissions(permissions);
}
return container;
});
_lazyMemoryCache = new Lazy<MemoryCache>(
() =>
{
var cache = MemoryCache.Default;
var packages = BlogFilesContainer.ListBlobs().OfType<CloudBlockBlob>().Select(SafeReadZipPackage).Where(package => package != null);
foreach (var package in packages)
{
AddToCache(package, cache);
}
return cache;
});
}
public string Source
{
get
{
return _packagesBlob;
}
}
public PackageSaveModes PackageSaveMode { get; set; }
public bool SupportsPrereleasePackages
{
get
{
return false;
}
}
public IQueryable<IPackage> GetPackages()
{
return Cache.Select(keyValue => keyValue.Value as IPackage).AsQueryable();
}
public IQueryable<IWebPackage> GetWebPackages()
{
return GetPackages().OfType<IWebPackage>();
}
public async Task AddPackageAsync(IPackage package)
{
if (package == null)
{
throw new ArgumentNullException("package");
}
if (package is ZipPackage)
(package as ZipPackage).Published = DateTimeOffset.Now;
var blockBlobReference = BlogFilesContainer.GetBlockBlobReference(GetPackageKey(package));
await blockBlobReference.UploadFromStreamAsync(package.GetStream());
AddToCache(new WebZipPackage(package.GetStream(), blockBlobReference.Uri));
}
public async Task RemovePackageAsync(string packageId, string packageVersion)
{
if (packageId == null)
{
throw new ArgumentNullException("packageId");
}
if (packageVersion == null)
{
throw new ArgumentNullException("packageVersion");
}
await BlogFilesContainer.GetBlockBlobReference(GetPackageKey(packageId, packageVersion)).DeleteAsync();
var cachedPackage = Cache[packageId] as IWebPackage;
if (cachedPackage != null && cachedPackage.Version == SemanticVersion.Parse(packageVersion))
{
Cache.Remove(packageId);
// Load the latest package to Cache
var packages = BlogFilesContainer.ListBlobs().OfType<CloudBlockBlob>().Select(SafeReadZipPackage).Where(package => package != null).Where(p => p.Id == packageId);
if (packages.Any())
{
var latestPackage = packages.MaxBy(p => p.Version);
if (latestPackage != null)
{
AddToCache(latestPackage);
}
}
}
}
public IWebPackage GetPackage(string id, string version)
{
if (Cache[id] != null && ((IWebPackage)Cache[id]).Version == new SemanticVersion(version))
{
return Cache[id] as IWebPackage;
}
return SafeReadZipPackage(BlogFilesContainer.GetBlockBlobReference(GetPackageKey(id, version)));
}
private MemoryCache Cache
{
get
{
return _lazyMemoryCache.Value;
}
}
private CloudBlobContainer BlogFilesContainer
{
get
{
return _blogFilesContainer.Value;
}
}
private void AddToCache(IPackageName package)
{
var memoryCache = Cache;
AddToCache(package, memoryCache);
}
private static void AddToCache(IPackageName package, MemoryCache memoryCache)
{
var cachedObject = memoryCache[package.Id];
if (cachedObject != null)
{
if (package.Version > ((IPackage)cachedObject).Version)
{
memoryCache[package.Id] = package;
}
}
else
{
memoryCache[package.Id] = package;
}
}
private static string GetPackageKey(IPackageName package)
{
return GetPackageKey(package.Id, package.Version.ToString());
}
private static string GetPackageKey(string packageId, string packageVersion)
{
return packageId + "-" + packageVersion + ".nupkg";
}
private static WebZipPackage SafeReadZipPackage(CloudBlockBlob blob)
{
try
{
return new WebZipPackage(blob.OpenRead(), blob.Uri);
}
catch (Exception)
{
return null;
}
}
//public async Task<string> TEst
//{
// get
// {
// await Task.FromResult("Ble");
// }
//}
}
}
| |
// Copyright (c) 2009, Tom Lokovic
// 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.
//
// 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.Runtime.InteropServices;
using System.Text;
namespace Midi
{
/// <summary>
/// C# wrappers for the Win32 MIDI API.
/// </summary>
/// Because .NET does not provide MIDI support itself, in C# we must use P/Invoke to wrap the
/// Win32 API. That API consists of the MMSystem.h C header and the winmm.dll library. The API
/// is described in detail here: http://msdn.microsoft.com/en-us/library/ms712733(VS.85).aspx.
/// The P/Invoke interop mechanism is described here:
/// http://msdn.microsoft.com/en-us/library/aa288468(VS.71).aspx.
///
/// This file covers the subset of the MIDI protocol needed to manage input and output devices
/// and send and receive Note On/Off, Control Change, Pitch Bend and Program Change messages.
/// Other portions of the MIDI protocol (such as sysex events) are supported in the Win32 API
/// but are not wrapped here.
///
/// Some of the C functions are not typesafe when wrapped, so those wrappers are made private
/// and typesafe variants are provided.
static class Win32API
{
#region Constants
// The following constants come from MMSystem.h.
/// <summary>
/// Max length of a manufacturer name in the Win32 API.
/// </summary>
public const UInt32 MAXPNAMELEN = 32;
/// <summary>
/// Status type returned from most functions in the Win32 API.
/// </summary>
public enum MMRESULT : uint
{
// General return codes.
MMSYSERR_BASE = 0,
MMSYSERR_NOERROR = MMSYSERR_BASE + 0,
MMSYSERR_ERROR = MMSYSERR_BASE + 1,
MMSYSERR_BADDEVICEID = MMSYSERR_BASE + 2,
MMSYSERR_NOTENABLED = MMSYSERR_BASE + 3,
MMSYSERR_ALLOCATED = MMSYSERR_BASE + 4,
MMSYSERR_INVALHANDLE = MMSYSERR_BASE + 5,
MMSYSERR_NODRIVER = MMSYSERR_BASE + 6,
MMSYSERR_NOMEM = MMSYSERR_BASE + 7,
MMSYSERR_NOTSUPPORTED = MMSYSERR_BASE + 8,
MMSYSERR_BADERRNUM = MMSYSERR_BASE + 9,
MMSYSERR_INVALFLAG = MMSYSERR_BASE + 10,
MMSYSERR_INVALPARAM = MMSYSERR_BASE + 11,
MMSYSERR_HANDLEBUSY = MMSYSERR_BASE + 12,
MMSYSERR_INVALIDALIAS = MMSYSERR_BASE + 13,
MMSYSERR_BADDB = MMSYSERR_BASE + 14,
MMSYSERR_KEYNOTFOUND = MMSYSERR_BASE + 15,
MMSYSERR_READERROR = MMSYSERR_BASE + 16,
MMSYSERR_WRITEERROR = MMSYSERR_BASE + 17,
MMSYSERR_DELETEERROR = MMSYSERR_BASE + 18,
MMSYSERR_VALNOTFOUND = MMSYSERR_BASE + 19,
MMSYSERR_NODRIVERCB = MMSYSERR_BASE + 20,
MMSYSERR_MOREDATA = MMSYSERR_BASE + 21,
MMSYSERR_LASTERROR = MMSYSERR_BASE + 21,
// MIDI-specific return codes.
MIDIERR_BASE = 64,
MIDIERR_UNPREPARED = MIDIERR_BASE + 0,
MIDIERR_STILLPLAYING = MIDIERR_BASE + 1,
MIDIERR_NOMAP = MIDIERR_BASE + 2,
MIDIERR_NOTREADY = MIDIERR_BASE + 3,
MIDIERR_NODEVICE = MIDIERR_BASE + 4,
MIDIERR_INVALIDSETUP = MIDIERR_BASE + 5,
MIDIERR_BADOPENMODE = MIDIERR_BASE + 6,
MIDIERR_DONT_CONTINUE = MIDIERR_BASE + 7,
MIDIERR_LASTERROR = MIDIERR_BASE + 7
}
/// <summary>
/// Flags passed to midiInOpen() and midiOutOpen().
/// </summary>
public enum MidiOpenFlags : uint
{
CALLBACK_TYPEMASK = 0x70000,
CALLBACK_NULL = 0x00000,
CALLBACK_WINDOW = 0x10000,
CALLBACK_TASK = 0x20000,
CALLBACK_FUNCTION = 0x30000,
CALLBACK_THREAD = CALLBACK_TASK,
CALLBACK_EVENT = 0x50000,
MIDI_IO_STATUS = 0x00020
}
/// <summary>
/// Values for wTechnology field of MIDIOUTCAPS structure.
/// </summary>
public enum MidiDeviceType : ushort
{
MOD_MIDIPORT = 1,
MOD_SYNTH = 2,
MOD_SQSYNTH = 3,
MOD_FMSYNTH = 4,
MOD_MAPPER = 5,
MOD_WAVETABLE = 6,
MOD_SWSYNTH = 7
}
/// <summary>
/// Flags for dwSupport field of MIDIOUTCAPS structure.
/// </summary>
public enum MidiExtraFeatures : uint
{
MIDICAPS_VOLUME = 0x0001,
MIDICAPS_LRVOLUME = 0x0002,
MIDICAPS_CACHE = 0x0004,
MIDICAPS_STREAM = 0x0008
}
/// <summary>
/// "Midi Out Messages", passed to wMsg param of MidiOutProc.
/// </summary>
public enum MidiOutMessage : uint
{
MOM_OPEN = 0x3C7,
MOM_CLOSE = 0x3C8,
MOM_DONE = 0x3C9
}
/// <summary>
/// "Midi In Messages", passed to wMsg param of MidiInProc.
/// </summary>
public enum MidiInMessage : uint
{
MIM_OPEN = 0x3C1,
MIM_CLOSE = 0x3C2,
MIM_DATA = 0x3C3,
MIM_LONGDATA = 0x3C4,
MIM_ERROR = 0x3C5,
MIM_LONGERROR = 0x3C6,
MIM_MOREDATA = 0x3CC
}
#endregion
#region Handles
/// <summary>
/// Win32 handle for a MIDI output device.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public struct HMIDIOUT
{
public IntPtr handle;
}
/// <summary>
/// Win32 handle for a MIDI input device.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public struct HMIDIIN
{
public IntPtr handle;
}
#endregion
#region Structs
/// <summary>
/// Struct representing the capabilities of an output device.
/// </summary>
/// Win32 docs: http://msdn.microsoft.com/en-us/library/ms711619(VS.85).aspx
[StructLayout(LayoutKind.Sequential)]
public struct MIDIOUTCAPS
{
public UInt16 wMid;
public UInt16 wPid;
public UInt32 vDriverVersion;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = (int)MAXPNAMELEN)]
public string szPname;
public MidiDeviceType wTechnology;
public UInt16 wVoices;
public UInt16 wNotes;
public UInt16 wChannelMask;
public MidiExtraFeatures dwSupport;
}
/// <summary>
/// Struct representing the capabilities of an input device.
/// </summary>
/// Win32 docs: http://msdn.microsoft.com/en-us/library/ms711596(VS.85).aspx
[StructLayout(LayoutKind.Sequential)]
public struct MIDIINCAPS
{
public UInt16 wMid;
public UInt16 wPid;
public UInt32 vDriverVersion;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = (int)MAXPNAMELEN)]
public string szPname;
public UInt32 dwSupport;
}
#region SysEx
/// <summary>
/// Strut to hold outgoing long messages (sysex)
/// </summary>
/// Win32 docs: http://msdn.microsoft.com/en-us/library/ms711592(v=VS.85).aspx
[StructLayout(LayoutKind.Sequential)]
public struct MIDIHDR
{
public IntPtr lpData;
public int dwBufferLength;
public int dwBytesRecorded;
public IntPtr dwUser;
public int dwFlags;
public IntPtr lpNext;
public IntPtr reserved;
public int dwOffset;
//public IntPtr dwReserved;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]
public int[] reservedArray;
}
#endregion
#endregion
#region Functions for MIDI Output
/// <summary>
/// Returns the number of MIDI output devices on this system.
/// </summary>
/// Win32 docs: http://msdn.microsoft.com/en-us/library/ms711627(VS.85).aspx
[DllImport("winmm.dll", SetLastError = true)]
public static extern UInt32 midiOutGetNumDevs();
/// <summary>
/// Fills in the capabilities struct for a specific output device.
/// </summary>
/// NOTE: This is adapted from the original Win32 function in order to make it typesafe.
///
/// Win32 docs: http://msdn.microsoft.com/en-us/library/ms711621(VS.85).aspx
public static MMRESULT midiOutGetDevCaps(UIntPtr uDeviceID, out MIDIOUTCAPS caps)
{
return midiOutGetDevCaps(uDeviceID, out caps,
(UInt32)Marshal.SizeOf(typeof(MIDIOUTCAPS)));
}
/// <summary>
/// Callback invoked when a MIDI output device is opened, closed, or finished with a buffer.
/// </summary>
/// Win32 docs: http://msdn.microsoft.com/en-us/library/ms711637(VS.85).aspx
public delegate void MidiOutProc(HMIDIOUT hmo, MidiOutMessage wMsg, UIntPtr dwInstance,
UIntPtr dwParam1, UIntPtr dwParam2);
/// <summary>
/// Opens a MIDI output device.
/// </summary>
/// NOTE: This is adapted from the original Win32 function in order to make it typesafe.
///
/// Win32 docs: http://msdn.microsoft.com/en-us/library/ms711632(VS.85).aspx
public static MMRESULT midiOutOpen(out HMIDIOUT lphmo, UIntPtr uDeviceID,
MidiOutProc dwCallback, UIntPtr dwCallbackInstance)
{
//return midiOutOpen(out lphmo, uDeviceID, dwCallback, dwCallbackInstance,
// dwCallback == null ? MidiOpenFlags.CALLBACK_NULL : MidiOpenFlags.CALLBACK_FUNCTION);
#region SysEx
return midiOutOpen(out lphmo, uDeviceID, dwCallback, dwCallbackInstance,
dwCallback == null ? MidiOpenFlags.CALLBACK_NULL : MidiOpenFlags.CALLBACK_FUNCTION & MidiOpenFlags.MIDI_IO_STATUS);
#endregion
}
/// <summary>
/// Turns off all notes and sustains on a MIDI output device.
/// </summary>
/// Win32 docs: http://msdn.microsoft.com/en-us/library/dd798479(VS.85).aspx
[DllImport("winmm.dll", SetLastError = true)]
public static extern MMRESULT midiOutReset(HMIDIOUT hmo);
/// <summary>
/// Closes a MIDI output device.
/// </summary>
/// Win32 docs: http://msdn.microsoft.com/en-us/library/ms711620(VS.85).aspx
[DllImport("winmm.dll", SetLastError = true)]
public static extern MMRESULT midiOutClose(HMIDIOUT hmo);
/// <summary>
/// Sends a short MIDI message (anything but sysex or stream).
/// </summary>
/// Win32 docs: http://msdn.microsoft.com/en-us/library/ms711640(VS.85).aspx
[DllImport("winmm.dll", SetLastError = true)]
public static extern MMRESULT midiOutShortMsg(HMIDIOUT hmo, UInt32 dwMsg);
#region SysEx
/// <summary>
/// Sends a long MIDI message (sysex).
/// </summary>
/// Win32 docs: http://msdn.microsoft.com/en-us/library/ms711629(VS.85).aspx
[DllImport("winmm.dll", SetLastError = true)]
public static extern MMRESULT midiOutLongMsg(HMIDIOUT hmo, IntPtr lpMidiOutHdr, UInt32 cbMidiOutHdr);
// MMRESULT midiOutLongMsg(HMIDIOUT hmo, LPMIDIHDR lpMidiOutHdr, UINT cbMidiOutHdr);
/// <summary>
/// Prepares a long message for sending
/// </summary>
/// Win32 docs: http://msdn.microsoft.com/en-us/library/ms711634(v=VS.85).aspx
[DllImport("winmm.dll", SetLastError = true)]
public static extern MMRESULT midiOutPrepareHeader(HMIDIOUT hmo, IntPtr lpMidiOutHdr, UInt32 cbMidiOutHdr);
/// <summary>
/// Frees header space after sending long message
/// </summary>
/// Win32 docs: http://msdn.microsoft.com/en-us/library/ms711641(v=VS.85).aspx
[DllImport("winmm.dll", SetLastError = true)]
public static extern MMRESULT midiOutUnprepareHeader(HMIDIOUT hmo, IntPtr lpMidiOutHdr, UInt32 cbMidiOutHdr);
#endregion
/// <summary>
/// Gets the error text for a return code related to an output device.
/// </summary>
/// NOTE: This is adapted from the original Win32 function in order to make it typesafe.
///
/// Win32 docs: http://msdn.microsoft.com/en-us/library/ms711622(VS.85).aspx
public static MMRESULT midiOutGetErrorText(MMRESULT mmrError, StringBuilder lpText)
{
return midiOutGetErrorText(mmrError, lpText, (UInt32)lpText.Capacity);
}
#endregion
#region Functions for MIDI Input
/// <summary>
/// Returns the number of MIDI input devices on this system.
/// </summary>
/// Win32 docs: http://msdn.microsoft.com/en-us/library/ms711608(VS.85).aspx
[DllImport("winmm.dll", SetLastError = true)]
public static extern UInt32 midiInGetNumDevs();
/// <summary>
/// Fills in the capabilities struct for a specific input device.
/// </summary>
/// NOTE: This is adapted from the original Win32 function in order to make it typesafe.
///
/// Win32 docs: http://msdn.microsoft.com/en-us/library/ms711604(VS.85).aspx
public static MMRESULT midiInGetDevCaps(UIntPtr uDeviceID, out MIDIINCAPS caps)
{
return midiInGetDevCaps(uDeviceID, out caps,
(UInt32)Marshal.SizeOf(typeof(MIDIINCAPS)));
}
/// <summary>
/// Callback invoked when a MIDI event is received from an input device.
/// </summary>
/// Win32 docs: http://msdn.microsoft.com/en-us/library/ms711612(VS.85).aspx
public delegate void MidiInProc(HMIDIIN hMidiIn, MidiInMessage wMsg, UIntPtr dwInstance,
UIntPtr dwParam1, UIntPtr dwParam2);
/// <summary>
/// Opens a MIDI input device.
/// </summary>
/// NOTE: This is adapted from the original Win32 function in order to make it typesafe.
///
/// Win32 docs: http://msdn.microsoft.com/en-us/library/ms711610(VS.85).aspx
public static MMRESULT midiInOpen(out HMIDIIN lphMidiIn, UIntPtr uDeviceID,
MidiInProc dwCallback, UIntPtr dwCallbackInstance)
{
return midiInOpen(out lphMidiIn, uDeviceID, dwCallback, dwCallbackInstance,
dwCallback == null ? MidiOpenFlags.CALLBACK_NULL : MidiOpenFlags.CALLBACK_FUNCTION);
}
/// <summary>
/// Starts input on a MIDI input device.
/// </summary>
/// Win32 docs: http://msdn.microsoft.com/en-us/library/ms711614(VS.85).aspx
[DllImport("winmm.dll", SetLastError = true)]
public static extern MMRESULT midiInStart(HMIDIIN hMidiIn);
/// <summary>
/// Stops input on a MIDI input device.
/// </summary>
/// Win32 docs: http://msdn.microsoft.com/en-us/library/ms711615(VS.85).aspx
[DllImport("winmm.dll", SetLastError = true)]
public static extern MMRESULT midiInStop(HMIDIIN hMidiIn);
/// <summary>
/// Resets input on a MIDI input device.
/// </summary>
/// Win32 docs: http://msdn.microsoft.com/en-us/library/ms711613(VS.85).aspx
[DllImport("winmm.dll", SetLastError = true)]
public static extern MMRESULT midiInReset(HMIDIIN hMidiIn);
/// <summary>
/// Closes a MIDI input device.
/// </summary>
/// Win32 docs: http://msdn.microsoft.com/en-us/library/ms711602(VS.85).aspx
[DllImport("winmm.dll", SetLastError = true)]
public static extern MMRESULT midiInClose(HMIDIIN hMidiIn);
/// <summary>
/// Gets the error text for a return code related to an input device.
/// </summary>
/// NOTE: This is adapted from the original Win32 function in order to make it typesafe.
///
/// Win32 docs: http://msdn.microsoft.com/en-us/library/ms711605(VS.85).aspx
public static MMRESULT midiInGetErrorText(MMRESULT mmrError, StringBuilder lpText)
{
return midiInGetErrorText(mmrError, lpText, (UInt32)lpText.Capacity);
}
#region SysEx
/// <summary>
/// Send a buffer to and input device in order to receive SysEx messages.
/// </summary>
/// Win32 docs: http://msdn.microsoft.com/en-us/library/dd798450(VS.85).aspx
[DllImport("winmm.dll", SetLastError = true)]
public static extern MMRESULT midiInAddBuffer(HMIDIIN hMidiIn, IntPtr lpMidiInHdr, UInt32 cbMidiInHdr);
/// <summary>
/// Prepare an input buffer before passing to midiInAddBuffer.
/// </summary>
/// Win32 docs: http://msdn.microsoft.com/en-us/library/dd798459(VS.85).aspx
[DllImport("winmm.dll", SetLastError = true)]
public static extern MMRESULT midiInPrepareHeader(HMIDIIN hMidiIn, IntPtr headerPtr, UInt32 cbMidiInHdr);
/// <summary>
/// Clean up preparation performed by midiInPrepareHeader.
/// </summary>
/// Win32 docs: http://msdn.microsoft.com/en-us/library/dd798464(VS.85).aspx
[DllImport("winmm.dll", SetLastError = true)]
public static extern MMRESULT midiInUnprepareHeader(HMIDIIN hMidiIn, IntPtr headerPtr, UInt32 cbMidiInHdr);
#endregion
#endregion
#region Non-Typesafe Bindings
// The bindings in this section are not typesafe, so we make them private and privide
// typesafe variants above.
[DllImport("winmm.dll", SetLastError = true)]
private static extern MMRESULT midiOutGetDevCaps(UIntPtr uDeviceID, out MIDIOUTCAPS caps,
UInt32 cbMidiOutCaps);
[DllImport("winmm.dll", SetLastError = true)]
private static extern MMRESULT midiOutOpen(out HMIDIOUT lphmo, UIntPtr uDeviceID,
MidiOutProc dwCallback, UIntPtr dwCallbackInstance, MidiOpenFlags dwFlags);
[DllImport("winmm.dll", SetLastError = true)]
private static extern MMRESULT midiOutGetErrorText(MMRESULT mmrError, StringBuilder lpText,
UInt32 cchText);
[DllImport("winmm.dll", SetLastError = true)]
private static extern MMRESULT midiInGetDevCaps(UIntPtr uDeviceID, out MIDIINCAPS caps,
UInt32 cbMidiInCaps);
[DllImport("winmm.dll", SetLastError = true)]
private static extern MMRESULT midiInOpen(out HMIDIIN lphMidiIn, UIntPtr uDeviceID,
MidiInProc dwCallback, UIntPtr dwCallbackInstance, MidiOpenFlags dwFlags);
[DllImport("winmm.dll", SetLastError = true)]
private static extern MMRESULT midiInGetErrorText(MMRESULT mmrError, StringBuilder lpText,
UInt32 cchText);
#endregion
}
}
| |
using UnityEngine;
using System.Collections;
using UMA;
/// <summary>
/// Human male DNA converter behaviour.
/// </summary>
/// <remarks>
/// Although intended for Humans this DNA converter includes ranges
/// far outside Human norms and can also be used for other Humanoid charatcers
/// such as Elves, Giants, Halflings, et al.
/// </remarks>
public class HumanMaleDNAConverterBehaviour : HumanoidDNAConverterBehaviour
{
public HumanMaleDNAConverterBehaviour()
{
this.ApplyDnaAction = UpdateUMAMaleDNABones;
this.DNAType = typeof(UMADnaHumanoid);
}
/// <summary>
/// Adjusts a skeleton to reflect the DNA values from UMA character data.
/// </summary>
/// <remarks>
/// This will set the postion, rotation, and scale of the various adjustment
/// bones used by the UMA human rigs to generate a unique character shape.
/// Also calculates a somewhat realistic mass for the character and the
/// height and radius of their default collider.
/// </remarks>
/// <param name="umaData">UMA data.</param>
/// <param name="skeleton">Skeleton.</param>
public static void UpdateUMAMaleDNABones(UMAData umaData, UMASkeleton skeleton)
{
var umaDna = umaData.GetDna<UMADnaHumanoid>();
skeleton.SetScale(headAdjustHash,
new Vector3(
Mathf.Clamp(1, 1, 1),
Mathf.Clamp(1 + (umaDna.headWidth - 0.5f) * 0.30f, 0.5f, 1.6f),
Mathf.Clamp(1 , 1, 1)));
//umaData.boneList["HeadAdjust"].boneTransform.localScale = new Vector3(
//Mathf.Clamp(1, 1, 1),
//Mathf.Clamp(1 + (umaDna.headWidth - 0.5f) * 0.30f, 0.5f, 1.6f),
//Mathf.Clamp(1 , 1, 1));
skeleton.SetScale(neckAdjustHash,
new Vector3(
Mathf.Clamp(1, 0.6f, 2),
Mathf.Clamp(1 + (umaDna.neckThickness - 0.5f) * 0.80f, 0.5f, 1.6f),
Mathf.Clamp(1 + (umaDna.neckThickness - 0.5f) * 1.2f, 0.5f, 1.6f)));
//umaData.boneList["NeckAdjust"].boneTransform.localScale = new Vector3(
//Mathf.Clamp(1, 0.6f, 2),
//Mathf.Clamp(1 + (umaDna.neckThickness - 0.5f) * 0.80f, 0.5f, 1.6f),
//Mathf.Clamp(1 + (umaDna.neckThickness - 0.5f) * 1.2f, 0.5f, 1.6f));
skeleton.SetScale(leftOuterBreastHash,
new Vector3(
Mathf.Clamp(1 + (umaDna.breastSize - 0.5f) * 1.50f + (umaDna.upperWeight - 0.5f) * 0.10f, 0.6f, 1.5f),
Mathf.Clamp(1 + (umaDna.breastSize - 0.5f) * 1.50f + (umaDna.upperWeight - 0.5f) * 0.10f, 0.6f, 1.5f),
Mathf.Clamp(1 + (umaDna.breastSize - 0.5f) * 1.50f + (umaDna.upperWeight - 0.5f) * 0.10f, 0.6f, 1.5f)));
skeleton.SetScale(rightOuterBreastHash,
new Vector3(
Mathf.Clamp(1 + (umaDna.breastSize - 0.5f) * 1.50f + (umaDna.upperWeight - 0.5f) * 0.10f, 0.6f, 1.5f),
Mathf.Clamp(1 + (umaDna.breastSize - 0.5f) * 1.50f + (umaDna.upperWeight - 0.5f) * 0.10f, 0.6f, 1.5f),
Mathf.Clamp(1 + (umaDna.breastSize - 0.5f) * 1.50f + (umaDna.upperWeight - 0.5f) * 0.10f, 0.6f, 1.5f)));
//umaData.boneList["LeftOuterBreast"].boneTransform.localScale = new Vector3(
//Mathf.Clamp(1 + (umaDna.breastSize - 0.5f) * 1.50f + (umaDna.upperWeight - 0.5f) * 0.10f, 0.6f, 1.5f),
//Mathf.Clamp(1 + (umaDna.breastSize - 0.5f) * 1.50f + (umaDna.upperWeight - 0.5f) * 0.10f, 0.6f, 1.5f),
//Mathf.Clamp(1 + (umaDna.breastSize - 0.5f) * 1.50f + (umaDna.upperWeight - 0.5f) * 0.10f, 0.6f, 1.5f));
//umaData.boneList["RightOuterBreast"].boneTransform.localScale = new Vector3(
//Mathf.Clamp(1 + (umaDna.breastSize - 0.5f) * 1.50f + (umaDna.upperWeight - 0.5f) * 0.10f, 0.6f, 1.5f),
//Mathf.Clamp(1 + (umaDna.breastSize - 0.5f) * 1.50f + (umaDna.upperWeight - 0.5f) * 0.10f, 0.6f, 1.5f),
//Mathf.Clamp(1 + (umaDna.breastSize - 0.5f) * 1.50f + (umaDna.upperWeight - 0.5f) * 0.10f, 0.6f, 1.5f));
skeleton.SetScale(leftEyeHash,
new Vector3(
Mathf.Clamp(1 + (umaDna.eyeSize - 0.5f) * 0.3f , 0.7f, 1.4f),
Mathf.Clamp(1 + (umaDna.eyeSize - 0.5f) * 0.3f , 0.7f, 1.4f),
Mathf.Clamp(1 + (umaDna.eyeSize - 0.5f) * 0.3f , 0.7f, 1.4f)));
skeleton.SetScale(rightEyeHash,
new Vector3(
Mathf.Clamp(1 + (umaDna.eyeSize - 0.5f) * 0.3f , 0.7f, 1.4f),
Mathf.Clamp(1 + (umaDna.eyeSize - 0.5f) * 0.3f , 0.7f, 1.4f),
Mathf.Clamp(1 + (umaDna.eyeSize - 0.5f) * 0.3f , 0.7f, 1.4f)));
//umaData.boneList["LeftEye"].boneTransform.localScale = new Vector3(
//Mathf.Clamp(1 + (umaDna.eyeSize - 0.5f) * 0.3f , 0.7f, 1.4f),
//Mathf.Clamp(1 + (umaDna.eyeSize - 0.5f) * 0.3f , 0.7f, 1.4f),
//Mathf.Clamp(1 + (umaDna.eyeSize - 0.5f) * 0.3f , 0.7f, 1.4f));
//umaData.boneList["RightEye"].boneTransform.localScale = new Vector3(
//Mathf.Clamp(1 + (umaDna.eyeSize - 0.5f) * 0.3f , 0.7f, 1.4f),
//Mathf.Clamp(1 + (umaDna.eyeSize - 0.5f) * 0.3f , 0.7f, 1.4f),
//Mathf.Clamp(1 + (umaDna.eyeSize - 0.5f) * 0.3f , 0.7f, 1.4f));
skeleton.SetRotation(leftEyeAdjustHash,
Quaternion.Euler(new Vector3((umaDna.eyeRotation - 0.5f) * 20, 0, 0)));
skeleton.SetRotation(rightEyeAdjustHash,
Quaternion.Euler(new Vector3(-(umaDna.eyeRotation - 0.5f) * 20, 0, 0)));
//umaData.boneList["LeftEye"].boneTransform.localEulerAngles = new Vector3((umaDna.eyeRotation - 0.5f) * 20, -90, -180);
//umaData.boneList["RightEye"].boneTransform.localEulerAngles = new Vector3(-(umaDna.eyeRotation - 0.5f) * 20, -90, -180);
skeleton.SetScale(spine1AdjustHash,
new Vector3(
Mathf.Clamp(1, 0.6f, 2),
Mathf.Clamp(0.9f + (umaDna.upperWeight - 0.5f) * 0.10f + (umaDna.upperMuscle - 0.5f) * 0.5f, 0.45f, 1.50f),
Mathf.Clamp(0.7f + (umaDna.upperWeight - 0.5f) * 0.45f + (umaDna.upperMuscle - 0.5f) * 0.45f, 0.55f, 1.15f)));
//umaData.boneList["Spine1Adjust"].boneTransform.localScale = new Vector3(
//Mathf.Clamp(1, 0.6f, 2),
//Mathf.Clamp(0.9f + (umaDna.upperWeight - 0.5f) * 0.10f + (umaDna.upperMuscle - 0.5f) * 0.5f, 0.45f, 1.50f),
//Mathf.Clamp(0.7f + (umaDna.upperWeight - 0.5f) * 0.45f + (umaDna.upperMuscle - 0.5f) * 0.45f, 0.55f, 1.15f));
skeleton.SetScale(spineAdjustHash,
new Vector3(
Mathf.Clamp(1, 0.6f, 2),
Mathf.Clamp(0.9f + (umaDna.upperWeight - 0.5f) * 0.35f + (umaDna.upperMuscle - 0.5f) * 0.45f, 0.75f, 1.350f),
Mathf.Clamp(0.8f + (umaDna.upperWeight - 0.5f) * 0.35f + (umaDna.upperMuscle - 0.5f) * 0.25f, 0.75f, 1.350f)));
//umaData.boneList["SpineAdjust"].boneTransform.localScale = new Vector3(
//Mathf.Clamp(1, 0.6f, 2),
//Mathf.Clamp(0.9f + (umaDna.upperWeight - 0.5f) * 0.35f + (umaDna.upperMuscle - 0.5f) * 0.45f, 0.75f, 1.350f),
//Mathf.Clamp(0.8f + (umaDna.upperWeight - 0.5f) * 0.35f + (umaDna.upperMuscle - 0.5f) * 0.25f, 0.75f, 1.350f));
skeleton.SetScale(lowerBackBellyHash,
new Vector3(
Mathf.Clamp(1 + (umaDna.belly - 0.5f) * 1.0f, 0.35f, 1.75f),
Mathf.Clamp(1 + (umaDna.belly - 0.5f) * 0.35f, 0.35f, 1.75f),
Mathf.Clamp(1 + (umaDna.belly - 0.5f) * 1.25f, 0.35f, 1.75f)));
//umaData.boneList["LowerBackBelly"].boneTransform.localScale = new Vector3(
//Mathf.Clamp(1 + (umaDna.belly - 0.5f) * 1.0f, 0.35f, 1.75f),
//Mathf.Clamp(1 + (umaDna.belly - 0.5f) * 0.35f, 0.35f, 1.75f),
//Mathf.Clamp(1 + (umaDna.belly - 0.5f) * 1.25f, 0.35f, 1.75f));
skeleton.SetScale(lowerBackAdjustHash,
new Vector3(
Mathf.Clamp(1 + (umaDna.upperWeight - 0.5f) * 0.25f + (umaDna.lowerWeight - 0.5f) * 0.15f, 0.85f, 1.5f),
Mathf.Clamp(1 + (umaDna.upperWeight - 0.5f) * 0.25f + (umaDna.lowerWeight - 0.5f) * 0.15f + (umaDna.waist - 0.5f) * 0.45f, 0.65f, 1.75f),
Mathf.Clamp(1 + (umaDna.upperWeight - 0.5f) * 0.25f + (umaDna.lowerWeight - 0.5f) * 0.15f, 0.85f, 1.5f)));
//umaData.boneList["LowerBackAdjust"].boneTransform.localScale = new Vector3(
//Mathf.Clamp(1 + (umaDna.upperWeight - 0.5f) * 0.25f + (umaDna.lowerWeight - 0.5f) * 0.15f, 0.85f, 1.5f),
//Mathf.Clamp(1 + (umaDna.upperWeight - 0.5f) * 0.25f + (umaDna.lowerWeight - 0.5f) * 0.15f + (umaDna.waist - 0.5f) * 0.45f, 0.65f, 1.75f),
//Mathf.Clamp(1 + (umaDna.upperWeight - 0.5f) * 0.25f + (umaDna.lowerWeight - 0.5f) * 0.15f, 0.85f, 1.5f));
skeleton.SetScale(leftTrapeziusHash,
new Vector3(
Mathf.Clamp(1 + (umaDna.upperMuscle - 0.5f) * 1.35f, 0.65f, 1.35f),
Mathf.Clamp(1 + (umaDna.upperMuscle - 0.5f) * 1.35f, 0.65f, 1.35f),
Mathf.Clamp(1 + (umaDna.upperMuscle - 0.5f) * 1.35f, 0.65f, 1.35f)));
skeleton.SetScale(rightTrapeziusHash,
new Vector3(
Mathf.Clamp(1 + (umaDna.upperMuscle - 0.5f) * 1.35f, 0.65f, 1.35f),
Mathf.Clamp(1 + (umaDna.upperMuscle - 0.5f) * 1.35f, 0.65f, 1.35f),
Mathf.Clamp(1 + (umaDna.upperMuscle - 0.5f) * 1.35f, 0.65f, 1.35f)));
//umaData.boneList["LeftTrapezius"].boneTransform.localScale = new Vector3(
//Mathf.Clamp(1 + (umaDna.upperMuscle - 0.5f) * 1.35f, 0.65f, 1.35f),
//Mathf.Clamp(1 + (umaDna.upperMuscle - 0.5f) * 1.35f, 0.65f, 1.35f),
//Mathf.Clamp(1 + (umaDna.upperMuscle - 0.5f) * 1.35f, 0.65f, 1.35f));
//umaData.boneList["RightTrapezius"].boneTransform.localScale = new Vector3(
//Mathf.Clamp(1 + (umaDna.upperMuscle - 0.5f) * 1.35f, 0.65f, 1.35f),
//Mathf.Clamp(1 + (umaDna.upperMuscle - 0.5f) * 1.35f, 0.65f, 1.35f),
//Mathf.Clamp(1 + (umaDna.upperMuscle - 0.5f) * 1.35f, 0.65f, 1.35f));
skeleton.SetScale(leftArmAdjustHash,
new Vector3(
Mathf.Clamp(1, 0.6f, 2),
Mathf.Clamp(1 + (umaDna.armWidth - 0.5f) * 0.65f, 0.65f, 1.65f),
Mathf.Clamp(1 + (umaDna.armWidth - 0.5f) * 0.65f, 0.65f, 1.65f)));
skeleton.SetScale(rightArmAdjustHash,
new Vector3(
Mathf.Clamp(1, 0.6f, 2),
Mathf.Clamp(1 + (umaDna.armWidth - 0.5f) * 0.65f, 0.65f, 1.65f),
Mathf.Clamp(1 + (umaDna.armWidth - 0.5f) * 0.65f, 0.65f, 1.65f)));
//umaData.boneList["LeftArmAdjust"].boneTransform.localScale = new Vector3(
//Mathf.Clamp(1, 0.6f, 2),
//Mathf.Clamp(1 + (umaDna.armWidth - 0.5f) * 0.65f, 0.65f, 1.65f),
//Mathf.Clamp(1 + (umaDna.armWidth - 0.5f) * 0.65f, 0.65f, 1.65f));
//umaData.boneList["RightArmAdjust"].boneTransform.localScale = new Vector3(
//Mathf.Clamp(1, 0.6f, 2),
//Mathf.Clamp(1 + (umaDna.armWidth - 0.5f) * 0.65f, 0.65f, 1.65f),
//Mathf.Clamp(1 + (umaDna.armWidth - 0.5f) * 0.65f, 0.65f, 1.65f));
skeleton.SetScale(leftForeArmAdjustHash,
new Vector3(
Mathf.Clamp(1, 0.6f, 2),
Mathf.Clamp(1 + (umaDna.forearmWidth - 0.5f) * 0.65f, 0.75f, 1.25f),
Mathf.Clamp(1 + (umaDna.forearmWidth - 0.5f) * 0.65f, 0.75f, 1.25f)));
skeleton.SetScale(rightForeArmAdjustHash,
new Vector3(
Mathf.Clamp(1, 0.6f, 2),
Mathf.Clamp(1 + (umaDna.forearmWidth - 0.5f) * 0.65f, 0.75f, 1.25f),
Mathf.Clamp(1 + (umaDna.forearmWidth - 0.5f) * 0.65f, 0.75f, 1.25f)));
//umaData.boneList["LeftForeArmAdjust"].boneTransform.localScale = new Vector3(
//Mathf.Clamp(1, 0.6f, 2),
//Mathf.Clamp(1 + (umaDna.forearmWidth - 0.5f) * 0.65f, 0.75f, 1.25f),
//Mathf.Clamp(1 + (umaDna.forearmWidth - 0.5f) * 0.65f, 0.75f, 1.25f));
//umaData.boneList["RightForeArmAdjust"].boneTransform.localScale = new Vector3(
//Mathf.Clamp(1, 0.6f, 2),
//Mathf.Clamp(1 + (umaDna.forearmWidth - 0.5f) * 0.65f, 0.75f, 1.25f),
//Mathf.Clamp(1 + (umaDna.forearmWidth - 0.5f) * 0.65f, 0.75f, 1.25f));
skeleton.SetScale(leftForeArmTwistAdjustHash,
new Vector3(
Mathf.Clamp(1, 0.6f, 2),
Mathf.Clamp(1 + (umaDna.forearmWidth - 0.5f) * 0.35f, 0.75f, 1.25f),
Mathf.Clamp(1 + (umaDna.forearmWidth - 0.5f) * 0.35f, 0.75f, 1.25f)));
skeleton.SetScale(rightForeArmTwistAdjustHash,
new Vector3(
Mathf.Clamp(1, 0.6f, 2),
Mathf.Clamp(1 + (umaDna.forearmWidth - 0.5f) * 0.35f, 0.75f, 1.25f),
Mathf.Clamp(1 + (umaDna.forearmWidth - 0.5f) * 0.35f, 0.75f, 1.25f)));
//umaData.boneList["LeftForeArmTwistAdjust"].boneTransform.localScale = new Vector3(
//Mathf.Clamp(1, 0.6f, 2),
//Mathf.Clamp(1 + (umaDna.forearmWidth - 0.5f) * 0.35f, 0.75f, 1.25f),
//Mathf.Clamp(1 + (umaDna.forearmWidth - 0.5f) * 0.35f, 0.75f, 1.25f));
//umaData.boneList["RightForeArmTwistAdjust"].boneTransform.localScale = new Vector3(
//Mathf.Clamp(1, 0.6f, 2),
//Mathf.Clamp(1 + (umaDna.forearmWidth - 0.5f) * 0.35f, 0.75f, 1.25f),
//Mathf.Clamp(1 + (umaDna.forearmWidth - 0.5f) * 0.35f, 0.75f, 1.25f));
skeleton.SetScale(leftShoulderAdjustHash,
new Vector3(
Mathf.Clamp(1, 0.6f, 2),
Mathf.Clamp(1 + (umaDna.upperWeight - 0.5f) * 0.35f + (umaDna.upperMuscle - 0.5f) * 0.55f, 0.75f, 1.25f),
Mathf.Clamp(1 + (umaDna.upperWeight - 0.5f) * 0.35f + (umaDna.upperMuscle - 0.5f) * 0.55f, 0.75f, 1.25f)));
skeleton.SetScale(rightShoulderAdjustHash,
new Vector3(
Mathf.Clamp(1, 0.6f, 2),
Mathf.Clamp(1 + (umaDna.upperWeight - 0.5f) * 0.35f + (umaDna.upperMuscle - 0.5f) * 0.55f, 0.75f, 1.25f),
Mathf.Clamp(1 + (umaDna.upperWeight - 0.5f) * 0.35f + (umaDna.upperMuscle - 0.5f) * 0.55f, 0.75f, 1.25f)));
//umaData.boneList["LeftShoulderAdjust"].boneTransform.localScale = new Vector3(
//Mathf.Clamp(1, 0.6f, 2),
//Mathf.Clamp(1 + (umaDna.upperWeight - 0.5f) * 0.35f + (umaDna.upperMuscle - 0.5f) * 0.55f, 0.75f, 1.25f),
//Mathf.Clamp(1 + (umaDna.upperWeight - 0.5f) * 0.35f + (umaDna.upperMuscle - 0.5f) * 0.55f, 0.75f, 1.25f));
//umaData.boneList["RightShoulderAdjust"].boneTransform.localScale = new Vector3(
//Mathf.Clamp(1, 0.6f, 2),
//Mathf.Clamp(1 + (umaDna.upperWeight - 0.5f) * 0.35f + (umaDna.upperMuscle - 0.5f) * 0.55f, 0.75f, 1.25f),
//Mathf.Clamp(1 + (umaDna.upperWeight - 0.5f) * 0.35f + (umaDna.upperMuscle - 0.5f) * 0.55f, 0.75f, 1.25f));
skeleton.SetScale(leftUpLegAdjustHash,
new Vector3(
Mathf.Clamp(1, 0.6f, 2),
Mathf.Clamp(1 + (umaDna.lowerWeight - 0.5f) * 0.45f + (umaDna.lowerMuscle - 0.5f) * 0.15f - (umaDna.legsSize - 0.5f), 0.45f, 1.15f),
Mathf.Clamp(1 + (umaDna.lowerWeight - 0.5f) * 0.45f + (umaDna.lowerMuscle - 0.5f) * 0.15f - (umaDna.legsSize - 0.5f), 0.45f, 1.15f)));
skeleton.SetScale(rightUpLegAdjustHash,
new Vector3(
Mathf.Clamp(1, 0.6f, 2),
Mathf.Clamp(1 + (umaDna.lowerWeight - 0.5f) * 0.45f + (umaDna.lowerMuscle - 0.5f) * 0.15f - (umaDna.legsSize - 0.5f), 0.45f, 1.15f),
Mathf.Clamp(1 + (umaDna.lowerWeight - 0.5f) * 0.45f + (umaDna.lowerMuscle - 0.5f) * 0.15f - (umaDna.legsSize - 0.5f), 0.45f, 1.15f)));
//umaData.boneList["LeftUpLegAdjust"].boneTransform.localScale = new Vector3(
//Mathf.Clamp(1, 0.6f, 2),
//Mathf.Clamp(1 + (umaDna.lowerWeight - 0.5f) * 0.45f + (umaDna.lowerMuscle - 0.5f) * 0.15f - (umaDna.legsSize - 0.5f), 0.45f, 1.15f),
//Mathf.Clamp(1 + (umaDna.lowerWeight - 0.5f) * 0.45f + (umaDna.lowerMuscle - 0.5f) * 0.15f - (umaDna.legsSize - 0.5f), 0.45f, 1.15f));
//umaData.boneList["RightUpLegAdjust"].boneTransform.localScale = new Vector3(
//Mathf.Clamp(1, 0.6f, 2),
//Mathf.Clamp(1 + (umaDna.lowerWeight - 0.5f) * 0.45f + (umaDna.lowerMuscle - 0.5f) * 0.15f - (umaDna.legsSize - 0.5f), 0.45f, 1.15f),
//Mathf.Clamp(1 + (umaDna.lowerWeight - 0.5f) * 0.45f + (umaDna.lowerMuscle - 0.5f) * 0.15f - (umaDna.legsSize - 0.5f), 0.45f, 1.15f));
skeleton.SetScale(leftLegAdjustHash,
new Vector3(
Mathf.Clamp(1, 0.6f, 2),
Mathf.Clamp(1 + (umaDna.lowerWeight - 0.5f) * 0.15f + (umaDna.lowerMuscle - 0.5f) * 0.95f - (umaDna.legsSize - 0.5f), 0.65f, 1.45f),
Mathf.Clamp(1 + (umaDna.lowerWeight - 0.5f) * 0.15f + (umaDna.lowerMuscle - 0.5f) * 0.75f - (umaDna.legsSize - 0.5f), 0.65f, 1.45f)));
skeleton.SetScale(rightLegAdjustHash,
new Vector3(
Mathf.Clamp(1, 0.6f, 2),
Mathf.Clamp(1 + (umaDna.lowerWeight - 0.5f) * 0.15f + (umaDna.lowerMuscle - 0.5f) * 0.95f - (umaDna.legsSize - 0.5f), 0.65f, 1.45f),
Mathf.Clamp(1 + (umaDna.lowerWeight - 0.5f) * 0.15f + (umaDna.lowerMuscle - 0.5f) * 0.75f - (umaDna.legsSize - 0.5f), 0.65f, 1.45f)));
//umaData.boneList["LeftLegAdjust"].boneTransform.localScale = new Vector3(
//Mathf.Clamp(1, 0.6f, 2),
//Mathf.Clamp(1 + (umaDna.lowerWeight - 0.5f) * 0.15f + (umaDna.lowerMuscle - 0.5f) * 0.95f - (umaDna.legsSize - 0.5f), 0.65f, 1.45f),
//Mathf.Clamp(1 + (umaDna.lowerWeight - 0.5f) * 0.15f + (umaDna.lowerMuscle - 0.5f) * 0.75f - (umaDna.legsSize - 0.5f), 0.65f, 1.45f));
//umaData.boneList["RightLegAdjust"].boneTransform.localScale = new Vector3(
//Mathf.Clamp(1, 0.6f, 2),
//Mathf.Clamp(1 + (umaDna.lowerWeight - 0.5f) * 0.15f + (umaDna.lowerMuscle - 0.5f) * 0.95f - (umaDna.legsSize - 0.5f), 0.65f, 1.45f),
//Mathf.Clamp(1 + (umaDna.lowerWeight - 0.5f) * 0.15f + (umaDna.lowerMuscle - 0.5f) * 0.75f - (umaDna.legsSize - 0.5f), 0.65f, 1.45f));
skeleton.SetScale(leftGluteusHash,
new Vector3(
Mathf.Clamp(1 + (umaDna.gluteusSize - 0.5f) * 1.35f , 0.25f, 2.35f),
Mathf.Clamp(1 + (umaDna.gluteusSize - 0.5f) * 1.35f , 0.25f, 2.35f),
Mathf.Clamp(1 + (umaDna.gluteusSize - 0.5f) * 1.35f , 0.25f, 2.35f)));
skeleton.SetScale(rightGluteusHash,
new Vector3(
Mathf.Clamp(1 + (umaDna.gluteusSize - 0.5f) * 1.35f , 0.25f, 2.35f),
Mathf.Clamp(1 + (umaDna.gluteusSize - 0.5f) * 1.35f , 0.25f, 2.35f),
Mathf.Clamp(1 + (umaDna.gluteusSize - 0.5f) * 1.35f , 0.25f, 2.35f)));
//umaData.boneList["LeftGluteus"].boneTransform.localScale = new Vector3(
//Mathf.Clamp(1 + (umaDna.gluteusSize - 0.5f) * 1.35f , 0.25f, 2.35f),
//Mathf.Clamp(1 + (umaDna.gluteusSize - 0.5f) * 1.35f , 0.25f, 2.35f),
//Mathf.Clamp(1 + (umaDna.gluteusSize - 0.5f) * 1.35f , 0.25f, 2.35f));
//umaData.boneList["RightGluteus"].boneTransform.localScale = new Vector3(
//Mathf.Clamp(1 + (umaDna.gluteusSize - 0.5f) * 1.35f , 0.25f, 2.35f),
//Mathf.Clamp(1 + (umaDna.gluteusSize - 0.5f) * 1.35f , 0.25f, 2.35f),
//Mathf.Clamp(1 + (umaDna.gluteusSize - 0.5f) * 1.35f , 0.25f, 2.35f));
skeleton.SetScale(leftEarAdjustHash,
new Vector3(
Mathf.Clamp(1 + (umaDna.earsSize - 0.5f) * 1.0f, 0.75f, 1.5f),
Mathf.Clamp(1 + (umaDna.earsSize - 0.5f) * 1.0f, 0.75f, 1.5f),
Mathf.Clamp(1 + (umaDna.earsSize - 0.5f) * 1.0f, 0.75f, 1.5f)));
skeleton.SetScale(rightEarAdjustHash,
new Vector3(
Mathf.Clamp(1 + (umaDna.earsSize - 0.5f) * 1.0f, 0.75f, 1.5f),
Mathf.Clamp(1 + (umaDna.earsSize - 0.5f) * 1.0f, 0.75f, 1.5f),
Mathf.Clamp(1 + (umaDna.earsSize - 0.5f) * 1.0f, 0.75f, 1.5f)));
//umaData.boneList["LeftEarAdjust"].boneTransform.localScale = new Vector3(
//Mathf.Clamp(1 + (umaDna.earsSize - 0.5f) * 1.0f, 0.75f, 1.5f),
//Mathf.Clamp(1 + (umaDna.earsSize - 0.5f) * 1.0f, 0.75f, 1.5f),
//Mathf.Clamp(1 + (umaDna.earsSize - 0.5f) * 1.0f, 0.75f, 1.5f));
//umaData.boneList["RightEarAdjust"].boneTransform.localScale = new Vector3(
//Mathf.Clamp(1 + (umaDna.earsSize - 0.5f) * 1.0f, 0.75f, 1.5f),
//Mathf.Clamp(1 + (umaDna.earsSize - 0.5f) * 1.0f, 0.75f, 1.5f),
//Mathf.Clamp(1 + (umaDna.earsSize - 0.5f) * 1.0f, 0.75f, 1.5f));
skeleton.SetPositionRelative(leftEarAdjustHash,
new Vector3(
Mathf.Clamp(0 + (umaDna.headWidth - 0.5f) * -0.01f, -0.01f, 0.01f),
Mathf.Clamp(0 + (umaDna.headWidth - 0.5f) * -0.03f, -0.03f, 0.03f),
Mathf.Clamp(0 + (umaDna.earsPosition - 0.5f) * 0.02f, -0.02f, 0.02f)));
skeleton.SetPositionRelative(rightEarAdjustHash,
new Vector3(
Mathf.Clamp(0 + (umaDna.headWidth - 0.5f) * -0.01f, -0.01f, 0.01f),
Mathf.Clamp(0 + (umaDna.headWidth - 0.5f) * 0.03f, -0.03f, 0.03f),
Mathf.Clamp(0 + (umaDna.earsPosition - 0.5f) * 0.02f, -0.02f, 0.02f)));
skeleton.SetRotation(leftEarAdjustHash,
Quaternion.Euler(new Vector3(
Mathf.Clamp(0, -30, 80),
Mathf.Clamp(0, -30, 80),
Mathf.Clamp((umaDna.earsRotation - 0.5f) * 40, -15, 40))));
skeleton.SetRotation(rightEarAdjustHash,
Quaternion.Euler(new Vector3(
Mathf.Clamp(0, -30, 80),
Mathf.Clamp(0, -30, 80),
Mathf.Clamp((umaDna.earsRotation - 0.5f) * -40, -40, 15))));
skeleton.SetScale(noseBaseAdjustHash,
new Vector3(
Mathf.Clamp(1 + (umaDna.noseSize - 0.5f) * 1.5f, 0.25f, 3.0f),
Mathf.Clamp(1 + (umaDna.noseSize - 0.5f) * 0.15f + (umaDna.noseWidth - 0.5f) * 1.0f, 0.25f, 3.0f),
Mathf.Clamp(1 + (umaDna.noseSize - 0.5f) * 0.15f + (umaDna.noseFlatten - 0.5f) * 0.75f, 0.25f, 3.0f)));
skeleton.SetScale(noseMiddleAdjustHash,
new Vector3(
Mathf.Clamp(1 + (umaDna.noseCurve - 0.5f) * 1.5f + (umaDna.noseSize - 0.5f) * 1.0f, 0.5f, 3.0f),
Mathf.Clamp(1 + (umaDna.noseCurve - 0.5f) * 0.15f + (umaDna.noseSize - 0.5f) * 0.25f + (umaDna.noseWidth - 0.5f) * 0.5f, 0.5f, 3.0f),
Mathf.Clamp(1 + (umaDna.noseCurve - 0.5f) * 0.15f + (umaDna.noseSize - 0.5f) * 0.10f, 0.5f, 3.0f)));
skeleton.SetRotation(noseBaseAdjustHash,
Quaternion.Euler(new Vector3(
Mathf.Clamp(0, -30, 80),
Mathf.Clamp((umaDna.noseInclination - 0.5f) * 60, -60, 30),
Mathf.Clamp(0, -30, 80))));
skeleton.SetPositionRelative(noseBaseAdjustHash,
new Vector3(
Mathf.Clamp(0 + (umaDna.nosePronounced - 0.5f) * -0.025f, -0.025f, 0.025f),
Mathf.Clamp(0, -0.05f, 0.05f),
Mathf.Clamp(0 + (umaDna.nosePosition - 0.5f) * 0.025f, -0.025f, 0.025f)));
skeleton.SetPositionRelative(noseMiddleAdjustHash,
new Vector3(
Mathf.Clamp(0 + (umaDna.nosePronounced - 0.5f) * -0.012f, -0.012f, 0.012f),
Mathf.Clamp(0, -0.05f, 0.05f),
Mathf.Clamp(0 + (umaDna.nosePosition - 0.5f) * 0.015f, -0.015f, 0.015f)));
skeleton.SetPositionRelative(leftNoseAdjustHash,
new Vector3(
Mathf.Clamp(0 + (umaDna.nosePronounced - 0.5f) * -0.025f, -0.025f, 0.025f),
Mathf.Clamp(0, -0.05f, 0.05f),
Mathf.Clamp(0 + (umaDna.nosePosition - 0.5f) * 0.025f, -0.025f, 0.025f)));
skeleton.SetPositionRelative(rightNoseAdjustHash,
new Vector3(
Mathf.Clamp(0 + (umaDna.nosePronounced - 0.5f) * -0.025f, -0.025f, 0.025f),
Mathf.Clamp(0, -0.05f, 0.05f),
Mathf.Clamp(0 + (umaDna.nosePosition - 0.5f) * 0.025f, -0.025f, 0.025f)));
skeleton.SetPositionRelative(upperLipsAdjustHash,
new Vector3(
Mathf.Clamp(0, -0.05f, 0.05f),
Mathf.Clamp(0, -0.05f, 0.05f),
Mathf.Clamp(0 + (umaDna.nosePosition - 0.5f) * 0.0045f, -0.0045f, 0.0045f)));
skeleton.SetScale(mandibleAdjustHash,
new Vector3(
Mathf.Clamp(1 + (umaDna.chinPronounced - 0.5f) * 0.18f, 0.55f, 1.75f),
Mathf.Clamp(1 + (umaDna.chinSize - 0.5f) * 1.3f, 0.75f, 1.3f),
Mathf.Clamp(1, 0.4f, 1.5f)));
skeleton.SetPositionRelative(mandibleAdjustHash,
new Vector3(
Mathf.Clamp(0, -0.0125f, 0.0125f),
Mathf.Clamp(0, -0.0125f, 0.0125f),
Mathf.Clamp(0 + (umaDna.chinPosition - 0.5f) * 0.0075f, -0.0075f, 0.0075f)));
skeleton.SetPositionRelative(leftLowMaxilarAdjustHash,
new Vector3(
Mathf.Clamp(0, -0.05f, 0.05f),
Mathf.Clamp(0 + (umaDna.jawsSize - 0.5f) * 0.025f, -0.025f, 0.025f),
Mathf.Clamp(0 + (umaDna.jawsPosition - 0.5f) * 0.03f, -0.03f, 0.03f)));
skeleton.SetPositionRelative(rightLowMaxilarAdjustHash,
new Vector3(
Mathf.Clamp(0, -0.05f, 0.05f),
Mathf.Clamp(0 + (umaDna.jawsSize - 0.5f) * -0.025f, -0.025f, 0.025f),
Mathf.Clamp(0 + (umaDna.jawsPosition - 0.5f) * 0.03f, -0.03f, 0.03f)));
skeleton.SetScale(leftCheekAdjustHash,
new Vector3(
Mathf.Clamp(1 + (umaDna.cheekSize - 0.5f) * 1.05f, 0.35f, 2.05f),
Mathf.Clamp(1 + (umaDna.cheekSize - 0.5f) * 1.05f, 0.35f, 2.05f),
Mathf.Clamp(1 + (umaDna.cheekSize - 0.5f) * 1.05f, 0.35f, 2.05f)));
skeleton.SetScale(rightCheekAdjustHash,
new Vector3(
Mathf.Clamp(1 + (umaDna.cheekSize - 0.5f) * 1.05f, 0.35f, 2.05f),
Mathf.Clamp(1 + (umaDna.cheekSize - 0.5f) * 1.05f, 0.35f, 2.05f),
Mathf.Clamp(1 + (umaDna.cheekSize - 0.5f) * 1.05f, 0.35f, 2.05f)));
skeleton.SetPositionRelative(leftCheekAdjustHash,
new Vector3(
Mathf.Clamp(0, -0.05f, 0.05f),
Mathf.Clamp(0, -0.05f, 0.05f),
Mathf.Clamp(0 + (umaDna.cheekPosition - 0.5f) * 0.03f, -0.03f, 0.03f)));
skeleton.SetPositionRelative(rightCheekAdjustHash,
new Vector3(
Mathf.Clamp(0, -0.05f, 0.05f),
Mathf.Clamp(0, -0.05f, 0.05f),
Mathf.Clamp(0 + (umaDna.cheekPosition - 0.5f) * 0.03f, -0.03f, 0.03f)));
skeleton.SetPositionRelative(leftLowCheekAdjustHash,
new Vector3(
Mathf.Clamp(0 + (umaDna.lowCheekPronounced - 0.5f) * -0.07f, -0.07f, 0.07f),
Mathf.Clamp(0, -0.05f, 0.05f),
Mathf.Clamp(0 + (umaDna.lowCheekPosition - 0.5f) * 0.06f, -0.06f, 0.06f)));
skeleton.SetPositionRelative(rightLowCheekAdjustHash,
new Vector3(
Mathf.Clamp(0 + (umaDna.lowCheekPronounced - 0.5f) * -0.07f, -0.07f, 0.07f),
Mathf.Clamp(0, -0.05f, 0.05f),
Mathf.Clamp(0 + (umaDna.lowCheekPosition - 0.5f) * 0.06f, -0.06f, 0.06f)));
skeleton.SetPositionRelative(noseTopAdjustHash,
new Vector3(
Mathf.Clamp(0 + (umaDna.foreheadSize - 0.5f) * -0.015f, -0.025f, 0.005f),
Mathf.Clamp(0, -0.05f, 0.05f),
Mathf.Clamp(0 + (umaDna.foreheadPosition - 0.5f) * -0.025f + (umaDna.foreheadSize - 0.5f) * -0.0015f, -0.015f, 0.0025f)));
skeleton.SetPositionRelative(leftEyebrowLowAdjustHash,
new Vector3(
Mathf.Clamp(0 + (umaDna.foreheadSize - 0.5f) * -0.015f, -0.025f, 0.005f),
Mathf.Clamp(0, -0.05f, 0.05f),
Mathf.Clamp(0 + (umaDna.foreheadPosition - 0.5f) * -0.02f + (umaDna.foreheadSize - 0.5f) * -0.005f, -0.015f, 0.005f)));
skeleton.SetPositionRelative(leftEyebrowMiddleAdjustHash,
new Vector3(
Mathf.Clamp(0 + (umaDna.foreheadSize - 0.5f) * -0.015f, -0.025f, 0.005f),
Mathf.Clamp(0, -0.05f, 0.05f),
Mathf.Clamp(0 + (umaDna.foreheadPosition - 0.5f) * -0.05f + (umaDna.foreheadSize - 0.5f) * -0.005f, -0.025f, 0.005f)));
skeleton.SetPositionRelative(leftEyebrowUpAdjustHash,
new Vector3(
Mathf.Clamp(0 + (umaDna.foreheadSize - 0.5f) * -0.015f, -0.025f, 0.005f),
Mathf.Clamp(0, -0.05f, 0.05f),
Mathf.Clamp(0 + (umaDna.foreheadPosition - 0.5f) * -0.007f + (umaDna.foreheadSize - 0.5f) * -0.005f, -0.010f, 0.005f)));
skeleton.SetPositionRelative(rightEyebrowLowAdjustHash,
new Vector3(
Mathf.Clamp(0 + (umaDna.foreheadSize - 0.5f) * -0.015f, -0.025f, 0.005f),
Mathf.Clamp(0, -0.05f, 0.05f),
Mathf.Clamp(0 + (umaDna.foreheadPosition - 0.5f) * -0.02f + (umaDna.foreheadSize - 0.5f) * -0.005f, -0.015f, 0.005f)));
skeleton.SetPositionRelative(rightEyebrowMiddleAdjustHash,
new Vector3(
Mathf.Clamp(0 + (umaDna.foreheadSize - 0.5f) * -0.015f, -0.025f, 0.005f),
Mathf.Clamp(0, -0.05f, 0.05f),
Mathf.Clamp(0 + (umaDna.foreheadPosition - 0.5f) * -0.05f + (umaDna.foreheadSize - 0.5f) * -0.005f, -0.025f, 0.005f)));
skeleton.SetPositionRelative(rightEyebrowUpAdjustHash,
new Vector3(
Mathf.Clamp(0 + (umaDna.foreheadSize - 0.5f) * -0.015f, -0.025f, 0.005f),
Mathf.Clamp(0, -0.05f, 0.05f),
Mathf.Clamp(0 + (umaDna.foreheadPosition - 0.5f) * -0.007f + (umaDna.foreheadSize - 0.5f) * -0.005f, -0.010f, 0.005f)));
skeleton.SetScale(lipsSuperiorAdjustHash,
new Vector3(
Mathf.Clamp(1 + (umaDna.lipsSize - 0.5f) * 0.05f, 1.0f, 1.05f),
Mathf.Clamp(1 + (umaDna.lipsSize - 0.5f) * 0.9f, 0.65f, 1.5f),
Mathf.Clamp(1 + (umaDna.lipsSize - 0.5f) * 0.9f, 0.65f, 1.5f)));
skeleton.SetScale(lipsInferiorAdjustHash,
new Vector3(
Mathf.Clamp(1 + (umaDna.lipsSize - 0.5f) * 0.05f, 1.0f, 1.05f),
Mathf.Clamp(1 + (umaDna.lipsSize - 0.5f) * 1.0f, 0.65f, 1.5f),
Mathf.Clamp(1 + (umaDna.lipsSize - 0.5f) * 1.0f, 0.65f, 1.5f)));
skeleton.SetScale(leftLipsSuperiorMiddleAdjustHash,
new Vector3(
Mathf.Clamp(1 + (umaDna.lipsSize - 0.5f) * 0.05f, 1.0f, 1.05f),
Mathf.Clamp(1 + (umaDna.lipsSize - 0.5f) * 0.9f, 0.65f, 1.5f),
Mathf.Clamp(1 + (umaDna.lipsSize - 0.5f) * 0.9f, 0.65f, 1.5f)));
skeleton.SetScale(rightLipsSuperiorMiddleAdjustHash,
new Vector3(
Mathf.Clamp(1 + (umaDna.lipsSize - 0.5f) * 0.05f, 1.0f, 1.05f),
Mathf.Clamp(1 + (umaDna.lipsSize - 0.5f) * 0.9f, 0.65f, 1.5f),
Mathf.Clamp(1 + (umaDna.lipsSize - 0.5f) * 0.9f, 0.65f, 1.5f)));
skeleton.SetScale(leftLipsInferiorAdjustHash,
new Vector3(
Mathf.Clamp(1 + (umaDna.lipsSize - 0.5f) * 0.05f, 1.0f, 1.05f),
Mathf.Clamp(1 + (umaDna.lipsSize - 0.5f) * 0.9f, 0.65f, 1.5f),
Mathf.Clamp(1 + (umaDna.lipsSize - 0.5f) * 0.9f, 0.65f, 1.5f)));
skeleton.SetScale(rightLipsInferiorAdjustHash,
new Vector3(
Mathf.Clamp(1 + (umaDna.lipsSize - 0.5f) * 0.05f, 1.0f, 1.05f),
Mathf.Clamp(1 + (umaDna.lipsSize - 0.5f) * 0.9f, 0.65f, 1.5f),
Mathf.Clamp(1 + (umaDna.lipsSize - 0.5f) * 0.9f, 0.65f, 1.5f)));
skeleton.SetPositionRelative(lipsInferiorAdjustHash,
new Vector3(
Mathf.Clamp(0, -0.05f, 0.05f),
Mathf.Clamp(0, -0.05f, 0.05f),
Mathf.Clamp(0 + (umaDna.lipsSize - 0.5f) * -0.008f, -0.1f, 0.1f)));
skeleton.SetPositionRelative(leftLipsAdjustHash,
new Vector3(
Mathf.Clamp(0, -0.05f, 0.05f),
Mathf.Clamp(0 + (umaDna.mouthSize - 0.5f) * 0.03f, -0.02f, 0.005f),
Mathf.Clamp(0, -0.05f, 0.05f)));
skeleton.SetPositionRelative(rightLipsAdjustHash,
new Vector3(
Mathf.Clamp(0, -0.05f, 0.05f),
Mathf.Clamp(0 + (umaDna.mouthSize - 0.5f) * -0.03f, -0.005f, 0.02f),
Mathf.Clamp(0, -0.05f, 0.05f)));
skeleton.SetPositionRelative(leftLipsSuperiorMiddleAdjustHash,
new Vector3(
Mathf.Clamp(0, -0.05f, 0.05f),
Mathf.Clamp(0 + (umaDna.mouthSize - 0.5f) * 0.007f, -0.02f, 0.005f),
Mathf.Clamp(0, -0.05f, 0.05f)));
skeleton.SetPositionRelative(rightLipsSuperiorMiddleAdjustHash,
new Vector3(
Mathf.Clamp(0, -0.05f, 0.05f),
Mathf.Clamp(0 + (umaDna.mouthSize - 0.5f) * -0.007f, -0.005f, 0.02f),
Mathf.Clamp(0, -0.05f, 0.05f)));
skeleton.SetPositionRelative(leftLipsInferiorAdjustHash,
new Vector3(
Mathf.Clamp(0, -0.05f, 0.05f),
Mathf.Clamp(0 + (umaDna.mouthSize - 0.5f) * 0.007f, -0.02f, 0.005f),
Mathf.Clamp(0 + (umaDna.lipsSize - 0.5f) * -0.008f, -0.1f, 0.1f)));
skeleton.SetPositionRelative(rightLipsInferiorAdjustHash,
new Vector3(
Mathf.Clamp(0, -0.05f, 0.05f),
Mathf.Clamp(0 + (umaDna.mouthSize - 0.5f) * -0.007f, -0.005f, 0.02f),
Mathf.Clamp(0 + (umaDna.lipsSize - 0.5f) * -0.008f, -0.1f, 0.1f)));
////Bone structure change
float overallScale = 0.88f + (umaDna.height - 0.5f) * 1.0f + (umaDna.legsSize - 0.5f) * 1.0f;
overallScale = Mathf.Clamp(overallScale, 0.5f, 2f);
skeleton.SetScale(positionHash, new Vector3(overallScale, overallScale, overallScale));
skeleton.SetPositionRelative(positionHash,
new Vector3(
Mathf.Clamp((umaDna.feetSize - 0.5f) * -0.27f, -0.15f, 0.0675f),
Mathf.Clamp(0, -10, 10),
Mathf.Clamp(0, -10, 10)));
float lowerBackScale = Mathf.Clamp(1 - (umaDna.legsSize - 0.5f) * 1.0f, 0.5f, 3.0f);
skeleton.SetScale(lowerBackHash, new Vector3(lowerBackScale, lowerBackScale, lowerBackScale));
skeleton.SetScale(headHash,
new Vector3(
Mathf.Clamp(1 + (umaDna.headSize - 0.5f) * 2.0f, 0.5f, 2),
Mathf.Clamp(1 + (umaDna.headSize - 0.5f) * 2.0f, 0.5f, 2),
Mathf.Clamp(1 + (umaDna.headSize - 0.5f) * 2.0f, 0.5f, 2)));
skeleton.SetScale(leftArmHash,
new Vector3(
Mathf.Clamp(1 + (umaDna.armLength - 0.5f) * 2.0f, 0.5f, 2.0f),
Mathf.Clamp(1 + (umaDna.armLength - 0.5f) * 2.0f, 0.5f, 2.0f),
Mathf.Clamp(1 + (umaDna.armLength - 0.5f) * 2.0f, 0.5f, 2.0f)));
skeleton.SetScale(rightArmHash,
new Vector3(
Mathf.Clamp(1 + (umaDna.armLength - 0.5f) * 2.0f, 0.5f, 2.0f),
Mathf.Clamp(1 + (umaDna.armLength - 0.5f) * 2.0f, 0.5f, 2.0f),
Mathf.Clamp(1 + (umaDna.armLength - 0.5f) * 2.0f, 0.5f, 2.0f)));
skeleton.SetScale(leftForeArmHash,
new Vector3(
Mathf.Clamp(1 + (umaDna.forearmLength - 0.5f) * 2.0f, 0.5f, 2.0f),
Mathf.Clamp(1 + (umaDna.forearmLength - 0.5f) * 2.0f, 0.5f, 2.0f),
Mathf.Clamp(1 + (umaDna.forearmLength - 0.5f) * 2.0f, 0.5f, 2.0f)));
skeleton.SetScale(rightForeArmHash,
new Vector3(
Mathf.Clamp(1 + (umaDna.forearmLength - 0.5f) * 2.0f, 0.5f, 2.0f),
Mathf.Clamp(1 + (umaDna.forearmLength - 0.5f) * 2.0f, 0.5f, 2.0f),
Mathf.Clamp(1 + (umaDna.forearmLength - 0.5f) * 2.0f, 0.5f, 2.0f)));
skeleton.SetScale(leftHandHash,
new Vector3(
Mathf.Clamp(1 + (umaDna.handsSize - 0.5f) * 2.0f, 0.5f, 2.0f),
Mathf.Clamp(1 + (umaDna.handsSize - 0.5f) * 2.0f, 0.5f, 2.0f),
Mathf.Clamp(1 + (umaDna.handsSize - 0.5f) * 2.0f, 0.5f, 2.0f)));
skeleton.SetScale(rightHandHash,
new Vector3(
Mathf.Clamp(1 + (umaDna.handsSize - 0.5f) * 2.0f, 0.5f, 2.0f),
Mathf.Clamp(1 + (umaDna.handsSize - 0.5f) * 2.0f, 0.5f, 2.0f),
Mathf.Clamp(1 + (umaDna.handsSize - 0.5f) * 2.0f, 0.5f, 2.0f)));
skeleton.SetScale(leftFootHash,
new Vector3(
Mathf.Clamp(1 + (umaDna.feetSize - 0.5f) * 2.0f, 0.5f, 2.0f),
Mathf.Clamp(1 + (umaDna.feetSize - 0.5f) * 2.0f, 0.5f, 2.0f),
Mathf.Clamp(1 + (umaDna.feetSize - 0.5f) * 2.0f, 0.5f, 2.0f)));
skeleton.SetScale(rightFootHash,
new Vector3(
Mathf.Clamp(1 + (umaDna.feetSize - 0.5f) * 2.0f, 0.5f, 2.0f),
Mathf.Clamp(1 + (umaDna.feetSize - 0.5f) * 2.0f, 0.5f, 2.0f),
Mathf.Clamp(1 + (umaDna.feetSize - 0.5f) * 2.0f, 0.5f, 2.0f)));
skeleton.SetPositionRelative(leftUpLegHash,
new Vector3(
Mathf.Clamp(0, -10, 10),
Mathf.Clamp((umaDna.legSeparation - 0.5f) * -0.15f + (umaDna.lowerWeight - 0.5f) * -0.035f + (umaDna.legsSize - 0.5f) * 0.1f, -0.025f, 0.025f),
Mathf.Clamp(0, -10, 10)));
skeleton.SetPositionRelative(rightUpLegHash,
new Vector3(
Mathf.Clamp(0, -10, 10),
Mathf.Clamp((umaDna.legSeparation - 0.5f) * 0.15f + (umaDna.lowerWeight - 0.5f) * 0.035f + (umaDna.legsSize - 0.5f) * -0.1f, -0.025f, 0.025f),
Mathf.Clamp(0, -10, 10)));
skeleton.SetPositionRelative(leftShoulderHash,
new Vector3(
Mathf.Clamp(0, -10, 10),
Mathf.Clamp(0.003f + (umaDna.upperMuscle - 0.5f) * -0.265f, -0.085f, 0.015f),
Mathf.Clamp(0, -10, 10)));
skeleton.SetPositionRelative(rightShoulderHash,
new Vector3(
Mathf.Clamp(0, -10, 10),
Mathf.Clamp(0.003f + (umaDna.upperMuscle - 0.5f) * 0.265f, -0.015f, 0.085f),
Mathf.Clamp(0, -10, 10)));
skeleton.SetScale(mandibleHash,
new Vector3(
Mathf.Clamp(1 + (umaDna.mandibleSize - 0.5f) * 0.35f, 0.35f, 1.35f),
Mathf.Clamp(1 + (umaDna.mandibleSize - 0.5f) * 0.35f, 0.35f, 1.35f),
Mathf.Clamp(1 + (umaDna.mandibleSize - 0.5f) * 0.35f, 0.35f, 1.35f)));
umaData.characterHeight = overallScale * (0.85f + 1.2f * lowerBackScale);
umaData.characterRadius = 0.28f * overallScale;
umaData.characterMass = 46f * overallScale + 26f * umaDna.upperWeight + 26f * umaDna.lowerWeight;
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.ApiManagement
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Extension methods for EmailTemplateOperations.
/// </summary>
public static partial class EmailTemplateOperationsExtensions
{
/// <summary>
/// Lists a collection of properties defined within a service instance.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// The name of the API Management service.
/// </param>
/// <param name='top'>
/// Number of records to return.
/// </param>
/// <param name='skip'>
/// Number of records to skip.
/// </param>
public static IPage<EmailTemplateContract> ListByService(this IEmailTemplateOperations operations, string resourceGroupName, string serviceName, int? top = default(int?), int? skip = default(int?))
{
return operations.ListByServiceAsync(resourceGroupName, serviceName, top, skip).GetAwaiter().GetResult();
}
/// <summary>
/// Lists a collection of properties defined within a service instance.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// The name of the API Management service.
/// </param>
/// <param name='top'>
/// Number of records to return.
/// </param>
/// <param name='skip'>
/// Number of records to skip.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<EmailTemplateContract>> ListByServiceAsync(this IEmailTemplateOperations operations, string resourceGroupName, string serviceName, int? top = default(int?), int? skip = default(int?), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListByServiceWithHttpMessagesAsync(resourceGroupName, serviceName, top, skip, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets the details of the email template specified by its identifier.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// The name of the API Management service.
/// </param>
/// <param name='templateName'>
/// Email Template Name Identifier. Possible values include:
/// 'applicationApprovedNotificationMessage', 'accountClosedDeveloper',
/// 'quotaLimitApproachingDeveloperNotificationMessage',
/// 'newDeveloperNotificationMessage', 'emailChangeIdentityDefault',
/// 'inviteUserNotificationMessage', 'newCommentNotificationMessage',
/// 'confirmSignUpIdentityDefault', 'newIssueNotificationMessage',
/// 'purchaseDeveloperNotificationMessage', 'passwordResetIdentityDefault',
/// 'passwordResetByAdminNotificationMessage',
/// 'rejectDeveloperNotificationMessage', 'requestDeveloperNotificationMessage'
/// </param>
public static EmailTemplateContract Get(this IEmailTemplateOperations operations, string resourceGroupName, string serviceName, string templateName)
{
return operations.GetAsync(resourceGroupName, serviceName, templateName).GetAwaiter().GetResult();
}
/// <summary>
/// Gets the details of the email template specified by its identifier.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// The name of the API Management service.
/// </param>
/// <param name='templateName'>
/// Email Template Name Identifier. Possible values include:
/// 'applicationApprovedNotificationMessage', 'accountClosedDeveloper',
/// 'quotaLimitApproachingDeveloperNotificationMessage',
/// 'newDeveloperNotificationMessage', 'emailChangeIdentityDefault',
/// 'inviteUserNotificationMessage', 'newCommentNotificationMessage',
/// 'confirmSignUpIdentityDefault', 'newIssueNotificationMessage',
/// 'purchaseDeveloperNotificationMessage', 'passwordResetIdentityDefault',
/// 'passwordResetByAdminNotificationMessage',
/// 'rejectDeveloperNotificationMessage', 'requestDeveloperNotificationMessage'
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<EmailTemplateContract> GetAsync(this IEmailTemplateOperations operations, string resourceGroupName, string serviceName, string templateName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, serviceName, templateName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Updates an Email Template.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// The name of the API Management service.
/// </param>
/// <param name='templateName'>
/// Email Template Name Identifier. Possible values include:
/// 'applicationApprovedNotificationMessage', 'accountClosedDeveloper',
/// 'quotaLimitApproachingDeveloperNotificationMessage',
/// 'newDeveloperNotificationMessage', 'emailChangeIdentityDefault',
/// 'inviteUserNotificationMessage', 'newCommentNotificationMessage',
/// 'confirmSignUpIdentityDefault', 'newIssueNotificationMessage',
/// 'purchaseDeveloperNotificationMessage', 'passwordResetIdentityDefault',
/// 'passwordResetByAdminNotificationMessage',
/// 'rejectDeveloperNotificationMessage', 'requestDeveloperNotificationMessage'
/// </param>
/// <param name='parameters'>
/// Email Template update parameters.
/// </param>
public static EmailTemplateContract CreateOrUpdate(this IEmailTemplateOperations operations, string resourceGroupName, string serviceName, string templateName, EmailTemplateUpdateParameters parameters)
{
return operations.CreateOrUpdateAsync(resourceGroupName, serviceName, templateName, parameters).GetAwaiter().GetResult();
}
/// <summary>
/// Updates an Email Template.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// The name of the API Management service.
/// </param>
/// <param name='templateName'>
/// Email Template Name Identifier. Possible values include:
/// 'applicationApprovedNotificationMessage', 'accountClosedDeveloper',
/// 'quotaLimitApproachingDeveloperNotificationMessage',
/// 'newDeveloperNotificationMessage', 'emailChangeIdentityDefault',
/// 'inviteUserNotificationMessage', 'newCommentNotificationMessage',
/// 'confirmSignUpIdentityDefault', 'newIssueNotificationMessage',
/// 'purchaseDeveloperNotificationMessage', 'passwordResetIdentityDefault',
/// 'passwordResetByAdminNotificationMessage',
/// 'rejectDeveloperNotificationMessage', 'requestDeveloperNotificationMessage'
/// </param>
/// <param name='parameters'>
/// Email Template update parameters.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<EmailTemplateContract> CreateOrUpdateAsync(this IEmailTemplateOperations operations, string resourceGroupName, string serviceName, string templateName, EmailTemplateUpdateParameters parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, serviceName, templateName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Updates the specific Email Template.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// The name of the API Management service.
/// </param>
/// <param name='templateName'>
/// Email Template Name Identifier. Possible values include:
/// 'applicationApprovedNotificationMessage', 'accountClosedDeveloper',
/// 'quotaLimitApproachingDeveloperNotificationMessage',
/// 'newDeveloperNotificationMessage', 'emailChangeIdentityDefault',
/// 'inviteUserNotificationMessage', 'newCommentNotificationMessage',
/// 'confirmSignUpIdentityDefault', 'newIssueNotificationMessage',
/// 'purchaseDeveloperNotificationMessage', 'passwordResetIdentityDefault',
/// 'passwordResetByAdminNotificationMessage',
/// 'rejectDeveloperNotificationMessage', 'requestDeveloperNotificationMessage'
/// </param>
/// <param name='parameters'>
/// Update parameters.
/// </param>
public static void Update(this IEmailTemplateOperations operations, string resourceGroupName, string serviceName, string templateName, EmailTemplateUpdateParameters parameters)
{
operations.UpdateAsync(resourceGroupName, serviceName, templateName, parameters).GetAwaiter().GetResult();
}
/// <summary>
/// Updates the specific Email Template.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// The name of the API Management service.
/// </param>
/// <param name='templateName'>
/// Email Template Name Identifier. Possible values include:
/// 'applicationApprovedNotificationMessage', 'accountClosedDeveloper',
/// 'quotaLimitApproachingDeveloperNotificationMessage',
/// 'newDeveloperNotificationMessage', 'emailChangeIdentityDefault',
/// 'inviteUserNotificationMessage', 'newCommentNotificationMessage',
/// 'confirmSignUpIdentityDefault', 'newIssueNotificationMessage',
/// 'purchaseDeveloperNotificationMessage', 'passwordResetIdentityDefault',
/// 'passwordResetByAdminNotificationMessage',
/// 'rejectDeveloperNotificationMessage', 'requestDeveloperNotificationMessage'
/// </param>
/// <param name='parameters'>
/// Update parameters.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task UpdateAsync(this IEmailTemplateOperations operations, string resourceGroupName, string serviceName, string templateName, EmailTemplateUpdateParameters parameters, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.UpdateWithHttpMessagesAsync(resourceGroupName, serviceName, templateName, parameters, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Reset the Email Template to default template provided by the API Management
/// service instance.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// The name of the API Management service.
/// </param>
/// <param name='templateName'>
/// Email Template Name Identifier. Possible values include:
/// 'applicationApprovedNotificationMessage', 'accountClosedDeveloper',
/// 'quotaLimitApproachingDeveloperNotificationMessage',
/// 'newDeveloperNotificationMessage', 'emailChangeIdentityDefault',
/// 'inviteUserNotificationMessage', 'newCommentNotificationMessage',
/// 'confirmSignUpIdentityDefault', 'newIssueNotificationMessage',
/// 'purchaseDeveloperNotificationMessage', 'passwordResetIdentityDefault',
/// 'passwordResetByAdminNotificationMessage',
/// 'rejectDeveloperNotificationMessage', 'requestDeveloperNotificationMessage'
/// </param>
/// <param name='ifMatch'>
/// The entity state (Etag) version of the Email Template to delete. A value of
/// "*" can be used for If-Match to unconditionally apply the operation.
/// </param>
public static void Delete(this IEmailTemplateOperations operations, string resourceGroupName, string serviceName, string templateName, string ifMatch)
{
operations.DeleteAsync(resourceGroupName, serviceName, templateName, ifMatch).GetAwaiter().GetResult();
}
/// <summary>
/// Reset the Email Template to default template provided by the API Management
/// service instance.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// The name of the API Management service.
/// </param>
/// <param name='templateName'>
/// Email Template Name Identifier. Possible values include:
/// 'applicationApprovedNotificationMessage', 'accountClosedDeveloper',
/// 'quotaLimitApproachingDeveloperNotificationMessage',
/// 'newDeveloperNotificationMessage', 'emailChangeIdentityDefault',
/// 'inviteUserNotificationMessage', 'newCommentNotificationMessage',
/// 'confirmSignUpIdentityDefault', 'newIssueNotificationMessage',
/// 'purchaseDeveloperNotificationMessage', 'passwordResetIdentityDefault',
/// 'passwordResetByAdminNotificationMessage',
/// 'rejectDeveloperNotificationMessage', 'requestDeveloperNotificationMessage'
/// </param>
/// <param name='ifMatch'>
/// The entity state (Etag) version of the Email Template to delete. A value of
/// "*" can be used for If-Match to unconditionally apply the operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeleteAsync(this IEmailTemplateOperations operations, string resourceGroupName, string serviceName, string templateName, string ifMatch, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.DeleteWithHttpMessagesAsync(resourceGroupName, serviceName, templateName, ifMatch, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Lists a collection of properties defined within a service instance.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<EmailTemplateContract> ListByServiceNext(this IEmailTemplateOperations operations, string nextPageLink)
{
return operations.ListByServiceNextAsync(nextPageLink).GetAwaiter().GetResult();
}
/// <summary>
/// Lists a collection of properties defined within a service instance.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<EmailTemplateContract>> ListByServiceNextAsync(this IEmailTemplateOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListByServiceNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.IO;
using System.Linq;
using System.Globalization;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Runtime.InteropServices;
using System.Text;
using System.Security.Cryptography.Pkcs;
using System.Security.Cryptography.Xml;
using System.Security.Cryptography.X509Certificates;
using Xunit;
using Test.Cryptography;
using System.Security.Cryptography.Pkcs.Tests;
namespace System.Security.Cryptography.Pkcs.EnvelopedCmsTests.Tests
{
public static partial class UnprotectedAttributeTests
{
[Fact]
public static void TestUnprotectedAttributes0_RoundTrip()
{
byte[] encodedMessage = CreateEcmsWithAttributes();
VerifyUnprotectedAttributes0(encodedMessage);
}
[Fact]
public static void TestUnprotectedAttributes0_FixedValue()
{
byte[] encodedMessage =
("3082010c06092a864886f70d010703a081fe3081fb0201003181c83081c5020100302e301a311830160603550403130f5253"
+ "414b65795472616e7366657231021031d935fb63e8cfab48a0bf7b397b67c0300d06092a864886f70d010101050004818048"
+ "fea7a626159f3792b8daa8e064de2f986cf0e432428c6cb80ed4bf6e593db74a7f907e0918b4bee6d55e1e0f9da6b6519e42"
+ "23d58b0f717165a727d7dac87556916c800e2346beac5a825c973e9bba4fe6c549baafd151d85fd7c266769dbb57f28e45f8"
+ "6bb5478d018e132cb576079d8c2a7f4217973c3ff1f0617364809c302b06092a864886f70d010701301406082a864886f70d"
+ "030704083979569d26db4c278008d2fa4271358f9a2f").HexToByteArray();
VerifyUnprotectedAttributes0(encodedMessage);
}
private static void VerifyUnprotectedAttributes0(byte[] encodedMessage)
{
EnvelopedCms ecms = new EnvelopedCms();
ecms.Decode(encodedMessage);
AsnEncodedData[] attributes = ecms.UnprotectedAttributes.FlattenAndSort();
Assert.Equal(0, attributes.Length);
}
[Fact]
public static void TestUnprotectedAttributes1_DocumentDescription_RoundTrip()
{
byte[] encodedMessage = CreateEcmsWithAttributes(new Pkcs9DocumentDescription("My Description"));
VerifyUnprotectedAttributes1_DocumentDescription(encodedMessage);
}
[Fact]
public static void TestUnprotectedAttributes1_DocumentDescription_FixedValue()
{
byte[] encodedMessage =
("3082014006092a864886f70d010703a08201313082012d0201023181c83081c5020100302e301a311830160603550403130f"
+ "5253414b65795472616e7366657231021031d935fb63e8cfab48a0bf7b397b67c0300d06092a864886f70d01010105000481"
+ "801dba607648ab56b88dffb4bfe36170d698910562cef64dc2f3098ca2d7fa97334e721b6d00250470f8a16b5d2f5f38cc84"
+ "c05d49e5aa7390ed4e0d6a7369f72f8bb0209545b6b8d3302c2c3fc8c8e7f5a54dd30b20855a77b5cd40c6f2b59376252aef"
+ "e1d90965916e25c63f509e32f86a9213b740796927bbb0573b024b7ba3302b06092a864886f70d010701301406082a864886"
+ "f70d03070408df8ced363e2a76288008262ce8fe027530a3a130302e060a2b0601040182375802023120041e4d0079002000"
+ "4400650073006300720069007000740069006f006e000000").HexToByteArray();
VerifyUnprotectedAttributes1_DocumentDescription(encodedMessage);
}
private static void VerifyUnprotectedAttributes1_DocumentDescription(byte[] encodedMessage)
{
EnvelopedCms ecms = new EnvelopedCms();
ecms.Decode(encodedMessage);
AsnEncodedData[] attributes = ecms.UnprotectedAttributes.FlattenAndSort();
Assert.Equal(1, attributes.Length);
attributes[0].AssertIsDocumentationDescription("My Description");
}
[Fact]
public static void TestUnprotectedAttributes1_DocumenName_RoundTrip()
{
byte[] encodedMessage = CreateEcmsWithAttributes(new Pkcs9DocumentName("My Name"));
VerifyUnprotectedAttributes1_DocumentName(encodedMessage);
}
[Fact]
public static void TestUnprotectedAttributes1_DocumentName_FixedValue()
{
byte[] encodedMessage =
("3082013206092a864886f70d010703a08201233082011f0201023181c83081c5020100302e301a311830160603550403130f"
+ "5253414b65795472616e7366657231021031d935fb63e8cfab48a0bf7b397b67c0300d06092a864886f70d01010105000481"
+ "8000d17895fe3d35a30f0666e4064cc40757251404f785c4878ab98d1440d7f1706991cf854b2498bca8781c7728805b03e8"
+ "d36329f34d7508bf38e4e4d5447e8c7d6d1c652f0a40bb3fc396e1139094d6349e08a7d233b9323c4760a96199660c87c7f0"
+ "2c891711efcee6085f07fa0060da6f9b22d895b312caed824916b14314302b06092a864886f70d010701301406082a864886"
+ "f70d03070408817ee1c4bb617f828008de69d9d27afef823a1223020060a2b060104018237580201311204104d0079002000"
+ "4e0061006d0065000000").HexToByteArray();
VerifyUnprotectedAttributes1_DocumentName(encodedMessage);
}
private static void VerifyUnprotectedAttributes1_DocumentName(byte[] encodedMessage)
{
EnvelopedCms ecms = new EnvelopedCms();
ecms.Decode(encodedMessage);
AsnEncodedData[] attributes = ecms.UnprotectedAttributes.FlattenAndSort();
Assert.Equal(1, attributes.Length);
attributes[0].AssertIsDocumentationName("My Name");
}
[Fact]
public static void TestUnprotectedAttributes1_SigningTime_RoundTrip()
{
byte[] encodedMessage = CreateEcmsWithAttributes(new Pkcs9SigningTime(new DateTime(2018, 4, 1, 8, 30, 05)));
VerifyUnprotectedAttributes1_SigningTime(encodedMessage);
}
[Fact]
public static void TestUnprotectedAttributes1_SigningTime_FixedValue()
{
byte[] encodedMessage =
("3082012e06092a864886f70d010703a082011f3082011b0201023181c83081c5020100302e301a311830160603550403130f"
+ "5253414b65795472616e7366657231021031d935fb63e8cfab48a0bf7b397b67c0300d06092a864886f70d01010105000481"
+ "801cf4efe18f457c32753fd3c908372ac8075cd4c4bdec98a912cc241b604b7ba46f44c657c769e84998384c28ee9a670d7d"
+ "8d7427f5a3bffb2a6e09269f1c89a7b1906eb0a828487d6e4fcb2c6e9023f3d9f8114701cf01c2fcb4db0c9ab7144c8e2b73"
+ "6551ca1a348ac3c25cca9de1bdef79c0bdd2ba8b79e6e668f947cf1bc7302b06092a864886f70d010701301406082a864886"
+ "f70d03070408e7575fbec5da862080084306defef088dd0ea11e301c06092a864886f70d010905310f170d31383034303130"
+ "38333030355a").HexToByteArray();
VerifyUnprotectedAttributes1_SigningTime(encodedMessage);
}
private static void VerifyUnprotectedAttributes1_SigningTime(byte[] encodedMessage)
{
EnvelopedCms ecms = new EnvelopedCms();
ecms.Decode(encodedMessage);
AsnEncodedData[] attributes = ecms.UnprotectedAttributes.FlattenAndSort();
Assert.Equal(1, attributes.Length);
DateTime expectedSigningTIme = new DateTime(2018, 4, 1, 8, 30, 05);
attributes[0].AssertIsSigningTime(expectedSigningTIme);
}
[Fact]
public static void TestUnprotectedAttributes1_ContentType_RoundTrip()
{
byte[] rawData = "06072a9fa20082f300".HexToByteArray();
Pkcs9AttributeObject pkcs9ContentType = new Pkcs9AttributeObject(Oids.ContentType, rawData);
byte[] encodedMessage = CreateEcmsWithAttributes(pkcs9ContentType);
VerifyUnprotectedAttributes1_ContentType(encodedMessage);
}
[Fact]
public static void TestUnprotectedAttributes1_ContentType_FixedValue()
{
byte[] encodedMessage =
("3082012806092a864886f70d010703a0820119308201150201023181c83081c5020100302e301a311830160603550403130f"
+ "5253414b65795472616e7366657231021031d935fb63e8cfab48a0bf7b397b67c0300d06092a864886f70d01010105000481"
+ "804abd2e5b20b7d255234ffa6b025a9c6a35362ac4affc4d78ed02a647ac9d9cb8d02bf64f924f19c731fc6e7f333180c6f1"
+ "0be40c382b5da5db96b0303819573dc3598aa978704ee96a98113ec110d48aef57c745ee0188feceac27a3739663bb52fccc"
+ "37e106ed3d8ecf3806bcc4df83ce989080405e3e856e725a85aa205bda302b06092a864886f70d010701301406082a864886"
+ "f70d030704084a0375f470805f908008522c8448feaf357da118301606092a864886f70d010903310906072a9fa20082f300").HexToByteArray();
VerifyUnprotectedAttributes1_ContentType(encodedMessage);
}
private static void VerifyUnprotectedAttributes1_ContentType(byte[] encodedMessage)
{
EnvelopedCms ecms = new EnvelopedCms();
ecms.Decode(encodedMessage);
AsnEncodedData[] attributes = ecms.UnprotectedAttributes.FlattenAndSort();
Assert.Equal(1, attributes.Length);
attributes[0].AssertIsContentType("1.2.512256.47488");
}
[Fact]
public static void TestUnprotectedAttributes1_MessageDigest_RoundTrip()
{
byte[] rawData = "0405032d58805d".HexToByteArray();
Pkcs9AttributeObject pkcs9MessageDigest = new Pkcs9AttributeObject(Oids.MessageDigest, rawData);
byte[] encodedMessage = CreateEcmsWithAttributes(pkcs9MessageDigest);
VerifyUnprotectedAttributes1_MessageDigest(encodedMessage);
}
[Fact]
public static void TestUnprotectedAttributes1_MessageDigest_FixedValue()
{
byte[] encodedMessage =
("3082012606092a864886f70d010703a0820117308201130201023181c83081c5020100302e301a311830160603550403130f"
+ "5253414b65795472616e7366657231021031d935fb63e8cfab48a0bf7b397b67c0300d06092a864886f70d01010105000481"
+ "802ed2085366bf01caca75c260d900c12ef3377f868d879c7b33734dd912aeffcb55f8f8fefea550bd75472ad20f56dd6edf"
+ "d1c9669f3653e41d48f03c0796513da5b922587415853fc46ef5f452cea25a58c6da296527c51111a2fa6e472651391e2c3a"
+ "ffb081ce6f7e4aee275d0f3d3e351b5e76c84afb5f80bb1ef594eb9b92302b06092a864886f70d010701301406082a864886"
+ "f70d030704088b5d38dad37f599280081d626f58eabeeb0aa116301406092a864886f70d01090431070405032d58805d").HexToByteArray();
VerifyUnprotectedAttributes1_MessageDigest(encodedMessage);
}
private static void VerifyUnprotectedAttributes1_MessageDigest(byte[] encodedMessage)
{
byte[] expectedMessageDigest = "032d58805d".HexToByteArray();
EnvelopedCms ecms = new EnvelopedCms();
ecms.Decode(encodedMessage);
AsnEncodedData[] attributes = ecms.UnprotectedAttributes.FlattenAndSort();
Assert.Equal(1, attributes.Length);
attributes[0].AssertIsMessageDigest(expectedMessageDigest);
}
[Fact]
public static void TestUnprotectedAttributes1_Merge3_RoundTrip()
{
byte[] encodedMessage = CreateEcmsWithAttributes(
new Pkcs9DocumentDescription("My Description 1"),
new Pkcs9DocumentDescription("My Description 2"),
new Pkcs9DocumentDescription("My Description 3")
);
VerifyUnprotectedAttributes_Merge3(encodedMessage);
}
[Fact]
public static void TestUnprotectedAttributes1_Merge3_FixedValue()
{
byte[] encodedMessage =
("3082018c06092a864886f70d010703a082017d308201790201023181c83081c5020100302e301a311830160603550403130f"
+ "5253414b65795472616e7366657231021031d935fb63e8cfab48a0bf7b397b67c0300d06092a864886f70d01010105000481"
+ "809203ec6ad0877ae56dbc8a480e59e94ca953839f8f769ec1b262b4f4916c9863ee9c41007c356fbf2fc3f3d03e4aa1ea46"
+ "575d0fbc0c5f47e41778f34535eea84e648009955f271a9e3c24f8c192d31406d46a40396b78d4013cfe3dcc443ac9ca9213"
+ "7ffa503297ca1d241f68e905c60134c02e7ce8e1e67481abebe3d7faa1302b06092a864886f70d010701301406082a864886"
+ "f70d030704085e2e9ca7859583a08008fb219dbb2a84a2eda17c307a060a2b060104018237580202316c04224d0079002000"
+ "4400650073006300720069007000740069006f006e0020003100000004224d00790020004400650073006300720069007000"
+ "740069006f006e0020003200000004224d00790020004400650073006300720069007000740069006f006e00200033000000").HexToByteArray();
VerifyUnprotectedAttributes_Merge3(encodedMessage);
}
private static void VerifyUnprotectedAttributes_Merge3(byte[] encodedMessage)
{
EnvelopedCms ecms = new EnvelopedCms();
ecms.Decode(encodedMessage);
AsnEncodedData[] attributes = ecms.UnprotectedAttributes.FlattenAndSort();
Assert.Equal(3, attributes.Length);
attributes[0].AssertIsDocumentationDescription("My Description 1");
attributes[1].AssertIsDocumentationDescription("My Description 2");
attributes[2].AssertIsDocumentationDescription("My Description 3");
}
[Fact]
public static void TestUnprotectedAttributes1_Heterogenous3_RoundTrip()
{
byte[] encodedMessage = CreateEcmsWithAttributes(
new Pkcs9DocumentDescription("My Description 1"),
new Pkcs9DocumentDescription("My Description 2"),
new Pkcs9DocumentName("My Name 1")
);
VerifyUnprotectedAttributes_Heterogenous3(encodedMessage);
}
private static void VerifyUnprotectedAttributes_Heterogenous3(byte[] encodedMessage)
{
EnvelopedCms ecms = new EnvelopedCms();
ecms.Decode(encodedMessage);
AsnEncodedData[] attributes = ecms.UnprotectedAttributes.FlattenAndSort();
Assert.Equal(3, attributes.Length);
attributes[0].AssertIsDocumentationName("My Name 1");
attributes[1].AssertIsDocumentationDescription("My Description 1");
attributes[2].AssertIsDocumentationDescription("My Description 2");
}
[Fact]
public static void TestUnprotectedAttributes1_EmptySet()
{
// This tests the behavior of unprotected attribute extraction when one of the attribute sequences declares an
// attribute type, but the contained SET OF AttributeValue is empty.
//
// Attribute ::= SEQUENCE {
// attrType OBJECT IDENTIFIER,
// attrValues SET OF AttributeValue }
//
// The encoded message was built in ASN.1 editor and tested in framework.It contains an enveloped message
// version 2 with a key transport recipient, the enveloped message contains data encrypted with 3DES.
//
// The attributes set is built as
// {
// { attrType: document description, attrValues: { value1, value2 } },
// { attrType: document name, attrValues: { } },
// }
//
// The important part of this test is that there are 0 attributes of a type that is declared within the encoded message.
// This should return 2 as it should create a CryptographicAttributeObjectCollection with two CryptographicAttributeObjects,
// the first one holding a list of document description with the two values, the second one holding an empty list of
// document name.
byte[] encodedMessage =
("3082017806092A864886F70D010703A0820169308201650201023181C83081C5020100302E301A311830160603550403"
+ "130F5253414B65795472616E7366657231021031D935FB63E8CFAB48A0BF7B397B67C0300D06092A864886F70D010101"
+ "05000481802EE6A4AAA9F907E8EF472D8CD8603098488EC1C462815E6FC5A53A3DF6EB730F3D191746FDBBCA89114C6D"
+ "45FB6C4F26088043894D5A706889A29D52E03ABEDFAC98336BD01B0A9CFA57CC6C80908F4B42EFCE5E60E7A761451A4D"
+ "1A39783072000E551062027795A1CEB079791BA48C5F77D360EE48E185DE6C8CCB1C093D4B302B06092A864886F70D01"
+ "0701301406082A864886F70D03070408F55F613664678EE9800800BC3504D1F59470A168300E060A2B06010401823758"
+ "020131003056060A2B060104018237580202314804224D00790020004400650073006300720069007000740069006F00"
+ "6E0020003100000004224D00790020004400650073006300720069007000740069006F006E00200032000000").HexToByteArray();
EnvelopedCms ecms = new EnvelopedCms();
ecms.Decode(encodedMessage);
Assert.Equal(2, ecms.UnprotectedAttributes.Count);
CryptographicAttributeObjectCollection collection = ecms.UnprotectedAttributes;
string attrObj0Oid = collection[0].Oid.Value;
CryptographicAttributeObject documentDescObj = (attrObj0Oid == Oids.DocumentDescription) ?
collection[0] :
collection[1];
CryptographicAttributeObject documentNameObj = (attrObj0Oid == Oids.DocumentName) ?
collection[0] :
collection[1];
Assert.Equal(0, documentNameObj.Values.Count);
Assert.Equal(2, documentDescObj.Values.Count);
}
[Fact]
public static void TestUnprotectedAttributes1_Arbitrary_RoundTrip()
{
byte[] encodedMessage = CreateEcmsWithAttributes(
new AsnEncodedData(new Oid(Oids.Pkcs7Data), new byte[] { 4, 3, 6, 7, 8 })
);
VerifyUnprotectedAttributes_Arbitrary1(encodedMessage);
}
[Fact]
public static void TestUnprotectedAttributes1_Arbitrary_FixedValue()
{
byte[] encodedMessage =
("3082012406092a864886f70d010703a0820115308201110201023181c83081c5020100302e301a311830160603550403130f"
+ "5253414b65795472616e7366657231021031d935fb63e8cfab48a0bf7b397b67c0300d06092a864886f70d01010105000481"
+ "800f310e1c63177fd87bbacd13de65aae943fff87a1da112b9d1a2578c444ebfeb5d72db13104e1f72231651f1a46dec72c1"
+ "91ae859e2cd96df3f94599fff2fdc9074ea9722739c9b0ac870acd073c11375d79ab7679b0d2ebab839f0c2ee975d7ef4a59"
+ "5933aebfcae745f98109c0e5cfd298960cebd244d6a029d9f21bfe60fb302b06092a864886f70d010701301406082a864886"
+ "f70d03070408aa76edcbc0a03d7d8008aefe2086db6f8f7ca114301206092a864886f70d01070131050403060708").HexToByteArray();
VerifyUnprotectedAttributes_Arbitrary1(encodedMessage);
}
private static void VerifyUnprotectedAttributes_Arbitrary1(byte[] encodedMessage)
{
EnvelopedCms ecms = new EnvelopedCms();
ecms.Decode(encodedMessage);
AsnEncodedData[] attributes = ecms.UnprotectedAttributes.FlattenAndSort();
Assert.Equal(1, attributes.Length);
AsnEncodedData a = attributes[0];
Assert.Equal(Oids.Pkcs7Data, a.Oid.Value);
byte[] expectedRawData = { 4, 3, 6, 7, 8 };
Assert.Equal<byte>(expectedRawData, a.RawData);
}
[Fact]
public static void TestUnprotectedAttributes1_OutOfNamespace_RoundTrip()
{
byte[] constraintsRawData = "30070101ff02020100".HexToByteArray();
byte[] encodedMessage = CreateEcmsWithAttributes(
new AsnEncodedData(Oids.BasicConstraints2, constraintsRawData)
);
VerifyUnprotectedAttributes1_OutOfNamespace(encodedMessage);
}
[Fact]
public static void TestUnprotectedAttributes1_OutOfNamespace_FixedValue()
{
byte[] encodedMessage =
("3082012206092a864886f70d010703a08201133082010f0201023181c83081c5020100302e301a311830160603550403130f"
+ "5253414b65795472616e7366657231021031d935fb63e8cfab48a0bf7b397b67c0300d06092a864886f70d01010105000481"
+ "801dd92ffa848bc03011c8aae71d63c9a81fdbb2e2c82c284bcbe40d77c3f67beb8cdd2c017470a48189e8ccd3d310bde567"
+ "202e3a03cb9866d19262bda6a489c957e14b1068ecfb2ae8ea1cbf47c6a934a5eed8ce05965356e033f2a1c68001cd308604"
+ "50f28b7949af886727fb506d64ae7889f613c03729a7b834591881666c302b06092a864886f70d010701301406082a864886"
+ "f70d0307040814a020bca56417de8008a260d0e4e138743ea11230100603551d13310930070101ff02020100").HexToByteArray();
VerifyUnprotectedAttributes1_OutOfNamespace(encodedMessage);
}
private static void VerifyUnprotectedAttributes1_OutOfNamespace(byte[] encodedMessage)
{
byte[] constraintsRawData = "30070101ff02020100".HexToByteArray();
EnvelopedCms ecms = new EnvelopedCms();
ecms.Decode(encodedMessage);
AsnEncodedData[] attributes = ecms.UnprotectedAttributes.FlattenAndSort();
Assert.Equal(1, attributes.Length);
AsnEncodedData a = attributes[0];
Assert.Equal(Oids.BasicConstraints2, a.Oid.Value);
Assert.Equal<byte>(constraintsRawData, a.RawData);
}
[Fact]
public static void TestUnprotectedAttributes_AlwaysReturnsPkcs9AttributeObject()
{
byte[] encodedMessage = CreateEcmsWithAttributes(
new AsnEncodedData(new Oid(Oids.Pkcs7Data), new byte[] { 4, 3, 6, 7, 8 })
);
// ecms.Decode() always populates UnprotectedAttribute objects with Pkcs9AttributeObjects (or one of its derived classes) rather than
// AsnEncodedData instances. Verify that any new implementation does this as someone out there is probably
// casting to Pkcs9AttributeObject without checking.
EnvelopedCms ecms = new EnvelopedCms();
ecms.Decode(encodedMessage);
AsnEncodedData[] attributes = ecms.UnprotectedAttributes.FlattenAndSort();
Assert.Equal(1, attributes.Length);
AsnEncodedData a = attributes[0];
Assert.True(a is Pkcs9AttributeObject);
}
private static void AssertIsDocumentationDescription(this AsnEncodedData attribute, string expectedDocumentDescription)
{
Assert.Equal(Oids.DocumentDescription, attribute.Oid.Value);
Pkcs9DocumentDescription enhancedAttribute = attribute as Pkcs9DocumentDescription;
Assert.NotNull(enhancedAttribute);
Assert.Equal(expectedDocumentDescription, enhancedAttribute.DocumentDescription);
}
private static void AssertIsDocumentationName(this AsnEncodedData attribute, string expectedDocumentName)
{
Assert.Equal(Oids.DocumentName, attribute.Oid.Value);
Pkcs9DocumentName enhancedAttribute = attribute as Pkcs9DocumentName;
Assert.NotNull(enhancedAttribute);
Assert.Equal(expectedDocumentName, enhancedAttribute.DocumentName);
}
private static void AssertIsSigningTime(this AsnEncodedData attribute, DateTime expectedTime)
{
Assert.Equal(Oids.SigningTime, attribute.Oid.Value);
Pkcs9SigningTime enhancedAttribute = attribute as Pkcs9SigningTime;
Assert.NotNull(enhancedAttribute);
Assert.Equal(expectedTime, enhancedAttribute.SigningTime);
}
private static void AssertIsContentType(this AsnEncodedData attribute, string expectedContentType)
{
Assert.Equal(Oids.ContentType, attribute.Oid.Value);
Pkcs9ContentType enhancedAttribute = attribute as Pkcs9ContentType;
Assert.NotNull(enhancedAttribute);
Assert.Equal(expectedContentType, enhancedAttribute.ContentType.Value);
}
private static void AssertIsMessageDigest(this AsnEncodedData attribute, byte[] expectedDigest)
{
Assert.Equal(Oids.MessageDigest, attribute.Oid.Value);
Pkcs9MessageDigest enhancedAttribute = attribute as Pkcs9MessageDigest;
Assert.NotNull(enhancedAttribute);
Assert.Equal<byte>(expectedDigest, enhancedAttribute.MessageDigest);
}
private static byte[] CreateEcmsWithAttributes(params AsnEncodedData[] attributes)
{
ContentInfo contentInfo = new ContentInfo(new byte[] { 1, 2, 3 });
EnvelopedCms ecms = new EnvelopedCms(contentInfo);
foreach (AsnEncodedData attribute in attributes)
{
ecms.UnprotectedAttributes.Add(attribute);
}
using (X509Certificate2 cert = Certificates.RSAKeyTransfer1.GetCertificate())
{
CmsRecipient cmsRecipient = new CmsRecipient(cert);
ecms.Encrypt(cmsRecipient);
}
byte[] encodedMessage = ecms.Encode();
return encodedMessage;
}
private static AsnEncodedData[] FlattenAndSort(this CryptographicAttributeObjectCollection col)
{
List<AsnEncodedData> attributes = new List<AsnEncodedData>();
foreach (CryptographicAttributeObject cao in col)
{
AsnEncodedDataCollection acol = cao.Values;
foreach (AsnEncodedData a in acol)
{
attributes.Add(a);
}
}
return attributes.OrderBy(a => a.RawData.ByteArrayToHex()).ToArray();
}
}
}
| |
// Python Tools for Visual Studio
// Copyright(c) Microsoft Corporation
// 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
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABILITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
extern alias analysis;
extern alias pythontools;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using pythontools::Microsoft.PythonTools;
using pythontools::Microsoft.PythonTools.Editor;
using Microsoft.PythonTools.Infrastructure;
using pythontools::Microsoft.PythonTools.Intellisense;
using analysis::Microsoft.PythonTools.Interpreter;
using pythontools::Microsoft.PythonTools.Options;
using analysis::Microsoft.PythonTools.Parsing;
using Microsoft.VisualStudio.Language.Intellisense;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudioTools.MockVsTests;
using TestUtilities;
namespace PythonToolsMockTests {
sealed class PythonEditor : IDisposable {
private readonly bool _disposeVS, _disposeFactory, _disposeAnalyzer;
public readonly MockVs VS;
public readonly IPythonInterpreterFactory Factory;
public readonly VsProjectAnalyzer Analyzer;
public readonly MockVsTextView View;
public readonly AdvancedEditorOptions AdvancedOptions;
public PythonEditor(
string content = null,
PythonLanguageVersion version = PythonLanguageVersion.V27,
MockVs vs = null,
IPythonInterpreterFactory factory = null,
VsProjectAnalyzer analyzer = null,
string filename = null,
bool? inProcAnalyzer = null
) {
if (vs == null) {
_disposeVS = true;
vs = new MockVs();
}
MockVsTextView view = null;
try {
AdvancedEditorOptions advancedOptions = null;
vs.InvokeSync(() => {
advancedOptions = vs.GetPyService().AdvancedOptions;
advancedOptions.AutoListMembers = true;
advancedOptions.AutoListIdentifiers = false;
});
AdvancedOptions = advancedOptions;
if (factory == null) {
vs.InvokeSync(() => {
factory = vs.ComponentModel.GetService<IInterpreterRegistryService>()
.Interpreters
.FirstOrDefault(c => c.GetLanguageVersion() == version && c.Configuration.Id.StartsWith("Global|PythonCore"));
if (factory != null) {
Console.WriteLine($"Using interpreter {factory.Configuration.InterpreterPath}");
}
});
if (factory == null) {
_disposeFactory = true;
factory = InterpreterFactoryCreator.CreateAnalysisInterpreterFactory(version.ToVersion());
Console.WriteLine("Using analysis-only interpreter");
}
}
if (analyzer == null) {
_disposeAnalyzer = true;
analyzer = vs.InvokeTask(() => VsProjectAnalyzer.CreateForTestsAsync(vs.ComponentModel.GetService<PythonEditorServices>(), factory, inProcAnalyzer ?? Debugger.IsAttached), 10000);
}
Uri uri;
if (string.IsNullOrEmpty(filename)) {
filename = Path.ChangeExtension(Path.GetRandomFileName(), ".py");
}
if (Path.IsPathRooted(filename)) {
uri = new Uri(filename);
} else {
var d = Path.GetRandomFileName();
uri = new Uri($"python://test/{d}/{filename}");
filename = $"_:\\PYTHON\\{d}\\{filename}";
}
var cancel = CancellationTokens.After60s;
view = vs.CreateTextView(PythonCoreConstants.ContentType, content ?? "",
v => {
v.TextView.TextBuffer.Properties[BufferParser.ParseImmediately] = true;
v.TextView.TextBuffer.Properties[IntellisenseController.SuppressErrorLists] = IntellisenseController.SuppressErrorLists;
v.TextView.TextBuffer.Properties[VsProjectAnalyzer._testAnalyzer] = analyzer;
v.TextView.TextBuffer.Properties[VsProjectAnalyzer._testFilename] = filename;
v.TextView.TextBuffer.Properties[VsProjectAnalyzer._testDocumentUri] = uri;
},
filename);
var services = vs.ComponentModel.GetService<PythonEditorServices>();
var bi = services.GetBufferInfo(view.TextView.TextBuffer);
var entry = bi.GetAnalysisEntryAsync(cancel).WaitAndUnwrapExceptions();
Assert.IsNotNull(entry, "failed to get analysis entry");
if (!string.IsNullOrEmpty(content) && !cancel.IsCancellationRequested && !entry.IsAnalyzed) {
var task = entry.Analyzer.WaitForNextCompleteAnalysis();
var bp = entry.TryGetBufferParser();
while (bp == null) {
Thread.Sleep(50);
cancel.ThrowIfCancellationRequested();
bp = entry.TryGetBufferParser();
}
try {
bp.EnsureCodeSyncedAsync(bi.Buffer, true).Wait(cancel);
task.Wait(cancel);
} catch (AggregateException ex) when (ex.InnerException != null) {
throw ex.InnerException;
} catch (OperationCanceledException) {
}
}
if (cancel.IsCancellationRequested) {
Assert.Fail("Timed out waiting for code analysis");
}
vs.ThrowPendingException();
View = view;
view = null;
Analyzer = analyzer;
analyzer = null;
Factory = factory;
factory = null;
VS = vs;
vs = null;
} finally {
if (view != null) {
view.Dispose();
}
if (analyzer != null && _disposeAnalyzer) {
analyzer.Dispose();
}
if (factory != null && _disposeFactory) {
var disp = factory as IDisposable;
if (disp != null) {
disp.Dispose();
}
}
if (vs != null && _disposeVS) {
vs.Dispose();
}
}
}
public string Text {
get { return View.Text; }
set {
var buffer = View.TextView.TextBuffer;
var bi = PythonTextBufferInfo.TryGetForBuffer(buffer);
if (bi?.AnalysisEntry == null) {
// No analysis yet, so just set the text.
using (var edit = View.TextView.TextBuffer.CreateEdit()) {
edit.Delete(0, edit.Snapshot.Length);
edit.Insert(0, value);
edit.Apply();
}
return;
}
var t = Analyzer.WaitForNextCompleteAnalysis();
using (var edit = buffer.CreateEdit()) {
edit.Replace(0, edit.Snapshot.Length, value);
edit.Apply();
}
t.Wait(CancellationTokens.After60s);
if (string.IsNullOrEmpty(value)) {
return;
}
}
}
public ITextSnapshot CurrentSnapshot {
get { return View.TextView.TextSnapshot; }
}
public WaitHandle AnalysisCompleteEvent {
get {
var evt = new AnalysisCompleteManualResetEvent(BufferInfo);
BufferInfo.AddSink(evt, evt);
return evt;
}
}
class AnalysisCompleteManualResetEvent : WaitHandle, IPythonTextBufferInfoEventSink {
private readonly ManualResetEvent _event;
private readonly PythonTextBufferInfo _info;
public AnalysisCompleteManualResetEvent(PythonTextBufferInfo info) {
_event = new ManualResetEvent(false);
_info = info;
SafeWaitHandle = _event.SafeWaitHandle;
}
protected override void Dispose(bool explicitDisposing) {
SafeWaitHandle = null;
base.Dispose(explicitDisposing);
_event.Dispose();
if (explicitDisposing) {
_info.RemoveSink(this);
}
}
public async Task PythonTextBufferEventAsync(PythonTextBufferInfo sender, PythonTextBufferInfoEventArgs e) {
if (e.Event == PythonTextBufferInfoEvents.NewAnalysis) {
var snapshot = _info.LastAnalysisSnapshot;
for (int retries = 100; retries > 0 && (snapshot = _info.LastAnalysisSnapshot) == null; --retries) {
await Task.Delay(100);
}
if (snapshot == null) {
throw new NullReferenceException("LastAnalysisSnapshot was not set");
}
if (snapshot.Version.VersionNumber >= _info.Buffer.CurrentSnapshot.Version.VersionNumber) {
try {
_event.Set();
} catch (ObjectDisposedException) {
}
_info.RemoveSink(this);
}
}
}
}
internal PythonEditorServices EditorServices => VS.ComponentModel.GetService<PythonEditorServices>();
internal PythonTextBufferInfo BufferInfo => EditorServices.GetBufferInfo(View.TextView.TextBuffer);
public List<Completion> GetCompletionListAfter(string substring, bool assertIfNoCompletions = true) {
var snapshot = CurrentSnapshot;
return GetCompletionList(snapshot.GetText().IndexOfEnd(substring), assertIfNoCompletions, snapshot);
}
public List<Completion> GetCompletionList(
int index,
bool assertIfNoCompletions = true,
ITextSnapshot snapshot = null
) {
for (int retries = 5; retries > 0; --retries) {
var completions = GetCompletionListNoRetry(index, false, snapshot);
if (completions.Any()) {
return completions;
}
}
if (assertIfNoCompletions) {
Assert.Fail("No completions");
}
return new List<Completion>();
}
public List<Completion> GetCompletionListNoRetry(
int index,
bool assertIfNoCompletions = true,
ITextSnapshot snapshot = null
) {
VS.Invoke(() => {
snapshot = snapshot ?? CurrentSnapshot;
if (index < 0) {
index += snapshot.Length + 1;
}
View.MoveCaret(new SnapshotPoint(snapshot, index));
View.MemberList();
});
using (var sh = View.WaitForSession<ICompletionSession>(assertIfNoSession: assertIfNoCompletions)) {
if (sh == null) {
return new List<Completion>();
}
Assert.AreNotEqual(0, sh.Session.CompletionSets.Count);
return sh.Session.CompletionSets.SelectMany(cs => cs.Completions)
.Where(c => !string.IsNullOrEmpty(c?.InsertionText))
.ToList();
}
}
public void Backspace() => VS.InvokeSync(() => View.Backspace());
public void Enter() => VS.InvokeSync(() => View.Enter());
public void Clear() => VS.InvokeSync(() => View.Clear());
public void MoveCaret(int line, int column) => View.MoveCaret(line, column);
public void MemberList() => VS.InvokeSync(() => View.MemberList());
public void ParamInfo() => VS.InvokeSync(() => View.ParamInfo());
public void Type(string text) => VS.InvokeSync(() => View.Type(text));
public void TypeAndWaitForAnalysis(string text) {
var task = Analyzer.WaitForNextCompleteAnalysis();
Type(text);
try {
task.Wait(CancellationTokens.After60s);
} catch (OperationCanceledException) {
Assert.Fail("Timed out waiting for code analysis");
}
VS.ThrowPendingException();
}
public IEnumerable<string> GetCompletions(int index) {
return GetCompletionList(index, false).Select(c => c.DisplayText);
}
public IEnumerable<string> GetCompletionsAfter(string substring) {
return GetCompletionListAfter(substring, false).Select(c => c.DisplayText);
}
public object GetAnalysisEntry(ITextBuffer buffer = null) {
return EditorServices.GetBufferInfo(buffer ?? View.TextView.TextBuffer).AnalysisEntry
?? throw new ArgumentException("no AnalysisEntry available");
}
public void Dispose() {
if (View != null) {
View.Dispose();
}
if (Analyzer != null && _disposeAnalyzer) {
Analyzer.Dispose();
}
if (Factory != null && _disposeFactory) {
var disp = Factory as IDisposable;
if (disp != null) {
disp.Dispose();
}
}
if (VS != null && _disposeVS) {
VS.Dispose();
}
}
}
}
| |
using System;
using System.Linq;
using System.Reflection;
using System.Security.Claims;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Localization;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Login.Api.Features.Shared.ViewModels;
using Login.Api.Infrastructure.Configuration;
using Login.Api.Features.User;
using Commons.Api.FlashScope;
using Commons.Api.Messages;
using Commons.Api.Controller;
namespace Login.Api.Features.Authentication
{
/// <summary>
/// main controller of application
/// </summary>
[Authorize]
public class AuthenticationController : AbstractMvcController
{
private static readonly string AssemblyVersion = Assembly.GetEntryAssembly().GetCustomAttribute<AssemblyInformationalVersionAttribute>().InformationalVersion;
private readonly IHtmlLocalizer<AuthenticationController> localizer;
private readonly ILogger logger;
private readonly IOptions<ApplicationConfiguration> appConfig;
private ILoginService loginService;
/// <summary>
/// constructor
/// </summary>
/// <param name="localizer"></param>
/// <param name="logger"></param>
/// <param name="flash"></param>
/// <param name="messageIntegrity"></param>
/// <param name="loginService"></param>
/// <param name="appConfig"></param>
public AuthenticationController(IHtmlLocalizer<AuthenticationController> localizer, ILogger<AuthenticationController> logger,
IFlashService flash, IMessageIntegrity messageIntegrity, ILoginService loginService,
IOptions<ApplicationConfiguration> appConfig) : base(logger, flash, messageIntegrity)
{
this.localizer = localizer;
this.logger = logger;
this.loginService = loginService;
this.appConfig = appConfig;
}
/// <summary>
/// show logoff page
/// </summary>
/// <returns></returns>
[AllowAnonymous]
[HttpGet]
[Route("logoff")]
public IActionResult LogOff()
{
this.CommonViewData();
var loginInfo = new LoginInfo
{
State = LoginState.Success,
Success = localizer["The user was successfully loged out!"].Value
};
return View("Error", loginInfo);
}
/// <summary>
/// perform logout
/// </summary>
/// <returns></returns>
[Route("logout")]
[HttpGet]
public async Task<IActionResult> Logout()
{
this.CommonViewData();
var cookies = HttpContext.Request.Cookies.Keys;
foreach (var cookie in cookies)
{
HttpContext.Response.Cookies.Delete(cookie, new CookieOptions
{
Domain = appConfig.Value.Jwt.CookieDomain
});
}
if (HttpContext.User.Identity.IsAuthenticated)
{
await HttpContext.SignOutAsync(OpenIdConnectDefaults.AuthenticationScheme);
await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
}
var loginInfo = new LoginInfo
{
State = LoginState.Success,
Success = localizer["The user was successfully loged out!"].Value
};
return View("Error", loginInfo);
}
/// <summary>
/// start the authtentication flow
/// </summary>
/// <param name="site"></param>
/// <param name="url"></param>
/// <returns></returns>
[HttpGet]
[Route("auth/flow")]
[AllowAnonymous]
public async Task<IActionResult> AuthenticationFlow([FromQuery(Name = "~site")] string site, [FromQuery(Name = "~url")] string url)
{
if(string.IsNullOrEmpty(site) || string.IsNullOrEmpty(url))
{
throw new Commons.Api.Exceptions.ApplicationException("Invalid paramters supplied for auth-flow!");
}
// if no authenticated user email is available - challenge the user by an auth request
if (string.IsNullOrEmpty(this.AuthenticatedUserEmail))
{
var props = new AuthenticationProperties
{
// redirect where I came from
RedirectUri = $"/auth/flow?~site={site}&~url={url}"
};
//return await HttpContext.ChallengeAsync(OpenIdConnectDefaults.AuthenticationScheme, props);
return new ChallengeResult(OpenIdConnectDefaults.AuthenticationScheme, props);
}
else
{
var user = await this.loginService.GetUserByEmail(this.AuthenticatedUserEmail);
if (user == null)
{
throw new Commons.Api.Exceptions.ApplicationException("No user is available!");
}
if (!this.loginService.IsValidRedirectUrl(user, site, url))
{
var loginInfo = new LoginInfo
{
State = LoginState.Error,
Error = string.Format(localizer["Could not redirect to the desired url {0}."].Value, url)
};
return View("Error", loginInfo); ;
}
return Redirect(url);
}
}
protected override ActionResult PrepareErrorResult(string key)
{
this.CommonViewData();
var message = string.Format(localizer["Failed to login the user!"].Value);
if (string.IsNullOrEmpty(key))
message = localizer["No active user token available - login is needed!"].Value;
else
{
if (_messageIntegrity.Verify(key))
{
message = _flash.Get(key);
}
}
return View(new LoginInfo
{
State = LoginState.Error,
Error = message
});
}
/// <summary>
/// Perform a login
/// </summary>
/// <returns></returns>
[HttpGet]
[Route("login")]
[AllowAnonymous]
public async Task Login()
{
var props = new AuthenticationProperties
{
RedirectUri = "/"
};
if (HttpContext.User == null || !HttpContext.User.Identity.IsAuthenticated)
{
await HttpContext.ChallengeAsync(OpenIdConnectDefaults.AuthenticationScheme, props);
}
}
[HttpGet]
[Route("relogin")]
public async Task ReLogin()
{
if (HttpContext.User != null && HttpContext.User.Identity.IsAuthenticated)
{
// logoff first, clear authentication holders
var cookies = HttpContext.Request.Cookies.Keys;
foreach (var cookie in cookies)
{
HttpContext.Response.Cookies.Delete(cookie, new CookieOptions
{
Domain = appConfig.Value.Jwt.CookieDomain
});
}
if (HttpContext.User.Identity.IsAuthenticated)
{
await HttpContext.SignOutAsync(OpenIdConnectDefaults.AuthenticationScheme);
await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
}
var props = new AuthenticationProperties
{
RedirectUri = "/"
};
await HttpContext.ChallengeAsync(OpenIdConnectDefaults.AuthenticationScheme, props);
}
else
{
HttpContext.Response.Redirect("/Error");
}
}
#if !BLAZOR
[HttpGet]
[Route("/")]
[Route("/ui/{path?}/{subpath?}")]
public IActionResult Index()
{
return Redirect("/ui/index.html");
}
#endif
void CommonViewData()
{
ViewData[Constants.APP_NAME] = this.appConfig.Value.Name;
ViewData[Constants.APP_VERSION] = AssemblyVersion;
}
string AuthenticatedUserEmail
{
get
{
return this.User.Identity.IsAuthenticated ? this.User.Claims.Where(x => x.Type == ClaimTypes.Email).FirstOrDefault()?.Value : "";
}
}
string Hash(string value)
{
using (var algorithm = SHA256.Create())
{
var hash = algorithm.ComputeHash(Encoding.UTF8.GetBytes(value));
return BitConverter.ToString(hash).Replace("-", "").ToLower();
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Security.Principal;
using System.Text;
using System.Threading.Tasks;
using AutoFixture.NUnit3;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Moq;
using NUnit.Framework;
using Umbraco.Cms.Core;
using Umbraco.Cms.Core.Models;
using Umbraco.Cms.Core.Security;
using Umbraco.Cms.Core.Services;
using Umbraco.Cms.Tests.UnitTests.AutoFixture;
using Umbraco.Cms.Web.Common.Security;
namespace Umbraco.Cms.Tests.UnitTests.Umbraco.Web.Common.Security
{
[TestFixture]
public class PublicAccessCheckerTests
{
private IHttpContextAccessor GetHttpContextAccessor(IMemberManager memberManager, out HttpContext httpContext)
{
var services = new ServiceCollection();
services.AddScoped<IMemberManager>(x => memberManager);
httpContext = new DefaultHttpContext
{
RequestServices = services.BuildServiceProvider()
};
HttpContext localHttpContext = httpContext;
return Mock.Of<IHttpContextAccessor>(x => x.HttpContext == localHttpContext);
}
private PublicAccessChecker CreateSut(IMemberManager memberManager, IPublicAccessService publicAccessService, IContentService contentService, out HttpContext httpContext)
{
var publicAccessChecker = new PublicAccessChecker(
GetHttpContextAccessor(memberManager, out httpContext),
publicAccessService,
contentService);
return publicAccessChecker;
}
private ClaimsPrincipal GetLoggedInUser()
{
var user = new ClaimsPrincipal(new ClaimsIdentity(new Claim[] {
new Claim(ClaimTypes.NameIdentifier, "1234"),
new Claim(ClaimTypes.Name, "test@example.com")
}, "TestAuthentication"));
return user;
}
private void MockGetRolesAsync(IMemberManager memberManager, IEnumerable<string> roles = null)
{
if (roles == null)
{
roles = new[]
{
"role1",
"role2"
};
}
Mock.Get(memberManager).Setup(x => x.GetRolesAsync(It.IsAny<MemberIdentityUser>()))
.Returns(Task.FromResult((IList<string>)new List<string>(roles)));
}
private void MockGetUserAsync(IMemberManager memberManager, MemberIdentityUser memberIdentityUser)
=> Mock.Get(memberManager).Setup(x => x.GetUserAsync(It.IsAny<ClaimsPrincipal>())).Returns(Task.FromResult(memberIdentityUser));
private PublicAccessEntry GetPublicAccessEntry(string usernameRuleValue, string roleRuleValue)
=> new PublicAccessEntry(Guid.NewGuid(), 123, 987, 987, new List<PublicAccessRule>
{
new PublicAccessRule
{
RuleType = Constants.Conventions.PublicAccess.MemberUsernameRuleType,
RuleValue = usernameRuleValue
},
new PublicAccessRule
{
RuleType = Constants.Conventions.PublicAccess.MemberRoleRuleType,
RuleValue = roleRuleValue
}
});
[AutoMoqData]
[Test]
public async Task GivenMemberNotLoggedIn_WhenIdentityIsChecked_ThenNotLoggedInResult(
IMemberManager memberManager,
IPublicAccessService publicAccessService,
IContentService contentService)
{
PublicAccessChecker sut = CreateSut(memberManager, publicAccessService, contentService, out HttpContext httpContext);
httpContext.User = new ClaimsPrincipal();
MockGetUserAsync(memberManager, new MemberIdentityUser());
var result = await sut.HasMemberAccessToContentAsync(123);
Assert.AreEqual(PublicAccessStatus.NotLoggedIn, result);
}
[AutoMoqData]
[Test]
public async Task GivenMemberNotLoggedIn_WhenMemberIsRequested_AndIsNull_ThenNotLoggedInResult(
IMemberManager memberManager,
IPublicAccessService publicAccessService,
IContentService contentService)
{
PublicAccessChecker sut = CreateSut(memberManager, publicAccessService, contentService, out HttpContext httpContext);
httpContext.User = GetLoggedInUser();
MockGetUserAsync(memberManager, null);
var result = await sut.HasMemberAccessToContentAsync(123);
Assert.AreEqual(PublicAccessStatus.NotLoggedIn, result);
}
[AutoMoqData]
[Test]
public async Task GivenMemberLoggedIn_WhenMemberHasNoRolesAndWrongUsername_ThenAccessDeniedResult(
IMemberManager memberManager,
IPublicAccessService publicAccessService,
IContentService contentService,
IContent protectedNode,
IContent loginNode,
IContent noAccessNode,
string username)
{
PublicAccessChecker sut = CreateSut(memberManager, publicAccessService, contentService, out HttpContext httpContext);
Mock.Get(publicAccessService).Setup(x => x.GetEntryForContent(It.IsAny<IContent>()))
.Returns(new PublicAccessEntry(protectedNode, loginNode, noAccessNode, new []
{
new PublicAccessRule(Guid.Empty, Guid.Empty)
{
RuleType = Constants.Conventions.PublicAccess.MemberUsernameRuleType,
RuleValue = "AnotherUsername"
}
}));
httpContext.User = GetLoggedInUser();
MockGetUserAsync(memberManager, new MemberIdentityUser(){IsApproved = true, UserName = username});
MockGetRolesAsync(memberManager, Enumerable.Empty<string>());
var result = await sut.HasMemberAccessToContentAsync(123);
Assert.AreEqual(PublicAccessStatus.AccessDenied, result);
}
[AutoMoqData]
[Test]
public async Task GivenMemberLoggedIn_WhenMemberIsLockedOut_ThenLockedOutResult(
IMemberManager memberManager,
IPublicAccessService publicAccessService,
IContentService contentService)
{
PublicAccessChecker sut = CreateSut(memberManager, publicAccessService, contentService, out HttpContext httpContext);
httpContext.User = GetLoggedInUser();
MockGetUserAsync(memberManager, new MemberIdentityUser { IsApproved = true, LockoutEnd = DateTime.UtcNow.AddDays(10) });
MockGetRolesAsync(memberManager);
var result = await sut.HasMemberAccessToContentAsync(123);
Assert.AreEqual(PublicAccessStatus.LockedOut, result);
}
[AutoMoqData]
[Test]
public async Task GivenMemberLoggedIn_WhenMemberIsNotApproved_ThenNotApprovedResult(
IMemberManager memberManager,
IPublicAccessService publicAccessService,
IContentService contentService)
{
PublicAccessChecker sut = CreateSut(memberManager, publicAccessService, contentService, out HttpContext httpContext);
httpContext.User = GetLoggedInUser();
MockGetUserAsync(memberManager, new MemberIdentityUser { IsApproved = false });
MockGetRolesAsync(memberManager);
var result = await sut.HasMemberAccessToContentAsync(123);
Assert.AreEqual(PublicAccessStatus.NotApproved, result);
}
[AutoMoqData]
[Test]
public async Task GivenMemberLoggedIn_WhenMemberHasRoles_AndContentDoesNotExist_ThenAccessAcceptedResult(
IMemberManager memberManager,
IPublicAccessService publicAccessService,
IContentService contentService)
{
PublicAccessChecker sut = CreateSut(memberManager, publicAccessService, contentService, out HttpContext httpContext);
httpContext.User = GetLoggedInUser();
MockGetUserAsync(memberManager, new MemberIdentityUser { IsApproved = true});
MockGetRolesAsync(memberManager);
Mock.Get(contentService).Setup(x => x.GetById(123)).Returns((IContent)null);
var result = await sut.HasMemberAccessToContentAsync(123);
Assert.AreEqual(PublicAccessStatus.AccessAccepted, result);
}
[AutoMoqData]
[Test]
public async Task GivenMemberLoggedIn_WhenMemberHasRoles_AndGetEntryForContentDoesNotExist_ThenAccessAcceptedResult(
IMemberManager memberManager,
IPublicAccessService publicAccessService,
IContentService contentService,
IContent content)
{
PublicAccessChecker sut = CreateSut(memberManager, publicAccessService, contentService, out HttpContext httpContext);
httpContext.User = GetLoggedInUser();
MockGetUserAsync(memberManager, new MemberIdentityUser { IsApproved = true });
MockGetRolesAsync(memberManager);
Mock.Get(contentService).Setup(x => x.GetById(123)).Returns(content);
Mock.Get(publicAccessService).Setup(x => x.GetEntryForContent(content)).Returns((PublicAccessEntry)null);
var result = await sut.HasMemberAccessToContentAsync(123);
Assert.AreEqual(PublicAccessStatus.AccessAccepted, result);
}
[AutoMoqData]
[Test]
public async Task GivenMemberLoggedIn_WhenMemberHasRoles_AndEntryRulesDontMatch_ThenAccessDeniedResult(
IMemberManager memberManager,
IPublicAccessService publicAccessService,
IContentService contentService,
IContent content)
{
PublicAccessChecker sut = CreateSut(memberManager, publicAccessService, contentService, out HttpContext httpContext);
httpContext.User = GetLoggedInUser();
MockGetUserAsync(memberManager, new MemberIdentityUser { UserName = "MyUsername", IsApproved = true });
MockGetRolesAsync(memberManager);
Mock.Get(contentService).Setup(x => x.GetById(123)).Returns(content);
Mock.Get(publicAccessService).Setup(x => x.GetEntryForContent(content)).Returns(GetPublicAccessEntry(string.Empty, string.Empty));
var result = await sut.HasMemberAccessToContentAsync(123);
Assert.AreEqual(PublicAccessStatus.AccessDenied, result);
}
[AutoMoqData]
[Test]
public async Task GivenMemberLoggedIn_WhenMemberHasRoles_AndUsernameRuleMatches_ThenAccessAcceptedResult(
IMemberManager memberManager,
IPublicAccessService publicAccessService,
IContentService contentService,
IContent content)
{
PublicAccessChecker sut = CreateSut(memberManager, publicAccessService, contentService, out HttpContext httpContext);
httpContext.User = GetLoggedInUser();
MockGetUserAsync(memberManager, new MemberIdentityUser { UserName = "MyUsername", IsApproved = true });
MockGetRolesAsync(memberManager);
Mock.Get(contentService).Setup(x => x.GetById(123)).Returns(content);
Mock.Get(publicAccessService).Setup(x => x.GetEntryForContent(content)).Returns(GetPublicAccessEntry("MyUsername", string.Empty));
var result = await sut.HasMemberAccessToContentAsync(123);
Assert.AreEqual(PublicAccessStatus.AccessAccepted, result);
}
[AutoMoqData]
[Test]
public async Task GivenMemberLoggedIn_WhenMemberHasRoles_AndRoleRuleMatches_ThenAccessAcceptedResult(
IMemberManager memberManager,
IPublicAccessService publicAccessService,
IContentService contentService,
IContent content)
{
PublicAccessChecker sut = CreateSut(memberManager, publicAccessService, contentService, out HttpContext httpContext);
httpContext.User = GetLoggedInUser();
MockGetUserAsync(memberManager, new MemberIdentityUser { UserName = "MyUsername", IsApproved = true });
MockGetRolesAsync(memberManager);
Mock.Get(contentService).Setup(x => x.GetById(123)).Returns(content);
Mock.Get(publicAccessService).Setup(x => x.GetEntryForContent(content)).Returns(GetPublicAccessEntry(string.Empty, "role1"));
var result = await sut.HasMemberAccessToContentAsync(123);
Assert.AreEqual(PublicAccessStatus.AccessAccepted, result);
}
}
}
| |
//
// 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;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using Microsoft.Rest.Azure;
using Microsoft.Azure.Management.ResourceManager;
using Microsoft.Azure.Management.ResourceManager.Models;
using Microsoft.Rest;
using Newtonsoft.Json.Linq;
using Xunit;
using Microsoft.Rest.Azure.OData;
namespace ResourceGroups.Tests
{
public class InMemoryResourceGroupTests
{
public ResourceManagementClient GetResourceManagementClient(RecordedDelegatingHandler handler)
{
var subscriptionId = Guid.NewGuid().ToString();
var token = new TokenCredentials(subscriptionId, "abc123");
handler.IsPassThrough = false;
var client = new ResourceManagementClient(token, handler);
client.SubscriptionId = subscriptionId;
return client;
}
[Fact]
public void ResourceGroupCreateOrUpdateValidateMessage()
{
var response = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent(@"{
'id': '/subscriptions/abc123/resourcegroups/csmrgr5mfggio',
'name': 'foo',
'location': 'WestEurope',
'tags' : {
'department':'finance',
'tagname':'tagvalue'
},
'properties': {
'provisioningState': 'Succeeded'
}
}")
};
var handler = new RecordedDelegatingHandler(response) { StatusCodeToReturn = HttpStatusCode.OK };
var client = GetResourceManagementClient(handler);
var result = client.ResourceGroups.CreateOrUpdate("foo", new ResourceGroup
{
Location = "WestEurope",
Tags = new Dictionary<string, string>() { { "department", "finance" }, { "tagname", "tagvalue" } },
});
JObject json = JObject.Parse(handler.Request);
// Validate headers
Assert.Equal("application/json; charset=utf-8", handler.ContentHeaders.GetValues("Content-Type").First());
Assert.Equal(HttpMethod.Put, handler.Method);
Assert.NotNull(handler.RequestHeaders.GetValues("Authorization"));
// Validate payload
Assert.Equal("WestEurope", json["location"].Value<string>());
Assert.Equal("finance", json["tags"]["department"].Value<string>());
Assert.Equal("tagvalue", json["tags"]["tagname"].Value<string>());
// Validate response
Assert.Equal("/subscriptions/abc123/resourcegroups/csmrgr5mfggio", result.Id);
Assert.Equal("Succeeded", result.Properties.ProvisioningState);
Assert.Equal("foo", result.Name);
Assert.Equal("finance", result.Tags["department"]);
Assert.Equal("tagvalue", result.Tags["tagname"]);
Assert.Equal("WestEurope", result.Location);
}
[Fact]
public void ResourceGroupCreateOrUpdateThrowsExceptions()
{
var handler = new RecordedDelegatingHandler();
var client = GetResourceManagementClient(handler);
Assert.Throws<Microsoft.Rest.ValidationException>(() => client.ResourceGroups.CreateOrUpdate(null, new ResourceGroup()));
Assert.Throws<Microsoft.Rest.ValidationException>(() => client.ResourceGroups.CreateOrUpdate("foo", null));
}
[Fact]
public void ResourceGroupExistsReturnsTrue()
{
var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.NoContent };
var client = GetResourceManagementClient(handler);
var result = client.ResourceGroups.CheckExistence("foo");
// Validate payload
Assert.Empty(handler.Request);
// Validate response
Assert.True(result);
}
[Fact]
public void ResourceGroupExistsReturnsFalse()
{
var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.NotFound };
var client = GetResourceManagementClient(handler);
var result = client.ResourceGroups.CheckExistence(Guid.NewGuid().ToString());
// Validate payload
Assert.Empty(handler.Request);
// Validate response
Assert.False(result);
}
[Fact()]
public void ResourceGroupExistsThrowsException()
{
var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.BadRequest };
var client = GetResourceManagementClient(handler);
Assert.Throws<CloudException>(() => client.ResourceGroups.CheckExistence("foo"));
}
[Fact]
public void ResourceGroupPatchValidateMessage()
{
var response = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent(@"{
'subscriptionId': '123456',
'name': 'foo',
'location': 'WestEurope',
'id': '/subscriptions/abc123/resourcegroups/csmrgr5mfggio',
'properties': {
'provisioningState': 'Succeeded'
}
}")
};
var handler = new RecordedDelegatingHandler(response) { StatusCodeToReturn = HttpStatusCode.OK };
var client = GetResourceManagementClient(handler);
var result = client.ResourceGroups.Patch("foo", new ResourceGroup
{
Location = "WestEurope",
});
JObject json = JObject.Parse(handler.Request);
// Validate headers
Assert.Equal("application/json; charset=utf-8", handler.ContentHeaders.GetValues("Content-Type").First());
Assert.Equal("patch", handler.Method.Method.Trim().ToLower());
Assert.NotNull(handler.RequestHeaders.GetValues("Authorization"));
// Validate payload
Assert.Equal("WestEurope", json["location"].Value<string>());
// Validate response
Assert.Equal("/subscriptions/abc123/resourcegroups/csmrgr5mfggio", result.Id);
Assert.Equal("Succeeded", result.Properties.ProvisioningState);
Assert.Equal("foo", result.Name);
Assert.Equal("WestEurope", result.Location);
}
[Fact(Skip = "Parameter validation using pattern match is not supported yet at code-gen, the work is on-going.")]
public void ResourceGroupUpdateStateThrowsExceptions()
{
var handler = new RecordedDelegatingHandler();
var client = GetResourceManagementClient(handler);
Assert.Throws<ArgumentNullException>(() => client.ResourceGroups.Patch(null, new ResourceGroup()));
Assert.Throws<ArgumentNullException>(() => client.ResourceGroups.Patch("foo", null));
Assert.Throws<ArgumentOutOfRangeException>(() => client.ResourceGroups.Patch("~`123", new ResourceGroup()));
}
[Fact]
public void ResourceGroupGetValidateMessage()
{
var response = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent(@"{
'id': '/subscriptions/abc123/resourcegroups/csmrgr5mfggio',
'name': 'foo',
'location': 'WestEurope',
'properties': {
'provisioningState': 'Succeeded'
}
}")
};
response.Headers.Add("x-ms-request-id", "1");
var handler = new RecordedDelegatingHandler(response) { StatusCodeToReturn = HttpStatusCode.OK };
var client = GetResourceManagementClient(handler);
var result = client.ResourceGroups.Get("foo");
// Validate headers
Assert.Equal(HttpMethod.Get, handler.Method);
Assert.NotNull(handler.RequestHeaders.GetValues("Authorization"));
// Validate result
Assert.Equal("/subscriptions/abc123/resourcegroups/csmrgr5mfggio", result.Id);
Assert.Equal("WestEurope", result.Location);
Assert.Equal("foo", result.Name);
Assert.Equal("Succeeded", result.Properties.ProvisioningState);
Assert.True(result.Properties.ProvisioningState == "Succeeded");
}
[Fact]
public void ResourceGroupNameAcceptsAllAllowableCharacters()
{
var response = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent(@"{
'id': '/subscriptions/abc123/resourcegroups/csmrgr5mfggio',
'name': 'foo',
'location': 'WestEurope',
'properties': {
'provisioningState': 'Succeeded'
}
}")
};
response.Headers.Add("x-ms-request-id", "1");
var handler = new RecordedDelegatingHandler(response) { StatusCodeToReturn = HttpStatusCode.OK };
var client = GetResourceManagementClient(handler);
client.ResourceGroups.Get("foo-123_(bar)");
}
[Fact(Skip = "Parameter validation using pattern match is not supported yet at code-gen, the work is on-going.")]
public void ResourceGroupGetThrowsExceptions()
{
var handler = new RecordedDelegatingHandler();
var client = GetResourceManagementClient(handler);
Assert.Throws<ArgumentNullException>(() => client.ResourceGroups.Get(null));
Assert.Throws<ArgumentOutOfRangeException>(() => client.ResourceGroups.Get("~`123"));
}
[Fact]
public void ResourceGroupListAllValidateMessage()
{
var response = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent(@"{
'value': [{
'id': '/subscriptions/abc123/resourcegroups/csmrgr5mfggio',
'name': 'myresourcegroup1',
'location': 'westus',
'properties': {
'provisioningState': 'Succeeded'
}
},
{
'id': '/subscriptions/abc123/resourcegroups/fdfdsdsf',
'name': 'myresourcegroup2',
'location': 'eastus',
'properties': {
'provisioningState': 'Succeeded'
}
}
],
'nextLink': 'https://wa/subscriptions/subId/resourcegroups?api-version=1.0&$skiptoken=662idk',
}")
};
response.Headers.Add("x-ms-request-id", "1");
var handler = new RecordedDelegatingHandler(response) { StatusCodeToReturn = HttpStatusCode.OK };
var client = GetResourceManagementClient(handler);
var result = client.ResourceGroups.List(null);
// Validate headers
Assert.Equal(HttpMethod.Get, handler.Method);
Assert.NotNull(handler.RequestHeaders.GetValues("Authorization"));
// Validate result
Assert.Equal(2, result.Count());
Assert.Equal("myresourcegroup1", result.First().Name);
Assert.Equal("Succeeded", result.First().Properties.ProvisioningState);
Assert.Equal("/subscriptions/abc123/resourcegroups/csmrgr5mfggio", result.First().Id);
Assert.Equal("https://wa/subscriptions/subId/resourcegroups?api-version=1.0&$skiptoken=662idk", result.NextPageLink);
}
[Fact]
public void ResourceGroupListAllWorksForEmptyLists()
{
var response = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent(@"{'value': []}")
};
response.Headers.Add("x-ms-request-id", "1");
var handler = new RecordedDelegatingHandler(response) { StatusCodeToReturn = HttpStatusCode.OK };
var client = GetResourceManagementClient(handler);
var result = client.ResourceGroups.List(null);
// Validate headers
Assert.Equal(HttpMethod.Get, handler.Method);
Assert.NotNull(handler.RequestHeaders.GetValues("Authorization"));
// Validate result
Assert.Equal(0, result.Count());
}
[Fact]
public void ResourceGroupListValidateMessage()
{
var response = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent(@"{
'value': [{
'name': 'myresourcegroup1',
'location': 'westus',
'locked': 'true'
},
{
'name': 'myresourcegroup2',
'location': 'eastus',
'locked': 'false'
}
],
'nextLink': 'https://wa/subscriptions/subId/resourcegroups?api-version=1.0&$skiptoken=662idk',
}")
};
response.Headers.Add("x-ms-request-id", "1");
var handler = new RecordedDelegatingHandler(response) { StatusCodeToReturn = HttpStatusCode.OK };
var client = GetResourceManagementClient(handler);
var result = client.ResourceGroups.List(new ODataQuery<ResourceGroupFilter> { Top = 5 });
// Validate headers
Assert.Equal(HttpMethod.Get, handler.Method);
Assert.NotNull(handler.RequestHeaders.GetValues("Authorization"));
Assert.True(handler.Uri.ToString().Contains("$top=5"));
// Validate result
Assert.Equal(2, result.Count());
Assert.Equal("myresourcegroup1", result.First().Name);
Assert.Equal("https://wa/subscriptions/subId/resourcegroups?api-version=1.0&$skiptoken=662idk", result.NextPageLink);
}
[Fact]
public void ResourceGroupDeleteValidateMessage()
{
var response = new HttpResponseMessage(HttpStatusCode.Accepted);
response.Headers.Add("Location", "http://foo");
var handler = new RecordedDelegatingHandler(response)
{
StatusCodeToReturn = HttpStatusCode.Accepted,
SubsequentStatusCodeToReturn = HttpStatusCode.OK
};
var client = GetResourceManagementClient(handler);
client.LongRunningOperationRetryTimeout = 0;
client.ResourceGroups.Delete("foo");
}
[Fact]
public void ResourceGroupDeleteThrowsExceptions()
{
var handler = new RecordedDelegatingHandler();
var client = GetResourceManagementClient(handler);
Assert.Throws<ValidationException>(() => client.ResourceGroups.Delete(null));
Assert.Throws<ValidationException>(() => client.ResourceGroups.Delete("~`123"));
}
}
}
| |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
namespace Google.Cloud.Vision.V1.Snippets
{
using Google.LongRunning;
using System.Collections.Generic;
using System.Threading.Tasks;
/// <summary>Generated snippets.</summary>
public sealed class AllGeneratedImageAnnotatorClientSnippets
{
/// <summary>Snippet for BatchAnnotateImages</summary>
public void BatchAnnotateImagesRequestObject()
{
// Snippet: BatchAnnotateImages(BatchAnnotateImagesRequest, CallSettings)
// Create client
ImageAnnotatorClient imageAnnotatorClient = ImageAnnotatorClient.Create();
// Initialize request argument(s)
BatchAnnotateImagesRequest request = new BatchAnnotateImagesRequest
{
Requests =
{
new AnnotateImageRequest(),
},
Parent = "",
};
// Make the request
BatchAnnotateImagesResponse response = imageAnnotatorClient.BatchAnnotateImages(request);
// End snippet
}
/// <summary>Snippet for BatchAnnotateImagesAsync</summary>
public async Task BatchAnnotateImagesRequestObjectAsync()
{
// Snippet: BatchAnnotateImagesAsync(BatchAnnotateImagesRequest, CallSettings)
// Additional: BatchAnnotateImagesAsync(BatchAnnotateImagesRequest, CancellationToken)
// Create client
ImageAnnotatorClient imageAnnotatorClient = await ImageAnnotatorClient.CreateAsync();
// Initialize request argument(s)
BatchAnnotateImagesRequest request = new BatchAnnotateImagesRequest
{
Requests =
{
new AnnotateImageRequest(),
},
Parent = "",
};
// Make the request
BatchAnnotateImagesResponse response = await imageAnnotatorClient.BatchAnnotateImagesAsync(request);
// End snippet
}
/// <summary>Snippet for BatchAnnotateImages</summary>
public void BatchAnnotateImages()
{
// Snippet: BatchAnnotateImages(IEnumerable<AnnotateImageRequest>, CallSettings)
// Create client
ImageAnnotatorClient imageAnnotatorClient = ImageAnnotatorClient.Create();
// Initialize request argument(s)
IEnumerable<AnnotateImageRequest> requests = new AnnotateImageRequest[]
{
new AnnotateImageRequest(),
};
// Make the request
BatchAnnotateImagesResponse response = imageAnnotatorClient.BatchAnnotateImages(requests);
// End snippet
}
/// <summary>Snippet for BatchAnnotateImagesAsync</summary>
public async Task BatchAnnotateImagesAsync()
{
// Snippet: BatchAnnotateImagesAsync(IEnumerable<AnnotateImageRequest>, CallSettings)
// Additional: BatchAnnotateImagesAsync(IEnumerable<AnnotateImageRequest>, CancellationToken)
// Create client
ImageAnnotatorClient imageAnnotatorClient = await ImageAnnotatorClient.CreateAsync();
// Initialize request argument(s)
IEnumerable<AnnotateImageRequest> requests = new AnnotateImageRequest[]
{
new AnnotateImageRequest(),
};
// Make the request
BatchAnnotateImagesResponse response = await imageAnnotatorClient.BatchAnnotateImagesAsync(requests);
// End snippet
}
/// <summary>Snippet for BatchAnnotateFiles</summary>
public void BatchAnnotateFilesRequestObject()
{
// Snippet: BatchAnnotateFiles(BatchAnnotateFilesRequest, CallSettings)
// Create client
ImageAnnotatorClient imageAnnotatorClient = ImageAnnotatorClient.Create();
// Initialize request argument(s)
BatchAnnotateFilesRequest request = new BatchAnnotateFilesRequest
{
Requests =
{
new AnnotateFileRequest(),
},
Parent = "",
};
// Make the request
BatchAnnotateFilesResponse response = imageAnnotatorClient.BatchAnnotateFiles(request);
// End snippet
}
/// <summary>Snippet for BatchAnnotateFilesAsync</summary>
public async Task BatchAnnotateFilesRequestObjectAsync()
{
// Snippet: BatchAnnotateFilesAsync(BatchAnnotateFilesRequest, CallSettings)
// Additional: BatchAnnotateFilesAsync(BatchAnnotateFilesRequest, CancellationToken)
// Create client
ImageAnnotatorClient imageAnnotatorClient = await ImageAnnotatorClient.CreateAsync();
// Initialize request argument(s)
BatchAnnotateFilesRequest request = new BatchAnnotateFilesRequest
{
Requests =
{
new AnnotateFileRequest(),
},
Parent = "",
};
// Make the request
BatchAnnotateFilesResponse response = await imageAnnotatorClient.BatchAnnotateFilesAsync(request);
// End snippet
}
/// <summary>Snippet for BatchAnnotateFiles</summary>
public void BatchAnnotateFiles()
{
// Snippet: BatchAnnotateFiles(IEnumerable<AnnotateFileRequest>, CallSettings)
// Create client
ImageAnnotatorClient imageAnnotatorClient = ImageAnnotatorClient.Create();
// Initialize request argument(s)
IEnumerable<AnnotateFileRequest> requests = new AnnotateFileRequest[]
{
new AnnotateFileRequest(),
};
// Make the request
BatchAnnotateFilesResponse response = imageAnnotatorClient.BatchAnnotateFiles(requests);
// End snippet
}
/// <summary>Snippet for BatchAnnotateFilesAsync</summary>
public async Task BatchAnnotateFilesAsync()
{
// Snippet: BatchAnnotateFilesAsync(IEnumerable<AnnotateFileRequest>, CallSettings)
// Additional: BatchAnnotateFilesAsync(IEnumerable<AnnotateFileRequest>, CancellationToken)
// Create client
ImageAnnotatorClient imageAnnotatorClient = await ImageAnnotatorClient.CreateAsync();
// Initialize request argument(s)
IEnumerable<AnnotateFileRequest> requests = new AnnotateFileRequest[]
{
new AnnotateFileRequest(),
};
// Make the request
BatchAnnotateFilesResponse response = await imageAnnotatorClient.BatchAnnotateFilesAsync(requests);
// End snippet
}
/// <summary>Snippet for AsyncBatchAnnotateImages</summary>
public void AsyncBatchAnnotateImagesRequestObject()
{
// Snippet: AsyncBatchAnnotateImages(AsyncBatchAnnotateImagesRequest, CallSettings)
// Create client
ImageAnnotatorClient imageAnnotatorClient = ImageAnnotatorClient.Create();
// Initialize request argument(s)
AsyncBatchAnnotateImagesRequest request = new AsyncBatchAnnotateImagesRequest
{
Requests =
{
new AnnotateImageRequest(),
},
OutputConfig = new OutputConfig(),
Parent = "",
};
// Make the request
Operation<AsyncBatchAnnotateImagesResponse, OperationMetadata> response = imageAnnotatorClient.AsyncBatchAnnotateImages(request);
// Poll until the returned long-running operation is complete
Operation<AsyncBatchAnnotateImagesResponse, OperationMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
AsyncBatchAnnotateImagesResponse result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<AsyncBatchAnnotateImagesResponse, OperationMetadata> retrievedResponse = imageAnnotatorClient.PollOnceAsyncBatchAnnotateImages(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
AsyncBatchAnnotateImagesResponse retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for AsyncBatchAnnotateImagesAsync</summary>
public async Task AsyncBatchAnnotateImagesRequestObjectAsync()
{
// Snippet: AsyncBatchAnnotateImagesAsync(AsyncBatchAnnotateImagesRequest, CallSettings)
// Additional: AsyncBatchAnnotateImagesAsync(AsyncBatchAnnotateImagesRequest, CancellationToken)
// Create client
ImageAnnotatorClient imageAnnotatorClient = await ImageAnnotatorClient.CreateAsync();
// Initialize request argument(s)
AsyncBatchAnnotateImagesRequest request = new AsyncBatchAnnotateImagesRequest
{
Requests =
{
new AnnotateImageRequest(),
},
OutputConfig = new OutputConfig(),
Parent = "",
};
// Make the request
Operation<AsyncBatchAnnotateImagesResponse, OperationMetadata> response = await imageAnnotatorClient.AsyncBatchAnnotateImagesAsync(request);
// Poll until the returned long-running operation is complete
Operation<AsyncBatchAnnotateImagesResponse, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
AsyncBatchAnnotateImagesResponse result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<AsyncBatchAnnotateImagesResponse, OperationMetadata> retrievedResponse = await imageAnnotatorClient.PollOnceAsyncBatchAnnotateImagesAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
AsyncBatchAnnotateImagesResponse retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for AsyncBatchAnnotateImages</summary>
public void AsyncBatchAnnotateImages()
{
// Snippet: AsyncBatchAnnotateImages(IEnumerable<AnnotateImageRequest>, OutputConfig, CallSettings)
// Create client
ImageAnnotatorClient imageAnnotatorClient = ImageAnnotatorClient.Create();
// Initialize request argument(s)
IEnumerable<AnnotateImageRequest> requests = new AnnotateImageRequest[]
{
new AnnotateImageRequest(),
};
OutputConfig outputConfig = new OutputConfig();
// Make the request
Operation<AsyncBatchAnnotateImagesResponse, OperationMetadata> response = imageAnnotatorClient.AsyncBatchAnnotateImages(requests, outputConfig);
// Poll until the returned long-running operation is complete
Operation<AsyncBatchAnnotateImagesResponse, OperationMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
AsyncBatchAnnotateImagesResponse result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<AsyncBatchAnnotateImagesResponse, OperationMetadata> retrievedResponse = imageAnnotatorClient.PollOnceAsyncBatchAnnotateImages(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
AsyncBatchAnnotateImagesResponse retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for AsyncBatchAnnotateImagesAsync</summary>
public async Task AsyncBatchAnnotateImagesAsync()
{
// Snippet: AsyncBatchAnnotateImagesAsync(IEnumerable<AnnotateImageRequest>, OutputConfig, CallSettings)
// Additional: AsyncBatchAnnotateImagesAsync(IEnumerable<AnnotateImageRequest>, OutputConfig, CancellationToken)
// Create client
ImageAnnotatorClient imageAnnotatorClient = await ImageAnnotatorClient.CreateAsync();
// Initialize request argument(s)
IEnumerable<AnnotateImageRequest> requests = new AnnotateImageRequest[]
{
new AnnotateImageRequest(),
};
OutputConfig outputConfig = new OutputConfig();
// Make the request
Operation<AsyncBatchAnnotateImagesResponse, OperationMetadata> response = await imageAnnotatorClient.AsyncBatchAnnotateImagesAsync(requests, outputConfig);
// Poll until the returned long-running operation is complete
Operation<AsyncBatchAnnotateImagesResponse, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
AsyncBatchAnnotateImagesResponse result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<AsyncBatchAnnotateImagesResponse, OperationMetadata> retrievedResponse = await imageAnnotatorClient.PollOnceAsyncBatchAnnotateImagesAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
AsyncBatchAnnotateImagesResponse retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for AsyncBatchAnnotateFiles</summary>
public void AsyncBatchAnnotateFilesRequestObject()
{
// Snippet: AsyncBatchAnnotateFiles(AsyncBatchAnnotateFilesRequest, CallSettings)
// Create client
ImageAnnotatorClient imageAnnotatorClient = ImageAnnotatorClient.Create();
// Initialize request argument(s)
AsyncBatchAnnotateFilesRequest request = new AsyncBatchAnnotateFilesRequest
{
Requests =
{
new AsyncAnnotateFileRequest(),
},
Parent = "",
};
// Make the request
Operation<AsyncBatchAnnotateFilesResponse, OperationMetadata> response = imageAnnotatorClient.AsyncBatchAnnotateFiles(request);
// Poll until the returned long-running operation is complete
Operation<AsyncBatchAnnotateFilesResponse, OperationMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
AsyncBatchAnnotateFilesResponse result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<AsyncBatchAnnotateFilesResponse, OperationMetadata> retrievedResponse = imageAnnotatorClient.PollOnceAsyncBatchAnnotateFiles(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
AsyncBatchAnnotateFilesResponse retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for AsyncBatchAnnotateFilesAsync</summary>
public async Task AsyncBatchAnnotateFilesRequestObjectAsync()
{
// Snippet: AsyncBatchAnnotateFilesAsync(AsyncBatchAnnotateFilesRequest, CallSettings)
// Additional: AsyncBatchAnnotateFilesAsync(AsyncBatchAnnotateFilesRequest, CancellationToken)
// Create client
ImageAnnotatorClient imageAnnotatorClient = await ImageAnnotatorClient.CreateAsync();
// Initialize request argument(s)
AsyncBatchAnnotateFilesRequest request = new AsyncBatchAnnotateFilesRequest
{
Requests =
{
new AsyncAnnotateFileRequest(),
},
Parent = "",
};
// Make the request
Operation<AsyncBatchAnnotateFilesResponse, OperationMetadata> response = await imageAnnotatorClient.AsyncBatchAnnotateFilesAsync(request);
// Poll until the returned long-running operation is complete
Operation<AsyncBatchAnnotateFilesResponse, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
AsyncBatchAnnotateFilesResponse result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<AsyncBatchAnnotateFilesResponse, OperationMetadata> retrievedResponse = await imageAnnotatorClient.PollOnceAsyncBatchAnnotateFilesAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
AsyncBatchAnnotateFilesResponse retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for AsyncBatchAnnotateFiles</summary>
public void AsyncBatchAnnotateFiles()
{
// Snippet: AsyncBatchAnnotateFiles(IEnumerable<AsyncAnnotateFileRequest>, CallSettings)
// Create client
ImageAnnotatorClient imageAnnotatorClient = ImageAnnotatorClient.Create();
// Initialize request argument(s)
IEnumerable<AsyncAnnotateFileRequest> requests = new AsyncAnnotateFileRequest[]
{
new AsyncAnnotateFileRequest(),
};
// Make the request
Operation<AsyncBatchAnnotateFilesResponse, OperationMetadata> response = imageAnnotatorClient.AsyncBatchAnnotateFiles(requests);
// Poll until the returned long-running operation is complete
Operation<AsyncBatchAnnotateFilesResponse, OperationMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
AsyncBatchAnnotateFilesResponse result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<AsyncBatchAnnotateFilesResponse, OperationMetadata> retrievedResponse = imageAnnotatorClient.PollOnceAsyncBatchAnnotateFiles(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
AsyncBatchAnnotateFilesResponse retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for AsyncBatchAnnotateFilesAsync</summary>
public async Task AsyncBatchAnnotateFilesAsync()
{
// Snippet: AsyncBatchAnnotateFilesAsync(IEnumerable<AsyncAnnotateFileRequest>, CallSettings)
// Additional: AsyncBatchAnnotateFilesAsync(IEnumerable<AsyncAnnotateFileRequest>, CancellationToken)
// Create client
ImageAnnotatorClient imageAnnotatorClient = await ImageAnnotatorClient.CreateAsync();
// Initialize request argument(s)
IEnumerable<AsyncAnnotateFileRequest> requests = new AsyncAnnotateFileRequest[]
{
new AsyncAnnotateFileRequest(),
};
// Make the request
Operation<AsyncBatchAnnotateFilesResponse, OperationMetadata> response = await imageAnnotatorClient.AsyncBatchAnnotateFilesAsync(requests);
// Poll until the returned long-running operation is complete
Operation<AsyncBatchAnnotateFilesResponse, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
AsyncBatchAnnotateFilesResponse result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<AsyncBatchAnnotateFilesResponse, OperationMetadata> retrievedResponse = await imageAnnotatorClient.PollOnceAsyncBatchAnnotateFilesAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
AsyncBatchAnnotateFilesResponse retrievedResult = retrievedResponse.Result;
}
// End snippet
}
}
}
| |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
#if UNITY_ANDROID
namespace Prime31
{
public class AndroidNotificationConfiguration
{
public long secondsFromNow;
public string title = string.Empty;
public string subtitle = string.Empty;
public string tickerText = string.Empty;
public string extraData = string.Empty;
public string smallIcon = string.Empty;
public string largeIcon = string.Empty;
public int requestCode = -1;
public string groupKey = string.Empty;
public int color = -1;
public bool isGroupSummary;
public int cancelsNotificationId = -1;
public AndroidNotificationConfiguration( long secondsFromNow, string title, string subtitle, string tickerText )
{
this.secondsFromNow = secondsFromNow;
this.title = title;
this.subtitle = subtitle;
this.tickerText = tickerText;
}
public AndroidNotificationConfiguration build()
{
if( requestCode == -1 )
requestCode = Random.Range( 0, int.MaxValue );
return this;
}
}
public enum TTSQueueMode
{
Flush = 0,
Add = 1
}
public class EtceteraAndroid
{
private static AndroidJavaObject _plugin;
public enum ScalingMode
{
None,
AspectFit,
Fill
}
static EtceteraAndroid()
{
if( Application.platform != RuntimePlatform.Android )
return;
// find the plugin instance
using( var pluginClass = new AndroidJavaClass( "com.prime31.EtceteraPlugin" ) )
_plugin = pluginClass.CallStatic<AndroidJavaObject>( "instance" );
}
// Loads up a Texture2D with the image at the given path
public static Texture2D textureFromFileAtPath( string filePath )
{
var bytes = System.IO.File.ReadAllBytes( filePath );
var tex = new Texture2D( 1, 1 );
tex.LoadImage( bytes );
tex.Apply();
Debug.Log( "texture size: " + tex.width + "x" + tex.height );
return tex;
}
// Toggles low profile mode for the standard decor view on Honeycomb+
public static void setSystemUiVisibilityToLowProfile( bool useLowProfile )
{
if( Application.platform != RuntimePlatform.Android )
return;
_plugin.Call( "setSystemUiVisibilityToLowProfile", useLowProfile );
}
// Plays a video either locally (must be in the StreamingAssets folder or accessible via full path) or remotely. The video format must be compatible with the current
// device. Many devices have different supported video formats so choose the most common (probably 3gp).
// When playing a video from the StreamingAssets folder you only need to provide the filename via the pathOrUrl parameter.
public static void playMovie( string pathOrUrl, uint bgColor, bool showControls, ScalingMode scalingMode, bool closeOnTouch )
{
if( Application.platform != RuntimePlatform.Android )
return;
_plugin.Call( "playMovie", pathOrUrl, (int)bgColor, showControls, (int)scalingMode, closeOnTouch );
}
// Sets the theme for any alerts displayed. See the Android documentation for available themes: http://developer.android.com/reference/android/app/AlertDialog.html#constants
// Make sure you know which Android OS version your app is currently installed on and ensure that you only use themes supported by that version!
public static void setAlertDialogTheme( int theme )
{
if( Application.platform != RuntimePlatform.Android )
return;
_plugin.Call( "setAlertDialogTheme", theme );
}
// Shows a Toast notification. You can choose either short or long duration
public static void showToast( string text, bool useShortDuration )
{
if( Application.platform != RuntimePlatform.Android )
return;
_plugin.Call( "showToast", text, useShortDuration );
}
// Shows a native alert with a single button
public static void showAlert( string title, string message, string positiveButton )
{
showAlert( title, message, positiveButton, string.Empty );
}
// Shows a native alert with two buttons
public static void showAlert( string title, string message, string positiveButton, string negativeButton )
{
if( Application.platform != RuntimePlatform.Android )
return;
_plugin.Call( "showAlert", title, message, positiveButton, negativeButton );
}
// Shows an alert with a text prompt embedded in it
public static void showAlertPrompt( string title, string message, string promptHint, string promptText, string positiveButton, string negativeButton )
{
if( Application.platform != RuntimePlatform.Android )
return;
_plugin.Call( "showAlertPrompt", title, message, promptHint, promptText, positiveButton, negativeButton );
}
// Shows an alert with two text prompts embedded in it
public static void showAlertPromptWithTwoFields( string title, string message, string promptHintOne, string promptTextOne, string promptHintTwo, string promptTextTwo, string positiveButton, string negativeButton )
{
if( Application.platform != RuntimePlatform.Android )
return;
_plugin.Call( "showAlertPromptWithTwoFields", title, message, promptHintOne, promptTextOne, promptHintTwo, promptTextTwo, positiveButton, negativeButton );
}
// Shows a native progress indicator. It will not be dismissed until you call hideProgressDialog
public static void showProgressDialog( string title, string message )
{
if( Application.platform != RuntimePlatform.Android )
return;
_plugin.Call( "showProgressDialog", title, message );
}
// Hides the progress dialog
public static void hideProgressDialog()
{
if( Application.platform != RuntimePlatform.Android )
return;
_plugin.Call( "hideProgressDialog" );
}
// Shows a web view with the given url. To display local files they must be in the StreamingAssets folder and can be referenced with a url like this: "file:///android_asset/some_file.html"
public static void showWebView( string url )
{
if( Application.platform != RuntimePlatform.Android )
return;
_plugin.Call( "showWebView", url );
}
// Shows a web view without a title bar optionally disabling the back button. If you disable the back button the only way
// a user can close the web view is if the web page they are on has a link with the protocol close:// It is highly recommended
// to not disable the back button! Users are accustomed to it working as it is a default Android feature.
public static void showCustomWebView( string url, bool disableTitle, bool disableBackButton )
{
if( Application.platform != RuntimePlatform.Android )
return;
_plugin.Call( "showCustomWebView", url, disableTitle, disableBackButton );
}
// Lets the user choose an email program (or uses the default one) to send an email prefilled with the arguments
public static void showEmailComposer( string toAddress, string subject, string text, bool isHTML )
{
showEmailComposer( toAddress, subject, text, isHTML, string.Empty );
}
public static void showEmailComposer( string toAddress, string subject, string text, bool isHTML, string attachmentFilePath )
{
if( Application.platform != RuntimePlatform.Android )
return;
_plugin.Call( "showEmailComposer", toAddress, subject, text, isHTML, attachmentFilePath );
}
// Checks to see if the SMS composer is available on this device
public static bool isSMSComposerAvailable()
{
if( Application.platform != RuntimePlatform.Android )
return false;
return _plugin.Call<bool>( "isSMSComposerAvailable" );
}
// Shows the SMS composer with the body string and optional recipients
public static void showSMSComposer( string body )
{
showSMSComposer( body, null );
}
public static void showSMSComposer( string body, string[] recipients )
{
if( Application.platform != RuntimePlatform.Android )
return;
// prep the recipients if we have any
var recipientString = string.Empty;
if( recipients != null && recipients.Length > 0 )
{
recipientString = "smsto:";
foreach( var r in recipients )
recipientString += r + ";";
}
_plugin.Call( "showSMSComposer", recipientString, body );
}
// Displays the Android native share intent for sharing just an image. Any apps installed that implement image sharing will show up
// in the chooser.
public static void shareImageWithNativeShareIntent( string pathToImage, string chooserText )
{
if( Application.platform != RuntimePlatform.Android )
return;
_plugin.Call( "shareImageWithNativeShareIntent", pathToImage, chooserText );
}
// Displays the Android native share intent for sharing text with an optional image. Any apps installed that implement image sharing will show up
// in the chooser.
public static void shareWithNativeShareIntent( string text, string subject, string chooserText, string pathToImage = null )
{
if( Application.platform != RuntimePlatform.Android )
return;
_plugin.Call( "shareWithNativeShareIntent", text, subject, chooserText, pathToImage );
}
// Prompts the user to take a photo. The photoChooserSucceededEvent/photoChooserCancelledEvent will fire with the result.
public static void promptToTakePhoto( string name )
{
if( Application.platform != RuntimePlatform.Android )
return;
_plugin.Call( "promptToTakePhoto", name );
}
// Prompts the user to choose an image from the photo album
public static void promptForPictureFromAlbum( string name )
{
if( Application.platform != RuntimePlatform.Android )
return;
_plugin.Call( "promptForPictureFromAlbum", name );
}
// Prompts the user to take a video and records it saving with the given name (no file extension is needed for the name)
public static void promptToTakeVideo( string name )
{
if( Application.platform != RuntimePlatform.Android )
return;
_plugin.Call( "promptToTakeVideo", name );
}
// Saves an image to the photo gallery
public static bool saveImageToGallery( string pathToPhoto, string title )
{
if( Application.platform != RuntimePlatform.Android )
return false;
return _plugin.Call<bool>( "saveImageToGallery", pathToPhoto, title );
}
// Scales the image. Scale should be 1 to not change the size and less than 1 for smaller images.
public static void scaleImageAtPath( string pathToImage, float scale )
{
if( Application.platform != RuntimePlatform.Android )
return;
_plugin.Call( "scaleImageAtPath", pathToImage, scale );
}
// Gets the image size for the image at the given path
public static Vector2 getImageSizeAtPath( string pathToImage )
{
if( Application.platform != RuntimePlatform.Android )
return Vector2.zero;
var sizeString = _plugin.Call<string>( "getImageSizeAtPath", pathToImage );
var parts = sizeString.Split( new char[] { ',' } );
return new Vector2( int.Parse( parts[0] ), int.Parse( parts[1] ) );
}
public static void enableImmersiveMode( bool shouldEnable )
{
if( Application.platform == RuntimePlatform.Android )
_plugin.Call( "enableImmersiveMode", shouldEnable ? 1 : 0 );
}
public static void loadContacts( int startingIndex, int totalToRetrieve )
{
if( Application.platform != RuntimePlatform.Android )
return;
_plugin.Call( "loadContacts", startingIndex, totalToRetrieve );
}
#region TTS
// Starts up the TTS system
public static void initTTS()
{
if( Application.platform != RuntimePlatform.Android )
return;
_plugin.Call( "initTTS" );
}
// Tears down and destroys the TTS system
public static void teardownTTS()
{
if( Application.platform != RuntimePlatform.Android )
return;
_plugin.Call( "teardownTTS" );
}
// Speaks the text passed in
public static void speak( string text )
{
speak( text, TTSQueueMode.Add );
}
// Speaks the text passed in optionally queuing it or flushing the current queue
public static void speak( string text, TTSQueueMode queueMode )
{
if( Application.platform != RuntimePlatform.Android )
return;
_plugin.Call( "speak", text, (int)queueMode );
}
// Stops the TTS system from speaking the current text
public static void stop()
{
if( Application.platform != RuntimePlatform.Android )
return;
_plugin.Call( "stop" );
}
// Plays silence for the specified duration in milliseconds
public static void playSilence( long durationInMs, TTSQueueMode queueMode )
{
if( Application.platform != RuntimePlatform.Android )
return;
_plugin.Call( "playSilence", durationInMs, (int)queueMode );
}
// Speech pitch. 1.0 is the normal pitch, lower values lower the tone of the synthesized voice, greater values increase it.
public static void setPitch( float pitch )
{
if( Application.platform != RuntimePlatform.Android )
return;
_plugin.Call( "setPitch", pitch );
}
// Speech rate. 1.0 is the normal speech rate, lower values slow down the speech (0.5 is half the
// normal speech rate), greater values accelerate it (2.0 is twice the normal speech rate).
public static void setSpeechRate( float rate )
{
if( Application.platform != RuntimePlatform.Android )
return;
_plugin.Call( "setSpeechRate", rate );
}
#endregion
#region Ask For Review
// Allows you to set the button titles when using any of the askForReview methods below
public static void askForReviewSetButtonTitles( string remindMeLaterTitle, string dontAskAgainTitle, string rateItTitle )
{
if( Application.platform != RuntimePlatform.Android )
return;
_plugin.Call( "askForReviewSetButtonTitles", remindMeLaterTitle, dontAskAgainTitle, rateItTitle );
}
// Shows the ask for review prompt with constraints. launchesUntilPrompt will not allow the prompt to be shown until it is launched that many times.
// hoursUntilFirstPrompt is the time since the first launch that needs to expire before the prompt is shown
// hoursBetweenPrompts is the time that needs to expire since the last time the prompt was shown
// NOTE: once a user reviews your app the prompt will never show again until you call resetAskForReview
public static void askForReview( int launchesUntilPrompt, int hoursUntilFirstPrompt, int hoursBetweenPrompts, string title, string message, bool isAmazonAppStore = false )
{
if( Application.platform != RuntimePlatform.Android )
return;
if( isAmazonAppStore )
_plugin.Set<bool>( "isAmazonAppStore", true );
_plugin.Call( "askForReview", launchesUntilPrompt, hoursUntilFirstPrompt, hoursBetweenPrompts, title, message );
}
// Shows the ask for review prompt immediately unless the user pressed the dont ask again button
public static void askForReviewNow( string title, string message, bool isAmazonAppStore = false )
{
if( Application.platform != RuntimePlatform.Android )
return;
if( isAmazonAppStore )
_plugin.Set<bool>( "isAmazonAppStore", true );
_plugin.Call( "askForReviewNow", title, message );
}
// Resets all stored values such as launch count, first launch date, etc. Use this if you release a new version and want that version to be reviewed
public static void resetAskForReview()
{
if( Application.platform != RuntimePlatform.Android )
return;
_plugin.Call( "resetAskForReview" );
}
// Opens the review page in the Play Store directly. This will do not checks. It is here to allow you to make your own in-game UI for your ask for review prompt.
public static void openReviewPageInPlayStore( bool isAmazonAppStore = false )
{
if( Application.platform != RuntimePlatform.Android )
return;
if( isAmazonAppStore )
_plugin.Set<bool>( "isAmazonAppStore", true );
_plugin.Call( "openReviewPageInPlayStore" );
}
#endregion
#region Inline web view
// Shows the inline web view. The values sent are multiplied by the screens dpi on the native side. Note that Unity's input handling will still occur so make sure
// nothing is touchable that is behind the web view while it is displayed.
public static void inlineWebViewShow( string url, int x, int y, int width, int height )
{
if( Application.platform != RuntimePlatform.Android )
return;
_plugin.Call( "inlineWebViewShow", url, x, y, width, height );
}
// Closes the inline web view
public static void inlineWebViewClose()
{
if( Application.platform != RuntimePlatform.Android )
return;
_plugin.Call( "inlineWebViewClose");
}
// Sets the current url for the inline web view
public static void inlineWebViewSetUrl( string url )
{
if( Application.platform != RuntimePlatform.Android )
return;
_plugin.Call( "inlineWebViewSetUrl", url );
}
// Sets the current frame for the inline web view. The values sent are multiplied by the screens dpi on the native side.
public static void inlineWebViewSetFrame( int x, int y, int width, int height )
{
if( Application.platform != RuntimePlatform.Android )
return;
_plugin.Call( "inlineWebViewSetFrame", x, y, width, height );
}
#endregion
#region Notifications
// Schedules a notification to fire in secondsFromNow. The extraData will be returned with the notificationReceivedEvent and the int returned (requestCode) can be used to cancel the notification.
// Note that you can specify your own requestCode by just passing in an int of your choosing for the requestCode parameter.
[System.Obsolete( "Use the scheduleNotification variant that accepts a AndroidNotificationConfiguration parameter" )]
public static int scheduleNotification( long secondsFromNow, string title, string subtitle, string tickerText, string extraData, int requestCode = -1 )
{
return scheduleNotification( new AndroidNotificationConfiguration( secondsFromNow, title, subtitle, tickerText )
{
extraData = extraData,
requestCode = requestCode
});
}
// Schedules a notification to fire in secondsFromNow. The extraData will be returned with the notificationReceivedEvent and the int returned (requestCode) can be used to cancel the notification.
// Note that you can specify your own requestCode by just passing in an int of your choosing for the requestCode parameter.
[System.Obsolete( "Use the scheduleNotification variant that accepts a AndroidNotificationConfiguration parameter" )]
public static int scheduleNotification( long secondsFromNow, string title, string subtitle, string tickerText, string extraData, string smallIcon, string largeIcon, int requestCode = -1 )
{
return scheduleNotification( new AndroidNotificationConfiguration( secondsFromNow, title, subtitle, tickerText )
{
extraData = extraData,
smallIcon = smallIcon,
largeIcon = largeIcon,
requestCode = requestCode
});
}
// Schedules a notification to fire. Use the fields in the AndroidNotificationConfiguration object to configure the notification. When dealing with grouped notifications
// the groupKey must match for all notifications and you must set one notification to be the summary notification (AndroidNotificationConfiguration.isGroupSummary
// must be true). The extraData will be returned with the notificationReceivedEvent and the int returned (requestCode) can be used to cancel the notification.
// If AndroidNotificationConfiguration.cancelsNotificationId is set when the notification fires it will call cancelNotification with that notification Id.
public static int scheduleNotification( AndroidNotificationConfiguration config )
{
if( Application.platform != RuntimePlatform.Android )
return -1;
config.build();
//return _plugin.Call<int>( "scheduleNotification", config.secondsFromNow, config.title, config.subtitle, config.tickerText, config.extraData, config.smallIcon, config.largeIcon, config.requestCode, config.color, config.groupKey, config.isGroupSummary );
return _plugin.Call<int>( "scheduleNotification", Json.encode( config ) );
}
// Cancels the notification with the given notificationId
public static void cancelNotification( int notificationId )
{
if( Application.platform != RuntimePlatform.Android )
return;
_plugin.Call( "cancelNotification", notificationId );
}
// Cancels all pending notifications
public static void cancelAllNotifications()
{
if( Application.platform != RuntimePlatform.Android )
return;
_plugin.Call( "cancelAllNotifications" );
}
// Checks to see if the app was launched from a notification. If it was the normal notificationReceivedEvent will fire.
// Calling this at every launch is a good idea if you are using notifications and want the extraData. This methiod
// will return the extraData from the last used intent everytime you call it.
public static void checkForNotifications()
{
if( Application.platform != RuntimePlatform.Android )
return;
_plugin.Call( "checkForNotifications" );
}
#endregion
public class Contact
{
public string name;
public List<string> emails;
public List<string> phoneNumbers;
}
}
}
#endif
| |
/*
** $Id: lbaselib.c,v 1.191.1.6 2008/02/14 16:46:22 roberto Exp $
** Basic library
** See Copyright Notice in lua.h
*/
using System;
namespace SharpLua
{
using lua_Number = System.Double;
public partial class Lua
{
/*
** If your system does not support `stdout', you can just remove this function.
** If you need, you can define your own `print' function, following this
** model but changing `fputs' to put the strings at a proper place
** (a console window or a log file, for instance).
*/
private static int luaB_print(LuaState L)
{
int n = lua_gettop(L); /* number of arguments */
int i;
lua_getglobal(L, "tostring");
for (i = 1; i <= n; i++)
{
CharPtr s;
lua_pushvalue(L, -1); /* function to be called */
lua_pushvalue(L, i); /* value to print */
lua_call(L, 1, 1);
s = lua_tostring(L, -1); /* get result */
if (s == null)
return luaL_error(L, LUA_QL("tostring") + " must return a string to " +
LUA_QL("print"));
if (i > 1) fputs("\t", stdout);
fputs(s, stdout);
lua_pop(L, 1); /* pop result */
}
fputs("\n", stdout);
return 0;
}
private static int luaB_tonumber(LuaState L)
{
int base_ = luaL_optint(L, 2, 10);
if (base_ == 10)
{ /* standard conversion */
luaL_checkany(L, 1);
if (lua_isnumber(L, 1) != 0)
{
lua_pushnumber(L, lua_tonumber(L, 1));
return 1;
}
}
else
{
CharPtr s1 = luaL_checkstring(L, 1);
CharPtr s2;
ulong n;
luaL_argcheck(L, 2 <= base_ && base_ <= 36, 2, "base out of range");
n = strtoul(s1, out s2, base_);
if (s1 != s2)
{ /* at least one valid digit? */
while (isspace((byte)(s2[0]))) s2 = s2.next(); /* skip trailing spaces */
if (s2[0] == '\0')
{ /* no invalid trailing characters? */
lua_pushnumber(L, (lua_Number)n);
return 1;
}
}
}
lua_pushnil(L); /* else not a number */
return 1;
}
private static int luaB_error(LuaState L)
{
int level = luaL_optint(L, 2, 1);
lua_settop(L, 1);
if ((lua_isstring(L, 1) != 0) && (level > 0))
{ /* add extra information? */
luaL_where(L, level);
lua_pushvalue(L, 1);
lua_concat(L, 2);
}
return lua_error(L);
}
private static int luaB_getmetatable(LuaState L)
{
luaL_checkany(L, 1);
if (lua_getmetatable(L, 1) == 0)
{
lua_pushnil(L);
return 1; /* no metatable */
}
luaL_getmetafield(L, 1, "__metatable");
return 1; /* returns either __metatable field (if present) or metatable */
}
private static int luaB_setmetatable(LuaState L)
{
int t = lua_type(L, 2);
luaL_checktype(L, 1, LUA_TTABLE);
luaL_argcheck(L, t == LUA_TNIL || t == LUA_TTABLE, 2,
"nil or table expected");
if (luaL_getmetafield(L, 1, "__metatable") != 0)
luaL_error(L, "cannot change a protected metatable");
lua_settop(L, 2);
lua_setmetatable(L, 1);
return 1;
}
private static void getfunc(LuaState L, int opt)
{
if (lua_isfunction(L, 1)) lua_pushvalue(L, 1);
else
{
lua_Debug ar = new lua_Debug();
int level = (opt != 0) ? luaL_optint(L, 1, 1) : luaL_checkint(L, 1);
luaL_argcheck(L, level >= 0, 1, "level must be non-negative");
if (lua_getstack(L, level, ar) == 0)
luaL_argerror(L, 1, "invalid level");
lua_getinfo(L, "f", ar);
if (lua_isnil(L, -1))
luaL_error(L, "no function environment for tail call at level %d",
level);
}
}
private static int luaB_getfenv(LuaState L)
{
getfunc(L, 1);
if (lua_iscfunction(L, -1)) /* is a C function? */
lua_pushvalue(L, LUA_GLOBALSINDEX); /* return the thread's global env. */
else
lua_getfenv(L, -1);
return 1;
}
private static int luaB_setfenv(LuaState L)
{
luaL_checktype(L, 2, LUA_TTABLE);
getfunc(L, 0);
lua_pushvalue(L, 2);
if ((lua_isnumber(L, 1) != 0) && (lua_tonumber(L, 1) == 0))
{
/* change environment of current thread */
lua_pushthread(L);
lua_insert(L, -2);
lua_setfenv(L, -2);
return 0;
}
else if (lua_iscfunction(L, -2) || lua_setfenv(L, -2) == 0)
luaL_error(L,
LUA_QL("setfenv") + " cannot change environment of given object");
return 1;
}
private static int luaB_rawequal(LuaState L)
{
luaL_checkany(L, 1);
luaL_checkany(L, 2);
lua_pushboolean(L, lua_rawequal(L, 1, 2));
return 1;
}
private static int luaB_rawget(LuaState L)
{
luaL_checktype(L, 1, LUA_TTABLE);
luaL_checkany(L, 2);
lua_settop(L, 2);
lua_rawget(L, 1);
return 1;
}
private static int luaB_rawset(LuaState L)
{
luaL_checktype(L, 1, LUA_TTABLE);
luaL_checkany(L, 2);
luaL_checkany(L, 3);
lua_settop(L, 3);
lua_rawset(L, 1);
return 1;
}
private static int luaB_gcinfo(LuaState L)
{
lua_pushinteger(L, lua_getgccount(L));
return 1;
}
public static readonly CharPtr[] opts = {"stop", "restart", "collect",
"count", "step", "setpause", "setstepmul", null};
public readonly static int[] optsnum = {LUA_GCSTOP, LUA_GCRESTART, LUA_GCCOLLECT,
LUA_GCCOUNT, LUA_GCSTEP, LUA_GCSETPAUSE, LUA_GCSETSTEPMUL};
private static int luaB_collectgarbage(LuaState L)
{
int o = luaL_checkoption(L, 1, "collect", opts);
int ex = luaL_optint(L, 2, 0);
int res = lua_gc(L, optsnum[o], ex);
switch (optsnum[o])
{
case LUA_GCCOUNT:
{
int b = lua_gc(L, LUA_GCCOUNTB, 0);
lua_pushnumber(L, res + ((lua_Number)b / 1024));
return 1;
}
case LUA_GCSTEP:
{
lua_pushboolean(L, res);
return 1;
}
default:
{
lua_pushnumber(L, res);
return 1;
}
}
}
private static int luaB_type(LuaState L)
{
luaL_checkany(L, 1);
lua_pushstring(L, luaL_typename(L, 1));
return 1;
}
/*
private static int luaB_next(LuaState L)
{
luaL_checktype(L, 1, LUA_TTABLE);
lua_settop(L, 2); // create a 2nd argument if there isn't one
if (lua_next(L, 1) != 0)
return 2;
else
{
lua_pushnil(L);
return 1;
}
}
private static int luaB_pairs(LuaState L)
{
luaL_checktype(L, 1, LUA_TTABLE);
lua_pushvalue(L, lua_upvalueindex(1)); // return generator,
lua_pushvalue(L, 1); // state,
lua_pushnil(L); // and initial value
return 3;
}
private static int ipairsaux(LuaState L)
{
int i = luaL_checkint(L, 2);
luaL_checktype(L, 1, LUA_TTABLE);
i++; // next value
lua_pushinteger(L, i);
lua_rawgeti(L, 1, i);
return (lua_isnil(L, -1)) ? 0 : 2;
}
*/
static int pairsmeta(LuaState L, CharPtr method, bool iszero, lua_CFunction iter)
{
if (luaL_getmetafield(L, 1, method) == 0)
{ /* no metamethod? */
luaL_checktype(L, 1, LUA_TTABLE); /* argument must be a table */
lua_pushcfunction(L, iter); /* will return generator, */
lua_pushvalue(L, 1); /* state, */
if (iszero)
lua_pushinteger(L, 0); /* and initial value */
else lua_pushnil(L);
}
else
{
lua_pushvalue(L, 1); /* argument 'self' to metamethod */
lua_call(L, 1, 3); /* get 3 values from metamethod */
}
return 3;
}
static int luaB_next(LuaState L)
{
luaL_checktype(L, 1, LUA_TTABLE);
lua_settop(L, 2); /* create a 2nd argument if there isn't one */
if (lua_next(L, 1) == 1)
return 2;
else
{
lua_pushnil(L);
return 1;
}
}
static int luaB_pairs(LuaState L)
{
return pairsmeta(L, new CharPtr("__pairs"), false, luaB_next);
}
static int ipairsaux(LuaState L)
{
int i = luaL_checkint(L, 2);
luaL_checktype(L, 1, LUA_TTABLE);
i++; /* next value */
lua_pushinteger(L, i);
lua_rawgeti(L, 1, i);
return (lua_isnil(L, -1)) ? 1 : 2;
}
static int luaB_ipairs(LuaState L)
{
return pairsmeta(L, "__ipairs", true, ipairsaux);
}
/*
private static int luaB_ipairs(LuaState L)
{
luaL_checktype(L, 1, LUA_TTABLE);
lua_pushvalue(L, lua_upvalueindex(1)); // return generator,
lua_pushvalue(L, 1); // state,
lua_pushinteger(L, 0); // and initial value
return 3;
}
*/
private static int load_aux(LuaState L, int status)
{
if (status == 0) /* OK? */
return 1;
else
{
lua_pushnil(L);
lua_insert(L, -2); /* put before error message */
return 2; /* return nil plus error message */
}
}
private static int luaB_loadstring(LuaState L)
{
uint l;
CharPtr s = luaL_checklstring(L, 1, out l);
CharPtr chunkname = luaL_optstring(L, 2, s);
return load_aux(L, luaL_loadbuffer(L, s, l, chunkname));
}
private static int luaB_loadfile(LuaState L)
{
CharPtr fname = luaL_optstring(L, 1, null);
return load_aux(L, luaL_loadfile(L, fname));
}
/*
** Reader for generic `load' function: `lua_load' uses the
** stack for internal stuff, so the reader cannot change the
** stack top. Instead, it keeps its resulting string in a
** reserved slot inside the stack.
*/
private static CharPtr generic_reader(LuaState L, object ud, out uint size)
{
//(void)ud; /* to avoid warnings */
luaL_checkstack(L, 2, "too many nested functions");
lua_pushvalue(L, 1); /* get function */
lua_call(L, 0, 1); /* call it */
if (lua_isnil(L, -1))
{
size = 0;
return null;
}
else if (lua_isstring(L, -1) != 0)
{
lua_replace(L, 3); /* save string in a reserved stack slot */
return lua_tolstring(L, 3, out size);
}
else
{
size = 0;
luaL_error(L, "reader function must return a string");
}
return null; /* to avoid warnings */
}
private static int luaB_load(LuaState L)
{
int status;
CharPtr cname = luaL_optstring(L, 2, "=(load)");
luaL_checktype(L, 1, LUA_TFUNCTION);
lua_settop(L, 3); /* function, eventual name, plus one reserved slot */
status = lua_load(L, generic_reader, null, cname);
return load_aux(L, status);
}
private static int luaB_dofile(LuaState L)
{
CharPtr fname = luaL_optstring(L, 1, null);
int n = lua_gettop(L);
if (luaL_loadfile(L, fname) != 0) lua_error(L);
lua_call(L, 0, LUA_MULTRET);
return lua_gettop(L) - n;
}
private static int luaB_assert(LuaState L)
{
luaL_checkany(L, 1);
if (lua_toboolean(L, 1) == 0)
return luaL_error(L, "%s", luaL_optstring(L, 2, "assertion failed!"));
return lua_gettop(L);
}
private static int luaB_unpack(LuaState L)
{
int i, e, n;
luaL_checktype(L, 1, LUA_TTABLE);
i = luaL_optint(L, 2, 1);
e = luaL_opt_integer(L, luaL_checkint, 3, luaL_getn(L, 1));
if (i > e) return 0; /* empty range */
n = e - i + 1; /* number of elements */
if (n <= 0 || (lua_checkstack(L, n) == 0)) /* n <= 0 means arith. overflow */
return luaL_error(L, "too many results to unpack");
lua_rawgeti(L, 1, i); /* push arg[i] (avoiding overflow problems) */
while (i++ < e) /* push arg[i + 1...e] */
lua_rawgeti(L, 1, i);
return n;
}
private static int luaB_select(LuaState L)
{
int n = lua_gettop(L);
if (lua_type(L, 1) == LUA_TSTRING && lua_tostring(L, 1)[0] == '#')
{
lua_pushinteger(L, n - 1);
return 1;
}
else
{
int i = luaL_checkint(L, 1);
if (i < 0) i = n + i;
else if (i > n) i = n;
luaL_argcheck(L, 1 <= i, 1, "index out of range");
return n - i;
}
}
private static int luaB_pcall(LuaState L)
{
int status;
luaL_checkany(L, 1);
status = lua_pcall(L, lua_gettop(L) - 1, LUA_MULTRET, 0);
lua_pushboolean(L, (status == 0) ? 1 : 0);
lua_insert(L, 1);
return lua_gettop(L); /* return status + all results */
}
private static int luaB_xpcall(LuaState L)
{
int status;
luaL_checkany(L, 2);
lua_settop(L, 2);
lua_insert(L, 1); /* put error function under function to be called */
status = lua_pcall(L, 0, LUA_MULTRET, 1);
lua_pushboolean(L, (status == 0) ? 1 : 0);
lua_replace(L, 1);
return lua_gettop(L); /* return status + all results */
}
private static int luaB_tostring(LuaState L)
{
luaL_checkany(L, 1);
if (luaL_callmeta(L, 1, "__tostring") != 0) /* is there a metafield? */
return 1; /* use its value */
switch (lua_type(L, 1))
{
case LUA_TNUMBER:
lua_pushstring(L, lua_tostring(L, 1));
break;
case LUA_TSTRING:
lua_pushvalue(L, 1);
break;
case LUA_TBOOLEAN:
lua_pushstring(L, (lua_toboolean(L, 1) != 0 ? "true" : "false"));
break;
case LUA_TNIL:
lua_pushliteral(L, "nil");
break;
default:
lua_pushfstring(L, "%s: %p", luaL_typename(L, 1), lua_topointer(L, 1));
break;
}
return 1;
}
public static int luaB_rawlen(LuaState L)
{
int t = lua_type(L, 1);
luaL_argcheck(L, t == LUA_TTABLE || t == LUA_TSTRING, 1,
"table or string expected");
lua_pushinteger(L, (int)lua_objlen(L, 1));
return 1;
}
private static int luaB_newproxy(LuaState L)
{
lua_settop(L, 1);
lua_newuserdata(L, 0); /* create proxy */
if (lua_toboolean(L, 1) == 0)
return 1; /* no metatable */
else if (lua_isboolean(L, 1))
{
lua_newtable(L); /* create a new metatable `m' ... */
lua_pushvalue(L, -1); /* ... and mark `m' as a valid metatable */
lua_pushboolean(L, 1);
lua_rawset(L, lua_upvalueindex(1)); /* weaktable[m] = true */
}
else
{
int validproxy = 0; /* to check if weaktable[metatable(u)] == true */
if (lua_getmetatable(L, 1) != 0)
{
lua_rawget(L, lua_upvalueindex(1));
validproxy = lua_toboolean(L, -1);
lua_pop(L, 1); /* remove value */
}
luaL_argcheck(L, validproxy != 0, 1, "boolean or proxy expected");
lua_getmetatable(L, 1); /* metatable is valid; get it */
}
lua_setmetatable(L, 2);
return 1;
}
/// <summary>
/// Waits milliseconds. If the second arg is a bool and true, it waits seconds
/// </summary>
/// <param name="L"></param>
/// <returns></returns>
static int luaB_wait(LuaState L)
{
int wait = -1;
wait = luaL_optint(L, 1, 25);
if (lua_isboolean(L, 2))
{
if (lua_toboolean(L, 2) == 1)
wait *= 1000;
}
System.Threading.Thread.Sleep(wait);
lua_pushinteger(L, wait);
return 1;
}
private readonly static luaL_Reg[] base_funcs = {
new luaL_Reg("assert", luaB_assert),
new luaL_Reg("collectgarbage", luaB_collectgarbage),
new luaL_Reg("dofile", luaB_dofile),
new luaL_Reg("error", luaB_error),
new luaL_Reg("gcinfo", luaB_gcinfo),
new luaL_Reg("getfenv", luaB_getfenv),
new luaL_Reg("getmetatable", luaB_getmetatable),
new luaL_Reg("loadfile", luaB_loadfile),
new luaL_Reg("load", luaB_load),
new luaL_Reg("loadstring", luaB_loadstring),
new luaL_Reg("next", luaB_next),
new luaL_Reg("pcall", luaB_pcall),
new luaL_Reg("print", luaB_print),
new luaL_Reg("rawlen", luaB_rawlen),
new luaL_Reg("rawequal", luaB_rawequal),
new luaL_Reg("rawget", luaB_rawget),
new luaL_Reg("rawset", luaB_rawset),
new luaL_Reg("select", luaB_select),
new luaL_Reg("setfenv", luaB_setfenv),
new luaL_Reg("setmetatable", luaB_setmetatable),
new luaL_Reg("tonumber", luaB_tonumber),
new luaL_Reg("tostring", luaB_tostring),
new luaL_Reg("type", luaB_type),
new luaL_Reg("unpack", luaB_unpack),
new luaL_Reg("xpcall", luaB_xpcall),
new luaL_Reg("decompile", decompileFunction),
new luaL_Reg("wait", luaB_wait),
new luaL_Reg("sleep", luaB_wait),
new luaL_Reg("pairs", luaB_pairs),
new luaL_Reg("ipairs", luaB_ipairs),
new luaL_Reg(null, null)
};
/*
** {======================================================
** Coroutine library
** =======================================================
*/
public const int CO_RUN = 0; /* running */
public const int CO_SUS = 1; /* suspended */
public const int CO_NOR = 2; /* 'normal' (it resumed another coroutine) */
public const int CO_DEAD = 3;
private static readonly string[] statnames = { "running", "suspended", "normal", "dead" };
private static int costatus(LuaState L, LuaState co)
{
if (L == co) return CO_RUN;
switch (lua_status(co))
{
case LUA_YIELD:
return CO_SUS;
case 0:
{
lua_Debug ar = new lua_Debug();
if (lua_getstack(co, 0, ar) > 0) /* does it have frames? */
return CO_NOR; /* it is running */
else if (lua_gettop(co) == 0)
return CO_DEAD;
else
return CO_SUS; /* initial state */
}
default: /* some error occured */
return CO_DEAD;
}
}
private static int luaB_costatus(LuaState L)
{
LuaState co = lua_tothread(L, 1);
luaL_argcheck(L, co != null, 1, "coroutine expected");
lua_pushstring(L, statnames[costatus(L, co)]);
return 1;
}
private static int auxresume(LuaState L, LuaState co, int narg)
{
int status = costatus(L, co);
if (lua_checkstack(co, narg) == 0)
luaL_error(L, "too many arguments to resume");
if (status != CO_SUS)
{
lua_pushfstring(L, "cannot resume %s coroutine", statnames[status]);
return -1; /* error flag */
}
lua_xmove(L, co, narg);
lua_setlevel(L, co);
status = lua_resume(co, narg);
if (status == 0 || status == LUA_YIELD)
{
int nres = lua_gettop(co);
if (lua_checkstack(L, nres + 1) == 0)
luaL_error(L, "too many results to resume");
lua_xmove(co, L, nres); /* move yielded values */
return nres;
}
else
{
lua_xmove(co, L, 1); /* move error message */
return -1; /* error flag */
}
}
private static int luaB_coresume(LuaState L)
{
LuaState co = lua_tothread(L, 1);
int r;
luaL_argcheck(L, co != null, 1, "coroutine expected");
r = auxresume(L, co, lua_gettop(L) - 1);
if (r < 0)
{
lua_pushboolean(L, 0);
lua_insert(L, -2);
return 2; /* return false + error message */
}
else
{
lua_pushboolean(L, 1);
lua_insert(L, -(r + 1));
return r + 1; /* return true + `resume' returns */
}
}
private static int luaB_auxwrap(LuaState L)
{
LuaState co = lua_tothread(L, lua_upvalueindex(1));
int r = auxresume(L, co, lua_gettop(L));
if (r < 0)
{
if (lua_isstring(L, -1) != 0)
{ /* error object is a string? */
luaL_where(L, 1); /* add extra info */
lua_insert(L, -2);
lua_concat(L, 2);
}
lua_error(L); /* propagate error */
}
return r;
}
private static int luaB_cocreate(LuaState L)
{
LuaState NL = lua_newthread(L);
luaL_argcheck(L, lua_isfunction(L, 1) && !lua_iscfunction(L, 1), 1,
"Lua function expected");
lua_pushvalue(L, 1); /* move function to top */
lua_xmove(L, NL, 1); /* move function from L to NL */
return 1;
}
private static int luaB_cowrap(LuaState L)
{
luaB_cocreate(L);
lua_pushcclosure(L, luaB_auxwrap, 1);
return 1;
}
private static int luaB_yield(LuaState L)
{
return lua_yield(L, lua_gettop(L));
}
private static int luaB_corunning(LuaState L)
{
if (lua_pushthread(L) != 0)
lua_pushnil(L); /* main thread is not a coroutine */
return 1;
}
private readonly static luaL_Reg[] co_funcs = {
new luaL_Reg("create", luaB_cocreate),
new luaL_Reg("resume", luaB_coresume),
new luaL_Reg("running", luaB_corunning),
new luaL_Reg("status", luaB_costatus),
new luaL_Reg("wrap", luaB_cowrap),
new luaL_Reg("yield", luaB_yield),
new luaL_Reg(null, null)
};
/* }====================================================== */
private static void auxopen(LuaState L, CharPtr name,
lua_CFunction f, lua_CFunction u)
{
lua_pushcfunction(L, u);
lua_pushcclosure(L, f, 1);
lua_setfield(L, -2, name);
}
public static int decompileFunction(LuaState L)
{
Decompiler.Decompiler d = new Decompiler.Decompiler();
Lua.Proto p = Pget(L, 1);
if (p == null)
{
lua_pushstring(L, "not a Lua function");
return 1;
}
string s = d.Decompile(p);
//Console.WriteLine(s);
lua_pushstring(L, s);
return 1;
}
static Lua.Proto Pget(Lua.LuaState L, int i)
{
if (Lua.lua_isuserdata(L, i) == 1)
return (Lua.Proto)Lua.lua_touserdata(L, i);
if (!Lua.lua_isfunction(L, i) || Lua.lua_iscfunction(L, i))
{
return null;
//Lua.luaL_typerror(L, i, "Lua function");
}
return ((Lua.Closure)Lua.lua_topointer(L, i)).l.p;
}
private static void base_open(LuaState L)
{
/* set global _G */
lua_pushvalue(L, LUA_GLOBALSINDEX);
lua_setglobal(L, "_G");
/* open lib into global table */
luaL_register(L, "_G", base_funcs);
lua_pushliteral(L, LUA_VERSION);
lua_setglobal(L, "_VERSION"); /* set global _VERSION */
/* `ipairs' and `pairs' need auxliliary functions as upvalues */
//auxopen(L, "ipairs", luaB_ipairs, ipairsaux);
//auxopen(L, "pairs", luaB_pairs, luaB_next);
/* `newproxy' needs a weaktable as upvalue */
lua_createtable(L, 0, 1); /* new table `w' */
lua_pushvalue(L, -1); /* `w' will be its own metatable */
lua_setmetatable(L, -2);
lua_pushliteral(L, "kv");
lua_setfield(L, -2, "__mode"); /* metatable(w).__mode = "kv" */
lua_pushcclosure(L, luaB_newproxy, 1);
lua_setglobal(L, "newproxy"); /* set global `newproxy' */
}
public static int luaopen_base(LuaState L)
{
base_open(L);
luaL_register(L, LUA_COLIBNAME, co_funcs);
return 2;
}
}
}
| |
using ICSharpCode.SharpZipLib.Encryption;
using System;
using System.IO;
using System.Security.Cryptography;
namespace ICSharpCode.SharpZipLib.Zip.Compression.Streams
{
/// <summary>
/// A special stream deflating or compressing the bytes that are
/// written to it. It uses a Deflater to perform actual deflating.<br/>
/// Authors of the original java version : Tom Tromey, Jochen Hoenicke
/// </summary>
public class DeflaterOutputStream : Stream
{
#region Constructors
/// <summary>
/// Creates a new DeflaterOutputStream with a default Deflater and default buffer size.
/// </summary>
/// <param name="baseOutputStream">
/// the output stream where deflated output should be written.
/// </param>
public DeflaterOutputStream(Stream baseOutputStream)
: this(baseOutputStream, new Deflater(), 512)
{
}
/// <summary>
/// Creates a new DeflaterOutputStream with the given Deflater and
/// default buffer size.
/// </summary>
/// <param name="baseOutputStream">
/// the output stream where deflated output should be written.
/// </param>
/// <param name="deflater">
/// the underlying deflater.
/// </param>
public DeflaterOutputStream(Stream baseOutputStream, Deflater deflater)
: this(baseOutputStream, deflater, 512)
{
}
/// <summary>
/// Creates a new DeflaterOutputStream with the given Deflater and
/// buffer size.
/// </summary>
/// <param name="baseOutputStream">
/// The output stream where deflated output is written.
/// </param>
/// <param name="deflater">
/// The underlying deflater to use
/// </param>
/// <param name="bufferSize">
/// The buffer size in bytes to use when deflating (minimum value 512)
/// </param>
/// <exception cref="ArgumentOutOfRangeException">
/// bufsize is less than or equal to zero.
/// </exception>
/// <exception cref="ArgumentException">
/// baseOutputStream does not support writing
/// </exception>
/// <exception cref="ArgumentNullException">
/// deflater instance is null
/// </exception>
public DeflaterOutputStream(Stream baseOutputStream, Deflater deflater, int bufferSize)
{
if (baseOutputStream == null)
{
throw new ArgumentNullException(nameof(baseOutputStream));
}
if (baseOutputStream.CanWrite == false)
{
throw new ArgumentException("Must support writing", nameof(baseOutputStream));
}
if (bufferSize < 512)
{
throw new ArgumentOutOfRangeException(nameof(bufferSize));
}
baseOutputStream_ = baseOutputStream;
buffer_ = new byte[bufferSize];
deflater_ = deflater ?? throw new ArgumentNullException(nameof(deflater));
}
#endregion Constructors
#region Public API
/// <summary>
/// Finishes the stream by calling finish() on the deflater.
/// </summary>
/// <exception cref="SharpZipBaseException">
/// Not all input is deflated
/// </exception>
public virtual void Finish()
{
deflater_.Finish();
while (!deflater_.IsFinished)
{
int len = deflater_.Deflate(buffer_, 0, buffer_.Length);
if (len <= 0)
{
break;
}
if (cryptoTransform_ != null)
{
EncryptBlock(buffer_, 0, len);
}
baseOutputStream_.Write(buffer_, 0, len);
}
if (!deflater_.IsFinished)
{
throw new SharpZipBaseException("Can't deflate all input?");
}
baseOutputStream_.Flush();
if (cryptoTransform_ != null)
{
if (cryptoTransform_ is ZipAESTransform)
{
AESAuthCode = ((ZipAESTransform)cryptoTransform_).GetAuthCode();
}
cryptoTransform_.Dispose();
cryptoTransform_ = null;
}
}
/// <summary>
/// Gets or sets a flag indicating ownership of underlying stream.
/// When the flag is true <see cref="Stream.Dispose()" /> will close the underlying stream also.
/// </summary>
/// <remarks>The default value is true.</remarks>
public bool IsStreamOwner { get; set; } = true;
/// <summary>
/// Allows client to determine if an entry can be patched after its added
/// </summary>
public bool CanPatchEntries
{
get
{
return baseOutputStream_.CanSeek;
}
}
#endregion Public API
#region Encryption
private string password;
private ICryptoTransform cryptoTransform_;
/// <summary>
/// Returns the 10 byte AUTH CODE to be appended immediately following the AES data stream.
/// </summary>
protected byte[] AESAuthCode;
/// <summary>
/// Get/set the password used for encryption.
/// </summary>
/// <remarks>When set to null or if the password is empty no encryption is performed</remarks>
public string Password
{
get
{
return password;
}
set
{
if ((value != null) && (value.Length == 0))
{
password = null;
}
else
{
password = value;
}
}
}
/// <summary>
/// Encrypt a block of data
/// </summary>
/// <param name="buffer">
/// Data to encrypt. NOTE the original contents of the buffer are lost
/// </param>
/// <param name="offset">
/// Offset of first byte in buffer to encrypt
/// </param>
/// <param name="length">
/// Number of bytes in buffer to encrypt
/// </param>
protected void EncryptBlock(byte[] buffer, int offset, int length)
{
cryptoTransform_.TransformBlock(buffer, 0, length, buffer, 0);
}
/// <summary>
/// Initializes encryption keys based on given <paramref name="password"/>.
/// </summary>
/// <param name="password">The password.</param>
protected void InitializePassword(string password)
{
var pkManaged = new PkzipClassicManaged();
byte[] key = PkzipClassic.GenerateKeys(ZipStrings.ConvertToArray(password));
cryptoTransform_ = pkManaged.CreateEncryptor(key, null);
}
/// <summary>
/// Initializes encryption keys based on given password.
/// </summary>
protected void InitializeAESPassword(ZipEntry entry, string rawPassword,
out byte[] salt, out byte[] pwdVerifier)
{
salt = new byte[entry.AESSaltLen];
// Salt needs to be cryptographically random, and unique per file
if (_aesRnd == null)
_aesRnd = RandomNumberGenerator.Create();
_aesRnd.GetBytes(salt);
int blockSize = entry.AESKeySize / 8; // bits to bytes
cryptoTransform_ = new ZipAESTransform(rawPassword, salt, blockSize, true);
pwdVerifier = ((ZipAESTransform)cryptoTransform_).PwdVerifier;
}
#endregion Encryption
#region Deflation Support
/// <summary>
/// Deflates everything in the input buffers. This will call
/// <code>def.deflate()</code> until all bytes from the input buffers
/// are processed.
/// </summary>
protected void Deflate()
{
Deflate(false);
}
private void Deflate(bool flushing)
{
while (flushing || !deflater_.IsNeedingInput)
{
int deflateCount = deflater_.Deflate(buffer_, 0, buffer_.Length);
if (deflateCount <= 0)
{
break;
}
if (cryptoTransform_ != null)
{
EncryptBlock(buffer_, 0, deflateCount);
}
baseOutputStream_.Write(buffer_, 0, deflateCount);
}
if (!deflater_.IsNeedingInput)
{
throw new SharpZipBaseException("DeflaterOutputStream can't deflate all input?");
}
}
#endregion Deflation Support
#region Stream Overrides
/// <summary>
/// Gets value indicating stream can be read from
/// </summary>
public override bool CanRead
{
get
{
return false;
}
}
/// <summary>
/// Gets a value indicating if seeking is supported for this stream
/// This property always returns false
/// </summary>
public override bool CanSeek
{
get
{
return false;
}
}
/// <summary>
/// Get value indicating if this stream supports writing
/// </summary>
public override bool CanWrite
{
get
{
return baseOutputStream_.CanWrite;
}
}
/// <summary>
/// Get current length of stream
/// </summary>
public override long Length
{
get
{
return baseOutputStream_.Length;
}
}
/// <summary>
/// Gets the current position within the stream.
/// </summary>
/// <exception cref="NotSupportedException">Any attempt to set position</exception>
public override long Position
{
get
{
return baseOutputStream_.Position;
}
set
{
throw new NotSupportedException("Position property not supported");
}
}
/// <summary>
/// Sets the current position of this stream to the given value. Not supported by this class!
/// </summary>
/// <param name="offset">The offset relative to the <paramref name="origin"/> to seek.</param>
/// <param name="origin">The <see cref="SeekOrigin"/> to seek from.</param>
/// <returns>The new position in the stream.</returns>
/// <exception cref="NotSupportedException">Any access</exception>
public override long Seek(long offset, SeekOrigin origin)
{
throw new NotSupportedException("DeflaterOutputStream Seek not supported");
}
/// <summary>
/// Sets the length of this stream to the given value. Not supported by this class!
/// </summary>
/// <param name="value">The new stream length.</param>
/// <exception cref="NotSupportedException">Any access</exception>
public override void SetLength(long value)
{
throw new NotSupportedException("DeflaterOutputStream SetLength not supported");
}
/// <summary>
/// Read a byte from stream advancing position by one
/// </summary>
/// <returns>The byte read cast to an int. THe value is -1 if at the end of the stream.</returns>
/// <exception cref="NotSupportedException">Any access</exception>
public override int ReadByte()
{
throw new NotSupportedException("DeflaterOutputStream ReadByte not supported");
}
/// <summary>
/// Read a block of bytes from stream
/// </summary>
/// <param name="buffer">The buffer to store read data in.</param>
/// <param name="offset">The offset to start storing at.</param>
/// <param name="count">The maximum number of bytes to read.</param>
/// <returns>The actual number of bytes read. Zero if end of stream is detected.</returns>
/// <exception cref="NotSupportedException">Any access</exception>
public override int Read(byte[] buffer, int offset, int count)
{
throw new NotSupportedException("DeflaterOutputStream Read not supported");
}
/// <summary>
/// Flushes the stream by calling <see cref="DeflaterOutputStream.Flush">Flush</see> on the deflater and then
/// on the underlying stream. This ensures that all bytes are flushed.
/// </summary>
public override void Flush()
{
deflater_.Flush();
Deflate(true);
baseOutputStream_.Flush();
}
/// <summary>
/// Calls <see cref="Finish"/> and closes the underlying
/// stream when <see cref="IsStreamOwner"></see> is true.
/// </summary>
protected override void Dispose(bool disposing)
{
if (!isClosed_)
{
isClosed_ = true;
try
{
Finish();
if (cryptoTransform_ != null)
{
GetAuthCodeIfAES();
cryptoTransform_.Dispose();
cryptoTransform_ = null;
}
}
finally
{
if (IsStreamOwner)
{
baseOutputStream_.Dispose();
}
}
}
}
/// <summary>
/// Get the Auth code for AES encrypted entries
/// </summary>
protected void GetAuthCodeIfAES()
{
if (cryptoTransform_ is ZipAESTransform)
{
AESAuthCode = ((ZipAESTransform)cryptoTransform_).GetAuthCode();
}
}
/// <summary>
/// Writes a single byte to the compressed output stream.
/// </summary>
/// <param name="value">
/// The byte value.
/// </param>
public override void WriteByte(byte value)
{
byte[] b = new byte[1];
b[0] = value;
Write(b, 0, 1);
}
/// <summary>
/// Writes bytes from an array to the compressed stream.
/// </summary>
/// <param name="buffer">
/// The byte array
/// </param>
/// <param name="offset">
/// The offset into the byte array where to start.
/// </param>
/// <param name="count">
/// The number of bytes to write.
/// </param>
public override void Write(byte[] buffer, int offset, int count)
{
deflater_.SetInput(buffer, offset, count);
Deflate();
}
#endregion Stream Overrides
#region Instance Fields
/// <summary>
/// This buffer is used temporarily to retrieve the bytes from the
/// deflater and write them to the underlying output stream.
/// </summary>
private byte[] buffer_;
/// <summary>
/// The deflater which is used to deflate the stream.
/// </summary>
protected Deflater deflater_;
/// <summary>
/// Base stream the deflater depends on.
/// </summary>
protected Stream baseOutputStream_;
private bool isClosed_;
#endregion Instance Fields
#region Static Fields
// Static to help ensure that multiple files within a zip will get different random salt
private static RandomNumberGenerator _aesRnd = RandomNumberGenerator.Create();
#endregion Static Fields
}
}
| |
// ***********************************************************************
// Copyright (c) 2007 Charlie Poole
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ***********************************************************************
using System;
using System.Collections.Generic;
using NUnit.Framework;
namespace NUnit.TestData.OneTimeSetUpTearDownData
{
[TestFixture]
public class SetUpAndTearDownFixture
{
public int setUpCount = 0;
public int tearDownCount = 0;
public bool throwInBaseSetUp = false;
[OneTimeSetUp]
public virtual void Init()
{
setUpCount++;
if (throwInBaseSetUp)
throw new Exception("Error in base OneTimeSetUp");
}
[OneTimeTearDown]
public virtual void Destroy()
{
tearDownCount++;
}
[Test]
public void Success(){}
[Test]
public void EvenMoreSuccess(){}
}
[TestFixture]
public class SetUpAndTearDownFixtureWithTestCases
{
public int setUpCount = 0;
public int tearDownCount = 0;
[OneTimeSetUp]
public virtual void Init()
{
setUpCount++;
}
[OneTimeTearDown]
public virtual void Destroy()
{
tearDownCount++;
}
[TestCase(1)]
[TestCase(2)]
[TestCase(3)]
[TestCase(4)]
public void Success(int i)
{
Assert.Pass("Passed with test case {0}", i);
}
}
[TestFixture]
public class SetUpAndTearDownFixtureWithTheories
{
public int setUpCount = 0;
public int tearDownCount = 0;
[OneTimeSetUp]
public virtual void Init()
{
setUpCount++;
}
[OneTimeTearDown]
public virtual void Destroy()
{
tearDownCount++;
}
public struct Data
{
public int Id { get; set; }
}
[DatapointSource]
public IEnumerable<Data> fetchAllRows()
{
yield return new Data { Id = 1 };
yield return new Data { Id = 2 };
yield return new Data { Id = 3 };
yield return new Data { Id = 4 };
}
[Theory]
public void TheoryTest(Data entry)
{
Assert.Pass("Passed with theory id {0}", entry.Id);
}
}
[TestFixture,Explicit]
public class ExplicitSetUpAndTearDownFixture
{
public int setUpCount = 0;
public int tearDownCount = 0;
[OneTimeSetUp]
public virtual void Init()
{
setUpCount++;
}
[OneTimeTearDown]
public virtual void Destroy()
{
tearDownCount++;
}
[Test]
public void Success(){}
[Test]
public void EvenMoreSuccess(){}
}
[TestFixture]
public class InheritSetUpAndTearDown : SetUpAndTearDownFixture
{
[Test]
public void AnotherTest(){}
[Test]
public void YetAnotherTest(){}
}
[TestFixture]
public class OverrideSetUpAndTearDown : SetUpAndTearDownFixture
{
public int derivedSetUpCount;
public int derivedTearDownCount;
[OneTimeSetUp]
public override void Init()
{
derivedSetUpCount++;
}
[OneTimeTearDown]
public override void Destroy()
{
derivedTearDownCount++;
}
[Test]
public void AnotherTest() { }
[Test]
public void YetAnotherTest() { }
}
[TestFixture]
public class DerivedSetUpAndTearDownFixture : SetUpAndTearDownFixture
{
public int derivedSetUpCount;
public int derivedTearDownCount;
public bool baseSetUpCalledFirst;
public bool baseTearDownCalledLast;
[OneTimeSetUp]
public void Init2()
{
derivedSetUpCount++;
baseSetUpCalledFirst = this.setUpCount > 0;
}
[OneTimeTearDown]
public void Destroy2()
{
derivedTearDownCount++;
baseTearDownCalledLast = this.tearDownCount == 0;
}
[Test]
public void AnotherTest() { }
[Test]
public void YetAnotherTest() { }
}
[TestFixture]
public class StaticSetUpAndTearDownFixture
{
public static int setUpCount = 0;
public static int tearDownCount = 0;
[OneTimeSetUp]
public static void Init()
{
setUpCount++;
}
[OneTimeTearDown]
public static void Destroy()
{
tearDownCount++;
}
[Test]
public static void MyTest() { }
}
[TestFixture]
public class DerivedStaticSetUpAndTearDownFixture : StaticSetUpAndTearDownFixture
{
public static int derivedSetUpCount;
public static int derivedTearDownCount;
public static bool baseSetUpCalledFirst;
public static bool baseTearDownCalledLast;
[OneTimeSetUp]
public static void Init2()
{
derivedSetUpCount++;
baseSetUpCalledFirst = setUpCount > 0;
}
[OneTimeTearDown]
public static void Destroy2()
{
derivedTearDownCount++;
baseTearDownCalledLast = tearDownCount == 0;
}
[Test]
public static void SomeTest() { }
}
[TestFixture]
public static class StaticClassSetUpAndTearDownFixture
{
public static int setUpCount = 0;
public static int tearDownCount = 0;
[OneTimeSetUp]
public static void Init()
{
setUpCount++;
}
[OneTimeTearDown]
public static void Destroy()
{
tearDownCount++;
}
[Test]
public static void MyTest() { }
}
[TestFixture]
public class MisbehavingFixture
{
public bool blowUpInSetUp = false;
public bool blowUpInTest = false;
public bool blowUpInTearDown = false;
public int setUpCount = 0;
public int tearDownCount = 0;
public void Reinitialize()
{
setUpCount = 0;
tearDownCount = 0;
blowUpInSetUp = false;
blowUpInTearDown = false;
}
[OneTimeSetUp]
public void BlowUpInSetUp()
{
setUpCount++;
if (blowUpInSetUp)
throw new Exception("This was thrown from fixture setup");
}
[OneTimeTearDown]
public void BlowUpInTearDown()
{
tearDownCount++;
if ( blowUpInTearDown )
throw new Exception("This was thrown from fixture teardown");
}
[Test]
public void BlowUpInTest()
{
if (blowUpInTest)
throw new Exception("This was thrown from a test");
}
}
[TestFixture]
public class ExceptionInConstructor
{
public ExceptionInConstructor()
{
throw new Exception( "This was thrown in constructor" );
}
[Test]
public void nothingToTest()
{
}
}
[TestFixture]
public class IgnoreInFixtureSetUp
{
[OneTimeSetUp]
public void SetUpCallsIgnore()
{
Assert.Ignore( "TestFixtureSetUp called Ignore" );
}
[Test]
public void nothingToTest()
{
}
}
[TestFixture]
public class SetUpAndTearDownWithTestInName
{
public int setUpCount = 0;
public int tearDownCount = 0;
[OneTimeSetUp]
public virtual void TestFixtureSetUp()
{
setUpCount++;
}
[OneTimeTearDown]
public virtual void TestFixtureTearDown()
{
tearDownCount++;
}
[Test]
public void Success(){}
[Test]
public void EvenMoreSuccess(){}
}
[TestFixture, Ignore( "Do Not Run This" )]
public class IgnoredFixture
{
public bool setupCalled = false;
public bool teardownCalled = false;
[OneTimeSetUp]
public virtual void ShouldNotRun()
{
setupCalled = true;
}
[OneTimeTearDown]
public virtual void NeitherShouldThis()
{
teardownCalled = true;
}
[Test]
public void Success(){}
[Test]
public void EvenMoreSuccess(){}
}
[TestFixture]
public class FixtureWithNoTests
{
public bool setupCalled = false;
public bool teardownCalled = false;
[OneTimeSetUp]
public virtual void Init()
{
setupCalled = true;
}
[OneTimeTearDown]
public virtual void Destroy()
{
teardownCalled = true;
}
}
[TestFixture]
public class DisposableFixture : IDisposable
{
public int disposeCalled = 0;
[Test]
public void OneTest() { }
public void Dispose()
{
disposeCalled++;
}
}
[TestFixture]
public class DisposableFixtureWithTestCases : IDisposable
{
public int disposeCalled = 0;
[TestCase(1)]
[TestCase(2)]
[TestCase(3)]
[TestCase(4)]
public void TestCaseTest(int data) { }
public void Dispose()
{
disposeCalled++;
}
}
}
| |
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
namespace Microsoft.Zelig.CodeGeneration.IR.CompilationSteps.Handlers
{
using System;
using System.Collections.Generic;
using Microsoft.Zelig.Runtime.TypeSystem;
public class WellKnownMethodHandlers
{
[CompilationSteps.PhaseFilter( typeof(Phases.HighLevelTransformations) )]
[CompilationSteps.CallToWellKnownMethodHandler( "Configuration_ExecuteApplication" )]
private static void Handle_Configuration_ExecuteApplication( PhaseExecution.NotificationContext nc )
{
CallOperator op = nc.GetOperatorAndThrowIfNotCall();
TypeSystemForCodeTransformation ts = nc.TypeSystem;
MethodRepresentation md = op.TargetMethod;
MethodRepresentation mdApp = ts.ApplicationEntryPoint;
if(md.MatchSignature( mdApp, null ))
{
op.TargetMethod = mdApp;
nc.MarkAsModified();
return;
}
if(mdApp.ThisPlusArguments.Length == 2)
{
TypeRepresentation tdArg = mdApp.ThisPlusArguments[1];
if(tdArg is ArrayReferenceTypeRepresentation)
{
if(tdArg.ContainedType == ts.WellKnownTypes.System_String)
{
Expression[] rhs = ts.AddTypePointerToArgumentsOfStaticMethod( mdApp, ts.CreateNullPointer( mdApp.ThisPlusArguments[1] ) );
CallOperator callNew = StaticCallOperator.New( op.DebugInfo, CallOperator.CallKind.Direct, mdApp, rhs );
op.SubstituteWithOperator( callNew, Operator.SubstitutionFlags.Default );
nc.MarkAsModified();
return;
}
}
}
throw TypeConsistencyErrorException.Create( "Cannot use '{0}' as an application entry point, incompatible signature", md );
}
//--//--//--//--//--//--//--//--//--//--//--//--//--//--//
[CompilationSteps.PhaseFilter( typeof(Phases.HighLevelTransformations) )]
[CompilationSteps.CallToWellKnownMethodHandler( "RuntimeHelpers_InitializeArray" )]
private static void Handle_RuntimeHelpers_InitializeArray( PhaseExecution.NotificationContext nc )
{
CallOperator op = nc.GetOperatorAndThrowIfNotCall();
ConstantExpression exConst = op.ThirdArgument as ConstantExpression;
if(exConst != null)
{
DataManager.ObjectDescriptor odHandle = (DataManager.ObjectDescriptor)exConst.Value;
DataManager.ObjectDescriptor odField = (DataManager.ObjectDescriptor)odHandle.Get( (InstanceFieldRepresentation)nc.TypeSystem.WellKnownFields.RuntimeFieldHandleImpl_m_value );
FieldRepresentation fd = (FieldRepresentation)odField.Source;
TypeSystemForCodeTransformation ts = nc.TypeSystem;
//
// Get the field, extract the default value, convert it to an array of the right type, then copy the array.
//
ArrayReferenceTypeRepresentation td = (ArrayReferenceTypeRepresentation)op.SecondArgument.Type;
ScalarTypeRepresentation tdElement = td.ContainedType as ScalarTypeRepresentation;
if(tdElement != null)
{
byte[] rawData = ts.GetDefaultValue( fd );
Type t = tdElement.ConvertToRuntimeType();
Array srcData = Array.CreateInstance( t, rawData.Length / tdElement.Size );
MethodRepresentation md = ts.WellKnownMethods.RuntimeHelpers_InitializeArray2;
Buffer.BlockCopy( rawData, 0, srcData, 0, rawData.Length );
Expression[] rhs = new Expression[] { op.FirstArgument, op.SecondArgument, ts.GenerateConstantArrayAccessor( op, td, srcData, null ) };
CallOperator callNew = StaticCallOperator.New( op.DebugInfo, CallOperator.CallKind.Direct, md, rhs );
op.SubstituteWithOperator( callNew, Operator.SubstitutionFlags.Default );
nc.MarkAsModified();
return;
}
}
throw TypeConsistencyErrorException.Create( "Unsupported array initializer in {0}", op );
}
//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//
//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//
//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//
[CompilationSteps.PhaseFilter( typeof(Phases.HighLevelTransformations) )]
[CompilationSteps.CallToWellKnownMethodHandler( "MarshalImpl_SizeOf__Type" )]
private static void Handle_MarshalImpl_SizeOf__Type( PhaseExecution.NotificationContext nc )
{
CallOperator op = nc.GetOperatorAndThrowIfNotCall();
TypeSystemForCodeTransformation ts = nc.TypeSystem;
ControlFlowGraphStateForCodeTransformation cfg = nc.CurrentCFG;
while(true)
{
SingleAssignmentOperator opDef;
VTable vTable = InferVirtualTableFromConstantTypeParameter( ts, cfg, op.SecondArgument, out opDef );
if(vTable == null)
{
break;
}
var opNew = SingleAssignmentOperator.New( op.DebugInfo, op.FirstResult, ts.CreateConstantForTypeSize( vTable.TypeInfo ) );
if(cfg.FindSingleUse( opDef.FirstResult ) == op)
{
opDef.Delete();
}
op.SubstituteWithOperator( opNew, Operator.SubstitutionFlags.Default );
nc.StopScan();
return;
}
}
//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//
//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//
//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//
[CompilationSteps.PhaseFilter( typeof(Phases.HighLevelTransformations) )]
[CompilationSteps.CallToWellKnownMethodHandler( "RuntimeHelpers_get_OffsetToStringData" )]
private static void Handle_RuntimeHelpers_get_OffsetToStringData( PhaseExecution.NotificationContext nc )
{
CallOperator op = nc.GetOperatorAndThrowIfNotCall();
TypeSystemForCodeTransformation ts = nc.TypeSystem;
var opNew = SingleAssignmentOperator.New( op.DebugInfo, op.FirstResult, ts.CreateConstantForFieldOffset( ts.WellKnownFields.StringImpl_FirstChar ) );
op.SubstituteWithOperator( opNew, Operator.SubstitutionFlags.Default );
nc.MarkAsModified();
}
//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//
//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//
//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//
[CompilationSteps.PhaseFilter( typeof(Phases.HighLevelTransformations) )]
[CompilationSteps.CallToWellKnownMethodHandler( "Object_NullCheck" )]
private static void Handle_Object_NullCheck( PhaseExecution.NotificationContext nc )
{
CallOperator op = nc.GetOperatorAndThrowIfNotCall();
TypeSystemForCodeTransformation ts = nc.TypeSystem;
NullCheckOperator opNew = NullCheckOperator.New( op.DebugInfo, op.SecondArgument );
op.SubstituteWithOperator( opNew, Operator.SubstitutionFlags.Default );
nc.MarkAsModified();
}
//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//
//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//
//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//
[CompilationSteps.CallToWellKnownMethodHandler( "Microsoft_Zelig_Runtime_AbstractMethodWrapper_AddActivationRecordEvent" )]
private static void Handle_Microsoft_Zelig_Runtime_AbstractMethodWrapper_AddActivationRecordEvent( PhaseExecution.NotificationContext nc )
{
CallOperator op = nc.GetOperatorAndThrowIfNotCall();
TypeSystemForCodeTransformation ts = nc.TypeSystem;
if(nc.IsParameterConstant( op, 1 ))
{
int ev = nc.ExtractConstantIntParameter( op, 1 );
var opNew = AddActivationRecordEventOperator.New( op.DebugInfo, (Runtime.ActivationRecordEvents)ev );
op.SubstituteWithOperator( opNew, Operator.SubstitutionFlags.Default );
nc.MarkAsModified();
}
}
//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//
//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//
//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//
[CompilationSteps.PhaseFilter( typeof(Phases.HighLevelTransformations) )]
[CompilationSteps.CustomAttributeHandler( "Microsoft_Zelig_Runtime_TypeSystem_GenerateUnsafeCastAttribute" )]
private static void Handle_GenerateUnsafeCast( PhaseExecution.NotificationContext nc ,
CustomAttributeRepresentation ca )
{
CallOperator op = nc.GetOperatorAndThrowIfNotCall();
int offset;
if(op.TargetMethod is StaticMethodRepresentation)
{
offset = 1;
}
else
{
offset = 0;
}
if(op.Arguments.Length != offset + 1)
{
throw TypeConsistencyErrorException.Create( "GenerateUnsafeCastAttribute use incompatible with signature for method '{0}'", op.TargetMethod );
}
var opNew = SingleAssignmentOperator.New( op.DebugInfo, op.FirstResult, op.Arguments[offset] );
op.SubstituteWithOperator( opNew, Operator.SubstitutionFlags.Default );
nc.MarkAsModified();
}
//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//
//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//
//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//
[CompilationSteps.PhaseFilter( typeof(Phases.ApplyConfigurationSettings) )]
[CompilationSteps.CustomAttributeHandler( "Microsoft_Zelig_Runtime_ConfigurationOptionAttribute" )]
private static void Handle_ConfigurationOption( PhaseExecution.NotificationContext nc ,
CustomAttributeRepresentation ca )
{
var cfgProv = nc.TypeSystem.GetEnvironmentService< IConfigurationProvider >();
var op = nc.CurrentOperator;
if(cfgProv != null)
{
string name = (string)ca.FixedArgsValues[0];
object val;
if(cfgProv.GetValue( name, out val ))
{
ConstantExpression ex = nc.TypeSystem.CreateConstantFromObject( val );
if(op is CallOperator)
{
op.SubstituteWithOperator( SingleAssignmentOperator.New( op.DebugInfo, op.FirstResult, ex ), Operator.SubstitutionFlags.Default );
nc.MarkAsModified();
return;
}
if(op is LoadFieldOperator)
{
op.SubstituteWithOperator( SingleAssignmentOperator.New( op.DebugInfo, op.FirstResult, ex ), Operator.SubstitutionFlags.Default );
nc.MarkAsModified();
return;
}
}
}
var call = op as CallOperator;
if(call != null)
{
nc.Phase.CallsDataBase.QueueForForcedInlining( call );
}
}
//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//
//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//
//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//
[CompilationSteps.PhaseFilter( typeof(Phases.HighLevelToMidLevelConversion) )]
[CompilationSteps.CallToWellKnownMethodHandler( "TypeSystemManager_CastToType" )]
[CompilationSteps.CallToWellKnownMethodHandler( "TypeSystemManager_CastToTypeNoThrow" )]
[CompilationSteps.CallToWellKnownMethodHandler( "TypeSystemManager_CastToSealedType" )]
[CompilationSteps.CallToWellKnownMethodHandler( "TypeSystemManager_CastToSealedTypeNoThrow" )]
private static void Handle_CastToType( PhaseExecution.NotificationContext nc )
{
CallOperator call = nc.GetOperatorAndThrowIfNotCall();
Expression exSrc = call.SecondArgument;
ConstantExpression exVTable = call.ThirdArgument as ConstantExpression;
if(exVTable != null)
{
DataManager.ObjectDescriptor od = (DataManager.ObjectDescriptor)exVTable.Value;
VTable vtable = (VTable )od.Source;
TypeRepresentation tdTarget = vtable.TypeInfo;
TypeRepresentation tdSource = exSrc.Type;
TypeRepresentation tdSource2 = nc.TypeSystem.FindSingleConcreteImplementation( tdSource );
if(tdSource2 != null && tdTarget.CanBeAssignedFrom( tdSource2, null ))
{
var opNew = SingleAssignmentOperator.New( call.DebugInfo, call.FirstResult, exSrc );
call.SubstituteWithOperator( opNew, Operator.SubstitutionFlags.Default );
nc.MarkAsModified();
}
}
}
//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//
//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//
//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//
[CompilationSteps.PhaseFilter( typeof(Phases.HighLevelTransformations) )]
[CompilationSteps.CallToWellKnownMethodHandler( "TypeImpl_GetTypeFromHandle" )]
private static void Handle_TypeImpl_GetTypeFromHandle( PhaseExecution.NotificationContext nc )
{
CallOperator op = nc.GetOperatorAndThrowIfNotCall();
TypeSystemForCodeTransformation ts = nc.TypeSystem;
ControlFlowGraphStateForCodeTransformation cfg = nc.CurrentCFG;
ConstantExpression exTd = op.SecondArgument as ConstantExpression;
if(exTd == null)
{
return;
}
DataManager.ObjectDescriptor odRuntimeTypeHandle = exTd.Value as DataManager.ObjectDescriptor;
if(odRuntimeTypeHandle == null)
{
return;
}
DataManager.ObjectDescriptor odVTable = odRuntimeTypeHandle.Get( (InstanceFieldRepresentation)ts.WellKnownFields.RuntimeTypeHandleImpl_m_value ) as DataManager.ObjectDescriptor;
if(odVTable == null)
{
return;
}
op.SubstituteWithOperator( SingleAssignmentOperator.New( op.DebugInfo, op.FirstResult, ts.CreateConstantForType( (VTable)odVTable.Source ) ), Operator.SubstitutionFlags.Default );
nc.MarkAsModified();
}
//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//
//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//
//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//
[CompilationSteps.PhaseFilter( typeof(Phases.HighLevelTransformations) )]
[CompilationSteps.CallToWellKnownMethodHandler( "ActivatorImpl_CreateInstanceInner" )]
private static void Handle_ActivatorImpl_CreateInstanceInner( PhaseExecution.NotificationContext nc )
{
CallOperator op = nc.GetOperatorAndThrowIfNotCall();
TypeSystemForCodeTransformation ts = nc.TypeSystem;
ControlFlowGraphStateForCodeTransformation cfg = nc.CurrentCFG;
//
// We need to substitute the sequence:
//
// opDef : $Temp_1[0](System.Type) = callStatic StaticMethodRepresentation(System.Type System.Type::GetTypeFromHandle(System.RuntimeTypeHandle))( <null value>, $Const(System.RuntimeTypeHandle $Object(System.RuntimeTypeHandle)) )
// op : $Temp_2[1](object) = callStatic StaticMethodRepresentation(object System.Activator::CreateInstanceInner(System.Type))( <null value>, $Temp_1[0](System.Type) )
// opUse : <target>(T) = $Temp_2[1](object) cast as T
//
// with the sequence:
//
// <target>(T) = new T;
// call <target>(T)T()
//
while(true)
{
SingleAssignmentOperator opDef;
VTable vTable = InferVirtualTableFromConstantTypeParameter( ts, cfg, op.SecondArgument, out opDef );
if(vTable == null)
{
break;
}
TypeRepresentation tdTarget = vTable.TypeInfo;
CastOperator opUse = cfg.FindSingleUse( op.FirstResult ) as CastOperator;
if(opUse == null)
{
break;
}
VariableExpression varTarget = opUse.FirstResult;
if(varTarget.Type.CanBeAssignedFrom( tdTarget, null ) == false)
{
break;
}
ConstructorMethodRepresentation mdTarget = tdTarget.FindDefaultConstructor();
if(mdTarget == null)
{
break;
}
op.AddOperatorBefore( ObjectAllocationOperator.New( op.DebugInfo, tdTarget, varTarget ) );
op.AddOperatorBefore( InstanceCallOperator .New( op.DebugInfo, CallOperator.CallKind.Direct, mdTarget, new Expression[] { varTarget }, true ) );
if(cfg.FindSingleUse( opDef.FirstResult ) == op)
{
opDef.Delete();
}
op .Delete();
opUse.Delete();
nc.StopScan();
return;
}
throw TypeConsistencyErrorException.Create( "INTERNAL ERROR: Unrecognized use of {0}", op.TargetMethod );
}
//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//
//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//
//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//
public static VTable InferVirtualTableFromConstantTypeParameter( TypeSystemForCodeTransformation ts ,
ControlFlowGraphStateForCodeTransformation cfg ,
Expression ex ,
out SingleAssignmentOperator opDef )
{
opDef = cfg.FindSingleDefinition( ex ) as SingleAssignmentOperator;
if(opDef == null)
{
return null;
}
var exType = opDef.FirstArgument as ConstantExpression;
if(exType == null)
{
return null;
}
var dt = exType.Value as TypeSystemForCodeTransformation.DelayedType;
if(dt != null)
{
return dt.VTable;
}
return null;
}
}
}
| |
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Stream.Rest;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Stream
{
public class CollectionObject
{
public string ID { get; set; }
public string UserID { get; set; }
internal GenericData _data = new GenericData();
public CollectionObject() { }
public CollectionObject(string id)
{
ID = id;
}
public T GetData<T>(string name) => _data.GetData<T>(name);
public void SetData<T>(string name, T data) => _data.SetData<T>(name, data);
public void SetData(IEnumerable<KeyValuePair<string, object>> data) => data.ForEach(x => SetData(x.Key, x.Value, null));
public void SetData<T>(string name, T data, JsonSerializer serializer) => _data.SetData<T>(name, data, serializer);
public string Ref(string collectionName) => Collections.Ref(collectionName, this);
internal JObject ToJObject()
{
var root = new JObject();
if (this.ID != null)
{
root.Add(new JProperty("id", this.ID));
}
if (this.UserID != null)
{
root.Add(new JProperty("user_id", this.UserID));
}
this._data.AddToJObject(ref root);
return root;
}
internal string ToJson()
{
var root = new JObject();
if (this.ID != null)
{
root.Add(new JProperty("id", this.ID));
}
if (this.UserID != null)
{
root.Add(new JProperty("user_id", this.UserID));
}
root.Add(new JProperty("data", this._data.ToJObject()));
return root.ToString();
}
internal static CollectionObject FromBatchJSON(JObject obj)
{
CollectionObject result = new CollectionObject();
obj.Properties().ForEach(prop =>
{
switch (prop.Name)
{
case "id": result.ID = prop.Value.Value<string>(); break;
case "user_id": result.UserID = prop.Value.Value<string>(); break;
default: result._data.SetData(prop.Name, prop.Value); break;
}
});
return result;
}
internal static CollectionObject FromJSON(JObject obj)
{
CollectionObject result = new CollectionObject();
obj.Properties().ForEach(prop =>
{
switch (prop.Name)
{
case "id": result.ID = prop.Value.Value<string>(); break;
case "user_id": result.UserID = prop.Value.Value<string>(); break;
case "data":
{
var dataObj = prop.Value as JObject;
dataObj.Properties().ForEach(p =>
{
result.SetData(p.Name, p.Value);
});
break;
}
}
});
return result;
}
}
public class Collections
{
readonly StreamClient _client;
internal Collections(StreamClient client)
{
_client = client;
}
public async Task Upsert(string collectionName, CollectionObject data)
{
await this.UpsertMany(collectionName, new CollectionObject[] { data });
}
public async Task UpsertMany(string collectionName, IEnumerable<CollectionObject> data)
{
var dataJson = new JObject(
new JProperty("data", new JObject(
new JProperty(collectionName, data.Select(x => x.ToJObject())))));
var request = this._client.BuildAppRequest("collections/", HttpMethod.POST);
request.SetJsonBody(dataJson.ToString());
var response = await this._client.MakeRequest(request);
if (response.StatusCode != System.Net.HttpStatusCode.Created)
throw StreamException.FromResponse(response);
}
public async Task<CollectionObject> Select(string collectionName, string id)
{
var result = await this.SelectMany(collectionName, new string[] { id });
return result.FirstOrDefault();
}
public async Task<IEnumerable<CollectionObject>> SelectMany(string collectionName, IEnumerable<string> ids)
{
var foreignIds = ids.Select(x => string.Format("{0}:{1}", collectionName, x));
var request = this._client.BuildAppRequest("collections/", HttpMethod.GET);
request.AddQueryParameter("foreign_ids", string.Join(",", foreignIds));
var response = await this._client.MakeRequest(request);
if (response.StatusCode == System.Net.HttpStatusCode.OK)
return Collections.GetResults(response.Content);
throw StreamException.FromResponse(response);
}
public async Task DeleteMany(string collectionName, IEnumerable<string> ids)
{
var request = this._client.BuildAppRequest("collections/", HttpMethod.DELETE);
request.AddQueryParameter("collection_name", collectionName);
request.AddQueryParameter("ids", string.Join(",", ids));
var response = await this._client.MakeRequest(request);
if (response.StatusCode != System.Net.HttpStatusCode.OK)
throw StreamException.FromResponse(response);
}
public async Task<CollectionObject> Add(string collectionName, GenericData data, string ID = null, string userID = null)
{
var collectionObject = new CollectionObject()
{
ID = ID,
UserID = userID,
_data = data,
};
var request = this._client.BuildAppRequest($"collections/{collectionName}/", HttpMethod.POST);
request.SetJsonBody(collectionObject.ToJson());
var response = await this._client.MakeRequest(request);
if (response.StatusCode != System.Net.HttpStatusCode.Created)
throw StreamException.FromResponse(response);
return CollectionObject.FromJSON(JObject.Parse(response.Content));
}
public async Task<CollectionObject> Get(string collectionName, string ID)
{
var request = this._client.BuildAppRequest($"collections/{collectionName}/{ID}/", HttpMethod.GET);
var response = await this._client.MakeRequest(request);
if (response.StatusCode != System.Net.HttpStatusCode.OK)
throw StreamException.FromResponse(response);
return CollectionObject.FromJSON(JObject.Parse(response.Content));
}
public async Task<CollectionObject> Update(string collectionName, string ID, GenericData data)
{
var dataJson = new JObject(new JProperty("data", data.ToJObject()));
var request = this._client.BuildAppRequest($"collections/{collectionName}/{ID}/", HttpMethod.PUT);
request.SetJsonBody(dataJson.ToString());
var response = await this._client.MakeRequest(request);
if (response.StatusCode != System.Net.HttpStatusCode.Created)
throw StreamException.FromResponse(response);
return CollectionObject.FromJSON(JObject.Parse(response.Content));
}
public async Task Delete(string collectionName, string ID)
{
var request = this._client.BuildAppRequest($"collections/{collectionName}/{ID}/", HttpMethod.DELETE);
var response = await this._client.MakeRequest(request);
if (response.StatusCode != System.Net.HttpStatusCode.OK)
throw StreamException.FromResponse(response);
}
public static string Ref(string collectionName, string collectionObjectID)
{
return string.Format("SO:{0}:{1}", collectionName, collectionObjectID);
}
public static string Ref(string collectionName, CollectionObject obj)
{
return Ref(collectionName, obj.ID);
}
private static IEnumerable<CollectionObject> GetResults(string json)
{
var obj = JObject.Parse(json);
var response = obj.Property("response").Value as JObject;
var data = response.Property("data").Value as JArray;
foreach (var result in data)
{
var resultObj = result as JObject;
var foreignID = resultObj.Property("foreign_id").Value.Value<string>();
var objectID = foreignID.Split(':')[1];
var objectData = resultObj.Property("data").Value as JObject;
var collectionObject = CollectionObject.FromBatchJSON(objectData);
collectionObject.ID = objectID;
yield return collectionObject;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Transactions;
using PCSComUtils.Admin.DS;
using PCSComUtils.Common;
using PCSComUtils.DataAccess;
using PCSComUtils.DataContext;
using PCSComUtils.PCSExc;
namespace PCSComUtils.Admin.BO
{
/// <summary>
/// Biz Object of ManageMenu form
/// </summary>
public class ManageMenuBO
{
private const string THIS = "PCSComUtils.Admin.BO.ManageMenuBO";
#region ManageMenuBO Members
/// <summary>
/// Insert a new record into database
/// </summary>
public void Add(object pObjectDetail)
{
throw new NotImplementedException();
}
/// <summary>
/// We need to check this menu is already have transaction or not.
/// If have transaction, unable to delete.
/// If have no transaction, delete it
/// </summary>
public void Delete(int menuId)
{
const string METHOD_NAME = THIS + ".Delete()";
try
{
using (var trans = new TransactionScope())
{
var dcPCS = new PCSDataContext(Utils.Instance.ConnectionString);
var menu = dcPCS.Sys_Menu_Entries.SingleOrDefault(m => m.Menu_EntryID == menuId);
var objRights = dcPCS.Sys_Rights.SingleOrDefault(m => m.Menu_EntryID == menuId);
var dsMenuEntry = new Sys_Menu_EntryDS();
// we need to check this menu is already have transaction or not
int intNumOfTrans = 0;
if (menu.TableName != null)
{
if (menu.TableName.Trim() != string.Empty && menu.TransNoFieldName.Trim() != string.Empty)
intNumOfTrans = dsMenuEntry.GetAllTransactions(menu);
}
// if have transaction, unable to delete
if (intNumOfTrans > 0)
throw new PCSBOException(ErrorCode.MESSAGE_COULD_NOT_DELETE_MENU, METHOD_NAME, new Exception());
// update button caption
var subMenus = dcPCS.Sys_Menu_Entries.Where(
m => m.Parent_Shortcut == menu.Shortcut && m.Button_Caption > menu.Button_Caption).OrderBy(
m => m.Button_Caption).ToList();
subMenus.ForEach(m => m.Button_Caption = m.Button_Caption - 1);
// if have no transction, delete it
if (objRights != null)
{
dcPCS.Sys_Rights.DeleteOnSubmit(objRights);
}
dcPCS.Sys_Menu_Entries.DeleteOnSubmit(menu);
// submit changes
dcPCS.SubmitChanges();
trans.Complete();
}
}
catch (SqlException ex)
{
if (ex.Errors.Count > 1)
{
if (ex.Number == ErrorCode.SQLCASCADE_PREVENT_KEYCODE)
throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex);
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex);
}
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex);
}
}
/// <summary>
/// Get the object information by ID of VO class
/// </summary>
public Sys_Menu_Entry GetMenu(int menuId)
{
PCSDataContext dataContext = new PCSDataContext(Utils.Instance.ConnectionString);
return dataContext.Sys_Menu_Entries.SingleOrDefault(m => m.Menu_EntryID == menuId);
}
/// <summary>
/// Get all right
/// </summary>
/// <returns></returns>
public List<Sys_Right> GetRightAll()
{
List<Sys_Right> list = new List<Sys_Right>();
using (var trans = new TransactionScope())
{
using (var db = new PCSDataContext(Utils.Instance.ConnectionString))
{
var l = from obj in db.Sys_Rights
orderby obj.RoleID
select obj;
if (l != null) list = l.ToList<Sys_Right>();
}
}
return list;
}
/// <summary>
/// Get all Role
/// </summary>
/// <returns></returns>
public List<Sys_Role> GetRoleAll()
{
List<Sys_Role> list = new List<Sys_Role>();
using (var trans = new TransactionScope())
{
using (var db = new PCSDataContext(Utils.Instance.ConnectionString))
{
var l = from obj in db.Sys_Roles
where obj.Name != Constants.ALL_ROLE
orderby obj.RoleID
select obj;
if (l != null) list = l.ToList<Sys_Role>();
}
}
return list;
}
/// <summary>
/// Get All menu
/// </summary>
/// <returns></returns>
public List<Sys_Menu_Entry> GetMenuAll()
{
List<Sys_Menu_Entry> list = new List<Sys_Menu_Entry>();
using (var trans = new TransactionScope())
{
using (var db = new PCSDataContext(Utils.Instance.ConnectionString))
{
var l = from obj in db.Sys_Menu_Entries
where (obj.Text_CaptionDefault != "-" && (obj.Type == (int)MenuTypeEnum.VisibleBoth || obj.Type == (int)MenuTypeEnum.InvisibleMenu))
orderby obj.Text_CaptionDefault
select obj;
if (l != null) list = l.ToList<Sys_Menu_Entry>();
}
}
return list;
}
//cuonglv
public List<Sys_Menu_Entry> GetMenuAllWithImageFields()
{
List<Sys_Menu_Entry> list = new List<Sys_Menu_Entry>();
using (var trans = new TransactionScope())
{
using (var db = new PCSDataContext(Utils.Instance.ConnectionString))
{
var l = from obj in db.Sys_Menu_Entries
orderby obj.Parent_Shortcut, obj.Button_Caption
select obj;
if (l != null) list = l.ToList<Sys_Menu_Entry>();
}
}
return list;
}
/// <summary>
/// Return the DataSet (list of record) by inputing the FieldList and Condition
/// </summary>
public void UpdateDataSet(DataSet dstData)
{
const string METHOD_NAME = THIS + ".Delete()";
try
{
using (var trans = new TransactionScope())
{
var dsMenuEntry = new Sys_Menu_EntryDS();
dsMenuEntry.UpdateDataSet(dstData);
trans.Complete();
}
}
catch (SqlException ex)
{
if (ex.Errors.Count > 1)
{
if (ex.Number == ErrorCode.SQLDUPLICATE_UNIQUE_KEYCODE)
throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex);
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex);
}
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex);
}
}
/// <summary>
/// Update data table
/// </summary>
public void UpdateDataTable(DataTable pdtbData)
{
const string METHOD_NAME = THIS + ".Delete()";
try
{
using (var trans = new TransactionScope())
{
var dsMenuEntry = new Sys_Menu_EntryDS();
dsMenuEntry.UpdateDataTable(pdtbData);
trans.Complete();
}
}
catch (SqlException ex)
{
if (ex.Errors.Count > 1)
{
if (ex.Number == ErrorCode.SQLDUPLICATE_UNIQUE_KEYCODE)
throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex);
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex);
}
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex);
}
}
/// <summary>
/// Update into Database
/// </summary>
public void Update(Sys_Menu_Entry menu, int roleId)
{
const string METHOD_NAME = THIS + ".Delete()";
try
{
using (var trans = new TransactionScope())
{
PCSDataContext dataContext = new PCSDataContext(Utils.Instance.ConnectionString);
var current = dataContext.Sys_Menu_Entries.SingleOrDefault(m => m.Menu_EntryID == menu.Menu_EntryID);
if (current != null)
{
current.Button_Caption = menu.Button_Caption;
current.CollapsedImage = menu.CollapsedImage;
current.Description = menu.Description;
current.ExpandedImage = menu.ExpandedImage;
current.FormLoad = menu.FormLoad;
current.IsTransaction = menu.IsTransaction;
current.IsUserCreated = menu.IsUserCreated;
current.Parent_Child = menu.Parent_Child;
current.Parent_Shortcut = menu.Parent_Shortcut;
current.Prefix = menu.Prefix;
current.ReportID = menu.ReportID;
current.Shortcut = menu.Shortcut;
current.TableName = menu.TableName;
current.Text_Caption_EN_US = menu.Text_Caption_EN_US;
current.Text_Caption_JA_JP = menu.Text_Caption_JA_JP;
current.Text_Caption_VI_VN = menu.Text_Caption_VI_VN;
current.Text_Caption_Language_Default = menu.Text_Caption_Language_Default;
current.Text_CaptionDefault = menu.Text_CaptionDefault;
current.TransFormat = menu.TransFormat;
current.TransNoFieldName = menu.TransNoFieldName;
current.Type = menu.Type;
}
else
{
dataContext.Sys_Menu_Entries.InsertOnSubmit(menu);
// create right for new menu
var right = new Sys_Right
{
Menu_EntryID = menu.Menu_EntryID,
Permission = 1,
RoleID = roleId
};
dataContext.Sys_Rights.InsertOnSubmit(right);
}
dataContext.SubmitChanges();
trans.Complete();
}
}
catch (SqlException ex)
{
if (ex.Errors.Count > 1)
{
if (ex.Number == ErrorCode.SQLDUPLICATE_UNIQUE_KEYCODE)
throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex);
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex);
}
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex);
}
}
/// <summary>
/// Add new menu to database and return id
/// </summary>
/// <param name="menu">SysMenuEntry object</param>
/// <param name="roleId">Role ID</param>
/// <returns>New ID</returns>
public int AddAndReturnID(Sys_Menu_Entry menu, int roleId)
{
const string METHOD_NAME = THIS + ".AddAndReturnID()";
try
{
using (var trans = new TransactionScope())
{
PCSDataContext dataContext = new PCSDataContext(Utils.Instance.ConnectionString);
dataContext.Sys_Menu_Entries.InsertOnSubmit(menu);
// update button caption
var subMenus = dataContext.Sys_Menu_Entries.Where(
m => m.Parent_Shortcut == menu.Parent_Shortcut && m.Button_Caption > menu.Button_Caption).OrderBy(
m => m.Button_Caption).ToList();
subMenus.ForEach(m => m.Button_Caption = m.Button_Caption + 1);
// save new menu
menu.Button_Caption += 1;
// submit changes
dataContext.SubmitChanges();
// create right for new menu
var right = new Sys_Right
{
Menu_EntryID = menu.Menu_EntryID,
Permission = 1,
RoleID = roleId
};
dataContext.Sys_Rights.InsertOnSubmit(right);
dataContext.SubmitChanges();
trans.Complete();
return menu.Menu_EntryID;
}
}
catch (SqlException ex)
{
if (ex.Errors.Count > 1)
{
if (ex.Number == ErrorCode.SQLDUPLICATE_UNIQUE_KEYCODE)
throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex);
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex);
}
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex);
}
}
/// <summary>
/// Get menu by its short cut
/// </summary>
/// <param name="pstrShortCut">Shortcut of menu</param>
/// <returns>SysMenu</returns>
public object GetMenuByShortCut(string pstrShortCut)
{
var dsMenuEntry = new Sys_Menu_EntryDS();
return dsMenuEntry.GetMenuByShortCut(pstrShortCut);
}
public void UpdateTrans(Sys_Menu_Entry menu, int roleId)
{
const string METHOD_NAME = THIS + ".Delete()";
try
{
using (var trans = new TransactionScope())
{
PCSDataContext dataContext = new PCSDataContext(Utils.Instance.ConnectionString);
var current = dataContext.Sys_Menu_Entries.SingleOrDefault(m => m.Menu_EntryID == menu.Menu_EntryID);
if (current != null)
{
current.Text_Caption_EN_US = menu.Text_Caption_EN_US;
current.Text_Caption_JA_JP = menu.Text_Caption_JA_JP;
current.Text_Caption_VI_VN = menu.Text_Caption_VI_VN;
current.Text_CaptionDefault = menu.Text_CaptionDefault;
current.Prefix = menu.Prefix;
current.TransFormat = menu.TransFormat;
}
else
{
dataContext.Sys_Menu_Entries.InsertOnSubmit(menu);
// create right for new menu
var right = new Sys_Right
{
Menu_EntryID = menu.Menu_EntryID,
Permission = 1,
RoleID = roleId
};
dataContext.Sys_Rights.InsertOnSubmit(right);
}
dataContext.SubmitChanges();
trans.Complete();
}
}
catch (SqlException ex)
{
if (ex.Errors.Count > 1)
{
if (ex.Number == ErrorCode.SQLDUPLICATE_UNIQUE_KEYCODE)
throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex);
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex);
}
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex);
}
}
#endregion
}
}
| |
// Prexonite
//
// Copyright (c) 2014, Christian Klauser
// 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.
// The names of the 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.
#region
using System;
using System.Globalization;
using System.Reflection;
using Prexonite.Compiler.Cil;
using NoDebug = System.Diagnostics.DebuggerStepThroughAttribute;
#endregion
namespace Prexonite.Types
{
[PTypeLiteral("Char")]
public class CharPType : PType, ICilCompilerAware
{
#region Singleton
private static readonly CharPType instance;
public static CharPType Instance
{
[NoDebug]
get { return instance; }
}
static CharPType()
{
instance = new CharPType();
}
[NoDebug]
private CharPType()
{
}
#endregion
#region Static: CreatePValue
public static PValue CreatePValue(char c)
{
return new PValue(c, instance);
}
public static PValue CreatePValue(int i)
{
return new PValue((char) i, instance);
}
#endregion
#region PType interface
public override bool TryConstruct(StackContext sctx, PValue[] args, out PValue result)
{
char c;
result = null;
if (sctx == null)
throw new ArgumentNullException("sctx");
if (args == null)
throw new ArgumentNullException("args");
PValue v;
if (args.Length < 1 || args[0].IsNull)
{
c = '\0';
}
else if (args[0].TryConvertTo(sctx, Char, out v))
{
c = (char) v.Value;
}
else if (args[0].TryConvertTo(sctx, Int, false, out v))
{
c = (char) (int) v.Value;
}
else
{
c = '\0';
}
result = c;
return true;
}
public override bool TryDynamicCall(
StackContext sctx,
PValue subject,
PValue[] args,
PCall call,
string id,
out PValue result)
{
if (sctx == null)
throw new ArgumentNullException("sctx");
if (subject == null)
throw new ArgumentNullException("subject");
if (args == null)
throw new ArgumentNullException("args");
if (id == null)
id = "";
var c = (char) subject.Value;
CultureInfo ci;
switch (id.ToLowerInvariant())
{
case "getnumericvalue":
result = System.Char.GetNumericValue(c);
break;
case "getunicodecategory":
result = sctx.CreateNativePValue(System.Char.GetUnicodeCategory(c));
break;
case "iscontrol":
result = System.Char.IsControl(c);
break;
case "isdigit":
result = System.Char.IsDigit(c);
break;
case "ishighsurrogate":
result = System.Char.IsHighSurrogate(c);
break;
case "isletter":
result = System.Char.IsLetter(c);
break;
case "isletterordigit":
result = System.Char.IsLetterOrDigit(c);
break;
case "islower":
result = System.Char.IsLower(c);
break;
case "islowsurrogate":
result = System.Char.IsLowSurrogate(c);
break;
case "isnumber":
result = System.Char.IsNumber(c);
break;
case "ispunctuation":
result = System.Char.IsPunctuation(c);
break;
case "issurrogate":
result = System.Char.IsSurrogate(c);
break;
case "issymbol":
result = System.Char.IsSymbol(c);
break;
case "isupper":
result = System.Char.IsUpper(c);
break;
case "iswhitespace":
result = System.Char.IsWhiteSpace(c);
break;
case "tolower":
if (args.Length > 0 && args[0].TryConvertTo(sctx, false, out ci))
result = System.Char.ToLower(c, ci);
else
result = System.Char.ToLower(c);
break;
case "toupper":
if (args.Length > 0 && args[0].TryConvertTo(sctx, false, out ci))
result = System.Char.ToUpper(c, ci);
else
result = System.Char.ToUpper(c);
break;
case "tolowerinvariant":
result = System.Char.ToLowerInvariant(c);
break;
case "toupperinvariant":
result = System.Char.ToUpperInvariant(c);
break;
case "length":
result = 1;
break;
default:
//Try CLR dynamic call
var clrint = Object[subject.ClrType];
if (!clrint.TryDynamicCall(sctx, subject, args, call, id, out result))
result = null;
break;
}
return result != null;
}
public override bool TryStaticCall(
StackContext sctx, PValue[] args, PCall call, string id, out PValue result)
{
//Try CLR static call
var clrint = Object[typeof (int)];
if (clrint.TryStaticCall(sctx, args, call, id, out result))
return true;
return false;
}
protected override bool InternalConvertTo(
StackContext sctx, PValue subject, PType target, bool useExplicit, out PValue result)
{
if (sctx == null)
throw new ArgumentNullException("sctx");
if (subject == null || subject.IsNull)
throw new ArgumentNullException("subject");
if ((object) target == null)
throw new ArgumentNullException("target");
result = null;
var c = (char) subject.Value;
var bi = target.ToBuiltIn();
if (useExplicit)
{
switch (bi)
{
case BuiltIn.Object:
var clrType = ((ObjectPType) target).ClrType;
switch (Type.GetTypeCode(clrType))
{
case TypeCode.Byte:
result = new PValue(Convert.ToByte(c), target);
break;
}
break;
}
}
if (result == null)
{
switch (bi)
{
case BuiltIn.Int:
result = (int) c;
break;
case BuiltIn.String:
result = c.ToString();
break;
case BuiltIn.Object:
var clrType = ((ObjectPType) target).ClrType;
switch (Type.GetTypeCode(clrType))
{
case TypeCode.Char:
result = new PValue(c, target);
break;
case TypeCode.Int32:
result = new PValue((Int32) c, target);
break;
}
break;
}
}
return result != null;
}
protected override bool InternalConvertFrom(
StackContext sctx, PValue subject, bool useExplicit, out PValue result)
{
if (sctx == null)
throw new ArgumentNullException("sctx");
if (subject == null || subject.IsNull)
throw new ArgumentNullException("subject");
var source = subject.Type;
var bi = source.ToBuiltIn();
result = null;
if (useExplicit)
{
switch (bi)
{
case BuiltIn.String:
var s = (string) subject.Value;
if (s.Length == 1)
result = s[0];
break;
}
}
if (result == null)
{
switch (bi)
{
case BuiltIn.Int:
result = (char) (int) subject.Value;
break;
case BuiltIn.Object:
var clrType = ((ObjectPType) source).ClrType;
var tc = Type.GetTypeCode(clrType);
switch (tc)
{
case TypeCode.Byte:
result = (char) subject.Value;
break;
case TypeCode.Int32:
result = (char) (Int32) subject.Value;
break;
case TypeCode.Char:
result = (char) subject.Value;
break;
}
if (result == null &&
source.TryConvertTo(sctx, subject, Object[typeof (char)], useExplicit,
out result))
{
result = (char) result.Value;
}
break;
}
}
return result != null;
}
protected override bool InternalIsEqual(PType otherType)
{
return otherType is CharPType;
}
private const int _hashcode = 361633961;
public const string Literal = "Char";
public override int GetHashCode()
{
return _hashcode;
}
public override string ToString()
{
return Literal;
}
#endregion
#region Operators
public override PValue CreatePValue(object value)
{
return Convert.ToChar(value);
}
private bool _tryConvert(StackContext sctx, PValue pv, out char c)
{
c = '\0';
switch (pv.Type.ToBuiltIn())
{
case BuiltIn.Char:
c = (char) pv.Value;
return true;
case BuiltIn.Int:
c = (char) (int) pv.Value;
return true;
case BuiltIn.Null:
return true;
case BuiltIn.String:
var s = (string) pv.Value;
if (s.Length == 1)
{
c = s[0];
return true;
}
else
{
return false;
}
case BuiltIn.Object:
if (pv.TryConvertTo(sctx, Char, false, out pv))
return _tryConvert(sctx, pv, out c);
else
return false;
case BuiltIn.Structure:
case BuiltIn.Hash:
case BuiltIn.List:
case BuiltIn.Bool:
case BuiltIn.None:
case BuiltIn.Real:
return false;
default:
throw new ArgumentOutOfRangeException();
}
}
public override bool Equality(StackContext sctx, PValue leftOperand, PValue rightOperand,
out PValue result)
{
result = null;
char left;
char right;
if (_tryConvert(sctx, leftOperand, out left) &&
_tryConvert(sctx, rightOperand, out right))
result = left == right;
return result != null;
}
public override bool Inequality(StackContext sctx, PValue leftOperand, PValue rightOperand,
out PValue result)
{
char left;
char right;
if (!(_tryConvert(sctx, leftOperand, out left)) ||
!(_tryConvert(sctx, rightOperand, out right)))
result = false;
else
result = left != right;
return true;
}
#endregion
#region ICilCompilerAware Members
/// <summary>
/// Asses qualification and preferences for a certain instruction.
/// </summary>
/// <param name = "ins">The instruction that is about to be compiled.</param>
/// <returns>A set of <see cref = "CompilationFlags" />.</returns>
CompilationFlags ICilCompilerAware.CheckQualification(Instruction ins)
{
return CompilationFlags.PrefersCustomImplementation;
}
private static readonly MethodInfo _getCharPType =
typeof (PType).GetProperty("Char").GetGetMethod();
/// <summary>
/// Provides a custom compiler routine for emitting CIL byte code for a specific instruction.
/// </summary>
/// <param name = "state">The compiler state.</param>
/// <param name = "ins">The instruction to compile.</param>
void ICilCompilerAware.ImplementInCil(CompilerState state, Instruction ins)
{
state.EmitCall(_getCharPType);
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
namespace Hydra.Framework.ImageProcessing.Analysis.Maths
{
//
//**********************************************************************
/// <summary>
/// Fourier Transformation
/// </summary>
//**********************************************************************
//
public class FourierTransform
{
#region Private Member Variables
//
//**********************************************************************
/// <summary>
/// Minimum Length
/// </summary>
//**********************************************************************
//
private const int minLength_m = 2;
//
//**********************************************************************
/// <summary>
/// Maximum Length
/// </summary>
//**********************************************************************
//
private const int maxLength_m = 16384;
//
//**********************************************************************
/// <summary>
/// Minimum number of Bits
/// </summary>
//**********************************************************************
//
private const int minBits_m = 1;
//
//**********************************************************************
/// <summary>
/// Maximum number of Bits
/// </summary>
//**********************************************************************
//
private const int maxBits_m = 14;
//
//**********************************************************************
/// <summary>
/// Reverse the Bit Order
/// </summary>
//**********************************************************************
//
private static int[][] reversedBits_m = new int[maxBits_m][];
//
//**********************************************************************
/// <summary>
/// Complex Rotation object
/// </summary>
//**********************************************************************
//
private static Complex[,][] complexRotation_m = new Complex[maxBits_m, 2][];
#endregion
#region Statics
//
//**********************************************************************
/// <summary>
/// One dimensional Discrete Fourier Transform
/// </summary>
/// <param name="data">The data.</param>
/// <param name="direction">The direction.</param>
//**********************************************************************
//
public static void DFT (Complex[] data, FourierDirectionType direction)
{
int n = data.Length;
double arg, cos, sin;
Complex[] dst = new Complex[n];
//
// for each destination element
//
for (int i = 0; i < n; i++)
{
dst[i] = Complex.Zero;
arg = - (int) direction * 2.0 * System.Math.PI * (double) i / (double) n;
//
// sum source elements
//
for (int j = 0; j < n; j++)
{
cos = System.Math.Cos(j * arg);
sin = System.Math.Sin(j * arg);
dst[i].Re += (float) (data[j].Re * cos - data[j].Im * sin);
dst[i].Im += (float) (data[j].Re * sin + data[j].Im * cos);
}
}
//
// copy elements
//
if (direction == FourierDirectionType.Forward)
{
//
// divide also for forward transform
//
for (int i = 0; i < n; i++)
{
data[i].Re = dst[i].Re / n;
data[i].Im = dst[i].Im / n;
}
}
else
{
for (int i = 0; i < n; i++)
{
data[i].Re = dst[i].Re;
data[i].Im = dst[i].Im;
}
}
}
//
//**********************************************************************
/// <summary>
/// Two dimensional Discrete Fourier Transform
/// </summary>
/// <param name="data">The data.</param>
/// <param name="direction">The direction.</param>
//**********************************************************************
//
public static void DFT2(Complex[,] data, FourierDirectionType direction)
{
int n = data.GetLength(0); // rows
int m = data.GetLength(1); // columns
double arg, cos, sin;
Complex[] dst = new Complex[System.Math.Max(n, m)];
//
// process rows
//
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
dst[j] = Complex.Zero;
arg = - (int) direction * 2.0 * System.Math.PI * (double) j / (double) m;
//
// sum source elements
//
for (int k = 0; k < m; k++)
{
cos = System.Math.Cos(k * arg);
sin = System.Math.Sin(k * arg);
dst[j].Re += (float) (data[i, k].Re * cos - data[i, k].Im * sin);
dst[j].Im += (float) (data[i, k].Re * sin + data[i, k].Im * cos);
}
}
//
// copy elements
//
if (direction == FourierDirectionType.Forward)
{
//
// divide also for forward transform
//
for (int j = 0; j < m; j++)
{
data[i, j].Re = dst[j].Re / m;
data[i, j].Im = dst[j].Im / m;
}
}
else
{
for (int j = 0; j < m; j++)
{
data[i, j].Re = dst[j].Re;
data[i, j].Im = dst[j].Im;
}
}
}
//
// process columns
//
for (int j = 0; j < m; j++)
{
for (int i = 0; i < n; i++)
{
dst[i] = Complex.Zero;
arg = - (int) direction * 2.0 * System.Math.PI * (double) i / (double) n;
//
// sum source elements
//
for (int k = 0; k < n; k++)
{
cos = System.Math.Cos(k * arg);
sin = System.Math.Sin(k * arg);
dst[i].Re += (float) (data[k, j].Re * cos - data[k, j].Im * sin);
dst[i].Im += (float) (data[k, j].Re * sin + data[k, j].Im * cos);
}
}
//
// copy elements
//
if (direction == FourierDirectionType.Forward)
{
//
// divide also for forward transform
//
for (int i = 0; i < n; i++)
{
data[i, j].Re = dst[i].Re / n;
data[i, j].Im = dst[i].Im / n;
}
}
else
{
for (int i = 0; i < n; i++)
{
data[i, j].Re = dst[i].Re;
data[i, j].Im = dst[i].Im;
}
}
}
}
//
//**********************************************************************
/// <summary>
/// One dimensional Fast Fourier Transform
/// </summary>
/// <param name="data">The data.</param>
/// <param name="direction">The direction.</param>
//**********************************************************************
//
public static void FFT(Complex[] data, FourierDirectionType direction)
{
int n = data.Length;
int m = Tools.Log2(n);
//
// reorder data first
//
ReorderData(data);
//
// compute FFT
//
int tn = 1, tm;
for (int k = 1; k <= m; k++)
{
Complex[] rotation = FourierTransform.GetComplexRotation(k, direction);
tm = tn;
tn <<= 1;
for (int i = 0; i < tm; i++)
{
Complex t = rotation[i];
for (int even = i; even < n; even += tn)
{
int odd = even + tm;
Complex ce = data[even];
Complex co = data[odd];
float tr = co.Re * t.Re - co.Im * t.Im;
float ti = co.Re * t.Im + co.Im * t.Re;
data[even].Re += tr;
data[even].Im += ti;
data[odd].Re = ce.Re - tr;
data[odd].Im = ce.Im - ti;
}
}
}
if (direction == FourierDirectionType.Forward)
{
for (int i = 0; i < n; i++)
{
data[i].Re /= (float) n;
data[i].Im /= (float) n;
}
}
}
//
//**********************************************************************
/// <summary>
/// Two dimensional Fast Fourier Transform
/// </summary>
/// <param name="data">The data.</param>
/// <param name="direction">The direction.</param>
//**********************************************************************
//
public static void FFT2(Complex[,] data, FourierDirectionType direction)
{
int k = data.GetLength(0);
int n = data.GetLength(1);
//
// check data size
//
if ((!Tools.IsPowerOf2(k)) || (!Tools.IsPowerOf2(n)) ||
(k < minLength_m) || (k > maxLength_m) ||
(n < minLength_m) || (n > maxLength_m))
{
throw new ArgumentException();
}
//
// process rows
//
Complex[] row = new Complex[n];
for (int i = 0; i < k; i++)
{
//
// copy row
//
for (int j = 0; j < n; j++)
row[j] = data[i, j];
//
// transform it
//
FourierTransform.FFT(row, direction);
//
// copy back
//
for (int j = 0; j < n; j++)
data[i, j] = row[j];
}
//
// process columns
//
Complex[] col = new Complex[k];
for (int j = 0; j < n; j++)
{
//
// copy column
//
for (int i = 0; i < k; i++)
col[i] = data[i, j];
//
// transform it
//
FourierTransform.FFT(col, direction);
//
// copy back
//
for (int i = 0; i < k; i++)
data[i, j] = col[i];
}
}
#endregion
#region Private Methods
//
//**********************************************************************
/// <summary>
/// Get array, indicating which data members should be swapped before FFT
/// </summary>
/// <param name="numberOfBits">The number of bits.</param>
/// <returns></returns>
//**********************************************************************
//
private static int[] GetReversedBits(int numberOfBits)
{
if ((numberOfBits < minBits_m) || (numberOfBits > maxBits_m))
throw new ArgumentOutOfRangeException();
//
// check if the array is already calculated
//
if (reversedBits_m[numberOfBits - 1] == null)
{
int n = Tools.Pow2(numberOfBits);
int[] rBits = new int[n];
//
// calculate the array
//
for (int i = 0; i < n; i++)
{
int oldBits = i;
int newBits = 0;
for (int j = 0; j < numberOfBits; j++)
{
newBits = (newBits << 1) | (oldBits & 1);
oldBits = (oldBits >> 1);
}
rBits[i] = newBits;
}
reversedBits_m[numberOfBits - 1] = rBits;
}
return reversedBits_m[numberOfBits - 1];
}
//
//**********************************************************************
/// <summary>
/// Get rotation of complex number
/// </summary>
/// <param name="numberOfBits">The number of bits.</param>
/// <param name="direction">The direction.</param>
/// <returns></returns>
//**********************************************************************
//
private static Complex[] GetComplexRotation(int numberOfBits, FourierDirectionType direction)
{
int directionIndex = (direction == FourierDirectionType.Forward) ? 0 : 1;
//
// check if the array is already calculated
//
if (complexRotation_m[numberOfBits - 1, directionIndex] == null)
{
int n = 1 << (numberOfBits - 1);
float uR = 1.0f;
float uI = 0.0f;
double angle = System.Math.PI / n * (int) direction;
float wR = (float) System.Math.Cos(angle);
float wI = (float) System.Math.Sin(angle);
float t;
Complex[] rotation = new Complex[n];
for (int i = 0; i < n; i++ )
{
rotation[i] = new Complex(uR, uI);
t = uR * wI + uI * wR;
uR = uR * wR - uI * wI;
uI = t;
}
complexRotation_m[numberOfBits - 1, directionIndex] = rotation;
}
return complexRotation_m[numberOfBits - 1, directionIndex];
}
//
//**********************************************************************
/// <summary>
/// Reorder data for FFT using
/// </summary>
/// <param name="data">The data.</param>
//**********************************************************************
//
private static void ReorderData(Complex[] data)
{
int len = data.Length;
//
// check data length
//
if ((len < minLength_m) ||
(len > maxLength_m) ||
(!Tools.IsPowerOf2(len)))
{
throw new ArgumentException();
}
int[] rBits = GetReversedBits(Tools.Log2(len));
for (int i = 0; i < len; i++)
{
int s = rBits[i];
if (s > i)
{
Complex t = data[i];
data[i] = data[s];
data[s] = t;
}
}
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.Xml.Serialization
{
using System.Reflection;
using System.Collections;
using System.IO;
using System.Xml.Schema;
using System;
using System.Text;
using System.Threading;
using System.Globalization;
using System.Security;
using System.Diagnostics;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using Hashtable = System.Collections.IDictionary;
using XmlSchema = System.ServiceModel.Dispatcher.XmlSchemaConstants;
using XmlDeserializationEvents = System.Object;
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializerImplementation"]/*' />
///<internalonly/>
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public abstract class XmlSerializerImplementation
{
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializerImplementation.Reader"]/*' />
public virtual XmlSerializationReader Reader { get { throw new NotSupportedException(); } }
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializerImplementation.Writer"]/*' />
public virtual XmlSerializationWriter Writer { get { throw new NotSupportedException(); } }
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializerImplementation.ReadMethods"]/*' />
public virtual IDictionary ReadMethods { get { throw new NotSupportedException(); } }
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializerImplementation.WriteMethods"]/*' />
public virtual IDictionary WriteMethods { get { throw new NotSupportedException(); } }
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializerImplementation.TypedSerializers"]/*' />
public virtual IDictionary TypedSerializers { get { throw new NotSupportedException(); } }
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializerImplementation.CanSerialize"]/*' />
public virtual bool CanSerialize(Type type) { throw new NotSupportedException(); }
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializerImplementation.GetSerializer"]/*' />
public virtual XmlSerializer GetSerializer(Type type) { throw new NotSupportedException(); }
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public class XmlSerializer
{
private TempAssembly _tempAssembly;
private bool _typedSerializer;
private Type _primitiveType;
private XmlMapping _mapping;
private XmlDeserializationEvents _events = new XmlDeserializationEvents();
#if NET_NATIVE
public string DefaultNamespace = null;
private XmlSerializer innerSerializer;
private readonly Type rootType;
#endif
private static TempAssemblyCache s_cache = new TempAssemblyCache();
private static volatile XmlSerializerNamespaces s_defaultNamespaces;
private static XmlSerializerNamespaces DefaultNamespaces
{
get
{
if (s_defaultNamespaces == null)
{
XmlSerializerNamespaces nss = new XmlSerializerNamespaces();
nss.AddInternal("xsi", XmlSchema.InstanceNamespace);
nss.AddInternal("xsd", XmlSchema.Namespace);
if (s_defaultNamespaces == null)
{
s_defaultNamespaces = nss;
}
}
return s_defaultNamespaces;
}
}
private static readonly Dictionary<Type, Dictionary<XmlSerializerMappingKey, XmlSerializer>> s_xmlSerializerTable = new Dictionary<Type, Dictionary<XmlSerializerMappingKey, XmlSerializer>>();
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.XmlSerializer8"]/*' />
///<internalonly/>
protected XmlSerializer()
{
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.XmlSerializer"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public XmlSerializer(Type type, XmlAttributeOverrides overrides, Type[] extraTypes, XmlRootAttribute root, string defaultNamespace) :
this(type, overrides, extraTypes, root, defaultNamespace, null, null)
{
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.XmlSerializer2"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public XmlSerializer(Type type, XmlRootAttribute root) : this(type, null, Array.Empty<Type>(), root, null, null, null)
{
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.XmlSerializer3"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
#if !NET_NATIVE
public XmlSerializer(Type type, Type[] extraTypes) : this(type, null, extraTypes, null, null, null, null)
#else
public XmlSerializer(Type type, Type[] extraTypes) : this(type)
#endif // NET_NATIVE
{
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.XmlSerializer4"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public XmlSerializer(Type type, XmlAttributeOverrides overrides) : this(type, overrides, Array.Empty<Type>(), null, null, null, null)
{
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.XmlSerializer5"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public XmlSerializer(XmlTypeMapping xmlTypeMapping)
{
_tempAssembly = GenerateTempAssembly(xmlTypeMapping);
_mapping = xmlTypeMapping;
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.XmlSerializer6"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public XmlSerializer(Type type) : this(type, (string)null)
{
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.XmlSerializer1"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public XmlSerializer(Type type, string defaultNamespace)
{
if (type == null)
throw new ArgumentNullException(nameof(type));
#if NET_NATIVE
this.DefaultNamespace = defaultNamespace;
rootType = type;
#endif
_mapping = GetKnownMapping(type, defaultNamespace);
if (_mapping != null)
{
_primitiveType = type;
return;
}
#if !NET_NATIVE
_tempAssembly = s_cache[defaultNamespace, type];
if (_tempAssembly == null)
{
lock (s_cache)
{
_tempAssembly = s_cache[defaultNamespace, type];
if (_tempAssembly == null)
{
{
// need to reflect and generate new serialization assembly
XmlReflectionImporter importer = new XmlReflectionImporter(defaultNamespace);
_mapping = importer.ImportTypeMapping(type, null, defaultNamespace);
_tempAssembly = GenerateTempAssembly(_mapping, type, defaultNamespace);
}
}
s_cache.Add(defaultNamespace, type, _tempAssembly);
}
}
if (_mapping == null)
{
_mapping = XmlReflectionImporter.GetTopLevelMapping(type, defaultNamespace);
}
#else
XmlSerializerImplementation contract = GetXmlSerializerContractFromGeneratedAssembly();
if (contract != null)
{
this.innerSerializer = contract.GetSerializer(type);
}
#endif
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.XmlSerializer7"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
internal XmlSerializer(Type type, XmlAttributeOverrides overrides, Type[] extraTypes, XmlRootAttribute root, string defaultNamespace, object location, object evidence)
{
#if NET_NATIVE
throw new PlatformNotSupportedException();
#else
if (type == null)
throw new ArgumentNullException(nameof(type));
XmlReflectionImporter importer = new XmlReflectionImporter(overrides, defaultNamespace);
if (extraTypes != null)
{
for (int i = 0; i < extraTypes.Length; i++)
importer.IncludeType(extraTypes[i]);
}
_mapping = importer.ImportTypeMapping(type, root, defaultNamespace);
_tempAssembly = GenerateTempAssembly(_mapping, type, defaultNamespace);
#endif
}
internal static TempAssembly GenerateTempAssembly(XmlMapping xmlMapping)
{
return GenerateTempAssembly(xmlMapping, null, null);
}
internal static TempAssembly GenerateTempAssembly(XmlMapping xmlMapping, Type type, string defaultNamespace)
{
if (xmlMapping == null)
throw new ArgumentNullException(nameof(xmlMapping));
return new TempAssembly(new XmlMapping[] { xmlMapping }, new Type[] { type }, defaultNamespace, null, null);
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Serialize"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public void Serialize(TextWriter textWriter, object o)
{
Serialize(textWriter, o, null);
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Serialize1"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public void Serialize(TextWriter textWriter, object o, XmlSerializerNamespaces namespaces)
{
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
settings.IndentChars = " ";
XmlWriter xmlWriter = XmlWriter.Create(textWriter, settings);
Serialize(xmlWriter, o, namespaces);
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Serialize2"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public void Serialize(Stream stream, object o)
{
Serialize(stream, o, null);
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Serialize3"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public void Serialize(Stream stream, object o, XmlSerializerNamespaces namespaces)
{
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
settings.IndentChars = " ";
XmlWriter xmlWriter = XmlWriter.Create(stream, settings);
Serialize(xmlWriter, o, namespaces);
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Serialize4"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public void Serialize(XmlWriter xmlWriter, object o)
{
Serialize(xmlWriter, o, null);
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Serialize5"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public void Serialize(XmlWriter xmlWriter, object o, XmlSerializerNamespaces namespaces)
{
Serialize(xmlWriter, o, namespaces, null);
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Serialize6"]/*' />
internal void Serialize(XmlWriter xmlWriter, object o, XmlSerializerNamespaces namespaces, string encodingStyle)
{
Serialize(xmlWriter, o, namespaces, encodingStyle, null);
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Serialize6"]/*' />
internal void Serialize(XmlWriter xmlWriter, object o, XmlSerializerNamespaces namespaces, string encodingStyle, string id)
{
try
{
if (_primitiveType != null)
{
SerializePrimitive(xmlWriter, o, namespaces);
}
#if !NET_NATIVE
else if (_tempAssembly == null || _typedSerializer)
{
XmlSerializationWriter writer = CreateWriter();
writer.Init(xmlWriter, namespaces == null || namespaces.Count == 0 ? DefaultNamespaces : namespaces, encodingStyle, id, _tempAssembly);
try
{
Serialize(o, writer);
}
finally
{
writer.Dispose();
}
}
else
_tempAssembly.InvokeWriter(_mapping, xmlWriter, o, namespaces == null || namespaces.Count == 0 ? DefaultNamespaces : namespaces, encodingStyle, id);
#else
else
{
if (this.innerSerializer == null)
{
throw new InvalidOperationException(SR.Format(SR.Xml_MissingSerializationCodeException, this.rootType, typeof(XmlSerializer).Name));
}
if (!string.IsNullOrEmpty(this.DefaultNamespace))
{
this.innerSerializer.DefaultNamespace = this.DefaultNamespace;
}
XmlSerializationWriter writer = this.innerSerializer.CreateWriter();
writer.Init(xmlWriter, namespaces == null || namespaces.Count == 0 ? DefaultNamespaces : namespaces, encodingStyle, id);
try
{
this.innerSerializer.Serialize(o, writer);
}
finally
{
writer.Dispose();
}
}
#endif
}
catch (Exception e)
{
if (e is TargetInvocationException)
e = e.InnerException;
throw new InvalidOperationException(SR.XmlGenError, e);
}
xmlWriter.Flush();
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Deserialize"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public object Deserialize(Stream stream)
{
XmlReaderSettings settings = new XmlReaderSettings();
// WhitespaceHandling.Significant means that you only want events for *significant* whitespace
// resulting from elements marked with xml:space="preserve". All other whitespace
// (ie. XmlNodeType.Whitespace), deemed as insignificant for the XML infoset, is not
// reported by the reader. This mode corresponds to XmlReaderSettings.IgnoreWhitespace = true.
settings.IgnoreWhitespace = true;
settings.DtdProcessing = (DtdProcessing)2; /* DtdProcessing.Parse */
// Normalization = true, that's the default for the readers created with XmlReader.Create().
// The XmlTextReader has as default a non-conformant mode according to the XML spec
// which skips some of the required processing for new lines, hence the need for the explicit
// Normalization = true. The mode is no-longer exposed on XmlReader.Create()
XmlReader xmlReader = XmlReader.Create(stream, settings);
return Deserialize(xmlReader, null);
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Deserialize1"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public object Deserialize(TextReader textReader)
{
XmlReaderSettings settings = new XmlReaderSettings();
// WhitespaceHandling.Significant means that you only want events for *significant* whitespace
// resulting from elements marked with xml:space="preserve". All other whitespace
// (ie. XmlNodeType.Whitespace), deemed as insignificant for the XML infoset, is not
// reported by the reader. This mode corresponds to XmlReaderSettings.IgnoreWhitespace = true.
settings.IgnoreWhitespace = true;
settings.DtdProcessing = (DtdProcessing)2; /* DtdProcessing.Parse */
// Normalization = true, that's the default for the readers created with XmlReader.Create().
// The XmlTextReader has as default a non-conformant mode according to the XML spec
// which skips some of the required processing for new lines, hence the need for the explicit
// Normalization = true. The mode is no-longer exposed on XmlReader.Create()
XmlReader xmlReader = XmlReader.Create(textReader, settings);
return Deserialize(xmlReader, null);
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Deserialize2"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public object Deserialize(XmlReader xmlReader)
{
return Deserialize(xmlReader, null);
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Deserialize4"]/*' />
internal object Deserialize(XmlReader xmlReader, string encodingStyle)
{
return Deserialize(xmlReader, encodingStyle, _events);
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Deserialize5"]/*' />
internal object Deserialize(XmlReader xmlReader, string encodingStyle, XmlDeserializationEvents events)
{
try
{
if (_primitiveType != null)
{
return DeserializePrimitive(xmlReader, events);
}
#if !NET_NATIVE
else if (_tempAssembly == null || _typedSerializer)
{
XmlSerializationReader reader = CreateReader();
reader.Init(xmlReader, events, encodingStyle, _tempAssembly);
try
{
return Deserialize(reader);
}
finally
{
reader.Dispose();
}
}
else
{
return _tempAssembly.InvokeReader(_mapping, xmlReader, events, encodingStyle);
}
#else
else
{
if (this.innerSerializer == null)
{
throw new InvalidOperationException(SR.Format(SR.Xml_MissingSerializationCodeException, this.rootType, typeof(XmlSerializer).Name));
}
if (!string.IsNullOrEmpty(this.DefaultNamespace))
{
this.innerSerializer.DefaultNamespace = this.DefaultNamespace;
}
XmlSerializationReader reader = this.innerSerializer.CreateReader();
reader.Init(xmlReader, encodingStyle);
try
{
return this.innerSerializer.Deserialize(reader);
}
finally
{
reader.Dispose();
}
}
#endif
}
catch (Exception e)
{
if (e is TargetInvocationException)
e = e.InnerException;
if (xmlReader is IXmlLineInfo)
{
IXmlLineInfo lineInfo = (IXmlLineInfo)xmlReader;
throw new InvalidOperationException(SR.Format(SR.XmlSerializeErrorDetails, lineInfo.LineNumber.ToString(CultureInfo.InvariantCulture), lineInfo.LinePosition.ToString(CultureInfo.InvariantCulture)), e);
}
else
{
throw new InvalidOperationException(SR.XmlSerializeError, e);
}
}
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.CanDeserialize"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public virtual bool CanDeserialize(XmlReader xmlReader)
{
if (_primitiveType != null)
{
TypeDesc typeDesc = (TypeDesc)TypeScope.PrimtiveTypes[_primitiveType];
return xmlReader.IsStartElement(typeDesc.DataType.Name, string.Empty);
}
#if !NET_NATIVE
else if (_tempAssembly != null)
{
return _tempAssembly.CanRead(_mapping, xmlReader);
}
else
{
return false;
}
#else
if (this.innerSerializer == null)
{
return false;
}
return this.innerSerializer.CanDeserialize(xmlReader);
#endif
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.FromMappings"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static XmlSerializer[] FromMappings(XmlMapping[] mappings)
{
return FromMappings(mappings, (Type)null);
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.FromMappings1"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static XmlSerializer[] FromMappings(XmlMapping[] mappings, Type type)
{
if (mappings == null || mappings.Length == 0) return Array.Empty<XmlSerializer>();
XmlSerializerImplementation contract = null;
TempAssembly tempAssembly = null;
{
if (XmlMapping.IsShallow(mappings))
{
return Array.Empty<XmlSerializer>();
}
else
{
if (type == null)
{
tempAssembly = new TempAssembly(mappings, new Type[] { type }, null, null, null);
XmlSerializer[] serializers = new XmlSerializer[mappings.Length];
contract = tempAssembly.Contract;
for (int i = 0; i < serializers.Length; i++)
{
serializers[i] = (XmlSerializer)contract.TypedSerializers[mappings[i].Key];
serializers[i].SetTempAssembly(tempAssembly, mappings[i]);
}
return serializers;
}
else
{
// Use XmlSerializer cache when the type is not null.
return GetSerializersFromCache(mappings, type);
}
}
}
}
private static XmlSerializer[] GetSerializersFromCache(XmlMapping[] mappings, Type type)
{
XmlSerializer[] serializers = new XmlSerializer[mappings.Length];
Dictionary<XmlSerializerMappingKey, XmlSerializer> typedMappingTable = null;
lock (s_xmlSerializerTable)
{
if (!s_xmlSerializerTable.TryGetValue(type, out typedMappingTable))
{
typedMappingTable = new Dictionary<XmlSerializerMappingKey, XmlSerializer>();
s_xmlSerializerTable[type] = typedMappingTable;
}
}
lock (typedMappingTable)
{
var pendingKeys = new Dictionary<XmlSerializerMappingKey, int>();
for (int i = 0; i < mappings.Length; i++)
{
XmlSerializerMappingKey mappingKey = new XmlSerializerMappingKey(mappings[i]);
if (!typedMappingTable.TryGetValue(mappingKey, out serializers[i]))
{
pendingKeys.Add(mappingKey, i);
}
}
if (pendingKeys.Count > 0)
{
XmlMapping[] pendingMappings = new XmlMapping[pendingKeys.Count];
int index = 0;
foreach (XmlSerializerMappingKey mappingKey in pendingKeys.Keys)
{
pendingMappings[index++] = mappingKey.Mapping;
}
TempAssembly tempAssembly = new TempAssembly(pendingMappings, new Type[] { type }, null, null, null);
XmlSerializerImplementation contract = tempAssembly.Contract;
foreach (XmlSerializerMappingKey mappingKey in pendingKeys.Keys)
{
index = pendingKeys[mappingKey];
serializers[index] = (XmlSerializer)contract.TypedSerializers[mappingKey.Mapping.Key];
serializers[index].SetTempAssembly(tempAssembly, mappingKey.Mapping);
typedMappingTable[mappingKey] = serializers[index];
}
}
}
return serializers;
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.FromTypes"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static XmlSerializer[] FromTypes(Type[] types)
{
if (types == null)
return Array.Empty<XmlSerializer>();
#if NET_NATIVE
var serializers = new XmlSerializer[types.Length];
for (int i = 0; i < types.Length; i++)
{
serializers[i] = new XmlSerializer(types[i]);
}
return serializers;
#else
XmlReflectionImporter importer = new XmlReflectionImporter();
XmlTypeMapping[] mappings = new XmlTypeMapping[types.Length];
for (int i = 0; i < types.Length; i++)
{
mappings[i] = importer.ImportTypeMapping(types[i]);
}
return FromMappings(mappings);
#endif
}
#if NET_NATIVE
// this the global XML serializer contract introduced for multi-file
private static XmlSerializerImplementation xmlSerializerContract;
internal static XmlSerializerImplementation GetXmlSerializerContractFromGeneratedAssembly()
{
// hack to pull in SetXmlSerializerContract which is only referenced from the
// code injected by MainMethodInjector transform
// there's probably also a way to do this via [DependencyReductionRoot],
// but I can't get the compiler to find that...
if (xmlSerializerContract == null)
SetXmlSerializerContract(null);
// this method body used to be rewritten by an IL transform
// with the restructuring for multi-file, it has become a regular method
return xmlSerializerContract;
}
public static void SetXmlSerializerContract(XmlSerializerImplementation xmlSerializerImplementation)
{
xmlSerializerContract = xmlSerializerImplementation;
}
#endif
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.CreateReader"]/*' />
///<internalonly/>
protected virtual XmlSerializationReader CreateReader() { throw new PlatformNotSupportedException(); }
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Deserialize4"]/*' />
///<internalonly/>
protected virtual object Deserialize(XmlSerializationReader reader) { throw new PlatformNotSupportedException(); }
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.CreateWriter"]/*' />
///<internalonly/>
protected virtual XmlSerializationWriter CreateWriter() { throw new PlatformNotSupportedException(); }
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Serialize7"]/*' />
///<internalonly/>
protected virtual void Serialize(object o, XmlSerializationWriter writer) { throw new PlatformNotSupportedException(); }
internal void SetTempAssembly(TempAssembly tempAssembly, XmlMapping mapping)
{
_tempAssembly = tempAssembly;
_mapping = mapping;
_typedSerializer = true;
}
private static XmlTypeMapping GetKnownMapping(Type type, string ns)
{
if (ns != null && ns != string.Empty)
return null;
TypeDesc typeDesc;
if (!TypeScope.PrimtiveTypes.TryGetValue(type, out typeDesc))
return null;
ElementAccessor element = new ElementAccessor();
element.Name = typeDesc.DataType.Name;
XmlTypeMapping mapping = new XmlTypeMapping(null, element);
mapping.SetKeyInternal(XmlMapping.GenerateKey(type, null, null));
return mapping;
}
private void SerializePrimitive(XmlWriter xmlWriter, object o, XmlSerializerNamespaces namespaces)
{
XmlSerializationPrimitiveWriter writer = new XmlSerializationPrimitiveWriter();
writer.Init(xmlWriter, namespaces, null, null, null);
switch (_primitiveType.GetTypeCode())
{
case TypeCode.String:
writer.Write_string(o);
break;
case TypeCode.Int32:
writer.Write_int(o);
break;
case TypeCode.Boolean:
writer.Write_boolean(o);
break;
case TypeCode.Int16:
writer.Write_short(o);
break;
case TypeCode.Int64:
writer.Write_long(o);
break;
case TypeCode.Single:
writer.Write_float(o);
break;
case TypeCode.Double:
writer.Write_double(o);
break;
case TypeCode.Decimal:
writer.Write_decimal(o);
break;
case TypeCode.DateTime:
writer.Write_dateTime(o);
break;
case TypeCode.Char:
writer.Write_char(o);
break;
case TypeCode.Byte:
writer.Write_unsignedByte(o);
break;
case TypeCode.SByte:
writer.Write_byte(o);
break;
case TypeCode.UInt16:
writer.Write_unsignedShort(o);
break;
case TypeCode.UInt32:
writer.Write_unsignedInt(o);
break;
case TypeCode.UInt64:
writer.Write_unsignedLong(o);
break;
default:
if (_primitiveType == typeof(XmlQualifiedName))
{
writer.Write_QName(o);
}
else if (_primitiveType == typeof(byte[]))
{
writer.Write_base64Binary(o);
}
else if (_primitiveType == typeof(Guid))
{
writer.Write_guid(o);
}
else if (_primitiveType == typeof(TimeSpan))
{
writer.Write_TimeSpan(o);
}
else
{
throw new InvalidOperationException(SR.Format(SR.XmlUnxpectedType, _primitiveType.FullName));
}
break;
}
}
private object DeserializePrimitive(XmlReader xmlReader, XmlDeserializationEvents events)
{
XmlSerializationPrimitiveReader reader = new XmlSerializationPrimitiveReader();
reader.Init(xmlReader, events, null, null);
object o;
switch (_primitiveType.GetTypeCode())
{
case TypeCode.String:
o = reader.Read_string();
break;
case TypeCode.Int32:
o = reader.Read_int();
break;
case TypeCode.Boolean:
o = reader.Read_boolean();
break;
case TypeCode.Int16:
o = reader.Read_short();
break;
case TypeCode.Int64:
o = reader.Read_long();
break;
case TypeCode.Single:
o = reader.Read_float();
break;
case TypeCode.Double:
o = reader.Read_double();
break;
case TypeCode.Decimal:
o = reader.Read_decimal();
break;
case TypeCode.DateTime:
o = reader.Read_dateTime();
break;
case TypeCode.Char:
o = reader.Read_char();
break;
case TypeCode.Byte:
o = reader.Read_unsignedByte();
break;
case TypeCode.SByte:
o = reader.Read_byte();
break;
case TypeCode.UInt16:
o = reader.Read_unsignedShort();
break;
case TypeCode.UInt32:
o = reader.Read_unsignedInt();
break;
case TypeCode.UInt64:
o = reader.Read_unsignedLong();
break;
default:
if (_primitiveType == typeof(XmlQualifiedName))
{
o = reader.Read_QName();
}
else if (_primitiveType == typeof(byte[]))
{
o = reader.Read_base64Binary();
}
else if (_primitiveType == typeof(Guid))
{
o = reader.Read_guid();
}
else if (_primitiveType == typeof(TimeSpan))
{
o = reader.Read_TimeSpan();
}
else
{
throw new InvalidOperationException(SR.Format(SR.XmlUnxpectedType, _primitiveType.FullName));
}
break;
}
return o;
}
private class XmlSerializerMappingKey
{
public XmlMapping Mapping;
public XmlSerializerMappingKey(XmlMapping mapping)
{
this.Mapping = mapping;
}
public override bool Equals(object obj)
{
XmlSerializerMappingKey other = obj as XmlSerializerMappingKey;
if (other == null)
return false;
if (this.Mapping.Key != other.Mapping.Key)
return false;
if (this.Mapping.ElementName != other.Mapping.ElementName)
return false;
if (this.Mapping.Namespace != other.Mapping.Namespace)
return false;
if (this.Mapping.IsSoap != other.Mapping.IsSoap)
return false;
return true;
}
public override int GetHashCode()
{
int hashCode = this.Mapping.IsSoap ? 0 : 1;
if (this.Mapping.Key != null)
hashCode ^= this.Mapping.Key.GetHashCode();
if (this.Mapping.ElementName != null)
hashCode ^= this.Mapping.ElementName.GetHashCode();
if (this.Mapping.Namespace != null)
hashCode ^= this.Mapping.Namespace.GetHashCode();
return hashCode;
}
}
}
}
| |
using System;
using static OneOf.Functions;
namespace OneOf
{
public struct OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> : IOneOf
{
readonly T0 _value0;
readonly T1 _value1;
readonly T2 _value2;
readonly T3 _value3;
readonly T4 _value4;
readonly T5 _value5;
readonly T6 _value6;
readonly T7 _value7;
readonly T8 _value8;
readonly T9 _value9;
readonly T10 _value10;
readonly T11 _value11;
readonly int _index;
OneOf(int index, T0 value0 = default, T1 value1 = default, T2 value2 = default, T3 value3 = default, T4 value4 = default, T5 value5 = default, T6 value6 = default, T7 value7 = default, T8 value8 = default, T9 value9 = default, T10 value10 = default, T11 value11 = default)
{
_index = index;
_value0 = value0;
_value1 = value1;
_value2 = value2;
_value3 = value3;
_value4 = value4;
_value5 = value5;
_value6 = value6;
_value7 = value7;
_value8 = value8;
_value9 = value9;
_value10 = value10;
_value11 = value11;
}
public object Value =>
_index switch
{
0 => _value0,
1 => _value1,
2 => _value2,
3 => _value3,
4 => _value4,
5 => _value5,
6 => _value6,
7 => _value7,
8 => _value8,
9 => _value9,
10 => _value10,
11 => _value11,
_ => throw new InvalidOperationException()
};
public int Index => _index;
public bool IsT0 => _index == 0;
public bool IsT1 => _index == 1;
public bool IsT2 => _index == 2;
public bool IsT3 => _index == 3;
public bool IsT4 => _index == 4;
public bool IsT5 => _index == 5;
public bool IsT6 => _index == 6;
public bool IsT7 => _index == 7;
public bool IsT8 => _index == 8;
public bool IsT9 => _index == 9;
public bool IsT10 => _index == 10;
public bool IsT11 => _index == 11;
public T0 AsT0 =>
_index == 0 ?
_value0 :
throw new InvalidOperationException($"Cannot return as T0 as result is T{_index}");
public T1 AsT1 =>
_index == 1 ?
_value1 :
throw new InvalidOperationException($"Cannot return as T1 as result is T{_index}");
public T2 AsT2 =>
_index == 2 ?
_value2 :
throw new InvalidOperationException($"Cannot return as T2 as result is T{_index}");
public T3 AsT3 =>
_index == 3 ?
_value3 :
throw new InvalidOperationException($"Cannot return as T3 as result is T{_index}");
public T4 AsT4 =>
_index == 4 ?
_value4 :
throw new InvalidOperationException($"Cannot return as T4 as result is T{_index}");
public T5 AsT5 =>
_index == 5 ?
_value5 :
throw new InvalidOperationException($"Cannot return as T5 as result is T{_index}");
public T6 AsT6 =>
_index == 6 ?
_value6 :
throw new InvalidOperationException($"Cannot return as T6 as result is T{_index}");
public T7 AsT7 =>
_index == 7 ?
_value7 :
throw new InvalidOperationException($"Cannot return as T7 as result is T{_index}");
public T8 AsT8 =>
_index == 8 ?
_value8 :
throw new InvalidOperationException($"Cannot return as T8 as result is T{_index}");
public T9 AsT9 =>
_index == 9 ?
_value9 :
throw new InvalidOperationException($"Cannot return as T9 as result is T{_index}");
public T10 AsT10 =>
_index == 10 ?
_value10 :
throw new InvalidOperationException($"Cannot return as T10 as result is T{_index}");
public T11 AsT11 =>
_index == 11 ?
_value11 :
throw new InvalidOperationException($"Cannot return as T11 as result is T{_index}");
public static implicit operator OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11>(T0 t) => new OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11>(0, value0: t);
public static implicit operator OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11>(T1 t) => new OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11>(1, value1: t);
public static implicit operator OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11>(T2 t) => new OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11>(2, value2: t);
public static implicit operator OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11>(T3 t) => new OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11>(3, value3: t);
public static implicit operator OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11>(T4 t) => new OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11>(4, value4: t);
public static implicit operator OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11>(T5 t) => new OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11>(5, value5: t);
public static implicit operator OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11>(T6 t) => new OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11>(6, value6: t);
public static implicit operator OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11>(T7 t) => new OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11>(7, value7: t);
public static implicit operator OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11>(T8 t) => new OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11>(8, value8: t);
public static implicit operator OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11>(T9 t) => new OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11>(9, value9: t);
public static implicit operator OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11>(T10 t) => new OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11>(10, value10: t);
public static implicit operator OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11>(T11 t) => new OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11>(11, value11: t);
public void Switch(Action<T0> f0, Action<T1> f1, Action<T2> f2, Action<T3> f3, Action<T4> f4, Action<T5> f5, Action<T6> f6, Action<T7> f7, Action<T8> f8, Action<T9> f9, Action<T10> f10, Action<T11> f11)
{
if (_index == 0 && f0 != null)
{
f0(_value0);
return;
}
if (_index == 1 && f1 != null)
{
f1(_value1);
return;
}
if (_index == 2 && f2 != null)
{
f2(_value2);
return;
}
if (_index == 3 && f3 != null)
{
f3(_value3);
return;
}
if (_index == 4 && f4 != null)
{
f4(_value4);
return;
}
if (_index == 5 && f5 != null)
{
f5(_value5);
return;
}
if (_index == 6 && f6 != null)
{
f6(_value6);
return;
}
if (_index == 7 && f7 != null)
{
f7(_value7);
return;
}
if (_index == 8 && f8 != null)
{
f8(_value8);
return;
}
if (_index == 9 && f9 != null)
{
f9(_value9);
return;
}
if (_index == 10 && f10 != null)
{
f10(_value10);
return;
}
if (_index == 11 && f11 != null)
{
f11(_value11);
return;
}
throw new InvalidOperationException();
}
public TResult Match<TResult>(Func<T0, TResult> f0, Func<T1, TResult> f1, Func<T2, TResult> f2, Func<T3, TResult> f3, Func<T4, TResult> f4, Func<T5, TResult> f5, Func<T6, TResult> f6, Func<T7, TResult> f7, Func<T8, TResult> f8, Func<T9, TResult> f9, Func<T10, TResult> f10, Func<T11, TResult> f11)
{
if (_index == 0 && f0 != null)
{
return f0(_value0);
}
if (_index == 1 && f1 != null)
{
return f1(_value1);
}
if (_index == 2 && f2 != null)
{
return f2(_value2);
}
if (_index == 3 && f3 != null)
{
return f3(_value3);
}
if (_index == 4 && f4 != null)
{
return f4(_value4);
}
if (_index == 5 && f5 != null)
{
return f5(_value5);
}
if (_index == 6 && f6 != null)
{
return f6(_value6);
}
if (_index == 7 && f7 != null)
{
return f7(_value7);
}
if (_index == 8 && f8 != null)
{
return f8(_value8);
}
if (_index == 9 && f9 != null)
{
return f9(_value9);
}
if (_index == 10 && f10 != null)
{
return f10(_value10);
}
if (_index == 11 && f11 != null)
{
return f11(_value11);
}
throw new InvalidOperationException();
}
public static OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> FromT0(T0 input) => input;
public static OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> FromT1(T1 input) => input;
public static OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> FromT2(T2 input) => input;
public static OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> FromT3(T3 input) => input;
public static OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> FromT4(T4 input) => input;
public static OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> FromT5(T5 input) => input;
public static OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> FromT6(T6 input) => input;
public static OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> FromT7(T7 input) => input;
public static OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> FromT8(T8 input) => input;
public static OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> FromT9(T9 input) => input;
public static OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> FromT10(T10 input) => input;
public static OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> FromT11(T11 input) => input;
public OneOf<TResult, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> MapT0<TResult>(Func<T0, TResult> mapFunc)
{
if (mapFunc == null)
{
throw new ArgumentNullException(nameof(mapFunc));
}
return _index switch
{
0 => mapFunc(AsT0),
1 => AsT1,
2 => AsT2,
3 => AsT3,
4 => AsT4,
5 => AsT5,
6 => AsT6,
7 => AsT7,
8 => AsT8,
9 => AsT9,
10 => AsT10,
11 => AsT11,
_ => throw new InvalidOperationException()
};
}
public OneOf<T0, TResult, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> MapT1<TResult>(Func<T1, TResult> mapFunc)
{
if (mapFunc == null)
{
throw new ArgumentNullException(nameof(mapFunc));
}
return _index switch
{
0 => AsT0,
1 => mapFunc(AsT1),
2 => AsT2,
3 => AsT3,
4 => AsT4,
5 => AsT5,
6 => AsT6,
7 => AsT7,
8 => AsT8,
9 => AsT9,
10 => AsT10,
11 => AsT11,
_ => throw new InvalidOperationException()
};
}
public OneOf<T0, T1, TResult, T3, T4, T5, T6, T7, T8, T9, T10, T11> MapT2<TResult>(Func<T2, TResult> mapFunc)
{
if (mapFunc == null)
{
throw new ArgumentNullException(nameof(mapFunc));
}
return _index switch
{
0 => AsT0,
1 => AsT1,
2 => mapFunc(AsT2),
3 => AsT3,
4 => AsT4,
5 => AsT5,
6 => AsT6,
7 => AsT7,
8 => AsT8,
9 => AsT9,
10 => AsT10,
11 => AsT11,
_ => throw new InvalidOperationException()
};
}
public OneOf<T0, T1, T2, TResult, T4, T5, T6, T7, T8, T9, T10, T11> MapT3<TResult>(Func<T3, TResult> mapFunc)
{
if (mapFunc == null)
{
throw new ArgumentNullException(nameof(mapFunc));
}
return _index switch
{
0 => AsT0,
1 => AsT1,
2 => AsT2,
3 => mapFunc(AsT3),
4 => AsT4,
5 => AsT5,
6 => AsT6,
7 => AsT7,
8 => AsT8,
9 => AsT9,
10 => AsT10,
11 => AsT11,
_ => throw new InvalidOperationException()
};
}
public OneOf<T0, T1, T2, T3, TResult, T5, T6, T7, T8, T9, T10, T11> MapT4<TResult>(Func<T4, TResult> mapFunc)
{
if (mapFunc == null)
{
throw new ArgumentNullException(nameof(mapFunc));
}
return _index switch
{
0 => AsT0,
1 => AsT1,
2 => AsT2,
3 => AsT3,
4 => mapFunc(AsT4),
5 => AsT5,
6 => AsT6,
7 => AsT7,
8 => AsT8,
9 => AsT9,
10 => AsT10,
11 => AsT11,
_ => throw new InvalidOperationException()
};
}
public OneOf<T0, T1, T2, T3, T4, TResult, T6, T7, T8, T9, T10, T11> MapT5<TResult>(Func<T5, TResult> mapFunc)
{
if (mapFunc == null)
{
throw new ArgumentNullException(nameof(mapFunc));
}
return _index switch
{
0 => AsT0,
1 => AsT1,
2 => AsT2,
3 => AsT3,
4 => AsT4,
5 => mapFunc(AsT5),
6 => AsT6,
7 => AsT7,
8 => AsT8,
9 => AsT9,
10 => AsT10,
11 => AsT11,
_ => throw new InvalidOperationException()
};
}
public OneOf<T0, T1, T2, T3, T4, T5, TResult, T7, T8, T9, T10, T11> MapT6<TResult>(Func<T6, TResult> mapFunc)
{
if (mapFunc == null)
{
throw new ArgumentNullException(nameof(mapFunc));
}
return _index switch
{
0 => AsT0,
1 => AsT1,
2 => AsT2,
3 => AsT3,
4 => AsT4,
5 => AsT5,
6 => mapFunc(AsT6),
7 => AsT7,
8 => AsT8,
9 => AsT9,
10 => AsT10,
11 => AsT11,
_ => throw new InvalidOperationException()
};
}
public OneOf<T0, T1, T2, T3, T4, T5, T6, TResult, T8, T9, T10, T11> MapT7<TResult>(Func<T7, TResult> mapFunc)
{
if (mapFunc == null)
{
throw new ArgumentNullException(nameof(mapFunc));
}
return _index switch
{
0 => AsT0,
1 => AsT1,
2 => AsT2,
3 => AsT3,
4 => AsT4,
5 => AsT5,
6 => AsT6,
7 => mapFunc(AsT7),
8 => AsT8,
9 => AsT9,
10 => AsT10,
11 => AsT11,
_ => throw new InvalidOperationException()
};
}
public OneOf<T0, T1, T2, T3, T4, T5, T6, T7, TResult, T9, T10, T11> MapT8<TResult>(Func<T8, TResult> mapFunc)
{
if (mapFunc == null)
{
throw new ArgumentNullException(nameof(mapFunc));
}
return _index switch
{
0 => AsT0,
1 => AsT1,
2 => AsT2,
3 => AsT3,
4 => AsT4,
5 => AsT5,
6 => AsT6,
7 => AsT7,
8 => mapFunc(AsT8),
9 => AsT9,
10 => AsT10,
11 => AsT11,
_ => throw new InvalidOperationException()
};
}
public OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, TResult, T10, T11> MapT9<TResult>(Func<T9, TResult> mapFunc)
{
if (mapFunc == null)
{
throw new ArgumentNullException(nameof(mapFunc));
}
return _index switch
{
0 => AsT0,
1 => AsT1,
2 => AsT2,
3 => AsT3,
4 => AsT4,
5 => AsT5,
6 => AsT6,
7 => AsT7,
8 => AsT8,
9 => mapFunc(AsT9),
10 => AsT10,
11 => AsT11,
_ => throw new InvalidOperationException()
};
}
public OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, TResult, T11> MapT10<TResult>(Func<T10, TResult> mapFunc)
{
if (mapFunc == null)
{
throw new ArgumentNullException(nameof(mapFunc));
}
return _index switch
{
0 => AsT0,
1 => AsT1,
2 => AsT2,
3 => AsT3,
4 => AsT4,
5 => AsT5,
6 => AsT6,
7 => AsT7,
8 => AsT8,
9 => AsT9,
10 => mapFunc(AsT10),
11 => AsT11,
_ => throw new InvalidOperationException()
};
}
public OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, TResult> MapT11<TResult>(Func<T11, TResult> mapFunc)
{
if (mapFunc == null)
{
throw new ArgumentNullException(nameof(mapFunc));
}
return _index switch
{
0 => AsT0,
1 => AsT1,
2 => AsT2,
3 => AsT3,
4 => AsT4,
5 => AsT5,
6 => AsT6,
7 => AsT7,
8 => AsT8,
9 => AsT9,
10 => AsT10,
11 => mapFunc(AsT11),
_ => throw new InvalidOperationException()
};
}
public bool TryPickT0(out T0 value, out OneOf<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> remainder)
{
value = IsT0 ? AsT0 : default;
remainder = _index switch
{
0 => default,
1 => AsT1,
2 => AsT2,
3 => AsT3,
4 => AsT4,
5 => AsT5,
6 => AsT6,
7 => AsT7,
8 => AsT8,
9 => AsT9,
10 => AsT10,
11 => AsT11,
_ => throw new InvalidOperationException()
};
return this.IsT0;
}
public bool TryPickT1(out T1 value, out OneOf<T0, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> remainder)
{
value = IsT1 ? AsT1 : default;
remainder = _index switch
{
0 => AsT0,
1 => default,
2 => AsT2,
3 => AsT3,
4 => AsT4,
5 => AsT5,
6 => AsT6,
7 => AsT7,
8 => AsT8,
9 => AsT9,
10 => AsT10,
11 => AsT11,
_ => throw new InvalidOperationException()
};
return this.IsT1;
}
public bool TryPickT2(out T2 value, out OneOf<T0, T1, T3, T4, T5, T6, T7, T8, T9, T10, T11> remainder)
{
value = IsT2 ? AsT2 : default;
remainder = _index switch
{
0 => AsT0,
1 => AsT1,
2 => default,
3 => AsT3,
4 => AsT4,
5 => AsT5,
6 => AsT6,
7 => AsT7,
8 => AsT8,
9 => AsT9,
10 => AsT10,
11 => AsT11,
_ => throw new InvalidOperationException()
};
return this.IsT2;
}
public bool TryPickT3(out T3 value, out OneOf<T0, T1, T2, T4, T5, T6, T7, T8, T9, T10, T11> remainder)
{
value = IsT3 ? AsT3 : default;
remainder = _index switch
{
0 => AsT0,
1 => AsT1,
2 => AsT2,
3 => default,
4 => AsT4,
5 => AsT5,
6 => AsT6,
7 => AsT7,
8 => AsT8,
9 => AsT9,
10 => AsT10,
11 => AsT11,
_ => throw new InvalidOperationException()
};
return this.IsT3;
}
public bool TryPickT4(out T4 value, out OneOf<T0, T1, T2, T3, T5, T6, T7, T8, T9, T10, T11> remainder)
{
value = IsT4 ? AsT4 : default;
remainder = _index switch
{
0 => AsT0,
1 => AsT1,
2 => AsT2,
3 => AsT3,
4 => default,
5 => AsT5,
6 => AsT6,
7 => AsT7,
8 => AsT8,
9 => AsT9,
10 => AsT10,
11 => AsT11,
_ => throw new InvalidOperationException()
};
return this.IsT4;
}
public bool TryPickT5(out T5 value, out OneOf<T0, T1, T2, T3, T4, T6, T7, T8, T9, T10, T11> remainder)
{
value = IsT5 ? AsT5 : default;
remainder = _index switch
{
0 => AsT0,
1 => AsT1,
2 => AsT2,
3 => AsT3,
4 => AsT4,
5 => default,
6 => AsT6,
7 => AsT7,
8 => AsT8,
9 => AsT9,
10 => AsT10,
11 => AsT11,
_ => throw new InvalidOperationException()
};
return this.IsT5;
}
public bool TryPickT6(out T6 value, out OneOf<T0, T1, T2, T3, T4, T5, T7, T8, T9, T10, T11> remainder)
{
value = IsT6 ? AsT6 : default;
remainder = _index switch
{
0 => AsT0,
1 => AsT1,
2 => AsT2,
3 => AsT3,
4 => AsT4,
5 => AsT5,
6 => default,
7 => AsT7,
8 => AsT8,
9 => AsT9,
10 => AsT10,
11 => AsT11,
_ => throw new InvalidOperationException()
};
return this.IsT6;
}
public bool TryPickT7(out T7 value, out OneOf<T0, T1, T2, T3, T4, T5, T6, T8, T9, T10, T11> remainder)
{
value = IsT7 ? AsT7 : default;
remainder = _index switch
{
0 => AsT0,
1 => AsT1,
2 => AsT2,
3 => AsT3,
4 => AsT4,
5 => AsT5,
6 => AsT6,
7 => default,
8 => AsT8,
9 => AsT9,
10 => AsT10,
11 => AsT11,
_ => throw new InvalidOperationException()
};
return this.IsT7;
}
public bool TryPickT8(out T8 value, out OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T9, T10, T11> remainder)
{
value = IsT8 ? AsT8 : default;
remainder = _index switch
{
0 => AsT0,
1 => AsT1,
2 => AsT2,
3 => AsT3,
4 => AsT4,
5 => AsT5,
6 => AsT6,
7 => AsT7,
8 => default,
9 => AsT9,
10 => AsT10,
11 => AsT11,
_ => throw new InvalidOperationException()
};
return this.IsT8;
}
public bool TryPickT9(out T9 value, out OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T10, T11> remainder)
{
value = IsT9 ? AsT9 : default;
remainder = _index switch
{
0 => AsT0,
1 => AsT1,
2 => AsT2,
3 => AsT3,
4 => AsT4,
5 => AsT5,
6 => AsT6,
7 => AsT7,
8 => AsT8,
9 => default,
10 => AsT10,
11 => AsT11,
_ => throw new InvalidOperationException()
};
return this.IsT9;
}
public bool TryPickT10(out T10 value, out OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T11> remainder)
{
value = IsT10 ? AsT10 : default;
remainder = _index switch
{
0 => AsT0,
1 => AsT1,
2 => AsT2,
3 => AsT3,
4 => AsT4,
5 => AsT5,
6 => AsT6,
7 => AsT7,
8 => AsT8,
9 => AsT9,
10 => default,
11 => AsT11,
_ => throw new InvalidOperationException()
};
return this.IsT10;
}
public bool TryPickT11(out T11 value, out OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10> remainder)
{
value = IsT11 ? AsT11 : default;
remainder = _index switch
{
0 => AsT0,
1 => AsT1,
2 => AsT2,
3 => AsT3,
4 => AsT4,
5 => AsT5,
6 => AsT6,
7 => AsT7,
8 => AsT8,
9 => AsT9,
10 => AsT10,
11 => default,
_ => throw new InvalidOperationException()
};
return this.IsT11;
}
bool Equals(OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> other) =>
_index == other._index &&
_index switch
{
0 => Equals(_value0, other._value0),
1 => Equals(_value1, other._value1),
2 => Equals(_value2, other._value2),
3 => Equals(_value3, other._value3),
4 => Equals(_value4, other._value4),
5 => Equals(_value5, other._value5),
6 => Equals(_value6, other._value6),
7 => Equals(_value7, other._value7),
8 => Equals(_value8, other._value8),
9 => Equals(_value9, other._value9),
10 => Equals(_value10, other._value10),
11 => Equals(_value11, other._value11),
_ => false
};
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj))
{
return false;
}
return obj is OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> o && Equals(o);
}
public override string ToString() =>
_index switch {
0 => FormatValue(_value0),
1 => FormatValue(_value1),
2 => FormatValue(_value2),
3 => FormatValue(_value3),
4 => FormatValue(_value4),
5 => FormatValue(_value5),
6 => FormatValue(_value6),
7 => FormatValue(_value7),
8 => FormatValue(_value8),
9 => FormatValue(_value9),
10 => FormatValue(_value10),
11 => FormatValue(_value11),
_ => throw new InvalidOperationException("Unexpected index, which indicates a problem in the OneOf codegen.")
};
public override int GetHashCode()
{
unchecked
{
int hashCode = _index switch
{
0 => _value0?.GetHashCode(),
1 => _value1?.GetHashCode(),
2 => _value2?.GetHashCode(),
3 => _value3?.GetHashCode(),
4 => _value4?.GetHashCode(),
5 => _value5?.GetHashCode(),
6 => _value6?.GetHashCode(),
7 => _value7?.GetHashCode(),
8 => _value8?.GetHashCode(),
9 => _value9?.GetHashCode(),
10 => _value10?.GetHashCode(),
11 => _value11?.GetHashCode(),
_ => 0
} ?? 0;
return (hashCode*397) ^ _index;
}
}
}
}
| |
using System;
using System.Threading;
using UnityEngine;
using UnityEditor;
namespace GitHub.Unity
{
[Serializable]
class GitHubAuthenticationView : Subview
{
private static readonly Vector2 viewSize = new Vector2(290, 290);
private const string CredentialsNeedRefreshMessage = "We've detected that your stored credentials are out of sync with your current user. This can happen if you have signed in to git outside of Unity. Sign in again to refresh your credentials.";
private const string NeedAuthenticationMessage = "We need you to authenticate first";
private const string WindowTitle = "Authenticate";
private const string UsernameLabel = "Username";
private const string PasswordLabel = "Password";
private const string TwofaLabel = "2FA Code";
private const string LoginButton = "Sign in";
private const string BackButton = "Back";
private const string AuthTitle = "Sign in to GitHub";
private const string TwofaTitle = "Two-Factor Authentication";
private const string TwofaDescription = "Open the two-factor authentication app on your device to view your 2FA code and verify your identity.";
private const string TwofaButton = "Verify";
[SerializeField] private Vector2 scroll;
[SerializeField] private string username = string.Empty;
[SerializeField] private string two2fa = string.Empty;
[SerializeField] private string message;
[SerializeField] private string errorMessage;
[SerializeField] private bool need2fa;
[NonSerialized] private bool isBusy;
[NonSerialized] private bool enterPressed;
[NonSerialized] private string password = string.Empty;
[NonSerialized] private AuthenticationService authenticationService;
[NonSerialized] private string oAuthState;
[NonSerialized] private string oAuthOpenUrl;
public override void InitializeView(IView parent)
{
Logger.Trace("InitializeView");
base.InitializeView(parent);
need2fa = isBusy = false;
message = errorMessage = null;
Title = WindowTitle;
Size = viewSize;
oAuthState = Guid.NewGuid().ToString();
oAuthOpenUrl = AuthenticationService.GetLoginUrl(oAuthState).ToString();
OAuthCallbackManager.OnCallback += OnOAuthCallback;
}
public void Initialize(Exception exception)
{
var usernameMismatchException = exception as TokenUsernameMismatchException;
if (usernameMismatchException != null)
{
message = CredentialsNeedRefreshMessage;
username = usernameMismatchException.CachedUsername;
}
var keychainEmptyException = exception as KeychainEmptyException;
if (keychainEmptyException != null)
{
message = NeedAuthenticationMessage;
}
if (usernameMismatchException == null && keychainEmptyException == null)
{
message = exception.Message;
}
}
public override void OnGUI()
{
HandleEnterPressed();
EditorGUIUtility.labelWidth = 90f;
scroll = GUILayout.BeginScrollView(scroll);
{
GUILayout.BeginHorizontal(Styles.AuthHeaderBoxStyle);
{
GUILayout.Label(AuthTitle, Styles.HeaderRepoLabelStyle);
}
GUILayout.EndHorizontal();
GUILayout.BeginVertical();
{
if (!need2fa)
{
OnGUILogin();
}
else
{
OnGUI2FA();
}
}
GUILayout.EndVertical();
}
GUILayout.EndScrollView();
}
private void HandleEnterPressed()
{
if (Event.current.type != EventType.KeyDown)
return;
enterPressed = Event.current.keyCode == KeyCode.Return || Event.current.keyCode == KeyCode.KeypadEnter;
if (enterPressed)
Event.current.Use();
}
private void OnGUILogin()
{
EditorGUI.BeginDisabledGroup(isBusy);
{
ShowMessage();
EditorGUILayout.Space();
GUILayout.BeginHorizontal();
{
username = EditorGUILayout.TextField(UsernameLabel, username, Styles.TextFieldStyle);
}
GUILayout.EndHorizontal();
EditorGUILayout.Space();
GUILayout.BeginHorizontal();
{
password = EditorGUILayout.PasswordField(PasswordLabel, password, Styles.TextFieldStyle);
}
GUILayout.EndHorizontal();
EditorGUILayout.Space();
ShowErrorMessage();
GUILayout.Space(Styles.BaseSpacing + 3);
GUILayout.BeginHorizontal();
{
GUILayout.FlexibleSpace();
if (GUILayout.Button(LoginButton) || (!isBusy && enterPressed))
{
GUI.FocusControl(null);
isBusy = true;
AuthenticationService.Login(username, password, DoRequire2fa, DoResult);
}
}
GUILayout.EndHorizontal();
if (OAuthCallbackManager.IsRunning)
{
GUILayout.Space(Styles.BaseSpacing + 3);
GUILayout.BeginHorizontal();
{
GUILayout.FlexibleSpace();
if (GUILayout.Button("Sign in with your browser", Styles.HyperlinkStyle))
{
GUI.FocusControl(null);
Application.OpenURL(oAuthOpenUrl);
}
}
GUILayout.EndHorizontal();
}
}
EditorGUI.EndDisabledGroup();
}
private void OnGUI2FA()
{
GUILayout.BeginVertical();
{
GUILayout.Label(TwofaTitle, EditorStyles.boldLabel);
GUILayout.Label(TwofaDescription, EditorStyles.wordWrappedLabel);
EditorGUI.BeginDisabledGroup(isBusy);
{
EditorGUILayout.Space();
two2fa = EditorGUILayout.TextField(TwofaLabel, two2fa, Styles.TextFieldStyle);
EditorGUILayout.Space();
ShowErrorMessage();
GUILayout.BeginHorizontal();
{
GUILayout.FlexibleSpace();
if (GUILayout.Button(BackButton))
{
GUI.FocusControl(null);
Clear();
}
if (GUILayout.Button(TwofaButton) || (!isBusy && enterPressed))
{
GUI.FocusControl(null);
isBusy = true;
AuthenticationService.LoginWith2fa(two2fa);
}
}
GUILayout.EndHorizontal();
EditorGUILayout.Space();
}
EditorGUI.EndDisabledGroup();
}
GUILayout.EndVertical();
}
private void OnOAuthCallback(string state, string code)
{
if (state.Equals(oAuthState))
{
isBusy = true;
authenticationService.LoginWithOAuthCode(code, (b, s) => TaskManager.RunInUI(() => DoOAuthCodeResult(b, s)));
}
}
private void DoRequire2fa(string msg)
{
need2fa = true;
errorMessage = msg;
isBusy = false;
Redraw();
}
private void Clear()
{
need2fa = false;
errorMessage = null;
isBusy = false;
Redraw();
}
private void DoResult(bool success, string msg)
{
isBusy = false;
if (success)
{
UsageTracker.IncrementAuthenticationViewButtonAuthentication();
Clear();
Finish(true);
}
else
{
errorMessage = msg;
Redraw();
}
}
private void DoOAuthCodeResult(bool success, string msg)
{
isBusy = false;
if (success)
{
UsageTracker.IncrementAuthenticationViewButtonAuthentication();
Clear();
Finish(true);
}
else
{
errorMessage = msg;
Redraw();
}
}
private void ShowMessage()
{
if (message != null)
{
EditorGUILayout.HelpBox(message, MessageType.Warning);
}
}
private void ShowErrorMessage()
{
if (errorMessage != null)
{
EditorGUILayout.HelpBox(errorMessage, MessageType.Error);
}
}
private AuthenticationService AuthenticationService
{
get
{
if (authenticationService == null)
{
AuthenticationService = new AuthenticationService(UriString.ToUriString(HostAddress.GitHubDotComHostAddress.WebUri), Platform.Keychain, Manager.ProcessManager, Manager.TaskManager, Environment);
}
return authenticationService;
}
set
{
authenticationService = value;
}
}
public override bool IsBusy
{
get { return isBusy; }
}
}
}
| |
// This file was generated by CSLA Object Generator - CslaGenFork v4.5
//
// Filename: DocClassEditDynaColl
// ObjectType: DocClassEditDynaColl
// CSLAType: DynamicEditableRootCollection
using System;
using System.Data;
using System.Data.SqlClient;
using Csla;
using Csla.Data;
using DocStore.Business.Util;
using Csla.Rules;
using Csla.Rules.CommonRules;
using UsingLibrary;
namespace DocStore.Business
{
/// <summary>
/// DocClassEditDynaColl (dynamic root list).<br/>
/// This is a generated <see cref="DocClassEditDynaColl"/> business object.
/// </summary>
/// <remarks>
/// The items of the collection are <see cref="DocClassEditDyna"/> objects.
/// </remarks>
[Serializable]
#if WINFORMS
public partial class DocClassEditDynaColl : MyDynamicBindingListBase<DocClassEditDyna>, IHaveInterface, IHaveGenericInterface<DocClassEditDynaColl>
#else
public partial class DocClassEditDynaColl : MyDynamicListBase<DocClassEditDyna>, IHaveInterface, IHaveGenericInterface<DocClassEditDynaColl>
#endif
{
#region Collection Business Methods
/// <summary>
/// Adds a new <see cref="DocClassEditDyna"/> item to the collection.
/// </summary>
/// <param name="item">The item to add.</param>
/// <exception cref="System.Security.SecurityException">if the user isn't authorized to add items to the collection.</exception>
/// <exception cref="ArgumentException">if the item already exists in the collection.</exception>
public new void Add(DocClassEditDyna item)
{
if (!CanAddObject())
throw new System.Security.SecurityException("User not authorized to create a DocClassEditDyna.");
if (Contains(item.DocClassID))
throw new ArgumentException("DocClassEditDyna already exists.");
base.Add(item);
}
/// <summary>
/// Removes a <see cref="DocClassEditDyna"/> item from the collection.
/// </summary>
/// <param name="item">The item to remove.</param>
/// <returns><c>true</c> if the item was removed from the collection, otherwise <c>false</c>.</returns>
/// <exception cref="System.Security.SecurityException">if the user isn't authorized to remove items from the collection.</exception>
public new bool Remove(DocClassEditDyna item)
{
if (!CanDeleteObject())
throw new System.Security.SecurityException("User not authorized to remove a DocClassEditDyna.");
return base.Remove(item);
}
/// <summary>
/// Adds a new <see cref="DocClassEditDyna"/> item to the collection.
/// </summary>
/// <returns>The new DocClassEditDyna item added to the collection.</returns>
public DocClassEditDyna Add()
{
var item = DocClassEditDyna.NewDocClassEditDyna();
Add(item);
return item;
}
/// <summary>
/// Asynchronously adds a new <see cref="DocClassEditDyna"/> item to the collection.
/// </summary>
public void BeginAdd()
{
DocClassEditDyna docClassEditDyna = null;
DocClassEditDyna.NewDocClassEditDyna((o, e) =>
{
if (e.Error != null)
throw e.Error;
else
docClassEditDyna = e.Object;
});
Add(docClassEditDyna);
}
/// <summary>
/// Removes a <see cref="DocClassEditDyna"/> item from the collection.
/// </summary>
/// <param name="docClassID">The DocClassID of the item to be removed.</param>
public void Remove(int docClassID)
{
foreach (var docClassEditDyna in this)
{
if (docClassEditDyna.DocClassID == docClassID)
{
Remove(docClassEditDyna);
break;
}
}
}
/// <summary>
/// Determines whether a <see cref="DocClassEditDyna"/> item is in the collection.
/// </summary>
/// <param name="docClassID">The DocClassID of the item to search for.</param>
/// <returns><c>true</c> if the DocClassEditDyna is a collection item; otherwise, <c>false</c>.</returns>
public bool Contains(int docClassID)
{
foreach (var docClassEditDyna in this)
{
if (docClassEditDyna.DocClassID == docClassID)
{
return true;
}
}
return false;
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Creates a new <see cref="DocClassEditDynaColl"/> collection.
/// </summary>
/// <returns>A reference to the created <see cref="DocClassEditDynaColl"/> collection.</returns>
public static DocClassEditDynaColl NewDocClassEditDynaColl()
{
return DataPortal.Create<DocClassEditDynaColl>();
}
/// <summary>
/// Factory method. Loads a <see cref="DocClassEditDynaColl"/> collection.
/// </summary>
/// <returns>A reference to the fetched <see cref="DocClassEditDynaColl"/> collection.</returns>
public static DocClassEditDynaColl GetDocClassEditDynaColl()
{
return DataPortal.Fetch<DocClassEditDynaColl>();
}
/// <summary>
/// Factory method. Asynchronously creates a new <see cref="DocClassEditDynaColl"/> collection.
/// </summary>
/// <param name="callback">The completion callback method.</param>
public static void NewDocClassEditDynaColl(EventHandler<DataPortalResult<DocClassEditDynaColl>> callback)
{
DataPortal.BeginCreate<DocClassEditDynaColl>(callback);
}
/// <summary>
/// Factory method. Asynchronously loads a <see cref="DocClassEditDynaColl"/> collection.
/// </summary>
/// <param name="callback">The completion callback method.</param>
public static void GetDocClassEditDynaColl(EventHandler<DataPortalResult<DocClassEditDynaColl>> callback)
{
DataPortal.BeginFetch<DocClassEditDynaColl>(callback);
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="DocClassEditDynaColl"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public DocClassEditDynaColl()
{
// Use factory methods and do not use direct creation.
var rlce = RaiseListChangedEvents;
RaiseListChangedEvents = false;
AllowNew = DocClassEditDynaColl.CanAddObject();
AllowEdit = DocClassEditDynaColl.CanEditObject();
AllowRemove = DocClassEditDynaColl.CanDeleteObject();
RaiseListChangedEvents = rlce;
}
#endregion
#region Object Authorization
/// <summary>
/// Adds the object authorization rules.
/// </summary>
protected static void AddObjectAuthorizationRules()
{
BusinessRules.AddRule(typeof (DocClassEditDynaColl), new IsInRole(AuthorizationActions.CreateObject, "Admin"));
BusinessRules.AddRule(typeof (DocClassEditDynaColl), new IsInRole(AuthorizationActions.GetObject, "User"));
BusinessRules.AddRule(typeof (DocClassEditDynaColl), new IsInRole(AuthorizationActions.EditObject, "Admin"));
BusinessRules.AddRule(typeof (DocClassEditDynaColl), new IsInRole(AuthorizationActions.DeleteObject, "Admin"));
AddObjectAuthorizationRulesExtend();
}
/// <summary>
/// Allows the set up of custom object authorization rules.
/// </summary>
static partial void AddObjectAuthorizationRulesExtend();
/// <summary>
/// Checks if the current user can create a new DocClassEditDynaColl object.
/// </summary>
/// <returns><c>true</c> if the user can create a new object; otherwise, <c>false</c>.</returns>
public static bool CanAddObject()
{
return BusinessRules.HasPermission(Csla.Rules.AuthorizationActions.CreateObject, typeof(DocClassEditDynaColl));
}
/// <summary>
/// Checks if the current user can retrieve DocClassEditDynaColl's properties.
/// </summary>
/// <returns><c>true</c> if the user can read the object; otherwise, <c>false</c>.</returns>
public static bool CanGetObject()
{
return BusinessRules.HasPermission(Csla.Rules.AuthorizationActions.GetObject, typeof(DocClassEditDynaColl));
}
/// <summary>
/// Checks if the current user can change DocClassEditDynaColl's properties.
/// </summary>
/// <returns><c>true</c> if the user can update the object; otherwise, <c>false</c>.</returns>
public static bool CanEditObject()
{
return BusinessRules.HasPermission(Csla.Rules.AuthorizationActions.EditObject, typeof(DocClassEditDynaColl));
}
/// <summary>
/// Checks if the current user can delete a DocClassEditDynaColl object.
/// </summary>
/// <returns><c>true</c> if the user can delete the object; otherwise, <c>false</c>.</returns>
public static bool CanDeleteObject()
{
return BusinessRules.HasPermission(Csla.Rules.AuthorizationActions.DeleteObject, typeof(DocClassEditDynaColl));
}
#endregion
#region Data Access
/// <summary>
/// Loads a <see cref="DocClassEditDynaColl"/> collection from the database.
/// </summary>
protected void DataPortal_Fetch()
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager(Database.DocStoreConnection, false))
{
using (var cmd = new SqlCommand("GetDocClassEditDynaColl", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
var args = new DataPortalHookArgs(cmd);
OnFetchPre(args);
LoadCollection(cmd);
OnFetchPost(args);
}
}
}
private void LoadCollection(SqlCommand cmd)
{
using (var dr = new SafeDataReader(cmd.ExecuteReader()))
{
Fetch(dr);
}
}
/// <summary>
/// Loads all <see cref="DocClassEditDynaColl"/> collection items from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
private void Fetch(SafeDataReader dr)
{
var rlce = RaiseListChangedEvents;
RaiseListChangedEvents = false;
while (dr.Read())
{
Add(DocClassEditDyna.GetDocClassEditDyna(dr));
}
RaiseListChangedEvents = rlce;
}
#endregion
#region DataPortal Hooks
/// <summary>
/// Occurs after setting query parameters and before the fetch operation.
/// </summary>
partial void OnFetchPre(DataPortalHookArgs args);
/// <summary>
/// Occurs after the fetch operation (object or collection is fully loaded and set up).
/// </summary>
partial void OnFetchPost(DataPortalHookArgs args);
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
namespace Kalingrad
{
/// <summary>
/// This is the main type for your game
/// </summary>
public class Game1 : Microsoft.Xna.Framework.Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
// a black texture (used to draw circles,lines ,etc ...)
private Texture2D pixel;
private List<Vector2> lines;
public const int HEIGHT = 600;
public const int WIDTH = 800;
// right shape
private List<RightShape> rightShapes;
private RightShape currentRightShape;
private int currentRightShapeIdx;
// left shape
private LeftShape leftShape;
// Mouse states
MouseState currentMouseState, previousMouseState;
KeyboardState currentKeyboardState, previousKeyboardState;
private int currentSelectedPoint;
private bool gotShape;
private float watingTime;
private static Color dotSmallColor = Color.Black;
private static Color dotBigColor = Color.Black;
private static Color lineColor = Color.Black;
private static Color textColor = Color.Black;
private static Color bgColor = Color.White;
private SpriteFont textFont;
public Game1()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
this.lines = new List<Vector2>();
this.gotShape = false;
}
/// <summary>
/// Allows the game to perform any initialization it needs to before starting to run.
/// This is where it can query for any required services and load any non-graphic
/// related content. Calling base.Initialize will enumerate through any components
/// and initialize them as well.
/// </summary>
protected override void Initialize()
{
// TODO: Add your initialization logic here
graphics.PreferredBackBufferHeight = HEIGHT;
graphics.PreferredBackBufferWidth = WIDTH;
this.IsMouseVisible = true;
// creating an empty pixel
this.pixel = new Texture2D(graphics.GraphicsDevice, 1, 1);
pixel.SetData(new[] { Color.White });
// get mouse state
currentMouseState = Mouse.GetState();
currentKeyboardState = Keyboard.GetState();
// create right shapes
this.rightShapes = new List<RightShape>();
rightShapes.Add(UserShapes.createHouseShape());
rightShapes.Add(UserShapes.createDiamond());
rightShapes.Add(UserShapes.createPent());
rightShapes.Add(RandomShapeGenerator.GenerateShape(6));
currentRightShapeIdx = 0;
currentRightShape = rightShapes[currentRightShapeIdx];
leftShape = new LeftShape(currentRightShape);
this.watingTime = 0;
base.Initialize();
}
/// <summary>
/// LoadContent will be called once per game and is the place to load
/// all of your content.
/// </summary>
protected override void LoadContent()
{
// Create a new SpriteBatch, which can be used to draw textures.
spriteBatch = new SpriteBatch(GraphicsDevice);
textFont = this.Content.Load<SpriteFont>(@"Fonts/arial");
// TODO: use this.Content to load your game content here
}
/// <summary>
/// UnloadContent will be called once per game and is the place to unload
/// all content.
/// </summary>
protected override void UnloadContent()
{
// TODO: Unload any non ContentManager content here
}
/// <summary>
/// Allows the game to run logic such as updating the world,
/// checking for collisions, gathering input, and playing audio.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Update(GameTime gameTime)
{
// Allows the game to exit
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
this.Exit();
// TODO: Add your update logic here
previousMouseState = currentMouseState;
currentMouseState = Mouse.GetState();
previousKeyboardState = currentKeyboardState;
currentKeyboardState = Keyboard.GetState();
currentSelectedPoint = -1;
for (int i = 0; i < leftShape.points.Count; i++)
{
Rectangle checkRectangle = new Rectangle((int)leftShape.points[i].X - 3,
(int)leftShape.points[i].Y - 3, 5, 5);
if (Rectangle.Intersect(checkRectangle,
new Rectangle(currentMouseState.X - 3, currentMouseState.Y - 3, 5, 5)) != Rectangle.Empty)
{
currentSelectedPoint = i;
}
}
if (currentMouseState.LeftButton == ButtonState.Pressed && previousMouseState.LeftButton == ButtonState.Released && currentSelectedPoint != -1)
{
if (!gotShape) leftShape.AddClick(currentSelectedPoint);
else nextShape();
}
if (currentKeyboardState.IsKeyDown(Keys.Escape) && previousKeyboardState.IsKeyUp(Keys.Escape))
{
this.Exit();
}
if (currentKeyboardState.IsKeyDown(Keys.N) && previousKeyboardState.IsKeyUp(Keys.N))
{
nextShape();
}
if (currentMouseState.RightButton == ButtonState.Pressed && previousMouseState.RightButton == ButtonState.Released)
{
clearLeftShape();
}
// check for win
if (leftShape.HasWon() && !gotShape)
{
gotShape = true;
watingTime = 1;
}
if (gotShape) this.watingTime -= (float)gameTime.ElapsedGameTime.TotalSeconds;
if (watingTime < 0)
{
nextShape();
}
base.Update(gameTime);
}
private void clearLeftShape()
{
leftShape.myEdges.Clear();
leftShape.lastSelectedPoint = -1;
gotShape = false;
}
private void nextShape()
{
clearLeftShape();
watingTime = 0;
currentRightShapeIdx++;
if (currentRightShapeIdx < rightShapes.Count) currentRightShape = rightShapes[currentRightShapeIdx];
else currentRightShape = RandomShapeGenerator.GenerateShape(6);
leftShape = new LeftShape(currentRightShape);
}
private void HandleMouseClick(Vector2 vector2)
{
this.lines.Add(vector2);
}
/// <summary>
/// This is called when the game should draw itself.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Game1.bgColor);
// TODO: Add your drawing code here
// Draw the split screen
spriteBatch.Begin();
spriteBatch.Draw(pixel, new Rectangle((WIDTH/2)-5,0,10,HEIGHT), Game1.lineColor);
// Draw instructions
spriteBatch.DrawString(textFont,
"Try To Redraw the shape on the right \nusing only one pen stroke\nLeft mouse click to start drawing\nRight mouse click to clear drawing",
new Vector2((WIDTH/2)+20,HEIGHT-220),
Game1.textColor);
DrawRightShape();
DrawLines();
if (gotShape) drawWinString();
spriteBatch.End();
base.Draw(gameTime);
}
private void drawWinString()
{
spriteBatch.DrawString(textFont,
"You did it!",
new Vector2((WIDTH / 2) - 360, HEIGHT - 180),
Game1.textColor);
}
private void DrawLines()
{
for (int i = 0; i < this.lines.Count - 1;i++ )
{
DrawLineSegment(spriteBatch, lines[i], lines[i + 1], Game1.lineColor, 2);
}
// draw lines
for (int i = 0; i < leftShape.myEdges.Count; i++)
{
DrawLineSegment(spriteBatch,
leftShape.points[leftShape.myEdges[i].X],
leftShape.points[leftShape.myEdges[i].Y],
Game1.lineColor, 2);
}
if (leftShape.lastSelectedPoint != -1 && !gotShape && currentMouseState.X <= (WIDTH/2))
{
DrawLineSegment(spriteBatch, leftShape.points[leftShape.lastSelectedPoint], new Vector2(currentMouseState.X, currentMouseState.Y), Game1.lineColor, 2);
}
}
private void DrawRightShape()
{
// draw circles
for (int i = 0; i < currentRightShape.points.Count; i++)
{
DrawCircle(spriteBatch, currentRightShape.points[i], 5, Game1.dotSmallColor, 5);
}
// draw lines
for (int i = 0; i < currentRightShape.edges.Count; i++)
{
DrawLineSegment(spriteBatch,
currentRightShape.points[currentRightShape.edges[i].X],
currentRightShape.points[currentRightShape.edges[i].Y],
Game1.lineColor, 2);
}
for (int i = 0; i < leftShape.points.Count; i++)
{
if (i != currentSelectedPoint) DrawCircle(spriteBatch, leftShape.points[i], 5, Game1.dotSmallColor, 5);
else DrawCircle(spriteBatch, leftShape.points[i], 10, Game1.dotBigColor, 10);
}
}
private void DrawLineSegment(SpriteBatch spriteBatch, Vector2 point1, Vector2 point2, Color color, int lineWidth)
{
float angle = (float)Math.Atan2(point2.Y - point1.Y, point2.X - point1.X);
float length = Vector2.Distance(point1, point2);
spriteBatch.Draw(this.pixel, point1, null, color,
angle, Vector2.Zero, new Vector2(length, lineWidth),
SpriteEffects.None, 0f);
}
private void DrawPolygon(SpriteBatch spriteBatch, Vector2[] vertex, int count, Color color, int lineWidth)
{
if (count > 0)
{
for (int i = 0; i < count - 1; i++)
{
DrawLineSegment(spriteBatch, vertex[i], vertex[i + 1], color, lineWidth);
}
DrawLineSegment(spriteBatch, vertex[count - 1], vertex[0], color, lineWidth);
}
}
private void DrawRectangle(SpriteBatch spriteBatch, Rectangle rectangle, Color color, int lineWidth)
{
Vector2[] vertex = new Vector2[4];
vertex[0] = new Vector2(rectangle.Left, rectangle.Top);
vertex[1] = new Vector2(rectangle.Right, rectangle.Top);
vertex[2] = new Vector2(rectangle.Right, rectangle.Bottom);
vertex[3] = new Vector2(rectangle.Left, rectangle.Bottom);
DrawPolygon(spriteBatch, vertex, 4, color, lineWidth);
}
private void DrawCircle(SpriteBatch spritbatch, Vector2 center, float radius, Color color, int lineWidth, int segments = 16)
{
Vector2[] vertex = new Vector2[segments];
double increment = Math.PI * 2.0 / segments;
double theta = 0.0;
for (int i = 0; i < segments; i++)
{
vertex[i] = center + radius * new Vector2((float)Math.Cos(theta), (float)Math.Sin(theta));
theta += increment;
}
DrawPolygon(spritbatch, vertex, segments, color, lineWidth);
}
}
}
| |
using System;
using Newtonsoft.Json;
using TheMovieDbNet.Models.Common;
namespace TheMovieDbNet.Models.TVs
{
/// <summary>
/// Represents the data of a tv series.
/// </summary>
public class TV : TVBase
{
[JsonConstructor]
internal TV(
int id,
double popularity,
string poster_path,
string backdrop_path,
string overview,
double vote_average,
int vote_count,
DateTime? first_air_date,
string[] origin_country,
string name,
string original_name,
TVCreator[] created_by,
int[] episode_run_time,
Genre[] genres,
string homepage,
bool in_production,
string[] languages,
DateTime? last_air_date,
Network[] networks,
int number_of_episodes,
int number_of_seasons,
string original_language,
ProductionCompany[] production_companies,
Season[] seasons,
string status,
string type,
PagedResult<TVSearchItem> similar,
PagedResult<TVSearchItem> recommendations,
TVExternals external_ids)
: base(
id,
popularity,
poster_path,
backdrop_path,
overview,
vote_average,
vote_count,
first_air_date,
origin_country,
name,
original_name)
{
CreatedBy =created_by;
EpisodeRunTime =episode_run_time;
Genres = genres;
Homepage = homepage;
InProduction = in_production;
Languages = languages;
LastAirDate = last_air_date;
Networks = networks;
NumberOfEpisodes = number_of_episodes;
NumberOfSeasons = number_of_seasons;
OriginalLanguage = original_language;
ProductionCompanies = production_companies;
Seasons = seasons;
Status = status;
Type = type;
SimilarTVs = similar;
Recommendations = recommendations;
ExternalIds = external_ids;
}
/// <summary>
/// Gets the creators of the tv.
/// </summary>
public TVCreator[] CreatedBy { get; }
/// <summary>
/// Gets the runtimes of episodes.
/// </summary>
public int[] EpisodeRunTime { get; }
/// <summary>
/// Gets the genres of the tv.
/// </summary>
public Genre[] Genres { get; }
/// <summary>
/// Gets the homepage of the tv.
/// </summary>
public string Homepage { get; }
/// <summary>
/// Gets whethet the tv is still in production.
/// </summary>
public bool InProduction { get; }
/// <summary>
/// Gets the languages used in tv.
/// </summary>
public string[] Languages { get; }
/// <summary>
/// Gets the last air date.
/// </summary>
public DateTime? LastAirDate { get; }
/// <summary>
/// Gets the networks tv is available on.
/// </summary>
public Network[] Networks { get; }
/// <summary>
/// Gets the number of episodes of the tv.
/// </summary>
public int NumberOfEpisodes { get; }
/// <summary>
/// Gets the number of seasons.
/// </summary>
public int NumberOfSeasons { get; }
/// <summary>
/// Gets the original language of the tv.
/// </summary>
public string OriginalLanguage { get; }
/// <summary>
/// Gets the production companies.
/// </summary>
public ProductionCompany[] ProductionCompanies { get; }
/// <summary>
/// Gets the seasons detail.
/// </summary>
public Season[] Seasons { get; }
/// <summary>
/// Gets the status of the tv series.
/// </summary>
public string Status { get; }
/// <summary>
/// Gets the type of tv series
/// </summary>
public string Type { get; }
/// <summary>
/// Gets the tv identifier on external sites.
/// </summary>
public TVExternals ExternalIds { get; }
/// <summary>
/// Gets the Recommendations for the tv.
/// </summary>
public PagedResult<TVSearchItem> Recommendations { get; }
/// <summary>
/// Gets the similar tvs.
/// </summary>
public PagedResult<TVSearchItem> SimilarTVs { get; }
/// <summary>
/// Gets or Sets the alternative titles for the tv series.
/// </summary>
[JsonIgnore]
public AlternativeTitle[] AlternativeTitles { get; set; }
/// <summary>
/// Gets or Sets the videos of the tv.
/// </summary>
[JsonIgnore]
public Video[] Videos { get; set; }
/// <summary>
/// Gets or Sets the backdrop images.
/// </summary>
[JsonIgnore]
public Image[] Backdrops { get; set; }
/// <summary>
/// Gets or Sets the poster images.
/// </summary>
[JsonIgnore]
public Image[] Posters { get; set; }
/// <summary>
/// Gets or Sets cast of the tv.
/// </summary>
[JsonIgnore]
public MediaCast[] Cast { get; set; }
/// <summary>
/// Gets or Sets crew of the tv.
/// </summary>
[JsonIgnore]
public MediaCrew[] Crew { get; set;}
/// <summary>
/// Gets or Sets the keywords of the tv.
/// </summary>
[JsonIgnore]
public Keyword[] Keywords { get; set; }
/// <summary>
/// Gets or Sets available translation for the tv.
/// </summary>
[JsonIgnore]
public Translation[] Translations { get; set; }
/// <summary>
/// Gets or Sets the content rating for the tv series.
/// </summary>
[JsonIgnore]
public ContentRating[] ContentRatings { get; set; }
}
}
| |
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Globalization;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Shapes;
namespace Brushes
{
/// <summary>
/// Enables the user to configure a LinearGradientBrush interactively.
/// </summary>
public partial class InteractiveLinearGradientBrushExample : Page
{
public static readonly DependencyProperty SelectedMarkerProperty =
DependencyProperty.Register
("SelectedMarker", typeof (Shape), typeof (InteractiveLinearGradientBrushExample),
new PropertyMetadata(null));
public InteractiveLinearGradientBrushExample()
{
InitializeComponent();
}
private void OnPageLoaded(object sender, RoutedEventArgs s)
{
MappingModeComboBox.SelectionChanged += MappingModeChanged;
OnStartPointTextBoxKeyUp(StartPointTextBox, null);
OnEndPointTextBoxKeyUp(EndPointTextBox, null);
}
// Update the StartPoint and EndPoint markers when the gradient display
// element's size changes.
private void GradientDisplaySizeChanged(object sender, SizeChangedEventArgs e)
{
// The marker positions only need recalcutated if the brush's MappingMode
// is RelativeToBoundingBox.
if (InteractiveLinearGradientBrush.MappingMode ==
BrushMappingMode.RelativeToBoundingBox)
{
StartPointMarkerTranslateTransform.X =
InteractiveLinearGradientBrush.StartPoint.X*e.NewSize.Width;
StartPointMarkerTranslateTransform.Y =
InteractiveLinearGradientBrush.StartPoint.Y*e.NewSize.Height;
EndPointMarkerTranslateTransform.X =
InteractiveLinearGradientBrush.EndPoint.X*e.NewSize.Width;
EndPointMarkerTranslateTransform.Y =
InteractiveLinearGradientBrush.EndPoint.Y*e.NewSize.Height;
}
}
private void OnStartPointTextBoxKeyUp(object sender, KeyEventArgs args)
{
var t = (TextBox) sender;
try
{
var p = Point.Parse(t.Text);
if (InteractiveLinearGradientBrush.MappingMode == BrushMappingMode.RelativeToBoundingBox)
{
StartPointMarkerTranslateTransform.X = p.X*GradientDisplayElement.ActualWidth;
StartPointMarkerTranslateTransform.Y = p.Y*GradientDisplayElement.ActualHeight;
}
else
{
StartPointMarkerTranslateTransform.X = p.X;
StartPointMarkerTranslateTransform.Y = p.Y;
}
}
catch (InvalidOperationException)
{
// Ignore errors.
}
catch (FormatException)
{
// Ignore errors.
}
}
private void OnEndPointTextBoxKeyUp(object sender, KeyEventArgs args)
{
var t = (TextBox) sender;
try
{
var p = Point.Parse(t.Text);
if (InteractiveLinearGradientBrush.MappingMode == BrushMappingMode.RelativeToBoundingBox)
{
EndPointMarkerTranslateTransform.X = p.X*GradientDisplayElement.ActualWidth;
EndPointMarkerTranslateTransform.Y = p.Y*GradientDisplayElement.ActualHeight;
}
else
{
EndPointMarkerTranslateTransform.X = p.X;
EndPointMarkerTranslateTransform.Y = p.Y;
}
}
catch (InvalidOperationException)
{
// Ignore errors.
}
catch (FormatException)
{
// Ignore errors.
}
}
// Determine whether the user clicked a marker.
private void GradientDisplayMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
if (e.OriginalSource is Shape)
{
SetValue(SelectedMarkerProperty, (Shape) e.OriginalSource);
}
else
SetValue(SelectedMarkerProperty, null);
}
// Determines whether the user just finished dragging a marker. If so,
// this method updates the brush's StartPoint or EndPoint property,
// depending on which marker was dragged.
private void GradientDisplayMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
var clickPoint = e.GetPosition(GradientDisplayElement);
var s = (Shape) GetValue(SelectedMarkerProperty);
if (s == EndPointMarker || s == StartPointMarker)
{
var translation = (TranslateTransform) s.RenderTransform;
translation.X = clickPoint.X;
translation.Y = clickPoint.Y;
SetValue(SelectedMarkerProperty, null);
Mouse.Synchronize();
Point p;
if (InteractiveLinearGradientBrush.MappingMode == BrushMappingMode.RelativeToBoundingBox)
{
p = new Point(clickPoint.X/GradientDisplayElement.ActualWidth,
clickPoint.Y/GradientDisplayElement.ActualHeight);
}
else
{
p = clickPoint;
}
if (s == StartPointMarker)
{
InteractiveLinearGradientBrush.StartPoint = p;
StartPointTextBox.Text = p.X.ToString("F4") + "," + p.Y.ToString("F4");
}
else
{
InteractiveLinearGradientBrush.EndPoint = p;
EndPointTextBox.Text = p.X.ToString("F4") + "," + p.Y.ToString("F4");
}
}
}
// Update the StartPoint or EndPoint when the user drags one of the
// points with the mouse.
private void GradientDisplayMouseMove(object sender, MouseEventArgs e)
{
var currentPoint = e.GetPosition(GradientDisplayElement);
var s = (Shape) GetValue(SelectedMarkerProperty);
// Determine whether the user dragged a StartPoint or
// EndPoint marker.
if (s == EndPointMarker || s == StartPointMarker)
{
// Move the selected marker to the current mouse position.
var translation = (TranslateTransform) s.RenderTransform;
translation.X = currentPoint.X;
translation.Y = currentPoint.Y;
Mouse.Synchronize();
Point p;
// Calculate the StartPoint or EndPoint.
if (InteractiveLinearGradientBrush.MappingMode ==
BrushMappingMode.RelativeToBoundingBox)
{
// If the MappingMode is relative, compute the relative
// value of the new point.
p = new Point(currentPoint.X/GradientDisplayElement.ActualWidth,
currentPoint.Y/GradientDisplayElement.ActualHeight);
}
else
{
// If the MappingMode is absolute, there's no more
// work to do.
p = currentPoint;
}
if (s == StartPointMarker)
{
// If the selected marker is the StartPoint marker,
// update the brush's StartPoint.
InteractiveLinearGradientBrush.StartPoint = p;
StartPointTextBox.Text = p.X.ToString("F4") + "," + p.Y.ToString("F4");
}
else
{
// Otherwise, update the brush's EndPoint.
InteractiveLinearGradientBrush.EndPoint = p;
EndPointTextBox.Text = p.X.ToString("F4") + "," + p.Y.ToString("F4");
}
}
}
// Updates the StartPoint and EndPoint and their markers when
// the user changes the brush's MappingMode.
private void MappingModeChanged(object sender, SelectionChangedEventArgs e)
{
var oldStartPoint = InteractiveLinearGradientBrush.StartPoint;
var newStartPoint = new Point();
var oldEndPoint = InteractiveLinearGradientBrush.EndPoint;
var newEndPoint = new Point();
if (InteractiveLinearGradientBrush.MappingMode ==
BrushMappingMode.RelativeToBoundingBox)
{
// The MappingMode changed from absolute to relative.
// To find the new relative point, divide the old absolute points
// by the painted area's width and height.
newStartPoint.X = oldStartPoint.X/GradientDisplayElement.ActualWidth;
newStartPoint.Y = oldStartPoint.Y/GradientDisplayElement.ActualHeight;
InteractiveLinearGradientBrush.StartPoint = newStartPoint;
newEndPoint.X = oldEndPoint.X/GradientDisplayElement.ActualWidth;
newEndPoint.Y = oldEndPoint.Y/GradientDisplayElement.ActualHeight;
InteractiveLinearGradientBrush.EndPoint = newEndPoint;
}
else
{
// The MappingMode changed from relative to absolute.
// To find the new absolute point, multiply the old relative points
// by the painted area's width and height.
newStartPoint.X = oldStartPoint.X*GradientDisplayElement.ActualWidth;
newStartPoint.Y = oldStartPoint.Y*GradientDisplayElement.ActualHeight;
InteractiveLinearGradientBrush.StartPoint = newStartPoint;
newEndPoint.X = oldEndPoint.X*GradientDisplayElement.ActualWidth;
newEndPoint.Y = oldEndPoint.Y*GradientDisplayElement.ActualHeight;
InteractiveLinearGradientBrush.EndPoint = newEndPoint;
}
// Update the StartPoint and EndPoint display text.
StartPointTextBox.Text = newStartPoint.X.ToString("F4") +
"," + newStartPoint.Y.ToString("F4");
EndPointTextBox.Text = newEndPoint.X.ToString("F4") +
"," + newEndPoint.Y.ToString("F4");
}
// Update the markup display whenever the brush changes.
private void OnInteractiveLinearGradientBrushChanged(object sender, EventArgs e)
{
if (GradientDisplayElement != null)
{
markupOutputTextBlock.Text =
GenerateLinearGradientBrushMarkup(InteractiveLinearGradientBrush);
}
}
// Helper method that displays the markup of interest for
// creating the specified brush.
private static string GenerateLinearGradientBrushMarkup(LinearGradientBrush theBrush)
{
var sBuilder = new StringBuilder();
sBuilder.Append("<" + theBrush.GetType().Name + "\n" +
" StartPoint=\"" + theBrush.StartPoint + "\"" +
" EndPoint=\"" + theBrush.EndPoint + "\" \n" +
" MappingMode=\"" + theBrush.MappingMode + "\"" +
" SpreadMethod=\"" + theBrush.SpreadMethod + "\"\n" +
" ColorInterpolationMode=\"" + theBrush.ColorInterpolationMode + "\"" +
" Opacity=\"" + theBrush.Opacity.ToString(CultureInfo.InvariantCulture) + "\"" + ">\n");
foreach (var stop in theBrush.GradientStops)
{
sBuilder.Append
(
" <GradientStop Offset=\"" + stop.Offset.ToString("F4")
+ "\" Color=\"" + stop.Color + "\" />\n"
);
}
sBuilder.Append("</LinearGradientBrush>");
return sBuilder.ToString();
}
}
}
| |
/*
* Copyright 2012-2021 The Pkcs11Interop Project
*
* 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.
*/
/*
* Written for the Pkcs11Interop project by:
* Jaroslav IMRICH <jimrich@jimrich.sk>
*/
using System;
using Net.Pkcs11Interop.Common;
using Net.Pkcs11Interop.LowLevelAPI41;
using NUnit.Framework;
using NativeULong = System.UInt32;
// Note: Code in this file is maintained manually.
namespace Net.Pkcs11Interop.Tests.LowLevelAPI41
{
/// <summary>
/// C_GenerateKey and C_GenerateKeyPair tests.
/// </summary>
[TestFixture()]
public class _19_GenerateKeyAndKeyPairTest
{
/// <summary>
/// C_GenerateKey test.
/// </summary>
[Test()]
public void _01_GenerateKeyTest()
{
Helpers.CheckPlatform();
CKR rv = CKR.CKR_OK;
using (Pkcs11Library pkcs11Library = new Pkcs11Library(Settings.Pkcs11LibraryPath))
{
rv = pkcs11Library.C_Initialize(Settings.InitArgs41);
if ((rv != CKR.CKR_OK) && (rv != CKR.CKR_CRYPTOKI_ALREADY_INITIALIZED))
Assert.Fail(rv.ToString());
// Find first slot with token present
NativeULong slotId = Helpers.GetUsableSlot(pkcs11Library);
NativeULong session = CK.CK_INVALID_HANDLE;
rv = pkcs11Library.C_OpenSession(slotId, (CKF.CKF_SERIAL_SESSION | CKF.CKF_RW_SESSION), IntPtr.Zero, IntPtr.Zero, ref session);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Login as normal user
rv = pkcs11Library.C_Login(session, CKU.CKU_USER, Settings.NormalUserPinArray, ConvertUtils.UInt32FromInt32(Settings.NormalUserPinArray.Length));
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Prepare attribute template of new key
CK_ATTRIBUTE[] template = new CK_ATTRIBUTE[4];
template[0] = CkaUtils.CreateAttribute(CKA.CKA_CLASS, CKO.CKO_SECRET_KEY);
template[1] = CkaUtils.CreateAttribute(CKA.CKA_KEY_TYPE, CKK.CKK_DES3);
template[2] = CkaUtils.CreateAttribute(CKA.CKA_ENCRYPT, true);
template[3] = CkaUtils.CreateAttribute(CKA.CKA_DECRYPT, true);
// Specify key generation mechanism (needs no parameter => no unamanaged memory is needed)
CK_MECHANISM mechanism = CkmUtils.CreateMechanism(CKM.CKM_DES3_KEY_GEN);
// Generate key
NativeULong keyId = CK.CK_INVALID_HANDLE;
rv = pkcs11Library.C_GenerateKey(session, ref mechanism, template, ConvertUtils.UInt32FromInt32(template.Length), ref keyId);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// In LowLevelAPI we have to free unmanaged memory taken by attributes
for (int i = 0; i < template.Length; i++)
{
UnmanagedMemory.Free(ref template[i].value);
template[i].valueLen = 0;
}
// Do something interesting with generated key
// Destroy object
rv = pkcs11Library.C_DestroyObject(session, keyId);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
rv = pkcs11Library.C_Logout(session);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
rv = pkcs11Library.C_CloseSession(session);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
rv = pkcs11Library.C_Finalize(IntPtr.Zero);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
}
}
/// <summary>
/// C_GenerateKeyPair test.
/// </summary>
[Test()]
public void _02_GenerateKeyPairTest()
{
Helpers.CheckPlatform();
CKR rv = CKR.CKR_OK;
using (Pkcs11Library pkcs11Library = new Pkcs11Library(Settings.Pkcs11LibraryPath))
{
rv = pkcs11Library.C_Initialize(Settings.InitArgs41);
if ((rv != CKR.CKR_OK) && (rv != CKR.CKR_CRYPTOKI_ALREADY_INITIALIZED))
Assert.Fail(rv.ToString());
// Find first slot with token present
NativeULong slotId = Helpers.GetUsableSlot(pkcs11Library);
NativeULong session = CK.CK_INVALID_HANDLE;
rv = pkcs11Library.C_OpenSession(slotId, (CKF.CKF_SERIAL_SESSION | CKF.CKF_RW_SESSION), IntPtr.Zero, IntPtr.Zero, ref session);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Login as normal user
rv = pkcs11Library.C_Login(session, CKU.CKU_USER, Settings.NormalUserPinArray, ConvertUtils.UInt32FromInt32(Settings.NormalUserPinArray.Length));
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// The CKA_ID attribute is intended as a means of distinguishing multiple key pairs held by the same subject
byte[] ckaId = new byte[20];
rv = pkcs11Library.C_GenerateRandom(session, ckaId, ConvertUtils.UInt32FromInt32(ckaId.Length));
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Prepare attribute template of new public key
CK_ATTRIBUTE[] pubKeyTemplate = new CK_ATTRIBUTE[10];
pubKeyTemplate[0] = CkaUtils.CreateAttribute(CKA.CKA_TOKEN, true);
pubKeyTemplate[1] = CkaUtils.CreateAttribute(CKA.CKA_PRIVATE, false);
pubKeyTemplate[2] = CkaUtils.CreateAttribute(CKA.CKA_LABEL, Settings.ApplicationName);
pubKeyTemplate[3] = CkaUtils.CreateAttribute(CKA.CKA_ID, ckaId);
pubKeyTemplate[4] = CkaUtils.CreateAttribute(CKA.CKA_ENCRYPT, true);
pubKeyTemplate[5] = CkaUtils.CreateAttribute(CKA.CKA_VERIFY, true);
pubKeyTemplate[6] = CkaUtils.CreateAttribute(CKA.CKA_VERIFY_RECOVER, true);
pubKeyTemplate[7] = CkaUtils.CreateAttribute(CKA.CKA_WRAP, true);
pubKeyTemplate[8] = CkaUtils.CreateAttribute(CKA.CKA_MODULUS_BITS, 1024);
pubKeyTemplate[9] = CkaUtils.CreateAttribute(CKA.CKA_PUBLIC_EXPONENT, new byte[] { 0x01, 0x00, 0x01 });
// Prepare attribute template of new private key
CK_ATTRIBUTE[] privKeyTemplate = new CK_ATTRIBUTE[9];
privKeyTemplate[0] = CkaUtils.CreateAttribute(CKA.CKA_TOKEN, true);
privKeyTemplate[1] = CkaUtils.CreateAttribute(CKA.CKA_PRIVATE, true);
privKeyTemplate[2] = CkaUtils.CreateAttribute(CKA.CKA_LABEL, Settings.ApplicationName);
privKeyTemplate[3] = CkaUtils.CreateAttribute(CKA.CKA_ID, ckaId);
privKeyTemplate[4] = CkaUtils.CreateAttribute(CKA.CKA_SENSITIVE, true);
privKeyTemplate[5] = CkaUtils.CreateAttribute(CKA.CKA_DECRYPT, true);
privKeyTemplate[6] = CkaUtils.CreateAttribute(CKA.CKA_SIGN, true);
privKeyTemplate[7] = CkaUtils.CreateAttribute(CKA.CKA_SIGN_RECOVER, true);
privKeyTemplate[8] = CkaUtils.CreateAttribute(CKA.CKA_UNWRAP, true);
// Specify key generation mechanism (needs no parameter => no unamanaged memory is needed)
CK_MECHANISM mechanism = CkmUtils.CreateMechanism(CKM.CKM_RSA_PKCS_KEY_PAIR_GEN);
// Generate key pair
NativeULong pubKeyId = CK.CK_INVALID_HANDLE;
NativeULong privKeyId = CK.CK_INVALID_HANDLE;
rv = pkcs11Library.C_GenerateKeyPair(session, ref mechanism, pubKeyTemplate, ConvertUtils.UInt32FromInt32(pubKeyTemplate.Length), privKeyTemplate, ConvertUtils.UInt32FromInt32(privKeyTemplate.Length), ref pubKeyId, ref privKeyId);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// In LowLevelAPI we have to free unmanaged memory taken by attributes
for (int i = 0; i < privKeyTemplate.Length; i++)
{
UnmanagedMemory.Free(ref privKeyTemplate[i].value);
privKeyTemplate[i].valueLen = 0;
}
for (int i = 0; i < pubKeyTemplate.Length; i++)
{
UnmanagedMemory.Free(ref pubKeyTemplate[i].value);
pubKeyTemplate[i].valueLen = 0;
}
// Do something interesting with generated key pair
// Destroy object
rv = pkcs11Library.C_DestroyObject(session, privKeyId);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
rv = pkcs11Library.C_DestroyObject(session, pubKeyId);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
rv = pkcs11Library.C_Logout(session);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
rv = pkcs11Library.C_CloseSession(session);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
rv = pkcs11Library.C_Finalize(IntPtr.Zero);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
}
}
}
}
| |
#region .NET Disclaimer/Info
//===============================================================================
//
// gOODiDEA, uland.com
//===============================================================================
//
// $Header : $
// $Author : $
// $Date : $
// $Revision: $
// $History: $
//
//===============================================================================
#endregion
#region Java
/**
* Class GifDecoder - Decodes a GIF file into one or more frames.
* <br><pre>
* Example:
* GifDecoder d = new GifDecoder();
* d.read("sample.gif");
* int n = d.getFrameCount();
* for (int i = 0; i < n; i++) {
* BufferedImage frame = d.getFrame(i); // frame i
* int t = d.getDelay(i); // display duration of frame in milliseconds
* // do something with frame
* }
* </pre>
* No copyright asserted on the source code of this class. May be used for
* any purpose, however, refer to the Unisys LZW patent for any additional
* restrictions. Please forward any corrections to kweiner@fmsware.com.
*
* @author Kevin Weiner, FM Software; LZW decoder adapted from John Cristy's ImageMagick.
* @version 1.03 November 2003
*
*/
#endregion
using System;
using System.Collections;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
namespace Gif.Components
{
public class GifDecoder
{
/**
* File read status: No errors.
*/
public static readonly int STATUS_OK = 0;
/**
* File read status: Error decoding file (may be partially decoded)
*/
public static readonly int STATUS_FORMAT_ERROR = 1;
/**
* File read status: Unable to open source.
*/
public static readonly int STATUS_OPEN_ERROR = 2;
protected Stream inStream;
protected int status;
protected int width; // full image width
protected int height; // full image height
protected bool gctFlag; // global color table used
protected int gctSize; // size of global color table
protected int loopCount = 1; // iterations; 0 = repeat forever
protected int[] gct; // global color table
protected int[] lct; // local color table
protected int[] act; // active color table
protected int bgIndex; // background color index
protected int bgColor; // background color
protected int lastBgColor; // previous bg color
protected int pixelAspect; // pixel aspect ratio
protected bool lctFlag; // local color table flag
protected bool interlace; // interlace flag
protected int lctSize; // local color table size
protected int ix, iy, iw, ih; // current image rectangle
protected Rectangle lastRect; // last image rect
protected Image image; // current frame
protected Bitmap bitmap;
protected Image lastImage; // previous frame
protected byte[] block = new byte[256]; // current data block
protected int blockSize = 0; // block size
// last graphic control extension info
protected int dispose = 0;
// 0=no action; 1=leave in place; 2=restore to bg; 3=restore to prev
protected int lastDispose = 0;
protected bool transparency = false; // use transparent color
protected int delay = 0; // delay in milliseconds
protected int transIndex; // transparent color index
protected static readonly int MaxStackSize = 4096;
// max decoder pixel stack size
// LZW decoder working arrays
protected short[] prefix;
protected byte[] suffix;
protected byte[] pixelStack;
protected byte[] pixels;
protected ArrayList frames; // frames read from current file
protected int frameCount;
public class GifFrame
{
public GifFrame(Image im, int del)
{
image = im;
delay = del;
}
public Image image;
public int delay;
}
/**
* Gets display duration for specified frame.
*
* @param n int index of frame
* @return delay in milliseconds
*/
public int GetDelay(int n)
{
//
delay = -1;
if ((n >= 0) && (n < frameCount))
{
delay = ((GifFrame)frames[n]).delay;
}
return delay;
}
/**
* Gets the number of frames read from file.
* @return frame count
*/
public int GetFrameCount()
{
return frameCount;
}
/**
* Gets the first (or only) image read.
*
* @return BufferedImage containing first frame, or null if none.
*/
public Image GetImage()
{
return GetFrame(0);
}
/**
* Gets the "Netscape" iteration count, if any.
* A count of 0 means repeat indefinitiely.
*
* @return iteration count if one was specified, else 1.
*/
public int GetLoopCount()
{
return loopCount;
}
/**
* Creates new frame image from current data (and previous
* frames as specified by their disposition codes).
*/
int[] GetPixels(Bitmap bitmap)
{
int[] pixels = new int[3 * image.Width * image.Height];
int count = 0;
for (int th = 0; th < image.Height; th++)
{
for (int tw = 0; tw < image.Width; tw++)
{
Color color = bitmap.GetPixel(tw, th);
pixels[count] = color.R;
count++;
pixels[count] = color.G;
count++;
pixels[count] = color.B;
count++;
}
}
return pixels;
}
void SetPixels(int[] pixels)
{
int count = 0;
for (int th = 0; th < image.Height; th++)
{
for (int tw = 0; tw < image.Width; tw++)
{
Color color = Color.FromArgb(pixels[count++]);
bitmap.SetPixel(tw, th, color);
}
}
}
protected void SetPixels()
{
// expose destination image's pixels as int array
// int[] dest =
// (( int ) image.getRaster().getDataBuffer()).getData();
int[] dest = GetPixels(bitmap);
// fill in starting image contents based on last image's dispose code
if (lastDispose > 0)
{
if (lastDispose == 3)
{
// use image before last
int n = frameCount - 2;
if (n > 0)
{
lastImage = GetFrame(n - 1);
}
else
{
lastImage = null;
}
}
if (lastImage != null)
{
// int[] prev =
// ((DataBufferInt) lastImage.getRaster().getDataBuffer()).getData();
int[] prev = GetPixels(new Bitmap(lastImage));
Array.Copy(prev, 0, dest, 0, width * height);
// copy pixels
if (lastDispose == 2)
{
// fill last image rect area with background color
Graphics g = Graphics.FromImage(image);
Color c = Color.Empty;
if (transparency)
{
c = Color.FromArgb(0, 0, 0, 0); // assume background is transparent
}
else
{
c = Color.FromArgb(lastBgColor);
// c = new Color(lastBgColor); // use given background color
}
Brush brush = new SolidBrush(c);
g.FillRectangle(brush, lastRect);
brush.Dispose();
g.Dispose();
}
}
}
// copy each source line to the appropriate place in the destination
int pass = 1;
int inc = 8;
int iline = 0;
for (int i = 0; i < ih; i++)
{
int line = i;
if (interlace)
{
if (iline >= ih)
{
pass++;
switch (pass)
{
case 2:
iline = 4;
break;
case 3:
iline = 2;
inc = 4;
break;
case 4:
iline = 1;
inc = 2;
break;
}
}
line = iline;
iline += inc;
}
line += iy;
if (line < height)
{
int k = line * width;
int dx = k + ix; // start of line in dest
int dlim = dx + iw; // end of dest line
if ((k + width) < dlim)
{
dlim = k + width; // past dest edge
}
int sx = i * iw; // start of line in source
while (dx < dlim)
{
// map color and insert in destination
int index = ((int)pixels[sx++]) & 0xff;
int c = act[index];
if (c != 0)
{
dest[dx] = c;
}
dx++;
}
}
}
SetPixels(dest);
}
/**
* Gets the image contents of frame n.
*
* @return BufferedImage representation of frame, or null if n is invalid.
*/
public Image GetFrame(int n)
{
Image im = null;
if ((n >= 0) && (n < frameCount))
{
im = ((GifFrame)frames[n]).image;
}
return im;
}
/**
* Gets image size.
*
* @return GIF image dimensions
*/
public Size GetFrameSize()
{
return new Size(width, height);
}
/**
* Reads GIF image from stream
*
* @param BufferedInputStream containing GIF file.
* @return read status code (0 = no errors)
*/
public int Read(Stream inStream)
{
Init();
if (inStream != null)
{
this.inStream = inStream;
ReadHeader();
if (!Error())
{
ReadContents();
if (frameCount < 0)
{
status = STATUS_FORMAT_ERROR;
}
}
inStream.Close();
}
else
{
status = STATUS_OPEN_ERROR;
}
return status;
}
/**
* Reads GIF file from specified file/URL source
* (URL assumed if name contains ":/" or "file:")
*
* @param name String containing source
* @return read status code (0 = no errors)
*/
public int Read(String name)
{
status = STATUS_OK;
try
{
name = name.Trim().ToLower();
status = Read(new FileInfo(name).OpenRead());
}
catch (IOException)
{
status = STATUS_OPEN_ERROR;
}
return status;
}
/**
* Decodes LZW image data into pixel array.
* Adapted from John Cristy's ImageMagick.
*/
protected void DecodeImageData()
{
int NullCode = -1;
int npix = iw * ih;
int available,
clear,
code_mask,
code_size,
end_of_information,
in_code,
old_code,
bits,
code,
count,
i,
datum,
data_size,
first,
top,
bi,
pi;
if ((pixels == null) || (pixels.Length < npix))
{
pixels = new byte[npix]; // allocate new pixel array
}
if (prefix == null) prefix = new short[MaxStackSize];
if (suffix == null) suffix = new byte[MaxStackSize];
if (pixelStack == null) pixelStack = new byte[MaxStackSize + 1];
// Initialize GIF data stream decoder.
data_size = Read();
clear = 1 << data_size;
end_of_information = clear + 1;
available = clear + 2;
old_code = NullCode;
code_size = data_size + 1;
code_mask = (1 << code_size) - 1;
for (code = 0; code < clear; code++)
{
prefix[code] = 0;
suffix[code] = (byte)code;
}
// Decode GIF pixel stream.
datum = bits = count = first = top = pi = bi = 0;
for (i = 0; i < npix; )
{
if (top == 0)
{
if (bits < code_size)
{
// Load bytes until there are enough bits for a code.
if (count == 0)
{
// Read a new data block.
count = ReadBlock();
if (count <= 0)
break;
bi = 0;
}
datum += (((int)block[bi]) & 0xff) << bits;
bits += 8;
bi++;
count--;
continue;
}
// Get the next code.
code = datum & code_mask;
datum >>= code_size;
bits -= code_size;
// Interpret the code
if ((code > available) || (code == end_of_information))
break;
if (code == clear)
{
// Reset decoder.
code_size = data_size + 1;
code_mask = (1 << code_size) - 1;
available = clear + 2;
old_code = NullCode;
continue;
}
if (old_code == NullCode)
{
pixelStack[top++] = suffix[code];
old_code = code;
first = code;
continue;
}
in_code = code;
if (code == available)
{
pixelStack[top++] = (byte)first;
code = old_code;
}
while (code > clear)
{
pixelStack[top++] = suffix[code];
code = prefix[code];
}
first = ((int)suffix[code]) & 0xff;
// Add a new string to the string table,
if (available >= MaxStackSize)
break;
pixelStack[top++] = (byte)first;
prefix[available] = (short)old_code;
suffix[available] = (byte)first;
available++;
if (((available & code_mask) == 0)
&& (available < MaxStackSize))
{
code_size++;
code_mask += available;
}
old_code = in_code;
}
// Pop a pixel off the pixel stack.
top--;
pixels[pi++] = pixelStack[top];
i++;
}
for (i = pi; i < npix; i++)
{
pixels[i] = 0; // clear missing pixels
}
}
/**
* Returns true if an error was encountered during reading/decoding
*/
protected bool Error()
{
return status != STATUS_OK;
}
/**
* Initializes or re-initializes reader
*/
protected void Init()
{
status = STATUS_OK;
frameCount = 0;
frames = new ArrayList();
gct = null;
lct = null;
}
/**
* Reads a single byte from the input stream.
*/
protected int Read()
{
int curByte = 0;
try
{
curByte = inStream.ReadByte();
}
catch (IOException)
{
status = STATUS_FORMAT_ERROR;
}
return curByte;
}
/**
* Reads next variable length block from input.
*
* @return number of bytes stored in "buffer"
*/
protected int ReadBlock()
{
blockSize = Read();
int n = 0;
if (blockSize > 0)
{
try
{
int count = 0;
while (n < blockSize)
{
count = inStream.Read(block, n, blockSize - n);
if (count == -1)
break;
n += count;
}
}
catch (IOException)
{
}
if (n < blockSize)
{
status = STATUS_FORMAT_ERROR;
}
}
return n;
}
/**
* Reads color table as 256 RGB integer values
*
* @param ncolors int number of colors to read
* @return int array containing 256 colors (packed ARGB with full alpha)
*/
protected int[] ReadColorTable(int ncolors)
{
int nbytes = 3 * ncolors;
int[] tab = null;
byte[] c = new byte[nbytes];
int n = 0;
try
{
n = inStream.Read(c, 0, c.Length);
}
catch (IOException)
{
}
if (n < nbytes)
{
status = STATUS_FORMAT_ERROR;
}
else
{
tab = new int[256]; // max size to avoid bounds checks
int i = 0;
int j = 0;
while (i < ncolors)
{
UInt32 r = ((UInt32)c[j++]) & 0xff;
UInt32 g = ((UInt32)c[j++]) & 0xff;
UInt32 b = ((UInt32)c[j++]) & 0xff;
tab[i++] = (int)(0xff000000 | (r << 16) | (g << 8) | b);
}
}
return tab;
}
/**
* Main file parser. Reads GIF content blocks.
*/
protected void ReadContents()
{
// read GIF file content blocks
bool done = false;
while (!(done || Error()))
{
int code = Read();
switch (code)
{
case 0x2C: // image separator
ReadImage();
break;
case 0x21: // extension
code = Read();
switch (code)
{
case 0xf9: // graphics control extension
ReadGraphicControlExt();
break;
case 0xff: // application extension
ReadBlock();
String app = "";
for (int i = 0; i < 11; i++)
{
app += (char)block[i];
}
if (app.Equals("NETSCAPE2.0"))
{
ReadNetscapeExt();
}
else
Skip(); // don't care
break;
default: // uninteresting extension
Skip();
break;
}
break;
case 0x3b: // terminator
done = true;
break;
case 0x00: // bad byte, but keep going and see what happens
break;
default:
status = STATUS_FORMAT_ERROR;
break;
}
}
}
/**
* Reads Graphics Control Extension values
*/
protected void ReadGraphicControlExt()
{
Read(); // block size
int packed = Read(); // packed fields
dispose = (packed & 0x1c) >> 2; // disposal method
if (dispose == 0)
{
dispose = 1; // elect to keep old image if discretionary
}
transparency = (packed & 1) != 0;
delay = ReadShort() * 10; // delay in milliseconds
transIndex = Read(); // transparent color index
Read(); // block terminator
}
/**
* Reads GIF file header information.
*/
protected void ReadHeader()
{
String id = "";
for (int i = 0; i < 6; i++)
{
id += (char)Read();
}
if (!id.StartsWith("GIF"))
{
status = STATUS_FORMAT_ERROR;
return;
}
ReadLSD();
if (gctFlag && !Error())
{
gct = ReadColorTable(gctSize);
bgColor = gct[bgIndex];
}
}
/**
* Reads next frame image
*/
protected void ReadImage()
{
ix = ReadShort(); // (sub)image position & size
iy = ReadShort();
iw = ReadShort();
ih = ReadShort();
int packed = Read();
lctFlag = (packed & 0x80) != 0; // 1 - local color table flag
interlace = (packed & 0x40) != 0; // 2 - interlace flag
// 3 - sort flag
// 4-5 - reserved
lctSize = 2 << (packed & 7); // 6-8 - local color table size
if (lctFlag)
{
lct = ReadColorTable(lctSize); // read table
act = lct; // make local table active
}
else
{
act = gct; // make global table active
if (bgIndex == transIndex)
bgColor = 0;
}
int save = 0;
if (transparency)
{
save = act[transIndex];
act[transIndex] = 0; // set transparent color if specified
}
if (act == null)
{
status = STATUS_FORMAT_ERROR; // no color table defined
}
if (Error()) return;
DecodeImageData(); // decode pixel data
Skip();
if (Error()) return;
frameCount++;
// create new image to receive frame data
// image =
// new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB_PRE);
bitmap = new Bitmap(width, height);
image = bitmap;
SetPixels(); // transfer pixel data to image
frames.Add(new GifFrame(bitmap, delay)); // add image to frame list
if (transparency)
{
act[transIndex] = save;
}
ResetFrame();
}
/**
* Reads Logical Screen Descriptor
*/
protected void ReadLSD()
{
// logical screen size
width = ReadShort();
height = ReadShort();
// packed fields
int packed = Read();
gctFlag = (packed & 0x80) != 0; // 1 : global color table flag
// 2-4 : color resolution
// 5 : gct sort flag
gctSize = 2 << (packed & 7); // 6-8 : gct size
bgIndex = Read(); // background color index
pixelAspect = Read(); // pixel aspect ratio
}
/**
* Reads Netscape extenstion to obtain iteration count
*/
protected void ReadNetscapeExt()
{
do
{
ReadBlock();
if (block[0] == 1)
{
// loop count sub-block
int b1 = ((int)block[1]) & 0xff;
int b2 = ((int)block[2]) & 0xff;
loopCount = (b2 << 8) | b1;
}
} while ((blockSize > 0) && !Error());
}
/**
* Reads next 16-bit value, LSB first
*/
protected int ReadShort()
{
// read 16-bit value, LSB first
return Read() | (Read() << 8);
}
/**
* Resets frame state for reading next image.
*/
protected void ResetFrame()
{
lastDispose = dispose;
lastRect = new Rectangle(ix, iy, iw, ih);
lastImage = image;
lastBgColor = bgColor;
// int dispose = 0;
lct = null;
}
/**
* Skips variable length blocks up to and including
* next zero length block.
*/
protected void Skip()
{
do
{
ReadBlock();
} while ((blockSize > 0) && !Error());
}
}
}
| |
// Copyright 2017, Google Inc. 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.
// Generated code. DO NOT EDIT!
using Google.Api.Gax;
using Google.Api.Gax.Grpc;
using Google.Protobuf.WellKnownTypes;
using Grpc.Core;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Threading;
using System.Threading.Tasks;
namespace Google.Cloud.Logging.V2
{
/// <summary>
/// Settings for a <see cref="MetricsServiceV2Client"/>.
/// </summary>
public sealed partial class MetricsServiceV2Settings : ServiceSettingsBase
{
/// <summary>
/// Get a new instance of the default <see cref="MetricsServiceV2Settings"/>.
/// </summary>
/// <returns>
/// A new instance of the default <see cref="MetricsServiceV2Settings"/>.
/// </returns>
public static MetricsServiceV2Settings GetDefault() => new MetricsServiceV2Settings();
/// <summary>
/// Constructs a new <see cref="MetricsServiceV2Settings"/> object with default settings.
/// </summary>
public MetricsServiceV2Settings() { }
private MetricsServiceV2Settings(MetricsServiceV2Settings existing) : base(existing)
{
GaxPreconditions.CheckNotNull(existing, nameof(existing));
ListLogMetricsSettings = existing.ListLogMetricsSettings;
GetLogMetricSettings = existing.GetLogMetricSettings;
CreateLogMetricSettings = existing.CreateLogMetricSettings;
UpdateLogMetricSettings = existing.UpdateLogMetricSettings;
DeleteLogMetricSettings = existing.DeleteLogMetricSettings;
OnCopy(existing);
}
partial void OnCopy(MetricsServiceV2Settings existing);
/// <summary>
/// The filter specifying which RPC <see cref="StatusCode"/>s are eligible for retry
/// for "Idempotent" <see cref="MetricsServiceV2Client"/> RPC methods.
/// </summary>
/// <remarks>
/// The eligible RPC <see cref="StatusCode"/>s for retry for "Idempotent" RPC methods are:
/// <list type="bullet">
/// <item><description><see cref="StatusCode.DeadlineExceeded"/></description></item>
/// <item><description><see cref="StatusCode.Unavailable"/></description></item>
/// </list>
/// </remarks>
public static Predicate<RpcException> IdempotentRetryFilter { get; } =
RetrySettings.FilterForStatusCodes(StatusCode.DeadlineExceeded, StatusCode.Unavailable);
/// <summary>
/// The filter specifying which RPC <see cref="StatusCode"/>s are eligible for retry
/// for "NonIdempotent" <see cref="MetricsServiceV2Client"/> RPC methods.
/// </summary>
/// <remarks>
/// The eligible RPC <see cref="StatusCode"/>s for retry for "NonIdempotent" RPC methods are:
/// <list type="bullet">
/// <item><description><see cref="StatusCode.Unavailable"/></description></item>
/// </list>
/// </remarks>
public static Predicate<RpcException> NonIdempotentRetryFilter { get; } =
RetrySettings.FilterForStatusCodes(StatusCode.Unavailable);
/// <summary>
/// "Default" retry backoff for <see cref="MetricsServiceV2Client"/> RPC methods.
/// </summary>
/// <returns>
/// The "Default" retry backoff for <see cref="MetricsServiceV2Client"/> RPC methods.
/// </returns>
/// <remarks>
/// The "Default" retry backoff for <see cref="MetricsServiceV2Client"/> RPC methods is defined as:
/// <list type="bullet">
/// <item><description>Initial delay: 100 milliseconds</description></item>
/// <item><description>Maximum delay: 1000 milliseconds</description></item>
/// <item><description>Delay multiplier: 1.2</description></item>
/// </list>
/// </remarks>
public static BackoffSettings GetDefaultRetryBackoff() => new BackoffSettings(
delay: TimeSpan.FromMilliseconds(100),
maxDelay: TimeSpan.FromMilliseconds(1000),
delayMultiplier: 1.2
);
/// <summary>
/// "Default" timeout backoff for <see cref="MetricsServiceV2Client"/> RPC methods.
/// </summary>
/// <returns>
/// The "Default" timeout backoff for <see cref="MetricsServiceV2Client"/> RPC methods.
/// </returns>
/// <remarks>
/// The "Default" timeout backoff for <see cref="MetricsServiceV2Client"/> RPC methods is defined as:
/// <list type="bullet">
/// <item><description>Initial timeout: 2000 milliseconds</description></item>
/// <item><description>Timeout multiplier: 1.5</description></item>
/// <item><description>Maximum timeout: 30000 milliseconds</description></item>
/// </list>
/// </remarks>
public static BackoffSettings GetDefaultTimeoutBackoff() => new BackoffSettings(
delay: TimeSpan.FromMilliseconds(2000),
maxDelay: TimeSpan.FromMilliseconds(30000),
delayMultiplier: 1.5
);
/// <summary>
/// <see cref="CallSettings"/> for synchronous and asynchronous calls to
/// <c>MetricsServiceV2Client.ListLogMetrics</c> and <c>MetricsServiceV2Client.ListLogMetricsAsync</c>.
/// </summary>
/// <remarks>
/// The default <c>MetricsServiceV2Client.ListLogMetrics</c> and
/// <c>MetricsServiceV2Client.ListLogMetricsAsync</c> <see cref="RetrySettings"/> are:
/// <list type="bullet">
/// <item><description>Initial retry delay: 100 milliseconds</description></item>
/// <item><description>Retry delay multiplier: 1.2</description></item>
/// <item><description>Retry maximum delay: 1000 milliseconds</description></item>
/// <item><description>Initial timeout: 2000 milliseconds</description></item>
/// <item><description>Timeout multiplier: 1.5</description></item>
/// <item><description>Timeout maximum delay: 30000 milliseconds</description></item>
/// </list>
/// Retry will be attempted on the following response status codes:
/// <list>
/// <item><description><see cref="StatusCode.DeadlineExceeded"/></description></item>
/// <item><description><see cref="StatusCode.Unavailable"/></description></item>
/// </list>
/// Default RPC expiration is 45000 milliseconds.
/// </remarks>
public CallSettings ListLogMetricsSettings { get; set; } = CallSettings.FromCallTiming(
CallTiming.FromRetry(new RetrySettings(
retryBackoff: GetDefaultRetryBackoff(),
timeoutBackoff: GetDefaultTimeoutBackoff(),
totalExpiration: Expiration.FromTimeout(TimeSpan.FromMilliseconds(45000)),
retryFilter: IdempotentRetryFilter
)));
/// <summary>
/// <see cref="CallSettings"/> for synchronous and asynchronous calls to
/// <c>MetricsServiceV2Client.GetLogMetric</c> and <c>MetricsServiceV2Client.GetLogMetricAsync</c>.
/// </summary>
/// <remarks>
/// The default <c>MetricsServiceV2Client.GetLogMetric</c> and
/// <c>MetricsServiceV2Client.GetLogMetricAsync</c> <see cref="RetrySettings"/> are:
/// <list type="bullet">
/// <item><description>Initial retry delay: 100 milliseconds</description></item>
/// <item><description>Retry delay multiplier: 1.2</description></item>
/// <item><description>Retry maximum delay: 1000 milliseconds</description></item>
/// <item><description>Initial timeout: 2000 milliseconds</description></item>
/// <item><description>Timeout multiplier: 1.5</description></item>
/// <item><description>Timeout maximum delay: 30000 milliseconds</description></item>
/// </list>
/// Retry will be attempted on the following response status codes:
/// <list>
/// <item><description><see cref="StatusCode.DeadlineExceeded"/></description></item>
/// <item><description><see cref="StatusCode.Unavailable"/></description></item>
/// </list>
/// Default RPC expiration is 45000 milliseconds.
/// </remarks>
public CallSettings GetLogMetricSettings { get; set; } = CallSettings.FromCallTiming(
CallTiming.FromRetry(new RetrySettings(
retryBackoff: GetDefaultRetryBackoff(),
timeoutBackoff: GetDefaultTimeoutBackoff(),
totalExpiration: Expiration.FromTimeout(TimeSpan.FromMilliseconds(45000)),
retryFilter: IdempotentRetryFilter
)));
/// <summary>
/// <see cref="CallSettings"/> for synchronous and asynchronous calls to
/// <c>MetricsServiceV2Client.CreateLogMetric</c> and <c>MetricsServiceV2Client.CreateLogMetricAsync</c>.
/// </summary>
/// <remarks>
/// The default <c>MetricsServiceV2Client.CreateLogMetric</c> and
/// <c>MetricsServiceV2Client.CreateLogMetricAsync</c> <see cref="RetrySettings"/> are:
/// <list type="bullet">
/// <item><description>Initial retry delay: 100 milliseconds</description></item>
/// <item><description>Retry delay multiplier: 1.2</description></item>
/// <item><description>Retry maximum delay: 1000 milliseconds</description></item>
/// <item><description>Initial timeout: 2000 milliseconds</description></item>
/// <item><description>Timeout multiplier: 1.5</description></item>
/// <item><description>Timeout maximum delay: 30000 milliseconds</description></item>
/// </list>
/// Retry will be attempted on the following response status codes:
/// <list>
/// <item><description><see cref="StatusCode.Unavailable"/></description></item>
/// </list>
/// Default RPC expiration is 45000 milliseconds.
/// </remarks>
public CallSettings CreateLogMetricSettings { get; set; } = CallSettings.FromCallTiming(
CallTiming.FromRetry(new RetrySettings(
retryBackoff: GetDefaultRetryBackoff(),
timeoutBackoff: GetDefaultTimeoutBackoff(),
totalExpiration: Expiration.FromTimeout(TimeSpan.FromMilliseconds(45000)),
retryFilter: NonIdempotentRetryFilter
)));
/// <summary>
/// <see cref="CallSettings"/> for synchronous and asynchronous calls to
/// <c>MetricsServiceV2Client.UpdateLogMetric</c> and <c>MetricsServiceV2Client.UpdateLogMetricAsync</c>.
/// </summary>
/// <remarks>
/// The default <c>MetricsServiceV2Client.UpdateLogMetric</c> and
/// <c>MetricsServiceV2Client.UpdateLogMetricAsync</c> <see cref="RetrySettings"/> are:
/// <list type="bullet">
/// <item><description>Initial retry delay: 100 milliseconds</description></item>
/// <item><description>Retry delay multiplier: 1.2</description></item>
/// <item><description>Retry maximum delay: 1000 milliseconds</description></item>
/// <item><description>Initial timeout: 2000 milliseconds</description></item>
/// <item><description>Timeout multiplier: 1.5</description></item>
/// <item><description>Timeout maximum delay: 30000 milliseconds</description></item>
/// </list>
/// Retry will be attempted on the following response status codes:
/// <list>
/// <item><description><see cref="StatusCode.Unavailable"/></description></item>
/// </list>
/// Default RPC expiration is 45000 milliseconds.
/// </remarks>
public CallSettings UpdateLogMetricSettings { get; set; } = CallSettings.FromCallTiming(
CallTiming.FromRetry(new RetrySettings(
retryBackoff: GetDefaultRetryBackoff(),
timeoutBackoff: GetDefaultTimeoutBackoff(),
totalExpiration: Expiration.FromTimeout(TimeSpan.FromMilliseconds(45000)),
retryFilter: NonIdempotentRetryFilter
)));
/// <summary>
/// <see cref="CallSettings"/> for synchronous and asynchronous calls to
/// <c>MetricsServiceV2Client.DeleteLogMetric</c> and <c>MetricsServiceV2Client.DeleteLogMetricAsync</c>.
/// </summary>
/// <remarks>
/// The default <c>MetricsServiceV2Client.DeleteLogMetric</c> and
/// <c>MetricsServiceV2Client.DeleteLogMetricAsync</c> <see cref="RetrySettings"/> are:
/// <list type="bullet">
/// <item><description>Initial retry delay: 100 milliseconds</description></item>
/// <item><description>Retry delay multiplier: 1.2</description></item>
/// <item><description>Retry maximum delay: 1000 milliseconds</description></item>
/// <item><description>Initial timeout: 2000 milliseconds</description></item>
/// <item><description>Timeout multiplier: 1.5</description></item>
/// <item><description>Timeout maximum delay: 30000 milliseconds</description></item>
/// </list>
/// Retry will be attempted on the following response status codes:
/// <list>
/// <item><description><see cref="StatusCode.DeadlineExceeded"/></description></item>
/// <item><description><see cref="StatusCode.Unavailable"/></description></item>
/// </list>
/// Default RPC expiration is 45000 milliseconds.
/// </remarks>
public CallSettings DeleteLogMetricSettings { get; set; } = CallSettings.FromCallTiming(
CallTiming.FromRetry(new RetrySettings(
retryBackoff: GetDefaultRetryBackoff(),
timeoutBackoff: GetDefaultTimeoutBackoff(),
totalExpiration: Expiration.FromTimeout(TimeSpan.FromMilliseconds(45000)),
retryFilter: IdempotentRetryFilter
)));
/// <summary>
/// Creates a deep clone of this object, with all the same property values.
/// </summary>
/// <returns>A deep clone of this <see cref="MetricsServiceV2Settings"/> object.</returns>
public MetricsServiceV2Settings Clone() => new MetricsServiceV2Settings(this);
}
/// <summary>
/// MetricsServiceV2 client wrapper, for convenient use.
/// </summary>
public abstract partial class MetricsServiceV2Client
{
/// <summary>
/// The default endpoint for the MetricsServiceV2 service, which is a host of "logging.googleapis.com" and a port of 443.
/// </summary>
public static ServiceEndpoint DefaultEndpoint { get; } = new ServiceEndpoint("logging.googleapis.com", 443);
/// <summary>
/// The default MetricsServiceV2 scopes.
/// </summary>
/// <remarks>
/// The default MetricsServiceV2 scopes are:
/// <list type="bullet">
/// <item><description>"https://www.googleapis.com/auth/cloud-platform"</description></item>
/// <item><description>"https://www.googleapis.com/auth/cloud-platform.read-only"</description></item>
/// <item><description>"https://www.googleapis.com/auth/logging.admin"</description></item>
/// <item><description>"https://www.googleapis.com/auth/logging.read"</description></item>
/// <item><description>"https://www.googleapis.com/auth/logging.write"</description></item>
/// </list>
/// </remarks>
public static IReadOnlyList<string> DefaultScopes { get; } = new ReadOnlyCollection<string>(new string[] {
"https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/cloud-platform.read-only",
"https://www.googleapis.com/auth/logging.admin",
"https://www.googleapis.com/auth/logging.read",
"https://www.googleapis.com/auth/logging.write",
});
private static readonly ChannelPool s_channelPool = new ChannelPool(DefaultScopes);
// Note: we could have parameterless overloads of Create and CreateAsync,
// documented to just use the default endpoint, settings and credentials.
// Pros:
// - Might be more reassuring on first use
// - Allows method group conversions
// Con: overloads!
/// <summary>
/// Asynchronously creates a <see cref="MetricsServiceV2Client"/>, applying defaults for all unspecified settings,
/// and creating a channel connecting to the given endpoint with application default credentials where
/// necessary.
/// </summary>
/// <param name="endpoint">Optional <see cref="ServiceEndpoint"/>.</param>
/// <param name="settings">Optional <see cref="MetricsServiceV2Settings"/>.</param>
/// <returns>The task representing the created <see cref="MetricsServiceV2Client"/>.</returns>
public static async Task<MetricsServiceV2Client> CreateAsync(ServiceEndpoint endpoint = null, MetricsServiceV2Settings settings = null)
{
Channel channel = await s_channelPool.GetChannelAsync(endpoint ?? DefaultEndpoint).ConfigureAwait(false);
return Create(channel, settings);
}
/// <summary>
/// Synchronously creates a <see cref="MetricsServiceV2Client"/>, applying defaults for all unspecified settings,
/// and creating a channel connecting to the given endpoint with application default credentials where
/// necessary.
/// </summary>
/// <param name="endpoint">Optional <see cref="ServiceEndpoint"/>.</param>
/// <param name="settings">Optional <see cref="MetricsServiceV2Settings"/>.</param>
/// <returns>The created <see cref="MetricsServiceV2Client"/>.</returns>
public static MetricsServiceV2Client Create(ServiceEndpoint endpoint = null, MetricsServiceV2Settings settings = null)
{
Channel channel = s_channelPool.GetChannel(endpoint ?? DefaultEndpoint);
return Create(channel, settings);
}
/// <summary>
/// Creates a <see cref="MetricsServiceV2Client"/> which uses the specified channel for remote operations.
/// </summary>
/// <param name="channel">The <see cref="Channel"/> for remote operations. Must not be null.</param>
/// <param name="settings">Optional <see cref="MetricsServiceV2Settings"/>.</param>
/// <returns>The created <see cref="MetricsServiceV2Client"/>.</returns>
public static MetricsServiceV2Client Create(Channel channel, MetricsServiceV2Settings settings = null)
{
GaxPreconditions.CheckNotNull(channel, nameof(channel));
MetricsServiceV2.MetricsServiceV2Client grpcClient = new MetricsServiceV2.MetricsServiceV2Client(channel);
return new MetricsServiceV2ClientImpl(grpcClient, settings);
}
/// <summary>
/// Shuts down any channels automatically created by <see cref="Create(ServiceEndpoint, MetricsServiceV2Settings)"/>
/// and <see cref="CreateAsync(ServiceEndpoint, MetricsServiceV2Settings)"/>. Channels which weren't automatically
/// created are not affected.
/// </summary>
/// <remarks>After calling this method, further calls to <see cref="Create(ServiceEndpoint, MetricsServiceV2Settings)"/>
/// and <see cref="CreateAsync(ServiceEndpoint, MetricsServiceV2Settings)"/> will create new channels, which could
/// in turn be shut down by another call to this method.</remarks>
/// <returns>A task representing the asynchronous shutdown operation.</returns>
public static Task ShutdownDefaultChannelsAsync() => s_channelPool.ShutdownChannelsAsync();
/// <summary>
/// The underlying gRPC MetricsServiceV2 client.
/// </summary>
public virtual MetricsServiceV2.MetricsServiceV2Client GrpcClient
{
get { throw new NotImplementedException(); }
}
/// <summary>
/// Lists logs-based metrics.
/// </summary>
/// <param name="parent">
/// Required. The name of the project containing the metrics:
///
/// "projects/[PROJECT_ID]"
/// </param>
/// <param name="pageToken">
/// The token returned from the previous request.
/// A value of <c>null</c> or an empty string retrieves the first page.
/// </param>
/// <param name="pageSize">
/// The size of page to request. The response will not be larger than this, but may be smaller.
/// A value of <c>null</c> or 0 uses a server-defined page size.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// A pageable asynchronous sequence of <see cref="LogMetric"/> resources.
/// </returns>
public virtual PagedAsyncEnumerable<ListLogMetricsResponse, LogMetric> ListLogMetricsAsync(
ParentNameOneof parent,
string pageToken = null,
int? pageSize = null,
CallSettings callSettings = null) => ListLogMetricsAsync(
new ListLogMetricsRequest
{
ParentAsParentNameOneof = GaxPreconditions.CheckNotNull(parent, nameof(parent)),
PageToken = pageToken ?? "",
PageSize = pageSize ?? 0,
},
callSettings);
/// <summary>
/// Lists logs-based metrics.
/// </summary>
/// <param name="parent">
/// Required. The name of the project containing the metrics:
///
/// "projects/[PROJECT_ID]"
/// </param>
/// <param name="pageToken">
/// The token returned from the previous request.
/// A value of <c>null</c> or an empty string retrieves the first page.
/// </param>
/// <param name="pageSize">
/// The size of page to request. The response will not be larger than this, but may be smaller.
/// A value of <c>null</c> or 0 uses a server-defined page size.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// A pageable sequence of <see cref="LogMetric"/> resources.
/// </returns>
public virtual PagedEnumerable<ListLogMetricsResponse, LogMetric> ListLogMetrics(
ParentNameOneof parent,
string pageToken = null,
int? pageSize = null,
CallSettings callSettings = null) => ListLogMetrics(
new ListLogMetricsRequest
{
ParentAsParentNameOneof = GaxPreconditions.CheckNotNull(parent, nameof(parent)),
PageToken = pageToken ?? "",
PageSize = pageSize ?? 0,
},
callSettings);
/// <summary>
/// Lists logs-based metrics.
/// </summary>
/// <param name="request">
/// The request object containing all of the parameters for the API call.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// A pageable asynchronous sequence of <see cref="LogMetric"/> resources.
/// </returns>
public virtual PagedAsyncEnumerable<ListLogMetricsResponse, LogMetric> ListLogMetricsAsync(
ListLogMetricsRequest request,
CallSettings callSettings = null)
{
throw new NotImplementedException();
}
/// <summary>
/// Lists logs-based metrics.
/// </summary>
/// <param name="request">
/// The request object containing all of the parameters for the API call.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// A pageable sequence of <see cref="LogMetric"/> resources.
/// </returns>
public virtual PagedEnumerable<ListLogMetricsResponse, LogMetric> ListLogMetrics(
ListLogMetricsRequest request,
CallSettings callSettings = null)
{
throw new NotImplementedException();
}
/// <summary>
/// Gets a logs-based metric.
/// </summary>
/// <param name="metricName">
/// The resource name of the desired metric:
///
/// "projects/[PROJECT_ID]/metrics/[METRIC_ID]"
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// A Task containing the RPC response.
/// </returns>
public virtual Task<LogMetric> GetLogMetricAsync(
MetricNameOneof metricName,
CallSettings callSettings = null) => GetLogMetricAsync(
new GetLogMetricRequest
{
MetricNameAsMetricNameOneof = GaxPreconditions.CheckNotNull(metricName, nameof(metricName)),
},
callSettings);
/// <summary>
/// Gets a logs-based metric.
/// </summary>
/// <param name="metricName">
/// The resource name of the desired metric:
///
/// "projects/[PROJECT_ID]/metrics/[METRIC_ID]"
/// </param>
/// <param name="cancellationToken">
/// A <see cref="CancellationToken"/> to use for this RPC.
/// </param>
/// <returns>
/// A Task containing the RPC response.
/// </returns>
public virtual Task<LogMetric> GetLogMetricAsync(
MetricNameOneof metricName,
CancellationToken cancellationToken) => GetLogMetricAsync(
metricName,
CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Gets a logs-based metric.
/// </summary>
/// <param name="metricName">
/// The resource name of the desired metric:
///
/// "projects/[PROJECT_ID]/metrics/[METRIC_ID]"
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// The RPC response.
/// </returns>
public virtual LogMetric GetLogMetric(
MetricNameOneof metricName,
CallSettings callSettings = null) => GetLogMetric(
new GetLogMetricRequest
{
MetricNameAsMetricNameOneof = GaxPreconditions.CheckNotNull(metricName, nameof(metricName)),
},
callSettings);
/// <summary>
/// Gets a logs-based metric.
/// </summary>
/// <param name="request">
/// The request object containing all of the parameters for the API call.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// A Task containing the RPC response.
/// </returns>
public virtual Task<LogMetric> GetLogMetricAsync(
GetLogMetricRequest request,
CallSettings callSettings = null)
{
throw new NotImplementedException();
}
/// <summary>
/// Gets a logs-based metric.
/// </summary>
/// <param name="request">
/// The request object containing all of the parameters for the API call.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// The RPC response.
/// </returns>
public virtual LogMetric GetLogMetric(
GetLogMetricRequest request,
CallSettings callSettings = null)
{
throw new NotImplementedException();
}
/// <summary>
/// Creates a logs-based metric.
/// </summary>
/// <param name="parent">
/// The resource name of the project in which to create the metric:
///
/// "projects/[PROJECT_ID]"
///
/// The new metric must be provided in the request.
/// </param>
/// <param name="metric">
/// The new logs-based metric, which must not have an identifier that
/// already exists.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// A Task containing the RPC response.
/// </returns>
public virtual Task<LogMetric> CreateLogMetricAsync(
ParentNameOneof parent,
LogMetric metric,
CallSettings callSettings = null) => CreateLogMetricAsync(
new CreateLogMetricRequest
{
ParentAsParentNameOneof = GaxPreconditions.CheckNotNull(parent, nameof(parent)),
Metric = GaxPreconditions.CheckNotNull(metric, nameof(metric)),
},
callSettings);
/// <summary>
/// Creates a logs-based metric.
/// </summary>
/// <param name="parent">
/// The resource name of the project in which to create the metric:
///
/// "projects/[PROJECT_ID]"
///
/// The new metric must be provided in the request.
/// </param>
/// <param name="metric">
/// The new logs-based metric, which must not have an identifier that
/// already exists.
/// </param>
/// <param name="cancellationToken">
/// A <see cref="CancellationToken"/> to use for this RPC.
/// </param>
/// <returns>
/// A Task containing the RPC response.
/// </returns>
public virtual Task<LogMetric> CreateLogMetricAsync(
ParentNameOneof parent,
LogMetric metric,
CancellationToken cancellationToken) => CreateLogMetricAsync(
parent,
metric,
CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Creates a logs-based metric.
/// </summary>
/// <param name="parent">
/// The resource name of the project in which to create the metric:
///
/// "projects/[PROJECT_ID]"
///
/// The new metric must be provided in the request.
/// </param>
/// <param name="metric">
/// The new logs-based metric, which must not have an identifier that
/// already exists.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// The RPC response.
/// </returns>
public virtual LogMetric CreateLogMetric(
ParentNameOneof parent,
LogMetric metric,
CallSettings callSettings = null) => CreateLogMetric(
new CreateLogMetricRequest
{
ParentAsParentNameOneof = GaxPreconditions.CheckNotNull(parent, nameof(parent)),
Metric = GaxPreconditions.CheckNotNull(metric, nameof(metric)),
},
callSettings);
/// <summary>
/// Creates a logs-based metric.
/// </summary>
/// <param name="request">
/// The request object containing all of the parameters for the API call.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// A Task containing the RPC response.
/// </returns>
public virtual Task<LogMetric> CreateLogMetricAsync(
CreateLogMetricRequest request,
CallSettings callSettings = null)
{
throw new NotImplementedException();
}
/// <summary>
/// Creates a logs-based metric.
/// </summary>
/// <param name="request">
/// The request object containing all of the parameters for the API call.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// The RPC response.
/// </returns>
public virtual LogMetric CreateLogMetric(
CreateLogMetricRequest request,
CallSettings callSettings = null)
{
throw new NotImplementedException();
}
/// <summary>
/// Creates or updates a logs-based metric.
/// </summary>
/// <param name="metricName">
/// The resource name of the metric to update:
///
/// "projects/[PROJECT_ID]/metrics/[METRIC_ID]"
///
/// The updated metric must be provided in the request and it's
/// `name` field must be the same as `[METRIC_ID]` If the metric
/// does not exist in `[PROJECT_ID]`, then a new metric is created.
/// </param>
/// <param name="metric">
/// The updated metric.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// A Task containing the RPC response.
/// </returns>
public virtual Task<LogMetric> UpdateLogMetricAsync(
MetricNameOneof metricName,
LogMetric metric,
CallSettings callSettings = null) => UpdateLogMetricAsync(
new UpdateLogMetricRequest
{
MetricNameAsMetricNameOneof = GaxPreconditions.CheckNotNull(metricName, nameof(metricName)),
Metric = GaxPreconditions.CheckNotNull(metric, nameof(metric)),
},
callSettings);
/// <summary>
/// Creates or updates a logs-based metric.
/// </summary>
/// <param name="metricName">
/// The resource name of the metric to update:
///
/// "projects/[PROJECT_ID]/metrics/[METRIC_ID]"
///
/// The updated metric must be provided in the request and it's
/// `name` field must be the same as `[METRIC_ID]` If the metric
/// does not exist in `[PROJECT_ID]`, then a new metric is created.
/// </param>
/// <param name="metric">
/// The updated metric.
/// </param>
/// <param name="cancellationToken">
/// A <see cref="CancellationToken"/> to use for this RPC.
/// </param>
/// <returns>
/// A Task containing the RPC response.
/// </returns>
public virtual Task<LogMetric> UpdateLogMetricAsync(
MetricNameOneof metricName,
LogMetric metric,
CancellationToken cancellationToken) => UpdateLogMetricAsync(
metricName,
metric,
CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Creates or updates a logs-based metric.
/// </summary>
/// <param name="metricName">
/// The resource name of the metric to update:
///
/// "projects/[PROJECT_ID]/metrics/[METRIC_ID]"
///
/// The updated metric must be provided in the request and it's
/// `name` field must be the same as `[METRIC_ID]` If the metric
/// does not exist in `[PROJECT_ID]`, then a new metric is created.
/// </param>
/// <param name="metric">
/// The updated metric.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// The RPC response.
/// </returns>
public virtual LogMetric UpdateLogMetric(
MetricNameOneof metricName,
LogMetric metric,
CallSettings callSettings = null) => UpdateLogMetric(
new UpdateLogMetricRequest
{
MetricNameAsMetricNameOneof = GaxPreconditions.CheckNotNull(metricName, nameof(metricName)),
Metric = GaxPreconditions.CheckNotNull(metric, nameof(metric)),
},
callSettings);
/// <summary>
/// Creates or updates a logs-based metric.
/// </summary>
/// <param name="request">
/// The request object containing all of the parameters for the API call.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// A Task containing the RPC response.
/// </returns>
public virtual Task<LogMetric> UpdateLogMetricAsync(
UpdateLogMetricRequest request,
CallSettings callSettings = null)
{
throw new NotImplementedException();
}
/// <summary>
/// Creates or updates a logs-based metric.
/// </summary>
/// <param name="request">
/// The request object containing all of the parameters for the API call.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// The RPC response.
/// </returns>
public virtual LogMetric UpdateLogMetric(
UpdateLogMetricRequest request,
CallSettings callSettings = null)
{
throw new NotImplementedException();
}
/// <summary>
/// Deletes a logs-based metric.
/// </summary>
/// <param name="metricName">
/// The resource name of the metric to delete:
///
/// "projects/[PROJECT_ID]/metrics/[METRIC_ID]"
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// A Task containing the RPC response.
/// </returns>
public virtual Task DeleteLogMetricAsync(
MetricNameOneof metricName,
CallSettings callSettings = null) => DeleteLogMetricAsync(
new DeleteLogMetricRequest
{
MetricNameAsMetricNameOneof = GaxPreconditions.CheckNotNull(metricName, nameof(metricName)),
},
callSettings);
/// <summary>
/// Deletes a logs-based metric.
/// </summary>
/// <param name="metricName">
/// The resource name of the metric to delete:
///
/// "projects/[PROJECT_ID]/metrics/[METRIC_ID]"
/// </param>
/// <param name="cancellationToken">
/// A <see cref="CancellationToken"/> to use for this RPC.
/// </param>
/// <returns>
/// A Task containing the RPC response.
/// </returns>
public virtual Task DeleteLogMetricAsync(
MetricNameOneof metricName,
CancellationToken cancellationToken) => DeleteLogMetricAsync(
metricName,
CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Deletes a logs-based metric.
/// </summary>
/// <param name="metricName">
/// The resource name of the metric to delete:
///
/// "projects/[PROJECT_ID]/metrics/[METRIC_ID]"
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// The RPC response.
/// </returns>
public virtual void DeleteLogMetric(
MetricNameOneof metricName,
CallSettings callSettings = null) => DeleteLogMetric(
new DeleteLogMetricRequest
{
MetricNameAsMetricNameOneof = GaxPreconditions.CheckNotNull(metricName, nameof(metricName)),
},
callSettings);
/// <summary>
/// Deletes a logs-based metric.
/// </summary>
/// <param name="request">
/// The request object containing all of the parameters for the API call.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// A Task containing the RPC response.
/// </returns>
public virtual Task DeleteLogMetricAsync(
DeleteLogMetricRequest request,
CallSettings callSettings = null)
{
throw new NotImplementedException();
}
/// <summary>
/// Deletes a logs-based metric.
/// </summary>
/// <param name="request">
/// The request object containing all of the parameters for the API call.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// The RPC response.
/// </returns>
public virtual void DeleteLogMetric(
DeleteLogMetricRequest request,
CallSettings callSettings = null)
{
throw new NotImplementedException();
}
}
/// <summary>
/// MetricsServiceV2 client wrapper implementation, for convenient use.
/// </summary>
public sealed partial class MetricsServiceV2ClientImpl : MetricsServiceV2Client
{
private readonly ApiCall<ListLogMetricsRequest, ListLogMetricsResponse> _callListLogMetrics;
private readonly ApiCall<GetLogMetricRequest, LogMetric> _callGetLogMetric;
private readonly ApiCall<CreateLogMetricRequest, LogMetric> _callCreateLogMetric;
private readonly ApiCall<UpdateLogMetricRequest, LogMetric> _callUpdateLogMetric;
private readonly ApiCall<DeleteLogMetricRequest, Empty> _callDeleteLogMetric;
/// <summary>
/// Constructs a client wrapper for the MetricsServiceV2 service, with the specified gRPC client and settings.
/// </summary>
/// <param name="grpcClient">The underlying gRPC client.</param>
/// <param name="settings">The base <see cref="MetricsServiceV2Settings"/> used within this client </param>
public MetricsServiceV2ClientImpl(MetricsServiceV2.MetricsServiceV2Client grpcClient, MetricsServiceV2Settings settings)
{
this.GrpcClient = grpcClient;
MetricsServiceV2Settings effectiveSettings = settings ?? MetricsServiceV2Settings.GetDefault();
ClientHelper clientHelper = new ClientHelper(effectiveSettings);
_callListLogMetrics = clientHelper.BuildApiCall<ListLogMetricsRequest, ListLogMetricsResponse>(
GrpcClient.ListLogMetricsAsync, GrpcClient.ListLogMetrics, effectiveSettings.ListLogMetricsSettings);
_callGetLogMetric = clientHelper.BuildApiCall<GetLogMetricRequest, LogMetric>(
GrpcClient.GetLogMetricAsync, GrpcClient.GetLogMetric, effectiveSettings.GetLogMetricSettings);
_callCreateLogMetric = clientHelper.BuildApiCall<CreateLogMetricRequest, LogMetric>(
GrpcClient.CreateLogMetricAsync, GrpcClient.CreateLogMetric, effectiveSettings.CreateLogMetricSettings);
_callUpdateLogMetric = clientHelper.BuildApiCall<UpdateLogMetricRequest, LogMetric>(
GrpcClient.UpdateLogMetricAsync, GrpcClient.UpdateLogMetric, effectiveSettings.UpdateLogMetricSettings);
_callDeleteLogMetric = clientHelper.BuildApiCall<DeleteLogMetricRequest, Empty>(
GrpcClient.DeleteLogMetricAsync, GrpcClient.DeleteLogMetric, effectiveSettings.DeleteLogMetricSettings);
OnConstruction(grpcClient, effectiveSettings, clientHelper);
}
partial void OnConstruction(MetricsServiceV2.MetricsServiceV2Client grpcClient, MetricsServiceV2Settings effectiveSettings, ClientHelper clientHelper);
/// <summary>
/// The underlying gRPC MetricsServiceV2 client.
/// </summary>
public override MetricsServiceV2.MetricsServiceV2Client GrpcClient { get; }
// Partial modifier methods contain '_' to ensure no name conflicts with RPC methods.
partial void Modify_ListLogMetricsRequest(ref ListLogMetricsRequest request, ref CallSettings settings);
partial void Modify_GetLogMetricRequest(ref GetLogMetricRequest request, ref CallSettings settings);
partial void Modify_CreateLogMetricRequest(ref CreateLogMetricRequest request, ref CallSettings settings);
partial void Modify_UpdateLogMetricRequest(ref UpdateLogMetricRequest request, ref CallSettings settings);
partial void Modify_DeleteLogMetricRequest(ref DeleteLogMetricRequest request, ref CallSettings settings);
/// <summary>
/// Lists logs-based metrics.
/// </summary>
/// <param name="request">
/// The request object containing all of the parameters for the API call.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// A pageable asynchronous sequence of <see cref="LogMetric"/> resources.
/// </returns>
public override PagedAsyncEnumerable<ListLogMetricsResponse, LogMetric> ListLogMetricsAsync(
ListLogMetricsRequest request,
CallSettings callSettings = null)
{
Modify_ListLogMetricsRequest(ref request, ref callSettings);
return new GrpcPagedAsyncEnumerable<ListLogMetricsRequest, ListLogMetricsResponse, LogMetric>(_callListLogMetrics, request, callSettings);
}
/// <summary>
/// Lists logs-based metrics.
/// </summary>
/// <param name="request">
/// The request object containing all of the parameters for the API call.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// A pageable sequence of <see cref="LogMetric"/> resources.
/// </returns>
public override PagedEnumerable<ListLogMetricsResponse, LogMetric> ListLogMetrics(
ListLogMetricsRequest request,
CallSettings callSettings = null)
{
Modify_ListLogMetricsRequest(ref request, ref callSettings);
return new GrpcPagedEnumerable<ListLogMetricsRequest, ListLogMetricsResponse, LogMetric>(_callListLogMetrics, request, callSettings);
}
/// <summary>
/// Gets a logs-based metric.
/// </summary>
/// <param name="request">
/// The request object containing all of the parameters for the API call.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// A Task containing the RPC response.
/// </returns>
public override Task<LogMetric> GetLogMetricAsync(
GetLogMetricRequest request,
CallSettings callSettings = null)
{
Modify_GetLogMetricRequest(ref request, ref callSettings);
return _callGetLogMetric.Async(request, callSettings);
}
/// <summary>
/// Gets a logs-based metric.
/// </summary>
/// <param name="request">
/// The request object containing all of the parameters for the API call.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// The RPC response.
/// </returns>
public override LogMetric GetLogMetric(
GetLogMetricRequest request,
CallSettings callSettings = null)
{
Modify_GetLogMetricRequest(ref request, ref callSettings);
return _callGetLogMetric.Sync(request, callSettings);
}
/// <summary>
/// Creates a logs-based metric.
/// </summary>
/// <param name="request">
/// The request object containing all of the parameters for the API call.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// A Task containing the RPC response.
/// </returns>
public override Task<LogMetric> CreateLogMetricAsync(
CreateLogMetricRequest request,
CallSettings callSettings = null)
{
Modify_CreateLogMetricRequest(ref request, ref callSettings);
return _callCreateLogMetric.Async(request, callSettings);
}
/// <summary>
/// Creates a logs-based metric.
/// </summary>
/// <param name="request">
/// The request object containing all of the parameters for the API call.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// The RPC response.
/// </returns>
public override LogMetric CreateLogMetric(
CreateLogMetricRequest request,
CallSettings callSettings = null)
{
Modify_CreateLogMetricRequest(ref request, ref callSettings);
return _callCreateLogMetric.Sync(request, callSettings);
}
/// <summary>
/// Creates or updates a logs-based metric.
/// </summary>
/// <param name="request">
/// The request object containing all of the parameters for the API call.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// A Task containing the RPC response.
/// </returns>
public override Task<LogMetric> UpdateLogMetricAsync(
UpdateLogMetricRequest request,
CallSettings callSettings = null)
{
Modify_UpdateLogMetricRequest(ref request, ref callSettings);
return _callUpdateLogMetric.Async(request, callSettings);
}
/// <summary>
/// Creates or updates a logs-based metric.
/// </summary>
/// <param name="request">
/// The request object containing all of the parameters for the API call.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// The RPC response.
/// </returns>
public override LogMetric UpdateLogMetric(
UpdateLogMetricRequest request,
CallSettings callSettings = null)
{
Modify_UpdateLogMetricRequest(ref request, ref callSettings);
return _callUpdateLogMetric.Sync(request, callSettings);
}
/// <summary>
/// Deletes a logs-based metric.
/// </summary>
/// <param name="request">
/// The request object containing all of the parameters for the API call.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// A Task containing the RPC response.
/// </returns>
public override Task DeleteLogMetricAsync(
DeleteLogMetricRequest request,
CallSettings callSettings = null)
{
Modify_DeleteLogMetricRequest(ref request, ref callSettings);
return _callDeleteLogMetric.Async(request, callSettings);
}
/// <summary>
/// Deletes a logs-based metric.
/// </summary>
/// <param name="request">
/// The request object containing all of the parameters for the API call.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// The RPC response.
/// </returns>
public override void DeleteLogMetric(
DeleteLogMetricRequest request,
CallSettings callSettings = null)
{
Modify_DeleteLogMetricRequest(ref request, ref callSettings);
_callDeleteLogMetric.Sync(request, callSettings);
}
}
// Partial classes to enable page-streaming
public partial class ListLogMetricsRequest : IPageRequest { }
public partial class ListLogMetricsResponse : IPageResponse<LogMetric>
{
/// <summary>
/// Returns an enumerator that iterates through the resources in this response.
/// </summary>
public IEnumerator<LogMetric> GetEnumerator() => Metrics.GetEnumerator();
/// <inheritdoc/>
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gagvr = Google.Ads.GoogleAds.V8.Resources;
using gax = Google.Api.Gax;
using gaxgrpc = Google.Api.Gax.Grpc;
using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore;
using proto = Google.Protobuf;
using grpccore = Grpc.Core;
using grpcinter = Grpc.Core.Interceptors;
using sys = System;
using scg = System.Collections.Generic;
using sco = System.Collections.ObjectModel;
using st = System.Threading;
using stt = System.Threading.Tasks;
namespace Google.Ads.GoogleAds.V8.Services
{
/// <summary>Settings for <see cref="AdGroupServiceClient"/> instances.</summary>
public sealed partial class AdGroupServiceSettings : gaxgrpc::ServiceSettingsBase
{
/// <summary>Get a new instance of the default <see cref="AdGroupServiceSettings"/>.</summary>
/// <returns>A new instance of the default <see cref="AdGroupServiceSettings"/>.</returns>
public static AdGroupServiceSettings GetDefault() => new AdGroupServiceSettings();
/// <summary>Constructs a new <see cref="AdGroupServiceSettings"/> object with default settings.</summary>
public AdGroupServiceSettings()
{
}
private AdGroupServiceSettings(AdGroupServiceSettings existing) : base(existing)
{
gax::GaxPreconditions.CheckNotNull(existing, nameof(existing));
GetAdGroupSettings = existing.GetAdGroupSettings;
MutateAdGroupsSettings = existing.MutateAdGroupsSettings;
OnCopy(existing);
}
partial void OnCopy(AdGroupServiceSettings existing);
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>AdGroupServiceClient.GetAdGroup</c> and <c>AdGroupServiceClient.GetAdGroupAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>Initial retry delay: 5000 milliseconds.</description></item>
/// <item><description>Retry delay multiplier: 1.3</description></item>
/// <item><description>Retry maximum delay: 60000 milliseconds.</description></item>
/// <item><description>Maximum attempts: Unlimited</description></item>
/// <item>
/// <description>
/// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>,
/// <see cref="grpccore::StatusCode.DeadlineExceeded"/>.
/// </description>
/// </item>
/// <item><description>Timeout: 3600 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings GetAdGroupSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded)));
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>AdGroupServiceClient.MutateAdGroups</c> and <c>AdGroupServiceClient.MutateAdGroupsAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>Initial retry delay: 5000 milliseconds.</description></item>
/// <item><description>Retry delay multiplier: 1.3</description></item>
/// <item><description>Retry maximum delay: 60000 milliseconds.</description></item>
/// <item><description>Maximum attempts: Unlimited</description></item>
/// <item>
/// <description>
/// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>,
/// <see cref="grpccore::StatusCode.DeadlineExceeded"/>.
/// </description>
/// </item>
/// <item><description>Timeout: 3600 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings MutateAdGroupsSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded)));
/// <summary>Creates a deep clone of this object, with all the same property values.</summary>
/// <returns>A deep clone of this <see cref="AdGroupServiceSettings"/> object.</returns>
public AdGroupServiceSettings Clone() => new AdGroupServiceSettings(this);
}
/// <summary>
/// Builder class for <see cref="AdGroupServiceClient"/> to provide simple configuration of credentials, endpoint
/// etc.
/// </summary>
internal sealed partial class AdGroupServiceClientBuilder : gaxgrpc::ClientBuilderBase<AdGroupServiceClient>
{
/// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary>
public AdGroupServiceSettings Settings { get; set; }
/// <summary>Creates a new builder with default settings.</summary>
public AdGroupServiceClientBuilder()
{
UseJwtAccessWithScopes = AdGroupServiceClient.UseJwtAccessWithScopes;
}
partial void InterceptBuild(ref AdGroupServiceClient client);
partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<AdGroupServiceClient> task);
/// <summary>Builds the resulting client.</summary>
public override AdGroupServiceClient Build()
{
AdGroupServiceClient client = null;
InterceptBuild(ref client);
return client ?? BuildImpl();
}
/// <summary>Builds the resulting client asynchronously.</summary>
public override stt::Task<AdGroupServiceClient> BuildAsync(st::CancellationToken cancellationToken = default)
{
stt::Task<AdGroupServiceClient> task = null;
InterceptBuildAsync(cancellationToken, ref task);
return task ?? BuildAsyncImpl(cancellationToken);
}
private AdGroupServiceClient BuildImpl()
{
Validate();
grpccore::CallInvoker callInvoker = CreateCallInvoker();
return AdGroupServiceClient.Create(callInvoker, Settings);
}
private async stt::Task<AdGroupServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken)
{
Validate();
grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false);
return AdGroupServiceClient.Create(callInvoker, Settings);
}
/// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary>
protected override string GetDefaultEndpoint() => AdGroupServiceClient.DefaultEndpoint;
/// <summary>
/// Returns the default scopes for this builder type, used if no scopes are otherwise specified.
/// </summary>
protected override scg::IReadOnlyList<string> GetDefaultScopes() => AdGroupServiceClient.DefaultScopes;
/// <summary>Returns the channel pool to use when no other options are specified.</summary>
protected override gaxgrpc::ChannelPool GetChannelPool() => AdGroupServiceClient.ChannelPool;
/// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary>
protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance;
}
/// <summary>AdGroupService client wrapper, for convenient use.</summary>
/// <remarks>
/// Service to manage ad groups.
/// </remarks>
public abstract partial class AdGroupServiceClient
{
/// <summary>
/// The default endpoint for the AdGroupService service, which is a host of "googleads.googleapis.com" and a
/// port of 443.
/// </summary>
public static string DefaultEndpoint { get; } = "googleads.googleapis.com:443";
/// <summary>The default AdGroupService scopes.</summary>
/// <remarks>
/// The default AdGroupService scopes are:
/// <list type="bullet"><item><description>https://www.googleapis.com/auth/adwords</description></item></list>
/// </remarks>
public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[]
{
"https://www.googleapis.com/auth/adwords",
});
internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes);
internal static bool UseJwtAccessWithScopes
{
get
{
bool useJwtAccessWithScopes = true;
MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes);
return useJwtAccessWithScopes;
}
}
static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes);
/// <summary>
/// Asynchronously creates a <see cref="AdGroupServiceClient"/> using the default credentials, endpoint and
/// settings. To specify custom credentials or other settings, use <see cref="AdGroupServiceClientBuilder"/>.
/// </summary>
/// <param name="cancellationToken">
/// The <see cref="st::CancellationToken"/> to use while creating the client.
/// </param>
/// <returns>The task representing the created <see cref="AdGroupServiceClient"/>.</returns>
public static stt::Task<AdGroupServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) =>
new AdGroupServiceClientBuilder().BuildAsync(cancellationToken);
/// <summary>
/// Synchronously creates a <see cref="AdGroupServiceClient"/> using the default credentials, endpoint and
/// settings. To specify custom credentials or other settings, use <see cref="AdGroupServiceClientBuilder"/>.
/// </summary>
/// <returns>The created <see cref="AdGroupServiceClient"/>.</returns>
public static AdGroupServiceClient Create() => new AdGroupServiceClientBuilder().Build();
/// <summary>
/// Creates a <see cref="AdGroupServiceClient"/> which uses the specified call invoker for remote operations.
/// </summary>
/// <param name="callInvoker">
/// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null.
/// </param>
/// <param name="settings">Optional <see cref="AdGroupServiceSettings"/>.</param>
/// <returns>The created <see cref="AdGroupServiceClient"/>.</returns>
internal static AdGroupServiceClient Create(grpccore::CallInvoker callInvoker, AdGroupServiceSettings settings = null)
{
gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker));
grpcinter::Interceptor interceptor = settings?.Interceptor;
if (interceptor != null)
{
callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor);
}
AdGroupService.AdGroupServiceClient grpcClient = new AdGroupService.AdGroupServiceClient(callInvoker);
return new AdGroupServiceClientImpl(grpcClient, settings);
}
/// <summary>
/// Shuts down any channels automatically created by <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not
/// affected.
/// </summary>
/// <remarks>
/// After calling this method, further calls to <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down
/// by another call to this method.
/// </remarks>
/// <returns>A task representing the asynchronous shutdown operation.</returns>
public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync();
/// <summary>The underlying gRPC AdGroupService client</summary>
public virtual AdGroupService.AdGroupServiceClient GrpcClient => throw new sys::NotImplementedException();
/// <summary>
/// Returns the requested ad group in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual gagvr::AdGroup GetAdGroup(GetAdGroupRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Returns the requested ad group in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::AdGroup> GetAdGroupAsync(GetAdGroupRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Returns the requested ad group in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::AdGroup> GetAdGroupAsync(GetAdGroupRequest request, st::CancellationToken cancellationToken) =>
GetAdGroupAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Returns the requested ad group in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the ad group to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual gagvr::AdGroup GetAdGroup(string resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetAdGroup(new GetAdGroupRequest
{
ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested ad group in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the ad group to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::AdGroup> GetAdGroupAsync(string resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetAdGroupAsync(new GetAdGroupRequest
{
ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested ad group in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the ad group to fetch.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::AdGroup> GetAdGroupAsync(string resourceName, st::CancellationToken cancellationToken) =>
GetAdGroupAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Returns the requested ad group in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the ad group to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual gagvr::AdGroup GetAdGroup(gagvr::AdGroupName resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetAdGroup(new GetAdGroupRequest
{
ResourceNameAsAdGroupName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested ad group in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the ad group to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::AdGroup> GetAdGroupAsync(gagvr::AdGroupName resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetAdGroupAsync(new GetAdGroupRequest
{
ResourceNameAsAdGroupName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested ad group in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the ad group to fetch.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::AdGroup> GetAdGroupAsync(gagvr::AdGroupName resourceName, st::CancellationToken cancellationToken) =>
GetAdGroupAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Creates, updates, or removes ad groups. Operation statuses are returned.
///
/// List of thrown errors:
/// [AdGroupError]()
/// [AdxError]()
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [BiddingError]()
/// [BiddingStrategyError]()
/// [DatabaseError]()
/// [DateError]()
/// [DistinctError]()
/// [FieldError]()
/// [FieldMaskError]()
/// [HeaderError]()
/// [IdError]()
/// [InternalError]()
/// [ListOperationError]()
/// [MultiplierError]()
/// [MutateError]()
/// [NewResourceCreationError]()
/// [NotEmptyError]()
/// [NullError]()
/// [OperationAccessDeniedError]()
/// [OperatorError]()
/// [QuotaError]()
/// [RangeError]()
/// [RequestError]()
/// [ResourceCountLimitExceededError]()
/// [SettingError]()
/// [SizeLimitError]()
/// [StringFormatError]()
/// [StringLengthError]()
/// [UrlFieldError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual MutateAdGroupsResponse MutateAdGroups(MutateAdGroupsRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Creates, updates, or removes ad groups. Operation statuses are returned.
///
/// List of thrown errors:
/// [AdGroupError]()
/// [AdxError]()
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [BiddingError]()
/// [BiddingStrategyError]()
/// [DatabaseError]()
/// [DateError]()
/// [DistinctError]()
/// [FieldError]()
/// [FieldMaskError]()
/// [HeaderError]()
/// [IdError]()
/// [InternalError]()
/// [ListOperationError]()
/// [MultiplierError]()
/// [MutateError]()
/// [NewResourceCreationError]()
/// [NotEmptyError]()
/// [NullError]()
/// [OperationAccessDeniedError]()
/// [OperatorError]()
/// [QuotaError]()
/// [RangeError]()
/// [RequestError]()
/// [ResourceCountLimitExceededError]()
/// [SettingError]()
/// [SizeLimitError]()
/// [StringFormatError]()
/// [StringLengthError]()
/// [UrlFieldError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<MutateAdGroupsResponse> MutateAdGroupsAsync(MutateAdGroupsRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Creates, updates, or removes ad groups. Operation statuses are returned.
///
/// List of thrown errors:
/// [AdGroupError]()
/// [AdxError]()
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [BiddingError]()
/// [BiddingStrategyError]()
/// [DatabaseError]()
/// [DateError]()
/// [DistinctError]()
/// [FieldError]()
/// [FieldMaskError]()
/// [HeaderError]()
/// [IdError]()
/// [InternalError]()
/// [ListOperationError]()
/// [MultiplierError]()
/// [MutateError]()
/// [NewResourceCreationError]()
/// [NotEmptyError]()
/// [NullError]()
/// [OperationAccessDeniedError]()
/// [OperatorError]()
/// [QuotaError]()
/// [RangeError]()
/// [RequestError]()
/// [ResourceCountLimitExceededError]()
/// [SettingError]()
/// [SizeLimitError]()
/// [StringFormatError]()
/// [StringLengthError]()
/// [UrlFieldError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<MutateAdGroupsResponse> MutateAdGroupsAsync(MutateAdGroupsRequest request, st::CancellationToken cancellationToken) =>
MutateAdGroupsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Creates, updates, or removes ad groups. Operation statuses are returned.
///
/// List of thrown errors:
/// [AdGroupError]()
/// [AdxError]()
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [BiddingError]()
/// [BiddingStrategyError]()
/// [DatabaseError]()
/// [DateError]()
/// [DistinctError]()
/// [FieldError]()
/// [FieldMaskError]()
/// [HeaderError]()
/// [IdError]()
/// [InternalError]()
/// [ListOperationError]()
/// [MultiplierError]()
/// [MutateError]()
/// [NewResourceCreationError]()
/// [NotEmptyError]()
/// [NullError]()
/// [OperationAccessDeniedError]()
/// [OperatorError]()
/// [QuotaError]()
/// [RangeError]()
/// [RequestError]()
/// [ResourceCountLimitExceededError]()
/// [SettingError]()
/// [SizeLimitError]()
/// [StringFormatError]()
/// [StringLengthError]()
/// [UrlFieldError]()
/// </summary>
/// <param name="customerId">
/// Required. The ID of the customer whose ad groups are being modified.
/// </param>
/// <param name="operations">
/// Required. The list of operations to perform on individual ad groups.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual MutateAdGroupsResponse MutateAdGroups(string customerId, scg::IEnumerable<AdGroupOperation> operations, gaxgrpc::CallSettings callSettings = null) =>
MutateAdGroups(new MutateAdGroupsRequest
{
CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)),
Operations =
{
gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)),
},
}, callSettings);
/// <summary>
/// Creates, updates, or removes ad groups. Operation statuses are returned.
///
/// List of thrown errors:
/// [AdGroupError]()
/// [AdxError]()
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [BiddingError]()
/// [BiddingStrategyError]()
/// [DatabaseError]()
/// [DateError]()
/// [DistinctError]()
/// [FieldError]()
/// [FieldMaskError]()
/// [HeaderError]()
/// [IdError]()
/// [InternalError]()
/// [ListOperationError]()
/// [MultiplierError]()
/// [MutateError]()
/// [NewResourceCreationError]()
/// [NotEmptyError]()
/// [NullError]()
/// [OperationAccessDeniedError]()
/// [OperatorError]()
/// [QuotaError]()
/// [RangeError]()
/// [RequestError]()
/// [ResourceCountLimitExceededError]()
/// [SettingError]()
/// [SizeLimitError]()
/// [StringFormatError]()
/// [StringLengthError]()
/// [UrlFieldError]()
/// </summary>
/// <param name="customerId">
/// Required. The ID of the customer whose ad groups are being modified.
/// </param>
/// <param name="operations">
/// Required. The list of operations to perform on individual ad groups.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<MutateAdGroupsResponse> MutateAdGroupsAsync(string customerId, scg::IEnumerable<AdGroupOperation> operations, gaxgrpc::CallSettings callSettings = null) =>
MutateAdGroupsAsync(new MutateAdGroupsRequest
{
CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)),
Operations =
{
gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)),
},
}, callSettings);
/// <summary>
/// Creates, updates, or removes ad groups. Operation statuses are returned.
///
/// List of thrown errors:
/// [AdGroupError]()
/// [AdxError]()
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [BiddingError]()
/// [BiddingStrategyError]()
/// [DatabaseError]()
/// [DateError]()
/// [DistinctError]()
/// [FieldError]()
/// [FieldMaskError]()
/// [HeaderError]()
/// [IdError]()
/// [InternalError]()
/// [ListOperationError]()
/// [MultiplierError]()
/// [MutateError]()
/// [NewResourceCreationError]()
/// [NotEmptyError]()
/// [NullError]()
/// [OperationAccessDeniedError]()
/// [OperatorError]()
/// [QuotaError]()
/// [RangeError]()
/// [RequestError]()
/// [ResourceCountLimitExceededError]()
/// [SettingError]()
/// [SizeLimitError]()
/// [StringFormatError]()
/// [StringLengthError]()
/// [UrlFieldError]()
/// </summary>
/// <param name="customerId">
/// Required. The ID of the customer whose ad groups are being modified.
/// </param>
/// <param name="operations">
/// Required. The list of operations to perform on individual ad groups.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<MutateAdGroupsResponse> MutateAdGroupsAsync(string customerId, scg::IEnumerable<AdGroupOperation> operations, st::CancellationToken cancellationToken) =>
MutateAdGroupsAsync(customerId, operations, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
}
/// <summary>AdGroupService client wrapper implementation, for convenient use.</summary>
/// <remarks>
/// Service to manage ad groups.
/// </remarks>
public sealed partial class AdGroupServiceClientImpl : AdGroupServiceClient
{
private readonly gaxgrpc::ApiCall<GetAdGroupRequest, gagvr::AdGroup> _callGetAdGroup;
private readonly gaxgrpc::ApiCall<MutateAdGroupsRequest, MutateAdGroupsResponse> _callMutateAdGroups;
/// <summary>
/// Constructs a client wrapper for the AdGroupService service, with the specified gRPC client and settings.
/// </summary>
/// <param name="grpcClient">The underlying gRPC client.</param>
/// <param name="settings">The base <see cref="AdGroupServiceSettings"/> used within this client.</param>
public AdGroupServiceClientImpl(AdGroupService.AdGroupServiceClient grpcClient, AdGroupServiceSettings settings)
{
GrpcClient = grpcClient;
AdGroupServiceSettings effectiveSettings = settings ?? AdGroupServiceSettings.GetDefault();
gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings);
_callGetAdGroup = clientHelper.BuildApiCall<GetAdGroupRequest, gagvr::AdGroup>(grpcClient.GetAdGroupAsync, grpcClient.GetAdGroup, effectiveSettings.GetAdGroupSettings).WithGoogleRequestParam("resource_name", request => request.ResourceName);
Modify_ApiCall(ref _callGetAdGroup);
Modify_GetAdGroupApiCall(ref _callGetAdGroup);
_callMutateAdGroups = clientHelper.BuildApiCall<MutateAdGroupsRequest, MutateAdGroupsResponse>(grpcClient.MutateAdGroupsAsync, grpcClient.MutateAdGroups, effectiveSettings.MutateAdGroupsSettings).WithGoogleRequestParam("customer_id", request => request.CustomerId);
Modify_ApiCall(ref _callMutateAdGroups);
Modify_MutateAdGroupsApiCall(ref _callMutateAdGroups);
OnConstruction(grpcClient, effectiveSettings, clientHelper);
}
partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>;
partial void Modify_GetAdGroupApiCall(ref gaxgrpc::ApiCall<GetAdGroupRequest, gagvr::AdGroup> call);
partial void Modify_MutateAdGroupsApiCall(ref gaxgrpc::ApiCall<MutateAdGroupsRequest, MutateAdGroupsResponse> call);
partial void OnConstruction(AdGroupService.AdGroupServiceClient grpcClient, AdGroupServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper);
/// <summary>The underlying gRPC AdGroupService client</summary>
public override AdGroupService.AdGroupServiceClient GrpcClient { get; }
partial void Modify_GetAdGroupRequest(ref GetAdGroupRequest request, ref gaxgrpc::CallSettings settings);
partial void Modify_MutateAdGroupsRequest(ref MutateAdGroupsRequest request, ref gaxgrpc::CallSettings settings);
/// <summary>
/// Returns the requested ad group in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override gagvr::AdGroup GetAdGroup(GetAdGroupRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetAdGroupRequest(ref request, ref callSettings);
return _callGetAdGroup.Sync(request, callSettings);
}
/// <summary>
/// Returns the requested ad group in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<gagvr::AdGroup> GetAdGroupAsync(GetAdGroupRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetAdGroupRequest(ref request, ref callSettings);
return _callGetAdGroup.Async(request, callSettings);
}
/// <summary>
/// Creates, updates, or removes ad groups. Operation statuses are returned.
///
/// List of thrown errors:
/// [AdGroupError]()
/// [AdxError]()
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [BiddingError]()
/// [BiddingStrategyError]()
/// [DatabaseError]()
/// [DateError]()
/// [DistinctError]()
/// [FieldError]()
/// [FieldMaskError]()
/// [HeaderError]()
/// [IdError]()
/// [InternalError]()
/// [ListOperationError]()
/// [MultiplierError]()
/// [MutateError]()
/// [NewResourceCreationError]()
/// [NotEmptyError]()
/// [NullError]()
/// [OperationAccessDeniedError]()
/// [OperatorError]()
/// [QuotaError]()
/// [RangeError]()
/// [RequestError]()
/// [ResourceCountLimitExceededError]()
/// [SettingError]()
/// [SizeLimitError]()
/// [StringFormatError]()
/// [StringLengthError]()
/// [UrlFieldError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override MutateAdGroupsResponse MutateAdGroups(MutateAdGroupsRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_MutateAdGroupsRequest(ref request, ref callSettings);
return _callMutateAdGroups.Sync(request, callSettings);
}
/// <summary>
/// Creates, updates, or removes ad groups. Operation statuses are returned.
///
/// List of thrown errors:
/// [AdGroupError]()
/// [AdxError]()
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [BiddingError]()
/// [BiddingStrategyError]()
/// [DatabaseError]()
/// [DateError]()
/// [DistinctError]()
/// [FieldError]()
/// [FieldMaskError]()
/// [HeaderError]()
/// [IdError]()
/// [InternalError]()
/// [ListOperationError]()
/// [MultiplierError]()
/// [MutateError]()
/// [NewResourceCreationError]()
/// [NotEmptyError]()
/// [NullError]()
/// [OperationAccessDeniedError]()
/// [OperatorError]()
/// [QuotaError]()
/// [RangeError]()
/// [RequestError]()
/// [ResourceCountLimitExceededError]()
/// [SettingError]()
/// [SizeLimitError]()
/// [StringFormatError]()
/// [StringLengthError]()
/// [UrlFieldError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<MutateAdGroupsResponse> MutateAdGroupsAsync(MutateAdGroupsRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_MutateAdGroupsRequest(ref request, ref callSettings);
return _callMutateAdGroups.Async(request, callSettings);
}
}
}
| |
using System;
using System.Collections.Generic;
using Xunit;
using Xunit.Sdk;
// TODO: These are xunit1 tests
#if false
namespace tests.xunit.unsupported
{
// The default ordering is reflection order, which is top-down order of the source file.
// Note that reflection order is not guaranteed to remain constant across all
// versions and implementations of the CLR.
// TEST: The class should be marked as a test class
// TEST: Running the class runs all of the tests
// TEST: All tests pass
[PrioritizedFixture]
public class DefaultOrdering
{
public static bool Test1Called;
public static bool Test2Called;
public static bool Test3Called;
// TEST: The method should be marked as a test class
// TEST: Can run individual test
[Fact]
public void Test1()
{
Test1Called = true;
Assert.False(Test2Called);
Assert.False(Test3Called);
}
// TEST: The method should be marked as a test class
// TEST: Can run individual test
[Fact]
public void Test2()
{
Test2Called = true;
Assert.True(Test1Called);
Assert.False(Test3Called);
}
// TEST: The method should be marked as a test class
// TEST: Can run individual test
[Fact]
public void Test3()
{
Test3Called = true;
Assert.True(Test1Called);
Assert.True(Test2Called);
}
}
// The default priority is 0. Within a given priority, the tests are run in
// reflection order, just like the example above. Since reflection order should
// not be relied upon, use test priority to ensure certain classes of tests run
// before others as appropriate.
// TEST: The class should be marked as a test class
// TEST: Running the class runs all of the tests
// TEST: All tests pass
[PrioritizedFixture]
public class CustomOrdering
{
public static bool Test1Called;
public static bool Test2Called;
public static bool Test3Called;
// TEST: The method should be marked as a test class
// TEST: Can run individual test
[Fact, TestPriority(5)]
public void Test3()
{
Test3Called = true;
Assert.True(Test1Called);
Assert.True(Test2Called);
}
// TEST: The method should be marked as a test class
// TEST: Can run individual test
[Fact]
public void Test2()
{
Test2Called = true;
Assert.True(Test1Called);
Assert.False(Test3Called);
}
// TEST: The method should be marked as a test class
// TEST: Can run individual test
[Fact, TestPriority(-5)]
public void Test1()
{
Test1Called = true;
Assert.False(Test2Called);
Assert.False(Test3Called);
}
}
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
public class TestPriorityAttribute : Attribute
{
public TestPriorityAttribute(int priority)
{
Priority = priority;
}
public int Priority { get; private set; }
}
public class PrioritizedFixtureAttribute : RunWithAttribute
{
public PrioritizedFixtureAttribute() : base(typeof (PrioritizedFixtureClassCommand))
{
}
}
public class PrioritizedFixtureClassCommand : ITestClassCommand
{
// Delegate most of the work to the existing TestClassCommand class so that we
// can preserve any existing behavior (like supporting IUseFixture<T>).
private readonly TestClassCommand cmd = new TestClassCommand();
public object ObjectUnderTest
{
get { return cmd.ObjectUnderTest; }
}
public ITypeInfo TypeUnderTest
{
get { return cmd.TypeUnderTest; }
set { cmd.TypeUnderTest = value; }
}
public int ChooseNextTest(ICollection<IMethodInfo> testsLeftToRun)
{
// Always run the next test in the list, since the list is already ordered
return 0;
}
public Exception ClassFinish()
{
return cmd.ClassFinish();
}
public Exception ClassStart()
{
return cmd.ClassStart();
}
public IEnumerable<ITestCommand> EnumerateTestCommands(IMethodInfo testMethod)
{
return cmd.EnumerateTestCommands(testMethod);
}
public IEnumerable<IMethodInfo> EnumerateTestMethods()
{
var sortedMethods = new SortedDictionary<int, List<IMethodInfo>>();
foreach (IMethodInfo method in cmd.EnumerateTestMethods())
{
int priority = 0;
foreach (IAttributeInfo attr in method.GetCustomAttributes(typeof (TestPriorityAttribute)))
priority = attr.GetPropertyValue<int>("Priority");
GetOrCreate(sortedMethods, priority).Add(method);
}
foreach (int priority in sortedMethods.Keys)
foreach (IMethodInfo method in sortedMethods[priority])
yield return method;
}
public bool IsTestMethod(IMethodInfo testMethod)
{
return cmd.IsTestMethod(testMethod);
}
// Dictionary helper method
private static TValue GetOrCreate<TKey, TValue>(IDictionary<TKey, TValue> dictionary, TKey key)
where TValue : new()
{
TValue result;
if (!dictionary.TryGetValue(key, out result))
{
result = new TValue();
dictionary[key] = result;
}
return result;
}
}
}
#endif
| |
using System;
namespace Lunet.Api.DotNet.Extractor
{
public partial class JsonSerializer
{
static JsonSerializer()
{
_serializers.Add(typeof(Microsoft.DocAsCode.Metadata.ManagedReference.MetadataItem), SerializeMicrosoft_DocAsCode_Metadata_ManagedReference_MetadataItem);
_serializers.Add(typeof(Microsoft.DocAsCode.Metadata.ManagedReference.ReferenceItem), SerializeMicrosoft_DocAsCode_Metadata_ManagedReference_ReferenceItem);
_serializers.Add(typeof(Microsoft.DocAsCode.Metadata.ManagedReference.LinkItem), SerializeMicrosoft_DocAsCode_Metadata_ManagedReference_LinkItem);
_serializers.Add(typeof(Microsoft.DocAsCode.Metadata.ManagedReference.SyntaxDetail), SerializeMicrosoft_DocAsCode_Metadata_ManagedReference_SyntaxDetail);
_serializers.Add(typeof(Microsoft.DocAsCode.DataContracts.ManagedReference.AdditionalNotes), SerializeMicrosoft_DocAsCode_DataContracts_ManagedReference_AdditionalNotes);
_serializers.Add(typeof(Microsoft.DocAsCode.DataContracts.ManagedReference.ApiParameter), SerializeMicrosoft_DocAsCode_DataContracts_ManagedReference_ApiParameter);
_serializers.Add(typeof(Microsoft.DocAsCode.DataContracts.ManagedReference.ArgumentInfo), SerializeMicrosoft_DocAsCode_DataContracts_ManagedReference_ArgumentInfo);
_serializers.Add(typeof(Microsoft.DocAsCode.DataContracts.ManagedReference.AttributeInfo), SerializeMicrosoft_DocAsCode_DataContracts_ManagedReference_AttributeInfo);
_serializers.Add(typeof(Microsoft.DocAsCode.DataContracts.ManagedReference.ExceptionInfo), SerializeMicrosoft_DocAsCode_DataContracts_ManagedReference_ExceptionInfo);
_serializers.Add(typeof(Microsoft.DocAsCode.DataContracts.ManagedReference.ItemViewModel), SerializeMicrosoft_DocAsCode_DataContracts_ManagedReference_ItemViewModel);
_serializers.Add(typeof(Microsoft.DocAsCode.DataContracts.ManagedReference.LinkInfo), SerializeMicrosoft_DocAsCode_DataContracts_ManagedReference_LinkInfo);
_serializers.Add(typeof(Microsoft.DocAsCode.DataContracts.ManagedReference.NamedArgumentInfo), SerializeMicrosoft_DocAsCode_DataContracts_ManagedReference_NamedArgumentInfo);
_serializers.Add(typeof(Microsoft.DocAsCode.DataContracts.ManagedReference.PageViewModel), SerializeMicrosoft_DocAsCode_DataContracts_ManagedReference_PageViewModel);
_serializers.Add(typeof(Microsoft.DocAsCode.DataContracts.ManagedReference.SyntaxDetailViewModel), SerializeMicrosoft_DocAsCode_DataContracts_ManagedReference_SyntaxDetailViewModel);
_serializers.Add(typeof(Microsoft.DocAsCode.DataContracts.Common.ReferenceViewModel), SerializeMicrosoft_DocAsCode_DataContracts_Common_ReferenceViewModel);
_serializers.Add(typeof(Microsoft.DocAsCode.DataContracts.Common.SourceDetail), SerializeMicrosoft_DocAsCode_DataContracts_Common_SourceDetail);
_serializers.Add(typeof(Microsoft.DocAsCode.DataContracts.Common.SpecViewModel), SerializeMicrosoft_DocAsCode_DataContracts_Common_SpecViewModel);
_serializers.Add(typeof(Microsoft.DocAsCode.DataContracts.Common.TocItemViewModel), SerializeMicrosoft_DocAsCode_DataContracts_Common_TocItemViewModel);
_serializers.Add(typeof(Microsoft.DocAsCode.DataContracts.Common.TocRootViewModel), SerializeMicrosoft_DocAsCode_DataContracts_Common_TocRootViewModel);
_serializers.Add(typeof(Microsoft.DocAsCode.Common.Git.GitDetail), SerializeMicrosoft_DocAsCode_Common_Git_GitDetail);
_serializers.Add(typeof(Lunet.Api.DotNet.Extractor.AssemblyViewModel), SerializeLunet_Api_DotNet_Extractor_AssemblyViewModel);
_serializers.Add(typeof(Microsoft.DocAsCode.Common.HtmlLogListener.ReportItem), SerializeMicrosoft_DocAsCode_Common_HtmlLogListener_ReportItem);
_serializers.Add(typeof(Microsoft.DocAsCode.Common.ReportLogListener.ReportItem), SerializeMicrosoft_DocAsCode_Common_ReportLogListener_ReportItem);
}
private static void SerializeMicrosoft_DocAsCode_Metadata_ManagedReference_MetadataItem(JsonSerializer serializer, object valueObj)
{
var value = (Microsoft.DocAsCode.Metadata.ManagedReference.MetadataItem)valueObj;
serializer.StartObject();
serializer.WriteJsonKeyValue("isEii", value.IsExplicitInterfaceImplementation);
serializer.WriteJsonKeyValue("isExtensionMethod", value.IsExtensionMethod);
serializer.WriteJsonKeyValue("id", value.Name);
serializer.WriteJsonKeyValue("commentId", value.CommentId);
serializer.WriteJsonKeyValue("language", value.Language);
serializer.WriteJsonKeyValue("name", value.DisplayNames);
serializer.WriteJsonKeyValue("nameWithType", value.DisplayNamesWithType);
serializer.WriteJsonKeyValue("qualifiedName", value.DisplayQualifiedNames);
serializer.WriteJsonKeyValue("parent", value.Parent);
serializer.WriteJsonKeyValue("type", value.Type);
serializer.WriteJsonKeyValue("assemblies", value.AssemblyNameList);
serializer.WriteJsonKeyValue("namespace", value.NamespaceName);
serializer.WriteJsonKeyValue("source", value.Source);
serializer.WriteJsonKeyValue("documentation", value.Documentation);
serializer.WriteJsonKeyValue("summary", value.Summary);
serializer.WriteJsonKeyValue("remarks", value.Remarks);
serializer.WriteJsonKeyValue("example", value.Examples);
serializer.WriteJsonKeyValue("syntax", value.Syntax);
serializer.WriteJsonKeyValue("overload", value.Overload);
serializer.WriteJsonKeyValue("overridden", value.Overridden);
serializer.WriteJsonKeyValue("exceptions", value.Exceptions);
serializer.WriteJsonKeyValue("see", value.Sees);
serializer.WriteJsonKeyValue("seealso", value.SeeAlsos);
serializer.WriteJsonKeyValue("inheritance", value.Inheritance);
serializer.WriteJsonKeyValue("derivedClasses", value.DerivedClasses);
serializer.WriteJsonKeyValue("implements", value.Implements);
serializer.WriteJsonKeyValue("inheritedMembers", value.InheritedMembers);
serializer.WriteJsonKeyValue("extensionMethods", value.ExtensionMethods);
serializer.WriteJsonKeyValue("attributes", value.Attributes);
serializer.WriteJsonKeyValue("modifiers", value.Modifiers);
serializer.WriteJsonKeyValue("items", value.Items);
serializer.WriteJsonKeyValue("references", value.References);
serializer.EndObject();
}
private static void SerializeMicrosoft_DocAsCode_Metadata_ManagedReference_ReferenceItem(JsonSerializer serializer, object valueObj)
{
var value = (Microsoft.DocAsCode.Metadata.ManagedReference.ReferenceItem)valueObj;
serializer.StartObject();
serializer.WriteJsonKeyValue("name", value.Parts);
serializer.WriteJsonKeyValue("isDefinition", value.IsDefinition);
serializer.WriteJsonKeyValue("definition", value.Definition);
serializer.WriteJsonKeyValue("parent", value.Parent);
serializer.WriteJsonKeyValue("commentId", value.CommentId);
serializer.EndObject();
}
private static void SerializeMicrosoft_DocAsCode_Metadata_ManagedReference_LinkItem(JsonSerializer serializer, object valueObj)
{
var value = (Microsoft.DocAsCode.Metadata.ManagedReference.LinkItem)valueObj;
serializer.StartObject();
serializer.WriteJsonKeyValue("id", value.Name);
serializer.WriteJsonKeyValue("name", value.DisplayName);
serializer.WriteJsonKeyValue("nameWithType", value.DisplayNamesWithType);
serializer.WriteJsonKeyValue("qualifiedName", value.DisplayQualifiedNames);
serializer.WriteJsonKeyValue("isExternal", value.IsExternalPath);
serializer.WriteJsonKeyValue("href", value.Href);
serializer.EndObject();
}
private static void SerializeMicrosoft_DocAsCode_Metadata_ManagedReference_SyntaxDetail(JsonSerializer serializer, object valueObj)
{
var value = (Microsoft.DocAsCode.Metadata.ManagedReference.SyntaxDetail)valueObj;
serializer.StartObject();
serializer.WriteJsonKeyValue("content", value.Content);
serializer.WriteJsonKeyValue("parameters", value.Parameters);
serializer.WriteJsonKeyValue("typeParameters", value.TypeParameters);
serializer.WriteJsonKeyValue("return", value.Return);
serializer.EndObject();
}
private static void SerializeMicrosoft_DocAsCode_DataContracts_ManagedReference_AdditionalNotes(JsonSerializer serializer, object valueObj)
{
var value = (Microsoft.DocAsCode.DataContracts.ManagedReference.AdditionalNotes)valueObj;
serializer.StartObject();
serializer.WriteJsonKeyValue("caller", value.Caller);
serializer.WriteJsonKeyValue("implementer", value.Implementer);
serializer.WriteJsonKeyValue("inheritor", value.Inheritor);
serializer.EndObject();
}
private static void SerializeMicrosoft_DocAsCode_DataContracts_ManagedReference_ApiParameter(JsonSerializer serializer, object valueObj)
{
var value = (Microsoft.DocAsCode.DataContracts.ManagedReference.ApiParameter)valueObj;
serializer.StartObject();
serializer.WriteJsonKeyValue("id", value.Name);
serializer.WriteJsonKeyValue("type", value.Type);
serializer.WriteJsonKeyValue("description", value.Description);
serializer.WriteJsonKeyValue("attributes", value.Attributes);
serializer.EndObject();
}
private static void SerializeMicrosoft_DocAsCode_DataContracts_ManagedReference_ArgumentInfo(JsonSerializer serializer, object valueObj)
{
var value = (Microsoft.DocAsCode.DataContracts.ManagedReference.ArgumentInfo)valueObj;
serializer.StartObject();
serializer.WriteJsonKeyValue("type", value.Type);
serializer.WriteJsonKeyValue("value", value.Value);
serializer.EndObject();
}
private static void SerializeMicrosoft_DocAsCode_DataContracts_ManagedReference_AttributeInfo(JsonSerializer serializer, object valueObj)
{
var value = (Microsoft.DocAsCode.DataContracts.ManagedReference.AttributeInfo)valueObj;
serializer.StartObject();
serializer.WriteJsonKeyValue("type", value.Type);
serializer.WriteJsonKeyValue("ctor", value.Constructor);
serializer.WriteJsonKeyValue("arguments", value.Arguments);
serializer.WriteJsonKeyValue("namedArguments", value.NamedArguments);
serializer.EndObject();
}
private static void SerializeMicrosoft_DocAsCode_DataContracts_ManagedReference_ExceptionInfo(JsonSerializer serializer, object valueObj)
{
var value = (Microsoft.DocAsCode.DataContracts.ManagedReference.ExceptionInfo)valueObj;
serializer.StartObject();
serializer.WriteJsonKeyValue("type", value.Type);
serializer.WriteJsonKeyValue("commentId", value.CommentId);
serializer.WriteJsonKeyValue("description", value.Description);
serializer.EndObject();
}
private static void SerializeMicrosoft_DocAsCode_DataContracts_ManagedReference_ItemViewModel(JsonSerializer serializer, object valueObj)
{
var value = (Microsoft.DocAsCode.DataContracts.ManagedReference.ItemViewModel)valueObj;
serializer.StartObject();
serializer.WriteJsonKeyValue("uid", value.Uid);
serializer.WriteJsonKeyValue("commentId", value.CommentId);
serializer.WriteJsonKeyValue("id", value.Id);
serializer.WriteJsonKeyValue("isEii", value.IsExplicitInterfaceImplementation);
serializer.WriteJsonKeyValue("isExtensionMethod", value.IsExtensionMethod);
serializer.WriteJsonKeyValue("parent", value.Parent);
serializer.WriteJsonKeyValue("children", value.Children);
serializer.WriteJsonKeyValue("href", value.Href);
serializer.WriteJsonKeyValue("langs", value.SupportedLanguages);
serializer.WriteJsonKeyValue("name", value.Name);
serializer.WriteJsonKeyValue("nameWithType", value.NameWithType);
serializer.WriteJsonKeyValue("fullName", value.FullName);
serializer.WriteJsonKeyValue("type", value.Type);
serializer.WriteJsonKeyValue("source", value.Source);
serializer.WriteJsonKeyValue("documentation", value.Documentation);
serializer.WriteJsonKeyValue("assemblies", value.AssemblyNameList);
serializer.WriteJsonKeyValue("namespace", value.NamespaceName);
serializer.WriteJsonKeyValue("summary", value.Summary);
serializer.WriteJsonKeyValue("additionalNotes", value.AdditionalNotes);
serializer.WriteJsonKeyValue("remarks", value.Remarks);
serializer.WriteJsonKeyValue("example", value.Examples);
serializer.WriteJsonKeyValue("syntax", value.Syntax);
serializer.WriteJsonKeyValue("overridden", value.Overridden);
serializer.WriteJsonKeyValue("overload", value.Overload);
serializer.WriteJsonKeyValue("exceptions", value.Exceptions);
serializer.WriteJsonKeyValue("seealso", value.SeeAlsos);
serializer.WriteJsonKeyValue("see", value.Sees);
serializer.WriteJsonKeyValue("inheritance", value.Inheritance);
serializer.WriteJsonKeyValue("derivedClasses", value.DerivedClasses);
serializer.WriteJsonKeyValue("implements", value.Implements);
serializer.WriteJsonKeyValue("inheritedMembers", value.InheritedMembers);
serializer.WriteJsonKeyValue("extensionMethods", value.ExtensionMethods);
serializer.WriteJsonKeyValue("conceptual", value.Conceptual);
serializer.WriteJsonKeyValue("platform", value.Platform);
serializer.WriteJsonKeyValue("attributes", value.Attributes);
serializer.EndObject();
}
private static void SerializeMicrosoft_DocAsCode_DataContracts_ManagedReference_LinkInfo(JsonSerializer serializer, object valueObj)
{
var value = (Microsoft.DocAsCode.DataContracts.ManagedReference.LinkInfo)valueObj;
serializer.StartObject();
serializer.WriteJsonKeyValue("linkType", value.LinkType);
serializer.WriteJsonKeyValue("linkId", value.LinkId);
serializer.WriteJsonKeyValue("commentId", value.CommentId);
serializer.WriteJsonKeyValue("altText", value.AltText);
serializer.EndObject();
}
private static void SerializeMicrosoft_DocAsCode_DataContracts_ManagedReference_NamedArgumentInfo(JsonSerializer serializer, object valueObj)
{
var value = (Microsoft.DocAsCode.DataContracts.ManagedReference.NamedArgumentInfo)valueObj;
serializer.StartObject();
serializer.WriteJsonKeyValue("name", value.Name);
serializer.WriteJsonKeyValue("type", value.Type);
serializer.WriteJsonKeyValue("value", value.Value);
serializer.EndObject();
}
private static void SerializeMicrosoft_DocAsCode_DataContracts_ManagedReference_PageViewModel(JsonSerializer serializer, object valueObj)
{
var value = (Microsoft.DocAsCode.DataContracts.ManagedReference.PageViewModel)valueObj;
serializer.StartObject();
serializer.WriteJsonKeyValue("items", value.Items);
serializer.WriteJsonKeyValue("references", value.References);
serializer.EndObject();
}
private static void SerializeMicrosoft_DocAsCode_DataContracts_ManagedReference_SyntaxDetailViewModel(JsonSerializer serializer, object valueObj)
{
var value = (Microsoft.DocAsCode.DataContracts.ManagedReference.SyntaxDetailViewModel)valueObj;
serializer.StartObject();
serializer.WriteJsonKeyValue("content", value.Content);
serializer.WriteJsonKeyValue("parameters", value.Parameters);
serializer.WriteJsonKeyValue("typeParameters", value.TypeParameters);
serializer.WriteJsonKeyValue("return", value.Return);
serializer.EndObject();
}
private static void SerializeMicrosoft_DocAsCode_DataContracts_Common_ReferenceViewModel(JsonSerializer serializer, object valueObj)
{
var value = (Microsoft.DocAsCode.DataContracts.Common.ReferenceViewModel)valueObj;
serializer.StartObject();
serializer.WriteJsonKeyValue("uid", value.Uid);
serializer.WriteJsonKeyValue("commentId", value.CommentId);
serializer.WriteJsonKeyValue("parent", value.Parent);
serializer.WriteJsonKeyValue("definition", value.Definition);
serializer.WriteJsonKeyValue("isExternal", value.IsExternal);
serializer.WriteJsonKeyValue("href", value.Href);
serializer.WriteJsonKeyValue("name", value.Name);
serializer.WriteJsonKeyValue("nameWithType", value.NameWithType);
serializer.WriteJsonKeyValue("fullName", value.FullName);
serializer.EndObject();
}
private static void SerializeMicrosoft_DocAsCode_DataContracts_Common_SourceDetail(JsonSerializer serializer, object valueObj)
{
var value = (Microsoft.DocAsCode.DataContracts.Common.SourceDetail)valueObj;
serializer.StartObject();
serializer.WriteJsonKeyValue("remote", value.Remote);
serializer.WriteJsonKeyValue("base", value.BasePath);
serializer.WriteJsonKeyValue("id", value.Name);
serializer.WriteJsonKeyValue("href", value.Href);
serializer.WriteJsonKeyValue("path", value.Path);
serializer.WriteJsonKeyValue("startLine", value.StartLine);
serializer.WriteJsonKeyValue("endLine", value.EndLine);
serializer.WriteJsonKeyValue("content", value.Content);
serializer.WriteJsonKeyValue("isExternal", value.IsExternalPath);
serializer.EndObject();
}
private static void SerializeMicrosoft_DocAsCode_DataContracts_Common_SpecViewModel(JsonSerializer serializer, object valueObj)
{
var value = (Microsoft.DocAsCode.DataContracts.Common.SpecViewModel)valueObj;
serializer.StartObject();
serializer.WriteJsonKeyValue("uid", value.Uid);
serializer.WriteJsonKeyValue("name", value.Name);
serializer.WriteJsonKeyValue("nameWithType", value.NameWithType);
serializer.WriteJsonKeyValue("fullName", value.FullName);
serializer.WriteJsonKeyValue("isExternal", value.IsExternal);
serializer.WriteJsonKeyValue("href", value.Href);
serializer.EndObject();
}
private static void SerializeMicrosoft_DocAsCode_DataContracts_Common_TocItemViewModel(JsonSerializer serializer, object valueObj)
{
var value = (Microsoft.DocAsCode.DataContracts.Common.TocItemViewModel)valueObj;
serializer.StartObject();
serializer.WriteJsonKeyValue("uid", value.Uid);
serializer.WriteJsonKeyValue("name", value.Name);
serializer.WriteJsonKeyValue("displayName", value.DisplayName);
serializer.WriteJsonKeyValue("href", value.Href);
serializer.WriteJsonKeyValue("originalHref", value.OriginalHref);
serializer.WriteJsonKeyValue("tocHref", value.TocHref);
serializer.WriteJsonKeyValue("originalTocHref", value.OriginalTocHref);
serializer.WriteJsonKeyValue("topicHref", value.TopicHref);
serializer.WriteJsonKeyValue("originalTopicHref", value.OriginalTopicHref);
serializer.WriteJsonKeyValue("includedFrom", value.IncludedFrom);
serializer.WriteJsonKeyValue("homepage", value.Homepage);
serializer.WriteJsonKeyValue("originallHomepage", value.OriginalHomepage);
serializer.WriteJsonKeyValue("homepageUid", value.HomepageUid);
serializer.WriteJsonKeyValue("topicUid", value.TopicUid);
serializer.WriteJsonKeyValue("items", value.Items);
serializer.EndObject();
}
private static void SerializeMicrosoft_DocAsCode_DataContracts_Common_TocRootViewModel(JsonSerializer serializer, object valueObj)
{
var value = (Microsoft.DocAsCode.DataContracts.Common.TocRootViewModel)valueObj;
serializer.StartObject();
serializer.WriteJsonKeyValue("items", value.Items);
serializer.EndObject();
}
private static void SerializeMicrosoft_DocAsCode_Common_Git_GitDetail(JsonSerializer serializer, object valueObj)
{
var value = (Microsoft.DocAsCode.Common.Git.GitDetail)valueObj;
serializer.StartObject();
serializer.WriteJsonKeyValue("path", value.RelativePath);
serializer.WriteJsonKeyValue("branch", value.RemoteBranch);
serializer.WriteJsonKeyValue("repo", value.RemoteRepositoryUrl);
serializer.EndObject();
}
private static void SerializeLunet_Api_DotNet_Extractor_AssemblyViewModel(JsonSerializer serializer, object valueObj)
{
var value = (Lunet.Api.DotNet.Extractor.AssemblyViewModel)valueObj;
serializer.StartObject();
serializer.WriteJsonKeyValue("name", value.Name);
serializer.WriteJsonKeyValue("items", value.Items);
serializer.EndObject();
}
private static void SerializeMicrosoft_DocAsCode_Common_HtmlLogListener_ReportItem(JsonSerializer serializer, object valueObj)
{
var value = (Microsoft.DocAsCode.Common.HtmlLogListener.ReportItem)valueObj;
serializer.StartObject();
serializer.WriteJsonKeyValue("message", value.Message);
serializer.WriteJsonKeyValue("source", value.Source);
serializer.WriteJsonKeyValue("file", value.File);
serializer.WriteJsonKeyValue("line", value.Line);
serializer.WriteJsonKeyValue("date_time", value.DateTime);
serializer.WriteJsonKeyValue("message_severity", value.Severity);
serializer.EndObject();
}
private static void SerializeMicrosoft_DocAsCode_Common_ReportLogListener_ReportItem(JsonSerializer serializer, object valueObj)
{
var value = (Microsoft.DocAsCode.Common.ReportLogListener.ReportItem)valueObj;
serializer.StartObject();
serializer.WriteJsonKeyValue("message", value.Message);
serializer.WriteJsonKeyValue("source", value.Source);
serializer.WriteJsonKeyValue("file", value.File);
serializer.WriteJsonKeyValue("line", value.Line);
serializer.WriteJsonKeyValue("date_time", value.DateTime);
serializer.WriteJsonKeyValue("message_severity", value.Severity);
serializer.WriteJsonKeyValue("code", value.Code);
serializer.WriteJsonKeyValue("correlation_id", value.CorrelationId);
serializer.EndObject();
}
}
}
| |
//
// TypeDefinition.cs
//
// Author:
// Jb Evain (jbevain@gmail.com)
//
// Copyright (c) 2008 - 2011 Jb Evain
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using Mono.Cecil.Metadata;
using Mono.Collections.Generic;
namespace Mono.Cecil {
public sealed class TypeDefinition : TypeReference, IMemberDefinition, ISecurityDeclarationProvider {
uint attributes;
TypeReference base_type;
internal Range fields_range;
internal Range methods_range;
short packing_size = Mixin.NotResolvedMarker;
int class_size = Mixin.NotResolvedMarker;
Collection<TypeReference> interfaces;
Collection<TypeDefinition> nested_types;
Collection<MethodDefinition> methods;
Collection<FieldDefinition> fields;
Collection<EventDefinition> events;
Collection<PropertyDefinition> properties;
Collection<CustomAttribute> custom_attributes;
Collection<SecurityDeclaration> security_declarations;
public TypeAttributes Attributes {
get { return (TypeAttributes) attributes; }
set { attributes = (uint) value; }
}
public TypeReference BaseType {
get { return base_type; }
set { base_type = value; }
}
void ResolveLayout ()
{
if (packing_size != Mixin.NotResolvedMarker || class_size != Mixin.NotResolvedMarker)
return;
if (!HasImage) {
packing_size = Mixin.NoDataMarker;
class_size = Mixin.NoDataMarker;
return;
}
var row = Module.Read (this, (type, reader) => reader.ReadTypeLayout (type));
packing_size = row.Col1;
class_size = row.Col2;
}
public bool HasLayoutInfo {
get {
if (packing_size >= 0 || class_size >= 0)
return true;
ResolveLayout ();
return packing_size >= 0 || class_size >= 0;
}
}
public short PackingSize {
get {
if (packing_size >= 0)
return packing_size;
ResolveLayout ();
return packing_size >= 0 ? packing_size : (short) -1;
}
set { packing_size = value; }
}
public int ClassSize {
get {
if (class_size >= 0)
return class_size;
ResolveLayout ();
return class_size >= 0 ? class_size : -1;
}
set { class_size = value; }
}
public bool HasInterfaces {
get {
if (interfaces != null)
return interfaces.Count > 0;
if (HasImage)
return Module.Read (this, (type, reader) => reader.HasInterfaces (type));
return false;
}
}
public Collection<TypeReference> Interfaces {
get {
if (interfaces != null)
return interfaces;
if (HasImage)
return Module.Read (ref interfaces, this, (type, reader) => reader.ReadInterfaces (type));
return interfaces = new Collection<TypeReference> ();
}
}
public bool HasNestedTypes {
get {
if (nested_types != null)
return nested_types.Count > 0;
if (HasImage)
return Module.Read (this, (type, reader) => reader.HasNestedTypes (type));
return false;
}
}
public Collection<TypeDefinition> NestedTypes {
get {
if (nested_types != null)
return nested_types;
if (HasImage)
return Module.Read (ref nested_types, this, (type, reader) => reader.ReadNestedTypes (type));
return nested_types = new MemberDefinitionCollection<TypeDefinition> (this);
}
}
public bool HasMethods {
get {
if (methods != null)
return methods.Count > 0;
if (HasImage)
return methods_range.Length > 0;
return false;
}
}
public Collection<MethodDefinition> Methods {
get {
if (methods != null)
return methods;
if (HasImage)
return Module.Read (ref methods, this, (type, reader) => reader.ReadMethods (type));
return methods = new MemberDefinitionCollection<MethodDefinition> (this);
}
}
public bool HasFields {
get {
if (fields != null)
return fields.Count > 0;
if (HasImage)
return fields_range.Length > 0;
return false;
}
}
public Collection<FieldDefinition> Fields {
get {
if (fields != null)
return fields;
if (HasImage)
return Module.Read (ref fields, this, (type, reader) => reader.ReadFields (type));
return fields = new MemberDefinitionCollection<FieldDefinition> (this);
}
}
public bool HasEvents {
get {
if (events != null)
return events.Count > 0;
if (HasImage)
return Module.Read (this, (type, reader) => reader.HasEvents (type));
return false;
}
}
public Collection<EventDefinition> Events {
get {
if (events != null)
return events;
if (HasImage)
return Module.Read (ref events, this, (type, reader) => reader.ReadEvents (type));
return events = new MemberDefinitionCollection<EventDefinition> (this);
}
}
public bool HasProperties {
get {
if (properties != null)
return properties.Count > 0;
if (HasImage)
return Module.Read (this, (type, reader) => reader.HasProperties (type));
return false;
}
}
public Collection<PropertyDefinition> Properties {
get {
if (properties != null)
return properties;
if (HasImage)
return Module.Read (ref properties, this, (type, reader) => reader.ReadProperties (type));
return properties = new MemberDefinitionCollection<PropertyDefinition> (this);
}
}
public bool HasSecurityDeclarations {
get {
if (security_declarations != null)
return security_declarations.Count > 0;
return this.GetHasSecurityDeclarations (Module);
}
}
public Collection<SecurityDeclaration> SecurityDeclarations {
get { return security_declarations ?? (this.GetSecurityDeclarations (ref security_declarations, Module)); }
}
public bool HasCustomAttributes {
get {
if (custom_attributes != null)
return custom_attributes.Count > 0;
return this.GetHasCustomAttributes (Module);
}
}
public Collection<CustomAttribute> CustomAttributes {
get { return custom_attributes ?? (this.GetCustomAttributes (ref custom_attributes, Module)); }
}
public override bool HasGenericParameters {
get {
if (generic_parameters != null)
return generic_parameters.Count > 0;
return this.GetHasGenericParameters (Module);
}
}
public override Collection<GenericParameter> GenericParameters {
get { return generic_parameters ?? (this.GetGenericParameters (ref generic_parameters, Module)); }
}
#region TypeAttributes
public bool IsNotPublic {
get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NotPublic); }
set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NotPublic, value); }
}
public bool IsPublic {
get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.Public); }
set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.Public, value); }
}
public bool IsNestedPublic {
get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedPublic); }
set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedPublic, value); }
}
public bool IsNestedPrivate {
get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedPrivate); }
set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedPrivate, value); }
}
public bool IsNestedFamily {
get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedFamily); }
set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedFamily, value); }
}
public bool IsNestedAssembly {
get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedAssembly); }
set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedAssembly, value); }
}
public bool IsNestedFamilyAndAssembly {
get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedFamANDAssem); }
set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedFamANDAssem, value); }
}
public bool IsNestedFamilyOrAssembly {
get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedFamORAssem); }
set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedFamORAssem, value); }
}
public bool IsAutoLayout {
get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.LayoutMask, (uint) TypeAttributes.AutoLayout); }
set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.LayoutMask, (uint) TypeAttributes.AutoLayout, value); }
}
public bool IsSequentialLayout {
get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.LayoutMask, (uint) TypeAttributes.SequentialLayout); }
set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.LayoutMask, (uint) TypeAttributes.SequentialLayout, value); }
}
public bool IsExplicitLayout {
get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.LayoutMask, (uint) TypeAttributes.ExplicitLayout); }
set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.LayoutMask, (uint) TypeAttributes.ExplicitLayout, value); }
}
public bool IsClass {
get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.ClassSemanticMask, (uint) TypeAttributes.Class); }
set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.ClassSemanticMask, (uint) TypeAttributes.Class, value); }
}
public bool IsInterface {
get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.ClassSemanticMask, (uint) TypeAttributes.Interface); }
set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.ClassSemanticMask, (uint) TypeAttributes.Interface, value); }
}
public bool IsAbstract {
get { return attributes.GetAttributes ((uint) TypeAttributes.Abstract); }
set { attributes = attributes.SetAttributes ((uint) TypeAttributes.Abstract, value); }
}
public bool IsSealed {
get { return attributes.GetAttributes ((uint) TypeAttributes.Sealed); }
set { attributes = attributes.SetAttributes ((uint) TypeAttributes.Sealed, value); }
}
public bool IsSpecialName {
get { return attributes.GetAttributes ((uint) TypeAttributes.SpecialName); }
set { attributes = attributes.SetAttributes ((uint) TypeAttributes.SpecialName, value); }
}
public bool IsImport {
get { return attributes.GetAttributes ((uint) TypeAttributes.Import); }
set { attributes = attributes.SetAttributes ((uint) TypeAttributes.Import, value); }
}
public bool IsSerializable {
get { return attributes.GetAttributes ((uint) TypeAttributes.Serializable); }
set { attributes = attributes.SetAttributes ((uint) TypeAttributes.Serializable, value); }
}
public bool IsWindowsRuntime {
get { return attributes.GetAttributes ((uint) TypeAttributes.WindowsRuntime); }
set { attributes = attributes.SetAttributes ((uint) TypeAttributes.WindowsRuntime, value); }
}
public bool IsAnsiClass {
get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.StringFormatMask, (uint) TypeAttributes.AnsiClass); }
set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.StringFormatMask, (uint) TypeAttributes.AnsiClass, value); }
}
public bool IsUnicodeClass {
get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.StringFormatMask, (uint) TypeAttributes.UnicodeClass); }
set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.StringFormatMask, (uint) TypeAttributes.UnicodeClass, value); }
}
public bool IsAutoClass {
get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.StringFormatMask, (uint) TypeAttributes.AutoClass); }
set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.StringFormatMask, (uint) TypeAttributes.AutoClass, value); }
}
public bool IsBeforeFieldInit {
get { return attributes.GetAttributes ((uint) TypeAttributes.BeforeFieldInit); }
set { attributes = attributes.SetAttributes ((uint) TypeAttributes.BeforeFieldInit, value); }
}
public bool IsRuntimeSpecialName {
get { return attributes.GetAttributes ((uint) TypeAttributes.RTSpecialName); }
set { attributes = attributes.SetAttributes ((uint) TypeAttributes.RTSpecialName, value); }
}
public bool HasSecurity {
get { return attributes.GetAttributes ((uint) TypeAttributes.HasSecurity); }
set { attributes = attributes.SetAttributes ((uint) TypeAttributes.HasSecurity, value); }
}
#endregion
public bool IsEnum {
get { return base_type != null && base_type.IsTypeOf ("System", "Enum"); }
}
public override bool IsValueType {
get {
if (base_type == null)
return false;
return base_type.IsTypeOf ("System", "Enum") || (base_type.IsTypeOf ("System", "ValueType") && !this.IsTypeOf ("System", "Enum"));
}
}
public override bool IsPrimitive {
get {
ElementType primitive_etype;
return MetadataSystem.TryGetPrimitiveElementType (this, out primitive_etype);
}
}
public override MetadataType MetadataType {
get {
ElementType primitive_etype;
if (MetadataSystem.TryGetPrimitiveElementType (this, out primitive_etype))
return (MetadataType) primitive_etype;
return base.MetadataType;
}
}
public override bool IsDefinition {
get { return true; }
}
public new TypeDefinition DeclaringType {
get { return (TypeDefinition) base.DeclaringType; }
set { base.DeclaringType = value; }
}
public TypeDefinition (string @namespace, string name, TypeAttributes attributes)
: base (@namespace, name)
{
this.attributes = (uint) attributes;
this.token = new MetadataToken (TokenType.TypeDef);
}
public TypeDefinition (string @namespace, string name, TypeAttributes attributes, TypeReference baseType) :
this (@namespace, name, attributes)
{
this.BaseType = baseType;
}
public override TypeDefinition Resolve ()
{
return this;
}
}
static partial class Mixin {
public static TypeReference GetEnumUnderlyingType (this TypeDefinition self)
{
var fields = self.Fields;
for (int i = 0; i < fields.Count; i++) {
var field = fields [i];
if (!field.IsStatic)
return field.FieldType;
}
throw new ArgumentException ();
}
public static TypeDefinition GetNestedType (this TypeDefinition self, string name)
{
if (!self.HasNestedTypes)
return null;
var nested_types = self.NestedTypes;
for (int i = 0; i < nested_types.Count; i++) {
var nested_type = nested_types [i];
if (nested_type.Name == name)
return nested_type;
}
return null;
}
}
}
| |
using System;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Xml;
using System.Xml.Serialization;
using SubSonic;
using SubSonic.Utilities;
// <auto-generated />
namespace SAEON.Observations.Data{
/// <summary>
/// Strongly-typed collection for the VObservationJSON class.
/// </summary>
[Serializable]
public partial class VObservationJSONCollection : ReadOnlyList<VObservationJSON, VObservationJSONCollection>
{
public VObservationJSONCollection() {}
}
/// <summary>
/// This is Read-only wrapper class for the vObservationJSON view.
/// </summary>
[Serializable]
public partial class VObservationJSON : ReadOnlyRecord<VObservationJSON>, IReadOnlyRecord
{
#region Default Settings
protected static void SetSQLProps()
{
GetTableSchema();
}
#endregion
#region Schema Accessor
public static TableSchema.Table Schema
{
get
{
if (BaseSchema == null)
{
SetSQLProps();
}
return BaseSchema;
}
}
private static void GetTableSchema()
{
if(!IsSchemaInitialized)
{
//Schema declaration
TableSchema.Table schema = new TableSchema.Table("vObservationJSON", TableType.View, DataService.GetInstance("ObservationsDB"));
schema.Columns = new TableSchema.TableColumnCollection();
schema.SchemaName = @"dbo";
//columns
TableSchema.TableColumn colvarId = new TableSchema.TableColumn(schema);
colvarId.ColumnName = "ID";
colvarId.DataType = DbType.Int32;
colvarId.MaxLength = 0;
colvarId.AutoIncrement = false;
colvarId.IsNullable = false;
colvarId.IsPrimaryKey = false;
colvarId.IsForeignKey = false;
colvarId.IsReadOnly = false;
schema.Columns.Add(colvarId);
TableSchema.TableColumn colvarValueDate = new TableSchema.TableColumn(schema);
colvarValueDate.ColumnName = "ValueDate";
colvarValueDate.DataType = DbType.DateTime;
colvarValueDate.MaxLength = 0;
colvarValueDate.AutoIncrement = false;
colvarValueDate.IsNullable = false;
colvarValueDate.IsPrimaryKey = false;
colvarValueDate.IsForeignKey = false;
colvarValueDate.IsReadOnly = false;
schema.Columns.Add(colvarValueDate);
TableSchema.TableColumn colvarValueDay = new TableSchema.TableColumn(schema);
colvarValueDay.ColumnName = "ValueDay";
colvarValueDay.DataType = DbType.Date;
colvarValueDay.MaxLength = 0;
colvarValueDay.AutoIncrement = false;
colvarValueDay.IsNullable = true;
colvarValueDay.IsPrimaryKey = false;
colvarValueDay.IsForeignKey = false;
colvarValueDay.IsReadOnly = false;
schema.Columns.Add(colvarValueDay);
TableSchema.TableColumn colvarValueYear = new TableSchema.TableColumn(schema);
colvarValueYear.ColumnName = "ValueYear";
colvarValueYear.DataType = DbType.Int32;
colvarValueYear.MaxLength = 0;
colvarValueYear.AutoIncrement = false;
colvarValueYear.IsNullable = true;
colvarValueYear.IsPrimaryKey = false;
colvarValueYear.IsForeignKey = false;
colvarValueYear.IsReadOnly = false;
schema.Columns.Add(colvarValueYear);
TableSchema.TableColumn colvarValueDecade = new TableSchema.TableColumn(schema);
colvarValueDecade.ColumnName = "ValueDecade";
colvarValueDecade.DataType = DbType.Int32;
colvarValueDecade.MaxLength = 0;
colvarValueDecade.AutoIncrement = false;
colvarValueDecade.IsNullable = true;
colvarValueDecade.IsPrimaryKey = false;
colvarValueDecade.IsForeignKey = false;
colvarValueDecade.IsReadOnly = false;
schema.Columns.Add(colvarValueDecade);
TableSchema.TableColumn colvarTextValue = new TableSchema.TableColumn(schema);
colvarTextValue.ColumnName = "TextValue";
colvarTextValue.DataType = DbType.AnsiString;
colvarTextValue.MaxLength = 10;
colvarTextValue.AutoIncrement = false;
colvarTextValue.IsNullable = true;
colvarTextValue.IsPrimaryKey = false;
colvarTextValue.IsForeignKey = false;
colvarTextValue.IsReadOnly = false;
schema.Columns.Add(colvarTextValue);
TableSchema.TableColumn colvarRawValue = new TableSchema.TableColumn(schema);
colvarRawValue.ColumnName = "RawValue";
colvarRawValue.DataType = DbType.Double;
colvarRawValue.MaxLength = 0;
colvarRawValue.AutoIncrement = false;
colvarRawValue.IsNullable = true;
colvarRawValue.IsPrimaryKey = false;
colvarRawValue.IsForeignKey = false;
colvarRawValue.IsReadOnly = false;
schema.Columns.Add(colvarRawValue);
TableSchema.TableColumn colvarDataValue = new TableSchema.TableColumn(schema);
colvarDataValue.ColumnName = "DataValue";
colvarDataValue.DataType = DbType.Double;
colvarDataValue.MaxLength = 0;
colvarDataValue.AutoIncrement = false;
colvarDataValue.IsNullable = true;
colvarDataValue.IsPrimaryKey = false;
colvarDataValue.IsForeignKey = false;
colvarDataValue.IsReadOnly = false;
schema.Columns.Add(colvarDataValue);
TableSchema.TableColumn colvarComment = new TableSchema.TableColumn(schema);
colvarComment.ColumnName = "Comment";
colvarComment.DataType = DbType.AnsiString;
colvarComment.MaxLength = 250;
colvarComment.AutoIncrement = false;
colvarComment.IsNullable = true;
colvarComment.IsPrimaryKey = false;
colvarComment.IsForeignKey = false;
colvarComment.IsReadOnly = false;
schema.Columns.Add(colvarComment);
TableSchema.TableColumn colvarCorrelationID = new TableSchema.TableColumn(schema);
colvarCorrelationID.ColumnName = "CorrelationID";
colvarCorrelationID.DataType = DbType.Guid;
colvarCorrelationID.MaxLength = 0;
colvarCorrelationID.AutoIncrement = false;
colvarCorrelationID.IsNullable = true;
colvarCorrelationID.IsPrimaryKey = false;
colvarCorrelationID.IsForeignKey = false;
colvarCorrelationID.IsReadOnly = false;
schema.Columns.Add(colvarCorrelationID);
TableSchema.TableColumn colvarLatitude = new TableSchema.TableColumn(schema);
colvarLatitude.ColumnName = "Latitude";
colvarLatitude.DataType = DbType.Double;
colvarLatitude.MaxLength = 0;
colvarLatitude.AutoIncrement = false;
colvarLatitude.IsNullable = true;
colvarLatitude.IsPrimaryKey = false;
colvarLatitude.IsForeignKey = false;
colvarLatitude.IsReadOnly = false;
schema.Columns.Add(colvarLatitude);
TableSchema.TableColumn colvarLongitude = new TableSchema.TableColumn(schema);
colvarLongitude.ColumnName = "Longitude";
colvarLongitude.DataType = DbType.Double;
colvarLongitude.MaxLength = 0;
colvarLongitude.AutoIncrement = false;
colvarLongitude.IsNullable = true;
colvarLongitude.IsPrimaryKey = false;
colvarLongitude.IsForeignKey = false;
colvarLongitude.IsReadOnly = false;
schema.Columns.Add(colvarLongitude);
TableSchema.TableColumn colvarElevation = new TableSchema.TableColumn(schema);
colvarElevation.ColumnName = "Elevation";
colvarElevation.DataType = DbType.Double;
colvarElevation.MaxLength = 0;
colvarElevation.AutoIncrement = false;
colvarElevation.IsNullable = true;
colvarElevation.IsPrimaryKey = false;
colvarElevation.IsForeignKey = false;
colvarElevation.IsReadOnly = false;
schema.Columns.Add(colvarElevation);
TableSchema.TableColumn colvarUserId = new TableSchema.TableColumn(schema);
colvarUserId.ColumnName = "UserId";
colvarUserId.DataType = DbType.Guid;
colvarUserId.MaxLength = 0;
colvarUserId.AutoIncrement = false;
colvarUserId.IsNullable = false;
colvarUserId.IsPrimaryKey = false;
colvarUserId.IsForeignKey = false;
colvarUserId.IsReadOnly = false;
schema.Columns.Add(colvarUserId);
TableSchema.TableColumn colvarAddedDate = new TableSchema.TableColumn(schema);
colvarAddedDate.ColumnName = "AddedDate";
colvarAddedDate.DataType = DbType.DateTime;
colvarAddedDate.MaxLength = 0;
colvarAddedDate.AutoIncrement = false;
colvarAddedDate.IsNullable = false;
colvarAddedDate.IsPrimaryKey = false;
colvarAddedDate.IsForeignKey = false;
colvarAddedDate.IsReadOnly = false;
schema.Columns.Add(colvarAddedDate);
TableSchema.TableColumn colvarAddedAt = new TableSchema.TableColumn(schema);
colvarAddedAt.ColumnName = "AddedAt";
colvarAddedAt.DataType = DbType.DateTime;
colvarAddedAt.MaxLength = 0;
colvarAddedAt.AutoIncrement = false;
colvarAddedAt.IsNullable = true;
colvarAddedAt.IsPrimaryKey = false;
colvarAddedAt.IsForeignKey = false;
colvarAddedAt.IsReadOnly = false;
schema.Columns.Add(colvarAddedAt);
TableSchema.TableColumn colvarUpdatedAt = new TableSchema.TableColumn(schema);
colvarUpdatedAt.ColumnName = "UpdatedAt";
colvarUpdatedAt.DataType = DbType.DateTime;
colvarUpdatedAt.MaxLength = 0;
colvarUpdatedAt.AutoIncrement = false;
colvarUpdatedAt.IsNullable = true;
colvarUpdatedAt.IsPrimaryKey = false;
colvarUpdatedAt.IsForeignKey = false;
colvarUpdatedAt.IsReadOnly = false;
schema.Columns.Add(colvarUpdatedAt);
TableSchema.TableColumn colvarImportBatchID = new TableSchema.TableColumn(schema);
colvarImportBatchID.ColumnName = "ImportBatch.ID";
colvarImportBatchID.DataType = DbType.Guid;
colvarImportBatchID.MaxLength = 0;
colvarImportBatchID.AutoIncrement = false;
colvarImportBatchID.IsNullable = false;
colvarImportBatchID.IsPrimaryKey = false;
colvarImportBatchID.IsForeignKey = false;
colvarImportBatchID.IsReadOnly = false;
schema.Columns.Add(colvarImportBatchID);
TableSchema.TableColumn colvarImportBatchCode = new TableSchema.TableColumn(schema);
colvarImportBatchCode.ColumnName = "ImportBatch.Code";
colvarImportBatchCode.DataType = DbType.Int32;
colvarImportBatchCode.MaxLength = 0;
colvarImportBatchCode.AutoIncrement = false;
colvarImportBatchCode.IsNullable = false;
colvarImportBatchCode.IsPrimaryKey = false;
colvarImportBatchCode.IsForeignKey = false;
colvarImportBatchCode.IsReadOnly = false;
schema.Columns.Add(colvarImportBatchCode);
TableSchema.TableColumn colvarImportBatchDate = new TableSchema.TableColumn(schema);
colvarImportBatchDate.ColumnName = "ImportBatch.Date";
colvarImportBatchDate.DataType = DbType.DateTime;
colvarImportBatchDate.MaxLength = 0;
colvarImportBatchDate.AutoIncrement = false;
colvarImportBatchDate.IsNullable = false;
colvarImportBatchDate.IsPrimaryKey = false;
colvarImportBatchDate.IsForeignKey = false;
colvarImportBatchDate.IsReadOnly = false;
schema.Columns.Add(colvarImportBatchDate);
TableSchema.TableColumn colvarSiteID = new TableSchema.TableColumn(schema);
colvarSiteID.ColumnName = "Site.ID";
colvarSiteID.DataType = DbType.Guid;
colvarSiteID.MaxLength = 0;
colvarSiteID.AutoIncrement = false;
colvarSiteID.IsNullable = false;
colvarSiteID.IsPrimaryKey = false;
colvarSiteID.IsForeignKey = false;
colvarSiteID.IsReadOnly = false;
schema.Columns.Add(colvarSiteID);
TableSchema.TableColumn colvarSiteCode = new TableSchema.TableColumn(schema);
colvarSiteCode.ColumnName = "Site.Code";
colvarSiteCode.DataType = DbType.AnsiString;
colvarSiteCode.MaxLength = 50;
colvarSiteCode.AutoIncrement = false;
colvarSiteCode.IsNullable = false;
colvarSiteCode.IsPrimaryKey = false;
colvarSiteCode.IsForeignKey = false;
colvarSiteCode.IsReadOnly = false;
schema.Columns.Add(colvarSiteCode);
TableSchema.TableColumn colvarSiteName = new TableSchema.TableColumn(schema);
colvarSiteName.ColumnName = "Site.Name";
colvarSiteName.DataType = DbType.AnsiString;
colvarSiteName.MaxLength = 150;
colvarSiteName.AutoIncrement = false;
colvarSiteName.IsNullable = false;
colvarSiteName.IsPrimaryKey = false;
colvarSiteName.IsForeignKey = false;
colvarSiteName.IsReadOnly = false;
schema.Columns.Add(colvarSiteName);
TableSchema.TableColumn colvarStationID = new TableSchema.TableColumn(schema);
colvarStationID.ColumnName = "Station.ID";
colvarStationID.DataType = DbType.Guid;
colvarStationID.MaxLength = 0;
colvarStationID.AutoIncrement = false;
colvarStationID.IsNullable = false;
colvarStationID.IsPrimaryKey = false;
colvarStationID.IsForeignKey = false;
colvarStationID.IsReadOnly = false;
schema.Columns.Add(colvarStationID);
TableSchema.TableColumn colvarStationCode = new TableSchema.TableColumn(schema);
colvarStationCode.ColumnName = "Station.Code";
colvarStationCode.DataType = DbType.AnsiString;
colvarStationCode.MaxLength = 50;
colvarStationCode.AutoIncrement = false;
colvarStationCode.IsNullable = false;
colvarStationCode.IsPrimaryKey = false;
colvarStationCode.IsForeignKey = false;
colvarStationCode.IsReadOnly = false;
schema.Columns.Add(colvarStationCode);
TableSchema.TableColumn colvarStationName = new TableSchema.TableColumn(schema);
colvarStationName.ColumnName = "Station.Name";
colvarStationName.DataType = DbType.AnsiString;
colvarStationName.MaxLength = 150;
colvarStationName.AutoIncrement = false;
colvarStationName.IsNullable = false;
colvarStationName.IsPrimaryKey = false;
colvarStationName.IsForeignKey = false;
colvarStationName.IsReadOnly = false;
schema.Columns.Add(colvarStationName);
TableSchema.TableColumn colvarInstrumentID = new TableSchema.TableColumn(schema);
colvarInstrumentID.ColumnName = "Instrument.ID";
colvarInstrumentID.DataType = DbType.Guid;
colvarInstrumentID.MaxLength = 0;
colvarInstrumentID.AutoIncrement = false;
colvarInstrumentID.IsNullable = false;
colvarInstrumentID.IsPrimaryKey = false;
colvarInstrumentID.IsForeignKey = false;
colvarInstrumentID.IsReadOnly = false;
schema.Columns.Add(colvarInstrumentID);
TableSchema.TableColumn colvarInstrumentCode = new TableSchema.TableColumn(schema);
colvarInstrumentCode.ColumnName = "Instrument.Code";
colvarInstrumentCode.DataType = DbType.AnsiString;
colvarInstrumentCode.MaxLength = 50;
colvarInstrumentCode.AutoIncrement = false;
colvarInstrumentCode.IsNullable = false;
colvarInstrumentCode.IsPrimaryKey = false;
colvarInstrumentCode.IsForeignKey = false;
colvarInstrumentCode.IsReadOnly = false;
schema.Columns.Add(colvarInstrumentCode);
TableSchema.TableColumn colvarInstrumentName = new TableSchema.TableColumn(schema);
colvarInstrumentName.ColumnName = "Instrument.Name";
colvarInstrumentName.DataType = DbType.AnsiString;
colvarInstrumentName.MaxLength = 150;
colvarInstrumentName.AutoIncrement = false;
colvarInstrumentName.IsNullable = false;
colvarInstrumentName.IsPrimaryKey = false;
colvarInstrumentName.IsForeignKey = false;
colvarInstrumentName.IsReadOnly = false;
schema.Columns.Add(colvarInstrumentName);
TableSchema.TableColumn colvarSensorID = new TableSchema.TableColumn(schema);
colvarSensorID.ColumnName = "Sensor.ID";
colvarSensorID.DataType = DbType.Guid;
colvarSensorID.MaxLength = 0;
colvarSensorID.AutoIncrement = false;
colvarSensorID.IsNullable = false;
colvarSensorID.IsPrimaryKey = false;
colvarSensorID.IsForeignKey = false;
colvarSensorID.IsReadOnly = false;
schema.Columns.Add(colvarSensorID);
TableSchema.TableColumn colvarSensorCode = new TableSchema.TableColumn(schema);
colvarSensorCode.ColumnName = "Sensor.Code";
colvarSensorCode.DataType = DbType.AnsiString;
colvarSensorCode.MaxLength = 75;
colvarSensorCode.AutoIncrement = false;
colvarSensorCode.IsNullable = false;
colvarSensorCode.IsPrimaryKey = false;
colvarSensorCode.IsForeignKey = false;
colvarSensorCode.IsReadOnly = false;
schema.Columns.Add(colvarSensorCode);
TableSchema.TableColumn colvarSensorName = new TableSchema.TableColumn(schema);
colvarSensorName.ColumnName = "Sensor.Name";
colvarSensorName.DataType = DbType.AnsiString;
colvarSensorName.MaxLength = 150;
colvarSensorName.AutoIncrement = false;
colvarSensorName.IsNullable = false;
colvarSensorName.IsPrimaryKey = false;
colvarSensorName.IsForeignKey = false;
colvarSensorName.IsReadOnly = false;
schema.Columns.Add(colvarSensorName);
TableSchema.TableColumn colvarPhenomenonID = new TableSchema.TableColumn(schema);
colvarPhenomenonID.ColumnName = "Phenomenon.ID";
colvarPhenomenonID.DataType = DbType.Guid;
colvarPhenomenonID.MaxLength = 0;
colvarPhenomenonID.AutoIncrement = false;
colvarPhenomenonID.IsNullable = false;
colvarPhenomenonID.IsPrimaryKey = false;
colvarPhenomenonID.IsForeignKey = false;
colvarPhenomenonID.IsReadOnly = false;
schema.Columns.Add(colvarPhenomenonID);
TableSchema.TableColumn colvarPhenomenonCode = new TableSchema.TableColumn(schema);
colvarPhenomenonCode.ColumnName = "Phenomenon.Code";
colvarPhenomenonCode.DataType = DbType.AnsiString;
colvarPhenomenonCode.MaxLength = 50;
colvarPhenomenonCode.AutoIncrement = false;
colvarPhenomenonCode.IsNullable = false;
colvarPhenomenonCode.IsPrimaryKey = false;
colvarPhenomenonCode.IsForeignKey = false;
colvarPhenomenonCode.IsReadOnly = false;
schema.Columns.Add(colvarPhenomenonCode);
TableSchema.TableColumn colvarPhenomenonName = new TableSchema.TableColumn(schema);
colvarPhenomenonName.ColumnName = "Phenomenon.Name";
colvarPhenomenonName.DataType = DbType.AnsiString;
colvarPhenomenonName.MaxLength = 150;
colvarPhenomenonName.AutoIncrement = false;
colvarPhenomenonName.IsNullable = false;
colvarPhenomenonName.IsPrimaryKey = false;
colvarPhenomenonName.IsForeignKey = false;
colvarPhenomenonName.IsReadOnly = false;
schema.Columns.Add(colvarPhenomenonName);
TableSchema.TableColumn colvarOfferingID = new TableSchema.TableColumn(schema);
colvarOfferingID.ColumnName = "Offering.ID";
colvarOfferingID.DataType = DbType.Guid;
colvarOfferingID.MaxLength = 0;
colvarOfferingID.AutoIncrement = false;
colvarOfferingID.IsNullable = false;
colvarOfferingID.IsPrimaryKey = false;
colvarOfferingID.IsForeignKey = false;
colvarOfferingID.IsReadOnly = false;
schema.Columns.Add(colvarOfferingID);
TableSchema.TableColumn colvarOfferingCode = new TableSchema.TableColumn(schema);
colvarOfferingCode.ColumnName = "Offering.Code";
colvarOfferingCode.DataType = DbType.AnsiString;
colvarOfferingCode.MaxLength = 50;
colvarOfferingCode.AutoIncrement = false;
colvarOfferingCode.IsNullable = false;
colvarOfferingCode.IsPrimaryKey = false;
colvarOfferingCode.IsForeignKey = false;
colvarOfferingCode.IsReadOnly = false;
schema.Columns.Add(colvarOfferingCode);
TableSchema.TableColumn colvarOfferingName = new TableSchema.TableColumn(schema);
colvarOfferingName.ColumnName = "Offering.Name";
colvarOfferingName.DataType = DbType.AnsiString;
colvarOfferingName.MaxLength = 150;
colvarOfferingName.AutoIncrement = false;
colvarOfferingName.IsNullable = false;
colvarOfferingName.IsPrimaryKey = false;
colvarOfferingName.IsForeignKey = false;
colvarOfferingName.IsReadOnly = false;
schema.Columns.Add(colvarOfferingName);
TableSchema.TableColumn colvarUnitID = new TableSchema.TableColumn(schema);
colvarUnitID.ColumnName = "Unit.ID";
colvarUnitID.DataType = DbType.Guid;
colvarUnitID.MaxLength = 0;
colvarUnitID.AutoIncrement = false;
colvarUnitID.IsNullable = false;
colvarUnitID.IsPrimaryKey = false;
colvarUnitID.IsForeignKey = false;
colvarUnitID.IsReadOnly = false;
schema.Columns.Add(colvarUnitID);
TableSchema.TableColumn colvarUnitCode = new TableSchema.TableColumn(schema);
colvarUnitCode.ColumnName = "Unit.Code";
colvarUnitCode.DataType = DbType.AnsiString;
colvarUnitCode.MaxLength = 50;
colvarUnitCode.AutoIncrement = false;
colvarUnitCode.IsNullable = false;
colvarUnitCode.IsPrimaryKey = false;
colvarUnitCode.IsForeignKey = false;
colvarUnitCode.IsReadOnly = false;
schema.Columns.Add(colvarUnitCode);
TableSchema.TableColumn colvarUnitName = new TableSchema.TableColumn(schema);
colvarUnitName.ColumnName = "Unit.Name";
colvarUnitName.DataType = DbType.AnsiString;
colvarUnitName.MaxLength = 100;
colvarUnitName.AutoIncrement = false;
colvarUnitName.IsNullable = false;
colvarUnitName.IsPrimaryKey = false;
colvarUnitName.IsForeignKey = false;
colvarUnitName.IsReadOnly = false;
schema.Columns.Add(colvarUnitName);
TableSchema.TableColumn colvarUnitSymbol = new TableSchema.TableColumn(schema);
colvarUnitSymbol.ColumnName = "Unit.Symbol";
colvarUnitSymbol.DataType = DbType.AnsiString;
colvarUnitSymbol.MaxLength = 20;
colvarUnitSymbol.AutoIncrement = false;
colvarUnitSymbol.IsNullable = false;
colvarUnitSymbol.IsPrimaryKey = false;
colvarUnitSymbol.IsForeignKey = false;
colvarUnitSymbol.IsReadOnly = false;
schema.Columns.Add(colvarUnitSymbol);
TableSchema.TableColumn colvarStatusID = new TableSchema.TableColumn(schema);
colvarStatusID.ColumnName = "Status.ID";
colvarStatusID.DataType = DbType.Guid;
colvarStatusID.MaxLength = 0;
colvarStatusID.AutoIncrement = false;
colvarStatusID.IsNullable = true;
colvarStatusID.IsPrimaryKey = false;
colvarStatusID.IsForeignKey = false;
colvarStatusID.IsReadOnly = false;
schema.Columns.Add(colvarStatusID);
TableSchema.TableColumn colvarStatusCode = new TableSchema.TableColumn(schema);
colvarStatusCode.ColumnName = "Status.Code";
colvarStatusCode.DataType = DbType.AnsiString;
colvarStatusCode.MaxLength = 50;
colvarStatusCode.AutoIncrement = false;
colvarStatusCode.IsNullable = true;
colvarStatusCode.IsPrimaryKey = false;
colvarStatusCode.IsForeignKey = false;
colvarStatusCode.IsReadOnly = false;
schema.Columns.Add(colvarStatusCode);
TableSchema.TableColumn colvarStatusName = new TableSchema.TableColumn(schema);
colvarStatusName.ColumnName = "Status.Name";
colvarStatusName.DataType = DbType.AnsiString;
colvarStatusName.MaxLength = 150;
colvarStatusName.AutoIncrement = false;
colvarStatusName.IsNullable = true;
colvarStatusName.IsPrimaryKey = false;
colvarStatusName.IsForeignKey = false;
colvarStatusName.IsReadOnly = false;
schema.Columns.Add(colvarStatusName);
TableSchema.TableColumn colvarStatusReasonID = new TableSchema.TableColumn(schema);
colvarStatusReasonID.ColumnName = "StatusReason.ID";
colvarStatusReasonID.DataType = DbType.Guid;
colvarStatusReasonID.MaxLength = 0;
colvarStatusReasonID.AutoIncrement = false;
colvarStatusReasonID.IsNullable = true;
colvarStatusReasonID.IsPrimaryKey = false;
colvarStatusReasonID.IsForeignKey = false;
colvarStatusReasonID.IsReadOnly = false;
schema.Columns.Add(colvarStatusReasonID);
TableSchema.TableColumn colvarStatusReasonCode = new TableSchema.TableColumn(schema);
colvarStatusReasonCode.ColumnName = "StatusReason.Code";
colvarStatusReasonCode.DataType = DbType.AnsiString;
colvarStatusReasonCode.MaxLength = 50;
colvarStatusReasonCode.AutoIncrement = false;
colvarStatusReasonCode.IsNullable = true;
colvarStatusReasonCode.IsPrimaryKey = false;
colvarStatusReasonCode.IsForeignKey = false;
colvarStatusReasonCode.IsReadOnly = false;
schema.Columns.Add(colvarStatusReasonCode);
TableSchema.TableColumn colvarStatusReasonName = new TableSchema.TableColumn(schema);
colvarStatusReasonName.ColumnName = "StatusReason.Name";
colvarStatusReasonName.DataType = DbType.AnsiString;
colvarStatusReasonName.MaxLength = 150;
colvarStatusReasonName.AutoIncrement = false;
colvarStatusReasonName.IsNullable = true;
colvarStatusReasonName.IsPrimaryKey = false;
colvarStatusReasonName.IsForeignKey = false;
colvarStatusReasonName.IsReadOnly = false;
schema.Columns.Add(colvarStatusReasonName);
BaseSchema = schema;
//add this schema to the provider
//so we can query it later
DataService.Providers["ObservationsDB"].AddSchema("vObservationJSON",schema);
}
}
#endregion
#region Query Accessor
public static Query CreateQuery()
{
return new Query(Schema);
}
#endregion
#region .ctors
public VObservationJSON()
{
SetSQLProps();
SetDefaults();
MarkNew();
}
public VObservationJSON(bool useDatabaseDefaults)
{
SetSQLProps();
if(useDatabaseDefaults)
{
ForceDefaults();
}
MarkNew();
}
public VObservationJSON(object keyID)
{
SetSQLProps();
LoadByKey(keyID);
}
public VObservationJSON(string columnName, object columnValue)
{
SetSQLProps();
LoadByParam(columnName,columnValue);
}
#endregion
#region Props
[XmlAttribute("Id")]
[Bindable(true)]
public int Id
{
get
{
return GetColumnValue<int>("ID");
}
set
{
SetColumnValue("ID", value);
}
}
[XmlAttribute("ValueDate")]
[Bindable(true)]
public DateTime ValueDate
{
get
{
return GetColumnValue<DateTime>("ValueDate");
}
set
{
SetColumnValue("ValueDate", value);
}
}
[XmlAttribute("ValueDay")]
[Bindable(true)]
public DateTime? ValueDay
{
get
{
return GetColumnValue<DateTime?>("ValueDay");
}
set
{
SetColumnValue("ValueDay", value);
}
}
[XmlAttribute("ValueYear")]
[Bindable(true)]
public int? ValueYear
{
get
{
return GetColumnValue<int?>("ValueYear");
}
set
{
SetColumnValue("ValueYear", value);
}
}
[XmlAttribute("ValueDecade")]
[Bindable(true)]
public int? ValueDecade
{
get
{
return GetColumnValue<int?>("ValueDecade");
}
set
{
SetColumnValue("ValueDecade", value);
}
}
[XmlAttribute("TextValue")]
[Bindable(true)]
public string TextValue
{
get
{
return GetColumnValue<string>("TextValue");
}
set
{
SetColumnValue("TextValue", value);
}
}
[XmlAttribute("RawValue")]
[Bindable(true)]
public double? RawValue
{
get
{
return GetColumnValue<double?>("RawValue");
}
set
{
SetColumnValue("RawValue", value);
}
}
[XmlAttribute("DataValue")]
[Bindable(true)]
public double? DataValue
{
get
{
return GetColumnValue<double?>("DataValue");
}
set
{
SetColumnValue("DataValue", value);
}
}
[XmlAttribute("Comment")]
[Bindable(true)]
public string Comment
{
get
{
return GetColumnValue<string>("Comment");
}
set
{
SetColumnValue("Comment", value);
}
}
[XmlAttribute("CorrelationID")]
[Bindable(true)]
public Guid? CorrelationID
{
get
{
return GetColumnValue<Guid?>("CorrelationID");
}
set
{
SetColumnValue("CorrelationID", value);
}
}
[XmlAttribute("Latitude")]
[Bindable(true)]
public double? Latitude
{
get
{
return GetColumnValue<double?>("Latitude");
}
set
{
SetColumnValue("Latitude", value);
}
}
[XmlAttribute("Longitude")]
[Bindable(true)]
public double? Longitude
{
get
{
return GetColumnValue<double?>("Longitude");
}
set
{
SetColumnValue("Longitude", value);
}
}
[XmlAttribute("Elevation")]
[Bindable(true)]
public double? Elevation
{
get
{
return GetColumnValue<double?>("Elevation");
}
set
{
SetColumnValue("Elevation", value);
}
}
[XmlAttribute("UserId")]
[Bindable(true)]
public Guid UserId
{
get
{
return GetColumnValue<Guid>("UserId");
}
set
{
SetColumnValue("UserId", value);
}
}
[XmlAttribute("AddedDate")]
[Bindable(true)]
public DateTime AddedDate
{
get
{
return GetColumnValue<DateTime>("AddedDate");
}
set
{
SetColumnValue("AddedDate", value);
}
}
[XmlAttribute("AddedAt")]
[Bindable(true)]
public DateTime? AddedAt
{
get
{
return GetColumnValue<DateTime?>("AddedAt");
}
set
{
SetColumnValue("AddedAt", value);
}
}
[XmlAttribute("UpdatedAt")]
[Bindable(true)]
public DateTime? UpdatedAt
{
get
{
return GetColumnValue<DateTime?>("UpdatedAt");
}
set
{
SetColumnValue("UpdatedAt", value);
}
}
[XmlAttribute("ImportBatchID")]
[Bindable(true)]
public Guid ImportBatchID
{
get
{
return GetColumnValue<Guid>("ImportBatch.ID");
}
set
{
SetColumnValue("ImportBatch.ID", value);
}
}
[XmlAttribute("ImportBatchCode")]
[Bindable(true)]
public int ImportBatchCode
{
get
{
return GetColumnValue<int>("ImportBatch.Code");
}
set
{
SetColumnValue("ImportBatch.Code", value);
}
}
[XmlAttribute("ImportBatchDate")]
[Bindable(true)]
public DateTime ImportBatchDate
{
get
{
return GetColumnValue<DateTime>("ImportBatch.Date");
}
set
{
SetColumnValue("ImportBatch.Date", value);
}
}
[XmlAttribute("SiteID")]
[Bindable(true)]
public Guid SiteID
{
get
{
return GetColumnValue<Guid>("Site.ID");
}
set
{
SetColumnValue("Site.ID", value);
}
}
[XmlAttribute("SiteCode")]
[Bindable(true)]
public string SiteCode
{
get
{
return GetColumnValue<string>("Site.Code");
}
set
{
SetColumnValue("Site.Code", value);
}
}
[XmlAttribute("SiteName")]
[Bindable(true)]
public string SiteName
{
get
{
return GetColumnValue<string>("Site.Name");
}
set
{
SetColumnValue("Site.Name", value);
}
}
[XmlAttribute("StationID")]
[Bindable(true)]
public Guid StationID
{
get
{
return GetColumnValue<Guid>("Station.ID");
}
set
{
SetColumnValue("Station.ID", value);
}
}
[XmlAttribute("StationCode")]
[Bindable(true)]
public string StationCode
{
get
{
return GetColumnValue<string>("Station.Code");
}
set
{
SetColumnValue("Station.Code", value);
}
}
[XmlAttribute("StationName")]
[Bindable(true)]
public string StationName
{
get
{
return GetColumnValue<string>("Station.Name");
}
set
{
SetColumnValue("Station.Name", value);
}
}
[XmlAttribute("InstrumentID")]
[Bindable(true)]
public Guid InstrumentID
{
get
{
return GetColumnValue<Guid>("Instrument.ID");
}
set
{
SetColumnValue("Instrument.ID", value);
}
}
[XmlAttribute("InstrumentCode")]
[Bindable(true)]
public string InstrumentCode
{
get
{
return GetColumnValue<string>("Instrument.Code");
}
set
{
SetColumnValue("Instrument.Code", value);
}
}
[XmlAttribute("InstrumentName")]
[Bindable(true)]
public string InstrumentName
{
get
{
return GetColumnValue<string>("Instrument.Name");
}
set
{
SetColumnValue("Instrument.Name", value);
}
}
[XmlAttribute("SensorID")]
[Bindable(true)]
public Guid SensorID
{
get
{
return GetColumnValue<Guid>("Sensor.ID");
}
set
{
SetColumnValue("Sensor.ID", value);
}
}
[XmlAttribute("SensorCode")]
[Bindable(true)]
public string SensorCode
{
get
{
return GetColumnValue<string>("Sensor.Code");
}
set
{
SetColumnValue("Sensor.Code", value);
}
}
[XmlAttribute("SensorName")]
[Bindable(true)]
public string SensorName
{
get
{
return GetColumnValue<string>("Sensor.Name");
}
set
{
SetColumnValue("Sensor.Name", value);
}
}
[XmlAttribute("PhenomenonID")]
[Bindable(true)]
public Guid PhenomenonID
{
get
{
return GetColumnValue<Guid>("Phenomenon.ID");
}
set
{
SetColumnValue("Phenomenon.ID", value);
}
}
[XmlAttribute("PhenomenonCode")]
[Bindable(true)]
public string PhenomenonCode
{
get
{
return GetColumnValue<string>("Phenomenon.Code");
}
set
{
SetColumnValue("Phenomenon.Code", value);
}
}
[XmlAttribute("PhenomenonName")]
[Bindable(true)]
public string PhenomenonName
{
get
{
return GetColumnValue<string>("Phenomenon.Name");
}
set
{
SetColumnValue("Phenomenon.Name", value);
}
}
[XmlAttribute("OfferingID")]
[Bindable(true)]
public Guid OfferingID
{
get
{
return GetColumnValue<Guid>("Offering.ID");
}
set
{
SetColumnValue("Offering.ID", value);
}
}
[XmlAttribute("OfferingCode")]
[Bindable(true)]
public string OfferingCode
{
get
{
return GetColumnValue<string>("Offering.Code");
}
set
{
SetColumnValue("Offering.Code", value);
}
}
[XmlAttribute("OfferingName")]
[Bindable(true)]
public string OfferingName
{
get
{
return GetColumnValue<string>("Offering.Name");
}
set
{
SetColumnValue("Offering.Name", value);
}
}
[XmlAttribute("UnitID")]
[Bindable(true)]
public Guid UnitID
{
get
{
return GetColumnValue<Guid>("Unit.ID");
}
set
{
SetColumnValue("Unit.ID", value);
}
}
[XmlAttribute("UnitCode")]
[Bindable(true)]
public string UnitCode
{
get
{
return GetColumnValue<string>("Unit.Code");
}
set
{
SetColumnValue("Unit.Code", value);
}
}
[XmlAttribute("UnitName")]
[Bindable(true)]
public string UnitName
{
get
{
return GetColumnValue<string>("Unit.Name");
}
set
{
SetColumnValue("Unit.Name", value);
}
}
[XmlAttribute("UnitSymbol")]
[Bindable(true)]
public string UnitSymbol
{
get
{
return GetColumnValue<string>("Unit.Symbol");
}
set
{
SetColumnValue("Unit.Symbol", value);
}
}
[XmlAttribute("StatusID")]
[Bindable(true)]
public Guid? StatusID
{
get
{
return GetColumnValue<Guid?>("Status.ID");
}
set
{
SetColumnValue("Status.ID", value);
}
}
[XmlAttribute("StatusCode")]
[Bindable(true)]
public string StatusCode
{
get
{
return GetColumnValue<string>("Status.Code");
}
set
{
SetColumnValue("Status.Code", value);
}
}
[XmlAttribute("StatusName")]
[Bindable(true)]
public string StatusName
{
get
{
return GetColumnValue<string>("Status.Name");
}
set
{
SetColumnValue("Status.Name", value);
}
}
[XmlAttribute("StatusReasonID")]
[Bindable(true)]
public Guid? StatusReasonID
{
get
{
return GetColumnValue<Guid?>("StatusReason.ID");
}
set
{
SetColumnValue("StatusReason.ID", value);
}
}
[XmlAttribute("StatusReasonCode")]
[Bindable(true)]
public string StatusReasonCode
{
get
{
return GetColumnValue<string>("StatusReason.Code");
}
set
{
SetColumnValue("StatusReason.Code", value);
}
}
[XmlAttribute("StatusReasonName")]
[Bindable(true)]
public string StatusReasonName
{
get
{
return GetColumnValue<string>("StatusReason.Name");
}
set
{
SetColumnValue("StatusReason.Name", value);
}
}
#endregion
#region Columns Struct
public struct Columns
{
public static string Id = @"ID";
public static string ValueDate = @"ValueDate";
public static string ValueDay = @"ValueDay";
public static string ValueYear = @"ValueYear";
public static string ValueDecade = @"ValueDecade";
public static string TextValue = @"TextValue";
public static string RawValue = @"RawValue";
public static string DataValue = @"DataValue";
public static string Comment = @"Comment";
public static string CorrelationID = @"CorrelationID";
public static string Latitude = @"Latitude";
public static string Longitude = @"Longitude";
public static string Elevation = @"Elevation";
public static string UserId = @"UserId";
public static string AddedDate = @"AddedDate";
public static string AddedAt = @"AddedAt";
public static string UpdatedAt = @"UpdatedAt";
public static string ImportBatchID = @"ImportBatch.ID";
public static string ImportBatchCode = @"ImportBatch.Code";
public static string ImportBatchDate = @"ImportBatch.Date";
public static string SiteID = @"Site.ID";
public static string SiteCode = @"Site.Code";
public static string SiteName = @"Site.Name";
public static string StationID = @"Station.ID";
public static string StationCode = @"Station.Code";
public static string StationName = @"Station.Name";
public static string InstrumentID = @"Instrument.ID";
public static string InstrumentCode = @"Instrument.Code";
public static string InstrumentName = @"Instrument.Name";
public static string SensorID = @"Sensor.ID";
public static string SensorCode = @"Sensor.Code";
public static string SensorName = @"Sensor.Name";
public static string PhenomenonID = @"Phenomenon.ID";
public static string PhenomenonCode = @"Phenomenon.Code";
public static string PhenomenonName = @"Phenomenon.Name";
public static string OfferingID = @"Offering.ID";
public static string OfferingCode = @"Offering.Code";
public static string OfferingName = @"Offering.Name";
public static string UnitID = @"Unit.ID";
public static string UnitCode = @"Unit.Code";
public static string UnitName = @"Unit.Name";
public static string UnitSymbol = @"Unit.Symbol";
public static string StatusID = @"Status.ID";
public static string StatusCode = @"Status.Code";
public static string StatusName = @"Status.Name";
public static string StatusReasonID = @"StatusReason.ID";
public static string StatusReasonCode = @"StatusReason.Code";
public static string StatusReasonName = @"StatusReason.Name";
}
#endregion
#region IAbstractRecord Members
public new CT GetColumnValue<CT>(string columnName) {
return base.GetColumnValue<CT>(columnName);
}
public object GetColumnValue(string columnName) {
return base.GetColumnValue<object>(columnName);
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using Mono.Cecil;
namespace BackwardCompatibilityChecker.Introspection.Query
{
public class FieldQuery : BaseQuery
{
bool? myIsConst;
bool? myIsReadonly;
bool myExcludeCompilerGeneratedFields;
string FieldTypeFilter
{
get;
set;
}
static FieldQuery myAllFields = new FieldQuery();
public static FieldQuery AllFields
{
get { return myAllFields; }
}
static FieldQuery myAllFieldsIncludingCompilerGenerated = new FieldQuery("!nocompilergenerated * *");
public static FieldQuery AllFieldsIncludingCompilerGenerated
{
get { return myAllFieldsIncludingCompilerGenerated; }
}
const string All = " * *";
static FieldQuery myPublicFields = new FieldQuery("public " + All );
public static FieldQuery PublicFields
{
get { return myPublicFields; }
}
static FieldQuery myProtectedFields = new FieldQuery("protected " + All);
public static FieldQuery ProtectedFields
{
get { return myProtectedFields; }
}
static FieldQuery myInternalFields = new FieldQuery("internal " + All);
public static FieldQuery InteralFields
{
get { return myInternalFields; }
}
static FieldQuery myPrivateFields = new FieldQuery("private " + All);
public static FieldQuery PrivateFields
{
get { return myPrivateFields; }
}
/// <summary>
/// Searches for all fields in a class
/// </summary>
public FieldQuery()
: this("* *")
{
}
/// <summary>
/// Queries for specific fields in a class
/// </summary>
/// <param name="query">Query string</param>
/// <remarks>
/// The field query must contain at least the field type and name to query for. Access modifier
/// are optional
/// Example:
/// public * *
/// protectd * *
/// static readonly protected * *
/// string m_*
/// * my* // Get all fields which field name begins with my
/// </remarks>
public FieldQuery(string query):base(query)
{
this.Parser = FieldQueryParser;
var match = this.Parser.Match(query);
if (!match.Success)
{
throw new ArgumentException(
String.Format("The field query string {0} was not a valid query.", query));
}
this.myExcludeCompilerGeneratedFields = true;
this.SetModifierFilter(match);
this.FieldTypeFilter = GenericTypeMapper.ConvertClrTypeNames(this.Value(match, "fieldType"));
if (!this.FieldTypeFilter.StartsWith("*"))
this.FieldTypeFilter = "*" + this.FieldTypeFilter;
if (this.FieldTypeFilter == "*")
this.FieldTypeFilter = null;
this.NameFilter = this.Value(match, "fieldName");
}
protected override void SetModifierFilter(Match match)
{
base.SetModifierFilter(match);
this.myIsReadonly = this.Captures(match, "readonly");
this.myIsConst = this.Captures(match, "const");
bool ?excludeCompilerGenerated = this.Captures(match, "nocompilergenerated");
this.myExcludeCompilerGeneratedFields = excludeCompilerGenerated == null ? true : excludeCompilerGenerated.Value;
}
public List<FieldDefinition> GetMatchingFields(TypeDefinition type)
{
if (type == null)
throw new ArgumentNullException("type");
List<FieldDefinition> retFields = new List<FieldDefinition>();
foreach (FieldDefinition field in type.Fields)
{
if (this.Match(field,type))
{
retFields.Add(field);
}
}
return retFields;
}
internal bool Match(FieldDefinition field, TypeDefinition type)
{
bool lret = true;
lret = this.MatchFieldModifiers(field);
if (lret)
lret = this.MatchFieldType(field);
if (lret)
lret = this.MatchName(field.Name);
if (lret && this.myExcludeCompilerGeneratedFields )
lret = !this.IsEventFieldOrPropertyBackingFieldOrEnumBackingField(field, type);
return lret;
}
private bool IsEventFieldOrPropertyBackingFieldOrEnumBackingField(FieldDefinition field, TypeDefinition def)
{
// Is Property backing field
if (field.Name.EndsWith(">k__BackingField"))
return true;
if (field.IsSpecialName)
return true;
// Is event backing field for event delegate
foreach (EventDefinition ev in def.Events)
{
if (ev.Name == field.Name)
return true;
}
return false;
}
private bool MatchFieldType(FieldDefinition field)
{
if (String.IsNullOrEmpty(this.FieldTypeFilter) || this.FieldTypeFilter == "*")
{
return true;
}
return Matcher.MatchWithWildcards(this.FieldTypeFilter, field.FieldType.FullName, StringComparison.OrdinalIgnoreCase);
}
bool MatchFieldModifiers(FieldDefinition field)
{
bool lret = true;
if (lret && this.myIsConst.HasValue) // Literal fields are always constant so there is no need to make a distinction here
lret = this.myIsConst == field.HasConstant;
if (lret && this.MyIsInternal.HasValue)
lret = this.MyIsInternal == field.IsAssembly;
if (lret && this.MyIsPrivate.HasValue)
lret = this.MyIsPrivate == field.IsPrivate;
if (lret && this.MyIsProtected.HasValue)
lret = this.MyIsProtected == field.IsFamily;
if (lret && this.MyIsProtectedInternal.HasValue)
lret = this.MyIsProtectedInternal == field.IsFamilyOrAssembly;
if (lret && this.MyIsPublic.HasValue)
lret = this.MyIsPublic == field.IsPublic;
if (lret && this.myIsReadonly.HasValue)
lret = this.myIsReadonly == field.IsInitOnly;
if (lret && this.MyIsStatic.HasValue)
lret = this.MyIsStatic == (field.IsStatic && !field.HasConstant);
return lret;
}
}
}
| |
#region Using Directives
using System;
using System.Collections.Generic;
using System.Text;
#endregion Using Directives
namespace ScintillaNET
{
// NOTE: This class will be deprecated and it's members made part of the internal NativeMethods
public class Constants
{
public const int INVALID_POSITION = -1;
public const uint SCI_START = 2000;
public const uint SCI_OPTIONAL_START = 3000;
public const uint SCI_LEXER_START = 4000;
public const uint SCI_ADDTEXT = 2001;
public const uint SCI_ADDSTYLEDTEXT = 2002;
public const uint SCI_INSERTTEXT = 2003;
public const uint SCI_CLEARALL = 2004;
public const uint SCI_CLEARDOCUMENTSTYLE = 2005;
public const uint SCI_GETLENGTH = 2006;
public const uint SCI_GETCHARAT = 2007;
public const uint SCI_GETCURRENTPOS = 2008;
public const uint SCI_GETANCHOR = 2009;
public const uint SCI_GETSTYLEAT = 2010;
public const uint SCI_REDO = 2011;
public const uint SCI_SETUNDOCOLLECTION = 2012;
public const uint SCI_SELECTALL = 2013;
public const uint SCI_SETSAVEPOINT = 2014;
public const uint SCI_GETSTYLEDTEXT = 2015;
public const uint SCI_CANREDO = 2016;
public const uint SCI_MARKERLINEFROMHANDLE = 2017;
public const uint SCI_MARKERDELETEHANDLE = 2018;
public const uint SCI_GETUNDOCOLLECTION = 2019;
public const uint SCWS_INVISIBLE = 0;
public const uint SCWS_VISIBLEALWAYS = 1;
public const uint SCWS_VISIBLEAFTERINDENT = 2;
public const uint SCI_GETVIEWWS = 2020;
public const uint SCI_SETVIEWWS = 2021;
public const uint SCI_POSITIONFROMPOINT = 2022;
public const uint SCI_POSITIONFROMPOINTCLOSE = 2023;
public const uint SCI_GOTOLINE = 2024;
public const uint SCI_GOTOPOS = 2025;
public const uint SCI_SETANCHOR = 2026;
public const uint SCI_GETENDSTYLED = 2028;
public const uint SC_EOL_CRLF = 0;
public const uint SC_EOL_CR = 1;
public const uint SC_EOL_LF = 2;
public const uint SCI_CONVERTEOLS = 2029;
public const uint SCI_GETEOLMODE = 2030;
public const uint SCI_SETEOLMODE = 2031;
public const uint SCI_STARTSTYLING = 2032;
public const uint SCI_SETSTYLING = 2033;
public const uint SCI_GETBUFFEREDDRAW = 2034;
public const uint SCI_SETBUFFEREDDRAW = 2035;
public const uint SCI_SETTABWIDTH = 2036;
public const uint SCI_GETTABWIDTH = 2121;
public const uint SC_CP_UTF8 = 65001;
public const uint SC_CP_DBCS = 1;
public const uint SCI_SETCODEPAGE = 2037;
public const uint SCI_SETUSEPALETTE = 2039;
public const uint MARKER_MAX = 31;
public const uint SC_MARK_CIRCLE = 0;
public const uint SC_MARK_ROUNDRECT = 1;
public const uint SC_MARK_ARROW = 2;
public const uint SC_MARK_SMALLRECT = 3;
public const uint SC_MARK_SHORTARROW = 4;
public const uint SC_MARK_EMPTY = 5;
public const uint SC_MARK_ARROWDOWN = 6;
public const uint SC_MARK_MINUS = 7;
public const uint SC_MARK_PLUS = 8;
public const uint SC_MARK_VLINE = 9;
public const uint SC_MARK_LCORNER = 10;
public const uint SC_MARK_TCORNER = 11;
public const uint SC_MARK_BOXPLUS = 12;
public const uint SC_MARK_BOXPLUSCONNECTED = 13;
public const uint SC_MARK_BOXMINUS = 14;
public const uint SC_MARK_BOXMINUSCONNECTED = 15;
public const uint SC_MARK_LCORNERCURVE = 16;
public const uint SC_MARK_TCORNERCURVE = 17;
public const uint SC_MARK_CIRCLEPLUS = 18;
public const uint SC_MARK_CIRCLEPLUSCONNECTED = 19;
public const uint SC_MARK_CIRCLEMINUS = 20;
public const uint SC_MARK_CIRCLEMINUSCONNECTED = 21;
public const uint SC_MARK_BACKGROUND = 22;
public const uint SC_MARK_DOTDOTDOT = 23;
public const uint SC_MARK_ARROWS = 24;
public const uint SC_MARK_PIXMAP = 25;
public const uint SC_MARK_FULLRECT = 26;
public const uint SC_MARK_CHARACTER = 10000;
public const int SC_MARKNUM_FOLDEREND = 25;
public const int SC_MARKNUM_FOLDEROPENMID = 26;
public const int SC_MARKNUM_FOLDERMIDTAIL = 27;
public const int SC_MARKNUM_FOLDERTAIL = 28;
public const int SC_MARKNUM_FOLDERSUB = 29;
public const int SC_MARKNUM_FOLDER = 30;
public const int SC_MARKNUM_FOLDEROPEN = 31;
public const int SC_MASK_FOLDERS = -33554432;
public const uint SCI_MARKERDEFINE = 2040;
public const uint SCI_MARKERSETFORE = 2041;
public const uint SCI_MARKERSETBACK = 2042;
public const uint SCI_MARKERSETALPHA = 2476;
public const uint SCI_MARKERADD = 2043;
public const uint SCI_MARKERDELETE = 2044;
public const uint SCI_MARKERDELETEALL = 2045;
public const uint SCI_MARKERGET = 2046;
public const uint SCI_MARKERNEXT = 2047;
public const uint SCI_MARKERPREVIOUS = 2048;
public const uint SCI_MARKERDEFINEPIXMAP = 2049;
public const uint SCI_MARKERADDSET = 2466;
public const uint SC_MARGIN_SYMBOL = 0;
public const uint SC_MARGIN_NUMBER = 1;
public const uint SCI_SETMARGINTYPEN = 2240;
public const uint SCI_GETMARGINTYPEN = 2241;
public const uint SCI_SETMARGINWIDTHN = 2242;
public const uint SCI_GETMARGINWIDTHN = 2243;
public const uint SCI_SETMARGINMASKN = 2244;
public const uint SCI_GETMARGINMASKN = 2245;
public const uint SCI_SETMARGINSENSITIVEN = 2246;
public const uint SCI_GETMARGINSENSITIVEN = 2247;
public const int STYLE_DEFAULT = 32;
public const int STYLE_LINENUMBER = 33;
public const int STYLE_BRACELIGHT = 34;
public const int STYLE_BRACEBAD = 35;
public const int STYLE_CONTROLCHAR = 36;
public const int STYLE_INDENTGUIDE = 37;
public const int STYLE_CALLTIP = 38;
public const int STYLE_LASTPREDEFINED = 39;
public const int STYLE_MAX = 127;
public const int SC_CHARSET_ANSI = 0;
public const int SC_CHARSET_DEFAULT = 1;
public const int SC_CHARSET_BALTIC = 186;
public const int SC_CHARSET_CHINESEBIG5 = 136;
public const int SC_CHARSET_EASTEUROPE = 238;
public const int SC_CHARSET_GB2312 = 134;
public const int SC_CHARSET_GREEK = 161;
public const int SC_CHARSET_HANGUL = 129;
public const int SC_CHARSET_MAC = 77;
public const int SC_CHARSET_OEM = 255;
public const int SC_CHARSET_RUSSIAN = 204;
public const int SC_CHARSET_CYRILLIC = 1251;
public const int SC_CHARSET_SHIFTJIS = 128;
public const int SC_CHARSET_SYMBOL = 2;
public const int SC_CHARSET_TURKISH = 162;
public const int SC_CHARSET_JOHAB = 130;
public const int SC_CHARSET_HEBREW = 177;
public const int SC_CHARSET_ARABIC = 178;
public const int SC_CHARSET_VIETNAMESE = 163;
public const int SC_CHARSET_THAI = 222;
public const int SC_CHARSET_8859_15 = 1000;
public const uint SCI_STYLECLEARALL = 2050;
public const uint SCI_STYLESETFORE = 2051;
public const uint SCI_STYLESETBACK = 2052;
public const uint SCI_STYLESETBOLD = 2053;
public const uint SCI_STYLESETITALIC = 2054;
public const uint SCI_STYLESETSIZE = 2055;
public const uint SCI_STYLESETFONT = 2056;
public const uint SCI_STYLESETEOLFILLED = 2057;
public const uint SCI_STYLERESETDEFAULT = 2058;
public const uint SCI_STYLESETUNDERLINE = 2059;
public const uint SC_CASE_MIXED = 0;
public const uint SC_CASE_UPPER = 1;
public const uint SC_CASE_LOWER = 2;
public const uint SCI_STYLESETCASE = 2060;
public const uint SCI_STYLESETCHARACTERSET = 2066;
public const uint SCI_STYLESETHOTSPOT = 2409;
public const uint SCI_SETSELFORE = 2067;
public const uint SCI_SETSELBACK = 2068;
public const uint SCI_SETCARETFORE = 2069;
public const uint SCI_ASSIGNCMDKEY = 2070;
public const uint SCI_CLEARCMDKEY = 2071;
public const uint SCI_CLEARALLCMDKEYS = 2072;
public const uint SCI_SETSTYLINGEX = 2073;
public const uint SCI_STYLESETVISIBLE = 2074;
public const uint SCI_GETCARETPERIOD = 2075;
public const uint SCI_SETCARETPERIOD = 2076;
public const uint SCI_SETWORDCHARS = 2077;
public const uint SCI_BEGINUNDOACTION = 2078;
public const uint SCI_ENDUNDOACTION = 2079;
public const uint INDIC_MAX = 31;
public const uint INDIC_PLAIN = 0;
public const uint INDIC_SQUIGGLE = 1;
public const uint INDIC_TT = 2;
public const uint INDIC_DIAGONAL = 3;
public const uint INDIC_STRIKE = 4;
public const uint INDIC_HIDDEN = 5;
public const uint INDIC_BOX = 6;
public const uint INDIC_ROUNDBOX = 7;
public const int INDIC0_MASK = 0x20;
public const int INDIC1_MASK = 0x40;
public const int INDIC2_MASK = 0x80;
public const int INDICS_MASK = 0xE0;
public const uint SCI_INDICSETSTYLE = 2080;
public const uint SCI_INDICGETSTYLE = 2081;
public const uint SCI_INDICSETFORE = 2082;
public const uint SCI_INDICGETFORE = 2083;
public const uint SCI_SETWHITESPACEFORE = 2084;
public const uint SCI_SETWHITESPACEBACK = 2085;
public const uint SCI_SETSTYLEBITS = 2090;
public const uint SCI_GETSTYLEBITS = 2091;
public const uint SCI_SETLINESTATE = 2092;
public const uint SCI_GETLINESTATE = 2093;
public const uint SCI_GETMAXLINESTATE = 2094;
public const uint SCI_GETCARETLINEVISIBLE = 2095;
public const uint SCI_SETCARETLINEVISIBLE = 2096;
public const uint SCI_GETCARETLINEBACK = 2097;
public const uint SCI_SETCARETLINEBACK = 2098;
public const uint SCI_STYLESETCHANGEABLE = 2099;
public const uint SCI_AUTOCSHOW = 2100;
public const uint SCI_AUTOCCANCEL = 2101;
public const uint SCI_AUTOCACTIVE = 2102;
public const uint SCI_AUTOCPOSSTART = 2103;
public const uint SCI_AUTOCCOMPLETE = 2104;
public const uint SCI_AUTOCSTOPS = 2105;
public const uint SCI_AUTOCSETSEPARATOR = 2106;
public const uint SCI_AUTOCGETSEPARATOR = 2107;
public const uint SCI_AUTOCSELECT = 2108;
public const uint SCI_AUTOCSETCANCELATSTART = 2110;
public const uint SCI_AUTOCGETCANCELATSTART = 2111;
public const uint SCI_AUTOCSETFILLUPS = 2112;
public const uint SCI_AUTOCSETCHOOSESINGLE = 2113;
public const uint SCI_AUTOCGETCHOOSESINGLE = 2114;
public const uint SCI_AUTOCSETIGNORECASE = 2115;
public const uint SCI_AUTOCGETIGNORECASE = 2116;
public const uint SCI_USERLISTSHOW = 2117;
public const uint SCI_AUTOCSETAUTOHIDE = 2118;
public const uint SCI_AUTOCGETAUTOHIDE = 2119;
public const uint SCI_AUTOCSETDROPRESTOFWORD = 2270;
public const uint SCI_AUTOCGETDROPRESTOFWORD = 2271;
public const uint SCI_REGISTERIMAGE = 2405;
public const uint SCI_CLEARREGISTEREDIMAGES = 2408;
public const uint SCI_AUTOCGETTYPESEPARATOR = 2285;
public const uint SCI_AUTOCSETTYPESEPARATOR = 2286;
public const uint SCI_AUTOCSETMAXWIDTH = 2208;
public const uint SCI_AUTOCGETMAXWIDTH = 2209;
public const uint SCI_AUTOCSETMAXHEIGHT = 2210;
public const uint SCI_AUTOCGETMAXHEIGHT = 2211;
public const uint SCI_SETINDENT = 2122;
public const uint SCI_GETINDENT = 2123;
public const uint SCI_SETUSETABS = 2124;
public const uint SCI_GETUSETABS = 2125;
public const uint SCI_SETLINEINDENTATION = 2126;
public const uint SCI_GETLINEINDENTATION = 2127;
public const uint SCI_GETLINEINDENTPOSITION = 2128;
public const uint SCI_GETCOLUMN = 2129;
public const uint SCI_SETHSCROLLBAR = 2130;
public const uint SCI_GETHSCROLLBAR = 2131;
public const uint SCI_SETINDENTATIONGUIDES = 2132;
public const uint SCI_GETINDENTATIONGUIDES = 2133;
public const uint SCI_SETHIGHLIGHTGUIDE = 2134;
public const uint SCI_GETHIGHLIGHTGUIDE = 2135;
public const uint SCI_GETLINEENDPOSITION = 2136;
public const uint SCI_GETCODEPAGE = 2137;
public const uint SCI_GETCARETFORE = 2138;
public const uint SCI_GETUSEPALETTE = 2139;
public const uint SCI_GETREADONLY = 2140;
public const uint SCI_SETCURRENTPOS = 2141;
public const uint SCI_SETSELECTIONSTART = 2142;
public const uint SCI_GETSELECTIONSTART = 2143;
public const uint SCI_SETSELECTIONEND = 2144;
public const uint SCI_GETSELECTIONEND = 2145;
public const uint SCI_SETPRINTMAGNIFICATION = 2146;
public const uint SCI_GETPRINTMAGNIFICATION = 2147;
public const uint SC_PRINT_NORMAL = 0;
public const uint SC_PRINT_INVERTLIGHT = 1;
public const uint SC_PRINT_BLACKONWHITE = 2;
public const uint SC_PRINT_COLOURONWHITE = 3;
public const uint SC_PRINT_COLOURONWHITEDEFAULTBG = 4;
public const uint SCI_SETPRINTCOLOURMODE = 2148;
public const uint SCI_GETPRINTCOLOURMODE = 2149;
public const uint SCFIND_WHOLEWORD = 2;
public const uint SCFIND_MATCHCASE = 4;
public const uint SCFIND_WORDSTART = 0x00100000;
public const uint SCFIND_REGEXP = 0x00200000;
public const uint SCFIND_POSIX = 0x00400000;
public const uint SCI_FINDTEXT = 2150;
public const uint SCI_FORMATRANGE = 2151;
public const uint SCI_GETFIRSTVISIBLELINE = 2152;
public const uint SCI_GETLINE = 2153;
public const uint SCI_SETMARGINLEFT = 2155;
public const uint SCI_GETMARGINLEFT = 2156;
public const uint SCI_SETMARGINRIGHT = 2157;
public const uint SCI_GETMARGINRIGHT = 2158;
public const uint SCI_GETMODIFY = 2159;
public const uint SCI_SETSEL = 2160;
public const uint SCI_GETSELTEXT = 2161;
public const uint SCI_GETTEXTRANGE = 2162;
public const uint SCI_HIDESELECTION = 2163;
public const uint SCI_POINTXFROMPOSITION = 2164;
public const uint SCI_POINTYFROMPOSITION = 2165;
public const uint SCI_LINEFROMPOSITION = 2166;
public const uint SCI_POSITIONFROMLINE = 2167;
public const uint SCI_LINESCROLL = 2168;
public const uint SCI_SCROLLCARET = 2169;
public const uint SCI_REPLACESEL = 2170;
public const uint SCI_SETREADONLY = 2171;
public const uint SCI_NULL = 2172;
public const uint SCI_CANUNDO = 2174;
public const uint SCI_EMPTYUNDOBUFFER = 2175;
public const uint SCI_UNDO = 2176;
public const uint SCI_CLEAR = 2180;
public const uint SCI_SETTEXT = 2181;
public const uint SCI_GETTEXT = 2182;
public const uint SCI_GETTEXTLENGTH = 2183;
public const uint SCI_SETOVERTYPE = 2186;
public const uint SCI_GETOVERTYPE = 2187;
public const uint SCI_SETCARETWIDTH = 2188;
public const uint SCI_GETCARETWIDTH = 2189;
public const uint SCI_SETTARGETSTART = 2190;
public const uint SCI_GETTARGETSTART = 2191;
public const uint SCI_SETTARGETEND = 2192;
public const uint SCI_GETTARGETEND = 2193;
public const uint SCI_REPLACETARGET = 2194;
public const uint SCI_REPLACETARGETRE = 2195;
public const uint SCI_SEARCHINTARGET = 2197;
public const uint SCI_SETSEARCHFLAGS = 2198;
public const uint SCI_GETSEARCHFLAGS = 2199;
public const uint SCI_CALLTIPSHOW = 2200;
public const uint SCI_CALLTIPCANCEL = 2201;
public const uint SCI_CALLTIPACTIVE = 2202;
public const uint SCI_CALLTIPPOSSTART = 2203;
public const uint SCI_CALLTIPSETHLT = 2204;
public const uint SCI_CALLTIPSETBACK = 2205;
public const uint SCI_CALLTIPSETFORE = 2206;
public const uint SCI_CALLTIPSETFOREHLT = 2207;
public const uint SCI_CALLTIPUSESTYLE = 2212;
public const uint SCI_VISIBLEFROMDOCLINE = 2220;
public const uint SCI_DOCLINEFROMVISIBLE = 2221;
public const uint SC_FOLDLEVELBASE = 0x400;
public const uint SC_FOLDLEVELWHITEFLAG = 0x1000;
public const uint SC_FOLDLEVELHEADERFLAG = 0x2000;
public const uint SC_FOLDLEVELBOXHEADERFLAG = 0x4000;
public const uint SC_FOLDLEVELBOXFOOTERFLAG = 0x8000;
public const uint SC_FOLDLEVELCONTRACTED = 0x10000;
public const uint SC_FOLDLEVELUNINDENT = 0x20000;
public const uint SC_FOLDLEVELNUMBERMASK = 0x0FFF;
public const uint SCI_SETFOLDLEVEL = 2222;
public const uint SCI_GETFOLDLEVEL = 2223;
public const uint SCI_GETLASTCHILD = 2224;
public const uint SCI_GETFOLDPARENT = 2225;
public const uint SCI_SHOWLINES = 2226;
public const uint SCI_HIDELINES = 2227;
public const uint SCI_GETLINEVISIBLE = 2228;
public const uint SCI_SETFOLDEXPANDED = 2229;
public const uint SCI_GETFOLDEXPANDED = 2230;
public const uint SCI_TOGGLEFOLD = 2231;
public const uint SCI_ENSUREVISIBLE = 2232;
public const uint SC_FOLDFLAG_LINEBEFORE_EXPANDED = 0x0002;
public const uint SC_FOLDFLAG_LINEBEFORE_CONTRACTED = 0x0004;
public const uint SC_FOLDFLAG_LINEAFTER_EXPANDED = 0x0008;
public const uint SC_FOLDFLAG_LINEAFTER_CONTRACTED = 0x0010;
public const uint SC_FOLDFLAG_LEVELNUMBERS = 0x0040;
public const uint SC_FOLDFLAG_BOX = 0x0001;
public const uint SCI_SETFOLDFLAGS = 2233;
public const uint SCI_ENSUREVISIBLEENFORCEPOLICY = 2234;
public const uint SCI_SETTABINDENTS = 2260;
public const uint SCI_GETTABINDENTS = 2261;
public const uint SCI_SETBACKSPACEUNINDENTS = 2262;
public const uint SCI_GETBACKSPACEUNINDENTS = 2263;
public const uint SC_TIME_FOREVER = 10000000;
public const uint SCI_SETMOUSEDWELLTIME = 2264;
public const uint SCI_GETMOUSEDWELLTIME = 2265;
public const uint SCI_WORDSTARTPOSITION = 2266;
public const uint SCI_WORDENDPOSITION = 2267;
public const uint SCI_SETSCROLLWIDTH = 2274;
public const uint SCI_GETSCROLLWIDTH = 2275;
public const uint SCI_TEXTWIDTH = 2276;
public const uint SCI_SETENDATLASTLINE = 2277;
public const uint SCI_GETENDATLASTLINE = 2278;
public const uint SCI_TEXTHEIGHT = 2279;
public const uint SCI_SETVSCROLLBAR = 2280;
public const uint SCI_GETVSCROLLBAR = 2281;
public const uint SCI_APPENDTEXT = 2282;
public const uint SCI_GETTWOPHASEDRAW = 2283;
public const uint SCI_SETTWOPHASEDRAW = 2284;
public const uint SCI_TARGETFROMSELECTION = 2287;
public const uint SCI_SETFOLDMARGINCOLOUR = 2290;
public const uint SCI_SETFOLDMARGINHICOLOUR = 2291;
public const uint SCI_LINEDOWN = 2300;
public const uint SCI_LINEDOWNEXTEND = 2301;
public const uint SCI_LINEUP = 2302;
public const uint SCI_LINEUPEXTEND = 2303;
public const uint SCI_CHARLEFT = 2304;
public const uint SCI_CHARLEFTEXTEND = 2305;
public const uint SCI_CHARRIGHT = 2306;
public const uint SCI_CHARRIGHTEXTEND = 2307;
public const uint SCI_WORDLEFT = 2308;
public const uint SCI_WORDLEFTEXTEND = 2309;
public const uint SCI_WORDRIGHT = 2310;
public const uint SCI_WORDRIGHTEXTEND = 2311;
public const uint SCI_HOME = 2312;
public const uint SCI_HOMEEXTEND = 2313;
public const uint SCI_LINEEND = 2314;
public const uint SCI_LINEENDEXTEND = 2315;
public const uint SCI_DOCUMENTSTART = 2316;
public const uint SCI_DOCUMENTSTARTEXTEND = 2317;
public const uint SCI_DOCUMENTEND = 2318;
public const uint SCI_DOCUMENTENDEXTEND = 2319;
public const uint SCI_PAGEUP = 2320;
public const uint SCI_PAGEUPEXTEND = 2321;
public const uint SCI_PAGEDOWN = 2322;
public const uint SCI_PAGEDOWNEXTEND = 2323;
public const uint SCI_EDITTOGGLEOVERTYPE = 2324;
public const uint SCI_CANCEL = 2325;
public const uint SCI_DELETEBACK = 2326;
public const uint SCI_TAB = 2327;
public const uint SCI_BACKTAB = 2328;
public const uint SCI_NEWLINE = 2329;
public const uint SCI_FORMFEED = 2330;
public const uint SCI_VCHOME = 2331;
public const uint SCI_VCHOMEEXTEND = 2332;
public const uint SCI_ZOOMIN = 2333;
public const uint SCI_ZOOMOUT = 2334;
public const uint SCI_DELWORDLEFT = 2335;
public const uint SCI_DELWORDRIGHT = 2336;
public const uint SCI_LINECUT = 2337;
public const uint SCI_LINEDELETE = 2338;
public const uint SCI_LINETRANSPOSE = 2339;
public const uint SCI_LINEDUPLICATE = 2404;
public const uint SCI_LOWERCASE = 2340;
public const uint SCI_UPPERCASE = 2341;
public const uint SCI_LINESCROLLDOWN = 2342;
public const uint SCI_LINESCROLLUP = 2343;
public const uint SCI_DELETEBACKNOTLINE = 2344;
public const uint SCI_HOMEDISPLAY = 2345;
public const uint SCI_HOMEDISPLAYEXTEND = 2346;
public const uint SCI_LINEENDDISPLAY = 2347;
public const uint SCI_LINEENDDISPLAYEXTEND = 2348;
public const uint SCI_HOMEWRAP = 2349;
public const uint SCI_HOMEWRAPEXTEND = 2450;
public const uint SCI_LINEENDWRAP = 2451;
public const uint SCI_LINEENDWRAPEXTEND = 2452;
public const uint SCI_VCHOMEWRAP = 2453;
public const uint SCI_VCHOMEWRAPEXTEND = 2454;
public const uint SCI_LINECOPY = 2455;
public const uint SCI_MOVECARETINSIDEVIEW = 2401;
public const uint SCI_LINELENGTH = 2350;
public const uint SCI_BRACEHIGHLIGHT = 2351;
public const uint SCI_BRACEBADLIGHT = 2352;
public const uint SCI_BRACEMATCH = 2353;
public const uint SCI_GETVIEWEOL = 2355;
public const uint SCI_SETVIEWEOL = 2356;
public const uint SCI_GETDOCPOINTER = 2357;
public const uint SCI_SETDOCPOINTER = 2358;
public const uint SCI_SETMODEVENTMASK = 2359;
public const uint EDGE_NONE = 0;
public const uint EDGE_LINE = 1;
public const uint EDGE_BACKGROUND = 2;
public const uint SCI_GETEDGECOLUMN = 2360;
public const uint SCI_SETEDGECOLUMN = 2361;
public const uint SCI_GETEDGEMODE = 2362;
public const uint SCI_SETEDGEMODE = 2363;
public const uint SCI_GETEDGECOLOUR = 2364;
public const uint SCI_SETEDGECOLOUR = 2365;
public const uint SCI_SEARCHANCHOR = 2366;
public const uint SCI_SEARCHNEXT = 2367;
public const uint SCI_SEARCHPREV = 2368;
public const uint SCI_LINESONSCREEN = 2370;
public const uint SCI_USEPOPUP = 2371;
public const uint SCI_SELECTIONISRECTANGLE = 2372;
public const uint SCI_SETZOOM = 2373;
public const uint SCI_GETZOOM = 2374;
public const uint SCI_CREATEDOCUMENT = 2375;
public const uint SCI_ADDREFDOCUMENT = 2376;
public const uint SCI_RELEASEDOCUMENT = 2377;
public const uint SCI_GETMODEVENTMASK = 2378;
public const uint SCI_SETFOCUS = 2380;
public const uint SCI_GETFOCUS = 2381;
public const uint SCI_SETSTATUS = 2382;
public const uint SCI_GETSTATUS = 2383;
public const uint SCI_SETMOUSEDOWNCAPTURES = 2384;
public const uint SCI_GETMOUSEDOWNCAPTURES = 2385;
public const int SC_CURSORNORMAL = -1;
public const int SC_CURSORWAIT = 4;
public const uint SCI_SETCURSOR = 2386;
public const uint SCI_GETCURSOR = 2387;
public const uint SCI_SETCONTROLCHARSYMBOL = 2388;
public const uint SCI_GETCONTROLCHARSYMBOL = 2389;
public const uint SCI_WORDPARTLEFT = 2390;
public const uint SCI_WORDPARTLEFTEXTEND = 2391;
public const uint SCI_WORDPARTRIGHT = 2392;
public const uint SCI_WORDPARTRIGHTEXTEND = 2393;
public const uint VISIBLE_SLOP = 0x01;
public const uint VISIBLE_STRICT = 0x04;
public const uint SCI_SETVISIBLEPOLICY = 2394;
public const uint SCI_DELLINELEFT = 2395;
public const uint SCI_DELLINERIGHT = 2396;
public const uint SCI_SETXOFFSET = 2397;
public const uint SCI_GETXOFFSET = 2398;
public const uint SCI_CHOOSECARETX = 2399;
public const uint SCI_GRABFOCUS = 2400;
public const uint CARET_SLOP = 0x01;
public const uint CARET_STRICT = 0x04;
public const uint CARET_JUMPS = 0x10;
public const uint CARET_EVEN = 0x08;
public const uint SCI_SETXCARETPOLICY = 2402;
public const uint SCI_SETYCARETPOLICY = 2403;
public const uint SCI_SETPRINTWRAPMODE = 2406;
public const uint SCI_GETPRINTWRAPMODE = 2407;
public const uint SCI_SETHOTSPOTACTIVEFORE = 2410;
public const uint SCI_SETHOTSPOTACTIVEBACK = 2411;
public const uint SCI_SETHOTSPOTACTIVEUNDERLINE = 2412;
public const uint SCI_SETHOTSPOTSINGLELINE = 2421;
public const uint SCI_PARADOWN = 2413;
public const uint SCI_PARADOWNEXTEND = 2414;
public const uint SCI_PARAUP = 2415;
public const uint SCI_PARAUPEXTEND = 2416;
public const uint SCI_POSITIONBEFORE = 2417;
public const uint SCI_POSITIONAFTER = 2418;
public const uint SC_SEL_STREAM = 0;
public const uint SC_SEL_RECTANGLE = 1;
public const uint SC_SEL_LINES = 2;
public const uint SCI_SETSELECTIONMODE = 2422;
public const uint SCI_GETSELECTIONMODE = 2423;
public const uint SCI_GETLINESELSTARTPOSITION = 2424;
public const uint SCI_GETLINESELENDPOSITION = 2425;
public const uint SCI_LINEDOWNRECTEXTEND = 2426;
public const uint SCI_LINEUPRECTEXTEND = 2427;
public const uint SCI_CHARLEFTRECTEXTEND = 2428;
public const uint SCI_CHARRIGHTRECTEXTEND = 2429;
public const uint SCI_HOMERECTEXTEND = 2430;
public const uint SCI_VCHOMERECTEXTEND = 2431;
public const uint SCI_LINEENDRECTEXTEND = 2432;
public const uint SCI_PAGEUPRECTEXTEND = 2433;
public const uint SCI_PAGEDOWNRECTEXTEND = 2434;
public const uint SCI_STUTTEREDPAGEUP = 2435;
public const uint SCI_STUTTEREDPAGEUPEXTEND = 2436;
public const uint SCI_STUTTEREDPAGEDOWN = 2437;
public const uint SCI_STUTTEREDPAGEDOWNEXTEND = 2438;
public const uint SCI_WORDLEFTEND = 2439;
public const uint SCI_WORDLEFTENDEXTEND = 2440;
public const uint SCI_WORDRIGHTEND = 2441;
public const uint SCI_WORDRIGHTENDEXTEND = 2442;
public const uint SCI_SETWHITESPACECHARS = 2443;
public const uint SCI_SETCHARSDEFAULT = 2444;
public const uint SCI_AUTOCGETCURRENT = 2445;
public const uint SCI_ALLOCATE = 2446;
public const uint SCI_TARGETASUTF8 = 2447;
public const uint SCI_SETLENGTHFORENCODE = 2448;
public const uint SCI_ENCODEDFROMUTF8 = 2449;
public const uint SCI_FINDCOLUMN = 2456;
public const uint SCI_GETCARETSTICKY = 2457;
public const uint SCI_SETCARETSTICKY = 2458;
public const uint SCI_TOGGLECARETSTICKY = 2459;
public const uint SCI_SELECTIONDUPLICATE = 2469;
public const uint SC_ALPHA_TRANSPARENT = 0;
public const uint SC_ALPHA_OPAQUE = 255;
public const uint SC_ALPHA_NOALPHA = 256;
public const uint SCI_SETCARETLINEBACKALPHA = 2470;
public const uint SCI_GETCARETLINEBACKALPHA = 2471;
public const uint SCI_STARTRECORD = 3001;
public const uint SCI_STOPRECORD = 3002;
public const uint SCI_SETLEXER = 4001;
public const uint SCI_GETLEXER = 4002;
public const uint SCI_COLOURISE = 4003;
public const uint SCI_SETPROPERTY = 4004;
public const uint KEYWORDSET_MAX = 8;
public const uint SCI_SETKEYWORDS = 4005;
public const uint SCI_SETLEXERLANGUAGE = 4006;
public const uint SCI_LOADLEXERLIBRARY = 4007;
public const uint SCI_GETPROPERTY = 4008;
public const uint SCI_GETPROPERTYEXPANDED = 4009;
public const uint SCI_GETPROPERTYINT = 4010;
public const uint SCI_GETSTYLEBITSNEEDED = 4011;
public const uint SC_MOD_INSERTTEXT = 0x1;
public const uint SC_MOD_DELETETEXT = 0x2;
public const uint SC_MOD_CHANGESTYLE = 0x4;
public const uint SC_MOD_CHANGEFOLD = 0x8;
public const uint SC_PERFORMED_USER = 0x10;
public const uint SC_PERFORMED_UNDO = 0x20;
public const uint SC_PERFORMED_REDO = 0x40;
public const uint SC_MULTISTEPUNDOREDO = 0x80;
public const uint SC_LASTSTEPINUNDOREDO = 0x100;
public const uint SC_MOD_CHANGEMARKER = 0x200;
public const uint SC_MOD_BEFOREINSERT = 0x400;
public const uint SC_MOD_BEFOREDELETE = 0x800;
public const uint SC_MULTILINEUNDOREDO = 0x1000;
public const int SC_MODEVENTMASKALL = 0x6FFF;
public const uint SCEN_SETFOCUS = 512;
public const uint SCEN_KILLFOCUS = 256;
public const uint SCK_DOWN = 300;
public const uint SCK_UP = 301;
public const uint SCK_LEFT = 302;
public const uint SCK_RIGHT = 303;
public const uint SCK_HOME = 304;
public const uint SCK_END = 305;
public const uint SCK_PRIOR = 306;
public const uint SCK_NEXT = 307;
public const uint SCK_DELETE = 308;
public const uint SCK_INSERT = 309;
public const uint SCK_ESCAPE = 7;
public const uint SCK_BACK = 8;
public const uint SCK_TAB = 9;
public const uint SCK_RETURN = 13;
public const uint SCK_ADD = 310;
public const uint SCK_SUBTRACT = 311;
public const uint SCK_DIVIDE = 312;
public const uint SCMOD_NORM = 0;
public const uint SCMOD_SHIFT = 1;
public const uint SCMOD_CTRL = 2;
public const uint SCMOD_ALT = 4;
public const uint SCN_STYLENEEDED = 2000;
public const uint SCN_CHARADDED = 2001;
public const uint SCN_SAVEPOINTREACHED = 2002;
public const uint SCN_SAVEPOINTLEFT = 2003;
public const uint SCN_MODIFYATTEMPTRO = 2004;
public const uint SCN_KEY = 2005;
public const uint SCN_DOUBLECLICK = 2006;
public const uint SCN_UPDATEUI = 2007;
public const uint SCN_MODIFIED = 2008;
public const uint SCN_MACRORECORD = 2009;
public const uint SCN_MARGINCLICK = 2010;
public const uint SCN_NEEDSHOWN = 2011;
public const uint SCN_PAINTED = 2013;
public const uint SCN_USERLISTSELECTION = 2014;
public const uint SCN_URIDROPPED = 2015;
public const uint SCN_DWELLSTART = 2016;
public const uint SCN_DWELLEND = 2017;
public const uint SCN_ZOOM = 2018;
public const uint SCN_CALLTIPCLICK = 2021;
public const uint SCN_AUTOCSELECTION = 2022;
public const uint SCI_STYLEGETFORE = 2481;
public const uint SCI_STYLEGETBACK = 2482;
public const uint SCI_STYLEGETBOLD = 2483;
public const uint SCI_STYLEGETITALIC = 2484;
public const uint SCI_STYLEGETSIZE = 2485;
public const uint SCI_STYLEGETFONT = 2486;
public const uint SCI_STYLEGETEOLFILLED = 2487;
public const uint SCI_STYLEGETUNDERLINE = 2488;
public const uint SCI_STYLEGETCASE = 2489;
public const uint SCI_STYLEGETCHARACTERSET = 2490;
public const uint SCI_STYLEGETVISIBLE = 2491;
public const uint SCI_STYLEGETCHANGEABLE = 2492;
public const uint SCI_STYLEGETHOTSPOT = 2493;
public const uint INDIC_CONTAINER = 8;
public const uint SCI_INDICSETUNDER = 2510;
public const uint SCI_INDICGETUNDER = 2511;
public const uint SCI_GETHOTSPOTACTIVEFORE = 2494;
public const uint SCI_GETHOTSPOTACTIVEBACK = 2495;
public const uint SCI_GETHOTSPOTACTIVEUNDERLINE = 2496;
public const uint SCI_GETHOTSPOTSINGLELINE = 2497;
public const uint CARETSTYLE_INVISIBLE = 0;
public const uint CARETSTYLE_LINE = 1;
public const uint CARETSTYLE_BLOCK = 2;
public const uint SCI_SETCARETSTYLE = 2512;
public const uint SCI_GETCARETSTYLE = 2513;
public const uint SCI_SETINDICATORCURRENT = 2500;
public const uint SCI_GETINDICATORCURRENT = 2501;
public const uint SCI_SETINDICATORVALUE = 2502;
public const uint SCI_GETINDICATORVALUE = 2503;
public const uint SCI_INDICATORFILLRANGE = 2504;
public const uint SCI_INDICATORCLEARRANGE = 2505;
public const uint SCI_INDICATORALLONFOR = 2506;
public const uint SCI_INDICATORVALUEAT = 2507;
public const uint SCI_INDICATORSTART = 2508;
public const uint SCI_INDICATOREND = 2509;
public const uint SC_MOD_CHANGEINDICATOR = 0x4000;
public const uint SCN_INDICATORCLICK = 2023;
public const uint SCN_INDICATORRELEASE = 2024;
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Configuration.Provider;
using System.Linq;
using System.Web.Hosting;
using Alienlab.Web.Security.Resources;
using Alienlab.Web.Security.Store;
namespace Alienlab.Web.Security {
/// <summary>
/// Custom XML implementation of <c>System.Web.Security.RoleProvider</c>
/// </summary>
public class XmlRoleProvider : RoleProviderBase, IDisposable {
#region Fields ///////////////////////////////////////////////////////////////////////////
string _file;
private XmlRoleStore _store;
#endregion
#region Properties ///////////////////////////////////////////////////////////////////////
/// <summary>
/// Gets the roles.
/// </summary>
/// <value>The roles.</value>
protected List<XmlRole> Roles { get { return this.Store.Roles; } }
/// <summary>
/// Gets the role store.
/// </summary>
/// <value>The role store.</value>
protected XmlRoleStore Store {
get {
return _store ?? (_store = new XmlRoleStore(_file));
}
}
#endregion
#region Construct / Destruct //////////////////////////////////////////////////////////////
/// <summary>
/// Initializes a new instance of the <see cref="XmlRoleProvider"/> class.
/// </summary>
public XmlRoleProvider() {
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
public void Dispose() {
Store.Dispose();
}
#endregion
#region Methods ///////////////////////////////////////////////////////////////////////////
/// <summary>
/// Adds the specified user names to the specified roles for the configured applicationName.
/// </summary>
/// <param name="usernames">A string array of user names to be added to the specified roles.</param>
/// <param name="roleNames">A string array of the role names to add the specified user names to.</param>
public override void AddUsersToRoles(string[] usernames, string[] roleNames) {
if (usernames == null)
throw new ArgumentNullException("usernames");
if (roleNames == null)
throw new ArgumentNullException("roleNames");
var comparer = this.Comparer;
lock (SyncRoot) {
foreach (string rolename in roleNames) {
XmlRole role = this.GetRole(rolename);
if (role != null) {
foreach (string username in usernames) {
if (!role.Users.Contains(username, comparer))
role.Users.Add(username);
}
}
}
this.Store.Save();
}
}
/// <summary>
/// Adds a new role to the data source for the configured applicationName.
/// </summary>
/// <param name="roleName">The name of the role to create.</param>
public override void CreateRole(string roleName) {
if (roleName == null)
throw new ArgumentNullException("roleName");
if (roleName.IndexOf(',') > 0)
throw new ArgumentException(Messages.RoleCannotContainCommas);
XmlRole role = this.GetRole(roleName);
if (role == null) {
role = new XmlRole {
Name = roleName,
Users = new List<string>()
};
lock (SyncRoot) {
this.Store.Roles.Add(role);
this.Store.Save();
}
}
else
throw new ProviderException(Messages.RoleExists.F(roleName));
}
/// <summary>
/// Removes a role from the data source for the configured applicationName.
/// </summary>
/// <param name="roleName">The name of the role to delete.</param>
/// <param name="throwOnPopulatedRole">If true, throw an exception if roleName has one or more members and do not delete roleName.</param>
/// <returns>
/// true if the role was successfully deleted; otherwise, false.
/// </returns>
public override bool DeleteRole(string roleName, bool throwOnPopulatedRole) {
if (roleName == null)
throw new ArgumentNullException("roleName");
lock (SyncRoot) {
XmlRole role = this.GetRole(roleName);
if (role != null) {
if (throwOnPopulatedRole && (role.Users.Count > 0))
throw new ProviderException(Messages.CannotDeletePopulatedRole);
this.Store.Roles.Remove(role);
this.Store.Save();
return true;
}
return false;
}
}
/// <summary>
/// Gets an array of user names in a role where the user name contains the specified user name to match.
/// </summary>
/// <param name="roleName">The role to search in.</param>
/// <param name="usernameToMatch">The user name to search for.</param>
/// <returns>
/// A string array containing the names of all the users where the user name matches usernameToMatch and the user is a member of the specified role.
/// </returns>
public override string[] FindUsersInRole(string roleName, string usernameToMatch) {
if (roleName == null)
throw new ArgumentNullException("roleName");
if (usernameToMatch == null)
throw new ArgumentNullException("usernameToMatch");
var comparison = this.Comparison;
var query = from role in this.Roles.AsQueryable()
from user in role.Users
where (user.IndexOf(usernameToMatch, comparison) >= 0)
&& role.Name.Equals(roleName, comparison)
select user;
lock (SyncRoot) {
return query.ToArray();
}
}
/// <summary>
/// Gets a list of all the roles for the configured applicationName.
/// </summary>
/// <returns>
/// A string array containing the names of all the roles stored in the data source for the configured applicationName.
/// </returns>
public override string[] GetAllRoles() {
var query = from r in this.Roles
select r.Name;
lock (SyncRoot) {
return query.ToArray();
}
}
/// <summary>
/// Gets the role.
/// </summary>
/// <param name="roleName">The name.</param>
/// <returns></returns>
public XmlRole GetRole(string roleName) {
if (roleName == null)
throw new ArgumentNullException("roleName");
var query = from r in this.Roles
where r.Name.Equals(roleName, this.Comparison)
select r;
lock (SyncRoot) {
return query.FirstOrDefault();
}
}
/// <summary>
/// Gets a list of the roles that a specified user is in for the configured applicationName.
/// </summary>
/// <param name="username">The user to return a list of roles for.</param>
/// <returns>
/// A string array containing the names of all the roles that the specified user is in for the configured applicationName.
/// </returns>
public override string[] GetRolesForUser(string username) {
if (username == null)
throw new ArgumentNullException("username");
var query = from r in this.Roles
where r.Users.Contains(username, this.Comparer)
select r.Name;
lock (SyncRoot) {
return query.ToArray();
}
}
/// <summary>
/// Gets a list of users in the specified role for the configured applicationName.
/// </summary>
/// <param name="roleName">The name of the role to get the list of users for.</param>
/// <returns>
/// A string array containing the names of all the users who are members of the specified role for the configured applicationName.
/// </returns>
public override string[] GetUsersInRole(string roleName) {
XmlRole role = this.GetRole(roleName);
if (role != null) {
lock (SyncRoot) {
return role.Users.ToArray();
}
}
throw new ProviderException(Messages.RoleNotExists.F(roleName));
}
/// <summary>
/// Gets a value indicating whether the specified user is in the specified role for the configured applicationName.
/// </summary>
/// <param name="username">The user name to search for.</param>
/// <param name="roleName">The role to search in.</param>
/// <returns>
/// true if the specified user is in the specified role for the configured applicationName; otherwise, false.
/// </returns>
public override bool IsUserInRole(string username, string roleName) {
if (username == null)
throw new ArgumentNullException("username");
XmlRole role = this.GetRole(roleName);
if (role != null) {
lock (SyncRoot) {
return role.Users.Contains(username, this.Comparer);
}
}
else
throw new ProviderException(Messages.RoleNotExists.F(roleName));
}
/// <summary>
/// Removes the specified user names from the specified roles for the configured applicationName.
/// </summary>
/// <param name="usernames">A string array of user names to be removed from the specified roles.</param>
/// <param name="roleNames">A string array of role names to remove the specified user names from.</param>
public override void RemoveUsersFromRoles(string[] usernames, string[] roleNames) {
if (usernames == null)
throw new ArgumentNullException("usernames");
if (roleNames == null)
throw new ArgumentNullException("roleNames");
var comparer = this.Comparer;
var query = from r in this.Roles
where roleNames.Contains(r.Name, comparer)
select r;
lock (SyncRoot) {
foreach (XmlRole role in query) {
foreach (string username in usernames) {
role.Users.Remove(username);
}
}
this.Store.Save();
}
}
/// <summary>
/// Gets a value indicating whether the specified role name already exists in the role data source for the configured applicationName.
/// </summary>
/// <param name="roleName">The name of the role to search for in the data source.</param>
/// <returns>
/// true if the role name already exists in the data source for the configured applicationName; otherwise, false.
/// </returns>
public override bool RoleExists(string roleName) {
return this.GetRole(roleName) != null;
}
#region - Initialize -
/// <summary>
/// Initializes the provider.
/// </summary>
/// <param name="name">The friendly name of the provider.</param>
/// <param name="config">A collection of the name/value pairs representing the provider-specific attributes specified in the configuration for this provider.</param>
/// <exception cref="T:System.ArgumentNullException">The name of the provider is null.</exception>
/// <exception cref="T:System.InvalidOperationException">An attempt is made to call <see cref="M:System.Configuration.Provider.ProviderBase.Initialize(System.String,System.Collections.Specialized.NameValueCollection)"></see> on a provider after the provider has already been initialized.</exception>
/// <exception cref="T:System.ArgumentException">The name of the provider has a length of zero.</exception>
public override void Initialize(string name, NameValueCollection config) {
if (config == null)
throw new ArgumentNullException("config");
// prerequisite
if (string.IsNullOrWhiteSpace(name)) {
name = "XmlRoleProvider";
}
if (string.IsNullOrEmpty(config["description"])) {
config.Remove("description");
config.Add("description", "XML Role Provider");
}
// initialize the base class
base.Initialize(name, config);
// initialize provider fields
string fileName = config.GetString("fileName", "Roles.xml");
string folder = config.GetString("folder", "~/App_Data/");
if (!folder.EndsWith("/")) folder += "/";
_file = HostingEnvironment.MapPath(string.Format("{0}{1}", folder, fileName));
}
#endregion
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Text;
using System.Xml;
using System.Xml.XPath;
using Umbraco.Core.Logging;
using Umbraco.Core;
using Umbraco.Core.Models;
using Umbraco.Core.Xml;
using Umbraco.Web.Routing;
using umbraco;
using System.Linq;
using umbraco.BusinessLogic;
using umbraco.presentation.preview;
namespace Umbraco.Web.PublishedCache.XmlPublishedCache
{
internal class PublishedContentCache : IPublishedContentCache
{
#region Routes cache
private readonly RoutesCache _routesCache = new RoutesCache(!UnitTesting);
// for INTERNAL, UNIT TESTS use ONLY
internal RoutesCache RoutesCache { get { return _routesCache; } }
// for INTERNAL, UNIT TESTS use ONLY
internal static bool UnitTesting = false;
public virtual IPublishedContent GetByRoute(UmbracoContext umbracoContext, bool preview, string route, bool? hideTopLevelNode = null)
{
if (route == null) throw new ArgumentNullException("route");
// try to get from cache if not previewing
var contentId = preview ? 0 : _routesCache.GetNodeId(route);
// if found id in cache then get corresponding content
// and clear cache if not found - for whatever reason
IPublishedContent content = null;
if (contentId > 0)
{
content = GetById(umbracoContext, preview, contentId);
if (content == null)
_routesCache.ClearNode(contentId);
}
// still have nothing? actually determine the id
hideTopLevelNode = hideTopLevelNode ?? GlobalSettings.HideTopLevelNodeFromPath; // default = settings
content = content ?? DetermineIdByRoute(umbracoContext, preview, route, hideTopLevelNode.Value);
// cache if we have a content and not previewing
if (content != null && !preview)
{
var domainRootNodeId = route.StartsWith("/") ? -1 : int.Parse(route.Substring(0, route.IndexOf('/')));
var iscanon = !UnitTesting && !DomainHelper.ExistsDomainInPath(DomainHelper.GetAllDomains(false), content.Path, domainRootNodeId);
// and only if this is the canonical url (the one GetUrl would return)
if (iscanon)
_routesCache.Store(contentId, route);
}
return content;
}
public virtual string GetRouteById(UmbracoContext umbracoContext, bool preview, int contentId)
{
// try to get from cache if not previewing
var route = preview ? null : _routesCache.GetRoute(contentId);
// if found in cache then return
if (route != null)
return route;
// else actually determine the route
route = DetermineRouteById(umbracoContext, preview, contentId);
// cache if we have a route and not previewing
if (route != null && !preview)
_routesCache.Store(contentId, route);
return route;
}
IPublishedContent DetermineIdByRoute(UmbracoContext umbracoContext, bool preview, string route, bool hideTopLevelNode)
{
if (route == null) throw new ArgumentNullException("route");
//the route always needs to be lower case because we only store the urlName attribute in lower case
route = route.ToLowerInvariant();
var pos = route.IndexOf('/');
var path = pos == 0 ? route : route.Substring(pos);
var startNodeId = pos == 0 ? 0 : int.Parse(route.Substring(0, pos));
IEnumerable<XPathVariable> vars;
var xpath = CreateXpathQuery(startNodeId, path, hideTopLevelNode, out vars);
//check if we can find the node in our xml cache
var content = GetSingleByXPath(umbracoContext, preview, xpath, vars == null ? null : vars.ToArray());
// if hideTopLevelNodePath is true then for url /foo we looked for /*/foo
// but maybe that was the url of a non-default top-level node, so we also
// have to look for /foo (see note in ApplyHideTopLevelNodeFromPath).
if (content == null && hideTopLevelNode && path.Length > 1 && path.IndexOf('/', 1) < 0)
{
xpath = CreateXpathQuery(startNodeId, path, false, out vars);
content = GetSingleByXPath(umbracoContext, preview, xpath, vars == null ? null : vars.ToArray());
}
return content;
}
string DetermineRouteById(UmbracoContext umbracoContext, bool preview, int contentId)
{
var node = GetById(umbracoContext, preview, contentId);
if (node == null)
return null;
// walk up from that node until we hit a node with a domain,
// or we reach the content root, collecting urls in the way
var pathParts = new List<string>();
var n = node;
var hasDomains = DomainHelper.NodeHasDomains(n.Id);
while (!hasDomains && n != null) // n is null at root
{
// get the url
var urlName = n.UrlName;
pathParts.Add(urlName);
// move to parent node
n = n.Parent;
hasDomains = n != null && DomainHelper.NodeHasDomains(n.Id);
}
// no domain, respect HideTopLevelNodeFromPath for legacy purposes
if (!hasDomains && global::umbraco.GlobalSettings.HideTopLevelNodeFromPath)
ApplyHideTopLevelNodeFromPath(umbracoContext, node, pathParts);
// assemble the route
pathParts.Reverse();
var path = "/" + string.Join("/", pathParts); // will be "/" or "/foo" or "/foo/bar" etc
var route = (n == null ? "" : n.Id.ToString(CultureInfo.InvariantCulture)) + path;
return route;
}
static void ApplyHideTopLevelNodeFromPath(UmbracoContext umbracoContext, IPublishedContent node, IList<string> pathParts)
{
// in theory if hideTopLevelNodeFromPath is true, then there should be only once
// top-level node, or else domains should be assigned. but for backward compatibility
// we add this check - we look for the document matching "/" and if it's not us, then
// we do not hide the top level path
// it has to be taken care of in GetByRoute too so if
// "/foo" fails (looking for "/*/foo") we try also "/foo".
// this does not make much sense anyway esp. if both "/foo/" and "/bar/foo" exist, but
// that's the way it works pre-4.10 and we try to be backward compat for the time being
if (node.Parent == null)
{
var rootNode = umbracoContext.ContentCache.GetByRoute("/", true);
if (rootNode == null)
throw new Exception("Failed to get node at /.");
if (rootNode.Id == node.Id) // remove only if we're the default node
pathParts.RemoveAt(pathParts.Count - 1);
}
else
{
pathParts.RemoveAt(pathParts.Count - 1);
}
}
#endregion
#region XPath Strings
class XPathStringsDefinition
{
public int Version { get; private set; }
public static string Root { get { return "/root"; } }
public string RootDocuments { get; private set; }
public string DescendantDocumentById { get; private set; }
public string ChildDocumentByUrlName { get; private set; }
public string ChildDocumentByUrlNameVar { get; private set; }
public string RootDocumentWithLowestSortOrder { get; private set; }
public XPathStringsDefinition(int version)
{
Version = version;
switch (version)
{
// legacy XML schema
case 0:
RootDocuments = "/root/node";
DescendantDocumentById = "//node [@id={0}]";
ChildDocumentByUrlName = "/node [@urlName='{0}']";
ChildDocumentByUrlNameVar = "/node [@urlName=${0}]";
RootDocumentWithLowestSortOrder = "/root/node [not(@sortOrder > ../node/@sortOrder)][1]";
break;
// default XML schema as of 4.10
case 1:
RootDocuments = "/root/* [@isDoc]";
DescendantDocumentById = "//* [@isDoc and @id={0}]";
ChildDocumentByUrlName = "/* [@isDoc and @urlName='{0}']";
ChildDocumentByUrlNameVar = "/* [@isDoc and @urlName=${0}]";
RootDocumentWithLowestSortOrder = "/root/* [@isDoc and not(@sortOrder > ../* [@isDoc]/@sortOrder)][1]";
break;
default:
throw new Exception(string.Format("Unsupported Xml schema version '{0}').", version));
}
}
}
static XPathStringsDefinition _xPathStringsValue;
static XPathStringsDefinition XPathStrings
{
get
{
// in theory XPathStrings should be a static variable that
// we should initialize in a static ctor - but then test cases
// that switch schemas fail - so cache and refresh when needed,
// ie never when running the actual site
var version = UmbracoSettings.UseLegacyXmlSchema ? 0 : 1;
if (_xPathStringsValue == null || _xPathStringsValue.Version != version)
_xPathStringsValue = new XPathStringsDefinition(version);
return _xPathStringsValue;
}
}
#endregion
#region Converters
private static IPublishedContent ConvertToDocument(XmlNode xmlNode)
{
return xmlNode == null ? null : new Models.XmlPublishedContent(xmlNode);
}
private static IEnumerable<IPublishedContent> ConvertToDocuments(XmlNodeList xmlNodes)
{
return xmlNodes.Cast<XmlNode>().Select(xmlNode => new Models.XmlPublishedContent(xmlNode));
}
#endregion
#region Getters
public virtual IPublishedContent GetById(UmbracoContext umbracoContext, bool preview, int nodeId)
{
return ConvertToDocument(GetXml(umbracoContext, preview).GetElementById(nodeId.ToString(CultureInfo.InvariantCulture)));
}
public virtual IEnumerable<IPublishedContent> GetAtRoot(UmbracoContext umbracoContext, bool preview)
{
return ConvertToDocuments(GetXml(umbracoContext, preview).SelectNodes(XPathStrings.RootDocuments));
}
public virtual IPublishedContent GetSingleByXPath(UmbracoContext umbracoContext, bool preview, string xpath, params XPathVariable[] vars)
{
if (xpath == null) throw new ArgumentNullException("xpath");
if (string.IsNullOrWhiteSpace(xpath)) return null;
var xml = GetXml(umbracoContext, preview);
var node = vars == null
? xml.SelectSingleNode(xpath)
: xml.SelectSingleNode(xpath, vars);
return ConvertToDocument(node);
}
public virtual IPublishedContent GetSingleByXPath(UmbracoContext umbracoContext, bool preview, XPathExpression xpath, params XPathVariable[] vars)
{
if (xpath == null) throw new ArgumentNullException("xpath");
var xml = GetXml(umbracoContext, preview);
var node = vars == null
? xml.SelectSingleNode(xpath)
: xml.SelectSingleNode(xpath, vars);
return ConvertToDocument(node);
}
public virtual IEnumerable<IPublishedContent> GetByXPath(UmbracoContext umbracoContext, bool preview, string xpath, params XPathVariable[] vars)
{
if (xpath == null) throw new ArgumentNullException("xpath");
if (string.IsNullOrWhiteSpace(xpath)) return Enumerable.Empty<IPublishedContent>();
var xml = GetXml(umbracoContext, preview);
var nodes = vars == null
? xml.SelectNodes(xpath)
: xml.SelectNodes(xpath, vars);
return ConvertToDocuments(nodes);
}
public virtual IEnumerable<IPublishedContent> GetByXPath(UmbracoContext umbracoContext, bool preview, XPathExpression xpath, params XPathVariable[] vars)
{
if (xpath == null) throw new ArgumentNullException("xpath");
var xml = GetXml(umbracoContext, preview);
var nodes = vars == null
? xml.SelectNodes(xpath)
: xml.SelectNodes(xpath, vars);
return ConvertToDocuments(nodes);
}
public virtual bool HasContent(UmbracoContext umbracoContext, bool preview)
{
var xml = GetXml(umbracoContext, preview);
if (xml == null)
return false;
var node = xml.SelectSingleNode(XPathStrings.RootDocuments);
return node != null;
}
public virtual XPathNavigator GetXPathNavigator(UmbracoContext umbracoContext, bool preview)
{
var xml = GetXml(umbracoContext, preview);
return xml.CreateNavigator();
}
#endregion
#region Legacy Xml
static readonly ConditionalWeakTable<UmbracoContext, PreviewContent> PreviewContentCache
= new ConditionalWeakTable<UmbracoContext, PreviewContent>();
private Func<UmbracoContext, bool, XmlDocument> _xmlDelegate;
/// <summary>
/// Gets/sets the delegate used to retreive the Xml content, generally the setter is only used for unit tests
/// and by default if it is not set will use the standard delegate which ONLY works when in the context an Http Request
/// </summary>
/// <remarks>
/// If not defined, we will use the standard delegate which ONLY works when in the context an Http Request
/// mostly because the 'content' object heavily relies on HttpContext, SQL connections and a bunch of other stuff
/// that when run inside of a unit test fails.
/// </remarks>
internal Func<UmbracoContext, bool, XmlDocument> GetXmlDelegate
{
get
{
return _xmlDelegate ?? (_xmlDelegate = (context, preview) =>
{
if (preview)
{
var previewContent = PreviewContentCache.GetOrCreateValue(context); // will use the ctor with no parameters
previewContent.EnsureInitialized(context.UmbracoUser, StateHelper.Cookies.Preview.GetValue(), true, () =>
{
if (previewContent.ValidPreviewSet)
previewContent.LoadPreviewset();
});
if (previewContent.ValidPreviewSet)
return previewContent.XmlContent;
}
return content.Instance.XmlContent;
});
}
set
{
_xmlDelegate = value;
}
}
internal XmlDocument GetXml(UmbracoContext umbracoContext, bool preview)
{
return GetXmlDelegate(umbracoContext, preview);
}
#endregion
#region XPathQuery
static readonly char[] SlashChar = new[] { '/' };
protected string CreateXpathQuery(int startNodeId, string path, bool hideTopLevelNodeFromPath, out IEnumerable<XPathVariable> vars)
{
string xpath;
vars = null;
if (path == string.Empty || path == "/")
{
// if url is empty
if (startNodeId > 0)
{
// if in a domain then use the root node of the domain
xpath = string.Format(XPathStringsDefinition.Root + XPathStrings.DescendantDocumentById, startNodeId);
}
else
{
// if not in a domain - what is the default page?
// let's say it is the first one in the tree, if any -- order by sortOrder
// but!
// umbraco does not consistently guarantee that sortOrder starts with 0
// so the one that we want is the one with the smallest sortOrder
// read http://stackoverflow.com/questions/1128745/how-can-i-use-xpath-to-find-the-minimum-value-of-an-attribute-in-a-set-of-elemen
// so that one does not work, because min(@sortOrder) maybe 1
// xpath = "/root/*[@isDoc and @sortOrder='0']";
// and we can't use min() because that's XPath 2.0
// that one works
xpath = XPathStrings.RootDocumentWithLowestSortOrder;
}
}
else
{
// if url is not empty, then use it to try lookup a matching page
var urlParts = path.Split(SlashChar, StringSplitOptions.RemoveEmptyEntries);
var xpathBuilder = new StringBuilder();
int partsIndex = 0;
List<XPathVariable> varsList = null;
if (startNodeId == 0)
{
if (hideTopLevelNodeFromPath)
xpathBuilder.Append(XPathStrings.RootDocuments); // first node is not in the url
else
xpathBuilder.Append(XPathStringsDefinition.Root);
}
else
{
xpathBuilder.AppendFormat(XPathStringsDefinition.Root + XPathStrings.DescendantDocumentById, startNodeId);
// always "hide top level" when there's a domain
}
while (partsIndex < urlParts.Length)
{
var part = urlParts[partsIndex++];
if (part.Contains('\'') || part.Contains('"'))
{
// use vars, escaping gets ugly pretty quickly
varsList = varsList ?? new List<XPathVariable>();
var varName = string.Format("var{0}", partsIndex);
varsList.Add(new XPathVariable(varName, part));
xpathBuilder.AppendFormat(XPathStrings.ChildDocumentByUrlNameVar, varName);
}
else
{
xpathBuilder.AppendFormat(XPathStrings.ChildDocumentByUrlName, part);
}
}
xpath = xpathBuilder.ToString();
if (varsList != null)
vars = varsList.ToArray();
}
return xpath;
}
#endregion
}
}
| |
using iSukces.Code.Interfaces;
using Xunit;
namespace iSukces.Code.Tests.DependsOnPropertyGenerator
{
public class DependsOnPropertyGeneratorTests
{
[Fact]
public void T01_Should_generate_simple()
{
var gen = new Code.DependsOnPropertyGenerator();
gen.Flags = DependsOnPropertyGeneratorFlags.None;
var q = new TestContext();
gen.Generate(typeof(Test), q);
const string exp = @"// ReSharper disable All
namespace iSukces.Code.Tests.DependsOnPropertyGenerator
{
partial class DependsOnPropertyGeneratorTests
{
partial class Test
{
public const string MasterDependent = ""Slave"";
}
}
}
";
Assert.Equal(exp, q.Code);
}
[Fact]
public void T02_Should_generate_with_GetDependedntProperties()
{
var gen = new Code.DependsOnPropertyGenerator
{
Flags = DependsOnPropertyGeneratorFlags.GetDependentProperties,
GetDependentPropertiesMethodName = "TestGetDependentProperties",
GetDependentPropertiesMethodVisibility = Visibilities.Protected
};
var q = new TestContext();
gen.Generate(typeof(Test), q);
const string exp = @"// ReSharper disable All
namespace iSukces.Code.Tests.DependsOnPropertyGenerator
{
partial class DependsOnPropertyGeneratorTests
{
partial class Test
{
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
private static string TestGetDependentProperties(string propertyName)
{
switch (propertyName)
{
case nameof(Master): return MasterDependent; // Slave
}
return null;
}
public const string MasterDependent = ""Slave"";
}
}
}
";
Assert.Equal(exp, q.Code);
}
[Fact]
public void T03_Should_generate_with_GetDependedntProperties()
{
var gen = new Code.DependsOnPropertyGenerator
{
Flags = DependsOnPropertyGeneratorFlags.GetDependentProperties,
GetDependentPropertiesMethodName = "TestGetDependentProperties",
GetDependentPropertiesMethodVisibility = Visibilities.Protected
};
var q = new TestContext();
gen.Generate(typeof(TestCascade), q);
const string expected = @"// ReSharper disable All
namespace iSukces.Code.Tests.DependsOnPropertyGenerator
{
partial class DependsOnPropertyGeneratorTests
{
partial class TestCascade
{
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
private static string TestGetDependentProperties(string propertyName)
{
switch (propertyName)
{
case nameof(Master): return MasterDependent; // Slave,DeepSlave,EvenDeeperSlave
case nameof(Slave): return ""DeepSlave,EvenDeeperSlave"";
case nameof(DeepSlave): return DeepSlaveDependent; // EvenDeeperSlave
case nameof(FirstName):
case nameof(LastName): return LastNameDependent; // FullNameA,FullNameB,FullNameA1,FullNameB1
case nameof(FullNameA): return ""FullNameA1"";
}
return null;
}
public const string MasterDependent = ""Slave,DeepSlave,EvenDeeperSlave"";
public const string DeepSlaveDependent = ""EvenDeeperSlave"";
public const string FirstNameDependent = ""FullNameA,FullNameB,FullNameA1,FullNameB1"";
public const string LastNameDependent = FirstNameDependent;
}
}
}
";
var code = q.Code;
Assert.Equal(expected, code);
}
[Fact]
public void T04_Should_not_allow_to_exclude_master_property()
{
var gen = new Code.DependsOnPropertyGenerator
{
Flags = DependsOnPropertyGeneratorFlags.GetDependentProperties,
GetDependentPropertiesMethodName = "TestGetDependentProperties",
GetDependentPropertiesMethodVisibility = Visibilities.Protected
};
var q = new TestContext();
Assert.Throws<DependsOnPropertyGeneratorException>(() =>
{
gen.Generate(typeof(WrongClass), q);
});
}
private class Test
{
public int Master { get; set; }
[DependsOnProperty(nameof(Master))]
public int Slave => Master + 1;
}
[DependsOnProperty2(SkipCreatingConstants = true)]
private class TestCascade
{
public int Master { get; set; }
[DependsOnProperty(nameof(Master), Flags = DependsOnPropertyFlags.SkipCreatingConstants)]
public int Slave => Master + 1;
[DependsOnProperty(nameof(Slave))]
public int DeepSlave => Slave + 1;
[DependsOnProperty(nameof(DeepSlave))]
public int EvenDeeperSlave => DeepSlave + 1;
public string FirstName { get; set; }
public string LastName { get; set; }
[DependsOnProperty(nameof(FirstName), nameof(LastName), Flags = DependsOnPropertyFlags.SkipCreatingConstants)]
public string FullNameA => FirstName + " " + LastName;
[DependsOnProperty(nameof(FirstName), nameof(LastName), Flags = DependsOnPropertyFlags.SkipCreatingConstants|DependsOnPropertyFlags.ExcludeFromGetDependentPropertiesMethod)]
public string FullNameB => FirstName + " " + LastName;
[DependsOnProperty(nameof(FullNameA), Flags = DependsOnPropertyFlags.SkipCreatingConstants)]
public string FullNameA1 => FullNameA + "?";
[DependsOnProperty(nameof(FullNameB), Flags = DependsOnPropertyFlags.ExcludeFromGetDependentPropertiesMethod)]
public string FullNameB1 => FullNameB + "?";
}
}
public class WrongClass
{
[DependsOnProperty(Flags = DependsOnPropertyFlags.ExcludeFromGetDependentPropertiesMethod)]
public string FirstName { get; set; }
public string LastName { get; set; }
[DependsOnProperty(nameof(FirstName), nameof(LastName))]
public string FullName => FirstName + " " + LastName;
}
}
| |
// 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.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void SubtractInt16()
{
var test = new SimpleBinaryOpTest__SubtractInt16();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local works
test.RunLclFldScenario();
// Validates passing an instance member works
test.RunFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleBinaryOpTest__SubtractInt16
{
private const int VectorSize = 32;
private const int Op1ElementCount = VectorSize / sizeof(Int16);
private const int Op2ElementCount = VectorSize / sizeof(Int16);
private const int RetElementCount = VectorSize / sizeof(Int16);
private static Int16[] _data1 = new Int16[Op1ElementCount];
private static Int16[] _data2 = new Int16[Op2ElementCount];
private static Vector256<Int16> _clsVar1;
private static Vector256<Int16> _clsVar2;
private Vector256<Int16> _fld1;
private Vector256<Int16> _fld2;
private SimpleBinaryOpTest__DataTable<Int16, Int16, Int16> _dataTable;
static SimpleBinaryOpTest__SubtractInt16()
{
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (short)(random.Next(short.MinValue, short.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _clsVar1), ref Unsafe.As<Int16, byte>(ref _data1[0]), VectorSize);
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (short)(random.Next(short.MinValue, short.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _clsVar2), ref Unsafe.As<Int16, byte>(ref _data2[0]), VectorSize);
}
public SimpleBinaryOpTest__SubtractInt16()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (short)(random.Next(short.MinValue, short.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), VectorSize);
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (short)(random.Next(short.MinValue, short.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), VectorSize);
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (short)(random.Next(short.MinValue, short.MaxValue)); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (short)(random.Next(short.MinValue, short.MaxValue)); }
_dataTable = new SimpleBinaryOpTest__DataTable<Int16, Int16, Int16>(_data1, _data2, new Int16[RetElementCount], VectorSize);
}
public bool IsSupported => Avx2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Avx2.Subtract(
Unsafe.Read<Vector256<Int16>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Int16>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
var result = Avx2.Subtract(
Avx.LoadVector256((Int16*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((Int16*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
var result = Avx2.Subtract(
Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
var result = typeof(Avx2).GetMethod(nameof(Avx2.Subtract), new Type[] { typeof(Vector256<Int16>), typeof(Vector256<Int16>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<Int16>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Int16>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
var result = typeof(Avx2).GetMethod(nameof(Avx2.Subtract), new Type[] { typeof(Vector256<Int16>), typeof(Vector256<Int16>) })
.Invoke(null, new object[] {
Avx.LoadVector256((Int16*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((Int16*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
var result = typeof(Avx2).GetMethod(nameof(Avx2.Subtract), new Type[] { typeof(Vector256<Int16>), typeof(Vector256<Int16>) })
.Invoke(null, new object[] {
Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
var result = Avx2.Subtract(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
var left = Unsafe.Read<Vector256<Int16>>(_dataTable.inArray1Ptr);
var right = Unsafe.Read<Vector256<Int16>>(_dataTable.inArray2Ptr);
var result = Avx2.Subtract(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
var left = Avx.LoadVector256((Int16*)(_dataTable.inArray1Ptr));
var right = Avx.LoadVector256((Int16*)(_dataTable.inArray2Ptr));
var result = Avx2.Subtract(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
var left = Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray1Ptr));
var right = Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray2Ptr));
var result = Avx2.Subtract(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclFldScenario()
{
var test = new SimpleBinaryOpTest__SubtractInt16();
var result = Avx2.Subtract(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunFldScenario()
{
var result = Avx2.Subtract(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunUnsupportedScenario()
{
Succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector256<Int16> left, Vector256<Int16> right, void* result, [CallerMemberName] string method = "")
{
Int16[] inArray1 = new Int16[Op1ElementCount];
Int16[] inArray2 = new Int16[Op2ElementCount];
Int16[] outArray = new Int16[RetElementCount];
Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left);
Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "")
{
Int16[] inArray1 = new Int16[Op1ElementCount];
Int16[] inArray2 = new Int16[Op2ElementCount];
Int16[] outArray = new Int16[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Int16[] left, Int16[] right, Int16[] result, [CallerMemberName] string method = "")
{
if ((short)(left[0] - right[0]) != result[0])
{
Succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if ((short)(left[i] - right[i]) != result[i])
{
Succeeded = false;
break;
}
}
}
if (!Succeeded)
{
Console.WriteLine($"{nameof(Avx2)}.{nameof(Avx2.Subtract)}<Int16>(Vector256<Int16>, Vector256<Int16>): {method} failed:");
Console.WriteLine($" left: ({string.Join(", ", left)})");
Console.WriteLine($" right: ({string.Join(", ", right)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Editor;
using Microsoft.CodeAnalysis.Editor.Host;
using Microsoft.CodeAnalysis.Editor.Implementation.GoToDefinition;
using Microsoft.CodeAnalysis.Editor.Undo;
using Microsoft.CodeAnalysis.FindSymbols;
using Microsoft.CodeAnalysis.GeneratedCodeRecognition;
using Microsoft.VisualStudio.LanguageServices.Implementation;
using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel;
using Microsoft.VisualStudio.LanguageServices.Implementation.Interop;
using Microsoft.VisualStudio.LanguageServices.Implementation.Library.ObjectBrowser.Lists;
using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem;
using Microsoft.VisualStudio.Shell;
using Roslyn.Utilities;
namespace Microsoft.VisualStudio.LanguageServices
{
[Export(typeof(VisualStudioWorkspace))]
[Export(typeof(VisualStudioWorkspaceImpl))]
internal class RoslynVisualStudioWorkspace : VisualStudioWorkspaceImpl
{
private readonly IEnumerable<Lazy<INavigableItemsPresenter>> _navigableItemsPresenters;
private readonly IEnumerable<Lazy<IReferencedSymbolsPresenter>> _referencedSymbolsPresenters;
private readonly IEnumerable<Lazy<INavigableDefinitionProvider>> _externalDefinitionProviders;
[ImportingConstructor]
private RoslynVisualStudioWorkspace(
SVsServiceProvider serviceProvider,
SaveEventsService saveEventsService,
[ImportMany] IEnumerable<Lazy<INavigableItemsPresenter>> navigableItemsPresenters,
[ImportMany] IEnumerable<Lazy<IReferencedSymbolsPresenter>> referencedSymbolsPresenters,
[ImportMany] IEnumerable<Lazy<INavigableDefinitionProvider>> externalDefinitionProviders)
: base(
serviceProvider,
backgroundWork: WorkspaceBackgroundWork.ParseAndCompile)
{
PrimaryWorkspace.Register(this);
InitializeStandardVisualStudioWorkspace(serviceProvider, saveEventsService);
_navigableItemsPresenters = navigableItemsPresenters;
_referencedSymbolsPresenters = referencedSymbolsPresenters;
_externalDefinitionProviders = externalDefinitionProviders;
}
public override EnvDTE.FileCodeModel GetFileCodeModel(DocumentId documentId)
{
if (documentId == null)
{
throw new ArgumentNullException(nameof(documentId));
}
var project = ProjectTracker.GetProject(documentId.ProjectId);
if (project == null)
{
throw new ArgumentException(ServicesVSResources.The_given_DocumentId_did_not_come_from_the_Visual_Studio_workspace, nameof(documentId));
}
var document = project.GetDocumentOrAdditionalDocument(documentId);
if (document == null)
{
throw new ArgumentException(ServicesVSResources.The_given_DocumentId_did_not_come_from_the_Visual_Studio_workspace, nameof(documentId));
}
var provider = project as IProjectCodeModelProvider;
if (provider != null)
{
var projectCodeModel = provider.ProjectCodeModel;
if (projectCodeModel.CanCreateFileCodeModelThroughProject(document.FilePath))
{
return (EnvDTE.FileCodeModel)projectCodeModel.CreateFileCodeModelThroughProject(document.FilePath);
}
}
return null;
}
internal override bool RenameFileCodeModelInstance(DocumentId documentId, string newFilePath)
{
if (documentId == null)
{
return false;
}
var project = ProjectTracker.GetProject(documentId.ProjectId);
if (project == null)
{
return false;
}
var document = project.GetDocumentOrAdditionalDocument(documentId);
if (document == null)
{
return false;
}
var codeModelProvider = project as IProjectCodeModelProvider;
if (codeModelProvider == null)
{
return false;
}
var codeModelCache = codeModelProvider.ProjectCodeModel.GetCodeModelCache();
if (codeModelCache == null)
{
return false;
}
codeModelCache.OnSourceFileRenaming(document.FilePath, newFilePath);
return true;
}
internal override IInvisibleEditor OpenInvisibleEditor(DocumentId documentId)
{
var hostDocument = GetHostDocument(documentId);
return OpenInvisibleEditor(hostDocument);
}
internal override IInvisibleEditor OpenInvisibleEditor(IVisualStudioHostDocument hostDocument)
{
// We need to ensure the file is saved, only if a global undo transaction is open
var globalUndoService = this.Services.GetService<IGlobalUndoService>();
var needsSave = globalUndoService.IsGlobalTransactionOpen(this);
var needsUndoDisabled = false;
if (needsSave)
{
if (this.CurrentSolution.ContainsDocument(hostDocument.Id))
{
// Disable undo on generated documents
needsUndoDisabled = this.Services.GetService<IGeneratedCodeRecognitionService>().IsGeneratedCode(this.CurrentSolution.GetDocument(hostDocument.Id));
}
else
{
// Enable undo on "additional documents" or if no document can be found.
needsUndoDisabled = false;
}
}
return new InvisibleEditor(ServiceProvider, hostDocument.FilePath, needsSave, needsUndoDisabled);
}
private static bool TryResolveSymbol(ISymbol symbol, Project project, CancellationToken cancellationToken, out ISymbol resolvedSymbol, out Project resolvedProject)
{
resolvedSymbol = null;
resolvedProject = null;
var currentProject = project.Solution.Workspace.CurrentSolution.GetProject(project.Id);
if (currentProject == null)
{
return false;
}
var originalCompilation = project.GetCompilationAsync(cancellationToken).WaitAndGetResult(cancellationToken);
var symbolId = SymbolKey.Create(symbol, cancellationToken);
var currentCompilation = currentProject.GetCompilationAsync(cancellationToken).WaitAndGetResult(cancellationToken);
var symbolInfo = symbolId.Resolve(currentCompilation, cancellationToken: cancellationToken);
if (symbolInfo.Symbol == null)
{
return false;
}
resolvedSymbol = symbolInfo.Symbol;
resolvedProject = currentProject;
return true;
}
public override bool TryGoToDefinition(ISymbol symbol, Project project, CancellationToken cancellationToken)
{
if (!_navigableItemsPresenters.Any())
{
return false;
}
ISymbol searchSymbol;
Project searchProject;
if (!TryResolveSymbol(symbol, project, cancellationToken, out searchSymbol, out searchProject))
{
return false;
}
return GoToDefinitionHelpers.TryGoToDefinition(
searchSymbol, searchProject, _externalDefinitionProviders, _navigableItemsPresenters, cancellationToken: cancellationToken);
}
public override bool TryFindAllReferences(ISymbol symbol, Project project, CancellationToken cancellationToken)
{
if (!_referencedSymbolsPresenters.Any())
{
return false;
}
ISymbol searchSymbol;
Project searchProject;
if (!TryResolveSymbol(symbol, project, cancellationToken, out searchSymbol, out searchProject))
{
return false;
}
var searchSolution = searchProject.Solution;
var result = SymbolFinder
.FindReferencesAsync(searchSymbol, searchSolution, cancellationToken)
.WaitAndGetResult(cancellationToken).ToList();
if (result != null)
{
DisplayReferencedSymbols(searchSolution, result);
return true;
}
return false;
}
public override void DisplayReferencedSymbols(Solution solution, IEnumerable<ReferencedSymbol> referencedSymbols)
{
foreach (var presenter in _referencedSymbolsPresenters)
{
presenter.Value.DisplayResult(solution, referencedSymbols);
}
}
internal override object GetBrowseObject(SymbolListItem symbolListItem)
{
var compilation = symbolListItem.GetCompilation(this);
if (compilation == null)
{
return null;
}
var symbol = symbolListItem.ResolveSymbol(compilation);
var sourceLocation = symbol.Locations.Where(l => l.IsInSource).FirstOrDefault();
if (sourceLocation == null)
{
return null;
}
var projectId = symbolListItem.ProjectId;
if (projectId == null)
{
return null;
}
var project = this.CurrentSolution.GetProject(projectId);
if (project == null)
{
return null;
}
var codeModelService = project.LanguageServices.GetService<ICodeModelService>();
if (codeModelService == null)
{
return null;
}
var tree = sourceLocation.SourceTree;
var document = project.GetDocument(tree);
var vsFileCodeModel = this.GetFileCodeModel(document.Id);
var fileCodeModel = ComAggregate.GetManagedObject<FileCodeModel>(vsFileCodeModel);
if (fileCodeModel != null)
{
var syntaxNode = tree.GetRoot().FindNode(sourceLocation.SourceSpan);
while (syntaxNode != null)
{
if (!codeModelService.TryGetNodeKey(syntaxNode).IsEmpty)
{
break;
}
syntaxNode = syntaxNode.Parent;
}
if (syntaxNode != null)
{
var codeElement = fileCodeModel.GetOrCreateCodeElement<EnvDTE.CodeElement>(syntaxNode);
if (codeElement != null)
{
return codeElement;
}
}
}
return null;
}
}
}
| |
// Copyright (c) 2002-2019 "Neo4j,"
// Neo4j Sweden AB [http://neo4j.com]
//
// This file is part of Neo4j.
//
// 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.Runtime.CompilerServices;
using System.Threading.Tasks;
using FluentAssertions;
using Xunit.Abstractions;
using static Neo4j.Driver.IntegrationTests.VersionComparison;
namespace Neo4j.Driver.IntegrationTests.Direct
{
public class BoltV4IT : DirectDriverTestBase
{
public BoltV4IT(ITestOutputHelper output, StandAloneIntegrationTestFixture fixture)
: base(output, fixture)
{
}
[RequireServerFact("4.0.0", GreaterThanOrEqualTo)]
public async Task ShouldReturnDatabaseInfoForDefaultDatabase()
{
await VerifyDatabaseNameOnSummary(null, "neo4j");
}
[RequireServerFact("4.0.0", GreaterThanOrEqualTo)]
public async Task ShouldReturnDatabaseInfoForDefaultDatabaseWhenSpecified()
{
await VerifyDatabaseNameOnSummary("neo4j", "neo4j");
}
[RequireServerFact("4.0.0", GreaterThanOrEqualTo)]
public async Task ShouldReturnDatabaseInfoForDatabase()
{
await CreateDatabase(Server.Driver, "foo");
try
{
await VerifyDatabaseNameOnSummary("foo", "foo");
}
finally
{
await DropDatabase(Server.Driver, "foo");
}
}
[RequireServerFact("4.0.0", GreaterThanOrEqualTo)]
public async Task ShouldReturnDatabaseInfoForDefaultDatabaseInTx()
{
await VerifyDatabaseNameOnSummaryTx(null, "neo4j");
}
[RequireServerFact("4.0.0", GreaterThanOrEqualTo)]
public async Task ShouldReturnDatabaseInfoForDefaultDatabaseWhenSpecifiedInTx()
{
await VerifyDatabaseNameOnSummaryTx("neo4j", "neo4j");
}
[RequireServerFact("4.0.0", GreaterThanOrEqualTo)]
public async Task ShouldReturnDatabaseInfoForDatabaseInTx()
{
await CreateDatabase(Server.Driver, "foo");
try
{
await VerifyDatabaseNameOnSummaryTx("foo", "foo");
}
finally
{
await DropDatabase(Server.Driver, "foo");
}
}
[RequireServerFact("4.0.0", GreaterThanOrEqualTo)]
public async Task ShouldReturnDatabaseInfoForDefaultDatabaseInTxFunc()
{
await VerifyDatabaseNameOnSummaryTxFunc(null, "neo4j");
}
[RequireServerFact("4.0.0", GreaterThanOrEqualTo)]
public async Task ShouldReturnDatabaseInfoForDefaultDatabaseWhenSpecifiedInTxFunc()
{
await VerifyDatabaseNameOnSummaryTxFunc("neo4j", "neo4j");
}
[RequireServerFact("4.0.0", GreaterThanOrEqualTo)]
public async Task ShouldReturnDatabaseInfoForDatabaseInTxFunc()
{
await CreateDatabase(Server.Driver, "foo");
try
{
await VerifyDatabaseNameOnSummaryTxFunc("foo", "foo");
}
finally
{
await DropDatabase(Server.Driver, "foo");
}
}
[RequireServerFact("4.0.0", GreaterThanOrEqualTo)]
public void ShouldThrowForNonExistentDatabase()
{
this.Awaiting(_ => VerifyDatabaseNameOnSummary("bar", "bar")).Should().Throw<ClientException>()
.WithMessage("*database does not exist.*");
}
[RequireServerFact("4.0.0", GreaterThanOrEqualTo)]
public void ShouldThrowForNonExistentDatabaseInTx()
{
this.Awaiting(_ => VerifyDatabaseNameOnSummaryTx("bar", "bar")).Should().Throw<ClientException>()
.WithMessage("*database does not exist.*");
}
[RequireServerFact("4.0.0", GreaterThanOrEqualTo)]
public void ShouldThrowForNonExistentDatabaseInTxFunc()
{
this.Awaiting(_ => VerifyDatabaseNameOnSummaryTxFunc("bar", "bar")).Should().Throw<ClientException>()
.WithMessage("*database does not exist.*");
}
[RequireServerFact("4.0.0", LessThan)]
public void ShouldThrowWhenDatabaseIsSpecified()
{
this.Awaiting(_ => VerifyDatabaseNameOnSummary("bar", "bar")).Should().Throw<ClientException>()
.WithMessage("*to a server that does not support multiple databases.*");
}
[RequireServerFact("4.0.0", LessThan)]
public void ShouldThrowWhenDatabaseIsSpecifiedInTx()
{
this.Awaiting(_ => VerifyDatabaseNameOnSummaryTx("bar", "bar")).Should().Throw<ClientException>()
.WithMessage("*to a server that does not support multiple databases.*");
}
[RequireServerFact("4.0.0", LessThan)]
public void ShouldThrowWhenDatabaseIsSpecifiedInTxFunc()
{
this.Awaiting(_ => VerifyDatabaseNameOnSummaryTxFunc("bar", "bar")).Should().Throw<ClientException>()
.WithMessage("*to a server that does not support multiple databases.*");
}
private async Task VerifyDatabaseNameOnSummary(string name, string expected)
{
var session = Server.Driver.AsyncSession(o =>
{
if (!string.IsNullOrEmpty(name))
{
o.Database = name;
}
});
try
{
var cursor = await session.RunAsync("RETURN 1");
var summary = await cursor.ConsumeAsync();
summary.Database.Should().NotBeNull();
summary.Database.Name.Should().Be(expected);
}
finally
{
await session.CloseAsync();
}
}
private async Task VerifyDatabaseNameOnSummaryTx(string name, string expected)
{
var session = Server.Driver.AsyncSession(o =>
{
if (!string.IsNullOrEmpty(name))
{
o.Database = name;
}
});
try
{
var txc = await session.BeginTransactionAsync();
var cursor = await txc.RunAsync("RETURN 1");
var summary = await cursor.ConsumeAsync();
summary.Database.Should().NotBeNull();
summary.Database.Name.Should().Be(expected);
await txc.CommitAsync();
}
finally
{
await session.CloseAsync();
}
}
private async Task VerifyDatabaseNameOnSummaryTxFunc(string name, string expected)
{
var session = Server.Driver.AsyncSession(o =>
{
if (!string.IsNullOrEmpty(name))
{
o.Database = name;
}
});
try
{
var summary = await session.ReadTransactionAsync(async txc =>
{
var cursor = await txc.RunAsync("RETURN 1");
return await cursor.ConsumeAsync();
});
summary.Database.Should().NotBeNull();
summary.Database.Name.Should().Be(expected);
}
finally
{
await session.CloseAsync();
}
}
private static async Task CreateDatabase(IDriver driver, string name)
{
var session = driver.AsyncSession(o => o.WithDatabase("system"));
try
{
var cursor = await session.RunAsync($"CREATE DATABASE {name}");
await cursor.ConsumeAsync();
}
finally
{
await session.CloseAsync();
}
}
private static async Task DropDatabase(IDriver driver, string name)
{
var session = driver.AsyncSession(o => o.WithDatabase("system"));
try
{
var cursor = await session.RunAsync($"DROP DATABASE {name}");
await cursor.ConsumeAsync();
}
finally
{
await session.CloseAsync();
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using HDisplayControl;
using HImageAcquisition;
using HalconDotNet;
/// <summary>
/// The application GrabAndDisplay shows, how the new codelets
/// controls HDisplayControl and HImageAcquisition can be used
/// in a .NET application.
/// HDisplayControl and HImageAcquisition are Ready-to-use .NET
/// controls that make the integration of visualization and
/// image acquistion in a .NET application easier.
/// For further information to development see also the delivered
/// documentation in "readme.txt"-file.
/// </summary>
namespace GrabAndDisplay
{
public partial class Form1 : Form
{
/// <summary>
/// Lock for SomeEvent delegate access.
/// </summary>
readonly object someEventLock;
public Form1()
{
InitializeComponent();
someEventLock = new object();
}
private void Form1_Load(object sender, EventArgs e)
{
if (hDisplayControl1.ImageViewState == ImageViewStates.fitToWindow)
rBFitToWindow.Checked = true;
else
rBFullImageSize.Checked = true;
if (hDisplayControl1.ShowROI)
chBUpdateROI.Checked = true;
else
chBUpdateROI.Checked = false;
setStatusInformation(" ", " ", "");
}
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
/// <summary>
/// Estimate connection to image acquisition device
/// </summary>
private void button1_Click(object sender, EventArgs e)
{
// If the connection to IA-Device already exists,
// then the button is resonsible for disconnection
//1). Stop IA
//2). Disconnect device
if ((hImageAcquisition1.Connected))
{
if (hImageAcquisition1.Grabbing)
hImageAcquisition1.StopGrabThread();
DisconnectDevice();
btnConnectDisconnect.Text = "Connect to device";
}
else
{
ConnectToDevice();
}
if (hImageAcquisition1.Connected)
{
try
{
hImageAcquisition1.GrabImage();
}
catch (HalconException ex3)
{
setStatusInformation(hImageAcquisition1.ImageCounter.ToString(),
hImageAcquisition1.TimeGrab.ToString("F2") + " ms",
"Grab of first image failed with error message: " +
ex3.Message);
}
}
hDisplayControl1.Invalidate();
}
/// <summary>
/// Connects to image acquisition device
/// </summary>
private void ConnectToDevice()
{
try
{
if ((hImageAcquisition1.Connected == false) &&
(hImageAcquisition1.IAName == "File"))
{
hImageAcquisition1.OpenDevice();
}
else
{
setStatusInformation("", "", "Connecting to device ... ");
hImageAcquisition1.OpenDevice(hImageAcquisition1.IAName,
hImageAcquisition1.CameraType);
// set specific camera parameters, if there are some saved in the
// corresponding list.
if (hImageAcquisition1.ListOfAdjustedDynamicParameters.Capacity > 0)
hImageAcquisition1.SetIADynamicParametersFromList(
hImageAcquisition1.ListOfAdjustedDynamicParameters);
}
setStatusInformation("","","Connected to device " +
hImageAcquisition1.CameraType+ ".");
btnConnectDisconnect.Text = "Disconnect";
}
catch (HalconException ex)
{
MessageBox.Show("The connection to image acquisition device " +
"\'" + hImageAcquisition1.CameraType + "\'" + " " +
"failed with error message: \n " +
ex.Message, "Connection error!",
MessageBoxButtons.OK);
toolStripStatusLabel3.Text = "The connection to image" +
" acquisition device " +
"failed!";
}
}
/// <summary>
/// Writes status information to status line
/// </summary>
private void setStatusInformation(string statusInfoLeft,
string statusInfoRight,
string statusInfoMessage)
{
if (statusInfoLeft.Length > 0)
toolStripStatusLabel1.Text = statusInfoLeft;
else
toolStripStatusLabel1.Text = " ";
if (statusInfoRight.Length > 0)
toolStripStatusLabel2.Text = statusInfoRight;
else
toolStripStatusLabel2.Text = " ";
toolStripStatusLabel3.Text = statusInfoMessage;
}
/// <summary>
/// Writes the new image to graphic window
/// </summary>
public void UpdateImage(object sender, HImage newimage)
{
// display the new received image
// lock with act, because the grabbing thread
// can overwrite the image
lock (someEventLock)
{
HImage image = newimage;
hDisplayControl1.Image = image;
}
if (hDisplayControl1 != null)
hDisplayControl1.Invalidate();
}
/// <summary>
/// Event handling after acquiring new image from device
/// </summary>
private void hImageAcquisition1_OnGrabbedImage(object sender, HImage image)
{
UpdateImage(sender,image);
setStatusInformation(hImageAcquisition1.ImageCounter.ToString(),
hImageAcquisition1.TimeGrab.ToString("F2") + " ms",
"Acquiring image.");
}
/// <summary>
/// Starts and stops image acquisition in "live" mode
/// </summary>
private void button2_Click(object sender, EventArgs e)
{
try
{
if (!hImageAcquisition1.Connected)
{
setStatusInformation("", "", "There is no connection " +
"to image acquisition device!");
}
else
{
if (!hImageAcquisition1.Grabbing)
{
hImageAcquisition1.StartGrabThread();
btnImageAcquisition.Text = "Stop Image Acquisition";
}
else
{
hImageAcquisition1.StopGrabThread();
btnImageAcquisition.Text = "Start Image Acquisition";
}
}
}
catch (HalconException ex)
{
MessageBox.Show(ex.Message);
}
}
/// <summary>
/// Acquires single image from device
/// </summary>
private void button4_Click(object sender, EventArgs e)
{
if (hImageAcquisition1.Connected)
{
try
{
if (hImageAcquisition1.Grabbing)
{
hImageAcquisition1.StopGrabThread();
btnImageAcquisition.Text = "Start Image Acquisition";
}
hImageAcquisition1.GrabSingleImage();
}
catch (HalconException ex)
{
MessageBox.Show(ex.Message);
}
}
else
setStatusInformation("", "", "There is no connection " +
"to image acquisition device!");
}
/// <summary>
/// By resizing the form of the application the graphic window
/// should be resized also.
/// </summary>
private void Form1_Resize(object sender, EventArgs e)
{
hDisplayControl1.Resize(sender,e);
}
/// <summary>
/// Changes the mode of displaying the image in the graphic window
/// </summary>
private void rBFitToWindow_CheckedChanged(object sender, EventArgs e)
{
if (rBFitToWindow.Checked)
hDisplayControl1.ImageViewState = ImageViewStates.fitToWindow;
}
/// <summary>
/// Changes the mode of displaying the image in the graphic window
/// </summary>
private void rBFullImageSize_CheckedChanged(object sender, EventArgs e)
{
if (rBFullImageSize.Checked)
hDisplayControl1.ImageViewState = ImageViewStates.fullSizeImage;
}
/// <summary>
/// Closes connection to image acquistion device
/// </summary>
private void DisconnectDevice()
{
try
{
hImageAcquisition1.CloseDevice();
btnImageAcquisition.Text = "Start Image Acquisition";
setStatusInformation("","","Device is disconnected.");
}
catch (HalconException ex)
{
MessageBox.Show(ex.Message);
}
hDisplayControl1.ClearGraphicStack();
}
/// <summary>
/// Sets some dynamic image acquisition parameters.
/// These parameters will be saved in the list, that
/// is managed by HImageAcquisition class. After losing
/// the connection to the device the changed parameters can be
/// resonstructed, because the list exists as long as the class
/// HImageAcquisition is not disposed.
/// ATTENTION: Works only for cameras that support listed
/// specific parameters.
/// </summary>
private void btnSetIAParameter_Click(object sender, EventArgs e)
{
try
{
hImageAcquisition1.SetIADynamicParam("exposure", 55);
hImageAcquisition1.SetIADynamicParam("auto_brightness_speed",
29);
hImageAcquisition1.SetIADynamicParam("edge_enhancement",
"weak");
hImageAcquisition1.SetIADynamicParam("exposure", 24.2915);
hImageAcquisition1.SetIADynamicParam("exposure", 55);
}
catch (ArgumentException aEcxp)
{
setStatusInformation(" "," ",aEcxp.Message);
}
catch (HOperatorException hEcxp)
{
setStatusInformation(" "," ",hEcxp.Message);
}
}
/// <summary>
/// Stops image acquisition and closes connection to image acquisition
/// device.
/// </summary>
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (hImageAcquisition1.Grabbing)
DisconnectDevice();
}
private void chBUpdateROI_CheckedChanged(object sender, EventArgs e)
{
if (chBUpdateROI.Checked)
{
hDisplayControl1.ShowROI = true;
}
else
{
hDisplayControl1.ShowROI = false;
}
hDisplayControl1.Invalidate();
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Runtime.InteropServices;
namespace System.Numerics.Matrices
{
/// <summary>
/// Represents a matrix of double precision floating-point values defined by its number of columns and rows
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public struct Matrix4x1: IEquatable<Matrix4x1>, IMatrix
{
public const int ColumnCount = 4;
public const int RowCount = 1;
static Matrix4x1()
{
Zero = new Matrix4x1(0);
}
/// <summary>
/// Gets the smallest value used to determine equality
/// </summary>
public double Epsilon { get { return MatrixHelper.Epsilon; } }
/// <summary>
/// Constant Matrix4x1 with all values initialized to zero
/// </summary>
public static readonly Matrix4x1 Zero;
/// <summary>
/// Initializes a Matrix4x1 with all of it values specifically set
/// </summary>
/// <param name="m11">The column 1, row 1 value</param>
/// <param name="m21">The column 2, row 1 value</param>
/// <param name="m31">The column 3, row 1 value</param>
/// <param name="m41">The column 4, row 1 value</param>
public Matrix4x1(double m11, double m21, double m31, double m41)
{
M11 = m11; M21 = m21; M31 = m31; M41 = m41;
}
/// <summary>
/// Initialized a Matrix4x1 with all values set to the same value
/// </summary>
/// <param name="value">The value to set all values to</param>
public Matrix4x1(double value)
{
M11 = M21 = M31 = M41 = value;
}
public double M11;
public double M21;
public double M31;
public double M41;
public unsafe double this[int col, int row]
{
get
{
if (col < 0 || col >= ColumnCount)
throw new ArgumentOutOfRangeException("col", String.Format("Expected greater than or equal to 0 and less than {0}, found {1}.", ColumnCount, col));
if (row < 0 || row >= RowCount)
throw new ArgumentOutOfRangeException("row", String.Format("Expected greater than or equal to 0 and less than {0}, found {1}.", RowCount, row));
fixed (Matrix4x1* p = &this)
{
double* d = (double*)p;
return d[row * ColumnCount + col];
}
}
set
{
if (col < 0 || col >= ColumnCount)
throw new ArgumentOutOfRangeException("col", String.Format("Expected greater than or equal to 0 and less than {0}, found {1}.", ColumnCount, col));
if (row < 0 || row >= RowCount)
throw new ArgumentOutOfRangeException("row", String.Format("Expected greater than or equal to 0 and less than {0}, found {1}.", RowCount, row));
fixed (Matrix4x1* p = &this)
{
double* d = (double*)p;
d[row * ColumnCount + col] = value;
}
}
}
/// <summary>
/// Gets the number of columns in the matrix
/// </summary>
public int Columns { get { return ColumnCount; } }
/// <summary>
/// Get the number of rows in the matrix
/// </summary>
public int Rows { get { return RowCount; } }
public override bool Equals(object obj)
{
if (obj is Matrix4x1)
return this == (Matrix4x1)obj;
return false;
}
public bool Equals(Matrix4x1 other)
{
return this == other;
}
public unsafe override int GetHashCode()
{
fixed (Matrix4x1* p = &this)
{
int* x = (int*)p;
unchecked
{
return 0xFFE1
+ 7 * ((((x[00] ^ x[01]) << 0) + ((x[02] ^ x[03]) << 1) + ((x[04] ^ x[05]) << 2) + ((x[06] ^ x[07]) << 3)) << 0);
}
}
}
public override string ToString()
{
return "Matrix4x1: "
+ String.Format("{{|{0:00}|{1:00}|{2:00}|{3:00}|}}", M11, M21, M31, M41);
}
/// <summary>
/// Creates and returns a transposed matrix
/// </summary>
/// <returns>Matrix with transposed values</returns>
public Matrix1x4 Transpose()
{
return new Matrix1x4(M11,
M21,
M31,
M41);
}
public static bool operator ==(Matrix4x1 matrix1, Matrix4x1 matrix2)
{
return MatrixHelper.AreEqual(matrix1.M11, matrix2.M11)
&& MatrixHelper.AreEqual(matrix1.M21, matrix2.M21)
&& MatrixHelper.AreEqual(matrix1.M31, matrix2.M31)
&& MatrixHelper.AreEqual(matrix1.M41, matrix2.M41);
}
public static bool operator !=(Matrix4x1 matrix1, Matrix4x1 matrix2)
{
return MatrixHelper.NotEqual(matrix1.M11, matrix2.M11)
|| MatrixHelper.NotEqual(matrix1.M21, matrix2.M21)
|| MatrixHelper.NotEqual(matrix1.M31, matrix2.M31)
|| MatrixHelper.NotEqual(matrix1.M41, matrix2.M41);
}
public static Matrix4x1 operator +(Matrix4x1 matrix1, Matrix4x1 matrix2)
{
double m11 = matrix1.M11 + matrix2.M11;
double m21 = matrix1.M21 + matrix2.M21;
double m31 = matrix1.M31 + matrix2.M31;
double m41 = matrix1.M41 + matrix2.M41;
return new Matrix4x1(m11, m21, m31, m41);
}
public static Matrix4x1 operator -(Matrix4x1 matrix1, Matrix4x1 matrix2)
{
double m11 = matrix1.M11 - matrix2.M11;
double m21 = matrix1.M21 - matrix2.M21;
double m31 = matrix1.M31 - matrix2.M31;
double m41 = matrix1.M41 - matrix2.M41;
return new Matrix4x1(m11, m21, m31, m41);
}
public static Matrix4x1 operator *(Matrix4x1 matrix, double scalar)
{
double m11 = matrix.M11 * scalar;
double m21 = matrix.M21 * scalar;
double m31 = matrix.M31 * scalar;
double m41 = matrix.M41 * scalar;
return new Matrix4x1(m11, m21, m31, m41);
}
public static Matrix4x1 operator *(double scalar, Matrix4x1 matrix)
{
double m11 = scalar * matrix.M11;
double m21 = scalar * matrix.M21;
double m31 = scalar * matrix.M31;
double m41 = scalar * matrix.M41;
return new Matrix4x1(m11, m21, m31, m41);
}
public static Matrix2x1 operator *(Matrix4x1 matrix1, Matrix2x4 matrix2)
{
double m11 = matrix1.M11 * matrix2.M11 + matrix1.M21 * matrix2.M12 + matrix1.M31 * matrix2.M13 + matrix1.M41 * matrix2.M14;
double m21 = matrix1.M11 * matrix2.M21 + matrix1.M21 * matrix2.M22 + matrix1.M31 * matrix2.M23 + matrix1.M41 * matrix2.M24;
return new Matrix2x1(m11, m21);
}
public static Matrix3x1 operator *(Matrix4x1 matrix1, Matrix3x4 matrix2)
{
double m11 = matrix1.M11 * matrix2.M11 + matrix1.M21 * matrix2.M12 + matrix1.M31 * matrix2.M13 + matrix1.M41 * matrix2.M14;
double m21 = matrix1.M11 * matrix2.M21 + matrix1.M21 * matrix2.M22 + matrix1.M31 * matrix2.M23 + matrix1.M41 * matrix2.M24;
double m31 = matrix1.M11 * matrix2.M31 + matrix1.M21 * matrix2.M32 + matrix1.M31 * matrix2.M33 + matrix1.M41 * matrix2.M34;
return new Matrix3x1(m11, m21, m31);
}
public static Matrix4x1 operator *(Matrix4x1 matrix1, Matrix4x4 matrix2)
{
double m11 = matrix1.M11 * matrix2.M11 + matrix1.M21 * matrix2.M12 + matrix1.M31 * matrix2.M13 + matrix1.M41 * matrix2.M14;
double m21 = matrix1.M11 * matrix2.M21 + matrix1.M21 * matrix2.M22 + matrix1.M31 * matrix2.M23 + matrix1.M41 * matrix2.M24;
double m31 = matrix1.M11 * matrix2.M31 + matrix1.M21 * matrix2.M32 + matrix1.M31 * matrix2.M33 + matrix1.M41 * matrix2.M34;
double m41 = matrix1.M11 * matrix2.M41 + matrix1.M21 * matrix2.M42 + matrix1.M31 * matrix2.M43 + matrix1.M41 * matrix2.M44;
return new Matrix4x1(m11, m21, m31, m41);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using NuGet;
namespace NuSelfUpdate.Tests.Helpers
{
public class MockFileSystem : IExtendedFileSystem
{
private ILogger _logger;
public MockFileSystem(string appDirectory)
{
AppDirectory = appDirectory;
Paths = new Dictionary<string, Func<Stream>>(StringComparer.OrdinalIgnoreCase);
Deleted = new HashSet<string>();
}
public virtual ILogger Logger
{
get
{
return _logger ?? NullLogger.Instance;
}
set
{
_logger = value;
}
}
public virtual string Root
{
get
{
return @"C:\MockFileSystem\";
}
}
public string AppDirectory { get; private set; }
public virtual IDictionary<string, Func<Stream>> Paths
{
get;
private set;
}
public virtual HashSet<string> Deleted
{
get;
private set;
}
public virtual void CreateDirectory(string path)
{
Paths.Add(path, null);
}
public virtual void DeleteDirectory(string path, bool recursive = false)
{
foreach (var file in Paths.Keys.ToList())
{
if (file.StartsWith(path))
{
Paths.Remove(file);
}
}
Deleted.Add(path);
}
public virtual string GetFullPath(string path)
{
return Path.Combine(Root, path);
}
public virtual IEnumerable<string> GetFiles(string path)
{
path = Path.GetDirectoryName(path);
return Paths.Select(f => f.Key)
.Where(f => Path.GetDirectoryName(f).Equals(path, StringComparison.OrdinalIgnoreCase));
}
public virtual IEnumerable<string> GetFiles(string path, string filter)
{
Regex matcher = GetFilterRegex(filter);
return GetFiles(path).Where(f => matcher.IsMatch(f));
}
private static Regex GetFilterRegex(string wildcard)
{
string pattern = String.Join(String.Empty, wildcard.Split('.').Select(GetPattern));
return new Regex(pattern, RegexOptions.IgnoreCase);
}
private static string GetPattern(string token)
{
return token == "*" ? @"(.*)" : @"(" + token + ")";
}
public virtual void DeleteFile(string path)
{
Paths.Remove(path);
Deleted.Add(path);
}
public virtual bool FileExists(string path)
{
return Paths.ContainsKey(path);
}
public virtual Stream OpenFile(string path)
{
Func<Stream> factory;
if (!Paths.TryGetValue(path, out factory))
{
throw new FileNotFoundException(path + " not found.");
}
return factory();
}
public string ReadAllText(string path)
{
return OpenFile(path).ReadToEnd();
}
public virtual bool DirectoryExists(string path)
{
while (path.EndsWith("\\"))
path = path.Substring(0, path.Length - 1);
return Paths.Select(file => file.Key)
.Any(file => Path.GetDirectoryName(file).Equals(path, StringComparison.OrdinalIgnoreCase));
}
public virtual IEnumerable<string> GetDirectories(string path)
{
return Paths.GroupBy(f => Path.GetDirectoryName(f.Key))
.SelectMany(g => InternalGetDirectories(g.Key))
.Where(f => !String.IsNullOrEmpty(f) &&
Path.GetDirectoryName(f).Equals(path, StringComparison.OrdinalIgnoreCase))
.Distinct();
}
public virtual void MoveFile(string sourcePath, string destinationPath)
{
Func<Stream> factory;
if (!Paths.TryGetValue(sourcePath, out factory))
throw new FileNotFoundException(sourcePath + " not found.");
if (Paths.ContainsKey(destinationPath))
throw new IOException(destinationPath + " Already exists");
Paths.Remove(sourcePath);
Paths[destinationPath] = factory;
}
public virtual void AddFile(string path)
{
AddFile(path, new MemoryStream());
}
public void AddFile(string path, string content)
{
AddFile(path, content.AsStream());
}
public virtual void AddFile(string path, Stream stream)
{
var ms = new MemoryStream((int)stream.Length);
stream.CopyTo(ms);
byte[] buffer = ms.ToArray();
Paths[path] = () => new MemoryStream(buffer);
}
public virtual void AddFile(string path, Func<Stream> getStream)
{
Paths[path] = getStream;
}
public virtual DateTimeOffset GetLastModified(string path)
{
return DateTime.UtcNow;
}
public virtual DateTimeOffset GetCreated(string path)
{
return DateTime.UtcNow;
}
IEnumerable<string> InternalGetDirectories(string path)
{
foreach (var index in IndexOfAll(path, Path.DirectorySeparatorChar))
{
yield return path.Substring(0, index);
}
yield return path;
}
IEnumerable<int> IndexOfAll(string value, char ch)
{
int index = -1;
do
{
index = value.IndexOf(ch, index + 1);
if (index >= 0)
{
yield return index;
}
}
while (index >= 0);
}
}
}
| |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using JetBrains.Annotations;
using osu.Framework.Allocation;
using osu.Framework.Audio;
using osu.Framework.Audio.Track;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.IO.Stores;
using osu.Framework.Platform;
using osu.Framework.Testing;
using osu.Framework.Timing;
using osu.Game.Beatmaps;
using osu.Game.Database;
using osu.Game.Online.API;
using osu.Game.Overlays;
using osu.Game.Rulesets;
using osu.Game.Rulesets.Mods;
using osu.Game.Rulesets.Objects;
using osu.Game.Rulesets.UI;
using osu.Game.Screens;
using osu.Game.Storyboards;
using osu.Game.Tests.Beatmaps;
namespace osu.Game.Tests.Visual
{
[ExcludeFromDynamicCompile]
public abstract class OsuTestScene : TestScene
{
protected Bindable<WorkingBeatmap> Beatmap { get; private set; }
protected Bindable<RulesetInfo> Ruleset;
protected Bindable<IReadOnlyList<Mod>> SelectedMods;
protected new OsuScreenDependencies Dependencies { get; private set; }
private DrawableRulesetDependencies rulesetDependencies;
private Lazy<Storage> localStorage;
protected Storage LocalStorage => localStorage.Value;
private Lazy<DatabaseContextFactory> contextFactory;
protected IResourceStore<byte[]> Resources;
protected IAPIProvider API
{
get
{
if (UseOnlineAPI)
throw new InvalidOperationException($"Using the {nameof(OsuTestScene)} dummy API is not supported when {nameof(UseOnlineAPI)} is true");
return dummyAPI;
}
}
private DummyAPIAccess dummyAPI;
protected DatabaseContextFactory ContextFactory => contextFactory.Value;
/// <summary>
/// Whether this test scene requires real-world API access.
/// If true, this will bypass the local <see cref="DummyAPIAccess"/> and use the <see cref="OsuGameBase"/> provided one.
/// </summary>
protected virtual bool UseOnlineAPI => false;
/// <summary>
/// When running headless, there is an opportunity to use the host storage rather than creating a second isolated one.
/// This is because the host is recycled per TestScene execution in headless at an nunit level.
/// </summary>
private Storage isolatedHostStorage;
protected override IReadOnlyDependencyContainer CreateChildDependencies(IReadOnlyDependencyContainer parent)
{
if (!UseFreshStoragePerRun)
isolatedHostStorage = (parent.Get<GameHost>() as HeadlessGameHost)?.Storage;
Resources = parent.Get<OsuGameBase>().Resources;
contextFactory = new Lazy<DatabaseContextFactory>(() =>
{
var factory = new DatabaseContextFactory(LocalStorage);
// only reset the database if not using the host storage.
// if we reset the host storage, it will delete global key bindings.
if (isolatedHostStorage == null)
factory.ResetDatabase();
using (var usage = factory.Get())
usage.Migrate();
return factory;
});
RecycleLocalStorage(false);
var baseDependencies = base.CreateChildDependencies(parent);
var providedRuleset = CreateRuleset();
if (providedRuleset != null)
baseDependencies = rulesetDependencies = new DrawableRulesetDependencies(providedRuleset, baseDependencies);
Dependencies = new OsuScreenDependencies(false, baseDependencies);
Beatmap = Dependencies.Beatmap;
Beatmap.SetDefault();
Ruleset = Dependencies.Ruleset;
Ruleset.SetDefault();
SelectedMods = Dependencies.Mods;
SelectedMods.SetDefault();
if (!UseOnlineAPI)
{
dummyAPI = new DummyAPIAccess();
Dependencies.CacheAs<IAPIProvider>(dummyAPI);
base.Content.Add(dummyAPI);
}
return Dependencies;
}
protected override Container<Drawable> Content => content ?? base.Content;
private readonly Container content;
protected OsuTestScene()
{
base.Content.Add(content = new DrawSizePreservingFillContainer());
}
protected virtual bool UseFreshStoragePerRun => false;
public virtual void RecycleLocalStorage(bool isDisposing)
{
if (localStorage?.IsValueCreated == true)
{
try
{
localStorage.Value.DeleteDirectory(".");
}
catch
{
// we don't really care if this fails; it will just leave folders lying around from test runs.
}
}
localStorage =
new Lazy<Storage>(() => isolatedHostStorage ?? new TemporaryNativeStorage($"{GetType().Name}-{Guid.NewGuid()}"));
}
[Resolved]
protected AudioManager Audio { get; private set; }
[Resolved]
protected MusicController MusicController { get; private set; }
/// <summary>
/// Creates the ruleset to be used for this test scene.
/// </summary>
/// <remarks>
/// When testing against ruleset-specific components, this method must be overriden to their corresponding ruleset.
/// </remarks>
[CanBeNull]
protected virtual Ruleset CreateRuleset() => null;
protected virtual IBeatmap CreateBeatmap(RulesetInfo ruleset) => new TestBeatmap(ruleset);
protected WorkingBeatmap CreateWorkingBeatmap(RulesetInfo ruleset) =>
CreateWorkingBeatmap(CreateBeatmap(ruleset));
protected virtual WorkingBeatmap CreateWorkingBeatmap(IBeatmap beatmap, Storyboard storyboard = null) =>
new ClockBackedTestWorkingBeatmap(beatmap, storyboard, Clock, Audio);
[BackgroundDependencyLoader]
private void load(RulesetStore rulesets)
{
Ruleset.Value = CreateRuleset()?.RulesetInfo ?? rulesets.AvailableRulesets.First();
}
protected override void Dispose(bool isDisposing)
{
base.Dispose(isDisposing);
rulesetDependencies?.Dispose();
if (MusicController?.TrackLoaded == true)
MusicController.Stop();
if (contextFactory?.IsValueCreated == true)
contextFactory.Value.ResetDatabase();
RecycleLocalStorage(true);
}
protected override ITestSceneTestRunner CreateRunner() => new OsuTestSceneTestRunner();
public class ClockBackedTestWorkingBeatmap : TestWorkingBeatmap
{
private readonly Track track;
private readonly TrackVirtualStore store;
/// <summary>
/// Create an instance which creates a <see cref="TestBeatmap"/> for the provided ruleset when requested.
/// </summary>
/// <param name="ruleset">The target ruleset.</param>
/// <param name="referenceClock">A clock which should be used instead of a stopwatch for virtual time progression.</param>
/// <param name="audio">Audio manager. Required if a reference clock isn't provided.</param>
public ClockBackedTestWorkingBeatmap(RulesetInfo ruleset, IFrameBasedClock referenceClock, AudioManager audio)
: this(new TestBeatmap(ruleset), null, referenceClock, audio)
{
}
/// <summary>
/// Create an instance which provides the <see cref="IBeatmap"/> when requested.
/// </summary>
/// <param name="beatmap">The beatmap</param>
/// <param name="storyboard">The storyboard.</param>
/// <param name="referenceClock">An optional clock which should be used instead of a stopwatch for virtual time progression.</param>
/// <param name="audio">Audio manager. Required if a reference clock isn't provided.</param>
public ClockBackedTestWorkingBeatmap(IBeatmap beatmap, Storyboard storyboard, IFrameBasedClock referenceClock, AudioManager audio)
: base(beatmap, storyboard, audio)
{
double trackLength = 60000;
if (beatmap.HitObjects.Count > 0)
// add buffer after last hitobject to allow for final replay frames etc.
trackLength = Math.Max(trackLength, beatmap.HitObjects.Max(h => h.GetEndTime()) + 2000);
if (referenceClock != null)
{
store = new TrackVirtualStore(referenceClock);
audio.AddItem(store);
track = store.GetVirtual(trackLength);
}
else
track = audio?.Tracks.GetVirtual(trackLength);
}
~ClockBackedTestWorkingBeatmap()
{
// Remove the track store from the audio manager
store?.Dispose();
}
protected override Track GetBeatmapTrack() => track;
public class TrackVirtualStore : AudioCollectionManager<Track>, ITrackStore
{
private readonly IFrameBasedClock referenceClock;
public TrackVirtualStore(IFrameBasedClock referenceClock)
{
this.referenceClock = referenceClock;
}
public Track Get(string name) => throw new NotImplementedException();
public Task<Track> GetAsync(string name) => throw new NotImplementedException();
public Stream GetStream(string name) => throw new NotImplementedException();
public IEnumerable<string> GetAvailableResources() => throw new NotImplementedException();
public Track GetVirtual(double length = double.PositiveInfinity)
{
var track = new TrackVirtualManual(referenceClock) { Length = length };
AddItem(track);
return track;
}
}
/// <summary>
/// A virtual track which tracks a reference clock.
/// </summary>
public class TrackVirtualManual : Track
{
private readonly IFrameBasedClock referenceClock;
private bool running;
public TrackVirtualManual(IFrameBasedClock referenceClock)
{
this.referenceClock = referenceClock;
Length = double.PositiveInfinity;
}
public override bool Seek(double seek)
{
accumulated = Math.Clamp(seek, 0, Length);
lastReferenceTime = null;
return accumulated == seek;
}
public override void Start()
{
running = true;
}
public override void Reset()
{
Seek(0);
base.Reset();
}
public override void Stop()
{
if (running)
{
running = false;
lastReferenceTime = null;
}
}
public override bool IsRunning => running;
private double? lastReferenceTime;
private double accumulated;
public override double CurrentTime => Math.Min(accumulated, Length);
protected override void UpdateState()
{
base.UpdateState();
if (running)
{
double refTime = referenceClock.CurrentTime;
double? lastRefTime = lastReferenceTime;
if (lastRefTime != null)
accumulated += (refTime - lastRefTime.Value) * Rate;
lastReferenceTime = refTime;
}
if (CurrentTime >= Length)
{
Stop();
// `RaiseCompleted` is not called here to prevent transitioning to the next song.
}
}
}
}
public class OsuTestSceneTestRunner : OsuGameBase, ITestSceneTestRunner
{
private TestSceneTestRunner.TestRunner runner;
protected override void LoadAsyncComplete()
{
// this has to be run here rather than LoadComplete because
// TestScene.cs is checking the IsLoaded state (on another thread) and expects
// the runner to be loaded at that point.
Add(runner = new TestSceneTestRunner.TestRunner());
}
protected override void InitialiseFonts()
{
// skip fonts load as it's not required for testing purposes.
}
public void RunTestBlocking(TestScene test) => runner.RunTestBlocking(test);
}
}
}
| |
// Code generated by Microsoft (R) AutoRest Code Generator 1.1.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace ApplicationGateway
{
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// VirtualNetworksOperations operations.
/// </summary>
public partial interface IVirtualNetworksOperations
{
/// <summary>
/// Deletes the specified virtual network.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkName'>
/// The name of the virtual network.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets the specified virtual network by resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkName'>
/// The name of the virtual network.
/// </param>
/// <param name='expand'>
/// Expands referenced resources.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<VirtualNetwork>> GetWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkName, string expand = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates or updates a virtual network in the specified resource
/// group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkName'>
/// The name of the virtual network.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create or update virtual network
/// operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<VirtualNetwork>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkName, VirtualNetwork parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all virtual networks in a subscription.
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<VirtualNetwork>>> ListAllWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all virtual networks in a resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<VirtualNetwork>>> ListWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Checks whether a private IP address is available for use.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkName'>
/// The name of the virtual network.
/// </param>
/// <param name='ipAddress'>
/// The private IP address to be verified.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPAddressAvailabilityResult>> CheckIPAddressAvailabilityWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkName, string ipAddress = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Deletes the specified virtual network.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkName'>
/// The name of the virtual network.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates or updates a virtual network in the specified resource
/// group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkName'>
/// The name of the virtual network.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create or update virtual network
/// operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<VirtualNetwork>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkName, VirtualNetwork parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all virtual networks in a subscription.
/// </summary>
/// <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>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<VirtualNetwork>>> ListAllNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all virtual networks in a resource group.
/// </summary>
/// <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>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<VirtualNetwork>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using Microsoft.Xna.Framework.Net;
using Microsoft.Xna.Framework.Storage;
using Ivy;
namespace Ceres
{
/// <summary>
/// This is the main type for your game
/// </summary>
public class Ceres : Ivy.IvyGame, IMessageSender
{
///@todo add player management
protected Player m_playerOne;
private Timer EscapeTimer;
public Ceres()
{
}
protected override void Initialize()
{
base.Initialize();
WorldZone shaftZone = new WorldZone(@"levels/shaft");
// Add player
// TODO: Find out if components need to be individually initialized here,
// XNA may provide a way of doing this.
m_playerOne = new Player(this);
m_playerOne.Initialize();
ChangeZoneMsg addEntityMsg = new ChangeZoneMsg(this, shaftZone, m_playerOne, shaftZone.ZoneName, new Point(112, 16), 0);
MessageDispatcher.Get().SendMessage(addEntityMsg);
SetCurrentZone(shaftZone);
SetCameraTarget(m_playerOne);
// Create Camera
Rectangle screenRect = new Rectangle(0, 0, 800, 600);
int cameraHeight = 192;
int cameraWidth = 256;
Rectangle cameraBounds = new Rectangle(0, 0, cameraWidth, cameraHeight);
Camera.Initialize(shaftZone.Bounds, cameraBounds, screenRect);
CameraGel = Content.Load<Texture2D>(@"art/bg_layer_blueaura");
GelTint = new Color(0.0f, 0.0f, 1.0f, 0.0f);
EscapeTimer = new Timer(1000 * 60); // One minute to escape
EscapeTimer.OnTimeExpired += OnEscapeTimeExpired;
#region Register Input Handlers
// Movement
InputMgr.Get().RegisterGamePadButton(Buttons.LeftThumbstickLeft, OnGamePadDirectionEvent);
InputMgr.Get().RegisterGamePadButton(Buttons.LeftThumbstickRight, OnGamePadDirectionEvent);
InputMgr.Get().RegisterGamePadButton(Buttons.LeftThumbstickUp, OnGamePadDirectionEvent);
InputMgr.Get().RegisterGamePadButton(Buttons.LeftThumbstickDown, OnGamePadDirectionEvent);
InputMgr.Get().RegisterGamePadButton(Buttons.DPadLeft, OnGamePadDirectionEvent);
InputMgr.Get().RegisterGamePadButton(Buttons.DPadRight, OnGamePadDirectionEvent);
InputMgr.Get().RegisterGamePadButton(Buttons.DPadUp, OnGamePadDirectionEvent);
InputMgr.Get().RegisterGamePadButton(Buttons.DPadDown, OnGamePadDirectionEvent);
InputMgr.Get().RegisterKey(Keys.Up, OnKeyboardDirectionEvent);
InputMgr.Get().RegisterKey(Keys.Down, OnKeyboardDirectionEvent);
InputMgr.Get().RegisterKey(Keys.Left, OnKeyboardDirectionEvent);
InputMgr.Get().RegisterKey(Keys.Right, OnKeyboardDirectionEvent);
// Actions
InputMgr.Get().RegisterGamePadButton(Buttons.A, OnGamePadButtonEvent); // Run/Alt
InputMgr.Get().RegisterGamePadButton(Buttons.B, OnGamePadButtonEvent); // Jump
InputMgr.Get().RegisterGamePadButton(Buttons.Y, OnGamePadButtonEvent); // Fire Weapon
// Keyboard Actions
InputMgr.Get().RegisterKey(Keys.F, OnKeyboardEvent); // Fire
InputMgr.Get().RegisterKey(Keys.Space, OnKeyboardEvent); // Jump
// Debug Actions
InputMgr.Get().RegisterGamePadButton(Buttons.X, DebugOnGamePadButtonEvent);
#endregion
}
protected override void LoadContent()
{
base.LoadContent();
}
protected override void Update(GameTime gameTime)
{
if (EscapeTimer != null)
{
EscapeTimer.Update(gameTime);
}
base.Update(gameTime);
ConsoleStr += "Energy: " + m_playerOne.Energy + "\n";
if ((EscapeTimer != null) && (EscapeTimer.Paused == false))
{
ConsoleStr += "Self Destruct in " + (EscapeTimer.TimeRemaining / 1000) + " seconds";
}
}
protected override void Draw(GameTime gameTime)
{
base.Draw(gameTime);
}
public override void ReceiveMessage(Message msg)
{
if (msg.Type == MessageType.RidleyDead)
{
EscapeTimer.Paused = false;
GetCurrentZone().SetEscapeMode(true);
CameraGel = Content.Load<Texture2D>(@"art/bg_layer_redaura");
GelTint = new Color(1.0f, 0.0f, 0.0f, 0.0f);
}
else
{
base.ReceiveMessage(msg);
}
}
private void OnEscapeTimeExpired()
{
MessageDispatcher.Get().SendMessage(new Message(MessageType.EndGame, this, this));
}
#region Input Handlers
bool OnGamePadDirectionEvent(GamePadButtonEvent e)
{
// TODO: design some way to map events to messages to avoid switch code like this
if ((e.Button == Buttons.LeftThumbstickLeft) ||
(e.Button == Buttons.DPadLeft))
{
if (e.EventType == InputEventType.Pressed)
{
Message msg = new Message(MessageType.MoveLeft, this, m_playerOne);
MessageDispatcher.Get().SendMessage(msg);
}
else if ((e.EventType == InputEventType.Released) &&
(InputMgr.Get().GamePadState.IsButtonUp(Buttons.LeftThumbstickRight)) &&
(InputMgr.Get().GamePadState.IsButtonUp(Buttons.DPadRight)))
{
// TODO: need a better way of handling mutually exclusive button inputs
Message msg = new Message(MessageType.Stand, this, m_playerOne);
MessageDispatcher.Get().SendMessage(msg);
}
}
else if ((e.Button == Buttons.LeftThumbstickRight) ||
(e.Button == Buttons.DPadRight))
{
if (e.EventType == InputEventType.Pressed)
{
Message msg = new Message(MessageType.MoveRight, this, m_playerOne);
MessageDispatcher.Get().SendMessage(msg);
}
else if ((e.EventType == InputEventType.Released) &&
(InputMgr.Get().GamePadState.IsButtonUp(Buttons.LeftThumbstickLeft)) &&
(InputMgr.Get().GamePadState.IsButtonUp(Buttons.DPadLeft)))
{
// TODO: need a better way of handling mutually exclusive button inputs
Message msg = new Message(MessageType.Stand, this, m_playerOne);
MessageDispatcher.Get().SendMessage(msg);
}
}
return true;
}
bool OnKeyboardDirectionEvent(KeyboardEvent e)
{
// TODO: design some way to map events to messages to avoid switch code like this
// TODO: add some intelligence here to make sure that left and right keys are mutually exclusive
if (e.Key == Keys.Left)
{
if (e.EventType == InputEventType.Pressed)
{
Message msg = new Message(MessageType.MoveLeft, this, m_playerOne);
MessageDispatcher.Get().SendMessage(msg);
}
else if (e.EventType == InputEventType.Released)
{
Message msg = new Message(MessageType.Stand, this, m_playerOne);
MessageDispatcher.Get().SendMessage(msg);
}
}
else if (e.Key == Keys.Right)
{
if (e.EventType == InputEventType.Pressed)
{
Message msg = new Message(MessageType.MoveRight, this, m_playerOne);
MessageDispatcher.Get().SendMessage(msg);
}
else if (e.EventType == InputEventType.Released)
{
Message msg = new Message(MessageType.Stand, this, m_playerOne);
MessageDispatcher.Get().SendMessage(msg);
}
}
return true;
}
protected override bool OnGamePadButtonEvent(GamePadButtonEvent e)
{
bool ret = true;
if (e.Button == Buttons.B)
{
if (e.EventType == InputEventType.Pressed)
{
// start jump
Message msg = new Message(MessageType.Jump, this, m_playerOne);
MessageDispatcher.Get().SendMessage(msg);
}
else if (e.EventType == InputEventType.Released)
{
// end jump!
Message msg = new Message(MessageType.Fall, this, m_playerOne);
MessageDispatcher.Get().SendMessage(msg);
}
}
else if ((e.Button == Buttons.Y) && (e.EventType == InputEventType.Pressed))
{
// Fire
Message msg = new Message(MessageType.FireWeapon, this, m_playerOne);
MessageDispatcher.Get().SendMessage(msg);
}
else
{
ret = base.OnGamePadButtonEvent(e);
}
return ret;
}
bool DebugOnGamePadButtonEvent(GamePadButtonEvent e)
{
return true;
}
protected override bool OnKeyboardEvent(KeyboardEvent e)
{
bool ret = true;
// Jump!
if (e.Key == Keys.Space)
{
if (e.EventType == InputEventType.Pressed)
{
// start jump
Message msg = new Message(MessageType.Jump, this, m_playerOne);
MessageDispatcher.Get().SendMessage(msg);
}
else if (e.EventType == InputEventType.Released)
{
// end jump
Message msg = new Message(MessageType.Fall, this, m_playerOne);
MessageDispatcher.Get().SendMessage(msg);
}
}
else if ((e.Key == Keys.F) && (e.EventType == InputEventType.Pressed))
{
// Fire
Message msg = new Message(MessageType.FireWeapon, this, m_playerOne);
MessageDispatcher.Get().SendMessage(msg);
}
else
{
ret = base.OnKeyboardEvent(e);
}
return ret;
}
#endregion
}
}
| |
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* 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.Collections.Generic;
using System.Linq;
using QuantConnect.Data;
using QuantConnect.Data.UniverseSelection;
using QuantConnect.Interfaces;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Tests a custom filter function when creating an ETF constituents universe for SPY
/// </summary>
public class ETFConstituentUniverseFilterFunctionRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
private Dictionary<Symbol, ETFConstituentData> _etfConstituentData = new Dictionary<Symbol, ETFConstituentData>();
private Symbol _aapl;
private Symbol _spy;
private bool _filtered;
private bool _securitiesChanged;
private bool _receivedData;
private bool _etfRebalanced;
private int _rebalanceCount;
private int _rebalanceAssetCount;
/// <summary>
/// Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.
/// </summary>
public override void Initialize()
{
SetStartDate(2020, 12, 1);
SetEndDate(2021, 1, 31);
SetCash(100000);
UniverseSettings.Resolution = Resolution.Hour;
_spy = AddEquity("SPY", Resolution.Hour).Symbol;
_aapl = QuantConnect.Symbol.Create("AAPL", SecurityType.Equity, Market.USA);
AddUniverse(Universe.ETF(_spy, universeFilterFunc: FilterETFs));
}
/// <summary>
/// Filters ETFs, performing some sanity checks
/// </summary>
/// <param name="constituents">Constituents of the ETF universe added above</param>
/// <returns>Constituent Symbols to add to algorithm</returns>
/// <exception cref="ArgumentException">Constituents collection was not structured as expected</exception>
private IEnumerable<Symbol> FilterETFs(IEnumerable<ETFConstituentData> constituents)
{
var constituentsData = constituents.ToList();
_etfConstituentData = constituentsData.ToDictionary(x => x.Symbol, x => x);
var constituentsSymbols = constituentsData.Select(x => x.Symbol).ToList();
if (constituentsData.Count == 0)
{
throw new ArgumentException($"Constituents collection is empty on {UtcTime:yyyy-MM-dd HH:mm:ss.fff}");
}
if (!constituentsSymbols.Contains(_aapl))
{
throw new ArgumentException("AAPL is not in the constituents data provided to the algorithm");
}
var aaplData = constituentsData.Single(x => x.Symbol == _aapl);
if (aaplData.Weight == 0m)
{
throw new ArgumentException("AAPL weight is expected to be a non-zero value");
}
_filtered = true;
_etfRebalanced = true;
return constituentsSymbols;
}
/// <summary>
/// OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.
/// </summary>
/// <param name="data">Slice object keyed by symbol containing the stock data</param>
public override void OnData(Slice data)
{
if (!_filtered && data.Bars.Count != 0 && data.Bars.ContainsKey(_aapl))
{
throw new Exception("AAPL TradeBar data added to algorithm before constituent universe selection took place");
}
if (data.Bars.Count == 1 && data.Bars.ContainsKey(_spy))
{
return;
}
if (data.Bars.Count != 0 && !data.Bars.ContainsKey(_aapl))
{
throw new Exception($"Expected AAPL TradeBar data in OnData on {UtcTime:yyyy-MM-dd HH:mm:ss}");
}
_receivedData = true;
// If the ETF hasn't changed its weights, then let's not update our holdings
if (!_etfRebalanced)
{
return;
}
foreach (var bar in data.Bars.Values)
{
if (_etfConstituentData.TryGetValue(bar.Symbol, out var constituentData) &&
constituentData.Weight != null &&
constituentData.Weight >= 0.0001m)
{
// If the weight of the constituent is less than 1%, then it will be set to 1%
// If the weight of the constituent exceeds more than 5%, then it will be capped to 5%
// Otherwise, if the weight falls in between, then we use that value.
var boundedWeight = Math.Max(0.01m, Math.Min(constituentData.Weight.Value, 0.05m));
SetHoldings(bar.Symbol, boundedWeight);
if (_etfRebalanced)
{
_rebalanceCount++;
}
_etfRebalanced = false;
_rebalanceAssetCount++;
}
}
}
/// <summary>
/// Checks if new securities have been added to the algorithm after universe selection has occurred
/// </summary>
/// <param name="changes">Security changes</param>
/// <exception cref="ArgumentException">Expected number of stocks were not added to the algorithm</exception>
public override void OnSecuritiesChanged(SecurityChanges changes)
{
if (_filtered && !_securitiesChanged && changes.AddedSecurities.Count < 500)
{
throw new ArgumentException($"Added SPY S&P 500 ETF to algorithm, but less than 500 equities were loaded (added {changes.AddedSecurities.Count} securities)");
}
_securitiesChanged = true;
}
/// <summary>
/// Ensures that all expected events were triggered by the end of the algorithm
/// </summary>
/// <exception cref="Exception">An expected event didn't happen</exception>
public override void OnEndOfAlgorithm()
{
if (_rebalanceCount != 1)
{
throw new Exception($"Expected 1 rebalance, instead rebalanced: {_rebalanceCount}");
}
if (_rebalanceAssetCount != 4)
{
throw new Exception($"Invested in {_rebalanceAssetCount} assets (expected 4)");
}
if (!_filtered)
{
throw new Exception("Universe selection was never triggered");
}
if (!_securitiesChanged)
{
throw new Exception("Security changes never propagated to the algorithm");
}
if (!_receivedData)
{
throw new Exception("Data was never loaded for the S&P 500 constituent AAPL");
}
}
/// <summary>
/// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm.
/// </summary>
public bool CanRunLocally { get; } = true;
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public Language[] Languages { get; } = { Language.CSharp, Language.Python };
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "4"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "2.118%"},
{"Drawdown", "0.600%"},
{"Expectancy", "0"},
{"Net Profit", "0.343%"},
{"Sharpe Ratio", "1.03"},
{"Probabilistic Sharpe Ratio", "50.428%"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "0.008"},
{"Beta", "0.098"},
{"Annual Standard Deviation", "0.014"},
{"Annual Variance", "0"},
{"Information Ratio", "-0.611"},
{"Tracking Error", "0.096"},
{"Treynor Ratio", "0.151"},
{"Total Fees", "$4.00"},
{"Estimated Strategy Capacity", "$100000000.00"},
{"Lowest Capacity Asset", "AIG R735QTJ8XC9X"},
{"Fitness Score", "0.001"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "4.028"},
{"Return Over Maximum Drawdown", "7.694"},
{"Portfolio Turnover", "0.001"},
{"Total Insights Generated", "0"},
{"Total Insights Closed", "0"},
{"Total Insights Analysis Completed", "0"},
{"Long Insight Count", "0"},
{"Short Insight Count", "0"},
{"Long/Short Ratio", "100%"},
{"Estimated Monthly Alpha Value", "$0"},
{"Total Accumulated Estimated Alpha Value", "$0"},
{"Mean Population Estimated Insight Value", "$0"},
{"Mean Population Direction", "0%"},
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "12bc2f33ccf788ffb2c0a57a68199485"}
};
}
}
| |
using System;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Xml;
using System.Xml.Serialization;
using SubSonic;
using SubSonic.Utilities;
namespace DalSic
{
/// <summary>
/// Strongly-typed collection for the PnParametro class.
/// </summary>
[Serializable]
public partial class PnParametroCollection : ActiveList<PnParametro, PnParametroCollection>
{
public PnParametroCollection() {}
/// <summary>
/// Filters an existing collection based on the set criteria. This is an in-memory filter
/// Thanks to developingchris for this!
/// </summary>
/// <returns>PnParametroCollection</returns>
public PnParametroCollection Filter()
{
for (int i = this.Count - 1; i > -1; i--)
{
PnParametro o = this[i];
foreach (SubSonic.Where w in this.wheres)
{
bool remove = false;
System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName);
if (pi.CanRead)
{
object val = pi.GetValue(o, null);
switch (w.Comparison)
{
case SubSonic.Comparison.Equals:
if (!val.Equals(w.ParameterValue))
{
remove = true;
}
break;
}
}
if (remove)
{
this.Remove(o);
break;
}
}
}
return this;
}
}
/// <summary>
/// This is an ActiveRecord class which wraps the PN_parametros table.
/// </summary>
[Serializable]
public partial class PnParametro : ActiveRecord<PnParametro>, IActiveRecord
{
#region .ctors and Default Settings
public PnParametro()
{
SetSQLProps();
InitSetDefaults();
MarkNew();
}
private void InitSetDefaults() { SetDefaults(); }
public PnParametro(bool useDatabaseDefaults)
{
SetSQLProps();
if(useDatabaseDefaults)
ForceDefaults();
MarkNew();
}
public PnParametro(object keyID)
{
SetSQLProps();
InitSetDefaults();
LoadByKey(keyID);
}
public PnParametro(string columnName, object columnValue)
{
SetSQLProps();
InitSetDefaults();
LoadByParam(columnName,columnValue);
}
protected static void SetSQLProps() { GetTableSchema(); }
#endregion
#region Schema and Query Accessor
public static Query CreateQuery() { return new Query(Schema); }
public static TableSchema.Table Schema
{
get
{
if (BaseSchema == null)
SetSQLProps();
return BaseSchema;
}
}
private static void GetTableSchema()
{
if(!IsSchemaInitialized)
{
//Schema declaration
TableSchema.Table schema = new TableSchema.Table("PN_parametros", TableType.Table, DataService.GetInstance("sicProvider"));
schema.Columns = new TableSchema.TableColumnCollection();
schema.SchemaName = @"dbo";
//columns
TableSchema.TableColumn colvarParametro = new TableSchema.TableColumn(schema);
colvarParametro.ColumnName = "parametro";
colvarParametro.DataType = DbType.AnsiString;
colvarParametro.MaxLength = -1;
colvarParametro.AutoIncrement = false;
colvarParametro.IsNullable = true;
colvarParametro.IsPrimaryKey = false;
colvarParametro.IsForeignKey = false;
colvarParametro.IsReadOnly = false;
colvarParametro.DefaultSetting = @"";
colvarParametro.ForeignKeyTableName = "";
schema.Columns.Add(colvarParametro);
TableSchema.TableColumn colvarValor = new TableSchema.TableColumn(schema);
colvarValor.ColumnName = "valor";
colvarValor.DataType = DbType.AnsiString;
colvarValor.MaxLength = -1;
colvarValor.AutoIncrement = false;
colvarValor.IsNullable = true;
colvarValor.IsPrimaryKey = false;
colvarValor.IsForeignKey = false;
colvarValor.IsReadOnly = false;
colvarValor.DefaultSetting = @"";
colvarValor.ForeignKeyTableName = "";
schema.Columns.Add(colvarValor);
TableSchema.TableColumn colvarComentario = new TableSchema.TableColumn(schema);
colvarComentario.ColumnName = "comentario";
colvarComentario.DataType = DbType.AnsiString;
colvarComentario.MaxLength = -1;
colvarComentario.AutoIncrement = false;
colvarComentario.IsNullable = true;
colvarComentario.IsPrimaryKey = false;
colvarComentario.IsForeignKey = false;
colvarComentario.IsReadOnly = false;
colvarComentario.DefaultSetting = @"";
colvarComentario.ForeignKeyTableName = "";
schema.Columns.Add(colvarComentario);
TableSchema.TableColumn colvarIdParametro = new TableSchema.TableColumn(schema);
colvarIdParametro.ColumnName = "id_parametro";
colvarIdParametro.DataType = DbType.Int32;
colvarIdParametro.MaxLength = 0;
colvarIdParametro.AutoIncrement = true;
colvarIdParametro.IsNullable = false;
colvarIdParametro.IsPrimaryKey = true;
colvarIdParametro.IsForeignKey = false;
colvarIdParametro.IsReadOnly = false;
colvarIdParametro.DefaultSetting = @"";
colvarIdParametro.ForeignKeyTableName = "";
schema.Columns.Add(colvarIdParametro);
BaseSchema = schema;
//add this schema to the provider
//so we can query it later
DataService.Providers["sicProvider"].AddSchema("PN_parametros",schema);
}
}
#endregion
#region Props
[XmlAttribute("Parametro")]
[Bindable(true)]
public string Parametro
{
get { return GetColumnValue<string>(Columns.Parametro); }
set { SetColumnValue(Columns.Parametro, value); }
}
[XmlAttribute("Valor")]
[Bindable(true)]
public string Valor
{
get { return GetColumnValue<string>(Columns.Valor); }
set { SetColumnValue(Columns.Valor, value); }
}
[XmlAttribute("Comentario")]
[Bindable(true)]
public string Comentario
{
get { return GetColumnValue<string>(Columns.Comentario); }
set { SetColumnValue(Columns.Comentario, value); }
}
[XmlAttribute("IdParametro")]
[Bindable(true)]
public int IdParametro
{
get { return GetColumnValue<int>(Columns.IdParametro); }
set { SetColumnValue(Columns.IdParametro, value); }
}
#endregion
//no foreign key tables defined (0)
//no ManyToMany tables defined (0)
#region ObjectDataSource support
/// <summary>
/// Inserts a record, can be used with the Object Data Source
/// </summary>
public static void Insert(string varParametro,string varValor,string varComentario)
{
PnParametro item = new PnParametro();
item.Parametro = varParametro;
item.Valor = varValor;
item.Comentario = varComentario;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
/// <summary>
/// Updates a record, can be used with the Object Data Source
/// </summary>
public static void Update(string varParametro,string varValor,string varComentario,int varIdParametro)
{
PnParametro item = new PnParametro();
item.Parametro = varParametro;
item.Valor = varValor;
item.Comentario = varComentario;
item.IdParametro = varIdParametro;
item.IsNew = false;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
#endregion
#region Typed Columns
public static TableSchema.TableColumn ParametroColumn
{
get { return Schema.Columns[0]; }
}
public static TableSchema.TableColumn ValorColumn
{
get { return Schema.Columns[1]; }
}
public static TableSchema.TableColumn ComentarioColumn
{
get { return Schema.Columns[2]; }
}
public static TableSchema.TableColumn IdParametroColumn
{
get { return Schema.Columns[3]; }
}
#endregion
#region Columns Struct
public struct Columns
{
public static string Parametro = @"parametro";
public static string Valor = @"valor";
public static string Comentario = @"comentario";
public static string IdParametro = @"id_parametro";
}
#endregion
#region Update PK Collections
#endregion
#region Deep Save
#endregion
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Reflection.Metadata;
using Microsoft.DiaSymReader;
namespace Microsoft.CodeAnalysis.ExpressionEvaluator
{
internal partial class MethodDebugInfo<TTypeSymbol, TLocalSymbol>
{
public unsafe static MethodDebugInfo<TTypeSymbol, TLocalSymbol> ReadMethodDebugInfo(
ISymUnmanagedReader3 symReader,
EESymbolProvider<TTypeSymbol, TLocalSymbol> symbolProviderOpt, // TODO: only null in DTEE case where we looking for default namesapace
int methodToken,
int methodVersion,
int ilOffset,
bool isVisualBasicMethod)
{
// no symbols
if (symReader == null)
{
return None;
}
var symReader4 = symReader as ISymUnmanagedReader4;
if (symReader4 != null) // TODO: VB Portable PDBs
{
byte* metadata;
int size;
// TODO: version
int hr = symReader4.GetPortableDebugMetadata(out metadata, out size);
SymUnmanagedReaderExtensions.ThrowExceptionForHR(hr);
if (metadata != null)
{
var mdReader = new MetadataReader(metadata, size);
try
{
return ReadFromPortable(mdReader, methodToken, ilOffset, symbolProviderOpt, isVisualBasicMethod);
}
catch (BadImageFormatException)
{
// bad CDI, ignore
return None;
}
}
}
var allScopes = ArrayBuilder<ISymUnmanagedScope>.GetInstance();
var containingScopes = ArrayBuilder<ISymUnmanagedScope>.GetInstance();
try
{
ImmutableArray<HoistedLocalScopeRecord> hoistedLocalScopeRecords;
ImmutableArray<ImmutableArray<ImportRecord>> importRecordGroups;
ImmutableArray<ExternAliasRecord> externAliasRecords;
ImmutableDictionary<int, ImmutableArray<bool>> dynamicLocalMap;
ImmutableDictionary<string, ImmutableArray<bool>> dynamicLocalConstantMap;
string defaultNamespaceName;
var symMethod = symReader.GetMethodByVersion(methodToken, methodVersion);
if (symMethod != null)
{
symMethod.GetAllScopes(allScopes, containingScopes, ilOffset, isScopeEndInclusive: isVisualBasicMethod);
}
if (isVisualBasicMethod)
{
ReadVisualBasicImportsDebugInfo(
symReader,
methodToken,
methodVersion,
out importRecordGroups,
out defaultNamespaceName);
hoistedLocalScopeRecords = ImmutableArray<HoistedLocalScopeRecord>.Empty;
externAliasRecords = ImmutableArray<ExternAliasRecord>.Empty;
dynamicLocalMap = null;
dynamicLocalConstantMap = null;
}
else
{
Debug.Assert(symbolProviderOpt != null);
ReadCSharpNativeImportsInfo(
symReader,
symbolProviderOpt,
methodToken,
methodVersion,
out importRecordGroups,
out externAliasRecords);
ReadCSharpNativeCustomDebugInfo(
symReader,
methodToken,
methodVersion,
allScopes,
out hoistedLocalScopeRecords,
out dynamicLocalMap,
out dynamicLocalConstantMap);
defaultNamespaceName = "";
}
var constantsBuilder = ArrayBuilder<TLocalSymbol>.GetInstance();
if (symbolProviderOpt != null) // TODO
{
GetConstants(constantsBuilder, symbolProviderOpt, containingScopes, dynamicLocalConstantMap);
}
var reuseSpan = GetReuseSpan(allScopes, ilOffset, isVisualBasicMethod);
return new MethodDebugInfo<TTypeSymbol, TLocalSymbol>(
hoistedLocalScopeRecords,
importRecordGroups,
externAliasRecords,
dynamicLocalMap,
defaultNamespaceName,
containingScopes.GetLocalNames(),
constantsBuilder.ToImmutableAndFree(),
reuseSpan);
}
catch (InvalidOperationException)
{
// bad CDI, ignore
return None;
}
finally
{
allScopes.Free();
containingScopes.Free();
}
}
private static void ReadCSharpNativeImportsInfo(
ISymUnmanagedReader3 reader,
EESymbolProvider<TTypeSymbol, TLocalSymbol> symbolProvider,
int methodToken,
int methodVersion,
out ImmutableArray<ImmutableArray<ImportRecord>> importRecordGroups,
out ImmutableArray<ExternAliasRecord> externAliasRecords)
{
ImmutableArray<string> externAliasStrings;
var importStringGroups = reader.GetCSharpGroupedImportStrings(methodToken, methodVersion, out externAliasStrings);
Debug.Assert(importStringGroups.IsDefault == externAliasStrings.IsDefault);
ArrayBuilder<ImmutableArray<ImportRecord>> importRecordGroupBuilder = null;
ArrayBuilder<ExternAliasRecord> externAliasRecordBuilder = null;
if (!importStringGroups.IsDefault)
{
importRecordGroupBuilder = ArrayBuilder<ImmutableArray<ImportRecord>>.GetInstance(importStringGroups.Length);
foreach (var importStringGroup in importStringGroups)
{
var groupBuilder = ArrayBuilder<ImportRecord>.GetInstance(importStringGroup.Length);
foreach (var importString in importStringGroup)
{
ImportRecord record;
if (TryCreateImportRecordFromCSharpImportString(symbolProvider, importString, out record))
{
groupBuilder.Add(record);
}
else
{
Debug.WriteLine($"Failed to parse import string {importString}");
}
}
importRecordGroupBuilder.Add(groupBuilder.ToImmutableAndFree());
}
if (!externAliasStrings.IsDefault)
{
externAliasRecordBuilder = ArrayBuilder<ExternAliasRecord>.GetInstance(externAliasStrings.Length);
foreach (string externAliasString in externAliasStrings)
{
string alias;
string externAlias;
string target;
ImportTargetKind kind;
if (!CustomDebugInfoReader.TryParseCSharpImportString(externAliasString, out alias, out externAlias, out target, out kind))
{
Debug.WriteLine($"Unable to parse extern alias '{externAliasString}'");
continue;
}
Debug.Assert(kind == ImportTargetKind.Assembly, "Programmer error: How did a non-assembly get in the extern alias list?");
Debug.Assert(alias != null); // Name of the extern alias.
Debug.Assert(externAlias == null); // Not used.
Debug.Assert(target != null); // Name of the target assembly.
AssemblyIdentity targetIdentity;
if (!AssemblyIdentity.TryParseDisplayName(target, out targetIdentity))
{
Debug.WriteLine($"Unable to parse target of extern alias '{externAliasString}'");
continue;
}
externAliasRecordBuilder.Add(new ExternAliasRecord(alias, targetIdentity));
}
}
}
importRecordGroups = importRecordGroupBuilder?.ToImmutableAndFree() ?? ImmutableArray<ImmutableArray<ImportRecord>>.Empty;
externAliasRecords = externAliasRecordBuilder?.ToImmutableAndFree() ?? ImmutableArray<ExternAliasRecord>.Empty;
}
private static bool TryCreateImportRecordFromCSharpImportString(EESymbolProvider<TTypeSymbol, TLocalSymbol> symbolProvider, string importString, out ImportRecord record)
{
ImportTargetKind targetKind;
string externAlias;
string alias;
string targetString;
if (CustomDebugInfoReader.TryParseCSharpImportString(importString, out alias, out externAlias, out targetString, out targetKind))
{
ITypeSymbol type = null;
if (targetKind == ImportTargetKind.Type)
{
type = symbolProvider.GetTypeSymbolForSerializedType(targetString);
targetString = null;
}
record = new ImportRecord(
targetKind: targetKind,
alias: alias,
targetType: type,
targetString: targetString,
targetAssembly: null,
targetAssemblyAlias: externAlias);
return true;
}
record = default(ImportRecord);
return false;
}
private static void ReadCSharpNativeCustomDebugInfo(
ISymUnmanagedReader3 reader,
int methodToken,
int methodVersion,
IEnumerable<ISymUnmanagedScope> scopes,
out ImmutableArray<HoistedLocalScopeRecord> hoistedLocalScopeRecords,
out ImmutableDictionary<int, ImmutableArray<bool>> dynamicLocalMap,
out ImmutableDictionary<string, ImmutableArray<bool>> dynamicLocalConstantMap)
{
hoistedLocalScopeRecords = ImmutableArray<HoistedLocalScopeRecord>.Empty;
dynamicLocalMap = ImmutableDictionary<int, ImmutableArray<bool>>.Empty;
dynamicLocalConstantMap = ImmutableDictionary<string, ImmutableArray<bool>>.Empty;
byte[] customDebugInfoBytes = reader.GetCustomDebugInfoBytes(methodToken, methodVersion);
if (customDebugInfoBytes == null)
{
return;
}
var customDebugInfoRecord = CustomDebugInfoReader.TryGetCustomDebugInfoRecord(customDebugInfoBytes, CustomDebugInfoKind.StateMachineHoistedLocalScopes);
if (!customDebugInfoRecord.IsDefault)
{
hoistedLocalScopeRecords = CustomDebugInfoReader.DecodeStateMachineHoistedLocalScopesRecord(customDebugInfoRecord)
.SelectAsArray(s => new HoistedLocalScopeRecord(s.StartOffset, s.EndOffset - s.StartOffset + 1));
}
CustomDebugInfoReader.GetCSharpDynamicLocalInfo(
customDebugInfoBytes,
methodToken,
methodVersion,
scopes,
out dynamicLocalMap,
out dynamicLocalConstantMap);
}
private static void ReadVisualBasicImportsDebugInfo(
ISymUnmanagedReader reader,
int methodToken,
int methodVersion,
out ImmutableArray<ImmutableArray<ImportRecord>> importRecordGroups,
out string defaultNamespaceName)
{
importRecordGroups = ImmutableArray<ImmutableArray<ImportRecord>>.Empty;
var importStrings = reader.GetVisualBasicImportStrings(methodToken, methodVersion);
if (importStrings.IsDefault)
{
defaultNamespaceName = "";
return;
}
defaultNamespaceName = null;
var projectLevelImportRecords = ArrayBuilder<ImportRecord>.GetInstance();
var fileLevelImportRecords = ArrayBuilder<ImportRecord>.GetInstance();
foreach (string importString in importStrings)
{
Debug.Assert(importString != null);
if (importString.Length > 0 && importString[0] == '*')
{
string alias = null;
string target = null;
ImportTargetKind kind = 0;
ImportScope scope = 0;
if (!CustomDebugInfoReader.TryParseVisualBasicImportString(importString, out alias, out target, out kind, out scope))
{
Debug.WriteLine($"Unable to parse import string '{importString}'");
continue;
}
else if (kind == ImportTargetKind.Defunct)
{
continue;
}
Debug.Assert(alias == null); // The default namespace is never aliased.
Debug.Assert(target != null);
Debug.Assert(kind == ImportTargetKind.DefaultNamespace);
// We only expect to see one of these, but it looks like ProcedureContext::LoadImportsAndDefaultNamespaceNormal
// implicitly uses the last one if there are multiple.
Debug.Assert(defaultNamespaceName == null);
defaultNamespaceName = target;
}
else
{
ImportRecord importRecord;
ImportScope scope = 0;
if (TryCreateImportRecordFromVisualBasicImportString(importString, out importRecord, out scope))
{
if (scope == ImportScope.Project)
{
projectLevelImportRecords.Add(importRecord);
}
else
{
Debug.Assert(scope == ImportScope.File || scope == ImportScope.Unspecified);
fileLevelImportRecords.Add(importRecord);
}
}
else
{
Debug.WriteLine($"Failed to parse import string {importString}");
}
}
}
importRecordGroups = ImmutableArray.Create(
fileLevelImportRecords.ToImmutableAndFree(),
projectLevelImportRecords.ToImmutableAndFree());
defaultNamespaceName = defaultNamespaceName ?? "";
}
private static bool TryCreateImportRecordFromVisualBasicImportString(string importString, out ImportRecord record, out ImportScope scope)
{
ImportTargetKind targetKind;
string alias;
string targetString;
if (CustomDebugInfoReader.TryParseVisualBasicImportString(importString, out alias, out targetString, out targetKind, out scope))
{
record = new ImportRecord(
targetKind: targetKind,
alias: alias,
targetType: null,
targetString: targetString,
targetAssembly: null,
targetAssemblyAlias: null);
return true;
}
record = default(ImportRecord);
return false;
}
private static ILSpan GetReuseSpan(ArrayBuilder<ISymUnmanagedScope> scopes, int ilOffset, bool isEndInclusive)
{
return MethodContextReuseConstraints.CalculateReuseSpan(
ilOffset,
ILSpan.MaxValue,
scopes.Select(scope => new ILSpan((uint)scope.GetStartOffset(), (uint)(scope.GetEndOffset() + (isEndInclusive ? 1 : 0)))));
}
public static void GetConstants(
ArrayBuilder<TLocalSymbol> builder,
EESymbolProvider<TTypeSymbol, TLocalSymbol> symbolProvider,
ArrayBuilder<ISymUnmanagedScope> scopes,
ImmutableDictionary<string, ImmutableArray<bool>> dynamicLocalConstantMapOpt)
{
foreach (var scope in scopes)
{
foreach (var constant in scope.GetConstants())
{
string name = constant.GetName();
object rawValue = constant.GetValue();
var signature = constant.GetSignature().ToImmutableArray();
TTypeSymbol type;
try
{
type = symbolProvider.DecodeLocalVariableType(signature);
}
catch (Exception e) when (e is UnsupportedSignatureContent || e is BadImageFormatException)
{
// ignore
continue;
}
if (type.Kind == SymbolKind.ErrorType)
{
continue;
}
ConstantValue constantValue = PdbHelpers.GetSymConstantValue(type, rawValue);
// TODO (https://github.com/dotnet/roslyn/issues/1815): report error properly when the symbol is used
if (constantValue.IsBad)
{
continue;
}
var dynamicFlags = default(ImmutableArray<bool>);
dynamicLocalConstantMapOpt?.TryGetValue(name, out dynamicFlags);
builder.Add(symbolProvider.GetLocalConstant(name, type, constantValue, dynamicFlags));
}
}
}
/// <summary>
/// Returns symbols for the locals emitted in the original method,
/// based on the local signatures from the IL and the names and
/// slots from the PDB. The actual locals are needed to ensure the
/// local slots in the generated method match the original.
/// </summary>
public static void GetLocals(
ArrayBuilder<TLocalSymbol> builder,
EESymbolProvider<TTypeSymbol, TLocalSymbol> symbolProvider,
ImmutableArray<string> names,
ImmutableArray<LocalInfo<TTypeSymbol>> localInfo,
ImmutableDictionary<int, ImmutableArray<bool>> dynamicLocalMapOpt)
{
if (localInfo.Length == 0)
{
// When debugging a .dmp without a heap, localInfo will be empty although
// names may be non-empty if there is a PDB. Since there's no type info, the
// locals are dropped. Note this means the local signature of any generated
// method will not match the original signature, so new locals will overlap
// original locals. That is ok since there is no live process for the debugger
// to update (any modified values exist in the debugger only).
return;
}
Debug.Assert(localInfo.Length >= names.Length);
for (int i = 0; i < localInfo.Length; i++)
{
string name = (i < names.Length) ? names[i] : null;
var dynamicFlags = default(ImmutableArray<bool>);
dynamicLocalMapOpt?.TryGetValue(i, out dynamicFlags);
builder.Add(symbolProvider.GetLocalVariable(name, i, localInfo[i], dynamicFlags));
}
}
}
}
| |
// 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.
//
// This file defines many COM dual interfaces which are legacy and,
// cannot be changed. Tolerate possible obsoletion.
//
#pragma warning disable CS0618 // Type or member is obsolete
namespace System.DirectoryServices.AccountManagement
{
using System.Runtime.InteropServices;
using System;
using System.Security;
using System.Text;
internal class Constants
{
private Constants() { }
internal static byte[] GUID_USERS_CONTAINER_BYTE = new byte[] { 0xa9, 0xd1, 0xca, 0x15, 0x76, 0x88, 0x11, 0xd1, 0xad, 0xed, 0x00, 0xc0, 0x4f, 0xd8, 0xd5, 0xcd };
internal static byte[] GUID_COMPUTRS_CONTAINER_BYTE = new byte[] { 0xaa, 0x31, 0x28, 0x25, 0x76, 0x88, 0x11, 0xd1, 0xad, 0xed, 0x00, 0xc0, 0x4f, 0xd8, 0xd5, 0xcd };
internal static byte[] GUID_FOREIGNSECURITYPRINCIPALS_CONTAINER_BYTE = new byte[] { 0x22, 0xb7, 0x0c, 0x67, 0xd5, 0x6e, 0x4e, 0xfb, 0x91, 0xe9, 0x30, 0x0f, 0xca, 0x3d, 0xc1, 0xaa };
}
internal class SafeNativeMethods
{
// To stop the compiler from autogenerating a constructor for this class
private SafeNativeMethods() { }
[DllImport("kernel32.dll", CallingConvention = CallingConvention.StdCall, EntryPoint = "GetCurrentThreadId", CharSet = CharSet.Unicode)]
static extern public int GetCurrentThreadId();
[DllImport("advapi32.dll", CallingConvention = CallingConvention.StdCall, EntryPoint = "LsaNtStatusToWinError", CharSet = CharSet.Unicode)]
static extern public int LsaNtStatusToWinError(int ntStatus);
}
internal class UnsafeNativeMethods
{
// To stop the compiler from autogenerating a constructor for this class
private UnsafeNativeMethods() { }
[DllImport(ExternDll.Activeds, ExactSpelling = true, EntryPoint = "ADsOpenObject", CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
private static extern int IntADsOpenObject(string path, string userName, string password, int flags, [In, Out] ref Guid iid, [Out, MarshalAs(UnmanagedType.Interface)] out object ppObject);
public static int ADsOpenObject(string path, string userName, string password, int flags, [In, Out] ref Guid iid, [Out, MarshalAs(UnmanagedType.Interface)] out object ppObject)
{
try
{
return IntADsOpenObject(path, userName, password, flags, ref iid, out ppObject);
}
catch (EntryPointNotFoundException)
{
throw new InvalidOperationException(SR.AdsiNotInstalled);
}
}
//
// ADSI Interopt
//
internal enum ADS_PASSWORD_ENCODING_ENUM
{
ADS_PASSWORD_ENCODE_REQUIRE_SSL = 0,
ADS_PASSWORD_ENCODE_CLEAR = 1
}
internal enum ADS_OPTION_ENUM
{
ADS_OPTION_SERVERNAME = 0,
ADS_OPTION_REFERRALS = 1,
ADS_OPTION_PAGE_SIZE = 2,
ADS_OPTION_SECURITY_MASK = 3,
ADS_OPTION_MUTUAL_AUTH_STATUS = 4,
ADS_OPTION_QUOTA = 5,
ADS_OPTION_PASSWORD_PORTNUMBER = 6,
ADS_OPTION_PASSWORD_METHOD = 7,
ADS_OPTION_ACCUMULATIVE_MODIFICATION = 8,
ADS_OPTION_SKIP_SID_LOOKUP = 9
}
[ComImport, Guid("7E99C0A2-F935-11D2-BA96-00C04FB6D0D1"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsDual)]
public interface IADsDNWithBinary
{
object BinaryValue { get; set; }
string DNString { get; set; }
}
[ComImport, Guid("9068270b-0939-11D1-8be1-00c04fd8d503"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsDual)]
public interface IADsLargeInteger
{
int HighPart { get; set; }
int LowPart { get; set; }
}
[ComImport, Guid("927971f5-0939-11d1-8be1-00c04fd8d503")]
public class ADsLargeInteger
{
}
[ComImport, Guid("46f14fda-232b-11d1-a808-00c04fd8d5a8"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsDual)]
public interface IAdsObjectOptions
{
[return: MarshalAs(UnmanagedType.Struct)]
object GetOption(
[In]
int option);
void PutOption(
[In]
int option,
[In, MarshalAs(UnmanagedType.Struct)]
object vProp);
}
[ComImport, Guid("FD8256D0-FD15-11CE-ABC4-02608C9E7553"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsDual)]
public interface IADs
{
string Name
{
[return: MarshalAs(UnmanagedType.BStr)]
get;
}
string Class
{
[return: MarshalAs(UnmanagedType.BStr)]
get;
}
string GUID
{
[return: MarshalAs(UnmanagedType.BStr)]
get;
}
string ADsPath
{
[return: MarshalAs(UnmanagedType.BStr)]
get;
}
string Parent
{
[return: MarshalAs(UnmanagedType.BStr)]
get;
}
string Schema
{
[return: MarshalAs(UnmanagedType.BStr)]
get;
}
void GetInfo();
void SetInfo();
[return: MarshalAs(UnmanagedType.Struct)]
object Get(
[In, MarshalAs(UnmanagedType.BStr)]
string bstrName);
void Put(
[In, MarshalAs(UnmanagedType.BStr)]
string bstrName,
[In, MarshalAs(UnmanagedType.Struct)]
object vProp);
[return: MarshalAs(UnmanagedType.Struct)]
object GetEx(
[In, MarshalAs(UnmanagedType.BStr)]
string bstrName);
void PutEx(
[In, MarshalAs(UnmanagedType.U4)]
int lnControlCode,
[In, MarshalAs(UnmanagedType.BStr)]
string bstrName,
[In, MarshalAs(UnmanagedType.Struct)]
object vProp);
void GetInfoEx(
[In, MarshalAs(UnmanagedType.Struct)]
object vProperties,
[In, MarshalAs(UnmanagedType.U4)]
int lnReserved);
}
[ComImport, Guid("27636b00-410f-11cf-b1ff-02608c9e7553"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsDual)]
public interface IADsGroup
{
string Name
{
[return: MarshalAs(UnmanagedType.BStr)]
get;
}
string Class
{
[return: MarshalAs(UnmanagedType.BStr)]
get;
}
string GUID
{
[return: MarshalAs(UnmanagedType.BStr)]
get;
}
string ADsPath
{
[return: MarshalAs(UnmanagedType.BStr)]
get;
}
string Parent
{
[return: MarshalAs(UnmanagedType.BStr)]
get;
}
string Schema
{
[return: MarshalAs(UnmanagedType.BStr)]
get;
}
void GetInfo();
void SetInfo();
[return: MarshalAs(UnmanagedType.Struct)]
object Get(
[In, MarshalAs(UnmanagedType.BStr)]
string bstrName);
void Put(
[In, MarshalAs(UnmanagedType.BStr)]
string bstrName,
[In, MarshalAs(UnmanagedType.Struct)]
object vProp);
[return: MarshalAs(UnmanagedType.Struct)]
object GetEx(
[In, MarshalAs(UnmanagedType.BStr)]
string bstrName);
void PutEx(
[In, MarshalAs(UnmanagedType.U4)]
int lnControlCode,
[In, MarshalAs(UnmanagedType.BStr)]
string bstrName,
[In, MarshalAs(UnmanagedType.Struct)]
object vProp);
void GetInfoEx(
[In, MarshalAs(UnmanagedType.Struct)]
object vProperties,
[In, MarshalAs(UnmanagedType.U4)]
int lnReserved);
string Description
{
[return: MarshalAs(UnmanagedType.BStr)]
get;
[param: MarshalAs(UnmanagedType.BStr)]
set;
}
IADsMembers Members();
bool IsMember([In, MarshalAs(UnmanagedType.BStr)] string bstrMember);
void Add([In, MarshalAs(UnmanagedType.BStr)] string bstrNewItem);
void Remove([In, MarshalAs(UnmanagedType.BStr)] string bstrItemToBeRemoved);
}
[ComImport, Guid("451a0030-72ec-11cf-b03b-00aa006e0975"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsDual)]
public interface IADsMembers
{
int Count
{
[return: MarshalAs(UnmanagedType.U4)]
get;
}
object _NewEnum
{
[return: MarshalAs(UnmanagedType.Interface)]
get;
}
object Filter
{
[return: MarshalAs(UnmanagedType.Struct)]
get;
[param: MarshalAs(UnmanagedType.Struct)]
set;
}
}
[ComImport, Guid("080d0d78-f421-11d0-a36e-00c04fb950dc")]
public class Pathname
{
}
[ComImport, Guid("d592aed4-f420-11d0-a36e-00c04fb950dc"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsDual)]
public interface IADsPathname
{
void Set(
[In, MarshalAs(UnmanagedType.BStr)] string bstrADsPath,
[In, MarshalAs(UnmanagedType.U4)] int lnSetType
);
void SetDisplayType(
[In, MarshalAs(UnmanagedType.U4)] int lnDisplayType
);
[return: MarshalAs(UnmanagedType.BStr)]
string Retrieve(
[In, MarshalAs(UnmanagedType.U4)] int lnFormatType
);
[return: MarshalAs(UnmanagedType.U4)]
int GetNumElements();
[return: MarshalAs(UnmanagedType.BStr)]
string
GetElement(
[In, MarshalAs(UnmanagedType.U4)] int lnElementIndex
);
void AddLeafElement(
[In, MarshalAs(UnmanagedType.BStr)] string bstrLeafElement
);
void RemoveLeafElement();
[return: MarshalAs(UnmanagedType.Struct)]
object CopyPath();
[return: MarshalAs(UnmanagedType.BStr)]
string GetEscapedElement(
[In, MarshalAs(UnmanagedType.U4)] int lnReserved,
[In, MarshalAs(UnmanagedType.BStr)] string bstrInStr
);
int EscapedMode
{
[return: MarshalAs(UnmanagedType.U4)]
get;
[param: MarshalAs(UnmanagedType.U4)]
set;
}
}
//
// DSInteropt
//
/*
typedef enum
{
DsRole_RoleStandaloneWorkstation,
DsRole_RoleMemberWorkstation,
DsRole_RoleStandaloneServer,
DsRole_RoleMemberServer,
DsRole_RoleBackupDomainController,
DsRole_RolePrimaryDomainController,
DsRole_WorkstationWithSharedAccountDomain,
DsRole_ServerWithSharedAccountDomain,
DsRole_MemberWorkstationWithSharedAccountDomain,
DsRole_MemberServerWithSharedAccountDomain
}DSROLE_MACHINE_ROLE;
*/
public enum DSROLE_MACHINE_ROLE
{
DsRole_RoleStandaloneWorkstation,
DsRole_RoleMemberWorkstation,
DsRole_RoleStandaloneServer,
DsRole_RoleMemberServer,
DsRole_RoleBackupDomainController,
DsRole_RolePrimaryDomainController,
DsRole_WorkstationWithSharedAccountDomain,
DsRole_ServerWithSharedAccountDomain,
DsRole_MemberWorkstationWithSharedAccountDomain,
DsRole_MemberServerWithSharedAccountDomain
}
/*
typedef enum
{
DsRolePrimaryDomainInfoBasic,
DsRoleUpgradeStatus,
DsRoleOperationState,
DsRolePrimaryDomainInfoBasicEx
}DSROLE_PRIMARY_DOMAIN_INFO_LEVEL;
*/
public enum DSROLE_PRIMARY_DOMAIN_INFO_LEVEL
{
DsRolePrimaryDomainInfoBasic = 1,
DsRoleUpgradeStatus = 2,
DsRoleOperationState = 3,
DsRolePrimaryDomainInfoBasicEx = 4
}
/*
typedef struct _DSROLE_PRIMARY_DOMAIN_INFO_BASIC {
DSROLE_MACHINE_ROLE MachineRole;
ULONG Flags;
LPWSTR DomainNameFlat;
LPWSTR DomainNameDns;
LPWSTR DomainForestName;
GUID DomainGuid;
} DSROLE_PRIMARY_DOMAIN_INFO_BASIC, *PDSROLE_PRIMARY_DOMAIN_INFO_BASIC;
*/
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public sealed class DSROLE_PRIMARY_DOMAIN_INFO_BASIC
{
public DSROLE_MACHINE_ROLE MachineRole;
public uint Flags;
[MarshalAs(UnmanagedType.LPWStr)]
public string DomainNameFlat;
[MarshalAs(UnmanagedType.LPWStr)]
public string DomainNameDns;
[MarshalAs(UnmanagedType.LPWStr)]
public string DomainForestName;
public Guid DomainGuid = new Guid();
}
/*
DWORD DsRoleGetPrimaryDomainInformation(
LPCWSTR lpServer,
DSROLE_PRIMARY_DOMAIN_INFO_LEVEL InfoLevel,
PBYTE* Buffer
); */
[DllImport("dsrole.dll", CallingConvention = CallingConvention.StdCall, EntryPoint = "DsRoleGetPrimaryDomainInformation", CharSet = CharSet.Unicode)]
public static extern int DsRoleGetPrimaryDomainInformation(
[MarshalAs(UnmanagedType.LPTStr)] string lpServer,
[In] DSROLE_PRIMARY_DOMAIN_INFO_LEVEL InfoLevel,
out IntPtr Buffer);
/*typedef struct _DOMAIN_CONTROLLER_INFO {
LPTSTR DomainControllerName;
LPTSTR DomainControllerAddress;
ULONG DomainControllerAddressType;
GUID DomainGuid;
LPTSTR DomainName;
LPTSTR DnsForestName;
ULONG Flags;
LPTSTR DcSiteName;
LPTSTR ClientSiteName;
} DOMAIN_CONTROLLER_INFO, *PDOMAIN_CONTROLLER_INFO; */
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public sealed class DomainControllerInfo
{
public string DomainControllerName = null;
public string DomainControllerAddress = null;
public int DomainControllerAddressType = 0;
public Guid DomainGuid = new Guid();
public string DomainName = null;
public string DnsForestName = null;
public int Flags = 0;
public string DcSiteName = null;
public string ClientSiteName = null;
}
/*
void DsRoleFreeMemory(
PVOID Buffer
);
*/
[DllImport("dsrole.dll")]
public static extern int DsRoleFreeMemory(
[In] IntPtr buffer);
/*DWORD DsGetDcName(
LPCTSTR ComputerName,
LPCTSTR DomainName,
GUID* DomainGuid,
LPCTSTR SiteName,
ULONG Flags,
PDOMAIN_CONTROLLER_INFO* DomainControllerInfo
);*/
[DllImport("logoncli.dll", CallingConvention = CallingConvention.StdCall, EntryPoint = "DsGetDcNameW", CharSet = CharSet.Unicode)]
public static extern int DsGetDcName(
[In] string computerName,
[In] string domainName,
[In] IntPtr domainGuid,
[In] string siteName,
[In] int flags,
[Out] out IntPtr domainControllerInfo);
/* typedef struct _WKSTA_INFO_100 {
DWORD wki100_platform_id;
LMSTR wki100_computername;
LMSTR wki100_langroup;
DWORD wki100_ver_major;
DWORD wki100_ver_minor;
} WKSTA_INFO_100, *PWKSTA_INFO_100; */
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public sealed class WKSTA_INFO_100
{
public int wki100_platform_id = 0;
public string wki100_computername = null;
public string wki100_langroup = null;
public int wki100_ver_major = 0;
public int wki100_ver_minor = 0;
};
[DllImport("wkscli.dll", CallingConvention = CallingConvention.StdCall, EntryPoint = "NetWkstaGetInfo", CharSet = CharSet.Unicode)]
public static extern int NetWkstaGetInfo(string server, int level, ref IntPtr buffer);
[DllImport("netutils.dll")]
public static extern int NetApiBufferFree(
[In] IntPtr buffer);
//
// SID
//
[DllImport("advapi32.dll", SetLastError = true, CallingConvention = CallingConvention.StdCall, EntryPoint = "ConvertSidToStringSidW", CharSet = CharSet.Unicode)]
public static extern bool ConvertSidToStringSid(IntPtr sid, ref string stringSid);
[DllImport("advapi32.dll", CallingConvention = CallingConvention.StdCall, EntryPoint = "ConvertStringSidToSidW", CharSet = CharSet.Unicode)]
public static extern bool ConvertStringSidToSid(string stringSid, ref IntPtr sid);
[DllImport("advapi32.dll")]
public static extern int GetLengthSid(IntPtr sid);
[DllImport("advapi32.dll", SetLastError = true)]
public static extern bool IsValidSid(IntPtr sid);
[DllImport("advapi32.dll")]
public static extern IntPtr GetSidIdentifierAuthority(IntPtr sid);
[DllImport("advapi32.dll")]
public static extern IntPtr GetSidSubAuthority(IntPtr sid, int index);
[DllImport("advapi32.dll")]
public static extern IntPtr GetSidSubAuthorityCount(IntPtr sid);
[DllImport("advapi32.dll")]
public static extern bool EqualDomainSid(IntPtr pSid1, IntPtr pSid2, ref bool equal);
[DllImport("advapi32.dll", SetLastError = true)]
public static extern bool CopySid(int destinationLength, IntPtr pSidDestination, IntPtr pSidSource);
[DllImport("kernel32.dll")]
public static extern IntPtr LocalFree(IntPtr ptr);
[DllImport("Credui.dll", SetLastError = true, CallingConvention = CallingConvention.StdCall, EntryPoint = "CredUIParseUserNameW", CharSet = CharSet.Unicode)]
public static extern unsafe int CredUIParseUserName(
string pszUserName,
char* pszUser,
uint ulUserMaxChars,
char* pszDomain,
uint ulDomainMaxChars);
// These contants were taken from the wincred.h file
public const int CRED_MAX_USERNAME_LENGTH = 514;
public const int CRED_MAX_DOMAIN_TARGET_LENGTH = 338;
//
// AuthZ functions
//
internal sealed class AUTHZ_RM_FLAG
{
private AUTHZ_RM_FLAG() { }
public static int AUTHZ_RM_FLAG_NO_AUDIT = 0x1;
public static int AUTHZ_RM_FLAG_INITIALIZE_UNDER_IMPERSONATION = 0x2;
public static int AUTHZ_VALID_RM_INIT_FLAGS = (AUTHZ_RM_FLAG_NO_AUDIT | AUTHZ_RM_FLAG_INITIALIZE_UNDER_IMPERSONATION);
}
[DllImport("authz.dll", SetLastError = true, CallingConvention = CallingConvention.StdCall, EntryPoint = "AuthzInitializeResourceManager", CharSet = CharSet.Unicode)]
static extern public bool AuthzInitializeResourceManager(
int flags,
IntPtr pfnAccessCheck,
IntPtr pfnComputeDynamicGroups,
IntPtr pfnFreeDynamicGroups,
string name,
out IntPtr rm
);
/*
BOOL WINAPI AuthzInitializeContextFromSid(
DWORD Flags,
PSID UserSid,
AUTHZ_RESOURCE_MANAGER_HANDLE AuthzResourceManager,
PLARGE_INTEGER pExpirationTime,
LUID Identifier,
PVOID DynamicGroupArgs,
PAUTHZ_CLIENT_CONTEXT_HANDLE pAuthzClientContext
);
*/
[DllImport("authz.dll", SetLastError = true, CallingConvention = CallingConvention.StdCall, EntryPoint = "AuthzInitializeContextFromSid", CharSet = CharSet.Unicode)]
static extern public bool AuthzInitializeContextFromSid(
int Flags,
IntPtr UserSid,
IntPtr AuthzResourceManager,
IntPtr pExpirationTime,
LUID Identitifier,
IntPtr DynamicGroupArgs,
out IntPtr pAuthzClientContext
);
/*
[DllImport("authz.dll", SetLastError=true, CallingConvention=CallingConvention.StdCall, EntryPoint="AuthzInitializeContextFromToken", CharSet=CharSet.Unicode)]
static extern public bool AuthzInitializeContextFromToken(
int Flags,
IntPtr TokenHandle,
IntPtr AuthzResourceManager,
IntPtr pExpirationTime,
LUID Identitifier,
IntPtr DynamicGroupArgs,
out IntPtr pAuthzClientContext
);
*/
[DllImport("authz.dll", SetLastError = true, CallingConvention = CallingConvention.StdCall, EntryPoint = "AuthzGetInformationFromContext", CharSet = CharSet.Unicode)]
static extern public bool AuthzGetInformationFromContext(
IntPtr hAuthzClientContext,
int InfoClass,
int BufferSize,
out int pSizeRequired,
IntPtr Buffer
);
[DllImport("authz.dll", CallingConvention = CallingConvention.StdCall, EntryPoint = "AuthzFreeContext", CharSet = CharSet.Unicode)]
static extern public bool AuthzFreeContext(
IntPtr AuthzClientContext
);
[DllImport("authz.dll", CallingConvention = CallingConvention.StdCall, EntryPoint = "AuthzFreeResourceManager", CharSet = CharSet.Unicode)]
static extern public bool AuthzFreeResourceManager(
IntPtr rm
);
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct LUID
{
public int low;
public int high;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public sealed class TOKEN_GROUPS
{
public int groupCount = 0;
public IntPtr groups = IntPtr.Zero;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public sealed class SID_AND_ATTR
{
public IntPtr pSid = IntPtr.Zero;
public int attrs = 0;
}
//
// Token
//
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public sealed class TOKEN_USER
{
public SID_AND_ATTR sidAndAttributes = new SID_AND_ATTR();
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public sealed class SID_IDENTIFIER_AUTHORITY
{
public byte b1 = 0;
public byte b2 = 0;
public byte b3 = 0;
public byte b4 = 0;
public byte b5 = 0;
public byte b6 = 0;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public sealed class LSA_OBJECT_ATTRIBUTES
{
public int length = 0;
public IntPtr rootDirectory = IntPtr.Zero;
public IntPtr objectName = IntPtr.Zero;
public int attributes = 0;
public IntPtr securityDescriptor = IntPtr.Zero;
public IntPtr securityQualityOfService = IntPtr.Zero;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public sealed class POLICY_ACCOUNT_DOMAIN_INFO
{
public LSA_UNICODE_STRING domainName = new LSA_UNICODE_STRING();
public IntPtr domainSid = IntPtr.Zero;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public sealed class LSA_UNICODE_STRING
{
public ushort length = 0;
public ushort maximumLength = 0;
public IntPtr buffer = IntPtr.Zero;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public sealed class LSA_UNICODE_STRING_Managed
{
public ushort length = 0;
public ushort maximumLength = 0;
public string buffer;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public sealed class LSA_TRANSLATED_NAME
{
public int use = 0;
public LSA_UNICODE_STRING name = new LSA_UNICODE_STRING();
public int domainIndex = 0;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public sealed class LSA_REFERENCED_DOMAIN_LIST
{
// To stop the compiler from autogenerating a constructor for this class
private LSA_REFERENCED_DOMAIN_LIST() { }
public int entries = 0;
public IntPtr domains = IntPtr.Zero;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public sealed class LSA_TRUST_INFORMATION
{
public LSA_UNICODE_STRING name = new LSA_UNICODE_STRING();
private IntPtr _pSid = IntPtr.Zero;
}
[DllImport("advapi32.dll", SetLastError = true, CallingConvention = CallingConvention.StdCall, EntryPoint = "OpenThreadToken", CharSet = CharSet.Unicode)]
static extern public bool OpenThreadToken(
IntPtr threadHandle,
int desiredAccess,
bool openAsSelf,
ref IntPtr tokenHandle
);
[DllImport("advapi32.dll", SetLastError = true, CallingConvention = CallingConvention.StdCall, EntryPoint = "OpenProcessToken", CharSet = CharSet.Unicode)]
static extern public bool OpenProcessToken(
IntPtr processHandle,
int desiredAccess,
ref IntPtr tokenHandle
);
[DllImport("kernel32.dll", CallingConvention = CallingConvention.StdCall, EntryPoint = "CloseHandle", CharSet = CharSet.Unicode)]
static extern public bool CloseHandle(IntPtr handle);
[DllImport("kernel32.dll", CallingConvention = CallingConvention.StdCall, EntryPoint = "GetCurrentThread", CharSet = CharSet.Unicode)]
static extern public IntPtr GetCurrentThread();
[DllImport("kernel32.dll", CallingConvention = CallingConvention.StdCall, EntryPoint = "GetCurrentProcess", CharSet = CharSet.Unicode)]
static extern public IntPtr GetCurrentProcess();
[DllImport("advapi32.dll", SetLastError = true, CallingConvention = CallingConvention.StdCall, EntryPoint = "GetTokenInformation", CharSet = CharSet.Unicode)]
static extern public bool GetTokenInformation(
IntPtr tokenHandle,
int tokenInformationClass,
IntPtr buffer,
int bufferSize,
ref int returnLength
);
[DllImport("advapi32.dll", CallingConvention = CallingConvention.StdCall, EntryPoint = "LsaOpenPolicy", CharSet = CharSet.Unicode)]
static extern public int LsaOpenPolicy(
IntPtr lsaUnicodeString,
IntPtr lsaObjectAttributes,
int desiredAccess,
ref IntPtr policyHandle);
[DllImport("advapi32.dll", CallingConvention = CallingConvention.StdCall, EntryPoint = "LsaQueryInformationPolicy", CharSet = CharSet.Unicode)]
static extern public int LsaQueryInformationPolicy(
IntPtr policyHandle,
int policyInformationClass,
ref IntPtr buffer
);
[DllImport("advapi32.dll", CallingConvention = CallingConvention.StdCall, EntryPoint = "LsaLookupSids", CharSet = CharSet.Unicode)]
public static extern int LsaLookupSids(
IntPtr policyHandle,
int count,
IntPtr[] sids,
out IntPtr referencedDomains,
out IntPtr names
);
[DllImport("advapi32.dll", CallingConvention = CallingConvention.StdCall, EntryPoint = "LsaFreeMemory", CharSet = CharSet.Unicode)]
static extern public int LsaFreeMemory(IntPtr buffer);
[DllImport("advapi32.dll", CallingConvention = CallingConvention.StdCall, EntryPoint = "LsaClose", CharSet = CharSet.Unicode)]
static extern public int LsaClose(IntPtr policyHandle);
//
// Impersonation
//
[DllImport("advapi32.dll", SetLastError = true, CallingConvention = CallingConvention.StdCall, EntryPoint = "LogonUserW", CharSet = CharSet.Unicode)]
static extern public int LogonUser(
string lpszUsername,
string lpszDomain,
string lpszPassword,
int dwLogonType,
int dwLogonProvider,
ref IntPtr phToken);
[DllImport("advapi32.dll", SetLastError = true, CallingConvention = CallingConvention.StdCall, EntryPoint = "ImpersonateLoggedOnUser", CharSet = CharSet.Unicode)]
static extern public int ImpersonateLoggedOnUser(IntPtr hToken);
[DllImport("Advapi32.dll", CallingConvention = CallingConvention.StdCall, EntryPoint = "RevertToSelf", CharSet = CharSet.Unicode)]
static extern public int RevertToSelf();
}
}
| |
// 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.
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
//
// Test class using UnitTestDriver that ensures all the public ctor of Task, Future and
// promise are properly working
//
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
using Xunit;
using System;
using System.Threading;
using System.Threading.Tasks;
using System.Diagnostics;
namespace System.Threading.Tasks.Tests
{
public sealed class TaskCreateTests
{
#region Test Methods
[Fact]
public static void TaskCreateTest0()
{
TestParameters parameters = new TestParameters(TaskType.FutureT)
{
HasCancellationToken = true,
HasActionState = false,
HasTaskManager = false,
HasTaskOption = false,
ExceptionTestsAction = ExceptionTestsAction.None,
};
TaskCreateTest test = new TaskCreateTest(parameters);
test.CreateTask();
}
[Fact]
public static void TaskCreateTest1()
{
TestParameters parameters = new TestParameters(TaskType.FutureT)
{
HasCancellationToken = false,
HasActionState = false,
HasTaskManager = false,
HasTaskOption = true,
ExceptionTestsAction = ExceptionTestsAction.None,
};
TaskCreateTest test = new TaskCreateTest(parameters);
test.CreateTask();
}
[Fact]
public static void TaskCreateTest2()
{
TestParameters parameters = new TestParameters(TaskType.FutureT)
{
HasCancellationToken = true,
HasActionState = false,
HasTaskManager = false,
HasTaskOption = true,
ExceptionTestsAction = ExceptionTestsAction.None,
};
TaskCreateTest test = new TaskCreateTest(parameters);
test.CreateTask();
}
[Fact]
public static void TaskCreateTest3()
{
TestParameters parameters = new TestParameters(TaskType.FutureT)
{
HasCancellationToken = true,
HasActionState = true,
HasTaskManager = false,
HasTaskOption = false,
ExceptionTestsAction = ExceptionTestsAction.None,
};
TaskCreateTest test = new TaskCreateTest(parameters);
test.CreateTask();
}
[Fact]
public static void TaskCreateTest4()
{
TestParameters parameters = new TestParameters(TaskType.FutureT)
{
HasCancellationToken = false,
HasActionState = true,
HasTaskManager = false,
HasTaskOption = true,
ExceptionTestsAction = ExceptionTestsAction.None,
};
TaskCreateTest test = new TaskCreateTest(parameters);
test.CreateTask();
}
[Fact]
public static void TaskCreateTest5()
{
TestParameters parameters = new TestParameters(TaskType.FutureT)
{
HasCancellationToken = true,
HasActionState = false,
HasTaskManager = false,
HasTaskOption = false,
ExceptionTestsAction = ExceptionTestsAction.InvalidTaskOption,
};
TaskCreateTest test = new TaskCreateTest(parameters);
test.ExceptionTests();
}
[Fact]
public static void TaskCreateTest6()
{
TestParameters parameters = new TestParameters(TaskType.FutureT)
{
HasCancellationToken = true,
HasActionState = false,
HasTaskManager = false,
HasTaskOption = false,
ExceptionTestsAction = ExceptionTestsAction.NullAction,
};
TaskCreateTest test = new TaskCreateTest(parameters);
test.ExceptionTests();
}
[Fact]
public static void TaskCreateTest7()
{
TestParameters parameters = new TestParameters(TaskType.FutureT)
{
HasCancellationToken = true,
HasActionState = false,
HasTaskManager = false,
HasTaskOption = false,
ExceptionTestsAction = ExceptionTestsAction.NullTaskManager,
};
TaskCreateTest test = new TaskCreateTest(parameters);
test.ExceptionTests();
}
[Fact]
public static void TaskCreateTest8()
{
TestParameters parameters = new TestParameters(TaskType.FutureT)
{
HasCancellationToken = true,
HasActionState = false,
HasTaskManager = false,
HasTaskOption = false,
ExceptionTestsAction = ExceptionTestsAction.None,
};
TaskCreateTest test = new TaskCreateTest(parameters);
test.StartNewTask();
}
[Fact]
public static void TaskCreateTest9()
{
TestParameters parameters = new TestParameters(TaskType.FutureT)
{
HasCancellationToken = false,
HasActionState = false,
HasTaskManager = false,
HasTaskOption = true,
ExceptionTestsAction = ExceptionTestsAction.None,
};
TaskCreateTest test = new TaskCreateTest(parameters);
test.StartNewTask();
}
[Fact]
public static void TaskCreateTest10()
{
TestParameters parameters = new TestParameters(TaskType.FutureT)
{
HasCancellationToken = true,
HasActionState = false,
HasTaskManager = true,
HasTaskOption = true,
ExceptionTestsAction = ExceptionTestsAction.None,
};
TaskCreateTest test = new TaskCreateTest(parameters);
test.StartNewTask();
}
[Fact]
public static void TaskCreateTest11()
{
TestParameters parameters = new TestParameters(TaskType.FutureT)
{
HasCancellationToken = true,
HasActionState = true,
HasTaskManager = false,
HasTaskOption = false,
ExceptionTestsAction = ExceptionTestsAction.None,
};
TaskCreateTest test = new TaskCreateTest(parameters);
test.StartNewTask();
}
[Fact]
public static void TaskCreateTest12()
{
TestParameters parameters = new TestParameters(TaskType.FutureT)
{
HasCancellationToken = false,
HasActionState = true,
HasTaskManager = false,
HasTaskOption = true,
ExceptionTestsAction = ExceptionTestsAction.None,
};
TaskCreateTest test = new TaskCreateTest(parameters);
test.StartNewTask();
}
[Fact]
public static void TaskCreateTest13()
{
TestParameters parameters = new TestParameters(TaskType.FutureT)
{
HasCancellationToken = true,
HasActionState = true,
HasTaskManager = true,
HasTaskOption = true,
ExceptionTestsAction = ExceptionTestsAction.None,
};
TaskCreateTest test = new TaskCreateTest(parameters);
test.StartNewTask();
}
[Fact]
public static void TaskCreateTest14()
{
TestParameters parameters = new TestParameters(TaskType.FutureT)
{
HasCancellationToken = true,
HasActionState = false,
HasTaskManager = false,
HasTaskOption = false,
ExceptionTestsAction = ExceptionTestsAction.None,
};
TaskCreateTest test = new TaskCreateTest(parameters);
test.StartTask();
}
[Fact]
public static void TaskCreateTest15()
{
TestParameters parameters = new TestParameters(TaskType.FutureT)
{
HasCancellationToken = false,
HasActionState = false,
HasTaskManager = false,
HasTaskOption = true,
ExceptionTestsAction = ExceptionTestsAction.None,
};
TaskCreateTest test = new TaskCreateTest(parameters);
test.StartTask();
}
[Fact]
public static void TaskCreateTest16()
{
TestParameters parameters = new TestParameters(TaskType.FutureT)
{
HasCancellationToken = true,
HasActionState = false,
HasTaskManager = true,
HasTaskOption = true,
ExceptionTestsAction = ExceptionTestsAction.None,
};
TaskCreateTest test = new TaskCreateTest(parameters);
test.StartTask();
}
[Fact]
public static void TaskCreateTest17()
{
TestParameters parameters = new TestParameters(TaskType.FutureT)
{
HasCancellationToken = true,
HasActionState = true,
HasTaskManager = false,
HasTaskOption = false,
ExceptionTestsAction = ExceptionTestsAction.None,
};
TaskCreateTest test = new TaskCreateTest(parameters);
test.StartTask();
}
[Fact]
public static void TaskCreateTest18()
{
TestParameters parameters = new TestParameters(TaskType.FutureT)
{
HasCancellationToken = false,
HasActionState = true,
HasTaskManager = false,
HasTaskOption = true,
ExceptionTestsAction = ExceptionTestsAction.None,
};
TaskCreateTest test = new TaskCreateTest(parameters);
test.StartTask();
}
[Fact]
public static void TaskCreateTest19()
{
TestParameters parameters = new TestParameters(TaskType.FutureT)
{
HasCancellationToken = true,
HasActionState = true,
HasTaskManager = false,
HasTaskOption = true,
ExceptionTestsAction = ExceptionTestsAction.None,
};
TaskCreateTest test = new TaskCreateTest(parameters);
test.StartTask();
}
[Fact]
public static void TaskCreateTest20()
{
TestParameters parameters = new TestParameters(TaskType.FutureT)
{
HasCancellationToken = true,
HasActionState = true,
HasTaskManager = true,
HasTaskOption = true,
ExceptionTestsAction = ExceptionTestsAction.None,
};
TaskCreateTest test = new TaskCreateTest(parameters);
test.StartTask();
}
[Fact]
public static void TaskCreateTest21()
{
TestParameters parameters = new TestParameters(TaskType.Future)
{
HasCancellationToken = true,
HasActionState = false,
HasTaskManager = false,
HasTaskOption = false,
ExceptionTestsAction = ExceptionTestsAction.InvalidTaskOption,
};
TaskCreateTest test = new TaskCreateTest(parameters);
test.ExceptionTests();
}
[Fact]
public static void TaskCreateTest22()
{
TestParameters parameters = new TestParameters(TaskType.Future)
{
HasCancellationToken = true,
HasActionState = false,
HasTaskManager = false,
HasTaskOption = false,
ExceptionTestsAction = ExceptionTestsAction.NullAction,
};
TaskCreateTest test = new TaskCreateTest(parameters);
test.ExceptionTests();
}
[Fact]
public static void TaskCreateTest23()
{
TestParameters parameters = new TestParameters(TaskType.Future)
{
HasCancellationToken = true,
HasActionState = false,
HasTaskManager = false,
HasTaskOption = false,
ExceptionTestsAction = ExceptionTestsAction.NullTaskManager,
};
TaskCreateTest test = new TaskCreateTest(parameters);
test.ExceptionTests();
}
[Fact]
public static void TaskCreateTest24()
{
TestParameters parameters = new TestParameters(TaskType.Future)
{
HasCancellationToken = true,
HasActionState = false,
HasTaskManager = false,
HasTaskOption = false,
ExceptionTestsAction = ExceptionTestsAction.None,
};
TaskCreateTest test = new TaskCreateTest(parameters);
test.StartNewTask();
}
[Fact]
public static void TaskCreateTest25()
{
TestParameters parameters = new TestParameters(TaskType.Future)
{
HasCancellationToken = false,
HasActionState = false,
HasTaskManager = false,
HasTaskOption = true,
ExceptionTestsAction = ExceptionTestsAction.None,
};
TaskCreateTest test = new TaskCreateTest(parameters);
test.StartNewTask();
}
[Fact]
public static void TaskCreateTest26()
{
TestParameters parameters = new TestParameters(TaskType.Future)
{
HasCancellationToken = true,
HasActionState = false,
HasTaskManager = true,
HasTaskOption = true,
ExceptionTestsAction = ExceptionTestsAction.None,
};
TaskCreateTest test = new TaskCreateTest(parameters);
test.StartNewTask();
}
[Fact]
public static void TaskCreateTest27()
{
TestParameters parameters = new TestParameters(TaskType.Future)
{
HasCancellationToken = true,
HasActionState = true,
HasTaskManager = false,
HasTaskOption = false,
ExceptionTestsAction = ExceptionTestsAction.None,
};
TaskCreateTest test = new TaskCreateTest(parameters);
test.StartNewTask();
}
[Fact]
public static void TaskCreateTest28()
{
TestParameters parameters = new TestParameters(TaskType.Future)
{
HasCancellationToken = false,
HasActionState = true,
HasTaskManager = false,
HasTaskOption = true,
ExceptionTestsAction = ExceptionTestsAction.None,
};
TaskCreateTest test = new TaskCreateTest(parameters);
test.StartNewTask();
}
[Fact]
public static void TaskCreateTest29()
{
TestParameters parameters = new TestParameters(TaskType.Future)
{
HasCancellationToken = true,
HasActionState = true,
HasTaskManager = true,
HasTaskOption = true,
ExceptionTestsAction = ExceptionTestsAction.None,
};
TaskCreateTest test = new TaskCreateTest(parameters);
test.StartNewTask();
}
[Fact]
public static void TaskCreateTest30()
{
TestParameters parameters = new TestParameters(TaskType.Promise)
{
HasCancellationToken = false,
HasActionState = false,
HasTaskManager = false,
HasTaskOption = true,
ExceptionTestsAction = ExceptionTestsAction.None,
};
TaskCreateTest test = new TaskCreateTest(parameters);
test.CreateTask();
}
[Fact]
public static void TaskCreateTest31()
{
TestParameters parameters = new TestParameters(TaskType.Promise)
{
HasCancellationToken = false,
HasActionState = true,
HasTaskManager = false,
HasTaskOption = true,
ExceptionTestsAction = ExceptionTestsAction.None,
};
TaskCreateTest test = new TaskCreateTest(parameters);
test.CreateTask();
}
[Fact]
public static void TaskCreateTest32()
{
TestParameters parameters = new TestParameters(TaskType.Task)
{
HasCancellationToken = true,
HasActionState = false,
HasTaskManager = false,
HasTaskOption = false,
ExceptionTestsAction = ExceptionTestsAction.None,
};
TaskCreateTest test = new TaskCreateTest(parameters);
test.CreateTask();
}
[Fact]
public static void TaskCreateTest33()
{
TestParameters parameters = new TestParameters(TaskType.Task)
{
HasCancellationToken = false,
HasActionState = false,
HasTaskManager = false,
HasTaskOption = true,
ExceptionTestsAction = ExceptionTestsAction.None,
};
TaskCreateTest test = new TaskCreateTest(parameters);
test.CreateTask();
}
[Fact]
public static void TaskCreateTest34()
{
TestParameters parameters = new TestParameters(TaskType.Task)
{
HasCancellationToken = true,
HasActionState = true,
HasTaskManager = false,
HasTaskOption = false,
ExceptionTestsAction = ExceptionTestsAction.None,
};
TaskCreateTest test = new TaskCreateTest(parameters);
test.CreateTask();
}
[Fact]
public static void TaskCreateTest35()
{
TestParameters parameters = new TestParameters(TaskType.Task)
{
HasCancellationToken = false,
HasActionState = true,
HasTaskManager = false,
HasTaskOption = true,
ExceptionTestsAction = ExceptionTestsAction.None,
};
TaskCreateTest test = new TaskCreateTest(parameters);
test.CreateTask();
}
[Fact]
public static void TaskCreateTest36()
{
TestParameters parameters = new TestParameters(TaskType.Task)
{
HasCancellationToken = true,
HasActionState = true,
HasTaskManager = false,
HasTaskOption = true,
ExceptionTestsAction = ExceptionTestsAction.None,
};
TaskCreateTest test = new TaskCreateTest(parameters);
test.CreateTask();
}
[Fact]
public static void TaskCreateTest37()
{
TestParameters parameters = new TestParameters(TaskType.Task)
{
HasCancellationToken = true,
HasActionState = false,
HasTaskManager = false,
HasTaskOption = false,
ExceptionTestsAction = ExceptionTestsAction.InvalidTaskOption,
};
TaskCreateTest test = new TaskCreateTest(parameters);
test.ExceptionTests();
}
[Fact]
public static void TaskCreateTest38()
{
TestParameters parameters = new TestParameters(TaskType.Task)
{
HasCancellationToken = true,
HasActionState = false,
HasTaskManager = false,
HasTaskOption = false,
ExceptionTestsAction = ExceptionTestsAction.MultipleTaskStart,
};
TaskCreateTest test = new TaskCreateTest(parameters);
test.ExceptionTests();
}
[Fact]
public static void TaskCreateTest39()
{
TestParameters parameters = new TestParameters(TaskType.Task)
{
HasCancellationToken = true,
HasActionState = false,
HasTaskManager = false,
HasTaskOption = false,
ExceptionTestsAction = ExceptionTestsAction.NullAction,
};
TaskCreateTest test = new TaskCreateTest(parameters);
test.ExceptionTests();
}
[Fact]
public static void TaskCreateTest40()
{
TestParameters parameters = new TestParameters(TaskType.Task)
{
HasCancellationToken = true,
HasActionState = false,
HasTaskManager = false,
HasTaskOption = false,
ExceptionTestsAction = ExceptionTestsAction.NullTaskManager,
};
TaskCreateTest test = new TaskCreateTest(parameters);
test.ExceptionTests();
}
[Fact]
public static void TaskCreateTest41()
{
TestParameters parameters = new TestParameters(TaskType.Task)
{
HasCancellationToken = true,
HasActionState = false,
HasTaskManager = false,
HasTaskOption = false,
ExceptionTestsAction = ExceptionTestsAction.StartOnContinueWith,
};
TaskCreateTest test = new TaskCreateTest(parameters);
test.ExceptionTests();
}
[Fact]
public static void TaskCreateTest42()
{
TestParameters parameters = new TestParameters(TaskType.Task)
{
HasCancellationToken = true,
HasActionState = false,
HasTaskManager = false,
HasTaskOption = false,
ExceptionTestsAction = ExceptionTestsAction.StartOnPromise,
};
TaskCreateTest test = new TaskCreateTest(parameters);
test.ExceptionTests();
}
[Fact]
public static void TaskCreateTest43()
{
TestParameters parameters = new TestParameters(TaskType.Task)
{
HasCancellationToken = true,
HasActionState = false,
HasTaskManager = false,
HasTaskOption = false,
ExceptionTestsAction = ExceptionTestsAction.None,
};
TaskCreateTest test = new TaskCreateTest(parameters);
test.StartNewTask();
}
[Fact]
public static void TaskCreateTest44()
{
TestParameters parameters = new TestParameters(TaskType.Task)
{
HasCancellationToken = false,
HasActionState = false,
HasTaskManager = false,
HasTaskOption = true,
ExceptionTestsAction = ExceptionTestsAction.None,
};
TaskCreateTest test = new TaskCreateTest(parameters);
test.StartNewTask();
}
[Fact]
public static void TaskCreateTest45()
{
TestParameters parameters = new TestParameters(TaskType.Task)
{
HasCancellationToken = true,
HasActionState = false,
HasTaskManager = true,
HasTaskOption = true,
ExceptionTestsAction = ExceptionTestsAction.None,
};
TaskCreateTest test = new TaskCreateTest(parameters);
test.StartNewTask();
}
[Fact]
public static void TaskCreateTest46()
{
TestParameters parameters = new TestParameters(TaskType.Task)
{
HasCancellationToken = true,
HasActionState = true,
HasTaskManager = false,
HasTaskOption = false,
ExceptionTestsAction = ExceptionTestsAction.None,
};
TaskCreateTest test = new TaskCreateTest(parameters);
test.StartNewTask();
}
[Fact]
public static void TaskCreateTest47()
{
TestParameters parameters = new TestParameters(TaskType.Task)
{
HasCancellationToken = false,
HasActionState = true,
HasTaskManager = false,
HasTaskOption = true,
ExceptionTestsAction = ExceptionTestsAction.None,
};
TaskCreateTest test = new TaskCreateTest(parameters);
test.StartNewTask();
}
[Fact]
public static void TaskCreateTest48()
{
TestParameters parameters = new TestParameters(TaskType.Task)
{
HasCancellationToken = true,
HasActionState = true,
HasTaskManager = true,
HasTaskOption = true,
ExceptionTestsAction = ExceptionTestsAction.None,
};
TaskCreateTest test = new TaskCreateTest(parameters);
test.StartNewTask();
}
[Fact]
public static void TaskCreateTest49()
{
TestParameters parameters = new TestParameters(TaskType.Task)
{
HasCancellationToken = true,
HasActionState = false,
HasTaskManager = false,
HasTaskOption = false,
ExceptionTestsAction = ExceptionTestsAction.None,
};
TaskCreateTest test = new TaskCreateTest(parameters);
test.StartTask();
}
[Fact]
public static void TaskCreateTest50()
{
TestParameters parameters = new TestParameters(TaskType.Task)
{
HasCancellationToken = false,
HasActionState = false,
HasTaskManager = false,
HasTaskOption = true,
ExceptionTestsAction = ExceptionTestsAction.None,
};
TaskCreateTest test = new TaskCreateTest(parameters);
test.StartTask();
}
[Fact]
public static void TaskCreateTest51()
{
TestParameters parameters = new TestParameters(TaskType.Task)
{
HasCancellationToken = true,
HasActionState = false,
HasTaskManager = true,
HasTaskOption = true,
ExceptionTestsAction = ExceptionTestsAction.None,
};
TaskCreateTest test = new TaskCreateTest(parameters);
test.StartTask();
}
[Fact]
public static void TaskCreateTest52()
{
TestParameters parameters = new TestParameters(TaskType.Task)
{
HasCancellationToken = true,
HasActionState = true,
HasTaskManager = false,
HasTaskOption = false,
ExceptionTestsAction = ExceptionTestsAction.None,
};
TaskCreateTest test = new TaskCreateTest(parameters);
test.StartTask();
}
[Fact]
public static void TaskCreateTest53()
{
TestParameters parameters = new TestParameters(TaskType.Task)
{
HasCancellationToken = false,
HasActionState = true,
HasTaskManager = false,
HasTaskOption = true,
ExceptionTestsAction = ExceptionTestsAction.None,
};
TaskCreateTest test = new TaskCreateTest(parameters);
test.StartTask();
}
[Fact]
public static void TaskCreateTest54()
{
TestParameters parameters = new TestParameters(TaskType.Task)
{
HasCancellationToken = true,
HasActionState = true,
HasTaskManager = true,
HasTaskOption = true,
ExceptionTestsAction = ExceptionTestsAction.None,
};
TaskCreateTest test = new TaskCreateTest(parameters);
test.StartTask();
}
#endregion
internal class TestParameters
{
internal readonly TaskType TaskType;
internal bool HasTaskManager;
internal bool HasActionState;
internal bool HasTaskOption;
internal bool HasCancellationToken;
internal ExceptionTestsAction ExceptionTestsAction;
internal TestParameters(TaskType taskType)
{
TaskType = taskType;
}
}
/// <summary>
/// Class that verifies that all the public constructors of Task, future, promise and futureT are working correctly
/// The test creates the test object (Task, Future, promise) using various ctor and ensures that they were
/// created and can be started. All the negative cases (exceptional cases are also covered in this test set).
/// </summary>
internal sealed class TaskCreateTest
{
#region Member Variables
//Bunch of constants that is used to simulate work done by TPL Task (does some funky maths
// (1 + 1/(2*2) + 1/(3*3) + ... + 1/(1000000*1000000) and verifies that the result is
//equals to Math.Pow (Math.PI, 2) / 6) aka not important from TPL test perspective
private const int ZETA_SEED = 1000000;
/// <summary>
/// Used to save the results that is returned by the Task upon completion (used to verify that task ran successfully)
/// </summary>
private double _result;
/// <summary>
/// Used to store the Task that is under test. initialized using method CreateTaskHelper()
/// </summary>
private Task _task;
/// <summary>
/// Used to differentiate what type of task to test
/// </summary>
private readonly TaskType _taskType = TaskType.Task;
private readonly bool _hasTaskManager;
private readonly bool _hasActionState;
private readonly bool _hasCancellationToken;
private readonly bool _hasTaskOption;
private readonly ExceptionTestsAction _exceptionTestsAction;
/// <summary>
/// Need a cancellationTokenSource to test the APIs that accept a cancellationTokens
/// </summary>
private CancellationTokenSource _cts;
#endregion
#region Constructor
public TaskCreateTest(TestParameters parameters)
{
_taskType = parameters.TaskType;
_hasTaskManager = parameters.HasTaskManager;
_hasActionState = parameters.HasActionState;
_hasTaskOption = parameters.HasTaskOption;
_hasCancellationToken = parameters.HasCancellationToken;
_exceptionTestsAction = parameters.ExceptionTestsAction;
}
#endregion
#region Test Methods (These are the ones that are actually invoked)
/// <summary>
/// Test that creates a Task, Future and Promise using various Ctor and ensures that the task was created successfully
/// </summary>
/// <returns>indicates whether test passed or failed (invoking ctor was success or not)</returns>
internal void CreateTask()
{
//Using the parameters specified in the XML input file create a Task, Future or promise
_task = CreateTaskHelper();
// Checks whether the task was created, initialized with specified action
Assert.NotNull(_task);
// If token was set on the Task, we should be able to cancel the Task
if (_cts != null)
{
_cts.Cancel();
if (!_task.IsCanceled || _task.Status != TaskStatus.Canceled)
Assert.True(false, string.Format("Task Token doesn't matched TokenSource's Token"));
}
}
/// <summary>
/// Tests to ensure that TaskTypes can be created, started and they run to completion successfully
/// </summary>
/// <returns></returns>
internal void StartTask()
{
// It is not allowed to Start Task multiple times, so this test will not try to do that
// instead it is part of exception testing
Debug.WriteLine("Testing Start() on Task, HasTaskManager={0}", _hasTaskManager);
_task = CreateTaskHelper();
if (_hasTaskManager)
_task.Start(TaskScheduler.Default);
else
_task.Start();
_task.Wait();
// Verification
CheckResult();
}
/// <summary>
/// Tests to ensure that TaskTypes can be created using the StartNew static TaskFactory method
/// </summary>
/// <returns></returns>
internal void StartNewTask()
{
CancellationTokenSource cts = new CancellationTokenSource();
Debug.WriteLine("Start new Task, HasActionState={0}, HasTaskOption={1}, HasTaskManager={2}, TaskType={3}, HasCancellationToken={4}",
_hasActionState, _hasTaskOption, _hasTaskManager, _taskType, _hasCancellationToken);
if (!_hasActionState)
{
if (_hasTaskManager && _hasTaskOption && _hasCancellationToken)
{
switch (_taskType)
{
case TaskType.Task:
_task = Task.Factory.StartNew(Work, cts.Token, TaskCreationOptions.None, TaskScheduler.Default);
break;
case TaskType.FutureT:
_task = Task<double>.Factory.StartNew(FutureWork, cts.Token, TaskCreationOptions.None, TaskScheduler.Default);
break;
case TaskType.Future:
_task = Task.Factory.StartNew<double>(FutureWork, cts.Token, TaskCreationOptions.None, TaskScheduler.Default);
break;
default:
throw new NotSupportedException("DOes not support this type: " + _taskType);
}
}
else if (_hasTaskOption)
{
switch (_taskType)
{
case TaskType.Task:
_task = Task.Factory.StartNew(Work, TaskCreationOptions.None);
break;
case TaskType.FutureT:
_task = Task<double>.Factory.StartNew(FutureWork, TaskCreationOptions.None);
break;
case TaskType.Future:
_task = Task.Factory.StartNew<double>(FutureWork, TaskCreationOptions.None);
break;
default:
throw new NotSupportedException("DOes not support this type: " + _taskType);
}
}
else if (_hasCancellationToken)
{
switch (_taskType)
{
case TaskType.Task:
_task = Task.Factory.StartNew(Work, cts.Token);
break;
case TaskType.FutureT:
_task = (Task<double>)Task<double>.Factory.StartNew(FutureWork, cts.Token);
break;
case TaskType.Future:
_task = Task.Factory.StartNew<double>(FutureWork, cts.Token);
break;
default:
throw new NotSupportedException("DOes not support this type: " + _taskType);
}
}
else
{
switch (_taskType)
{
case TaskType.Task:
_task = Task.Factory.StartNew(Work);
break;
case TaskType.FutureT:
_task = (Task<double>)Task<double>.Factory.StartNew(FutureWork);
break;
case TaskType.Future:
_task = Task.Factory.StartNew<double>(FutureWork);
break;
default:
throw new NotSupportedException("DOes not support this type: " + _taskType);
}
}
}
else
{
if (_hasTaskManager && _hasTaskOption && _hasCancellationToken)
{
switch (_taskType)
{
case TaskType.Task:
_task = Task.Factory.StartNew(WorkWithState, ZETA_SEED, cts.Token, TaskCreationOptions.None, TaskScheduler.Default);
break;
case TaskType.FutureT:
_task = Task<double>.Factory.StartNew(FutureWorkWithState, ZETA_SEED, cts.Token, TaskCreationOptions.None, TaskScheduler.Default);
break;
case TaskType.Future:
_task = Task.Factory.StartNew<double>(FutureWorkWithState, ZETA_SEED, cts.Token, TaskCreationOptions.None, TaskScheduler.Default);
break;
default:
throw new NotSupportedException("DOes not support this type: " + _taskType);
}
}
else if (_hasTaskOption)
{
switch (_taskType)
{
case TaskType.Task:
_task = Task.Factory.StartNew(WorkWithState, ZETA_SEED, TaskCreationOptions.None);
break;
case TaskType.FutureT:
_task = Task<double>.Factory.StartNew(FutureWorkWithState, ZETA_SEED, TaskCreationOptions.None);
break;
case TaskType.Future:
_task = Task.Factory.StartNew<double>(FutureWorkWithState, ZETA_SEED, TaskCreationOptions.None);
break;
default:
throw new NotSupportedException("DOes not support this type: " + _taskType);
}
}
else if (_hasCancellationToken)
{
switch (_taskType)
{
case TaskType.Task:
_task = Task.Factory.StartNew(Work, cts.Token);
break;
case TaskType.FutureT:
_task = Task<double>.Factory.StartNew(FutureWorkWithState, ZETA_SEED, cts.Token);
break;
case TaskType.Future:
_task = Task.Factory.StartNew<double>(FutureWorkWithState, ZETA_SEED, cts.Token);
break;
default:
throw new NotSupportedException("DOes not support this type: " + _taskType);
}
}
else
{
switch (_taskType)
{
case TaskType.Task:
_task = Task.Factory.StartNew(WorkWithState, ZETA_SEED);
break;
case TaskType.FutureT:
_task = Task<double>.Factory.StartNew(FutureWorkWithState, ZETA_SEED);
break;
case TaskType.Future:
_task = Task.Factory.StartNew<double>(FutureWorkWithState, ZETA_SEED);
break;
default:
throw new NotSupportedException("DOes not support this type: " + _taskType);
}
}
}
_task.Wait();
CheckResult();
}
/// <summary>
/// Test to ensure that exceptions are thrown for invalid ctor parameters
/// </summary>
/// <returns></returns>
internal void ExceptionTests()
{
switch (_exceptionTestsAction)
{
case ExceptionTestsAction.NullAction:
Debug.WriteLine("Test passing null Action/Func to Constructor and StartNew() of {0}", _taskType);
if (_taskType != TaskType.Promise)
{
//
// For Constructor
//
if (_taskType != TaskType.Future)
{
try
{
if (_taskType == TaskType.Task)
_task = new Task(null);
else if (_taskType == TaskType.FutureT)
_task = new Task<double>(null);
Assert.True(false, string.Format("Able to pass null Action/Func to Constructor of {0}, when expecting exception", _taskType));
}
catch (ArgumentNullException)
{
Debug.WriteLine("Exception throws as expected when trying to pass null Action/Func to Constructor of {0}", _taskType);
}
}
//
// For StartNew
//
try
{
Action o = null;
Func<double> o2 = null;
if (_taskType == TaskType.Task)
_task = Task.Factory.StartNew(o);
else if (_taskType == TaskType.FutureT)
_task = Task<double>.Factory.StartNew(o2);
else if (_taskType == TaskType.Future)
_task = Task.Factory.StartNew<double>(o2);
Assert.True(false, string.Format("Able to pass null Action/Func to StartNew() of {0}, when expecting exception", _taskType));
}
catch (ArgumentNullException)
{
Debug.WriteLine("Exception throws as expected when trying to pass null Action/Func to StartNew() of {0}", _taskType);
}
}
break;
case ExceptionTestsAction.InvalidTaskOption:
int invalidOption = 9999; //Used to create Invalid TaskCreationOption
Debug.WriteLine("Test passing invalid TaskCreationOptions {0} to Constructor and StartNew() of {1}", invalidOption, _taskType);
if (_taskType != TaskType.Promise)
{
//
// For Constructor
//
if (_taskType != TaskType.Future)
{
try
{
if (_taskType == TaskType.Task)
_task = new Task(Work, (TaskCreationOptions)invalidOption);
else if (_taskType == TaskType.FutureT)
_task = new Task<double>(FutureWork, (TaskCreationOptions)invalidOption);
Assert.True(false, string.Format("Able to pass invalid TaskCreationOptions to Constructor of {0}, when expecting exception", _taskType));
}
catch (ArgumentOutOfRangeException)
{
Debug.WriteLine("Exception throws as expected when trying to pass invalid TaskCreationOptions to Constructor of {0}", _taskType);
}
}
//
// For StartNew
//
try
{
if (_taskType == TaskType.Task)
_task = Task.Factory.StartNew(Work, (TaskCreationOptions)invalidOption);
else if (_taskType == TaskType.FutureT)
_task = Task<double>.Factory.StartNew(FutureWork, (TaskCreationOptions)invalidOption);
else if (_taskType == TaskType.Future)
_task = Task.Factory.StartNew<double>(FutureWork, (TaskCreationOptions)invalidOption);
Assert.True(false, string.Format("Able to pass invalid TaskCreationOptions to StartNew() of {0}, when expecting exception", _taskType));
}
catch (ArgumentOutOfRangeException)
{
Debug.WriteLine("Exception throws as expected when trying to pass invalid TaskCreationOptions to StartNew() of {0}", _taskType);
}
}
break;
case ExceptionTestsAction.NullTaskManager:
Debug.WriteLine("Test passing null TaskManager to Start() and StartNew() on {0}", _taskType);
TMExceptionTestHelper(null, "null");
break;
case ExceptionTestsAction.MultipleTaskStart:
Debug.WriteLine("Testing multiple Start() on {0}", _taskType);
try
{
_task = CreateTaskHelper();
_task.Start();
_task.Start();
Assert.True(false, string.Format("Able to Start {0} multiple times, when expecting exception", _taskType));
}
catch (InvalidOperationException)
{
Debug.WriteLine("Exception throws as expected when trying to Start {0} multiple times", _taskType);
}
break;
case ExceptionTestsAction.StartOnPromise:
Debug.WriteLine("Testing Start() on Promise");
try
{
TaskCompletionSource<double> f = new TaskCompletionSource<double>();
f.Task.Start();
Assert.True(false, string.Format("Able to Start a Promise, when expecting exception"));
}
catch (System.InvalidOperationException)
{
Debug.WriteLine("Exception throws as expected when trying to Start a Promise");
}
break;
case ExceptionTestsAction.StartOnContinueWith:
Debug.WriteLine("Testing Start() on ContinueWith Task");
try
{
Task t = CreateTaskHelper().ContinueWith(delegate { Work(); });
t.Start();
Assert.True(false, string.Format("Able to start task manually on ContinueWith Task, when expecting exception"));
}
catch (InvalidOperationException)
{
Debug.WriteLine("Exception throws as expected when trying to start ContinueWith Task manually");
}
break;
default:
Assert.True(false, string.Format("Invalid Exception Test Action given, {0}", _exceptionTestsAction));
break;
}
}
#endregion
#region Helper Methods
private void TMExceptionTestHelper(TaskScheduler tm, string tmInvalidMessage)
{
if (_taskType != TaskType.Promise)
{
//
// For Start()
//
if (_taskType != TaskType.Future)
{
try
{
_task = CreateTaskHelper();
_task.Start(tm);
Assert.True(false, string.Format("Able to pass {0} TaskManager to Start() on {1}, when expecting exception", tmInvalidMessage, _taskType));
}
catch (ArgumentNullException)
{
if (tmInvalidMessage.Equals("null", StringComparison.OrdinalIgnoreCase))
Debug.WriteLine("Exception ArgumentNullException throws as expected when trying to pass {0} TaskManager to Start() on {1}", tmInvalidMessage, _taskType);
else
throw;
}
catch (InvalidOperationException)
{
if (tmInvalidMessage.Equals("disposed", StringComparison.OrdinalIgnoreCase))
Debug.WriteLine("Exception InvalidOperationException throws as expected when trying to pass {0} TaskManager to Start() on {1}", tmInvalidMessage, _taskType);
else
throw;
}
}
//
// For StartNew()
//
try
{
CancellationToken token = new CancellationToken();
if (_taskType == TaskType.Task)
_task = Task.Factory.StartNew(Work, token, TaskCreationOptions.None, tm);
else if (_taskType == TaskType.FutureT)
_task = Task<double>.Factory.StartNew(FutureWork, token, TaskCreationOptions.None, tm);
else if (_taskType == TaskType.Future)
_task = Task.Factory.StartNew<double>(FutureWork, token, TaskCreationOptions.None, tm);
Assert.True(false, string.Format("Able to pass {0} TaskManager to StartNew() on {1}, when expecting exception", tmInvalidMessage, _taskType));
}
catch (ArgumentNullException)
{
if (tmInvalidMessage.Equals("null", StringComparison.OrdinalIgnoreCase))
Debug.WriteLine("Exception ArgumentNullException throws as expected when trying to pass {0} TaskManager to StartNew() on {1}", tmInvalidMessage, _taskType);
else
throw;
}
catch (InvalidOperationException)
{
if (tmInvalidMessage.Equals("disposed", StringComparison.OrdinalIgnoreCase))
Debug.WriteLine("Exception InvalidOperationException throws as expected when trying to pass {0} TaskManager to StartNew() on {1}", tmInvalidMessage, _taskType);
else
throw;
}
}
}
/// <summary>
/// Helper function that creates Task/Future based on test parameters
/// </summary>
/// <returns></returns>
private Task CreateTaskHelper()
{
CancellationToken token = CancellationToken.None;
Task newTask;
Debug.WriteLine("Creating Task, HasActionState={0}, HasTaskOption={1}, TaskType={2}", _hasActionState, _hasTaskOption, _taskType);
if (_taskType == TaskType.Promise)
{
if (_hasTaskOption && _hasActionState)
newTask = (new TaskCompletionSource<double>(new object(), TaskCreationOptions.None)).Task;
else if (_hasTaskOption)
newTask = (new TaskCompletionSource<double>(TaskCreationOptions.None)).Task;
else if (_hasActionState)
newTask = (new TaskCompletionSource<double>(new object())).Task;
else
newTask = (new TaskCompletionSource<double>()).Task;
}
else
{
if (!_hasActionState)
{
if (_hasTaskOption && _hasCancellationToken)
{
_cts = new CancellationTokenSource();
token = _cts.Token;
switch (_taskType)
{
case TaskType.Task:
newTask = new Task(Work, token, TaskCreationOptions.None);
break;
case TaskType.FutureT:
newTask = new Task<double>(FutureWork, token, TaskCreationOptions.None);
break;
default:
throw new ArgumentException("Cannot create an instance of static type: " + _taskType);
}
}
else if (_hasTaskOption)
{
switch (_taskType)
{
case TaskType.Task:
newTask = new Task(Work, TaskCreationOptions.None);
break;
case TaskType.FutureT:
newTask = new Task<double>(FutureWork, TaskCreationOptions.None);
break;
default:
throw new ArgumentException("Cannot create an instance of static type: " + _taskType);
}
}
else if (_hasCancellationToken)
{
_cts = new CancellationTokenSource();
token = _cts.Token;
switch (_taskType)
{
case TaskType.Task:
newTask = new Task(Work, token);
break;
case TaskType.FutureT:
newTask = new Task<double>(FutureWork, token);
break;
default:
throw new ArgumentException("Cannot create an instance of static type: " + _taskType);
}
}
else
{
switch (_taskType)
{
case TaskType.Task:
newTask = new Task(Work);
break;
case TaskType.FutureT:
newTask = new Task<double>(FutureWork);
break;
default:
throw new ArgumentException("Cannot create an instance of static type: " + _taskType);
}
}
}
else
{
if (_hasTaskOption && _hasCancellationToken)
{
_cts = new CancellationTokenSource();
token = _cts.Token;
switch (_taskType)
{
case TaskType.Task:
newTask = new Task(WorkWithState, ZETA_SEED, token, TaskCreationOptions.None);
break;
case TaskType.FutureT:
newTask = new Task<double>(FutureWorkWithState, ZETA_SEED, token, TaskCreationOptions.None);
break;
default:
throw new ArgumentException("Cannot create an instance of static type: " + _taskType);
}
}
else if (_hasTaskOption)
{
switch (_taskType)
{
case TaskType.Task:
newTask = new Task(WorkWithState, ZETA_SEED, TaskCreationOptions.None);
break;
case TaskType.FutureT:
newTask = new Task<double>(FutureWorkWithState, ZETA_SEED, TaskCreationOptions.None);
break;
default:
throw new ArgumentException("Cannot create an instance of static type: " + _taskType);
}
}
else if (_hasCancellationToken)
{
_cts = new CancellationTokenSource();
token = _cts.Token;
switch (_taskType)
{
case TaskType.Task:
newTask = new Task(WorkWithState, ZETA_SEED, token);
break;
case TaskType.FutureT:
newTask = new Task<double>(FutureWorkWithState, ZETA_SEED, token);
break;
default:
throw new ArgumentException("Cannot create an instance of static type: " + _taskType);
}
}
else
{
switch (_taskType)
{
case TaskType.Task:
newTask = new Task(WorkWithState, ZETA_SEED);
break;
case TaskType.FutureT:
newTask = new Task<double>(FutureWorkWithState, ZETA_SEED);
break;
default:
throw new ArgumentException("Cannot create an instance of static type: " + _taskType);
}
}
}
}
return newTask;
}
private void Work()
{
WorkWithState(ZETA_SEED);
}
private void WorkWithState(object o)
{
// There is a rare case when the main thread (that does the assignment of Task to task) is not
//executed before the delegate is invoked. This spinwait guards against such cases
while (_task == null)
{
SpinWait.SpinUntil(() => false, 100);
}
if (TaskScheduler.Current == TaskScheduler.Default
&& _task.CreationOptions == TaskCreationOptions.None)
{
//The Workloads are defined in the common folder
_result = ZetaSequence((int)o);
}
}
private double FutureWork()
{
return FutureWorkWithState(ZETA_SEED);
}
private double FutureWorkWithState(object o)
{
// Waiting until the task is assigned on StartNew scenario
while (_task == null)
{
SpinWait.SpinUntil(() => false, 100);
}
if (TaskScheduler.Current == TaskScheduler.Default
&& _task.CreationOptions == TaskCreationOptions.None)
{
return ZetaSequence((int)o);
}
else
{
return 0;
}
}
/// <summary>
/// Method used to verify that task was created
/// </summary>
/// <returns></returns>
private bool IsTaskCreated()
{
return _task != null;
}
public static double ZetaSequence(int n)
{
double result = 0;
for (int i = 1; i < n; i++)
{
result += 1.0 / ((double)i * (double)i);
}
return result;
}
/// <summary>
/// Method used to verify that task returns the expected result (which means task ran successfully)
/// </summary>
/// <returns></returns>
private void CheckResult()
{
double actualResult = 0;
switch (_taskType)
{
case TaskType.Task:
actualResult = _result;
break;
case TaskType.FutureT:
case TaskType.Future:
actualResult = ((Task<double>)_task).Result;
break;
default:
throw new NotSupportedException("Mismatch type, " + _taskType + " doesn't have value that can be verified");
}
//Function point comparison cant be done by rounding off to nearest decimal points since
//1.64 could be represented as 1.63999999 or as 1.6499999999. To perform floating point comparisons,
//a range has to be defined and check to ensure that the result obtained is within the specified range
double minLimit = 1.63;
double maxLimit = 1.65;
if (actualResult > minLimit && actualResult < maxLimit)
Debug.WriteLine("Result matched");
else
Assert.True(false, string.Format("Result mismatched, expecting to lie between {0} and {1} but got {2}", minLimit, maxLimit, actualResult));
}
#endregion
}
/// <summary>
/// Type of Task types to test for
/// </summary>
internal enum TaskType
{
Task,
Future,
FutureT,
Promise
}
/// <summary>
/// Types of exception test actions to test for
/// </summary>
internal enum ExceptionTestsAction
{
None,
NullAction,
InvalidTaskOption,
NullTaskManager,
MultipleTaskStart,
StartOnPromise,
StartOnContinueWith
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Threading.Tasks;
using AutoMapper;
using GitReleaseManager.Core.Provider;
using NSubstitute;
using NSubstitute.ExceptionExtensions;
using NUnit.Framework;
using Octokit;
using Shouldly;
using ApiException = GitReleaseManager.Core.Exceptions.ApiException;
using Issue = GitReleaseManager.Core.Model.Issue;
using IssueComment = GitReleaseManager.Core.Model.IssueComment;
using ItemState = GitReleaseManager.Core.Model.ItemState;
using ItemStateFilter = GitReleaseManager.Core.Model.ItemStateFilter;
using Label = GitReleaseManager.Core.Model.Label;
using Milestone = GitReleaseManager.Core.Model.Milestone;
using NotFoundException = GitReleaseManager.Core.Exceptions.NotFoundException;
using RateLimit = GitReleaseManager.Core.Model.RateLimit;
using Release = GitReleaseManager.Core.Model.Release;
using ReleaseAssetUpload = GitReleaseManager.Core.Model.ReleaseAssetUpload;
namespace GitReleaseManager.Core.Tests.Provider
{
[TestFixture]
public class GitHubProviderTests
{
private const string OWNER = "owner";
private const string REPOSITORY = "repository";
private const string BASE = "0.1.0";
private const string HEAD = "0.5.0";
private const int MILESTONE_NUMBER = 1;
private const string MILESTONE_NUMBER_STRING = "1";
private const string MILESTONE_TITLE = "0.1.0";
private const int ISSUE_NUMBER = 1;
private const string ISSUE_COMMENT = "Issue Comment";
private const string LABEL_NAME = "Label";
private const string TAG_NAME = "0.1.0";
private const int RELEASE_ID = 1;
private const int ASSET_ID = 1;
private const string NOT_FOUND_MESSAGE = "NotFound";
private const bool SKIP_PRERELEASES = false;
private readonly Release _release = new Release();
private readonly ReleaseAssetUpload _releaseAssetUpload = new ReleaseAssetUpload();
private readonly Octokit.NewLabel _newLabel = new Octokit.NewLabel(LABEL_NAME, "ffffff");
private readonly Octokit.NewRelease _newRelease = new Octokit.NewRelease(TAG_NAME);
private readonly Exception _exception = new Exception("API Error");
private readonly Octokit.NotFoundException _notFoundException = new Octokit.NotFoundException(NOT_FOUND_MESSAGE, HttpStatusCode.NotFound);
private IMapper _mapper;
private IGitHubClient _gitHubClient;
private GitHubProvider _gitHubProvider;
[SetUp]
public void Setup()
{
_mapper = Substitute.For<IMapper>();
_gitHubClient = Substitute.For<IGitHubClient>();
_gitHubProvider = new GitHubProvider(_gitHubClient, _mapper);
}
// Assets
[Test]
public async Task Should_Delete_Asset()
{
_gitHubClient.Repository.Release.DeleteAsset(OWNER, REPOSITORY, ASSET_ID)
.Returns(Task.FromResult);
await _gitHubProvider.DeleteAssetAsync(OWNER, REPOSITORY, ASSET_ID).ConfigureAwait(false);
await _gitHubClient.Repository.Release.Received(1).DeleteAsset(OWNER, REPOSITORY, ASSET_ID).ConfigureAwait(false);
}
[Test]
public async Task Should_Throw_An_Exception_On_Deleting_Asset_For_Non_Existing_Id()
{
_gitHubClient.Repository.Release.DeleteAsset(OWNER, REPOSITORY, ASSET_ID)
.Returns(Task.FromException(_notFoundException));
var ex = await Should.ThrowAsync<NotFoundException>(() => _gitHubProvider.DeleteAssetAsync(OWNER, REPOSITORY, ASSET_ID)).ConfigureAwait(false);
ex.Message.ShouldBe(_notFoundException.Message);
ex.InnerException.ShouldBe(_notFoundException);
}
[Test]
public async Task Should_Throw_An_Exception_On_Deleting_Asset()
{
_gitHubClient.Repository.Release.DeleteAsset(OWNER, REPOSITORY, ASSET_ID)
.Returns(Task.FromException(_exception));
var ex = await Should.ThrowAsync<ApiException>(() => _gitHubProvider.DeleteAssetAsync(OWNER, REPOSITORY, ASSET_ID)).ConfigureAwait(false);
ex.Message.ShouldBe(_exception.Message);
ex.InnerException.ShouldBe(_exception);
}
[Test]
public async Task Should_Upload_Asset()
{
var octokitRelease = new Octokit.Release();
var octokitReleaseAssetUpload = new Octokit.ReleaseAssetUpload();
_mapper.Map<Octokit.Release>(_release)
.Returns(octokitRelease);
_mapper.Map<Octokit.ReleaseAssetUpload>(_releaseAssetUpload)
.Returns(octokitReleaseAssetUpload);
_gitHubClient.Repository.Release.UploadAsset(octokitRelease, octokitReleaseAssetUpload)
.Returns(Task.FromResult(new Octokit.ReleaseAsset()));
await _gitHubProvider.UploadAssetAsync(_release, _releaseAssetUpload).ConfigureAwait(false);
_mapper.Received(1).Map<Octokit.Release>(_release);
_mapper.Received(1).Map<Octokit.ReleaseAssetUpload>(_releaseAssetUpload);
await _gitHubClient.Repository.Release.Received(1).UploadAsset(octokitRelease, octokitReleaseAssetUpload).ConfigureAwait(false);
}
[Test]
public async Task Should_Throw_An_Exception_On_Uploading_Asset_For_Non_Existing_Release()
{
_mapper.Map<Octokit.Release>(_release)
.Returns(new Octokit.Release());
_mapper.Map<Octokit.ReleaseAssetUpload>(_releaseAssetUpload)
.Returns(new Octokit.ReleaseAssetUpload());
_gitHubClient.Repository.Release.UploadAsset(Arg.Any<Octokit.Release>(), Arg.Any<Octokit.ReleaseAssetUpload>())
.Returns(Task.FromException<Octokit.ReleaseAsset>(_notFoundException));
var ex = await Should.ThrowAsync<NotFoundException>(() => _gitHubProvider.UploadAssetAsync(_release, _releaseAssetUpload)).ConfigureAwait(false);
ex.Message.ShouldBe(_notFoundException.Message);
ex.InnerException.ShouldBe(_notFoundException);
}
[Test]
public async Task Should_Throw_An_Exception_On_Uploading_Asset()
{
_mapper.Map<Octokit.Release>(_release)
.Returns(new Octokit.Release());
_mapper.Map<Octokit.ReleaseAssetUpload>(_releaseAssetUpload)
.Returns(new Octokit.ReleaseAssetUpload());
_gitHubClient.Repository.Release.UploadAsset(Arg.Any<Octokit.Release>(), Arg.Any<Octokit.ReleaseAssetUpload>())
.Returns(Task.FromException<Octokit.ReleaseAsset>(_exception));
var ex = await Should.ThrowAsync<ApiException>(() => _gitHubProvider.UploadAssetAsync(_release, _releaseAssetUpload)).ConfigureAwait(false);
ex.Message.ShouldBe(_exception.Message);
ex.InnerException.ShouldBe(_exception);
}
// Commits
[Test]
public async Task Should_Get_Commits_Count()
{
var commitsCount = 12;
_gitHubClient.Repository.Commit.Compare(OWNER, REPOSITORY, BASE, HEAD)
.Returns(Task.FromResult(new CompareResult(null, null, null, null, null, null, null, null, commitsCount, 0, 0, null, null)));
var result = await _gitHubProvider.GetCommitsCount(OWNER, REPOSITORY, BASE, HEAD).ConfigureAwait(false);
result.ShouldBe(commitsCount);
await _gitHubClient.Repository.Commit.Received(1).Compare(OWNER, REPOSITORY, BASE, HEAD).ConfigureAwait(false);
}
[Test]
public async Task Should_Get_Commits_Count_Zero_If_No_Commits_Found()
{
_gitHubClient.Repository.Commit.Compare(OWNER, REPOSITORY, BASE, HEAD)
.Returns(Task.FromException<CompareResult>(_notFoundException));
var result = await _gitHubProvider.GetCommitsCount(OWNER, REPOSITORY, BASE, HEAD).ConfigureAwait(false);
result.ShouldBe(0);
await _gitHubClient.Repository.Commit.Received(1).Compare(OWNER, REPOSITORY, BASE, HEAD).ConfigureAwait(false);
}
[Test]
public async Task Should_Throw_An_Exception_On_Getting_Commits_Count()
{
_gitHubClient.Repository.Commit.Compare(OWNER, REPOSITORY, BASE, HEAD)
.Returns(Task.FromException<CompareResult>(_exception));
var ex = await Should.ThrowAsync<ApiException>(() => _gitHubProvider.GetCommitsCount(OWNER, REPOSITORY, BASE, HEAD)).ConfigureAwait(false);
ex.Message.ShouldContain(_exception.Message);
ex.InnerException.ShouldBeSameAs(_exception);
}
[TestCase("0.1.0", null, "https://github.com/owner/repository/commits/0.1.0")]
[TestCase("0.5.0", "0.1.0", "https://github.com/owner/repository/compare/0.1.0...0.5.0")]
public void Should_Get_Commits_Url(string head, string @base, string expectedResult)
{
var result = _gitHubProvider.GetCommitsUrl(OWNER, REPOSITORY, head, @base);
result.ShouldBe(expectedResult);
}
[TestCaseSource(nameof(GetCommitsUrl_TestCases))]
public void Should_Throw_An_Exception_If_Parameter_Is_Invalid(string owner, string repository, string head, string paramName, Type expectedException)
{
var ex = Should.Throw(() => _gitHubProvider.GetCommitsUrl(owner, repository, head), expectedException);
ex.Message.ShouldContain(paramName);
}
public static IEnumerable GetCommitsUrl_TestCases()
{
var typeArgumentException = typeof(ArgumentException);
var typeArgumentNullException = typeof(ArgumentNullException);
yield return new TestCaseData(null, null, null, "owner", typeArgumentNullException);
yield return new TestCaseData(string.Empty, null, null, "owner", typeArgumentException);
yield return new TestCaseData(" ", null, null, "owner", typeArgumentException);
yield return new TestCaseData("owner", null, null, "repository", typeArgumentNullException);
yield return new TestCaseData("owner", string.Empty, null, "repository", typeArgumentException);
yield return new TestCaseData("owner", " ", null, "repository", typeArgumentException);
yield return new TestCaseData("owner", "repository", null, "head", typeArgumentNullException);
yield return new TestCaseData("owner", "repository", string.Empty, "head", typeArgumentException);
yield return new TestCaseData("owner", "repository", " ", "head", typeArgumentException);
}
// Issues
[Test]
public async Task Should_Create_Issue_Comment()
{
_gitHubClient.Issue.Comment.Create(OWNER, REPOSITORY, ISSUE_NUMBER, ISSUE_COMMENT)
.Returns(Task.FromResult(new Octokit.IssueComment()));
await _gitHubProvider.CreateIssueCommentAsync(OWNER, REPOSITORY, ISSUE_NUMBER, ISSUE_COMMENT).ConfigureAwait(false);
await _gitHubClient.Issue.Comment.Received(1).Create(OWNER, REPOSITORY, ISSUE_NUMBER, ISSUE_COMMENT).ConfigureAwait(false);
}
[Test]
public async Task Should_Throw_An_Exception_On_Creating_Issue_Comment_For_Non_Existing_Issue_Number()
{
_gitHubClient.Issue.Comment.Create(OWNER, REPOSITORY, ISSUE_NUMBER, ISSUE_COMMENT)
.Returns(Task.FromException<Octokit.IssueComment>(_notFoundException));
var ex = await Should.ThrowAsync<NotFoundException>(() => _gitHubProvider.CreateIssueCommentAsync(OWNER, REPOSITORY, ISSUE_NUMBER, ISSUE_COMMENT)).ConfigureAwait(false);
ex.Message.ShouldBe(_notFoundException.Message);
ex.InnerException.ShouldBe(_notFoundException);
}
[Test]
public async Task Should_Throw_An_Exception_On_Creating_Issue_Comment()
{
_gitHubClient.Issue.Comment.Create(OWNER, REPOSITORY, ISSUE_NUMBER, ISSUE_COMMENT)
.Returns(Task.FromException<Octokit.IssueComment>(_exception));
var ex = await Should.ThrowAsync<ApiException>(() => _gitHubProvider.CreateIssueCommentAsync(OWNER, REPOSITORY, ISSUE_NUMBER, ISSUE_COMMENT)).ConfigureAwait(false);
ex.Message.ShouldBe(_exception.Message);
ex.InnerException.ShouldBe(_exception);
}
[TestCase(ItemStateFilter.Open)]
[TestCase(ItemStateFilter.Closed)]
[TestCase(ItemStateFilter.All)]
public async Task Should_Get_Issues_For_Milestone(ItemStateFilter itemStateFilter)
{
var issues = new List<Issue>();
_gitHubClient.Issue.GetAllForRepository(OWNER, REPOSITORY, Arg.Any<RepositoryIssueRequest>(), Arg.Any<ApiOptions>())
.Returns(Task.FromResult((IReadOnlyList<Octokit.Issue>)new List<Octokit.Issue>()));
_mapper.Map<IEnumerable<Issue>>(Arg.Any<object>())
.Returns(issues);
var result = await _gitHubProvider.GetIssuesAsync(OWNER, REPOSITORY, MILESTONE_NUMBER, itemStateFilter).ConfigureAwait(false);
result.ShouldBeSameAs(issues);
await _gitHubClient.Issue.Received(1).GetAllForRepository(
OWNER,
REPOSITORY,
Arg.Is<RepositoryIssueRequest>(o => o.Milestone == MILESTONE_NUMBER_STRING && o.State == (Octokit.ItemStateFilter)itemStateFilter),
Arg.Any<ApiOptions>()).ConfigureAwait(false);
_mapper.ReceivedWithAnyArgs(1).Map<IEnumerable<Issue>>(default);
}
[Test]
public async Task Should_Throw_An_Exception_On_Getting_Issues_For_Non_Existent_Milestone()
{
_gitHubClient.Issue.GetAllForRepository(OWNER, REPOSITORY, Arg.Any<RepositoryIssueRequest>(), Arg.Any<ApiOptions>())
.Returns(Task.FromException<IReadOnlyList<Octokit.Issue>>(_exception));
var ex = await Should.ThrowAsync<ApiException>(() => _gitHubProvider.GetIssuesAsync(OWNER, REPOSITORY, 1)).ConfigureAwait(false);
ex.Message.ShouldBe(_exception.Message);
ex.InnerException.ShouldBe(_exception);
}
[Test]
public async Task Should_Get_Issue_Comments()
{
var comments = new List<IssueComment>();
_gitHubClient.Issue.Comment.GetAllForIssue(OWNER, REPOSITORY, ISSUE_NUMBER, Arg.Any<ApiOptions>())
.Returns(Task.FromResult((IReadOnlyList<Octokit.IssueComment>)new List<Octokit.IssueComment>()));
_mapper.Map<IEnumerable<IssueComment>>(Arg.Any<object>())
.Returns(comments);
var result = await _gitHubProvider.GetIssueCommentsAsync(OWNER, REPOSITORY, ISSUE_NUMBER).ConfigureAwait(false);
result.ShouldBeSameAs(comments);
await _gitHubClient.Issue.Comment.Received(1).GetAllForIssue(OWNER, REPOSITORY, ISSUE_NUMBER, Arg.Any<ApiOptions>()).ConfigureAwait(false);
_mapper.Received(1).Map<IEnumerable<IssueComment>>(Arg.Any<object>());
}
[Test]
public async Task Should_Throw_An_Exception_On_Getting_Issue_Comments_For_Non_Existing_Issue_Number()
{
_gitHubClient.Issue.Comment.GetAllForIssue(OWNER, REPOSITORY, ISSUE_NUMBER, Arg.Any<ApiOptions>())
.Returns(Task.FromException<IReadOnlyList<Octokit.IssueComment>>(_notFoundException));
var ex = await Should.ThrowAsync<NotFoundException>(() => _gitHubProvider.GetIssueCommentsAsync(OWNER, REPOSITORY, ISSUE_NUMBER)).ConfigureAwait(false);
ex.Message.ShouldBe(_notFoundException.Message);
ex.InnerException.ShouldBe(_notFoundException);
}
[Test]
public async Task Should_Throw_An_Exception_On_Getting_Issue_Comments()
{
_gitHubClient.Issue.Comment.GetAllForIssue(OWNER, REPOSITORY, ISSUE_NUMBER, Arg.Any<ApiOptions>())
.Returns(Task.FromException<IReadOnlyList<Octokit.IssueComment>>(_exception));
var ex = await Should.ThrowAsync<ApiException>(() => _gitHubProvider.GetIssueCommentsAsync(OWNER, REPOSITORY, ISSUE_NUMBER)).ConfigureAwait(false);
ex.Message.ShouldBe(_exception.Message);
ex.InnerException.ShouldBe(_exception);
}
// Labels
[Test]
public async Task Should_Create_Label()
{
_mapper.Map<Octokit.NewLabel>(Arg.Any<Label>())
.Returns(_newLabel);
_gitHubClient.Issue.Labels.Create(OWNER, REPOSITORY, _newLabel)
.Returns(Task.FromResult(new Octokit.Label()));
await _gitHubProvider.CreateLabelAsync(OWNER, REPOSITORY, new Label()).ConfigureAwait(false);
await _gitHubClient.Issue.Labels.Received(1).Create(OWNER, REPOSITORY, _newLabel).ConfigureAwait(false);
_mapper.Received(1).Map<Octokit.NewLabel>(Arg.Any<Label>());
}
[Test]
public async Task Should_Throw_An_Exception_On_Creating_Label()
{
var label = new Label();
_mapper.Map<Octokit.NewLabel>(label)
.Returns(_newLabel);
_gitHubClient.Issue.Labels.Create(OWNER, REPOSITORY, _newLabel)
.Returns(Task.FromException<Octokit.Label>(_exception));
var ex = await Should.ThrowAsync<ApiException>(() => _gitHubProvider.CreateLabelAsync(OWNER, REPOSITORY, label)).ConfigureAwait(false);
ex.Message.ShouldBe(_exception.Message);
ex.InnerException.ShouldBe(_exception);
}
[Test]
public async Task Should_Delete_Label()
{
_gitHubClient.Issue.Labels.Delete(OWNER, REPOSITORY, LABEL_NAME)
.Returns(Task.FromResult);
await _gitHubProvider.DeleteLabelAsync(OWNER, REPOSITORY, LABEL_NAME).ConfigureAwait(false);
await _gitHubClient.Issue.Labels.Received(1).Delete(OWNER, REPOSITORY, LABEL_NAME).ConfigureAwait(false);
}
[Test]
public async Task Should_Throw_An_Exception_On_Deleting_Label_For_Non_Existing_Label()
{
_gitHubClient.Issue.Labels.Delete(OWNER, REPOSITORY, LABEL_NAME)
.Returns(Task.FromException<IReadOnlyList<Octokit.Label>>(_notFoundException));
var ex = await Should.ThrowAsync<NotFoundException>(() => _gitHubProvider.DeleteLabelAsync(OWNER, REPOSITORY, LABEL_NAME)).ConfigureAwait(false);
ex.Message.ShouldBe(_notFoundException.Message);
ex.InnerException.ShouldBe(_notFoundException);
}
[Test]
public async Task Should_Throw_An_Exception_On_Deleting_Label()
{
_gitHubClient.Issue.Labels.Delete(OWNER, REPOSITORY, LABEL_NAME)
.Returns(Task.FromException<IReadOnlyList<Octokit.Label>>(_exception));
var ex = await Should.ThrowAsync<ApiException>(() => _gitHubProvider.DeleteLabelAsync(OWNER, REPOSITORY, LABEL_NAME)).ConfigureAwait(false);
ex.Message.ShouldBe(_exception.Message);
ex.InnerException.ShouldBe(_exception);
}
[Test]
public async Task Should_Get_Labels()
{
var labels = new List<Label>();
_gitHubClient.Issue.Labels.GetAllForRepository(OWNER, REPOSITORY, Arg.Any<ApiOptions>())
.Returns(Task.FromResult((IReadOnlyList<Octokit.Label>)new List<Octokit.Label>()));
_mapper.Map<IEnumerable<Label>>(Arg.Any<object>())
.Returns(labels);
var result = await _gitHubProvider.GetLabelsAsync(OWNER, REPOSITORY).ConfigureAwait(false);
result.ShouldBeSameAs(labels);
await _gitHubClient.Issue.Labels.Received(1).GetAllForRepository(OWNER, REPOSITORY, Arg.Any<ApiOptions>()).ConfigureAwait(false);
_mapper.ReceivedWithAnyArgs(1).Map<IEnumerable<Label>>(default);
}
[Test]
public async Task Should_Throw_An_Exception_On_Getting_Labels()
{
_gitHubClient.Issue.Labels.GetAllForRepository(OWNER, REPOSITORY, Arg.Any<ApiOptions>())
.Returns(Task.FromException<IReadOnlyList<Octokit.Label>>(_exception));
var ex = await Should.ThrowAsync<ApiException>(() => _gitHubProvider.GetLabelsAsync(OWNER, REPOSITORY)).ConfigureAwait(false);
ex.Message.ShouldBe(_exception.Message);
ex.InnerException.ShouldBe(_exception);
}
// Milestones
[TestCase(ItemStateFilter.Open)]
[TestCase(ItemStateFilter.Closed)]
[TestCase(ItemStateFilter.All)]
public async Task Should_Get_Milestone(ItemStateFilter itemStateFilter)
{
var milestone = new Milestone { Title = MILESTONE_TITLE };
var milestones = new List<Milestone> { milestone };
_gitHubClient.Issue.Milestone.GetAllForRepository(OWNER, REPOSITORY, Arg.Any<MilestoneRequest>(), Arg.Any<ApiOptions>())
.Returns(Task.FromResult((IReadOnlyList<Octokit.Milestone>)new List<Octokit.Milestone>()));
_mapper.Map<IEnumerable<Milestone>>(Arg.Any<object>())
.Returns(milestones);
var result = await _gitHubProvider.GetMilestoneAsync(OWNER, REPOSITORY, MILESTONE_TITLE, itemStateFilter).ConfigureAwait(false);
result.ShouldBeSameAs(milestone);
await _gitHubClient.Issue.Milestone.Received(1).GetAllForRepository(
OWNER,
REPOSITORY,
Arg.Is<MilestoneRequest>(o => o.State == (Octokit.ItemStateFilter)itemStateFilter),
Arg.Any<ApiOptions>()).ConfigureAwait(false);
_mapper.ReceivedWithAnyArgs(1).Map<IEnumerable<Milestone>>(default);
}
[Test]
public async Task Should_Throw_An_Exception_On_Getting_Milestone_For_Non_Existing_Title()
{
_gitHubClient.Issue.Milestone.GetAllForRepository(OWNER, REPOSITORY, Arg.Any<MilestoneRequest>())
.Returns(Task.FromResult((IReadOnlyList<Octokit.Milestone>)new List<Octokit.Milestone>()));
_mapper.Map<IEnumerable<Milestone>>(Arg.Any<object>())
.Returns(new List<Milestone>());
var ex = await Should.ThrowAsync<NotFoundException>(() => _gitHubProvider.GetMilestoneAsync(OWNER, REPOSITORY, MILESTONE_TITLE)).ConfigureAwait(false);
ex.Message.ShouldBe(NOT_FOUND_MESSAGE);
ex.InnerException.ShouldBeNull();
}
[TestCase(ItemStateFilter.Open)]
[TestCase(ItemStateFilter.Closed)]
[TestCase(ItemStateFilter.All)]
public async Task Should_Get_Milestones(ItemStateFilter itemStateFilter)
{
var milestones = new List<Milestone>();
_gitHubClient.Issue.Milestone.GetAllForRepository(OWNER, REPOSITORY, Arg.Any<MilestoneRequest>(), Arg.Any<ApiOptions>())
.Returns(Task.FromResult((IReadOnlyList<Octokit.Milestone>)new List<Octokit.Milestone>()));
_mapper.Map<IEnumerable<Milestone>>(Arg.Any<object>())
.Returns(milestones);
var result = await _gitHubProvider.GetMilestonesAsync(OWNER, REPOSITORY, itemStateFilter).ConfigureAwait(false);
result.ShouldBeSameAs(milestones);
await _gitHubClient.Issue.Milestone.Received(1).GetAllForRepository(
OWNER,
REPOSITORY,
Arg.Is<MilestoneRequest>(o => o.State == (Octokit.ItemStateFilter)itemStateFilter),
Arg.Any<ApiOptions>()).ConfigureAwait(false);
_mapper.ReceivedWithAnyArgs(1).Map<IEnumerable<Milestone>>(default);
}
[Test]
public async Task Should_Throw_An_Exception_On_Getting_Milestones()
{
_gitHubClient.Issue.Milestone.GetAllForRepository(OWNER, REPOSITORY, Arg.Any<MilestoneRequest>(), Arg.Any<ApiOptions>())
.Returns(Task.FromException<IReadOnlyList<Octokit.Milestone>>(_exception));
var ex = await Should.ThrowAsync<ApiException>(() => _gitHubProvider.GetMilestonesAsync(OWNER, REPOSITORY)).ConfigureAwait(false);
ex.Message.ShouldBe(_exception.Message);
ex.InnerException.ShouldBe(_exception);
}
[TestCase(ItemState.Closed)]
[TestCase(ItemState.Open)]
public async Task Should_Set_Milestone_State(ItemState itemState)
{
_gitHubClient.Issue.Milestone.Update(OWNER, REPOSITORY, MILESTONE_NUMBER, Arg.Any<MilestoneUpdate>())
.Returns(Task.FromResult(new Octokit.Milestone()));
await _gitHubProvider.SetMilestoneStateAsync(OWNER, REPOSITORY, MILESTONE_NUMBER, itemState).ConfigureAwait(false);
await _gitHubClient.Issue.Milestone.Received(1).Update(OWNER, REPOSITORY, MILESTONE_NUMBER, Arg.Is<MilestoneUpdate>(o => o.State == (Octokit.ItemState)itemState)).ConfigureAwait(false);
}
[Test]
public async Task Should_Throw_An_Exception_On_Setting_Milestone_State_For_Non_Existent_Number()
{
_gitHubClient.Issue.Milestone.Update(OWNER, REPOSITORY, MILESTONE_NUMBER, Arg.Any<MilestoneUpdate>())
.Returns(Task.FromException<Octokit.Milestone>(_notFoundException));
var ex = await Should.ThrowAsync<NotFoundException>(() => _gitHubProvider.SetMilestoneStateAsync(OWNER, REPOSITORY, MILESTONE_NUMBER, ItemState.Closed)).ConfigureAwait(false);
ex.Message.ShouldBe(_notFoundException.Message);
ex.InnerException.ShouldBeSameAs(_notFoundException);
}
[Test]
public async Task Should_Throw_An_Exception_On_Setting_Milestone_State()
{
_gitHubClient.Issue.Milestone.Update(OWNER, REPOSITORY, MILESTONE_NUMBER, Arg.Any<MilestoneUpdate>())
.Returns(Task.FromException<Octokit.Milestone>(_exception));
var ex = await Should.ThrowAsync<ApiException>(() => _gitHubProvider.SetMilestoneStateAsync(OWNER, REPOSITORY, MILESTONE_NUMBER, ItemState.Closed)).ConfigureAwait(false);
ex.Message.ShouldBe(_exception.Message);
ex.InnerException.ShouldBeSameAs(_exception);
}
// Releases
[Test]
public async Task Should_Create_Release()
{
var createRelease = new Release();
var resultRelease = new Release();
_mapper.Map<Octokit.NewRelease>(createRelease)
.Returns(_newRelease);
_gitHubClient.Repository.Release.Create(OWNER, REPOSITORY, _newRelease)
.Returns(Task.FromResult(new Octokit.Release()));
_mapper.Map<Release>(Arg.Any<Octokit.Release>())
.Returns(resultRelease);
var result = await _gitHubProvider.CreateReleaseAsync(OWNER, REPOSITORY, createRelease).ConfigureAwait(false);
result.ShouldBeSameAs(resultRelease);
await _gitHubClient.Repository.Release.Received(1).Create(OWNER, REPOSITORY, _newRelease).ConfigureAwait(false);
_mapper.Received(1).Map<Octokit.NewRelease>(Arg.Any<Release>());
_mapper.Received(1).Map<Release>(Arg.Any<Octokit.Release>());
}
[Test]
public async Task Should_Throw_An_Exception_On_Creating_Release()
{
var label = new Release();
_mapper.Map<Octokit.NewRelease>(label)
.Returns(_newRelease);
_gitHubClient.Repository.Release.Create(OWNER, REPOSITORY, _newRelease)
.Returns(Task.FromException<Octokit.Release>(_exception));
var ex = await Should.ThrowAsync<ApiException>(() => _gitHubProvider.CreateReleaseAsync(OWNER, REPOSITORY, label)).ConfigureAwait(false);
ex.Message.ShouldBe(_exception.Message);
ex.InnerException.ShouldBe(_exception);
}
[Test]
public async Task Should_Delete_Release()
{
var id = 1;
_gitHubClient.Repository.Release.Delete(OWNER, REPOSITORY, id)
.Returns(Task.CompletedTask);
await _gitHubProvider.DeleteReleaseAsync(OWNER, REPOSITORY, id).ConfigureAwait(false);
await _gitHubClient.Repository.Release.Received(1).Delete(OWNER, REPOSITORY, id).ConfigureAwait(false);
}
[Test]
public async Task Should_Throw_An_Exception_On_Deleting_Release_For_Non_Existent_Id()
{
var id = 1;
_gitHubClient.Repository.Release.Delete(OWNER, REPOSITORY, id)
.Returns(Task.FromException(_notFoundException));
var ex = await Should.ThrowAsync<NotFoundException>(() => _gitHubProvider.DeleteReleaseAsync(OWNER, REPOSITORY, id)).ConfigureAwait(false);
ex.Message.ShouldBe(_notFoundException.Message);
ex.InnerException.ShouldBeSameAs(_notFoundException);
}
[Test]
public async Task Should_Throw_An_Exception_On_Deleting_Release()
{
var id = 1;
_gitHubClient.Repository.Release.Delete(OWNER, REPOSITORY, id)
.Returns(Task.FromException(_exception));
var ex = await Should.ThrowAsync<ApiException>(() => _gitHubProvider.DeleteReleaseAsync(OWNER, REPOSITORY, id)).ConfigureAwait(false);
ex.Message.ShouldBe(_exception.Message);
ex.InnerException.ShouldBeSameAs(_exception);
}
[Test]
public async Task Should_Get_Release()
{
var release = new Release();
_gitHubClient.Repository.Release.Get(OWNER, REPOSITORY, TAG_NAME)
.Returns(Task.FromResult(new Octokit.Release()));
_mapper.Map<Release>(Arg.Any<object>())
.Returns(release);
var result = await _gitHubProvider.GetReleaseAsync(OWNER, REPOSITORY, TAG_NAME).ConfigureAwait(false);
result.ShouldBeSameAs(release);
await _gitHubClient.Repository.Release.Received(1).GetAll(OWNER, REPOSITORY).ConfigureAwait(false);
_mapper.Received(1).Map<Release>(Arg.Any<object>());
}
[Test]
public async Task Should_Return_Null_On_Getting_Release_For_Non_Existent_Tag()
{
_gitHubClient.Repository.Release.Get(OWNER, REPOSITORY, TAG_NAME)
.Returns(Task.FromException<Octokit.Release>(_notFoundException));
var release = await _gitHubProvider.GetReleaseAsync(OWNER, REPOSITORY, TAG_NAME).ConfigureAwait(false);
release.ShouldBeNull();
}
[Test]
public async Task Should_Return_Null_Getting_Release()
{
var release = await _gitHubProvider.GetReleaseAsync(OWNER, REPOSITORY, TAG_NAME).ConfigureAwait(false);
release.ShouldBeNull();
}
[Test]
public async Task Should_Get_Releases()
{
var releases = new List<Release>();
_gitHubClient.Repository.Release.GetAll(OWNER, REPOSITORY, Arg.Any<ApiOptions>())
.Returns(Task.FromResult((IReadOnlyList<Octokit.Release>)new List<Octokit.Release>()));
_mapper.Map<IEnumerable<Release>>(Arg.Any<object>())
.Returns(releases);
var result = await _gitHubProvider.GetReleasesAsync(OWNER, REPOSITORY, SKIP_PRERELEASES).ConfigureAwait(false);
result.ShouldBeSameAs(releases);
await _gitHubClient.Repository.Release.Received(1).GetAll(OWNER, REPOSITORY, Arg.Any<ApiOptions>()).ConfigureAwait(false);
_mapper.Received(1).Map<IEnumerable<Release>>(Arg.Any<object>());
}
[Test]
public async Task Should_Throw_An_Exception_On_Getting_Releases()
{
_gitHubClient.Repository.Release.GetAll(OWNER, REPOSITORY, Arg.Any<ApiOptions>())
.Returns(Task.FromException<IReadOnlyList<Octokit.Release>>(_exception));
var ex = await Should.ThrowAsync<ApiException>(() => _gitHubProvider.GetReleasesAsync(OWNER, REPOSITORY, SKIP_PRERELEASES)).ConfigureAwait(false);
ex.Message.ShouldBe(_exception.Message);
ex.InnerException.ShouldBe(_exception);
}
[Test]
public async Task Should_Publish_Release()
{
_gitHubClient.Repository.Release.Edit(OWNER, REPOSITORY, RELEASE_ID, Arg.Any<ReleaseUpdate>())
.Returns(Task.FromResult(new Octokit.Release()));
await _gitHubProvider.PublishReleaseAsync(OWNER, REPOSITORY, TAG_NAME, RELEASE_ID).ConfigureAwait(false);
await _gitHubClient.Repository.Release.Received(1).Edit(OWNER, REPOSITORY, RELEASE_ID, Arg.Is<ReleaseUpdate>(o =>
o.Draft == false &&
o.TagName == TAG_NAME)).ConfigureAwait(false);
}
[Test]
public async Task Should_Throw_An_Exception_On_Publishing_Release_For_Non_Existent_Id()
{
_gitHubClient.Repository.Release.Edit(OWNER, REPOSITORY, RELEASE_ID, Arg.Any<ReleaseUpdate>())
.Returns(Task.FromException<Octokit.Release>(_notFoundException));
var ex = await Should.ThrowAsync<NotFoundException>(() => _gitHubProvider.PublishReleaseAsync(OWNER, REPOSITORY, TAG_NAME, RELEASE_ID)).ConfigureAwait(false);
ex.Message.ShouldBe(_notFoundException.Message);
ex.InnerException.ShouldBe(_notFoundException);
}
[Test]
public async Task Should_Throw_An_Exception_On_Publishing_Release()
{
_gitHubClient.Repository.Release.Edit(OWNER, REPOSITORY, RELEASE_ID, Arg.Any<ReleaseUpdate>())
.Returns(Task.FromException<Octokit.Release>(_exception));
var ex = await Should.ThrowAsync<ApiException>(() => _gitHubProvider.PublishReleaseAsync(OWNER, REPOSITORY, TAG_NAME, RELEASE_ID)).ConfigureAwait(false);
ex.Message.ShouldBe(_exception.Message);
ex.InnerException.ShouldBe(_exception);
}
[Test]
public async Task Should_Update_Release()
{
var release = new Release
{
Id = RELEASE_ID,
Body = "Body",
Draft = true,
Name = "Name",
Prerelease = true,
TagName = "TagName",
TargetCommitish = "TargetCommitish",
};
_gitHubClient.Repository.Release.Edit(OWNER, REPOSITORY, release.Id, Arg.Any<ReleaseUpdate>())
.Returns(Task.FromResult(new Octokit.Release()));
await _gitHubProvider.UpdateReleaseAsync(OWNER, REPOSITORY, release).ConfigureAwait(false);
await _gitHubClient.Repository.Release.Received(1).Edit(OWNER, REPOSITORY, release.Id, Arg.Is<ReleaseUpdate>(o =>
o.Body == release.Body &&
o.Draft == release.Draft &&
o.Name == release.Name &&
o.Prerelease == release.Prerelease &&
o.TagName == release.TagName &&
o.TargetCommitish == release.TargetCommitish)).ConfigureAwait(false);
}
[Test]
public async Task Should_Throw_An_Exception_On_Updating_Release_For_Non_Existent_Id()
{
var release = new Release { Id = RELEASE_ID };
_gitHubClient.Repository.Release.Edit(OWNER, REPOSITORY, release.Id, Arg.Any<ReleaseUpdate>())
.Returns(Task.FromException<Octokit.Release>(_notFoundException));
var ex = await Should.ThrowAsync<NotFoundException>(() => _gitHubProvider.UpdateReleaseAsync(OWNER, REPOSITORY, release)).ConfigureAwait(false);
ex.Message.ShouldBe(_notFoundException.Message);
ex.InnerException.ShouldBe(_notFoundException);
}
[Test]
public async Task Should_Throw_An_Exception_On_Updating_Release()
{
var release = new Release { Id = RELEASE_ID };
_gitHubClient.Repository.Release.Edit(OWNER, REPOSITORY, release.Id, Arg.Any<ReleaseUpdate>())
.Returns(Task.FromException<Octokit.Release>(_exception));
var ex = await Should.ThrowAsync<ApiException>(() => _gitHubProvider.UpdateReleaseAsync(OWNER, REPOSITORY, release)).ConfigureAwait(false);
ex.Message.ShouldBe(_exception.Message);
ex.InnerException.ShouldBe(_exception);
}
[Test]
public void Should_Get_Rate_Limit()
{
var rateLimit = new RateLimit();
var apiInfo = new Octokit.ApiInfo(new Dictionary<string, Uri>(), new List<string>(), new List<string>(), string.Empty, new Octokit.RateLimit());
_gitHubClient.GetLastApiInfo()
.Returns(apiInfo);
_mapper.Map<RateLimit>(apiInfo.RateLimit)
.Returns(rateLimit);
var result = _gitHubProvider.GetRateLimit();
result.ShouldBeSameAs(rateLimit);
_gitHubClient.Received(1).GetLastApiInfo();
_mapper.Received(1).Map<RateLimit>(apiInfo.RateLimit);
}
[Test]
public void Should_Throw_An_Exception_On_Getting_Rate_Limit()
{
_gitHubClient.GetLastApiInfo()
.Throws(_exception);
var ex = Should.Throw<ApiException>(() => _gitHubProvider.GetRateLimit());
ex.Message.ShouldBe(_exception.Message);
ex.InnerException.ShouldBe(_exception);
}
}
}
| |
using System.Collections.Generic;
using System.Threading.Tasks;
using FitBot.Model;
using FitBot.Services;
namespace FitBot.Development
{
public class ExtraFollowersFitocracyDecorator : BaseFitocracyDecorator
{
public ExtraFollowersFitocracyDecorator(IFitocracyService decorated)
: base(decorated)
{
}
public override async Task<IList<User>> GetFollowers(int pageNum = 0)
{
var users = await base.GetFollowers(pageNum);
if (pageNum == 0)
{
//OTHER
users.Insert(0, new User {Id = 1728298, Username = "jperona"});
//RANDOM USERS
users.Insert(0, new User {Id = 1499493, Username = "Lillith32"});
users.Insert(0, new User {Id = 29512, Username = "JasonSuave"});
users.Insert(0, new User {Id = 1287135, Username = "plin_a"});
users.Insert(0, new User {Id = 1307284, Username = "BarrelOfSnakes"});
users.Insert(0, new User {Id = 134275, Username = "magnet"});
users.Insert(0, new User {Id = 1469979, Username = "vwalls99"});
users.Insert(0, new User {Id = 1514806, Username = "alandw"});
users.Insert(0, new User {Id = 154080, Username = "Shijin"});
users.Insert(0, new User {Id = 1604393, Username = "lukasiniho"});
users.Insert(0, new User {Id = 1629824, Username = "jbclay916"});
users.Insert(0, new User {Id = 253665, Username = "jrcchicago"});
users.Insert(0, new User {Id = 281261, Username = "Eyila"});
users.Insert(0, new User {Id = 384412, Username = "KristinaBodin"});
users.Insert(0, new User {Id = 385463, Username = "zmartin"});
users.Insert(0, new User {Id = 419593, Username = "Max_Power"});
users.Insert(0, new User {Id = 438823, Username = "AFitParent"});
users.Insert(0, new User {Id = 548901, Username = "Lothil"});
users.Insert(0, new User {Id = 792824, Username = "ChafedConfused"});
users.Insert(0, new User {Id = 818265, Username = "melabelle"});
users.Insert(0, new User {Id = 818810, Username = "danny_terrell29"});
//EARLY USERS
users.Insert(0, new User {Id = 1, Username = "FRED"});
users.Insert(0, new User {Id = 2, Username = "xenowang"});
users.Insert(0, new User {Id = 4, Username = "robinsparkles"});
users.Insert(0, new User {Id = 5, Username = "July"});
users.Insert(0, new User {Id = 6, Username = "kynes"});
users.Insert(0, new User {Id = 12, Username = "Patrick"});
users.Insert(0, new User {Id = 14, Username = "crazedazn203"});
users.Insert(0, new User {Id = 15, Username = "atryon"});
users.Insert(0, new User {Id = 16, Username = "TiderA"});
users.Insert(0, new User {Id = 17, Username = "ScotterC"});
users.Insert(0, new User {Id = 18, Username = "heavyliftah"});
users.Insert(0, new User {Id = 19, Username = "huangbp"});
users.Insert(0, new User {Id = 20, Username = "pablitoguth"});
users.Insert(0, new User {Id = 21, Username = "alanwdang"});
users.Insert(0, new User {Id = 22, Username = "Alesin"});
users.Insert(0, new User {Id = 23, Username = "kyoung"});
users.Insert(0, new User {Id = 28, Username = "dfrancis"});
users.Insert(0, new User {Id = 31, Username = "mgadow"});
users.Insert(0, new User {Id = 36, Username = "severedties"});
users.Insert(0, new User {Id = 38, Username = "Damienmyers"});
users.Insert(0, new User {Id = 39, Username = "Bagricula"});
users.Insert(0, new User {Id = 40, Username = "edwkim"});
users.Insert(0, new User {Id = 43, Username = "bliztacular"});
users.Insert(0, new User {Id = 44, Username = "rockcreekperk"});
users.Insert(0, new User {Id = 46, Username = "mobileglobal"});
users.Insert(0, new User {Id = 48, Username = "missambitions"});
users.Insert(0, new User {Id = 50, Username = "pescatello"});
users.Insert(0, new User {Id = 51, Username = "dshih"});
users.Insert(0, new User {Id = 52, Username = "smalter"});
users.Insert(0, new User {Id = 56, Username = "Alli89"});
users.Insert(0, new User {Id = 57, Username = "mschm"});
users.Insert(0, new User {Id = 59, Username = "rhiesa"});
users.Insert(0, new User {Id = 60, Username = "julianbell"});
users.Insert(0, new User {Id = 63, Username = "zazamor"});
users.Insert(0, new User {Id = 64, Username = "lilikoi"});
users.Insert(0, new User {Id = 65, Username = "ivanpk"});
users.Insert(0, new User {Id = 67, Username = "bbqcow"});
users.Insert(0, new User {Id = 68, Username = "Matt"});
users.Insert(0, new User {Id = 69, Username = "kevinh0143"});
users.Insert(0, new User {Id = 70, Username = "stickshift"});
//RECENT USERS
users.Insert(0, new User {Id = 1052041, Username = "bette_"});
users.Insert(0, new User {Id = 1092870, Username = "aztek1099"});
users.Insert(0, new User {Id = 1129889, Username = "gusts94"});
users.Insert(0, new User {Id = 1136408, Username = "Justin_44"});
users.Insert(0, new User {Id = 1148675, Username = "BalintGabriel"});
users.Insert(0, new User {Id = 1184136, Username = "alleday_cross"});
users.Insert(0, new User {Id = 1212190, Username = "manahime193"});
users.Insert(0, new User {Id = 1219800, Username = "Lanalia"});
users.Insert(0, new User {Id = 125933, Username = "dottore"});
users.Insert(0, new User {Id = 1347872, Username = "marster"});
users.Insert(0, new User {Id = 1355466, Username = "cacheng88"});
users.Insert(0, new User {Id = 136113, Username = "AprilCat"});
users.Insert(0, new User {Id = 1363908, Username = "H_Saxon"});
users.Insert(0, new User {Id = 137833, Username = "Eha"});
users.Insert(0, new User {Id = 1430777, Username = "bbooth29"});
users.Insert(0, new User {Id = 1482231, Username = "alisontgillaspy"});
users.Insert(0, new User {Id = 1490528, Username = "dmatsuura"});
users.Insert(0, new User {Id = 1510968, Username = "farshad"});
users.Insert(0, new User {Id = 1551259, Username = "RAW-in-caps"});
users.Insert(0, new User {Id = 15636, Username = "TheDart"});
users.Insert(0, new User {Id = 1603955, Username = "saharat83"});
users.Insert(0, new User {Id = 1609404, Username = "missdevonlynne"});
users.Insert(0, new User {Id = 1612283, Username = "JohnDozer"});
users.Insert(0, new User {Id = 1621554, Username = "anni_martikaine"});
users.Insert(0, new User {Id = 1632861, Username = "chap2850"});
users.Insert(0, new User {Id = 170355, Username = "LegaTron"});
users.Insert(0, new User {Id = 176346, Username = "tapani"});
users.Insert(0, new User {Id = 183486, Username = "Edgemo2001"});
users.Insert(0, new User {Id = 202423, Username = "dvdlcs"});
users.Insert(0, new User {Id = 2043, Username = "none"});
users.Insert(0, new User {Id = 214700, Username = "Bantering_Ram"});
users.Insert(0, new User {Id = 279913, Username = "powahmonkee"});
users.Insert(0, new User {Id = 284099, Username = "Cheese_Sandwich"});
users.Insert(0, new User {Id = 301366, Username = "hrr5010"});
users.Insert(0, new User {Id = 309175, Username = "Wellfleet"});
users.Insert(0, new User {Id = 41076, Username = "Brick_121"});
users.Insert(0, new User {Id = 436689, Username = "Georgina"});
users.Insert(0, new User {Id = 44036, Username = "erikjmc"});
users.Insert(0, new User {Id = 458580, Username = "Sensei_Lars"});
users.Insert(0, new User {Id = 492969, Username = "ParaMagician"});
users.Insert(0, new User {Id = 511533, Username = "MightyMora"});
users.Insert(0, new User {Id = 574536, Username = "likedevilsrain"});
users.Insert(0, new User {Id = 593635, Username = "amukid92"});
users.Insert(0, new User {Id = 596250, Username = "brianofarrell"});
users.Insert(0, new User {Id = 596481, Username = "adamlazaro"});
users.Insert(0, new User {Id = 610219, Username = "Carpathia_wave"});
users.Insert(0, new User {Id = 629758, Username = "a_ron50"});
users.Insert(0, new User {Id = 655193, Username = "sudofaulkner"});
users.Insert(0, new User {Id = 714560, Username = "grekulf"});
users.Insert(0, new User {Id = 762071, Username = "barbiefriend"});
users.Insert(0, new User {Id = 78155, Username = "dpyro"});
users.Insert(0, new User {Id = 809415, Username = "the_krister"});
users.Insert(0, new User {Id = 820365, Username = "mathieu_f"});
users.Insert(0, new User {Id = 832426, Username = "svenk"});
users.Insert(0, new User {Id = 83350, Username = "edicius"});
users.Insert(0, new User {Id = 852756, Username = "Mr_Dizzel"});
users.Insert(0, new User {Id = 874017, Username = "kaschongs"});
users.Insert(0, new User {Id = 881530, Username = "beanedge"});
users.Insert(0, new User {Id = 89293, Username = "jmolife"});
users.Insert(0, new User {Id = 95503, Username = "MichaelVo"});
//ALL TIME LEADERS
users.Insert(0, new User {Id = 370742, Username = "K-BEAST"});
users.Insert(0, new User {Id = 108557, Username = "EVeksler"});
users.Insert(0, new User {Id = 11020, Username = "Silenced_Knight"});
users.Insert(0, new User {Id = 202035, Username = "WiselyChosen"});
users.Insert(0, new User {Id = 103397, Username = "TheGreatMD"});
users.Insert(0, new User {Id = 444100, Username = "jkresh"});
users.Insert(0, new User {Id = 39535, Username = "fellrnr"});
users.Insert(0, new User {Id = 459746, Username = "Eric_Brown"});
users.Insert(0, new User {Id = 420532, Username = "Clefspeare"});
users.Insert(0, new User {Id = 102630, Username = "j0n"});
users.Insert(0, new User {Id = 118691, Username = "ocja0201"});
users.Insert(0, new User {Id = 614442, Username = "RyanLovesBacon"});
users.Insert(0, new User {Id = 944953, Username = "skellar2006"});
users.Insert(0, new User {Id = 97120, Username = "Motivated_Doc"});
users.Insert(0, new User {Id = 127947, Username = "MikeLaBossiere"});
users.Insert(0, new User {Id = 78493, Username = "kkitsune"});
users.Insert(0, new User {Id = 145779, Username = "JohnRock"});
users.Insert(0, new User {Id = 89520, Username = "Saracenn"});
users.Insert(0, new User {Id = 291168, Username = "Varangian"});
users.Insert(0, new User {Id = 39881, Username = "Segugio"});
//90 DAY LEADERS
users.Insert(0, new User {Id = 1317753, Username = "myrunningshoes"});
users.Insert(0, new User {Id = 1313975, Username = "scullerzpe"});
users.Insert(0, new User {Id = 1452700, Username = "regretting"});
users.Insert(0, new User {Id = 1216860, Username = "olivia_lasche"});
users.Insert(0, new User {Id = 1413891, Username = "JASON-MVP"});
users.Insert(0, new User {Id = 291833, Username = "GDesfarges"});
users.Insert(0, new User {Id = 526700, Username = "Xomby"});
users.Insert(0, new User {Id = 1498364, Username = "-O-Boy-"});
users.Insert(0, new User {Id = 600990, Username = "PeteT"});
users.Insert(0, new User {Id = 1480500, Username = "drew_7"});
users.Insert(0, new User {Id = 1094386, Username = "fit007"});
users.Insert(0, new User {Id = 678604, Username = "MiguelFurtado"});
users.Insert(0, new User {Id = 1487258, Username = "NicoleTrevisan"});
users.Insert(0, new User {Id = 249804, Username = "Raurisz"});
users.Insert(0, new User {Id = 1481812, Username = "rapidrich2"});
users.Insert(0, new User {Id = 1398246, Username = "Xtrem-E"});
users.Insert(0, new User {Id = 1311105, Username = "JackBrookes"});
users.Insert(0, new User {Id = 1290340, Username = "JustinPBG"});
users.Insert(0, new User {Id = 805162, Username = "LilPanda34"});
users.Insert(0, new User {Id = 1285933, Username = "BDinthecrowd"});
//30 DAY LEADERS
users.Insert(0, new User {Id = 1590163, Username = "OkCountryBoy"});
users.Insert(0, new User {Id = 1170581, Username = "mikeb12"});
users.Insert(0, new User {Id = 553711, Username = "jigbim1"});
users.Insert(0, new User {Id = 892834, Username = "mikeaguirre"});
users.Insert(0, new User {Id = 1541513, Username = "benchythesequel"});
users.Insert(0, new User {Id = 125884, Username = "ChinoZ32"});
users.Insert(0, new User {Id = 574076, Username = "acronuts"});
users.Insert(0, new User {Id = 665834, Username = "SonneJS"});
users.Insert(0, new User {Id = 1275522, Username = "Ultimateprice16"});
users.Insert(0, new User {Id = 1114402, Username = "ChristelKessler"});
users.Insert(0, new User {Id = 1134161, Username = "euphoracy"});
users.Insert(0, new User {Id = 116047, Username = "gloomchen"});
users.Insert(0, new User {Id = 1326055, Username = "brennah"});
users.Insert(0, new User {Id = 63328, Username = "breic"});
users.Insert(0, new User {Id = 1410990, Username = "Sveneezy"});
users.Insert(0, new User {Id = 939654, Username = "zvonimir_vanjak"});
users.Insert(0, new User {Id = 1137716, Username = "djfunkep"});
users.Insert(0, new User {Id = 605351, Username = "HappyRunnerGirl"});
users.Insert(0, new User {Id = 265773, Username = "Jarkko"});
users.Insert(0, new User {Id = 1515872, Username = "seeAnna"});
}
return users;
}
}
}
| |
namespace java.nio.channels
{
[global::MonoJavaBridge.JavaClass(typeof(global::java.nio.channels.SelectionKey_))]
public abstract partial class SelectionKey : java.lang.Object
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
static SelectionKey()
{
InitJNI();
}
protected SelectionKey(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
internal static global::MonoJavaBridge.MethodId _channel14532;
public abstract global::java.nio.channels.SelectableChannel channel();
internal static global::MonoJavaBridge.MethodId _isValid14533;
public abstract bool isValid();
internal static global::MonoJavaBridge.MethodId _cancel14534;
public abstract void cancel();
internal static global::MonoJavaBridge.MethodId _selector14535;
public abstract global::java.nio.channels.Selector selector();
internal static global::MonoJavaBridge.MethodId _interestOps14536;
public abstract int interestOps();
internal static global::MonoJavaBridge.MethodId _interestOps14537;
public abstract global::java.nio.channels.SelectionKey interestOps(int arg0);
internal static global::MonoJavaBridge.MethodId _attach14538;
public virtual global::java.lang.Object attach(java.lang.Object arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.nio.channels.SelectionKey._attach14538, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.Object;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.nio.channels.SelectionKey.staticClass, global::java.nio.channels.SelectionKey._attach14538, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.Object;
}
internal static global::MonoJavaBridge.MethodId _attachment14539;
public virtual global::java.lang.Object attachment()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.nio.channels.SelectionKey._attachment14539)) as java.lang.Object;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.nio.channels.SelectionKey.staticClass, global::java.nio.channels.SelectionKey._attachment14539)) as java.lang.Object;
}
internal static global::MonoJavaBridge.MethodId _readyOps14540;
public abstract int readyOps();
internal static global::MonoJavaBridge.MethodId _isReadable14541;
public virtual bool isReadable()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::java.nio.channels.SelectionKey._isReadable14541);
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::java.nio.channels.SelectionKey.staticClass, global::java.nio.channels.SelectionKey._isReadable14541);
}
internal static global::MonoJavaBridge.MethodId _isWritable14542;
public virtual bool isWritable()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::java.nio.channels.SelectionKey._isWritable14542);
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::java.nio.channels.SelectionKey.staticClass, global::java.nio.channels.SelectionKey._isWritable14542);
}
internal static global::MonoJavaBridge.MethodId _isConnectable14543;
public virtual bool isConnectable()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::java.nio.channels.SelectionKey._isConnectable14543);
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::java.nio.channels.SelectionKey.staticClass, global::java.nio.channels.SelectionKey._isConnectable14543);
}
internal static global::MonoJavaBridge.MethodId _isAcceptable14544;
public virtual bool isAcceptable()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::java.nio.channels.SelectionKey._isAcceptable14544);
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::java.nio.channels.SelectionKey.staticClass, global::java.nio.channels.SelectionKey._isAcceptable14544);
}
internal static global::MonoJavaBridge.MethodId _SelectionKey14545;
protected SelectionKey() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(java.nio.channels.SelectionKey.staticClass, global::java.nio.channels.SelectionKey._SelectionKey14545);
Init(@__env, handle);
}
public static int OP_READ
{
get
{
return 1;
}
}
public static int OP_WRITE
{
get
{
return 4;
}
}
public static int OP_CONNECT
{
get
{
return 8;
}
}
public static int OP_ACCEPT
{
get
{
return 16;
}
}
private static void InitJNI()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::java.nio.channels.SelectionKey.staticClass = @__env.NewGlobalRef(@__env.FindClass("java/nio/channels/SelectionKey"));
global::java.nio.channels.SelectionKey._channel14532 = @__env.GetMethodIDNoThrow(global::java.nio.channels.SelectionKey.staticClass, "channel", "()Ljava/nio/channels/SelectableChannel;");
global::java.nio.channels.SelectionKey._isValid14533 = @__env.GetMethodIDNoThrow(global::java.nio.channels.SelectionKey.staticClass, "isValid", "()Z");
global::java.nio.channels.SelectionKey._cancel14534 = @__env.GetMethodIDNoThrow(global::java.nio.channels.SelectionKey.staticClass, "cancel", "()V");
global::java.nio.channels.SelectionKey._selector14535 = @__env.GetMethodIDNoThrow(global::java.nio.channels.SelectionKey.staticClass, "selector", "()Ljava/nio/channels/Selector;");
global::java.nio.channels.SelectionKey._interestOps14536 = @__env.GetMethodIDNoThrow(global::java.nio.channels.SelectionKey.staticClass, "interestOps", "()I");
global::java.nio.channels.SelectionKey._interestOps14537 = @__env.GetMethodIDNoThrow(global::java.nio.channels.SelectionKey.staticClass, "interestOps", "(I)Ljava/nio/channels/SelectionKey;");
global::java.nio.channels.SelectionKey._attach14538 = @__env.GetMethodIDNoThrow(global::java.nio.channels.SelectionKey.staticClass, "attach", "(Ljava/lang/Object;)Ljava/lang/Object;");
global::java.nio.channels.SelectionKey._attachment14539 = @__env.GetMethodIDNoThrow(global::java.nio.channels.SelectionKey.staticClass, "attachment", "()Ljava/lang/Object;");
global::java.nio.channels.SelectionKey._readyOps14540 = @__env.GetMethodIDNoThrow(global::java.nio.channels.SelectionKey.staticClass, "readyOps", "()I");
global::java.nio.channels.SelectionKey._isReadable14541 = @__env.GetMethodIDNoThrow(global::java.nio.channels.SelectionKey.staticClass, "isReadable", "()Z");
global::java.nio.channels.SelectionKey._isWritable14542 = @__env.GetMethodIDNoThrow(global::java.nio.channels.SelectionKey.staticClass, "isWritable", "()Z");
global::java.nio.channels.SelectionKey._isConnectable14543 = @__env.GetMethodIDNoThrow(global::java.nio.channels.SelectionKey.staticClass, "isConnectable", "()Z");
global::java.nio.channels.SelectionKey._isAcceptable14544 = @__env.GetMethodIDNoThrow(global::java.nio.channels.SelectionKey.staticClass, "isAcceptable", "()Z");
global::java.nio.channels.SelectionKey._SelectionKey14545 = @__env.GetMethodIDNoThrow(global::java.nio.channels.SelectionKey.staticClass, "<init>", "()V");
}
}
[global::MonoJavaBridge.JavaProxy(typeof(global::java.nio.channels.SelectionKey))]
public sealed partial class SelectionKey_ : java.nio.channels.SelectionKey
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
static SelectionKey_()
{
InitJNI();
}
internal SelectionKey_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
internal static global::MonoJavaBridge.MethodId _channel14546;
public override global::java.nio.channels.SelectableChannel channel()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.nio.channels.SelectionKey_._channel14546)) as java.nio.channels.SelectableChannel;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.nio.channels.SelectionKey_.staticClass, global::java.nio.channels.SelectionKey_._channel14546)) as java.nio.channels.SelectableChannel;
}
internal static global::MonoJavaBridge.MethodId _isValid14547;
public override bool isValid()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::java.nio.channels.SelectionKey_._isValid14547);
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::java.nio.channels.SelectionKey_.staticClass, global::java.nio.channels.SelectionKey_._isValid14547);
}
internal static global::MonoJavaBridge.MethodId _cancel14548;
public override void cancel()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::java.nio.channels.SelectionKey_._cancel14548);
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::java.nio.channels.SelectionKey_.staticClass, global::java.nio.channels.SelectionKey_._cancel14548);
}
internal static global::MonoJavaBridge.MethodId _selector14549;
public override global::java.nio.channels.Selector selector()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.nio.channels.SelectionKey_._selector14549)) as java.nio.channels.Selector;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.nio.channels.SelectionKey_.staticClass, global::java.nio.channels.SelectionKey_._selector14549)) as java.nio.channels.Selector;
}
internal static global::MonoJavaBridge.MethodId _interestOps14550;
public override int interestOps()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::java.nio.channels.SelectionKey_._interestOps14550);
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::java.nio.channels.SelectionKey_.staticClass, global::java.nio.channels.SelectionKey_._interestOps14550);
}
internal static global::MonoJavaBridge.MethodId _interestOps14551;
public override global::java.nio.channels.SelectionKey interestOps(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.nio.channels.SelectionKey_._interestOps14551, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.nio.channels.SelectionKey;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.nio.channels.SelectionKey_.staticClass, global::java.nio.channels.SelectionKey_._interestOps14551, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.nio.channels.SelectionKey;
}
internal static global::MonoJavaBridge.MethodId _readyOps14552;
public override int readyOps()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::java.nio.channels.SelectionKey_._readyOps14552);
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::java.nio.channels.SelectionKey_.staticClass, global::java.nio.channels.SelectionKey_._readyOps14552);
}
private static void InitJNI()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::java.nio.channels.SelectionKey_.staticClass = @__env.NewGlobalRef(@__env.FindClass("java/nio/channels/SelectionKey"));
global::java.nio.channels.SelectionKey_._channel14546 = @__env.GetMethodIDNoThrow(global::java.nio.channels.SelectionKey_.staticClass, "channel", "()Ljava/nio/channels/SelectableChannel;");
global::java.nio.channels.SelectionKey_._isValid14547 = @__env.GetMethodIDNoThrow(global::java.nio.channels.SelectionKey_.staticClass, "isValid", "()Z");
global::java.nio.channels.SelectionKey_._cancel14548 = @__env.GetMethodIDNoThrow(global::java.nio.channels.SelectionKey_.staticClass, "cancel", "()V");
global::java.nio.channels.SelectionKey_._selector14549 = @__env.GetMethodIDNoThrow(global::java.nio.channels.SelectionKey_.staticClass, "selector", "()Ljava/nio/channels/Selector;");
global::java.nio.channels.SelectionKey_._interestOps14550 = @__env.GetMethodIDNoThrow(global::java.nio.channels.SelectionKey_.staticClass, "interestOps", "()I");
global::java.nio.channels.SelectionKey_._interestOps14551 = @__env.GetMethodIDNoThrow(global::java.nio.channels.SelectionKey_.staticClass, "interestOps", "(I)Ljava/nio/channels/SelectionKey;");
global::java.nio.channels.SelectionKey_._readyOps14552 = @__env.GetMethodIDNoThrow(global::java.nio.channels.SelectionKey_.staticClass, "readyOps", "()I");
}
}
}
| |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using NUnit.Framework;
using osu.Framework.Audio.Track;
using osu.Framework.Graphics.Textures;
using osu.Framework.IO.Stores;
using osu.Game.Beatmaps;
using osu.Game.Beatmaps.ControlPoints;
using osu.Game.Beatmaps.Formats;
using osu.Game.Beatmaps.Legacy;
using osu.Game.IO;
using osu.Game.IO.Serialization;
using osu.Game.Rulesets.Catch;
using osu.Game.Rulesets.Mania;
using osu.Game.Rulesets.Objects;
using osu.Game.Rulesets.Objects.Types;
using osu.Game.Rulesets.Osu;
using osu.Game.Rulesets.Osu.Objects;
using osu.Game.Rulesets.Taiko;
using osu.Game.Skinning;
using osu.Game.Tests.Resources;
using osuTK;
namespace osu.Game.Tests.Beatmaps.Formats
{
[TestFixture]
public class LegacyBeatmapEncoderTest
{
private static readonly DllResourceStore beatmaps_resource_store = TestResources.GetStore();
private static IEnumerable<string> allBeatmaps = beatmaps_resource_store.GetAvailableResources().Where(res => res.EndsWith(".osu", StringComparison.Ordinal));
[TestCaseSource(nameof(allBeatmaps))]
public void TestEncodeDecodeStability(string name)
{
var decoded = decodeFromLegacy(beatmaps_resource_store.GetStream(name), name);
var decodedAfterEncode = decodeFromLegacy(encodeToLegacy(decoded), name);
sort(decoded.beatmap);
sort(decodedAfterEncode.beatmap);
compareBeatmaps(decoded, decodedAfterEncode);
}
[TestCaseSource(nameof(allBeatmaps))]
public void TestEncodeDecodeStabilityDoubleConvert(string name)
{
var decoded = decodeFromLegacy(beatmaps_resource_store.GetStream(name), name);
var decodedAfterEncode = decodeFromLegacy(encodeToLegacy(decoded), name);
// run an extra convert. this is expected to be stable.
decodedAfterEncode.beatmap = convert(decodedAfterEncode.beatmap);
sort(decoded.beatmap);
sort(decodedAfterEncode.beatmap);
compareBeatmaps(decoded, decodedAfterEncode);
}
[TestCaseSource(nameof(allBeatmaps))]
public void TestEncodeDecodeStabilityWithNonLegacyControlPoints(string name)
{
var decoded = decodeFromLegacy(beatmaps_resource_store.GetStream(name), name);
// we are testing that the transfer of relevant data to hitobjects (from legacy control points) sticks through encode/decode.
// before the encode step, the legacy information is removed here.
decoded.beatmap.ControlPointInfo = removeLegacyControlPointTypes(decoded.beatmap.ControlPointInfo);
var decodedAfterEncode = decodeFromLegacy(encodeToLegacy(decoded), name);
compareBeatmaps(decoded, decodedAfterEncode);
ControlPointInfo removeLegacyControlPointTypes(ControlPointInfo controlPointInfo)
{
// emulate non-legacy control points by cloning the non-legacy portion.
// the assertion is that the encoder can recreate this losslessly from hitobject data.
Assert.IsInstanceOf<LegacyControlPointInfo>(controlPointInfo);
var newControlPoints = new ControlPointInfo();
foreach (var point in controlPointInfo.AllControlPoints)
{
// completely ignore "legacy" types, which have been moved to HitObjects.
// even though these would mostly be ignored by the Add call, they will still be available in groups,
// which isn't what we want to be testing here.
if (point is SampleControlPoint || point is DifficultyControlPoint)
continue;
newControlPoints.Add(point.Time, point.DeepClone());
}
return newControlPoints;
}
}
private void compareBeatmaps((IBeatmap beatmap, TestLegacySkin skin) expected, (IBeatmap beatmap, TestLegacySkin skin) actual)
{
// Check all control points that are still considered to be at a global level.
Assert.That(expected.beatmap.ControlPointInfo.TimingPoints.Serialize(), Is.EqualTo(actual.beatmap.ControlPointInfo.TimingPoints.Serialize()));
Assert.That(expected.beatmap.ControlPointInfo.EffectPoints.Serialize(), Is.EqualTo(actual.beatmap.ControlPointInfo.EffectPoints.Serialize()));
// Check all hitobjects.
Assert.That(expected.beatmap.HitObjects.Serialize(), Is.EqualTo(actual.beatmap.HitObjects.Serialize()));
// Check skin.
Assert.IsTrue(areComboColoursEqual(expected.skin.Configuration, actual.skin.Configuration));
}
[Test]
public void TestEncodeMultiSegmentSliderWithFloatingPointError()
{
var beatmap = new Beatmap
{
HitObjects =
{
new Slider
{
Position = new Vector2(0.6f),
Path = new SliderPath(new[]
{
new PathControlPoint(Vector2.Zero, PathType.Bezier),
new PathControlPoint(new Vector2(0.5f)),
new PathControlPoint(new Vector2(0.51f)), // This is actually on the same position as the previous one in legacy beatmaps (truncated to int).
new PathControlPoint(new Vector2(1f), PathType.Bezier),
new PathControlPoint(new Vector2(2f))
})
},
}
};
var decodedAfterEncode = decodeFromLegacy(encodeToLegacy((beatmap, new TestLegacySkin(beatmaps_resource_store, string.Empty))), string.Empty);
var decodedSlider = (Slider)decodedAfterEncode.beatmap.HitObjects[0];
Assert.That(decodedSlider.Path.ControlPoints.Count, Is.EqualTo(5));
}
private bool areComboColoursEqual(IHasComboColours a, IHasComboColours b)
{
// equal to null, no need to SequenceEqual
if (a.ComboColours == null && b.ComboColours == null)
return true;
if (a.ComboColours == null || b.ComboColours == null)
return false;
return a.ComboColours.SequenceEqual(b.ComboColours);
}
private void sort(IBeatmap beatmap)
{
// Sort control points to ensure a sane ordering, as they may be parsed in different orders. This works because each group contains only uniquely-typed control points.
foreach (var g in beatmap.ControlPointInfo.Groups)
{
ArrayList.Adapter((IList)g.ControlPoints).Sort(
Comparer<ControlPoint>.Create((c1, c2) => string.Compare(c1.GetType().ToString(), c2.GetType().ToString(), StringComparison.Ordinal)));
}
}
private (IBeatmap beatmap, TestLegacySkin skin) decodeFromLegacy(Stream stream, string name)
{
using (var reader = new LineBufferedReader(stream))
{
var beatmap = new LegacyBeatmapDecoder { ApplyOffsets = false }.Decode(reader);
var beatmapSkin = new TestLegacySkin(beatmaps_resource_store, name);
return (convert(beatmap), beatmapSkin);
}
}
private class TestLegacySkin : LegacySkin
{
public TestLegacySkin(IResourceStore<byte[]> storage, string fileName)
: base(new SkinInfo { Name = "Test Skin", Creator = "Craftplacer" }, storage, null, fileName)
{
}
}
private MemoryStream encodeToLegacy((IBeatmap beatmap, ISkin skin) fullBeatmap)
{
var (beatmap, beatmapSkin) = fullBeatmap;
var stream = new MemoryStream();
using (var writer = new StreamWriter(stream, Encoding.UTF8, 1024, true))
new LegacyBeatmapEncoder(beatmap, beatmapSkin).Encode(writer);
stream.Position = 0;
return stream;
}
private IBeatmap convert(IBeatmap beatmap)
{
switch (beatmap.BeatmapInfo.Ruleset.OnlineID)
{
case 0:
beatmap.BeatmapInfo.Ruleset = new OsuRuleset().RulesetInfo;
break;
case 1:
beatmap.BeatmapInfo.Ruleset = new TaikoRuleset().RulesetInfo;
break;
case 2:
beatmap.BeatmapInfo.Ruleset = new CatchRuleset().RulesetInfo;
break;
case 3:
beatmap.BeatmapInfo.Ruleset = new ManiaRuleset().RulesetInfo;
break;
}
return new TestWorkingBeatmap(beatmap).GetPlayableBeatmap(beatmap.BeatmapInfo.Ruleset);
}
private class TestWorkingBeatmap : WorkingBeatmap
{
private readonly IBeatmap beatmap;
public TestWorkingBeatmap(IBeatmap beatmap)
: base(beatmap.BeatmapInfo, null)
{
this.beatmap = beatmap;
}
protected override IBeatmap GetBeatmap() => beatmap;
protected override Texture GetBackground() => throw new NotImplementedException();
protected override Track GetBeatmapTrack() => throw new NotImplementedException();
protected internal override ISkin GetSkin() => throw new NotImplementedException();
public override Stream GetStream(string storagePath) => throw new NotImplementedException();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Buffers.Text;
using static System.Runtime.InteropServices.MemoryMarshal;
namespace System.Text.Http.Parser.Internal
{
internal static class HttpUtilities
{
public const string Http10Version = "HTTP/1.0";
public const string Http11Version = "HTTP/1.1";
public const string HttpUriScheme = "http://";
public const string HttpsUriScheme = "https://";
// readonly primitive statics can be Jit'd to consts https://github.com/dotnet/coreclr/issues/1079
private readonly static ulong _httpSchemeLong = GetAsciiStringAsLong(HttpUriScheme + "\0");
private readonly static ulong _httpsSchemeLong = GetAsciiStringAsLong(HttpsUriScheme);
private readonly static ulong _httpConnectMethodLong = GetAsciiStringAsLong("CONNECT ");
private readonly static ulong _httpDeleteMethodLong = GetAsciiStringAsLong("DELETE \0");
private const uint _httpGetMethodInt = 542393671; // retun of GetAsciiStringAsInt("GET "); const results in better codegen
private readonly static ulong _httpHeadMethodLong = GetAsciiStringAsLong("HEAD \0\0\0");
private readonly static ulong _httpPatchMethodLong = GetAsciiStringAsLong("PATCH \0\0");
private readonly static ulong _httpPostMethodLong = GetAsciiStringAsLong("POST \0\0\0");
private readonly static ulong _httpPutMethodLong = GetAsciiStringAsLong("PUT \0\0\0\0");
private readonly static ulong _httpOptionsMethodLong = GetAsciiStringAsLong("OPTIONS ");
private readonly static ulong _httpTraceMethodLong = GetAsciiStringAsLong("TRACE \0\0");
private const ulong _http10VersionLong = 3471766442030158920; // GetAsciiStringAsLong("HTTP/1.0"); const results in better codegen
private const ulong _http11VersionLong = 3543824036068086856; // GetAsciiStringAsLong("HTTP/1.1"); const results in better codegen
private readonly static ulong _mask8Chars = GetMaskAsLong(new byte[] { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff });
private readonly static ulong _mask7Chars = GetMaskAsLong(new byte[] { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00 });
private readonly static ulong _mask6Chars = GetMaskAsLong(new byte[] { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00 });
private readonly static ulong _mask5Chars = GetMaskAsLong(new byte[] { 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00 });
private readonly static ulong _mask4Chars = GetMaskAsLong(new byte[] { 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00 });
private readonly static (ulong Mask, ulong Signature, Http.Method Method, int Length)[] _knownMethods =
{
(_mask4Chars, _httpPutMethodLong, Http.Method.Put, 3),
(_mask5Chars, _httpPostMethodLong, Http.Method.Post, 4),
(_mask5Chars, _httpHeadMethodLong, Http.Method.Head, 4),
(_mask6Chars, _httpTraceMethodLong, Http.Method.Trace, 5),
(_mask6Chars, _httpPatchMethodLong, Http.Method.Patch, 5),
(_mask7Chars, _httpDeleteMethodLong, Http.Method.Delete, 6),
(_mask8Chars, _httpConnectMethodLong, Http.Method.Connect, 7),
(_mask8Chars, _httpOptionsMethodLong, Http.Method.Options, 7),
};
private readonly static string[] _methodNames = CreateMethodNames();
private static string[] CreateMethodNames()
{
var methodNames = new string[9];
methodNames[(byte)Http.Method.Get] = "GET";
methodNames[(byte)Http.Method.Put] = "PUT";
methodNames[(byte)Http.Method.Delete] = "DELETE";
methodNames[(byte)Http.Method.Post] = "POST";
methodNames[(byte)Http.Method.Head] = "HEAD";
methodNames[(byte)Http.Method.Trace] = "TRACE";
methodNames[(byte)Http.Method.Patch] = "PATCH";
methodNames[(byte)Http.Method.Connect] = "CONNECT";
methodNames[(byte)Http.Method.Options] = "OPTIONS";
return methodNames;
}
private static ulong GetAsciiStringAsLong(string str)
{
Debug.Assert(str.Length == 8, "String must be exactly 8 (ASCII) characters long.");
Span<byte> span = stackalloc byte[8];
Encodings.Utf16.ToUtf8(AsBytes(str.AsSpan()), span, out int consumed, out int written);
return Read<ulong>(span);
}
private unsafe static ulong GetMaskAsLong(byte[] bytes)
{
Debug.Assert(bytes.Length == 8, "Mask must be exactly 8 bytes long.");
fixed (byte* ptr = bytes)
{
return *(ulong*)ptr;
}
}
public static string GetAsciiStringEscaped(this ReadOnlySpan<byte> span, int maxChars)
{
var sb = new StringBuilder();
for (var i = 0; i < Math.Min(span.Length, maxChars); i++)
{
var ch = span[i];
sb.Append(ch < 0x20 || ch >= 0x7F ? $"\\x{ch:X2}" : ((char)ch).ToString());
}
if (span.Length > maxChars)
{
sb.Append("...");
}
return sb.ToString();
}
/// <summary>
/// Checks that up to 8 bytes from <paramref name="span"/> correspond to a known HTTP method.
/// </summary>
/// <remarks>
/// A "known HTTP method" can be an HTTP method name defined in the HTTP/1.1 RFC.
/// Since all of those fit in at most 8 bytes, they can be optimally looked up by reading those bytes as a long. Once
/// in that format, it can be checked against the known method.
/// The Known Methods (CONNECT, DELETE, GET, HEAD, PATCH, POST, PUT, OPTIONS, TRACE) are all less than 8 bytes
/// and will be compared with the required space. A mask is used if the Known method is less than 8 bytes.
/// To optimize performance the GET method will be checked first.
/// </remarks>
/// <returns><c>true</c> if the input matches a known string, <c>false</c> otherwise.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool GetKnownMethod(in this ReadOnlySpan<byte> span, out Http.Method method, out int length)
{
Debug.Assert(span.Length > sizeof(ulong));
length = 0;
method = Http.Method.Custom;
if (Unsafe.ReadUnaligned<uint>(ref GetReference(span)) == _httpGetMethodInt)
{
length = 3;
method = Http.Method.Get;
}
else
{
ulong value = Unsafe.ReadUnaligned<uint>(ref GetReference(span));
foreach (var (Mask, Signature, Method, Length) in _knownMethods)
{
if ((value & Mask) == Signature)
{
length = Length;
method = Method;
break;
}
}
}
return method != Http.Method.Custom;
}
/// <summary>
/// Checks 9 bytes from <paramref name="location"/> correspond to a known HTTP version.
/// </summary>
/// <remarks>
/// A "known HTTP version" Is is either HTTP/1.0 or HTTP/1.1.
/// Since those fit in 8 bytes, they can be optimally looked up by reading those bytes as a long. Once
/// in that format, it can be checked against the known versions.
/// To optimize performance the HTTP/1.1 will be checked first.
/// </remarks>
/// <returns><c>true</c> if the input matches a known string, <c>false</c> otherwise.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static bool GetKnownVersion(in ReadOnlySpan<byte> location, out Http.Version knownVersion)
{
knownVersion = Http.Version.Unknown;
if (location.Length == sizeof(ulong))
{
ulong version = Unsafe.ReadUnaligned<ulong>(ref GetReference(location));
if (version == _http11VersionLong)
{
knownVersion = Http.Version.Http11;
}
else if (version == _http10VersionLong)
{
knownVersion = Http.Version.Http10;
}
}
return knownVersion != Http.Version.Unknown;
}
/// <summary>
/// Checks 8 bytes from <paramref name="span"/> that correspond to 'http://' or 'https://'
/// </summary>
/// <param name="span">The span</param>
/// <param name="knownScheme">A reference to the known scheme, if the input matches any</param>
/// <returns>True when memory starts with known http or https schema</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool GetKnownHttpScheme(this Span<byte> span, out HttpScheme knownScheme)
{
if (span.Length >= sizeof(ulong))
{
ulong scheme = Unsafe.ReadUnaligned<ulong>(ref GetReference(span));
if ((scheme & _mask7Chars) == _httpSchemeLong)
{
knownScheme = HttpScheme.Http;
return true;
}
if (scheme == _httpsSchemeLong)
{
knownScheme = HttpScheme.Https;
return true;
}
}
knownScheme = HttpScheme.Unknown;
return false;
}
public static string VersionToString(Http.Version httpVersion)
{
switch (httpVersion)
{
case Http.Version.Http10:
return Http10Version;
case Http.Version.Http11:
return Http11Version;
default:
return null;
}
}
public static string MethodToString(Http.Method method)
{
int methodIndex = (int)method;
if (methodIndex >= 0 && methodIndex <= 8)
{
return _methodNames[methodIndex];
}
return null;
}
public static string SchemeToString(HttpScheme scheme)
{
switch (scheme)
{
case HttpScheme.Http:
return HttpUriScheme;
case HttpScheme.Https:
return HttpsUriScheme;
default:
return null;
}
}
}
}
| |
//
// Encog(tm) Core v3.2 - .Net Version
// http://www.heatonresearch.com/encog/
//
// Copyright 2008-2014 Heaton Research, 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.
//
// For more information on Heaton Research copyrights, licenses
// and trademarks visit:
// http://www.heatonresearch.com/copyright
//
using System;
using System.Linq;
using System.Text;
using Encog.MathUtil;
using Encog.Util.KMeans;
namespace Encog.ML.Data.Basic
{
/// <summary>
/// This class implements a data object that can hold complex numbers. It
/// implements the interface MLData, so it can be used with nearly any Encog
/// machine learning method. However, not all Encog machine learning methods
/// are designed to work with complex numbers. A Encog machine learning method
/// that does not support complex numbers will only be dealing with the
/// real-number portion of the complex number.
/// </summary>
[Serializable]
public class BasicMLComplexData : IMLComplexData
{
/// <summary>
/// The data held by this object.
/// </summary>
private ComplexNumber[] _data;
/// <summary>
/// Construct this object with the specified data. Use only real numbers.
/// </summary>
/// <param name="d">The data to construct this object with.</param>
public BasicMLComplexData(double[] d)
: this(d.Length)
{
}
/// <summary>
/// Construct this object with the specified data. Use complex numbers.
/// </summary>
/// <param name="d">The data to construct this object with.</param>
public BasicMLComplexData(ComplexNumber[] d)
{
_data = d;
}
/// <summary>
/// Construct this object with blank data and a specified size.
/// </summary>
/// <param name="size">The amount of data to store.</param>
public BasicMLComplexData(int size)
{
_data = new ComplexNumber[size];
}
/// <summary>
/// Construct a new BasicMLData object from an existing one. This makes a
/// copy of an array. If MLData is not complex, then only reals will be
/// created.
/// </summary>
/// <param name="d">The object to be copied.</param>
public BasicMLComplexData(IMLData d)
{
if (d is IMLComplexData)
{
var c = (IMLComplexData) d;
for (int i = 0; i < d.Count; i++)
{
_data[i] = new ComplexNumber(c.GetComplexData(i));
}
}
else
{
for (int i = 0; i < d.Count; i++)
{
_data[i] = new ComplexNumber(d[i], 0);
}
}
}
#region IMLComplexData Members
/// <summary>
/// Clear all values to zero.
/// </summary>
public void Clear()
{
for (int i = 0; i < _data.Length; i++)
{
_data[i] = new ComplexNumber(0, 0);
}
}
/// <inheritdoc/>
public Object Clone()
{
return new BasicMLComplexData(this);
}
/// <summary>
/// The complex numbers.
/// </summary>
public ComplexNumber[] ComplexData
{
get { return _data; }
set { _data = value; }
}
/// <inheritdoc/>
public ComplexNumber GetComplexData(int index)
{
return _data[index];
}
/// <summary>
/// Set a data element to a complex number.
/// </summary>
/// <param name="index">The index to set.</param>
/// <param name="d">The complex number.</param>
public void SetComplexData(int index, ComplexNumber d)
{
_data[index] = d;
}
/// <summary>
/// Set the complex data array.
/// </summary>
/// <param name="d">A new complex data array.</param>
public void SetComplexData(ComplexNumber[] d)
{
_data = d;
}
/// <summary>
/// Access the data by index.
/// </summary>
/// <param name="x">The index to access.</param>
/// <returns></returns>
public virtual double this[int x]
{
get { return _data[x].Real; }
set { _data[x] = new ComplexNumber(value, 0); }
}
/// <summary>
/// Get the data as an array.
/// </summary>
public virtual double[] Data
{
get
{
var d = new double[_data.Length];
for (int i = 0; i < d.Length; i++)
{
d[i] = _data[i].Real;
}
return d;
}
set
{
for (int i = 0; i < value.Length; i++)
{
_data[i] = new ComplexNumber(value[i], 0);
}
}
}
/// <inheritdoc/>
public int Count
{
get { return _data.Count(); }
}
#endregion
/// <inheritdoc/>
public override String ToString()
{
var builder = new StringBuilder("[");
builder.Append(GetType().Name);
builder.Append(":");
for (int i = 0; i < _data.Length; i++)
{
if (i != 0)
{
builder.Append(',');
}
builder.Append(_data[i].ToString());
}
builder.Append("]");
return builder.ToString();
}
/// <summary>
/// Not supported.
/// </summary>
/// <returns>Nothing.</returns>
public ICentroid<IMLData> CreateCentroid()
{
return null;
}
public void CopyTo(double[] target, int targetIndex, int count)
{
for(int i = 0; i < count; i++)
target[i + targetIndex] = _data[i].Real;
}
}
}
| |
/* ====================================================================
Copyright (C) 2004-2008 fyiReporting Software, LLC
This file is part of the fyiReporting RDL project.
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.
For additional information, email info@fyireporting.com or visit
the website www.fyiReporting.com.
*/
using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Windows.Forms;
using System.Xml;
using System.IO;
namespace fyiReporting.RdlDesign
{
/// <summary>
/// Summary description for TableColumnCtl.
/// </summary>
internal class TableColumnCtl : System.Windows.Forms.UserControl, IProperty
{
private XmlNode _TableColumn;
private DesignXmlDraw _Draw;
// flags for controlling whether syntax changed for a particular property
private bool fHidden, fToggle, fWidth, fFixedHeader;
private System.Windows.Forms.GroupBox grpBoxVisibility;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.TextBox tbHidden;
private System.Windows.Forms.ComboBox cbToggle;
private System.Windows.Forms.Button bHidden;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.TextBox tbColumnWidth;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.CheckBox chkFixedHeader;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
internal TableColumnCtl(DesignXmlDraw dxDraw, XmlNode tc)
{
_TableColumn = tc;
_Draw = dxDraw;
// This call is required by the Windows.Forms Form Designer.
InitializeComponent();
// Initialize form using the style node values
InitValues(tc);
}
private void InitValues(XmlNode node)
{
// Handle Width definition
this.tbColumnWidth.Text = _Draw.GetElementValue(node, "Width", "");
this.chkFixedHeader.Checked = _Draw.GetElementValue(node, "FixedHeader", "false").ToLower() == "true"? true: false;
// Handle Visiblity definition
XmlNode visNode = _Draw.GetNamedChildNode(node, "Visibility");
if (visNode != null)
{
this.tbHidden.Text = _Draw.GetElementValue(visNode, "Hidden", "");
this.cbToggle.Text = _Draw.GetElementValue(visNode, "ToggleItem", "");
}
IEnumerable list = _Draw.GetReportItems("//Textbox");
if (list != null)
{
foreach (XmlNode tNode in list)
{
XmlAttribute name = tNode.Attributes["Name"];
if (name != null && name.Value != null && name.Value.Length > 0)
cbToggle.Items.Add(name.Value);
}
}
// nothing has changed now
fWidth = fHidden = fToggle = fFixedHeader = false;
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.grpBoxVisibility = new System.Windows.Forms.GroupBox();
this.bHidden = new System.Windows.Forms.Button();
this.cbToggle = new System.Windows.Forms.ComboBox();
this.tbHidden = new System.Windows.Forms.TextBox();
this.label3 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.label1 = new System.Windows.Forms.Label();
this.tbColumnWidth = new System.Windows.Forms.TextBox();
this.chkFixedHeader = new System.Windows.Forms.CheckBox();
this.label4 = new System.Windows.Forms.Label();
this.grpBoxVisibility.SuspendLayout();
this.SuspendLayout();
//
// grpBoxVisibility
//
this.grpBoxVisibility.Controls.Add(this.bHidden);
this.grpBoxVisibility.Controls.Add(this.cbToggle);
this.grpBoxVisibility.Controls.Add(this.tbHidden);
this.grpBoxVisibility.Controls.Add(this.label3);
this.grpBoxVisibility.Controls.Add(this.label2);
this.grpBoxVisibility.Location = new System.Drawing.Point(8, 8);
this.grpBoxVisibility.Name = "grpBoxVisibility";
this.grpBoxVisibility.Size = new System.Drawing.Size(432, 80);
this.grpBoxVisibility.TabIndex = 1;
this.grpBoxVisibility.TabStop = false;
this.grpBoxVisibility.Text = "Visibility";
//
// bHidden
//
this.bHidden.Font = new System.Drawing.Font("Arial", 8.25F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))), System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
this.bHidden.Location = new System.Drawing.Point(400, 26);
this.bHidden.Name = "bHidden";
this.bHidden.Size = new System.Drawing.Size(22, 16);
this.bHidden.TabIndex = 1;
this.bHidden.Tag = "visibility";
this.bHidden.Text = "fx";
this.bHidden.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.bHidden.Click += new System.EventHandler(this.bExpr_Click);
//
// cbToggle
//
this.cbToggle.Location = new System.Drawing.Point(168, 48);
this.cbToggle.Name = "cbToggle";
this.cbToggle.Size = new System.Drawing.Size(152, 21);
this.cbToggle.TabIndex = 2;
this.cbToggle.TextChanged += new System.EventHandler(this.cbToggle_SelectedIndexChanged);
this.cbToggle.SelectedIndexChanged += new System.EventHandler(this.cbToggle_SelectedIndexChanged);
//
// tbHidden
//
this.tbHidden.Location = new System.Drawing.Point(168, 24);
this.tbHidden.Name = "tbHidden";
this.tbHidden.Size = new System.Drawing.Size(224, 20);
this.tbHidden.TabIndex = 0;
this.tbHidden.Text = "";
this.tbHidden.TextChanged += new System.EventHandler(this.tbHidden_TextChanged);
//
// label3
//
this.label3.Location = new System.Drawing.Point(16, 48);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(152, 23);
this.label3.TabIndex = 1;
this.label3.Text = "Toggle Item (Textbox name)";
//
// label2
//
this.label2.Location = new System.Drawing.Point(16, 24);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(120, 23);
this.label2.TabIndex = 0;
this.label2.Text = "Hidden (initial visibility)";
//
// label1
//
this.label1.Location = new System.Drawing.Point(8, 104);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(80, 16);
this.label1.TabIndex = 2;
this.label1.Text = "Column Width";
//
// tbColumnWidth
//
this.tbColumnWidth.Location = new System.Drawing.Point(88, 104);
this.tbColumnWidth.Name = "tbColumnWidth";
this.tbColumnWidth.TabIndex = 3;
this.tbColumnWidth.Text = "";
this.tbColumnWidth.TextChanged += new System.EventHandler(this.tbWidth_TextChanged);
//
// chkFixedHeader
//
this.chkFixedHeader.Location = new System.Drawing.Point(8, 136);
this.chkFixedHeader.Name = "chkFixedHeader";
this.chkFixedHeader.Size = new System.Drawing.Size(96, 24);
this.chkFixedHeader.TabIndex = 4;
this.chkFixedHeader.Text = "Fixed Header";
this.chkFixedHeader.CheckedChanged += new System.EventHandler(this.cbFixedHeader_CheckedChanged);
//
// label4
//
this.label4.Location = new System.Drawing.Point(112, 136);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(336, 24);
this.label4.TabIndex = 5;
this.label4.Text = "Note: Fixed headers must be contiguous and start at either the left or the right " +
"of the table. Current renderers ignore this parameter.";
//
// TableColumnCtl
//
this.Controls.Add(this.label4);
this.Controls.Add(this.chkFixedHeader);
this.Controls.Add(this.tbColumnWidth);
this.Controls.Add(this.label1);
this.Controls.Add(this.grpBoxVisibility);
this.Name = "TableColumnCtl";
this.Size = new System.Drawing.Size(472, 288);
this.grpBoxVisibility.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
public bool IsValid()
{
try
{
if (fWidth)
DesignerUtility.ValidateSize(this.tbColumnWidth.Text, true, false);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Width is Invalid");
return false;
}
if (fHidden)
{
string vh = this.tbHidden.Text.Trim();
if (vh.Length > 0)
{
if (vh.StartsWith("="))
{}
else
{
vh = vh.ToLower();
switch (vh)
{
case "true":
case "false":
break;
default:
MessageBox.Show(String.Format("{0} must be an expression or 'true' or 'false'", tbHidden.Text), "Hidden is Invalid");
return false;
}
}
}
}
return true;
}
public void Apply()
{
// take information in control and apply to all the style nodes
// Only change information that has been marked as modified;
// this way when group is selected it is possible to change just
// the items you want and keep the rest the same.
ApplyChanges(this._TableColumn);
// nothing has changed now
fWidth = fHidden = fToggle = false;
}
private void ApplyChanges(XmlNode rNode)
{
if (fHidden || fToggle)
{
XmlNode visNode = _Draw.SetElement(rNode, "Visibility", null);
if (fHidden)
{
string vh = this.tbHidden.Text.Trim();
if (vh.Length > 0)
_Draw.SetElement(visNode, "Hidden", vh);
else
_Draw.RemoveElement(visNode, "Hidden");
}
if (fToggle)
_Draw.SetElement(visNode, "ToggleItem", this.cbToggle.Text);
}
if (fWidth) // already validated
_Draw.SetElement(rNode, "Width", this.tbColumnWidth.Text);
if (fFixedHeader)
{
if (this.chkFixedHeader.Checked)
_Draw.SetElement(rNode, "FixedHeader", "true");
else
_Draw.RemoveElement(rNode, "FixedHeader"); // just get rid of it
}
}
private void tbHidden_TextChanged(object sender, System.EventArgs e)
{
fHidden = true;
}
private void tbWidth_TextChanged(object sender, System.EventArgs e)
{
fWidth = true;
}
private void cbToggle_SelectedIndexChanged(object sender, System.EventArgs e)
{
fToggle = true;
}
private void bExpr_Click(object sender, System.EventArgs e)
{
Button b = sender as Button;
if (b == null)
return;
Control c = null;
switch (b.Tag as string)
{
case "visibility":
c = tbHidden;
break;
}
if (c == null)
return;
using (DialogExprEditor ee = new DialogExprEditor(_Draw, c.Text, _TableColumn))
{
DialogResult dr = ee.ShowDialog();
if (dr == DialogResult.OK)
c.Text = ee.Expression;
}
return;
}
private void cbFixedHeader_CheckedChanged(object sender, System.EventArgs e)
{
fFixedHeader = true;
}
}
}
| |
using System;
using System.IO;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Diagnostics.CodeAnalysis;
using ESRI.ArcGIS.esriSystem;
using ESRI.ArcGIS.DataSourcesFile;
using ESRI.ArcGIS.DataSourcesGDB;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.Geometry;
using ESRI.ArcGIS.Location;
using esriLocationPrivate;
using log4net;
namespace ESRIUK.DynamicLocators.Core
{
/// <summary>
/// This class is the base class for all locators created with the SDK.
/// It contains the implementations of all of the interfaces that are required for an ArcGIS locator to work
/// Many of the method implementations minimal to enalbe basic functionality and to allow further customisation
///
/// This class CANNOT be used on as is to create a locator. The methods CreateFields, Properties, FindAddressCandidates and ReverseGeocode
/// must be overridden in a child class at a minimum to create a locator
/// </summary>
public class LocatorWrapper : ILocator, IAddressInputs, IGeocodingProperties, IAddressGeocoding, IAddressCandidates, IClone, ISingleLineAddressInput,
ILocatorImpl, ILocatorDataset, IESRILocatorReleaseInfo, IBatchGeocoding, IReverseGeocoding, IReverseGeocodingProperties, IGeocodeServerSingleLine
{
#region Member Variables
// Create new instance of logger, 1 per class recommended
log4net.ILog _log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
protected IFields m_addressFields = new FieldsClass();
protected IFields m_matchFields = new FieldsClass();
protected IFields m_candidateFields = new FieldsClass();
protected ISpatialReference m_spatialReference;
private string m_category = "Address";
private string m_description = "Locator Wrapper";
private string m_name = "Locator Wrapper";
private bool m_addPercentAlongToMatchFields = false;
private bool m_addReferenceIDToMatchFields = false;
private bool m_addStandardizeStringToMatchFields = false;
protected bool m_addXYCoordsToMatchFields = false;
private IPropertySet m_defaultInputFieldNames;
private int m_endOffset = 3;
private string m_intersectionConnectors = "& | @";
private bool m_matchIfScoresTie = true;
private int m_minimumCandidateScore = 10;
private int m_minimumMatchScore = 60;
private double m_sideOffset = 20;
private esriUnits m_sideOffsetUnits = esriUnits.esriFeet;
private int m_spellingSensitivity = 80;
private bool m_useRelativePaths = true;
protected IPropertySet m_locatorProperties = new PropertySetClass();
private bool m_needToUpdate = false;
protected String m_searchTokenName = "Address";
protected string m_searchTokenAlias = "Address";
private double m_searchDistance = 100;
private esriUnits m_searchDistanceUnits = esriUnits.esriFeet;
#endregion
/// <summary>
/// The constructor initialises the log4net configuration and calls the CreateFields method
/// </summary>
public LocatorWrapper()
{
// This section is used to get the local configuration file so that the log4net configuration can be accessed for debugging
string dllLoc = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase).Replace("file:\\","");
FileInfo file = new FileInfo(dllLoc+"/ESRIUK.DynamicLocators.Core.dll.config");
log4net.Config.XmlConfigurator.Configure(file);
// Create fields is called to initialise all of the required fields for a locator
CreateFields();
}
/// <summary>
/// This initialises all of the different fields that are required for the locator to function
/// It contains declarations for the Match and Candidate fields for the locator and so must be overridden in each child class
/// </summary>
protected virtual void CreateFields()
{
// Must be overridden in child class
}
#region Implement IReverseGeocode
/// <summary>
/// Generate an address based on a point.
/// </summary>
/// <param name="location"></param>
/// <param name="returnIntersection"></param>
/// <returns></returns>
public virtual IPropertySet ReverseGeocode(IPoint location, bool returnIntersection)
{
_log.Debug("IReverseGeocode ReverseGeocode");
IPropertySet reverseGeocodedResult = new PropertySetClass();
return reverseGeocodedResult;
}
#endregion
#region Implement IAddressCandidates
/// <summary>
/// Fields contained in a list of candidates.
/// </summary>
public IFields CandidateFields
{
get
{
_log.Debug("IAddressCandidates CandidateFields");
if (m_candidateFields == null)
m_candidateFields = new FieldsClass();
return m_candidateFields;
}
}
/// <summary>
/// Generates candidates for an address.
/// </summary>
/// <param name="address"></param>
/// <returns>Address candidates</returns>
public virtual IArray FindAddressCandidates(IPropertySet address)
{
_log.Debug("IAddressCandidates FindAddressCandidates");
IArray addressCandidates = new ArrayClass();
return addressCandidates;
}
#endregion
#region IClone Members
/// <summary>
/// Assigns the properties of src to the receiver.
/// </summary>
/// <param name="src"></param>
public void Assign(IClone src)
{
_log.Debug("IClone Assign");
throw new NotImplementedException();
}
/// <summary>
/// Clones the receiver and assigns the result to *clone.
/// </summary>
/// <returns></returns>
public IClone Clone()
{
_log.Debug("IClone Clone");
LocatorWrapper veLocator = this;
return veLocator as IClone;
}
/// <summary>
/// Returns TRUE when the receiver and other have the same properties.
/// </summary>
/// <param name="other"></param>
/// <returns></returns>
public bool IsEqual(IClone other)
{
_log.Debug("IClone IsEqual");
throw new NotImplementedException();
}
/// <summary>
/// Returns TRUE when the receiver and other are the same object.
/// </summary>
/// <param name="other"></param>
/// <returns></returns>
public bool IsIdentical(IClone other)
{
_log.Debug("IClone IsIdentical");
object clonedLocator = other as object;
object thisLocator = this as object;
return isSameObject(clonedLocator, thisLocator);
}
#endregion
#region ILocator Implemented
/// <summary>
/// Category of the locator.
/// </summary>
public string Category
{
get
{
_log.Debug("ILocator Category");
return m_category;
}
set
{
_log.Debug("ILocator Category");
m_category = value;
}
}
/// <summary>
/// Description of the locator.
/// </summary>
public string Description
{
get
{
_log.Debug("ILocator Description");
return m_description;
}
set
{
_log.Debug("ILocator Description");
m_description = value;
}
}
/// <summary>
/// Name of the locator.
/// </summary>
public string Name
{
get
{
_log.Debug("ILocator Name");
return m_name;
}
set
{
_log.Debug("ILocator Name");
m_name = value;
}
}
/// <summary>
/// User interface for the locator.
/// </summary>
public virtual ILocatorUI UserInterface
{
get
{
_log.Debug("ILocator UserInterface");
return new ESRI.ArcGIS.LocationUI.AddressLocatorUIClass();
}
}
#endregion
#region IAddressInputs Implemented
/// <summary>
/// Fields needed to geocode a table of addresses.
/// </summary>
public IFields AddressFields
{
get
{
_log.Debug("IAddressInputs AddressFields");
return m_addressFields;
}
}
/// <summary>
/// Recognized names for an input field.
/// </summary>
/// <param name="addressField"></param>
/// <returns></returns>
public object get_DefaultInputFieldNames(string addressField)
{
_log.Debug("IAddressInputs get_DefaultInputFieldNames");
return m_defaultInputFieldNames.GetProperty(addressField);
}
#endregion
#region IGeocodingProperties Implemented
/// <summary>
/// Indicates if the percentage along the reference feature at which the address is located is included in the geocoding result.
/// </summary>
public bool AddPercentAlongToMatchFields
{
get
{
_log.Debug("IGeocodingProperties AddPercentAlongToMatchFields");
return m_addPercentAlongToMatchFields;
}
set
{
_log.Debug("IGeocodingProperties AddPercentAlongToMatchFields");
m_addPercentAlongToMatchFields = value;
}
}
/// <summary>
/// Indicates if the feature ID of the matched feature is included in the geocoding result.
/// </summary>
public bool AddReferenceIDToMatchFields
{
get
{
_log.Debug("IGeocodingProperties AddReferenceIDToMatchFields");
return m_addReferenceIDToMatchFields;
}
set
{
_log.Debug("IGeocodingProperties AddReferenceIDToMatchFields");
m_addReferenceIDToMatchFields = value;
}
}
/// <summary>
/// Indicates if the standardized address is included in the geocoding result.
/// </summary>
public bool AddStandardizeStringToMatchFields
{
get
{
_log.Debug("IGeocodingProperties AddStandardizeStringToMatchFields");
return m_addStandardizeStringToMatchFields;
}
set
{
_log.Debug("IGeocodingProperties AddStandardizeStringToMatchFields");
m_addStandardizeStringToMatchFields = value;
}
}
/// <summary>
/// Indicates if the x and y coordinates of the address location are included in the geocoding result.
/// </summary>
public virtual bool AddXYCoordsToMatchFields
{
get
{
_log.Debug("IGeocodingProperties AddXYCoordsToMatchFields");
return m_addXYCoordsToMatchFields;
}
set
{
_log.Debug("IGeocodingProperties AddXYCoordsToMatchFields");
m_addXYCoordsToMatchFields = value;
IFieldsEdit newMatchFields = new FieldsClass();
IFieldsEdit newCandidateFields = new FieldsClass();
IFieldEdit XField = new FieldClass();
IFieldEdit YField = new FieldClass();
// Add the XY fields
if (m_addXYCoordsToMatchFields)
{
XField.Name_2 = "X";
YField.Name_2 = "Y";
XField.Type_2 = esriFieldType.esriFieldTypeDouble;
YField.Type_2 = esriFieldType.esriFieldTypeDouble;
XField.Scale_2 = 6;
YField.Scale_2 = 6;
YField.Precision_2 = 8;
XField.Precision_2 = 8;
newMatchFields = m_matchFields as IFieldsEdit;
newCandidateFields = m_candidateFields as IFieldsEdit;
newMatchFields.AddField(XField);
newCandidateFields.AddField(XField);
newMatchFields.AddField(YField);
newCandidateFields.AddField(YField);
m_matchFields = newMatchFields;
m_candidateFields = newCandidateFields;
}
// Remove any existing XY fields
else
{
newMatchFields = m_matchFields as IFieldsEdit;
newCandidateFields = m_candidateFields as IFieldsEdit;
try
{
newMatchFields.DeleteField(newMatchFields.get_Field(newMatchFields.FindField("X")));
newCandidateFields.DeleteField(newCandidateFields.get_Field(newCandidateFields.FindField("X")));
newMatchFields.DeleteField(newMatchFields.get_Field(newMatchFields.FindField("Y")));
newCandidateFields.DeleteField(newCandidateFields.get_Field(newCandidateFields.FindField("Y")));
}
catch { }
m_matchFields = newMatchFields;
m_candidateFields = newCandidateFields;
}
}
}
/// <summary>
/// Recognized names for a required input field.
/// </summary>
/// <param name="addressField"></param>
/// <param name="inputFieldNames"></param>
public void set_DefaultInputFieldNames(string addressField, object inputFieldNames)
{
_log.Debug("IGeocodingProperties set_DefaultInputFieldNames");
//add single line
if (m_defaultInputFieldNames == null)
{
m_defaultInputFieldNames = new PropertySetClass();
m_defaultInputFieldNames.SetProperty("SingleLine", this.DefaultInputFieldNames);
}
else if (m_defaultInputFieldNames.GetProperty("SingleLine") == null)
{
m_defaultInputFieldNames.SetProperty("SingleLine", this.DefaultInputFieldNames);
}
m_defaultInputFieldNames.SetProperty(addressField, inputFieldNames);
}
/// <summary>
/// End offset percentage.
/// </summary>
public int EndOffset
{
get
{
_log.Debug("IGeocodingProperties EndOffset");
return m_endOffset;
}
set
{
_log.Debug("IGeocodingProperties EndOffset");
m_endOffset = value;
}
}
/// <summary>
/// Connector strings used to designate intersections.
/// </summary>
public string IntersectionConnectors
{
get
{
_log.Debug("IGeocodingProperties IntersectionConnectors");
return m_intersectionConnectors;
}
set
{
_log.Debug("IGeocodingProperties IntersectionConnectors");
m_intersectionConnectors = value;
}
}
/// <summary>
/// Indicates whether addresses should be arbitrarily matched to a feature when two or more features have the same best score.
/// </summary>
public bool MatchIfScoresTie
{
get
{
_log.Debug("IGeocodingProperties MatchIfScoresTie");
return m_matchIfScoresTie;
}
set
{
_log.Debug("IGeocodingProperties MatchIfScoresTie");
m_matchIfScoresTie = value;
}
}
/// <summary>
/// Minimum candidate score setting.
/// </summary>
public int MinimumCandidateScore
{
get
{
_log.Debug("IGeocodingProperties MinimumCandidateScore");
return m_minimumCandidateScore;
}
set
{
_log.Debug("IGeocodingProperties MinimumCandidateScore");
m_minimumCandidateScore = value;
}
}
/// <summary>
/// Minimum match score setting.
/// </summary>
public int MinimumMatchScore
{
get
{
_log.Debug("IGeocodingProperties MinimumMatchScore");
return m_minimumMatchScore;
}
set
{
_log.Debug("IGeocodingProperties MinimumMatchScore");
m_minimumMatchScore = value;
}
}
/// <summary>
/// Side offset distance.
/// </summary>
public double SideOffset
{
get
{
_log.Debug("IGeocodingProperties SideOffset");
return m_sideOffset;
}
set
{
_log.Debug("IGeocodingProperties SideOffset");
m_sideOffset = value;
}
}
/// <summary>
/// Units used for the side offset.
/// </summary>
public esriUnits SideOffsetUnits
{
get
{
_log.Debug("IGeocodingProperties SideOffsetUnits");
return m_sideOffsetUnits;
}
set
{
_log.Debug("IGeocodingProperties SideOffsetUnits");
m_sideOffsetUnits = value;
}
}
/// <summary>
/// Spelling sensitivity setting.
/// </summary>
public int SpellingSensitivity
{
get
{
_log.Debug("IGeocodingProperties SpellingSensitivity");
return m_spellingSensitivity;
}
set
{
_log.Debug("IGeocodingProperties SpellingSensitivity");
m_spellingSensitivity = value;
}
}
/// <summary>
/// Indicates if the paths to the reference data should be stored relative to the locator.
/// </summary>
public bool UseRelativePaths
{
get
{
_log.Debug("IGeocodingProperties UseRelativePaths");
return m_useRelativePaths;
}
set
{
_log.Debug("IGeocodingProperties UseRelativePaths");
m_useRelativePaths = value;
}
}
#endregion
#region IReverseGeocodingProperties Implemented
/// <summary>
/// Search distance.
/// </summary>
public double SearchDistance
{
get
{
_log.Debug("IReverseGeocodingProperties SearchDistance");
return m_searchDistance;
}
set
{
_log.Debug("IReverseGeocodingProperties SearchDistance");
m_searchDistance = value;
}
}
/// <summary>
/// Units used for the search distance.
/// </summary>
public esriUnits SearchDistanceUnits
{
get
{
_log.Debug("IReverseGeocodingProperties SearchDistanceUnits");
return m_searchDistanceUnits;
}
set
{
_log.Debug("IReverseGeocodingProperties SearchDistanceUnits");
m_searchDistanceUnits = value;
}
}
#endregion
#region IAddressGeocoding Implemented
/// <summary>
/// Uses the FindAddressCandidates method to geocode a single address
/// </summary>
/// <param name="address">Input address</param>
/// <returns>IPropertySet that contains the matched address</returns>
public virtual IPropertySet MatchAddress(IPropertySet address)
{
_log.Debug("IAddressGeocoding MatchAddress");
IPropertySet resultSet = new PropertySetClass();
try
{
IArray addressCandidates = FindAddressCandidates(address);
if (addressCandidates.Count < 1)
throw new Exception();
resultSet = addressCandidates.get_Element(0) as IPropertySet;
object names;
object values;
// Get the name and value of all the properties in the property set
resultSet.GetAllProperties(out names, out values);
String[] nameArray = names as String[];
object[] valueArray = values as object[];
_log.Debug("MatchAddress Input address columns:" + string.Concat(nameArray));
// Add the Status Field to the Result
List<string> matchNames = new List<string>(nameArray);
List<object> matchValues = new List<object>(valueArray);
matchNames.Insert(1, "Status");
matchValues.Insert(1, "M");
// Set the field names and values for the matched address
names = matchNames.ToArray() as object;
values = matchValues.ToArray() as object;
resultSet.SetProperties(names, values);
return resultSet;
}
catch (Exception ex)
{
_log.Error("An error ocurred during MatchAddress: " + ex.Message);
// Return an empty address match to prevent errors
IGeometry emptyPoint = new PointClass() as IGeometry;
emptyPoint.SetEmpty();
resultSet.SetProperties(new string[] { "Shape", "Status", "Score", "Match_addr" },
new object[] { emptyPoint, "U", null, null });
return resultSet;
}
}
/// <summary>
/// Fields contained in the geocoding result.
/// </summary>
public IFields MatchFields
{
get
{
_log.Debug("IAddressGeocoding MatchFields");
if (m_matchFields == null)
m_matchFields = new FieldsClass();
return m_matchFields;
}
}
/// <summary>
/// Geocodes a table of addresses
/// </summary>
/// <param name="addressTable">Input address table</param>
/// <param name="addressFieldNames">Fields defined in the table</param>
/// <param name="whereClause">Query filter where clause</param>
/// <param name="outputFeatureClass">Output feature class for matched addresses</param>
/// <param name="outputFieldNames">Output field names</param>
/// <param name="fieldsToCopy"></param>
/// <param name="cancelTracker"></param>
public virtual void MatchTable(ITable addressTable, String addressFieldNames, String whereClause,
IFeatureClass outputFeatureClass, String outputFieldNames, IPropertySet fieldsToCopy, ITrackCancel cancelTracker)
{
_log.Debug("IAddressGeocoding MatchTable");
// Obtain the read and insert cursors
IQueryFilter queryFilter = new QueryFilterClass();
queryFilter.WhereClause = whereClause;
ICursor readCursor = null;
IFeatureCursor insertCursor = null;
IFeatureCursor updateCursor = null;
// m_needToUpdate will be True when a Rematch is being preformed
if (m_needToUpdate)
{
// Create update cursor to update matched records
updateCursor = outputFeatureClass.Update(queryFilter, false);
if (isSameObject(addressTable, outputFeatureClass))
readCursor = updateCursor as ICursor;
else
readCursor = addressTable.Search(queryFilter, true);
}
else
{
// Create insert cursor to add new records
readCursor = addressTable.Search(queryFilter, true);
insertCursor = outputFeatureClass.Insert(true);
}
int count = addressTable.RowCount(queryFilter);
// Progress dialog setup
IStepProgressor progressor = null;
if (cancelTracker != null)
progressor = cancelTracker.Progressor as IStepProgressor;
IProgressStatistics progStats = cancelTracker as IProgressStatistics;
if (progressor != null)
{
progressor.StepValue = 1;
progressor.MaxRange = addressTable.RowCount(null);
}
// Separate the input field names
string[] multilineFields = addressFieldNames.Split(',');
// Read the first row and get the address field
IRow row = readCursor.NextRow();
Dictionary<int, string> addressFieldIndexes = new Dictionary<int, string>();
// Get the index of each valid field
for (int i = 0; i < multilineFields.Length; i++)
{
if (multilineFields[i].Trim().Length > 0)
addressFieldIndexes.Add(row.Fields.FindField(multilineFields[i].Trim()), multilineFields[i].Trim());
}
string address;
IPropertySet addressProperties = new PropertySetClass();
IPropertySet resultSet;
IFeatureBuffer featureBuffer;
object copyTo, copyFrom, key, value;
// Get the name and value of all the properties in the property set
fieldsToCopy.GetAllProperties(out copyTo, out copyFrom);
string[] copyToArray = copyTo as string[];
object[] copyFromArray = copyFrom as object[];
string matchStatus = "U";
// Populate the output feature class
while (row != null)
{
featureBuffer = outputFeatureClass.CreateFeatureBuffer();
foreach (KeyValuePair<int,string> entry in addressFieldIndexes)
{
if (entry.Key != -1)
address = row.get_Value(entry.Key) as string;
else
address = row.get_Value(0) as string;
addressProperties.SetProperty(entry.Value, address);
}
resultSet = MatchAddress(addressProperties);
// Get all of the fields and values of the result
resultSet.GetAllProperties(out key, out value);
string[] names = key as string[];
object[] items = value as object[];
// Output match fields and values
// Insert the Feature into the output featureClass and get the next row
if (m_needToUpdate)
{
_log.Debug("IAddressGeocoding Updating Feature" + row.OID.ToString());
// Record is being rematched so find record to update
IFeature feature = outputFeatureClass.GetFeature(row.OID);
for (int i = 0; i < names.Length; i++)
{
if (names[i] == "Shape")
feature.Shape = items[i] as IGeometry;
else
{
if (names[i] == "Status")
{
matchStatus = items[i] as string;
feature.set_Value(outputFeatureClass.FindField(names[i]), items[i]);
}
}
}
// Set the match type
if (outputFeatureClass.FindField("Match_type") != -1)
{
feature.set_Value(outputFeatureClass.FindField("Match_type"), "A");
}
// Copy over values from address table
for (int j = 0; j < copyToArray.Length; j++)
{
feature.set_Value(outputFeatureClass.FindField(copyToArray[j]),
row.get_Value(addressTable.FindField(copyFromArray[j] as string)));
}
updateCursor.UpdateFeature(feature);
}
else
{
// set shape and status of matched record
for (int i = 0; i < names.Length; i++)
{
if (names[i] == "Shape")
featureBuffer.Shape = items[i] as IGeometry;
else
{
if (names[i] == "Status")
matchStatus = items[i] as string;
featureBuffer.set_Value(outputFeatureClass.FindField(names[i]), items[i]);
}
}
// Set the match type
if (outputFeatureClass.FindField("Match_type") != -1)
{
featureBuffer.set_Value(outputFeatureClass.FindField("Match_type"), "A");
}
// Copy over values from address table
for (int j = 0; j < copyToArray.Length; j++)
{
try
{
featureBuffer.set_Value(outputFeatureClass.FindField(copyToArray[j]),
row.get_Value(addressTable.FindField(copyFromArray[j] as string)));
}
catch (Exception ex)
{
_log.Error("An error occurred copying values from the address table: " + ex.Message);
}
}
insertCursor.InsertFeature(featureBuffer);
}
row = readCursor.NextRow();
// Update the MatchTable progress
if (progStats != null)
{
progStats.StepByValue(matchStatus);
progStats.Update();
}
if (cancelTracker != null)
{
if (!cancelTracker.Continue())
break;
}
}
_log.Debug("IAddressGeocoding MatchTable End of updating features.");
// Clean up the cursors
if (insertCursor != null)
{
insertCursor.Flush();
Marshal.ReleaseComObject(insertCursor);
}
if (updateCursor != null)
{
updateCursor.Flush();
Marshal.ReleaseComObject(updateCursor);
}
if (readCursor != null)
Marshal.ReleaseComObject(readCursor);
}
/// <summary>
/// Checks that the locator properties and locator dataset are present and valid.
/// </summary>
public void Validate() { }
#endregion
#region ILocatorImpl Implemented
/// <summary>
/// Getter and Setter for the Locators properties
/// </summary>
public virtual IPropertySet Properties
{
get
{
_log.Debug("ILocatorImpl Properties");
return m_locatorProperties;
}
set
{
try
{
_log.Debug("ILocatorImpl Properties");
object names, values;
// Get the name and value of all the properties in the property set
value.GetAllProperties(out names, out values);
string[] nameArray = names as string[];
object[] valueArray = values as object[];
// Set the property names and values
for (int i = 0; i < value.Count; i++)
{
m_locatorProperties.SetProperty(nameArray[i], valueArray[i]);
}
object property = getProperty(m_locatorProperties, "WriteXYCoordFields");
if (property != null)
m_addXYCoordsToMatchFields = bool.Parse(property as String);
property = getProperty(m_locatorProperties, "Fields");
if (property != null)
m_searchTokenName = property as String;
set_DefaultInputFieldNames(m_searchTokenName, (new string[] { "FullAddress", "Address", "ADDRESS", "Search" }) as object);
// Create the addressFields
IFieldsEdit fieldsEdit = new FieldsClass();
IFieldEdit fieldEdit = new FieldClass();
fieldEdit.Name_2 = m_searchTokenName;
fieldEdit.AliasName_2 = m_searchTokenAlias;
fieldEdit.Required_2 = true;
fieldEdit.Type_2 = esriFieldType.esriFieldTypeString;
fieldEdit.Length_2 = 50;
fieldsEdit.AddField(fieldEdit);
m_addressFields = fieldsEdit as IFields;
}
catch
{
}
}
}
#endregion
#region ILocatorDataset Implemented
/// <summary>
/// Contains a getter for the Locator name object which is taken from the Locator workspace
/// </summary>
public ILocatorName FullName
{
get
{
_log.Debug("ILocatorDataset FullName");
object locatorStringObject = m_locatorProperties.GetProperty("LocatorWorkspaceString");
string[] locatorStringArray = locatorStringObject as string[];
string locatorString = locatorStringObject as string;
// If the LocatorWorkspaceString had more than one row in the file
if (locatorStringArray != null)
{
locatorString = string.Join("", locatorStringArray);
}
_log.Debug("locatorString=" + locatorString);
string[] workspacePropertiesArray = tokenizeLocatorWorkspaceString(locatorString);
if (workspacePropertiesArray == null)
throw new Exception("Error parsing LocatorWorkspaceString.");
string progID = workspacePropertiesArray[0];
string path = workspacePropertiesArray[1];
IWorkspace workspace = null;
ILocatorWorkspace locatorWorkspace = null;
ILocatorManager locatorManager = new LocatorManagerClass();
ILocatorName locatorName = null;
try
{
// Set up the correct workspace type
if (progID.Contains("esriDataSourcesFile.ShapefileWorkspaceFactory"))
{
IWorkspaceFactory workpspaceFactory = new ShapefileWorkspaceFactoryClass();
workspace = workpspaceFactory.OpenFromFile(path, 0);
if (workspace == null)
return null;
locatorWorkspace = locatorManager.GetLocatorWorkspace(workspace);
}
else if (progID.Contains("esriDataSourcesGDB.FileGDBWorkspaceFactory"))
{
workspace = createGDBWorkspace(path, "gdb");
if (workspace == null)
return null;
locatorWorkspace = locatorManager.GetLocatorWorkspace(workspace);
}
else if (progID.Contains("esriDataSourcesGDB.AccessWorkspaceFactory"))
{
workspace = createGDBWorkspace(path, "mdb");
if (workspace == null)
return null;
locatorWorkspace = locatorManager.GetLocatorWorkspace(workspace);
}
else if (progID.Contains("esriDataSourcesGDB.SdeWorkspaceFactory"))
{
string connectionString = tokenizeSDEProperties(path);
IWorkspaceName2 workspaceName = new WorkspaceNameClass();
workspaceName.WorkspaceFactoryProgID = progID;
workspaceName.ConnectionString = connectionString;
workspaceName.BrowseName = m_name;
IWorkspaceFactory workspaceFactory = new SdeWorkspaceFactoryClass();
workspace = workspaceFactory.Open(workspaceName.ConnectionProperties, 0);
locatorWorkspace = locatorManager.GetLocatorWorkspace(workspace);
}
else
{
throw new NotImplementedException();
}
locatorName = locatorWorkspace.GetLocatorName(m_name);
}
catch (Exception e)
{
throw new Exception("Error opening the Locator Workspace.", e);
}
return locatorName;
}
}
public ILocatorWorkspace LocatorWorkspace
{
get
{
_log.Debug("ILocatorDataset LocatorWorkspace");
IName name = FullName.LocatorWorkspaceName as IName;
return name.Open() as ILocatorWorkspace;
}
}
#endregion
#region IBatchGeocoding Members
/// <summary>
/// Uses MatchAddress to geocode a cursor of addresses to a RecordSet
/// This is called by ArcGIS Server Geocode Addresses
/// </summary>
/// <param name="addressCursor">Cursor containing address to be geocoded</param>
/// <param name="addressFieldNames">The address fields that make up a record in the cursor</param>
/// <param name="outputRecordSet">The output record set</param>
/// <param name="outputFieldNames">The output field names</param>
/// <param name="fieldsToCopy"></param>
/// <param name="cancelTracker"></param>
public void MatchRecordSet(ICursor addressCursor, string addressFieldNames, IRecordSetInit outputRecordSet,
string outputFieldNames, IPropertySet fieldsToCopy, ITrackCancel cancelTracker)
{
_log.Debug("IBatchGeocoding MatchRecordSet");
_log.Debug("MatchRecordSet addressFieldNames:" + addressFieldNames);
_log.Debug("MatchRecordSet outputFieldNames:" + outputFieldNames);
ICursor resultCursor = outputRecordSet.Insert();
IRow row = addressCursor.NextRow();
IRowBuffer rowBuffer = null;
IFields fields = row.Fields;
IFields bufferFields = null;
String[] fieldNames = addressFieldNames.Split(',');
String[] outputFields = outputFieldNames.Split(',');
int addressFieldsSize = fieldNames.Length;
int outputFieldsSize = outputFields.Length;
int copyFieldsSize = 0;
String addressValue = "";
IPropertySet addressProperty;
IPropertySet results;
object value, values, names;
String[] nameArray;
object[] valueArray;
Dictionary<string, int> addressFieldInds = new Dictionary<string,int>();
Dictionary<string, int> outputFieldInds = new Dictionary<string, int>();
string fieldName;
string outFieldName;
// Get all address field indexes
for (int i = 0; i < addressFieldsSize; i++)
{
fieldName = fieldNames[i].Trim();
if(!addressFieldInds.ContainsKey(fieldName))
addressFieldInds.Add(fieldName, fields.FindField(fieldName));
}
//loop through each record
while (row != null)
{
addressProperty = new PropertySetClass();
rowBuffer = outputRecordSet.CreateRowBuffer();
bufferFields = rowBuffer.Fields;
//populate a property set of search values
for (int i = 0; i < addressFieldsSize; i++)
{
fieldName = fieldNames[i].Trim();
addressValue = row.get_Value(addressFieldInds[fieldName]) as String;
if(!string.IsNullOrEmpty(addressValue))
addressProperty.SetProperty(fieldName, addressValue);
}
// Geocode the Address
results = MatchAddress(addressProperty);
// Get all output field indexes, only do this once to save processing
if (outputFieldInds.Count == 0)
{
for (int i = 0; i < outputFieldsSize; i++)
{
outFieldName = outputFields[i].Trim();
outputFieldInds.Add(outFieldName, bufferFields.FindField(outFieldName));
}
}
//add the result to the recordset
for (int i = 0; i < outputFieldsSize; i++)
{
outFieldName = outputFields[i].Trim();
value = results.GetProperty(outFieldName);
_log.Debug("MatchRecordSet outputFields[i]:" + outFieldName);
rowBuffer.set_Value(outputFieldInds[outFieldName], value);
}
//copy extra fields
fieldsToCopy.GetAllProperties(out names, out values);
nameArray = names as String[];
valueArray = values as object[];
copyFieldsSize = nameArray.Length;
for (int i = 0; i < copyFieldsSize; i++)
{
string fieldToCopy = nameArray[i];
if(fieldToCopy == "ResultID")
rowBuffer.set_Value(bufferFields.FindField(fieldToCopy), row.OID);
else
rowBuffer.set_Value(bufferFields.FindField(fieldToCopy), row.get_Value(fields.FindField(fieldToCopy)));
}
//insert row
resultCursor.InsertRow(rowBuffer);
row = addressCursor.NextRow();
}
// Clean up the cursors
resultCursor.Flush();
Marshal.ReleaseComObject(resultCursor);
Marshal.ReleaseComObject(addressCursor);
}
/// <summary>
/// Uses MatchTable to rematch addresses in a feature class
/// </summary>
/// <param name="pInputTable">Input table containing addresses</param>
/// <param name="inputFieldNames">In put tables fields</param>
/// <param name="inputJoinFieldName">Input join field name</param>
/// <param name="resultTable">The rematch result table</param>
/// <param name="outputFieldNames">Output field names</param>
/// <param name="outputJoinFieldName">Output join field name</param>
/// <param name="whereClause">Where Clause for the Match Table method</param>
/// <param name="cancelTracker"></param>
public void RematchTable(ITable pInputTable, string inputFieldNames, string inputJoinFieldName, IFeatureClass resultTable,
string outputFieldNames, string outputJoinFieldName, string whereClause, ITrackCancel cancelTracker)
{
_log.Debug("IBatchGeocoding RematchTable");
if (inputJoinFieldName == null && inputJoinFieldName == "")
inputJoinFieldName = pInputTable.OIDFieldName;
if (outputJoinFieldName == null && outputJoinFieldName == "")
outputJoinFieldName = resultTable.OIDFieldName;
// Setup the edit session
IWorkspaceEdit workspaceEdit = setupEditSession(resultTable);
IPropertySet fieldsToCopy = new PropertySetClass();
try
{
m_needToUpdate = true;
MatchTable(pInputTable, inputFieldNames, whereClause, resultTable, outputFieldNames, fieldsToCopy, cancelTracker);
m_needToUpdate = false;
}
catch (Exception e)
{
m_needToUpdate = false;
workspaceEdit.AbortEditOperation();
workspaceEdit.StopEditing(false);
throw new Exception("Failed to Rematch the table. ", e);
}
workspaceEdit.StopEditOperation();
workspaceEdit.StopEditing(true);
}
#endregion
#region IESRILocatorReleaseInfo Implemented
public string Release
{
get
{
_log.Debug("IESRILocatorReleaseInfo Release");
return m_locatorProperties.GetProperty("Version") as string;
}
}
#endregion
#region ISingleLineAddressInput Implemented
/// <summary>
/// Recognized names for the single line input field.
/// </summary>
public object DefaultInputFieldNames
{
get
{
_log.Debug("ISingleLineAddressInput DefaultInputFieldNames Get");
return (new string[] { "SingleLine", "SingleLineInput", "Address" }) as object;
}
}
/// <summary>
/// Getter for Single Line Address field
/// </summary>
public IField SingleLineAddressField
{
get
{
_log.Debug("ISingleLineAddressInput SingleLineAddressField Get");
IFieldEdit singleLieField = new FieldClass();
singleLieField.Name_2 = "SingleLine";
singleLieField.Type_2 = esriFieldType.esriFieldTypeString;
singleLieField.AliasName_2 = "Single Line Input";
singleLieField.Required_2 = false;
singleLieField.Length_2 = 50;
return singleLieField;
}
}
#endregion
#region IGeocodeServerSingleLine Implemented
/// <summary>
/// Recognized names for the single line input field.
/// </summary>
/// <returns></returns>
public object GetDefaultInputFieldNames ()
{
_log.Debug("IGeocodeServerSingleLine GetDefaultInputFieldNames");
return DefaultInputFieldNames;
}
/// <summary>
/// Field needed to geocode a single line address.
/// </summary>
/// <returns></returns>
public IField GetSingleLineAddressField ()
{
_log.Debug("IGeocodeServerSingleLine GetSingleLineAddressField");
return SingleLineAddressField;
}
#endregion
#region Misc
/// <summary>
/// Compare two objects to see if they are identical
/// </summary>
/// <param name="a"></param>
/// <param name="b"></param>
/// <returns></returns>
protected bool isSameObject(object a, object b)
{
_log.Debug("Misc isSameObject");
if (a.Equals(b))
return true;
else
return false;
}
/// <summary>
/// Get the path for a locator stored in a file folder
/// </summary>
/// <param name="locatorWorkspaceString"></param>
/// <returns></returns>
private string[] tokenizeLocatorWorkspaceString(string locatorWorkspaceString)
{
_log.Debug("Misc tokenizeLocatorWorkspaceString");
if (locatorWorkspaceString == null)
throw new ArgumentNullException("The locatorWorkspaceString is null.");
string progID = "";
string path = "";
try
{
string[] parsedString = locatorWorkspaceString.Split(new char[] { ';' }, 2);
// First get the WorkspaceFactory Type
if (parsedString.Length > 0)
{
progID = parsedString[0];
string[] progIDArray = progID.Split('=');
// Get the workspaceFactory string and trim the whitespace
if (progIDArray.Length == 2)
progID = progIDArray[1].Trim();
}
// Next get the path
if (parsedString.Length == 2)
{
path = parsedString[1];
string[] pathArray = path.Split('=');
// Get the path to the locator
if (pathArray.Length == 2)
path = pathArray[1].Trim();
}
if (progID == "" || path == "")
throw new Exception("Error parsing LocatorWorkspaceString.");
}
catch (System.ArgumentOutOfRangeException)
{
throw new Exception("Error parsing LocatorWorkspaceString.");
}
return new string[] { progID, path };
}
/// <summary>
/// Get connection properties for FGDB and PGDB
/// </summary>
/// <param name="connection"></param>
/// <returns></returns>
private string[] tokenizeConnectionProperties(string connection)
{
_log.Debug("Misc tokenizeConnectionProperties");
if (connection == null)
throw new ArgumentNullException("The connection properties are null.");
string[] connectionPath;
try
{
string[] connectionArray = connection.Split(new char[] { '=' }, 2);
if (connectionArray.Length == 2)
connection = connectionArray[1];
connectionPath = connection.Split(';');
}
catch (System.ArgumentOutOfRangeException)
{
throw new Exception("Error parsing LocatorWorkspaceString.");
}
return connectionPath;
}
/// <summary>
/// Builds a property set that contains the connection info for SDE
/// </summary>
/// <param name="connection"></param>
/// <returns></returns>
private string tokenizeSDEProperties(string connection)
{
_log.Debug("Misc tokenizeSDEProperties");
if (connection == null)
throw new ArgumentNullException("The SDE connection properties are null.");
try
{
connection = connection.Split(new char[] { '=' }, 2)[1];
connection = connection.Trim();
connection = connection.Trim(new char[] { '(', ')' });
}
catch (System.ArgumentOutOfRangeException)
{
throw new Exception("Error parsing LocatorWorkspaceString.");
}
return connection;
}
/// <summary>
/// Create a workspace for a FGDB or PGDB
/// </summary>
/// <param name="path"></param>
/// <param name="gdbType"></param>
/// <returns></returns>
private IWorkspace createGDBWorkspace(string path, string gdbType)
{
_log.Debug("Misc createGDBWorkspace");
string fullPath = "";
string[] connectionProperties = tokenizeConnectionProperties(path);
if (connectionProperties == null)
throw new ArgumentNullException("The connection properties are null.");
if (connectionProperties.Length > 0)
{
fullPath = connectionProperties[0];
try
{
string[] pathArray = fullPath.Split('=');
// Get the path to the locator
if (pathArray.Length == 2)
{
fullPath = pathArray[1].TrimEnd(')');
fullPath = fullPath.Trim();
}
}
catch (Exception e)
{
throw new Exception("Error parsing LocatorWorkspaceString.", e);
}
}
IWorkspaceFactory workspaceFactory;
if (gdbType.ToLower() == "mdb")
workspaceFactory = new AccessWorkspaceFactoryClass();
else if (gdbType.ToLower() == "gdb")
workspaceFactory = new FileGDBWorkspaceFactoryClass();
else
throw new ArgumentException("Expected GDB Type equal to 'mdb' or 'gdb'.");
return workspaceFactory.OpenFromFile(fullPath, 0);
}
/// <summary>
/// Setup an edit Session for a table
/// </summary>
/// <param name="table"></param>
/// <returns></returns>
private IWorkspaceEdit setupEditSession(IClass table)
{
_log.Debug("Misc setupEditSession");
IDataset dataset = table as IDataset;
IWorkspace workspace = dataset.Workspace;
IWorkspaceEdit workspaceEdit = null;
IVersionedObject versionedObject = table as IVersionedObject;
IObjectClassInfo2 objectClassInfo = table as IObjectClassInfo2;
if (versionedObject != null && versionedObject.IsRegisteredAsVersioned ||
objectClassInfo != null && !objectClassInfo.CanBypassEditSession())
return workspace as IWorkspaceEdit;
workspaceEdit = workspace as IWorkspaceEdit;
if (workspaceEdit != null && !workspaceEdit.IsBeingEdited())
{
try
{
workspaceEdit.StartEditing(true);
}
catch (Exception e)
{
throw new Exception("Exception thrown trying to start the edit session. ", e);
}
try
{
workspaceEdit.StartEditOperation();
}
catch (Exception e)
{
throw new Exception("Exception thrown trying to start editing. ", e);
}
}
return workspaceEdit;
}
/// <summary>
/// Helper method for getting a property and returning null if it isn't found
/// instead of throwing an exception.
/// </summary>
/// <param name="locatorProperties"></param>
/// <param name="Name"></param>
/// <returns>The property value if found. Otherwise 'null'</returns>
protected object getProperty(IPropertySet locatorProperties, String Name)
{
_log.Debug("Misc getProperty");
try
{
return locatorProperties.GetProperty(Name);
}
catch
{
return null;
}
}
/// <summary>
/// Member that allows for getting and setting the Name for the Search Token.
/// Ex. On the Find Dialog, the text that will be displayed in front of the textbox.
///
/// Set this in the .loc file as Fields = YourString
/// </summary>
protected virtual String SearchPropertyName
{
get
{
_log.Debug("Misc SearchPropertyName");
return m_searchTokenName;
}
set
{
_log.Debug("Misc SearchPropertyName");
m_searchTokenName = value;
}
}
protected virtual string SearchTokenAlias
{
get
{
_log.Debug("Misc SearchAliasName");
return m_searchTokenAlias;
}
set
{
_log.Debug("Misc SearchAliasName");
m_searchTokenAlias = value;
}
}
#endregion
}
}
| |
using System;
using System.IO;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Reflection;
using LibUsbDotNet;
using LibUsbDotNet.Info;
using LibUsbDotNet.Main;
#if WIN32
using ATMCD32CS;
#elif x64
using ATMCD64CS;
#endif
namespace WasatchNET
{
[ComVisible(true)]
[Guid("E71326C8-C2BC-404F-81E4-394D95541A24")]
[ProgId("WasatchNET.Driver")]
[ClassInterface(ClassInterfaceType.None)]
public class Driver : IDriver
{
const int MAX_RESETS = 3;
[DllImport("kernel32", SetLastError = true)]
static extern IntPtr LoadLibrary(string lpFileName);
static bool CheckLibrary(string fileName)
{
return LoadLibrary(fileName) != IntPtr.Zero;
}
static Driver instance = new Driver();
List<Spectrometer> spectrometers = new List<Spectrometer>();
bool opened = false;
bool suppressErrors = false;
int resetCount = 0;
public Logger logger { get; } = Logger.getInstance();
public string version { get; }
// This is a Driver-level (singleton) object which tracks whether any
// given spectrometer is believed to be in an "error state" (requiring
// re-initialization) or not. It is passed into each Spectrometer so
// they can update it with their state over time, but there is only one
// instance in the process.
SpectrometerUptime uptime = new SpectrometerUptime();
////////////////////////////////////////////////////////////////////////
// static methods
////////////////////////////////////////////////////////////////////////
/// <summary>
/// Get a handle to the Driver Singleton. Idempotent (can be called
/// repeatedly with no side-effects).
/// </summary>
/// <returns>reference to the Driver Singleton</returns>
public static Driver getInstance()
{
return instance;
}
////////////////////////////////////////////////////////////////////////
// public methods
////////////////////////////////////////////////////////////////////////
/// <summary>
/// Iterate over all discoverable Wasatch Photonics USB spectrometers,
/// and return the number found. Individual spectrometers can then be
/// accessed via the getSpectrometer(index) call.
/// </summary>
/// <remarks>
/// If called multiple times during an application session WITHOUT calling
/// closeAllSpectrometers() in between, will only add/open "new"
/// spectrometers which have been "hotplugged" since the previous call.
///
/// It is unclear how reliable this method will be on subsequent calls
/// if a previously-opened spectrometer has been power-cycled or otherwise
/// reset, but not formally "closed" via Spectrometer.close() or
/// Driver.closeAllSpectrometers().
/// </remarks>
/// <returns>number of Wasatch Photonics USB spectrometers found</returns>
public int openAllSpectrometers()
{
logger.header("openAllSpectrometers: start");
logger.info("Wasatch.NET v{0}", Assembly.GetExecutingAssembly().GetName().Version.ToString());
SortedDictionary<string, List<Spectrometer>> sorted = new SortedDictionary<string, List<Spectrometer>>();
// This requires libusb-1.0.dll in the path, and generates a slew of errors like:
// MonoUsbProfileHandle : ReleaseHandle #9
// LibUsbDotNet.LudnMonoLibUsb.MonoUsbDevice[non - UsbEndpointBase]: MonoApiError: GetDescriptor Failed
// LibUsbDotNet.LudnMonoLibUsb.MonoUsbDevice[non - UsbEndpointBase]: Win32Error: GetLangIDs
//
// UsbDevice.ForceLibUsbWinBack = true;
// This seems to be mainly for Linux
UsbDevice.ForceLegacyLibUsb = false;
UsbDevice.UsbErrorEvent += OnUsbError;
////////////////////////////////////////////////////////////////////
// Add Wasatch Photonics USB spectrometers
////////////////////////////////////////////////////////////////////
// @todo move away from UsbRegistry to prep for LibUsbDotNet 3.x
UsbRegDeviceList deviceRegistries = UsbDevice.AllDevices;
foreach (UsbRegistry usbRegistry in deviceRegistries)
{
String desc = String.Format("Vid:0x{0:x4} Pid:0x{1:x4} (rev:{2}) - {3}",
usbRegistry.Vid,
usbRegistry.Pid,
(ushort) usbRegistry.Rev,
usbRegistry[SPDRP.DeviceDesc]);
// Generate a "unique key" for the spectrometer based on its
// "physical" USB properties (no EEPROM fields involved). This
// is being explored as a way to better recognize individual
// spectrometers within a set, where one spectrometer has been
// power-cycled or re-enumerated, but the others have not (and
// the caller doesn't necessarily know which, so a repeat call
// to "openAllSpectrometers" is intended to "get the new one(s)
// running, without disrupting the old one(s)".
logger.debug("USB Registry for: {0}", desc);
logDevice(usbRegistry);
if (usbRegistry.Vid == 0x24aa && usbRegistry.Pid == 0x5000)
{
HOCTSpectrometer spectrometer = new HOCTSpectrometer(usbRegistry);
if (spectrometer.open())
{
string key = String.Format("{0}-{1}", "HOCT", "0000");
if (!sorted.ContainsKey(key))
sorted.Add(key, new List<Spectrometer>());
sorted[key].Add(spectrometer);
}
}
else if (usbRegistry.Vid == 0x24aa)
{
Spectrometer spectrometer = new Spectrometer(usbRegistry) { uptime = uptime };
if (spectrometer.open())
{
// sort them by model, serial (allow duplicates for unconfigured)
string key = String.Format("{0}-{1}", spectrometer.eeprom.model, spectrometer.eeprom.serialNumber);
if (!sorted.ContainsKey(key))
sorted.Add(key, new List<Spectrometer>());
sorted[key].Add(spectrometer);
logger.debug("openAllSpectrometers: found key {0} ({1})", key, desc);
}
else
{
logger.error("openAllSpectrometers: failed to open {0}", desc);
}
}
else
{
logger.debug("openAllSpectrometers: ignored {0}", desc);
}
}
// add to final list in sorted order
spectrometers.Clear();
logger.debug("openAllSpectrometers: sorting indices for deterministic behavior");
foreach (KeyValuePair<string, List<Spectrometer>> pair in sorted)
{
foreach (Spectrometer s in pair.Value)
{
spectrometers.Add(s);
logger.debug(" index {0}: {1} {2}", spectrometers.Count - 1, s.model, s.serialNumber);
}
}
////////////////////////////////////////////////////////////////////
// Add Wasatch Photonics SPI spectrometers
////////////////////////////////////////////////////////////////////
if (Environment.GetEnvironmentVariable("WASATCHNET_USE_SPI") != null)
{
logger.debug("Checking for SPI spectrometers");
string currentDir = Directory.GetCurrentDirectory(); // pushdir
logger.debug("caching directory {0}", currentDir);
try
{
// to load FTD2XX.dll, we apparently need to be in its directory
string dllDir = Path.Combine(new string[] {
Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), // "Program Files" or "(ibid) x86" as appropriate
"Wasatch Photonics",
"Wasatch.NET" });
logger.debug("changing directory to {0}", dllDir);
Directory.SetCurrentDirectory(dllDir);
logger.debug("directory now {0}", Directory.GetCurrentDirectory());
SPISpectrometer spiSpec = new SPISpectrometer(null);
logger.debug("attempting to open spi spectrometer");
bool opened = spiSpec.open();
if (opened)
{
logger.debug("found SPISpectrometer");
spectrometers.Add(spiSpec);
}
else
{
logger.debug("no SPISpectrometer found");
}
}
catch
{
logger.debug("Unable to check for SPISpectrometer");
}
finally
{
logger.debug("restoring directory {0}", currentDir);
Directory.SetCurrentDirectory(currentDir); // popdir
}
}
////////////////////////////////////////////////////////////////////
// Add 3rd-party USB spectrometers (e.g. Ocean Optics, etc)
////////////////////////////////////////////////////////////////////
if (Environment.GetEnvironmentVariable("WASATCHNET_USE_SEABREEZE") != null)
{
logger.debug("Checking for SeaBreeze and Ocean Optics spectrometers");
// Add 3rd-party USB spectrometers (e.g. Ocean Optics, etc)
bool sbPresent = CheckLibrary("SeaBreeze");
logger.debug("SeaBreeze {0} installed", sbPresent ? "appears" : "not");
if (deviceRegistries.Count > 0 && Environment.Is64BitProcess && sbPresent)
{
UsbRegistry usbRegistry2 = deviceRegistries[0];
String desc2 = String.Format("Vid:0x{0:x4} Pid:0x{1:x4} (rev:{2}) - {3}",
usbRegistry2.Vid,
usbRegistry2.Pid,
(ushort)usbRegistry2.Rev,
usbRegistry2[SPDRP.DeviceDesc]);
int boulderIndex = 0;
try
{
BoulderSpectrometer boulderSpectrometer = new BoulderSpectrometer(usbRegistry2, boulderIndex);
while (boulderSpectrometer.open())
{
boulderSpectrometer.detectorTECSetpointDegC = 15.0f;
spectrometers.Add(boulderSpectrometer);
++boulderIndex;
boulderSpectrometer = new BoulderSpectrometer(usbRegistry2, boulderIndex);
}
if (boulderIndex == 0)
{
logger.debug("openAllSpectrometers: failed to open {0}", desc2);
}
}
catch (DllNotFoundException)
{
logger.debug("SeaBreeze does not appear to be installed, not trying to open relevant Spectrometers");
}
}
}
#if WIN32
AndorSDK andorDriver = new ATMCD32CS.AndorSDK();
#elif x64
AndorSDK andorDriver = new ATMCD64CS.AndorSDK();
#endif
#if WIN32 || x64
int numAndorAvailable = 0;
andorDriver.GetAvailableCameras(ref numAndorAvailable);
logger.info("Found {0} Andor cameras", numAndorAvailable);
if (numAndorAvailable > 0)
{
for (int i = 0; i < numAndorAvailable; ++i)
{
logger.info("Attempting to open Andor camera {0}", i);
AndorSpectrometer spec = new AndorSpectrometer(null, i);
if (spec.open())
spectrometers.Add(spec);
}
}
#endif
logger.debug($"openAllSpectrometers: returning {spectrometers.Count}");
opened = true;
return spectrometers.Count;
}
public int openMockSpectrometer(uint pixels)
{
MockSpectrometer mockSpectrometer = new MockSpectrometer(null);
if(mockSpectrometer.open(pixels))
spectrometers.Add(mockSpectrometer);
return spectrometers.Count;
}
/// <summary>
/// How many Wasatch USB spectrometers were found.
/// </summary>
/// <returns>number of enumerated Wasatch spectrometers</returns>
public int getNumberOfSpectrometers()
{
return spectrometers.Count;
}
/// <summary>
/// Obtains a reference to the specified spectrometer, performing any
/// prelimary "open" / instantiation steps required to leave the spectrometer
/// fully ready for use.
/// </summary>
/// <param name="index">zero-indexed (should be less than the value returned by openAllSpectrometers() / getNumberOfSpectrometers())</param>
/// <remarks>Spectrometers are deterministically ordered by (model, serialNumber) for repeatability.</remarks>
/// <returns>a reference to the requested Spectrometer object, or null on error</returns>
public Spectrometer getSpectrometer(int index)
{
if (index < spectrometers.Count)
return spectrometers[index];
return null;
}
/// <summary>
/// Automatically called as part of application shutdown (can be called manually).
/// </summary>
public void closeAllSpectrometers()
{
if (!opened)
{
logger.debug("closeAllSpectrometers: not opened");
return;
}
logger.debug("closeAllSpectrometers: start");
lock (this)
{
if (spectrometers.Count > 0)
{
foreach (Spectrometer spectrometer in spectrometers)
{
logger.debug("closeAllSpectrometers: closing spectrometer");
spectrometer.close();
}
spectrometers.Clear();
}
else
logger.debug("closeAllSpectrometers: no spectrometers to close");
logger.debug("closeAllSpectrometers: unregistering error handler");
UsbDevice.UsbErrorEvent -= OnUsbError;
logger.debug("closeAllSpectrometers: exiting UsbDevice");
UsbDevice.Exit();
}
opened = false;
logger.debug("closeAllSpectrometers: done");
}
////////////////////////////////////////////////////////////////////////
// private methods
////////////////////////////////////////////////////////////////////////
private Driver()
{
version = String.Format("Wasatch.NET v{0}", Assembly.GetExecutingAssembly().GetName().Version.ToString());
}
~Driver()
{
logger.close();
closeAllSpectrometers();
}
void logDevice(UsbRegistry usbRegistry)
{
UsbDevice device;
if (!usbRegistry.Open(out device))
return;
// split device.Info's string representation on linefeeds
// iterateDevice: Vid:0x2457 Pid:0x101E (rev:2) - Ocean Optics USB2000+ (WinUSB)
// iterateDevice: Vid:0x24AA Pid:0x1000 (rev:100) - Wasatch Photonics Spectrometer
// Not all device info summaries will appear in device.Configs...not sure why
string[] deviceInfoSummaries = device.Info.ToString().Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
foreach (string line in deviceInfoSummaries)
logger.debug("Summary: {0}", line);
// SiG-VIS doesn't seem to like the advanced logging?
// if (usbRegistry.Pid == 0x4000)
// {
// device.Close();
// return;
// }
foreach (UsbConfigInfo cfgInfo in device.Configs)
{
logger.debug("Config {0}", cfgInfo.Descriptor.ConfigID);
// log UsbConfigInfo
logNameValuePairs(cfgInfo.ToString().Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries));
// log UsbInterfaceInfo
foreach (UsbInterfaceInfo interfaceInfo in cfgInfo.InterfaceInfoList)
{
logger.debug("Interface [InterfaceID {0}, AlternateID {1}]", interfaceInfo.Descriptor.InterfaceID, interfaceInfo.Descriptor.AlternateID);
logNameValuePairs(interfaceInfo.ToString().Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries));
// log UsbEndpointInfo
foreach (UsbEndpointInfo endpointInfo in interfaceInfo.EndpointInfoList)
{
logger.debug(" Endpoint 0x" + (endpointInfo.Descriptor.EndpointID).ToString("x2"));
logNameValuePairs(endpointInfo.ToString().Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries), " ");
}
}
}
device.Close();
UsbSymbolicName symName = UsbSymbolicName.Parse(usbRegistry.SymbolicName);
logger.debug("Symbolic Name:");
logger.debug(" VID: 0x{0:x4}", symName.Vid);
logger.debug(" PID: 0x{0:x4}", symName.Pid);
logger.debug(" SerialNumber: {0}", symName.SerialNumber);
logger.debug(" Class Guid: {0}", symName.ClassGuid);
logger.debug("Device Properties:");
foreach (KeyValuePair<string, object> pair in usbRegistry.DeviceProperties)
{
string key = pair.Key;
object value = pair.Value;
if (value is string[])
logger.debug(" {0}: {1}", key, string.Format("[ {0} ]", string.Join(", ", value as string[])));
else if (value is string)
logger.debug(" {0}: {1}", key, value as string);
}
}
void logNameValuePairs(string[] pairs, string prefix = " ")
{
foreach (string pair in pairs)
{
string[] tok = pair.Split(':');
if (tok.Length == 2)
logger.debug("{0}{1} = {2}", prefix, tok[0], tok[1]);
else
logger.debug("{0}unparseable: {1}", prefix, pair);
}
}
void attemptReset(object sender)
{
UsbDevice usb = sender as UsbDevice;
if (usb != null && usb.IsOpen)
{
if (resetCount > MAX_RESETS)
{
logger.error("exceeded max resets, closing device");
usb.Close();
return;
}
UsbEndpointBase baseDevice = sender as UsbEndpointBase;
if (baseDevice != null)
{
// UsbEndpointInfo uei = baseDevice.EndpointInfo;
// LibUsbDotNet.Descriptors.UsbEndpointDescriptor ued = uei.Descriptor;
logger.error($"[UsbEndPointBase]: usb device still open on endpoint 0x{baseDevice.EpNum}, so resetting endpoint");
baseDevice.Reset();
resetCount++;
}
}
else
{
// probably need to reconnect, per https://stackoverflow.com/questions/20822869/libusbdotnet-strange-errors-after-working-with-usb-device-for-awhile
// except the reconnect recommended by the above SO link is basically
// what we already have in Spectrometer.reconnect(), so maybe we want
// to continue to "silently ignore" here and handle this from
// Spectrometer.getSpectrum()?
// Perhaps this would be a good place to throw a custom exception
// that could be caught in getSpectrum, which could then trigger reconnect()?
logger.error("YOU ARE HERE -- add disconnect / reconnect logic?");
UsbEndpointReader reader = sender as UsbEndpointReader;
if (reader != null)
{
logger.error($"[UsbEndpointReader]: hit error at endpoint 0x{reader.EpNum:x2}");
//reader.Reset();
//reader.Flush();
return;
}
}
}
void OnUsbError(object sender, UsbError e)
{
if (suppressErrors)
return;
string prefix = String.Format("WasatchNET.Driver.OnUsbError (sender {0}):", sender.GetType());
if (sender is UsbEndpointBase)
{
logger.error("{0} [UsbEndPointBase]: Win32ErrorNumber {1} ({2}): {3}",
prefix, e.Win32ErrorNumber, e.Win32ErrorString, e.Description);
if (e.Win32ErrorNumber == 31)
{
// Magic number 31 came from here: http://libusbdotnet.sourceforge.net/V2/html/718df290-f19a-9033-3a26-1e8917adf15d.htm
// (actually arises with ARM devices in testing)
// per https://docs.microsoft.com/en-us/windows/win32/debug/system-error-codes--0-499-
// 31 == ERROR_GEN_FAILURE (0x1f) "A device attached to the system is not functioning."
logger.error("[Driver] A device attached to the system is not functioning");
attemptReset(sender);
}
else if (e.Win32ErrorNumber == 22)
{
logger.error("[Driver] The device does not recognize the command");
attemptReset(sender);
}
else
{
// silently ignore errors other than Win32Error 31
}
}
else if (sender is UsbTransfer)
{
logger.error("{0} [UsbTransfer]: Win32ErrorNumber {1} ({2}): {3}",
prefix, e.Win32ErrorNumber, e.Win32ErrorString, e.Description);
UsbEndpointBase ep = ((UsbTransfer)sender).EndpointBase;
logger.error("{0} [UsbTransfer]: Endpoint = 0x{1:x2}", prefix, ep.EpNum);
}
else if (sender is Type)
{
Type t = sender as Type;
// reduce log level on these, as they seem to flood during
// recovery from errors logged elsewhere:
if (sender.GetType().ToString() == "System.RuntimeType" && t.Name == "LibUsbDriverIO")
logger.debug("{0} [Type]: type = {1}", prefix, t.Name);
else
logger.error("{0} [Type]: type = {1}", prefix, t.Name);
}
else
{
logger.error("{0} [other]: {1}", prefix, e.ToString());
// is there anything we should DO here, other than logging it?
}
}
// if ((mSender is UsbEndpointBase)|| (mSender is UsbTransfer))
// {
// UsbEndpointBase ep;
// if (mSender is UsbTransfer)
// ep = ((UsbTransfer) mSender).EndpointBase;
// else
// ep = mSender as UsbEndpointBase;
//
// if (ep.mEpNum != 0)
// {
// senderText = senderText+=string.Format(" Ep 0x{0:X2} ", ep.mEpNum);
// }
// }
// else if (mSender is Type)
// {
// Type t = mSender as Type;
// senderText = senderText += string.Format(" {0} ", t.Name);
// }
public MultiChannelWrapper getMultiChannelWrapper()
{
return MultiChannelWrapper.getInstance();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics.Contracts;
using System.Threading;
using System.Threading.Tasks;
namespace System.IO
{
public partial class FileStream : Stream
{
internal const int DefaultBufferSize = 4096;
private const FileShare DefaultShare = FileShare.Read;
private const bool DefaultUseAsync = false;
private const bool DefaultIsAsync = false;
private FileStreamBase _innerStream;
internal FileStream(FileStreamBase innerStream)
{
if (innerStream == null)
{
throw new ArgumentNullException(nameof(innerStream));
}
this._innerStream = innerStream;
}
public FileStream(Microsoft.Win32.SafeHandles.SafeFileHandle handle, FileAccess access) :
this(handle, access, DefaultBufferSize)
{
}
public FileStream(string path, System.IO.FileMode mode) :
this(path, mode, (mode == FileMode.Append ? FileAccess.Write : FileAccess.ReadWrite), DefaultShare, DefaultBufferSize, DefaultUseAsync)
{ }
public FileStream(string path, System.IO.FileMode mode, FileAccess access) :
this(path, mode, access, DefaultShare, DefaultBufferSize, DefaultUseAsync)
{ }
public FileStream(string path, System.IO.FileMode mode, FileAccess access, FileShare share) :
this(path, mode, access, share, DefaultBufferSize, DefaultUseAsync)
{ }
public FileStream(string path, System.IO.FileMode mode, FileAccess access, FileShare share, int bufferSize) :
this(path, mode, access, share, bufferSize, DefaultUseAsync)
{ }
public FileStream(string path, System.IO.FileMode mode, FileAccess access, FileShare share, int bufferSize, bool useAsync) :
this(path, mode, access, share, bufferSize, useAsync ? FileOptions.Asynchronous : FileOptions.None)
{ }
public FileStream(string path, System.IO.FileMode mode, FileAccess access, FileShare share, int bufferSize, FileOptions options)
{
Init(path, mode, access, share, bufferSize, options);
}
private void Init(String path, FileMode mode, FileAccess access, FileShare share, int bufferSize, FileOptions options)
{
if (path == null)
throw new ArgumentNullException(nameof(path), SR.ArgumentNull_Path);
if (path.Length == 0)
throw new ArgumentException(SR.Argument_EmptyPath, nameof(path));
// don't include inheritable in our bounds check for share
FileShare tempshare = share & ~FileShare.Inheritable;
String badArg = null;
if (mode < FileMode.CreateNew || mode > FileMode.Append)
badArg = "mode";
else if (access < FileAccess.Read || access > FileAccess.ReadWrite)
badArg = "access";
else if (tempshare < FileShare.None || tempshare > (FileShare.ReadWrite | FileShare.Delete))
badArg = "share";
if (badArg != null)
throw new ArgumentOutOfRangeException(badArg, SR.ArgumentOutOfRange_Enum);
// NOTE: any change to FileOptions enum needs to be matched here in the error validation
if (options != FileOptions.None && (options & ~(FileOptions.WriteThrough | FileOptions.Asynchronous | FileOptions.RandomAccess | FileOptions.DeleteOnClose | FileOptions.SequentialScan | FileOptions.Encrypted | (FileOptions)0x20000000 /* NoBuffering */)) != 0)
throw new ArgumentOutOfRangeException(nameof(options), SR.ArgumentOutOfRange_Enum);
if (bufferSize <= 0)
throw new ArgumentOutOfRangeException(nameof(bufferSize), SR.ArgumentOutOfRange_NeedPosNum);
// Write access validation
if ((access & FileAccess.Write) == 0)
{
if (mode == FileMode.Truncate || mode == FileMode.CreateNew || mode == FileMode.Create || mode == FileMode.Append)
{
// No write access, mode and access disagree but flag access since mode comes first
throw new ArgumentException(SR.Format(SR.Argument_InvalidFileModeAndAccessCombo, mode, access), nameof(access));
}
}
string fullPath = Path.GetFullPath(path);
ValidatePath(fullPath, "path");
if ((access & FileAccess.Read) != 0 && mode == FileMode.Append)
throw new ArgumentException(SR.Argument_InvalidAppendMode, nameof(access));
this._innerStream = FileSystem.Current.Open(fullPath, mode, access, share, bufferSize, options, this);
}
static partial void ValidatePath(string fullPath, string paramName);
// InternalOpen, InternalCreate, and InternalAppend:
// Factory methods for FileStream used by File, FileInfo, and ReadLinesIterator
// Specifies default access and sharing options for FileStreams created by those classes
internal static FileStream InternalOpen(String path, int bufferSize = DefaultBufferSize, bool useAsync = DefaultUseAsync)
{
return new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, bufferSize, useAsync);
}
internal static FileStream InternalCreate(String path, int bufferSize = DefaultBufferSize, bool useAsync = DefaultUseAsync)
{
return new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read, bufferSize, useAsync);
}
internal static FileStream InternalAppend(String path, int bufferSize = DefaultBufferSize, bool useAsync = DefaultUseAsync)
{
return new FileStream(path, FileMode.Append, FileAccess.Write, FileShare.Read, bufferSize, useAsync);
}
#region FileStream members
public virtual bool IsAsync { get { return this._innerStream.IsAsync; } }
public string Name { get { return this._innerStream.Name; } }
public virtual Microsoft.Win32.SafeHandles.SafeFileHandle SafeFileHandle { get { return this._innerStream.SafeFileHandle; } }
public virtual IntPtr Handle { get { return SafeFileHandle.DangerousGetHandle(); } }
public virtual void Flush(bool flushToDisk)
{
this._innerStream.Flush(flushToDisk);
}
public virtual void Lock(long position, long length)
{
if (position < 0 || length < 0)
{
throw new ArgumentOutOfRangeException(position < 0 ? nameof(position) : nameof(length), SR.ArgumentOutOfRange_NeedNonNegNum);
}
_innerStream.Lock(position, length);
}
public virtual void Unlock(long position, long length)
{
if (position < 0 || length < 0)
{
throw new ArgumentOutOfRangeException(position < 0 ? nameof(position) : nameof(length), SR.ArgumentOutOfRange_NeedNonNegNum);
}
_innerStream.Unlock(position, length);
}
#endregion
#region Stream members
#region Properties
public override bool CanRead
{
get { return _innerStream.CanRead; }
}
public override bool CanSeek
{
get { return _innerStream.CanSeek; }
}
public override bool CanWrite
{
get { return _innerStream.CanWrite; }
}
public override long Length
{
get { return _innerStream.Length; }
}
public override long Position
{
get { return _innerStream.Position; }
set { _innerStream.Position = value; }
}
public override int ReadTimeout
{
get { return _innerStream.ReadTimeout; }
set { _innerStream.ReadTimeout = value; }
}
public override bool CanTimeout
{
get { return _innerStream.CanTimeout; }
}
public override int WriteTimeout
{
get { return _innerStream.WriteTimeout; }
set { _innerStream.WriteTimeout = value; }
}
#endregion Properties
#region Methods
public override Task CopyToAsync(Stream destination, int bufferSize, CancellationToken cancellationToken)
{
return _innerStream.CopyToAsync(destination, bufferSize, cancellationToken);
}
protected override void Dispose(bool disposing)
{
if (_innerStream != null)
{
// called even during finalization
_innerStream.DisposeInternal(disposing);
}
base.Dispose(disposing);
}
public override void Flush()
{
_innerStream.Flush();
}
public override Task FlushAsync(CancellationToken cancellationToken)
{
// If we have been inherited into a subclass, the following implementation could be incorrect
// since it does not call through to Flush() which a subclass might have overridden. To be safe
// we will only use this implementation in cases where we know it is safe to do so,
// and delegate to our base class (which will call into Flush) when we are not sure.
if (this.GetType() != typeof(FileStream))
return base.FlushAsync(cancellationToken);
return _innerStream.FlushAsync(cancellationToken);
}
public override int Read(byte[] buffer, int offset, int count)
{
return _innerStream.Read(buffer, offset, count);
}
public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
if (buffer == null)
throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
if (offset < 0)
throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum);
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
if (buffer.Length - offset < count)
throw new ArgumentException(SR.Argument_InvalidOffLen /*, no good single parameter name to pass*/);
Contract.EndContractBlock();
// If we have been inherited into a subclass, the following implementation could be incorrect
// since it does not call through to Read() or ReadAsync() which a subclass might have overridden.
// To be safe we will only use this implementation in cases where we know it is safe to do so,
// and delegate to our base class (which will call into Read/ReadAsync) when we are not sure.
if (this.GetType() != typeof(FileStream))
return base.ReadAsync(buffer, offset, count, cancellationToken);
return _innerStream.ReadAsync(buffer, offset, count, cancellationToken);
}
public override int ReadByte()
{
return _innerStream.ReadByte();
}
public override long Seek(long offset, SeekOrigin origin)
{
return _innerStream.Seek(offset, origin);
}
public override void SetLength(long value)
{
_innerStream.SetLength(value);
}
public override void Write(byte[] buffer, int offset, int count)
{
_innerStream.Write(buffer, offset, count);
}
public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
if (buffer == null)
throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
if (offset < 0)
throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum);
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
if (buffer.Length - offset < count)
throw new ArgumentException(SR.Argument_InvalidOffLen /*, no good single parameter name to pass*/);
Contract.EndContractBlock();
// If we have been inherited into a subclass, the following implementation could be incorrect
// since it does not call through to Write() or WriteAsync() which a subclass might have overridden.
// To be safe we will only use this implementation in cases where we know it is safe to do so,
// and delegate to our base class (which will call into Write/WriteAsync) when we are not sure.
if (this.GetType() != typeof(FileStream))
return base.WriteAsync(buffer, offset, count, cancellationToken);
return _innerStream.WriteAsync(buffer, offset, count, cancellationToken);
}
public override void WriteByte(byte value)
{
_innerStream.WriteByte(value);
}
#endregion Methods
#endregion Stream members
[Security.SecuritySafeCritical]
~FileStream()
{
// Preserved for compatibility since FileStream has defined a
// finalizer in past releases and derived classes may depend
// on Dispose(false) call.
Dispose(false);
}
}
}
| |
// ReSharper disable All
using System.Collections.Generic;
using System.Dynamic;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Frapid.ApplicationState.Cache;
using Frapid.ApplicationState.Models;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Frapid.Account.DataAccess;
using Frapid.DataAccess;
using Frapid.DataAccess.Models;
using Frapid.Framework;
using Frapid.Framework.Extensions;
namespace Frapid.Account.Api
{
/// <summary>
/// Provides a direct HTTP access to perform various tasks such as adding, editing, and removing Reset Requests.
/// </summary>
[RoutePrefix("api/v1.0/account/reset-request")]
public class ResetRequestController : FrapidApiController
{
/// <summary>
/// The ResetRequest repository.
/// </summary>
private readonly IResetRequestRepository ResetRequestRepository;
public ResetRequestController()
{
this._LoginId = AppUsers.GetCurrent().View.LoginId.To<long>();
this._UserId = AppUsers.GetCurrent().View.UserId.To<int>();
this._OfficeId = AppUsers.GetCurrent().View.OfficeId.To<int>();
this._Catalog = AppUsers.GetCatalog();
this.ResetRequestRepository = new Frapid.Account.DataAccess.ResetRequest
{
_Catalog = this._Catalog,
_LoginId = this._LoginId,
_UserId = this._UserId
};
}
public ResetRequestController(IResetRequestRepository repository, string catalog, LoginView view)
{
this._LoginId = view.LoginId.To<long>();
this._UserId = view.UserId.To<int>();
this._OfficeId = view.OfficeId.To<int>();
this._Catalog = catalog;
this.ResetRequestRepository = repository;
}
public long _LoginId { get; }
public int _UserId { get; private set; }
public int _OfficeId { get; private set; }
public string _Catalog { get; }
/// <summary>
/// Creates meta information of "reset request" entity.
/// </summary>
/// <returns>Returns the "reset request" meta information to perform CRUD operation.</returns>
[AcceptVerbs("GET", "HEAD")]
[Route("meta")]
[Route("~/api/account/reset-request/meta")]
[Authorize]
public EntityView GetEntityView()
{
if (this._LoginId == 0)
{
return new EntityView();
}
return new EntityView
{
PrimaryKey = "request_id",
Columns = new List<EntityColumn>()
{
new EntityColumn { ColumnName = "request_id", PropertyName = "RequestId", DataType = "System.Guid", DbDataType = "uuid", IsNullable = false, IsPrimaryKey = true, IsSerial = false, Value = "", MaxLength = 0 },
new EntityColumn { ColumnName = "user_id", PropertyName = "UserId", DataType = "int", DbDataType = "int4", IsNullable = false, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 0 },
new EntityColumn { ColumnName = "email", PropertyName = "Email", DataType = "string", DbDataType = "text", IsNullable = true, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 0 },
new EntityColumn { ColumnName = "name", PropertyName = "Name", DataType = "string", DbDataType = "text", IsNullable = true, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 0 },
new EntityColumn { ColumnName = "requested_on", PropertyName = "RequestedOn", DataType = "DateTime", DbDataType = "timestamptz", IsNullable = false, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 0 },
new EntityColumn { ColumnName = "expires_on", PropertyName = "ExpiresOn", DataType = "DateTime", DbDataType = "timestamptz", IsNullable = false, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 0 },
new EntityColumn { ColumnName = "browser", PropertyName = "Browser", DataType = "string", DbDataType = "text", IsNullable = true, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 0 },
new EntityColumn { ColumnName = "ip_address", PropertyName = "IpAddress", DataType = "string", DbDataType = "varchar", IsNullable = true, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 50 },
new EntityColumn { ColumnName = "confirmed", PropertyName = "Confirmed", DataType = "bool", DbDataType = "bool", IsNullable = true, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 0 },
new EntityColumn { ColumnName = "confirmed_on", PropertyName = "ConfirmedOn", DataType = "DateTime", DbDataType = "timestamptz", IsNullable = true, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 0 }
}
};
}
/// <summary>
/// Counts the number of reset requests.
/// </summary>
/// <returns>Returns the count of the reset requests.</returns>
[AcceptVerbs("GET", "HEAD")]
[Route("count")]
[Route("~/api/account/reset-request/count")]
[Authorize]
public long Count()
{
try
{
return this.ResetRequestRepository.Count();
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Returns all collection of reset request.
/// </summary>
/// <returns></returns>
[AcceptVerbs("GET", "HEAD")]
[Route("all")]
[Route("~/api/account/reset-request/all")]
[Authorize]
public IEnumerable<Frapid.Account.Entities.ResetRequest> GetAll()
{
try
{
return this.ResetRequestRepository.GetAll();
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Returns collection of reset request for export.
/// </summary>
/// <returns></returns>
[AcceptVerbs("GET", "HEAD")]
[Route("export")]
[Route("~/api/account/reset-request/export")]
[Authorize]
public IEnumerable<dynamic> Export()
{
try
{
return this.ResetRequestRepository.Export();
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Returns an instance of reset request.
/// </summary>
/// <param name="requestId">Enter RequestId to search for.</param>
/// <returns></returns>
[AcceptVerbs("GET", "HEAD")]
[Route("{requestId}")]
[Route("~/api/account/reset-request/{requestId}")]
[Authorize]
public Frapid.Account.Entities.ResetRequest Get(System.Guid requestId)
{
try
{
return this.ResetRequestRepository.Get(requestId);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
[AcceptVerbs("GET", "HEAD")]
[Route("get")]
[Route("~/api/account/reset-request/get")]
[Authorize]
public IEnumerable<Frapid.Account.Entities.ResetRequest> Get([FromUri] System.Guid[] requestIds)
{
try
{
return this.ResetRequestRepository.Get(requestIds);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Returns the first instance of reset request.
/// </summary>
/// <returns></returns>
[AcceptVerbs("GET", "HEAD")]
[Route("first")]
[Route("~/api/account/reset-request/first")]
[Authorize]
public Frapid.Account.Entities.ResetRequest GetFirst()
{
try
{
return this.ResetRequestRepository.GetFirst();
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Returns the previous instance of reset request.
/// </summary>
/// <param name="requestId">Enter RequestId to search for.</param>
/// <returns></returns>
[AcceptVerbs("GET", "HEAD")]
[Route("previous/{requestId}")]
[Route("~/api/account/reset-request/previous/{requestId}")]
[Authorize]
public Frapid.Account.Entities.ResetRequest GetPrevious(System.Guid requestId)
{
try
{
return this.ResetRequestRepository.GetPrevious(requestId);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Returns the next instance of reset request.
/// </summary>
/// <param name="requestId">Enter RequestId to search for.</param>
/// <returns></returns>
[AcceptVerbs("GET", "HEAD")]
[Route("next/{requestId}")]
[Route("~/api/account/reset-request/next/{requestId}")]
[Authorize]
public Frapid.Account.Entities.ResetRequest GetNext(System.Guid requestId)
{
try
{
return this.ResetRequestRepository.GetNext(requestId);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Returns the last instance of reset request.
/// </summary>
/// <returns></returns>
[AcceptVerbs("GET", "HEAD")]
[Route("last")]
[Route("~/api/account/reset-request/last")]
[Authorize]
public Frapid.Account.Entities.ResetRequest GetLast()
{
try
{
return this.ResetRequestRepository.GetLast();
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Creates a paginated collection containing 10 reset requests on each page, sorted by the property RequestId.
/// </summary>
/// <returns>Returns the first page from the collection.</returns>
[AcceptVerbs("GET", "HEAD")]
[Route("")]
[Route("~/api/account/reset-request")]
[Authorize]
public IEnumerable<Frapid.Account.Entities.ResetRequest> GetPaginatedResult()
{
try
{
return this.ResetRequestRepository.GetPaginatedResult();
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Creates a paginated collection containing 10 reset requests on each page, sorted by the property RequestId.
/// </summary>
/// <param name="pageNumber">Enter the page number to produce the resultset.</param>
/// <returns>Returns the requested page from the collection.</returns>
[AcceptVerbs("GET", "HEAD")]
[Route("page/{pageNumber}")]
[Route("~/api/account/reset-request/page/{pageNumber}")]
[Authorize]
public IEnumerable<Frapid.Account.Entities.ResetRequest> GetPaginatedResult(long pageNumber)
{
try
{
return this.ResetRequestRepository.GetPaginatedResult(pageNumber);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Counts the number of reset requests using the supplied filter(s).
/// </summary>
/// <param name="filters">The list of filter conditions.</param>
/// <returns>Returns the count of filtered reset requests.</returns>
[AcceptVerbs("POST")]
[Route("count-where")]
[Route("~/api/account/reset-request/count-where")]
[Authorize]
public long CountWhere([FromBody]JArray filters)
{
try
{
List<Frapid.DataAccess.Models.Filter> f = filters.ToObject<List<Frapid.DataAccess.Models.Filter>>(JsonHelper.GetJsonSerializer());
return this.ResetRequestRepository.CountWhere(f);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Creates a filtered and paginated collection containing 10 reset requests on each page, sorted by the property RequestId.
/// </summary>
/// <param name="pageNumber">Enter the page number to produce the resultset. If you provide a negative number, the result will not be paginated.</param>
/// <param name="filters">The list of filter conditions.</param>
/// <returns>Returns the requested page from the collection using the supplied filters.</returns>
[AcceptVerbs("POST")]
[Route("get-where/{pageNumber}")]
[Route("~/api/account/reset-request/get-where/{pageNumber}")]
[Authorize]
public IEnumerable<Frapid.Account.Entities.ResetRequest> GetWhere(long pageNumber, [FromBody]JArray filters)
{
try
{
List<Frapid.DataAccess.Models.Filter> f = filters.ToObject<List<Frapid.DataAccess.Models.Filter>>(JsonHelper.GetJsonSerializer());
return this.ResetRequestRepository.GetWhere(pageNumber, f);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Counts the number of reset requests using the supplied filter name.
/// </summary>
/// <param name="filterName">The named filter.</param>
/// <returns>Returns the count of filtered reset requests.</returns>
[AcceptVerbs("GET", "HEAD")]
[Route("count-filtered/{filterName}")]
[Route("~/api/account/reset-request/count-filtered/{filterName}")]
[Authorize]
public long CountFiltered(string filterName)
{
try
{
return this.ResetRequestRepository.CountFiltered(filterName);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Creates a filtered and paginated collection containing 10 reset requests on each page, sorted by the property RequestId.
/// </summary>
/// <param name="pageNumber">Enter the page number to produce the resultset. If you provide a negative number, the result will not be paginated.</param>
/// <param name="filterName">The named filter.</param>
/// <returns>Returns the requested page from the collection using the supplied filters.</returns>
[AcceptVerbs("GET", "HEAD")]
[Route("get-filtered/{pageNumber}/{filterName}")]
[Route("~/api/account/reset-request/get-filtered/{pageNumber}/{filterName}")]
[Authorize]
public IEnumerable<Frapid.Account.Entities.ResetRequest> GetFiltered(long pageNumber, string filterName)
{
try
{
return this.ResetRequestRepository.GetFiltered(pageNumber, filterName);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Displayfield is a lightweight key/value collection of reset requests.
/// </summary>
/// <returns>Returns an enumerable key/value collection of reset requests.</returns>
[AcceptVerbs("GET", "HEAD")]
[Route("display-fields")]
[Route("~/api/account/reset-request/display-fields")]
[Authorize]
public IEnumerable<Frapid.DataAccess.Models.DisplayField> GetDisplayFields()
{
try
{
return this.ResetRequestRepository.GetDisplayFields();
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// A custom field is a user defined field for reset requests.
/// </summary>
/// <returns>Returns an enumerable custom field collection of reset requests.</returns>
[AcceptVerbs("GET", "HEAD")]
[Route("custom-fields")]
[Route("~/api/account/reset-request/custom-fields")]
[Authorize]
public IEnumerable<Frapid.DataAccess.Models.CustomField> GetCustomFields()
{
try
{
return this.ResetRequestRepository.GetCustomFields(null);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// A custom field is a user defined field for reset requests.
/// </summary>
/// <returns>Returns an enumerable custom field collection of reset requests.</returns>
[AcceptVerbs("GET", "HEAD")]
[Route("custom-fields/{resourceId}")]
[Route("~/api/account/reset-request/custom-fields/{resourceId}")]
[Authorize]
public IEnumerable<Frapid.DataAccess.Models.CustomField> GetCustomFields(string resourceId)
{
try
{
return this.ResetRequestRepository.GetCustomFields(resourceId);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Adds or edits your instance of ResetRequest class.
/// </summary>
/// <param name="resetRequest">Your instance of reset requests class to add or edit.</param>
[AcceptVerbs("POST")]
[Route("add-or-edit")]
[Route("~/api/account/reset-request/add-or-edit")]
[Authorize]
public object AddOrEdit([FromBody]Newtonsoft.Json.Linq.JArray form)
{
dynamic resetRequest = form[0].ToObject<ExpandoObject>(JsonHelper.GetJsonSerializer());
List<Frapid.DataAccess.Models.CustomField> customFields = form[1].ToObject<List<Frapid.DataAccess.Models.CustomField>>(JsonHelper.GetJsonSerializer());
if (resetRequest == null)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.MethodNotAllowed));
}
try
{
return this.ResetRequestRepository.AddOrEdit(resetRequest, customFields);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Adds your instance of ResetRequest class.
/// </summary>
/// <param name="resetRequest">Your instance of reset requests class to add.</param>
[AcceptVerbs("POST")]
[Route("add/{resetRequest}")]
[Route("~/api/account/reset-request/add/{resetRequest}")]
[Authorize]
public void Add(Frapid.Account.Entities.ResetRequest resetRequest)
{
if (resetRequest == null)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.MethodNotAllowed));
}
try
{
this.ResetRequestRepository.Add(resetRequest);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Edits existing record with your instance of ResetRequest class.
/// </summary>
/// <param name="resetRequest">Your instance of ResetRequest class to edit.</param>
/// <param name="requestId">Enter the value for RequestId in order to find and edit the existing record.</param>
[AcceptVerbs("PUT")]
[Route("edit/{requestId}")]
[Route("~/api/account/reset-request/edit/{requestId}")]
[Authorize]
public void Edit(System.Guid requestId, [FromBody] Frapid.Account.Entities.ResetRequest resetRequest)
{
if (resetRequest == null)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.MethodNotAllowed));
}
try
{
this.ResetRequestRepository.Update(resetRequest, requestId);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
private List<ExpandoObject> ParseCollection(JArray collection)
{
return JsonConvert.DeserializeObject<List<ExpandoObject>>(collection.ToString(), JsonHelper.GetJsonSerializerSettings());
}
/// <summary>
/// Adds or edits multiple instances of ResetRequest class.
/// </summary>
/// <param name="collection">Your collection of ResetRequest class to bulk import.</param>
/// <returns>Returns list of imported requestIds.</returns>
/// <exception cref="DataAccessException">Thrown when your any ResetRequest class in the collection is invalid or malformed.</exception>
[AcceptVerbs("POST")]
[Route("bulk-import")]
[Route("~/api/account/reset-request/bulk-import")]
[Authorize]
public List<object> BulkImport([FromBody]JArray collection)
{
List<ExpandoObject> resetRequestCollection = this.ParseCollection(collection);
if (resetRequestCollection == null || resetRequestCollection.Count.Equals(0))
{
return null;
}
try
{
return this.ResetRequestRepository.BulkImport(resetRequestCollection);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Deletes an existing instance of ResetRequest class via RequestId.
/// </summary>
/// <param name="requestId">Enter the value for RequestId in order to find and delete the existing record.</param>
[AcceptVerbs("DELETE")]
[Route("delete/{requestId}")]
[Route("~/api/account/reset-request/delete/{requestId}")]
[Authorize]
public void Delete(System.Guid requestId)
{
try
{
this.ResetRequestRepository.Delete(requestId);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
}
}
| |
// 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.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void MaxInt16()
{
var test = new SimpleBinaryOpTest__MaxInt16();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (Avx.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (Avx.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (Avx.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (Avx.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (Avx.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleBinaryOpTest__MaxInt16
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle inHandle2;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Int16[] inArray1, Int16[] inArray2, Int16[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int16>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int16>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int16>();
if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Int16, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int16, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector256<Int16> _fld1;
public Vector256<Int16> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref testStruct._fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref testStruct._fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>());
return testStruct;
}
public void RunStructFldScenario(SimpleBinaryOpTest__MaxInt16 testClass)
{
var result = Avx2.Max(_fld1, _fld2);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleBinaryOpTest__MaxInt16 testClass)
{
fixed (Vector256<Int16>* pFld1 = &_fld1)
fixed (Vector256<Int16>* pFld2 = &_fld2)
{
var result = Avx2.Max(
Avx.LoadVector256((Int16*)(pFld1)),
Avx.LoadVector256((Int16*)(pFld2))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 32;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Int16>>() / sizeof(Int16);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<Int16>>() / sizeof(Int16);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<Int16>>() / sizeof(Int16);
private static Int16[] _data1 = new Int16[Op1ElementCount];
private static Int16[] _data2 = new Int16[Op2ElementCount];
private static Vector256<Int16> _clsVar1;
private static Vector256<Int16> _clsVar2;
private Vector256<Int16> _fld1;
private Vector256<Int16> _fld2;
private DataTable _dataTable;
static SimpleBinaryOpTest__MaxInt16()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _clsVar1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _clsVar2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>());
}
public SimpleBinaryOpTest__MaxInt16()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); }
_dataTable = new DataTable(_data1, _data2, new Int16[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Avx2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Avx2.Max(
Unsafe.Read<Vector256<Int16>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Int16>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Avx2.Max(
Avx.LoadVector256((Int16*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((Int16*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Avx2.Max(
Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Avx2).GetMethod(nameof(Avx2.Max), new Type[] { typeof(Vector256<Int16>), typeof(Vector256<Int16>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<Int16>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Int16>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Avx2).GetMethod(nameof(Avx2.Max), new Type[] { typeof(Vector256<Int16>), typeof(Vector256<Int16>) })
.Invoke(null, new object[] {
Avx.LoadVector256((Int16*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((Int16*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Avx2).GetMethod(nameof(Avx2.Max), new Type[] { typeof(Vector256<Int16>), typeof(Vector256<Int16>) })
.Invoke(null, new object[] {
Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Avx2.Max(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector256<Int16>* pClsVar1 = &_clsVar1)
fixed (Vector256<Int16>* pClsVar2 = &_clsVar2)
{
var result = Avx2.Max(
Avx.LoadVector256((Int16*)(pClsVar1)),
Avx.LoadVector256((Int16*)(pClsVar2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector256<Int16>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector256<Int16>>(_dataTable.inArray2Ptr);
var result = Avx2.Max(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = Avx.LoadVector256((Int16*)(_dataTable.inArray1Ptr));
var op2 = Avx.LoadVector256((Int16*)(_dataTable.inArray2Ptr));
var result = Avx2.Max(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var op1 = Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray1Ptr));
var op2 = Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray2Ptr));
var result = Avx2.Max(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleBinaryOpTest__MaxInt16();
var result = Avx2.Max(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new SimpleBinaryOpTest__MaxInt16();
fixed (Vector256<Int16>* pFld1 = &test._fld1)
fixed (Vector256<Int16>* pFld2 = &test._fld2)
{
var result = Avx2.Max(
Avx.LoadVector256((Int16*)(pFld1)),
Avx.LoadVector256((Int16*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Avx2.Max(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector256<Int16>* pFld1 = &_fld1)
fixed (Vector256<Int16>* pFld2 = &_fld2)
{
var result = Avx2.Max(
Avx.LoadVector256((Int16*)(pFld1)),
Avx.LoadVector256((Int16*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Avx2.Max(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = Avx2.Max(
Avx.LoadVector256((Int16*)(&test._fld1)),
Avx.LoadVector256((Int16*)(&test._fld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector256<Int16> op1, Vector256<Int16> op2, void* result, [CallerMemberName] string method = "")
{
Int16[] inArray1 = new Int16[Op1ElementCount];
Int16[] inArray2 = new Int16[Op2ElementCount];
Int16[] outArray = new Int16[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), op2);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Int16>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "")
{
Int16[] inArray1 = new Int16[Op1ElementCount];
Int16[] inArray2 = new Int16[Op2ElementCount];
Int16[] outArray = new Int16[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector256<Int16>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector256<Int16>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Int16>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Int16[] left, Int16[] right, Int16[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (result[0] != Math.Max(left[0], right[0]))
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (result[i] != Math.Max(left[i], right[i]))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Avx2)}.{nameof(Avx2.Max)}<Int16>(Vector256<Int16>, Vector256<Int16>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace System.Collections.Concurrent.Tests
{
public class ConcurrentDictionaryTests
{
[Fact]
public static void TestBasicScenarios()
{
ConcurrentDictionary<int, int> cd = new ConcurrentDictionary<int, int>();
Task[] tks = new Task[2];
tks[0] = Task.Run(() =>
{
var ret = cd.TryAdd(1, 11);
if (!ret)
{
ret = cd.TryUpdate(1, 11, 111);
Assert.True(ret);
}
ret = cd.TryAdd(2, 22);
if (!ret)
{
ret = cd.TryUpdate(2, 22, 222);
Assert.True(ret);
}
});
tks[1] = Task.Run(() =>
{
var ret = cd.TryAdd(2, 222);
if (!ret)
{
ret = cd.TryUpdate(2, 222, 22);
Assert.True(ret);
}
ret = cd.TryAdd(1, 111);
if (!ret)
{
ret = cd.TryUpdate(1, 111, 11);
Assert.True(ret);
}
});
Task.WaitAll(tks);
}
[Fact]
public static void TestAdd1()
{
TestAdd1(1, 1, 1, 10000);
TestAdd1(5, 1, 1, 10000);
TestAdd1(1, 1, 2, 5000);
TestAdd1(1, 1, 5, 2000);
TestAdd1(4, 0, 4, 2000);
TestAdd1(16, 31, 4, 2000);
TestAdd1(64, 5, 5, 5000);
TestAdd1(5, 5, 5, 2500);
}
private static void TestAdd1(int cLevel, int initSize, int threads, int addsPerThread)
{
ConcurrentDictionary<int, int> dictConcurrent = new ConcurrentDictionary<int, int>(cLevel, 1);
IDictionary<int, int> dict = dictConcurrent;
int count = threads;
using (ManualResetEvent mre = new ManualResetEvent(false))
{
for (int i = 0; i < threads; i++)
{
int ii = i;
Task.Run(
() =>
{
for (int j = 0; j < addsPerThread; j++)
{
dict.Add(j + ii * addsPerThread, -(j + ii * addsPerThread));
}
if (Interlocked.Decrement(ref count) == 0) mre.Set();
});
}
mre.WaitOne();
}
foreach (var pair in dict)
{
Assert.Equal(pair.Key, -pair.Value);
}
List<int> gotKeys = new List<int>();
foreach (var pair in dict)
gotKeys.Add(pair.Key);
gotKeys.Sort();
List<int> expectKeys = new List<int>();
int itemCount = threads * addsPerThread;
for (int i = 0; i < itemCount; i++)
expectKeys.Add(i);
Assert.Equal(expectKeys.Count, gotKeys.Count);
for (int i = 0; i < expectKeys.Count; i++)
{
Assert.True(expectKeys[i].Equals(gotKeys[i]),
String.Format("The set of keys in the dictionary is are not the same as the expected" + Environment.NewLine +
"TestAdd1(cLevel={0}, initSize={1}, threads={2}, addsPerThread={3})", cLevel, initSize, threads, addsPerThread)
);
}
// Finally, let's verify that the count is reported correctly.
int expectedCount = threads * addsPerThread;
Assert.Equal(expectedCount, dict.Count);
Assert.Equal(expectedCount, dictConcurrent.ToArray().Length);
}
[Fact]
public static void TestUpdate1()
{
TestUpdate1(1, 1, 10000);
TestUpdate1(5, 1, 10000);
TestUpdate1(1, 2, 5000);
TestUpdate1(1, 5, 2001);
TestUpdate1(4, 4, 2001);
TestUpdate1(15, 5, 2001);
TestUpdate1(64, 5, 5000);
TestUpdate1(5, 5, 25000);
}
private static void TestUpdate1(int cLevel, int threads, int updatesPerThread)
{
IDictionary<int, int> dict = new ConcurrentDictionary<int, int>(cLevel, 1);
for (int i = 1; i <= updatesPerThread; i++) dict[i] = i;
int running = threads;
using (ManualResetEvent mre = new ManualResetEvent(false))
{
for (int i = 0; i < threads; i++)
{
int ii = i;
Task.Run(
() =>
{
for (int j = 1; j <= updatesPerThread; j++)
{
dict[j] = (ii + 2) * j;
}
if (Interlocked.Decrement(ref running) == 0) mre.Set();
});
}
mre.WaitOne();
}
foreach (var pair in dict)
{
var div = pair.Value / pair.Key;
var rem = pair.Value % pair.Key;
Assert.Equal(0, rem);
Assert.True(div > 1 && div <= threads + 1,
String.Format("* Invalid value={3}! TestUpdate1(cLevel={0}, threads={1}, updatesPerThread={2})", cLevel, threads, updatesPerThread, div));
}
List<int> gotKeys = new List<int>();
foreach (var pair in dict)
gotKeys.Add(pair.Key);
gotKeys.Sort();
List<int> expectKeys = new List<int>();
for (int i = 1; i <= updatesPerThread; i++)
expectKeys.Add(i);
Assert.Equal(expectKeys.Count, gotKeys.Count);
for (int i = 0; i < expectKeys.Count; i++)
{
Assert.True(expectKeys[i].Equals(gotKeys[i]),
String.Format("The set of keys in the dictionary is are not the same as the expected." + Environment.NewLine +
"TestUpdate1(cLevel={0}, threads={1}, updatesPerThread={2})", cLevel, threads, updatesPerThread)
);
}
}
[Fact]
public static void TestRead1()
{
TestRead1(1, 1, 10000);
TestRead1(5, 1, 10000);
TestRead1(1, 2, 5000);
TestRead1(1, 5, 2001);
TestRead1(4, 4, 2001);
TestRead1(15, 5, 2001);
TestRead1(64, 5, 5000);
TestRead1(5, 5, 25000);
}
private static void TestRead1(int cLevel, int threads, int readsPerThread)
{
IDictionary<int, int> dict = new ConcurrentDictionary<int, int>(cLevel, 1);
for (int i = 0; i < readsPerThread; i += 2) dict[i] = i;
int count = threads;
using (ManualResetEvent mre = new ManualResetEvent(false))
{
for (int i = 0; i < threads; i++)
{
int ii = i;
Task.Run(
() =>
{
for (int j = 0; j < readsPerThread; j++)
{
int val = 0;
if (dict.TryGetValue(j, out val))
{
Assert.Equal(0, j % 2);
Assert.Equal(j, val);
}
else
{
Assert.Equal(1, j % 2);
}
}
if (Interlocked.Decrement(ref count) == 0) mre.Set();
});
}
mre.WaitOne();
}
}
[Fact]
public static void TestRemove1()
{
TestRemove1(1, 1, 10000);
TestRemove1(5, 1, 1000);
TestRemove1(1, 5, 2001);
TestRemove1(4, 4, 2001);
TestRemove1(15, 5, 2001);
TestRemove1(64, 5, 5000);
}
private static void TestRemove1(int cLevel, int threads, int removesPerThread)
{
ConcurrentDictionary<int, int> dict = new ConcurrentDictionary<int, int>(cLevel, 1);
string methodparameters = string.Format("* TestRemove1(cLevel={0}, threads={1}, removesPerThread={2})", cLevel, threads, removesPerThread);
int N = 2 * threads * removesPerThread;
for (int i = 0; i < N; i++) dict[i] = -i;
// The dictionary contains keys [0..N), each key mapped to a value equal to the key.
// Threads will cooperatively remove all even keys
int running = threads;
using (ManualResetEvent mre = new ManualResetEvent(false))
{
for (int i = 0; i < threads; i++)
{
int ii = i;
Task.Run(
() =>
{
for (int j = 0; j < removesPerThread; j++)
{
int value;
int key = 2 * (ii + j * threads);
Assert.True(dict.TryRemove(key, out value), "Failed to remove an element! " + methodparameters);
Assert.Equal(-key, value);
}
if (Interlocked.Decrement(ref running) == 0) mre.Set();
});
}
mre.WaitOne();
}
foreach (var pair in dict)
{
Assert.Equal(pair.Key, -pair.Value);
}
List<int> gotKeys = new List<int>();
foreach (var pair in dict)
gotKeys.Add(pair.Key);
gotKeys.Sort();
List<int> expectKeys = new List<int>();
for (int i = 0; i < (threads * removesPerThread); i++)
expectKeys.Add(2 * i + 1);
Assert.Equal(expectKeys.Count, gotKeys.Count);
for (int i = 0; i < expectKeys.Count; i++)
{
Assert.True(expectKeys[i].Equals(gotKeys[i]), " > Unexpected key value! " + methodparameters);
}
// Finally, let's verify that the count is reported correctly.
Assert.Equal(expectKeys.Count, dict.Count);
Assert.Equal(expectKeys.Count, dict.ToArray().Length);
}
[Fact]
public static void TestRemove2()
{
TestRemove2(1);
TestRemove2(10);
TestRemove2(5000);
}
private static void TestRemove2(int removesPerThread)
{
ConcurrentDictionary<int, int> dict = new ConcurrentDictionary<int, int>();
for (int i = 0; i < removesPerThread; i++) dict[i] = -i;
// The dictionary contains keys [0..N), each key mapped to a value equal to the key.
// Threads will cooperatively remove all even keys.
const int SIZE = 2;
int running = SIZE;
bool[][] seen = new bool[SIZE][];
for (int i = 0; i < SIZE; i++) seen[i] = new bool[removesPerThread];
using (ManualResetEvent mre = new ManualResetEvent(false))
{
for (int t = 0; t < SIZE; t++)
{
int thread = t;
Task.Run(
() =>
{
for (int key = 0; key < removesPerThread; key++)
{
int value;
if (dict.TryRemove(key, out value))
{
seen[thread][key] = true;
Assert.Equal(-key, value);
}
}
if (Interlocked.Decrement(ref running) == 0) mre.Set();
});
}
mre.WaitOne();
}
Assert.Equal(0, dict.Count);
for (int i = 0; i < removesPerThread; i++)
{
Assert.False(seen[0][i] == seen[1][i],
String.Format("> FAILED. Two threads appear to have removed the same element. TestRemove2(removesPerThread={0})", removesPerThread)
);
}
}
[Fact]
public static void TestRemove3()
{
ConcurrentDictionary<int, int> dict = new ConcurrentDictionary<int, int>();
dict[99] = -99;
ICollection<KeyValuePair<int, int>> col = dict;
// Make sure we cannot "remove" a key/value pair which is not in the dictionary
for (int i = 0; i < 200; i++)
{
if (i != 99)
{
Assert.False(col.Remove(new KeyValuePair<int, int>(i, -99)), "Should not remove not existing a key/value pair - new KeyValuePair<int, int>(i, -99)");
Assert.False(col.Remove(new KeyValuePair<int, int>(99, -i)), "Should not remove not existing a key/value pair - new KeyValuePair<int, int>(99, -i)");
}
}
// Can we remove a key/value pair successfully?
Assert.True(col.Remove(new KeyValuePair<int, int>(99, -99)), "Failed to remove existing key/value pair");
// Make sure the key/value pair is gone
Assert.False(col.Remove(new KeyValuePair<int, int>(99, -99)), "Should not remove the key/value pair which has been removed");
// And that the dictionary is empty. We will check the count in a few different ways:
Assert.Equal(0, dict.Count);
Assert.Equal(0, dict.ToArray().Length);
}
[Fact]
public static void TestGetOrAdd()
{
TestGetOrAddOrUpdate(1, 1, 1, 10000, true);
TestGetOrAddOrUpdate(5, 1, 1, 10000, true);
TestGetOrAddOrUpdate(1, 1, 2, 5000, true);
TestGetOrAddOrUpdate(1, 1, 5, 2000, true);
TestGetOrAddOrUpdate(4, 0, 4, 2000, true);
TestGetOrAddOrUpdate(16, 31, 4, 2000, true);
TestGetOrAddOrUpdate(64, 5, 5, 5000, true);
TestGetOrAddOrUpdate(5, 5, 5, 25000, true);
}
[Fact]
public static void TestAddOrUpdate()
{
TestGetOrAddOrUpdate(1, 1, 1, 10000, false);
TestGetOrAddOrUpdate(5, 1, 1, 10000, false);
TestGetOrAddOrUpdate(1, 1, 2, 5000, false);
TestGetOrAddOrUpdate(1, 1, 5, 2000, false);
TestGetOrAddOrUpdate(4, 0, 4, 2000, false);
TestGetOrAddOrUpdate(16, 31, 4, 2000, false);
TestGetOrAddOrUpdate(64, 5, 5, 5000, false);
TestGetOrAddOrUpdate(5, 5, 5, 25000, false);
}
private static void TestGetOrAddOrUpdate(int cLevel, int initSize, int threads, int addsPerThread, bool isAdd)
{
ConcurrentDictionary<int, int> dict = new ConcurrentDictionary<int, int>(cLevel, 1);
int count = threads;
using (ManualResetEvent mre = new ManualResetEvent(false))
{
for (int i = 0; i < threads; i++)
{
int ii = i;
Task.Run(
() =>
{
for (int j = 0; j < addsPerThread; j++)
{
if (isAdd)
{
//call one of the overloads of GetOrAdd
switch (j % 3)
{
case 0:
dict.GetOrAdd(j, -j);
break;
case 1:
dict.GetOrAdd(j, x => -x);
break;
case 2:
dict.GetOrAdd(j, (x,m) => x * m, -1);
break;
}
}
else
{
switch (j % 3)
{
case 0:
dict.AddOrUpdate(j, -j, (k, v) => -j);
break;
case 1:
dict.AddOrUpdate(j, (k) => -k, (k, v) => -k);
break;
case 2:
dict.AddOrUpdate(j, (k,m) => k*m, (k, v, m) => k * m, -1);
break;
}
}
}
if (Interlocked.Decrement(ref count) == 0) mre.Set();
});
}
mre.WaitOne();
}
foreach (var pair in dict)
{
Assert.Equal(pair.Key, -pair.Value);
}
List<int> gotKeys = new List<int>();
foreach (var pair in dict)
gotKeys.Add(pair.Key);
gotKeys.Sort();
List<int> expectKeys = new List<int>();
for (int i = 0; i < addsPerThread; i++)
expectKeys.Add(i);
Assert.Equal(expectKeys.Count, gotKeys.Count);
for (int i = 0; i < expectKeys.Count; i++)
{
Assert.True(expectKeys[i].Equals(gotKeys[i]),
String.Format("* Test '{4}': Level={0}, initSize={1}, threads={2}, addsPerThread={3})" + Environment.NewLine +
"> FAILED. The set of keys in the dictionary is are not the same as the expected.",
cLevel, initSize, threads, addsPerThread, isAdd ? "GetOrAdd" : "GetOrUpdate"));
}
// Finally, let's verify that the count is reported correctly.
Assert.Equal(addsPerThread, dict.Count);
Assert.Equal(addsPerThread, dict.ToArray().Length);
}
[Fact]
public static void TestBugFix669376()
{
var cd = new ConcurrentDictionary<string, int>(new OrdinalStringComparer());
cd["test"] = 10;
Assert.True(cd.ContainsKey("TEST"), "Customized comparer didn't work");
}
private class OrdinalStringComparer : IEqualityComparer<string>
{
public bool Equals(string x, string y)
{
var xlower = x.ToLowerInvariant();
var ylower = y.ToLowerInvariant();
return string.CompareOrdinal(xlower, ylower) == 0;
}
public int GetHashCode(string obj)
{
return 0;
}
}
[Fact]
public static void TestConstructor()
{
var dictionary = new ConcurrentDictionary<int, int>(new[] { new KeyValuePair<int, int>(1, 1) });
Assert.False(dictionary.IsEmpty);
Assert.Equal(1, dictionary.Keys.Count);
Assert.Equal(1, dictionary.Values.Count);
}
[Fact]
public static void TestDebuggerAttributes()
{
DebuggerAttributes.ValidateDebuggerDisplayReferences(new ConcurrentDictionary<string, int>());
DebuggerAttributes.ValidateDebuggerTypeProxyProperties(new ConcurrentDictionary<string, int>());
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, ".NET Framework hasn't received the fix for https://github.com/dotnet/corefx/issues/18432 yet.")]
public static void TestNullComparer()
{
AssertDefaultComparerBehavior(new ConcurrentDictionary<EqualityApiSpy, int>((IEqualityComparer<EqualityApiSpy>)null));
AssertDefaultComparerBehavior(new ConcurrentDictionary<EqualityApiSpy, int>(new[] { new KeyValuePair<EqualityApiSpy, int>(new EqualityApiSpy(), 1) }, null));
AssertDefaultComparerBehavior(new ConcurrentDictionary<EqualityApiSpy, int>(1, new[] { new KeyValuePair<EqualityApiSpy, int>(new EqualityApiSpy(), 1) }, null));
AssertDefaultComparerBehavior(new ConcurrentDictionary<EqualityApiSpy, int>(1, 1, null));
void AssertDefaultComparerBehavior(ConcurrentDictionary<EqualityApiSpy, int> dictionary)
{
var spyKey = new EqualityApiSpy();
Assert.True(dictionary.TryAdd(spyKey, 1));
Assert.False(dictionary.TryAdd(spyKey, 1));
Assert.False(spyKey.ObjectApiUsed);
Assert.True(spyKey.IEquatableApiUsed);
}
}
private sealed class EqualityApiSpy : IEquatable<EqualityApiSpy>
{
public bool ObjectApiUsed { get; private set; }
public bool IEquatableApiUsed { get; private set; }
public override bool Equals(object obj)
{
ObjectApiUsed = true;
return ReferenceEquals(this, obj);
}
public override int GetHashCode() => base.GetHashCode();
public bool Equals(EqualityApiSpy other)
{
IEquatableApiUsed = true;
return ReferenceEquals(this, other);
}
}
[Fact]
[SkipOnTargetFramework(~TargetFrameworkMonikers.NetFramework, ".NET Framework hasn't received the fix for https://github.com/dotnet/corefx/issues/18432 yet.")]
public static void TestNullComparer_netfx()
{
Assert.Throws<ArgumentNullException>(
() => new ConcurrentDictionary<int, int>((IEqualityComparer<int>)null));
// "TestConstructor: FAILED. Constructor didn't throw ANE when null IEqualityComparer is passed");
Assert.Throws<ArgumentNullException>(
() => new ConcurrentDictionary<int, int>(new[] { new KeyValuePair<int, int>(1, 1) }, null));
// "TestConstructor: FAILED. Constructor didn't throw ANE when non null collection and null IEqualityComparer passed");
Assert.Throws<ArgumentNullException>(
() => new ConcurrentDictionary<int, int>(1, new[] { new KeyValuePair<int, int>(1, 1) }, null));
// "TestConstructor: FAILED. Constructor didn't throw ANE when null comparer is passed");
Assert.Throws<ArgumentNullException>(
() => new ConcurrentDictionary<int, int>(1, 1, null));
// "TestConstructor: FAILED. Constructor didn't throw ANE when null comparer is passed");
}
[Fact]
public static void TestConstructor_Negative()
{
Assert.Throws<ArgumentNullException>(
() => new ConcurrentDictionary<int, int>((ICollection<KeyValuePair<int, int>>)null));
// "TestConstructor: FAILED. Constructor didn't throw ANE when null collection is passed");
Assert.Throws<ArgumentNullException>(
() => new ConcurrentDictionary<int, int>((ICollection<KeyValuePair<int, int>>)null, EqualityComparer<int>.Default));
// "TestConstructor: FAILED. Constructor didn't throw ANE when null collection and non null IEqualityComparer passed");
Assert.Throws<ArgumentNullException>(
() => new ConcurrentDictionary<string, int>(new[] { new KeyValuePair<string, int>(null, 1) }));
// "TestConstructor: FAILED. Constructor didn't throw ANE when collection has null key passed");
Assert.Throws<ArgumentException>(
() => new ConcurrentDictionary<int, int>(new[] { new KeyValuePair<int, int>(1, 1), new KeyValuePair<int, int>(1, 2) }));
// "TestConstructor: FAILED. Constructor didn't throw AE when collection has duplicate keys passed");
Assert.Throws<ArgumentNullException>(
() => new ConcurrentDictionary<int, int>(1, null, EqualityComparer<int>.Default));
// "TestConstructor: FAILED. Constructor didn't throw ANE when null collection is passed");
Assert.Throws<ArgumentOutOfRangeException>(
() => new ConcurrentDictionary<int, int>(0, 10));
// "TestConstructor: FAILED. Constructor didn't throw AORE when <1 concurrencyLevel passed");
Assert.Throws<ArgumentOutOfRangeException>(
() => new ConcurrentDictionary<int, int>(-1, 0));
// "TestConstructor: FAILED. Constructor didn't throw AORE when < 0 capacity passed");
}
[Fact]
public static void TestExceptions()
{
var dictionary = new ConcurrentDictionary<string, int>();
Assert.Throws<ArgumentNullException>(
() => dictionary.TryAdd(null, 0));
// "TestExceptions: FAILED. TryAdd didn't throw ANE when null key is passed");
Assert.Throws<ArgumentNullException>(
() => dictionary.ContainsKey(null));
// "TestExceptions: FAILED. Contains didn't throw ANE when null key is passed");
int item;
Assert.Throws<ArgumentNullException>(
() => dictionary.TryRemove(null, out item));
// "TestExceptions: FAILED. TryRemove didn't throw ANE when null key is passed");
Assert.Throws<ArgumentNullException>(
() => dictionary.TryGetValue(null, out item));
// "TestExceptions: FAILED. TryGetValue didn't throw ANE when null key is passed");
Assert.Throws<ArgumentNullException>(
() => { var x = dictionary[null]; });
// "TestExceptions: FAILED. this[] didn't throw ANE when null key is passed");
Assert.Throws<KeyNotFoundException>(
() => { var x = dictionary["1"]; });
// "TestExceptions: FAILED. this[] TryGetValue didn't throw KeyNotFoundException!");
Assert.Throws<ArgumentNullException>(
() => dictionary[null] = 1);
// "TestExceptions: FAILED. this[] didn't throw ANE when null key is passed");
Assert.Throws<ArgumentNullException>(
() => dictionary.GetOrAdd(null, (k,m) => 0, 0));
// "TestExceptions: FAILED. GetOrAdd didn't throw ANE when null key is passed");
Assert.Throws<ArgumentNullException>(
() => dictionary.GetOrAdd("1", null, 0));
// "TestExceptions: FAILED. GetOrAdd didn't throw ANE when null valueFactory is passed");
Assert.Throws<ArgumentNullException>(
() => dictionary.GetOrAdd(null, (k) => 0));
// "TestExceptions: FAILED. GetOrAdd didn't throw ANE when null key is passed");
Assert.Throws<ArgumentNullException>(
() => dictionary.GetOrAdd("1", null));
// "TestExceptions: FAILED. GetOrAdd didn't throw ANE when null valueFactory is passed");
Assert.Throws<ArgumentNullException>(
() => dictionary.GetOrAdd(null, 0));
// "TestExceptions: FAILED. GetOrAdd didn't throw ANE when null key is passed");
Assert.Throws<ArgumentNullException>(
() => dictionary.AddOrUpdate(null, (k, m) => 0, (k, v, m) => 0, 42));
// "TestExceptions: FAILED. AddOrUpdate didn't throw ANE when null key is passed");
Assert.Throws<ArgumentNullException>(
() => dictionary.AddOrUpdate("1", (k, m) => 0, null, 42));
// "TestExceptions: FAILED. AddOrUpdate didn't throw ANE when null updateFactory is passed");
Assert.Throws<ArgumentNullException>(
() => dictionary.AddOrUpdate("1", null, (k, v, m) => 0, 42));
// "TestExceptions: FAILED. AddOrUpdate didn't throw ANE when null addFactory is passed");
Assert.Throws<ArgumentNullException>(
() => dictionary.AddOrUpdate(null, (k) => 0, (k, v) => 0));
// "TestExceptions: FAILED. AddOrUpdate didn't throw ANE when null key is passed");
Assert.Throws<ArgumentNullException>(
() => dictionary.AddOrUpdate("1", null, (k, v) => 0));
// "TestExceptions: FAILED. AddOrUpdate didn't throw ANE when null updateFactory is passed");
Assert.Throws<ArgumentNullException>(
() => dictionary.AddOrUpdate(null, (k) => 0, null));
// "TestExceptions: FAILED. AddOrUpdate didn't throw ANE when null addFactory is passed");
dictionary.TryAdd("1", 1);
Assert.Throws<ArgumentException>(
() => ((IDictionary<string, int>)dictionary).Add("1", 2));
// "TestExceptions: FAILED. IDictionary didn't throw AE when duplicate key is passed");
}
[Fact]
public static void TestIDictionary()
{
IDictionary dictionary = new ConcurrentDictionary<string, int>();
Assert.False(dictionary.IsReadOnly);
// Empty dictionary should not enumerate
Assert.Empty(dictionary);
const int SIZE = 10;
for (int i = 0; i < SIZE; i++)
dictionary.Add(i.ToString(), i);
Assert.Equal(SIZE, dictionary.Count);
//test contains
Assert.False(dictionary.Contains(1), "TestIDictionary: FAILED. Contain returned true for incorrect key type");
Assert.False(dictionary.Contains("100"), "TestIDictionary: FAILED. Contain returned true for incorrect key");
Assert.True(dictionary.Contains("1"), "TestIDictionary: FAILED. Contain returned false for correct key");
//test GetEnumerator
int count = 0;
foreach (var obj in dictionary)
{
DictionaryEntry entry = (DictionaryEntry)obj;
string key = (string)entry.Key;
int value = (int)entry.Value;
int expectedValue = int.Parse(key);
Assert.True(value == expectedValue,
String.Format("TestIDictionary: FAILED. Unexpected value returned from GetEnumerator, expected {0}, actual {1}", value, expectedValue));
count++;
}
Assert.Equal(SIZE, count);
Assert.Equal(SIZE, dictionary.Keys.Count);
Assert.Equal(SIZE, dictionary.Values.Count);
//Test Remove
dictionary.Remove("9");
Assert.Equal(SIZE - 1, dictionary.Count);
//Test this[]
for (int i = 0; i < dictionary.Count; i++)
Assert.Equal(i, (int)dictionary[i.ToString()]);
dictionary["1"] = 100; // try a valid setter
Assert.Equal(100, (int)dictionary["1"]);
//non-existing key
Assert.Null(dictionary["NotAKey"]);
}
[Fact]
public static void TestIDictionary_Negative()
{
IDictionary dictionary = new ConcurrentDictionary<string, int>();
Assert.Throws<ArgumentNullException>(
() => dictionary.Add(null, 1));
// "TestIDictionary: FAILED. Add didn't throw ANE when null key is passed");
Assert.Throws<ArgumentException>(
() => dictionary.Add(1, 1));
// "TestIDictionary: FAILED. Add didn't throw AE when incorrect key type is passed");
Assert.Throws<ArgumentException>(
() => dictionary.Add("1", "1"));
// "TestIDictionary: FAILED. Add didn't throw AE when incorrect value type is passed");
Assert.Throws<ArgumentNullException>(
() => dictionary.Contains(null));
// "TestIDictionary: FAILED. Contain didn't throw ANE when null key is passed");
//Test Remove
Assert.Throws<ArgumentNullException>(
() => dictionary.Remove(null));
// "TestIDictionary: FAILED. Remove didn't throw ANE when null key is passed");
//Test this[]
Assert.Throws<ArgumentNullException>(
() => { object val = dictionary[null]; });
// "TestIDictionary: FAILED. this[] getter didn't throw ANE when null key is passed");
Assert.Throws<ArgumentNullException>(
() => dictionary[null] = 0);
// "TestIDictionary: FAILED. this[] setter didn't throw ANE when null key is passed");
Assert.Throws<ArgumentException>(
() => dictionary[1] = 0);
// "TestIDictionary: FAILED. this[] setter didn't throw AE when invalid key type is passed");
Assert.Throws<ArgumentException>(
() => dictionary["1"] = "0");
// "TestIDictionary: FAILED. this[] setter didn't throw AE when invalid value type is passed");
}
[Fact]
public static void IDictionary_Remove_NullKeyInKeyValuePair_ThrowsArgumentNullException()
{
IDictionary<string, int> dictionary = new ConcurrentDictionary<string, int>();
Assert.Throws<ArgumentNullException>(() => dictionary.Remove(new KeyValuePair<string, int>(null, 0)));
}
[Fact]
public static void TestICollection()
{
ICollection dictionary = new ConcurrentDictionary<int, int>();
Assert.False(dictionary.IsSynchronized, "TestICollection: FAILED. IsSynchronized returned true!");
int key = -1;
int value = +1;
//add one item to the dictionary
((ConcurrentDictionary<int, int>)dictionary).TryAdd(key, value);
var objectArray = new Object[1];
dictionary.CopyTo(objectArray, 0);
Assert.Equal(key, ((KeyValuePair<int, int>)objectArray[0]).Key);
Assert.Equal(value, ((KeyValuePair<int, int>)objectArray[0]).Value);
var keyValueArray = new KeyValuePair<int, int>[1];
dictionary.CopyTo(keyValueArray, 0);
Assert.Equal(key, keyValueArray[0].Key);
Assert.Equal(value, keyValueArray[0].Value);
var entryArray = new DictionaryEntry[1];
dictionary.CopyTo(entryArray, 0);
Assert.Equal(key, (int)entryArray[0].Key);
Assert.Equal(value, (int)entryArray[0].Value);
}
[Fact]
public static void TestICollection_Negative()
{
ICollection dictionary = new ConcurrentDictionary<int, int>();
Assert.False(dictionary.IsSynchronized, "TestICollection: FAILED. IsSynchronized returned true!");
Assert.Throws<NotSupportedException>(() => { var obj = dictionary.SyncRoot; });
// "TestICollection: FAILED. SyncRoot property didn't throw");
Assert.Throws<ArgumentNullException>(() => dictionary.CopyTo(null, 0));
// "TestICollection: FAILED. CopyTo didn't throw ANE when null Array is passed");
Assert.Throws<ArgumentOutOfRangeException>(() => dictionary.CopyTo(new object[] { }, -1));
// "TestICollection: FAILED. CopyTo didn't throw AORE when negative index passed");
//add one item to the dictionary
((ConcurrentDictionary<int, int>)dictionary).TryAdd(1, 1);
Assert.Throws<ArgumentException>(() => dictionary.CopyTo(new object[] { }, 0));
// "TestICollection: FAILED. CopyTo didn't throw AE when the Array size is smaller than the dictionary count");
}
[Fact]
public static void TestClear()
{
var dictionary = new ConcurrentDictionary<int, int>();
for (int i = 0; i < 10; i++)
dictionary.TryAdd(i, i);
Assert.Equal(10, dictionary.Count);
dictionary.Clear();
Assert.Equal(0, dictionary.Count);
int item;
Assert.False(dictionary.TryRemove(1, out item), "TestClear: FAILED. TryRemove succeeded after Clear");
Assert.True(dictionary.IsEmpty, "TestClear: FAILED. IsEmpty returned false after Clear");
}
[Fact]
public static void TestTryUpdate()
{
var dictionary = new ConcurrentDictionary<string, int>();
Assert.Throws<ArgumentNullException>(
() => dictionary.TryUpdate(null, 0, 0));
// "TestTryUpdate: FAILED. TryUpdate didn't throw ANE when null key is passed");
for (int i = 0; i < 10; i++)
dictionary.TryAdd(i.ToString(), i);
for (int i = 0; i < 10; i++)
{
Assert.True(dictionary.TryUpdate(i.ToString(), i + 1, i), "TestTryUpdate: FAILED. TryUpdate failed!");
Assert.Equal(i + 1, dictionary[i.ToString()]);
}
//test TryUpdate concurrently
dictionary.Clear();
for (int i = 0; i < 1000; i++)
dictionary.TryAdd(i.ToString(), i);
var mres = new ManualResetEventSlim();
Task[] tasks = new Task[10];
ThreadLocal<ThreadData> updatedKeys = new ThreadLocal<ThreadData>(true);
for (int i = 0; i < tasks.Length; i++)
{
// We are creating the Task using TaskCreationOptions.LongRunning because...
// there is no guarantee that the Task will be created on another thread.
// There is also no guarantee that using this TaskCreationOption will force
// it to be run on another thread.
tasks[i] = Task.Factory.StartNew((obj) =>
{
mres.Wait();
int index = (((int)obj) + 1) + 1000;
updatedKeys.Value = new ThreadData();
updatedKeys.Value.ThreadIndex = index;
for (int j = 0; j < dictionary.Count; j++)
{
if (dictionary.TryUpdate(j.ToString(), index, j))
{
if (dictionary[j.ToString()] != index)
{
updatedKeys.Value.Succeeded = false;
return;
}
updatedKeys.Value.Keys.Add(j.ToString());
}
}
}, i, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default);
}
mres.Set();
Task.WaitAll(tasks);
int numberSucceeded = 0;
int totalKeysUpdated = 0;
foreach (var threadData in updatedKeys.Values)
{
totalKeysUpdated += threadData.Keys.Count;
if (threadData.Succeeded)
numberSucceeded++;
}
Assert.True(numberSucceeded == tasks.Length, "One or more threads failed!");
Assert.True(totalKeysUpdated == dictionary.Count,
String.Format("TestTryUpdate: FAILED. The updated keys count doesn't match the dictionary count, expected {0}, actual {1}", dictionary.Count, totalKeysUpdated));
foreach (var value in updatedKeys.Values)
{
for (int i = 0; i < value.Keys.Count; i++)
Assert.True(dictionary[value.Keys[i]] == value.ThreadIndex,
String.Format("TestTryUpdate: FAILED. The updated value doesn't match the thread index, expected {0} actual {1}", value.ThreadIndex, dictionary[value.Keys[i]]));
}
//test TryUpdate with non atomic values (intPtr > 8)
var dict = new ConcurrentDictionary<int, Struct16>();
dict.TryAdd(1, new Struct16(1, -1));
Assert.True(dict.TryUpdate(1, new Struct16(2, -2), new Struct16(1, -1)), "TestTryUpdate: FAILED. TryUpdate failed for non atomic values ( > 8 bytes)");
}
#region Helper Classes and Methods
private class ThreadData
{
public int ThreadIndex;
public bool Succeeded = true;
public List<string> Keys = new List<string>();
}
private struct Struct16 : IEqualityComparer<Struct16>
{
public long L1, L2;
public Struct16(long l1, long l2)
{
L1 = l1;
L2 = l2;
}
public bool Equals(Struct16 x, Struct16 y)
{
return x.L1 == y.L1 && x.L2 == y.L2;
}
public int GetHashCode(Struct16 obj)
{
return (int)L1;
}
}
#endregion
}
}
| |
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using PrimerProObjects;
using PrimerProLocalization;
using GenLib;
namespace PrimerProForms
{
/// <summary>
/// Summary description for FormSearchOptions.
/// </summary>
public class FormSearchOptions : System.Windows.Forms.Form
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
private System.Windows.Forms.Button btnOK;
private System.Windows.Forms.Button btnCancel;
private System.Windows.Forms.Label labPS;
private System.Windows.Forms.ComboBox cbPS;
private System.Windows.Forms.CheckBox ckRootsOnly;
private System.Windows.Forms.CheckBox ckVwlInRootSame;
private System.Windows.Forms.CheckBox ckVwlSame;
private System.Windows.Forms.Label labWordCV;
private System.Windows.Forms.TextBox tbWordCV;
private System.Windows.Forms.Label labRootCV;
private System.Windows.Forms.TextBox tbRootCV;
private System.Windows.Forms.GroupBox gbWordPosition;
private System.Windows.Forms.RadioButton rbWordAny;
private System.Windows.Forms.RadioButton rbWordInitial;
private System.Windows.Forms.RadioButton rbWordMedial;
private System.Windows.Forms.RadioButton rbWordFinal;
private System.Windows.Forms.GroupBox gbRootPosition;
private System.Windows.Forms.RadioButton rbRootAny;
private System.Windows.Forms.RadioButton rbRootInitial;
private System.Windows.Forms.RadioButton rbRootMedial;
private System.Windows.Forms.RadioButton rbRootFinal;
private CheckBox ckBrowseView;
private bool m_IsRootOnly;
private bool m_IsIdenticalVowelsInWord;
private bool m_IsIdenticalVowelsInRoot;
private bool m_IsBrowseView;
private string m_WordCVShape;
private string m_RootCVShape;
private int m_MinSyllables;
private int m_MaxSyllables;
private SearchOptions.Position m_WordPosition;
private SearchOptions.Position m_RootPosition;
private CodeTableEntry m_PSTE; //PSTable Entry
private CodeTable m_PST; //PSTable
private bool m_MiniForm;
private bool m_Browse;
private NumericUpDown nudMinSyllables;
private Label labMinSyllable;
private Label labMaxSyllables;
private NumericUpDown nudMaxSyllables;
//public enum Position { Any, Initial, Medial, Final };
public FormSearchOptions(CodeTable PST, bool fMiniForm, bool fBrowse)
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
m_PST = PST;
m_MiniForm = fMiniForm;
m_Browse = fBrowse;
InitializeCT();
if (m_MiniForm)
{
this.ckRootsOnly.Enabled = false;
this.rbRootFinal.Enabled = false;
this.rbRootInitial.Enabled = false;
this.rbRootMedial.Enabled = false;
this.rbWordFinal.Enabled = false;
this.rbWordInitial.Enabled = false;
this.rbWordMedial.Enabled = false;
}
if (m_Browse)
{
this.ckBrowseView.Visible = true;
this.ckBrowseView.Checked = false;
}
}
public FormSearchOptions(CodeTable PST, bool fMiniForm, bool fBrowse, LocalizationTable table)
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
m_PST = PST;
m_MiniForm = fMiniForm;
m_Browse = fBrowse;
InitializeCT();
if (m_MiniForm)
{
this.ckRootsOnly.Enabled = false;
this.rbRootFinal.Enabled = false;
this.rbRootInitial.Enabled = false;
this.rbRootMedial.Enabled = false;
this.rbWordFinal.Enabled = false;
this.rbWordInitial.Enabled = false;
this.rbWordMedial.Enabled = false;
}
if (m_Browse)
{
this.ckBrowseView.Visible = true;
this.ckBrowseView.Checked = false;
}
this.UpdateFormForLocalization(table);
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(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()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FormSearchOptions));
this.btnOK = new System.Windows.Forms.Button();
this.btnCancel = new System.Windows.Forms.Button();
this.cbPS = new System.Windows.Forms.ComboBox();
this.labPS = new System.Windows.Forms.Label();
this.ckRootsOnly = new System.Windows.Forms.CheckBox();
this.ckVwlSame = new System.Windows.Forms.CheckBox();
this.ckVwlInRootSame = new System.Windows.Forms.CheckBox();
this.labWordCV = new System.Windows.Forms.Label();
this.tbWordCV = new System.Windows.Forms.TextBox();
this.labRootCV = new System.Windows.Forms.Label();
this.tbRootCV = new System.Windows.Forms.TextBox();
this.gbWordPosition = new System.Windows.Forms.GroupBox();
this.rbWordFinal = new System.Windows.Forms.RadioButton();
this.rbWordMedial = new System.Windows.Forms.RadioButton();
this.rbWordInitial = new System.Windows.Forms.RadioButton();
this.rbWordAny = new System.Windows.Forms.RadioButton();
this.gbRootPosition = new System.Windows.Forms.GroupBox();
this.rbRootFinal = new System.Windows.Forms.RadioButton();
this.rbRootMedial = new System.Windows.Forms.RadioButton();
this.rbRootInitial = new System.Windows.Forms.RadioButton();
this.rbRootAny = new System.Windows.Forms.RadioButton();
this.ckBrowseView = new System.Windows.Forms.CheckBox();
this.nudMinSyllables = new System.Windows.Forms.NumericUpDown();
this.labMinSyllable = new System.Windows.Forms.Label();
this.labMaxSyllables = new System.Windows.Forms.Label();
this.nudMaxSyllables = new System.Windows.Forms.NumericUpDown();
this.gbWordPosition.SuspendLayout();
this.gbRootPosition.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.nudMinSyllables)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.nudMaxSyllables)).BeginInit();
this.SuspendLayout();
//
// btnOK
//
this.btnOK.DialogResult = System.Windows.Forms.DialogResult.OK;
this.btnOK.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.btnOK.Location = new System.Drawing.Point(329, 345);
this.btnOK.Name = "btnOK";
this.btnOK.Size = new System.Drawing.Size(86, 26);
this.btnOK.TabIndex = 16;
this.btnOK.Text = "OK";
this.btnOK.Click += new System.EventHandler(this.btnOK_Click);
//
// btnCancel
//
this.btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.btnCancel.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.btnCancel.Location = new System.Drawing.Point(465, 345);
this.btnCancel.Name = "btnCancel";
this.btnCancel.Size = new System.Drawing.Size(85, 26);
this.btnCancel.TabIndex = 17;
this.btnCancel.Text = "Cancel";
this.btnCancel.Click += new System.EventHandler(this.btnCancel_Click);
//
// cbPS
//
this.cbPS.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cbPS.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.cbPS.Location = new System.Drawing.Point(21, 46);
this.cbPS.Name = "cbPS";
this.cbPS.Size = new System.Drawing.Size(226, 23);
this.cbPS.TabIndex = 1;
//
// labPS
//
this.labPS.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.labPS.Location = new System.Drawing.Point(21, 20);
this.labPS.Name = "labPS";
this.labPS.Size = new System.Drawing.Size(150, 19);
this.labPS.TabIndex = 0;
this.labPS.Text = "Parts of speech:";
//
// ckRootsOnly
//
this.ckRootsOnly.AutoSize = true;
this.ckRootsOnly.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.ckRootsOnly.Location = new System.Drawing.Point(27, 86);
this.ckRootsOnly.Name = "ckRootsOnly";
this.ckRootsOnly.Size = new System.Drawing.Size(83, 19);
this.ckRootsOnly.TabIndex = 2;
this.ckRootsOnly.Text = "&Roots only";
//
// ckVwlSame
//
this.ckVwlSame.AutoSize = true;
this.ckVwlSame.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.ckVwlSame.Location = new System.Drawing.Point(27, 125);
this.ckVwlSame.Name = "ckVwlSame";
this.ckVwlSame.Size = new System.Drawing.Size(149, 19);
this.ckVwlSame.TabIndex = 3;
this.ckVwlSame.Text = "&All vowels are identical";
this.ckVwlSame.CheckedChanged += new System.EventHandler(this.ckVwlSame_CheckedChanged);
//
// ckVwlInRootSame
//
this.ckVwlInRootSame.AutoSize = true;
this.ckVwlInRootSame.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.ckVwlInRootSame.Location = new System.Drawing.Point(27, 152);
this.ckVwlInRootSame.Name = "ckVwlInRootSame";
this.ckVwlInRootSame.Size = new System.Drawing.Size(186, 19);
this.ckVwlInRootSame.TabIndex = 4;
this.ckVwlInRootSame.Text = "All &vowels in root are identical";
this.ckVwlInRootSame.CheckedChanged += new System.EventHandler(this.ckVwlInRootSame_CheckedChanged);
//
// labWordCV
//
this.labWordCV.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.labWordCV.Location = new System.Drawing.Point(27, 198);
this.labWordCV.Name = "labWordCV";
this.labWordCV.Size = new System.Drawing.Size(139, 19);
this.labWordCV.TabIndex = 5;
this.labWordCV.Text = "Word CV Shape";
//
// tbWordCV
//
this.tbWordCV.CharacterCasing = System.Windows.Forms.CharacterCasing.Upper;
this.tbWordCV.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.tbWordCV.Location = new System.Drawing.Point(171, 198);
this.tbWordCV.Name = "tbWordCV";
this.tbWordCV.Size = new System.Drawing.Size(103, 21);
this.tbWordCV.TabIndex = 6;
this.tbWordCV.TextChanged += new System.EventHandler(this.tbWordCV_TextChanged);
//
// labRootCV
//
this.labRootCV.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.labRootCV.Location = new System.Drawing.Point(27, 224);
this.labRootCV.Name = "labRootCV";
this.labRootCV.Size = new System.Drawing.Size(139, 19);
this.labRootCV.TabIndex = 7;
this.labRootCV.Text = "Root CV Shape";
//
// tbRootCV
//
this.tbRootCV.CharacterCasing = System.Windows.Forms.CharacterCasing.Upper;
this.tbRootCV.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.tbRootCV.Location = new System.Drawing.Point(171, 224);
this.tbRootCV.Name = "tbRootCV";
this.tbRootCV.Size = new System.Drawing.Size(103, 21);
this.tbRootCV.TabIndex = 8;
this.tbRootCV.TextChanged += new System.EventHandler(this.tbRootCV_TextChanged);
//
// gbWordPosition
//
this.gbWordPosition.Controls.Add(this.rbWordFinal);
this.gbWordPosition.Controls.Add(this.rbWordMedial);
this.gbWordPosition.Controls.Add(this.rbWordInitial);
this.gbWordPosition.Controls.Add(this.rbWordAny);
this.gbWordPosition.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.gbWordPosition.Location = new System.Drawing.Point(329, 13);
this.gbWordPosition.Name = "gbWordPosition";
this.gbWordPosition.Size = new System.Drawing.Size(221, 132);
this.gbWordPosition.TabIndex = 14;
this.gbWordPosition.TabStop = false;
this.gbWordPosition.Text = "By word position";
//
// rbWordFinal
//
this.rbWordFinal.AutoSize = true;
this.rbWordFinal.Location = new System.Drawing.Point(14, 99);
this.rbWordFinal.Name = "rbWordFinal";
this.rbWordFinal.Size = new System.Drawing.Size(127, 19);
this.rbWordFinal.TabIndex = 4;
this.rbWordFinal.Text = "Word-&final position";
//
// rbWordMedial
//
this.rbWordMedial.AutoSize = true;
this.rbWordMedial.Location = new System.Drawing.Point(14, 74);
this.rbWordMedial.Name = "rbWordMedial";
this.rbWordMedial.Size = new System.Drawing.Size(142, 19);
this.rbWordMedial.TabIndex = 3;
this.rbWordMedial.Text = "Word-&medial position";
//
// rbWordInitial
//
this.rbWordInitial.AutoSize = true;
this.rbWordInitial.Location = new System.Drawing.Point(14, 49);
this.rbWordInitial.Name = "rbWordInitial";
this.rbWordInitial.Size = new System.Drawing.Size(133, 19);
this.rbWordInitial.TabIndex = 1;
this.rbWordInitial.Text = "Word-&initial position";
//
// rbWordAny
//
this.rbWordAny.AutoSize = true;
this.rbWordAny.Checked = true;
this.rbWordAny.Location = new System.Drawing.Point(14, 25);
this.rbWordAny.Name = "rbWordAny";
this.rbWordAny.Size = new System.Drawing.Size(90, 19);
this.rbWordAny.TabIndex = 0;
this.rbWordAny.TabStop = true;
this.rbWordAny.Text = "An&y position";
//
// gbRootPosition
//
this.gbRootPosition.Controls.Add(this.rbRootFinal);
this.gbRootPosition.Controls.Add(this.rbRootMedial);
this.gbRootPosition.Controls.Add(this.rbRootInitial);
this.gbRootPosition.Controls.Add(this.rbRootAny);
this.gbRootPosition.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.gbRootPosition.Location = new System.Drawing.Point(329, 170);
this.gbRootPosition.Name = "gbRootPosition";
this.gbRootPosition.Size = new System.Drawing.Size(221, 131);
this.gbRootPosition.TabIndex = 15;
this.gbRootPosition.TabStop = false;
this.gbRootPosition.Text = "By root position";
//
// rbRootFinal
//
this.rbRootFinal.AutoSize = true;
this.rbRootFinal.Location = new System.Drawing.Point(14, 99);
this.rbRootFinal.Name = "rbRootFinal";
this.rbRootFinal.Size = new System.Drawing.Size(124, 19);
this.rbRootFinal.TabIndex = 4;
this.rbRootFinal.Text = "Root-final positio&n";
//
// rbRootMedial
//
this.rbRootMedial.AutoSize = true;
this.rbRootMedial.Location = new System.Drawing.Point(14, 74);
this.rbRootMedial.Name = "rbRootMedial";
this.rbRootMedial.Size = new System.Drawing.Size(139, 19);
this.rbRootMedial.TabIndex = 3;
this.rbRootMedial.Text = "Root-medial po&sition";
//
// rbRootInitial
//
this.rbRootInitial.AutoSize = true;
this.rbRootInitial.Location = new System.Drawing.Point(14, 49);
this.rbRootInitial.Name = "rbRootInitial";
this.rbRootInitial.Size = new System.Drawing.Size(130, 19);
this.rbRootInitial.TabIndex = 1;
this.rbRootInitial.Text = "Root-initial &position";
//
// rbRootAny
//
this.rbRootAny.AutoSize = true;
this.rbRootAny.Checked = true;
this.rbRootAny.Location = new System.Drawing.Point(14, 25);
this.rbRootAny.Name = "rbRootAny";
this.rbRootAny.Size = new System.Drawing.Size(90, 19);
this.rbRootAny.TabIndex = 0;
this.rbRootAny.TabStop = true;
this.rbRootAny.Text = "Any p&osition";
//
// ckBrowseView
//
this.ckBrowseView.AutoSize = true;
this.ckBrowseView.Location = new System.Drawing.Point(30, 345);
this.ckBrowseView.Name = "ckBrowseView";
this.ckBrowseView.Size = new System.Drawing.Size(152, 19);
this.ckBrowseView.TabIndex = 13;
this.ckBrowseView.Text = "Display in Browse View";
this.ckBrowseView.UseVisualStyleBackColor = true;
this.ckBrowseView.Visible = false;
//
// nudMinSyllables
//
this.nudMinSyllables.Location = new System.Drawing.Point(236, 272);
this.nudMinSyllables.Maximum = new decimal(new int[] {
9,
0,
0,
0});
this.nudMinSyllables.Name = "nudMinSyllables";
this.nudMinSyllables.Size = new System.Drawing.Size(32, 21);
this.nudMinSyllables.TabIndex = 10;
this.nudMinSyllables.ValueChanged += new System.EventHandler(this.nudMinSyllables_ValueChanged);
//
// labMinSyllable
//
this.labMinSyllable.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.labMinSyllable.Location = new System.Drawing.Point(27, 272);
this.labMinSyllable.Name = "labMinSyllable";
this.labMinSyllable.Size = new System.Drawing.Size(203, 19);
this.labMinSyllable.TabIndex = 9;
this.labMinSyllable.Text = "Minimal Number of Syllables";
//
// labMaxSyllables
//
this.labMaxSyllables.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.labMaxSyllables.Location = new System.Drawing.Point(27, 300);
this.labMaxSyllables.Name = "labMaxSyllables";
this.labMaxSyllables.Size = new System.Drawing.Size(203, 19);
this.labMaxSyllables.TabIndex = 11;
this.labMaxSyllables.Text = "Maximal Number of Syllables";
//
// nudMaxSyllables
//
this.nudMaxSyllables.Location = new System.Drawing.Point(236, 300);
this.nudMaxSyllables.Maximum = new decimal(new int[] {
9,
0,
0,
0});
this.nudMaxSyllables.Name = "nudMaxSyllables";
this.nudMaxSyllables.Size = new System.Drawing.Size(32, 21);
this.nudMaxSyllables.TabIndex = 12;
this.nudMaxSyllables.ValueChanged += new System.EventHandler(this.nudMaxSyllables_ValueChanged);
//
// FormSearchOptions
//
this.AcceptButton = this.btnOK;
this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);
this.CancelButton = this.btnCancel;
this.ClientSize = new System.Drawing.Size(654, 437);
this.Controls.Add(this.labMaxSyllables);
this.Controls.Add(this.nudMaxSyllables);
this.Controls.Add(this.labMinSyllable);
this.Controls.Add(this.nudMinSyllables);
this.Controls.Add(this.ckBrowseView);
this.Controls.Add(this.gbWordPosition);
this.Controls.Add(this.tbRootCV);
this.Controls.Add(this.tbWordCV);
this.Controls.Add(this.labRootCV);
this.Controls.Add(this.labWordCV);
this.Controls.Add(this.labPS);
this.Controls.Add(this.cbPS);
this.Controls.Add(this.ckVwlSame);
this.Controls.Add(this.ckVwlInRootSame);
this.Controls.Add(this.ckRootsOnly);
this.Controls.Add(this.btnCancel);
this.Controls.Add(this.btnOK);
this.Controls.Add(this.gbRootPosition);
this.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.Name = "FormSearchOptions";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "Search Options Filter";
this.gbWordPosition.ResumeLayout(false);
this.gbWordPosition.PerformLayout();
this.gbRootPosition.ResumeLayout(false);
this.gbRootPosition.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.nudMinSyllables)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.nudMaxSyllables)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
public bool IsRootOnly
{
get {return m_IsRootOnly;}
}
public bool IsIdenticalVowelsInWord
{
get {return m_IsIdenticalVowelsInWord;}
}
public bool IsIdenticalVowelsInRoot
{
get {return m_IsIdenticalVowelsInRoot;}
}
public bool IsBrowseView
{
get {return m_IsBrowseView;}
}
public string WordCVShape
{
get {return m_WordCVShape;}
}
public string RootCVShape
{
get {return m_RootCVShape;}
}
public int MinSyllables
{
get { return m_MinSyllables; }
}
public int MaxSyllables
{
get { return m_MaxSyllables; }
}
public SearchOptions.Position WordPosition
{
get {return m_WordPosition;}
}
public SearchOptions.Position RootPosition
{
get {return m_RootPosition;}
}
public CodeTableEntry PSTE
{
get { return m_PSTE; }
}
private void InitializeCT()
{
//PSTable pst = m_SearchOptions.PSTable;
CodeTableEntry cte = null;
Object[] objItem = new object[m_PST.Count() + 1];
string strItem = "";
objItem[0] = "None";
for ( int i = 0; i < m_PST.Count(); i++)
{
cte = m_PST.GetEntry(i);
strItem = cte.Description + " (" + cte.Code + ")";
objItem[i+1] = strItem;
}
cbPS.Items.AddRange(objItem);
cbPS.Text = objItem[0].ToString();
}
private void ckVwlSame_CheckedChanged(object sender, System.EventArgs e)
{
//ckVwlInRootSame.Checked = ckVwlSame.Checked;
}
private void ckVwlInRootSame_CheckedChanged(object sender, System.EventArgs e)
{
//if (ckVwlSame.Checked)
// ckVwlInRootSame.Checked = ckVwlSame.Checked;
}
private void tbWordCV_TextChanged(object sender, System.EventArgs e)
{
string str1 = tbWordCV.Text;
string str2 = "";
for (int i = 0; i < str1.Length; i++)
{
if ( (str1.Substring(i,1) == "C") || (str1.Substring(i,1) == "V") )
str2 += str1.Substring(i,1);
}
tbWordCV.Text = str2;
}
private void tbRootCV_TextChanged(object sender, System.EventArgs e)
{
string str1 = tbRootCV.Text;
string str2 = "";
for (int i = 0; i < str1.Length; i++)
{
if ( (str1.Substring(i,1) == "C") || (str1.Substring(i,1) == "V") )
str2 += str1.Substring(i,1);
}
tbRootCV.Text = str2;
}
private void nudMinSyllables_ValueChanged(object sender, EventArgs e)
{
if (nudMaxSyllables.Value < nudMinSyllables.Value)
nudMaxSyllables.Value = nudMinSyllables.Value;
}
private void nudMaxSyllables_ValueChanged(object sender, EventArgs e)
{
if (nudMinSyllables.Value > nudMaxSyllables.Value)
nudMinSyllables.Value = nudMaxSyllables.Value;
}
private void btnOK_Click(object sender, System.EventArgs e)
{
m_PSTE = BuildCTE(cbPS.Text.Trim());
m_IsRootOnly = ckRootsOnly.Checked;
m_IsIdenticalVowelsInWord = ckVwlSame.Checked;
m_IsIdenticalVowelsInRoot = ckVwlInRootSame.Checked;
m_WordCVShape = tbWordCV.Text;
m_RootCVShape = tbRootCV.Text;
m_MinSyllables = Convert.ToInt16(nudMinSyllables.Value);
m_MaxSyllables = Convert.ToInt16(nudMaxSyllables.Value);
if (rbWordFinal.Checked)
m_WordPosition = SearchOptions.Position.Final;
else if (rbWordMedial.Checked)
m_WordPosition = SearchOptions.Position.Medial;
else if (rbWordInitial.Checked)
m_WordPosition = SearchOptions.Position.Initial;
else m_WordPosition = SearchOptions.Position.Any;
if (rbRootFinal.Checked)
m_RootPosition = SearchOptions.Position.Final;
else if (rbRootMedial.Checked)
m_RootPosition = SearchOptions.Position.Medial;
else if (rbRootInitial.Checked)
m_RootPosition = SearchOptions.Position.Initial;
else m_RootPosition = SearchOptions.Position.Any;
if (m_Browse)
{
m_IsBrowseView = this.ckBrowseView.Checked;
}
}
private void btnCancel_Click(object sender, System.EventArgs e)
{
m_PSTE = null;
m_IsRootOnly = false;
m_IsIdenticalVowelsInWord = false;
m_IsIdenticalVowelsInRoot = false;
m_IsBrowseView = false;
m_WordCVShape = "";
m_RootCVShape = "";
m_MinSyllables = 0;
m_MaxSyllables = 0;
m_WordPosition = SearchOptions.Position.Any;
m_RootPosition = SearchOptions.Position.Any;
m_PSTE = null;
this.Close();
}
private CodeTableEntry BuildCTE(string strPS)
{
CodeTableEntry cte = null;
string strCode = "";
string strDesc = "";
int ndx1 = 0;
int ndx2 = 0;
if ( strPS == "None")
return cte;
ndx1 = strPS.IndexOf( "(" );
ndx2 = strPS.IndexOf( ")" );
strDesc = strPS.Substring(0, ndx1);
strCode = strPS.Substring(ndx1 + 1, ndx2 - ndx1 - 1);
cte = new CodeTableEntry(strCode, strDesc);
return cte;
}
private void UpdateFormForLocalization(LocalizationTable table)
{
string strText = "";
strText = table.GetForm("FormSearchOptionsT");
if (strText != "")
this.Text = strText;
strText = table.GetForm("FormSearchOptions0");
if (strText != "")
this.labPS.Text = strText;
strText = table.GetForm("FormSearchOptions2");
if (strText != "")
this.ckRootsOnly.Text = strText;
strText = table.GetForm("FormSearchOptions3");
if (strText != "")
this.ckVwlSame.Text = strText;
strText = table.GetForm("FormSearchOptions4");
if (strText != "")
this.ckVwlInRootSame.Text = strText;
strText = table.GetForm("FormSearchOptions5");
if (strText != "")
this.labWordCV.Text = strText;
strText = table.GetForm("FormSearchOptions7");
if (strText != "")
this.labRootCV.Text = strText;
strText = table.GetForm("FormSearchOptions9");
if (strText != "")
this.labMinSyllable.Text = strText;
strText = table.GetForm("FormSearchOptions11");
if (strText != "")
this.labMaxSyllables.Text = strText;
strText = table.GetForm("FormSearchOptions13");
if (strText != "")
this.ckBrowseView.Text = strText;
strText = table.GetForm("FormSearchOptions14");
if (strText != "")
this.gbWordPosition.Text = strText;
strText = table.GetForm("FormSearchOptionsW0");
if (strText != "")
this.rbWordAny.Text = strText;
strText = table.GetForm("FormSearchOptionsW1");
if (strText != "")
this.rbWordInitial.Text = strText;
strText = table.GetForm("FormSearchOptionsW2");
if (strText != "")
this.rbWordMedial.Text = strText;
strText = table.GetForm("FormSearchOptionsW3");
if (strText != "")
this.rbWordFinal.Text = strText;
strText = table.GetForm("FormSearchOptions15");
if (strText != "")
this.gbRootPosition.Text = strText;
strText = table.GetForm("FormSearchOptionsR0");
if (strText != "")
this.rbRootAny.Text = strText;
strText = table.GetForm("FormSearchOptionsR1");
if (strText != "")
this.rbRootInitial.Text = strText;
strText = table.GetForm("FormSearchOptionsR2");
if (strText != "")
this.rbRootMedial.Text = strText;
strText = table.GetForm("FormSearchOptionsR3");
if (strText != "")
this.rbRootFinal.Text = strText;
strText = table.GetForm("FormSearchOptions16");
if (strText != "")
this.btnOK.Text = strText;
strText = table.GetForm("FormSearchOptions17");
if (strText != "")
this.btnCancel.Text = strText;
return;
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.FindSymbols;
using Microsoft.CodeAnalysis.FindSymbols.Finders;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Formatting.Rules;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.Notification;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.ChangeSignature
{
internal abstract class AbstractChangeSignatureService : ILanguageService
{
protected SyntaxAnnotation changeSignatureFormattingAnnotation = new SyntaxAnnotation("ChangeSignatureFormatting");
/// <summary>
/// Determines the symbol on which we are invoking ReorderParameters
/// </summary>
public abstract Task<ISymbol> GetInvocationSymbolAsync(Document document, int position, bool restrictToDeclarations, CancellationToken cancellationToken);
/// <summary>
/// Given a SyntaxNode for which we want to reorder parameters/arguments, find the
/// SyntaxNode of a kind where we know how to reorder parameters/arguments.
/// </summary>
public abstract SyntaxNode FindNodeToUpdate(Document document, SyntaxNode node);
public abstract Task<ImmutableArray<SymbolAndProjectId>> DetermineCascadedSymbolsFromDelegateInvoke(
SymbolAndProjectId<IMethodSymbol> symbolAndProjectId, Document document, CancellationToken cancellationToken);
public abstract SyntaxNode ChangeSignature(
Document document,
ISymbol declarationSymbol,
SyntaxNode potentiallyUpdatedNode,
SyntaxNode originalNode,
SignatureChange signaturePermutation,
CancellationToken cancellationToken);
protected abstract IEnumerable<IFormattingRule> GetFormattingRules(Document document);
public async Task<ImmutableArray<ChangeSignatureCodeAction>> GetChangeSignatureCodeActionAsync(Document document, TextSpan span, CancellationToken cancellationToken)
{
var context = await GetContextAsync(document, span.Start, restrictToDeclarations: true, cancellationToken: cancellationToken).ConfigureAwait(false);
return context.CanChangeSignature
? ImmutableArray.Create(new ChangeSignatureCodeAction(this, context))
: ImmutableArray<ChangeSignatureCodeAction>.Empty;
}
internal ChangeSignatureResult ChangeSignature(Document document, int position, Action<string, NotificationSeverity> errorHandler, CancellationToken cancellationToken)
{
var context = GetContextAsync(document, position, restrictToDeclarations: false, cancellationToken: cancellationToken).WaitAndGetResult(cancellationToken);
if (context.CanChangeSignature)
{
return ChangeSignatureWithContext(context, cancellationToken);
}
else
{
switch (context.CannotChangeSignatureReason)
{
case CannotChangeSignatureReason.DefinedInMetadata:
errorHandler(FeaturesResources.The_member_is_defined_in_metadata, NotificationSeverity.Error);
break;
case CannotChangeSignatureReason.IncorrectKind:
errorHandler(FeaturesResources.You_can_only_change_the_signature_of_a_constructor_indexer_method_or_delegate, NotificationSeverity.Error);
break;
case CannotChangeSignatureReason.InsufficientParameters:
errorHandler(FeaturesResources.This_signature_does_not_contain_parameters_that_can_be_changed, NotificationSeverity.Error);
break;
}
return new ChangeSignatureResult(succeeded: false);
}
}
private async Task<ChangeSignatureAnalyzedContext> GetContextAsync(
Document document, int position, bool restrictToDeclarations, CancellationToken cancellationToken)
{
var symbol = await GetInvocationSymbolAsync(
document, position, restrictToDeclarations, cancellationToken).ConfigureAwait(false);
// Cross-language symbols will show as metadata, so map it to source if possible.
symbol = await SymbolFinder.FindSourceDefinitionAsync(symbol, document.Project.Solution, cancellationToken).ConfigureAwait(false) ?? symbol;
if (symbol == null)
{
return new ChangeSignatureAnalyzedContext(CannotChangeSignatureReason.IncorrectKind);
}
if (symbol is IMethodSymbol method)
{
var containingType = method.ContainingType;
if (method.Name == WellKnownMemberNames.DelegateBeginInvokeName &&
containingType != null &&
containingType.IsDelegateType() &&
containingType.DelegateInvokeMethod != null)
{
symbol = containingType.DelegateInvokeMethod;
}
}
if (symbol is IEventSymbol ev)
{
symbol = ev.Type;
}
if (symbol is INamedTypeSymbol typeSymbol)
{
if (typeSymbol.IsDelegateType() && typeSymbol.DelegateInvokeMethod != null)
{
symbol = typeSymbol.DelegateInvokeMethod;
}
}
if (symbol.Locations.Any(loc => loc.IsInMetadata))
{
return new ChangeSignatureAnalyzedContext(CannotChangeSignatureReason.DefinedInMetadata);
}
if (!symbol.MatchesKind(SymbolKind.Method, SymbolKind.Property, SymbolKind.NamedType))
{
return new ChangeSignatureAnalyzedContext(CannotChangeSignatureReason.IncorrectKind);
}
var parameterConfiguration = ParameterConfiguration.Create(symbol.GetParameters().ToList(), symbol is IMethodSymbol && (symbol as IMethodSymbol).IsExtensionMethod);
if (!parameterConfiguration.IsChangeable())
{
return new ChangeSignatureAnalyzedContext(CannotChangeSignatureReason.InsufficientParameters);
}
return new ChangeSignatureAnalyzedContext(
document.Project, symbol, parameterConfiguration);
}
private ChangeSignatureResult ChangeSignatureWithContext(ChangeSignatureAnalyzedContext context, CancellationToken cancellationToken)
{
var options = GetChangeSignatureOptions(context, CancellationToken.None);
if (options.IsCancelled)
{
return new ChangeSignatureResult(succeeded: false);
}
return ChangeSignatureWithContext(context, options, cancellationToken);
}
internal ChangeSignatureResult ChangeSignatureWithContext(ChangeSignatureAnalyzedContext context, ChangeSignatureOptionsResult options, CancellationToken cancellationToken)
{
var succeeded = TryCreateUpdatedSolution(context, options, cancellationToken, out var updatedSolution);
return new ChangeSignatureResult(succeeded, updatedSolution, context.Symbol.ToDisplayString(), context.Symbol.GetGlyph(), options.PreviewChanges);
}
internal ChangeSignatureOptionsResult GetChangeSignatureOptions(
ChangeSignatureAnalyzedContext context, CancellationToken cancellationToken)
{
var notificationService = context.Solution.Workspace.Services.GetService<INotificationService>();
var changeSignatureOptionsService = context.Solution.Workspace.Services.GetService<IChangeSignatureOptionsService>();
var isExtensionMethod = context.Symbol is IMethodSymbol && (context.Symbol as IMethodSymbol).IsExtensionMethod;
return changeSignatureOptionsService.GetChangeSignatureOptions(context.Symbol, context.ParameterConfiguration, notificationService);
}
private static async Task<ImmutableArray<ReferencedSymbol>> FindChangeSignatureReferencesAsync(
SymbolAndProjectId symbolAndProjectId,
Solution solution,
CancellationToken cancellationToken)
{
using (Logger.LogBlock(FunctionId.FindReference_ChangeSignature, cancellationToken))
{
var streamingProgress = new StreamingProgressCollector(
StreamingFindReferencesProgress.Instance);
IImmutableSet<Document> documents = null;
var engine = new FindReferencesSearchEngine(
solution,
documents,
ReferenceFinders.DefaultReferenceFinders.Add(DelegateInvokeMethodReferenceFinder.DelegateInvokeMethod),
streamingProgress,
cancellationToken);
await engine.FindReferencesAsync(symbolAndProjectId).ConfigureAwait(false);
return streamingProgress.GetReferencedSymbols();
}
}
private bool TryCreateUpdatedSolution(
ChangeSignatureAnalyzedContext context, ChangeSignatureOptionsResult options, CancellationToken cancellationToken, out Solution updatedSolution)
{
updatedSolution = context.Solution;
var declaredSymbol = context.Symbol;
var nodesToUpdate = new Dictionary<DocumentId, List<SyntaxNode>>();
var definitionToUse = new Dictionary<SyntaxNode, ISymbol>();
bool hasLocationsInMetadata = false;
var symbols = FindChangeSignatureReferencesAsync(
SymbolAndProjectId.Create(declaredSymbol, context.Project.Id),
context.Solution, cancellationToken).WaitAndGetResult(cancellationToken);
foreach (var symbol in symbols)
{
if (symbol.Definition.Kind == SymbolKind.Method &&
((symbol.Definition as IMethodSymbol).MethodKind == MethodKind.PropertyGet || (symbol.Definition as IMethodSymbol).MethodKind == MethodKind.PropertySet))
{
continue;
}
if (symbol.Definition.Kind == SymbolKind.NamedType)
{
continue;
}
if (symbol.Definition.Locations.Any(loc => loc.IsInMetadata))
{
hasLocationsInMetadata = true;
continue;
}
var symbolWithSyntacticParameters = symbol.Definition;
var symbolWithSemanticParameters = symbol.Definition;
var includeDefinitionLocations = true;
if (symbol.Definition.Kind == SymbolKind.Field)
{
includeDefinitionLocations = false;
}
if (symbolWithSyntacticParameters.Kind == SymbolKind.Event)
{
var eventSymbol = symbolWithSyntacticParameters as IEventSymbol;
var type = eventSymbol.Type as INamedTypeSymbol;
if (type != null && type.DelegateInvokeMethod != null)
{
symbolWithSemanticParameters = type.DelegateInvokeMethod;
}
else
{
continue;
}
}
if (symbolWithSyntacticParameters.Kind == SymbolKind.Method)
{
var methodSymbol = symbolWithSyntacticParameters as IMethodSymbol;
if (methodSymbol.MethodKind == MethodKind.DelegateInvoke)
{
symbolWithSyntacticParameters = methodSymbol.ContainingType;
}
if (methodSymbol.Name == WellKnownMemberNames.DelegateBeginInvokeName &&
methodSymbol.ContainingType != null &&
methodSymbol.ContainingType.IsDelegateType())
{
includeDefinitionLocations = false;
}
}
// Find and annotate all the relevant definitions
if (includeDefinitionLocations)
{
foreach (var def in symbolWithSyntacticParameters.Locations)
{
if (!TryGetNodeWithEditableSignatureOrAttributes(def, updatedSolution, out var nodeToUpdate, out var documentId))
{
continue;
}
if (!nodesToUpdate.ContainsKey(documentId))
{
nodesToUpdate.Add(documentId, new List<SyntaxNode>());
}
AddUpdatableNodeToDictionaries(nodesToUpdate, documentId, nodeToUpdate, definitionToUse, symbolWithSemanticParameters);
}
}
// Find and annotate all the relevant references
foreach (var location in symbol.Locations)
{
if (location.Location.IsInMetadata)
{
hasLocationsInMetadata = true;
continue;
}
if (!TryGetNodeWithEditableSignatureOrAttributes(location.Location, updatedSolution, out var nodeToUpdate2, out var documentId2))
{
continue;
}
if (!nodesToUpdate.ContainsKey(documentId2))
{
nodesToUpdate.Add(documentId2, new List<SyntaxNode>());
}
AddUpdatableNodeToDictionaries(nodesToUpdate, documentId2, nodeToUpdate2, definitionToUse, symbolWithSemanticParameters);
}
}
if (hasLocationsInMetadata)
{
var notificationService = context.Solution.Workspace.Services.GetService<INotificationService>();
if (!notificationService.ConfirmMessageBox(FeaturesResources.This_symbol_has_related_definitions_or_references_in_metadata_Changing_its_signature_may_result_in_build_errors_Do_you_want_to_continue, severity: NotificationSeverity.Warning))
{
return false;
}
}
// Construct all the relevant syntax trees from the base solution
var updatedRoots = new Dictionary<DocumentId, SyntaxNode>();
foreach (var docId in nodesToUpdate.Keys)
{
var doc = updatedSolution.GetDocument(docId);
var updater = doc.Project.LanguageServices.GetService<AbstractChangeSignatureService>();
var root = doc.GetSyntaxRootSynchronously(CancellationToken.None);
var nodes = nodesToUpdate[docId];
var newRoot = root.ReplaceNodes(nodes, (originalNode, potentiallyUpdatedNode) =>
{
return updater.ChangeSignature(doc, definitionToUse[originalNode], potentiallyUpdatedNode, originalNode, CreateCompensatingSignatureChange(definitionToUse[originalNode], options.UpdatedSignature), cancellationToken);
});
var annotatedNodes = newRoot.GetAnnotatedNodes<SyntaxNode>(syntaxAnnotation: changeSignatureFormattingAnnotation);
var formattedRoot = Formatter.FormatAsync(
newRoot,
changeSignatureFormattingAnnotation,
doc.Project.Solution.Workspace,
options: null,
rules: GetFormattingRules(doc),
cancellationToken: CancellationToken.None).WaitAndGetResult(CancellationToken.None);
updatedRoots[docId] = formattedRoot;
}
// Update the documents using the updated syntax trees
foreach (var docId in nodesToUpdate.Keys)
{
updatedSolution = updatedSolution.WithDocumentSyntaxRoot(docId, updatedRoots[docId]);
}
return true;
}
private void AddUpdatableNodeToDictionaries(Dictionary<DocumentId, List<SyntaxNode>> nodesToUpdate, DocumentId documentId, SyntaxNode nodeToUpdate, Dictionary<SyntaxNode, ISymbol> definitionToUse, ISymbol symbolWithSemanticParameters)
{
nodesToUpdate[documentId].Add(nodeToUpdate);
if (definitionToUse.TryGetValue(nodeToUpdate, out var sym) && sym != symbolWithSemanticParameters)
{
Debug.Assert(false, "Change Signature: Attempted to modify node twice with different semantic parameters.");
}
definitionToUse[nodeToUpdate] = symbolWithSemanticParameters;
}
private bool TryGetNodeWithEditableSignatureOrAttributes(Location location, Solution solution, out SyntaxNode nodeToUpdate, out DocumentId documentId)
{
var tree = location.SourceTree;
documentId = solution.GetDocumentId(tree);
var document = solution.GetDocument(documentId);
var root = tree.GetRoot();
SyntaxNode node = root.FindNode(location.SourceSpan, findInsideTrivia: true, getInnermostNodeForTie: true);
var updater = document.Project.LanguageServices.GetService<AbstractChangeSignatureService>();
nodeToUpdate = updater.FindNodeToUpdate(document, node);
return nodeToUpdate != null;
}
protected static List<IUnifiedArgumentSyntax> PermuteArguments(
Document document,
ISymbol declarationSymbol,
List<IUnifiedArgumentSyntax> arguments,
SignatureChange updatedSignature,
bool isReducedExtensionMethod = false)
{
// 1. Determine which parameters are permutable
var declarationParameters = declarationSymbol.GetParameters().ToList();
var declarationParametersToPermute = GetParametersToPermute(arguments, declarationParameters, isReducedExtensionMethod);
var argumentsToPermute = arguments.Take(declarationParametersToPermute.Count).ToList();
// 2. Create an argument to parameter map, and a parameter to index map for the sort.
var argumentToParameterMap = new Dictionary<IUnifiedArgumentSyntax, IParameterSymbol>();
var parameterToIndexMap = new Dictionary<IParameterSymbol, int>();
for (int i = 0; i < declarationParametersToPermute.Count; i++)
{
var decl = declarationParametersToPermute[i];
var arg = argumentsToPermute[i];
argumentToParameterMap[arg] = decl;
var originalIndex = declarationParameters.IndexOf(decl);
var updatedIndex = updatedSignature.GetUpdatedIndex(originalIndex);
// If there's no value, then we may be handling a method with more parameters than the original symbol (like BeginInvoke).
parameterToIndexMap[decl] = updatedIndex.HasValue ? updatedIndex.Value : -1;
}
// 3. Sort the arguments that need to be reordered
argumentsToPermute.Sort((a1, a2) => { return parameterToIndexMap[argumentToParameterMap[a1]].CompareTo(parameterToIndexMap[argumentToParameterMap[a2]]); });
// 4. Add names to arguments where necessary.
var newArguments = new List<IUnifiedArgumentSyntax>();
int expectedIndex = 0 + (isReducedExtensionMethod ? 1 : 0);
bool seenNamedArgument = false;
foreach (var argument in argumentsToPermute)
{
var param = argumentToParameterMap[argument];
var actualIndex = updatedSignature.GetUpdatedIndex(declarationParameters.IndexOf(param));
if (!actualIndex.HasValue)
{
continue;
}
if ((seenNamedArgument || actualIndex != expectedIndex) && !argument.IsNamed)
{
newArguments.Add(argument.WithName(param.Name).WithAdditionalAnnotations(Formatter.Annotation));
seenNamedArgument = true;
}
else
{
newArguments.Add(argument);
}
seenNamedArgument |= argument.IsNamed;
expectedIndex++;
}
// 5. Add the remaining arguments. These will already have names or be params arguments, but may have been removed.
bool removedParams = updatedSignature.OriginalConfiguration.ParamsParameter != null && updatedSignature.UpdatedConfiguration.ParamsParameter == null;
for (int i = declarationParametersToPermute.Count; i < arguments.Count; i++)
{
if (!arguments[i].IsNamed && removedParams && i >= updatedSignature.UpdatedConfiguration.ToListOfParameters().Count)
{
break;
}
if (!arguments[i].IsNamed || updatedSignature.UpdatedConfiguration.ToListOfParameters().Any(p => p.Name == arguments[i].GetName()))
{
newArguments.Add(arguments[i]);
}
}
return newArguments;
}
private static SignatureChange CreateCompensatingSignatureChange(ISymbol declarationSymbol, SignatureChange updatedSignature)
{
if (declarationSymbol.GetParameters().Length > updatedSignature.OriginalConfiguration.ToListOfParameters().Count)
{
var origStuff = updatedSignature.OriginalConfiguration.ToListOfParameters();
var newStuff = updatedSignature.UpdatedConfiguration.ToListOfParameters();
var realStuff = declarationSymbol.GetParameters();
var bonusParameters = realStuff.Skip(origStuff.Count);
origStuff.AddRange(bonusParameters);
newStuff.AddRange(bonusParameters);
var newOrigParams = ParameterConfiguration.Create(origStuff, updatedSignature.OriginalConfiguration.ThisParameter != null);
var newUpdatedParams = ParameterConfiguration.Create(newStuff, updatedSignature.OriginalConfiguration.ThisParameter != null);
updatedSignature = new SignatureChange(newOrigParams, newUpdatedParams);
}
return updatedSignature;
}
private static List<IParameterSymbol> GetParametersToPermute(
List<IUnifiedArgumentSyntax> arguments,
List<IParameterSymbol> originalParameters,
bool isReducedExtensionMethod)
{
int position = -1 + (isReducedExtensionMethod ? 1 : 0);
var parametersToPermute = new List<IParameterSymbol>();
foreach (var argument in arguments)
{
if (argument.IsNamed)
{
var name = argument.GetName();
// TODO: file bug for var match = originalParameters.FirstOrDefault(p => p.Name == <ISymbol here>);
var match = originalParameters.FirstOrDefault(p => p.Name == name);
if (match == null || originalParameters.IndexOf(match) <= position)
{
break;
}
else
{
position = originalParameters.IndexOf(match);
parametersToPermute.Add(match);
}
}
else
{
position++;
if (position >= originalParameters.Count)
{
break;
}
parametersToPermute.Add(originalParameters[position]);
}
}
return parametersToPermute;
}
}
}
| |
// ***********************************************************************
// Copyright (c) 2011 Charlie Poole, Rob Prouse
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ***********************************************************************
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using NUnit.Compatibility;
using NUnit.Framework.Constraints;
using NUnit.Framework.Interfaces;
using NUnit.Framework.Internal;
using NUnit.Framework.Internal.Execution;
namespace NUnit.Framework
{
/// <summary>
/// Provide the context information of the current test.
/// This is an adapter for the internal ExecutionContext
/// class, hiding the internals from the user test.
/// </summary>
public class TestContext
{
private readonly TestExecutionContext _testExecutionContext;
private TestAdapter _test;
private ResultAdapter _result;
#region Constructor
/// <summary>
/// Construct a TestContext for an ExecutionContext
/// </summary>
/// <param name="testExecutionContext">The ExecutionContext to adapt</param>
public TestContext(TestExecutionContext testExecutionContext)
{
_testExecutionContext = testExecutionContext;
}
#endregion
#region Properties
/// <summary>
/// Get the current test context. This is created
/// as needed. The user may save the context for
/// use within a test, but it should not be used
/// outside the test for which it is created.
/// </summary>
public static TestContext CurrentContext
{
get { return new TestContext(TestExecutionContext.CurrentContext); }
}
/// <summary>
/// Gets a TextWriter that will send output to the current test result.
/// </summary>
public static TextWriter Out
{
get { return TestExecutionContext.CurrentContext.OutWriter; }
}
/// <summary>
/// Gets a TextWriter that will send output directly to Console.Error
/// </summary>
public static TextWriter Error = new EventListenerTextWriter("Error", Console.Error);
/// <summary>
/// Gets a TextWriter for use in displaying immediate progress messages
/// </summary>
public static readonly TextWriter Progress = new EventListenerTextWriter("Progress", Console.Error);
/// <summary>
/// TestParameters object holds parameters for the test run, if any are specified
/// </summary>
public static readonly TestParameters Parameters = new TestParameters();
/// <summary>
/// Static DefaultWorkDirectory is now used as the source
/// of the public instance property WorkDirectory. This is
/// a bit odd but necessary to avoid breaking user tests.
/// </summary>
internal static string DefaultWorkDirectory;
/// <summary>
/// Get a representation of the current test.
/// </summary>
public TestAdapter Test
{
get { return _test ?? (_test = new TestAdapter(_testExecutionContext.CurrentTest)); }
}
/// <summary>
/// Gets a Representation of the TestResult for the current test.
/// </summary>
public ResultAdapter Result
{
get { return _result ?? (_result = new ResultAdapter(_testExecutionContext.CurrentResult)); }
}
#if PARALLEL
/// <summary>
/// Gets the unique name of the Worker that is executing this test.
/// </summary>
public string WorkerId
{
get { return _testExecutionContext.TestWorker.Name; }
}
#endif
/// <summary>
/// Gets the directory containing the current test assembly.
/// </summary>
public string TestDirectory
{
get
{
Assembly assembly = _testExecutionContext?.CurrentTest?.Type?.GetTypeInfo().Assembly;
if (assembly != null)
return AssemblyHelper.GetDirectoryName(assembly);
#if NETSTANDARD1_4
// Test is null, we may be loading tests rather than executing.
// Assume that the NUnit framework is in the same directory as the tests
return AssemblyHelper.GetDirectoryName(typeof(TestContext).GetTypeInfo().Assembly);
#else
// Test is null, we may be loading tests rather than executing.
// Assume that calling assembly is the test assembly.
return AssemblyHelper.GetDirectoryName(Assembly.GetCallingAssembly());
#endif
}
}
/// <summary>
/// Gets the directory to be used for outputting files created
/// by this test run.
/// </summary>
public string WorkDirectory
{
get
{
return DefaultWorkDirectory;
}
}
/// <summary>
/// Gets the random generator.
/// </summary>
/// <value>
/// The random generator.
/// </value>
public Randomizer Random
{
get { return _testExecutionContext.RandomGenerator; }
}
/// <summary>
/// Gets the number of assertions executed
/// up to this point in the test.
/// </summary>
public int AssertCount
{
get { return _testExecutionContext.AssertCount; }
}
/// <summary>
/// Get the number of times the current Test has been repeated. This is currently only
/// set when using the <see cref="RetryAttribute"/>.
/// TODO: add this to the RepeatAttribute as well
/// </summary>
public int CurrentRepeatCount
{
get { return _testExecutionContext.CurrentRepeatCount; }
}
#endregion
#region Static Methods
/// <summary>Write the string representation of a boolean value to the current result</summary>
public static void Write(bool value) { Out.Write(value); }
/// <summary>Write a char to the current result</summary>
public static void Write(char value) { Out.Write(value); }
/// <summary>Write a char array to the current result</summary>
public static void Write(char[] value) { Out.Write(value); }
/// <summary>Write the string representation of a double to the current result</summary>
public static void Write(double value) { Out.Write(value); }
/// <summary>Write the string representation of an Int32 value to the current result</summary>
public static void Write(Int32 value) { Out.Write(value); }
/// <summary>Write the string representation of an Int64 value to the current result</summary>
public static void Write(Int64 value) { Out.Write(value); }
/// <summary>Write the string representation of a decimal value to the current result</summary>
public static void Write(decimal value) { Out.Write(value); }
/// <summary>Write the string representation of an object to the current result</summary>
public static void Write(object value) { Out.Write(value); }
/// <summary>Write the string representation of a Single value to the current result</summary>
public static void Write(Single value) { Out.Write(value); }
/// <summary>Write a string to the current result</summary>
public static void Write(string value) { Out.Write(value); }
/// <summary>Write the string representation of a UInt32 value to the current result</summary>
[CLSCompliant(false)]
public static void Write(UInt32 value) { Out.Write(value); }
/// <summary>Write the string representation of a UInt64 value to the current result</summary>
[CLSCompliant(false)]
public static void Write(UInt64 value) { Out.Write(value); }
/// <summary>Write a formatted string to the current result</summary>
public static void Write(string format, object arg1) { Out.Write(format, arg1); }
/// <summary>Write a formatted string to the current result</summary>
public static void Write(string format, object arg1, object arg2) { Out.Write(format, arg1, arg2); }
/// <summary>Write a formatted string to the current result</summary>
public static void Write(string format, object arg1, object arg2, object arg3) { Out.Write(format, arg1, arg2, arg3); }
/// <summary>Write a formatted string to the current result</summary>
public static void Write(string format, params object[] args) { Out.Write(format, args); }
/// <summary>Write a line terminator to the current result</summary>
public static void WriteLine() { Out.WriteLine(); }
/// <summary>Write the string representation of a boolean value to the current result followed by a line terminator</summary>
public static void WriteLine(bool value) { Out.WriteLine(value); }
/// <summary>Write a char to the current result followed by a line terminator</summary>
public static void WriteLine(char value) { Out.WriteLine(value); }
/// <summary>Write a char array to the current result followed by a line terminator</summary>
public static void WriteLine(char[] value) { Out.WriteLine(value); }
/// <summary>Write the string representation of a double to the current result followed by a line terminator</summary>
public static void WriteLine(double value) { Out.WriteLine(value); }
/// <summary>Write the string representation of an Int32 value to the current result followed by a line terminator</summary>
public static void WriteLine(Int32 value) { Out.WriteLine(value); }
/// <summary>Write the string representation of an Int64 value to the current result followed by a line terminator</summary>
public static void WriteLine(Int64 value) { Out.WriteLine(value); }
/// <summary>Write the string representation of a decimal value to the current result followed by a line terminator</summary>
public static void WriteLine(decimal value) { Out.WriteLine(value); }
/// <summary>Write the string representation of an object to the current result followed by a line terminator</summary>
public static void WriteLine(object value) { Out.WriteLine(value); }
/// <summary>Write the string representation of a Single value to the current result followed by a line terminator</summary>
public static void WriteLine(Single value) { Out.WriteLine(value); }
/// <summary>Write a string to the current result followed by a line terminator</summary>
public static void WriteLine(string value) { Out.WriteLine(value); }
/// <summary>Write the string representation of a UInt32 value to the current result followed by a line terminator</summary>
[CLSCompliant(false)]
public static void WriteLine(UInt32 value) { Out.WriteLine(value); }
/// <summary>Write the string representation of a UInt64 value to the current result followed by a line terminator</summary>
[CLSCompliant(false)]
public static void WriteLine(UInt64 value) { Out.WriteLine(value); }
/// <summary>Write a formatted string to the current result followed by a line terminator</summary>
public static void WriteLine(string format, object arg1) { Out.WriteLine(format, arg1); }
/// <summary>Write a formatted string to the current result followed by a line terminator</summary>
public static void WriteLine(string format, object arg1, object arg2) { Out.WriteLine(format, arg1, arg2); }
/// <summary>Write a formatted string to the current result followed by a line terminator</summary>
public static void WriteLine(string format, object arg1, object arg2, object arg3) { Out.WriteLine(format, arg1, arg2, arg3); }
/// <summary>Write a formatted string to the current result followed by a line terminator</summary>
public static void WriteLine(string format, params object[] args) { Out.WriteLine(format, args); }
/// <summary>
/// This method adds the a new ValueFormatterFactory to the
/// chain of responsibility used for formatting values in messages.
/// The scope of the change is the current TestContext.
/// </summary>
/// <param name="formatterFactory">The factory delegate</param>
public static void AddFormatter(ValueFormatterFactory formatterFactory)
{
TestExecutionContext.CurrentContext.AddFormatter(formatterFactory);
}
/// <summary>
/// Attach a file to the current test result
/// </summary>
/// <param name="filePath">Relative or absolute file path to attachment</param>
/// <param name="description">Optional description of attachment</param>
public static void AddTestAttachment(string filePath, string description = null)
{
Guard.ArgumentNotNull(filePath, nameof(filePath));
Guard.ArgumentValid(filePath.IndexOfAny(Path.GetInvalidPathChars()) == -1,
$"Test attachment file path contains invalid path characters. {filePath}", nameof(filePath));
if (!Path.IsPathRooted(filePath))
filePath = Path.Combine(TestContext.CurrentContext.WorkDirectory, filePath);
if (!File.Exists(filePath))
throw new FileNotFoundException("Test attachment file path could not be found.", filePath);
var result = TestExecutionContext.CurrentContext.CurrentResult;
result.AddTestAttachment(new TestAttachment(filePath, description));
}
/// <summary>
/// This method provides a simplified way to add a ValueFormatter
/// delegate to the chain of responsibility, creating the factory
/// delegate internally. It is useful when the Type of the object
/// is the only criterion for selection of the formatter, since
/// it can be used without getting involved with a compound function.
/// </summary>
/// <typeparam name="TSUPPORTED">The type supported by this formatter</typeparam>
/// <param name="formatter">The ValueFormatter delegate</param>
public static void AddFormatter<TSUPPORTED>(ValueFormatter formatter)
{
AddFormatter(next => val => (val is TSUPPORTED) ? formatter(val) : next(val));
}
#endregion
#region Nested TestAdapter Class
/// <summary>
/// TestAdapter adapts a Test for consumption by
/// the user test code.
/// </summary>
public class TestAdapter
{
private readonly Test _test;
#region Constructor
/// <summary>
/// Construct a TestAdapter for a Test
/// </summary>
/// <param name="test">The Test to be adapted</param>
public TestAdapter(Test test)
{
_test = test;
}
#endregion
#region Properties
/// <summary>
/// Gets the unique Id of a test
/// </summary>
public String ID
{
get { return _test.Id; }
}
/// <summary>
/// The name of the test, which may or may not be
/// the same as the method name.
/// </summary>
public string Name
{
get { return _test.Name; }
}
/// <summary>
/// The name of the method representing the test.
/// </summary>
public string MethodName
{
get
{
return _test is TestMethod
? _test.Method.Name
: null;
}
}
/// <summary>
/// The FullName of the test
/// </summary>
public string FullName
{
get { return _test.FullName; }
}
/// <summary>
/// The ClassName of the test
/// </summary>
public string ClassName
{
get { return _test.ClassName; }
}
/// <summary>
/// A shallow copy of the properties of the test.
/// </summary>
public PropertyBagAdapter Properties
{
get { return new PropertyBagAdapter(_test.Properties); }
}
/// <summary>
/// The arguments to use in creating the test or empty array if none are required.
/// </summary>
public object[] Arguments
{
get { return _test.Arguments; }
}
#endregion
}
#endregion
#region Nested ResultAdapter Class
/// <summary>
/// ResultAdapter adapts a TestResult for consumption by
/// the user test code.
/// </summary>
public class ResultAdapter
{
private readonly TestResult _result;
#region Constructor
/// <summary>
/// Construct a ResultAdapter for a TestResult
/// </summary>
/// <param name="result">The TestResult to be adapted</param>
public ResultAdapter(TestResult result)
{
_result = result;
}
#endregion
#region Properties
/// <summary>
/// Gets a ResultState representing the outcome of the test
/// up to this point in its execution.
/// </summary>
public ResultState Outcome
{
get { return _result.ResultState; }
}
/// <summary>
/// Gets a list of the assertion results generated
/// up to this point in the test.
/// </summary>
public IEnumerable<AssertionResult> Assertions
{
get { return _result.AssertionResults; }
}
/// <summary>
/// Gets the message associated with a test
/// failure or with not running the test
/// </summary>
public string Message
{
get { return _result.Message; }
}
/// <summary>
/// Gets any stack trace associated with an
/// error or failure.
/// </summary>
public virtual string StackTrace
{
get { return _result.StackTrace; }
}
/// <summary>
/// Gets the number of test cases that failed
/// when running the test and all its children.
/// </summary>
public int FailCount
{
get { return _result.FailCount; }
}
/// <summary>
/// Gets the number of test cases that had warnings
/// when running the test and all its children.
/// </summary>
public int WarningCount
{
get { return _result.WarningCount; }
}
/// <summary>
/// Gets the number of test cases that passed
/// when running the test and all its children.
/// </summary>
public int PassCount
{
get { return _result.PassCount; }
}
/// <summary>
/// Gets the number of test cases that were skipped
/// when running the test and all its children.
/// </summary>
public int SkipCount
{
get { return _result.SkipCount; }
}
/// <summary>
/// Gets the number of test cases that were inconclusive
/// when running the test and all its children.
/// </summary>
public int InconclusiveCount
{
get { return _result.InconclusiveCount; }
}
#endregion
}
#endregion
#region Nested PropertyBagAdapter Class
/// <summary>
/// <see cref="PropertyBagAdapter"/> adapts an <see cref="IPropertyBag"/>
/// for consumption by the user.
/// </summary>
public class PropertyBagAdapter
{
private readonly IPropertyBag _source;
/// <summary>
/// Construct a <see cref="PropertyBagAdapter"/> from a source
/// <see cref="IPropertyBag"/>.
/// </summary>
public PropertyBagAdapter(IPropertyBag source)
{
_source = source;
}
/// <summary>
/// Get the first property with the given <paramref name="key"/>, if it can be found, otherwise
/// returns null.
/// </summary>
public object Get(string key)
{
return _source.Get(key);
}
/// <summary>
/// Indicates whether <paramref name="key"/> is found in this
/// <see cref="PropertyBagAdapter"/>.
/// </summary>
public bool ContainsKey(string key)
{
return _source.ContainsKey(key);
}
/// <summary>
/// Returns a collection of properties
/// with the given <paramref name="key"/>.
/// </summary>
public IEnumerable<object> this[string key]
{
get
{
var list = new List<object>();
foreach(var item in _source[key])
{
list.Add(item);
}
return list;
}
}
/// <summary>
/// Returns the count of elements with the given <paramref name="key"/>.
/// </summary>
public int Count(string key)
{
return _source[key].Count;
}
/// <summary>
/// Returns a collection of the property keys.
/// </summary>
public ICollection<string> Keys
{
get
{
return _source.Keys;
}
}
}
#endregion
}
}
| |
using System;
using System.IO;
using FluentAssertions;
using FluentAssertions.Extensions;
using TestableFileSystem.Fakes.Builders;
using TestableFileSystem.Interfaces;
using Xunit;
namespace TestableFileSystem.Fakes.Tests.Specs.FakeFile
{
public sealed class FileTimeCreationSpecs
{
private static readonly DateTime DefaultTimeUtc = 1.February(2034).At(12, 34, 56).AsUtc();
private static readonly DateTime DefaultTime = DefaultTimeUtc.ToLocalTime();
private static readonly DateTime HighTime = DateTime.MaxValue.AddDays(-2).AsUtc().ToLocalTime();
private static readonly DateTime ZeroFileTime = 1.January(1601).AsUtc().ToLocalTime();
[Fact]
private void When_getting_creation_time_in_local_zone_for_null_it_must_fail()
{
// Arrange
IFileSystem fileSystem = new FakeFileSystemBuilder()
.Build();
// Act
// ReSharper disable once AssignNullToNotNullAttribute
Action action = () => fileSystem.File.GetCreationTime(null);
// Assert
action.Should().ThrowExactly<ArgumentNullException>();
}
[Fact]
private void When_setting_creation_time_in_local_zone_for_null_it_must_fail()
{
// Arrange
IFileSystem fileSystem = new FakeFileSystemBuilder()
.Build();
// Act
// ReSharper disable once AssignNullToNotNullAttribute
Action action = () => fileSystem.File.SetCreationTime(null, DefaultTime);
// Assert
action.Should().ThrowExactly<ArgumentNullException>();
}
[Fact]
private void When_getting_creation_time_in_local_zone_for_empty_string_it_must_fail()
{
// Arrange
IFileSystem fileSystem = new FakeFileSystemBuilder()
.Build();
// Act
Action action = () => fileSystem.File.GetCreationTime(string.Empty);
// Assert
action.Should().ThrowExactly<ArgumentException>().WithMessage("The path is not of a legal form.*");
}
[Fact]
private void When_setting_creation_time_in_local_zone_for_empty_string_it_must_fail()
{
// Arrange
IFileSystem fileSystem = new FakeFileSystemBuilder()
.Build();
// Act
Action action = () => fileSystem.File.SetCreationTime(string.Empty, DefaultTime);
// Assert
action.Should().ThrowExactly<ArgumentException>().WithMessage("The path is not of a legal form.*");
}
[Fact]
private void When_getting_creation_time_in_local_zone_for_whitespace_it_must_fail()
{
// Arrange
IFileSystem fileSystem = new FakeFileSystemBuilder()
.Build();
// Act
Action action = () => fileSystem.File.GetCreationTime(" ");
// Assert
action.Should().ThrowExactly<ArgumentException>().WithMessage("The path is not of a legal form.*");
}
[Fact]
private void When_setting_creation_time_in_local_zone_for_whitespace_it_must_fail()
{
// Arrange
IFileSystem fileSystem = new FakeFileSystemBuilder()
.Build();
// Act
Action action = () => fileSystem.File.SetCreationTime(" ", DefaultTime);
// Assert
action.Should().ThrowExactly<ArgumentException>().WithMessage("The path is not of a legal form.*");
}
[Fact]
private void When_getting_creation_time_in_local_zone_for_invalid_drive_it_must_fail()
{
// Arrange
IFileSystem fileSystem = new FakeFileSystemBuilder()
.Build();
// Act
Action action = () => fileSystem.File.GetCreationTime("_:");
// Assert
action.Should().ThrowExactly<NotSupportedException>().WithMessage("The given path's format is not supported.");
}
[Fact]
private void When_setting_creation_time_in_local_zone_for_invalid_drive_it_must_fail()
{
// Arrange
IFileSystem fileSystem = new FakeFileSystemBuilder()
.Build();
// Act
Action action = () => fileSystem.File.SetCreationTime("_:", DefaultTime);
// Assert
action.Should().ThrowExactly<NotSupportedException>().WithMessage("The given path's format is not supported.");
}
[Fact]
private void When_getting_creation_time_in_local_zone_for_wildcard_characters_it_must_fail()
{
// Arrange
IFileSystem fileSystem = new FakeFileSystemBuilder()
.Build();
// Act
Action action = () => fileSystem.File.GetCreationTime(@"c:\dir?i");
// Assert
action.Should().ThrowExactly<ArgumentException>().WithMessage("Illegal characters in path.*");
}
[Fact]
private void When_setting_creation_time_in_local_zone_for_wildcard_characters_it_must_fail()
{
// Arrange
IFileSystem fileSystem = new FakeFileSystemBuilder()
.Build();
// Act
Action action = () => fileSystem.File.SetCreationTime(@"c:\dir?i", DefaultTime);
// Assert
action.Should().ThrowExactly<ArgumentException>().WithMessage("Illegal characters in path.*");
}
[Fact]
private void When_getting_creation_time_in_local_zone_for_missing_file_it_must_succeed()
{
// Arrange
IFileSystem fileSystem = new FakeFileSystemBuilder()
.IncludingDirectory(@"C:\some")
.Build();
// Act
DateTime time = fileSystem.File.GetCreationTime(@"C:\some\file.txt");
// Assert
time.Should().Be(ZeroFileTime);
}
[Fact]
private void When_setting_creation_time_in_local_zone_for_missing_file_it_must_fail()
{
// Arrange
IFileSystem fileSystem = new FakeFileSystemBuilder()
.IncludingDirectory(@"C:\some")
.Build();
// Act
Action action = () => fileSystem.File.SetCreationTime(@"C:\some\file.txt", DefaultTime);
// Assert
action.Should().ThrowExactly<FileNotFoundException>().WithMessage(@"Could not find file 'C:\some\file.txt'.");
}
[Fact]
private void When_setting_creation_time_in_local_zone_for_existing_file_it_must_succeed()
{
// Arrange
const string path = @"C:\some.txt";
IFileSystem fileSystem = new FakeFileSystemBuilder()
.IncludingEmptyFile(path)
.Build();
// Act
fileSystem.File.SetCreationTime(path, DefaultTime);
// Assert
fileSystem.File.GetCreationTime(path).Should().Be(DefaultTime);
}
[Fact]
private void When_setting_creation_time_in_local_zone_for_existing_file_with_trailing_whitespace_it_must_succeed()
{
// Arrange
IFileSystem fileSystem = new FakeFileSystemBuilder()
.IncludingEmptyFile(@"C:\some.txt")
.Build();
// Act
fileSystem.File.SetCreationTime(@"C:\some.txt ", DefaultTime);
// Assert
fileSystem.File.GetCreationTime(@"C:\some.txt ").Should().Be(DefaultTime);
}
[Fact]
private void When_setting_creation_time_in_local_zone_for_existing_readonly_file_it_must_fail()
{
// Arrange
IFileSystem fileSystem = new FakeFileSystemBuilder()
.IncludingEmptyFile(@"C:\some.txt", FileAttributes.ReadOnly)
.Build();
// Act
Action action = () => fileSystem.File.SetCreationTime(@"C:\some.txt", DefaultTime);
// Assert
action.Should().ThrowExactly<UnauthorizedAccessException>()
.WithMessage(@"Access to the path 'C:\some.txt' is denied.");
}
[Fact]
private void When_setting_creation_time_in_local_zone_for_existing_file_in_readonly_directory_it_must_succeed()
{
// Arrange
IFileSystem fileSystem = new FakeFileSystemBuilder()
.IncludingDirectory(@"c:\folder", FileAttributes.ReadOnly)
.IncludingEmptyFile(@"C:\folder\some.txt")
.Build();
// Act
fileSystem.File.SetCreationTime(@"C:\folder\some.txt", DefaultTime);
// Assert
fileSystem.File.GetCreationTime(@"C:\folder\some.txt").Should().Be(DefaultTime);
}
[Fact]
private void When_setting_creation_time_in_local_zone_for_opened_file_it_must_fail()
{
// Arrange
const string path = @"C:\folder\some.txt";
IFileSystem fileSystem = new FakeFileSystemBuilder()
.IncludingEmptyFile(path)
.Build();
using (fileSystem.File.OpenRead(path))
{
// Act
Action action = () => fileSystem.File.SetCreationTime(path, DefaultTime);
// Assert
action.Should().ThrowExactly<IOException>().WithMessage(
@"The process cannot access the file 'C:\folder\some.txt' because it is being used by another process.");
}
}
[Fact]
private void When_setting_creation_time_in_local_zone_for_existing_file_to_MinValue_it_must_fail()
{
// Arrange
const string path = @"C:\some.txt";
IFileSystem fileSystem = new FakeFileSystemBuilder()
.IncludingEmptyFile(path)
.Build();
// Act
Action action = () => fileSystem.File.SetCreationTime(path, DateTime.MinValue);
// Assert
action.Should().ThrowExactly<ArgumentOutOfRangeException>().WithMessage(
"The UTC time represented when the offset is applied must be between year 0 and 10,000.*");
}
[Fact]
private void When_setting_creation_time_in_local_zone_for_existing_file_to_MaxValue_it_must_succeed()
{
// Arrange
const string path = @"C:\some.txt";
IFileSystem fileSystem = new FakeFileSystemBuilder()
.IncludingEmptyFile(path)
.Build();
// Act
fileSystem.File.SetCreationTime(path, HighTime);
// Assert
fileSystem.File.GetCreationTime(path).Should().Be(HighTime);
}
[Fact]
private void When_getting_creation_time_in_local_zone_for_drive_it_must_succeed()
{
// Arrange
const string path = @"C:\";
var clock = new SystemClock(() => DefaultTimeUtc);
IFileSystem fileSystem = new FakeFileSystemBuilder(clock)
.IncludingDirectory(path)
.Build();
// Act
DateTime time = fileSystem.File.GetCreationTime(path);
// Assert
time.Should().Be(DefaultTime);
}
[Fact]
private void When_setting_creation_time_in_local_zone_for_drive_it_must_fail()
{
// Arrange
const string path = @"C:\";
IFileSystem fileSystem = new FakeFileSystemBuilder()
.IncludingDirectory(path)
.Build();
// Act
Action action = () => fileSystem.File.SetCreationTime(path, DefaultTime);
// Assert
action.Should().ThrowExactly<ArgumentException>().WithMessage("Path must not be a drive.*");
}
[Fact]
private void When_getting_creation_time_in_local_zone_using_absolute_path_without_drive_letter_it_must_succeed()
{
// Arrange
var clock = new SystemClock(() => DefaultTimeUtc);
IFileSystem fileSystem = new FakeFileSystemBuilder(clock)
.IncludingDirectory(@"c:\some")
.IncludingEmptyFile(@"C:\file.txt")
.Build();
fileSystem.Directory.SetCurrentDirectory(@"C:\some");
// Act
DateTime time = fileSystem.File.GetCreationTime(@"\file.txt");
// Assert
time.Should().Be(DefaultTime);
}
[Fact]
private void When_setting_creation_time_in_local_zone_using_absolute_path_without_drive_letter_it_must_succeed()
{
// Arrange
var clock = new SystemClock(() => DefaultTimeUtc);
IFileSystem fileSystem = new FakeFileSystemBuilder(clock)
.IncludingDirectory(@"c:\some")
.IncludingEmptyFile(@"C:\file.txt")
.Build();
fileSystem.Directory.SetCurrentDirectory(@"C:\some");
// Act
fileSystem.File.SetCreationTime(@"\file.txt", DefaultTime);
// Assert
fileSystem.File.GetCreationTime(@"c:\file.txt").Should().Be(DefaultTime);
}
[Fact]
private void When_getting_creation_time_in_local_zone_for_existing_relative_local_file_it_must_succeed()
{
// Arrange
var clock = new SystemClock(() => DefaultTimeUtc);
IFileSystem fileSystem = new FakeFileSystemBuilder(clock)
.IncludingEmptyFile(@"C:\folder\some.txt")
.Build();
fileSystem.Directory.SetCurrentDirectory(@"c:\folder");
// Act
DateTime time = fileSystem.File.GetCreationTime(@"some.txt");
// Assert
time.Should().Be(DefaultTime);
}
[Fact]
private void When_setting_creation_time_in_local_zone_for_existing_relative_local_file_it_must_succeed()
{
// Arrange
IFileSystem fileSystem = new FakeFileSystemBuilder()
.IncludingEmptyFile(@"C:\folder\some.txt")
.Build();
fileSystem.Directory.SetCurrentDirectory(@"c:\folder");
// Act
fileSystem.File.SetCreationTime(@"some.txt", DefaultTime);
// Assert
fileSystem.File.GetCreationTime(@"C:\folder\some.txt").Should().Be(DefaultTime);
}
[Fact]
private void When_getting_creation_time_in_local_zone_for_existing_local_file_with_different_casing_it_must_succeed()
{
// Arrange
var clock = new SystemClock(() => DefaultTimeUtc);
IFileSystem fileSystem = new FakeFileSystemBuilder(clock)
.IncludingEmptyFile(@"C:\FOLDER\some.TXT")
.Build();
// Act
DateTime time = fileSystem.File.GetCreationTime(@"C:\folder\SOME.txt");
// Assert
time.Should().Be(DefaultTime);
}
[Fact]
private void When_setting_creation_time_in_local_zone_for_existing_local_file_with_different_casing_it_must_succeed()
{
// Arrange
IFileSystem fileSystem = new FakeFileSystemBuilder()
.IncludingEmptyFile(@"C:\FOLDER\some.TXT")
.Build();
// Act
fileSystem.File.SetCreationTime(@"C:\folder\SOME.txt", DefaultTime);
// Assert
fileSystem.File.GetCreationTime(@"C:\FOLDER\some.TXT").Should().Be(DefaultTime);
}
[Fact]
private void When_getting_creation_time_in_local_zone_for_missing_parent_directory_it_must_succeed()
{
// Arrange
IFileSystem fileSystem = new FakeFileSystemBuilder()
.Build();
// Act
DateTime time = fileSystem.File.GetCreationTime(@"C:\some\file.txt");
// Assert
time.Should().Be(ZeroFileTime);
}
[Fact]
private void When_setting_creation_time_in_local_zone_for_missing_parent_directory_it_must_fail()
{
// Arrange
IFileSystem fileSystem = new FakeFileSystemBuilder()
.Build();
// Act
Action action = () => fileSystem.File.SetCreationTime(@"C:\some\file.txt", DefaultTime);
// Assert
action.Should().ThrowExactly<DirectoryNotFoundException>().WithMessage(
@"Could not find a part of the path 'C:\some\file.txt'.");
}
[Fact]
private void When_getting_creation_time_in_local_zone_for_existing_directory_it_must_succeed()
{
// Arrange
const string path = @"C:\some\subfolder";
var clock = new SystemClock(() => DefaultTimeUtc);
IFileSystem fileSystem = new FakeFileSystemBuilder(clock)
.IncludingDirectory(path)
.Build();
// Act
DateTime time = fileSystem.File.GetCreationTime(path);
// Assert
time.Should().Be(DefaultTime);
}
[Fact]
private void When_setting_creation_time_in_local_zone_for_existing_directory_it_must_fail()
{
// Arrange
const string path = @"C:\some\subfolder";
IFileSystem fileSystem = new FakeFileSystemBuilder()
.IncludingDirectory(path)
.Build();
// Act
Action action = () => fileSystem.File.SetCreationTime(path, DefaultTime);
// Assert
action.Should().ThrowExactly<DirectoryNotFoundException>().WithMessage(
@"Could not find a part of the path 'C:\some\subfolder'.");
}
[Fact]
private void When_getting_creation_time_in_local_zone_for_parent_directory_that_exists_as_file_it_must_succeed()
{
// Arrange
IFileSystem fileSystem = new FakeFileSystemBuilder()
.IncludingEmptyFile(@"c:\some\file.txt")
.Build();
// Act
DateTime time = fileSystem.File.GetCreationTime(@"c:\some\file.txt\nested.txt");
// Assert
time.Should().Be(ZeroFileTime);
}
[Fact]
private void When_setting_creation_time_in_local_zone_for_parent_directory_that_exists_as_file_it_must_fail()
{
// Arrange
IFileSystem fileSystem = new FakeFileSystemBuilder()
.IncludingEmptyFile(@"c:\some\file.txt")
.Build();
// Act
Action action = () => fileSystem.File.SetCreationTime(@"c:\some\file.txt\nested.txt", DefaultTime);
// Assert
action.Should().ThrowExactly<DirectoryNotFoundException>().WithMessage(
@"Could not find a part of the path 'c:\some\file.txt\nested.txt'.");
}
[Fact]
private void When_getting_creation_time_in_local_zone_for_parent_parent_directory_that_exists_as_file_it_must_succeed()
{
// Arrange
IFileSystem fileSystem = new FakeFileSystemBuilder()
.IncludingEmptyFile(@"c:\some\file.txt")
.Build();
// Act
DateTime time = fileSystem.File.GetCreationTime(@"c:\some\file.txt\nested.txt\more.txt");
// Assert
time.Should().Be(ZeroFileTime);
}
[Fact]
private void When_setting_creation_time_in_local_zone_for_parent_parent_directory_that_exists_as_file_it_must_fail()
{
// Arrange
IFileSystem fileSystem = new FakeFileSystemBuilder()
.IncludingEmptyFile(@"c:\some\file.txt")
.Build();
// Act
Action action = () => fileSystem.File.SetCreationTime(@"c:\some\file.txt\nested.txt\more.txt", DefaultTime);
// Assert
action.Should().ThrowExactly<DirectoryNotFoundException>().WithMessage(
@"Could not find a part of the path 'c:\some\file.txt\nested.txt\more.txt'.");
}
[Fact]
private void When_getting_creation_time_in_local_zone_for_missing_network_share_it_must_fail()
{
// Arrange
const string path = @"\\server\share\missing.txt";
IFileSystem fileSystem = new FakeFileSystemBuilder()
.Build();
// Act
Action action = () => fileSystem.File.GetCreationTime(path);
// Assert
action.Should().ThrowExactly<IOException>().WithMessage("The network path was not found.");
}
[Fact]
private void When_setting_creation_time_in_local_zone_for_missing_network_share_it_must_fail()
{
// Arrange
const string path = @"\\server\share\missing.docx";
IFileSystem fileSystem = new FakeFileSystemBuilder()
.Build();
// Act
Action action = () => fileSystem.File.SetCreationTime(path, DefaultTime);
// Assert
action.Should().ThrowExactly<IOException>().WithMessage("The network path was not found.");
}
[Fact]
private void When_getting_creation_time_in_local_zone_for_existing_network_share_it_must_succeed()
{
// Arrange
const string path = @"\\server\share";
var clock = new SystemClock(() => DefaultTimeUtc);
IFileSystem fileSystem = new FakeFileSystemBuilder(clock)
.IncludingDirectory(path)
.Build();
// Act
DateTime time = fileSystem.File.GetCreationTime(path);
// Assert
time.Should().Be(DefaultTime);
}
[Fact]
private void When_setting_creation_time_in_local_zone_for_existing_network_share_it_must_fail()
{
// Arrange
const string path = @"\\server\share";
IFileSystem fileSystem = new FakeFileSystemBuilder()
.IncludingDirectory(path)
.Build();
// Act
Action action = () => fileSystem.File.SetCreationTime(path, DefaultTime);
// Assert
action.Should().ThrowExactly<UnauthorizedAccessException>()
.WithMessage(@"Access to the path '\\server\share' is denied.");
}
[Fact]
private void When_getting_creation_time_in_local_zone_for_missing_remote_file_it_must_succeed()
{
// Arrange
const string path = @"\\server\share\missing.txt";
IFileSystem fileSystem = new FakeFileSystemBuilder()
.IncludingDirectory(@"\\server\share")
.Build();
// Act
DateTime time = fileSystem.File.GetCreationTime(path);
// Assert
time.Should().Be(ZeroFileTime);
}
[Fact]
private void When_setting_creation_time_in_local_zone_for_missing_remote_file_it_must_fail()
{
// Arrange
const string path = @"\\server\share\missing.docx";
IFileSystem fileSystem = new FakeFileSystemBuilder()
.IncludingDirectory(@"\\server\share")
.Build();
// Act
Action action = () => fileSystem.File.SetCreationTime(path, DefaultTime);
// Assert
action.Should().ThrowExactly<FileNotFoundException>()
.WithMessage(@"Could not find file '\\server\share\missing.docx'.");
}
[Fact]
private void When_setting_creation_time_in_local_zone_for_existing_remote_file_it_must_succeed()
{
// Arrange
const string path = @"\\server\share\personal.docx";
IFileSystem fileSystem = new FakeFileSystemBuilder()
.IncludingEmptyFile(path)
.Build();
// Act
fileSystem.File.SetCreationTime(path, DefaultTime);
// Assert
fileSystem.File.GetCreationTime(path).Should().Be(DefaultTime);
}
[Fact]
private void When_getting_creation_time_in_local_zone_for_reserved_name_it_must_fail()
{
// Arrange
IFileSystem fileSystem = new FakeFileSystemBuilder()
.Build();
// Act
Action action = () => fileSystem.File.GetCreationTime("COM1");
// Assert
action.Should().ThrowExactly<PlatformNotSupportedException>().WithMessage("Reserved names are not supported.");
}
[Fact]
private void When_setting_creation_time_in_local_zone_for_reserved_name_it_must_fail()
{
// Arrange
IFileSystem fileSystem = new FakeFileSystemBuilder()
.Build();
// Act
Action action = () => fileSystem.File.SetCreationTime("COM1", DefaultTime);
// Assert
action.Should().ThrowExactly<PlatformNotSupportedException>().WithMessage("Reserved names are not supported.");
}
[Fact]
private void When_getting_creation_time_in_local_zone_for_missing_extended_local_file_it_must_succeed()
{
// Arrange
IFileSystem fileSystem = new FakeFileSystemBuilder()
.IncludingDirectory(@"c:\some")
.Build();
// Act
DateTime time = fileSystem.File.GetCreationTime(@"\\?\C:\some\missing.txt");
// Assert
time.Should().Be(ZeroFileTime);
}
[Fact]
private void When_setting_creation_time_in_local_zone_for_missing_extended_local_file_it_must_fail()
{
// Arrange
IFileSystem fileSystem = new FakeFileSystemBuilder()
.IncludingDirectory(@"c:\some")
.Build();
// Act
Action action = () => fileSystem.File.SetCreationTime(@"\\?\C:\some\missing.txt", DefaultTime);
// Assert
action.Should().ThrowExactly<FileNotFoundException>().WithMessage(@"Could not find file '\\?\C:\some\missing.txt'.");
}
[Fact]
private void When_setting_creation_time_in_local_zone_for_existing_extended_local_file_it_must_succeed()
{
// Arrange
IFileSystem fileSystem = new FakeFileSystemBuilder()
.IncludingEmptyFile(@"C:\some\other.txt")
.Build();
// Act
fileSystem.File.SetCreationTime(@"\\?\C:\some\other.txt", DefaultTime);
// Assert
fileSystem.File.GetCreationTime(@"\\?\C:\some\other.txt").Should().Be(DefaultTime);
}
}
}
| |
// Copyright 2006 Alp Toker <alp@atoker.com>
// This software is made available under the MIT License
// See COPYING for details
using System;
using System.Text;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
namespace DBus
{
partial class MessageReader
{
protected EndianFlag endianness;
//protected byte[] data;
public byte[] data;
//TODO: this should be uint or long to handle long messages
//internal int pos = 0;
public int pos = 0;
protected Message message;
public MessageReader (EndianFlag endianness, byte[] data)
{
//if (data == null)
// throw new ArgumentNullException ("data");
if (data == null)
data = new byte[0];
this.endianness = endianness;
this.IsNativeEndian = endianness == Connection.NativeEndianness;
this.data = data;
}
public MessageReader (Message message) : this (message.Header.Endianness, message.Body)
{
if (message == null)
throw new ArgumentNullException ("message");
this.message = message;
}
public readonly bool IsNativeEndian;
public object ReadValue (Type type)
{
if (type == typeof (void))
return null;
if (type.IsArray) {
return ReadArray (type.GetElementType ());
} else if (type == typeof (ObjectPath)) {
return ReadObjectPath ();
} else if (type == typeof (Signature)) {
return ReadSignature ();
} else if (type == typeof (object)) {
return ReadVariant ();
} else if (type == typeof (string)) {
return ReadString ();
} else if (type.IsGenericType && type.GetGenericTypeDefinition () == typeof (IDictionary<,>)) {
Type[] genArgs = type.GetGenericArguments ();
//Type dictType = typeof (Dictionary<,>).MakeGenericType (genArgs);
//workaround for Mono bug #81035 (memory leak)
Type dictType = Mapper.GetGenericType (typeof (Dictionary<,>), genArgs);
System.Collections.IDictionary idict = (System.Collections.IDictionary)Activator.CreateInstance(dictType, new object[0]);
GetValueToDict (genArgs[0], genArgs[1], idict);
return idict;
} else if (Mapper.IsPublic (type)) {
return GetObject (type);
} else if (!type.IsPrimitive && !type.IsEnum) {
return ReadStruct (type);
} else {
object val;
DType dtype = Signature.TypeToDType (type);
val = ReadValue (dtype);
if (type.IsEnum)
val = Enum.ToObject (type, val);
return val;
}
}
//helper method, should not be used generally
public object ReadValue (DType dtype)
{
switch (dtype)
{
case DType.Byte:
return ReadByte ();
case DType.Boolean:
return ReadBoolean ();
case DType.Int16:
return ReadInt16 ();
case DType.UInt16:
return ReadUInt16 ();
case DType.Int32:
return ReadInt32 ();
case DType.UInt32:
return ReadUInt32 ();
case DType.Int64:
return ReadInt64 ();
case DType.UInt64:
return ReadUInt64 ();
#if !DISABLE_SINGLE
case DType.Single:
return ReadSingle ();
#endif
case DType.Double:
return ReadDouble ();
case DType.String:
return ReadString ();
case DType.ObjectPath:
return ReadObjectPath ();
case DType.Signature:
return ReadSignature ();
case DType.Variant:
return ReadVariant ();
default:
throw new Exception ("Unhandled D-Bus type: " + dtype);
}
}
public object GetObject (Type type)
{
ObjectPath path = ReadObjectPath ();
return message.Connection.GetObject (type, (string)message.Header[FieldCode.Sender], path);
}
public byte ReadByte ()
{
return data[pos++];
}
public bool ReadBoolean ()
{
uint intval = ReadUInt32 ();
switch (intval) {
case 0:
return false;
case 1:
return true;
default:
throw new Exception ("Read value " + intval + " at position " + pos + " while expecting boolean (0/1)");
}
}
unsafe protected void MarshalUShort (void* dstPtr)
{
ReadPad (2);
if (data.Length < pos + 2)
throw new Exception ("Cannot read beyond end of data");
if (endianness == Connection.NativeEndianness) {
fixed (byte* p = &data[pos])
*((ushort*)dstPtr) = *((ushort*)p);
} else {
byte* dst = (byte*)dstPtr;
dst[0] = data[pos + 1];
dst[1] = data[pos + 0];
}
pos += 2;
}
unsafe public short ReadInt16 ()
{
short val;
MarshalUShort (&val);
return val;
}
unsafe public ushort ReadUInt16 ()
{
ushort val;
MarshalUShort (&val);
return val;
}
unsafe protected void MarshalUInt (void* dstPtr)
{
ReadPad (4);
if (data.Length < pos + 4)
throw new Exception ("Cannot read beyond end of data");
if (endianness == Connection.NativeEndianness) {
fixed (byte* p = &data[pos])
*((uint*)dstPtr) = *((uint*)p);
} else {
byte* dst = (byte*)dstPtr;
dst[0] = data[pos + 3];
dst[1] = data[pos + 2];
dst[2] = data[pos + 1];
dst[3] = data[pos + 0];
}
pos += 4;
}
unsafe public int ReadInt32 ()
{
int val;
MarshalUInt (&val);
return val;
}
unsafe public uint ReadUInt32 ()
{
uint val;
MarshalUInt (&val);
return val;
}
unsafe protected void MarshalULong (void* dstPtr)
{
ReadPad (8);
if (data.Length < pos + 8)
throw new Exception ("Cannot read beyond end of data");
if (endianness == Connection.NativeEndianness) {
fixed (byte* p = &data[pos])
*((ulong*)dstPtr) = *((ulong*)p);
} else {
byte* dst = (byte*)dstPtr;
for (int i = 0; i < 8; ++i)
dst[i] = data[pos + (7 - i)];
}
pos += 8;
}
unsafe public long ReadInt64 ()
{
long val;
MarshalULong (&val);
return val;
}
unsafe public ulong ReadUInt64 ()
{
ulong val;
MarshalULong (&val);
return val;
}
#if !DISABLE_SINGLE
unsafe public float ReadSingle ()
{
float val;
MarshalUInt (&val);
return val;
}
#endif
unsafe public double ReadDouble ()
{
double val;
MarshalULong (&val);
return val;
}
public string ReadString ()
{
uint ln = ReadUInt32 ();
string val = Encoding.UTF8.GetString (data, pos, (int)ln);
pos += (int)ln;
ReadNull ();
return val;
}
public ObjectPath ReadObjectPath ()
{
//exactly the same as string
return new ObjectPath (ReadString ());
}
public Signature ReadSignature ()
{
byte ln = ReadByte ();
// Avoid an array allocation for small signatures
if (ln == 1) {
DType dtype = (DType)ReadByte ();
ReadNull ();
return new Signature (dtype);
}
if (ln > Protocol.MaxSignatureLength)
throw new Exception ("Signature length " + ln + " exceeds maximum allowed " + Protocol.MaxSignatureLength + " bytes");
byte[] sigData = new byte[ln];
Array.Copy (data, pos, sigData, 0, (int)ln);
pos += (int)ln;
ReadNull ();
return Signature.Take (sigData);
}
public object ReadVariant ()
{
return ReadValue (ReadSignature ());
}
// Used primarily for reading variant values
object ReadValue (Signature sig)
{
if (sig.IsPrimitive)
return ReadValue (sig[0]);
Type t = null;
try {
t = sig.ToType ();
} catch (NotSupportedException e) {
// We don't catch other exceptions as they indicate a malformed signature
if (Protocol.Verbose)
Console.Error.WriteLine (e.Message);
}
/*
if (t == null) {
StepOver (sig);
return null;
}
*/
if (t == null) {
ReadPad (sig.Alignment);
int startPos = pos;
StepOver (sig);
int ln = pos - startPos;
DValue dv = new DValue();
dv.endianness = endianness;
dv.signature = sig;
dv.data = new byte[ln];
Array.Copy (data, startPos, dv.data, 0, ln);
return dv;
}
return ReadValue (t);
}
//not pretty or efficient but works
public void GetValueToDict (Type keyType, Type valType, System.Collections.IDictionary val)
{
uint ln = ReadUInt32 ();
if (ln > Protocol.MaxArrayLength)
throw new Exception ("Dict length " + ln + " exceeds maximum allowed " + Protocol.MaxArrayLength + " bytes");
//advance to the alignment of the element
//ReadPad (Protocol.GetAlignment (Signature.TypeToDType (type)));
ReadPad (8);
int endPos = pos + (int)ln;
//while (stream.Position != endPos)
while (pos < endPos)
{
ReadPad (8);
val.Add (ReadValue (keyType), ReadValue (valType));
}
if (pos != endPos)
throw new Exception ("Read pos " + pos + " != ep " + endPos);
}
//this could be made generic to avoid boxing
public Array ReadArray (Type elemType)
{
uint ln = ReadUInt32 ();
if (ln > Protocol.MaxArrayLength)
throw new Exception ("Array length " + ln + " exceeds maximum allowed " + Protocol.MaxArrayLength + " bytes");
//TODO: more fast paths for primitive arrays
if (elemType == typeof (byte)) {
byte[] valb = new byte[ln];
Array.Copy (data, pos, valb, 0, (int)ln);
pos += (int)ln;
return valb;
}
//advance to the alignment of the element
ReadPad (Protocol.GetAlignment (Signature.TypeToDType (elemType)));
int endPos = pos + (int)ln;
//List<T> vals = new List<T> ();
System.Collections.ArrayList vals = new System.Collections.ArrayList ();
//while (stream.Position != endPos)
while (pos < endPos)
vals.Add (ReadValue (elemType));
if (pos != endPos)
throw new Exception ("Read pos " + pos + " != ep " + endPos);
return vals.ToArray (elemType);
}
//struct
//probably the wrong place for this
//there might be more elegant solutions
public object ReadStruct (Type type)
{
ReadPad (8);
object val = Activator.CreateInstance (type);
/*
if (type.IsGenericType && type.GetGenericTypeDefinition () == typeof (KeyValuePair<,>)) {
object elem;
System.Reflection.PropertyInfo key_prop = type.GetProperty ("Key");
GetValue (key_prop.PropertyType, out elem);
key_prop.SetValue (val, elem, null);
System.Reflection.PropertyInfo val_prop = type.GetProperty ("Value");
GetValue (val_prop.PropertyType, out elem);
val_prop.SetValue (val, elem, null);
return;
}
*/
FieldInfo[] fis = type.GetFields (BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
foreach (System.Reflection.FieldInfo fi in fis)
fi.SetValue (val, ReadValue (fi.FieldType));
return val;
}
public void ReadNull ()
{
if (data[pos] != 0)
throw new Exception ("Read non-zero byte at position " + pos + " while expecting null terminator");
pos++;
}
/*
public void ReadPad (int alignment)
{
pos = Protocol.Padded (pos, alignment);
}
*/
public void ReadPad (int alignment)
{
for (int endPos = Protocol.Padded (pos, alignment) ; pos != endPos ; pos++)
if (data[pos] != 0)
throw new Exception ("Read non-zero byte at position " + pos + " while expecting padding");
}
}
}
| |
// Copyright (c) 2006, Gustavo Franco
// Email: gustavo_franco@hotmail.com
// 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.
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
// KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR
// PURPOSE. IT CAN BE DISTRIBUTED FREE OF CHARGE AS LONG AS THIS HEADER
// REMAINS UNCHANGED.
using System;
using System.IO;
using System.Text;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Drawing.IconLib.Exceptions;
using System.Drawing.Imaging;
using System.Collections;
namespace System.Drawing.IconLib.EncodingFormats
{
[Author("Franco, Gustavo")]
internal class PEFormat : ILibraryFormat
{
#region Variables Declaration
private static List<string> mIconsIDs;
#endregion
#region Methods
public bool IsRecognizedFormat(Stream stream)
{
stream.Position = 0;
try
{
// Has a valid MS-DOS header?
IMAGE_DOS_HEADER dos_header = new IMAGE_DOS_HEADER(stream);
if (dos_header.e_magic != (int) HeaderSignatures.IMAGE_DOS_SIGNATURE) //MZ
return false;
//Lets position over the "PE" header
stream.Seek(dos_header.e_lfanew, SeekOrigin.Begin);
//Lets read the NE header
IMAGE_NT_HEADERS nt_header = new IMAGE_NT_HEADERS(stream);
if (nt_header.Signature != (int) HeaderSignatures.IMAGE_NT_SIGNATURE) //PE
return false;
return true;
}
catch(Exception){}
return false;
}
public unsafe MultiIcon Load(Stream stream)
{
// LoadLibraryEx only can load files from File System, lets create a tmp file
string tmpFile = null;
IntPtr hLib = IntPtr.Zero;
try
{
stream.Position = 0;
// Find a tmp file where to dump the DLL stream, later we will remove this file
tmpFile = Path.GetTempFileName();
FileStream fs = new FileStream(tmpFile, FileMode.Create, FileAccess.Write);
byte[] buffer = new byte[stream.Length];
stream.Read(buffer, 0, buffer.Length);
fs.Write(buffer, 0, buffer.Length);
fs.Close();
hLib = Win32.LoadLibraryEx(tmpFile, IntPtr.Zero, LoadLibraryFlags.LOAD_LIBRARY_AS_DATAFILE);
if (hLib == IntPtr.Zero)
throw new InvalidFileException();
List<string> iconsIDs;
lock (typeof(PEFormat))
{
mIconsIDs = new List<string>();
bool bResult = Win32.EnumResourceNames(hLib, (IntPtr) ResourceType.RT_GROUP_ICON, new Win32.EnumResNameProc(EnumResNameProc), IntPtr.Zero);
if (bResult == false)
{
// No Resources in this file
}
iconsIDs = new List<string>(mIconsIDs);
}
MultiIcon multiIcon = new MultiIcon();
for(int index=0; index<iconsIDs.Count; index++)
{
string id = iconsIDs[index];
IntPtr hRsrc = IntPtr.Zero;
if (Win32.IS_INTRESOURCE(id))
hRsrc = Win32.FindResource(hLib, int.Parse(id), (IntPtr) ResourceType.RT_GROUP_ICON);
else
hRsrc = Win32.FindResource(hLib, id, (IntPtr) ResourceType.RT_GROUP_ICON);
if (hRsrc == IntPtr.Zero)
throw new InvalidFileException();
IntPtr hGlobal = Win32.LoadResource(hLib, hRsrc);
if (hGlobal == IntPtr.Zero)
throw new InvalidFileException();
MEMICONDIR* pDirectory = (MEMICONDIR*) Win32.LockResource(hGlobal);
if (pDirectory->wCount != 0)
{
MEMICONDIRENTRY* pEntry = &(pDirectory->arEntries);
SingleIcon singleIcon = new SingleIcon(id);
for(int i=0;i<pDirectory->wCount; i++)
{
IntPtr hIconInfo = Win32.FindResource(hLib, (IntPtr) pEntry[i].wId, (IntPtr) ResourceType.RT_ICON);
if (hIconInfo == IntPtr.Zero)
throw new InvalidFileException();
IntPtr hIconRes = Win32.LoadResource(hLib, hIconInfo);
if (hIconRes == IntPtr.Zero)
throw new InvalidFileException();
IntPtr dibBits = Win32.LockResource(hIconRes);
if (dibBits == IntPtr.Zero)
throw new InvalidFileException();
buffer = new byte[Win32.SizeofResource(hLib, hIconInfo)];
Marshal.Copy(dibBits, buffer, 0, buffer.Length);
MemoryStream ms = new MemoryStream(buffer);
IconImage iconImage = new IconImage(ms, buffer.Length);
singleIcon.Add(iconImage);
}
multiIcon.Add(singleIcon);
}
}
// If everything went well then lets return the multiIcon.
return multiIcon;
}
catch(Exception)
{
throw new InvalidFileException();
}
finally
{
if (hLib != null)
Win32.FreeLibrary(hLib);
if (tmpFile != null)
File.Delete(tmpFile);
}
}
public unsafe void Save(MultiIcon multiIcon, Stream stream)
{
throw new NotImplementedException("DLL Icon Saving not implemented");
/*// LoadLibraryEx only can load files from File System, lets create a tmp file
string tmpFile = null;
IntPtr hLib = IntPtr.Zero;
MemoryStream ms;
bool bResult;
try
{
stream.Position = 0;
// Find a tmp file where to dump the DLL stream, later we will remove this file
tmpFile = Path.GetTempFileName();
FileStream fs = new FileStream(tmpFile, FileMode.Create, FileAccess.Write);
byte[] buffer = Resource.EmptyDll;
stream.Read(buffer, 0, buffer.Length);
fs.Write(buffer, 0, buffer.Length);
fs.Close();
// Begin the injection process
IntPtr updPtr = Win32.BeginUpdateResource(tmpFile, false);
if (updPtr == IntPtr.Zero)
throw new InvalidFileException();
ushort iconIndex = 1;
foreach(SingleIcon singleIcon in multiIcon)
{
// Lets scan all groups
GRPICONDIR grpIconDir = GRPICONDIR.Initalizated;
grpIconDir.idCount = (ushort) singleIcon.Count;
grpIconDir.idEntries = new GRPICONDIRENTRY[grpIconDir.idCount];
for(int i=0;i<singleIcon.Count; i++)
{
// Inside every Icon let update every image format
IconImage iconImage = singleIcon[i];
grpIconDir.idEntries[i] = iconImage.GRPICONDIRENTRY;
grpIconDir.idEntries[i].nID = iconIndex;
// Buffer creation with the same size of the icon to optimize write call
ms = new MemoryStream((int) grpIconDir.idEntries[i].dwBytesInRes);
iconImage.Write(ms);
buffer = ms.GetBuffer();
// Update resource but it doesn't write to disk yet
bResult = Win32.UpdateResource(updPtr, (int) ResourceType.RT_ICON, iconIndex, 0, buffer, (uint) ms.Length);
iconIndex++;
// For some reason Windows will fail if there are many calls to update resource and no call to endUpdateResource
// It is like there some internal buffer that gets full, after that all calls fail.
// This workaround will save the changes every 70 icons, for big files this slow the saving process significantly
// but I didn't find a way to make EndUpdateResource works without save frequently
if ((iconIndex % 70) == 0)
{
bResult = Win32.EndUpdateResource(updPtr, false);
updPtr = Win32.BeginUpdateResource(tmpFile, false);
if (updPtr == IntPtr.Zero)
throw new InvalidFileException();
}
}
// Buffer creation with the same size of the group to optimize write call
ms = new MemoryStream(grpIconDir.GroupDirSize);
grpIconDir.Write(ms);
buffer = ms.GetBuffer();
int id;
if (int.TryParse(singleIcon.Name, out id))
{
// Write id as an integer
bResult = Win32.UpdateResource(updPtr, (int) ResourceType.RT_GROUP_ICON, (IntPtr) id, 0, buffer, (uint) ms.Length);
}
else
{
// Write id as string
IntPtr pName = Marshal.StringToHGlobalAnsi(singleIcon.Name.ToUpper());
bResult = Win32.UpdateResource(updPtr, (int) ResourceType.RT_GROUP_ICON, pName, 0, buffer, (uint) ms.Length);
Marshal.FreeHGlobal(pName);
}
}
// Last call to update the file with the rest not that was not write before
bResult = Win32.EndUpdateResource(updPtr, false);
// Because Windows Resource functions requiere a filepath, and we need to return an string then lets open
// the temporary file and dump it to the stream received as parameter.
fs = new FileStream(tmpFile, FileMode.Open, FileAccess.Read);
buffer = new byte[fs.Length];
fs.Read(buffer, 0, buffer.Length);
stream.Write(buffer, 0, buffer.Length);
fs.Close();
}
catch(Exception)
{
throw new InvalidFileException();
}
finally
{
if (hLib != null)
Win32.FreeLibrary(hLib);
if (tmpFile != null)
File.Delete(tmpFile);
}*/
}
#endregion
#region Private Methods
private static unsafe bool EnumResNameProc(IntPtr hModule, IntPtr pType, IntPtr pName, IntPtr param)
{
if (Win32.IS_INTRESOURCE(pName))
{
mIconsIDs.Add(pName.ToString());
}
else
{
mIconsIDs.Add(Marshal.PtrToStringUni(pName));
}
return true;
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
/// <summary>
/// char.IsDigit(string, int)
/// Indicates whether the character at the specified position in a specified string is categorized
/// as a decimal digit character.
/// </summary>
public class CharIsDigit
{
private const int c_MIN_STR_LEN = 2;
private const int c_MAX_STR_LEN = 256;
private static readonly char[] r_decimalDigits =
{
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'
};
public static int Main()
{
CharIsDigit testObj = new CharIsDigit();
TestLibrary.TestFramework.BeginTestCase("for method: char.IsDigit(string, int)");
if(testObj.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
TestLibrary.TestFramework.LogInformation("[Negaitive]");
retVal = NegTest1() && retVal;
retVal = NegTest2() && retVal;
retVal = NegTest3() && retVal;
return retVal;
}
#region Positive tests
public bool PosTest1()
{
//Generate the character for validate
int index = TestLibrary.Generator.GetInt32(-55) % r_decimalDigits.Length;
char ch = r_decimalDigits[index];
return this.DoTest("PosTest1: Random decimal digit character (0-9).",
"P001", "001", "002", ch,
true);
}
public bool PosTest2()
{
//Generate a non character for validate
char ch = TestLibrary.Generator.GetCharLetter(-55);
return this.DoTest("PosTest2: Non decimal digit character.",
"P002", "003", "004", ch,
false);
}
#endregion
#region Helper method for positive tests
private bool DoTest(string testDesc,
string testId,
string errorNum1,
string errorNum2,
char ch,
bool expectedResult)
{
bool retVal = true;
string errorDesc;
TestLibrary.TestFramework.BeginScenario(testDesc);
try
{
string str = new string(ch, 1);
bool actualResult = char.IsDigit(str, 0);
if (expectedResult != actualResult)
{
if (expectedResult)
{
errorDesc = string.Format("Character \\u{0:x} should belong to decimal digit characters.", (int)ch);
}
else
{
errorDesc = string.Format("Character \\u{0:x} does not belong to decimal digit characters.", (int)ch);
}
TestLibrary.TestFramework.LogError(errorNum1+ " TestId-" + testId, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
errorDesc = "Unexpected exception: " + e;
errorDesc += string.Format("\nCharacter is \\u{0:x}", (int)ch);
TestLibrary.TestFramework.LogError(errorNum2 + " TestId-" + testId, errorDesc);
retVal = false;
}
return retVal;
}
#endregion
#region Negative tests
//ArgumentNullException
public bool NegTest1()
{
bool retVal = true;
const string c_TEST_ID = "N001";
const string c_TEST_DESC = "NegTest1: String is a null reference (Nothing in Visual Basic).";
string errorDesc;
int index = 0;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
index = TestLibrary.Generator.GetInt32(-55);
char.IsDigit(null, index);
errorDesc = "ArgumentNullException is not thrown as expected, index is " + index;
TestLibrary.TestFramework.LogError("005" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
catch (ArgumentNullException)
{
}
catch (Exception e)
{
errorDesc = "Unexpected exception: " + e + "\n Index is " + index;
TestLibrary.TestFramework.LogError("006" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
return retVal;
}
//ArgumentOutOfRangeException
public bool NegTest2()
{
bool retVal = true;
const string c_TEST_ID = "N002";
const string c_TEST_DESC = "NegTest2: Index is too great.";
string errorDesc;
string str = string.Empty;
int index = 0;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
str = TestLibrary.Generator.GetString(-55, false, c_MIN_STR_LEN, c_MAX_STR_LEN);
index = str.Length + TestLibrary.Generator.GetInt16(-55);
index = str.Length;
char.IsDigit(str, index);
errorDesc = "ArgumentOutOfRangeException is not thrown as expected";
TestLibrary.TestFramework.LogError("007" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
catch (ArgumentOutOfRangeException)
{
}
catch (Exception e)
{
errorDesc = "Unexpected exception: " + e;
errorDesc += string.Format("\nThe character is \\u{0:x}", str[index]);
TestLibrary.TestFramework.LogError("008" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
return retVal;
}
public bool NegTest3()
{
bool retVal = true;
const string c_TEST_ID = "N003";
const string c_TEST_DESC = "NegTest3: Index is a negative value";
string errorDesc;
string str = string.Empty;
int index = 0;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
str = TestLibrary.Generator.GetString(-55, false, c_MIN_STR_LEN, c_MAX_STR_LEN);
index = -1 * (TestLibrary.Generator.GetInt16(-55));
char.IsDigit(str, index);
errorDesc = "ArgumentOutOfRangeException is not thrown as expected";
TestLibrary.TestFramework.LogError("009" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
catch (ArgumentOutOfRangeException)
{
}
catch (Exception e)
{
errorDesc = "Unexpected exception: " + e;
errorDesc += string.Format("\nThe character is \\u{0:x}", str[index]);
TestLibrary.TestFramework.LogError("010" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
return retVal;
}
#endregion
}
|