context
stringlengths
2.52k
185k
gt
stringclasses
1 value
using System; using System.Diagnostics; using System.Net; using System.Threading; using NUnit.Framework; using ServiceStack.Text; namespace RazorRockstars.Console { [TestFixture] public class RazorRockstars_EmbeddedFilesTests { AppHost appHost; Stopwatch startedAt; [TestFixtureSetUp] public void TestFixtureSetUp() { startedAt = Stopwatch.StartNew(); appHost = new AppHost(); appHost.Init(); appHost.Start("http://*:1337/"); } [TestFixtureTearDown] public void TestFixtureTearDown() { "Time Taken {0}ms".Fmt(startedAt.ElapsedMilliseconds).Print(); appHost.Dispose(); } [Ignore("Debug Run")][Test] public void RunFor10Mins() { Thread.Sleep(TimeSpan.FromMinutes(10)); } public static string AcceptContentType = "*/*"; public void Assert200(string url, params string[] containsItems) { url.Print(); var text = url.GetStringFromUrl(AcceptContentType, r => { if (r.StatusCode != HttpStatusCode.OK) Assert.Fail(url + " did not return 200 OK"); }); foreach (var item in containsItems) { if (!text.Contains(item)) { Assert.Fail(item + " was not found in " + url); } } } public void Assert200UrlContentType(string url, string contentType) { url.Print(); url.GetStringFromUrl(AcceptContentType, r => { if (r.StatusCode != HttpStatusCode.OK) Assert.Fail(url + " did not return 200 OK: " + r.StatusCode); if (!r.ContentType.StartsWith(contentType)) Assert.Fail(url + " did not return contentType " + contentType); }); } public static string Host = "http://localhost:1337"; static string ViewRockstars = "<!--view:Rockstars.cshtml-->"; static string ViewRockstars2 = "<!--view:Rockstars2.cshtml-->"; static string ViewRockstars3 = "<!--view:Rockstars3.cshtml-->"; static string ViewRockstarsMark = "<!--view:RockstarsMark.md-->"; static string ViewNoModelNoController = "<!--view:NoModelNoController.cshtml-->"; static string ViewTypedModelNoController = "<!--view:TypedModelNoController.cshtml-->"; static string ViewPage1 = "<!--view:Page1.cshtml-->"; static string ViewPage2 = "<!--view:Page2.cshtml-->"; static string ViewPage3 = "<!--view:Page3.cshtml-->"; static string ViewPage4 = "<!--view:Page4.cshtml-->"; static string ViewMarkdownRootPage = "<!--view:MRootPage.md-->"; static string ViewMPage1 = "<!--view:MPage1.md-->"; static string ViewMPage2 = "<!--view:MPage2.md-->"; static string ViewMPage3 = "<!--view:MPage3.md-->"; static string ViewMPage4 = "<!--view:MPage4.md-->"; static string ViewRazorPartial = "<!--view:RazorPartial.cshtml-->"; static string ViewMarkdownPartial = "<!--view:MarkdownPartial.md-->"; static string ViewRazorPartialModel = "<!--view:RazorPartialModel.cshtml-->"; static string View_Default = "<!--view:default.cshtml-->"; static string View_Pages_Default = "<!--view:Pages/default.cshtml-->"; static string View_Pages_Dir_Default = "<!--view:Pages/Dir/default.cshtml-->"; static string ViewM_Pages_Dir2_Default = "<!--view:Pages/Dir2/default.md-->"; static string Template_Layout = "<!--template:_Layout.cshtml-->"; static string Template_Pages_Layout = "<!--template:Pages/_Layout.cshtml-->"; static string Template_Pages_Dir_Layout = "<!--template:Pages/Dir/_Layout.cshtml-->"; static string Template_SimpleLayout = "<!--template:SimpleLayout.cshtml-->"; static string Template_SimpleLayout2 = "<!--template:SimpleLayout2.cshtml-->"; static string Template_HtmlReport = "<!--template:HtmlReport.cshtml-->"; static string TemplateM_Layout = "<!--template:_Layout.shtml-->"; static string TemplateM_Pages_Layout = "<!--template:Pages/_Layout.shtml-->"; static string TemplateM_Pages_Dir_Layout = "<!--template:Pages/Dir/_Layout.shtml-->"; static string TemplateM_HtmlReport = "<!--template:HtmlReport.shtml-->"; [Test] public void Can_get_page_with_default_view_and_template() { Assert200(Host + "/rockstars", ViewRockstars, Template_HtmlReport); } [Test] public void Can_get_page_with_alt_view_and_default_template() { Assert200(Host + "/rockstars?View=Rockstars2", ViewRockstars2, Template_Layout); } [Test] public void Can_get_page_with_alt_viewengine_view_and_default_template() { Assert200(Host + "/rockstars?View=RockstarsMark", ViewRockstarsMark, TemplateM_HtmlReport); } [Test] public void Can_get_page_with_default_view_and_alt_template() { Assert200(Host + "/rockstars?Template=SimpleLayout", ViewRockstars, Template_SimpleLayout); } [Test] public void Can_get_page_with_alt_viewengine_view_and_alt_razor_template() { Assert200(Host + "/rockstars?View=Rockstars2&Template=SimpleLayout2", ViewRockstars2, Template_SimpleLayout2); } [Test] public void Can_get_razor_content_pages() { Assert200(Host + "/TypedModelNoController", ViewTypedModelNoController, Template_SimpleLayout, ViewRazorPartial, ViewMarkdownPartial, ViewRazorPartialModel); Assert200(Host + "/nomodelnocontroller", ViewNoModelNoController, Template_SimpleLayout, ViewRazorPartial, ViewMarkdownPartial); Assert200(Host + "/pages/page1", ViewPage1, Template_Pages_Layout, ViewRazorPartialModel, ViewMarkdownPartial); Assert200(Host + "/pages/dir/Page2", ViewPage2, Template_Pages_Dir_Layout, ViewRazorPartial, ViewMarkdownPartial); Assert200(Host + "/pages/dir2/Page3", ViewPage3, Template_Pages_Layout, ViewRazorPartial, ViewMarkdownPartial); Assert200(Host + "/pages/dir2/Page4", ViewPage4, Template_HtmlReport, ViewRazorPartial, ViewMarkdownPartial); } [Test] public void Can_get_razor_content_pages_with_partials() { Assert200(Host + "/pages/dir2/Page4", ViewPage4, Template_HtmlReport, ViewRazorPartial, ViewMarkdownPartial, ViewMPage3); } [Test] public void Can_get_markdown_content_pages() { Assert200(Host + "/MRootPage", ViewMarkdownRootPage, TemplateM_Layout); Assert200(Host + "/pages/mpage1", ViewMPage1, TemplateM_Pages_Layout); Assert200(Host + "/pages/dir/mPage2", ViewMPage2, TemplateM_Pages_Dir_Layout); } [Test] public void Redirects_when_trying_to_get_razor_page_with_extension() { Assert200(Host + "/pages/dir2/Page4.cshtml", ViewPage4, Template_HtmlReport, ViewRazorPartial, ViewMarkdownPartial, ViewMPage3); } [Test] public void Redirects_when_trying_to_get_markdown_page_with_extension() { Assert200(Host + "/pages/mpage1.md", ViewMPage1, TemplateM_Pages_Layout); } [Test] public void Can_get_default_razor_pages() { Assert200(Host + "/", View_Default, Template_SimpleLayout, ViewRazorPartial, ViewMarkdownPartial, ViewRazorPartialModel); Assert200(Host + "/Pages/", View_Pages_Default, Template_Pages_Layout, ViewRazorPartial, ViewMarkdownPartial, ViewRazorPartialModel); Assert200(Host + "/Pages/Dir/", View_Pages_Dir_Default, Template_SimpleLayout, ViewRazorPartial, ViewMarkdownPartial, ViewRazorPartialModel); } [Test] public void Can_get_default_markdown_pages() { Assert200(Host + "/Pages/Dir2/", ViewM_Pages_Dir2_Default, TemplateM_Pages_Layout); } [Test] //Good for testing adhoc compilation public void Can_get_last_view_template_compiled() { Assert200(Host + "/rockstars?View=Rockstars3", ViewRockstars3, Template_SimpleLayout2); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Xml.Linq; using System.Xml.Serialization; using Sekhmet.Serialization.Utility; namespace Sekhmet.Serialization.XmlSerializerSupport { /// <summary> /// Mapper used for collections. /// </summary> /// <remarks> /// MapForDeserialization: assumes that target contains one member that when SetValue is called adds an element to /// the collection it represents. /// /// MapForSerialization: assumes that the source contains one member for each element in the collection it represents. /// Also each member should have the attributes associated with the member containing the /// collection. These are needed because they might contain information about what to name /// the elements. /// /// Futhermore it only look at elements, not attributes of the source. /// </remarks> public class XmlSerializerCollectionMapper : IMapper { public IEnumerable<IMapping<XObject, IMemberContext>> MapForDeserialization(XElement source, IMemberContext target, IAdviceRequester adviceRequester) { var targetObject = target.GetValue(); if (targetObject == null) throw new ArgumentException("Target should have had it value set to a collection at this point.", "target"); var elementNames = GetElementNames(target); return source.Elements() .Where(e => elementNames.Contains(e.Name, CaseInsensitiveXNameComparer.Instance)) .Select(elem => new Mapping<XObject, IMemberContext>(elem, targetObject.Members.Single())) .ToList(); } public IEnumerable<IMapping<IMemberContext, XObject>> MapForSerialization(IMemberContext source, XElement target, IAdviceRequester adviceRequester) { if (source == null) throw new ArgumentNullException("source"); var elementType = GetElementType(source.GetActualType()); if (elementType == null) throw new ArgumentException("Collection mapper has been invoked for target that is not a known list type: '" + source.GetActualType() + "'.", "target"); var sourceObject = source.GetValue(); if (sourceObject == null) return Enumerable.Empty<IMapping<IMemberContext, XObject>>(); return sourceObject.Members .Select(CreateMapping); } private static Mapping<IMemberContext, XElement> CreateMapping(IMemberContext m) { var elem = new XElement(NameElement(m)); return new Mapping<IMemberContext, XElement>(m, elem); } private static IEnumerable<XName> GetElementNames(IMemberContext target) { return GetElementsNamesFromElementAttributes(target) ?? GetElementNamesFromXmlArrayItemAttributes(target) ?? GetElementNamesFromElementType(target); } private static IEnumerable<XName> GetElementNamesFromElementType(IMemberContext target) { var elementType = GetElementType(target.ContractType); return new[] { elementType.Name.SafeToXName() }; } private static IEnumerable<XName> GetElementNamesFromXmlArrayItemAttributes(IMemberContext target) { var arrayItemNames = target.Attributes .OfType<XmlArrayItemAttribute>() .Select(a => (XName)a.ElementName) .Where(n => n != null) .ToList(); if (!arrayItemNames.Any()) return null; return arrayItemNames; } private static Type GetElementType(Type type) { var enumInterface = type.GetInterface("System.Collections.Generic.IEnumerable`1"); if (enumInterface != null) return enumInterface.GetGenericArguments()[0]; if (type.IsSubTypeOf<IEnumerable>()) return typeof(object); return null; } private static IEnumerable<XName> GetElementsNamesFromElementAttributes(IMemberContext target) { var elemAttrs = target.Attributes .OfType<XmlElementAttribute>() .ToList(); if (!elemAttrs.Any()) return null; var elemNames = elemAttrs .Select(a => (XName)a.ElementName) .Where(n => n != null) .ToList(); if (!elemAttrs.Any()) return new XName[] { target.Name }; return elemNames; } private static XName NameElement(IMemberContext memberContext) { return NameElementFromElementAttributeExactType(memberContext) ?? NameElementFromElementAttributeInstanceOfType(memberContext) ?? NameElementFromElementAttributeNoType(memberContext) ?? NameElementFromArrayItemAttributeExactType(memberContext) ?? NameElementFromArrayItemAttributeInstanceOfType(memberContext) ?? NameElementFromArrayItemAttributeNoType(memberContext) ?? NameElementFromActualType(memberContext) ?? NameElementFromContractType(memberContext); } private static XName NameElementFromActualType(IMemberContext memberContext) { var actualType = memberContext.GetActualType(); if (actualType == null) return null; return actualType.Name.SafeToXName(); } private static string NameElementFromArrayItemAttributeExactType(IMemberContext memberContext) { return memberContext.Attributes.OfType<XmlArrayItemAttribute>() .Where(a => a.Type == memberContext.GetActualType()) .Where(a => !string.IsNullOrWhiteSpace(a.ElementName)) .Select(a => a.ElementName) .FirstOrDefault(); } private static string NameElementFromArrayItemAttributeInstanceOfType(IMemberContext memberContext) { return memberContext.Attributes.OfType<XmlArrayItemAttribute>() .Where(a => a.Type != null && memberContext.GetActualType().IsSubTypeOf(a.Type)) .Select(a => a.ElementName) .FirstOrDefault(); } private static string NameElementFromArrayItemAttributeNoType(IMemberContext memberContext) { return memberContext.Attributes.OfType<XmlArrayItemAttribute>() .Where(a => a.Type == null) .Where(a => !string.IsNullOrWhiteSpace(a.ElementName)) .Select(a => a.ElementName) .FirstOrDefault(); } private static XName NameElementFromContractType(IMemberContext memberContext) { return memberContext.ContractType.Name.SafeToXName(); } private static string NameElementFromElementAttributeExactType(IMemberContext memberContext) { return memberContext.Attributes.OfType<XmlElementAttribute>() .Where(a => a.Type == memberContext.GetActualType()) .Where(a => !string.IsNullOrWhiteSpace(a.ElementName)) .Select(a => a.ElementName) .FirstOrDefault(); } private static string NameElementFromElementAttributeInstanceOfType(IMemberContext memberContext) { return memberContext.Attributes.OfType<XmlElementAttribute>() .Where(a => a.Type != null && memberContext.GetActualType().IsSubTypeOf(a.Type)) .Select(a => a.ElementName) .FirstOrDefault(); } private static string NameElementFromElementAttributeNoType(IMemberContext memberContext) { return memberContext.Attributes.OfType<XmlElementAttribute>() .Where(a => a.Type == null) .Where(a => !string.IsNullOrWhiteSpace(a.ElementName)) .Select(a => a.ElementName) .FirstOrDefault(); } } }
// 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, // MERCHANTABLITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing // permissions and limitations under the License. using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Runtime.ExceptionServices; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Input; using Microsoft.PythonTools.Analysis; using Microsoft.PythonTools.Infrastructure; using Microsoft.PythonTools.Interpreter; using Resources = Microsoft.PythonTools.EnvironmentsList.Properties.Resources; namespace Microsoft.PythonTools.EnvironmentsList { internal partial class DBExtension : UserControl { public static readonly RoutedCommand StartRefreshDB = new RoutedCommand(); private readonly DBExtensionProvider _provider; private readonly CollectionViewSource _sortedPackages; public DBExtension(DBExtensionProvider provider) { _provider = provider; DataContextChanged += DBExtension_DataContextChanged; InitializeComponent(); // Set the default sort order _sortedPackages = (CollectionViewSource)_packageList.FindResource("SortedPackages"); _sortedPackages.SortDescriptions.Add(new SortDescription("IsUpToDate", ListSortDirection.Ascending)); _sortedPackages.SortDescriptions.Add(new SortDescription("FullName", ListSortDirection.Ascending)); } private void DBExtension_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e) { var view = e.NewValue as EnvironmentView; if (view != null) { var current = Subcontext.DataContext as DBEnvironmentView; if (current == null || current.EnvironmentView != view) { if (current != null) { current.Dispose(); } Subcontext.DataContext = new DBEnvironmentView(view, _provider); } } } } sealed class DBEnvironmentView : DependencyObject, IDisposable { private readonly EnvironmentView _view; private readonly DBExtensionProvider _provider; private ObservableCollection<DBPackageView> _packages; private readonly object _packagesLock = new object(); internal DBEnvironmentView( EnvironmentView view, DBExtensionProvider provider ) { _view = view; _provider = provider; _provider.ModulesChanged += Provider_ModulesChanged; } public void Dispose() { _provider.ModulesChanged -= Provider_ModulesChanged; } public EnvironmentView EnvironmentView { get { return _view; } } public ObservableCollection<DBPackageView> Packages { get { if (_packages == null) { lock (_packagesLock) { _packages = _packages ?? new ObservableCollection<DBPackageView>(); RefreshPackages(); } } return _packages; } } private async void RefreshPackages() { try { await RefreshPackagesAsync(); } catch (OperationCanceledException) { } catch (Exception ex) { if (ex.IsCriticalException()) { throw; } ToolWindow.SendUnhandledException(_provider.WpfObject, ExceptionDispatchInfo.Capture(ex)); } } private async Task RefreshPackagesAsync() { IEnumerable<DBPackageView> views; try { views = DBPackageView.FromModuleList( await _provider.EnumerateAllModules(), await _provider.EnumerateStdLibModules(), _provider.Factory ).ToList(); } catch (InvalidOperationException) { // Configuration is invalid, so don't display any packages return; } if (_packages == null) { lock (_packagesLock) { _packages = _packages ?? new ObservableCollection<DBPackageView>(); } } await Dispatcher.InvokeAsync(() => { lock (_packagesLock) { _packages.Merge( views, DBPackageViewComparer.Instance, DBPackageViewComparer.Instance ); } }); } private async void Provider_ModulesChanged(object sender, EventArgs e) { try { await RefreshPackagesAsync(); } catch (OperationCanceledException) { } catch (Exception ex) { if (ex.IsCriticalException()) { throw; } ToolWindow.SendUnhandledException(_provider.WpfObject, ExceptionDispatchInfo.Capture(ex)); } } } class DBPackageViewComparer : IEqualityComparer<DBPackageView>, IComparer<DBPackageView> { public static readonly DBPackageViewComparer Instance = new DBPackageViewComparer(); public bool Equals(DBPackageView x, DBPackageView y) { if (x != null && y != null) { return StringComparer.OrdinalIgnoreCase.Equals(x.FullName, y.FullName); } return x == y; } public int GetHashCode(DBPackageView obj) { if (obj != null) { return StringComparer.OrdinalIgnoreCase.GetHashCode(obj.FullName); } return 0; } public int Compare(DBPackageView x, DBPackageView y) { if (x != null && y != null) { return StringComparer.CurrentCultureIgnoreCase.Compare(x.FullName, y.FullName); } else if (x == null && y == null) { return 0; } else { return x == null ? 1 : -1; } } } internal sealed class DBPackageView { private readonly string _fullname; private readonly string _name; private bool _isUpToDate; private int _moduleCount; public DBPackageView(string fullname) { _fullname = fullname; _name = _fullname.Substring(_fullname.LastIndexOf('.') + 1); _isUpToDate = true; } public static IEnumerable<DBPackageView> FromModuleList( IList<string> modules, IList<string> stdLibModules, IPythonInterpreterFactoryWithDatabase factory ) { var stdLib = new HashSet<string>(stdLibModules, StringComparer.Ordinal); var stdLibPackage = new DBPackageView("(Standard Library)"); yield return stdLibPackage; #if DEBUG var seenPackages = new HashSet<string>(StringComparer.Ordinal); #endif HashSet<string> knownModules = null; bool areKnownModulesUpToDate = false; if (!factory.IsCurrent) { var factory2 = factory as IPythonInterpreterFactoryWithDatabase2; if (factory2 == null) { knownModules = new HashSet<string>(Regex.Matches( factory.GetIsCurrentReason(CultureInfo.InvariantCulture), @"\b[\w\d\.]+\b" ).Cast<Match>().Select(m => m.Value), StringComparer.Ordinal ); areKnownModulesUpToDate = false; } else { knownModules = new HashSet<string>(factory2.GetUpToDateModules(), StringComparer.Ordinal); areKnownModulesUpToDate = true; } } for (int i = 0; i < modules.Count; ) { if (stdLib.Contains(modules[i])) { stdLibPackage._isUpToDate = knownModules == null || knownModules.Contains(modules[i]) == areKnownModulesUpToDate; ; stdLibPackage._moduleCount += 1; i += 1; continue; } #if DEBUG Debug.Assert(seenPackages.Add(modules[i])); #endif var package = new DBPackageView(modules[i]); package._isUpToDate = knownModules == null || knownModules.Contains(modules[i]) == areKnownModulesUpToDate; package._moduleCount = 1; var dotName = package._fullname + "."; for (++i; i < modules.Count && modules[i].StartsWith(dotName, StringComparison.Ordinal); ++i) { package._isUpToDate &= knownModules == null || knownModules.Contains(modules[i]) == areKnownModulesUpToDate; package._moduleCount += 1; } yield return package; } } public string FullName { get { return _fullname; } } public string Name { get { return _name; } } public int TotalModules { get { return _moduleCount; } } /// <summary> /// '1' if the package is up to date; otherwise '0'. Numbers are used /// instead of bool to make it easier to sort by status. /// </summary> public int IsUpToDate { get { return _isUpToDate ? 1 : 0; } } } public sealed class DBExtensionProvider : IEnvironmentViewExtension { private readonly PythonInterpreterFactoryWithDatabase _factory; private FrameworkElement _wpfObject; private List<string> _modules; private List<string> _stdLibModules; public DBExtensionProvider(PythonInterpreterFactoryWithDatabase factory) { _factory = factory; _factory.IsCurrentChanged += Factory_IsCurrentChanged; } private void Factory_IsCurrentChanged(object sender, EventArgs e) { _modules = null; var evt = ModulesChanged; if (evt != null) { evt(this, EventArgs.Empty); } } public int SortPriority { get { return -7; } } public string LocalizedDisplayName { get { return Resources.DBExtensionDisplayName; } } public object HelpContent { get { return Resources.DBExtensionHelpContent; } } public FrameworkElement WpfObject { get { if (_wpfObject == null) { _wpfObject = new DBExtension(this); } return _wpfObject; } } public event EventHandler ModulesChanged; public IPythonInterpreterFactoryWithDatabase Factory { get { return _factory; } } private void AbortOnInvalidConfiguration() { if (_factory == null || _factory.Configuration == null || string.IsNullOrEmpty(_factory.Configuration.InterpreterPath)) { throw new InvalidOperationException(Resources.MisconfiguredEnvironment); } } private static IEnumerable<string> GetParentModuleNames(string fullname) { var sb = new StringBuilder(); foreach (var bit in fullname.Split('.')) { sb.Append(bit); yield return sb.ToString(); sb.Append('.'); } } public async Task<List<string>> EnumerateStdLibModules(bool refresh = false) { if (_stdLibModules == null || refresh) { await EnumerateAllModules(true); Debug.Assert(_stdLibModules != null); } return _stdLibModules; } public async Task<List<string>> EnumerateAllModules(bool refresh = false) { AbortOnInvalidConfiguration(); if (_modules == null || refresh) { var stdLibPaths = new HashSet<string>(StringComparer.OrdinalIgnoreCase); stdLibPaths.Add(_factory.Configuration.LibraryPath); stdLibPaths.Add(Path.Combine(_factory.Configuration.PrefixPath, "DLLs")); stdLibPaths.Add(Path.GetDirectoryName(_factory.Configuration.InterpreterPath)); var results = await Task.Run(() => { List<PythonLibraryPath> paths; if (_factory.AssumeSimpleLibraryLayout) { paths = PythonTypeDatabase.GetDefaultDatabaseSearchPaths(_factory.Configuration.LibraryPath); } else { paths = PythonTypeDatabase.GetCachedDatabaseSearchPaths(_factory.DatabasePath); if (paths == null) { paths = PythonTypeDatabase.GetUncachedDatabaseSearchPathsAsync( _factory.Configuration.InterpreterPath ).WaitAndUnwrapExceptions(); try { PythonTypeDatabase.WriteDatabaseSearchPaths(_factory.DatabasePath, paths); } catch (Exception ex) { if (ex.IsCriticalException()) { throw; } } } } var groups = PythonTypeDatabase.GetDatabaseExpectedModules( _factory.Configuration.Version, paths ).ToList(); var stdLibModules = groups[0].Select(mp => mp.ModuleName).ToList(); var modules = groups.SelectMany().Select(mp => mp.ModuleName).ToList(); stdLibModules.Sort(); modules.Sort(); for (int i = stdLibModules.Count - 1; i > 0; --i) { if (stdLibModules[i - 1] == stdLibModules[i]) { stdLibModules.RemoveAt(i); } } for (int i = modules.Count - 1; i > 0; --i) { if (modules[i - 1] == modules[i]) { modules.RemoveAt(i); } } return Tuple.Create(modules, stdLibModules); }); _modules = results.Item1; _stdLibModules = results.Item2; } return _modules; } } }
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ using System; using System.IO; using JavaScriptEngineSwitcher.Core; using Moq; using React.Exceptions; using React.RenderFunctions; using Xunit; namespace React.Tests.Core { public class ReactComponentTest { [Fact] public void RenderHtmlShouldThrowExceptionIfComponentDoesNotExist() { var environment = new Mock<IReactEnvironment>(); environment.Setup(x => x.Execute<bool>("typeof Foo !== 'undefined'")).Returns(false); var config = CreateDefaultConfigMock(); config.Setup(x => x.UseServerSideRendering).Returns(true); var reactIdGenerator = new Mock<IReactIdGenerator>(); var component = new ReactComponent(environment.Object, config.Object, reactIdGenerator.Object, "Foo", "container"); Assert.Throws<ReactInvalidComponentException>(() => { component.RenderHtml(); }); } [Fact] public void RenderHtmlShouldCallRenderComponent() { var environment = new Mock<IReactEnvironment>(); environment.Setup(x => x.Execute<bool>("typeof Foo !== 'undefined'")).Returns(true); var config = CreateDefaultConfigMock(); config.Setup(x => x.UseServerSideRendering).Returns(true); var reactIdGenerator = new Mock<IReactIdGenerator>(); var component = new ReactComponent(environment.Object, config.Object, reactIdGenerator.Object, "Foo", "container") { Props = new { hello = "World" } }; component.RenderHtml(); environment.Verify(x => x.Execute<string>(@"ReactDOMServer.renderToString(React.createElement(Foo, {""hello"":""World""}))")); } [Fact] public void RenderHtmlShouldWrapComponentInDiv() { var environment = new Mock<IReactEnvironment>(); environment.Setup(x => x.Execute<bool>("typeof Foo !== 'undefined'")).Returns(true); environment.Setup(x => x.Execute<string>(@"ReactDOMServer.renderToString(React.createElement(Foo, {""hello"":""World""}))")) .Returns("[HTML]"); var config = CreateDefaultConfigMock(); config.Setup(x => x.UseServerSideRendering).Returns(true); var reactIdGenerator = new Mock<IReactIdGenerator>(); var component = new ReactComponent(environment.Object, config.Object, reactIdGenerator.Object, "Foo", "container") { Props = new { hello = "World" } }; var result = component.RenderHtml(); Assert.Equal(@"<div id=""container"">[HTML]</div>", result); } [Fact] public void RenderHtmlShouldNotRenderComponentHtml() { var environment = new Mock<IReactEnvironment>(); environment.Setup(x => x.Execute<bool>("typeof Foo !== 'undefined'")).Returns(true); environment.Setup(x => x.Execute<string>(@"React.renderToString(React.createElement(Foo, {""hello"":""World""}))")) .Returns("[HTML]"); var config = CreateDefaultConfigMock(); var reactIdGenerator = new Mock<IReactIdGenerator>(); var component = new ReactComponent(environment.Object, config.Object, reactIdGenerator.Object, "Foo", "container") { Props = new { hello = "World" } }; var result = component.RenderHtml(renderContainerOnly: true); Assert.Equal(@"<div id=""container""></div>", result); environment.Verify(x => x.Execute(It.IsAny<string>()), Times.Never); } [Fact] public void RenderHtmlShouldNotRenderClientSideAttributes() { var environment = new Mock<IReactEnvironment>(); environment.Setup(x => x.Execute<bool>("typeof Foo !== 'undefined'")).Returns(true); var config = CreateDefaultConfigMock(); config.Setup(x => x.UseServerSideRendering).Returns(true); var reactIdGenerator = new Mock<IReactIdGenerator>(); var component = new ReactComponent(environment.Object, config.Object, reactIdGenerator.Object, "Foo", "container") { Props = new { hello = "World" } }; component.RenderHtml(renderServerOnly: true); environment.Verify(x => x.Execute<string>(@"ReactDOMServer.renderToStaticMarkup(React.createElement(Foo, {""hello"":""World""}))")); } [Fact] public void RenderHtmlShouldWrapComponentInCustomElement() { var config = CreateDefaultConfigMock(); config.Setup(x => x.UseServerSideRendering).Returns(true); var environment = new Mock<IReactEnvironment>(); environment.Setup(x => x.Execute<bool>("typeof Foo !== 'undefined'")).Returns(true); environment.Setup(x => x.Execute<string>(@"ReactDOMServer.renderToString(React.createElement(Foo, {""hello"":""World""}))")) .Returns("[HTML]"); var reactIdGenerator = new Mock<IReactIdGenerator>(); var component = new ReactComponent(environment.Object, config.Object, reactIdGenerator.Object, "Foo", "container") { Props = new { hello = "World" }, ContainerTag = "span" }; var result = component.RenderHtml(); Assert.Equal(@"<span id=""container"">[HTML]</span>", result); } [Fact] public void RenderHtmlShouldNotRenderComponentWhenContainerOnly() { var config = CreateDefaultConfigMock(); config.Setup(x => x.UseServerSideRendering).Returns(true); var environment = new Mock<IReactEnvironment>(); environment.Setup(x => x.Execute<bool>("typeof Foo !== 'undefined'")).Returns(true); environment.Setup(x => x.Execute<string>(@"ReactDOMServer.renderToString(React.createElement(Foo, {""hello"":""World""}))")) .Returns("[HTML]"); var reactIdGenerator = new Mock<IReactIdGenerator>(); var component = new ReactComponent(environment.Object, config.Object, reactIdGenerator.Object, "Foo", "container") { Props = new { hello = "World" }, ContainerTag = "span" }; var result = component.RenderHtml(true, false); Assert.Equal(@"<span id=""container""></span>", result); } [Fact] public void RenderHtmlShouldNotWrapComponentWhenServerSideOnly() { var config = CreateDefaultConfigMock(); config.Setup(x => x.UseServerSideRendering).Returns(true); var environment = new Mock<IReactEnvironment>(); environment.Setup(x => x.Execute<bool>("typeof Foo !== 'undefined'")).Returns(true); environment.Setup(x => x.Execute<string>(@"ReactDOMServer.renderToStaticMarkup(React.createElement(Foo, {""hello"":""World""}))")) .Returns("[HTML]"); var reactIdGenerator = new Mock<IReactIdGenerator>(); var component = new ReactComponent(environment.Object, config.Object, reactIdGenerator.Object, "Foo", "container") { Props = new { hello = "World" }, }; var result = component.RenderHtml(false, true); Assert.Equal(@"[HTML]", result); } [Fact] public void RenderHtmlShouldAddClassToElement() { var config = CreateDefaultConfigMock(); config.Setup(x => x.UseServerSideRendering).Returns(true); var environment = new Mock<IReactEnvironment>(); environment.Setup(x => x.Execute<bool>("typeof Foo !== 'undefined'")).Returns(true); environment.Setup(x => x.Execute<string>(@"ReactDOMServer.renderToString(React.createElement(Foo, {""hello"":""World""}))")) .Returns("[HTML]"); var reactIdGenerator = new Mock<IReactIdGenerator>(); var component = new ReactComponent(environment.Object, config.Object, reactIdGenerator.Object, "Foo", "container") { Props = new { hello = "World" }, ContainerClass = "test-class" }; var result = component.RenderHtml(); Assert.Equal(@"<div id=""container"" class=""test-class"">[HTML]</div>", result); } [Fact] public void RenderJavaScriptShouldCallRenderComponent() { var environment = new Mock<IReactEnvironment>(); var config = CreateDefaultConfigMock(); var reactIdGenerator = new Mock<IReactIdGenerator>(); var component = new ReactComponent(environment.Object, config.Object, reactIdGenerator.Object, "Foo", "container") { Props = new { hello = "World" } }; var result = component.RenderJavaScript(false); Assert.Equal( @"ReactDOM.hydrate(React.createElement(Foo, {""hello"":""World""}), document.getElementById(""container""))", result ); } [Fact] public void RenderJavaScriptShouldCallRenderComponentWithReactDOMRender() { var environment = new Mock<IReactEnvironment>(); var config = CreateDefaultConfigMock(); var reactIdGenerator = new Mock<IReactIdGenerator>(); var component = new ReactComponent(environment.Object, config.Object, reactIdGenerator.Object, "Foo", "container") { ClientOnly = true, Props = new { hello = "World" } }; var result = component.RenderJavaScript(false); Assert.Equal( @"ReactDOM.render(React.createElement(Foo, {""hello"":""World""}), document.getElementById(""container""))", result ); } [Fact] public void RenderJavaScriptShouldCallRenderComponentwithReactDOMHydrate() { var environment = new Mock<IReactEnvironment>(); var config = CreateDefaultConfigMock(); var reactIdGenerator = new Mock<IReactIdGenerator>(); var component = new ReactComponent(environment.Object, config.Object, reactIdGenerator.Object, "Foo", "container") { ClientOnly = false, Props = new { hello = "World" } }; var result = component.RenderJavaScript(false); Assert.Equal( @"ReactDOM.hydrate(React.createElement(Foo, {""hello"":""World""}), document.getElementById(""container""))", result ); } [Fact] public void RenderJavaScriptShouldCallRenderComponentWithReactDomRenderWhenSsrDisabled() { var environment = new Mock<IReactEnvironment>(); var config = CreateDefaultConfigMock(); config.SetupGet(x => x.UseServerSideRendering).Returns(false); var reactIdGenerator = new Mock<IReactIdGenerator>(); var component = new ReactComponent(environment.Object, config.Object, reactIdGenerator.Object, "Foo", "container") { ClientOnly = false, Props = new {hello = "World"} }; var result = component.RenderJavaScript(false); Assert.Equal( @"ReactDOM.render(React.createElement(Foo, {""hello"":""World""}), document.getElementById(""container""))", result ); } [Fact] public void RenderJavaScriptShouldHandleWaitForContentLoad() { var environment = new Mock<IReactEnvironment>(); var config = CreateDefaultConfigMock(); config.SetupGet(x => x.UseServerSideRendering).Returns(false); var reactIdGenerator = new Mock<IReactIdGenerator>(); var component = new ReactComponent(environment.Object, config.Object, reactIdGenerator.Object, "Foo", "container") { ClientOnly = false, Props = new {hello = "World"} }; using (var writer = new StringWriter()) { component.RenderJavaScript(writer, waitForDOMContentLoad: true); Assert.Equal( @"window.addEventListener('DOMContentLoaded', function() {ReactDOM.render(React.createElement(Foo, {""hello"":""World""}), document.getElementById(""container""))});", writer.ToString() ); } } [Theory] [InlineData("Foo", true)] [InlineData("Foo.Bar", true)] [InlineData("Foo.Bar.Baz", true)] [InlineData("alert()", false)] [InlineData("Foo.alert()", false)] [InlineData("lol what", false)] public void TestEnsureComponentNameValid(string input, bool expected) { var isValid = true; try { ReactComponent.EnsureComponentNameValid(input); } catch (ReactInvalidComponentException) { isValid = false; } Assert.Equal(expected, isValid); } [Fact] public void GeneratesContainerIdIfNotProvided() { var environment = new Mock<IReactEnvironment>(); var config = CreateDefaultConfigMock(); var reactIdGenerator = new Mock<IReactIdGenerator>(); reactIdGenerator.Setup(x => x.Generate()).Returns("customReactId"); var component = new ReactComponent(environment.Object, config.Object, reactIdGenerator.Object, "Foo", null); Assert.Equal("customReactId", component.ContainerId); } [Fact] public void ExceptionThrownIsHandled() { var environment = new Mock<IReactEnvironment>(); environment.Setup(x => x.Execute<bool>("typeof Foo !== 'undefined'")).Returns(true); environment.Setup(x => x.Execute<string>(@"ReactDOMServer.renderToString(React.createElement(Foo, {""hello"":""World""}))")) .Throws(new JsRuntimeException("'undefined' is not an object")); var config = CreateDefaultConfigMock(); config.Setup(x => x.UseServerSideRendering).Returns(true); config.Setup(x => x.ExceptionHandler).Returns(() => throw new ReactServerRenderingException("test")); var reactIdGenerator = new Mock<IReactIdGenerator>(); var component = new ReactComponent(environment.Object, config.Object, reactIdGenerator.Object, "Foo", "container") { Props = new { hello = "World" } }; // Default behavior bool exceptionCaught = false; try { component.RenderHtml(); } catch (ReactServerRenderingException) { exceptionCaught = true; } Assert.True(exceptionCaught); // Custom handler passed into render call bool customHandlerInvoked = false; Action<Exception, string, string> customHandler = (ex, name, id) => customHandlerInvoked = true; component.RenderHtml(exceptionHandler: customHandler); Assert.True(customHandlerInvoked); // Custom exception handler set Exception caughtException = null; config.Setup(x => x.ExceptionHandler).Returns((ex, name, id) => caughtException = ex); var result = component.RenderHtml(); Assert.Equal(@"<div id=""container""></div>", result); Assert.NotNull(caughtException); } [Fact] public void RenderFunctionsCalled() { var environment = new Mock<IReactEnvironment>(); environment.Setup(x => x.Execute<bool>("typeof Foo !== 'undefined'")).Returns(true); environment.Setup(x => x.Execute<string>(@"outerWrap(ReactDOMServer.renderToString(wrap(React.createElement(Foo, {""hello"":""World""}))))")) .Returns("[HTML]"); environment.Setup(x => x.Execute<string>(@"prerender();")) .Returns("prerender-result"); environment.Setup(x => x.Execute<string>(@"postrender();")) .Returns("postrender-result"); var config = CreateDefaultConfigMock(); config.Setup(x => x.UseServerSideRendering).Returns(true); var reactIdGenerator = new Mock<IReactIdGenerator>(); var component = new ReactComponent(environment.Object, config.Object, reactIdGenerator.Object, "Foo", "container") { Props = new { hello = "World" } }; var renderFunctions = new TestRenderFunctions(); var result = component.RenderHtml(renderFunctions: renderFunctions); Assert.Equal(@"<div id=""container"">[HTML]</div>", result); Assert.Equal(@"prerender-result", renderFunctions.PreRenderResult); Assert.Equal(@"postrender-result", renderFunctions.PostRenderResult); } [Fact] public void ChainedRenderFunctionsCalled() { var firstInstance = new TestRenderFunctions(); var secondInstance = new TestRenderFunctions(); var chainedRenderFunctions = new ChainedRenderFunctions(firstInstance, secondInstance); chainedRenderFunctions.PreRender(a => "prerender-result"); Assert.Equal("prerender-result", firstInstance.PreRenderResult); Assert.Equal("prerender-result", secondInstance.PreRenderResult); string wrapComponentResult = chainedRenderFunctions.WrapComponent("React.createElement('div', null)"); Assert.Equal("wrap(wrap(React.createElement('div', null)))", wrapComponentResult); Assert.Equal("outerWrap(input)", firstInstance.TransformRenderedHtml("input")); Assert.Equal("outerWrap(outerWrap(input))", chainedRenderFunctions.TransformRenderedHtml("input")); chainedRenderFunctions.PostRender(a => "postrender-result"); Assert.Equal("postrender-result", firstInstance.PostRenderResult); Assert.Equal("postrender-result", secondInstance.PostRenderResult); } [Fact] public void RenderFunctionsCalledServerOnly() { var environment = new Mock<IReactEnvironment>(); environment.Setup(x => x.Execute<bool>("typeof Foo !== 'undefined'")).Returns(true); environment.Setup(x => x.Execute<string>(@"outerWrap(ReactDOMServer.renderToStaticMarkup(wrap(React.createElement(Foo, {""hello"":""World""}))))")) .Returns("[HTML]"); environment.Setup(x => x.Execute<string>(@"prerender();")) .Returns("prerender-result"); environment.Setup(x => x.Execute<string>(@"postrender();")) .Returns("postrender-result"); var config = CreateDefaultConfigMock(); config.Setup(x => x.UseServerSideRendering).Returns(true); var reactIdGenerator = new Mock<IReactIdGenerator>(); var component = new ReactComponent(environment.Object, config.Object, reactIdGenerator.Object, "Foo", "container") { Props = new { hello = "World" } }; var renderFunctions = new TestRenderFunctions(); var result = component.RenderHtml(renderFunctions: renderFunctions, renderServerOnly: true); Assert.Equal(@"[HTML]", result); Assert.Equal(@"prerender-result", renderFunctions.PreRenderResult); Assert.Equal(@"postrender-result", renderFunctions.PostRenderResult); } private static Mock<IReactSiteConfiguration> CreateDefaultConfigMock() { var configMock = new Mock<IReactSiteConfiguration>(); configMock.SetupGet(x => x.UseServerSideRendering).Returns(true); return configMock; } private sealed class TestRenderFunctions : RenderFunctionsBase { public string PreRenderResult { get; private set; } public string PostRenderResult { get; private set; } public override void PreRender(Func<string, string> executeJs) { PreRenderResult = executeJs("prerender();"); } public override string WrapComponent(string componentToRender) { return $"wrap({componentToRender})"; } public override string TransformRenderedHtml(string input) { return $"outerWrap({input})"; } public override void PostRender(Func<string, string> executeJs) { PostRenderResult = executeJs("postrender();"); } } } }
/* * Copyright (c) 2007, Second Life Reverse Engineering Team * 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. * - Neither the name of the Second Life Reverse Engineering Team nor the names * of its contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ using System; namespace libsecondlife.Imaging { public class ManagedImage { [Flags] public enum ImageChannels { Gray = 1, Color = 2, Alpha = 4, Bump = 8 }; public enum ImageResizeAlgorithm { NearestNeighbor } /// <summary> /// Image width /// </summary> public int Width; /// <summary> /// Image height /// </summary> public int Height; /// <summary> /// Image channel flags /// </summary> public ImageChannels Channels; /// <summary> /// Red channel data /// </summary> public byte[] Red; /// <summary> /// Green channel data /// </summary> public byte[] Green; /// <summary> /// Blue channel data /// </summary> public byte[] Blue; /// <summary> /// Alpha channel data /// </summary> public byte[] Alpha; /// <summary> /// Bump channel data /// </summary> public byte[] Bump; /// <summary> /// Create a new blank image /// </summary> /// <param name="width">width</param> /// <param name="height">height</param> /// <param name="channels">channel flags</param> public ManagedImage(int width, int height, ImageChannels channels) { Width = width; Height = height; Channels = channels; int n = width * height; if ((channels & ImageChannels.Gray) != 0) { Red = new byte[n]; } else if ((channels & ImageChannels.Color) != 0) { Red = new byte[n]; Green = new byte[n]; Blue = new byte[n]; } if ((channels & ImageChannels.Alpha) != 0) Alpha = new byte[n]; if ((channels & ImageChannels.Bump) != 0) Bump = new byte[n]; } #if !NO_UNSAFE /// <summary> /// /// </summary> /// <param name="bitmap"></param> public ManagedImage(System.Drawing.Bitmap bitmap) { Width = bitmap.Width; Height = bitmap.Height; int pixelCount = Width * Height; if (bitmap.PixelFormat == System.Drawing.Imaging.PixelFormat.Format32bppArgb) { Channels = ImageChannels.Alpha & ImageChannels.Color; Red = new byte[pixelCount]; Green = new byte[pixelCount]; Blue = new byte[pixelCount]; Alpha = new byte[pixelCount]; System.Drawing.Imaging.BitmapData bd = bitmap.LockBits(new System.Drawing.Rectangle(0, 0, Width, Height), System.Drawing.Imaging.ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb); unsafe { byte* pixel = (byte*)bd.Scan0; for (int i = 0; i < pixelCount; i++) { // GDI+ gives us BGRA and we need to turn that in to RGBA Blue[i] = *(pixel++); Green[i] = *(pixel++); Red[i] = *(pixel++); Alpha[i] = *(pixel++); } } bitmap.UnlockBits(bd); } else if (bitmap.PixelFormat == System.Drawing.Imaging.PixelFormat.Format16bppGrayScale) { Channels = ImageChannels.Gray; Red = new byte[pixelCount]; throw new NotImplementedException("16bpp grayscale image support is incomplete"); } else if (bitmap.PixelFormat == System.Drawing.Imaging.PixelFormat.Format24bppRgb) { Channels = ImageChannels.Color; Red = new byte[pixelCount]; Green = new byte[pixelCount]; Blue = new byte[pixelCount]; System.Drawing.Imaging.BitmapData bd = bitmap.LockBits(new System.Drawing.Rectangle(0, 0, Width, Height), System.Drawing.Imaging.ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format24bppRgb); unsafe { byte* pixel = (byte*)bd.Scan0; for (int i = 0; i < pixelCount; i++) { // GDI+ gives us BGR and we need to turn that in to RGB Blue[i] = *(pixel++); Green[i] = *(pixel++); Red[i] = *(pixel++); } } bitmap.UnlockBits(bd); } else { throw new NotSupportedException("Unrecognized pixel format: " + bitmap.PixelFormat.ToString()); } } #endif /// <summary> /// Convert the channels in the image. Channels are created or destroyed as required. /// </summary> /// <param name="channels">new channel flags</param> public void ConvertChannels(ImageChannels channels) { if (Channels == channels) return; int n = Width * Height; ImageChannels add = Channels ^ channels & channels; ImageChannels del = Channels ^ channels & Channels; if ((add & ImageChannels.Color) != 0) { Red = new byte[n]; Green = new byte[n]; Blue = new byte[n]; } else if ((del & ImageChannels.Color) != 0) { Red = null; Green = null; Blue = null; } if ((add & ImageChannels.Alpha) != 0) { Alpha = new byte[n]; FillArray(Alpha, 255); } else if ((del & ImageChannels.Alpha) != 0) Alpha = null; if ((add & ImageChannels.Bump) != 0) Bump = new byte[n]; else if ((del & ImageChannels.Bump) != 0) Bump = null; Channels = channels; } /// <summary> /// Resize or stretch the image using nearest neighbor (ugly) resampling /// </summary> /// <param name="width">new width</param> /// <param name="height">new height</param> public void ResizeNearestNeighbor(int width, int height) { if (width == Width && height == Height) return; byte[] red = null, green = null, blue = null, alpha = null, bump = null; int n = width * height; int di = 0, si; if (Red != null) red = new byte[n]; if (Green != null) green = new byte[n]; if (Blue != null) blue = new byte[n]; if (Alpha != null) alpha = new byte[n]; if (Bump != null) bump = new byte[n]; for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { si = (y * Height / height) * Width + (x * Width / width); if (Red != null) red[di] = Red[si]; if (Green != null) green[di] = Green[si]; if (Blue != null) blue[di] = Blue[si]; if (Alpha != null) alpha[di] = Alpha[si]; if (Bump != null) bump[di] = Bump[si]; di++; } } Width = width; Height = height; Red = red; Green = green; Blue = blue; Alpha = alpha; Bump = bump; } public byte[] ExportRaw() { int n = Width * Height; int di = 0; byte[] raw = new byte[n * 4]; if ((Channels & ImageChannels.Alpha) != 0) { if ((Channels & ImageChannels.Color) != 0) { // RGBA for (int i = 0; i < n; i++) { raw[di++] = Red[i]; raw[di++] = Green[i]; raw[di++] = Blue[i]; raw[di++] = Alpha[i]; } } else { // Alpha only for (int i = 0; i < n; i++) { raw[di++] = Alpha[i]; raw[di++] = Alpha[i]; raw[di++] = Alpha[i]; raw[di++] = Byte.MaxValue; } } } else { // RGB for (int i = 0; i < n; i++) { raw[di++] = Red[i]; raw[di++] = Green[i]; raw[di++] = Blue[i]; raw[di++] = Byte.MaxValue; } } return raw; } public byte[] ExportTGA() { byte[] tga = new byte[Width * Height * ((Channels & ImageChannels.Alpha) == 0 ? 3 : 4) + 32]; int di = 0; tga[di++] = 0; // idlength tga[di++] = 0; // colormaptype = 0: no colormap tga[di++] = 2; // image type = 2: uncompressed RGB tga[di++] = 0; // color map spec is five zeroes for no color map tga[di++] = 0; // color map spec is five zeroes for no color map tga[di++] = 0; // color map spec is five zeroes for no color map tga[di++] = 0; // color map spec is five zeroes for no color map tga[di++] = 0; // color map spec is five zeroes for no color map tga[di++] = 0; // x origin = two bytes tga[di++] = 0; // x origin = two bytes tga[di++] = 0; // y origin = two bytes tga[di++] = 0; // y origin = two bytes tga[di++] = (byte)(Width & 0xFF); // width - low byte tga[di++] = (byte)(Width >> 8); // width - hi byte tga[di++] = (byte)(Height & 0xFF); // height - low byte tga[di++] = (byte)(Height >> 8); // height - hi byte tga[di++] = (byte)((Channels & ImageChannels.Alpha) == 0 ? 24 : 32); // 24/32 bits per pixel tga[di++] = (byte)((Channels & ImageChannels.Alpha) == 0 ? 32 : 40); // image descriptor byte int n = Width * Height; if ((Channels & ImageChannels.Alpha) != 0) { if ((Channels & ImageChannels.Color) != 0) { // RGBA for (int i = 0; i < n; i++) { tga[di++] = Blue[i]; tga[di++] = Green[i]; tga[di++] = Red[i]; tga[di++] = Alpha[i]; } } else { // Alpha only for (int i = 0; i < n; i++) { tga[di++] = Alpha[i]; tga[di++] = Alpha[i]; tga[di++] = Alpha[i]; tga[di++] = Byte.MaxValue; } } } else { // RGB for (int i = 0; i < n; i++) { tga[di++] = Blue[i]; tga[di++] = Green[i]; tga[di++] = Red[i]; } } return tga; } private static void FillArray(byte[] array, byte value) { if (array != null) { for (int i = 0; i < array.Length; i++) array[i] = value; } } public void Clear() { FillArray(Red, 0); FillArray(Green, 0); FillArray(Blue, 0); FillArray(Alpha, 0); FillArray(Bump, 0); } public ManagedImage Clone() { ManagedImage image = new ManagedImage(Width, Height, Channels); if (Red != null) image.Red = (byte[])Red.Clone(); if (Green != null) image.Green = (byte[])Green.Clone(); if (Blue != null) image.Blue = (byte[])Blue.Clone(); if (Alpha != null) image.Alpha = (byte[])Alpha.Clone(); if (Bump != null) image.Bump = (byte[])Bump.Clone(); return image; } } }
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 Wrench.src.Managers; using Wrench.src.Helpers; using Wrench.src.BaseClasses; namespace Wrench.src.GameObjects { /// <summary> /// This is a game component that implements IUpdateable. /// </summary> public class Player : GameObject { //its position will always be on the floor, so we need an offset to 'elevate' the camera Vector3 headPosition; //The position the player looks at when not rotated Vector3 cameraReference = Vector3.Forward; HolsteredGun gun; SpriteFont font; private Texture2D gunFlashTexture; private Texture2D gunTexture; //Time for next shot availability private DateTime bulletTime; SoundEffect shotSound; SoundEffect hurtSound; public bool Shot { get; private set; } int health = 100; public int Health { get { return health; } private set { } } public Player(Game game, Vector3 pos) : base(game) { //Initialize everything bulletTime = DateTime.Today; this.position = pos; headPosition = new Vector3(0, 0.6f, 0); RotationSpeed = 0.1f; ForwardSpeed = 10f; boxMin = new Vector3(-0.235f, 0, -0.235f); boxMax = new Vector3(0.235f, 0.8f, 0.235f); boundingBox = new BoundingBox(position + boxMin, position + boxMax); font = ContentPreImporter.GetFont("TextFont"); gunTexture = ContentPreImporter.GetTexture("gun"); gunFlashTexture = ContentPreImporter.GetTexture("gunflash"); shotSound = ContentPreImporter.GetSound("shot"); hurtSound = ContentPreImporter.GetSound("playerHurt"); gun = new HolsteredGun(game, gunTexture, new Vector2(0.1f)); gun.SetPositionRotation(position, amountOfRotation); gun.ForceUpdate(); Matrix rotationMatrix = Matrix.CreateRotationY(amountOfRotation); Vector3 cameraPosition = position + headPosition; rotationMatrix = Matrix.CreateRotationY(amountOfRotation); Vector3 transformedReference = Vector3.Transform(cameraReference, rotationMatrix); Vector3 cameraLookat = cameraPosition + transformedReference; #if VIEWDEBUG Manager.MatrixManager.SetPosition(cameraPosition + new Vector3(1f, 4.0f, 1f)); Manager.MatrixManager.SetLookAt(cameraPosition); #else Manager.MatrixManager.SetPosition(cameraPosition); Manager.MatrixManager.SetLookAt(cameraLookat); #endif // TODO: Construct any child components here } /// <summary> /// Allows the game component to perform any initialization it needs to before starting /// to run. This is where it can query for any required services and load content. /// </summary> public override void Initialize() { // TODO: Add your initialization code here base.Initialize(); } /// <summary> /// Allows the game component to update itself. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> public override void Update(GameTime gameTime) { // TODO: Add your update code here Matrix rotationMatrix = Matrix.CreateRotationY(amountOfRotation); //Rotate towards the mouse movement amountOfRotation += Manager.InputManager.MouseChange.X * RotationSpeed * (float)gameTime.ElapsedGameTime.TotalSeconds; //Amount returned by joystick is much smaller, so multiply it by a large number amountOfRotation -= Manager.InputManager.RightThumbstick().X * 50 * RotationSpeed * (float)gameTime.ElapsedGameTime.TotalSeconds; //Move player based on button/gamepad press if (Manager.InputManager.IsDown(Keys.W) || Manager.InputManager.IsDown(Buttons.LeftThumbstickUp)) { Matrix forwardMovement = Matrix.CreateRotationY(amountOfRotation); Vector3 v = new Vector3(0, 0, -ForwardSpeed * (float)gameTime.ElapsedGameTime.TotalSeconds); v = Vector3.Transform(v, forwardMovement); velocity += v; } if (Manager.InputManager.IsDown(Keys.S) || Manager.InputManager.IsDown(Buttons.LeftThumbstickDown)) { Matrix forwardMovement = Matrix.CreateRotationY(amountOfRotation); Vector3 v = new Vector3(0, 0, ForwardSpeed * (float)gameTime.ElapsedGameTime.TotalSeconds); v = Vector3.Transform(v, forwardMovement); velocity += v; } if (Manager.InputManager.IsDown(Keys.A) || Manager.InputManager.IsDown(Buttons.LeftThumbstickLeft)) { Matrix forwardMovement = Matrix.CreateRotationY(amountOfRotation + MathHelper.ToRadians(90)); Vector3 v = new Vector3(0, 0, -ForwardSpeed * (float)gameTime.ElapsedGameTime.TotalSeconds); v = Vector3.Transform(v, forwardMovement); velocity += v; } if (Manager.InputManager.IsDown(Keys.D) || Manager.InputManager.IsDown(Buttons.LeftThumbstickRight)) { Matrix forwardMovement = Matrix.CreateRotationY(amountOfRotation + MathHelper.ToRadians(90)); Vector3 v = new Vector3(0, 0, ForwardSpeed * (float)gameTime.ElapsedGameTime.TotalSeconds); v = Vector3.Transform(v, forwardMovement); velocity += v; } MoveForward(gameTime); //Update the camera Vector3 cameraPosition = position + headPosition; rotationMatrix = Matrix.CreateRotationY(amountOfRotation); Vector3 transformedReference = Vector3.Transform(cameraReference, rotationMatrix); Vector3 cameraLookat = cameraPosition + transformedReference; //Shoot if mouse clicked Shot = false; if (Manager.InputManager.HasBeenClicked(InputManager.MouseButton.Left) || Manager.InputManager.HasBeenPressed(Buttons.A)) { Shot = true; gun.SetTexture(gunFlashTexture); shotSound.Play(); bulletTime = DateTime.Now.AddSeconds(0.1); } if (DateTime.Now > bulletTime) gun.SetTexture(gunTexture); //Update the matrices #if VIEWDEBUG Manager.MatrixManager.SetPosition(cameraPosition + new Vector3(1f, 4.0f, 1f)); Manager.MatrixManager.SetLookAt(cameraPosition); #else Manager.MatrixManager.SetPosition(cameraPosition); Manager.MatrixManager.SetLookAt(cameraLookat); #endif //Update the bounding box and gun position boundingBox = new BoundingBox(position + boxMin, position + boxMax); gun.SetPositionRotation(position, amountOfRotation); gun.Update(gameTime); base.Update(gameTime); } //Add health to the player public void AddLife(int amount) { health += amount; health = (int)MathHelper.Clamp(health, 0, 100); } //Backup the players position if it hits an obstacle public override void Backup(GameTime gameTime) { position = lastPosition; Matrix rotationMatrix = Matrix.CreateRotationY(amountOfRotation); Vector3 cameraPosition = position + headPosition; rotationMatrix = Matrix.CreateRotationY(amountOfRotation); Vector3 transformedReference = Vector3.Transform(cameraReference, rotationMatrix); Vector3 cameraLookat = cameraPosition + transformedReference; #if VIEWDEBUG Manager.MatrixManager.SetPosition(cameraPosition + new Vector3(1f, 4.0f,1f)); Manager.MatrixManager.SetLookAt(cameraPosition); #else Manager.MatrixManager.SetPosition(cameraPosition); Manager.MatrixManager.SetLookAt(cameraLookat); #endif boundingBox = new BoundingBox(position + boxMin, position + boxMax); gun.SetPositionRotation(position, amountOfRotation); gun.Update(gameTime); } //Draw all the required information public override void Draw(GameTime gameTime) { SpriteBatch sp = Game.Services.GetService(typeof(SpriteBatch)) as SpriteBatch; sp.Begin(); sp.DrawString(font, "Life: " + health, new Vector2(10, 25), Color.Red); sp.End(); GraphicsDevice.BlendState = BlendState.Opaque; GraphicsDevice.DepthStencilState = DepthStencilState.Default; GraphicsDevice.SamplerStates[0] = SamplerState.LinearWrap; #if DEBUG Vector3 lineStart = position + new Vector3(0, 0.5f, 0); Matrix rotationMatrix = Matrix.CreateRotationY(amountOfRotation); Vector3 transformedReference = Vector3.Transform(Vector3.Forward * 0.3f, rotationMatrix); Helpers.DebugShapeRenderer.AddLine(lineStart, lineStart + transformedReference, Color.Purple); Helpers.DebugShapeRenderer.AddBoundingBox(boundingBox, Color.Green); #endif gun.Draw(gameTime); base.Draw(gameTime); } //Do damage to the player public override void Hit(int damage) { hurtSound.Play(); health -= damage; if (health <= 0) Alive = 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.Net.Http; using Microsoft.DotNet.RemoteExecutor; using Xunit; using Xunit.Abstractions; namespace System.Net.Http.Tests { public class HttpEnvironmentProxyTest { private readonly ITestOutputHelper _output; private static readonly Uri fooHttp = new Uri("http://foo.com"); private static readonly Uri fooHttps = new Uri("https://foo.com"); // This will clean specific environmental variables // to be sure they do not interfere with the test. private void CleanEnv() { var envVars = new List<string>() { "http_proxy", "HTTP_PROXY", "https_proxy", "HTTPS_PROXY", "all_proxy", "ALL_PROXY", "no_proxy", "NO_PROXY", "GATEWAY_INTERFACE" }; foreach (string v in envVars) { Environment.SetEnvironmentVariable(v, null); } } public HttpEnvironmentProxyTest(ITestOutputHelper output) { _output = output; CleanEnv(); } [Fact] public void HttpProxy_EnvironmentProxy_Loaded() { RemoteExecutor.Invoke(() => { IWebProxy p; Uri u; // It should not return object if there are no variables set. Assert.False(HttpEnvironmentProxy.TryCreate(out p)); Environment.SetEnvironmentVariable("all_proxy", "http://1.1.1.1:3000"); Assert.True(HttpEnvironmentProxy.TryCreate(out p)); Assert.NotNull(p); Assert.Null(p.Credentials); u = p.GetProxy(fooHttp); Assert.True(u != null && u.Host == "1.1.1.1"); u = p.GetProxy(fooHttps); Assert.True(u != null && u.Host == "1.1.1.1"); Environment.SetEnvironmentVariable("http_proxy", "http://1.1.1.2:3001"); Assert.True(HttpEnvironmentProxy.TryCreate(out p)); Assert.NotNull(p); // Protocol specific variables should take precedence over all_ // and https should still use all_proxy. u = p.GetProxy(fooHttp); Assert.True(u != null && u.Host == "1.1.1.2" && u.Port == 3001); u = p.GetProxy(fooHttps); Assert.True(u != null && u.Host == "1.1.1.1" && u.Port == 3000); // Set https to invalid strings and use only IP & port for http. Environment.SetEnvironmentVariable("http_proxy", "1.1.1.3:3003"); Environment.SetEnvironmentVariable("https_proxy", "ab!cd"); Assert.True(HttpEnvironmentProxy.TryCreate(out p)); Assert.NotNull(p); u = p.GetProxy(fooHttp); Assert.True(u != null && u.Host == "1.1.1.3" && u.Port == 3003); u = p.GetProxy(fooHttps); Assert.True(u != null && u.Host == "1.1.1.1" && u.Port == 3000); // Try valid URI with unsupported protocol. It will be ignored // to mimic curl behavior. Environment.SetEnvironmentVariable("https_proxy", "socks5://1.1.1.4:3004"); Assert.True(HttpEnvironmentProxy.TryCreate(out p)); Assert.NotNull(p); u = p.GetProxy(fooHttps); Assert.True(u != null && u.Host == "1.1.1.1" && u.Port == 3000); // Set https to valid URI but different from http. Environment.SetEnvironmentVariable("https_proxy", "http://1.1.1.5:3005"); Assert.True(HttpEnvironmentProxy.TryCreate(out p)); Assert.NotNull(p); u = p.GetProxy(fooHttp); Assert.True(u != null && u.Host == "1.1.1.3" && u.Port == 3003); u = p.GetProxy(fooHttps); Assert.True(u != null && u.Host == "1.1.1.5" && u.Port == 3005); }).Dispose(); } [Theory] [InlineData("1.1.1.5", "1.1.1.5", "80", null, null)] [InlineData("http://1.1.1.5:3005", "1.1.1.5", "3005", null, null)] [InlineData("http://foo@1.1.1.5", "1.1.1.5", "80", "foo", "")] [InlineData("http://[::1]:80", "[::1]", "80", null, null)] [InlineData("foo:bar@[::1]:3128", "[::1]", "3128", "foo", "bar")] [InlineData("foo:Pass$!#\\.$@127.0.0.1:3128", "127.0.0.1", "3128", "foo", "Pass$!#\\.$")] [InlineData("[::1]", "[::1]", "80", null, null)] [InlineData("domain\\foo:bar@1.1.1.1", "1.1.1.1", "80", "foo", "bar")] [InlineData("domain%5Cfoo:bar@1.1.1.1", "1.1.1.1", "80", "foo", "bar")] [InlineData("HTTP://ABC.COM/", "abc.com", "80", null, null)] [InlineData("http://10.30.62.64:7890/", "10.30.62.64", "7890", null, null)] [InlineData("http://1.2.3.4:8888/foo", "1.2.3.4", "8888", null, null)] public void HttpProxy_Uri_Parsing(string _input, string _host, string _port, string _user, string _password) { RemoteExecutor.Invoke((input, host, port, user, password) => { // Remote exec does not allow to pass null at this moment. if (user == "null") { user = null; } if (password == "null") { password = null; } Environment.SetEnvironmentVariable("all_proxy", input); IWebProxy p; Uri u; Assert.True(HttpEnvironmentProxy.TryCreate(out p)); Assert.NotNull(p); u = p.GetProxy(fooHttp); Assert.Equal(host, u.Host); Assert.Equal(Convert.ToInt32(port), u.Port); if (user != null) { NetworkCredential nc = p.Credentials.GetCredential(u, "Basic"); Assert.NotNull(nc); Assert.Equal(user, nc.UserName); Assert.Equal(password, nc.Password); } return RemoteExecutor.SuccessExitCode; }, _input, _host, _port, _user ?? "null", _password ?? "null").Dispose(); } [Fact] public void HttpProxy_CredentialParsing_Basic() { RemoteExecutor.Invoke(() => { IWebProxy p; Environment.SetEnvironmentVariable("all_proxy", "http://foo:bar@1.1.1.1:3000"); Assert.True(HttpEnvironmentProxy.TryCreate(out p)); Assert.NotNull(p); Assert.NotNull(p.Credentials); // Use user only without password. Environment.SetEnvironmentVariable("all_proxy", "http://foo@1.1.1.1:3000"); Assert.True(HttpEnvironmentProxy.TryCreate(out p)); Assert.NotNull(p); Assert.NotNull(p.Credentials); // Use different user for http and https Environment.SetEnvironmentVariable("https_proxy", "http://foo1:bar1@1.1.1.1:3000"); Assert.True(HttpEnvironmentProxy.TryCreate(out p)); Assert.NotNull(p); Uri u = p.GetProxy(fooHttp); Assert.NotNull(p.Credentials.GetCredential(u, "Basic")); u = p.GetProxy(fooHttps); Assert.NotNull(p.Credentials.GetCredential(u, "Basic")); // This should not match Proxy Uri Assert.Null(p.Credentials.GetCredential(fooHttp, "Basic")); Assert.Null(p.Credentials.GetCredential(null, null)); }).Dispose(); } [Fact] public void HttpProxy_Exceptions_Match() { RemoteExecutor.Invoke(() => { IWebProxy p; Environment.SetEnvironmentVariable("no_proxy", ".test.com,, foo.com"); Environment.SetEnvironmentVariable("all_proxy", "http://foo:bar@1.1.1.1:3000"); Assert.True(HttpEnvironmentProxy.TryCreate(out p)); Assert.NotNull(p); Assert.True(p.IsBypassed(fooHttp)); Assert.True(p.IsBypassed(fooHttps)); Assert.True(p.IsBypassed(new Uri("http://test.com"))); Assert.False(p.IsBypassed(new Uri("http://1test.com"))); Assert.True(p.IsBypassed(new Uri("http://www.test.com"))); }).Dispose(); } public static IEnumerable<object[]> HttpProxyNoProxyEnvVarMemberData() { yield return new object[] { "http_proxy", "no_proxy" }; yield return new object[] { "http_proxy", "NO_PROXY" }; yield return new object[] { "HTTP_PROXY", "no_proxy" }; yield return new object[] { "HTTP_PROXY", "NO_PROXY" }; } [Theory] [MemberData(nameof(HttpProxyNoProxyEnvVarMemberData))] public void HttpProxy_TryCreate_CaseInsensitiveVariables(string proxyEnvVar, string noProxyEnvVar) { string proxy = "http://foo:bar@1.1.1.1:3000"; var options = new RemoteInvokeOptions(); options.StartInfo.EnvironmentVariables.Add(proxyEnvVar, proxy); options.StartInfo.EnvironmentVariables.Add(noProxyEnvVar, ".test.com, foo.com"); RemoteExecutor.Invoke((proxy) => { var directUri = new Uri("http://test.com"); var thruProxyUri = new Uri("http://atest.com"); Assert.True(HttpEnvironmentProxy.TryCreate(out IWebProxy p)); Assert.NotNull(p); Assert.True(p.IsBypassed(directUri)); Assert.False(p.IsBypassed(thruProxyUri)); Assert.Equal(new Uri(proxy), p.GetProxy(thruProxyUri)); }, proxy, options).Dispose(); } public static IEnumerable<object[]> HttpProxyCgiEnvVarMemberData() { foreach (bool cgi in new object[] { false, true }) { yield return new object[] { "http_proxy", cgi, !cgi || !PlatformDetection.IsWindows }; yield return new object[] { "HTTP_PROXY", cgi, !cgi }; } } [Theory] [MemberData(nameof(HttpProxyCgiEnvVarMemberData))] public void HttpProxy_TryCreateAndPossibleCgi_HttpProxyUpperCaseDisabledInCgi( string proxyEnvVar, bool cgi, bool expectedProxyUse) { string proxy = "http://foo:bar@1.1.1.1:3000"; var options = new RemoteInvokeOptions(); options.StartInfo.EnvironmentVariables.Add(proxyEnvVar, proxy); if (cgi) { options.StartInfo.EnvironmentVariables.Add("GATEWAY_INTERFACE", "CGI/1.1"); } RemoteExecutor.Invoke((proxy, expectedProxyUseString) => { bool expectedProxyUse = bool.Parse(expectedProxyUseString); var destinationUri = new Uri("http://test.com"); bool created = HttpEnvironmentProxy.TryCreate(out IWebProxy p); if (expectedProxyUse) { Assert.True(created); Assert.NotNull(p); Assert.Equal(new Uri(proxy), p.GetProxy(destinationUri)); } else { Assert.False(created); } }, proxy, expectedProxyUse.ToString(), options).Dispose(); } } }
/* * Copyright (c) 2006-2016, openmetaverse.co * 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. * - Neither the name of the openmetaverse.co nor the names * of its contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Text; using System.IO; namespace OpenMetaverse.StructuredData { /// <summary> /// /// </summary> public static partial class OSDParser { private const string baseIndent = " "; private const char undefNotationValue = '!'; private const char trueNotationValueOne = '1'; private const char trueNotationValueTwo = 't'; private static readonly char[] trueNotationValueTwoFull = { 't', 'r', 'u', 'e' }; private const char trueNotationValueThree = 'T'; private static readonly char[] trueNotationValueThreeFull = { 'T', 'R', 'U', 'E' }; private const char falseNotationValueOne = '0'; private const char falseNotationValueTwo = 'f'; private static readonly char[] falseNotationValueTwoFull = { 'f', 'a', 'l', 's', 'e' }; private const char falseNotationValueThree = 'F'; private static readonly char[] falseNotationValueThreeFull = { 'F', 'A', 'L', 'S', 'E' }; private const char integerNotationMarker = 'i'; private const char realNotationMarker = 'r'; private const char uuidNotationMarker = 'u'; private const char binaryNotationMarker = 'b'; private const char stringNotationMarker = 's'; private const char uriNotationMarker = 'l'; private const char dateNotationMarker = 'd'; private const char arrayBeginNotationMarker = '['; private const char arrayEndNotationMarker = ']'; private const char mapBeginNotationMarker = '{'; private const char mapEndNotationMarker = '}'; private const char kommaNotationDelimiter = ','; private const char keyNotationDelimiter = ':'; private const char sizeBeginNotationMarker = '('; private const char sizeEndNotationMarker = ')'; private const char doubleQuotesNotationMarker = '"'; private const char singleQuotesNotationMarker = '\''; public static OSD DeserializeLLSDNotation(string notationData) { StringReader reader = new StringReader(notationData); OSD osd = DeserializeLLSDNotation(reader); reader.Close(); return osd; } public static OSD DeserializeLLSDNotation(StringReader reader) { OSD osd = DeserializeLLSDNotationElement(reader); return osd; } public static string SerializeLLSDNotation(OSD osd) { StringWriter writer = SerializeLLSDNotationStream(osd); string s = writer.ToString(); writer.Close(); return s; } public static StringWriter SerializeLLSDNotationStream(OSD osd) { StringWriter writer = new StringWriter(); SerializeLLSDNotationElement(writer, osd); return writer; } public static string SerializeLLSDNotationFormatted(OSD osd) { StringWriter writer = SerializeLLSDNotationStreamFormatted(osd); string s = writer.ToString(); writer.Close(); return s; } public static StringWriter SerializeLLSDNotationStreamFormatted(OSD osd) { StringWriter writer = new StringWriter(); string indent = String.Empty; SerializeLLSDNotationElementFormatted(writer, indent, osd); return writer; } /// <summary> /// /// </summary> /// <param name="reader"></param> /// <returns></returns> private static OSD DeserializeLLSDNotationElement(StringReader reader) { int character = ReadAndSkipWhitespace(reader); if (character < 0) return new OSD(); // server returned an empty file, so we're going to pass along a null LLSD object OSD osd; int matching; switch ((char)character) { case undefNotationValue: osd = new OSD(); break; case trueNotationValueOne: osd = OSD.FromBoolean(true); break; case trueNotationValueTwo: matching = BufferCharactersEqual(reader, trueNotationValueTwoFull, 1); if (matching > 1 && matching < trueNotationValueTwoFull.Length) throw new OSDException("Notation LLSD parsing: True value parsing error:"); osd = OSD.FromBoolean(true); break; case trueNotationValueThree: matching = BufferCharactersEqual(reader, trueNotationValueThreeFull, 1); if (matching > 1 && matching < trueNotationValueThreeFull.Length) throw new OSDException("Notation LLSD parsing: True value parsing error:"); osd = OSD.FromBoolean(true); break; case falseNotationValueOne: osd = OSD.FromBoolean(false); break; case falseNotationValueTwo: matching = BufferCharactersEqual(reader, falseNotationValueTwoFull, 1); if (matching > 1 && matching < falseNotationValueTwoFull.Length) throw new OSDException("Notation LLSD parsing: True value parsing error:"); osd = OSD.FromBoolean(false); break; case falseNotationValueThree: matching = BufferCharactersEqual(reader, falseNotationValueThreeFull, 1); if (matching > 1 && matching < falseNotationValueThreeFull.Length) throw new OSDException("Notation LLSD parsing: True value parsing error:"); osd = OSD.FromBoolean(false); break; case integerNotationMarker: osd = DeserializeLLSDNotationInteger(reader); break; case realNotationMarker: osd = DeserializeLLSDNotationReal(reader); break; case uuidNotationMarker: char[] uuidBuf = new char[36]; if (reader.Read(uuidBuf, 0, 36) < 36) throw new OSDException("Notation LLSD parsing: Unexpected end of stream in UUID."); UUID lluuid; if (!UUID.TryParse(new String(uuidBuf), out lluuid)) throw new OSDException("Notation LLSD parsing: Invalid UUID discovered."); osd = OSD.FromUUID(lluuid); break; case binaryNotationMarker: byte[] bytes = Utils.EmptyBytes; int bChar = reader.Peek(); if (bChar < 0) throw new OSDException("Notation LLSD parsing: Unexpected end of stream in binary."); if ((char)bChar == sizeBeginNotationMarker) { throw new OSDException("Notation LLSD parsing: Raw binary encoding not supported."); } else if (Char.IsDigit((char)bChar)) { char[] charsBaseEncoding = new char[2]; if (reader.Read(charsBaseEncoding, 0, 2) < 2) throw new OSDException("Notation LLSD parsing: Unexpected end of stream in binary."); int baseEncoding; if (!Int32.TryParse(new String(charsBaseEncoding), out baseEncoding)) throw new OSDException("Notation LLSD parsing: Invalid binary encoding base."); if (baseEncoding == 64) { if (reader.Read() < 0) throw new OSDException("Notation LLSD parsing: Unexpected end of stream in binary."); string bytes64 = GetStringDelimitedBy(reader, doubleQuotesNotationMarker); bytes = Convert.FromBase64String(bytes64); } else { throw new OSDException("Notation LLSD parsing: Encoding base" + baseEncoding + " + not supported."); } } osd = OSD.FromBinary(bytes); break; case stringNotationMarker: int numChars = GetLengthInBrackets(reader); if (reader.Read() < 0) throw new OSDException("Notation LLSD parsing: Unexpected end of stream in string."); char[] chars = new char[numChars]; if (reader.Read(chars, 0, numChars) < numChars) throw new OSDException("Notation LLSD parsing: Unexpected end of stream in string."); if (reader.Read() < 0) throw new OSDException("Notation LLSD parsing: Unexpected end of stream in string."); osd = OSD.FromString(new String(chars)); break; case singleQuotesNotationMarker: string sOne = GetStringDelimitedBy(reader, singleQuotesNotationMarker); osd = OSD.FromString(sOne); break; case doubleQuotesNotationMarker: string sTwo = GetStringDelimitedBy(reader, doubleQuotesNotationMarker); osd = OSD.FromString(sTwo); break; case uriNotationMarker: if (reader.Read() < 0) throw new OSDException("Notation LLSD parsing: Unexpected end of stream in string."); string sUri = GetStringDelimitedBy(reader, doubleQuotesNotationMarker); Uri uri; try { uri = new Uri(sUri, UriKind.RelativeOrAbsolute); } catch { throw new OSDException("Notation LLSD parsing: Invalid Uri format detected."); } osd = OSD.FromUri(uri); break; case dateNotationMarker: if (reader.Read() < 0) throw new OSDException("Notation LLSD parsing: Unexpected end of stream in date."); string date = GetStringDelimitedBy(reader, doubleQuotesNotationMarker); DateTime dt; if (!DateTime.TryParse(date, out dt)) throw new OSDException("Notation LLSD parsing: Invalid date discovered."); osd = OSD.FromDate(dt); break; case arrayBeginNotationMarker: osd = DeserializeLLSDNotationArray(reader); break; case mapBeginNotationMarker: osd = DeserializeLLSDNotationMap(reader); break; default: throw new OSDException("Notation LLSD parsing: Unknown type marker '" + (char)character + "'."); } return osd; } private static OSD DeserializeLLSDNotationInteger(StringReader reader) { int character; StringBuilder s = new StringBuilder(); if (((character = reader.Peek()) > 0) && ((char)character == '-')) { s.Append((char)character); reader.Read(); } while ((character = reader.Peek()) > 0 && Char.IsDigit((char)character)) { s.Append((char)character); reader.Read(); } int integer; if (!Int32.TryParse(s.ToString(), out integer)) throw new OSDException("Notation LLSD parsing: Can't parse integer value." + s.ToString()); return OSD.FromInteger(integer); } private static OSD DeserializeLLSDNotationReal(StringReader reader) { int character; StringBuilder s = new StringBuilder(); if (((character = reader.Peek()) > 0) && ((char)character == '-' && (char)character == '+')) { s.Append((char)character); reader.Read(); } while (((character = reader.Peek()) > 0) && (Char.IsDigit((char)character) || (char)character == '.' || (char)character == 'e' || (char)character == 'E' || (char)character == '+' || (char)character == '-')) { s.Append((char)character); reader.Read(); } double dbl; if (!Utils.TryParseDouble(s.ToString(), out dbl)) throw new OSDException("Notation LLSD parsing: Can't parse real value: " + s.ToString()); return OSD.FromReal(dbl); } private static OSD DeserializeLLSDNotationArray(StringReader reader) { int character; OSDArray osdArray = new OSDArray(); while (((character = PeekAndSkipWhitespace(reader)) > 0) && ((char)character != arrayEndNotationMarker)) { osdArray.Add(DeserializeLLSDNotationElement(reader)); character = ReadAndSkipWhitespace(reader); if (character < 0) throw new OSDException("Notation LLSD parsing: Unexpected end of array discovered."); else if ((char)character == kommaNotationDelimiter) continue; else if ((char)character == arrayEndNotationMarker) break; } if (character < 0) throw new OSDException("Notation LLSD parsing: Unexpected end of array discovered."); return (OSD)osdArray; } private static OSD DeserializeLLSDNotationMap(StringReader reader) { int character; OSDMap osdMap = new OSDMap(); while (((character = PeekAndSkipWhitespace(reader)) > 0) && ((char)character != mapEndNotationMarker)) { OSD osdKey = DeserializeLLSDNotationElement(reader); if (osdKey.Type != OSDType.String) throw new OSDException("Notation LLSD parsing: Invalid key in map"); string key = osdKey.AsString(); character = ReadAndSkipWhitespace(reader); if ((char)character != keyNotationDelimiter) throw new OSDException("Notation LLSD parsing: Unexpected end of stream in map."); if ((char)character != keyNotationDelimiter) throw new OSDException("Notation LLSD parsing: Invalid delimiter in map."); osdMap[key] = DeserializeLLSDNotationElement(reader); character = ReadAndSkipWhitespace(reader); if (character < 0) throw new OSDException("Notation LLSD parsing: Unexpected end of map discovered."); else if ((char)character == kommaNotationDelimiter) continue; else if ((char)character == mapEndNotationMarker) break; } if (character < 0) throw new OSDException("Notation LLSD parsing: Unexpected end of map discovered."); return (OSD)osdMap; } private static void SerializeLLSDNotationElement(StringWriter writer, OSD osd) { switch (osd.Type) { case OSDType.Unknown: writer.Write(undefNotationValue); break; case OSDType.Boolean: if (osd.AsBoolean()) writer.Write(trueNotationValueTwo); else writer.Write(falseNotationValueTwo); break; case OSDType.Integer: writer.Write(integerNotationMarker); writer.Write(osd.AsString()); break; case OSDType.Real: writer.Write(realNotationMarker); writer.Write(osd.AsString()); break; case OSDType.UUID: writer.Write(uuidNotationMarker); writer.Write(osd.AsString()); break; case OSDType.String: writer.Write(singleQuotesNotationMarker); writer.Write(EscapeCharacter(osd.AsString(), singleQuotesNotationMarker)); writer.Write(singleQuotesNotationMarker); break; case OSDType.Binary: writer.Write(binaryNotationMarker); writer.Write("64"); writer.Write(doubleQuotesNotationMarker); writer.Write(osd.AsString()); writer.Write(doubleQuotesNotationMarker); break; case OSDType.Date: writer.Write(dateNotationMarker); writer.Write(doubleQuotesNotationMarker); writer.Write(osd.AsString()); writer.Write(doubleQuotesNotationMarker); break; case OSDType.URI: writer.Write(uriNotationMarker); writer.Write(doubleQuotesNotationMarker); writer.Write(EscapeCharacter(osd.AsString(), doubleQuotesNotationMarker)); writer.Write(doubleQuotesNotationMarker); break; case OSDType.Array: SerializeLLSDNotationArray(writer, (OSDArray)osd); break; case OSDType.Map: SerializeLLSDNotationMap(writer, (OSDMap)osd); break; default: throw new OSDException("Notation serialization: Not existing element discovered."); } } private static void SerializeLLSDNotationArray(StringWriter writer, OSDArray osdArray) { writer.Write(arrayBeginNotationMarker); int lastIndex = osdArray.Count - 1; for (int idx = 0; idx <= lastIndex; idx++) { SerializeLLSDNotationElement(writer, osdArray[idx]); if (idx < lastIndex) writer.Write(kommaNotationDelimiter); } writer.Write(arrayEndNotationMarker); } private static void SerializeLLSDNotationMap(StringWriter writer, OSDMap osdMap) { writer.Write(mapBeginNotationMarker); int lastIndex = osdMap.Count - 1; int idx = 0; foreach (KeyValuePair<string, OSD> kvp in osdMap) { writer.Write(singleQuotesNotationMarker); writer.Write(EscapeCharacter(kvp.Key, singleQuotesNotationMarker)); writer.Write(singleQuotesNotationMarker); writer.Write(keyNotationDelimiter); SerializeLLSDNotationElement(writer, kvp.Value); if (idx < lastIndex) writer.Write(kommaNotationDelimiter); idx++; } writer.Write(mapEndNotationMarker); } private static void SerializeLLSDNotationElementFormatted(StringWriter writer, string indent, OSD osd) { switch (osd.Type) { case OSDType.Unknown: writer.Write(undefNotationValue); break; case OSDType.Boolean: if (osd.AsBoolean()) writer.Write(trueNotationValueTwo); else writer.Write(falseNotationValueTwo); break; case OSDType.Integer: writer.Write(integerNotationMarker); writer.Write(osd.AsString()); break; case OSDType.Real: writer.Write(realNotationMarker); writer.Write(osd.AsString()); break; case OSDType.UUID: writer.Write(uuidNotationMarker); writer.Write(osd.AsString()); break; case OSDType.String: writer.Write(singleQuotesNotationMarker); writer.Write(EscapeCharacter(osd.AsString(), singleQuotesNotationMarker)); writer.Write(singleQuotesNotationMarker); break; case OSDType.Binary: writer.Write(binaryNotationMarker); writer.Write("64"); writer.Write(doubleQuotesNotationMarker); writer.Write(osd.AsString()); writer.Write(doubleQuotesNotationMarker); break; case OSDType.Date: writer.Write(dateNotationMarker); writer.Write(doubleQuotesNotationMarker); writer.Write(osd.AsString()); writer.Write(doubleQuotesNotationMarker); break; case OSDType.URI: writer.Write(uriNotationMarker); writer.Write(doubleQuotesNotationMarker); writer.Write(EscapeCharacter(osd.AsString(), doubleQuotesNotationMarker)); writer.Write(doubleQuotesNotationMarker); break; case OSDType.Array: SerializeLLSDNotationArrayFormatted(writer, indent + baseIndent, (OSDArray)osd); break; case OSDType.Map: SerializeLLSDNotationMapFormatted(writer, indent + baseIndent, (OSDMap)osd); break; default: throw new OSDException("Notation serialization: Not existing element discovered."); } } private static void SerializeLLSDNotationArrayFormatted(StringWriter writer, string intend, OSDArray osdArray) { writer.WriteLine(); writer.Write(intend); writer.Write(arrayBeginNotationMarker); int lastIndex = osdArray.Count - 1; for (int idx = 0; idx <= lastIndex; idx++) { if (osdArray[idx].Type != OSDType.Array && osdArray[idx].Type != OSDType.Map) writer.WriteLine(); writer.Write(intend + baseIndent); SerializeLLSDNotationElementFormatted(writer, intend, osdArray[idx]); if (idx < lastIndex) { writer.Write(kommaNotationDelimiter); } } writer.WriteLine(); writer.Write(intend); writer.Write(arrayEndNotationMarker); } private static void SerializeLLSDNotationMapFormatted(StringWriter writer, string intend, OSDMap osdMap) { writer.WriteLine(); writer.Write(intend); writer.WriteLine(mapBeginNotationMarker); int lastIndex = osdMap.Count - 1; int idx = 0; foreach (KeyValuePair<string, OSD> kvp in osdMap) { writer.Write(intend + baseIndent); writer.Write(singleQuotesNotationMarker); writer.Write(EscapeCharacter(kvp.Key, singleQuotesNotationMarker)); writer.Write(singleQuotesNotationMarker); writer.Write(keyNotationDelimiter); SerializeLLSDNotationElementFormatted(writer, intend, kvp.Value); if (idx < lastIndex) { writer.WriteLine(); writer.Write(intend + baseIndent); writer.WriteLine(kommaNotationDelimiter); } idx++; } writer.WriteLine(); writer.Write(intend); writer.Write(mapEndNotationMarker); } /// <summary> /// /// </summary> /// <param name="reader"></param> /// <returns></returns> public static int PeekAndSkipWhitespace(StringReader reader) { int character; while ((character = reader.Peek()) > 0) { char c = (char)character; if (c == ' ' || c == '\t' || c == '\n' || c == '\r') { reader.Read(); continue; } else break; } return character; } /// <summary> /// /// </summary> /// <param name="reader"></param> /// <returns></returns> public static int ReadAndSkipWhitespace(StringReader reader) { int character = PeekAndSkipWhitespace(reader); reader.Read(); return character; } /// <summary> /// /// </summary> /// <param name="reader"></param> /// <returns></returns> public static int GetLengthInBrackets(StringReader reader) { int character; StringBuilder s = new StringBuilder(); if (((character = PeekAndSkipWhitespace(reader)) > 0) && ((char)character == sizeBeginNotationMarker)) { reader.Read(); } while (((character = reader.Read()) > 0) && Char.IsDigit((char)character) && ((char)character != sizeEndNotationMarker)) { s.Append((char)character); } if (character < 0) throw new OSDException("Notation LLSD parsing: Can't parse length value cause unexpected end of stream."); int length; if (!Int32.TryParse(s.ToString(), out length)) throw new OSDException("Notation LLSD parsing: Can't parse length value."); return length; } /// <summary> /// /// </summary> /// <param name="reader"></param> /// <param name="delimiter"></param> /// <returns></returns> public static string GetStringDelimitedBy(StringReader reader, char delimiter) { int character; bool foundEscape = false; StringBuilder s = new StringBuilder(); while (((character = reader.Read()) > 0) && (((char)character != delimiter) || ((char)character == delimiter && foundEscape))) { if (foundEscape) { foundEscape = false; switch ((char)character) { case 'a': s.Append('\a'); break; case 'b': s.Append('\b'); break; case 'f': s.Append('\f'); break; case 'n': s.Append('\n'); break; case 'r': s.Append('\r'); break; case 't': s.Append('\t'); break; case 'v': s.Append('\v'); break; default: s.Append((char)character); break; } } else if ((char)character == '\\') foundEscape = true; else s.Append((char)character); } if (character < 0) throw new OSDException("Notation LLSD parsing: Can't parse text because unexpected end of stream while expecting a '" + delimiter + "' character."); return s.ToString(); } /// <summary> /// /// </summary> /// <param name="reader"></param> /// <param name="buffer"></param> /// <param name="offset"></param> /// <returns></returns> public static int BufferCharactersEqual(StringReader reader, char[] buffer, int offset) { int character; int lastIndex = buffer.Length - 1; int crrIndex = offset; bool charactersEqual = true; while ((character = reader.Peek()) > 0 && crrIndex <= lastIndex && charactersEqual) { if (((char)character) != buffer[crrIndex]) { charactersEqual = false; break; } crrIndex++; reader.Read(); } return crrIndex; } /// <summary> /// /// </summary> /// <param name="s"></param> /// <param name="c"></param> /// <returns></returns> public static string UnescapeCharacter(String s, char c) { string oldOne = "\\" + c; string newOne = new String(c, 1); String sOne = s.Replace("\\\\", "\\").Replace(oldOne, newOne); return sOne; } /// <summary> /// /// </summary> /// <param name="s"></param> /// <param name="c"></param> /// <returns></returns> public static string EscapeCharacter(String s, char c) { string oldOne = new String(c, 1); string newOne = "\\" + c; String sOne = s.Replace("\\", "\\\\").Replace(oldOne, newOne); return sOne; } } }
// MIT License // // Copyright (c) 2017 Maarten van Sambeek. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. namespace ConnectQl.ExtensionMethods { using System; using System.Linq; using System.Reflection; using System.Threading.Tasks; using JetBrains.Annotations; /// <summary> /// The type extensions. /// </summary> internal static class TypeExtensions { /// <summary> /// Gets a generic method on a type. /// </summary> /// <param name="type"> /// The type. /// </param> /// <param name="name"> /// The name of the method. /// </param> /// <param name="parameters"> /// The types of the parameters. /// </param> /// <returns> /// The <see cref="MethodInfo"/>. /// </returns> [CanBeNull] public static MethodInfo GetGenericMethod(this Type type, string name, params Type[] parameters) { return type.GetRuntimeMethods().FirstOrDefault( m => m.Name == name && m.GetParameters().Select( p => p.ParameterType.IsConstructedGenericType && p.ParameterType.GenericTypeArguments.Any(ta => ta.IsGenericParameter) ? p.ParameterType.GetGenericTypeDefinition() : p.ParameterType.IsGenericParameter ? null : p.ParameterType).SequenceEqual(parameters)); } /// <summary> /// Checks if the type is a <see cref="Task{T}"/>. /// </summary> /// <param name="type"> /// The type to check. /// </param> /// <returns> /// <c>true</c> if this is a task, <c>false</c> otherwise. /// </returns> public static bool IsTask(this Type type) { return type.IsConstructedGenericType && type.GetGenericTypeDefinition() == typeof(Task<>); } /// <summary> /// Checks if the type is a <see cref="Task{T}"/>, and if so, returns the result type of the task. /// </summary> /// <param name="type"> /// The type to unwrap. /// </param> /// <returns> /// A non-task type. /// </returns> public static Type UnwrapTasks(this Type type) { return type.IsTask() ? type.GenericTypeArguments[0] : type; } /// <summary> /// Gets the constructor. /// </summary> /// <param name="type"> /// The type to get the constructor from. /// </param> /// <param name="parameters"> /// The parameters. /// </param> /// <returns> /// The <see cref="ConstructorInfo"/>. /// </returns> [CanBeNull] public static ConstructorInfo GetConstructor(this Type type, params Type[] parameters) { return type.GetTypeInfo().DeclaredConstructors.FirstOrDefault(c => c.GetParameters().Select(p => p.ParameterType).SequenceEqual(parameters)); } /// <summary> /// Gets the interface if the <paramref name="type"/> implements it. When <paramref name="interfaceType"/> is a generic type definition, /// the constructed generic interface is returned. /// </summary> /// <param name="type"> /// The type. /// </param> /// <param name="interfaceType"> /// The interface type. /// </param> /// <returns> /// The <see cref="Type"/>. /// </returns> [CanBeNull] public static Type GetInterface(this Type type, Type interfaceType) { if (interfaceType.GetTypeInfo().IsGenericTypeDefinition) { return type.GetTypeInfo().IsGenericType && type.GetGenericTypeDefinition() == interfaceType ? type : type.GetTypeInfo().ImplementedInterfaces.FirstOrDefault(i => i.GetTypeInfo().IsGenericType && i.GetGenericTypeDefinition() == interfaceType); } return type.GetTypeInfo().ImplementedInterfaces.Contains(interfaceType) || type == interfaceType ? interfaceType : null; } /// <summary> /// Gets the base type if the <paramref name="type"/> implements it. When <paramref name="baseType"/> is a generic type definition, /// the constructed generic interface is returned. /// </summary> /// <param name="type"> /// The type. /// </param> /// <param name="baseType"> /// The base type. /// </param> /// <returns> /// The <see cref="Type"/>. /// </returns> [CanBeNull] public static Type GetBaseType(this Type type, Type baseType) { var baseTypeInfo = baseType.GetTypeInfo(); while (type != null) { var typeInfo = type.GetTypeInfo(); if (type == baseType || baseTypeInfo.IsGenericTypeDefinition && type.IsConstructedGenericType && type.GetGenericTypeDefinition() == baseType) { return type; } type = typeInfo.BaseType; } return null; } /// <summary> /// Gets a generic method on a type. /// </summary> /// <param name="type"> /// The type. /// </param> /// <param name="name"> /// The name of the method. /// </param> /// <param name="parameters"> /// The types of the parameters. /// </param> /// <returns> /// The <see cref="MethodInfo"/>. /// </returns> public static MethodInfo GetMethod(this Type type, string name, params Type[] parameters) { return type.GetRuntimeMethod(name, parameters); } /// <summary> /// The has interface. /// </summary> /// <param name="type"> /// The type. /// </param> /// <param name="interfaceType"> /// The interface type. /// </param> /// <returns> /// The <see cref="bool"/>. /// </returns> public static bool HasInterface(this Type type, Type interfaceType) { return type.GetInterface(interfaceType) != null; } } }
// 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. using System; using System.Collections.Generic; using System.IO; using System.Linq; using Microsoft.PythonTools.Infrastructure; using Microsoft.VisualStudio.TestTools.UnitTesting; using TestUtilities; using TestUtilities.Python; namespace PythonToolsTests { [TestClass] public class PathUtilsTests { [ClassInitialize] public static void DoDeployment(TestContext context) { AssertListener.Initialize(); } [TestMethod, Priority(UnitTestPriority.P0)] public void TestMakeUri() { Assert.AreEqual(@"C:\a\b\c\", PathUtils.MakeUri(@"C:\a\b\c", true, UriKind.Absolute).LocalPath); Assert.AreEqual(@"C:\a\b\c", PathUtils.MakeUri(@"C:\a\b\c", false, UriKind.Absolute).LocalPath); Assert.AreEqual(@"\\a\b\c\", PathUtils.MakeUri(@"\\a\b\c", true, UriKind.Absolute).LocalPath); Assert.AreEqual(@"\\a\b\c", PathUtils.MakeUri(@"\\a\b\c", false, UriKind.Absolute).LocalPath); Assert.AreEqual(@"ftp://me@a.net:123/b/c/", PathUtils.MakeUri(@"ftp://me@a.net:123/b/c", true, UriKind.Absolute).AbsoluteUri); Assert.AreEqual(@"ftp://me@a.net:123/b/c", PathUtils.MakeUri(@"ftp://me@a.net:123/b/c", false, UriKind.Absolute).AbsoluteUri); Assert.AreEqual(@"C:\a b c\d e f\g\", PathUtils.MakeUri(@"C:\a b c\d e f\g", true, UriKind.Absolute).LocalPath); Assert.AreEqual(@"C:\a b c\d e f\g", PathUtils.MakeUri(@"C:\a b c\d e f\g", false, UriKind.Absolute).LocalPath); Assert.AreEqual(@"C:\a\b\c\", PathUtils.MakeUri(@"C:\a\b\c\d\..", true, UriKind.Absolute).LocalPath); Assert.AreEqual(@"C:\a\b\c\e", PathUtils.MakeUri(@"C:\a\b\c\d\..\e", false, UriKind.Absolute).LocalPath); Assert.AreEqual(@"\\a\b\c\", PathUtils.MakeUri(@"\\a\b\c\d\..", true, UriKind.Absolute).LocalPath); Assert.AreEqual(@"\\a\b\c\e", PathUtils.MakeUri(@"\\a\b\c\d\..\e", false, UriKind.Absolute).LocalPath); Assert.AreEqual(@"ftp://me@a.net:123/b/c/", PathUtils.MakeUri(@"ftp://me@a.net:123/b/c/d/..", true, UriKind.Absolute).AbsoluteUri); Assert.AreEqual(@"ftp://me@a.net:123/b/c/e", PathUtils.MakeUri(@"ftp://me@a.net:123/b/c/d/../e", false, UriKind.Absolute).AbsoluteUri); Assert.IsTrue(PathUtils.MakeUri(@"C:\a\b", false, UriKind.RelativeOrAbsolute).IsAbsoluteUri); Assert.IsTrue(PathUtils.MakeUri(@"\\a\b", false, UriKind.RelativeOrAbsolute).IsAbsoluteUri); Assert.IsTrue(PathUtils.MakeUri(@"ftp://me@a.net:123/b/c", false, UriKind.RelativeOrAbsolute).IsAbsoluteUri); Assert.IsFalse(PathUtils.MakeUri(@"a\b", false, UriKind.RelativeOrAbsolute).IsAbsoluteUri); Assert.IsFalse(PathUtils.MakeUri(@"\a\b", false, UriKind.RelativeOrAbsolute).IsAbsoluteUri); Assert.IsFalse(PathUtils.MakeUri(@".\a\b", false, UriKind.RelativeOrAbsolute).IsAbsoluteUri); Assert.IsFalse(PathUtils.MakeUri(@"..\a\b", false, UriKind.RelativeOrAbsolute).IsAbsoluteUri); Assert.IsTrue(PathUtils.MakeUri(@"C:\a\b", false, UriKind.RelativeOrAbsolute).IsFile); Assert.IsTrue(PathUtils.MakeUri(@"C:\a\b", true, UriKind.RelativeOrAbsolute).IsFile); Assert.IsTrue(PathUtils.MakeUri(@"\\a\b", false, UriKind.RelativeOrAbsolute).IsFile); Assert.IsTrue(PathUtils.MakeUri(@"\\a\b", true, UriKind.RelativeOrAbsolute).IsFile); Assert.IsFalse(PathUtils.MakeUri(@"ftp://me@a.net:123/b/c", false, UriKind.RelativeOrAbsolute).IsFile); Assert.IsFalse(PathUtils.MakeUri(@"ftp://me@a.net:123/b/c", true, UriKind.RelativeOrAbsolute).IsFile); Assert.AreEqual(@"..\a\b\c\", PathUtils.MakeUri(@"..\a\b\c", true, UriKind.Relative).ToString()); Assert.AreEqual(@"..\a\b\c", PathUtils.MakeUri(@"..\a\b\c", false, UriKind.Relative).ToString()); Assert.AreEqual(@"..\a b c\", PathUtils.MakeUri(@"..\a b c", true, UriKind.Relative).ToString()); Assert.AreEqual(@"..\a b c", PathUtils.MakeUri(@"..\a b c", false, UriKind.Relative).ToString()); Assert.AreEqual(@"../a/b/c\", PathUtils.MakeUri(@"../a/b/c", true, UriKind.Relative).ToString()); Assert.AreEqual(@"../a/b/c", PathUtils.MakeUri(@"../a/b/c", false, UriKind.Relative).ToString()); Assert.AreEqual(@"../a b c\", PathUtils.MakeUri(@"../a b c", true, UriKind.Relative).ToString()); Assert.AreEqual(@"../a b c", PathUtils.MakeUri(@"../a b c", false, UriKind.Relative).ToString()); } private static void AssertIsNotSameDirectory(string first, string second) { Assert.IsFalse(PathUtils.IsSameDirectory(first, second), string.Format("First: {0} Second: {1}", first, second)); first = first.Replace("\\", "/"); second = second.Replace("\\", "/"); Assert.IsFalse(PathUtils.IsSameDirectory(first, second), string.Format("First: {0} Second: {1}", first, second)); } private static void AssertIsSameDirectory(string first, string second) { Assert.IsTrue(PathUtils.IsSameDirectory(first, second), string.Format("First: {0} Second: {1}", first, second)); first = first.Replace("\\", "/"); second = second.Replace("\\", "/"); Assert.IsTrue(PathUtils.IsSameDirectory(first, second), string.Format("First: {0} Second: {1}", first, second)); } private static void AssertIsNotSamePath(string first, string second) { Assert.IsFalse(PathUtils.IsSamePath(first, second), string.Format("First: {0} Second: {1}", first, second)); first = first.Replace("\\", "/"); second = second.Replace("\\", "/"); Assert.IsFalse(PathUtils.IsSamePath(first, second), string.Format("First: {0} Second: {1}", first, second)); } private static void AssertIsSamePath(string first, string second) { Assert.IsTrue(PathUtils.IsSamePath(first, second), string.Format("First: {0} Second: {1}", first, second)); first = first.Replace("\\", "/"); second = second.Replace("\\", "/"); Assert.IsTrue(PathUtils.IsSamePath(first, second), string.Format("First: {0} Second: {1}", first, second)); } [TestMethod, Priority(UnitTestPriority.P0)] public void TestIsSamePath() { // These paths should all look like files. Separators are added to the end // to test the directory cases. Paths ending in "." or ".." are always directories, // and will fail the tests here. foreach (var testCase in Pairs( @"a\b\c", @"a\b\c", @"a\b\.\c", @"a\b\c", @"a\b\d\..\c", @"a\b\c", @"a\b\c", @"a\..\a\b\..\b\c\..\c" )) { foreach (var root in new[] { @"C:\", @"\\pc\Share\", @"ftp://me@ftp.home.net/" }) { string first, second; first = root + testCase.Item1; second = root + testCase.Item2; AssertIsSamePath(first, second); AssertIsNotSamePath(first + "\\", second); AssertIsNotSamePath(first, second + "\\"); AssertIsSamePath(first + "\\", second + "\\"); if (!root.StartsWith("ftp", StringComparison.OrdinalIgnoreCase)) { // Files are case-insensitive AssertIsSamePath(first.ToLowerInvariant(), second.ToUpperInvariant()); } else { // FTP is case-sensitive AssertIsNotSamePath(first.ToLowerInvariant(), second.ToUpperInvariant()); } AssertIsSameDirectory(first, second); AssertIsSameDirectory(first + "\\", second); AssertIsSameDirectory(first, second + "\\"); AssertIsSameDirectory(first + "\\", second + "\\"); if (!root.StartsWith("ftp", StringComparison.OrdinalIgnoreCase)) { // Files are case-insensitive AssertIsSameDirectory(first.ToLowerInvariant(), second.ToUpperInvariant()); } else { // FTP is case-sensitive AssertIsNotSameDirectory(first.ToLowerInvariant(), second.ToUpperInvariant()); } } } // The first part always resolves to a directory, regardless of whether there // is a separator at the end. foreach (var testCase in Pairs( @"a\b\c\..", @"a\b", @"a\b\c\..\..", @"a" )) { foreach (var root in new[] { @"C:\", @"\\pc\Share\", @"ftp://me@example.com/" }) { string first, second; first = root + testCase.Item1; second = root + testCase.Item2; AssertIsNotSamePath(first, second); AssertIsNotSamePath(first + "\\", second); AssertIsSamePath(first, second + "\\"); AssertIsSamePath(first + "\\", second + "\\"); AssertIsNotSamePath(first.ToLowerInvariant(), second.ToUpperInvariant()); AssertIsSameDirectory(first, second); AssertIsSameDirectory(first + "\\", second); AssertIsSameDirectory(first, second + "\\"); AssertIsSameDirectory(first + "\\", second + "\\"); if (!root.StartsWith("ftp", StringComparison.OrdinalIgnoreCase)) { // Files are case-insensitive AssertIsSameDirectory(first.ToLowerInvariant(), second.ToUpperInvariant()); } else { // FTP is case-sensitive AssertIsNotSameDirectory(first.ToLowerInvariant(), second.ToUpperInvariant()); } } } } [TestMethod, Priority(UnitTestPriority.P0)] public void TestCreateFriendlyDirectoryPath() { foreach (var testCase in Triples( @"C:\a\b", @"C:\", @"..\..", @"C:\a\b", @"C:\a", @"..", @"C:\a\b", @"C:\a\b", @".", @"C:\a\b", @"C:\a\b\c", @"c", @"C:\a\b", @"D:\a\b", @"D:\a\b", @"C:\a\b", @"C:\", @"..\..", @"\\pc\share\a\b", @"\\pc\share\", @"..\..", @"\\pc\share\a\b", @"\\pc\share\a", @"..", @"\\pc\share\a\b", @"\\pc\share\a\b", @".", @"\\pc\share\a\b", @"\\pc\share\a\b\c", @"c", @"\\pc\share\a\b", @"\\pc\othershare\a\b", @"..\..\..\othershare\a\b", @"ftp://me@example.com/a/b", @"ftp://me@example.com/", @"../..", @"ftp://me@example.com/a/b", @"ftp://me@example.com/a", @"..", @"ftp://me@example.com/a/b", @"ftp://me@example.com/a/b", @".", @"ftp://me@example.com/a/b", @"ftp://me@example.com/a/b/c", @"c", @"ftp://me@example.com/a/b", @"ftp://me@another.example.com/a/b", @"ftp://me@another.example.com/a/b" )) { var expected = testCase.Item3; var actual = PathUtils.CreateFriendlyDirectoryPath(testCase.Item1, testCase.Item2); Assert.AreEqual(expected, actual); } } [TestMethod, Priority(UnitTestPriority.P0)] public void TestCreateFriendlyFilePath() { foreach (var testCase in Triples( @"C:\a\b", @"C:\file.exe", @"..\..\file.exe", @"C:\a\b", @"C:\a\file.exe", @"..\file.exe", @"C:\a\b", @"C:\a\b\file.exe", @"file.exe", @"C:\a\b", @"C:\a\b\c\file.exe", @"c\file.exe", @"C:\a\b", @"D:\a\b\file.exe", @"D:\a\b\file.exe", @"\\pc\share\a\b", @"\\pc\share\file.exe", @"..\..\file.exe", @"\\pc\share\a\b", @"\\pc\share\a\file.exe", @"..\file.exe", @"\\pc\share\a\b", @"\\pc\share\a\b\file.exe", @"file.exe", @"\\pc\share\a\b", @"\\pc\share\a\b\c\file.exe", @"c\file.exe", @"\\pc\share\a\b", @"\\pc\othershare\a\b\file.exe", @"..\..\..\othershare\a\b\file.exe", @"ftp://me@example.com/a/b", @"ftp://me@example.com/file.exe", @"../../file.exe", @"ftp://me@example.com/a/b", @"ftp://me@example.com/a/file.exe", @"../file.exe", @"ftp://me@example.com/a/b", @"ftp://me@example.com/a/b/file.exe", @"file.exe", @"ftp://me@example.com/a/b", @"ftp://me@example.com/a/b/c/file.exe", @"c/file.exe", @"ftp://me@example.com/a/b", @"ftp://me@another.example.com/a/b/file.exe", @"ftp://me@another.example.com/a/b/file.exe" )) { var expected = testCase.Item3; var actual = PathUtils.CreateFriendlyFilePath(testCase.Item1, testCase.Item2); Assert.AreEqual(expected, actual); } } [TestMethod, Priority(UnitTestPriority.P0)] public void TestGetRelativeDirectoryPath() { foreach (var testCase in Triples( @"C:\a\b", @"C:\", @"..\..\", @"C:\a\b", @"C:\a", @"..\", @"C:\a\b\c", @"C:\a", @"..\..\", @"C:\a\b", @"C:\a\b", @"", @"C:\a\b", @"C:\a\b\c", @"c\", @"C:\a\b", @"D:\a\b", @"D:\a\b\", @"C:\a\b", @"C:\d\e", @"..\..\d\e\", @"\\root\share\path", @"\\Root\Share", @"..\", @"\\root\share\path", @"\\Root\share\Path\subpath", @"subpath\", @"\\root\share\path\subpath", @"\\Root\share\Path\othersubpath", @"..\othersubpath\", @"\\root\share\path", @"\\root\othershare\path", @"..\..\othershare\path\", @"\\root\share\path", @"\\root\share\otherpath\", @"..\otherpath\", @"ftp://me@example.com/share/path", @"ftp://me@example.com/", @"../../", @"ftp://me@example.com/share/path", @"ftp://me@example.com/Share", @"../../Share/", @"ftp://me@example.com/share/path", @"ftp://me@example.com/share/path/subpath", @"subpath/", @"ftp://me@example.com/share/path", @"ftp://me@example.com/share/Path/subpath", @"../Path/subpath/", @"ftp://me@example.com/share/path/subpath", @"ftp://me@example.com/share/path/othersubpath", @"../othersubpath/", @"ftp://me@example.com/share/path/subpath", @"ftp://me@example.com/share/Path/othersubpath", @"../../Path/othersubpath/", @"ftp://me@example.com/path", @"ftp://me@example.com/otherpath/", @"../otherpath/", @"C:\a\b\c\d", @"C:\.dottedname", @"..\..\..\..\.dottedname\", @"C:\a\b\c\d", @"C:\..dottedname", @"..\..\..\..\..dottedname\", @"C:\a\b\c\d", @"C:\a\.dottedname", @"..\..\..\.dottedname\", @"C:\a\b\c\d", @"C:\a\..dottedname", @"..\..\..\..dottedname\", "C:\\a\\b\\", @"C:\a\b", @"", @"C:\a\b", "C:\\a\\b\\", @"" )) { var expected = testCase.Item3; var actual = PathUtils.GetRelativeDirectoryPath(testCase.Item1, testCase.Item2); Assert.AreEqual(expected, actual, string.Format("From {0} to {1}", testCase.Item1, testCase.Item2)); } } [TestMethod, Priority(UnitTestPriority.P0)] public void TestGetRelativeFilePath() { foreach (var testCase in Triples( @"C:\a\b", @"C:\file.exe", @"..\..\file.exe", @"C:\a\b", @"C:\a\file.exe", @"..\file.exe", @"C:\a\b\c", @"C:\a\file.exe", @"..\..\file.exe", @"C:\a\b", @"C:\A\B\file.exe", @"file.exe", @"C:\a\b", @"C:\a\B\C\file.exe", @"C\file.exe", @"C:\a\b", @"D:\a\b\file.exe", @"D:\a\b\file.exe", @"C:\a\b", @"C:\d\e\file.exe", @"..\..\d\e\file.exe", @"\\root\share\path", @"\\Root\Share\file.exe", @"..\file.exe", @"\\root\share\path", @"\\Root\Share\Path\file.exe", @"file.exe", @"\\root\share\path", @"\\Root\share\Path\subpath\file.exe", @"subpath\file.exe", @"\\root\share\path\subpath", @"\\Root\share\Path\othersubpath\file.exe", @"..\othersubpath\file.exe", @"\\root\share\path", @"\\root\othershare\path\file.exe", @"..\..\othershare\path\file.exe", @"\\root\share\path", @"\\root\share\otherpath\file.exe", @"..\otherpath\file.exe", @"\\root\share\", @"\\otherroot\share\file.exe", @"\\otherroot\share\file.exe", @"ftp://me@example.com/share/path", @"ftp://me@example.com/file.exe", @"../../file.exe", @"ftp://me@example.com/share/path", @"ftp://me@example.com/Share/file.exe", @"../../Share/file.exe", @"ftp://me@example.com/share/path", @"ftp://me@example.com/share/path/subpath/file.exe", @"subpath/file.exe", @"ftp://me@example.com/share/path", @"ftp://me@example.com/share/Path/subpath/file.exe", @"../Path/subpath/file.exe", @"ftp://me@example.com/share/path/subpath", @"ftp://me@example.com/share/path/othersubpath/file.exe", @"../othersubpath/file.exe", @"ftp://me@example.com/share/path/subpath", @"ftp://me@example.com/share/Path/othersubpath/file.exe", @"../../Path/othersubpath/file.exe", @"ftp://me@example.com/path", @"ftp://me@example.com/otherpath/file.exe", @"../otherpath/file.exe", @"C:\a\b", "C:\\a\\b\\", @"", // This is the expected behavior for GetRelativeFilePath // because the 'b' in the second part is assumed to be a file // and hence may be different to the directory 'b' in the first // part. // GetRelativeDirectoryPath returns an empty string, because it // assumes that both paths are directories. "C:\\a\\b\\", @"C:\a\b", @"..\b", // Ensure end-separators are retained when the target is a // directory rather than a file. "C:\\a\\", "C:\\a\\b\\", "b\\", "C:\\a", "C:\\a\\b\\", "b\\" )) { var expected = testCase.Item3; var actual = PathUtils.GetRelativeFilePath(testCase.Item1, testCase.Item2); Assert.AreEqual(expected, actual, string.Format("From {0} to {1}", testCase.Item1, testCase.Item2)); } } [TestMethod, Priority(UnitTestPriority.P0)] public void TestGetAbsoluteDirectoryPath() { foreach (var testCase in Triples( @"C:\a\b", @"\", @"C:\", @"C:\a\b", @"..\", @"C:\a\", @"C:\a\b", @"", @"C:\a\b\", @"C:\a\b", @".", @"C:\a\b\", @"C:\a\b", @"c", @"C:\a\b\c\", @"C:\a\b", @"D:\a\b", @"D:\a\b\", @"C:\a\b", @"\d\e", @"C:\d\e\", @"C:\a\b\c\d", @"..\..\..\..", @"C:\", @"\\root\share\path", @"..", @"\\root\share\", @"\\root\share\path", @"subpath", @"\\root\share\path\subpath\", @"\\root\share\path", @"..\otherpath\", @"\\root\share\otherpath\", @"ftp://me@example.com/path", @"..", @"ftp://me@example.com/", @"ftp://me@example.com/path", @"subpath", @"ftp://me@example.com/path/subpath/", @"ftp://me@example.com/path", @"../otherpath/", @"ftp://me@example.com/otherpath/" )) { var expected = testCase.Item3; var actual = PathUtils.GetAbsoluteDirectoryPath(testCase.Item1, testCase.Item2); Assert.AreEqual(expected, actual); } } [TestMethod, Priority(UnitTestPriority.P0)] public void TestGetAbsoluteFilePath() { foreach (var testCase in Triples( @"C:\a\b", @"\file.exe", @"C:\file.exe", @"C:\a\b", @"..\file.exe", @"C:\a\file.exe", @"C:\a\b", @"file.exe", @"C:\a\b\file.exe", @"C:\a\b", @"c\file.exe", @"C:\a\b\c\file.exe", @"C:\a\b", @"D:\a\b\file.exe", @"D:\a\b\file.exe", @"C:\a\b", @"\d\e\file.exe", @"C:\d\e\file.exe", @"C:\a\b\c\d\", @"..\..\..\..\", @"C:\", @"\\root\share\path", @"..\file.exe", @"\\root\share\file.exe", @"\\root\share\path", @"file.exe", @"\\root\share\path\file.exe", @"\\root\share\path", @"subpath\file.exe", @"\\root\share\path\subpath\file.exe", @"\\root\share\path", @"..\otherpath\file.exe", @"\\root\share\otherpath\file.exe", @"ftp://me@example.com/path", @"../file.exe", @"ftp://me@example.com/file.exe", @"ftp://me@example.com/path", @"file.exe", @"ftp://me@example.com/path/file.exe", @"ftp://me@example.com/path", @"subpath/file.exe", @"ftp://me@example.com/path/subpath/file.exe", @"ftp://me@example.com/path", @"../otherpath/file.exe", @"ftp://me@example.com/otherpath/file.exe" )) { var expected = testCase.Item3; var actual = PathUtils.GetAbsoluteFilePath(testCase.Item1, testCase.Item2); Assert.AreEqual(expected, actual); } } [TestMethod, Priority(UnitTestPriority.P0)] public void TestNormalizeDirectoryPath() { foreach (var testCase in Pairs( @"a\b\c", @"a\b\c\", @"a\b\.\c", @"a\b\c\", @"a\b\d\..\c", @"a\b\c\", @"a\b\\c", @"a\b\c\" )) { foreach (var root in new[] { "", @".\", @"..\", @"\" }) { var expected = (root == @".\" ? "" : root) + testCase.Item2; var actual = PathUtils.NormalizeDirectoryPath(root + testCase.Item1); Assert.AreEqual(expected, actual); } } foreach (var testCase in Pairs( @"a\b\c", @"a\b\c\", @"a\b\.\c", @"a\b\c\", @"a\b\d\..\c", @"a\b\c\", @"a\..\..\b", @"b\" )) { foreach (var root in new[] { @"C:\", @"\\pc\share\", @"ftp://me@example.com/" }) { var expected = root + testCase.Item2; var actual = PathUtils.NormalizeDirectoryPath(root + testCase.Item1); if (root.StartsWith("ftp", StringComparison.OrdinalIgnoreCase)) { expected = expected.Replace('\\', '/'); } Assert.AreEqual(expected, actual); actual = PathUtils.NormalizeDirectoryPath(root + testCase.Item1 + @"\"); Assert.AreEqual(expected, actual); } } } [TestMethod, Priority(UnitTestPriority.P0)] public void TestNormalizePath() { foreach (var testCase in Pairs( @"a\b\c", @"a\b\c", @"a\b\.\c", @"a\b\c", @"a\b\d\..\c", @"a\b\c", @"a\b\\c", @"a\b\c" )) { foreach (var root in new[] { "", @".\", @"..\", @"\" }) { var expected = (root == @".\" ? "" : root) + testCase.Item2; var actual = PathUtils.NormalizePath(root + testCase.Item1); Assert.AreEqual(expected, actual); expected += @"\"; actual = PathUtils.NormalizePath(root + testCase.Item1 + @"\"); Assert.AreEqual(expected, actual); } } foreach (var testCase in Pairs( @"a\b\c", @"a\b\c", @"a\b\.\c", @"a\b\c", @"a\b\d\..\c", @"a\b\c", @"a\..\..\b", @"b" )) { foreach (var root in new[] { @"C:\", @"\\pc\share\", @"ftp://me@example.com/" }) { var expected = root + testCase.Item2; var actual = PathUtils.NormalizePath(root + testCase.Item1); if (root.StartsWith("ftp", StringComparison.OrdinalIgnoreCase)) { expected = expected.Replace('\\', '/'); } Assert.AreEqual(expected, actual); expected += @"\"; actual = PathUtils.NormalizePath(root + testCase.Item1 + @"\"); if (root.StartsWith("ftp", StringComparison.OrdinalIgnoreCase)) { expected = expected.Replace('\\', '/'); } Assert.AreEqual(expected, actual); } } } [TestMethod, Priority(UnitTestPriority.P0)] public void TestTrimEndSeparator() { // TrimEndSeparator uses System.IO.Path.(Alt)DirectorySeparatorChar // Here we assume these are '\\' and '/' foreach (var testCase in Pairs( @"no separator", @"no separator", @"one slash/", @"one slash", @"two slashes//", @"two slashes/", @"one backslash\", @"one backslash", @"two backslashes\\", @"two backslashes\", @"mixed/\", @"mixed/", @"mixed\/", @"mixed\", @"/leading", @"/leading", @"\leading", @"\leading", @"wit/hin", @"wit/hin", @"wit\hin", @"wit\hin", @"C:\a\", @"C:\a", @"C:\", @"C:\", @"ftp://a/", @"ftp://a", @"ftp://", @"ftp://" )) { var expected = testCase.Item2; var actual = PathUtils.TrimEndSeparator(testCase.Item1); Assert.AreEqual(expected, actual); } } [TestMethod, Priority(UnitTestPriority.P0)] public void TestIsSubpathOf() { // Positive tests foreach (var testCase in Pairs( @"C:\a\b", @"C:\A\B", @"C:\a\b\", @"C:\A\B", // IsSubpathOf has a special case for this @"C:\a\b", @"C:\A\B\C", @"C:\a\b\", @"C:\a\b\c", // IsSubpathOf has a quick path for this @"C:\a\b\", @"C:\A\B\C", // Quick path should not be taken @"C:", @"C:\a\b\", @"C:\a\b", @"C:\A\X\..\B\C" )) { Assert.IsTrue(PathUtils.IsSubpathOf(testCase.Item1, testCase.Item2), string.Format("{0} should be subpath of {1}", testCase.Item2, testCase.Item1)); } // Negative tests foreach (var testCase in Pairs( @"C:\a\b\c", @"C:\A\B", @"C:\a\bcd", @"c:\a\b\cd", // Quick path should not be taken @"C:\a\bcd", @"C:\A\B\CD", // Quick path should not be taken @"C:\a\b", @"D:\A\B\C", @"C:\a\b\c", @"C:\B\A\C\D", @"C:\a\b\", @"C:\a\b\..\x\c" // Quick path should not be taken )) { Assert.IsFalse(PathUtils.IsSubpathOf(testCase.Item1, testCase.Item2), string.Format("{0} should not be subpath of {1}", testCase.Item2, testCase.Item1)); } } [TestMethod, Priority(UnitTestPriority.P0)] public void TestGetLastDirectoryName() { foreach (var testCase in Pairs( @"a\b\c", "b", @"a\b\", "b", @"a\b\c\", "c", @"a\b\.\c", "b", @"a\b\.\.\.\.\.\.\c", "b" )) { foreach (var scheme in new[] { "", "C:\\", "\\", ".\\", "\\\\share\\root\\", "ftp://" }) { var path = scheme + testCase.Item1; Assert.AreEqual(testCase.Item2, PathUtils.GetLastDirectoryName(path), "Path: " + path); if (path.IndexOf('.') >= 0) { // Path.GetFileName will always fail on these, so don't // even bother testing. continue; } string ioPathResult; try { ioPathResult = Path.GetFileName(PathUtils.TrimEndSeparator(Path.GetDirectoryName(path))); } catch (ArgumentException) { continue; } Assert.AreEqual( PathUtils.GetLastDirectoryName(path), ioPathResult ?? string.Empty, "Did not match Path.GetFileName(...) result for " + path ); } } } [TestMethod, Priority(UnitTestPriority.P0)] public void TestGetParentOfDirectory() { foreach (var testCase in Pairs( @"a\b\c", @"a\b\", @"a\b\", @"a\", @"a\b\c\", @"a\b\" )) { foreach (var scheme in new[] { "", "C:\\", "\\", ".\\", "\\\\share\\root\\", "ftp://" }) { var path = scheme + testCase.Item1; var expected = scheme + testCase.Item2; Assert.AreEqual(expected, PathUtils.GetParent(path), "Path: " + path); if (scheme.Contains("://")) { // Path.GetFileName will always fail on these, so don't // even bother testing. continue; } string ioPathResult; try { ioPathResult = Path.GetDirectoryName(PathUtils.TrimEndSeparator(path)) + Path.DirectorySeparatorChar; } catch (ArgumentException) { continue; } Assert.AreEqual( PathUtils.GetParent(path), ioPathResult ?? string.Empty, "Did not match Path.GetDirectoryName(...) result for " + path ); } } } [TestMethod, Priority(UnitTestPriority.P0)] public void TestGetFileOrDirectoryName() { foreach (var testCase in Pairs( @"a\b\c", @"c", @"a\b\", @"b", @"a\b\c\", @"c", @"a", @"a", @"a\", @"a" )) { foreach (var scheme in new[] { "", "C:\\", "\\", ".\\", "\\\\share\\root\\", "ftp://" }) { var path = scheme + testCase.Item1; var expected = testCase.Item2; Assert.AreEqual(expected, PathUtils.GetFileOrDirectoryName(path), "Path: " + path); if (scheme.Contains("://")) { // Path.GetFileName will always fail on these, so don't // even bother testing. continue; } string ioPathResult; try { ioPathResult = PathUtils.GetFileOrDirectoryName(path); } catch (ArgumentException) { continue; } Assert.AreEqual( PathUtils.GetFileOrDirectoryName(path), ioPathResult ?? string.Empty, "Did not match Path.GetDirectoryName(...) result for " + path ); } } } [TestMethod, Priority(UnitTestPriority.P0)] public void TestEnumerateDirectories() { var root = Path.Combine(TestData.Root, "TestData"); var dirs = PathUtils.EnumerateDirectories(root).ToList(); Assert.AreNotEqual(0, dirs.Count); // Expect all paths to be rooted AssertUtil.ContainsExactly(dirs.Where(d => !Path.IsPathRooted(d))); // Expect all paths to be within Windows AssertUtil.ContainsExactly(dirs.Where(d => !PathUtils.IsSubpathOf(root, d))); dirs = PathUtils.EnumerateDirectories(root, recurse: false, fullPaths: false).ToList(); Assert.AreNotEqual(0, dirs.Count); // Expect all paths to be relative AssertUtil.ContainsExactly(dirs.Where(d => Path.IsPathRooted(d))); // Expect all paths to be within root AssertUtil.ContainsExactly(dirs.Where(d => !Directory.Exists(Path.Combine(root, d)))); } [TestMethod, Priority(UnitTestPriority.P0)] public void TestEnumerateFiles() { var root = Path.Combine(TestData.Root, "TestData"); var files = PathUtils.EnumerateFiles(root).ToList(); Assert.AreNotEqual(0, files.Count); // Expect all paths to be rooted AssertUtil.ContainsExactly(files.Where(f => !Path.IsPathRooted(f))); // Expect all paths to be within Windows AssertUtil.ContainsExactly(files.Where(f => !PathUtils.IsSubpathOf(root, f))); // Expect multiple extensions Assert.AreNotEqual(1, files.Select(f => Path.GetExtension(f)).ToSet().Count); files = PathUtils.EnumerateFiles(root, recurse: false, fullPaths: false).ToList(); Assert.AreNotEqual(0, files.Count); // Expect all paths to be relative AssertUtil.ContainsExactly(files.Where(f => Path.IsPathRooted(f))); // Expect all paths to be only filenames AssertUtil.ContainsExactly(files.Where(f => f.IndexOfAny(new[] { '\\', '/' }) >= 0)); // Expect all paths to be within root AssertUtil.ContainsExactly(files.Where(f => !File.Exists(Path.Combine(root, f)))); files = PathUtils.EnumerateFiles(root, "*.sln", recurse: false, fullPaths: false).ToList(); Assert.AreNotEqual(0, files.Count); // Expect all paths to be relative AssertUtil.ContainsExactly(files.Where(f => Path.IsPathRooted(f))); // Expect all paths to be within root AssertUtil.ContainsExactly(files.Where(f => !File.Exists(Path.Combine(root, f)))); // Expect only one extension AssertUtil.ContainsExactly(files.Select(f => Path.GetExtension(f).ToLowerInvariant()).ToSet(), ".sln"); } [TestMethod, Priority(UnitTestPriority.P0)] public void TestFindFile() { var root = TestData.GetPath("TestData"); // File is too deep - should not find Assert.IsNull(PathUtils.FindFile(root, "9E90EF25FCE648B397D0CCEC67305A68.txt", depthLimit: 0)); // Find file with BFS Assert.IsNotNull(PathUtils.FindFile(root, "9E90EF25FCE648B397D0CCEC67305A68.txt", depthLimit: 1)); // Find file with correct firstCheck Assert.IsNotNull(PathUtils.FindFile(root, "9E90EF25FCE648B397D0CCEC67305A68.txt", depthLimit: 1, firstCheck: new[] { "FindFile" })); // Find file with incorrect firstCheck Assert.IsNotNull(PathUtils.FindFile(root, "9E90EF25FCE648B397D0CCEC67305A68.txt", depthLimit: 1, firstCheck: new[] { "FindFileX" })); // File is too deep Assert.IsNull(PathUtils.FindFile(root, "D75BD8CE1BBA41A7A2547CF3652AD3AF.txt", depthLimit: 0)); Assert.IsNull(PathUtils.FindFile(root, "D75BD8CE1BBA41A7A2547CF3652AD3AF.txt", depthLimit: 1)); Assert.IsNull(PathUtils.FindFile(root, "D75BD8CE1BBA41A7A2547CF3652AD3AF.txt", depthLimit: 2)); Assert.IsNull(PathUtils.FindFile(root, "D75BD8CE1BBA41A7A2547CF3652AD3AF.txt", depthLimit: 3)); // File is found Assert.IsNotNull(PathUtils.FindFile(root, "D75BD8CE1BBA41A7A2547CF3652AD3AF.txt", depthLimit: 4)); } private IEnumerable<Tuple<string, string>> Pairs(params string[] items) { using (var e = items.Cast<string>().GetEnumerator()) { while (e.MoveNext()) { var first = e.Current; if (!e.MoveNext()) { yield break; } var second = e.Current; yield return new Tuple<string, string>(first, second); } } } private IEnumerable<Tuple<string, string, string>> Triples(params string[] items) { using (var e = items.Cast<string>().GetEnumerator()) { while (e.MoveNext()) { var first = e.Current; if (!e.MoveNext()) { yield break; } var second = e.Current; if (!e.MoveNext()) { yield break; } var third = e.Current; yield return new Tuple<string, string, string>(first, second, third); } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Net.Security; using System.Runtime.InteropServices; using System.Security.Authentication; using System.Security.Authentication.ExtendedProtection; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using Microsoft.Win32.SafeHandles; internal static partial class Interop { internal static partial class OpenSsl { private static Ssl.SslCtxSetVerifyCallback s_verifyClientCertificate = VerifyClientCertificate; #region internal methods internal static SafeChannelBindingHandle QueryChannelBinding(SafeSslHandle context, ChannelBindingKind bindingType) { SafeChannelBindingHandle bindingHandle; switch (bindingType) { case ChannelBindingKind.Endpoint: bindingHandle = new SafeChannelBindingHandle(bindingType); QueryEndPointChannelBinding(context, bindingHandle); break; case ChannelBindingKind.Unique: bindingHandle = new SafeChannelBindingHandle(bindingType); QueryUniqueChannelBinding(context, bindingHandle); break; default: // Keeping parity with windows, we should return null in this case. bindingHandle = null; break; } return bindingHandle; } internal static SafeSslHandle AllocateSslContext(SslProtocols protocols, SafeX509Handle certHandle, SafeEvpPKeyHandle certKeyHandle, EncryptionPolicy policy, bool isServer, bool remoteCertRequired) { SafeSslHandle context = null; IntPtr method = GetSslMethod(protocols); using (SafeSslContextHandle innerContext = Ssl.SslCtxCreate(method)) { if (innerContext.IsInvalid) { throw CreateSslException(SR.net_allocate_ssl_context_failed); } // Configure allowed protocols. It's ok to use DangerousGetHandle here without AddRef/Release as we just // create the handle, it's rooted by the using, no one else has a reference to it, etc. Ssl.SetProtocolOptions(innerContext.DangerousGetHandle(), protocols); // The logic in SafeSslHandle.Disconnect is simple because we are doing a quiet // shutdown (we aren't negotiating for session close to enable later session // restoration). // // If you find yourself wanting to remove this line to enable bidirectional // close-notify, you'll probably need to rewrite SafeSslHandle.Disconnect(). // https://www.openssl.org/docs/manmaster/ssl/SSL_shutdown.html Ssl.SslCtxSetQuietShutdown(innerContext); if (!Ssl.SetEncryptionPolicy(innerContext, policy)) { throw new PlatformNotSupportedException(SR.Format(SR.net_ssl_encryptionpolicy_notsupported, policy)); } if (certHandle != null && certKeyHandle != null) { SetSslCertificate(innerContext, certHandle, certKeyHandle); } if (remoteCertRequired) { Debug.Assert(isServer, "isServer flag should be true"); Ssl.SslCtxSetVerify(innerContext, s_verifyClientCertificate); //update the client CA list UpdateCAListFromRootStore(innerContext); } context = SafeSslHandle.Create(innerContext, isServer); Debug.Assert(context != null, "Expected non-null return value from SafeSslHandle.Create"); if (context.IsInvalid) { context.Dispose(); throw CreateSslException(SR.net_allocate_ssl_context_failed); } } return context; } internal static bool DoSslHandshake(SafeSslHandle context, byte[] recvBuf, int recvOffset, int recvCount, out byte[] sendBuf, out int sendCount) { sendBuf = null; sendCount = 0; if ((recvBuf != null) && (recvCount > 0)) { BioWrite(context.InputBio, recvBuf, recvOffset, recvCount); } int retVal = Ssl.SslDoHandshake(context); if (retVal != 1) { Exception innerError; Ssl.SslErrorCode error = GetSslError(context, retVal, out innerError); if ((retVal != -1) || (error != Ssl.SslErrorCode.SSL_ERROR_WANT_READ)) { throw new SslException(SR.Format(SR.net_ssl_handshake_failed_error, error), innerError); } } sendCount = Crypto.BioCtrlPending(context.OutputBio); if (sendCount > 0) { sendBuf = new byte[sendCount]; try { sendCount = BioRead(context.OutputBio, sendBuf, sendCount); } finally { if (sendCount <= 0) { sendBuf = null; sendCount = 0; } } } bool stateOk = Ssl.IsSslStateOK(context); if (stateOk) { context.MarkHandshakeCompleted(); } return stateOk; } internal static int Encrypt(SafeSslHandle context, byte[] input, int offset, int count, ref byte[] output, out Ssl.SslErrorCode errorCode) { Debug.Assert(input != null); Debug.Assert(offset >= 0); Debug.Assert(count >= 0); Debug.Assert(offset <= input.Length); Debug.Assert(input.Length - offset >= count); errorCode = Ssl.SslErrorCode.SSL_ERROR_NONE; int retVal; unsafe { fixed (byte* fixedBuffer = input) { retVal = Ssl.SslWrite(context, fixedBuffer + offset, count); } } if (retVal != count) { Exception innerError; errorCode = GetSslError(context, retVal, out innerError); retVal = 0; switch (errorCode) { // indicate end-of-file case Ssl.SslErrorCode.SSL_ERROR_ZERO_RETURN: case Ssl.SslErrorCode.SSL_ERROR_WANT_READ: break; default: throw new SslException(SR.Format(SR.net_ssl_encrypt_failed, errorCode), innerError); } } else { int capacityNeeded = Crypto.BioCtrlPending(context.OutputBio); if (output == null || output.Length < capacityNeeded) { output = new byte[capacityNeeded]; } retVal = BioRead(context.OutputBio, output, capacityNeeded); } return retVal; } internal static int Decrypt(SafeSslHandle context, byte[] outBuffer, int count, out Ssl.SslErrorCode errorCode) { errorCode = Ssl.SslErrorCode.SSL_ERROR_NONE; int retVal = BioWrite(context.InputBio, outBuffer, 0, count); if (retVal == count) { retVal = Ssl.SslRead(context, outBuffer, outBuffer.Length); if (retVal > 0) { count = retVal; } } if (retVal != count) { Exception innerError; errorCode = GetSslError(context, retVal, out innerError); retVal = 0; switch (errorCode) { // indicate end-of-file case Ssl.SslErrorCode.SSL_ERROR_ZERO_RETURN: break; case Ssl.SslErrorCode.SSL_ERROR_WANT_READ: // update error code to renegotiate if renegotiate is pending, otherwise make it SSL_ERROR_WANT_READ errorCode = Ssl.IsSslRenegotiatePending(context) ? Ssl.SslErrorCode.SSL_ERROR_RENEGOTIATE : Ssl.SslErrorCode.SSL_ERROR_WANT_READ; break; default: throw new SslException(SR.Format(SR.net_ssl_decrypt_failed, errorCode), innerError); } } return retVal; } internal static SafeX509Handle GetPeerCertificate(SafeSslHandle context) { return Ssl.SslGetPeerCertificate(context); } internal static SafeSharedX509StackHandle GetPeerCertificateChain(SafeSslHandle context) { return Ssl.SslGetPeerCertChain(context); } #endregion #region private methods private static void QueryEndPointChannelBinding(SafeSslHandle context, SafeChannelBindingHandle bindingHandle) { using (SafeX509Handle certSafeHandle = GetPeerCertificate(context)) { if (certSafeHandle == null || certSafeHandle.IsInvalid) { throw CreateSslException(SR.net_ssl_invalid_certificate); } bool gotReference = false; try { certSafeHandle.DangerousAddRef(ref gotReference); using (X509Certificate2 cert = new X509Certificate2(certSafeHandle.DangerousGetHandle())) using (HashAlgorithm hashAlgo = GetHashForChannelBinding(cert)) { byte[] bindingHash = hashAlgo.ComputeHash(cert.RawData); bindingHandle.SetCertHash(bindingHash); } } finally { if (gotReference) { certSafeHandle.DangerousRelease(); } } } } private static void QueryUniqueChannelBinding(SafeSslHandle context, SafeChannelBindingHandle bindingHandle) { bool sessionReused = Ssl.SslSessionReused(context); int certHashLength = context.IsServer ^ sessionReused ? Ssl.SslGetPeerFinished(context, bindingHandle.CertHashPtr, bindingHandle.Length) : Ssl.SslGetFinished(context, bindingHandle.CertHashPtr, bindingHandle.Length); if (0 == certHashLength) { throw CreateSslException(SR.net_ssl_get_channel_binding_token_failed); } bindingHandle.SetCertHashLength(certHashLength); } private static IntPtr GetSslMethod(SslProtocols protocols) { Debug.Assert(protocols != SslProtocols.None, "All protocols are disabled"); bool ssl2 = (protocols & SslProtocols.Ssl2) == SslProtocols.Ssl2; bool ssl3 = (protocols & SslProtocols.Ssl3) == SslProtocols.Ssl3; bool tls10 = (protocols & SslProtocols.Tls) == SslProtocols.Tls; bool tls11 = (protocols & SslProtocols.Tls11) == SslProtocols.Tls11; bool tls12 = (protocols & SslProtocols.Tls12) == SslProtocols.Tls12; IntPtr method = Ssl.SslMethods.SSLv23_method; // default string methodName = "SSLv23_method"; if (!ssl2) { if (!ssl3) { if (!tls11 && !tls12) { method = Ssl.SslMethods.TLSv1_method; methodName = "TLSv1_method"; } else if (!tls10 && !tls12) { method = Ssl.SslMethods.TLSv1_1_method; methodName = "TLSv1_1_method"; } else if (!tls10 && !tls11) { method = Ssl.SslMethods.TLSv1_2_method; methodName = "TLSv1_2_method"; } } else if (!tls10 && !tls11 && !tls12) { method = Ssl.SslMethods.SSLv3_method; methodName = "SSLv3_method"; } } if (IntPtr.Zero == method) { throw new SslException(SR.Format(SR.net_get_ssl_method_failed, methodName)); } return method; } private static int VerifyClientCertificate(int preverify_ok, IntPtr x509_ctx_ptr) { // Full validation is handled after the handshake in VerifyCertificateProperties and the // user callback. It's also up to those handlers to decide if a null certificate // is appropriate. So just return success to tell OpenSSL that the cert is acceptable, // we'll process it after the handshake finishes. const int OpenSslSuccess = 1; return OpenSslSuccess; } private static void UpdateCAListFromRootStore(SafeSslContextHandle context) { using (SafeX509NameStackHandle nameStack = Crypto.NewX509NameStack()) { //maintaining the HashSet of Certificate's issuer name to keep track of duplicates HashSet<string> issuerNameHashSet = new HashSet<string>(); //Enumerate Certificates from LocalMachine and CurrentUser root store AddX509Names(nameStack, StoreLocation.LocalMachine, issuerNameHashSet); AddX509Names(nameStack, StoreLocation.CurrentUser, issuerNameHashSet); Ssl.SslCtxSetClientCAList(context, nameStack); // The handle ownership has been transferred into the CTX. nameStack.SetHandleAsInvalid(); } } private static void AddX509Names(SafeX509NameStackHandle nameStack, StoreLocation storeLocation, HashSet<string> issuerNameHashSet) { using (var store = new X509Store(StoreName.Root, storeLocation)) { store.Open(OpenFlags.ReadOnly); foreach (var certificate in store.Certificates) { //Check if issuer name is already present //Avoiding duplicate names if (!issuerNameHashSet.Add(certificate.Issuer)) { continue; } using (SafeX509Handle certHandle = Crypto.X509Duplicate(certificate.Handle)) { using (SafeX509NameHandle nameHandle = Crypto.DuplicateX509Name(Crypto.X509GetIssuerName(certHandle))) { if (Crypto.PushX509NameStackField(nameStack, nameHandle)) { // The handle ownership has been transferred into the STACK_OF(X509_NAME). nameHandle.SetHandleAsInvalid(); } else { throw new CryptographicException(SR.net_ssl_x509Name_push_failed_error); } } } } } } private static int BioRead(SafeBioHandle bio, byte[] buffer, int count) { Debug.Assert(buffer != null); Debug.Assert(count >= 0); Debug.Assert(buffer.Length >= count); int bytes = Crypto.BioRead(bio, buffer, count); if (bytes != count) { throw CreateSslException(SR.net_ssl_read_bio_failed_error); } return bytes; } private static int BioWrite(SafeBioHandle bio, byte[] buffer, int offset, int count) { Debug.Assert(buffer != null); Debug.Assert(offset >= 0); Debug.Assert(count >= 0); Debug.Assert(buffer.Length >= offset + count); int bytes; unsafe { fixed (byte* bufPtr = buffer) { bytes = Ssl.BioWrite(bio, bufPtr + offset, count); } } if (bytes != count) { throw CreateSslException(SR.net_ssl_write_bio_failed_error); } return bytes; } private static Ssl.SslErrorCode GetSslError(SafeSslHandle context, int result, out Exception innerError) { ErrorInfo lastErrno = Sys.GetLastErrorInfo(); // cache it before we make more P/Invoke calls, just in case we need it Ssl.SslErrorCode retVal = Ssl.SslGetError(context, result); switch (retVal) { case Ssl.SslErrorCode.SSL_ERROR_SYSCALL: // Some I/O error occurred innerError = Crypto.ErrPeekError() != 0 ? Crypto.CreateOpenSslCryptographicException() : // crypto error queue not empty result == 0 ? new EndOfStreamException() : // end of file that violates protocol result == -1 && lastErrno.Error != Error.SUCCESS ? new IOException(lastErrno.GetErrorMessage(), lastErrno.RawErrno) : // underlying I/O error null; // no additional info available break; case Ssl.SslErrorCode.SSL_ERROR_SSL: // OpenSSL failure occurred. The error queue contains more details. innerError = Interop.Crypto.CreateOpenSslCryptographicException(); break; default: // No additional info available. innerError = null; break; } return retVal; } private static void SetSslCertificate(SafeSslContextHandle contextPtr, SafeX509Handle certPtr, SafeEvpPKeyHandle keyPtr) { Debug.Assert(certPtr != null && !certPtr.IsInvalid, "certPtr != null && !certPtr.IsInvalid"); Debug.Assert(keyPtr != null && !keyPtr.IsInvalid, "keyPtr != null && !keyPtr.IsInvalid"); int retVal = Ssl.SslCtxUseCertificate(contextPtr, certPtr); if (1 != retVal) { throw CreateSslException(SR.net_ssl_use_cert_failed); } retVal = Ssl.SslCtxUsePrivateKey(contextPtr, keyPtr); if (1 != retVal) { throw CreateSslException(SR.net_ssl_use_private_key_failed); } //check private key retVal = Ssl.SslCtxCheckPrivateKey(contextPtr); if (1 != retVal) { throw CreateSslException(SR.net_ssl_check_private_key_failed); } } internal static SslException CreateSslException(string message) { ulong errorVal = Crypto.ErrGetError(); string msg = SR.Format(message, Marshal.PtrToStringAnsi(Crypto.ErrReasonErrorString(errorVal))); return new SslException(msg, (int)errorVal); } #endregion #region Internal class internal sealed class SslException : Exception { public SslException(string inputMessage) : base(inputMessage) { } public SslException(string inputMessage, Exception ex) : base(inputMessage, ex) { } public SslException(string inputMessage, int error) : this(inputMessage) { HResult = error; } public SslException(int error) : this(SR.Format(SR.net_generic_operation_failed, error)) { HResult = error; } } #endregion } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using ManyConsole; using Newtonsoft.Json; using Npgsql; using TroutDash.DatabaseImporter.Convention; using TroutDash.EntityFramework.Models; using TroutStreamMangler.MN; using TroutStreamMangler.US.Models; namespace TroutStreamMangler.US { public class ExportUsData : ConsoleCommand { private readonly IDatabaseConnection _troutDashDbConnection; private readonly IDatabaseConnection _usImportDbConnection; private readonly Lazy<ILookup<int, FipsCode>> _fips; private readonly Lazy<Dictionary<string, Abbreviation>> _abbrevs; private readonly SequenceRestarter _sequenceRestarter; public ExportUsData(IDatabaseConnection troutDashDbConnection, IDatabaseConnection usImportDbConnection) { _troutDashDbConnection = troutDashDbConnection; _usImportDbConnection = usImportDbConnection; _sequenceRestarter = new SequenceRestarter(troutDashDbConnection); _abbrevs = new Lazy<Dictionary<string, Abbreviation>>(CreateAbbreviations); _fips = new Lazy<ILookup<int, FipsCode>>(CreateFipCode); HasOption("regionCsv=", "the location of the regions csv, etc", j => RegionCsv = j); HasOption("roadTypeCsv=", "the location of the road type csv, etc", j => RoadTypeCsv = j); } public string RoadTypeCsv { get; set; } public string RegionCsv { get; set; } private static Dictionary<string, Abbreviation> CreateAbbreviations() { var abbreviationsFile = new FileInfo(@"US\Data\US_State_abbreviations.json"); return JsonConvert.DeserializeObject<IEnumerable<Abbreviation>>(File.ReadAllText(abbreviationsFile.FullName)) .ToDictionary(i => i.State_name); } private ILookup<int, FipsCode> CreateFipCode() { var fipsCodesFile = new FileInfo(@"US\Data\US_FIPS_CODES.json"); var fipsCodes = JsonConvert.DeserializeObject<IEnumerable<CensusFipsCodes>>( File.ReadAllText(fipsCodesFile.FullName)) .Select(OnSelector).ToLookup(i => i.StateNumber); return fipsCodes; } private FipsCode OnSelector(CensusFipsCodes i) { return new FipsCode { CountyName = i.County_Name, CountyNumber = i.FIPS_County, StateName = i.State, StateNumber = i.FIPS_State, StateAbbreviation = _abbrevs.Value[i.State].State_abbreviation }; } public override int Run(string[] remainingArguments) { try { ImportStatesAndCounties(); ImportRegions(); ImportFederalRoadTypes(); } // update or delete on table "county" violates foreign key constraint "FK_Stream_County_County" on table "stream_county" catch (Exception) { throw; } return 0; } private void ImportFederalRoadTypes() { var roadTypes = GetRoadTypes(); using (var troutDashContext = new TroutDashPrototypeContext()) { Console.WriteLine("Deleting all regions"); troutDashContext.road_types.RemoveRange(troutDashContext.road_types); troutDashContext.SaveChanges(); foreach (var roadType in roadTypes) { var dbRoadType = new road_type(); dbRoadType.description = roadType.name; dbRoadType.source = "0"; dbRoadType.type = roadType.type; troutDashContext.road_types.Add(dbRoadType); } troutDashContext.SaveChanges(); } } private void ImportRegions() { const string regionNamesFileName = "RegionNames.csv"; var regionDirectory = new DirectoryInfo(RegionCsv); var csvs = regionDirectory.EnumerateFiles("*.csv", SearchOption.TopDirectoryOnly); var regionNamesFile = csvs.Single(f => f.Name == regionNamesFileName); var names = RegionsBuilder.GetCsvModel<RegionNameModel>(regionNamesFile.FullName).ToDictionary(i => i.FileName); var regions = csvs.Where(f => f.Name != regionNamesFileName) .Select(RegionsBuilder.GetRegionModel).ToList(); Console.WriteLine("Saving regions"); using (var troutDashContext = new TroutDashPrototypeContext()) { Console.WriteLine("Deleting all regions"); troutDashContext.regions.RemoveRange(troutDashContext.regions); troutDashContext.SaveChanges(); _sequenceRestarter.RestartSequence("region_id_seq"); Console.WriteLine("Saving region:"); foreach (var region in regions) { Console.WriteLine(" " + region.regionName); var r = new region(); r.name = region.regionName; var fipsCodes = region.Counties.Select(i => i.FIPS).ToList(); r.counties = troutDashContext.counties.Where(i => fipsCodes.Any(f => f == i.statefp + i.countyfp)) .ToList(); r.Geom = DisolveCountyGeometriesByRegion(region); r.long_name = names[region.regionName].FullName; troutDashContext.regions.Add(r); troutDashContext.SaveChanges(); } } } private IEnumerable<RoadTypeModel> GetRoadTypes() { const string regionNamesFileName = "RoadTypes.csv"; var regionDirectory = new DirectoryInfo(RoadTypeCsv); var roadTypeFile = regionDirectory.EnumerateFiles("*.csv", SearchOption.TopDirectoryOnly) .Single(f => f.Name == regionNamesFileName); var types = RegionsBuilder.GetCsvModel<RoadTypeModel>(roadTypeFile.FullName).ToList(); return types; } private string DisolveCountyGeometriesByRegion(RegionModel region) { var sql = @"select * from ST_Multi(ST_Union(ARRAY (SELECT geom_4326 FROM public.counties where CONCAT(statefp, countyfp) in ({0}))))"; var safeFipsTemplate = "'{0}'"; var connection = String.Format("Server={0};Port=5432;User Id={1};Database={2};Password=fakepassword;", _usImportDbConnection.HostName, _usImportDbConnection.UserName, _usImportDbConnection.DatabaseName); var conn = new NpgsqlConnection(connection); conn.Open(); var safeCountyFips = region.Counties.Select(i => String.Format(safeFipsTemplate, i.FIPS)).ToArray(); var args = string.Join(",", safeCountyFips); var query = string.Format(sql, args); var command = new NpgsqlCommand(query, conn); var dr = command.ExecuteReader(); while (dr.Read()) { var geom = dr.GetString(0); return geom; } return null; } private void ImportStatesAndCounties() { using (var context = new UsShapeDataContext()) using (var troutDashContext = new TroutDashPrototypeContext()) { var states = troutDashContext.states.ToList(); troutDashContext.states.RemoveRange(states); troutDashContext.SaveChanges(); _sequenceRestarter.RestartSequence("states_gid_seq"); _sequenceRestarter.RestartSequence("counties_gid_seq"); var counties = context.counties.ToLookup(c => c.statefp); foreach (var state in context.states) { var actualState = _fips.Value[Convert.ToInt32(state.statefp)].FirstOrDefault(); if (actualState == null) { continue; } Console.WriteLine("Adding state " + actualState.StateName); var stateCounties = counties[state.statefp]; var countyModels = stateCounties.Select(c => new TroutDash.EntityFramework.Models.county { Geom = c.Geom_4326, countyfp = c.countyfp, statefp = c.statefp, name = c.name, lsad = c.lsad, stream_count = 0 }).ToList(); var stateAbbreviation = actualState.StateAbbreviation; var stateName = actualState.StateName; var newState = new TroutDash.EntityFramework.Models.state { counties = countyModels, Name = stateName, short_name = stateAbbreviation, statefp = state.statefp, Geom = state.Geom_4326, }; troutDashContext.states.Add(newState); troutDashContext.SaveChanges(); } } } } }
using System; using System.Linq; using System.Runtime.InteropServices; using Torque6.Engine.SimObjects; using Torque6.Engine.SimObjects.Scene; using Torque6.Engine.Namespaces; using Torque6.Utility; namespace Torque6.Engine.SimObjects { public unsafe class ModuleDefinition : SimSet { public ModuleDefinition() { ObjectPtr = Sim.WrapObject(InternalUnsafeMethods.ModuleDefinitionCreateInstance()); } public ModuleDefinition(uint pId) : base(pId) { } public ModuleDefinition(string pName) : base(pName) { } public ModuleDefinition(IntPtr pObjPtr) : base(pObjPtr) { } public ModuleDefinition(Sim.SimObjectPtr* pObjPtr) : base(pObjPtr) { } public ModuleDefinition(SimObject pObj) : base(pObj) { } #region UnsafeNativeMethods new internal struct InternalUnsafeMethods { [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate IntPtr _ModuleDefinitionGetModuleId(IntPtr moduleDefinition); private static _ModuleDefinitionGetModuleId _ModuleDefinitionGetModuleIdFunc; internal static IntPtr ModuleDefinitionGetModuleId(IntPtr moduleDefinition) { if (_ModuleDefinitionGetModuleIdFunc == null) { _ModuleDefinitionGetModuleIdFunc = (_ModuleDefinitionGetModuleId)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "ModuleDefinitionGetModuleId"), typeof(_ModuleDefinitionGetModuleId)); } return _ModuleDefinitionGetModuleIdFunc(moduleDefinition); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void _ModuleDefinitionSetModuleId(IntPtr moduleDefinition, string value); private static _ModuleDefinitionSetModuleId _ModuleDefinitionSetModuleIdFunc; internal static void ModuleDefinitionSetModuleId(IntPtr moduleDefinition, string value) { if (_ModuleDefinitionSetModuleIdFunc == null) { _ModuleDefinitionSetModuleIdFunc = (_ModuleDefinitionSetModuleId)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "ModuleDefinitionSetModuleId"), typeof(_ModuleDefinitionSetModuleId)); } _ModuleDefinitionSetModuleIdFunc(moduleDefinition, value); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate int _ModuleDefinitionGetVersionId(IntPtr moduleDefinition); private static _ModuleDefinitionGetVersionId _ModuleDefinitionGetVersionIdFunc; internal static int ModuleDefinitionGetVersionId(IntPtr moduleDefinition) { if (_ModuleDefinitionGetVersionIdFunc == null) { _ModuleDefinitionGetVersionIdFunc = (_ModuleDefinitionGetVersionId)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "ModuleDefinitionGetVersionId"), typeof(_ModuleDefinitionGetVersionId)); } return _ModuleDefinitionGetVersionIdFunc(moduleDefinition); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void _ModuleDefinitionSetVersionId(IntPtr moduleDefinition, int value); private static _ModuleDefinitionSetVersionId _ModuleDefinitionSetVersionIdFunc; internal static void ModuleDefinitionSetVersionId(IntPtr moduleDefinition, int value) { if (_ModuleDefinitionSetVersionIdFunc == null) { _ModuleDefinitionSetVersionIdFunc = (_ModuleDefinitionSetVersionId)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "ModuleDefinitionSetVersionId"), typeof(_ModuleDefinitionSetVersionId)); } _ModuleDefinitionSetVersionIdFunc(moduleDefinition, value); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate int _ModuleDefinitionGetBuildId(IntPtr moduleDefinition); private static _ModuleDefinitionGetBuildId _ModuleDefinitionGetBuildIdFunc; internal static int ModuleDefinitionGetBuildId(IntPtr moduleDefinition) { if (_ModuleDefinitionGetBuildIdFunc == null) { _ModuleDefinitionGetBuildIdFunc = (_ModuleDefinitionGetBuildId)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "ModuleDefinitionGetBuildId"), typeof(_ModuleDefinitionGetBuildId)); } return _ModuleDefinitionGetBuildIdFunc(moduleDefinition); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void _ModuleDefinitionSetBuildId(IntPtr moduleDefinition, int value); private static _ModuleDefinitionSetBuildId _ModuleDefinitionSetBuildIdFunc; internal static void ModuleDefinitionSetBuildId(IntPtr moduleDefinition, int value) { if (_ModuleDefinitionSetBuildIdFunc == null) { _ModuleDefinitionSetBuildIdFunc = (_ModuleDefinitionSetBuildId)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "ModuleDefinitionSetBuildId"), typeof(_ModuleDefinitionSetBuildId)); } _ModuleDefinitionSetBuildIdFunc(moduleDefinition, value); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate bool _ModuleDefinitionGetEnabled(IntPtr moduleDefinition); private static _ModuleDefinitionGetEnabled _ModuleDefinitionGetEnabledFunc; internal static bool ModuleDefinitionGetEnabled(IntPtr moduleDefinition) { if (_ModuleDefinitionGetEnabledFunc == null) { _ModuleDefinitionGetEnabledFunc = (_ModuleDefinitionGetEnabled)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "ModuleDefinitionGetEnabled"), typeof(_ModuleDefinitionGetEnabled)); } return _ModuleDefinitionGetEnabledFunc(moduleDefinition); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void _ModuleDefinitionSetEnabled(IntPtr moduleDefinition, bool value); private static _ModuleDefinitionSetEnabled _ModuleDefinitionSetEnabledFunc; internal static void ModuleDefinitionSetEnabled(IntPtr moduleDefinition, bool value) { if (_ModuleDefinitionSetEnabledFunc == null) { _ModuleDefinitionSetEnabledFunc = (_ModuleDefinitionSetEnabled)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "ModuleDefinitionSetEnabled"), typeof(_ModuleDefinitionSetEnabled)); } _ModuleDefinitionSetEnabledFunc(moduleDefinition, value); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate bool _ModuleDefinitionGetSynchronized(IntPtr moduleDefinition); private static _ModuleDefinitionGetSynchronized _ModuleDefinitionGetSynchronizedFunc; internal static bool ModuleDefinitionGetSynchronized(IntPtr moduleDefinition) { if (_ModuleDefinitionGetSynchronizedFunc == null) { _ModuleDefinitionGetSynchronizedFunc = (_ModuleDefinitionGetSynchronized)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "ModuleDefinitionGetSynchronized"), typeof(_ModuleDefinitionGetSynchronized)); } return _ModuleDefinitionGetSynchronizedFunc(moduleDefinition); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void _ModuleDefinitionSetSynchronized(IntPtr moduleDefinition, bool value); private static _ModuleDefinitionSetSynchronized _ModuleDefinitionSetSynchronizedFunc; internal static void ModuleDefinitionSetSynchronized(IntPtr moduleDefinition, bool value) { if (_ModuleDefinitionSetSynchronizedFunc == null) { _ModuleDefinitionSetSynchronizedFunc = (_ModuleDefinitionSetSynchronized)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "ModuleDefinitionSetSynchronized"), typeof(_ModuleDefinitionSetSynchronized)); } _ModuleDefinitionSetSynchronizedFunc(moduleDefinition, value); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate bool _ModuleDefinitionGetDeprecated(IntPtr moduleDefinition); private static _ModuleDefinitionGetDeprecated _ModuleDefinitionGetDeprecatedFunc; internal static bool ModuleDefinitionGetDeprecated(IntPtr moduleDefinition) { if (_ModuleDefinitionGetDeprecatedFunc == null) { _ModuleDefinitionGetDeprecatedFunc = (_ModuleDefinitionGetDeprecated)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "ModuleDefinitionGetDeprecated"), typeof(_ModuleDefinitionGetDeprecated)); } return _ModuleDefinitionGetDeprecatedFunc(moduleDefinition); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void _ModuleDefinitionSetDeprecated(IntPtr moduleDefinition, bool value); private static _ModuleDefinitionSetDeprecated _ModuleDefinitionSetDeprecatedFunc; internal static void ModuleDefinitionSetDeprecated(IntPtr moduleDefinition, bool value) { if (_ModuleDefinitionSetDeprecatedFunc == null) { _ModuleDefinitionSetDeprecatedFunc = (_ModuleDefinitionSetDeprecated)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "ModuleDefinitionSetDeprecated"), typeof(_ModuleDefinitionSetDeprecated)); } _ModuleDefinitionSetDeprecatedFunc(moduleDefinition, value); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate bool _ModuleDefinitionGetCriticalMerge(IntPtr moduleDefinition); private static _ModuleDefinitionGetCriticalMerge _ModuleDefinitionGetCriticalMergeFunc; internal static bool ModuleDefinitionGetCriticalMerge(IntPtr moduleDefinition) { if (_ModuleDefinitionGetCriticalMergeFunc == null) { _ModuleDefinitionGetCriticalMergeFunc = (_ModuleDefinitionGetCriticalMerge)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "ModuleDefinitionGetCriticalMerge"), typeof(_ModuleDefinitionGetCriticalMerge)); } return _ModuleDefinitionGetCriticalMergeFunc(moduleDefinition); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void _ModuleDefinitionSetCriticalMerge(IntPtr moduleDefinition, bool value); private static _ModuleDefinitionSetCriticalMerge _ModuleDefinitionSetCriticalMergeFunc; internal static void ModuleDefinitionSetCriticalMerge(IntPtr moduleDefinition, bool value) { if (_ModuleDefinitionSetCriticalMergeFunc == null) { _ModuleDefinitionSetCriticalMergeFunc = (_ModuleDefinitionSetCriticalMerge)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "ModuleDefinitionSetCriticalMerge"), typeof(_ModuleDefinitionSetCriticalMerge)); } _ModuleDefinitionSetCriticalMergeFunc(moduleDefinition, value); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate IntPtr _ModuleDefinitionGetDescription(IntPtr moduleDefinition); private static _ModuleDefinitionGetDescription _ModuleDefinitionGetDescriptionFunc; internal static IntPtr ModuleDefinitionGetDescription(IntPtr moduleDefinition) { if (_ModuleDefinitionGetDescriptionFunc == null) { _ModuleDefinitionGetDescriptionFunc = (_ModuleDefinitionGetDescription)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "ModuleDefinitionGetDescription"), typeof(_ModuleDefinitionGetDescription)); } return _ModuleDefinitionGetDescriptionFunc(moduleDefinition); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void _ModuleDefinitionSetDescription(IntPtr moduleDefinition, string value); private static _ModuleDefinitionSetDescription _ModuleDefinitionSetDescriptionFunc; internal static void ModuleDefinitionSetDescription(IntPtr moduleDefinition, string value) { if (_ModuleDefinitionSetDescriptionFunc == null) { _ModuleDefinitionSetDescriptionFunc = (_ModuleDefinitionSetDescription)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "ModuleDefinitionSetDescription"), typeof(_ModuleDefinitionSetDescription)); } _ModuleDefinitionSetDescriptionFunc(moduleDefinition, value); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate IntPtr _ModuleDefinitionGetAuthor(IntPtr moduleDefinition); private static _ModuleDefinitionGetAuthor _ModuleDefinitionGetAuthorFunc; internal static IntPtr ModuleDefinitionGetAuthor(IntPtr moduleDefinition) { if (_ModuleDefinitionGetAuthorFunc == null) { _ModuleDefinitionGetAuthorFunc = (_ModuleDefinitionGetAuthor)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "ModuleDefinitionGetAuthor"), typeof(_ModuleDefinitionGetAuthor)); } return _ModuleDefinitionGetAuthorFunc(moduleDefinition); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void _ModuleDefinitionSetAuthor(IntPtr moduleDefinition, string value); private static _ModuleDefinitionSetAuthor _ModuleDefinitionSetAuthorFunc; internal static void ModuleDefinitionSetAuthor(IntPtr moduleDefinition, string value) { if (_ModuleDefinitionSetAuthorFunc == null) { _ModuleDefinitionSetAuthorFunc = (_ModuleDefinitionSetAuthor)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "ModuleDefinitionSetAuthor"), typeof(_ModuleDefinitionSetAuthor)); } _ModuleDefinitionSetAuthorFunc(moduleDefinition, value); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate IntPtr _ModuleDefinitionGetGroup(IntPtr moduleDefinition); private static _ModuleDefinitionGetGroup _ModuleDefinitionGetGroupFunc; internal static IntPtr ModuleDefinitionGetGroup(IntPtr moduleDefinition) { if (_ModuleDefinitionGetGroupFunc == null) { _ModuleDefinitionGetGroupFunc = (_ModuleDefinitionGetGroup)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "ModuleDefinitionGetGroup"), typeof(_ModuleDefinitionGetGroup)); } return _ModuleDefinitionGetGroupFunc(moduleDefinition); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void _ModuleDefinitionSetGroup(IntPtr moduleDefinition, string value); private static _ModuleDefinitionSetGroup _ModuleDefinitionSetGroupFunc; internal static void ModuleDefinitionSetGroup(IntPtr moduleDefinition, string value) { if (_ModuleDefinitionSetGroupFunc == null) { _ModuleDefinitionSetGroupFunc = (_ModuleDefinitionSetGroup)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "ModuleDefinitionSetGroup"), typeof(_ModuleDefinitionSetGroup)); } _ModuleDefinitionSetGroupFunc(moduleDefinition, value); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate IntPtr _ModuleDefinitionGetType(IntPtr moduleDefinition); private static _ModuleDefinitionGetType _ModuleDefinitionGetTypeFunc; internal static IntPtr ModuleDefinitionGetType(IntPtr moduleDefinition) { if (_ModuleDefinitionGetTypeFunc == null) { _ModuleDefinitionGetTypeFunc = (_ModuleDefinitionGetType)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "ModuleDefinitionGetType"), typeof(_ModuleDefinitionGetType)); } return _ModuleDefinitionGetTypeFunc(moduleDefinition); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void _ModuleDefinitionSetType(IntPtr moduleDefinition, string value); private static _ModuleDefinitionSetType _ModuleDefinitionSetTypeFunc; internal static void ModuleDefinitionSetType(IntPtr moduleDefinition, string value) { if (_ModuleDefinitionSetTypeFunc == null) { _ModuleDefinitionSetTypeFunc = (_ModuleDefinitionSetType)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "ModuleDefinitionSetType"), typeof(_ModuleDefinitionSetType)); } _ModuleDefinitionSetTypeFunc(moduleDefinition, value); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate IntPtr _ModuleDefinitionGetDependencies(IntPtr moduleDefinition); private static _ModuleDefinitionGetDependencies _ModuleDefinitionGetDependenciesFunc; internal static IntPtr ModuleDefinitionGetDependencies(IntPtr moduleDefinition) { if (_ModuleDefinitionGetDependenciesFunc == null) { _ModuleDefinitionGetDependenciesFunc = (_ModuleDefinitionGetDependencies)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "ModuleDefinitionGetDependencies"), typeof(_ModuleDefinitionGetDependencies)); } return _ModuleDefinitionGetDependenciesFunc(moduleDefinition); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void _ModuleDefinitionSetDependencies(IntPtr moduleDefinition, string value); private static _ModuleDefinitionSetDependencies _ModuleDefinitionSetDependenciesFunc; internal static void ModuleDefinitionSetDependencies(IntPtr moduleDefinition, string value) { if (_ModuleDefinitionSetDependenciesFunc == null) { _ModuleDefinitionSetDependenciesFunc = (_ModuleDefinitionSetDependencies)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "ModuleDefinitionSetDependencies"), typeof(_ModuleDefinitionSetDependencies)); } _ModuleDefinitionSetDependenciesFunc(moduleDefinition, value); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate IntPtr _ModuleDefinitionGetScriptFile(IntPtr moduleDefinition); private static _ModuleDefinitionGetScriptFile _ModuleDefinitionGetScriptFileFunc; internal static IntPtr ModuleDefinitionGetScriptFile(IntPtr moduleDefinition) { if (_ModuleDefinitionGetScriptFileFunc == null) { _ModuleDefinitionGetScriptFileFunc = (_ModuleDefinitionGetScriptFile)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "ModuleDefinitionGetScriptFile"), typeof(_ModuleDefinitionGetScriptFile)); } return _ModuleDefinitionGetScriptFileFunc(moduleDefinition); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void _ModuleDefinitionSetScriptFile(IntPtr moduleDefinition, string value); private static _ModuleDefinitionSetScriptFile _ModuleDefinitionSetScriptFileFunc; internal static void ModuleDefinitionSetScriptFile(IntPtr moduleDefinition, string value) { if (_ModuleDefinitionSetScriptFileFunc == null) { _ModuleDefinitionSetScriptFileFunc = (_ModuleDefinitionSetScriptFile)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "ModuleDefinitionSetScriptFile"), typeof(_ModuleDefinitionSetScriptFile)); } _ModuleDefinitionSetScriptFileFunc(moduleDefinition, value); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate IntPtr _ModuleDefinitionGetCreateFunction(IntPtr moduleDefinition); private static _ModuleDefinitionGetCreateFunction _ModuleDefinitionGetCreateFunctionFunc; internal static IntPtr ModuleDefinitionGetCreateFunction(IntPtr moduleDefinition) { if (_ModuleDefinitionGetCreateFunctionFunc == null) { _ModuleDefinitionGetCreateFunctionFunc = (_ModuleDefinitionGetCreateFunction)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "ModuleDefinitionGetCreateFunction"), typeof(_ModuleDefinitionGetCreateFunction)); } return _ModuleDefinitionGetCreateFunctionFunc(moduleDefinition); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void _ModuleDefinitionSetCreateFunction(IntPtr moduleDefinition, string value); private static _ModuleDefinitionSetCreateFunction _ModuleDefinitionSetCreateFunctionFunc; internal static void ModuleDefinitionSetCreateFunction(IntPtr moduleDefinition, string value) { if (_ModuleDefinitionSetCreateFunctionFunc == null) { _ModuleDefinitionSetCreateFunctionFunc = (_ModuleDefinitionSetCreateFunction)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "ModuleDefinitionSetCreateFunction"), typeof(_ModuleDefinitionSetCreateFunction)); } _ModuleDefinitionSetCreateFunctionFunc(moduleDefinition, value); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate IntPtr _ModuleDefinitionGetDestroyFunction(IntPtr moduleDefinition); private static _ModuleDefinitionGetDestroyFunction _ModuleDefinitionGetDestroyFunctionFunc; internal static IntPtr ModuleDefinitionGetDestroyFunction(IntPtr moduleDefinition) { if (_ModuleDefinitionGetDestroyFunctionFunc == null) { _ModuleDefinitionGetDestroyFunctionFunc = (_ModuleDefinitionGetDestroyFunction)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "ModuleDefinitionGetDestroyFunction"), typeof(_ModuleDefinitionGetDestroyFunction)); } return _ModuleDefinitionGetDestroyFunctionFunc(moduleDefinition); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void _ModuleDefinitionSetDestroyFunction(IntPtr moduleDefinition, string value); private static _ModuleDefinitionSetDestroyFunction _ModuleDefinitionSetDestroyFunctionFunc; internal static void ModuleDefinitionSetDestroyFunction(IntPtr moduleDefinition, string value) { if (_ModuleDefinitionSetDestroyFunctionFunc == null) { _ModuleDefinitionSetDestroyFunctionFunc = (_ModuleDefinitionSetDestroyFunction)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "ModuleDefinitionSetDestroyFunction"), typeof(_ModuleDefinitionSetDestroyFunction)); } _ModuleDefinitionSetDestroyFunctionFunc(moduleDefinition, value); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate IntPtr _ModuleDefinitionGetAssetTagsManifest(IntPtr moduleDefinition); private static _ModuleDefinitionGetAssetTagsManifest _ModuleDefinitionGetAssetTagsManifestFunc; internal static IntPtr ModuleDefinitionGetAssetTagsManifest(IntPtr moduleDefinition) { if (_ModuleDefinitionGetAssetTagsManifestFunc == null) { _ModuleDefinitionGetAssetTagsManifestFunc = (_ModuleDefinitionGetAssetTagsManifest)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "ModuleDefinitionGetAssetTagsManifest"), typeof(_ModuleDefinitionGetAssetTagsManifest)); } return _ModuleDefinitionGetAssetTagsManifestFunc(moduleDefinition); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void _ModuleDefinitionSetAssetTagsManifest(IntPtr moduleDefinition, string value); private static _ModuleDefinitionSetAssetTagsManifest _ModuleDefinitionSetAssetTagsManifestFunc; internal static void ModuleDefinitionSetAssetTagsManifest(IntPtr moduleDefinition, string value) { if (_ModuleDefinitionSetAssetTagsManifestFunc == null) { _ModuleDefinitionSetAssetTagsManifestFunc = (_ModuleDefinitionSetAssetTagsManifest)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "ModuleDefinitionSetAssetTagsManifest"), typeof(_ModuleDefinitionSetAssetTagsManifest)); } _ModuleDefinitionSetAssetTagsManifestFunc(moduleDefinition, value); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate int _ModuleDefinitionGetScopeSet(IntPtr moduleDefinition); private static _ModuleDefinitionGetScopeSet _ModuleDefinitionGetScopeSetFunc; internal static int ModuleDefinitionGetScopeSet(IntPtr moduleDefinition) { if (_ModuleDefinitionGetScopeSetFunc == null) { _ModuleDefinitionGetScopeSetFunc = (_ModuleDefinitionGetScopeSet)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "ModuleDefinitionGetScopeSet"), typeof(_ModuleDefinitionGetScopeSet)); } return _ModuleDefinitionGetScopeSetFunc(moduleDefinition); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate IntPtr _ModuleDefinitionGetModulePath(IntPtr moduleDefinition); private static _ModuleDefinitionGetModulePath _ModuleDefinitionGetModulePathFunc; internal static IntPtr ModuleDefinitionGetModulePath(IntPtr moduleDefinition) { if (_ModuleDefinitionGetModulePathFunc == null) { _ModuleDefinitionGetModulePathFunc = (_ModuleDefinitionGetModulePath)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "ModuleDefinitionGetModulePath"), typeof(_ModuleDefinitionGetModulePath)); } return _ModuleDefinitionGetModulePathFunc(moduleDefinition); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate IntPtr _ModuleDefinitionGetModuleFile(IntPtr moduleDefinition); private static _ModuleDefinitionGetModuleFile _ModuleDefinitionGetModuleFileFunc; internal static IntPtr ModuleDefinitionGetModuleFile(IntPtr moduleDefinition) { if (_ModuleDefinitionGetModuleFileFunc == null) { _ModuleDefinitionGetModuleFileFunc = (_ModuleDefinitionGetModuleFile)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "ModuleDefinitionGetModuleFile"), typeof(_ModuleDefinitionGetModuleFile)); } return _ModuleDefinitionGetModuleFileFunc(moduleDefinition); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate IntPtr _ModuleDefinitionGetModuleFilePath(IntPtr moduleDefinition); private static _ModuleDefinitionGetModuleFilePath _ModuleDefinitionGetModuleFilePathFunc; internal static IntPtr ModuleDefinitionGetModuleFilePath(IntPtr moduleDefinition) { if (_ModuleDefinitionGetModuleFilePathFunc == null) { _ModuleDefinitionGetModuleFilePathFunc = (_ModuleDefinitionGetModuleFilePath)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "ModuleDefinitionGetModuleFilePath"), typeof(_ModuleDefinitionGetModuleFilePath)); } return _ModuleDefinitionGetModuleFilePathFunc(moduleDefinition); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate IntPtr _ModuleDefinitionGetModuleScriptFilePath(IntPtr moduleDefinition); private static _ModuleDefinitionGetModuleScriptFilePath _ModuleDefinitionGetModuleScriptFilePathFunc; internal static IntPtr ModuleDefinitionGetModuleScriptFilePath(IntPtr moduleDefinition) { if (_ModuleDefinitionGetModuleScriptFilePathFunc == null) { _ModuleDefinitionGetModuleScriptFilePathFunc = (_ModuleDefinitionGetModuleScriptFilePath)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "ModuleDefinitionGetModuleScriptFilePath"), typeof(_ModuleDefinitionGetModuleScriptFilePath)); } return _ModuleDefinitionGetModuleScriptFilePathFunc(moduleDefinition); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate IntPtr _ModuleDefinitionCreateInstance(); private static _ModuleDefinitionCreateInstance _ModuleDefinitionCreateInstanceFunc; internal static IntPtr ModuleDefinitionCreateInstance() { if (_ModuleDefinitionCreateInstanceFunc == null) { _ModuleDefinitionCreateInstanceFunc = (_ModuleDefinitionCreateInstance)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "ModuleDefinitionCreateInstance"), typeof(_ModuleDefinitionCreateInstance)); } return _ModuleDefinitionCreateInstanceFunc(); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate IntPtr _ModuleDefinitionGetSignature(IntPtr moduleDefinition); private static _ModuleDefinitionGetSignature _ModuleDefinitionGetSignatureFunc; internal static IntPtr ModuleDefinitionGetSignature(IntPtr moduleDefinition) { if (_ModuleDefinitionGetSignatureFunc == null) { _ModuleDefinitionGetSignatureFunc = (_ModuleDefinitionGetSignature)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "ModuleDefinitionGetSignature"), typeof(_ModuleDefinitionGetSignature)); } return _ModuleDefinitionGetSignatureFunc(moduleDefinition); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate bool _ModuleDefinitionSave(IntPtr moduleDefinition); private static _ModuleDefinitionSave _ModuleDefinitionSaveFunc; internal static bool ModuleDefinitionSave(IntPtr moduleDefinition) { if (_ModuleDefinitionSaveFunc == null) { _ModuleDefinitionSaveFunc = (_ModuleDefinitionSave)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "ModuleDefinitionSave"), typeof(_ModuleDefinitionSave)); } return _ModuleDefinitionSaveFunc(moduleDefinition); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate IntPtr _ModuleDefinitionGetModuleManager(IntPtr moduleDefinition); private static _ModuleDefinitionGetModuleManager _ModuleDefinitionGetModuleManagerFunc; internal static IntPtr ModuleDefinitionGetModuleManager(IntPtr moduleDefinition) { if (_ModuleDefinitionGetModuleManagerFunc == null) { _ModuleDefinitionGetModuleManagerFunc = (_ModuleDefinitionGetModuleManager)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "ModuleDefinitionGetModuleManager"), typeof(_ModuleDefinitionGetModuleManager)); } return _ModuleDefinitionGetModuleManagerFunc(moduleDefinition); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate int _ModuleDefinitionGetDependencyCount(IntPtr moduleDefinition); private static _ModuleDefinitionGetDependencyCount _ModuleDefinitionGetDependencyCountFunc; internal static int ModuleDefinitionGetDependencyCount(IntPtr moduleDefinition) { if (_ModuleDefinitionGetDependencyCountFunc == null) { _ModuleDefinitionGetDependencyCountFunc = (_ModuleDefinitionGetDependencyCount)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "ModuleDefinitionGetDependencyCount"), typeof(_ModuleDefinitionGetDependencyCount)); } return _ModuleDefinitionGetDependencyCountFunc(moduleDefinition); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate IntPtr _ModuleDefinitionGetDependency(IntPtr moduleDefinition, int dependencyIndex); private static _ModuleDefinitionGetDependency _ModuleDefinitionGetDependencyFunc; internal static IntPtr ModuleDefinitionGetDependency(IntPtr moduleDefinition, int dependencyIndex) { if (_ModuleDefinitionGetDependencyFunc == null) { _ModuleDefinitionGetDependencyFunc = (_ModuleDefinitionGetDependency)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "ModuleDefinitionGetDependency"), typeof(_ModuleDefinitionGetDependency)); } return _ModuleDefinitionGetDependencyFunc(moduleDefinition, dependencyIndex); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate bool _ModuleDefinitionAddDependency(IntPtr moduleDefinition, string moduleId, int versionId); private static _ModuleDefinitionAddDependency _ModuleDefinitionAddDependencyFunc; internal static bool ModuleDefinitionAddDependency(IntPtr moduleDefinition, string moduleId, int versionId) { if (_ModuleDefinitionAddDependencyFunc == null) { _ModuleDefinitionAddDependencyFunc = (_ModuleDefinitionAddDependency)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "ModuleDefinitionAddDependency"), typeof(_ModuleDefinitionAddDependency)); } return _ModuleDefinitionAddDependencyFunc(moduleDefinition, moduleId, versionId); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate bool _ModuleDefinitionRemoveDependency(IntPtr moduleDefinition, string moduleId); private static _ModuleDefinitionRemoveDependency _ModuleDefinitionRemoveDependencyFunc; internal static bool ModuleDefinitionRemoveDependency(IntPtr moduleDefinition, string moduleId) { if (_ModuleDefinitionRemoveDependencyFunc == null) { _ModuleDefinitionRemoveDependencyFunc = (_ModuleDefinitionRemoveDependency)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "ModuleDefinitionRemoveDependency"), typeof(_ModuleDefinitionRemoveDependency)); } return _ModuleDefinitionRemoveDependencyFunc(moduleDefinition, moduleId); } } #endregion #region Properties public string ModuleId { get { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); return Marshal.PtrToStringAnsi(InternalUnsafeMethods.ModuleDefinitionGetModuleId(ObjectPtr->ObjPtr)); } set { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); InternalUnsafeMethods.ModuleDefinitionSetModuleId(ObjectPtr->ObjPtr, value); } } public int VersionId { get { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); return InternalUnsafeMethods.ModuleDefinitionGetVersionId(ObjectPtr->ObjPtr); } set { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); InternalUnsafeMethods.ModuleDefinitionSetVersionId(ObjectPtr->ObjPtr, value); } } public int BuildId { get { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); return InternalUnsafeMethods.ModuleDefinitionGetBuildId(ObjectPtr->ObjPtr); } set { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); InternalUnsafeMethods.ModuleDefinitionSetBuildId(ObjectPtr->ObjPtr, value); } } public bool Enabled { get { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); return InternalUnsafeMethods.ModuleDefinitionGetEnabled(ObjectPtr->ObjPtr); } set { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); InternalUnsafeMethods.ModuleDefinitionSetEnabled(ObjectPtr->ObjPtr, value); } } public bool Synchronized { get { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); return InternalUnsafeMethods.ModuleDefinitionGetSynchronized(ObjectPtr->ObjPtr); } set { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); InternalUnsafeMethods.ModuleDefinitionSetSynchronized(ObjectPtr->ObjPtr, value); } } public bool Deprecated { get { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); return InternalUnsafeMethods.ModuleDefinitionGetDeprecated(ObjectPtr->ObjPtr); } set { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); InternalUnsafeMethods.ModuleDefinitionSetDeprecated(ObjectPtr->ObjPtr, value); } } public bool CriticalMerge { get { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); return InternalUnsafeMethods.ModuleDefinitionGetCriticalMerge(ObjectPtr->ObjPtr); } set { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); InternalUnsafeMethods.ModuleDefinitionSetCriticalMerge(ObjectPtr->ObjPtr, value); } } public string Description { get { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); return Marshal.PtrToStringAnsi(InternalUnsafeMethods.ModuleDefinitionGetDescription(ObjectPtr->ObjPtr)); } set { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); InternalUnsafeMethods.ModuleDefinitionSetDescription(ObjectPtr->ObjPtr, value); } } public string Author { get { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); return Marshal.PtrToStringAnsi(InternalUnsafeMethods.ModuleDefinitionGetAuthor(ObjectPtr->ObjPtr)); } set { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); InternalUnsafeMethods.ModuleDefinitionSetAuthor(ObjectPtr->ObjPtr, value); } } public string Group { get { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); return Marshal.PtrToStringAnsi(InternalUnsafeMethods.ModuleDefinitionGetGroup(ObjectPtr->ObjPtr)); } set { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); InternalUnsafeMethods.ModuleDefinitionSetGroup(ObjectPtr->ObjPtr, value); } } public string Type { get { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); return Marshal.PtrToStringAnsi(InternalUnsafeMethods.ModuleDefinitionGetType(ObjectPtr->ObjPtr)); } set { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); InternalUnsafeMethods.ModuleDefinitionSetType(ObjectPtr->ObjPtr, value); } } public string Dependencies { get { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); return Marshal.PtrToStringAnsi(InternalUnsafeMethods.ModuleDefinitionGetDependencies(ObjectPtr->ObjPtr)); } set { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); InternalUnsafeMethods.ModuleDefinitionSetDependencies(ObjectPtr->ObjPtr, value); } } public string ScriptFile { get { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); return Marshal.PtrToStringAnsi(InternalUnsafeMethods.ModuleDefinitionGetScriptFile(ObjectPtr->ObjPtr)); } set { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); InternalUnsafeMethods.ModuleDefinitionSetScriptFile(ObjectPtr->ObjPtr, value); } } public string CreateFunction { get { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); return Marshal.PtrToStringAnsi(InternalUnsafeMethods.ModuleDefinitionGetCreateFunction(ObjectPtr->ObjPtr)); } set { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); InternalUnsafeMethods.ModuleDefinitionSetCreateFunction(ObjectPtr->ObjPtr, value); } } public string DestroyFunction { get { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); return Marshal.PtrToStringAnsi(InternalUnsafeMethods.ModuleDefinitionGetDestroyFunction(ObjectPtr->ObjPtr)); } set { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); InternalUnsafeMethods.ModuleDefinitionSetDestroyFunction(ObjectPtr->ObjPtr, value); } } public string AssetTagsManifest { get { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); return Marshal.PtrToStringAnsi(InternalUnsafeMethods.ModuleDefinitionGetAssetTagsManifest(ObjectPtr->ObjPtr)); } set { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); InternalUnsafeMethods.ModuleDefinitionSetAssetTagsManifest(ObjectPtr->ObjPtr, value); } } public int ScopeSet { get { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); return InternalUnsafeMethods.ModuleDefinitionGetScopeSet(ObjectPtr->ObjPtr); } } public string ModulePath { get { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); return Marshal.PtrToStringAnsi(InternalUnsafeMethods.ModuleDefinitionGetModulePath(ObjectPtr->ObjPtr)); } } public string ModuleFile { get { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); return Marshal.PtrToStringAnsi(InternalUnsafeMethods.ModuleDefinitionGetModuleFile(ObjectPtr->ObjPtr)); } } public string ModuleFilePath { get { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); return Marshal.PtrToStringAnsi(InternalUnsafeMethods.ModuleDefinitionGetModuleFilePath(ObjectPtr->ObjPtr)); } } public string ModuleScriptFilePath { get { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); return Marshal.PtrToStringAnsi(InternalUnsafeMethods.ModuleDefinitionGetModuleScriptFilePath(ObjectPtr->ObjPtr)); } } #endregion #region Methods public string GetSignature() { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); return Marshal.PtrToStringAnsi(InternalUnsafeMethods.ModuleDefinitionGetSignature(ObjectPtr->ObjPtr)); } public bool Save() { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); return InternalUnsafeMethods.ModuleDefinitionSave(ObjectPtr->ObjPtr); } public ModuleManager GetModuleManager() { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); return new ModuleManager(InternalUnsafeMethods.ModuleDefinitionGetModuleManager(ObjectPtr->ObjPtr)); } public int GetDependencyCount() { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); return InternalUnsafeMethods.ModuleDefinitionGetDependencyCount(ObjectPtr->ObjPtr); } public string GetDependency(int dependencyIndex) { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); return Marshal.PtrToStringAnsi(InternalUnsafeMethods.ModuleDefinitionGetDependency(ObjectPtr->ObjPtr, dependencyIndex)); } public bool AddDependency(string moduleId, int versionId) { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); return InternalUnsafeMethods.ModuleDefinitionAddDependency(ObjectPtr->ObjPtr, moduleId, versionId); } public bool RemoveDependency(string moduleId) { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); return InternalUnsafeMethods.ModuleDefinitionRemoveDependency(ObjectPtr->ObjPtr, moduleId); } #endregion } }
using System; using System.Drawing; using System.IO; using System.Windows.Forms; using Shuttle.Core.Infrastructure; using Shuttle.Esb; using Shuttle.Esb.Management.Shell; namespace Shuttle.Esb.Management.Messages { public class MessageManagementPresenter : ManagementModulePresenter, IMessageManagementPresenter, IDisposable { private readonly ILog _log; private readonly IQueueManager _queueManager; private readonly ISerializer _serializer; private readonly IMessageManagementView _view; public MessageManagementPresenter() { _log = Log.For(this); _view = new MessageManagementView(this); _queueManager = new QueueManager(); _queueManager.ScanForQueueFactories(); var messageConfiguration = new MessageConfiguration(); _serializer = messageConfiguration.GetSerializer(); } public override string Text { get { return MessageResources.TextMessages; } } public override Image Image { get { return MessageResources.ImageMessage; } } public override UserControl ViewUserControl { get { return (UserControl)_view; } } protected bool HasCheckedMessages { get { return _view.GetCheckedMessages().Count > 0; } } public void Dispose() { if (_queueManager != null) { _queueManager.AttemptDispose(); } } public void Acknowledge() { if (!HasCheckedMessages) { _log.Information(MessageResources.NoMessageChecked); return; } if (MessageBox.Show(MessageResources.ConfirmMessageDeletion, MessageResources.Confirmation, MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes) { return; } ClearMessageView(); QueueTask("Acknowledge", () => { foreach (var receivedMessageItem in _view.GetCheckedMessages()) { receivedMessageItem.Queue.Acknowledge(receivedMessageItem.ReceivedMessage.AcknowledgementToken); } RemoveCheckedMessages(); }); } public void Move() { if (!HasCheckedMessages) { _log.Information(MessageResources.NoMessageChecked); return; } ClearMessageView(); var destinationQueueUriValue = _view.DestinationQueueUriValue; QueueTask("Move", () => { foreach (var receivedMessageItem in _view.GetCheckedMessages()) { var destination = _queueManager.GetQueue(destinationQueueUriValue); destination.Enqueue(receivedMessageItem.TransportMessage, receivedMessageItem.ReceivedMessage.Stream); receivedMessageItem.Queue.Acknowledge(receivedMessageItem.ReceivedMessage.AcknowledgementToken); _log.Information(string.Format(MessageResources.EnqueuedMessage, receivedMessageItem.TransportMessage.MessageId, destinationQueueUriValue)); _log.Information(string.Format(MessageResources.RemovedMessage, receivedMessageItem.TransportMessage.MessageId, receivedMessageItem.Queue)); } RemoveCheckedMessages(); }); } public void MoveAll() { var sourceQueueUriValue = _view.SourceQueueUriValue; var destinationQueueUriValue = _view.DestinationQueueUriValue; if (MessageBox.Show( string.Format(MessageResources.ConfirmMoveAll, sourceQueueUriValue, destinationQueueUriValue), MessageResources.Confirmation, MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes) { return; } ClearMessageView(); ReleaseMessage(); QueueTask("MoveAll", () => { var destination = _queueManager.GetQueue(destinationQueueUriValue); var source = _queueManager.GetQueue(sourceQueueUriValue); var totalMessagesMoved = 0; ReceivedMessage receivedMessage; do { receivedMessage = source.GetMessage(); if (receivedMessage == null) { continue; } var transportMessage = (TransportMessage) _serializer.Deserialize(typeof(TransportMessage), receivedMessage.Stream); destination.Enqueue(transportMessage, receivedMessage.Stream); source.Acknowledge(receivedMessage.AcknowledgementToken); totalMessagesMoved++; } while (receivedMessage != null); RemoveAllMessages(); _log.Information(string.Format(MessageResources.MoveAllComplete, totalMessagesMoved, sourceQueueUriValue, destinationQueueUriValue)); }); } private void RemoveAllMessages() { _view.RemoveAllItems(); } public void Copy() { if (!HasCheckedMessages) { _log.Information(MessageResources.NoMessageChecked); return; } var destinationQueueUriValue = _view.DestinationQueueUriValue; QueueTask("Copy", () => { foreach (var receivedMessageItem in _view.GetCheckedMessages()) { _queueManager.GetQueue(destinationQueueUriValue) .Enqueue(receivedMessageItem.TransportMessage, receivedMessageItem.ReceivedMessage.Stream); _log.Information(string.Format(MessageResources.EnqueuedMessage, receivedMessageItem.TransportMessage.MessageId, destinationQueueUriValue)); } RemoveCheckedMessages(); }); } public void CopyAll() { var sourceQueueUriValue = _view.SourceQueueUriValue; var destinationQueueUriValue = _view.DestinationQueueUriValue; if (!HasCheckedMessages) { _log.Information(MessageResources.NoMessageChecked); return; } if (MessageBox.Show( string.Format(MessageResources.ConfirmCopyAll, sourceQueueUriValue, destinationQueueUriValue), MessageResources.Confirmation, MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes) { return; } ClearMessageView(); QueueTask("CopyAll", () => { var destination = _queueManager.GetQueue(destinationQueueUriValue); var source = _queueManager.GetQueue(sourceQueueUriValue); var totalMessagesCopied = 0; var startMessageId = Guid.Empty; ReceivedMessage receivedMessage; TransportMessage transportMessage = null; do { receivedMessage = source.GetMessage(); if (receivedMessage == null) { continue; } transportMessage = (TransportMessage) _serializer.Deserialize(typeof(TransportMessage), receivedMessage.Stream); if (!transportMessage.MessageId.Equals(startMessageId)) { if (startMessageId.Equals(Guid.Empty)) { startMessageId = transportMessage.MessageId; } destination.Enqueue(transportMessage, receivedMessage.Stream); source.Release(receivedMessage.AcknowledgementToken); totalMessagesCopied++; } } while (receivedMessage != null && !startMessageId.Equals(transportMessage.MessageId)); RemoveAllMessages(); _log.Information(string.Format(MessageResources.CopyAllComplete, totalMessagesCopied, sourceQueueUriValue, destinationQueueUriValue)); }); } public void ReturnToSourceQueue() { if (!HasCheckedMessages) { _log.Information(MessageResources.NoMessageChecked); return; } ClearMessageView(); QueueTask("ReturnToSourceQueue", () => { foreach (var receivedMessageItem in _view.GetCheckedMessages()) { var destination = _queueManager.GetQueue(receivedMessageItem.TransportMessage.RecipientInboxWorkQueueUri); receivedMessageItem.TransportMessage.StopIgnoring(); receivedMessageItem.TransportMessage.FailureMessages.Clear(); destination.Enqueue(receivedMessageItem.TransportMessage, _serializer.Serialize(receivedMessageItem.TransportMessage)); receivedMessageItem.Queue.Acknowledge(receivedMessageItem.ReceivedMessage.AcknowledgementToken); _log.Information(string.Format(MessageResources.RemovedMessage, receivedMessageItem.TransportMessage.MessageId, receivedMessageItem.Queue)); _log.Information(string.Format(MessageResources.EnqueuedMessage, receivedMessageItem.TransportMessage.MessageId, receivedMessageItem.TransportMessage.RecipientInboxWorkQueueUri)); } RemoveCheckedMessages(); }); } public void ReturnAllToSourceQueue() { var sourceQueueUriValue = _view.SourceQueueUriValue; if (MessageBox.Show(string.Format(MessageResources.ConfirmReturnAllToSourceQueue, sourceQueueUriValue), MessageResources.Confirmation, MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes) { return; } ReleaseMessage(); ClearMessageView(); QueueTask("MoveAll", () => { var source = _queueManager.GetQueue(sourceQueueUriValue); var totalMessagesReturned = 0; ReceivedMessage receivedMessage; do { receivedMessage = source.GetMessage(); if (receivedMessage == null) { continue; } var transportMessage = (TransportMessage) _serializer.Deserialize(typeof(TransportMessage), receivedMessage.Stream); var destination = _queueManager.GetQueue(transportMessage.RecipientInboxWorkQueueUri); destination.Enqueue(transportMessage, receivedMessage.Stream); source.Acknowledge(receivedMessage.AcknowledgementToken); totalMessagesReturned++; } while (receivedMessage != null); RemoveAllMessages(); _log.Information(string.Format(MessageResources.ReturnAllToSourceQueueComplete, totalMessagesReturned, sourceQueueUriValue)); }); } public void GetMessage() { var sourceQueueUri = _view.SourceQueueUriValue; ClearMessageView(); QueueTask("GetMessage", () => { var queue = _queueManager.GetQueue(sourceQueueUri); if (queue == null) { _log.Error(MessageResources.SourceQueueUriReader); return; } var receivedMessage = queue.GetMessage(); if (receivedMessage == null) { return; } var transportMessage = (TransportMessage)_serializer.Deserialize(typeof(TransportMessage), receivedMessage.Stream); _view.AddReceivedMessageItem(new ReceivedMessageItem(queue, receivedMessage, transportMessage)); }); } public override void OnViewReady() { RefreshQueues(); } public void RefreshQueues() { QueueTask("RefreshQueues", () => _view.PopulateQueues(ManagementConfiguration.QueueRepository().All())); } public void MessageSelected(ReceivedMessageItem receivedMessageItem) { object message = null; var transportMessage = receivedMessageItem.TransportMessage; try { var type = Type.GetType(transportMessage.AssemblyQualifiedName, true, true); var canDisplayMessage = true; if (transportMessage.CompressionEnabled()) { _log.Warning(string.Format(MessageResources.MessageCompressed, transportMessage.MessageId)); canDisplayMessage = false; } if (transportMessage.EncryptionEnabled()) { _log.Warning(string.Format(MessageResources.MessageEncrypted, transportMessage.MessageId)); canDisplayMessage = false; } if (canDisplayMessage) { using (var stream = new MemoryStream(transportMessage.Message)) { message = _serializer.Deserialize(type, stream); } if (!type.AssemblyQualifiedName.Equals(transportMessage.AssemblyQualifiedName)) { _log.Warning(string.Format(MessageResources.MessageTypeMismatch, transportMessage.AssemblyQualifiedName, type.AssemblyQualifiedName)); } } } catch (Exception ex) { _log.Warning(string.Format(MessageResources.CannotObtainMessageType, transportMessage.AssemblyQualifiedName)); _log.Error(ex.Message); } _view.ShowMessage(transportMessage, message); } public void MessageSelectionCleared() { ClearMessageView(); } public void StopIgnoring() { if (!HasCheckedMessages) { _log.Information(MessageResources.NoMessageChecked); return; } ClearMessageView(); QueueTask("StopIgnoring", () => { foreach (var receivedMessageItem in _view.GetCheckedMessages()) { receivedMessageItem.TransportMessage.StopIgnoring(); receivedMessageItem.Queue.Enqueue(receivedMessageItem.TransportMessage, _serializer.Serialize(receivedMessageItem.TransportMessage)); receivedMessageItem.Queue.Acknowledge(receivedMessageItem.ReceivedMessage.AcknowledgementToken); } RemoveCheckedMessages(); }); } private void ClearMessageView() { _view.ClearMessageView(); } public void ReleaseMessage() { if (!HasCheckedMessages) { _log.Information(MessageResources.NoMessageChecked); return; } ClearMessageView(); QueueTask("ReleaseMessage", () => { foreach (var receivedMessageItem in _view.GetCheckedMessages()) { receivedMessageItem.Queue.Release(receivedMessageItem.ReceivedMessage.AcknowledgementToken); } RemoveCheckedMessages(); }); } private void RemoveCheckedMessages() { _view.RemoveCheckedItems(); } public class ReceivedMessageItem { public ReceivedMessageItem(IQueue queue, ReceivedMessage receivedMessage, TransportMessage transportMessage) { Guard.AgainstNull(queue, "queue"); Queue = queue; ReceivedMessage = receivedMessage; TransportMessage = transportMessage; } public IQueue Queue { get; private set; } public ReceivedMessage ReceivedMessage { get; private set; } public TransportMessage TransportMessage { get; private set; } } } }
using System; using ASMMath; using ASMDM; using System.Threading; using System.Collections; namespace LocalMachine { public class ASMProcessor { public ProgramCode currentcode; public RaiseError raiseerror; private ASMProcessorOperation[] ASMOperations = new ASMProcessorOperation[49]; public ASMProcessor() { 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--; //} }*/ public int PlaceMatrix(Matrix matrix){ lock(this) { for(int a=0;a<currentcode.matrixmemory.Length;a++) if(Object.ReferenceEquals(currentcode.matrixmemory[a], null)) { currentcode.matrixmemory[a] = matrix; return a; } } throw new Exception("Not enough Matrix Memory."); } /*private void FreeMatrixMemory(int loc){ currentcode.matrixmemory[loc]= null; }*/ 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)) { Matrix temp = currentcode.matrixmemory[(int)tempvar2]; temp = temp + tempvar1; if(tempvar2type==MEMTYPECONSTANTS.TEMPREFERENCE) { currentcode.matrixmemory[(int)tempvar2] = temp; tempvar1 = tempvar2; tempvar1type = MEMTYPECONSTANTS.TEMPREFERENCE; } else { tempvar1 = PlaceMatrix(temp); tempvar1type = MEMTYPECONSTANTS.TEMPREFERENCE; } } else if(tempvar2type==MEMTYPECONSTANTS.VALUE && (tempvar1type==MEMTYPECONSTANTS.REFERENCE || tempvar1type==MEMTYPECONSTANTS.TEMPREFERENCE)) { Matrix temp = currentcode.matrixmemory[(int)tempvar1]; temp = temp + tempvar2; if(tempvar1type==MEMTYPECONSTANTS.TEMPREFERENCE) currentcode.matrixmemory[(int)tempvar1] = temp; else { tempvar1 = PlaceMatrix(temp); tempvar1type = MEMTYPECONSTANTS.TEMPREFERENCE; } } else if((tempvar2type==MEMTYPECONSTANTS.REFERENCE || tempvar2type==MEMTYPECONSTANTS.TEMPREFERENCE) && (tempvar1type==MEMTYPECONSTANTS.REFERENCE || tempvar1type==MEMTYPECONSTANTS.TEMPREFERENCE)) { Matrix temp1 = currentcode.matrixmemory[(int)tempvar1]; Matrix temp2 = currentcode.matrixmemory[(int)tempvar2]; temp1 = temp1+temp2; if(tempvar1type==MEMTYPECONSTANTS.TEMPREFERENCE) { currentcode.matrixmemory[(int)tempvar1] = temp1; if(tempvar2type==MEMTYPECONSTANTS.TEMPREFERENCE)currentcode.matrixmemory[(int)tempvar2]= null; } else if(tempvar2type==MEMTYPECONSTANTS.TEMPREFERENCE) { 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_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)) { Matrix temp = currentcode.matrixmemory[(int)tempvar2]; temp = temp * tempvar1; if(tempvar2type==MEMTYPECONSTANTS.TEMPREFERENCE) { currentcode.matrixmemory[(int)tempvar2] = temp; tempvar1 = tempvar2; tempvar1type = MEMTYPECONSTANTS.TEMPREFERENCE; } else { tempvar1 = PlaceMatrix(temp); tempvar1type = MEMTYPECONSTANTS.TEMPREFERENCE; } } else if(tempvar2type==MEMTYPECONSTANTS.VALUE && (tempvar1type==MEMTYPECONSTANTS.REFERENCE || tempvar1type==MEMTYPECONSTANTS.TEMPREFERENCE)) { Matrix temp = currentcode.matrixmemory[(int)tempvar1]; temp = temp * tempvar2; if(tempvar1type==MEMTYPECONSTANTS.TEMPREFERENCE) currentcode.matrixmemory[(int)tempvar1] = temp; else { tempvar1 = PlaceMatrix(temp); tempvar1type = MEMTYPECONSTANTS.TEMPREFERENCE; } } else if((tempvar2type==MEMTYPECONSTANTS.REFERENCE || tempvar2type==MEMTYPECONSTANTS.TEMPREFERENCE) && (tempvar1type==MEMTYPECONSTANTS.REFERENCE || tempvar1type==MEMTYPECONSTANTS.TEMPREFERENCE)) { Matrix temp1 = currentcode.matrixmemory[(int)tempvar1]; Matrix temp2 = currentcode.matrixmemory[(int)tempvar2]; temp1 = temp1*temp2; if(tempvar1type==MEMTYPECONSTANTS.TEMPREFERENCE) { currentcode.matrixmemory[(int)tempvar1] = temp1; if(tempvar2type==MEMTYPECONSTANTS.TEMPREFERENCE)currentcode.matrixmemory[(int)tempvar2]= null; } else if(tempvar2type==MEMTYPECONSTANTS.TEMPREFERENCE) { 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_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)) { Matrix temp = currentcode.matrixmemory[(int)tempvar1]; temp = temp - tempvar2; if(tempvar1type==MEMTYPECONSTANTS.TEMPREFERENCE) currentcode.matrixmemory[(int)tempvar1] = temp; else { tempvar1 = PlaceMatrix(temp); tempvar1type = MEMTYPECONSTANTS.TEMPREFERENCE; } } else if(tempvar1type==MEMTYPECONSTANTS.VALUE && (tempvar2type==MEMTYPECONSTANTS.REFERENCE || tempvar2type==MEMTYPECONSTANTS.TEMPREFERENCE)) { if(tempvar2type==MEMTYPECONSTANTS.TEMPREFERENCE) { currentcode.matrixmemory[(int)tempvar2].InvSub(tempvar1); 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)) { Matrix temp1 = currentcode.matrixmemory[(int)tempvar1]; Matrix temp2 = currentcode.matrixmemory[(int)tempvar2]; temp1 = temp1-temp2; if(tempvar1type==MEMTYPECONSTANTS.TEMPREFERENCE) { currentcode.matrixmemory[(int)tempvar1] = temp1; if(tempvar2type==MEMTYPECONSTANTS.TEMPREFERENCE)currentcode.matrixmemory[(int)tempvar2]= null; } else if(tempvar2type==MEMTYPECONSTANTS.TEMPREFERENCE) { 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)) { Matrix temp = currentcode.matrixmemory[(int)tempvar1]; temp = temp / tempvar2; if(tempvar1type==MEMTYPECONSTANTS.TEMPREFERENCE) currentcode.matrixmemory[(int)tempvar1] = temp; else { tempvar1 = PlaceMatrix(temp); tempvar1type = MEMTYPECONSTANTS.TEMPREFERENCE; } } else if(tempvar1type==MEMTYPECONSTANTS.VALUE && (tempvar2type==MEMTYPECONSTANTS.REFERENCE || tempvar2type==MEMTYPECONSTANTS.TEMPREFERENCE)) { if(tempvar2type==MEMTYPECONSTANTS.TEMPREFERENCE) { currentcode.matrixmemory[(int)tempvar2].InvDiv(tempvar1); 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)) { Matrix temp1 = currentcode.matrixmemory[(int)tempvar1]; Matrix temp2 = currentcode.matrixmemory[(int)tempvar2]; temp1 = temp1/temp2; if(tempvar1type==MEMTYPECONSTANTS.TEMPREFERENCE) { currentcode.matrixmemory[(int)tempvar1] = temp1; if(tempvar2type==MEMTYPECONSTANTS.TEMPREFERENCE)currentcode.matrixmemory[(int)tempvar2]= null; } else if(tempvar2type==MEMTYPECONSTANTS.TEMPREFERENCE) { 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_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)) { Matrix temp = currentcode.matrixmemory[(int)tempvar1]; temp = temp ^ tempvar2; if(tempvar1type==MEMTYPECONSTANTS.TEMPREFERENCE) currentcode.matrixmemory[(int)tempvar1] = temp; else { tempvar1 = PlaceMatrix(temp); tempvar1type = MEMTYPECONSTANTS.TEMPREFERENCE; } } else if(tempvar1type==MEMTYPECONSTANTS.VALUE && (tempvar2type==MEMTYPECONSTANTS.REFERENCE || tempvar2type==MEMTYPECONSTANTS.TEMPREFERENCE)) { if(tempvar2type==MEMTYPECONSTANTS.TEMPREFERENCE) { currentcode.matrixmemory[(int)tempvar2].InvExp(tempvar1); 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)) { Matrix temp1 = currentcode.matrixmemory[(int)tempvar1]; Matrix temp2 = currentcode.matrixmemory[(int)tempvar2]; temp1 = temp1^temp2; if(tempvar1type==MEMTYPECONSTANTS.TEMPREFERENCE) { currentcode.matrixmemory[(int)tempvar1] = temp1; if(tempvar2type==MEMTYPECONSTANTS.TEMPREFERENCE)currentcode.matrixmemory[(int)tempvar2]= null; } else if(tempvar2type==MEMTYPECONSTANTS.TEMPREFERENCE) { 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_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)) { Matrix temp = currentcode.matrixmemory[(int)tempvar1]; temp = temp % tempvar2; if(tempvar1type==MEMTYPECONSTANTS.TEMPREFERENCE) currentcode.matrixmemory[(int)tempvar1] = temp; else { tempvar1 = PlaceMatrix(temp); tempvar1type = MEMTYPECONSTANTS.TEMPREFERENCE; } } else if(tempvar1type==MEMTYPECONSTANTS.VALUE && (tempvar2type==MEMTYPECONSTANTS.REFERENCE || tempvar2type==MEMTYPECONSTANTS.TEMPREFERENCE)) { if(tempvar2type==MEMTYPECONSTANTS.TEMPREFERENCE) { currentcode.matrixmemory[(int)tempvar2].InvMod(tempvar1); 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)) { Matrix temp1 = currentcode.matrixmemory[(int)tempvar1]; Matrix temp2 = currentcode.matrixmemory[(int)tempvar2]; temp1 = temp1%temp2; if(tempvar1type==MEMTYPECONSTANTS.TEMPREFERENCE) { currentcode.matrixmemory[(int)tempvar1] = temp1; if(tempvar2type==MEMTYPECONSTANTS.TEMPREFERENCE)currentcode.matrixmemory[(int)tempvar2]= null; } else if(tempvar2type==MEMTYPECONSTANTS.TEMPREFERENCE) { 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_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) { Matrix temp = currentcode.matrixmemory[(int)tempvar1]; temp = temp.ReturnNegative(); if(tempvar1type==MEMTYPECONSTANTS.TEMPREFERENCE) currentcode.matrixmemory[(int)tempvar1] = temp; 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]; 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) currentcode.matrixmemory[rmm]=null; } 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) { 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"); } 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) { 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"); currentcode.matrixmemory[(int)tempvar1].SetValue((int)tempvar2,(int)tempvar3,tempvar4); } 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++; 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)){ currentthread.cmpflag = (currentcode.matrixmemory[(int)tempvar1] == currentcode.matrixmemory[(int)tempvar2]); if(tempvar1type == MEMTYPECONSTANTS.TEMPREFERENCE)currentcode.matrixmemory[(int)tempvar1]= null; if(tempvar2type == MEMTYPECONSTANTS.TEMPREFERENCE)currentcode.matrixmemory[(int)tempvar2]= null; }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)) { currentthread.cmpflag = (currentcode.matrixmemory[(int)tempvar1] != currentcode.matrixmemory[(int)tempvar2]); if(tempvar1type == MEMTYPECONSTANTS.TEMPREFERENCE)currentcode.matrixmemory[(int)tempvar1]= null; if(tempvar2type == MEMTYPECONSTANTS.TEMPREFERENCE)currentcode.matrixmemory[(int)tempvar2]= null; } 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) { tempvar1 = PlaceMatrix(currentcode.matrixmemory[(int)tempvar1].ReturnTranspose()); tempvar1type = MEMTYPECONSTANTS.TEMPREFERENCE; } else if(tempvar1type == MEMTYPECONSTANTS.TEMPREFERENCE ){ currentcode.matrixmemory[(int)tempvar1].Transpose(); }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) { tempvar1 = PlaceMatrix(currentcode.matrixmemory[(int)tempvar1].ReturnAdjoint()); tempvar1type = MEMTYPECONSTANTS.TEMPREFERENCE; } else if(tempvar1type == MEMTYPECONSTANTS.TEMPREFERENCE ) { currentcode.matrixmemory[(int)tempvar1]=currentcode.matrixmemory[(int)tempvar1].ReturnAdjoint(); } 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) { tempvar1 = PlaceMatrix(currentcode.matrixmemory[(int)tempvar1].ReturnCos()); tempvar1type = MEMTYPECONSTANTS.TEMPREFERENCE; } else if(tempvar1type == MEMTYPECONSTANTS.TEMPREFERENCE ) { currentcode.matrixmemory[(int)tempvar1].Cos(); } 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) { tempvar1 = PlaceMatrix(currentcode.matrixmemory[(int)tempvar1].ReturnSin()); tempvar1type = MEMTYPECONSTANTS.TEMPREFERENCE; } else if(tempvar1type == MEMTYPECONSTANTS.TEMPREFERENCE ) { currentcode.matrixmemory[(int)tempvar1].Sin(); } 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) { tempvar1 = PlaceMatrix(currentcode.matrixmemory[(int)tempvar1].ReturnTan()); tempvar1type = MEMTYPECONSTANTS.TEMPREFERENCE; } else if(tempvar1type == MEMTYPECONSTANTS.TEMPREFERENCE ) { currentcode.matrixmemory[(int)tempvar1].Tan(); } 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) { tempvar1 = PlaceMatrix(currentcode.matrixmemory[(int)tempvar1].ReturnArcCos()); tempvar1type = MEMTYPECONSTANTS.TEMPREFERENCE; } else if(tempvar1type == MEMTYPECONSTANTS.TEMPREFERENCE ) { currentcode.matrixmemory[(int)tempvar1].ArcCos(); } 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) { tempvar1 = PlaceMatrix(currentcode.matrixmemory[(int)tempvar1].ReturnArcSin()); tempvar1type = MEMTYPECONSTANTS.TEMPREFERENCE; } else if(tempvar1type == MEMTYPECONSTANTS.TEMPREFERENCE ) { currentcode.matrixmemory[(int)tempvar1].ArcSin(); } 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) { tempvar1 = PlaceMatrix(currentcode.matrixmemory[(int)tempvar1].ReturnArcTan()); tempvar1type = MEMTYPECONSTANTS.TEMPREFERENCE; } else if(tempvar1type == MEMTYPECONSTANTS.TEMPREFERENCE ) { currentcode.matrixmemory[(int)tempvar1].ArcTan(); } 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) { tempvar1 = PlaceMatrix(currentcode.matrixmemory[(int)tempvar1].ReturnSquareRoot()); tempvar1type = MEMTYPECONSTANTS.TEMPREFERENCE; } else if(tempvar1type == MEMTYPECONSTANTS.TEMPREFERENCE ) { 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) { 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) currentcode.matrixmemory[tempvar2]= null; } 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) currentcode.matrixmemory[tempvar1]= null; } 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"); 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) currentcode.matrixmemory[tempvar1]= null; } 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"); 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) currentcode.matrixmemory[tempvar1]= null; } 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){ WrappedThreadObject tempthread = new WrappedThreadObject(this); ArrayList threads= new ArrayList(); ushort pcounter=1,scounter=0; while(pcounter>0){ currentthread.inspointer++; switch((ASMPROCESSOR_OPERATIONS)currentcode.instructions[currentthread.inspointer]){ case ASMPROCESSOR_OPERATIONS.PARALLELSTART: pcounter++; break; case ASMPROCESSOR_OPERATIONS.PARALLELEND: pcounter--; if(scounter==0)scounter=1; break; case ASMPROCESSOR_OPERATIONS.STATEMENTSTART: if(scounter==0) tempthread.mthread.inspointer=currentthread.inspointer+1; scounter++; break; case ASMPROCESSOR_OPERATIONS.STATEMENTEND: scounter--; break; } if(scounter==0){ tempthread.mthread.endthread = currentthread.inspointer-1; if(tempthread.mthread.endthread>tempthread.mthread.inspointer){ threads.Add(tempthread); tempthread.Start(); tempthread = new WrappedThreadObject(this); } } } //currentthread.inspointer++; foreach(WrappedThreadObject temp in threads) temp.thread.Join(); threads = null; }*/ /*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++; currentthread.inspointer += (currentcode.instructions[currentthread.inspointer]+1); 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]]; WrappedThreadObject tempthread = new WrappedThreadObject(this); ArrayList threads= new ArrayList(); ArrayList remotethreads = new ArrayList(); while(currentcode.instructions[currentthread.inspointer]==(ushort)ASMPROCESSOR_OPERATIONS.CREATETHREAD) { if(RemoteProcessorsManager.FreeProcessors.Count>0) { RemoteProcessor tmprp = RemoteProcessorsManager.PopProcessor(); currentthread.inspointer++; tmprp.mthread.inspointer = paralleloffset + (int)currentcode.numconstants[ currentcode.instructions[currentthread.inspointer]]; currentthread.inspointer++; tmprp.mthread.endthread = paralleloffset + (int)currentcode.numconstants[ currentcode.instructions[currentthread.inspointer]]; currentthread.inspointer++; tmprp.localprocessor = this; tmprp.memstart = currentthread.inspointer+1; tmprp.memend = currentthread.inspointer+currentcode.instructions[currentthread.inspointer]; currentthread.inspointer += (currentcode.instructions[currentthread.inspointer]+1); remotethreads.Add(tmprp); tmprp.Proccess(); } else{ 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 WrappedThreadObject(this); } } foreach(WrappedThreadObject temp in threads) temp.thread.Join(); foreach(RemoteProcessor tmprp in remotethreads) { tmprp.Join(); RemoteProcessorsManager.FreeProcessor(tmprp); } //threads = null; } } public class WrappedThreadObject{ public ProgramThread mthread; ASMProcessor threadprocessor; public Thread thread; public WrappedThreadObject(ASMProcessor threadprocessor){ this.mthread = new ProgramThread(); this.mthread.pstack = new double[LocalMachine.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); threadprocessor.raiseerror(ee.Message); } } } }
// 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.Linq; using System.Threading.Tasks; using System.Threading; namespace System.Net.NetworkInformation { // Linux implementation of NetworkChange public class NetworkChange { private static NetworkAddressChangedEventHandler s_addressChangedSubscribers; private static NetworkAvailabilityChangedEventHandler s_availabilityChangedSubscribers; private static volatile int s_socket = 0; // Lock controlling access to delegate subscriptions, socket initialization, availability-changed state and timer. private static readonly object s_gate = new object(); private static readonly Interop.Sys.NetworkChangeEvent s_networkChangeCallback = ProcessEvent; // The "leniency" window for NetworkAvailabilityChanged socket events. // All socket events received within this duration will be coalesced into a // single event. Generally, many route changed events are fired in succession, // and we are not interested in all of them, just the fact that network availability // has potentially changed as a result. private const int AvailabilityTimerWindowMilliseconds = 150; private static readonly TimerCallback s_availabilityTimerFiredCallback = OnAvailabilityTimerFired; private static Timer s_availabilityTimer; private static bool s_availabilityHasChanged; // Introduced for supporting design-time loading of System.Windows.dll [Obsolete("This API supports the .NET Framework infrastructure and is not intended to be used directly from your code.", true)] public static void RegisterNetworkChange(NetworkChange nc) { } public static event NetworkAddressChangedEventHandler NetworkAddressChanged { add { lock (s_gate) { if (s_socket == 0) { CreateSocket(); } s_addressChangedSubscribers += value; } } remove { lock (s_gate) { if (s_addressChangedSubscribers == null && s_availabilityChangedSubscribers == null) { Debug.Assert(s_socket == 0, "s_socket != 0, but there are no subscribers to NetworkAddressChanged or NetworkAvailabilityChanged."); return; } s_addressChangedSubscribers -= value; if (s_addressChangedSubscribers == null && s_availabilityChangedSubscribers == null) { CloseSocket(); } } } } public static event NetworkAvailabilityChangedEventHandler NetworkAvailabilityChanged { add { lock (s_gate) { if (s_socket == 0) { CreateSocket(); } if (s_availabilityTimer == null) { s_availabilityTimer = new Timer(s_availabilityTimerFiredCallback, null, -1, -1); } s_availabilityChangedSubscribers += value; } } remove { lock (s_gate) { if (s_addressChangedSubscribers == null && s_availabilityChangedSubscribers == null) { Debug.Assert(s_socket == 0, "s_socket != 0, but there are no subscribers to NetworkAddressChanged or NetworkAvailabilityChanged."); return; } s_availabilityChangedSubscribers -= value; if (s_availabilityChangedSubscribers == null) { if (s_availabilityTimer != null) { s_availabilityTimer.Dispose(); s_availabilityTimer = null; s_availabilityHasChanged = false; } if (s_addressChangedSubscribers == null) { CloseSocket(); } } } } } private static void CreateSocket() { Debug.Assert(s_socket == 0, "s_socket != 0, must close existing socket before opening another."); int newSocket; Interop.Error result = Interop.Sys.CreateNetworkChangeListenerSocket(out newSocket); if (result != Interop.Error.SUCCESS) { string message = Interop.Sys.GetLastErrorInfo().GetErrorMessage(); throw new NetworkInformationException(message); } s_socket = newSocket; Task.Factory.StartNew(s => LoopReadSocket((int)s), s_socket, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default); } private static void CloseSocket() { Debug.Assert(s_socket != 0, "s_socket was 0 when CloseSocket was called."); Interop.Error result = Interop.Sys.CloseNetworkChangeListenerSocket(s_socket); if (result != Interop.Error.SUCCESS) { string message = Interop.Sys.GetLastErrorInfo().GetErrorMessage(); throw new NetworkInformationException(message); } s_socket = 0; } private static void LoopReadSocket(int socket) { while (socket == s_socket) { Interop.Sys.ReadEvents(socket, s_networkChangeCallback); } } private static void ProcessEvent(int socket, Interop.Sys.NetworkChangeKind kind) { if (kind != Interop.Sys.NetworkChangeKind.None) { lock (s_gate) { if (socket == s_socket) { OnSocketEvent(kind); } } } } private static void OnSocketEvent(Interop.Sys.NetworkChangeKind kind) { switch (kind) { case Interop.Sys.NetworkChangeKind.AddressAdded: case Interop.Sys.NetworkChangeKind.AddressRemoved: s_addressChangedSubscribers?.Invoke(null, EventArgs.Empty); break; case Interop.Sys.NetworkChangeKind.AvailabilityChanged: lock (s_gate) { if (s_availabilityTimer != null) { if (!s_availabilityHasChanged) { s_availabilityTimer.Change(AvailabilityTimerWindowMilliseconds, -1); } s_availabilityHasChanged = true; } } break; } } private static void OnAvailabilityTimerFired(object state) { bool changed; lock (s_gate) { changed = s_availabilityHasChanged; s_availabilityHasChanged = false; } if (changed) { s_availabilityChangedSubscribers?.Invoke(null, new NetworkAvailabilityEventArgs(NetworkInterface.GetIsNetworkAvailable())); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.IO.Compression; using System.Net; using System.Net.Http; using System.Net.Test.Common; using System.Runtime.InteropServices; using System.Security.Authentication; using System.Security.Cryptography.X509Certificates; using System.Text; using System.Threading; using System.Threading.Tasks; using Xunit; using Xunit.Abstractions; namespace System.Net.Http.WinHttpHandlerUnitTests { public class WinHttpHandlerTest { private const string FakeProxy = "http://proxy.contoso.com"; private readonly ITestOutputHelper _output; public WinHttpHandlerTest(ITestOutputHelper output) { _output = output; TestControl.ResetAll(); } [Fact] public void Ctor_ExpectedDefaultPropertyValues() { var handler = new WinHttpHandler(); Assert.Equal(SslProtocols.None, handler.SslProtocols); Assert.True(handler.AutomaticRedirection); Assert.Equal(50, handler.MaxAutomaticRedirections); Assert.Equal(DecompressionMethods.None, handler.AutomaticDecompression); Assert.Equal(CookieUsePolicy.UseInternalCookieStoreOnly, handler.CookieUsePolicy); Assert.Null(handler.CookieContainer); Assert.Null(handler.ServerCertificateValidationCallback); Assert.False(handler.CheckCertificateRevocationList); Assert.Equal(ClientCertificateOption.Manual, handler.ClientCertificateOption); X509Certificate2Collection certs = handler.ClientCertificates; Assert.True(certs.Count == 0); Assert.False(handler.PreAuthenticate); Assert.Null(handler.ServerCredentials); Assert.Equal(WindowsProxyUsePolicy.UseWinHttpProxy, handler.WindowsProxyUsePolicy); Assert.Null(handler.DefaultProxyCredentials); Assert.Null(handler.Proxy); Assert.Equal(int.MaxValue, handler.MaxConnectionsPerServer); Assert.Equal(TimeSpan.FromSeconds(30), handler.SendTimeout); Assert.Equal(TimeSpan.FromSeconds(30), handler.ReceiveHeadersTimeout); Assert.Equal(TimeSpan.FromSeconds(30), handler.ReceiveDataTimeout); Assert.Equal(64, handler.MaxResponseHeadersLength); Assert.Equal(64 * 1024, handler.MaxResponseDrainSize); Assert.NotNull(handler.Properties); } [Fact] public void AutomaticRedirection_SetFalseAndGet_ValueIsFalse() { var handler = new WinHttpHandler(); handler.AutomaticRedirection = false; Assert.False(handler.AutomaticRedirection); } [Fact] public void AutomaticRedirection_SetTrue_ExpectedWinHttpHandleSettings() { var handler = new WinHttpHandler(); SendRequestHelper.Send( handler, delegate { handler.AutomaticRedirection = true; }); Assert.Equal( Interop.WinHttp.WINHTTP_OPTION_REDIRECT_POLICY_DISALLOW_HTTPS_TO_HTTP, APICallHistory.WinHttpOptionRedirectPolicy); } [Fact] public void AutomaticRedirection_SetFalse_ExpectedWinHttpHandleSettings() { var handler = new WinHttpHandler(); SendRequestHelper.Send( handler, delegate { handler.AutomaticRedirection = false; }); Assert.Equal( Interop.WinHttp.WINHTTP_OPTION_REDIRECT_POLICY_NEVER, APICallHistory.WinHttpOptionRedirectPolicy); } [Fact] public void CheckCertificateRevocationList_SetTrue_ExpectedWinHttpHandleSettings() { var handler = new WinHttpHandler(); SendRequestHelper.Send(handler, delegate { handler.CheckCertificateRevocationList = true; }); Assert.True(APICallHistory.WinHttpOptionEnableSslRevocation.Value); } [Fact] public void CheckCertificateRevocationList_SetFalse_ExpectedWinHttpHandleSettings() { var handler = new WinHttpHandler(); SendRequestHelper.Send(handler, delegate { handler.CheckCertificateRevocationList = false; }); Assert.False(APICallHistory.WinHttpOptionEnableSslRevocation.HasValue); } [Fact] public void CookieContainer_WhenCreated_ReturnsNull() { var handler = new WinHttpHandler(); Assert.Null(handler.CookieContainer); } [Fact] public async Task CookieUsePolicy_UseSpecifiedCookieContainerAndNullContainer_ThrowsInvalidOperationException() { var handler = new WinHttpHandler(); Assert.Null(handler.CookieContainer); handler.CookieUsePolicy = CookieUsePolicy.UseSpecifiedCookieContainer; using (var client = new HttpClient(handler)) { TestServer.SetResponse(DecompressionMethods.None, TestServer.ExpectedResponseBody); var request = new HttpRequestMessage(HttpMethod.Post, TestServer.FakeServerEndpoint); await Assert.ThrowsAsync<InvalidOperationException>(() => client.SendAsync(request)); } } [Fact] public void CookieUsePolicy_SetUsingInvalidEnum_ThrowsArgumentOutOfRangeException() { var handler = new WinHttpHandler(); Assert.Throws<ArgumentOutOfRangeException>(() => { handler.CookieUsePolicy = (CookieUsePolicy)100; }); } [Fact] public void CookieUsePolicy_WhenCreated_ReturnsUseInternalCookieStoreOnly() { var handler = new WinHttpHandler(); Assert.Equal(CookieUsePolicy.UseInternalCookieStoreOnly, handler.CookieUsePolicy); } [Fact] public void CookieUsePolicy_SetIgnoreCookies_NoExceptionThrown() { var handler = new WinHttpHandler(); handler.CookieUsePolicy = CookieUsePolicy.IgnoreCookies; } [Fact] public void CookieUsePolicy_SetUseInternalCookieStoreOnly_NoExceptionThrown() { var handler = new WinHttpHandler(); handler.CookieUsePolicy = CookieUsePolicy.UseInternalCookieStoreOnly; } [Fact] public void CookieUsePolicy_SetUseSpecifiedCookieContainer_NoExceptionThrown() { var handler = new WinHttpHandler(); handler.CookieUsePolicy = CookieUsePolicy.UseSpecifiedCookieContainer; } [Fact] public void CookieUsePolicy_SetIgnoreCookies_ExpectedWinHttpHandleSettings() { var handler = new WinHttpHandler(); SendRequestHelper.Send(handler, delegate { handler.CookieUsePolicy = CookieUsePolicy.IgnoreCookies; }); Assert.True(APICallHistory.WinHttpOptionDisableCookies.Value); } [Fact] public void CookieUsePolicy_SetUseInternalCookieStoreOnly_ExpectedWinHttpHandleSettings() { var handler = new WinHttpHandler(); SendRequestHelper.Send( handler, delegate { handler.CookieUsePolicy = CookieUsePolicy.UseInternalCookieStoreOnly; }); Assert.False(APICallHistory.WinHttpOptionDisableCookies.HasValue); } [Fact] public void CookieUsePolicy_SetUseSpecifiedCookieContainerAndContainer_ExpectedWinHttpHandleSettings() { var handler = new WinHttpHandler(); SendRequestHelper.Send( handler, delegate { handler.CookieUsePolicy = CookieUsePolicy.UseSpecifiedCookieContainer; handler.CookieContainer = new CookieContainer(); }); Assert.True(APICallHistory.WinHttpOptionDisableCookies.HasValue); } [Fact] public void Properties_Get_CountIsZero() { var handler = new WinHttpHandler(); IDictionary<string, object> dict = handler.Properties; Assert.Equal(0, dict.Count); } [Fact] public void Properties_AddItemToDictionary_ItemPresent() { var handler = new WinHttpHandler(); IDictionary<string, object> dict = handler.Properties; Assert.Same(dict, handler.Properties); var item = new object(); dict.Add("item", item); object value; Assert.True(dict.TryGetValue("item", out value)); Assert.Equal(item, value); } [Fact] public void WindowsProxyUsePolicy_SetUsingInvalidEnum_ThrowArgumentOutOfRangeException() { var handler = new WinHttpHandler(); Assert.Throws<ArgumentOutOfRangeException>( () => { handler.WindowsProxyUsePolicy = (WindowsProxyUsePolicy)100; }); } [Fact] public void WindowsProxyUsePolicy_SetDoNotUseProxy_NoExceptionThrown() { var handler = new WinHttpHandler(); handler.WindowsProxyUsePolicy = WindowsProxyUsePolicy.DoNotUseProxy; } [Fact] public void WindowsProxyUsePolicy_SetUseWinHttpProxy_NoExceptionThrown() { var handler = new WinHttpHandler(); handler.WindowsProxyUsePolicy = WindowsProxyUsePolicy.UseWinHttpProxy; } [Fact] public void WindowsProxyUsePolicy_SetUseWinWinInetProxy_NoExceptionThrown() { var handler = new WinHttpHandler(); handler.WindowsProxyUsePolicy = WindowsProxyUsePolicy.UseWinInetProxy; } [Fact] public void WindowsProxyUsePolicy_SetUseCustomProxy_NoExceptionThrown() { var handler = new WinHttpHandler(); handler.WindowsProxyUsePolicy = WindowsProxyUsePolicy.UseCustomProxy; } [Fact] public async Task WindowsProxyUsePolicy_UseNonNullProxyAndIncorrectWindowsProxyUsePolicy_ThrowsInvalidOperationException() { var handler = new WinHttpHandler(); handler.Proxy = new CustomProxy(false); handler.WindowsProxyUsePolicy = WindowsProxyUsePolicy.DoNotUseProxy; using (var client = new HttpClient(handler)) { TestServer.SetResponse(DecompressionMethods.None, TestServer.ExpectedResponseBody); var request = new HttpRequestMessage(HttpMethod.Post, TestServer.FakeServerEndpoint); await Assert.ThrowsAsync<InvalidOperationException>(() => client.SendAsync(request)); } } [Fact] public async Task WindowsProxyUsePolicy_UseCustomProxyAndNullProxy_ThrowsInvalidOperationException() { var handler = new WinHttpHandler(); handler.WindowsProxyUsePolicy = WindowsProxyUsePolicy.UseCustomProxy; handler.Proxy = null; using (var client = new HttpClient(handler)) { TestServer.SetResponse(DecompressionMethods.None, TestServer.ExpectedResponseBody); var request = new HttpRequestMessage(HttpMethod.Post, TestServer.FakeServerEndpoint); await Assert.ThrowsAsync<InvalidOperationException>(() => client.SendAsync(request)); } } [Fact] public void MaxAutomaticRedirections_SetZero_ThrowsArgumentOutOfRangeException() { var handler = new WinHttpHandler(); Assert.Throws<ArgumentOutOfRangeException>(() => { handler.MaxAutomaticRedirections = 0; }); } [Fact] public void MaxAutomaticRedirections_SetNegativeValue_ThrowsArgumentOutOfRangeException() { var handler = new WinHttpHandler(); Assert.Throws<ArgumentOutOfRangeException>(() => { handler.MaxAutomaticRedirections = -1; }); } [Fact] public void MaxAutomaticRedirections_SetValidValue_ExpectedWinHttpHandleSettings() { var handler = new WinHttpHandler(); int redirections = 35; SendRequestHelper.Send(handler, delegate { handler.MaxAutomaticRedirections = redirections; }); Assert.Equal((uint)redirections, APICallHistory.WinHttpOptionMaxHttpAutomaticRedirects); } [Fact] public void MaxConnectionsPerServer_SetZero_ThrowsArgumentOutOfRangeException() { var handler = new WinHttpHandler(); Assert.Throws<ArgumentOutOfRangeException>(() => { handler.MaxConnectionsPerServer = 0; }); } [Fact] public void MaxConnectionsPerServer_SetNegativeValue_ThrowsArgumentOutOfRangeException() { var handler = new WinHttpHandler(); Assert.Throws<ArgumentOutOfRangeException>(() => { handler.MaxConnectionsPerServer = -1; }); } [Fact] public void MaxConnectionsPerServer_SetPositiveValue_Success() { var handler = new WinHttpHandler(); handler.MaxConnectionsPerServer = 1; } [Fact] public void ReceiveDataTimeout_SetNegativeValue_ThrowsArgumentOutOfRangeException() { var handler = new WinHttpHandler(); Assert.Throws<ArgumentOutOfRangeException>( () => { handler.ReceiveDataTimeout = TimeSpan.FromMinutes(-10); }); } [Fact] public void ReceiveDataTimeout_SetTooLargeValue_ThrowsArgumentOutOfRangeException() { var handler = new WinHttpHandler(); Assert.Throws<ArgumentOutOfRangeException>( () => { handler.ReceiveDataTimeout = TimeSpan.FromMilliseconds(int.MaxValue + 1.0); }); } [Fact] public void ReceiveDataTimeout_SetZeroValue_ThrowsArgumentOutOfRangeException() { var handler = new WinHttpHandler(); Assert.Throws<ArgumentOutOfRangeException>(() => { handler.ReceiveDataTimeout = TimeSpan.FromSeconds(0); }); } [Fact] public void ReceiveDataTimeout_SetInfiniteValue_NoExceptionThrown() { var handler = new WinHttpHandler(); handler.ReceiveDataTimeout = Timeout.InfiniteTimeSpan; } [Fact] public void ReceiveHeadersTimeout_SetNegativeValue_ThrowsArgumentOutOfRangeException() { var handler = new WinHttpHandler(); Assert.Throws<ArgumentOutOfRangeException>( () => { handler.ReceiveHeadersTimeout = TimeSpan.FromMinutes(-10); }); } [Fact] public void ReceiveHeadersTimeout_SetTooLargeValue_ThrowsArgumentOutOfRangeException() { var handler = new WinHttpHandler(); Assert.Throws<ArgumentOutOfRangeException>( () => { handler.ReceiveHeadersTimeout = TimeSpan.FromMilliseconds(int.MaxValue + 1.0); }); } [Fact] public void ReceiveHeadersTimeout_SetZeroValue_ThrowsArgumentOutOfRangeException() { var handler = new WinHttpHandler(); Assert.Throws<ArgumentOutOfRangeException>( () => { handler.ReceiveHeadersTimeout = TimeSpan.FromSeconds(0); }); } [Fact] public void ReceiveHeadersTimeout_SetInfiniteValue_NoExceptionThrown() { var handler = new WinHttpHandler(); handler.ReceiveHeadersTimeout = Timeout.InfiniteTimeSpan; } [Theory] [ClassData(typeof(SslProtocolSupport.SupportedSslProtocolsTestData))] public void SslProtocols_SetUsingSupported_Success(SslProtocols protocol) { var handler = new WinHttpHandler(); handler.SslProtocols = protocol; } [Fact] public void SslProtocols_SetUsingNone_Success() { var handler = new WinHttpHandler(); handler.SslProtocols = SslProtocols.None; } [Theory] [InlineData( SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12, Interop.WinHttp.WINHTTP_FLAG_SECURE_PROTOCOL_TLS1 | Interop.WinHttp.WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_1 | Interop.WinHttp.WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_2)] #pragma warning disable 0618 [InlineData( SslProtocols.Ssl2 | SslProtocols.Ssl3, Interop.WinHttp.WINHTTP_FLAG_SECURE_PROTOCOL_SSL2 | Interop.WinHttp.WINHTTP_FLAG_SECURE_PROTOCOL_SSL3)] #pragma warning restore 0618 public void SslProtocols_SetUsingValidEnums_ExpectedWinHttpHandleSettings( SslProtocols specified, uint expectedProtocols) { var handler = new WinHttpHandler(); SendRequestHelper.Send( handler, delegate { handler.SslProtocols = specified; }); Assert.Equal(expectedProtocols, APICallHistory.WinHttpOptionSecureProtocols); } [Fact] public async Task GetAsync_MultipleRequestsReusingSameClient_Success() { var handler = new WinHttpHandler(); using (var client = new HttpClient(handler)) { for (int i = 0; i < 3; i++) { TestServer.SetResponse(DecompressionMethods.None, TestServer.ExpectedResponseBody); using (HttpResponseMessage response = await client.GetAsync(TestServer.FakeServerEndpoint)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); } } } } [Fact] public async Task SendAsync_ReadFromStreamingServer_PartialDataRead() { var handler = new WinHttpHandler(); using (var client = new HttpClient(handler)) { TestServer.SetResponse(DecompressionMethods.None, TestServer.ExpectedResponseBody); TestServer.DataAvailablePercentage = 0.25; int bytesRead; byte[] buffer = new byte[TestServer.ExpectedResponseBody.Length]; var request = new HttpRequestMessage(HttpMethod.Get, TestServer.FakeServerEndpoint); using (var response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); var stream = await response.Content.ReadAsStreamAsync(); bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length); _output.WriteLine("bytesRead={0}", bytesRead); } Assert.True(bytesRead < buffer.Length, "bytesRead should be less than buffer.Length"); } } [Fact] public async Task SendAsync_ReadAllDataFromStreamingServer_AllDataRead() { var handler = new WinHttpHandler(); using (var client = new HttpClient(handler)) { TestServer.SetResponse(DecompressionMethods.None, TestServer.ExpectedResponseBody); TestServer.DataAvailablePercentage = 0.25; int totalBytesRead = 0; int bytesRead; byte[] buffer = new byte[TestServer.ExpectedResponseBody.Length]; var request = new HttpRequestMessage(HttpMethod.Get, TestServer.FakeServerEndpoint); using (var response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); var stream = await response.Content.ReadAsStreamAsync(); do { bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length); _output.WriteLine("bytesRead={0}", bytesRead); totalBytesRead += bytesRead; } while (bytesRead != 0); } Assert.Equal(buffer.Length, totalBytesRead); } } [Fact] public async Task SendAsync_PostContentWithContentLengthAndChunkedEncodingHeaders_Success() { var handler = new WinHttpHandler(); using (var client = new HttpClient(handler)) { client.DefaultRequestHeaders.TransferEncodingChunked = true; TestServer.SetResponse(DecompressionMethods.None, TestServer.ExpectedResponseBody); var content = new StringContent(TestServer.ExpectedResponseBody); Assert.True(content.Headers.ContentLength.HasValue); var request = new HttpRequestMessage(HttpMethod.Post, TestServer.FakeServerEndpoint); request.Content = content; (await client.SendAsync(request)).Dispose(); } } [Fact] public async Task SendAsync_PostNoContentObjectWithChunkedEncodingHeader_ExpectHttpRequestException() { var handler = new WinHttpHandler(); using (var client = new HttpClient(handler)) { client.DefaultRequestHeaders.TransferEncodingChunked = true; TestServer.SetResponse(DecompressionMethods.None, TestServer.ExpectedResponseBody); var request = new HttpRequestMessage(HttpMethod.Post, TestServer.FakeServerEndpoint); await Assert.ThrowsAsync<HttpRequestException>(() => client.SendAsync(request)); } } [Fact] public async Task SendAsync_NoWinHttpDecompressionSupportAndResponseBodyIsDeflateCompressed_ExpectedResponse() { TestControl.WinHttpDecompressionSupport = false; var handler = new WinHttpHandler(); using (HttpResponseMessage response = SendRequestHelper.Send( handler, delegate { handler.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip; TestServer.SetResponse(DecompressionMethods.Deflate, TestServer.ExpectedResponseBody); })) { await VerifyResponseContent( TestServer.ExpectedResponseBodyBytes, response.Content, responseContentWasOriginallyCompressed: true, responseContentWasAutoDecompressed: true); } } [Fact] public async Task SendAsync_NoWinHttpDecompressionSupportAndResponseBodyIsGZipCompressed_ExpectedResponse() { TestControl.WinHttpDecompressionSupport = false; var handler = new WinHttpHandler(); using (HttpResponseMessage response = SendRequestHelper.Send( handler, delegate { handler.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip; TestServer.SetResponse(DecompressionMethods.GZip, TestServer.ExpectedResponseBody); })) { await VerifyResponseContent( TestServer.ExpectedResponseBodyBytes, response.Content, responseContentWasOriginallyCompressed: true, responseContentWasAutoDecompressed: true); } } [Fact] public async Task SendAsync_NoWinHttpDecompressionSupportAndResponseBodyIsNotCompressed_ExpectedResponse() { TestControl.WinHttpDecompressionSupport = false; var handler = new WinHttpHandler(); using (HttpResponseMessage response = SendRequestHelper.Send( handler, delegate { handler.WindowsProxyUsePolicy = WindowsProxyUsePolicy.UseWinInetProxy; })) { await VerifyResponseContent( TestServer.ExpectedResponseBodyBytes, response.Content, responseContentWasOriginallyCompressed: false, responseContentWasAutoDecompressed: false); } } [Theory] [InlineData(false)] [InlineData(true)] public async Task SendAsync_NoWinHttpDecompressionSupport_AutoDecompressionSettingDiffers_ResponseIsNotDecompressed(bool responseIsGZip) { DecompressionMethods decompressionMethods = responseIsGZip ? DecompressionMethods.Deflate : DecompressionMethods.GZip; _output.WriteLine("DecompressionMethods = {0}", decompressionMethods.ToString()); TestControl.WinHttpDecompressionSupport = false; var handler = new WinHttpHandler(); using (HttpResponseMessage response = SendRequestHelper.Send( handler, delegate { handler.AutomaticDecompression = decompressionMethods; TestServer.SetResponse(responseIsGZip ? DecompressionMethods.GZip : DecompressionMethods.Deflate, TestServer.ExpectedResponseBody); })) { await VerifyResponseContent( TestServer.CompressBytes(TestServer.ExpectedResponseBodyBytes, useGZip: responseIsGZip), response.Content, responseContentWasOriginallyCompressed: true, responseContentWasAutoDecompressed: false); } } [Fact] public void SendAsync_AutomaticProxySupportAndUseWinInetSettings_ExpectedWinHttpSessionProxySettings() { TestControl.WinHttpAutomaticProxySupport = true; var handler = new WinHttpHandler(); SendRequestHelper.Send( handler, delegate { handler.WindowsProxyUsePolicy = WindowsProxyUsePolicy.UseWinInetProxy; }); Assert.Equal(Interop.WinHttp.WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY, APICallHistory.SessionProxySettings.AccessType); } [Fact] public void SendAsync_NoAutomaticProxySupportAndUseWinInetSettingsWithAutoDetectSetting_ExpectedWinHttpProxySettings() { TestControl.WinHttpAutomaticProxySupport = false; FakeRegistry.WinInetProxySettings.AutoDetect = true; var handler = new WinHttpHandler(); SendRequestHelper.Send( handler, delegate { handler.WindowsProxyUsePolicy = WindowsProxyUsePolicy.UseWinInetProxy; }); Assert.Equal(Interop.WinHttp.WINHTTP_ACCESS_TYPE_NO_PROXY, APICallHistory.SessionProxySettings.AccessType); Assert.Equal(Interop.WinHttp.WINHTTP_ACCESS_TYPE_NAMED_PROXY, APICallHistory.RequestProxySettings.AccessType); } [Fact] public void SendAsync_NoAutomaticProxySupportAndUseWinInetSettingsWithEmptySettings_ExpectedWinHttpProxySettings() { TestControl.WinHttpAutomaticProxySupport = false; var handler = new WinHttpHandler(); SendRequestHelper.Send( handler, delegate { handler.WindowsProxyUsePolicy = WindowsProxyUsePolicy.UseWinInetProxy; }); Assert.Equal(Interop.WinHttp.WINHTTP_ACCESS_TYPE_NO_PROXY, APICallHistory.SessionProxySettings.AccessType); Assert.False(APICallHistory.RequestProxySettings.AccessType.HasValue); } [Fact] public void SendAsync_NoAutomaticProxySupportAndUseWinInetSettingsWithManualSettingsOnly_ExpectedWinHttpProxySettings() { TestControl.WinHttpAutomaticProxySupport = false; FakeRegistry.WinInetProxySettings.Proxy = FakeProxy; var handler = new WinHttpHandler(); SendRequestHelper.Send( handler, delegate { handler.WindowsProxyUsePolicy = WindowsProxyUsePolicy.UseWinInetProxy; }); Assert.Equal(Interop.WinHttp.WINHTTP_ACCESS_TYPE_NAMED_PROXY, APICallHistory.SessionProxySettings.AccessType); Assert.False(APICallHistory.RequestProxySettings.AccessType.HasValue); } [Fact] public void SendAsync_NoAutomaticProxySupportAndUseWinInetSettingsWithMissingRegistrySettings_ExpectedWinHttpProxySettings() { TestControl.WinHttpAutomaticProxySupport = false; FakeRegistry.WinInetProxySettings.RegistryKeyMissing = true; var handler = new WinHttpHandler(); SendRequestHelper.Send( handler, delegate { handler.WindowsProxyUsePolicy = WindowsProxyUsePolicy.UseWinInetProxy; }); Assert.Equal(Interop.WinHttp.WINHTTP_ACCESS_TYPE_NO_PROXY, APICallHistory.SessionProxySettings.AccessType); Assert.False(APICallHistory.RequestProxySettings.AccessType.HasValue); } [Fact] public void SendAsync_NoAutomaticProxySupportAndUseWinInetSettingsWithAutoDetectButPACFileNotDetectedOnNetwork_ExpectedWinHttpProxySettings() { TestControl.WinHttpAutomaticProxySupport = false; TestControl.PACFileNotDetectedOnNetwork = true; FakeRegistry.WinInetProxySettings.AutoDetect = true; var handler = new WinHttpHandler(); SendRequestHelper.Send( handler, delegate { handler.WindowsProxyUsePolicy = WindowsProxyUsePolicy.UseWinInetProxy; }); Assert.Equal(Interop.WinHttp.WINHTTP_ACCESS_TYPE_NO_PROXY, APICallHistory.SessionProxySettings.AccessType); Assert.Null(APICallHistory.RequestProxySettings.AccessType); } [Fact] public void SendAsync_NoAutomaticProxySupportAndUseWinInetSettingsWithAutoDetectSettingAndManualSettingButPACFileNotFoundOnNetwork_ExpectedWinHttpProxySettings() { const string manualProxy = FakeProxy; TestControl.WinHttpAutomaticProxySupport = false; FakeRegistry.WinInetProxySettings.AutoDetect = true; FakeRegistry.WinInetProxySettings.Proxy = manualProxy; TestControl.PACFileNotDetectedOnNetwork = true; var handler = new WinHttpHandler(); SendRequestHelper.Send( handler, delegate { handler.WindowsProxyUsePolicy = WindowsProxyUsePolicy.UseWinInetProxy; }); // Both AutoDetect and manual proxy are specified. If AutoDetect fails to find // the PAC file on the network, then we should fall back to manual setting. Assert.Equal(Interop.WinHttp.WINHTTP_ACCESS_TYPE_NO_PROXY, APICallHistory.SessionProxySettings.AccessType); Assert.Equal(Interop.WinHttp.WINHTTP_ACCESS_TYPE_NAMED_PROXY, APICallHistory.RequestProxySettings.AccessType); Assert.Equal(manualProxy, APICallHistory.RequestProxySettings.Proxy); } [Fact] public void SendAsync_UseNoProxy_ExpectedWinHttpProxySettings() { var handler = new WinHttpHandler(); SendRequestHelper.Send(handler, delegate { handler.WindowsProxyUsePolicy = WindowsProxyUsePolicy.DoNotUseProxy; }); Assert.Equal(Interop.WinHttp.WINHTTP_ACCESS_TYPE_NO_PROXY, APICallHistory.SessionProxySettings.AccessType); } [Fact] public void SendAsync_UseCustomProxyWithNoBypass_ExpectedWinHttpProxySettings() { var handler = new WinHttpHandler(); var customProxy = new CustomProxy(false); SendRequestHelper.Send( handler, delegate { handler.WindowsProxyUsePolicy = WindowsProxyUsePolicy.UseCustomProxy; handler.Proxy = customProxy; }); Assert.Equal(Interop.WinHttp.WINHTTP_ACCESS_TYPE_NO_PROXY, APICallHistory.SessionProxySettings.AccessType); Assert.Equal(Interop.WinHttp.WINHTTP_ACCESS_TYPE_NAMED_PROXY, APICallHistory.RequestProxySettings.AccessType); Assert.Equal(FakeProxy, APICallHistory.RequestProxySettings.Proxy); } [Fact] public void SendAsync_UseCustomProxyWithBypass_ExpectedWinHttpProxySettings() { var handler = new WinHttpHandler(); var customProxy = new CustomProxy(true); SendRequestHelper.Send( handler, delegate { handler.WindowsProxyUsePolicy = WindowsProxyUsePolicy.UseCustomProxy; handler.Proxy = customProxy; }); Assert.Equal(Interop.WinHttp.WINHTTP_ACCESS_TYPE_NO_PROXY, APICallHistory.SessionProxySettings.AccessType); Assert.Equal(Interop.WinHttp.WINHTTP_ACCESS_TYPE_NO_PROXY, APICallHistory.RequestProxySettings.AccessType); } [Fact] public void SendAsync_AutomaticProxySupportAndUseDefaultWebProxy_ExpectedWinHttpSessionProxySettings() { TestControl.WinHttpAutomaticProxySupport = true; var handler = new WinHttpHandler(); SendRequestHelper.Send( handler, delegate { handler.WindowsProxyUsePolicy = WindowsProxyUsePolicy.UseCustomProxy; handler.Proxy = new FakeDefaultWebProxy(); }); Assert.Equal(Interop.WinHttp.WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY, APICallHistory.SessionProxySettings.AccessType); } [Fact] public async Task SendAsync_SlowPostRequestWithTimedCancellation_ExpectTaskCanceledException() { var handler = new WinHttpHandler(); TestControl.WinHttpReceiveResponse.Delay = 5000; CancellationTokenSource cts = new CancellationTokenSource(50); using (var client = new HttpClient(handler)) { var request = new HttpRequestMessage(HttpMethod.Post, TestServer.FakeServerEndpoint); var content = new StringContent(new string('a', 1000)); request.Content = content; await Assert.ThrowsAsync<TaskCanceledException>(() => client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cts.Token)); } } [Fact] public async Task SendAsync_SlowGetRequestWithTimedCancellation_ExpectTaskCanceledException() { var handler = new WinHttpHandler(); TestControl.WinHttpReceiveResponse.Delay = 5000; CancellationTokenSource cts = new CancellationTokenSource(50); using (var client = new HttpClient(handler)) { var request = new HttpRequestMessage(HttpMethod.Get, TestServer.FakeServerEndpoint); await Assert.ThrowsAsync<TaskCanceledException>(() => client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cts.Token)); } } [Fact] public async Task SendAsync_RequestWithCanceledToken_ExpectTaskCanceledException() { var handler = new WinHttpHandler(); CancellationTokenSource cts = new CancellationTokenSource(); cts.Cancel(); using (var client = new HttpClient(handler)) { var request = new HttpRequestMessage(HttpMethod.Get, TestServer.FakeServerEndpoint); await Assert.ThrowsAsync<TaskCanceledException>(() => client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cts.Token)); } } [Fact] public async Task SendAsync_WinHttpOpenReturnsError_ExpectHttpRequestException() { var handler = new WinHttpHandler(); var client = new HttpClient(handler); var request = new HttpRequestMessage(HttpMethod.Get, TestServer.FakeServerEndpoint); TestControl.WinHttpOpen.ErrorWithApiCall = true; Exception ex = await Assert.ThrowsAsync<HttpRequestException>(() => client.SendAsync(request)); Assert.Equal(typeof(WinHttpException), ex.InnerException.GetType()); } [Fact] public void SendAsync_MultipleCallsWithDispose_NoHandleLeaksManuallyVerifiedUsingLogging() { for (int i = 0; i < 50; i++) { using (var handler = new WinHttpHandler()) using (HttpResponseMessage response = SendRequestHelper.Send(handler, () => { })) { } } } private async Task VerifyResponseContent( byte[] expectedResponseBodyBytes, HttpContent responseContent, bool responseContentWasOriginallyCompressed, bool responseContentWasAutoDecompressed) { Nullable<long> contentLength = responseContent.Headers.ContentLength; ICollection<string> contentEncoding = responseContent.Headers.ContentEncoding; _output.WriteLine("Response Content.Headers.ContentLength = {0}", contentLength.HasValue ? contentLength.Value.ToString() : "(null)"); _output.WriteLine("Response Content.Headers.ContentEncoding = {0}", contentEncoding.Count > 0 ? contentEncoding.ToString() : "(null)"); byte[] responseBodyBytes = await responseContent.ReadAsByteArrayAsync(); _output.WriteLine($"Response Body = {BitConverter.ToString(responseBodyBytes)}"); _output.WriteLine($"Expected Response Body = {BitConverter.ToString(expectedResponseBodyBytes)}"); if (!responseContentWasOriginallyCompressed) { Assert.True(contentLength > 0); } else if (responseContentWasAutoDecompressed) { Assert.Null(contentLength); Assert.Equal(0, contentEncoding.Count); } else { Assert.True(contentLength > 0); Assert.True(contentEncoding.Count > 0); } Assert.Equal<byte>(expectedResponseBodyBytes, responseBodyBytes); } // Commented out as the test relies on finalizer for cleanup and only has value as written // when run on its own and manual analysis is done of logs. //[Fact] //public void SendAsync_MultipleCallsWithoutDispose_NoHandleLeaksManuallyVerifiedUsingLogging() //{ // WinHttpHandler handler; // HttpResponseMessage response; // for (int i = 0; i < 50; i++) // { // handler = new WinHttpHandler(); // response = SendRequestHelper.Send(handler, () => { }); // } //} public class CustomProxy : IWebProxy { private const string DefaultDomain = "domain"; private const string DefaultUsername = "username"; private const string DefaultPassword = "password"; private bool bypassAll; private NetworkCredential networkCredential; public CustomProxy(bool bypassAll) { this.bypassAll = bypassAll; this.networkCredential = new NetworkCredential(CustomProxy.DefaultUsername, CustomProxy.DefaultPassword, CustomProxy.DefaultDomain); } public string UsernameWithDomain { get { return CustomProxy.DefaultDomain + "\\" + CustomProxy.DefaultUsername; } } public string Password { get { return CustomProxy.DefaultPassword; } } public NetworkCredential NetworkCredential { get { return this.networkCredential; } } ICredentials IWebProxy.Credentials { get { return this.networkCredential; } set { } } Uri IWebProxy.GetProxy(Uri destination) { return new Uri(FakeProxy); } bool IWebProxy.IsBypassed(Uri host) { return this.bypassAll; } } public class FakeDefaultWebProxy : IWebProxy { private ICredentials _credentials = null; public FakeDefaultWebProxy() { } public ICredentials Credentials { get { return _credentials; } set { _credentials = value; } } // This is a sentinel object representing the internal default system proxy that a developer would // use when accessing the System.Net.WebRequest.DefaultWebProxy property (from the System.Net.Requests // package). It can't support the GetProxy or IsBypassed methods. WinHttpHandler will handle this // exception and use the appropriate system default proxy. public Uri GetProxy(Uri destination) { throw new PlatformNotSupportedException(); } public bool IsBypassed(Uri host) { throw new PlatformNotSupportedException(); } } } }
using System; using System.IO; using System.Web; using System.Web.Routing; using log4net; using MbUnit.Framework; using Moq; using Subtext.Framework.Data; using Subtext.Framework.Exceptions; using Subtext.Framework.Infrastructure.Installation; using Subtext.Framework.Routing; using Subtext.Framework.Web.HttpModules; using Subtext.Infrastructure; using Subtext.Web; namespace UnitTests.Subtext.SubtextWeb { [TestFixture] public class SubtextApplicationTests { [Test] public void StartApplication_SetsLogInitializedToFalse() { // arrange var app = new SubtextApplication(null); var server = new Mock<HttpServerUtilityBase>(); // act app.StartApplication(new SubtextRouteMapper(new RouteCollection(), new Mock<IServiceLocator>().Object), server.Object); // assert Assert.IsFalse(app.LogInitialized); } [Test] public void StartApplication_AddsAdminDirectoryToInvalidPaths_IfAdminDirectoryExistsInWrongPlace() { // arrange var app = new SubtextApplication(null); var server = new Mock<HttpServerUtilityBase>(); server.Setup(s => s.MapPath("~/Admin")).Returns(Directory.CreateDirectory("Admin").FullName); // act app.StartApplication(new SubtextRouteMapper(new RouteCollection(), new Mock<IServiceLocator>().Object), server.Object); // assert Assert.AreEqual("~/Admin", app.DeprecatedPhysicalPaths[0]); } [Test] public void StartApplication_AddsLoginFileToInvalidPaths_IfLoginFileExistsInWrongPlace() { // arrange var app = new SubtextApplication(null); var server = new Mock<HttpServerUtilityBase>(); using(StreamWriter writer = File.CreateText("login.aspx")) { writer.Write("test"); } server.Setup(s => s.MapPath("~/login.aspx")).Returns(Path.GetFullPath("login.aspx")); // act app.StartApplication(new SubtextRouteMapper(new RouteCollection(), new Mock<IServiceLocator>().Object), server.Object); // assert Assert.AreEqual("~/login.aspx", app.DeprecatedPhysicalPaths[0]); } [Test] public void StartApplication_AddsHostAdminDirectoryToInvalidPaths_IfHostAdminDirectoryExistsInWrongPlace() { // arrange var app = new SubtextApplication(null); var server = new Mock<HttpServerUtilityBase>(); server.Setup(s => s.MapPath("~/HostAdmin")).Returns(Directory.CreateDirectory("HostAdmin").FullName); // act app.StartApplication(new SubtextRouteMapper(new RouteCollection(), new Mock<IServiceLocator>().Object), server.Object); // assert Assert.AreEqual("~/HostAdmin", app.DeprecatedPhysicalPaths[0]); } [Test] public void BeginApplicationRequest_LogsThatTheApplicationHasStartedAndSetsLogInitializedTrue() { // arrange var app = new SubtextApplication(null); Assert.IsFalse(app.LogInitialized); var log = new Mock<ILog>(); string logMessage = null; log.Setup(l => l.Info(It.IsAny<string>())).Callback<object>(s => logMessage = s.ToString()); // act app.BeginApplicationRequest(log.Object); // assert Assert.AreEqual("Subtext Application Started", logMessage); Assert.IsTrue(app.LogInitialized); } [Test] public void BeginApplicationRequest_WithOldAdminDirectory_ThrowsDeprecatedFileExistsException() { // arrange var app = new SubtextApplication(null); var server = new Mock<HttpServerUtilityBase>(); server.Setup(s => s.MapPath("~/Admin")).Returns(Directory.CreateDirectory("Admin").FullName); app.StartApplication(new SubtextRouteMapper(new RouteCollection(), new Mock<IServiceLocator>().Object), server.Object); // act, assert var exception = UnitTestHelper.AssertThrows<DeprecatedPhysicalPathsException>(() => app.BeginApplicationRequest( new Mock<ILog>().Object)); Assert.AreEqual("~/Admin", exception.InvalidPhysicalPaths[0]); } [Test] public void UnwrapHttpUnhandledException_WithHttpUnhandledExceptionContainingNoInnerException_ReturnsNull() { // act Exception exception = SubtextApplication.UnwrapHttpUnhandledException(new HttpUnhandledException()); // assert Assert.IsNull(exception); } [Test] public void UnwrapHttpUnhandledException_WithHttpUnhandledExceptionContainingInnerException_ReturnsInnerException() { // arrange var innerException = new Exception(); // act Exception exception = SubtextApplication.UnwrapHttpUnhandledException(new HttpUnhandledException("whatever", innerException)); // assert Assert.AreEqual(innerException, exception); } [Test] public void OnApplicationError_WithUnhandledExceptionAndCustomErrorsEnabled_TransfersToErrorPage() { // arrange string transferLocation = null; var server = new Mock<HttpServerUtilityBase>(); server.Setup(s => s.Transfer(It.IsAny<string>())).Callback<string>(s => transferLocation = s); // act SubtextApplication.HandleUnhandledException(new Exception(), server.Object, true /* customErrorEnabled */, new Mock<ILog>().Object); // assert Assert.AreEqual("~/aspx/SystemMessages/error.aspx", transferLocation); } [Test] public void OnApplicationError_WithUnhandledExceptionAndCustomErrorsDisabled_LogsMessage() { // arrange var log = new Mock<ILog>(); string logMessage = null; log.Setup(l => l.Error(It.IsAny<object>(), It.IsAny<Exception>())).Callback<object, Exception>( (s, e) => logMessage = s.ToString()); // act SubtextApplication.HandleUnhandledException(new Exception(), null, false /* customErrorEnabled */, log.Object); // assert Assert.AreEqual("Unhandled Exception trapped in Global.asax", logMessage); } [Test] public void OnApplicationError_WithHttpUnhandledExceptionContainingNoInnerException_Transfers() { // arrange var app = new SubtextApplication(null); string transferLocation = null; var server = new Mock<HttpServerUtilityBase>(); server.Setup(s => s.Transfer(It.IsAny<string>())).Callback<string>(s => transferLocation = s); // act app.OnApplicationError(new HttpUnhandledException(), server.Object, new Mock<ILog>().Object, null); // assert Assert.AreEqual("~/aspx/SystemMessages/error.aspx", transferLocation); } [Test] public void LogIfCommentException_LogsCommentException() { // arrange var exception = new CommentDuplicateException(); var log = new Mock<ILog>(); string logMessage = null; log.Setup(l => l.Info(It.IsAny<string>(), exception)).Callback<object, Exception>( (o, e) => logMessage = o.ToString()); // act SubtextApplication.LogIfCommentException(exception, log.Object); // assert Assert.AreEqual("Comment exception thrown and handled in Global.asax.", logMessage); } [Test] public void LogIfCommentException_DoesNothingForNonCommentException() { // arrange var exception = new Exception(); var log = new Mock<ILog>(); log.Setup(l => l.Info(It.IsAny<string>())).Throws(new Exception("Nothing should have been logged")); // act, assert SubtextApplication.LogIfCommentException(exception, log.Object); } [Test] public void HandleDrepecatedFilePathsException_WithNonDeprecatedPhysicalPathsException_ReturnsFalse() { // arrange var exception = new Exception(); var application = new Mock<SubtextApplication>(); application.Setup(a => a.FinishRequest()); // act bool handled = SubtextApplication.HandleDeprecatedFilePathsException(exception, null, application.Object); // assert Assert.IsFalse(handled); } [Test] public void HandleDeprecatedFilePathsException_WithDepecatedPhysicalPathsException_ReturnsFalse() { // arrange var exception = new DeprecatedPhysicalPathsException(new[] {"~/Admin"}); var server = new Mock<HttpServerUtilityBase>(); string transferLocation = null; server.Setup(s => s.Execute(It.IsAny<string>(), false)).Callback<string, bool>( (s, b) => transferLocation = s); var application = new Mock<SubtextApplication>(); application.Setup(a => a.FinishRequest()); // act bool handled = SubtextApplication.HandleDeprecatedFilePathsException(exception, server.Object, application.Object); // assert Assert.AreEqual("~/aspx/SystemMessages/DeprecatedPhysicalPaths.aspx", transferLocation); Assert.IsTrue(handled); } [Test] public void HandleSqlException_ReturnsFalseForNonSqlException() { // arrange var exception = new Exception(); // act bool handled = SubtextApplication.HandleSqlException(exception, null); // assert Assert.IsFalse(handled); } [Test] public void HandleSqlException_WithSqlServerDoesNotExistOrAccessDeniedError_TransfersToBadConnectionStringPageAndReturnsTrue () { // arrange var server = new Mock<HttpServerUtilityBase>(); string transferLocation = null; server.Setup(s => s.Transfer(It.IsAny<string>())).Callback<string>(s => transferLocation = s); // act bool handled = SubtextApplication.HandleSqlExceptionNumber((int)SqlErrorMessage.SqlServerDoesNotExistOrAccessDenied, "", server.Object); // assert Assert.AreEqual("~/aspx/SystemMessages/CheckYourConnectionString.aspx", transferLocation); Assert.IsTrue(handled); } [Test] public void HandleSqlException_WithSqlServerCouldNotFindStoredProcedureAndProcNameIsBlog_GetConfig_TransfersToBadConnectionStringPageAndReturnsTrue () { // arrange var server = new Mock<HttpServerUtilityBase>(); string transferLocation = null; server.Setup(s => s.Transfer(It.IsAny<string>())).Callback<string>(s => transferLocation = s); // act bool handled = SubtextApplication.HandleSqlExceptionNumber( (int)SqlErrorMessage.CouldNotFindStoredProcedure, "'blog_GetConfig'", server.Object); // assert Assert.AreEqual("~/aspx/SystemMessages/CheckYourConnectionString.aspx", transferLocation); Assert.IsTrue(handled); } [Test] public void HandleRequestLocationException_WithInstallationActionRequired_RedirectsToInstallDefault() { // arrange var response = new Mock<HttpResponseBase>(); string redirectLocation = null; response.Setup(r => r.Redirect(It.IsAny<string>(), true)).Callback<string, bool>( (s, endRequest) => redirectLocation = s); var blogRequest = new BlogRequest("", "", new Uri("http://haacked.com/"), false); var installationManager = new Mock<IInstallationManager>(); installationManager.Setup(i => i.InstallationActionRequired(It.IsAny<Version>(), null)).Returns(true); // act bool handled = SubtextApplication.HandleRequestLocationException(null, blogRequest, installationManager.Object, response.Object); // assert Assert.AreEqual("~/install/default.aspx", redirectLocation); Assert.IsTrue(handled); } [Test] public void HandleRequestLocationException_IgnoresInstallationLocation() { // arrange var response = new Mock<HttpResponseBase>(); response.Setup(r => r.Redirect(It.IsAny<string>(), true)).Throws( new Exception("Test Failed. Should not have redirected")); var blogRequest = new BlogRequest("", "", new Uri("http://haacked.com/"), false, RequestLocation.Installation, "/"); var installManager = new Mock<IInstallationManager>(); installManager.Setup(i => i.InstallationActionRequired(It.IsAny<Version>(), null)).Throws(new InvalidOperationException()); // act bool handled = SubtextApplication.HandleRequestLocationException(new Exception(), blogRequest, installManager.Object, response.Object); // assert Assert.IsFalse(handled); } [Test] public void HandleRequestLocationException_IgnoresUpgradeLocation() { // arrange var response = new Mock<HttpResponseBase>(); response.Setup(r => r.Redirect(It.IsAny<string>(), true)).Throws( new Exception("Test Failed. Should not have redirected")); var blogRequest = new BlogRequest("", "", new Uri("http://haacked.com/"), false, RequestLocation.Upgrade, "/"); var installManager = new Mock<IInstallationManager>(); installManager.Setup(i => i.InstallationActionRequired(It.IsAny<Version>(), It.IsAny<Exception>())).Throws(new InvalidOperationException()); // act bool handled = SubtextApplication.HandleRequestLocationException(new Exception(), blogRequest, installManager.Object, response.Object); // assert Assert.IsFalse(handled); } [Test] public void HandleRequestLocationException_HandlesBlogInactiveException() { // arrange var exception = new BlogInactiveException(); var response = new Mock<HttpResponseBase>(); string redirectLocation = null; response.Setup(r => r.Redirect(It.IsAny<string>(), true)).Callback<string, bool>( (s, endRequest) => redirectLocation = s); var blogRequest = new BlogRequest("", "", new Uri("http://haacked.com/"), false); var installManager = new Mock<IInstallationManager>().Object; // act bool handled = SubtextApplication.HandleRequestLocationException(exception, blogRequest, installManager, response.Object); // assert Assert.AreEqual("~/SystemMessages/BlogNotActive.aspx", redirectLocation); Assert.IsTrue(handled); } [Test] public void HandleRequestLocationException_IgnoresBlogInactiveExceptionWhenInSystemMessagesDirectory() { // arrange var exception = new BlogInactiveException(); var response = new Mock<HttpResponseBase>(); response.Setup(r => r.Redirect(It.IsAny<string>(), true)).Throws(new Exception("Should not have redirected")); var blogRequest = new BlogRequest("", "", new Uri("http://haacked.com/"), false, RequestLocation.SystemMessages, "/"); var installManager = new Mock<IInstallationManager>().Object; // act bool handled = SubtextApplication.HandleRequestLocationException(exception, blogRequest, installManager, response.Object); // assert Assert.IsFalse(handled); } [Test] public void HandleBadConnectionStringException_WithInvalidOperationExceptionMentioningConnectionString_TransfersToBadConnectionStringPage () { // arrange var exception = new InvalidOperationException("No ConnectionString Found"); var server = new Mock<HttpServerUtilityBase>(); string transferLocation = null; server.Setup(s => s.Transfer(It.IsAny<string>())).Callback<string>(s => transferLocation = s); // act bool handled = SubtextApplication.HandleBadConnectionStringException(exception, server.Object); // assert Assert.IsTrue(handled); Assert.AreEqual("~/aspx/SystemMessages/CheckYourConnectionString.aspx", transferLocation); } [Test] public void HandleBadConnectionStringException_WithInvalidOperationExceptionContainingOtherMessages_IgnoresException() { // arrange var exception = new InvalidOperationException("Something or other"); var server = new Mock<HttpServerUtilityBase>(); server.Setup(s => s.Transfer(It.IsAny<string>())).Throws(new Exception("Should not have transfered")); // act bool handled = SubtextApplication.HandleBadConnectionStringException(exception, server.Object); // assert Assert.IsFalse(handled); } [Test] public void HandleBadConnectionStringException_WithArgumentExceptionContainingKeywordNotSupported_TransfersToBadConnectionStringPage () { // arrange var exception = new ArgumentException("Keyword not supported"); var server = new Mock<HttpServerUtilityBase>(); string transferLocation = null; server.Setup(s => s.Transfer(It.IsAny<string>())).Callback<string>(s => transferLocation = s); // act bool handled = SubtextApplication.HandleBadConnectionStringException(exception, server.Object); // assert Assert.IsTrue(handled); Assert.AreEqual("~/aspx/SystemMessages/CheckYourConnectionString.aspx", transferLocation); } [Test] public void HandleBadConnectionStringException_WithArgumentExceptionContainingInvalidValueForKey_TransfersToBadConnectionStringPage () { // arrange var exception = new ArgumentException("Invalid value for key"); var server = new Mock<HttpServerUtilityBase>(); string transferLocation = null; server.Setup(s => s.Transfer(It.IsAny<string>())).Callback<string>(s => transferLocation = s); // act bool handled = SubtextApplication.HandleBadConnectionStringException(exception, server.Object); // assert Assert.IsTrue(handled); Assert.AreEqual("~/aspx/SystemMessages/CheckYourConnectionString.aspx", transferLocation); } [Test] public void HandleBadConnectionStringException_WithArgumentExceptionContainingOtherMessages_IgnoresException() { // arrange var exception = new ArgumentException("Something or other"); var server = new Mock<HttpServerUtilityBase>(); server.Setup(s => s.Transfer(It.IsAny<string>())).Throws(new Exception("Should not have transfered")); // act bool handled = SubtextApplication.HandleBadConnectionStringException(exception, server.Object); // assert Assert.IsFalse(handled); } [Test] public void HandleBadConnectionStringException_IgnoresOtherExceptions() { // arrange var exception = new Exception(); var server = new Mock<HttpServerUtilityBase>(); server.Setup(s => s.Transfer(It.IsAny<string>())).Throws(new Exception("Should not have transfered")); // act bool handled = SubtextApplication.HandleBadConnectionStringException(exception, server.Object); // assert Assert.IsFalse(handled); } [SetUp] public void SetUp() { CleanupDirectories(); } [TearDown] public void TearDown() { CleanupDirectories(); File.Delete("login.aspx"); } private static void CleanupDirectories() { var directories = new[] {"Admin", "HostAdmin"}; Array.ForEach(directories, directory => { if(Directory.Exists(directory)) { Directory.Delete(directory, true); } }); } } }
// ZipHelperStream.cs // // Copyright 2006, 2007 John Reilly // // 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. // // Linking this library statically or dynamically with other modules is // making a combined work based on this library. Thus, the terms and // conditions of the GNU General Public License cover the whole // combination. // // As a special exception, the copyright holders of this library give you // permission to link this library with independent modules to produce an // executable, regardless of the license terms of these independent // modules, and to copy and distribute the resulting executable under // terms of your choice, provided that you also meet, for each linked // independent module, the terms and conditions of the license of that // module. An independent module is a module which is not derived from // or based on this library. If you modify this library, you may extend // this exception to your version of the library, but you are not // obligated to do so. If you do not wish to do so, delete this // exception statement from your version. using System; using System.IO; namespace ICSharpCode.SharpZipLib.Zip { /// <summary> /// Holds data pertinent to a data descriptor. /// </summary> public class DescriptorData { /// <summary> /// Get /set the compressed size of data. /// </summary> public long CompressedSize { get { return compressedSize; } set { compressedSize = value; } } /// <summary> /// Get / set the uncompressed size of data /// </summary> public long Size { get { return size; } set { size = value; } } /// <summary> /// Get /set the crc value. /// </summary> public long Crc { get { return crc; } set { crc = (value & 0xffffffff); } } #region Instance Fields long size; long compressedSize; long crc; #endregion } class EntryPatchData { public long SizePatchOffset { get { return sizePatchOffset_; } set { sizePatchOffset_ = value; } } public long CrcPatchOffset { get { return crcPatchOffset_; } set { crcPatchOffset_ = value; } } #region Instance Fields long sizePatchOffset_; long crcPatchOffset_; #endregion } /// <summary> /// This class assists with writing/reading from Zip files. /// </summary> internal class ZipHelperStream : Stream { #region Constructors /// <summary> /// Initialise an instance of this class. /// </summary> /// <param name="name">The name of the file to open.</param> public ZipHelperStream(string name) { stream_ = new FileStream(name, FileMode.Open, FileAccess.ReadWrite); isOwner_ = true; } /// <summary> /// Initialise a new instance of <see cref="ZipHelperStream"/>. /// </summary> /// <param name="stream">The stream to use.</param> public ZipHelperStream(Stream stream) { stream_ = stream; } #endregion /// <summary> /// Get / set a value indicating wether the the underlying stream is owned or not. /// </summary> /// <remarks>If the stream is owned it is closed when this instance is closed.</remarks> public bool IsStreamOwner { get { return isOwner_; } set { isOwner_ = value; } } #region Base Stream Methods public override bool CanRead { get { return stream_.CanRead; } } public override bool CanSeek { get { return stream_.CanSeek; } } #if !NET_1_0 && !NET_1_1 && !NETCF_1_0 public override bool CanTimeout { get { return stream_.CanTimeout; } } #endif public override long Length { get { return stream_.Length; } } public override long Position { get { return stream_.Position; } set { stream_.Position = value; } } public override bool CanWrite { get { return stream_.CanWrite; } } public override void Flush() { stream_.Flush(); } public override long Seek(long offset, SeekOrigin origin) { return stream_.Seek(offset, origin); } public override void SetLength(long value) { stream_.SetLength(value); } public override int Read(byte[] buffer, int offset, int count) { return stream_.Read(buffer, offset, count); } public override void Write(byte[] buffer, int offset, int count) { stream_.Write(buffer, offset, count); } /// <summary> /// Close the stream. /// </summary> /// <remarks> /// The underlying stream is closed only if <see cref="IsStreamOwner"/> is true. /// </remarks> override public void Close() { Stream toClose = stream_; stream_ = null; if (isOwner_ && (toClose != null)) { isOwner_ = false; toClose.Close(); } } #endregion // Write the local file header // TODO: ZipHelperStream.WriteLocalHeader is not yet used and needs checking for ZipFile and ZipOuptutStream usage void WriteLocalHeader(ZipEntry entry, EntryPatchData patchData) { CompressionMethod method = entry.CompressionMethod; bool headerInfoAvailable = true; // How to get this? bool patchEntryHeader = false; WriteLEInt(ZipConstants.LocalHeaderSignature); WriteLEShort(entry.Version); WriteLEShort(entry.Flags); WriteLEShort((byte)method); WriteLEInt((int)entry.DosTime); if (headerInfoAvailable == true) { WriteLEInt((int)entry.Crc); if ( entry.LocalHeaderRequiresZip64 ) { WriteLEInt(-1); WriteLEInt(-1); } else { WriteLEInt(entry.IsCrypted ? (int)entry.CompressedSize + ZipConstants.CryptoHeaderSize : (int)entry.CompressedSize); WriteLEInt((int)entry.Size); } } else { if (patchData != null) { patchData.CrcPatchOffset = stream_.Position; } WriteLEInt(0); // Crc if ( patchData != null ) { patchData.SizePatchOffset = stream_.Position; } // For local header both sizes appear in Zip64 Extended Information if ( entry.LocalHeaderRequiresZip64 && patchEntryHeader ) { WriteLEInt(-1); WriteLEInt(-1); } else { WriteLEInt(0); // Compressed size WriteLEInt(0); // Uncompressed size } } byte[] name = ZipConstants.ConvertToArray(entry.Flags, entry.Name); if (name.Length > 0xFFFF) { throw new ZipException("Entry name too long."); } ZipExtraData ed = new ZipExtraData(entry.ExtraData); if (entry.LocalHeaderRequiresZip64 && (headerInfoAvailable || patchEntryHeader)) { ed.StartNewEntry(); if (headerInfoAvailable) { ed.AddLeLong(entry.Size); ed.AddLeLong(entry.CompressedSize); } else { ed.AddLeLong(-1); ed.AddLeLong(-1); } ed.AddNewEntry(1); if ( !ed.Find(1) ) { throw new ZipException("Internal error cant find extra data"); } if ( patchData != null ) { patchData.SizePatchOffset = ed.CurrentReadIndex; } } else { ed.Delete(1); } byte[] extra = ed.GetEntryData(); WriteLEShort(name.Length); WriteLEShort(extra.Length); if ( name.Length > 0 ) { stream_.Write(name, 0, name.Length); } if ( entry.LocalHeaderRequiresZip64 && patchEntryHeader ) { patchData.SizePatchOffset += stream_.Position; } if ( extra.Length > 0 ) { stream_.Write(extra, 0, extra.Length); } } /// <summary> /// Locates a block with the desired <paramref name="signature"/>. /// </summary> /// <param name="signature">The signature to find.</param> /// <param name="endLocation">Location, marking the end of block.</param> /// <param name="minimumBlockSize">Minimum size of the block.</param> /// <param name="maximumVariableData">The maximum variable data.</param> /// <returns>Eeturns the offset of the first byte after the signature; -1 if not found</returns> public long LocateBlockWithSignature(int signature, long endLocation, int minimumBlockSize, int maximumVariableData) { long pos = endLocation - minimumBlockSize; if ( pos < 0 ) { return -1; } long giveUpMarker = Math.Max(pos - maximumVariableData, 0); // TODO: This loop could be optimised for speed. do { if ( pos < giveUpMarker ) { return -1; } Seek(pos--, SeekOrigin.Begin); } while ( ReadLEInt() != signature ); return Position; } /// <summary> /// Write Zip64 end of central directory records (File header and locator). /// </summary> /// <param name="noOfEntries">The number of entries in the central directory.</param> /// <param name="sizeEntries">The size of entries in the central directory.</param> /// <param name="centralDirOffset">The offset of the dentral directory.</param> public void WriteZip64EndOfCentralDirectory(long noOfEntries, long sizeEntries, long centralDirOffset) { long centralSignatureOffset = stream_.Position; WriteLEInt(ZipConstants.Zip64CentralFileHeaderSignature); WriteLELong(44); // Size of this record (total size of remaining fields in header or full size - 12) WriteLEShort(ZipConstants.VersionMadeBy); // Version made by WriteLEShort(ZipConstants.VersionZip64); // Version to extract WriteLEInt(0); // Number of this disk WriteLEInt(0); // number of the disk with the start of the central directory WriteLELong(noOfEntries); // No of entries on this disk WriteLELong(noOfEntries); // Total No of entries in central directory WriteLELong(sizeEntries); // Size of the central directory WriteLELong(centralDirOffset); // offset of start of central directory // zip64 extensible data sector not catered for here (variable size) // Write the Zip64 end of central directory locator WriteLEInt(ZipConstants.Zip64CentralDirLocatorSignature); // no of the disk with the start of the zip64 end of central directory WriteLEInt(0); // relative offset of the zip64 end of central directory record WriteLELong(centralSignatureOffset); // total number of disks WriteLEInt(1); } /// <summary> /// Write the required records to end the central directory. /// </summary> /// <param name="noOfEntries">The number of entries in the directory.</param> /// <param name="sizeEntries">The size of the entries in the directory.</param> /// <param name="startOfCentralDirectory">The start of the central directory.</param> /// <param name="comment">The archive comment. (This can be null).</param> public void WriteEndOfCentralDirectory(long noOfEntries, long sizeEntries, long startOfCentralDirectory, byte[] comment) { if ( (noOfEntries >= 0xffff) || (startOfCentralDirectory >= 0xffffffff) || (sizeEntries >= 0xffffffff) ) { WriteZip64EndOfCentralDirectory(noOfEntries, sizeEntries, startOfCentralDirectory); } WriteLEInt(ZipConstants.EndOfCentralDirectorySignature); // TODO: ZipFile Multi disk handling not done WriteLEShort(0); // number of this disk WriteLEShort(0); // no of disk with start of central dir // Number of entries if ( noOfEntries >= 0xffff ) { WriteLEUshort(0xffff); // Zip64 marker WriteLEUshort(0xffff); } else { WriteLEShort(( short )noOfEntries); // entries in central dir for this disk WriteLEShort(( short )noOfEntries); // total entries in central directory } // Size of the central directory if ( sizeEntries >= 0xffffffff ) { WriteLEUint(0xffffffff); // Zip64 marker } else { WriteLEInt(( int )sizeEntries); } // offset of start of central directory if ( startOfCentralDirectory >= 0xffffffff ) { WriteLEUint(0xffffffff); // Zip64 marker } else { WriteLEInt(( int )startOfCentralDirectory); } int commentLength = (comment != null) ? comment.Length : 0; if ( commentLength > 0xffff ) { throw new ZipException(string.Format("Comment length({0}) is too long can only be 64K", commentLength)); } WriteLEShort(commentLength); if ( commentLength > 0 ) { Write(comment, 0, comment.Length); } } #region LE value reading/writing /// <summary> /// Read an unsigned short in little endian byte order. /// </summary> /// <returns>Returns the value read.</returns> /// <exception cref="IOException"> /// An i/o error occurs. /// </exception> /// <exception cref="EndOfStreamException"> /// The file ends prematurely /// </exception> public int ReadLEShort() { int byteValue1 = stream_.ReadByte(); if (byteValue1 < 0) { throw new EndOfStreamException(); } int byteValue2 = stream_.ReadByte(); if (byteValue2 < 0) { throw new EndOfStreamException(); } return byteValue1 | (byteValue2 << 8); } /// <summary> /// Read an int in little endian byte order. /// </summary> /// <returns>Returns the value read.</returns> /// <exception cref="IOException"> /// An i/o error occurs. /// </exception> /// <exception cref="System.IO.EndOfStreamException"> /// The file ends prematurely /// </exception> public int ReadLEInt() { return ReadLEShort() | (ReadLEShort() << 16); } /// <summary> /// Read a long in little endian byte order. /// </summary> /// <returns>The value read.</returns> public long ReadLELong() { return (uint)ReadLEInt() | ((long)ReadLEInt() << 32); } /// <summary> /// Write an unsigned short in little endian byte order. /// </summary> /// <param name="value">The value to write.</param> public void WriteLEShort(int value) { stream_.WriteByte(( byte )(value & 0xff)); stream_.WriteByte(( byte )((value >> 8) & 0xff)); } /// <summary> /// Write a ushort in little endian byte order. /// </summary> /// <param name="value">The value to write.</param> public void WriteLEUshort(ushort value) { stream_.WriteByte(( byte )(value & 0xff)); stream_.WriteByte(( byte )(value >> 8)); } /// <summary> /// Write an int in little endian byte order. /// </summary> /// <param name="value">The value to write.</param> public void WriteLEInt(int value) { WriteLEShort(value); WriteLEShort(value >> 16); } /// <summary> /// Write a uint in little endian byte order. /// </summary> /// <param name="value">The value to write.</param> public void WriteLEUint(uint value) { WriteLEUshort(( ushort )(value & 0xffff)); WriteLEUshort(( ushort )(value >> 16)); } /// <summary> /// Write a long in little endian byte order. /// </summary> /// <param name="value">The value to write.</param> public void WriteLELong(long value) { WriteLEInt(( int )value); WriteLEInt(( int )(value >> 32)); } /// <summary> /// Write a ulong in little endian byte order. /// </summary> /// <param name="value">The value to write.</param> public void WriteLEUlong(ulong value) { WriteLEUint(( uint )(value & 0xffffffff)); WriteLEUint(( uint )(value >> 32)); } #endregion /// <summary> /// Write a data descriptor. /// </summary> /// <param name="entry">The entry to write a descriptor for.</param> /// <returns>Returns the number of descriptor bytes written.</returns> public int WriteDataDescriptor(ZipEntry entry) { if (entry == null) { throw new ArgumentNullException("entry"); } int result=0; // Add data descriptor if flagged as required if ((entry.Flags & (int)GeneralBitFlags.Descriptor) != 0) { // The signature is not PKZIP originally but is now described as optional // in the PKZIP Appnote documenting trhe format. WriteLEInt(ZipConstants.DataDescriptorSignature); WriteLEInt(unchecked((int)(entry.Crc))); result+=8; if (entry.LocalHeaderRequiresZip64) { WriteLELong(entry.CompressedSize); WriteLELong(entry.Size); result+=16; } else { WriteLEInt((int)entry.CompressedSize); WriteLEInt((int)entry.Size); result+=8; } } return result; } /// <summary> /// Read data descriptor at the end of compressed data. /// </summary> /// <param name="zip64">if set to <c>true</c> [zip64].</param> /// <param name="data">The data to fill in.</param> /// <returns>Returns the number of bytes read in the descriptor.</returns> public void ReadDataDescriptor(bool zip64, DescriptorData data) { int intValue = ReadLEInt(); // In theory this may not be a descriptor according to PKZIP appnote. // In practise its always there. if (intValue != ZipConstants.DataDescriptorSignature) { throw new ZipException("Data descriptor signature not found"); } data.Crc = ReadLEInt(); if (zip64) { data.CompressedSize = ReadLELong(); data.Size = ReadLELong(); } else { data.CompressedSize = ReadLEInt(); data.Size = ReadLEInt(); } } #region Instance Fields bool isOwner_; Stream stream_; #endregion } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. namespace Microsoft.Azure.Management.TrafficManager.Fluent { using TrafficManagerProfile.Update; using TrafficManagerProfile.Definition; using System.Collections.Generic; using System.Threading; using System.Linq; using System.Threading.Tasks; using ResourceManager.Fluent; using Models; /// <summary> /// Implementation for TrafficManagerProfile. /// </summary> ///GENTHASH:Y29tLm1pY3Jvc29mdC5henVyZS5tYW5hZ2VtZW50LnRyYWZmaWNtYW5hZ2VyLmltcGxlbWVudGF0aW9uLlRyYWZmaWNNYW5hZ2VyUHJvZmlsZUltcGw= internal partial class TrafficManagerProfileImpl : GroupableResource<ITrafficManagerProfile, ProfileInner, TrafficManagerProfileImpl, ITrafficManager, TrafficManagerProfile.Definition.IWithLeafDomainLabel, TrafficManagerProfile.Definition.IWithLeafDomainLabel, TrafficManagerProfile.Definition.IWithCreate, TrafficManagerProfile.Update.IUpdate>, ITrafficManagerProfile, IDefinition, IUpdate { private const string profileStatusDisabled = "Disabled"; private const string profileStatusEnabled = "Enabled"; private TrafficManagerEndpointsImpl endpoints; ///GENMHASH:C5CC2EE74F2176AA6473857322F7C248:4D37314EF7F75B745F5D65EF257C1402 internal TrafficManagerProfileImpl(string name, ProfileInner innerModel, ITrafficManager trafficManager) : base(name, innerModel, trafficManager) { endpoints = new TrafficManagerEndpointsImpl(this); } ///GENMHASH:C7D63CAAB4D5C78DCBABA455FA741326:50737CF16CD493FD8BB7A09EF461690C public string MonitoringPath() { return Inner.MonitorConfig.Path; } ///GENMHASH:6C28BB464B795DC8681442F876749A3D:57455B1D83CC1849A88FF401A87B3652 public IReadOnlyDictionary<string, ITrafficManagerExternalEndpoint> ExternalEndpoints() { return this.endpoints.ExternalEndpointsAsMap(); } ///GENMHASH:0C153B8A8223F6B3602B8C639E43B1A2:4B04E200B529E471D39F93CEBC5617FA public IReadOnlyDictionary<string, ITrafficManagerNestedProfileEndpoint> NestedProfileEndpoints() { return this.endpoints.NestedProfileEndpointsAsMap(); } ///GENMHASH:C6A6B547BAC20098D634B85B4700816E:68BB0F621666DC65A06B08FC37AF8535 public TrafficManagerProfileImpl WithWeightBasedRouting() { this.WithTrafficRoutingMethod(Microsoft.Azure.Management.TrafficManager.Fluent.TrafficRoutingMethod.Weighted); return this; } ///GENMHASH:BA29DA1F2009E6120D5974787A4DCC48:A743B4E1DEB81D6E9C28A26880134BF6 public TrafficManagerProfileImpl WithGeographicBasedRouting() { return this.WithTrafficRoutingMethod((Microsoft.Azure.Management.TrafficManager.Fluent.TrafficRoutingMethod.Geographic)); } public TrafficManagerProfileImpl WithMultiValueBasedRouting(int maxReturn = 2) { this.Inner.MaxReturn = maxReturn; return this.WithTrafficRoutingMethod((Microsoft.Azure.Management.TrafficManager.Fluent.TrafficRoutingMethod.MultiValue)); } public TrafficManagerProfileImpl WithSubnetBasedRouting() { return this.WithTrafficRoutingMethod((Microsoft.Azure.Management.TrafficManager.Fluent.TrafficRoutingMethod.Subnet)); } ///GENMHASH:B4A36FDF16CFB0AB15EF06C3C41DEAE6:3907B35E8FE4F9DF1790E670E5612AA5 public TrafficManagerEndpointImpl DefineExternalTargetEndpoint(string name) { return this.endpoints.DefineExteralTargetEndpoint(name); } ///GENMHASH:4FD71958F542A872CEE597B1CEA332F8:CD2E0F8F28E49A3BD6482AFD85AFF2C1 public TrafficManagerProfileImpl WithLeafDomainLabel(string dnsLabel) { Inner.DnsConfig.RelativeName = dnsLabel; return this; } ///GENMHASH:2C0DB6B1F104247169DC6BCC9246747C:D88E948223FB86124BBB6F6774621201 public int TimeToLive() { return (int)Inner.DnsConfig.Ttl.Value; } ///GENMHASH:5E218AF13EC4B07DD7170E0991E64373:B45FF059EA30EB01427BCCB27086FEBF public TrafficManagerEndpointImpl DefineNestedTargetEndpoint(string name) { return this.endpoints.DefineNestedProfileTargetEndpoint(name); } ///GENMHASH:9AEC42BC2F36531F5A364F6C9BC7299B:06AEBFC10FD1E07B85CFFC68257D1C3A public TrafficManagerProfileImpl WithProfileStatusEnabled() { Inner.ProfileStatus = TrafficManagerProfileImpl.profileStatusEnabled; return this; } ///GENMHASH:507A92D4DCD93CE9595A78198DEBDFCF:322DFB55FFECEA782B6CC4759AD25BD4 private async Task<ITrafficManagerProfile> UpdateResourceAsync(CancellationToken cancellationToken = default(CancellationToken)) { // In update we first commit the endpoints then update profile, the reason is through portal and direct API // call one can create endpoints without properties those are not applicable for the profile's current routing // method. We cannot update the routing method of the profile until existing endpoints contains the properties // required for the new routing method. var updatedEndpoints = await endpoints.CommitAndGetAllAsync(cancellationToken); Inner.Endpoints = endpoints.AllEndpointsInners(); ProfileInner profileInner = await Manager.Inner.Profiles.CreateOrUpdateAsync(ResourceGroupName, Name, Inner, cancellationToken); SetInner(profileInner); return this; } ///GENMHASH:0202A00A1DCF248D2647DBDBEF2CA865:44175AF0C87DAFA56DB9009ABE7645E4 public async override Task<ITrafficManagerProfile> CreateResourceAsync(CancellationToken cancellationToken = default(CancellationToken)) { if (IsInCreateMode) { ProfileInner profileInner = await Manager.Inner.Profiles.CreateOrUpdateAsync(ResourceGroupName, Name, Inner, cancellationToken); SetInner(profileInner); await endpoints.CommitAndGetAllAsync(cancellationToken); return this; } else { return await UpdateResourceAsync(cancellationToken); } } ///GENMHASH:655A859AB9D888489CDFDD334146F9D1:176F10BD0111531F78393D5651ABF7C5 public TrafficManagerProfileImpl WithProfileStatusDisabled() { Inner.ProfileStatus = profileStatusDisabled; return this; } ///GENMHASH:655A58D21C12B40631EB483D86D298A3:D63D64FAE4C0512A29775948289CD9AF public TrafficManagerEndpointImpl UpdateAzureTargetEndpoint(string name) { return this.endpoints.UpdateAzureEndpoint(name); } ///GENMHASH:46B51A2A6E317FB877781A1B0B0CE163:1999508BD6CE91CA6BAF0C5AEC85B294 public TrafficManagerProfileImpl WithoutEndpoint(string name) { this.endpoints.Remove(name); return this; } ///GENMHASH:3E133DCD07354DCF10F28C2FA07E1C8C:59E6C148DC851CD612F81A3DF8325AAF public IReadOnlyDictionary<string, ITrafficManagerAzureEndpoint> AzureEndpoints() { return this.endpoints.AzureEndpointsAsMap(); } ///GENMHASH:577F8437932AEC6E08E1A137969BDB4A:93FB31E2F199B29EB12AF1D037A21B91 public string Fqdn() { return Inner.DnsConfig.Fqdn; } ///GENMHASH:CBED4DBEF4FE611072BC440D90324271:80930CC778C5ED77B07A0B587D7C5950 public int MonitoringPort() { return (int)Inner.MonitorConfig.Port.Value; } ///GENMHASH:C69FFBA25D969C2C45775433EBFD49EA:01BC02A541C8C945111AEC0AF9DB6FF1 public TrafficManagerProfileImpl WithPriorityBasedRouting() { this.WithTrafficRoutingMethod(Fluent.TrafficRoutingMethod.Priority); return this; } ///GENMHASH:4002186478A1CB0B59732EBFB18DEB3A:280DEDDFDA82FD8E8EA83F4139D8C99A public override async Task<ITrafficManagerProfile> RefreshAsync(CancellationToken cancellationToken = default(CancellationToken)) { ProfileInner inner = await GetInnerAsync(cancellationToken); SetInner(inner); endpoints.Refresh(); return this; } protected override async Task<ProfileInner> GetInnerAsync(CancellationToken cancellationToken) { return await Manager.Inner.Profiles.GetAsync( ResourceGroupName, Name, cancellationToken: cancellationToken); } ///GENMHASH:4AF52DA6D7309E03BCF9F21C532F19E0:DEF2407DA0E866749EF9CC5952427470 public TrafficManagerProfileImpl WithPerformanceBasedRouting() { WithTrafficRoutingMethod(Fluent.TrafficRoutingMethod.Performance); return this; } ///GENMHASH:1306B0380955C0A661257F568E407491:91614D0A65D7DE56C3E04201D6614324 public TrafficManagerEndpointImpl UpdateExternalTargetEndpoint(string name) { return this.endpoints.UpdateExternalEndpoint(name); } ///GENMHASH:CF5737257DFBF1F0FB9DD7771AF4A4DD:6522777576C2DD8F098342824404B3E5 internal TrafficManagerProfileImpl WithEndpoint(TrafficManagerEndpointImpl endpoint) { this.endpoints.AddEndpoint(endpoint); return this; } ///GENMHASH:AA50DC9DCA33186877C0E55612409D74:DB63F33DBE42C3412FD84412DA6DF98C public TrafficManagerProfileImpl WithHttpMonitoring() { return this.WithHttpMonitoring(80, "/"); } ///GENMHASH:088F115956764D909356F941714DD214:72C3991B01AC2306292D697D6CB9A5EE public TrafficManagerProfileImpl WithHttpMonitoring(int port, string path) { Inner.MonitorConfig.Port = port; Inner.MonitorConfig.Path = path; Inner.MonitorConfig.Protocol = "http"; return this; } ///GENMHASH:C7D52FF3F5A2A28882BA7713BB288475:193FB4C1B236385E2ED537BCBD77E6D0 public TrafficManagerProfileImpl WithHttpsMonitoring() { return this.WithHttpsMonitoring(443, "/"); } ///GENMHASH:339D7124F9EE53875E3B1321B2E2D9FD:A28860E9058E7040BCE32AA17CDB136B public TrafficManagerProfileImpl WithHttpsMonitoring(int port, string path) { Inner.MonitorConfig.Port = port; Inner.MonitorConfig.Path = path; Inner.MonitorConfig.Protocol = "https"; return this; } ///GENMHASH:E75269B73212138A7E1E8F94A2FD913C:AD931D14F514F37D5342A16ACD3342B3 public TrafficManagerProfileImpl WithTimeToLive(int ttlInSeconds) { Inner.DnsConfig.Ttl = ttlInSeconds; return this; } ///GENMHASH:4E79F831CA615F31A3B9091C9216E524:1135A0CCE498B0EFFC0343DDE3CEB9BF public string DnsLabel() { return Inner.DnsConfig.RelativeName; } ///GENMHASH:3F2076D33F84FDFAB700A1F0C8C41647:8E2768B25039756DEB5365F724C21484 public bool IsEnabled() { return Inner.ProfileStatus.Equals(TrafficManagerProfileImpl.profileStatusEnabled, System.StringComparison.OrdinalIgnoreCase); } ///GENMHASH:BB0D1050B0185C55C13B3722F9DC8EFD:954997B5F0A4C3371FBFA90DB6C24AC3 public TrafficManagerProfileImpl WithTrafficRoutingMethod(TrafficRoutingMethod routingMethod) { Inner.TrafficRoutingMethod = routingMethod.ToString(); return this; } ///GENMHASH:C4319084EC81C9B9397CE86527D1A3CE:17F4836836395BFB8393F702736B5F31 public TrafficRoutingMethod TrafficRoutingMethod() { return Fluent.TrafficRoutingMethod.Parse(Inner.TrafficRoutingMethod); } ///GENMHASH:2BE295DCD7E2E4E353B535754D34B1FF:0B13B9735DB0972678CCB2C7544FA3F9 public ProfileMonitorStatus MonitorStatus() { if (Inner.MonitorConfig != null) { return ProfileMonitorStatus.Parse(Inner.MonitorConfig.ProfileMonitorStatus); } else { return null; } } ///GENMHASH:A912B64DAA5D27988A4E605BC2374EEA:EDA05BB34633EA106E7F50083F9059DD public TrafficManagerEndpointImpl DefineAzureTargetEndpoint(string name) { return this.endpoints.DefineAzureTargetEndpoint(name); } ///GENMHASH:3D482C7836B7C641301B728A17656970:426E2267E364721B07885A7317332651 public TrafficManagerEndpointImpl UpdateNestedProfileTargetEndpoint(string name) { return this.endpoints.UpdateNestedProfileEndpoint(name); } } }
/* * 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 System.Reflection; using QuantConnect.Data; using QuantConnect.Interfaces; using QuantConnect.Orders; using QuantConnect.Securities; namespace QuantConnect.Algorithm.CSharp { /// <summary> /// This regression algorithm tests Out of The Money (OTM) future option expiry for puts. /// We expect 2 orders from the algorithm, which are: /// /// * Initial entry, buy ES Put Option (expiring OTM) /// - contract expires worthless, not exercised, so never opened a position in the underlying /// /// * Liquidation of worthless ES Put OTM contract /// /// Additionally, we test delistings for future options and assert that our /// portfolio holdings reflect the orders the algorithm has submitted. /// </summary> /// <remarks> /// Total Trades in regression algorithm should be 1, but expiration is counted as a trade. /// </remarks> public class FutureOptionPutOTMExpiryRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition { private Symbol _es19m20; private Symbol _esOption; private Symbol _expectedContract; public override void Initialize() { SetStartDate(2020, 1, 5); SetEndDate(2020, 6, 30); _es19m20 = AddFutureContract( QuantConnect.Symbol.CreateFuture( Futures.Indices.SP500EMini, Market.CME, new DateTime(2020, 6, 19)), Resolution.Minute).Symbol; // Select a future option expiring ITM, and adds it to the algorithm. _esOption = AddFutureOptionContract(OptionChainProvider.GetOptionContractList(_es19m20, Time) .Where(x => x.ID.StrikePrice <= 3150m && x.ID.OptionRight == OptionRight.Put) .OrderByDescending(x => x.ID.StrikePrice) .Take(1) .Single(), Resolution.Minute).Symbol; _expectedContract = QuantConnect.Symbol.CreateOption(_es19m20, Market.CME, OptionStyle.American, OptionRight.Put, 3150m, new DateTime(2020, 6, 19)); if (_esOption != _expectedContract) { throw new Exception($"Contract {_expectedContract} was not found in the chain"); } Schedule.On(DateRules.Tomorrow, TimeRules.AfterMarketOpen(_es19m20, 1), () => { MarketOrder(_esOption, 1); }); } public override void OnData(Slice data) { // Assert delistings, so that we can make sure that we receive the delisting warnings at // the expected time. These assertions detect bug #4872 foreach (var delisting in data.Delistings.Values) { if (delisting.Type == DelistingType.Warning) { if (delisting.Time != new DateTime(2020, 6, 19)) { throw new Exception($"Delisting warning issued at unexpected date: {delisting.Time}"); } } if (delisting.Type == DelistingType.Delisted) { if (delisting.Time != new DateTime(2020, 6, 20)) { throw new Exception($"Delisting happened at unexpected date: {delisting.Time}"); } } } } public override void OnOrderEvent(OrderEvent orderEvent) { if (orderEvent.Status != OrderStatus.Filled) { // There's lots of noise with OnOrderEvent, but we're only interested in fills. return; } if (!Securities.ContainsKey(orderEvent.Symbol)) { throw new Exception($"Order event Symbol not found in Securities collection: {orderEvent.Symbol}"); } var security = Securities[orderEvent.Symbol]; if (security.Symbol == _es19m20) { throw new Exception("Invalid state: did not expect a position for the underlying to be opened, since this contract expires OTM"); } if (security.Symbol == _expectedContract) { AssertFutureOptionContractOrder(orderEvent, security); } else { throw new Exception($"Received order event for unknown Symbol: {orderEvent.Symbol}"); } Log($"{orderEvent}"); } private void AssertFutureOptionContractOrder(OrderEvent orderEvent, Security option) { if (orderEvent.Direction == OrderDirection.Buy && option.Holdings.Quantity != 1) { throw new Exception($"No holdings were created for option contract {option.Symbol}"); } if (orderEvent.Direction == OrderDirection.Sell && option.Holdings.Quantity != 0) { throw new Exception("Holdings were found after a filled option exercise"); } if (orderEvent.Direction == OrderDirection.Sell && !orderEvent.Message.Contains("OTM")) { throw new Exception("Contract did not expire OTM"); } if (orderEvent.Message.Contains("Exercise")) { throw new Exception("Exercised option, even though it expires OTM"); } } /// <summary> /// Ran at the end of the algorithm to ensure the algorithm has no holdings /// </summary> /// <exception cref="Exception">The algorithm has holdings</exception> public override void OnEndOfAlgorithm() { if (Portfolio.Invested) { throw new Exception($"Expected no holdings at end of algorithm, but are invested in: {string.Join(", ", Portfolio.Keys)}"); } } /// <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", "2"}, {"Average Win", "0%"}, {"Average Loss", "-5.11%"}, {"Compounding Annual Return", "-10.226%"}, {"Drawdown", "5.100%"}, {"Expectancy", "-1"}, {"Net Profit", "-5.114%"}, {"Sharpe Ratio", "-1.164"}, {"Probabilistic Sharpe Ratio", "0.009%"}, {"Loss Rate", "100%"}, {"Win Rate", "0%"}, {"Profit-Loss Ratio", "0"}, {"Alpha", "-0.07"}, {"Beta", "0.003"}, {"Annual Standard Deviation", "0.06"}, {"Annual Variance", "0.004"}, {"Information Ratio", "-0.243"}, {"Tracking Error", "0.378"}, {"Treynor Ratio", "-23.284"}, {"Total Fees", "$1.85"}, {"Estimated Strategy Capacity", "$360000000.00"}, {"Lowest Capacity Asset", "ES 31EL5FBZBMXES|ES XFH59UK0MYO1"}, {"Fitness Score", "0"}, {"Kelly Criterion Estimate", "0"}, {"Kelly Criterion Probability Value", "0"}, {"Sortino Ratio", "-0.182"}, {"Return Over Maximum Drawdown", "-2.002"}, {"Portfolio Turnover", "0"}, {"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", "ec799886c15ac6c4b8fb3d873d7e6b14"} }; } }
using System; using DevExpress.Mvvm.Native; using NUnit.Framework; namespace DevExpress.Mvvm.Tests { [TestFixture] public class ExpressionHelperTests { public class TestViewModel : BindableBase { string stringProperty; public string StringProperty { get { return stringProperty; } set { SetProperty(ref stringProperty, value, () => StringProperty); } } string stringProperty2; public string StringProperty2 { get { return stringProperty2; } set { SetProperty(ref stringProperty2, value, () => StringProperty2); } } NestedTestViewModel nestedViewModel; public NestedTestViewModel NestedViewModel { get { return nestedViewModel; } set { SetProperty(ref nestedViewModel, value, () => NestedViewModel); } } public int TestCommandExecuteCount { get; private set; } public object ExecuteParameter { get; private set; } public object CanExecuteParameter { get; private set; } public bool CanExecuteTestCommand { get; set; } DelegateCommand<object> testCommand; public DelegateCommand<object> TestCommand { get { if(testCommand == null) { testCommand = new DelegateCommand<object>(o => { ExecuteParameter = o; TestCommandExecuteCount++; }, o => { CanExecuteParameter = o; return CanExecuteTestCommand; }); } return testCommand; } } int intProperty; public int IntProperty { get { return intProperty; } set { SetProperty(ref intProperty, value, () => IntProperty); } } double doubleProperty; public double DoubleProperty { get { return doubleProperty; } set { SetProperty(ref doubleProperty, value, () => DoubleProperty); } } public TestViewModel() { CanExecuteTestCommand = true; } public void SomeMethod() { } public void SomeMethod(int x) { } public string SomeMethod2() { return null; } public int someField; } public class NestedTestViewModel : BindableBase { string nestedStringProperty; public string NestedStringProperty { get { return nestedStringProperty; } set { SetProperty(ref nestedStringProperty, value, () => NestedStringProperty); } } } public int MyProperty { get; set; } public int GetInt() { return 0; } [Test] public void GetPropertyName() { Assert.AreEqual("MyProperty", ExpressionHelper.GetPropertyName(() => MyProperty)); TestHelper.AssertThrows<ArgumentException>(() => { ExpressionHelper.GetPropertyName(() => GetInt()); }); TestHelper.AssertThrows<ArgumentNullException>(() => { ExpressionHelper.GetPropertyName<int>(null); }); TestViewModel viewModel = null; Assert.AreEqual("StringProperty", ExpressionHelper.GetPropertyName(() => viewModel.StringProperty)); TestHelper.AssertThrows<ArgumentException>(() => { ExpressionHelper.GetPropertyName(() => viewModel.NestedViewModel.NestedStringProperty); }); Assert.AreEqual("StringProperty", ExpressionHelper.GetPropertyName<object>(() => viewModel.StringProperty)); Assert.AreEqual("IntProperty", ExpressionHelper.GetPropertyName<object>(() => viewModel.IntProperty)); } [Test] public void GetPropertyName2() { Assert.AreEqual("MyProperty", ExpressionHelper.GetPropertyName((ExpressionHelperTests x) => x.MyProperty)); TestHelper.AssertThrows<ArgumentException>(() => { ExpressionHelper.GetPropertyName((ExpressionHelperTests x) => x.GetInt()); }); TestHelper.AssertThrows<ArgumentNullException>(() => { ExpressionHelper.GetPropertyName<ExpressionHelperTests, int>(null); }); Assert.AreEqual("StringProperty", ExpressionHelper.GetPropertyName((TestViewModel x) => x.StringProperty)); TestHelper.AssertThrows<ArgumentException>(() => { ExpressionHelper.GetPropertyName((TestViewModel x) => x.NestedViewModel.NestedStringProperty); }); Assert.AreEqual("StringProperty", ExpressionHelper.GetPropertyName<TestViewModel, object>(x => x.StringProperty)); Assert.AreEqual("IntProperty", ExpressionHelper.GetPropertyName<TestViewModel, object>(x => x.IntProperty)); Assert.AreEqual(System.ComponentModel.TypeDescriptor.GetProperties(this)["MyProperty"], ExpressionHelper.GetProperty((ExpressionHelperTests x) => x.MyProperty)); } [Test] public void GetMemberInfo() { Assert.AreEqual("SomeMethod", ExpressionHelper.GetMethodName(() => SomeMethod())); } void SomeMethod() { } string SomeMethod2() { return null; } [Test] public void GetArgumentMethodStrict() { Assert.AreEqual("SomeMethod", ExpressionHelper.GetArgumentMethodStrict<TestViewModel>(x => x.SomeMethod()).Name); Assert.AreEqual("SomeMethod", ExpressionHelper.GetArgumentMethodStrict<TestViewModel>(x => x.SomeMethod(default(int))).Name); TestHelper.AssertThrows<ArgumentException>(() => ExpressionHelper.GetArgumentMethodStrict<ExpressionHelperTests>(x => SomeMethod())); TestHelper.AssertThrows<ArgumentException>(() => ExpressionHelper.GetArgumentMethodStrict<TestViewModel>(x => x.StringProperty2.ToString())); string s = null; TestHelper.AssertThrows<ArgumentException>(() => ExpressionHelper.GetArgumentMethodStrict<TestViewModel>(x => s.ToString())); } [Test] public void GetFunctionMethodStrict() { Assert.AreEqual("SomeMethod2", ExpressionHelper.GetArgumentFunctionStrict<TestViewModel, string>(x => x.SomeMethod2()).Name); TestHelper.AssertThrows<ArgumentException>(() => ExpressionHelper.GetArgumentFunctionStrict<ExpressionHelperTests, string>(x => SomeMethod2())); } [Test] public void GetArgumentPropertyStrict() { Assert.AreEqual("IntProperty", ExpressionHelper.GetArgumentPropertyStrict<TestViewModel, int>(x => x.IntProperty).Name); TestHelper.AssertThrows<InvalidCastException>(() => ExpressionHelper.GetArgumentPropertyStrict<TestViewModel, int>(x => x.someField)); TestHelper.AssertThrows<ArgumentException>(() => ExpressionHelper.GetArgumentPropertyStrict<ExpressionHelperTests, int>(x => MyProperty)); TestHelper.AssertThrows<ArgumentException>(() => ExpressionHelper.GetArgumentPropertyStrict<TestViewModel, int>(x => x.SomeMethod2().Length)); string s = null; TestHelper.AssertThrows<ArgumentException>(() => ExpressionHelper.GetArgumentPropertyStrict<TestViewModel, int>(x => s.Length)); } public interface ISomeInterface { string Title { get; set; } } public class PublicClass : ISomeInterface { public int TitleCalledTimes = 0; public string Title { get { TitleCalledTimes++; return null; } set { } } } public class PublicClassWithExplicitImplementation : ISomeInterface { public int TitleCalledTimes = 0; public string Title { get { TitleCalledTimes++; return null; } set { } } string ISomeInterface.Title { get { TitleCalledTimes++; return null; } set { } } } class PrivateClass : ISomeInterface { public int TitleCalledTimes = 0; public string Title { get { TitleCalledTimes++; return null; } set { } } } [Test] public void PropertyHasImplicitImplementationTest() { Assert.IsTrue(ExpressionHelper.PropertyHasImplicitImplementation((ISomeInterface)new PublicClass(), i => i.Title)); Assert.IsFalse(ExpressionHelper.PropertyHasImplicitImplementation((ISomeInterface)new PublicClassWithExplicitImplementation(), i => i.Title)); Assert.IsTrue(ExpressionHelper.PropertyHasImplicitImplementation((ISomeInterface)new PrivateClass(), i => i.Title)); } [Test] public void PropertyHasImplicitImplementationTest2() { ISomeInterface obj; Assert.IsTrue(ExpressionHelper.PropertyHasImplicitImplementation(obj = (ISomeInterface)new PublicClass(), i => i.Title, false)); Assert.AreEqual(0, ((PublicClass)obj).TitleCalledTimes); Assert.IsFalse(ExpressionHelper.PropertyHasImplicitImplementation(obj = (ISomeInterface)new PublicClassWithExplicitImplementation(), i => i.Title, false)); Assert.AreEqual(0, ((PublicClassWithExplicitImplementation)obj).TitleCalledTimes); Assert.IsTrue(ExpressionHelper.PropertyHasImplicitImplementation(obj = (ISomeInterface)new PrivateClass(), i => i.Title, false)); Assert.AreEqual(0, ((PrivateClass)obj).TitleCalledTimes); } } public static class TestHelper { public static void AssertThrows<TException>(Action action) where TException : Exception { try { action(); } catch(TException) { return; } Assert.Fail(); } } }
// Copyright (C) by Housemarque, Inc. namespace Hopac { using System; using System.Runtime.CompilerServices; using Microsoft.FSharp.Core; using Hopac.Core; /// <summary>Represents a first class synchronous operation.</summary> public abstract class Alt<T> : Job<T> { internal abstract void TryAlt(ref Worker wr, int i, Cont<T> xK, Else xE); } namespace Core { /// public abstract class AltAfter<X, Y> : Alt<Y> { internal Alt<X> xA; /// [MethodImpl(AggressiveInlining.Flag)] public Alt<Y> InternalInit(Alt<X> xA) { this.xA = xA; return this; } /// public abstract JobContCont<X, Y> Do(); internal override void DoJob(ref Worker wr, Cont<Y> yK) { var xK = Do(); xK.yK = yK; xA.DoJob(ref wr, xK); } internal override void TryAlt(ref Worker wr, int i, Cont<Y> yK, Else yE) { var xK = Do(); xK.yK = yK; xA.TryAlt(ref wr, i, xK, yE); } } /// public abstract class AltPrepareFun<X> : Alt<X> { /// public abstract Alt<X> Do(); internal override void DoJob(ref Worker wr, Cont<X> xK) { Do().DoJob(ref wr, xK); } internal override void TryAlt(ref Worker wr, int i, Cont<X> xK, Else xE) { var pk = xE.pk; if (0 == Pick.Claim(pk)) { Alt<X> xA; try { xA = Do(); Pick.Unclaim(pk); } catch (Exception e) { Pick.PickClaimedAndSetNacks(ref wr, i, pk); xA = new AltFail<X>(e); } xA.TryAlt(ref wr, i, xK, xE); } } } /// public abstract class AltPrepareJob<X, xA> : Alt<X> where xA : Alt<X> { /// public abstract Job<xA> Do(); internal override void DoJob(ref Worker wr, Cont<X> xK) { Do().DoJob(ref wr, new PrepareJobCont<X, xA>(xK)); } internal override void TryAlt(ref Worker wr, int i, Cont<X> xK, Else xE) { var pk = xE.pk; if (0 == Pick.Claim(pk)) { Job<xA> xAJ; try { xAJ = Do(); } catch (Exception e) { Pick.PickClaimedAndSetNacks(ref wr, i, pk); xAJ = new AltFail<xA>(e); } xAJ.DoJob(ref wr, new PrepareAltCont<X, xA>(i, xK, xE)); } } } internal sealed class AltFail<X> : Alt<X> { internal Exception e; internal AltFail(Exception e) { this.e = e; } internal override void DoJob(ref Worker wr, Cont<X> xK) { Handler.DoHandle(xK, ref wr, e); } internal override void TryAlt(ref Worker wr, int i, Cont<X> xK, Else xE) { Handler.DoHandle(xK, ref wr, e); } } /// public abstract class AltRandom<X> : Alt<X> { /// public abstract Alt<X> Do(ulong random); internal override void DoJob(ref Worker wr, Cont<X> xK) { Do(Randomizer.Next(ref wr.RandomLo, ref wr.RandomHi)).DoJob(ref wr, xK); } internal override void TryAlt(ref Worker wr, int i, Cont<X> xK, Else xE) { var pk = xE.pk; if (0 == Pick.Claim(pk)) { Alt<X> xA; try { xA = Do(Randomizer.Next(ref wr.RandomLo, ref wr.RandomHi)); Pick.Unclaim(pk); } catch (Exception e) { Pick.PickClaimedAndSetNacks(ref wr, i, pk); xA = new AltFail<X>(e); } xA.TryAlt(ref wr, i, xK, xE); } } } internal class PrepareJobCont<X, xA> : Cont<xA> where xA : Alt<X> { private Cont<X> xK; internal PrepareJobCont(Cont<X> xK) { this.xK = xK; } internal override Proc GetProc(ref Worker wr) { return Handler.GetProc(ref wr, ref xK); } internal override void DoHandle(ref Worker wr, Exception e) { Handler.DoHandle(xK, ref wr, e); } internal override void DoWork(ref Worker wr) { Value.DoJob(ref wr, xK); } internal override void DoCont(ref Worker wr, xA value) { value.DoJob(ref wr, xK); } } internal class PrepareAltCont<X, xA> : Cont<xA> where xA : Alt<X> { private int i; private Cont<X> xK; private Else xE; internal PrepareAltCont(int i, Cont<X> xK, Else xE) { this.i = i; this.xK = xK; this.xE = xE; } internal override Proc GetProc(ref Worker wr) { return Handler.GetProc (ref wr, ref xK); } internal override void DoHandle(ref Worker wr, Exception e) { Pick.PickClaimedAndSetNacks(ref wr, i, xE.pk); var xK = this.xK; wr.Handler = xK; Handler.DoHandle(xK, ref wr, e); } internal override void DoWork(ref Worker wr) { var xE = this.xE; Pick.Unclaim(xE.pk); var xK = this.xK; wr.Handler = xK; Value.TryAlt(ref wr, i, xK, xE); } internal override void DoCont(ref Worker wr, xA xA) { var xE = this.xE; Pick.Unclaim(xE.pk); var xK = this.xK; wr.Handler = xK; xA.TryAlt(ref wr, i, xK, xE); } } internal class WithNackElse : Else { private Nack nk; private Else xE; internal WithNackElse(Nack nk, Else xE) : base(xE.pk) { this.nk = nk; this.xE = xE; } internal override void TryElse(ref Worker wr, int i) { nk.I1 = i; xE.TryElse(ref wr, i); } } internal class WithNackCont<X, xA> : Cont<xA> where xA : Alt<X> { private Cont<X> xK; private Else xE; internal WithNackCont(Cont<X> xK, Else xE) { this.xK = xK; this.xE = xE; } internal override Proc GetProc(ref Worker wr) { return Handler.GetProc(ref wr, ref xK); } internal override void DoHandle(ref Worker wr, Exception e) { var pk = xE.pk; Pick.PickClaimedAndSetNacks(ref wr, pk.Nacks.I0, pk); var xK = this.xK; wr.Handler = xK; Handler.DoHandle(xK, ref wr, e); } internal override void DoWork(ref Worker wr) { var xE = this.xE; var pk = xE.pk; var nk = pk.Nacks; Pick.Unclaim(pk); var xK = this.xK; wr.Handler = xK; Value.TryAlt(ref wr, nk.I0, xK, new WithNackElse(nk, xE)); } internal override void DoCont(ref Worker wr, xA value) { var xE = this.xE; var pk = xE.pk; var nk = pk.Nacks; Pick.Unclaim(pk); var xK = this.xK; wr.Handler = xK; value.TryAlt(ref wr, nk.I0, xK, new WithNackElse(nk, xE)); } } /// public abstract class AltWithNackJob<X, xA> : Alt<X> where xA : Alt<X> { /// public abstract Job<xA> Do(Promise<Unit> nack); internal override void DoJob(ref Worker wr, Cont<X> xK) { Do(StaticData.zero).DoJob(ref wr, new PrepareJobCont<X, xA>(xK)); } internal override void TryAlt(ref Worker wr, int i, Cont<X> xK, Else xE) { var nk = Pick.ClaimAndAddNack(xE.pk, i); if (null != nk) { var handler = new WithNackCont<X, xA>(xK, xE); wr.Handler = handler; Do(nk).DoJob(ref wr, handler); } } } /// public abstract class AltWithNackFun<X> : Alt<X> { /// public abstract Alt<X> Do(Promise<Unit> nack); internal override void DoJob(ref Worker wr, Cont<X> xK) { Do(StaticData.zero).DoJob(ref wr, xK); } internal override void TryAlt(ref Worker wr, int i, Cont<X> xK, Else xE) { var pk = xE.pk; var nk = Pick.ClaimAndAddNack(pk, i); if (null != nk) { Alt<X> xA; try { xA = Do(nk); Pick.Unclaim(pk); } catch (Exception e) { Pick.PickClaimedAndSetNacks(ref wr, i, pk); xA = new AltFail<X>(e); } xA.TryAlt(ref wr, i, xK, new WithNackElse(nk, xE)); } } } } }
// 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.Buffers; using System.Diagnostics; namespace System.Text.Json { public static partial class JsonSerializer { /// <summary> /// Reads one JSON value (including objects or arrays) from the provided reader into a <typeparamref name="TValue"/>. /// </summary> /// <returns>A <typeparamref name="TValue"/> representation of the JSON value.</returns> /// <param name="reader">The reader to read.</param> /// <param name="options">Options to control the serializer behavior during reading.</param> /// <exception cref="JsonException"> /// Thrown when the JSON is invalid, /// <typeparamref name="TValue"/> is not compatible with the JSON, /// or a value could not be read from the reader. /// </exception> /// <exception cref="ArgumentException"> /// <paramref name="reader"/> is using unsupported options. /// </exception> /// <remarks> /// <para> /// If the <see cref="Utf8JsonReader.TokenType"/> property of <paramref name="reader"/> /// is <see cref="JsonTokenType.PropertyName"/> or <see cref="JsonTokenType.None"/>, the /// reader will be advanced by one call to <see cref="Utf8JsonReader.Read"/> to determine /// the start of the value. /// </para> /// /// <para> /// Upon completion of this method <paramref name="reader"/> will be positioned at the /// final token in the JSON value. If an exception is thrown the reader is reset to /// the state it was in when the method was called. /// </para> /// /// <para> /// This method makes a copy of the data the reader acted on, so there is no caller /// requirement to maintain data integrity beyond the return of this method. /// </para> /// /// <para> /// The <see cref="JsonReaderOptions"/> used to create the instance of the <see cref="Utf8JsonReader"/> take precedence over the <see cref="JsonSerializerOptions"/> when they conflict. /// Hence, <see cref="JsonReaderOptions.AllowTrailingCommas"/>, <see cref="JsonReaderOptions.MaxDepth"/>, <see cref="JsonReaderOptions.CommentHandling"/> are used while reading. /// </para> /// </remarks> public static TValue Deserialize<TValue>(ref Utf8JsonReader reader, JsonSerializerOptions options = null) { return (TValue)ReadValueCore(ref reader, typeof(TValue), options); } /// <summary> /// Reads one JSON value (including objects or arrays) from the provided reader into a <paramref name="returnType"/>. /// </summary> /// <returns>A <paramref name="returnType"/> representation of the JSON value.</returns> /// <param name="reader">The reader to read.</param> /// <param name="returnType">The type of the object to convert to and return.</param> /// <param name="options">Options to control the serializer behavior during reading.</param> /// <exception cref="ArgumentNullException"> /// Thrown if <paramref name="returnType"/> is null. /// </exception> /// <exception cref="JsonException"> /// Thrown when the JSON is invalid, /// <paramref name="returnType"/> is not compatible with the JSON, /// or a value could not be read from the reader. /// </exception> /// <exception cref="ArgumentException"> /// <paramref name="reader"/> is using unsupported options. /// </exception> /// <remarks> /// <para> /// If the <see cref="Utf8JsonReader.TokenType"/> property of <paramref name="reader"/> /// is <see cref="JsonTokenType.PropertyName"/> or <see cref="JsonTokenType.None"/>, the /// reader will be advanced by one call to <see cref="Utf8JsonReader.Read"/> to determine /// the start of the value. /// </para> /// /// <para> /// Upon completion of this method <paramref name="reader"/> will be positioned at the /// final token in the JSON value. If an exception is thrown the reader is reset to /// the state it was in when the method was called. /// </para> /// /// <para> /// This method makes a copy of the data the reader acted on, so there is no caller /// requirement to maintain data integrity beyond the return of this method. /// </para> /// <para> /// The <see cref="JsonReaderOptions"/> used to create the instance of the <see cref="Utf8JsonReader"/> take precedence over the <see cref="JsonSerializerOptions"/> when they conflict. /// Hence, <see cref="JsonReaderOptions.AllowTrailingCommas"/>, <see cref="JsonReaderOptions.MaxDepth"/>, <see cref="JsonReaderOptions.CommentHandling"/> are used while reading. /// </para> /// </remarks> public static object Deserialize(ref Utf8JsonReader reader, Type returnType, JsonSerializerOptions options = null) { if (returnType == null) throw new ArgumentNullException(nameof(returnType)); return ReadValueCore(ref reader, returnType, options); } private static object ReadValueCore(ref Utf8JsonReader reader, Type returnType, JsonSerializerOptions options) { if (options == null) { options = JsonSerializerOptions.s_defaultOptions; } ReadStack readStack = default; readStack.Current.Initialize(returnType, options); ReadValueCore(options, ref reader, ref readStack); return readStack.Current.ReturnValue; } private static void CheckSupportedOptions(JsonReaderOptions readerOptions, string paramName) { if (readerOptions.CommentHandling == JsonCommentHandling.Allow) { throw new ArgumentException(SR.JsonSerializerDoesNotSupportComments, paramName); } } private static void ReadValueCore(JsonSerializerOptions options, ref Utf8JsonReader reader, ref ReadStack readStack) { JsonReaderState state = reader.CurrentState; CheckSupportedOptions(state.Options, nameof(reader)); // Value copy to overwrite the ref on an exception and undo the destructive reads. Utf8JsonReader restore = reader; ReadOnlySpan<byte> valueSpan = default; ReadOnlySequence<byte> valueSequence = default; try { switch (reader.TokenType) { // A new reader was created and has never been read, // so we need to move to the first token. // (or a reader has terminated and we're about to throw) case JsonTokenType.None: // Using a reader loop the caller has identified a property they wish to // hydrate into a JsonDocument. Move to the value first. case JsonTokenType.PropertyName: { if (!reader.Read()) { ThrowHelper.ThrowJsonReaderException(ref reader, ExceptionResource.ExpectedOneCompleteToken); } break; } } switch (reader.TokenType) { // Any of the "value start" states are acceptable. case JsonTokenType.StartObject: case JsonTokenType.StartArray: { long startingOffset = reader.TokenStartIndex; if (!reader.TrySkip()) { ThrowHelper.ThrowJsonReaderException(ref reader, ExceptionResource.NotEnoughData); } long totalLength = reader.BytesConsumed - startingOffset; ReadOnlySequence<byte> sequence = reader.OriginalSequence; if (sequence.IsEmpty) { valueSpan = reader.OriginalSpan.Slice( checked((int)startingOffset), checked((int)totalLength)); } else { valueSequence = sequence.Slice(startingOffset, totalLength); } Debug.Assert( reader.TokenType == JsonTokenType.EndObject || reader.TokenType == JsonTokenType.EndArray); break; } // Single-token values case JsonTokenType.Number: case JsonTokenType.True: case JsonTokenType.False: case JsonTokenType.Null: { if (reader.HasValueSequence) { valueSequence = reader.ValueSequence; } else { valueSpan = reader.ValueSpan; } break; } // String's ValueSequence/ValueSpan omits the quotes, we need them back. case JsonTokenType.String: { ReadOnlySequence<byte> sequence = reader.OriginalSequence; if (sequence.IsEmpty) { // Since the quoted string fit in a ReadOnlySpan originally // the contents length plus the two quotes can't overflow. int payloadLength = reader.ValueSpan.Length + 2; Debug.Assert(payloadLength > 1); ReadOnlySpan<byte> readerSpan = reader.OriginalSpan; Debug.Assert( readerSpan[(int)reader.TokenStartIndex] == (byte)'"', $"Calculated span starts with {readerSpan[(int)reader.TokenStartIndex]}"); Debug.Assert( readerSpan[(int)reader.TokenStartIndex + payloadLength - 1] == (byte)'"', $"Calculated span ends with {readerSpan[(int)reader.TokenStartIndex + payloadLength - 1]}"); valueSpan = readerSpan.Slice((int)reader.TokenStartIndex, payloadLength); } else { long payloadLength = 2; if (reader.HasValueSequence) { payloadLength += reader.ValueSequence.Length; } else { payloadLength += reader.ValueSpan.Length; } valueSequence = sequence.Slice(reader.TokenStartIndex, payloadLength); Debug.Assert( valueSequence.First.Span[0] == (byte)'"', $"Calculated sequence starts with {valueSequence.First.Span[0]}"); Debug.Assert( valueSequence.ToArray()[payloadLength - 1] == (byte)'"', $"Calculated sequence ends with {valueSequence.ToArray()[payloadLength - 1]}"); } break; } default: { byte displayByte; if (reader.HasValueSequence) { displayByte = reader.ValueSequence.First.Span[0]; } else { displayByte = reader.ValueSpan[0]; } ThrowHelper.ThrowJsonReaderException( ref reader, ExceptionResource.ExpectedStartOfValueNotFound, displayByte); break; } } } catch (JsonReaderException ex) { reader = restore; // Re-throw with Path information. ThrowHelper.ReThrowWithPath(readStack, ex); } int length = valueSpan.IsEmpty ? checked((int)valueSequence.Length) : valueSpan.Length; byte[] rented = ArrayPool<byte>.Shared.Rent(length); Span<byte> rentedSpan = rented.AsSpan(0, length); try { if (valueSpan.IsEmpty) { valueSequence.CopyTo(rentedSpan); } else { valueSpan.CopyTo(rentedSpan); } var newReader = new Utf8JsonReader(rentedSpan, isFinalBlock: true, state: default); ReadCore(options, ref newReader, ref readStack); // The reader should have thrown if we have remaining bytes. Debug.Assert(newReader.BytesConsumed == length); } catch (JsonException) { reader = restore; throw; } finally { rentedSpan.Clear(); ArrayPool<byte>.Shared.Return(rented); } } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Apache.Ignite.Core.Tests.Cache.Query.Continuous { using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Runtime.Serialization; using System.Threading; using Apache.Ignite.Core.Binary; using Apache.Ignite.Core.Cache; using Apache.Ignite.Core.Cache.Event; using Apache.Ignite.Core.Cache.Query; using Apache.Ignite.Core.Cache.Query.Continuous; using Apache.Ignite.Core.Cluster; using Apache.Ignite.Core.Common; using Apache.Ignite.Core.Impl; using Apache.Ignite.Core.Impl.Cache.Event; using Apache.Ignite.Core.Resource; using NUnit.Framework; /// <summary> /// Tests for continuous query. /// </summary> [SuppressMessage("ReSharper", "InconsistentNaming")] [SuppressMessage("ReSharper", "PossibleNullReferenceException")] [SuppressMessage("ReSharper", "StaticMemberInGenericType")] public abstract class ContinuousQueryAbstractTest { /** Cache name: ATOMIC, backup. */ protected const string CACHE_ATOMIC_BACKUP = "atomic_backup"; /** Cache name: ATOMIC, no backup. */ protected const string CACHE_ATOMIC_NO_BACKUP = "atomic_no_backup"; /** Cache name: TRANSACTIONAL, backup. */ protected const string CACHE_TX_BACKUP = "transactional_backup"; /** Cache name: TRANSACTIONAL, no backup. */ protected const string CACHE_TX_NO_BACKUP = "transactional_no_backup"; /** Listener events. */ public static BlockingCollection<CallbackEvent> CB_EVTS = new BlockingCollection<CallbackEvent>(); /** Listener events. */ public static BlockingCollection<FilterEvent> FILTER_EVTS = new BlockingCollection<FilterEvent>(); /** First node. */ private IIgnite grid1; /** Second node. */ private IIgnite grid2; /** Cache on the first node. */ private ICache<int, BinarizableEntry> cache1; /** Cache on the second node. */ private ICache<int, BinarizableEntry> cache2; /** Cache name. */ private readonly string cacheName; /// <summary> /// Constructor. /// </summary> /// <param name="cacheName">Cache name.</param> protected ContinuousQueryAbstractTest(string cacheName) { this.cacheName = cacheName; } /// <summary> /// Set-up routine. /// </summary> [TestFixtureSetUp] public void SetUp() { GC.Collect(); TestUtils.JvmDebug = true; IgniteConfigurationEx cfg = new IgniteConfigurationEx(); BinaryConfiguration portCfg = new BinaryConfiguration(); ICollection<BinaryTypeConfiguration> portTypeCfgs = new List<BinaryTypeConfiguration>(); portTypeCfgs.Add(new BinaryTypeConfiguration(typeof(BinarizableEntry))); portTypeCfgs.Add(new BinaryTypeConfiguration(typeof(BinarizableFilter))); portTypeCfgs.Add(new BinaryTypeConfiguration(typeof(KeepBinaryFilter))); portCfg.TypeConfigurations = portTypeCfgs; cfg.BinaryConfiguration = portCfg; cfg.JvmClasspath = TestUtils.CreateTestClasspath(); cfg.JvmOptions = TestUtils.TestJavaOptions(); cfg.SpringConfigUrl = "config\\cache-query-continuous.xml"; cfg.GridName = "grid-1"; grid1 = Ignition.Start(cfg); cache1 = grid1.GetCache<int, BinarizableEntry>(cacheName); cfg.GridName = "grid-2"; grid2 = Ignition.Start(cfg); cache2 = grid2.GetCache<int, BinarizableEntry>(cacheName); } /// <summary> /// Tear-down routine. /// </summary> [TestFixtureTearDown] public void TearDown() { Ignition.StopAll(true); } /// <summary> /// Before-test routine. /// </summary> [SetUp] public void BeforeTest() { CB_EVTS = new BlockingCollection<CallbackEvent>(); FILTER_EVTS = new BlockingCollection<FilterEvent>(); AbstractFilter<BinarizableEntry>.res = true; AbstractFilter<BinarizableEntry>.err = false; AbstractFilter<BinarizableEntry>.marshErr = false; AbstractFilter<BinarizableEntry>.unmarshErr = false; cache1.Remove(PrimaryKey(cache1)); cache1.Remove(PrimaryKey(cache2)); Assert.AreEqual(0, cache1.GetSize()); Assert.AreEqual(0, cache2.GetSize()); Console.WriteLine("Test started: " + TestContext.CurrentContext.Test.Name); } /// <summary> /// Test arguments validation. /// </summary> [Test] public void TestValidation() { Assert.Throws<ArgumentException>(() => { cache1.QueryContinuous(new ContinuousQuery<int, BinarizableEntry>(null)); }); } /// <summary> /// Test multiple closes. /// </summary> [Test] public void TestMultipleClose() { int key1 = PrimaryKey(cache1); int key2 = PrimaryKey(cache2); ContinuousQuery<int, BinarizableEntry> qry = new ContinuousQuery<int, BinarizableEntry>(new Listener<BinarizableEntry>()); IDisposable qryHnd; using (qryHnd = cache1.QueryContinuous(qry)) { // Put from local node. cache1.GetAndPut(key1, Entry(key1)); CheckCallbackSingle(key1, null, Entry(key1)); // Put from remote node. cache2.GetAndPut(key2, Entry(key2)); CheckCallbackSingle(key2, null, Entry(key2)); } qryHnd.Dispose(); } /// <summary> /// Test regular callback operations. /// </summary> [Test] public void TestCallback() { CheckCallback(false); } /// <summary> /// Check regular callback execution. /// </summary> /// <param name="loc"></param> protected void CheckCallback(bool loc) { int key1 = PrimaryKey(cache1); int key2 = PrimaryKey(cache2); ContinuousQuery<int, BinarizableEntry> qry = loc ? new ContinuousQuery<int, BinarizableEntry>(new Listener<BinarizableEntry>(), true) : new ContinuousQuery<int, BinarizableEntry>(new Listener<BinarizableEntry>()); using (cache1.QueryContinuous(qry)) { // Put from local node. cache1.GetAndPut(key1, Entry(key1)); CheckCallbackSingle(key1, null, Entry(key1)); cache1.GetAndPut(key1, Entry(key1 + 1)); CheckCallbackSingle(key1, Entry(key1), Entry(key1 + 1)); cache1.Remove(key1); CheckCallbackSingle(key1, Entry(key1 + 1), null); // Put from remote node. cache2.GetAndPut(key2, Entry(key2)); if (loc) CheckNoCallback(100); else CheckCallbackSingle(key2, null, Entry(key2)); cache1.GetAndPut(key2, Entry(key2 + 1)); if (loc) CheckNoCallback(100); else CheckCallbackSingle(key2, Entry(key2), Entry(key2 + 1)); cache1.Remove(key2); if (loc) CheckNoCallback(100); else CheckCallbackSingle(key2, Entry(key2 + 1), null); } cache1.Put(key1, Entry(key1)); CheckNoCallback(100); cache1.Put(key2, Entry(key2)); CheckNoCallback(100); } /// <summary> /// Test Ignite injection into callback. /// </summary> [Test] public void TestCallbackInjection() { Listener<BinarizableEntry> cb = new Listener<BinarizableEntry>(); Assert.IsNull(cb.ignite); using (cache1.QueryContinuous(new ContinuousQuery<int, BinarizableEntry>(cb))) { Assert.IsNotNull(cb.ignite); } } /// <summary> /// Test binarizable filter logic. /// </summary> [Test] public void TestFilterBinarizable() { CheckFilter(true, false); } /// <summary> /// Test serializable filter logic. /// </summary> [Test] public void TestFilterSerializable() { CheckFilter(false, false); } /// <summary> /// Check filter. /// </summary> /// <param name="binarizable">Binarizable.</param> /// <param name="loc">Local cache flag.</param> protected void CheckFilter(bool binarizable, bool loc) { ICacheEntryEventListener<int, BinarizableEntry> lsnr = new Listener<BinarizableEntry>(); ICacheEntryEventFilter<int, BinarizableEntry> filter = binarizable ? (AbstractFilter<BinarizableEntry>) new BinarizableFilter() : new SerializableFilter(); ContinuousQuery<int, BinarizableEntry> qry = loc ? new ContinuousQuery<int, BinarizableEntry>(lsnr, filter, true) : new ContinuousQuery<int, BinarizableEntry>(lsnr, filter); using (cache1.QueryContinuous(qry)) { // Put from local node. int key1 = PrimaryKey(cache1); cache1.GetAndPut(key1, Entry(key1)); CheckFilterSingle(key1, null, Entry(key1)); CheckCallbackSingle(key1, null, Entry(key1)); // Put from remote node. int key2 = PrimaryKey(cache2); cache1.GetAndPut(key2, Entry(key2)); if (loc) { CheckNoFilter(key2); CheckNoCallback(key2); } else { CheckFilterSingle(key2, null, Entry(key2)); CheckCallbackSingle(key2, null, Entry(key2)); } AbstractFilter<BinarizableEntry>.res = false; // Ignored put from local node. cache1.GetAndPut(key1, Entry(key1 + 1)); CheckFilterSingle(key1, Entry(key1), Entry(key1 + 1)); CheckNoCallback(100); // Ignored put from remote node. cache1.GetAndPut(key2, Entry(key2 + 1)); if (loc) CheckNoFilter(100); else CheckFilterSingle(key2, Entry(key2), Entry(key2 + 1)); CheckNoCallback(100); } } /// <summary> /// Test binarizable filter error during invoke. /// </summary> [Ignore("IGNITE-521")] [Test] public void TestFilterInvokeErrorBinarizable() { CheckFilterInvokeError(true); } /// <summary> /// Test serializable filter error during invoke. /// </summary> [Ignore("IGNITE-521")] [Test] public void TestFilterInvokeErrorSerializable() { CheckFilterInvokeError(false); } /// <summary> /// Check filter error handling logic during invoke. /// </summary> private void CheckFilterInvokeError(bool binarizable) { AbstractFilter<BinarizableEntry>.err = true; ICacheEntryEventListener<int, BinarizableEntry> lsnr = new Listener<BinarizableEntry>(); ICacheEntryEventFilter<int, BinarizableEntry> filter = binarizable ? (AbstractFilter<BinarizableEntry>) new BinarizableFilter() : new SerializableFilter(); ContinuousQuery<int, BinarizableEntry> qry = new ContinuousQuery<int, BinarizableEntry>(lsnr, filter); using (cache1.QueryContinuous(qry)) { // Put from local node. try { cache1.GetAndPut(PrimaryKey(cache1), Entry(1)); Assert.Fail("Should not reach this place."); } catch (IgniteException) { // No-op. } catch (Exception) { Assert.Fail("Unexpected error."); } // Put from remote node. try { cache1.GetAndPut(PrimaryKey(cache2), Entry(1)); Assert.Fail("Should not reach this place."); } catch (IgniteException) { // No-op. } catch (Exception) { Assert.Fail("Unexpected error."); } } } /// <summary> /// Test binarizable filter marshalling error. /// </summary> [Test] public void TestFilterMarshalErrorBinarizable() { CheckFilterMarshalError(true); } /// <summary> /// Test serializable filter marshalling error. /// </summary> [Test] public void TestFilterMarshalErrorSerializable() { CheckFilterMarshalError(false); } /// <summary> /// Check filter marshal error handling. /// </summary> /// <param name="binarizable">Binarizable flag.</param> private void CheckFilterMarshalError(bool binarizable) { AbstractFilter<BinarizableEntry>.marshErr = true; ICacheEntryEventListener<int, BinarizableEntry> lsnr = new Listener<BinarizableEntry>(); ICacheEntryEventFilter<int, BinarizableEntry> filter = binarizable ? (AbstractFilter<BinarizableEntry>)new BinarizableFilter() : new SerializableFilter(); ContinuousQuery<int, BinarizableEntry> qry = new ContinuousQuery<int, BinarizableEntry>(lsnr, filter); Assert.Throws<Exception>(() => { using (cache1.QueryContinuous(qry)) { // No-op. } }); } /// <summary> /// Test non-serializable filter error. /// </summary> [Test] public void TestFilterNonSerializable() { CheckFilterNonSerializable(false); } /// <summary> /// Test non-serializable filter behavior. /// </summary> /// <param name="loc"></param> protected void CheckFilterNonSerializable(bool loc) { AbstractFilter<BinarizableEntry>.unmarshErr = true; ICacheEntryEventListener<int, BinarizableEntry> lsnr = new Listener<BinarizableEntry>(); ICacheEntryEventFilter<int, BinarizableEntry> filter = new LocalFilter(); ContinuousQuery<int, BinarizableEntry> qry = loc ? new ContinuousQuery<int, BinarizableEntry>(lsnr, filter, true) : new ContinuousQuery<int, BinarizableEntry>(lsnr, filter); if (loc) { using (cache1.QueryContinuous(qry)) { // Local put must be fine. int key1 = PrimaryKey(cache1); cache1.GetAndPut(key1, Entry(key1)); CheckFilterSingle(key1, null, Entry(key1)); } } else { Assert.Throws<BinaryObjectException>(() => { using (cache1.QueryContinuous(qry)) { // No-op. } }); } } /// <summary> /// Test binarizable filter unmarshalling error. /// </summary> [Ignore("IGNITE-521")] [Test] public void TestFilterUnmarshalErrorBinarizable() { CheckFilterUnmarshalError(true); } /// <summary> /// Test serializable filter unmarshalling error. /// </summary> [Ignore("IGNITE-521")] [Test] public void TestFilterUnmarshalErrorSerializable() { CheckFilterUnmarshalError(false); } /// <summary> /// Check filter unmarshal error handling. /// </summary> /// <param name="binarizable">Binarizable flag.</param> private void CheckFilterUnmarshalError(bool binarizable) { AbstractFilter<BinarizableEntry>.unmarshErr = true; ICacheEntryEventListener<int, BinarizableEntry> lsnr = new Listener<BinarizableEntry>(); ICacheEntryEventFilter<int, BinarizableEntry> filter = binarizable ? (AbstractFilter<BinarizableEntry>) new BinarizableFilter() : new SerializableFilter(); ContinuousQuery<int, BinarizableEntry> qry = new ContinuousQuery<int, BinarizableEntry>(lsnr, filter); using (cache1.QueryContinuous(qry)) { // Local put must be fine. int key1 = PrimaryKey(cache1); cache1.GetAndPut(key1, Entry(key1)); CheckFilterSingle(key1, null, Entry(key1)); // Remote put must fail. try { cache1.GetAndPut(PrimaryKey(cache2), Entry(1)); Assert.Fail("Should not reach this place."); } catch (IgniteException) { // No-op. } catch (Exception) { Assert.Fail("Unexpected error."); } } } /// <summary> /// Test Ignite injection into filters. /// </summary> [Test] public void TestFilterInjection() { Listener<BinarizableEntry> cb = new Listener<BinarizableEntry>(); BinarizableFilter filter = new BinarizableFilter(); Assert.IsNull(filter.ignite); using (cache1.QueryContinuous(new ContinuousQuery<int, BinarizableEntry>(cb, filter))) { // Local injection. Assert.IsNotNull(filter.ignite); // Remote injection. cache1.GetAndPut(PrimaryKey(cache2), Entry(1)); FilterEvent evt; Assert.IsTrue(FILTER_EVTS.TryTake(out evt, 500)); Assert.IsNotNull(evt.ignite); } } /// <summary> /// Test "keep-binary" scenario. /// </summary> [Test] public void TestKeepBinary() { var cache = cache1.WithKeepBinary<int, IBinaryObject>(); ContinuousQuery<int, IBinaryObject> qry = new ContinuousQuery<int, IBinaryObject>( new Listener<IBinaryObject>(), new KeepBinaryFilter()); using (cache.QueryContinuous(qry)) { // 1. Local put. cache1.GetAndPut(PrimaryKey(cache1), Entry(1)); CallbackEvent cbEvt; FilterEvent filterEvt; Assert.IsTrue(FILTER_EVTS.TryTake(out filterEvt, 500)); Assert.AreEqual(PrimaryKey(cache1), filterEvt.entry.Key); Assert.AreEqual(null, filterEvt.entry.OldValue); Assert.AreEqual(Entry(1), (filterEvt.entry.Value as IBinaryObject) .Deserialize<BinarizableEntry>()); Assert.IsTrue(CB_EVTS.TryTake(out cbEvt, 500)); Assert.AreEqual(1, cbEvt.entries.Count); Assert.AreEqual(PrimaryKey(cache1), cbEvt.entries.First().Key); Assert.AreEqual(null, cbEvt.entries.First().OldValue); Assert.AreEqual(Entry(1), (cbEvt.entries.First().Value as IBinaryObject) .Deserialize<BinarizableEntry>()); // 2. Remote put. ClearEvents(); cache1.GetAndPut(PrimaryKey(cache2), Entry(2)); Assert.IsTrue(FILTER_EVTS.TryTake(out filterEvt, 500)); Assert.AreEqual(PrimaryKey(cache2), filterEvt.entry.Key); Assert.AreEqual(null, filterEvt.entry.OldValue); Assert.AreEqual(Entry(2), (filterEvt.entry.Value as IBinaryObject) .Deserialize<BinarizableEntry>()); Assert.IsTrue(CB_EVTS.TryTake(out cbEvt, 500)); Assert.AreEqual(1, cbEvt.entries.Count); Assert.AreEqual(PrimaryKey(cache2), cbEvt.entries.First().Key); Assert.AreEqual(null, cbEvt.entries.First().OldValue); Assert.AreEqual(Entry(2), (cbEvt.entries.First().Value as IBinaryObject).Deserialize<BinarizableEntry>()); } } /// <summary> /// Test value types (special handling is required for nulls). /// </summary> [Test] public void TestValueTypes() { var cache = grid1.GetCache<int, int>(cacheName); var qry = new ContinuousQuery<int, int>(new Listener<int>()); var key = PrimaryKey(cache); using (cache.QueryContinuous(qry)) { // First update cache.Put(key, 1); CallbackEvent cbEvt; Assert.IsTrue(CB_EVTS.TryTake(out cbEvt, 500)); var cbEntry = cbEvt.entries.Single(); Assert.IsFalse(cbEntry.HasOldValue); Assert.IsTrue(cbEntry.HasValue); Assert.AreEqual(key, cbEntry.Key); Assert.AreEqual(null, cbEntry.OldValue); Assert.AreEqual(1, cbEntry.Value); // Second update cache.Put(key, 2); Assert.IsTrue(CB_EVTS.TryTake(out cbEvt, 500)); cbEntry = cbEvt.entries.Single(); Assert.IsTrue(cbEntry.HasOldValue); Assert.IsTrue(cbEntry.HasValue); Assert.AreEqual(key, cbEntry.Key); Assert.AreEqual(1, cbEntry.OldValue); Assert.AreEqual(2, cbEntry.Value); // Remove cache.Remove(key); Assert.IsTrue(CB_EVTS.TryTake(out cbEvt, 500)); cbEntry = cbEvt.entries.Single(); Assert.IsTrue(cbEntry.HasOldValue); Assert.IsFalse(cbEntry.HasValue); Assert.AreEqual(key, cbEntry.Key); Assert.AreEqual(2, cbEntry.OldValue); Assert.AreEqual(null, cbEntry.Value); } } /// <summary> /// Test whether buffer size works fine. /// </summary> [Test] public void TestBufferSize() { // Put two remote keys in advance. List<int> rmtKeys = PrimaryKeys(cache2, 2); ContinuousQuery<int, BinarizableEntry> qry = new ContinuousQuery<int, BinarizableEntry>(new Listener<BinarizableEntry>()); qry.BufferSize = 2; qry.TimeInterval = TimeSpan.FromMilliseconds(1000000); using (cache1.QueryContinuous(qry)) { qry.BufferSize = 2; cache1.GetAndPut(rmtKeys[0], Entry(rmtKeys[0])); CheckNoCallback(100); cache1.GetAndPut(rmtKeys[1], Entry(rmtKeys[1])); CallbackEvent evt; Assert.IsTrue(CB_EVTS.TryTake(out evt, 1000)); Assert.AreEqual(2, evt.entries.Count); var entryRmt0 = evt.entries.Single(entry => { return entry.Key.Equals(rmtKeys[0]); }); var entryRmt1 = evt.entries.Single(entry => { return entry.Key.Equals(rmtKeys[1]); }); Assert.AreEqual(rmtKeys[0], entryRmt0.Key); Assert.IsNull(entryRmt0.OldValue); Assert.AreEqual(Entry(rmtKeys[0]), entryRmt0.Value); Assert.AreEqual(rmtKeys[1], entryRmt1.Key); Assert.IsNull(entryRmt1.OldValue); Assert.AreEqual(Entry(rmtKeys[1]), entryRmt1.Value); } cache1.Remove(rmtKeys[0]); cache1.Remove(rmtKeys[1]); } /// <summary> /// Test whether timeout works fine. /// </summary> [Test] public void TestTimeout() { int key1 = PrimaryKey(cache1); int key2 = PrimaryKey(cache2); ContinuousQuery<int, BinarizableEntry> qry = new ContinuousQuery<int, BinarizableEntry>(new Listener<BinarizableEntry>()); qry.BufferSize = 2; qry.TimeInterval = TimeSpan.FromMilliseconds(500); using (cache1.QueryContinuous(qry)) { // Put from local node. cache1.GetAndPut(key1, Entry(key1)); CheckCallbackSingle(key1, null, Entry(key1)); // Put from remote node. cache1.GetAndPut(key2, Entry(key2)); CheckNoCallback(100); CheckCallbackSingle(key2, null, Entry(key2), 1000); } } /// <summary> /// Test whether nested Ignite API call from callback works fine. /// </summary> [Test] public void TestNestedCallFromCallback() { var cache = cache1.WithKeepBinary<int, IBinaryObject>(); int key = PrimaryKey(cache1); NestedCallListener cb = new NestedCallListener(); using (cache.QueryContinuous(new ContinuousQuery<int, IBinaryObject>(cb))) { cache1.GetAndPut(key, Entry(key)); cb.countDown.Wait(); } cache.Remove(key); } /// <summary> /// Tests the initial query. /// </summary> [Test] public void TestInitialQuery() { // Scan query, GetAll TestInitialQuery(new ScanQuery<int, BinarizableEntry>(new InitialQueryScanFilter()), cur => cur.GetAll()); // Scan query, iterator TestInitialQuery(new ScanQuery<int, BinarizableEntry>(new InitialQueryScanFilter()), cur => cur.ToList()); // Sql query, GetAll TestInitialQuery(new SqlQuery(typeof(BinarizableEntry), "val < 33"), cur => cur.GetAll()); // Sql query, iterator TestInitialQuery(new SqlQuery(typeof(BinarizableEntry), "val < 33"), cur => cur.ToList()); // Text query, GetAll TestInitialQuery(new TextQuery(typeof(BinarizableEntry), "1*"), cur => cur.GetAll()); // Text query, iterator TestInitialQuery(new TextQuery(typeof(BinarizableEntry), "1*"), cur => cur.ToList()); // Test exception: invalid initial query var ex = Assert.Throws<IgniteException>( () => TestInitialQuery(new TextQuery(typeof (BinarizableEntry), "*"), cur => cur.GetAll())); Assert.AreEqual("Cannot parse '*': '*' or '?' not allowed as first character in WildcardQuery", ex.Message); } /// <summary> /// Tests the initial query. /// </summary> private void TestInitialQuery(QueryBase initialQry, Func<IQueryCursor<ICacheEntry<int, BinarizableEntry>>, IEnumerable<ICacheEntry<int, BinarizableEntry>>> getAllFunc) { var qry = new ContinuousQuery<int, BinarizableEntry>(new Listener<BinarizableEntry>()); cache1.Put(11, Entry(11)); cache1.Put(12, Entry(12)); cache1.Put(33, Entry(33)); try { IContinuousQueryHandle<ICacheEntry<int, BinarizableEntry>> contQry; using (contQry = cache1.QueryContinuous(qry, initialQry)) { // Check initial query var initialEntries = getAllFunc(contQry.GetInitialQueryCursor()).Distinct().OrderBy(x => x.Key).ToList(); Assert.Throws<InvalidOperationException>(() => contQry.GetInitialQueryCursor()); Assert.AreEqual(2, initialEntries.Count); for (int i = 0; i < initialEntries.Count; i++) { Assert.AreEqual(i + 11, initialEntries[i].Key); Assert.AreEqual(i + 11, initialEntries[i].Value.val); } // Check continuous query cache1.Put(44, Entry(44)); CheckCallbackSingle(44, null, Entry(44)); } Assert.Throws<ObjectDisposedException>(() => contQry.GetInitialQueryCursor()); contQry.Dispose(); // multiple dispose calls are ok } finally { cache1.Clear(); } } /// <summary> /// Check single filter event. /// </summary> /// <param name="expKey">Expected key.</param> /// <param name="expOldVal">Expected old value.</param> /// <param name="expVal">Expected value.</param> private void CheckFilterSingle(int expKey, BinarizableEntry expOldVal, BinarizableEntry expVal) { CheckFilterSingle(expKey, expOldVal, expVal, 1000); ClearEvents(); } /// <summary> /// Check single filter event. /// </summary> /// <param name="expKey">Expected key.</param> /// <param name="expOldVal">Expected old value.</param> /// <param name="expVal">Expected value.</param> /// <param name="timeout">Timeout.</param> private static void CheckFilterSingle(int expKey, BinarizableEntry expOldVal, BinarizableEntry expVal, int timeout) { FilterEvent evt; Assert.IsTrue(FILTER_EVTS.TryTake(out evt, timeout)); Assert.AreEqual(expKey, evt.entry.Key); Assert.AreEqual(expOldVal, evt.entry.OldValue); Assert.AreEqual(expVal, evt.entry.Value); ClearEvents(); } /// <summary> /// Clears the events collection. /// </summary> private static void ClearEvents() { while (FILTER_EVTS.Count > 0) FILTER_EVTS.Take(); } /// <summary> /// Ensure that no filter events are logged. /// </summary> /// <param name="timeout">Timeout.</param> private static void CheckNoFilter(int timeout) { FilterEvent evt; Assert.IsFalse(FILTER_EVTS.TryTake(out evt, timeout)); } /// <summary> /// Check single callback event. /// </summary> /// <param name="expKey">Expected key.</param> /// <param name="expOldVal">Expected old value.</param> /// <param name="expVal">Expected new value.</param> private static void CheckCallbackSingle(int expKey, BinarizableEntry expOldVal, BinarizableEntry expVal) { CheckCallbackSingle(expKey, expOldVal, expVal, 1000); } /// <summary> /// Check single callback event. /// </summary> /// <param name="expKey">Expected key.</param> /// <param name="expOldVal">Expected old value.</param> /// <param name="expVal">Expected new value.</param> /// <param name="timeout">Timeout.</param> private static void CheckCallbackSingle(int expKey, BinarizableEntry expOldVal, BinarizableEntry expVal, int timeout) { CallbackEvent evt; Assert.IsTrue(CB_EVTS.TryTake(out evt, timeout)); Assert.AreEqual(1, evt.entries.Count); Assert.AreEqual(expKey, evt.entries.First().Key); Assert.AreEqual(expOldVal, evt.entries.First().OldValue); Assert.AreEqual(expVal, evt.entries.First().Value); } /// <summary> /// Ensure that no callback events are logged. /// </summary> /// <param name="timeout">Timeout.</param> private void CheckNoCallback(int timeout) { CallbackEvent evt; Assert.IsFalse(CB_EVTS.TryTake(out evt, timeout)); } /// <summary> /// Craate entry. /// </summary> /// <param name="val">Value.</param> /// <returns>Entry.</returns> private static BinarizableEntry Entry(int val) { return new BinarizableEntry(val); } /// <summary> /// Get primary key for cache. /// </summary> /// <param name="cache">Cache.</param> /// <returns>Primary key.</returns> private static int PrimaryKey<T>(ICache<int, T> cache) { return PrimaryKeys(cache, 1)[0]; } /// <summary> /// Get primary keys for cache. /// </summary> /// <param name="cache">Cache.</param> /// <param name="cnt">Amount of keys.</param> /// <param name="startFrom">Value to start from.</param> /// <returns></returns> private static List<int> PrimaryKeys<T>(ICache<int, T> cache, int cnt, int startFrom = 0) { IClusterNode node = cache.Ignite.GetCluster().GetLocalNode(); ICacheAffinity aff = cache.Ignite.GetAffinity(cache.Name); List<int> keys = new List<int>(cnt); for (int i = startFrom; i < startFrom + 100000; i++) { if (aff.IsPrimary(node, i)) { keys.Add(i); if (keys.Count == cnt) return keys; } } Assert.Fail("Failed to find " + cnt + " primary keys."); return null; } /// <summary> /// Creates object-typed event. /// </summary> private static ICacheEntryEvent<object, object> CreateEvent<T, V>(ICacheEntryEvent<T,V> e) { if (!e.HasOldValue) return new CacheEntryCreateEvent<object, object>(e.Key, e.Value); if (!e.HasValue) return new CacheEntryRemoveEvent<object, object>(e.Key, e.OldValue); return new CacheEntryUpdateEvent<object, object>(e.Key, e.OldValue, e.Value); } /// <summary> /// Binarizable entry. /// </summary> public class BinarizableEntry { /** Value. */ public readonly int val; /** <inheritDot /> */ public override int GetHashCode() { return val; } /// <summary> /// Constructor. /// </summary> /// <param name="val">Value.</param> public BinarizableEntry(int val) { this.val = val; } /** <inheritDoc /> */ public override bool Equals(object obj) { return obj != null && obj is BinarizableEntry && ((BinarizableEntry)obj).val == val; } } /// <summary> /// Abstract filter. /// </summary> [Serializable] public abstract class AbstractFilter<V> : ICacheEntryEventFilter<int, V> { /** Result. */ public static volatile bool res = true; /** Throw error on invocation. */ public static volatile bool err; /** Throw error during marshalling. */ public static volatile bool marshErr; /** Throw error during unmarshalling. */ public static volatile bool unmarshErr; /** Grid. */ [InstanceResource] public IIgnite ignite; /** <inheritDoc /> */ public bool Evaluate(ICacheEntryEvent<int, V> evt) { if (err) throw new Exception("Filter error."); FILTER_EVTS.Add(new FilterEvent(ignite, CreateEvent(evt))); return res; } } /// <summary> /// Filter which cannot be serialized. /// </summary> public class LocalFilter : AbstractFilter<BinarizableEntry> { // No-op. } /// <summary> /// Binarizable filter. /// </summary> public class BinarizableFilter : AbstractFilter<BinarizableEntry>, IBinarizable { /** <inheritDoc /> */ public void WriteBinary(IBinaryWriter writer) { if (marshErr) throw new Exception("Filter marshalling error."); } /** <inheritDoc /> */ public void ReadBinary(IBinaryReader reader) { if (unmarshErr) throw new Exception("Filter unmarshalling error."); } } /// <summary> /// Serializable filter. /// </summary> [Serializable] public class SerializableFilter : AbstractFilter<BinarizableEntry>, ISerializable { /// <summary> /// Constructor. /// </summary> public SerializableFilter() { // No-op. } /// <summary> /// Serialization constructor. /// </summary> /// <param name="info">Info.</param> /// <param name="context">Context.</param> protected SerializableFilter(SerializationInfo info, StreamingContext context) { if (unmarshErr) throw new Exception("Filter unmarshalling error."); } /** <inheritDoc /> */ public void GetObjectData(SerializationInfo info, StreamingContext context) { if (marshErr) throw new Exception("Filter marshalling error."); } } /// <summary> /// Filter for "keep-binary" scenario. /// </summary> public class KeepBinaryFilter : AbstractFilter<IBinaryObject> { // No-op. } /// <summary> /// Listener. /// </summary> public class Listener<V> : ICacheEntryEventListener<int, V> { [InstanceResource] public IIgnite ignite; /** <inheritDoc /> */ public void OnEvent(IEnumerable<ICacheEntryEvent<int, V>> evts) { CB_EVTS.Add(new CallbackEvent(evts.Select(CreateEvent).ToList())); } } /// <summary> /// Listener with nested Ignite API call. /// </summary> public class NestedCallListener : ICacheEntryEventListener<int, IBinaryObject> { /** Event. */ public readonly CountdownEvent countDown = new CountdownEvent(1); public void OnEvent(IEnumerable<ICacheEntryEvent<int, IBinaryObject>> evts) { foreach (ICacheEntryEvent<int, IBinaryObject> evt in evts) { IBinaryObject val = evt.Value; IBinaryType meta = val.GetBinaryType(); Assert.AreEqual(typeof(BinarizableEntry).Name, meta.TypeName); } countDown.Signal(); } } /// <summary> /// Filter event. /// </summary> public class FilterEvent { /** Grid. */ public IIgnite ignite; /** Entry. */ public ICacheEntryEvent<object, object> entry; /// <summary> /// Constructor. /// </summary> /// <param name="ignite">Grid.</param> /// <param name="entry">Entry.</param> public FilterEvent(IIgnite ignite, ICacheEntryEvent<object, object> entry) { this.ignite = ignite; this.entry = entry; } } /// <summary> /// Callbakc event. /// </summary> public class CallbackEvent { /** Entries. */ public ICollection<ICacheEntryEvent<object, object>> entries; /// <summary> /// Constructor. /// </summary> /// <param name="entries">Entries.</param> public CallbackEvent(ICollection<ICacheEntryEvent<object, object>> entries) { this.entries = entries; } } /// <summary> /// ScanQuery filter for InitialQuery test. /// </summary> [Serializable] private class InitialQueryScanFilter : ICacheEntryFilter<int, BinarizableEntry> { /** <inheritdoc /> */ public bool Invoke(ICacheEntry<int, BinarizableEntry> entry) { return entry.Key < 33; } } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Apache.Ignite.Core.Tests.Client.Compute { using System; using System.Collections; using System.Linq; using System.Threading; using System.Threading.Tasks; using Apache.Ignite.Core.Binary; using Apache.Ignite.Core.Client; using Apache.Ignite.Core.Client.Compute; using Apache.Ignite.Core.Common; using Apache.Ignite.Core.Configuration; using Apache.Ignite.Core.Impl.Binary; using Apache.Ignite.Core.Impl.Client.Compute; using Apache.Ignite.Core.Log; using Apache.Ignite.Core.Tests.Client.Cache; using Apache.Ignite.Core.Tests.Compute; using NUnit.Framework; /// <summary> /// Tests for <see cref="ComputeClient"/>. /// </summary> public class ComputeClientTests : ClientTestBase { /** */ private const string TestTask = "org.apache.ignite.internal.client.thin.TestTask"; /** */ private const string TestResultCacheTask = "org.apache.ignite.internal.client.thin.TestResultCacheTask"; /** */ private const string TestFailoverTask = "org.apache.ignite.internal.client.thin.TestFailoverTask"; /** */ private const string ActiveTaskFuturesTask = "org.apache.ignite.platform.PlatformComputeActiveTaskFuturesTask"; /** */ private const int MaxTasks = 8; /// <summary> /// Initializes a new instance of <see cref="ComputeClientTests"/>. /// </summary> public ComputeClientTests() : base(3) { // No-op. } /// <summary> /// Tears down the test. /// </summary> [TearDown] public void TearDown() { var logger = (ListLogger) Client.GetConfiguration().Logger; var entries = logger.Entries; logger.Clear(); foreach (var entry in entries) { if (entry.Level >= LogLevel.Warn) { Assert.Fail(entry.Message); } } Assert.IsEmpty(Client.GetActiveNotificationListeners()); } /// <summary> /// Tests <see cref="IComputeClient.ExecuteJavaTask{TRes}"/>. /// </summary> [Test] public void TestExecuteJavaTask([Values(true, false)] bool async) { var res = async ? Client.GetCompute().ExecuteJavaTask<int>(ComputeApiTest.EchoTask, ComputeApiTest.EchoTypeInt) : Client.GetCompute().ExecuteJavaTaskAsync<int>(ComputeApiTest.EchoTask, ComputeApiTest.EchoTypeInt) .Result; Assert.AreEqual(1, res); } /// <summary> /// Tests <see cref="IComputeClient.ExecuteJavaTask{TRes}"/> with server-side error. /// </summary> [Test] public void TestExecuteJavaTaskWithError() { var ex = (IgniteClientException) Assert.Throws<AggregateException>( () => Client.GetCompute().ExecuteJavaTask<int>(ComputeApiTest.EchoTask, -42)) .GetInnermostException(); StringAssert.EndsWith("Unknown type: -42", ex.Message); } /// <summary> /// Tests <see cref="IComputeClient.ExecuteJavaTask{TRes}"/> throws exception /// when client disconnects during task execution. /// </summary> [Test] public void TestExecuteJavaTaskThrowsExceptionOnDisconnect() { var cfg = new IgniteConfiguration(GetIgniteConfiguration()) { AutoGenerateIgniteInstanceName = true }; var ignite = Ignition.Start(cfg); var port = ignite.GetCluster().GetLocalNode().GetAttribute<int>("clientListenerPort"); var clientCfg = new IgniteClientConfiguration(GetClientConfiguration()) { Endpoints = new[] {"127.0.0.1:" + port} }; var client = Ignition.StartClient(clientCfg); try { var task = client.GetCompute().ExecuteJavaTaskAsync<object>(TestTask, (long) 10000); ignite.Dispose(); var ex = Assert.Throws<AggregateException>(() => task.Wait()).GetInnermostException(); StringAssert.StartsWith("Task cancelled due to stopping of the grid", ex.Message); } finally { ignite.Dispose(); client.Dispose(); } } /// <summary> /// Tests <see cref="IComputeClient.ExecuteJavaTask{TRes}"/> with binary flag. /// </summary> [Test] public void TestExecuteJavaTaskWithKeepBinaryJavaOnlyResultClass() { var res = Client.GetCompute().WithKeepBinary().ExecuteJavaTask<IBinaryObject>( ComputeApiTest.EchoTask, ComputeApiTest.EchoTypeBinarizableJava); Assert.AreEqual(1, res.GetField<int>("field")); Assert.AreEqual("field", res.GetBinaryType().Fields.Single()); Assert.AreEqual("org.apache.ignite.platform.PlatformComputeJavaBinarizable", res.GetBinaryType().TypeName); } /// <summary> /// Tests <see cref="IComputeClient.ExecuteJavaTask{TRes}"/> with binary flag. /// </summary> [Test] public void TestExecuteJavaTaskWithKeepBinaryDotnetOnlyArgClass() { var arg = new PlatformComputeNetBinarizable {Field = 42}; var res = Client.GetCompute().WithKeepBinary().ExecuteJavaTask<int>(ComputeApiTest.BinaryArgTask, arg); Assert.AreEqual(arg.Field, res); } /// <summary> /// Tests <see cref="IComputeClient.ExecuteJavaTask{TRes}"/> with .NET-only arg class /// and without WithKeepBinary. /// </summary> [Test] public void TestExecuteJavaTaskWithDotnetOnlyArgClassThrowsCorrectException() { var arg = new PlatformComputeNetBinarizable {Field = 42}; var ex = Assert.Throws<AggregateException>(() => Client.GetCompute().ExecuteJavaTask<int>(ComputeApiTest.BinaryArgTask, arg)); var clientEx = (IgniteClientException) ex.GetInnermostException(); var expected = string.Format( "Failed to resolve .NET class '{0}' in Java [platformId=0, typeId=-315989221].", arg.GetType().FullName); Assert.AreEqual(expected, clientEx.Message); } /// <summary> /// Tests <see cref="IComputeClient.ExecuteJavaTask{TRes}"/> with no-failover flag. /// </summary> [Test] public void TestExecuteJavaTaskWithNoFailover() { var computeWithFailover = Client.GetCompute(); var computeWithNoFailover = Client.GetCompute().WithNoFailover(); Assert.IsTrue(computeWithFailover.ExecuteJavaTask<bool>(TestFailoverTask, null)); Assert.IsFalse(computeWithNoFailover.ExecuteJavaTask<bool>(TestFailoverTask, null)); } /// <summary> /// Tests <see cref="IComputeClient.ExecuteJavaTask{TRes}"/> with no-result-cache flag. /// </summary> [Test] public void TestExecuteJavaTaskWithNoResultCache() { var computeWithCache = Client.GetCompute(); var computeWithNoCache = Client.GetCompute().WithNoResultCache(); Assert.IsTrue(computeWithCache.ExecuteJavaTask<bool>(TestResultCacheTask, null)); Assert.IsFalse(computeWithNoCache.ExecuteJavaTask<bool>(TestResultCacheTask, null)); } /// <summary> /// Tests <see cref="IComputeClient.ExecuteJavaTask{TRes}"/> with a user-defined timeout. /// </summary> [Test] public void TestExecuteJavaTaskWithTimeout() { const long timeoutMs = 50; var compute = Client.GetCompute().WithTimeout(TimeSpan.FromMilliseconds(timeoutMs)); var ex = Assert.Throws<AggregateException>(() => compute.ExecuteJavaTask<object>(TestTask, timeoutMs * 4)); var clientEx = (IgniteClientException) ex.GetInnermostException(); StringAssert.StartsWith("Task timed out (check logs for error messages):", clientEx.Message); } /// <summary> /// Tests that <see cref="IIgniteClient.GetCompute"/> always returns the same instance. /// </summary> [Test] public void TestGetComputeAlwaysReturnsSameInstance() { Assert.AreSame(Client.GetCompute(), Client.GetCompute()); } /// <summary> /// Tests <see cref="IComputeClient.ExecuteJavaTask{TRes}"/> with cancellation. /// </summary> [Test] public void TestExecuteJavaTaskAsyncCancellation() { const long delayMs = 10000; // GetActiveTaskFutures uses Task internally, so it always returns at least 1 future. var futs1 = GetActiveTaskFutures(); Assert.AreEqual(1, futs1.Length); // Start a long-running task and verify that 2 futures are active. var cts = new CancellationTokenSource(); var task = Client.GetCompute().ExecuteJavaTaskAsync<object>(TestTask, delayMs, cts.Token); var taskFutures = GetActiveTaskFutures(); TestUtils.WaitForTrueCondition(() => { taskFutures = GetActiveTaskFutures(); return taskFutures.Length == 2; }); // Cancel and assert that the future from the step above is no longer present. cts.Cancel(); Assert.IsTrue(task.IsCanceled); TestUtils.WaitForTrueCondition(() => { var futures = GetActiveTaskFutures(); return futures.Length == 1 && !taskFutures.Contains(futures[0]); }, message: "Unexpected number of active tasks: " + GetActiveTaskFutures().Length); } /// <summary> /// Tests that cancellation does not affect finished tasks. /// </summary> [Test] public void TestExecuteJavaTaskAsyncCancelAfterFinish() { const long delayMs = 1; var cts = new CancellationTokenSource(); var task = Client.GetCompute().ExecuteJavaTaskAsync<object>(TestTask, delayMs, cts.Token); task.Wait(cts.Token); cts.Cancel(); Assert.IsTrue(task.IsCompleted); Assert.IsFalse(task.IsFaulted); } /// <summary> /// Tests <see cref="IComputeClient.ExecuteJavaTask{TRes}"/> with custom cluster group. /// </summary> [Test] public void TestExecuteJavaTaskWithClusterGroup() { Func<IComputeClient, Guid[]> getProjection = c => { var res = c.ExecuteJavaTask<IgniteBiTuple>(TestTask, null); return ((ArrayList) res.Item2).OfType<Guid>().ToArray(); }; // Default: full cluster. var nodeIds = Client.GetCluster().GetNodes().Select(n => n.Id).ToArray(); CollectionAssert.AreEquivalent(nodeIds, getProjection(Client.GetCompute())); // One node. var nodeId = nodeIds[1]; var proj = Client.GetCluster().ForPredicate(n => n.Id == nodeId); Assert.AreEqual(new[]{nodeId}, getProjection(proj.GetCompute())); // Two nodes. proj = Client.GetCluster().ForPredicate(n => n.Id != nodeId); CollectionAssert.AreEquivalent(new[] {nodeIds[0], nodeIds[2]}, getProjection(proj.GetCompute())); } /// <summary> /// Tests <see cref="IComputeClient.ExecuteJavaTask{TRes}"/> with custom cluster group. /// </summary> [Test] public void TestExecuteJavaTaskWithMixedModifiers() { const long timeoutMs = 200; var cluster = Client.GetCluster(); var nodeId = cluster.GetNode().Id; var compute = cluster.ForPredicate(n => n.Id == nodeId) .GetCompute() .WithNoFailover() .WithKeepBinary() .WithTimeout(TimeSpan.FromMilliseconds(timeoutMs)); // KeepBinary. var res = compute.ExecuteJavaTask<IBinaryObject>( ComputeApiTest.EchoTask, ComputeApiTest.EchoTypeBinarizableJava); Assert.AreEqual(1, res.GetField<int>("field")); // Timeout. var ex = Assert.Throws<AggregateException>(() => compute.ExecuteJavaTask<object>(TestTask, timeoutMs * 3)); var clientEx = (IgniteClientException) ex.GetInnermostException(); StringAssert.StartsWith("Task timed out (check logs for error messages):", clientEx.Message); // Flags. Assert.IsFalse(compute.ExecuteJavaTask<bool>(TestFailoverTask, null)); Assert.IsFalse(compute.WithNoResultCache().ExecuteJavaTask<bool>(TestResultCacheTask, null)); // Cluster. var executedNodeIds = (ArrayList) compute.ExecuteJavaTask<IgniteBiTuple>(TestTask, null).Item2; Assert.AreEqual(nodeId, executedNodeIds.Cast<Guid>().Single()); } /// <summary> /// Tests <see cref="IComputeClient.ExecuteJavaTask{TRes}"/> with unknown task class. /// </summary> [Test] public void TestExecuteJavaTaskWithUnknownClass() { var ex = Assert.Throws<AggregateException>( () => Client.GetCompute().ExecuteJavaTask<int>("bad", null)); var innerEx = ex.GetInnermostException(); StringAssert.StartsWith( "Unknown task name or failed to auto-deploy task (was task (re|un)deployed?) [taskName=bad, ", innerEx.Message); } /// <summary> /// Tests <see cref="IComputeClient.ExecuteJavaTask{TRes}"/> with exceeded /// <see cref="ThinClientConfiguration.MaxActiveComputeTasksPerConnection"/>. /// </summary> [Test] public void TestExecuteJavaTaskWithExceededTaskLimit() { var compute = Client.GetCompute().WithKeepBinary(); var tasks = Enumerable .Range(1, MaxTasks * 2) .Select(_ => (Task) compute.ExecuteJavaTaskAsync<object>(TestTask, (long) 500)) .ToArray(); var ex = Assert.Throws<AggregateException>(() => Task.WaitAll(tasks)); var clientEx = (IgniteClientException) ex.GetInnermostException(); StringAssert.StartsWith("Active compute tasks per connection limit (8) exceeded", clientEx.Message); Assert.AreEqual(ClientStatusCode.TooManyComputeTasks, clientEx.StatusCode); } /// <summary> /// Tests <see cref="IComputeClient.ExecuteJavaTaskAsync{TRes}(string,object)"/> from multiple threads. /// </summary> [Test] public void TestExecuteJavaTaskAsyncMultithreaded() { var count = 10000; var compute = Client.GetCompute().WithKeepBinary(); var cache = Client.GetOrCreateCache<int, int>(TestUtils.TestName); cache[1] = 1; TestUtils.RunMultiThreaded(() => { while (true) { var arg = new PlatformComputeNetBinarizable { Field = Interlocked.Decrement(ref count) }; var res = compute.ExecuteJavaTask<int>(ComputeApiTest.BinaryArgTask, arg); Assert.AreEqual(arg.Field, res); // Perform other operations to mix notifications and responses. Assert.AreEqual(1, cache[1]); Assert.AreEqual(1, cache.GetAsync(1).Result); if (res < 0) { break; } } }, MaxTasks - 2); } /// <summary> /// Tests that <see cref="IComputeClient.ExecuteJavaTaskAsync{TRes}(string,object)"/> with a long-running job /// does not block other client operations. /// </summary> [Test] public void TestExecuteJavaTaskAsyncWithLongJobDoesNotBlockOtherOperations() { var task = Client.GetCompute().ExecuteJavaTaskAsync<object>(TestTask, (long) 500); Client.GetCacheNames(); Assert.IsFalse(task.IsCompleted); task.Wait(); } /// <summary> /// Tests that failed deserialization (caused by missing type) produces correct exception. /// </summary> [Test] public void TestExecuteJavaTaskWithFailedResultDeserializationProducesBinaryObjectException() { var ex = Assert.Throws<AggregateException>( () => Client.GetCompute().ExecuteJavaTask<object>( ComputeApiTest.EchoTask, ComputeApiTest.EchoTypeBinarizableJava)); var clientEx = (IgniteClientException) ex.GetInnermostException(); Assert.AreEqual("Failed to resolve Java class 'org.apache.ignite.platform.PlatformComputeJavaBinarizable'" + " in .NET [platformId=1, typeId=-422570294].", clientEx.Message); } /// <summary> /// Tests that client timeout can be shorter than task duration. /// </summary> [Test] public void TestClientTimeoutShorterThanTaskDuration() { const long timeoutMs = 300; var cfg = new IgniteClientConfiguration(GetClientConfiguration()) { SocketTimeout = TimeSpan.FromMilliseconds(timeoutMs) }; using (var client = Ignition.StartClient(cfg)) { var compute = client.GetCompute().WithKeepBinary(); var res = compute.ExecuteJavaTask<IgniteBiTuple>(TestTask, timeoutMs * 3); Assert.IsInstanceOf<Guid>(res.Item1); } } /** <inheritdoc /> */ protected override IgniteConfiguration GetIgniteConfiguration() { return new IgniteConfiguration(base.GetIgniteConfiguration()) { ClientConnectorConfiguration = new ClientConnectorConfiguration { ThinClientConfiguration = new ThinClientConfiguration { MaxActiveComputeTasksPerConnection = MaxTasks } } }; } /** <inheritdoc /> */ protected override IgniteClientConfiguration GetClientConfiguration() { return new IgniteClientConfiguration(base.GetClientConfiguration()) { SocketTimeout = TimeSpan.FromSeconds(3), EnablePartitionAwareness = false }; } /// <summary> /// Gets active task futures from all server nodes. /// </summary> private IgniteGuid[] GetActiveTaskFutures() { return Client.GetCompute().ExecuteJavaTask<IgniteGuid[]>(ActiveTaskFuturesTask, null); } } }
using UnityEngine; using System.Collections; namespace RootMotion.FinalIK { /// <summary> /// Using a spherical polygon to limit the range of rotation on universal and ball-and-socket joints. A reach cone is specified as a spherical polygon /// on the surface of a a reach sphere that defines all positions the longitudinal segment axis beyond the joint can take. /// /// This class is based on the "Fast and Easy Reach-Cone Joint Limits" paper by Jane Wilhelms and Allen Van Gelder. /// Computer Science Dept., University of California, Santa Cruz, CA 95064. August 2, 2001 /// http://users.soe.ucsc.edu/~avg/Papers/jtl.pdf /// /// </summary> [HelpURL("http://www.root-motion.com/finalikdox/html/page12.html")] [AddComponentMenu("Scripts/RootMotion.FinalIK/Rotation Limits/Rotation Limit Polygonal")] public class RotationLimitPolygonal : RotationLimit { // Open the User Manual URL [ContextMenu("User Manual")] private void OpenUserManual() { Application.OpenURL("http://www.root-motion.com/finalikdox/html/page12.html"); } // Open the Script Reference URL [ContextMenu("Scrpt Reference")] private void OpenScriptReference() { Application.OpenURL("http://www.root-motion.com/finalikdox/html/class_root_motion_1_1_final_i_k_1_1_rotation_limit_polygonal.html"); } // Link to the Final IK Google Group [ContextMenu("Support Group")] void SupportGroup() { Application.OpenURL("https://groups.google.com/forum/#!forum/final-ik"); } // Link to the Final IK Asset Store thread in the Unity Community [ContextMenu("Asset Store Thread")] void ASThread() { Application.OpenURL("http://forum.unity3d.com/threads/final-ik-full-body-ik-aim-look-at-fabrik-ccd-ik-1-0-released.222685/"); } #region Main Interface /// <summary> /// Limit of twist rotation around the main axis. /// </summary> [Range(0f, 180f)] public float twistLimit = 180; /// <summary> /// The number of smoothing iterations applied to the polygon. /// </summary> [Range(0, 3)] public int smoothIterations = 0; /// <summary> /// Sets the limit points and recalculates the reach cones. /// </summary> /// <param name='_points'> /// _points. /// </param> public void SetLimitPoints(LimitPoint[] points) { if (points.Length < 3) { LogWarning("The polygon must have at least 3 Limit Points."); return; } this.points = points; BuildReachCones(); } #endregion Main Interface /* * Limits the rotation in the local space of this instance's Transform. * */ protected override Quaternion LimitRotation(Quaternion rotation) { if (reachCones.Length == 0) Start(); // Subtracting off-limits swing Quaternion swing = LimitSwing(rotation); // Apply twist limits return LimitTwist(swing, axis, secondaryAxis, twistLimit); } /* * Tetrahedron composed of 2 Limit points, the origin and an axis point. * */ [System.Serializable] public class ReachCone { public Vector3[] tetrahedron; public float volume; public Vector3 S, B; public Vector3 o { get { return tetrahedron[0]; }} public Vector3 a { get { return tetrahedron[1]; }} public Vector3 b { get { return tetrahedron[2]; }} public Vector3 c { get { return tetrahedron[3]; }} public ReachCone(Vector3 _o, Vector3 _a, Vector3 _b, Vector3 _c) { this.tetrahedron = new Vector3[4]; this.tetrahedron[0] = _o; // Origin this.tetrahedron[1] = _a; // Axis this.tetrahedron[2] = _b; // Limit Point 1 this.tetrahedron[3] = _c; // Limit Point 2 this.volume = 0; this.S = Vector3.zero; this.B = Vector3.zero; } public bool isValid { get { return volume > 0; }} public void Calculate() { Vector3 crossAB = Vector3.Cross(a, b); volume = Vector3.Dot(crossAB, c) / 6.0f; S = Vector3.Cross(a, b).normalized; B = Vector3.Cross(b, c).normalized; } } /* * The points defining the polygon * */ [System.Serializable] public class LimitPoint { public Vector3 point; public float tangentWeight; public LimitPoint() { this.point = Vector3.forward; this.tangentWeight = 1; } } [SerializeField][HideInInspector] public LimitPoint[] points; [SerializeField][HideInInspector] public Vector3[] P; [SerializeField][HideInInspector] public ReachCone[] reachCones = new ReachCone[0]; void Start() { if (points.Length < 3) ResetToDefault(); // Check if Limit Points are valid for (int i = 0; i < reachCones.Length; i++) { if (!reachCones[i].isValid) { if (smoothIterations <= 0) { int nextPoint = 0; if (i < reachCones.Length - 1) nextPoint = i + 1; else nextPoint = 0; LogWarning("Reach Cone {point " + i + ", point " + nextPoint + ", Origin} has negative volume. Make sure Axis vector is in the reachable area and the polygon is convex."); } else LogWarning("One of the Reach Cones in the polygon has negative volume. Make sure Axis vector is in the reachable area and the polygon is convex."); } } axis = axis.normalized; } #region Precalculations /* * Apply the default initial setup of 4 Limit Points * */ public void ResetToDefault() { points = new LimitPoint[4]; for (int i = 0; i < points.Length; i++) points[i] = new LimitPoint(); Quaternion swing1Rotation = Quaternion.AngleAxis(45, Vector3.right); Quaternion swing2Rotation = Quaternion.AngleAxis(45, Vector3.up); points[0].point = (swing1Rotation * swing2Rotation) * axis; points[1].point = (Quaternion.Inverse(swing1Rotation) * swing2Rotation) * axis; points[2].point = (Quaternion.Inverse(swing1Rotation) * Quaternion.Inverse(swing2Rotation)) * axis; points[3].point = (swing1Rotation * Quaternion.Inverse(swing2Rotation)) * axis; BuildReachCones(); } /* * Recalculate reach cones if the Limit Points have changed * */ public void BuildReachCones() { smoothIterations = Mathf.Clamp(smoothIterations, 0, 3); // Make another array for the points so that they could be smoothed without changing the initial points P = new Vector3[points.Length]; for (int i = 0; i < points.Length; i++) P[i] = points[i].point.normalized; for (int i = 0; i < smoothIterations; i++) P = SmoothPoints(); // Calculating the reach cones reachCones = new ReachCone[P.Length]; for (int i = 0; i < reachCones.Length - 1; i++) { reachCones[i] = new ReachCone(Vector3.zero, axis.normalized, P[i], P[i + 1]); } reachCones[P.Length - 1] = new ReachCone(Vector3.zero, axis.normalized, P[P.Length - 1], P[0]); for (int i = 0; i < reachCones.Length; i++) reachCones[i].Calculate(); } /* * Automatically adds virtual limit points to smooth the polygon * */ private Vector3[] SmoothPoints() { // Create the new point array with double length Vector3[] Q = new Vector3[P.Length * 2]; float scalar = GetScalar(P.Length); // Get the constant used for interpolation // Project all the existing points on a plane that is tangent to the unit sphere at the Axis point for (int i = 0; i < Q.Length; i+= 2) Q[i] = PointToTangentPlane(P[i / 2], 1); // Interpolate the new points for (int i = 1; i < Q.Length; i+= 2) { Vector3 minus2 = Vector3.zero; Vector3 plus1 = Vector3.zero; Vector3 plus2 = Vector3.zero; if (i > 1 && i < Q.Length - 2) { minus2 = Q[i - 2]; plus2 = Q[i + 1]; } else if (i == 1) { minus2 = Q[Q.Length - 2]; plus2 = Q[i + 1]; } else if (i == Q.Length - 1) { minus2 = Q[i - 2]; plus2 = Q[0]; } if (i < Q.Length - 1) plus1 = Q[i + 1]; else plus1 = Q[0]; int t = Q.Length / points.Length; // Interpolation Q[i] = (0.5f * (Q[i - 1] + plus1)) + (scalar * points[i / t].tangentWeight * (plus1 - minus2)) + (scalar * points[i / t].tangentWeight * (Q[i - 1] - plus2)); } // Project the points from tangent plane to the sphere for (int i = 0; i < Q.Length; i++) Q[i] = TangentPointToSphere(Q[i], 1); return Q; } /* * Returns scalar values used for interpolating smooth positions between limit points * */ private float GetScalar(int k) { // Values k (number of points) == 3, 4 and 6 are calculated by analytical geometry, values 5 and 7 were estimated by interpolation if (k <= 3) return .1667f; if (k == 4) return .1036f; if (k == 5) return .0850f; if (k == 6) return .0773f; if (k == 7) return .0700f; return .0625f; // Cubic spline fit } /* * Project a point on the sphere to a plane that is tangent to the unit sphere at the Axis point * */ private Vector3 PointToTangentPlane(Vector3 p, float r) { float d = Vector3.Dot(axis, p); float u = (2 * r * r) / ((r * r) + d); return (u * p) + ((1 - u) * -axis); } /* * Project a point on the tangent plane to the sphere * */ private Vector3 TangentPointToSphere(Vector3 q, float r) { float d = Vector3.Dot(q - axis, q - axis); float u = (4 * r * r) / ((4 * r * r) + d); return (u * q) + ((1 - u) * -axis); } #endregion Precalculations #region Runtime calculations /* * Applies Swing limit to the rotation * */ private Quaternion LimitSwing(Quaternion rotation) { if (rotation == Quaternion.identity) return rotation; // Assuming initial rotation is in the reachable area Vector3 L = rotation * axis; // Test this vector against the reach cones int r = GetReachCone(L); // Get the reach cone to test against (can be only 1) // Just in case we are running our application with invalid reach cones if (r == -1) { if (!Warning.logged) LogWarning("RotationLimitPolygonal reach cones are invalid."); return rotation; } // Dot product of cone normal and rotated axis float v = Vector3.Dot(reachCones[r].B, L); if (v > 0) return rotation; // Rotation is reachable // Find normal for a plane defined by origin, axis, and rotated axis Vector3 rotationNormal = Vector3.Cross(axis, L); // Find the line where this plane intersects with the reach cone plane L = Vector3.Cross(-reachCones[r].B, rotationNormal); // Rotation from current(illegal) swing rotation to the limited(legal) swing rotation Quaternion toLimits = Quaternion.FromToRotation(rotation * axis, L); // Subtract the illegal rotation return toLimits * rotation; } /* * Finding the reach cone to test against * */ private int GetReachCone(Vector3 L) { float p = 0; float p1 = Vector3.Dot(reachCones[0].S, L); for (int i = 0; i < reachCones.Length; i++) { p = p1; if (i < reachCones.Length - 1) p1 = Vector3.Dot(reachCones[i + 1].S, L); else p1 = Vector3.Dot(reachCones[0].S, L); if (p >= 0 && p1 < 0) return i; } return -1; } #endregion Runtime calculations } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.IO; using System.Text; using System.Xml.Schema; using System.Collections; using System.Diagnostics; using System.Threading.Tasks; namespace System.Xml { // // XmlCharCheckingWriter // internal partial class XmlCharCheckingWriter : XmlWrappingWriter { public override Task WriteDocTypeAsync(string name, string pubid, string sysid, string subset) { if (_checkNames) { ValidateQName(name); } if (_checkValues) { if (pubid != null) { int i; if ((i = _xmlCharType.IsPublicId(pubid)) >= 0) { throw XmlConvert.CreateInvalidCharException(pubid, i); } } if (sysid != null) { CheckCharacters(sysid); } if (subset != null) { CheckCharacters(subset); } } if (_replaceNewLines) { sysid = ReplaceNewLines(sysid); pubid = ReplaceNewLines(pubid); subset = ReplaceNewLines(subset); } return writer.WriteDocTypeAsync(name, pubid, sysid, subset); } public override Task WriteStartElementAsync(string prefix, string localName, string ns) { if (_checkNames) { if (localName == null || localName.Length == 0) { throw new ArgumentException(SR.Xml_EmptyLocalName); } ValidateNCName(localName); if (prefix != null && prefix.Length > 0) { ValidateNCName(prefix); } } return writer.WriteStartElementAsync(prefix, localName, ns); } protected internal override Task WriteStartAttributeAsync(string prefix, string localName, string ns) { if (_checkNames) { if (localName == null || localName.Length == 0) { throw new ArgumentException(SR.Xml_EmptyLocalName); } ValidateNCName(localName); if (prefix != null && prefix.Length > 0) { ValidateNCName(prefix); } } return writer.WriteStartAttributeAsync(prefix, localName, ns); } public override async Task WriteCDataAsync(string text) { if (text != null) { if (_checkValues) { CheckCharacters(text); } if (_replaceNewLines) { text = ReplaceNewLines(text); } int i; while ((i = text.IndexOf("]]>", StringComparison.Ordinal)) >= 0) { await writer.WriteCDataAsync(text.Substring(0, i + 2)).ConfigureAwait(false); text = text.Substring(i + 2); } } await writer.WriteCDataAsync(text).ConfigureAwait(false); } public override Task WriteCommentAsync(string text) { if (text != null) { if (_checkValues) { CheckCharacters(text); text = InterleaveInvalidChars(text, '-', '-'); } if (_replaceNewLines) { text = ReplaceNewLines(text); } } return writer.WriteCommentAsync(text); } public override Task WriteProcessingInstructionAsync(string name, string text) { if (_checkNames) { ValidateNCName(name); } if (text != null) { if (_checkValues) { CheckCharacters(text); text = InterleaveInvalidChars(text, '?', '>'); } if (_replaceNewLines) { text = ReplaceNewLines(text); } } return writer.WriteProcessingInstructionAsync(name, text); } public override Task WriteEntityRefAsync(string name) { if (_checkNames) { ValidateQName(name); } return writer.WriteEntityRefAsync(name); } public override Task WriteWhitespaceAsync(string ws) { if (ws == null) { ws = string.Empty; } // "checkNames" is intentional here; if false, the whitespaces are checked in XmlWellformedWriter if (_checkNames) { int i; if ((i = _xmlCharType.IsOnlyWhitespaceWithPos(ws)) != -1) { throw new ArgumentException(SR.Format(SR.Xml_InvalidWhitespaceCharacter, XmlException.BuildCharExceptionArgs(ws, i))); } } if (_replaceNewLines) { ws = ReplaceNewLines(ws); } return writer.WriteWhitespaceAsync(ws); } public override Task WriteStringAsync(string text) { if (text != null) { if (_checkValues) { CheckCharacters(text); } if (_replaceNewLines && WriteState != WriteState.Attribute) { text = ReplaceNewLines(text); } } return writer.WriteStringAsync(text); } public override Task WriteSurrogateCharEntityAsync(char lowChar, char highChar) { return writer.WriteSurrogateCharEntityAsync(lowChar, highChar); } public override Task WriteCharsAsync(char[] buffer, int index, int count) { if (buffer == null) { throw new ArgumentNullException("buffer"); } if (index < 0) { throw new ArgumentOutOfRangeException("index"); } if (count < 0) { throw new ArgumentOutOfRangeException("count"); } if (count > buffer.Length - index) { throw new ArgumentOutOfRangeException("count"); } if (_checkValues) { CheckCharacters(buffer, index, count); } if (_replaceNewLines && WriteState != WriteState.Attribute) { string text = ReplaceNewLines(buffer, index, count); if (text != null) { return WriteStringAsync(text); } } return writer.WriteCharsAsync(buffer, index, count); } public override Task WriteNmTokenAsync(string name) { if (_checkNames) { if (name == null || name.Length == 0) { throw new ArgumentException(SR.Xml_EmptyName); } XmlConvert.VerifyNMTOKEN(name); } return writer.WriteNmTokenAsync(name); } public override Task WriteNameAsync(string name) { if (_checkNames) { XmlConvert.VerifyQName(name, ExceptionType.XmlException); } return writer.WriteNameAsync(name); } public override Task WriteQualifiedNameAsync(string localName, string ns) { if (_checkNames) { ValidateNCName(localName); } return writer.WriteQualifiedNameAsync(localName, ns); } } }
//----------------------------------------------------------------------- // <copyright file="FieldData.cs" company="Marimer LLC"> // Copyright (c) Marimer LLC. All rights reserved. // Website: http://www.lhotka.net/cslanet/ // </copyright> // <summary>Contains a field value and related metadata.</summary> //----------------------------------------------------------------------- using System; using System.ComponentModel; using System.ComponentModel.DataAnnotations; namespace Csla.Core.FieldManager { /// <summary> /// Contains a field value and related metadata. /// </summary> /// <typeparam name="T">Type of field value contained.</typeparam> [Serializable()] public class FieldData<T> : IFieldData<T> { private string _name; private T _data; private bool _isDirty; /// <summary> /// Creates a new instance of the object. /// </summary> /// <param name="name"> /// Name of the field. /// </param> public FieldData(string name) { _name = name; } /// <summary> /// Gets the name of the field. /// </summary> public string Name { get { return _name; } } /// <summary> /// Gets or sets the value of the field. /// </summary> public virtual T Value { get { return _data; } set { _data = value; _isDirty = true; } } object IFieldData.Value { get { return this.Value; } set { if (value == null) this.Value = default(T); else this.Value = (T)value; } } bool ITrackStatus.IsDeleted { get { ITrackStatus child = _data as ITrackStatus; if (child != null) { return child.IsDeleted; } else { return false; } } } bool ITrackStatus.IsSavable { get { return true; } } bool ITrackStatus.IsChild { get { ITrackStatus child = _data as ITrackStatus; if (child != null) { return child.IsChild; } else { return false; } } } /// <summary> /// Gets a value indicating whether the field /// has been changed. /// </summary> public virtual bool IsSelfDirty { get { return IsDirty; } } /// <summary> /// Gets a value indicating whether the field /// has been changed. /// </summary> public virtual bool IsDirty { get { ITrackStatus child = _data as ITrackStatus; if (child != null) { return child.IsDirty; } else { return _isDirty; } } } /// <summary> /// Marks the field as unchanged. /// </summary> public virtual void MarkClean() { _isDirty = false; } bool ITrackStatus.IsNew { get { ITrackStatus child = _data as ITrackStatus; if (child != null) { return child.IsNew; } else { return false; } } } bool ITrackStatus.IsSelfValid { get { return IsValid; } } bool ITrackStatus.IsValid { get { return IsValid; } } /// <summary> /// Gets a value indicating whether this field /// is considered valid. /// </summary> protected virtual bool IsValid { get { ITrackStatus child = _data as ITrackStatus; if (child != null) { return child.IsValid; } else { return true; } } } #region INotifyBusy Members event BusyChangedEventHandler INotifyBusy.BusyChanged { add { throw new NotImplementedException(); } remove { throw new NotImplementedException(); } } /// <summary> /// Gets a value indicating whether this object or /// any of its child objects are busy. /// </summary> [Browsable(false)] [Display(AutoGenerateField = false)] #if !PCL46 && !PCL259 [System.ComponentModel.DataAnnotations.ScaffoldColumn(false)] #endif public bool IsBusy { get { bool isBusy = false; ITrackStatus child = _data as ITrackStatus; if (child != null) isBusy = child.IsBusy; return isBusy; } } bool INotifyBusy.IsSelfBusy { get { return IsBusy; } } #endregion #region INotifyUnhandledAsyncException Members [NotUndoable] [NonSerialized] private EventHandler<ErrorEventArgs> _unhandledAsyncException; /// <summary> /// Event indicating that an exception occurred on /// a background thread. /// </summary> public event EventHandler<ErrorEventArgs> UnhandledAsyncException { add { _unhandledAsyncException = (EventHandler<ErrorEventArgs>)Delegate.Combine(_unhandledAsyncException, value); } remove { _unhandledAsyncException = (EventHandler<ErrorEventArgs>)Delegate.Remove(_unhandledAsyncException, value); } } /// <summary> /// Raises the UnhandledAsyncException event. /// </summary> /// <param name="error">Exception that occurred on the background thread.</param> protected virtual void OnUnhandledAsyncException(ErrorEventArgs error) { if (_unhandledAsyncException != null) _unhandledAsyncException(this, error); } /// <summary> /// Raises the UnhandledAsyncException event. /// </summary> /// <param name="originalSender">Original source of the event.</param> /// <param name="error">Exception that occurred on the background thread.</param> protected void OnUnhandledAsyncException(object originalSender, Exception error) { OnUnhandledAsyncException(new ErrorEventArgs(originalSender, error)); } #endregion } }
// Copyright 2005-2010 Gallio Project - http://www.gallio.org/ // Portions Copyright 2000-2004 Jonathan de Halleux // // 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.Reflection; using System.Text; using Gallio.Common.Collections; using Gallio.Common; namespace Gallio.Common.Reflection.Impl { /// <summary> /// A <see cref="StaticReflectionPolicy"/> code element wrapper. /// </summary> public abstract class StaticCodeElementWrapper : StaticWrapper, ICodeElementInfo { private Memoizer<IEnumerable<IAttributeInfo>> allCustomAttributesMemoizer = new Memoizer<IEnumerable<IAttributeInfo>>(); /// <summary> /// Creates a wrapper. /// </summary> /// <param name="policy">The reflection policy.</param> /// <param name="handle">The underlying reflection object.</param> /// <exception cref="ArgumentNullException">Thrown if <paramref name="policy"/> or <paramref name="handle"/> is null.</exception> public StaticCodeElementWrapper(StaticReflectionPolicy policy, object handle) : base(policy, handle) { } /// <inheritdoc /> public abstract string Name { get; } /// <inheritdoc /> public abstract CodeElementKind Kind { get; } /// <inheritdoc /> public abstract CodeReference CodeReference { get; } /// <inheritdoc /> public IEnumerable<IAttributeInfo> GetAttributeInfos(ITypeInfo attributeType, bool inherit) { Dictionary<ITypeInfo, AttributeUsageAttribute> attributeUsages = inherit ? new Dictionary<ITypeInfo, AttributeUsageAttribute>() : null; // Yield all attributes declared by the member itself. // Keep track of which types were seen so we can resolve inherited but non-multiple attributes later. string qualifiedTypeName = attributeType != null ? attributeType.FullName : null; foreach (IAttributeInfo attribute in GetAllCustomAttributes()) { ITypeInfo type = attribute.Type; if (qualifiedTypeName == null || ReflectionUtils.IsDerivedFrom(type, qualifiedTypeName)) { yield return attribute; if (inherit) attributeUsages[type] = null; } } // Now loop over the inherited member declarations to find inherited attributes. // If we see an attribute of a kind we have seen before, then we check whether // multiple instances of it are allowed and discard it if not. if (inherit) { foreach (ICodeElementInfo inheritedMember in GetInheritedElements()) { foreach (IAttributeInfo attribute in inheritedMember.GetAttributeInfos(attributeType, false)) { ITypeInfo inheritedAttributeType = attribute.Type; AttributeUsageAttribute attributeUsage; bool seenBefore = attributeUsages.TryGetValue(inheritedAttributeType, out attributeUsage); if (attributeUsage == null) { attributeUsage = ReflectionPolicy.GetAttributeUsage(inheritedAttributeType); attributeUsages[inheritedAttributeType] = attributeUsage; } if (!attributeUsage.Inherited) continue; if (seenBefore && !attributeUsage.AllowMultiple) continue; yield return attribute; } } } } /// <inheritdoc /> public bool HasAttribute(ITypeInfo attributeType, bool inherit) { return GetAttributeInfos(attributeType, inherit).GetEnumerator().MoveNext(); } /// <inheritdoc /> public IEnumerable<object> GetAttributes(ITypeInfo attributeType, bool inherit) { return AttributeUtils.ResolveAttributes(GetAttributeInfos(attributeType, inherit)); } /// <inheritdoc /> public virtual string GetXmlDocumentation() { return null; } /// <inheritdoc /> public virtual CodeLocation GetCodeLocation() { return CodeLocation.Unknown; } /// <inheritdoc /> public bool Equals(ICodeElementInfo other) { return Equals((object)other); } /// <inheritdoc /> public override string ToString() { return Name; } /// <summary> /// Gets all attributes that appear on this code element, excluding inherited attributes. /// </summary> /// <returns>The attribute wrappers.</returns> protected abstract IEnumerable<StaticAttributeWrapper> GetCustomAttributes(); /// <summary> /// Gets all pseudo custom attributes associated with a member. /// </summary> /// <remarks> /// <para> /// These attributes do not really exist as custom attributes in the metadata. Rather, they are /// realizations of other metadata features in attribute form. For example, /// <see cref="SerializableAttribute" /> is represented in the metadata as a <see cref="TypeAttributes" /> /// flag. Pseudo custom attributes preserve the illusion of these attributes. /// </para> /// </remarks> /// <returns>The pseudo custom attributes.</returns> protected abstract IEnumerable<Attribute> GetPseudoCustomAttributes(); /// <summary> /// Gets an enumeration of elements from which this code element inherits. /// </summary> /// <returns>The inherited code elements.</returns> protected virtual IEnumerable<ICodeElementInfo> GetInheritedElements() { return EmptyArray<ICodeElementInfo>.Instance; } /// <summary> /// Appends a list of parameters to a signature. /// </summary> internal static void AppendParameterListToSignature(StringBuilder sig, IList<StaticParameterWrapper> parameters, bool isVarArgs) { for (int i = 0; i < parameters.Count; i++) { if (i != 0) sig.Append(@", "); sig.Append(GetTypeNameForSignature(parameters[i].ValueType)); } if (isVarArgs) sig.Append(@", ..."); } /// <summary> /// Appends a list of generic parameters to a signature. /// </summary> internal static void AppendGenericArgumentListToSignature(StringBuilder sig, IList<ITypeInfo> genericArguments) { if (genericArguments.Count != 0) { sig.Append('['); for (int i = 0; i < genericArguments.Count; i++) { if (i != 0) sig.Append(','); sig.Append(GetTypeNameForSignature(genericArguments[i])); } sig.Append(']'); } } /// <summary> /// Gets the name of a type for use in a ToString signature of an event, field, /// property, method, or constructor. /// </summary> internal static string GetTypeNameForSignature(ITypeInfo type) { return (ShouldUseShortNameForSignature(type) ? type.Name : type.ToString()).Replace("&", " ByRef"); } /// <summary> /// Determines whether a type should be represented by its short name /// for the purposes of creating a signature. /// </summary> /// <param name="type">The reflected type.</param> /// <returns>True if the type is primitive.</returns> private static bool ShouldUseShortNameForSignature(ITypeInfo type) { while (type.ElementType != null) type = type.ElementType; if (type.IsNested) return true; switch (type.FullName) { case "System.Boolean": case "System.Byte": case "System.Char": case "System.Double": case "System.Int16": case "System.Int32": case "System.Int64": case "System.SByte": case "System.Single": case "System.UInt16": case "System.UInt32": case "System.UInt64": case "System.IntPtr": case "System.UIntPtr": case "System.Void": return true; } return false; } private IEnumerable<IAttributeInfo> GetAllCustomAttributes() { return allCustomAttributesMemoizer.Memoize(() => { var attributes = new List<IAttributeInfo>(); foreach (StaticAttributeWrapper attributeWrapper in GetCustomAttributes()) attributes.Add(attributeWrapper); foreach (Attribute attribute in GetPseudoCustomAttributes()) attributes.Add(Reflector.Wrap(attribute)); return attributes; }); } } }
//////////////////////////////////////////////////////////////////////////////// // The MIT License (MIT) // // Copyright (c) 2020 Tim Stair // // 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.Drawing; using System.Linq; using System.Windows.Forms; namespace Support.UI { public class QueryPanelDialog : QueryPanel { private Form m_zForm; private int m_nMaxDesiredHeight = -1; private string m_sButtonPressed = string.Empty; public Form Form => m_zForm; /// <summary> /// Constructor /// </summary> /// <param name="sTitle">Title of the dialog</param> /// <param name="nWidth">Width of the dialog</param> /// <param name="bTabbed">Whether the panel should be tabbed</param> public QueryPanelDialog(string sTitle, int nWidth, bool bTabbed) : base(null, bTabbed) { InitForm(sTitle, nWidth, null, null); X_LABEL_SIZE = (int)((float)m_zPanel.Width * 0.25); } /// <summary> /// Constructor /// </summary> /// <param name="sTitle">Title of the dialog</param> /// <param name="nWidth">Width of the dialog</param> /// <param name="nLabelWidth">Width of labels</param> /// <param name="bTabbed">Flag indicating whether this should support tabs</param> public QueryPanelDialog(string sTitle, int nWidth, int nLabelWidth, bool bTabbed) : base(null, nLabelWidth, bTabbed) { InitForm(sTitle, nWidth, null, null); if (0 < nLabelWidth && nLabelWidth < m_zPanel.Width) { X_LABEL_SIZE = nLabelWidth; } } /// <summary> /// Constructor /// </summary> /// <param name="sTitle">Title of the dialog</param> /// <param name="nWidth">Width of the dialog</param> /// <param name="nLabelWidth">Width of labels</param> /// <param name="bTabbed">Flag indicating whether this should support tabs</param> /// <param name="arrayButtons">Array of button names to support</param> public QueryPanelDialog(string sTitle, int nWidth, int nLabelWidth, bool bTabbed, string[] arrayButtons) : base(null, nLabelWidth, bTabbed) { InitForm(sTitle, nWidth, arrayButtons, null); if (0 < nLabelWidth && nLabelWidth < m_zPanel.Width) { X_LABEL_SIZE = nLabelWidth; } } /// <summary> /// Constructor /// </summary> /// <param name="sTitle">Title of the dialog</param> /// <param name="nWidth">Width of the dialog</param> /// <param name="nLabelWidth">Width of labels</param> /// <param name="bTabbed">Flag indicating whether this should support tabs</param> /// <param name="arrayButtons">Array of button names to support</param> /// <param name="arrayHandlers">The handlers to associated with the buttons (order match with buttons, null is allowed for an event handler)</param> public QueryPanelDialog(string sTitle, int nWidth, int nLabelWidth, bool bTabbed, string[] arrayButtons, EventHandler[] arrayHandlers) : base(null, nLabelWidth, bTabbed) { InitForm(sTitle, nWidth, arrayButtons, arrayHandlers); if (0 < nLabelWidth && nLabelWidth < m_zPanel.Width) { X_LABEL_SIZE = nLabelWidth; } } /// <summary> /// Initializes the form associated with this QueryDialog /// </summary> /// <param name="sTitle">Title of the dialog</param> /// <param name="nWidth">Width of the dialog</param> /// <param name="arrayButtons">The names of the buttons to put on the dialog</param> /// <param name="arrayHandlers">event handlers for the buttons</param> private void InitForm(string sTitle, int nWidth, string[] arrayButtons, EventHandler[] arrayHandlers) { m_zForm = new Form { Size = new Size(nWidth, 300) }; Button btnDefault = null; // used to set the proper height of the internal panel // setup the buttons if (null == arrayButtons) { var btnCancel = new Button(); var btnOk = new Button(); btnOk.Click += btnOk_Click; btnCancel.Click += btnCancel_Click; btnOk.TabIndex = 65001; btnCancel.TabIndex = 65002; btnCancel.Text = "Cancel"; btnOk.Text = "OK"; btnCancel.Location = new Point((m_zForm.ClientSize.Width - (3 * X_CONTROL_BUFFER)) - btnCancel.Size.Width, (m_zForm.ClientSize.Height - Y_CONTROL_BUFFER) - btnCancel.Size.Height); btnOk.Location = new Point((btnCancel.Location.X - X_CONTROL_BUFFER) - btnOk.Size.Width, btnCancel.Location.Y); btnOk.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; btnCancel.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; m_zForm.AcceptButton = btnOk; m_zForm.CancelButton = btnCancel; m_zForm.Controls.Add(btnOk); m_zForm.Controls.Add(btnCancel); btnDefault = btnCancel; } else { Button btnPrevious = null; for (int nIdx = arrayButtons.Length - 1; nIdx > -1; nIdx--) { btnDefault = new Button(); var bHandlerSet = false; if (arrayHandlers?[nIdx] != null) { btnDefault.Click += arrayHandlers[nIdx]; bHandlerSet = true; } if (!bHandlerSet) { btnDefault.Click += btnGeneric_Click; } btnDefault.TabIndex = 65000 + nIdx; btnDefault.Text = arrayButtons[nIdx]; btnDefault.Location = null == btnPrevious ? new Point((m_zForm.ClientSize.Width - (3 * X_CONTROL_BUFFER)) - btnDefault.Size.Width, (m_zForm.ClientSize.Height - Y_CONTROL_BUFFER) - btnDefault.Size.Height) : new Point((btnPrevious.Location.X - X_CONTROL_BUFFER) - btnDefault.Size.Width, btnPrevious.Location.Y); btnDefault.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; m_zForm.Controls.Add(btnDefault); btnPrevious = btnDefault; } } // setup the form m_zForm.FormBorderStyle = FormBorderStyle.FixedSingle; m_zForm.MaximizeBox = false; m_zForm.MinimizeBox = false; m_zForm.Name = "QueryDialog"; m_zForm.ShowInTaskbar = false; m_zForm.SizeGripStyle = SizeGripStyle.Hide; m_zForm.StartPosition = FormStartPosition.CenterParent; m_zForm.Text = sTitle; m_zForm.Load += QueryDialog_Load; // setup the panel to contain the controls m_zPanel.Anchor = AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Top | AnchorStyles.Right; if (null != btnDefault) { m_zPanel.Size = new Size(m_zForm.ClientSize.Width, m_zForm.ClientSize.Height - (btnDefault.Size.Height + (2*Y_CONTROL_BUFFER))); } m_zPanel.AutoScroll = true; m_zPanel.Resize += m_zPanel_Resize; m_zForm.Controls.Add(m_zPanel); } void m_zPanel_Resize(object sender, EventArgs e) { SetupScrollState(m_zPanel); } /// <summary> /// Sets the title text of the dialog. /// </summary> /// <param name="sTitle"></param> public void SetTitleText(string sTitle) { m_zForm.Text = sTitle; } /// <summary> /// Flags the dialog to be shown in the task bar. /// </summary> /// <param name="bShow"></param> public void ShowInTaskBar(bool bShow) { m_zForm.ShowInTaskbar = bShow; } /// <summary> /// Allows the form to be resized. This should be used after all of the controls have been added to set the minimum size. /// </summary> public void AllowResize() { m_zForm.MaximizeBox = true; m_zForm.FormBorderStyle = FormBorderStyle.Sizable; } /// <summary> /// Sets the icon for the form /// </summary> /// <param name="zIcon">The icon to use for the dialog. If null is specified the icon is hidden.</param> public void SetIcon(Icon zIcon) { if (null == zIcon) { m_zForm.ShowIcon = false; } else { m_zForm.Icon = zIcon; } } /// <summary> /// Shows the dialog (much like the Form.ShowDialog method) /// </summary> /// <param name="zParentForm"></param> /// <returns></returns> public DialogResult ShowDialog(IWin32Window zParentForm) { return m_zForm.ShowDialog(zParentForm); } /// <summary> /// Returns the string on the button pressed on exit. /// </summary> /// <returns></returns> public string GetButtonPressedString() { return m_sButtonPressed; } #region Events /// <summary> /// Handles generic button presses (for those on the bottom of the dialog) /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnGeneric_Click(object sender, EventArgs e) { m_zForm.DialogResult = DialogResult.OK; m_sButtonPressed = ((Button)sender).Text; m_zForm.Close(); } /// <summary> /// Handles the Ok button press. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnOk_Click(object sender, EventArgs e) { m_zForm.DialogResult = DialogResult.OK; m_sButtonPressed = m_zForm.DialogResult.ToString(); } /// <summary> /// Handles the Cancel button press. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnCancel_Click(object sender, EventArgs e) { m_zForm.DialogResult = DialogResult.Cancel; m_sButtonPressed = m_zForm.DialogResult.ToString(); } /// <summary> /// Sets the max desired height for the dialog. /// </summary> /// <param name="nMaxHeight"></param> public void SetMaxHeight(int nMaxHeight) { m_nMaxDesiredHeight = nMaxHeight; } /// <summary> /// The dialog load event /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void QueryDialog_Load(object sender, EventArgs e) { if (null == m_zTabControl) { int nHeight = GetYPosition() + m_nButtonHeight + (Y_CONTROL_BUFFER * 2); if (m_nMaxDesiredHeight > 0) { if (nHeight > m_nMaxDesiredHeight) { nHeight = m_nMaxDesiredHeight; } } m_zForm.ClientSize = new Size(m_zForm.ClientSize.Width, nHeight); } else { var nLargestHeight = -1; foreach(var zPage in m_zTabControl.TabPages.OfType<TabPage>()) { if(nLargestHeight < (int)zPage.Tag) { nLargestHeight = (int)zPage.Tag; } } if (nLargestHeight > 0) { if (m_nMaxDesiredHeight > 0) { nLargestHeight = Math.Min(m_nMaxDesiredHeight, nLargestHeight); } // hard coded extra vertical space m_zForm.ClientSize = new Size(m_zForm.ClientSize.Width, nLargestHeight + 60); } } // add the panel controls after the client size has been set (adding them before displayed an odd issue with control anchor/size) FinalizeControls(); if (0 < m_zPanel.Controls.Count) { m_zPanel.SelectNextControl(m_zPanel.Controls[m_zPanel.Controls.Count - 1], true, true, true, true); } } #endregion } }
using System; using System.Collections.Generic; using Microsoft.Extensions.Logging; using Orleans.Configuration; using System.Threading.Tasks; using System.Threading; using Microsoft.Extensions.Options; using System.Linq; using Orleans.Internal; namespace Orleans.Runtime.MembershipService { /// <summary> /// Responsible for updating membership table with details about the local silo. /// </summary> internal class MembershipAgent : IHealthCheckParticipant, ILifecycleParticipant<ISiloLifecycle>, IDisposable, MembershipAgent.ITestAccessor { private readonly CancellationTokenSource cancellation = new CancellationTokenSource(); private readonly MembershipTableManager tableManager; private readonly ILocalSiloDetails localSilo; private readonly IFatalErrorHandler fatalErrorHandler; private readonly ClusterMembershipOptions clusterMembershipOptions; private readonly ILogger<MembershipAgent> log; private readonly IRemoteSiloProber siloProber; private readonly IAsyncTimer iAmAliveTimer; private Func<DateTime> getUtcDateTime = () => DateTime.UtcNow; public MembershipAgent( MembershipTableManager tableManager, ILocalSiloDetails localSilo, IFatalErrorHandler fatalErrorHandler, IOptions<ClusterMembershipOptions> options, ILogger<MembershipAgent> log, IAsyncTimerFactory timerFactory, IRemoteSiloProber siloProber) { this.tableManager = tableManager; this.localSilo = localSilo; this.fatalErrorHandler = fatalErrorHandler; this.clusterMembershipOptions = options.Value; this.log = log; this.siloProber = siloProber; this.iAmAliveTimer = timerFactory.Create( this.clusterMembershipOptions.IAmAliveTablePublishTimeout, nameof(UpdateIAmAlive)); } internal interface ITestAccessor { Action OnUpdateIAmAlive { get; set; } Func<DateTime> GetDateTime { get; set; } } Action ITestAccessor.OnUpdateIAmAlive { get; set; } Func<DateTime> ITestAccessor.GetDateTime { get => this.getUtcDateTime; set => this.getUtcDateTime = value ?? throw new ArgumentNullException(nameof(value)); } private async Task UpdateIAmAlive() { if (this.log.IsEnabled(LogLevel.Debug)) this.log.LogDebug("Starting periodic membership liveness timestamp updates"); try { TimeSpan? onceOffDelay = default; while (await this.iAmAliveTimer.NextTick(onceOffDelay) && !this.tableManager.CurrentStatus.IsTerminating()) { onceOffDelay = default; try { var stopwatch = ValueStopwatch.StartNew(); ((ITestAccessor)this).OnUpdateIAmAlive?.Invoke(); await this.tableManager.UpdateIAmAlive(); if (this.log.IsEnabled(LogLevel.Trace)) this.log.LogTrace("Updating IAmAlive took {Elapsed}", stopwatch.Elapsed); } catch (Exception exception) { this.log.LogError( (int)ErrorCode.MembershipUpdateIAmAliveFailure, "Failed to update table entry for this silo, will retry shortly: {Exception}", exception); // Retry quickly onceOffDelay = TimeSpan.FromMilliseconds(200); } } } catch (Exception exception) when (this.fatalErrorHandler.IsUnexpected(exception)) { this.log.LogError("Error updating liveness timestamp: {Exception}", exception); this.fatalErrorHandler.OnFatalException(this, nameof(UpdateIAmAlive), exception); } finally { if (this.log.IsEnabled(LogLevel.Debug)) this.log.LogDebug("Stopping periodic membership liveness timestamp updates"); } } private async Task BecomeActive() { this.log.LogInformation( (int)ErrorCode.MembershipBecomeActive, "-BecomeActive"); if (this.clusterMembershipOptions.ValidateInitialConnectivity) { await this.ValidateInitialConnectivity(); } else { this.log.LogWarning( (int)ErrorCode.MembershipSendingPreJoinPing, $"{nameof(ClusterMembershipOptions)}.{nameof(ClusterMembershipOptions.ValidateInitialConnectivity)} is set to false. This is NOT recommended for a production environment."); } try { await this.UpdateStatus(SiloStatus.Active); this.log.LogInformation( (int)ErrorCode.MembershipFinishBecomeActive, "-Finished BecomeActive."); } catch (Exception exception) { this.log.LogInformation( (int)ErrorCode.MembershipFailedToBecomeActive, "BecomeActive failed: {Exception}", exception); throw; } } private async Task ValidateInitialConnectivity() { // Continue attempting to validate connectivity until some reasonable timeout. var maxAttemptTime = this.clusterMembershipOptions.ProbeTimeout.Multiply(5.0 * this.clusterMembershipOptions.NumMissedProbesLimit); var attemptNumber = 1; var now = this.getUtcDateTime(); var attemptUntil = now + maxAttemptTime; var canContinue = true; while (true) { try { var activeSilos = new List<SiloAddress>(); foreach (var item in this.tableManager.MembershipTableSnapshot.Entries) { var entry = item.Value; if (entry.Status != SiloStatus.Active) continue; if (entry.SiloAddress.IsSameLogicalSilo(this.localSilo.SiloAddress)) continue; if (entry.HasMissedIAmAlivesSince(this.clusterMembershipOptions, now) != default) continue; activeSilos.Add(entry.SiloAddress); } var failedSilos = await CheckClusterConnectivity(activeSilos.ToArray()); var successfulSilos = activeSilos.Where(s => !failedSilos.Contains(s)).ToList(); // If there were no failures, terminate the loop and return without error. if (failedSilos.Count == 0) break; this.log.LogError( (int)ErrorCode.MembershipJoiningPreconditionFailure, "Failed to get ping responses from {FailedCount} of {ActiveCount} active silos. " + "Newly joining silos validate connectivity with all active silos that have recently updated their 'I Am Alive' value before joining the cluster. " + "Successfully contacted: {SuccessfulSilos}. Silos which did not respond successfully are: {FailedSilos}. " + "Will continue attempting to validate connectivity until {Timeout}. Attempt #{Attempt}", failedSilos.Count, activeSilos.Count, Utils.EnumerableToString(successfulSilos), Utils.EnumerableToString(failedSilos), attemptUntil, attemptNumber); if (now + TimeSpan.FromSeconds(5) > attemptUntil) { canContinue = false; var msg = $"Failed to get ping responses from {failedSilos.Count} of {activeSilos.Count} active silos. " + "Newly joining silos validate connectivity with all active silos that have recently updated their 'I Am Alive' value before joining the cluster. " + $"Successfully contacted: {Utils.EnumerableToString(successfulSilos)}. Failed to get response from: {Utils.EnumerableToString(failedSilos)}"; throw new OrleansClusterConnectivityCheckFailedException(msg); } // Refresh membership after some delay and retry. await Task.Delay(TimeSpan.FromSeconds(5)); await this.tableManager.Refresh(); } catch (Exception exception) when (canContinue) { this.log.LogError("Failed to validate initial cluster connectivity: {Exception}", exception); await Task.Delay(TimeSpan.FromSeconds(1)); } ++attemptNumber; now = this.getUtcDateTime(); } async Task<List<SiloAddress>> CheckClusterConnectivity(SiloAddress[] members) { if (members.Length == 0) return new List<SiloAddress>(); var tasks = new List<Task<bool>>(members.Length); this.log.LogInformation( (int)ErrorCode.MembershipSendingPreJoinPing, "About to send pings to {Count} nodes in order to validate communication in the Joining state. Pinged nodes = {Nodes}", members.Length, Utils.EnumerableToString(members)); var timeout = this.clusterMembershipOptions.ProbeTimeout; foreach (var silo in members) { tasks.Add(ProbeSilo(this.siloProber, silo, timeout, this.log)); } try { await Task.WhenAll(tasks); } catch { // Ignore exceptions for now. } var failed = new List<SiloAddress>(); for (var i = 0; i < tasks.Count; i++) { if (tasks[i].Status != TaskStatus.RanToCompletion || !tasks[i].GetAwaiter().GetResult()) { failed.Add(members[i]); } } return failed; } static async Task<bool> ProbeSilo(IRemoteSiloProber siloProber, SiloAddress silo, TimeSpan timeout, ILogger log) { Exception exception; try { using var cancellation = new CancellationTokenSource(timeout); var probeTask = siloProber.Probe(silo, 0); var cancellationTask = cancellation.Token.WhenCancelled(); var completedTask = await Task.WhenAny(probeTask, cancellationTask).ConfigureAwait(false); if (ReferenceEquals(completedTask, probeTask)) { cancellation.Cancel(); if (probeTask.IsFaulted) { exception = probeTask.Exception; } else if (probeTask.Status == TaskStatus.RanToCompletion) { return true; } else { exception = null; } } else { exception = null; } } catch (Exception ex) { exception = ex; } log.LogWarning(exception, "Did not receive a probe response from silo {SiloAddress} in timeout {Timeout}", silo.ToString(), timeout); return false; } } private async Task BecomeJoining() { this.log.Info(ErrorCode.MembershipJoining, "-Joining"); try { await this.UpdateStatus(SiloStatus.Joining); } catch (Exception exc) { this.log.Error(ErrorCode.MembershipFailedToJoin, "Error updating status to Joining", exc); throw; } } private async Task BecomeShuttingDown() { this.log.Info(ErrorCode.MembershipShutDown, "-Shutdown"); try { await this.UpdateStatus(SiloStatus.ShuttingDown); } catch (Exception exc) { this.log.Error(ErrorCode.MembershipFailedToShutdown, "Error updating status to ShuttingDown", exc); throw; } } private async Task BecomeStopping() { log.Info(ErrorCode.MembershipStop, "-Stop"); try { await this.UpdateStatus(SiloStatus.Stopping); } catch (Exception exc) { log.Error(ErrorCode.MembershipFailedToStop, "Error updating status to Stopping", exc); throw; } } private async Task BecomeDead() { this.log.LogInformation( (int)ErrorCode.MembershipKillMyself, "Updating status to Dead"); try { await this.UpdateStatus(SiloStatus.Dead); } catch (Exception exception) { this.log.LogError( (int)ErrorCode.MembershipFailedToKillMyself, "Failure updating status to " + nameof(SiloStatus.Dead) + ": {Exception}", exception); throw; } } private async Task UpdateStatus(SiloStatus status) { await this.tableManager.UpdateStatus(status); } void ILifecycleParticipant<ISiloLifecycle>.Participate(ISiloLifecycle lifecycle) { { Task OnRuntimeInitializeStart(CancellationToken ct) => Task.CompletedTask; async Task OnRuntimeInitializeStop(CancellationToken ct) { this.iAmAliveTimer.Dispose(); this.cancellation.Cancel(); await Task.WhenAny( Task.Run(() => this.BecomeDead()), Task.Delay(TimeSpan.FromMinutes(1))); } lifecycle.Subscribe( nameof(MembershipAgent), ServiceLifecycleStage.RuntimeInitialize + 1, // Gossip before the outbound queue gets closed OnRuntimeInitializeStart, OnRuntimeInitializeStop); } { async Task AfterRuntimeGrainServicesStart(CancellationToken ct) { await Task.Run(() => this.BecomeJoining()); } Task AfterRuntimeGrainServicesStop(CancellationToken ct) => Task.CompletedTask; lifecycle.Subscribe( nameof(MembershipAgent), ServiceLifecycleStage.AfterRuntimeGrainServices, AfterRuntimeGrainServicesStart, AfterRuntimeGrainServicesStop); } { var tasks = new List<Task>(); async Task OnBecomeActiveStart(CancellationToken ct) { await Task.Run(() => this.BecomeActive()); tasks.Add(Task.Run(() => this.UpdateIAmAlive())); } async Task OnBecomeActiveStop(CancellationToken ct) { this.iAmAliveTimer.Dispose(); this.cancellation.Cancel(throwOnFirstException: false); var cancellationTask = ct.WhenCancelled(); if (ct.IsCancellationRequested) { await Task.Run(() => this.BecomeStopping()); } else { // Allow some minimum time for graceful shutdown. var gracePeriod = Task.WhenAll(Task.Delay(ClusterMembershipOptions.ClusteringShutdownGracePeriod), cancellationTask); var task = await Task.WhenAny(gracePeriod, this.BecomeShuttingDown()); if (ReferenceEquals(task, gracePeriod)) { this.log.LogWarning("Graceful shutdown aborted: starting ungraceful shutdown"); await Task.Run(() => this.BecomeStopping()); } else { await Task.WhenAny(gracePeriod, Task.WhenAll(tasks)); } } } lifecycle.Subscribe( nameof(MembershipAgent), ServiceLifecycleStage.BecomeActive, OnBecomeActiveStart, OnBecomeActiveStop); } } public void Dispose() { this.iAmAliveTimer.Dispose(); } bool IHealthCheckable.CheckHealth(DateTime lastCheckTime, out string reason) => this.iAmAliveTimer.CheckHealth(lastCheckTime, out reason); } }
#region Copyright /*Copyright (C) 2015 Konstantin Udilovich Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #endregion using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using Kodestruct.Common.Mathematics; using Kodestruct.Loads.ASCE.ASCE7_10.WindLoads.Building.DirectionalProcedure; using Kodestruct.Loads.ASCE7.Entities; using Kodestruct.Loads.Properties; using MoreLinq; namespace Kodestruct.Loads.ASCE7.ASCE7_10.Wind { public partial class WindStructureGeneral : BuildingDirectionalProcedureElement { /// <summary> /// Calculates coefficient C_f for freestanding walls and signs /// </summary> /// <param name="h">Sign height</param> /// <param name="B">Horizontal dimension of sign, in feet</param> /// <param name="s">vertical dimension of the sign, in feet </param> /// <param name="epsion_s">ratio of solid area to gross area</param> /// <param name="x">horizontal distance from windward edge</param> /// <param name="L">Length of return wall</param> /// <param name="LoadCase">Case A, B or C</param> /// <returns></returns> public double GetWallOrSignPressureCoefficient(double h, double B, double s, double epsion_s, double x = 0, double L = 0, FreestandingWallLoadCase LoadCase = FreestandingWallLoadCase.C) { throw new NotImplementedException(); double C_f = 0.0; if (LoadCase == FreestandingWallLoadCase.A || LoadCase == FreestandingWallLoadCase.B) { C_f = GetCoefficientCaseAB(h, B, s, epsion_s); } else if (LoadCase == FreestandingWallLoadCase.C) { C_f = GetCoefficientCaseC(h, B, s, epsion_s, x, L); } else { throw new NotImplementedException(); } Quad q = new Quad(); } private double GetCoefficientCaseC(double h, double B, double s, double epsion_s, double x, double L) { throw new NotImplementedException(); } private double GetCoefficientCaseAB(double h, double B, double s, double epsion_s) { throw new NotImplementedException(); //using (StringReader reader = new StringReader(Resources.ASCE7_10Figure29_4_1SignsCaseAB)) //{ // List<double> B_sRatios = GetColumnHeaders(reader); // List<double> s_hRatios = GetRowHeaders(reader); // List<List<double>> Data = GetData(reader); // double ColumnValue = B / s; // double RowValue = s / h; // Quad ValueQuad = GetQuad(ColumnValue, RowValue,B_sRatios,s_hRatios, Data); // return (double)ValueQuad.GetInterpolatedValue((decimal)ColumnValue, (decimal)RowValue); //} } private Quad GetQuad(double ColumnValue, double RowValue, List<double> ColumnHeaders, List<double> RowHeaders, List<List<double>> Data) { //check for boundaries double ColumnLeft, ColumnRight, RowAbove, RowBelow; int columnLeftIndex, columnRightIndex, rowAboveIndex, rowBelowIndex; if (RowHeaders.Count != Data.Count || ColumnHeaders.Count!=Data[0].Count) { throw new Exception("Inconsistent data. Row or column headers do not match data."); } //SPECIAL CASES: coumn or row value out of range //---------------------------------------------------- if (ColumnValue < ColumnHeaders[0] || ColumnValue > ColumnHeaders[ColumnHeaders.Count - 1] || RowValue < RowHeaders[0] || RowValue > RowHeaders[RowHeaders.Count - 1]) { if (ColumnValue < ColumnHeaders[0] || ColumnValue > ColumnHeaders[ColumnHeaders.Count - 1]) { if (ColumnValue < ColumnHeaders[0]) { columnLeftIndex = 0; columnRightIndex = 0; } else // if ( ColumnValue > ColumnHeaders[ColumnHeaders.Count - 1]) { columnLeftIndex = ColumnHeaders.Count - 1; columnRightIndex = ColumnHeaders.Count - 1; } //Find low and high ROW values RowAbove = RowHeaders.Where(rv => rv <= RowValue).Max(); rowAboveIndex = RowHeaders.LastIndexOf(RowAbove); RowBelow = RowHeaders.Where(rv => rv >= RowValue).Min(); rowBelowIndex = RowHeaders.LastIndexOf(RowBelow); } else //if (RowValue < RowHeaders[0] || RowValue > RowHeaders[RowHeaders.Count - 1]) { if (RowValue < RowHeaders[0]) { rowAboveIndex = 0; rowBelowIndex = 0; } else //if (RowValue > RowHeaders[RowHeaders.Count-1]) { rowAboveIndex = RowHeaders.Count - 1; rowBelowIndex = RowHeaders.Count - 1; } //Find low and high COLUMN values ColumnLeft = ColumnHeaders.Where(cv => cv <= ColumnValue).Max(); columnLeftIndex = RowHeaders.LastIndexOf(ColumnLeft); ColumnRight = ColumnHeaders.Where(cv => cv >= ColumnValue).Min(); columnRightIndex = RowHeaders.LastIndexOf(ColumnRight); } } else { //Interpolated value within data table // REGULAR CASE //---------------------------------------------------- List<List<DataPoint2D>> DataPoints = new List<List<DataPoint2D>>(); //Create array of datapoints for (int i = 0; i < RowHeaders.Count; i++) { int j = 0; List<DataPoint2D> thisRowOfPoints = new List<DataPoint2D>(); foreach (var item in Data[i]) { thisRowOfPoints.Add(new DataPoint2D((decimal)ColumnHeaders[j], (decimal)RowHeaders[i], (decimal)Data[i][j])); } DataPoints.Add(thisRowOfPoints); } ColumnLeft = ColumnHeaders.Where(cv => cv <= ColumnValue).Max(); columnLeftIndex = ColumnHeaders.FindIndex( x => x==ColumnLeft); ColumnRight= ColumnHeaders.Where(cv => cv >= ColumnValue).Min(); columnRightIndex = ColumnHeaders.FindIndex(x => x ==ColumnRight); RowAbove = RowHeaders.Where(cv => cv <= RowValue).Max(); rowAboveIndex = RowHeaders.FindIndex(x => x==RowAbove); RowBelow = RowHeaders.Where(cv => cv >= RowValue).Min(); rowBelowIndex = RowHeaders.FindIndex(x => x ==RowBelow); } DataPoint2D lowerLeftPoint = new DataPoint2D((decimal)ColumnHeaders[columnLeftIndex], (decimal)RowHeaders[rowBelowIndex], (decimal)Data[rowBelowIndex][columnLeftIndex]); DataPoint2D lowerRightPoint = new DataPoint2D((decimal)ColumnHeaders[columnRightIndex],(decimal)RowHeaders[rowBelowIndex], (decimal)Data[rowBelowIndex][columnRightIndex]); DataPoint2D upperLeftPoint = new DataPoint2D((decimal)ColumnHeaders[columnLeftIndex], (decimal)RowHeaders[rowAboveIndex], (decimal)Data[rowAboveIndex][columnLeftIndex]); DataPoint2D upperRightPoint = new DataPoint2D((decimal)ColumnHeaders[columnRightIndex],(decimal)RowHeaders[rowAboveIndex], (decimal)Data[rowAboveIndex][columnRightIndex]); Quad q = new Quad() { LowerLeftPoint = lowerLeftPoint, LowerRightPoint = lowerRightPoint, UpperLeftPoint = upperLeftPoint, UpperRightPoint = upperRightPoint }; return q; } private List<List<double>> GetData(StringReader reader) { throw new NotImplementedException(); } private List<double> GetRowHeaders(StringReader reader) { throw new NotImplementedException(); } private List<double> GetColumnHeaders(StringReader reader) { throw new NotImplementedException(); } } }
// // Copyright 2011-2013, Xamarin 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. // using Plugin.Geolocator.Abstractions; using System; using System.Threading.Tasks; using Android.Locations; using System.Threading; using Android.App; using Android.OS; using System.Linq; using Android.Content; using Android.Content.PM; using Plugin.Permissions; namespace Plugin.Geolocator { /// <summary> /// Implementation for Feature /// </summary> public class GeolocatorImplementation : IGeolocator { /// <summary> /// Default constructor /// </summary> public GeolocatorImplementation() { DesiredAccuracy = 100; manager = (LocationManager)Application.Context.GetSystemService(Context.LocationService); providers = manager.GetProviders(enabledOnly: false).Where(s => s != LocationManager.PassiveProvider).ToArray(); } /// <inheritdoc/> public event EventHandler<PositionErrorEventArgs> PositionError; /// <inheritdoc/> public event EventHandler<PositionEventArgs> PositionChanged; /// <inheritdoc/> public bool IsListening { get { return listener != null; } } /// <inheritdoc/> public double DesiredAccuracy { get; set; } /// <inheritdoc/> public bool AllowsBackgroundUpdates { get; set; } /// <inheritdoc/> public bool PausesLocationUpdatesAutomatically { get; set; } /// <inheritdoc/> public bool SupportsHeading { get { return true; //Kind of, you should use the Compass plugin for better results } } /// <inheritdoc/> public bool IsGeolocationAvailable { get { return providers.Length > 0; } } /// <inheritdoc/> public bool IsGeolocationEnabled { get { return providers.Any(manager.IsProviderEnabled); } } /// <inheritdoc/> public async Task<Position> GetPositionAsync(int timeoutMilliseconds = Timeout.Infinite, CancellationToken? cancelToken = null, bool includeHeading = false) { var status = await CrossPermissions.Current.CheckPermissionStatusAsync(Permissions.Abstractions.Permission.Location).ConfigureAwait(false); if (status != Permissions.Abstractions.PermissionStatus.Granted) { Console.WriteLine("Currently does not have Location permissions, requesting permissions"); var request = await CrossPermissions.Current.RequestPermissionsAsync(Permissions.Abstractions.Permission.Location); if (request[Permissions.Abstractions.Permission.Location] != Permissions.Abstractions.PermissionStatus.Granted) { Console.WriteLine("Location permission denied, can not get positions async."); return null; } providers = manager.GetProviders(enabledOnly: false).Where(s => s != LocationManager.PassiveProvider).ToArray(); } if (providers.Length == 0) { providers = manager.GetProviders(enabledOnly: false).Where(s => s != LocationManager.PassiveProvider).ToArray(); } if (timeoutMilliseconds <= 0 && timeoutMilliseconds != Timeout.Infinite) throw new ArgumentOutOfRangeException("timeoutMilliseconds", "timeout must be greater than or equal to 0"); if (!cancelToken.HasValue) cancelToken = CancellationToken.None; var tcs = new TaskCompletionSource<Position>(); if (!IsListening) { GeolocationSingleListener singleListener = null; singleListener = new GeolocationSingleListener((float)DesiredAccuracy, timeoutMilliseconds, providers.Where(manager.IsProviderEnabled), finishedCallback: () => { for (int i = 0; i < providers.Length; ++i) manager.RemoveUpdates(singleListener); }); if (cancelToken != CancellationToken.None) { cancelToken.Value.Register(() => { singleListener.Cancel(); for (int i = 0; i < providers.Length; ++i) manager.RemoveUpdates(singleListener); }, true); } try { Looper looper = Looper.MyLooper() ?? Looper.MainLooper; int enabled = 0; for (int i = 0; i < providers.Length; ++i) { if (manager.IsProviderEnabled(providers[i])) enabled++; manager.RequestLocationUpdates(providers[i], 0, 0, singleListener, looper); } if (enabled == 0) { for (int i = 0; i < providers.Length; ++i) manager.RemoveUpdates(singleListener); tcs.SetException(new GeolocationException(GeolocationError.PositionUnavailable)); return await tcs.Task.ConfigureAwait(false); } } catch (Java.Lang.SecurityException ex) { tcs.SetException(new GeolocationException(GeolocationError.Unauthorized, ex)); return await tcs.Task.ConfigureAwait(false); } return await singleListener.Task.ConfigureAwait(false); } // If we're already listening, just use the current listener lock (positionSync) { if (lastPosition == null) { if (cancelToken != CancellationToken.None) { cancelToken.Value.Register(() => tcs.TrySetCanceled()); } EventHandler<PositionEventArgs> gotPosition = null; gotPosition = (s, e) => { tcs.TrySetResult(e.Position); PositionChanged -= gotPosition; }; PositionChanged += gotPosition; } else { tcs.SetResult(lastPosition); } } return await tcs.Task.ConfigureAwait(false); } /// <inheritdoc/> public async Task<bool> StartListeningAsync(int minTime, double minDistance, bool includeHeading = false) { var status = await CrossPermissions.Current.CheckPermissionStatusAsync(Permissions.Abstractions.Permission.Location).ConfigureAwait(false); if (status != Permissions.Abstractions.PermissionStatus.Granted) { Console.WriteLine("Currently does not have Location permissions, requesting permissions"); var request = await CrossPermissions.Current.RequestPermissionsAsync(Permissions.Abstractions.Permission.Location); if (request[Permissions.Abstractions.Permission.Location] != Permissions.Abstractions.PermissionStatus.Granted) { Console.WriteLine("Location permission denied, can not get positions async."); return false; } providers = manager.GetProviders(enabledOnly: false).Where(s => s != LocationManager.PassiveProvider).ToArray(); } if (providers.Length == 0) { providers = manager.GetProviders(enabledOnly: false).Where(s => s != LocationManager.PassiveProvider).ToArray(); } if (minTime < 0) throw new ArgumentOutOfRangeException("minTime"); if (minDistance < 0) throw new ArgumentOutOfRangeException("minDistance"); if (IsListening) throw new InvalidOperationException("This Geolocator is already listening"); listener = new GeolocationContinuousListener(manager, TimeSpan.FromMilliseconds(minTime), providers); listener.PositionChanged += OnListenerPositionChanged; listener.PositionError += OnListenerPositionError; Looper looper = Looper.MyLooper() ?? Looper.MainLooper; for (int i = 0; i < providers.Length; ++i) manager.RequestLocationUpdates(providers[i], minTime, (float)minDistance, listener, looper); return true; } /// <inheritdoc/> public Task<bool> StopListeningAsync() { if (listener == null) return Task.FromResult(true); listener.PositionChanged -= OnListenerPositionChanged; listener.PositionError -= OnListenerPositionError; for (int i = 0; i < providers.Length; ++i) manager.RemoveUpdates(listener); listener = null; return Task.FromResult(true); } private string[] providers; private readonly LocationManager manager; private string headingProvider; private GeolocationContinuousListener listener; private readonly object positionSync = new object(); private Position lastPosition; /// <inheritdoc/> private void OnListenerPositionChanged(object sender, PositionEventArgs e) { if (!IsListening) // ignore anything that might come in afterwards return; lock (positionSync) { lastPosition = e.Position; var changed = PositionChanged; if (changed != null) changed(this, e); } } /// <inheritdoc/> private async void OnListenerPositionError(object sender, PositionErrorEventArgs e) { await StopListeningAsync(); var error = PositionError; if (error != null) error(this, e); } private static readonly DateTime Epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); internal static DateTimeOffset GetTimestamp(Location location) { return new DateTimeOffset(Epoch.AddMilliseconds(location.Time)); } } }
// 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.Reflection.Metadata { public enum ILOpCode : ushort { Nop = 0x00, Break = 0x01, Ldarg_0 = 0x02, Ldarg_1 = 0x03, Ldarg_2 = 0x04, Ldarg_3 = 0x05, Ldloc_0 = 0x06, Ldloc_1 = 0x07, Ldloc_2 = 0x08, Ldloc_3 = 0x09, Stloc_0 = 0x0a, Stloc_1 = 0x0b, Stloc_2 = 0x0c, Stloc_3 = 0x0d, Ldarg_s = 0x0e, Ldarga_s = 0x0f, Starg_s = 0x10, Ldloc_s = 0x11, Ldloca_s = 0x12, Stloc_s = 0x13, Ldnull = 0x14, Ldc_i4_m1 = 0x15, Ldc_i4_0 = 0x16, Ldc_i4_1 = 0x17, Ldc_i4_2 = 0x18, Ldc_i4_3 = 0x19, Ldc_i4_4 = 0x1a, Ldc_i4_5 = 0x1b, Ldc_i4_6 = 0x1c, Ldc_i4_7 = 0x1d, Ldc_i4_8 = 0x1e, Ldc_i4_s = 0x1f, Ldc_i4 = 0x20, Ldc_i8 = 0x21, Ldc_r4 = 0x22, Ldc_r8 = 0x23, Dup = 0x25, Pop = 0x26, Jmp = 0x27, Call = 0x28, Calli = 0x29, Ret = 0x2a, Br_s = 0x2b, Brfalse_s = 0x2c, Brtrue_s = 0x2d, Beq_s = 0x2e, Bge_s = 0x2f, Bgt_s = 0x30, Ble_s = 0x31, Blt_s = 0x32, Bne_un_s = 0x33, Bge_un_s = 0x34, Bgt_un_s = 0x35, Ble_un_s = 0x36, Blt_un_s = 0x37, Br = 0x38, Brfalse = 0x39, Brtrue = 0x3a, Beq = 0x3b, Bge = 0x3c, Bgt = 0x3d, Ble = 0x3e, Blt = 0x3f, Bne_un = 0x40, Bge_un = 0x41, Bgt_un = 0x42, Ble_un = 0x43, Blt_un = 0x44, Switch = 0x45, Ldind_i1 = 0x46, Ldind_u1 = 0x47, Ldind_i2 = 0x48, Ldind_u2 = 0x49, Ldind_i4 = 0x4a, Ldind_u4 = 0x4b, Ldind_i8 = 0x4c, Ldind_i = 0x4d, Ldind_r4 = 0x4e, Ldind_r8 = 0x4f, Ldind_ref = 0x50, Stind_ref = 0x51, Stind_i1 = 0x52, Stind_i2 = 0x53, Stind_i4 = 0x54, Stind_i8 = 0x55, Stind_r4 = 0x56, Stind_r8 = 0x57, Add = 0x58, Sub = 0x59, Mul = 0x5a, Div = 0x5b, Div_un = 0x5c, Rem = 0x5d, Rem_un = 0x5e, And = 0x5f, Or = 0x60, Xor = 0x61, Shl = 0x62, Shr = 0x63, Shr_un = 0x64, Neg = 0x65, Not = 0x66, Conv_i1 = 0x67, Conv_i2 = 0x68, Conv_i4 = 0x69, Conv_i8 = 0x6a, Conv_r4 = 0x6b, Conv_r8 = 0x6c, Conv_u4 = 0x6d, Conv_u8 = 0x6e, Callvirt = 0x6f, Cpobj = 0x70, Ldobj = 0x71, Ldstr = 0x72, Newobj = 0x73, Castclass = 0x74, Isinst = 0x75, Conv_r_un = 0x76, Unbox = 0x79, Throw = 0x7a, Ldfld = 0x7b, Ldflda = 0x7c, Stfld = 0x7d, Ldsfld = 0x7e, Ldsflda = 0x7f, Stsfld = 0x80, Stobj = 0x81, Conv_ovf_i1_un = 0x82, Conv_ovf_i2_un = 0x83, Conv_ovf_i4_un = 0x84, Conv_ovf_i8_un = 0x85, Conv_ovf_u1_un = 0x86, Conv_ovf_u2_un = 0x87, Conv_ovf_u4_un = 0x88, Conv_ovf_u8_un = 0x89, Conv_ovf_i_un = 0x8a, Conv_ovf_u_un = 0x8b, Box = 0x8c, Newarr = 0x8d, Ldlen = 0x8e, Ldelema = 0x8f, Ldelem_i1 = 0x90, Ldelem_u1 = 0x91, Ldelem_i2 = 0x92, Ldelem_u2 = 0x93, Ldelem_i4 = 0x94, Ldelem_u4 = 0x95, Ldelem_i8 = 0x96, Ldelem_i = 0x97, Ldelem_r4 = 0x98, Ldelem_r8 = 0x99, Ldelem_ref = 0x9a, Stelem_i = 0x9b, Stelem_i1 = 0x9c, Stelem_i2 = 0x9d, Stelem_i4 = 0x9e, Stelem_i8 = 0x9f, Stelem_r4 = 0xa0, Stelem_r8 = 0xa1, Stelem_ref = 0xa2, Ldelem = 0xa3, Stelem = 0xa4, Unbox_any = 0xa5, Conv_ovf_i1 = 0xb3, Conv_ovf_u1 = 0xb4, Conv_ovf_i2 = 0xb5, Conv_ovf_u2 = 0xb6, Conv_ovf_i4 = 0xb7, Conv_ovf_u4 = 0xb8, Conv_ovf_i8 = 0xb9, Conv_ovf_u8 = 0xba, Refanyval = 0xc2, Ckfinite = 0xc3, Mkrefany = 0xc6, Ldtoken = 0xd0, Conv_u2 = 0xd1, Conv_u1 = 0xd2, Conv_i = 0xd3, Conv_ovf_i = 0xd4, Conv_ovf_u = 0xd5, Add_ovf = 0xd6, Add_ovf_un = 0xd7, Mul_ovf = 0xd8, Mul_ovf_un = 0xd9, Sub_ovf = 0xda, Sub_ovf_un = 0xdb, Endfinally = 0xdc, Leave = 0xdd, Leave_s = 0xde, Stind_i = 0xdf, Conv_u = 0xe0, Arglist = 0xfe00, Ceq = 0xfe01, Cgt = 0xfe02, Cgt_un = 0xfe03, Clt = 0xfe04, Clt_un = 0xfe05, Ldftn = 0xfe06, Ldvirtftn = 0xfe07, Ldarg = 0xfe09, Ldarga = 0xfe0a, Starg = 0xfe0b, Ldloc = 0xfe0c, Ldloca = 0xfe0d, Stloc = 0xfe0e, Localloc = 0xfe0f, Endfilter = 0xfe11, Unaligned = 0xfe12, Volatile = 0xfe13, Tail = 0xfe14, Initobj = 0xfe15, Constrained = 0xfe16, Cpblk = 0xfe17, Initblk = 0xfe18, Rethrow = 0xfe1a, Sizeof = 0xfe1c, Refanytype = 0xfe1d, Readonly = 0xfe1e, } }
// // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. // using System; using System.Collections.Generic; using UnityEngine; using HoloToolkit.Unity; namespace HoloToolkit.Sharing.Spawning { /// <summary> /// Structure linking a prefab and a data model class. /// </summary> [Serializable] public struct PrefabToDataModel { // TODO Should this be a Type? Or at least have a custom editor to have a dropdown list public string DataModelClassName; public GameObject Prefab; } /// <summary> /// Spawn manager that creates a GameObject based on a prefab when a new /// SyncSpawnedObject is created in the data model. /// </summary> public class PrefabSpawnManager : SpawnManager<SyncSpawnedObject> { /// <summary> /// List of prefabs that can be spawned by this application. /// </summary> /// <remarks>It is assumed that this list is the same on all connected applications.</remarks> [SerializeField] private List<PrefabToDataModel> spawnablePrefabs = null; private Dictionary<string, GameObject> typeToPrefab; /// <summary> /// Counter used to create objects and make sure that no two objects created /// by the local application have the same name. /// </summary> private int objectCreationCounter; private void Awake() { InitializePrefabs(); } private void InitializePrefabs() { typeToPrefab = new Dictionary<string, GameObject>(spawnablePrefabs.Count); for (int i = 0; i < spawnablePrefabs.Count; i++) { typeToPrefab.Add(spawnablePrefabs[i].DataModelClassName, spawnablePrefabs[i].Prefab); } } protected override void InstantiateFromNetwork(SyncSpawnedObject spawnedObject) { GameObject prefab = GetPrefab(spawnedObject, null); if (!prefab) { return; } // Find the parent object GameObject parent = null; if (!string.IsNullOrEmpty(spawnedObject.ParentPath.Value)) { parent = GameObject.Find(spawnedObject.ParentPath.Value); if (parent == null) { Debug.LogErrorFormat("Parent object '{0}' could not be found to instantiate object.", spawnedObject.ParentPath); return; } } CreatePrefabInstance(spawnedObject, prefab, parent, spawnedObject.Name.Value); } protected override void RemoveFromNetwork(SyncSpawnedObject removedObject) { if (removedObject.GameObject != null) { Destroy(removedObject.GameObject); removedObject.GameObject = null; } } protected virtual string CreateInstanceName(string baseName) { string instanceName = string.Format("{0}{1}_{2}", baseName, objectCreationCounter.ToString(), NetworkManager.AppInstanceUniqueId); objectCreationCounter++; return instanceName; } protected virtual string GetPrefabLookupKey(SyncSpawnedObject dataModel, string baseName) { return dataModel.GetType().Name; } protected virtual GameObject GetPrefab(SyncSpawnedObject dataModel, string baseName) { GameObject prefabToSpawn; string dataModelTypeName = GetPrefabLookupKey(dataModel, baseName); if (dataModelTypeName == null || !typeToPrefab.TryGetValue(dataModelTypeName, out prefabToSpawn)) { Debug.LogErrorFormat("Trying to instantiate an object from unregistered data model {0}.", dataModelTypeName); return null; } return prefabToSpawn; } /// <summary> /// Spawns content with the given parent. If no parent is specified it will be parented to the spawn manager itself. /// </summary> /// <param name="dataModel">Data model to use for spawning.</param> /// <param name="localPosition">Local position for the new instance.</param> /// <param name="localRotation">Local rotation for the new instance.</param> /// <param name="localScale">optional local scale for the new instance. If not specified, uses the prefabs scale.</param> /// <param name="parent">Parent to assign to the object.</param> /// <param name="baseName">Base name to use to name the created game object.</param> /// <param name="isOwnedLocally"> /// Indicates if the spawned object is owned by this device or not. /// An object that is locally owned will be removed from the sync system when its owner leaves the session. /// </param> /// <returns>True if spawning succeeded, false if not.</returns> public bool Spawn(SyncSpawnedObject dataModel, Vector3 localPosition, Quaternion localRotation, Vector3? localScale, GameObject parent, string baseName, bool isOwnedLocally) { if (SyncSource == null) { Debug.LogError("Can't spawn an object: PrefabSpawnManager is not initialized."); return false; } if (dataModel == null) { Debug.LogError("Can't spawn an object: dataModel argument is null."); return false; } if (parent == null) { parent = gameObject; } // Validate that the prefab is valid GameObject prefabToSpawn = GetPrefab(dataModel, baseName); if (!prefabToSpawn) { return false; } // Get a name for the object to create string instanceName = CreateInstanceName(baseName); // Add the data model object to the networked array, for networking and history purposes dataModel.Initialize(instanceName, parent.transform.GetFullPath("/")); dataModel.Transform.Position.Value = localPosition; dataModel.Transform.Rotation.Value = localRotation; if (localScale.HasValue) { dataModel.Transform.Scale.Value = localScale.Value; } else { dataModel.Transform.Scale.Value = prefabToSpawn.transform.localScale; } User owner = null; if (isOwnedLocally) { owner = SharingStage.Instance.Manager.GetLocalUser(); } SyncSource.AddObject(dataModel, owner); return true; } /// <summary> /// Instantiate data model on the network with the given parent. If no parent is specified it will be parented to the spawn manager itself. /// </summary> /// <param name="dataModel">Data model to use for spawning.</param> /// <param name="localPosition">Local space position for the new instance.</param> /// <param name="localRotation">Local space rotation for the new instance.</param> /// <param name="parent">Parent to assign to the object.</param> /// <param name="baseName">Base name to use to name the created game object.</param> /// <param name="isOwnedLocally"> /// Indicates if the spawned object is owned by this device or not. /// An object that is locally owned will be removed from the sync system when its owner leaves the session. /// </param> /// <returns>True if the function succeeded, false if not.</returns> public bool Spawn(SyncSpawnedObject dataModel, Vector3 localPosition, Quaternion localRotation, GameObject parent, string baseName, bool isOwnedLocally) { return Spawn(dataModel, localPosition, localRotation, null, parent, baseName, isOwnedLocally); } protected override void SetDataModelSource() { SyncSource = NetworkManager.Root.InstantiatedPrefabs; } public override void Delete(SyncSpawnedObject objectToDelete) { SyncSource.RemoveObject(objectToDelete); } /// <summary> /// Create a prefab instance in the scene, in reaction to data being added to the data model. /// </summary> /// <param name="dataModel">Object to spawn's data model.</param> /// <param name="prefabToInstantiate">Prefab to instantiate.</param> /// <param name="parentObject">Parent object under which the prefab should be.</param> /// <param name="objectName">Name of the object.</param> /// <returns></returns> protected virtual GameObject CreatePrefabInstance(SyncSpawnedObject dataModel, GameObject prefabToInstantiate, GameObject parentObject, string objectName) { GameObject instance = Instantiate(prefabToInstantiate, dataModel.Transform.Position.Value, dataModel.Transform.Rotation.Value); instance.transform.localScale = dataModel.Transform.Scale.Value; instance.transform.SetParent(parentObject.transform, false); instance.gameObject.name = objectName; dataModel.GameObject = instance; // Set the data model on the various ISyncModelAccessor components of the spawned game obejct ISyncModelAccessor[] syncModelAccessors = instance.GetComponentsInChildren<ISyncModelAccessor>(true); if (syncModelAccessors.Length <= 0) { // If no ISyncModelAccessor component exists, create a default one that gives access to the SyncObject instance ISyncModelAccessor defaultAccessor = instance.EnsureComponent<DefaultSyncModelAccessor>(); defaultAccessor.SetSyncModel(dataModel); } for (int i = 0; i < syncModelAccessors.Length; i++) { syncModelAccessors[i].SetSyncModel(dataModel); } // Setup the transform synchronization TransformSynchronizer transformSynchronizer = instance.EnsureComponent<TransformSynchronizer>(); transformSynchronizer.TransformDataModel = dataModel.Transform; return instance; } } }
/* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for Additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ using NPOI.SS.UserModel; using System; using Spreadsheet=NPOI.OpenXmlFormats.Spreadsheet; using NPOI.OpenXmlFormats.Spreadsheet; using NPOI.OpenXmlFormats.Dml; using Dml = NPOI.OpenXmlFormats.Dml; using NPOI.XSSF.Model; namespace NPOI.XSSF.UserModel { /** * Represents a font used in a workbook. * * @author Gisella Bronzetti */ public class XSSFFont : IFont { /** * By default, Microsoft Office Excel 2007 uses the Calibry font in font size 11 */ public const String DEFAULT_FONT_NAME = "Calibri"; /** * By default, Microsoft Office Excel 2007 uses the Calibry font in font size 11 */ public const short DEFAULT_FONT_SIZE = 11; /** * Default font color is black * @see NPOI.SS.usermodel.IndexedColors#BLACK */ public static short DEFAULT_FONT_COLOR = IndexedColors.Black.Index; private ThemesTable _themes; private CT_Font _ctFont; private short _index; /** * Create a new XSSFFont * * @param font the underlying CT_Font bean */ public XSSFFont(CT_Font font) { _ctFont = font; _index = 0; } public XSSFFont(CT_Font font, int index) { _ctFont = font; _index = (short)index; } /** * Create a new XSSFont. This method is protected to be used only by XSSFWorkbook */ public XSSFFont() { this._ctFont = new CT_Font(); FontName = DEFAULT_FONT_NAME; FontHeight =DEFAULT_FONT_SIZE; } /** * get the underlying CT_Font font */ public CT_Font GetCTFont() { return _ctFont; } /** * get a bool value for the boldness to use. * * @return bool - bold */ public bool IsBold { get { CT_BooleanProperty bold = _ctFont.SizeOfBArray() == 0 ? null : _ctFont.GetBArray(0); return (bold != null && bold.val); } set { if (value) { CT_BooleanProperty ctBold = _ctFont.SizeOfBArray() == 0 ? _ctFont.AddNewB() : _ctFont.GetBArray(0); ctBold.val = value; } else { _ctFont.SetBArray(null); } } } /** * get character-set to use. * * @return int - character-set (0-255) * @see NPOI.SS.usermodel.FontCharset */ public short Charset { get { CT_IntProperty charset = _ctFont.sizeOfCharsetArray() == 0 ? null : _ctFont.GetCharsetArray(0); int val = charset == null ? FontCharset.ANSI.Value : FontCharset.ValueOf(charset.val).Value; return (short)val; } set { } } /** * get the indexed color value for the font * References a color defined in IndexedColors. * * @return short - indexed color to use * @see IndexedColors */ public short Color { get { Spreadsheet.CT_Color color = _ctFont.sizeOfColorArray() == 0 ? null : _ctFont.GetColorArray(0); if (color == null) return IndexedColors.Black.Index; if (!color.indexedSpecified) return IndexedColors.Black.Index; long index = color.indexed; if (index == XSSFFont.DEFAULT_FONT_COLOR) { return IndexedColors.Black.Index; } else if (index == IndexedColors.Red.Index) { return IndexedColors.Red.Index; } else { return (short)index; } } set { Spreadsheet.CT_Color ctColor = _ctFont.sizeOfColorArray() == 0 ? _ctFont.AddNewColor() : _ctFont.GetColorArray(0); switch (value) { case (short)FontColor.Normal: ctColor.indexed = (uint)(XSSFFont.DEFAULT_FONT_COLOR); ctColor.indexedSpecified = true; break; case (short)FontColor.Red: ctColor.indexed = (uint)(IndexedColors.Red.Index); ctColor.indexedSpecified = true; break; default: ctColor.indexed = (uint)(value); ctColor.indexedSpecified = true; break; } } } /** * get the color value for the font * References a color defined as Standard Alpha Red Green Blue color value (ARGB). * * @return XSSFColor - rgb color to use */ public XSSFColor GetXSSFColor() { Spreadsheet.CT_Color ctColor = _ctFont.sizeOfColorArray() == 0 ? null : _ctFont.GetColorArray(0); if (ctColor != null) { XSSFColor color = new XSSFColor(ctColor); if (_themes != null) { _themes.InheritFromThemeAsRequired(color); } return color; } else { return null; } } /** * get the color value for the font * References a color defined in theme. * * @return short - theme defined to use */ public short GetThemeColor() { Spreadsheet.CT_Color color = _ctFont.sizeOfColorArray() == 0 ? null : _ctFont.GetColorArray(0); long index = ((color == null) || !color.themeSpecified) ? 0 : color.theme; return (short)index; } /** * get the font height in point. * * @return short - height in point */ public double FontHeight { get { CT_FontSize size = _ctFont.sizeOfSzArray() == 0 ? null : _ctFont.GetSzArray(0); if (size != null) { double fontHeight = size.val; return (short)(fontHeight * 20); } return (short)(DEFAULT_FONT_SIZE * 20); } set { CT_FontSize fontSize = _ctFont.sizeOfSzArray() == 0 ? _ctFont.AddNewSz() : _ctFont.GetSzArray(0); fontSize.val = value; } } /** * @see #GetFontHeight() */ public short FontHeightInPoints { get { return (short)(FontHeight / 20); } set { CT_FontSize fontSize = _ctFont.sizeOfSzArray() == 0 ? _ctFont.AddNewSz() : _ctFont.GetSzArray(0); fontSize.val = value; } } /** * get the name of the font (i.e. Arial) * * @return String - a string representing the name of the font to use */ public String FontName { get { CT_FontName name = _ctFont.name; return name == null ? DEFAULT_FONT_NAME : name.val; } set { CT_FontName fontName = _ctFont.name==null?_ctFont.AddNewName():_ctFont.name; fontName.val = value == null ? DEFAULT_FONT_NAME : value; } } /** * get a bool value that specify whether to use italics or not * * @return bool - value for italic */ public bool IsItalic { get { CT_BooleanProperty italic = _ctFont.sizeOfIArray() == 0 ? null : _ctFont.GetIArray(0); return italic != null && italic.val; } set { if (value) { CT_BooleanProperty bool1 = _ctFont.sizeOfIArray() == 0 ? _ctFont.AddNewI() : _ctFont.GetIArray(0); bool1.val = value; } else { _ctFont.SetIArray(null); } } } /** * get a bool value that specify whether to use a strikeout horizontal line through the text or not * * @return bool - value for strikeout */ public bool IsStrikeout { get { CT_BooleanProperty strike = _ctFont.sizeOfStrikeArray() == 0 ? null : _ctFont.GetStrikeArray(0); return strike != null && strike.val; } set { if (!value) _ctFont.SetStrikeArray(null); else { CT_BooleanProperty strike = _ctFont.sizeOfStrikeArray() == 0 ? _ctFont.AddNewStrike() : _ctFont.GetStrikeArray(0); strike.val = value; } } } /** * get normal,super or subscript. * * @return short - offset type to use (none,super,sub) * @see Font#SS_NONE * @see Font#SS_SUPER * @see Font#SS_SUB */ public FontSuperScript TypeOffset { get { CT_VerticalAlignFontProperty vAlign = _ctFont.sizeOfVertAlignArray() == 0 ? null : _ctFont.GetVertAlignArray(0); if (vAlign == null) { return FontSuperScript.None; } ST_VerticalAlignRun val = vAlign.val; switch (val) { case ST_VerticalAlignRun.baseline: return FontSuperScript.None; case ST_VerticalAlignRun.subscript: return FontSuperScript.Sub; case ST_VerticalAlignRun.superscript: return FontSuperScript.Super; default: throw new POIXMLException("Wrong offset value " + val); } } set { if (value == (short)FontSuperScript.None) { _ctFont.SetVertAlignArray(null); } else { CT_VerticalAlignFontProperty offSetProperty = _ctFont.sizeOfVertAlignArray() == 0 ? _ctFont.AddNewVertAlign() : _ctFont.GetVertAlignArray(0); switch (value) { case FontSuperScript.None: offSetProperty.val = ST_VerticalAlignRun.baseline; break; case FontSuperScript.Sub: offSetProperty.val = ST_VerticalAlignRun.subscript; break; case FontSuperScript.Super: offSetProperty.val = ST_VerticalAlignRun.superscript; break; } } } } /** * get type of text underlining to use * * @return byte - underlining type * @see NPOI.SS.usermodel.FontUnderline */ public FontUnderlineType Underline { get { CT_UnderlineProperty underline = _ctFont.sizeOfUArray() == 0 ? null : _ctFont.GetUArray(0); if (underline != null) { FontUnderline val = FontUnderline.ValueOf((int)underline.val); return (FontUnderlineType)val.ByteValue; } return (FontUnderlineType)FontUnderline.NONE.ByteValue; } set { SetUnderline(value); } } /** * get the boldness to use * @return boldweight * @see #BOLDWEIGHT_NORMAL * @see #BOLDWEIGHT_BOLD */ public short Boldweight { get { return (IsBold ? (short)FontBoldWeight.Bold : (short)FontBoldWeight.Normal); } set { this.IsBold = (value == (short)FontBoldWeight.Bold); } } /** * set character-set to use. * * @param charset - charset * @see FontCharset */ public void SetCharSet(byte charSet) { int cs = (int)charSet; if (cs < 0) { cs += 256; } SetCharSet(cs); } /** * set character-set to use. * * @param charset - charset * @see FontCharset */ public void SetCharSet(int charset) { FontCharset FontCharset = FontCharset.ValueOf(charset); if (FontCharset != null) { SetCharSet(FontCharset); } else { throw new POIXMLException("Attention: an attempt to set a type of unknow charset and charSet"); } } /** * set character-set to use. * * @param charSet */ public void SetCharSet(FontCharset charset) { CT_IntProperty charSetProperty; if (_ctFont.sizeOfCharsetArray() == 0) { charSetProperty = _ctFont.AddNewCharset(); } else { charSetProperty = _ctFont.GetCharsetArray(0); } // We know that FontCharset only has valid entries in it, // so we can just set the int value from it charSetProperty.val = charset.Value; } /** * set the color for the font in Standard Alpha Red Green Blue color value * * @param color - color to use */ public void SetColor(XSSFColor color) { if (color == null) _ctFont.SetColorArray(null); else { Spreadsheet.CT_Color ctColor = _ctFont.sizeOfColorArray() == 0 ? _ctFont.AddNewColor() : _ctFont.GetColorArray(0); ctColor.SetRgb(color.RGB); } } /** * set the theme color for the font to use * * @param theme - theme color to use */ public void SetThemeColor(short theme) { Spreadsheet.CT_Color ctColor = _ctFont.sizeOfColorArray() == 0 ? _ctFont.AddNewColor() : _ctFont.GetColorArray(0); ctColor.theme = (uint)theme; } /** * set an enumeration representing the style of underlining that is used. * The none style is equivalent to not using underlining at all. * The possible values for this attribute are defined by the FontUnderline * * @param underline - FontUnderline enum value */ internal void SetUnderline(FontUnderlineType underline) { if (underline == FontUnderlineType.None) { _ctFont.SetUArray(null); } else { CT_UnderlineProperty ctUnderline = _ctFont.sizeOfUArray() == 0 ? _ctFont.AddNewU() : _ctFont.GetUArray(0); ST_UnderlineValues val = (ST_UnderlineValues)FontUnderline.ValueOf(underline).Value; ctUnderline.val = val; } } public override String ToString() { return _ctFont.ToString(); } ///** // * Perform a registration of ourselves // * to the style table // */ public long RegisterTo(StylesTable styles) { this._themes = styles.GetTheme(); short idx = (short)styles.PutFont(this, true); this._index = idx; return idx; } /** * Records the Themes Table that is associated with * the current font, used when looking up theme * based colours and properties. */ public void SetThemesTable(ThemesTable themes) { this._themes = themes; } /** * get the font scheme property. * is used only in StylesTable to create the default instance of font * * @return FontScheme * @see NPOI.XSSF.model.StylesTable#CreateDefaultFont() */ public FontScheme GetScheme() { NPOI.OpenXmlFormats.Spreadsheet.CT_FontScheme scheme = _ctFont.sizeOfSchemeArray() == 0 ? null : _ctFont.GetSchemeArray(0); return scheme == null ? FontScheme.NONE : FontScheme.ValueOf((int)scheme.val); } /** * set font scheme property * * @param scheme - FontScheme enum value * @see FontScheme */ public void SetScheme(FontScheme scheme) { NPOI.OpenXmlFormats.Spreadsheet.CT_FontScheme ctFontScheme = _ctFont.sizeOfSchemeArray() == 0 ? _ctFont.AddNewScheme() : _ctFont.GetSchemeArray(0); ST_FontScheme val = (ST_FontScheme)scheme.Value; ctFontScheme.val = val; } /** * get the font family to use. * * @return the font family to use * @see NPOI.SS.usermodel.FontFamily */ public int Family { get { CT_IntProperty family = _ctFont.sizeOfFamilyArray() == 0 ? _ctFont.AddNewFamily() : _ctFont.GetFamilyArray(0); return family == null ? FontFamily.NOT_APPLICABLE.Value : FontFamily.ValueOf(family.val).Value; } set { CT_IntProperty family = _ctFont.sizeOfFamilyArray() == 0 ? _ctFont.AddNewFamily() : _ctFont.GetFamilyArray(0); family.val = value; } } /** * set an enumeration representing the font family this font belongs to. * A font family is a set of fonts having common stroke width and serif characteristics. * * @param family font family * @link #SetFamily(int value) */ public void SetFamily(FontFamily family) { Family = family.Value; } /** * get the index within the XSSFWorkbook (sequence within the collection of Font objects) * @return unique index number of the underlying record this Font represents (probably you don't care * unless you're comparing which one is which) */ public short Index { get { return _index; } } public override int GetHashCode() { return _ctFont.ToString().GetHashCode(); } public override bool Equals(Object o) { if (!(o is XSSFFont)) return false; XSSFFont cf = (XSSFFont)o; return _ctFont.ToString().Equals(cf.GetCTFont().ToString()); } } }
//******************************************************************************************************************************************************************************************// // Public Domain // // // // Written by Peter O. in 2014. // // // // Any copyright is dedicated to the Public Domain. http://creativecommons.org/publicdomain/zero/1.0/ // // // // If you like this, you should donate to Peter O. at: http://peteroupc.github.io/ // //******************************************************************************************************************************************************************************************// using System; using System.IO; namespace Neos.IdentityServer.MultiFactor.WebAuthN.Library.Cbor { // <summary>A general-purpose character input for reading text from // byte streams and text strings. When reading byte streams, this // class supports the UTF-8 character encoding by default, but can be // configured to support UTF-16 and UTF-32 as well.</summary> internal sealed class CharacterReader : ICharacterInput { private readonly int mode; private readonly bool errorThrow; private readonly bool dontSkipUtf8Bom; private readonly string str; private readonly int strLength; private readonly IByteReader stream; private int offset; private ICharacterInput reader; // <summary>Initializes a new instance of the // <see cref='PeterO.Cbor.CharacterReader'/> class.</summary> // <param name='str'>The parameter <paramref name='str'/> is a text // string.</param> public CharacterReader(string str) : this(str, false, false) { } // <summary>Initializes a new instance of the // <see cref='PeterO.Cbor.CharacterReader'/> class.</summary> // <param name='str'>The parameter <paramref name='str'/> is a text // string.</param> // <param name='skipByteOrderMark'>If true and the first character in // the string is U+FEFF, skip that character.</param> // <exception cref='ArgumentNullException'>The parameter <paramref // name='str'/> is null.</exception> public CharacterReader(string str, bool skipByteOrderMark) : this(str, skipByteOrderMark, false) { } // <summary>Initializes a new instance of the // <see cref='PeterO.Cbor.CharacterReader'/> class.</summary> // <param name='str'>The parameter <paramref name='str'/> is a text // string.</param> // <param name='skipByteOrderMark'>If true and the first character in // the string is U+FEFF, skip that character.</param> // <param name='errorThrow'>When encountering invalid encoding, throw // an exception if this parameter is true, or replace it with U+FFFD // (replacement character) if this parameter is false.</param> // <exception cref='ArgumentNullException'>The parameter <paramref // name='str'/> is null.</exception> public CharacterReader( string str, bool skipByteOrderMark, bool errorThrow) { if (str == null) { throw new ArgumentNullException(nameof(str)); } this.strLength = str.Length; this.offset = (skipByteOrderMark && this.strLength > 0 && str[0] == 0xfeff) ? 1 : 0; this.str = str; this.errorThrow = errorThrow; this.mode = -1; this.dontSkipUtf8Bom = false; this.stream = null; } // <summary>Initializes a new instance of the // <see cref='PeterO.Cbor.CharacterReader'/> class.</summary> // <param name='str'>The parameter <paramref name='str'/> is a text // string.</param> // <param name='offset'>An index, starting at 0, showing where the // desired portion of <paramref name='str'/> begins.</param> // <param name='length'>The length, in code units, of the desired // portion of <paramref name='str'/> (but not more than <paramref // name='str'/> 's length).</param> // <exception cref='ArgumentException'>Either &#x22;offset&#x22; or // &#x22;length&#x22; is less than 0 or greater than // &#x22;str&#x22;&#x27;s length, or &#x22;str&#x22;&#x27;s length // minus &#x22;offset&#x22; is less than // &#x22;length&#x22;.</exception> // <exception cref='ArgumentNullException'>The parameter <paramref // name='str'/> is null.</exception> public CharacterReader(string str, int offset, int length) : this(str, offset, length, false, false) { } // <summary>Initializes a new instance of the // <see cref='PeterO.Cbor.CharacterReader'/> class.</summary> // <param name='str'>The parameter <paramref name='str'/> is a text // string.</param> // <param name='offset'>An index, starting at 0, showing where the // desired portion of <paramref name='str'/> begins.</param> // <param name='length'>The length, in code units, of the desired // portion of <paramref name='str'/> (but not more than <paramref // name='str'/> 's length).</param> // <param name='skipByteOrderMark'>If true and the first character in // the string portion is U+FEFF, skip that character.</param> // <param name='errorThrow'>When encountering invalid encoding, throw // an exception if this parameter is true, or replace it with U+FFFD // (replacement character) if this parameter is false.</param> // <exception cref='ArgumentNullException'>The parameter <paramref // name='str'/> is null.</exception> // <exception cref='ArgumentException'>Either <paramref // name='offset'/> or <paramref name='length'/> is less than 0 or // greater than <paramref name='str'/> 's length, or <paramref // name='str'/> 's length minus <paramref name='offset'/> is less than // <paramref name='length'/>.</exception> public CharacterReader( string str, int offset, int length, bool skipByteOrderMark, bool errorThrow) { if (str == null) { throw new ArgumentNullException(nameof(str)); } if (offset < 0) { throw new ArgumentException("offset(" + offset + ") is less than 0"); } if (offset > str.Length) { throw new ArgumentException("offset(" + offset + ") is more than " + str.Length); } if (length < 0) { throw new ArgumentException("length(" + length + ") is less than 0"); } if (length > str.Length) { throw new ArgumentException("length(" + length + ") is more than " + str.Length); } if (str.Length - offset < length) { throw new ArgumentException("str's length minus " + offset + "(" + (str.Length - offset) + ") is less than " + length); } this.strLength = length; this.offset = (skipByteOrderMark && length > 0 && str[offset] == 0xfeff) ? offset + 1 : 0; this.str = str; this.errorThrow = errorThrow; this.mode = -1; this.dontSkipUtf8Bom = false; this.stream = null; } // <summary>Initializes a new instance of the // <see cref='PeterO.Cbor.CharacterReader'/> class; will read the // stream as UTF-8, skip the byte-order mark (U+FEFF) if it appears // first in the stream, and replace invalid byte sequences with // replacement characters (U+FFFD).</summary> // <param name='stream'>A readable data stream.</param> // <exception cref='ArgumentNullException'>The parameter <paramref // name='stream'/> is null.</exception> public CharacterReader(Stream stream) : this(stream, 0, false) { } // <summary>Initializes a new instance of the // <see cref='PeterO.Cbor.CharacterReader'/> class; will skip the // byte-order mark (U+FEFF) if it appears first in the stream and a // UTF-8 stream is detected.</summary> // <param name='stream'>A readable data stream.</param> // <param name='mode'>The method to use when detecting encodings other // than UTF-8 in the byte stream. This usually involves checking // whether the stream begins with a byte-order mark (BOM, U+FEFF) or a // non-zero basic code point (U+0001 to U+007F) before reading the // rest of the stream. This value can be one of the following: // <list> // <item>0: UTF-8 only.</item> // <item>1: Detect UTF-16 using BOM or non-zero basic code point, // otherwise UTF-8.</item> // <item>2: Detect UTF-16/UTF-32 using BOM or non-zero basic code // point, otherwise UTF-8. (Tries to detect UTF-32 first.)</item> // <item>3: Detect UTF-16 using BOM, otherwise UTF-8.</item> // <item>4: Detect UTF-16/UTF-32 using BOM, otherwise UTF-8. (Tries to // detect UTF-32 first.)</item></list>.</param> // <param name='errorThrow'>When encountering invalid encoding, throw // an exception if this parameter is true, or replace it with U+FFFD // (replacement character) if this parameter is false.</param> public CharacterReader(Stream stream, int mode, bool errorThrow) : this(stream, mode, errorThrow, false) { } // <summary>Initializes a new instance of the // <see cref='PeterO.Cbor.CharacterReader'/> class; will skip the // byte-order mark (U+FEFF) if it appears first in the stream and // replace invalid byte sequences with replacement characters // (U+FFFD).</summary> // <param name='stream'>A readable byte stream.</param> // <param name='mode'>The method to use when detecting encodings other // than UTF-8 in the byte stream. This usually involves checking // whether the stream begins with a byte-order mark (BOM, U+FEFF) or a // non-zero basic code point (U+0001 to U+007F) before reading the // rest of the stream. This value can be one of the following: // <list> // <item>0: UTF-8 only.</item> // <item>1: Detect UTF-16 using BOM or non-zero basic code point, // otherwise UTF-8.</item> // <item>2: Detect UTF-16/UTF-32 using BOM or non-zero basic code // point, otherwise UTF-8. (Tries to detect UTF-32 first.)</item> // <item>3: Detect UTF-16 using BOM, otherwise UTF-8.</item> // <item>4: Detect UTF-16/UTF-32 using BOM, otherwise UTF-8. (Tries to // detect UTF-32 first.)</item></list>.</param> // <exception cref='ArgumentNullException'>The parameter <paramref // name='stream'/> is null.</exception> public CharacterReader(Stream stream, int mode) : this(stream, mode, false, false) { } // <summary>Initializes a new instance of the // <see cref='PeterO.Cbor.CharacterReader'/> class.</summary> // <param name='stream'>A readable byte stream.</param> // <param name='mode'>The method to use when detecting encodings other // than UTF-8 in the byte stream. This usually involves checking // whether the stream begins with a byte-order mark (BOM, U+FEFF) or a // non-zero basic code point (U+0001 to U+007F) before reading the // rest of the stream. This value can be one of the following: // <list> // <item>0: UTF-8 only.</item> // <item>1: Detect UTF-16 using BOM or non-zero basic code point, // otherwise UTF-8.</item> // <item>2: Detect UTF-16/UTF-32 using BOM or non-zero basic code // point, otherwise UTF-8. (Tries to detect UTF-32 first.)</item> // <item>3: Detect UTF-16 using BOM, otherwise UTF-8.</item> // <item>4: Detect UTF-16/UTF-32 using BOM, otherwise UTF-8. (Tries to // detect UTF-32 first.)</item></list>.</param> // <param name='errorThrow'>If true, will throw an exception if // invalid byte sequences (in the detected encoding) are found in the // byte stream. If false, replaces those byte sequences with // replacement characters (U+FFFD) as the stream is read.</param> // <param name='dontSkipUtf8Bom'>If the stream is detected as UTF-8 // (including when "mode" is 0) and this parameter is <c>true</c>, // won't skip the BOM character if it occurs at the start of the // stream.</param> // <exception cref='ArgumentNullException'>The parameter <paramref // name='stream'/> is null.</exception> public CharacterReader( Stream stream, int mode, bool errorThrow, bool dontSkipUtf8Bom) { if (stream == null) { throw new ArgumentNullException(nameof(stream)); } this.stream = new WrappedStream(stream); this.mode = mode; this.errorThrow = errorThrow; this.dontSkipUtf8Bom = dontSkipUtf8Bom; this.str = String.Empty; this.strLength = -1; } private interface IByteReader { int ReadByte(); } // <summary>Reads a series of code points from a Unicode stream or a // string.</summary> // <param name='chars'>An array where the code points that were read // will be stored.</param> // <param name='index'>An index starting at 0 showing where the // desired portion of <paramref name='chars'/> begins.</param> // <param name='length'>The number of elements in the desired portion // of <paramref name='chars'/> (but not more than <paramref // name='chars'/> 's length).</param> // <returns>The number of code points read from the stream. This can // be less than the <paramref name='length'/> parameter if the end of // the stream is reached.</returns> // <exception cref='ArgumentNullException'>The parameter <paramref // name='chars'/> is null.</exception> // <exception cref='ArgumentException'>Either <paramref name='index'/> // or <paramref name='length'/> is less than 0 or greater than // <paramref name='chars'/> 's length, or <paramref name='chars'/> 's // length minus <paramref name='index'/> is less than <paramref // name='length'/>.</exception> public int Read(int[] chars, int index, int length) { if (chars == null) { throw new ArgumentNullException(nameof(chars)); } if (index < 0) { throw new ArgumentException("index(" + index + ") is less than 0"); } if (index > chars.Length) { throw new ArgumentException("index(" + index + ") is more than " + chars.Length); } if (length < 0) { throw new ArgumentException("length(" + length + ") is less than 0"); } if (length > chars.Length) { throw new ArgumentException("length(" + length + ") is more than " + chars.Length); } if (chars.Length - index < length) { throw new ArgumentException("chars's length minus " + index + "(" + (chars.Length - index) + ") is less than " + length); } var count = 0; for (int i = 0; i < length; ++i) { int c = this.ReadChar(); if (c < 0) { return count; } chars[index + i] = c; ++count; } return count; } // <summary>Reads the next character from a Unicode stream or a // string.</summary> // <returns>The next character, or -1 if the end of the string or // stream was reached.</returns> public int ReadChar() { if (this.reader != null) { return this.reader.ReadChar(); } if (this.stream != null) { return this.DetectUnicodeEncoding(); } else { int c = (this.offset < this.strLength) ? this.str[this.offset] : -1; if ((c & 0xfc00) == 0xd800 && this.offset + 1 < this.strLength && this.str[this.offset + 1] >= 0xdc00 && this.str[this.offset + 1] <= 0xdfff) { // Get the Unicode code point for the surrogate pair c = 0x10000 + ((c & 0x3ff) << 10) + (this.str[this.offset + 1] & 0x3ff); ++this.offset; } else if ((c & 0xf800) == 0xd800) { // unpaired surrogate if (this.errorThrow) { throw new InvalidOperationException("Unpaired surrogate code" + "\u0020point"); } else { c = 0xfffd; } } ++this.offset; return c; } } private int DetectUtf8Or16Or32(int c1) { int c2, c3, c4; if (c1 == 0xff || c1 == 0xfe) { // Start of a possible byte-order mark // FF FE 0 0 --> UTF-32LE // FF FE ... --> UTF-16LE // FE FF --> UTF-16BE c2 = this.stream.ReadByte(); bool bigEndian = c1 == 0xfe; int otherbyte = bigEndian ? 0xff : 0xfe; if (c2 == otherbyte) { c3 = this.stream.ReadByte(); c4 = this.stream.ReadByte(); if (!bigEndian && c3 == 0 && c4 == 0) { this.reader = new Utf32Reader(this.stream, false, this.errorThrow); return this.reader.ReadChar(); } else { var newReader = new Utf16Reader( this.stream, bigEndian, this.errorThrow); newReader.Unget(c3, c4); this.reader = newReader; return newReader.ReadChar(); } } // Assume UTF-8 here, so the 0xff or 0xfe is invalid if (this.errorThrow) { throw new InvalidOperationException("Invalid Unicode stream"); } else { var utf8reader = new Utf8Reader(this.stream, this.errorThrow); utf8reader.Unget(c2); this.reader = utf8reader; return 0xfffd; } } else if (c1 == 0 && this.mode == 4) { // Here, the relevant cases are: // 0 0 0 NZA --> UTF-32BE (if mode is 4) // 0 0 FE FF --> UTF-32BE // Anything else is treated as UTF-8 c2 = this.stream.ReadByte(); c3 = this.stream.ReadByte(); c4 = this.stream.ReadByte(); if (c2 == 0 && ((c3 == 0xfe && c4 == 0xff) || (c3 == 0 && c4 >= 0x01 && c4 <= 0x7f))) { this.reader = new Utf32Reader(this.stream, true, this.errorThrow); return c3 == 0 ? c4 : this.reader.ReadChar(); } else { var utf8reader = new Utf8Reader(this.stream, this.errorThrow); utf8reader.UngetThree(c2, c3, c4); this.reader = utf8reader; return c1; } } else if (this.mode == 2) { if (c1 >= 0x01 && c1 <= 0x7f) { // Nonzero ASCII character c2 = this.stream.ReadByte(); if (c2 == 0) { // NZA 0, so UTF-16LE or UTF-32LE c3 = this.stream.ReadByte(); c4 = this.stream.ReadByte(); if (c3 == 0 && c4 == 0) { this.reader = new Utf32Reader( this.stream, false, this.errorThrow); return c1; } else { var newReader = new Utf16Reader( this.stream, false, this.errorThrow); newReader.Unget(c3, c4); this.reader = newReader; return c1; } } else { // NZA NZ, so UTF-8 var utf8reader = new Utf8Reader(this.stream, this.errorThrow); utf8reader.Unget(c2); this.reader = utf8reader; return c1; } } else if (c1 == 0) { // Zero c2 = this.stream.ReadByte(); if (c2 >= 0x01 && c2 <= 0x7f) { // 0 NZA, so UTF-16BE var newReader = new Utf16Reader( this.stream, true, this.errorThrow); this.reader = newReader; return c2; } else if (c2 == 0) { // 0 0, so maybe UTF-32BE c3 = this.stream.ReadByte(); c4 = this.stream.ReadByte(); if (c3 == 0 && c4 >= 0x01 && c4 <= 0x7f) { // 0 0 0 NZA this.reader = new Utf32Reader( this.stream, true, this.errorThrow); return c4; } else if (c3 == 0xfe && c4 == 0xff) { // 0 0 FE FF this.reader = new Utf32Reader( this.stream, true, this.errorThrow); return this.reader.ReadChar(); } else { // 0 0 ... var newReader = new Utf8Reader(this.stream, this.errorThrow); newReader.UngetThree(c2, c3, c4); this.reader = newReader; return c1; } } else { // 0 NonAscii, so UTF-8 var utf8reader = new Utf8Reader(this.stream, this.errorThrow); utf8reader.Unget(c2); this.reader = utf8reader; return c1; } } } // Use default of UTF-8 return -2; } private int DetectUtf8OrUtf16(int c1) { int mode = this.mode; int c2; if (c1 == 0xff || c1 == 0xfe) { c2 = this.stream.ReadByte(); bool bigEndian = c1 == 0xfe; int otherbyte = bigEndian ? 0xff : 0xfe; if (c2 == otherbyte) { var newReader = new Utf16Reader( this.stream, bigEndian, this.errorThrow); this.reader = newReader; return newReader.ReadChar(); } // Assume UTF-8 here, so the 0xff or 0xfe is invalid if (this.errorThrow) { throw new InvalidOperationException("Invalid Unicode stream"); } else { var utf8reader = new Utf8Reader(this.stream, this.errorThrow); utf8reader.Unget(c2); this.reader = utf8reader; return 0xfffd; } } else if (mode == 1) { if (c1 >= 0x01 && c1 <= 0x7f) { // Nonzero ASCII character c2 = this.stream.ReadByte(); if (c2 == 0) { // NZA 0, so UTF-16LE var newReader = new Utf16Reader( this.stream, false, this.errorThrow); this.reader = newReader; } else { // NZA NZ var utf8reader = new Utf8Reader(this.stream, this.errorThrow); utf8reader.Unget(c2); this.reader = utf8reader; } return c1; } else if (c1 == 0) { // Zero c2 = this.stream.ReadByte(); if (c2 >= 0x01 && c2 <= 0x7f) { // 0 NZA, so UTF-16BE var newReader = new Utf16Reader( this.stream, true, this.errorThrow); this.reader = newReader; return c2; } else { var utf8reader = new Utf8Reader(this.stream, this.errorThrow); utf8reader.Unget(c2); this.reader = utf8reader; return c1; } } } // Use default of UTF-8 return -2; } // Detects a Unicode encoding private int DetectUnicodeEncoding() { int mode = this.mode; int c1 = this.stream.ReadByte(); int c2; if (c1 < 0) { return -1; } Utf8Reader utf8reader; switch (mode) { case 0: // UTF-8 only utf8reader = new Utf8Reader(this.stream, this.errorThrow); this.reader = utf8reader; utf8reader.Unget(c1); c1 = utf8reader.ReadChar(); if (c1 == 0xfeff && !this.dontSkipUtf8Bom) { // Skip BOM c1 = utf8reader.ReadChar(); } return c1; case 1: case 3: c2 = this.DetectUtf8OrUtf16(c1); if (c2 >= -1) { return c2; } break; case 2: case 4: // UTF-8, UTF-16, or UTF-32 c2 = this.DetectUtf8Or16Or32(c1); if (c2 >= -1) { return c2; } break; } // Default case: assume UTF-8 utf8reader = new Utf8Reader(this.stream, this.errorThrow); this.reader = utf8reader; utf8reader.Unget(c1); c1 = utf8reader.ReadChar(); if (!this.dontSkipUtf8Bom && c1 == 0xfeff) { // Skip BOM c1 = utf8reader.ReadChar(); } return c1; } private sealed class SavedState { private int[] saved; private int savedLength; private void Ensure(int size) { this.saved = this.saved ?? (new int[this.savedLength + size]); if (this.savedLength + size < this.saved.Length) { var newsaved = new int[this.savedLength + size + 4]; Array.Copy(this.saved, 0, newsaved, 0, this.savedLength); this.saved = newsaved; } } public void AddOne(int a) { this.Ensure(1); this.saved[this.savedLength++] = a; } public void AddTwo(int a, int b) { this.Ensure(2); this.saved[this.savedLength + 1] = a; this.saved[this.savedLength] = b; this.savedLength += 2; } public void AddThree(int a, int b, int c) { this.Ensure(3); this.saved[this.savedLength + 2] = a; this.saved[this.savedLength + 1] = b; this.saved[this.savedLength] = c; this.savedLength += 3; } public int Read(IByteReader input) { if (this.savedLength > 0) { int ret = this.saved[--this.savedLength]; return ret; } return input.ReadByte(); } } private sealed class Utf16Reader : ICharacterInput { private readonly bool bigEndian; private readonly IByteReader stream; private readonly SavedState state; private readonly bool errorThrow; public Utf16Reader(IByteReader stream, bool bigEndian, bool errorThrow) { this.stream = stream; this.bigEndian = bigEndian; this.state = new SavedState(); this.errorThrow = errorThrow; } public void Unget(int c1, int c2) { this.state.AddTwo(c1, c2); } public int ReadChar() { int c1 = this.state.Read(this.stream); if (c1 < 0) { return -1; } int c2 = this.state.Read(this.stream); if (c2 < 0) { this.state.AddOne(-1); if (this.errorThrow) { throw new InvalidOperationException("Invalid UTF-16"); } else { return 0xfffd; } } c1 = this.bigEndian ? ((c1 << 8) | c2) : ((c2 << 8) | c1); int surr = c1 & 0xfc00; if (surr == 0xd800) { surr = c1; c1 = this.state.Read(this.stream); c2 = this.state.Read(this.stream); if (c1 < 0 || c2 < 0) { this.state.AddOne(-1); if (this.errorThrow) { throw new InvalidOperationException("Invalid UTF-16"); } else { return 0xfffd; } } int unit2 = this.bigEndian ? ((c1 << 8) | c2) : ((c2 << 8) | c1); if ((unit2 & 0xfc00) == 0xdc00) { return 0x10000 + ((surr & 0x3ff) << 10) + (unit2 & 0x3ff); } this.Unget(c1, c2); if (this.errorThrow) { throw new InvalidOperationException("Invalid UTF-16"); } else { return 0xfffd; } } if (surr == 0xdc00) { if (this.errorThrow) { throw new InvalidOperationException("Invalid UTF-16"); } else { return 0xfffd; } } return c1; } public int Read(int[] chars, int index, int length) { var count = 0; for (int i = 0; i < length; ++i) { int c = this.ReadChar(); if (c < 0) { return count; } chars[index + i] = c; ++count; } return count; } } private sealed class Utf32Reader : ICharacterInput { private readonly bool bigEndian; private readonly IByteReader stream; private readonly bool errorThrow; private readonly SavedState state; public Utf32Reader(IByteReader stream, bool bigEndian, bool errorThrow) { this.stream = stream; this.bigEndian = bigEndian; this.state = new SavedState(); this.errorThrow = errorThrow; } public int ReadChar() { int c1 = this.state.Read(this.stream); if (c1 < 0) { return -1; } int c2 = this.state.Read(this.stream); int c3 = this.state.Read(this.stream); int c4 = this.state.Read(this.stream); if (c2 < 0 || c3 < 0 || c4 < 0) { this.state.AddOne(-1); if (this.errorThrow) { throw new InvalidOperationException("Invalid UTF-32"); } else { return 0xfffd; } } c1 = this.bigEndian ? ((c1 << 24) | (c2 << 16) | (c3 << 8) | c4) : ((c4 << 24) | (c3 << 16) | (c2 << 8) | c1); if (c1 < 0 || c1 >= 0x110000 || (c1 & 0xfff800) == 0xd800) { if (this.errorThrow) { throw new InvalidOperationException("Invalid UTF-32"); } else { return 0xfffd; } } return c1; } public int Read(int[] chars, int index, int length) { var count = 0; for (int i = 0; i < length; ++i) { int c = this.ReadChar(); if (c < 0) { return count; } chars[index + i] = c; ++count; } return count; } } private sealed class Utf8Reader : ICharacterInput { private readonly IByteReader stream; private readonly SavedState state; private readonly bool errorThrow; private int lastChar; public Utf8Reader(IByteReader stream, bool errorThrow) { this.stream = stream; this.lastChar = -1; this.state = new SavedState(); this.errorThrow = errorThrow; } public void Unget(int ch) { this.state.AddOne(ch); } public void UngetThree(int a, int b, int c) { this.state.AddThree(a, b, c); } public int ReadChar() { var cp = 0; var bytesSeen = 0; var bytesNeeded = 0; var lower = 0; var upper = 0; while (true) { int b; if (this.lastChar != -1) { b = this.lastChar; this.lastChar = -1; } else { b = this.state.Read(this.stream); } if (b < 0) { if (bytesNeeded != 0) { bytesNeeded = 0; if (this.errorThrow) { throw new InvalidOperationException("Invalid UTF-8"); } else { return 0xfffd; } } return -1; } if (bytesNeeded == 0) { if ((b & 0x7f) == b) { return b; } if (b >= 0xc2 && b <= 0xdf) { bytesNeeded = 1; lower = 0x80; upper = 0xbf; cp = (b - 0xc0) << 6; } else if (b >= 0xe0 && b <= 0xef) { lower = (b == 0xe0) ? 0xa0 : 0x80; upper = (b == 0xed) ? 0x9f : 0xbf; bytesNeeded = 2; cp = (b - 0xe0) << 12; } else if (b >= 0xf0 && b <= 0xf4) { lower = (b == 0xf0) ? 0x90 : 0x80; upper = (b == 0xf4) ? 0x8f : 0xbf; bytesNeeded = 3; cp = (b - 0xf0) << 18; } else { if (this.errorThrow) { throw new InvalidOperationException("Invalid UTF-8"); } else { return 0xfffd; } } continue; } if (b < lower || b > upper) { cp = bytesNeeded = bytesSeen = 0; this.state.AddOne(b); if (this.errorThrow) { throw new InvalidOperationException("Invalid UTF-8"); } else { return 0xfffd; } } lower = 0x80; upper = 0xbf; ++bytesSeen; cp += (b - 0x80) << (6 * (bytesNeeded - bytesSeen)); if (bytesSeen != bytesNeeded) { continue; } int ret = cp; cp = 0; bytesSeen = 0; bytesNeeded = 0; return ret; } } public int Read(int[] chars, int index, int length) { var count = 0; for (int i = 0; i < length; ++i) { int c = this.ReadChar(); if (c < 0) { return count; } chars[index + i] = c; ++count; } return count; } } private sealed class WrappedStream : IByteReader { private readonly Stream stream; public WrappedStream(Stream stream) { this.stream = stream; } public int ReadByte() { try { return this.stream.ReadByte(); } catch (IOException ex) { throw new InvalidOperationException(ex.Message, ex); } } } } }
/* * 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 OpenSim 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.IO; using System.Net; using System.Text; using System.Xml; using System.Collections; using System.Collections.Generic; using System.Reflection; using System.Threading; using OpenMetaverse; using log4net; using Nini.Config; using Nwc.XmlRpc; using OpenSim.Framework; using OpenSim.Framework.Capabilities; using OpenSim.Framework.Servers; using OpenSim.Framework.Servers.HttpServer; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using Caps = OpenSim.Framework.Capabilities.Caps; namespace OpenSim.Region.OptionalModules.Avatar.Voice.VivoxVoice { public class VivoxVoiceModule : ISharedRegionModule { // channel distance model values public const int CHAN_DIST_NONE = 0; // no attenuation public const int CHAN_DIST_INVERSE = 1; // inverse distance attenuation public const int CHAN_DIST_LINEAR = 2; // linear attenuation public const int CHAN_DIST_EXPONENT = 3; // exponential attenuation public const int CHAN_DIST_DEFAULT = CHAN_DIST_LINEAR; // channel type values public static readonly string CHAN_TYPE_POSITIONAL = "positional"; public static readonly string CHAN_TYPE_CHANNEL = "channel"; public static readonly string CHAN_TYPE_DEFAULT = CHAN_TYPE_POSITIONAL; // channel mode values public static readonly string CHAN_MODE_OPEN = "open"; public static readonly string CHAN_MODE_LECTURE = "lecture"; public static readonly string CHAN_MODE_PRESENTATION = "presentation"; public static readonly string CHAN_MODE_AUDITORIUM = "auditorium"; public static readonly string CHAN_MODE_DEFAULT = CHAN_MODE_OPEN; // unconstrained default values public const double CHAN_ROLL_OFF_DEFAULT = 2.0; // rate of attenuation public const double CHAN_ROLL_OFF_MIN = 1.0; public const double CHAN_ROLL_OFF_MAX = 4.0; public const int CHAN_MAX_RANGE_DEFAULT = 80; // distance at which channel is silent public const int CHAN_MAX_RANGE_MIN = 0; public const int CHAN_MAX_RANGE_MAX = 160; public const int CHAN_CLAMPING_DISTANCE_DEFAULT = 10; // distance before attenuation applies public const int CHAN_CLAMPING_DISTANCE_MIN = 0; public const int CHAN_CLAMPING_DISTANCE_MAX = 160; // Infrastructure private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private static readonly Object vlock = new Object(); // Capability strings private static readonly string m_parcelVoiceInfoRequestPath = "0107/"; private static readonly string m_provisionVoiceAccountRequestPath = "0108/"; private static readonly string m_chatSessionRequestPath = "0109/"; // Control info, e.g. vivox server, admin user, admin password private static bool m_pluginEnabled = false; private static bool m_adminConnected = false; private static string m_vivoxServer; private static string m_vivoxSipUri; private static string m_vivoxVoiceAccountApi; private static string m_vivoxAdminUser; private static string m_vivoxAdminPassword; private static string m_authToken = String.Empty; private static int m_vivoxChannelDistanceModel; private static double m_vivoxChannelRollOff; private static int m_vivoxChannelMaximumRange; private static string m_vivoxChannelMode; private static string m_vivoxChannelType; private static int m_vivoxChannelClampingDistance; private static Dictionary<string,string> m_parents = new Dictionary<string,string>(); private static bool m_dumpXml; private IConfig m_config; public void Initialise(IConfigSource config) { m_config = config.Configs["VivoxVoice"]; if (null == m_config) { m_log.Info("[VivoxVoice] no config found, plugin disabled"); return; } if (!m_config.GetBoolean("enabled", false)) { m_log.Info("[VivoxVoice] plugin disabled by configuration"); return; } try { // retrieve configuration variables m_vivoxServer = m_config.GetString("vivox_server", String.Empty); m_vivoxSipUri = m_config.GetString("vivox_sip_uri", String.Empty); m_vivoxAdminUser = m_config.GetString("vivox_admin_user", String.Empty); m_vivoxAdminPassword = m_config.GetString("vivox_admin_password", String.Empty); m_vivoxChannelDistanceModel = m_config.GetInt("vivox_channel_distance_model", CHAN_DIST_DEFAULT); m_vivoxChannelRollOff = m_config.GetDouble("vivox_channel_roll_off", CHAN_ROLL_OFF_DEFAULT); m_vivoxChannelMaximumRange = m_config.GetInt("vivox_channel_max_range", CHAN_MAX_RANGE_DEFAULT); m_vivoxChannelMode = m_config.GetString("vivox_channel_mode", CHAN_MODE_DEFAULT).ToLower(); m_vivoxChannelType = m_config.GetString("vivox_channel_type", CHAN_TYPE_DEFAULT).ToLower(); m_vivoxChannelClampingDistance = m_config.GetInt("vivox_channel_clamping_distance", CHAN_CLAMPING_DISTANCE_DEFAULT); m_dumpXml = m_config.GetBoolean("dump_xml", false); // Validate against constraints and default if necessary if (m_vivoxChannelRollOff < CHAN_ROLL_OFF_MIN || m_vivoxChannelRollOff > CHAN_ROLL_OFF_MAX) { m_log.WarnFormat("[VivoxVoice] Invalid value for roll off ({0}), reset to {1}.", m_vivoxChannelRollOff, CHAN_ROLL_OFF_DEFAULT); m_vivoxChannelRollOff = CHAN_ROLL_OFF_DEFAULT; } if (m_vivoxChannelMaximumRange < CHAN_MAX_RANGE_MIN || m_vivoxChannelMaximumRange > CHAN_MAX_RANGE_MAX) { m_log.WarnFormat("[VivoxVoice] Invalid value for maximum range ({0}), reset to {1}.", m_vivoxChannelMaximumRange, CHAN_MAX_RANGE_DEFAULT); m_vivoxChannelMaximumRange = CHAN_MAX_RANGE_DEFAULT; } if (m_vivoxChannelClampingDistance < CHAN_CLAMPING_DISTANCE_MIN || m_vivoxChannelClampingDistance > CHAN_CLAMPING_DISTANCE_MAX) { m_log.WarnFormat("[VivoxVoice] Invalid value for clamping distance ({0}), reset to {1}.", m_vivoxChannelClampingDistance, CHAN_CLAMPING_DISTANCE_DEFAULT); m_vivoxChannelClampingDistance = CHAN_CLAMPING_DISTANCE_DEFAULT; } switch (m_vivoxChannelMode) { case "open" : break; case "lecture" : break; case "presentation" : break; case "auditorium" : break; default : m_log.WarnFormat("[VivoxVoice] Invalid value for channel mode ({0}), reset to {1}.", m_vivoxChannelMode, CHAN_MODE_DEFAULT); m_vivoxChannelMode = CHAN_MODE_DEFAULT; break; } switch (m_vivoxChannelType) { case "positional" : break; case "channel" : break; default : m_log.WarnFormat("[VivoxVoice] Invalid value for channel type ({0}), reset to {1}.", m_vivoxChannelType, CHAN_TYPE_DEFAULT); m_vivoxChannelType = CHAN_TYPE_DEFAULT; break; } m_vivoxVoiceAccountApi = String.Format("http://{0}/api2", m_vivoxServer); // Admin interface required values if (String.IsNullOrEmpty(m_vivoxServer) || String.IsNullOrEmpty(m_vivoxSipUri) || String.IsNullOrEmpty(m_vivoxAdminUser) || String.IsNullOrEmpty(m_vivoxAdminPassword)) { m_log.Error("[VivoxVoice] plugin mis-configured"); m_log.Info("[VivoxVoice] plugin disabled: incomplete configuration"); return; } m_log.InfoFormat("[VivoxVoice] using vivox server {0}", m_vivoxServer); // Get admin rights and cleanup any residual channel definition DoAdminLogin(); m_pluginEnabled = true; m_log.Info("[VivoxVoice] plugin enabled"); } catch (Exception e) { m_log.ErrorFormat("[VivoxVoice] plugin initialization failed: {0}", e.Message); m_log.DebugFormat("[VivoxVoice] plugin initialization failed: {0}", e.ToString()); return; } } // Called to indicate that the module has been added to the region public void AddRegion(Scene scene) { if (m_pluginEnabled) { lock (vlock) { string channelId; string sceneUUID = scene.RegionInfo.RegionID.ToString(); string sceneName = scene.RegionInfo.RegionName; // Make sure that all local channels are deleted. // So we have to search for the children, and then do an // iteration over the set of chidren identified. // This assumes that there is just one directory per // region. if (VivoxTryGetDirectory(sceneUUID + "D", out channelId)) { m_log.DebugFormat("[VivoxVoice]: region {0}: uuid {1}: located directory id {2}", sceneName, sceneUUID, channelId); XmlElement children = VivoxListChildren(channelId); string count; if (XmlFind(children, "response.level0.channel-search.count", out count)) { int cnum = Convert.ToInt32(count); for (int i = 0; i < cnum; i++) { string id; if (XmlFind(children, "response.level0.channel-search.channels.channels.level4.id", i, out id)) { if (!IsOK(VivoxDeleteChannel(channelId, id))) m_log.WarnFormat("[VivoxVoice] Channel delete failed {0}:{1}:{2}", i, channelId, id); } } } } else { if (!VivoxTryCreateDirectory(sceneUUID + "D", sceneName, out channelId)) { m_log.WarnFormat("[VivoxVoice] Create failed <{0}:{1}:{2}>", "*", sceneUUID, sceneName); channelId = String.Empty; } } // Create a dictionary entry unconditionally. This eliminates the // need to check for a parent in the core code. The end result is // the same, if the parent table entry is an empty string, then // region channels will be created as first-level channels. lock (m_parents) if (m_parents.ContainsKey(sceneUUID)) { RemoveRegion(scene); m_parents.Add(sceneUUID, channelId); } else { m_parents.Add(sceneUUID, channelId); } } // we need to capture scene in an anonymous method // here as we need it later in the callbacks scene.EventManager.OnRegisterCaps += delegate(UUID agentID, Caps caps) { OnRegisterCaps(scene, agentID, caps); }; } } // Called to indicate that all loadable modules have now been added public void RegionLoaded(Scene scene) { // Do nothing. } // Called to indicate that the region is going away. public void RemoveRegion(Scene scene) { if (m_pluginEnabled) { lock (vlock) { string channelId; string sceneUUID = scene.RegionInfo.RegionID.ToString(); string sceneName = scene.RegionInfo.RegionName; // Make sure that all local channels are deleted. // So we have to search for the children, and then do an // iteration over the set of chidren identified. // This assumes that there is just one directory per // region. if (VivoxTryGetDirectory(sceneUUID + "D", out channelId)) { m_log.DebugFormat("[VivoxVoice]: region {0}: uuid {1}: located directory id {2}", sceneName, sceneUUID, channelId); XmlElement children = VivoxListChildren(channelId); string count; if (XmlFind(children, "response.level0.channel-search.count", out count)) { int cnum = Convert.ToInt32(count); for (int i = 0; i < cnum; i++) { string id; if (XmlFind(children, "response.level0.channel-search.channels.channels.level4.id", i, out id)) { if (!IsOK(VivoxDeleteChannel(channelId, id))) m_log.WarnFormat("[VivoxVoice] Channel delete failed {0}:{1}:{2}", i, channelId, id); } } } } if (!IsOK(VivoxDeleteChannel(null, channelId))) m_log.WarnFormat("[VivoxVoice] Parent channel delete failed {0}:{1}:{2}", sceneName, sceneUUID, channelId); // Remove the channel umbrella entry lock (m_parents) { if (m_parents.ContainsKey(sceneUUID)) { m_parents.Remove(sceneUUID); } } } } } public void PostInitialise() { // Do nothing. } public void Close() { if (m_pluginEnabled) VivoxLogout(); } public Type ReplaceableInterface { get { return null; } } public string Name { get { return "VivoxVoiceModule"; } } public bool IsSharedModule { get { return true; } } // <summary> // OnRegisterCaps is invoked via the scene.EventManager // everytime OpenSim hands out capabilities to a client // (login, region crossing). We contribute two capabilities to // the set of capabilities handed back to the client: // ProvisionVoiceAccountRequest and ParcelVoiceInfoRequest. // // ProvisionVoiceAccountRequest allows the client to obtain // the voice account credentials for the avatar it is // controlling (e.g., user name, password, etc). // // ParcelVoiceInfoRequest is invoked whenever the client // changes from one region or parcel to another. // // Note that OnRegisterCaps is called here via a closure // delegate containing the scene of the respective region (see // Initialise()). // </summary> public void OnRegisterCaps(Scene scene, UUID agentID, Caps caps) { m_log.DebugFormat("[VivoxVoice] OnRegisterCaps: agentID {0} caps {1}", agentID, caps); string capsBase = "/CAPS/" + caps.CapsObjectPath; caps.RegisterHandler("ProvisionVoiceAccountRequest", new RestStreamHandler("POST", capsBase + m_provisionVoiceAccountRequestPath, delegate(string request, string path, string param, OSHttpRequest httpRequest, OSHttpResponse httpResponse) { return ProvisionVoiceAccountRequest(scene, request, path, param, agentID, caps); })); caps.RegisterHandler("ParcelVoiceInfoRequest", new RestStreamHandler("POST", capsBase + m_parcelVoiceInfoRequestPath, delegate(string request, string path, string param, OSHttpRequest httpRequest, OSHttpResponse httpResponse) { return ParcelVoiceInfoRequest(scene, request, path, param, agentID, caps); })); caps.RegisterHandler("ChatSessionRequest", new RestStreamHandler("POST", capsBase + m_chatSessionRequestPath, delegate(string request, string path, string param, OSHttpRequest httpRequest, OSHttpResponse httpResponse) { return ChatSessionRequest(scene, request, path, param, agentID, caps); })); } /// <summary> /// Callback for a client request for Voice Account Details /// </summary> /// <param name="scene">current scene object of the client</param> /// <param name="request"></param> /// <param name="path"></param> /// <param name="param"></param> /// <param name="agentID"></param> /// <param name="caps"></param> /// <returns></returns> public string ProvisionVoiceAccountRequest(Scene scene, string request, string path, string param, UUID agentID, Caps caps) { try { ScenePresence avatar = null; string avatarName = null; if (scene == null) throw new Exception("[VivoxVoice][PROVISIONVOICE] Invalid scene"); avatar = scene.GetScenePresence(agentID); while (avatar == null) { Thread.Sleep(100); avatar = scene.GetScenePresence(agentID); } avatarName = avatar.Name; m_log.DebugFormat("[VivoxVoice][PROVISIONVOICE]: scene = {0}, agentID = {1}", scene, agentID); m_log.DebugFormat("[VivoxVoice][PROVISIONVOICE]: request: {0}, path: {1}, param: {2}", request, path, param); XmlElement resp; bool retry = false; string agentname = "x" + Convert.ToBase64String(agentID.GetBytes()); string password = new UUID(Guid.NewGuid()).ToString().Replace('-','Z').Substring(0,16); string code = String.Empty; agentname = agentname.Replace('+', '-').Replace('/', '_'); do { resp = VivoxGetAccountInfo(agentname); if (XmlFind(resp, "response.level0.status", out code)) { if (code != "OK") { if (XmlFind(resp, "response.level0.body.code", out code)) { // If the request was recognized, then this should be set to something switch (code) { case "201" : // Account expired m_log.ErrorFormat("[VivoxVoice]: avatar \"{0}\": Get account information failed : expired credentials", avatarName); m_adminConnected = false; retry = DoAdminLogin(); break; case "202" : // Missing credentials m_log.ErrorFormat("[VivoxVoice]: avatar \"{0}\": Get account information failed : missing credentials", avatarName); break; case "212" : // Not authorized m_log.ErrorFormat("[VivoxVoice]: avatar \"{0}\": Get account information failed : not authorized", avatarName); break; case "300" : // Required parameter missing m_log.ErrorFormat("[VivoxVoice]: avatar \"{0}\": Get account information failed : parameter missing", avatarName); break; case "403" : // Account does not exist resp = VivoxCreateAccount(agentname,password); // Note: This REALLY MUST BE status. Create Account does not return code. if (XmlFind(resp, "response.level0.status", out code)) { switch (code) { case "201" : // Account expired m_log.ErrorFormat("[VivoxVoice]: avatar \"{0}\": Create account information failed : expired credentials", avatarName); m_adminConnected = false; retry = DoAdminLogin(); break; case "202" : // Missing credentials m_log.ErrorFormat("[VivoxVoice]: avatar \"{0}\": Create account information failed : missing credentials", avatarName); break; case "212" : // Not authorized m_log.ErrorFormat("[VivoxVoice]: avatar \"{0}\": Create account information failed : not authorized", avatarName); break; case "300" : // Required parameter missing m_log.ErrorFormat("[VivoxVoice]: avatar \"{0}\": Create account information failed : parameter missing", avatarName); break; case "400" : // Create failed m_log.ErrorFormat("[VivoxVoice]: avatar \"{0}\": Create account information failed : create failed", avatarName); break; } } break; case "404" : // Failed to retrieve account m_log.ErrorFormat("[VivoxVoice]: avatar \"{0}\": Get account information failed : retrieve failed"); // [AMW] Sleep and retry for a fixed period? Or just abandon? break; } } } } } while (retry); if (code != "OK") { m_log.DebugFormat("[VivoxVoice][PROVISIONVOICE]: Get Account Request failed for \"{0}\"", avatarName); throw new Exception("Unable to execute request"); } // Unconditionally change the password on each request VivoxPassword(agentname, password); LLSDVoiceAccountResponse voiceAccountResponse = new LLSDVoiceAccountResponse(agentname, password, m_vivoxSipUri, m_vivoxVoiceAccountApi); string r = LLSDHelpers.SerialiseLLSDReply(voiceAccountResponse); m_log.DebugFormat("[VivoxVoice][PROVISIONVOICE]: avatar \"{0}\": {1}", avatarName, r); return r; } catch (Exception e) { m_log.ErrorFormat("[VivoxVoice][PROVISIONVOICE]: : {0}, retry later", e.Message); m_log.DebugFormat("[VivoxVoice][PROVISIONVOICE]: : {0} failed", e.ToString()); return "<llsd><undef /></llsd>"; } } /// <summary> /// Callback for a client request for ParcelVoiceInfo /// </summary> /// <param name="scene">current scene object of the client</param> /// <param name="request"></param> /// <param name="path"></param> /// <param name="param"></param> /// <param name="agentID"></param> /// <param name="caps"></param> /// <returns></returns> public string ParcelVoiceInfoRequest(Scene scene, string request, string path, string param, UUID agentID, Caps caps) { ScenePresence avatar = scene.GetScenePresence(agentID); string avatarName = avatar.Name; // - check whether we have a region channel in our cache // - if not: // create it and cache it // - send it to the client // - send channel_uri: as "sip:regionID@m_sipDomain" try { LLSDParcelVoiceInfoResponse parcelVoiceInfo; string channel_uri; if (null == scene.LandChannel) throw new Exception(String.Format("region \"{0}\": avatar \"{1}\": land data not yet available", scene.RegionInfo.RegionName, avatarName)); // get channel_uri: check first whether estate // settings allow voice, then whether parcel allows // voice, if all do retrieve or obtain the parcel // voice channel LandData land = scene.GetLandData(avatar.AbsolutePosition.X, avatar.AbsolutePosition.Y); m_log.DebugFormat("[VivoxVoice][PARCELVOICE]: region \"{0}\": Parcel \"{1}\" ({2}): avatar \"{3}\": request: {4}, path: {5}, param: {6}", scene.RegionInfo.RegionName, land.Name, land.LocalID, avatarName, request, path, param); // m_log.DebugFormat("[VivoxVoice][PARCELVOICE]: avatar \"{0}\": location: {1} {2} {3}", // avatarName, avatar.AbsolutePosition.X, avatar.AbsolutePosition.Y, avatar.AbsolutePosition.Z); // TODO: EstateSettings don't seem to get propagated... if (!scene.RegionInfo.EstateSettings.AllowVoice) { m_log.DebugFormat("[VivoxVoice][PARCELVOICE]: region \"{0}\": voice not enabled in estate settings", scene.RegionInfo.RegionName); channel_uri = String.Empty; } if ((land.Flags & (uint)ParcelFlags.AllowVoiceChat) == 0) { m_log.DebugFormat("[VivoxVoice][PARCELVOICE]: region \"{0}\": Parcel \"{1}\" ({2}): avatar \"{3}\": voice not enabled for parcel", scene.RegionInfo.RegionName, land.Name, land.LocalID, avatarName); channel_uri = String.Empty; } else { channel_uri = RegionGetOrCreateChannel(scene, land); } // fill in our response to the client Hashtable creds = new Hashtable(); creds["channel_uri"] = channel_uri; parcelVoiceInfo = new LLSDParcelVoiceInfoResponse(scene.RegionInfo.RegionName, land.LocalID, creds); string r = LLSDHelpers.SerialiseLLSDReply(parcelVoiceInfo); m_log.DebugFormat("[VivoxVoice][PARCELVOICE]: region \"{0}\": Parcel \"{1}\" ({2}): avatar \"{3}\": {4}", scene.RegionInfo.RegionName, land.Name, land.LocalID, avatarName, r); return r; } catch (Exception e) { m_log.ErrorFormat("[VivoxVoice][PARCELVOICE]: region \"{0}\": avatar \"{1}\": {2}, retry later", scene.RegionInfo.RegionName, avatarName, e.Message); m_log.DebugFormat("[VivoxVoice][PARCELVOICE]: region \"{0}\": avatar \"{1}\": {2} failed", scene.RegionInfo.RegionName, avatarName, e.ToString()); return "<llsd><undef /></llsd>"; } } /// <summary> /// Callback for a client request for a private chat channel /// </summary> /// <param name="scene">current scene object of the client</param> /// <param name="request"></param> /// <param name="path"></param> /// <param name="param"></param> /// <param name="agentID"></param> /// <param name="caps"></param> /// <returns></returns> public string ChatSessionRequest(Scene scene, string request, string path, string param, UUID agentID, Caps caps) { ScenePresence avatar = scene.GetScenePresence(agentID); string avatarName = avatar.Name; m_log.DebugFormat("[VivoxVoice][CHATSESSION]: avatar \"{0}\": request: {1}, path: {2}, param: {3}", avatarName, request, path, param); return "<llsd>true</llsd>"; } private string RegionGetOrCreateChannel(Scene scene, LandData land) { string channelUri = null; string channelId = null; string landUUID; string landName; string parentId; lock (m_parents) parentId = m_parents[scene.RegionInfo.RegionID.ToString()]; // Create parcel voice channel. If no parcel exists, then the voice channel ID is the same // as the directory ID. Otherwise, it reflects the parcel's ID. if (land.LocalID != 1 && (land.Flags & (uint)ParcelFlags.UseEstateVoiceChan) == 0) { landName = String.Format("{0}:{1}", scene.RegionInfo.RegionName, land.Name); landUUID = land.GlobalID.ToString(); m_log.DebugFormat("[VivoxVoice]: Region:Parcel \"{0}\": parcel id {1}: using channel name {2}", landName, land.LocalID, landUUID); } else { landName = String.Format("{0}:{1}", scene.RegionInfo.RegionName, scene.RegionInfo.RegionName); landUUID = scene.RegionInfo.RegionID.ToString(); m_log.DebugFormat("[VivoxVoice]: Region:Parcel \"{0}\": parcel id {1}: using channel name {2}", landName, land.LocalID, landUUID); } lock (vlock) { // Added by Adam to help debug channel not availible errors. if (VivoxTryGetChannel(parentId, landUUID, out channelId, out channelUri)) m_log.DebugFormat("[VivoxVoice] Found existing channel at " + channelUri); else if (VivoxTryCreateChannel(parentId, landUUID, landName, out channelUri)) m_log.DebugFormat("[VivoxVoice] Created new channel at " + channelUri); else throw new Exception("vivox channel uri not available"); m_log.DebugFormat("[VivoxVoice]: Region:Parcel \"{0}\": parent channel id {1}: retrieved parcel channel_uri {2} ", landName, parentId, channelUri); } return channelUri; } private static readonly string m_vivoxLoginPath = "http://{0}/api2/viv_signin.php?userid={1}&pwd={2}"; /// <summary> /// Perform administrative login for Vivox. /// Returns a hash table containing values returned from the request. /// </summary> private XmlElement VivoxLogin(string name, string password) { string requrl = String.Format(m_vivoxLoginPath, m_vivoxServer, name, password); return VivoxCall(requrl, false); } private static readonly string m_vivoxLogoutPath = "http://{0}/api2/viv_signout.php?auth_token={1}"; /// <summary> /// Perform administrative logout for Vivox. /// </summary> private XmlElement VivoxLogout() { string requrl = String.Format(m_vivoxLogoutPath, m_vivoxServer, m_authToken); return VivoxCall(requrl, false); } private static readonly string m_vivoxGetAccountPath = "http://{0}/api2/viv_get_acct.php?auth_token={1}&user_name={2}"; /// <summary> /// Retrieve account information for the specified user. /// Returns a hash table containing values returned from the request. /// </summary> private XmlElement VivoxGetAccountInfo(string user) { string requrl = String.Format(m_vivoxGetAccountPath, m_vivoxServer, m_authToken, user); return VivoxCall(requrl, true); } private static readonly string m_vivoxNewAccountPath = "http://{0}/api2/viv_adm_acct_new.php?username={1}&pwd={2}&auth_token={3}"; /// <summary> /// Creates a new account. /// For now we supply the minimum set of values, which /// is user name and password. We *can* supply a lot more /// demographic data. /// </summary> private XmlElement VivoxCreateAccount(string user, string password) { string requrl = String.Format(m_vivoxNewAccountPath, m_vivoxServer, user, password, m_authToken); return VivoxCall(requrl, true); } private static readonly string m_vivoxPasswordPath = "http://{0}/api2/viv_adm_password.php?user_name={1}&new_pwd={2}&auth_token={3}"; /// <summary> /// Change the user's password. /// </summary> private XmlElement VivoxPassword(string user, string password) { string requrl = String.Format(m_vivoxPasswordPath, m_vivoxServer, user, password, m_authToken); return VivoxCall(requrl, true); } private static readonly string m_vivoxChannelPath = "http://{0}/api2/viv_chan_mod.php?mode={1}&chan_name={2}&auth_token={3}"; /// <summary> /// Create a channel. /// Once again, there a multitude of options possible. In the simplest case /// we specify only the name and get a non-persistent cannel in return. Non /// persistent means that the channel gets deleted if no-one uses it for /// 5 hours. To accomodate future requirements, it may be a good idea to /// initially create channels under the umbrella of a parent ID based upon /// the region name. That way we have a context for side channels, if those /// are required in a later phase. /// /// In this case the call handles parent and description as optional values. /// </summary> private bool VivoxTryCreateChannel(string parent, string channelId, string description, out string channelUri) { string requrl = String.Format(m_vivoxChannelPath, m_vivoxServer, "create", channelId, m_authToken); if (parent != null && parent != String.Empty) { requrl = String.Format("{0}&chan_parent={1}", requrl, parent); } if (description != null && description != String.Empty) { requrl = String.Format("{0}&chan_desc={1}", requrl, description); } requrl = String.Format("{0}&chan_type={1}", requrl, m_vivoxChannelType); requrl = String.Format("{0}&chan_mode={1}", requrl, m_vivoxChannelMode); requrl = String.Format("{0}&chan_roll_off={1}", requrl, m_vivoxChannelRollOff); requrl = String.Format("{0}&chan_dist_model={1}", requrl, m_vivoxChannelDistanceModel); requrl = String.Format("{0}&chan_max_range={1}", requrl, m_vivoxChannelMaximumRange); requrl = String.Format("{0}&chan_ckamping_distance={1}", requrl, m_vivoxChannelClampingDistance); XmlElement resp = VivoxCall(requrl, true); if (XmlFind(resp, "response.level0.body.chan_uri", out channelUri)) return true; channelUri = String.Empty; return false; } /// <summary> /// Create a directory. /// Create a channel with an unconditional type of "dir" (indicating directory). /// This is used to create an arbitrary name tree for partitioning of the /// channel name space. /// The parent and description are optional values. /// </summary> private bool VivoxTryCreateDirectory(string dirId, string description, out string channelId) { string requrl = String.Format(m_vivoxChannelPath, m_vivoxServer, "create", dirId, m_authToken); // if (parent != null && parent != String.Empty) // { // requrl = String.Format("{0}&chan_parent={1}", requrl, parent); // } if (description != null && description != String.Empty) { requrl = String.Format("{0}&chan_desc={1}", requrl, description); } requrl = String.Format("{0}&chan_type={1}", requrl, "dir"); XmlElement resp = VivoxCall(requrl, true); if (IsOK(resp) && XmlFind(resp, "response.level0.body.chan_id", out channelId)) return true; channelId = String.Empty; return false; } private static readonly string m_vivoxChannelSearchPath = "http://{0}/api2/viv_chan_search.php?cond_channame={1}&auth_token={2}"; /// <summary> /// Retrieve a channel. /// Once again, there a multitude of options possible. In the simplest case /// we specify only the name and get a non-persistent cannel in return. Non /// persistent means that the channel gets deleted if no-one uses it for /// 5 hours. To accomodate future requirements, it may be a good idea to /// initially create channels under the umbrella of a parent ID based upon /// the region name. That way we have a context for side channels, if those /// are required in a later phase. /// In this case the call handles parent and description as optional values. /// </summary> private bool VivoxTryGetChannel(string channelParent, string channelName, out string channelId, out string channelUri) { string count; string requrl = String.Format(m_vivoxChannelSearchPath, m_vivoxServer, channelName, m_authToken); XmlElement resp = VivoxCall(requrl, true); if (XmlFind(resp, "response.level0.channel-search.count", out count)) { int channels = Convert.ToInt32(count); // Bug in Vivox Server r2978 where count returns 0 // Found by Adam if (channels == 0) { for (int j=0;j<100;j++) { string tmpId; if (!XmlFind(resp, "response.level0.channel-search.channels.channels.level4.id", j, out tmpId)) break; channels = j + 1; } } for (int i = 0; i < channels; i++) { string name; string id; string type; string uri; string parent; // skip if not a channel if (!XmlFind(resp, "response.level0.channel-search.channels.channels.level4.type", i, out type) || (type != "channel" && type != "positional_M")) { m_log.Debug("[VivoxVoice] Skipping Channel " + i + " as it's not a channel."); continue; } // skip if not the name we are looking for if (!XmlFind(resp, "response.level0.channel-search.channels.channels.level4.name", i, out name) || name != channelName) { m_log.Debug("[VivoxVoice] Skipping Channel " + i + " as it has no name."); continue; } // skip if parent does not match if (channelParent != null && !XmlFind(resp, "response.level0.channel-search.channels.channels.level4.parent", i, out parent)) { m_log.Debug("[VivoxVoice] Skipping Channel " + i + "/" + name + " as it's parent doesnt match"); continue; } // skip if no channel id available if (!XmlFind(resp, "response.level0.channel-search.channels.channels.level4.id", i, out id)) { m_log.Debug("[VivoxVoice] Skipping Channel " + i + "/" + name + " as it has no channel ID"); continue; } // skip if no channel uri available if (!XmlFind(resp, "response.level0.channel-search.channels.channels.level4.uri", i, out uri)) { m_log.Debug("[VivoxVoice] Skipping Channel " + i + "/" + name + " as it has no channel URI"); continue; } channelId = id; channelUri = uri; return true; } } else { m_log.Debug("[VivoxVoice] No count element?"); } channelId = String.Empty; channelUri = String.Empty; // Useful incase something goes wrong. //m_log.Debug("[VivoxVoice] Could not find channel in XMLRESP: " + resp.InnerXml); return false; } private bool VivoxTryGetDirectory(string directoryName, out string directoryId) { string count; string requrl = String.Format(m_vivoxChannelSearchPath, m_vivoxServer, directoryName, m_authToken); XmlElement resp = VivoxCall(requrl, true); if (XmlFind(resp, "response.level0.channel-search.count", out count)) { int channels = Convert.ToInt32(count); for (int i = 0; i < channels; i++) { string name; string id; string type; // skip if not a directory if (!XmlFind(resp, "response.level0.channel-search.channels.channels.level4.type", i, out type) || type != "dir") continue; // skip if not the name we are looking for if (!XmlFind(resp, "response.level0.channel-search.channels.channels.level4.name", i, out name) || name != directoryName) continue; // skip if no channel id available if (!XmlFind(resp, "response.level0.channel-search.channels.channels.level4.id", i, out id)) continue; directoryId = id; return true; } } directoryId = String.Empty; return false; } // private static readonly string m_vivoxChannelById = "http://{0}/api2/viv_chan_mod.php?mode={1}&chan_id={2}&auth_token={3}"; // private XmlElement VivoxGetChannelById(string parent, string channelid) // { // string requrl = String.Format(m_vivoxChannelById, m_vivoxServer, "get", channelid, m_authToken); // if (parent != null && parent != String.Empty) // return VivoxGetChild(parent, channelid); // else // return VivoxCall(requrl, true); // } /// <summary> /// Delete a channel. /// Once again, there a multitude of options possible. In the simplest case /// we specify only the name and get a non-persistent cannel in return. Non /// persistent means that the channel gets deleted if no-one uses it for /// 5 hours. To accomodate future requirements, it may be a good idea to /// initially create channels under the umbrella of a parent ID based upon /// the region name. That way we have a context for side channels, if those /// are required in a later phase. /// In this case the call handles parent and description as optional values. /// </summary> private static readonly string m_vivoxChannelDel = "http://{0}/api2/viv_chan_mod.php?mode={1}&chan_id={2}&auth_token={3}"; private XmlElement VivoxDeleteChannel(string parent, string channelid) { string requrl = String.Format(m_vivoxChannelDel, m_vivoxServer, "delete", channelid, m_authToken); if (parent != null && parent != String.Empty) { requrl = String.Format("{0}&chan_parent={1}", requrl, parent); } return VivoxCall(requrl, true); } /// <summary> /// Return information on channels in the given directory /// </summary> private static readonly string m_vivoxChannelSearch = "http://{0}/api2/viv_chan_search.php?&cond_chanparent={1}&auth_token={2}"; private XmlElement VivoxListChildren(string channelid) { string requrl = String.Format(m_vivoxChannelSearch, m_vivoxServer, channelid, m_authToken); return VivoxCall(requrl, true); } // private XmlElement VivoxGetChild(string parent, string child) // { // XmlElement children = VivoxListChildren(parent); // string count; // if (XmlFind(children, "response.level0.channel-search.count", out count)) // { // int cnum = Convert.ToInt32(count); // for (int i = 0; i < cnum; i++) // { // string name; // string id; // if (XmlFind(children, "response.level0.channel-search.channels.channels.level4.name", i, out name)) // { // if (name == child) // { // if (XmlFind(children, "response.level0.channel-search.channels.channels.level4.id", i, out id)) // { // return VivoxGetChannelById(null, id); // } // } // } // } // } // // One we *know* does not exist. // return VivoxGetChannel(null, Guid.NewGuid().ToString()); // } /// <summary> /// This method handles the WEB side of making a request over the /// Vivox interface. The returned values are tansferred to a has /// table which is returned as the result. /// The outcome of the call can be determined by examining the /// status value in the hash table. /// </summary> private XmlElement VivoxCall(string requrl, bool admin) { XmlDocument doc = null; // If this is an admin call, and admin is not connected, // and the admin id cannot be connected, then fail. if (admin && !m_adminConnected && !DoAdminLogin()) return null; doc = new XmlDocument(); try { // Otherwise prepare the request m_log.DebugFormat("[VivoxVoice] Sending request <{0}>", requrl); HttpWebRequest req = (HttpWebRequest)WebRequest.Create(requrl); HttpWebResponse rsp = null; // We are sending just parameters, no content req.ContentLength = 0; // Send request and retrieve the response rsp = (HttpWebResponse)req.GetResponse(); XmlTextReader rdr = new XmlTextReader(rsp.GetResponseStream()); doc.Load(rdr); rdr.Close(); } catch (Exception e) { m_log.ErrorFormat("[VivoxVoice] Error in admin call : {0}", e.Message); } // If we're debugging server responses, dump the whole // load now if (m_dumpXml) XmlScanl(doc.DocumentElement,0); return doc.DocumentElement; } /// <summary> /// Just say if it worked. /// </summary> private bool IsOK(XmlElement resp) { string status; XmlFind(resp, "response.level0.status", out status); return (status == "OK"); } /// <summary> /// Login has been factored in this way because it gets called /// from several places in the module, and we want it to work /// the same way each time. /// </summary> private bool DoAdminLogin() { m_log.Debug("[VivoxVoice] Establishing admin connection"); lock (vlock) { if (!m_adminConnected) { string status = "Unknown"; XmlElement resp = null; resp = VivoxLogin(m_vivoxAdminUser, m_vivoxAdminPassword); if (XmlFind(resp, "response.level0.body.status", out status)) { if (status == "Ok") { m_log.Info("[VivoxVoice] Admin connection established"); if (XmlFind(resp, "response.level0.body.auth_token", out m_authToken)) { if (m_dumpXml) m_log.DebugFormat("[VivoxVoice] Auth Token <{0}>", m_authToken); m_adminConnected = true; } } else { m_log.WarnFormat("[VivoxVoice] Admin connection failed, status = {0}", status); } } } } return m_adminConnected; } /// <summary> /// The XmlScan routine is provided to aid in the /// reverse engineering of incompletely /// documented packets returned by the Vivox /// voice server. It is only called if the /// m_dumpXml switch is set. /// </summary> private void XmlScanl(XmlElement e, int index) { if (e.HasChildNodes) { m_log.DebugFormat("<{0}>".PadLeft(index+5), e.Name); XmlNodeList children = e.ChildNodes; foreach (XmlNode node in children) switch (node.NodeType) { case XmlNodeType.Element : XmlScanl((XmlElement)node, index+1); break; case XmlNodeType.Text : m_log.DebugFormat("\"{0}\"".PadLeft(index+5), node.Value); break; default : break; } m_log.DebugFormat("</{0}>".PadLeft(index+6), e.Name); } else { m_log.DebugFormat("<{0}/>".PadLeft(index+6), e.Name); } } private static readonly char[] C_POINT = {'.'}; /// <summary> /// The Find method is passed an element whose /// inner text is scanned in an attempt to match /// the name hierarchy passed in the 'tag' parameter. /// If the whole hierarchy is resolved, the InnerText /// value at that point is returned. Note that this /// may itself be a subhierarchy of the entire /// document. The function returns a boolean indicator /// of the search's success. The search is performed /// by the recursive Search method. /// </summary> private bool XmlFind(XmlElement root, string tag, int nth, out string result) { if (root == null || tag == null || tag == String.Empty) { result = String.Empty; return false; } return XmlSearch(root,tag.Split(C_POINT),0, ref nth, out result); } private bool XmlFind(XmlElement root, string tag, out string result) { int nth = 0; if (root == null || tag == null || tag == String.Empty) { result = String.Empty; return false; } return XmlSearch(root,tag.Split(C_POINT),0, ref nth, out result); } /// <summary> /// XmlSearch is initially called by XmlFind, and then /// recursively called by itself until the document /// supplied to XmlFind is either exhausted or the name hierarchy /// is matched. /// /// If the hierarchy is matched, the value is returned in /// result, and true returned as the function's /// value. Otherwise the result is set to the empty string and /// false is returned. /// </summary> private bool XmlSearch(XmlElement e, string[] tags, int index, ref int nth, out string result) { if (index == tags.Length || e.Name != tags[index]) { result = String.Empty; return false; } if (tags.Length-index == 1) { if (nth == 0) { result = e.InnerText; return true; } else { nth--; result = String.Empty; return false; } } if (e.HasChildNodes) { XmlNodeList children = e.ChildNodes; foreach (XmlNode node in children) { switch (node.NodeType) { case XmlNodeType.Element : if (XmlSearch((XmlElement)node, tags, index+1, ref nth, out result)) return true; break; default : break; } } } result = String.Empty; return false; } } }
// The MIT License (MIT) // Copyright (c) 2013 lailongwei<lailongwei@126.com> // // Permission is hereby granted, free of charge, to any person obtaining a copy of // this software and associated documentation files (the "Software"), to deal in // the Software without restriction, including without limitation the rights to // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of // the Software, and to permit persons to whom the Software is furnished to do so, // subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS // FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR // COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER // IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. using System; namespace llbc { /// <summary> /// Log level enumeration. /// </summary> public enum LogLevel { Debug, Info, Warn, Error, Fatal } /// <summary> /// Logger class encapsulation. /// </summary> public class Logger { #region Ctor public Logger(string loggerName) { _loggerName = loggerName; IntPtr nativeLoggerName = LibUtil.CreateNativeStr(_loggerName); _nativeLogger = LLBCNative.csllbc_Log_GetLogger(nativeLoggerName); System.Runtime.InteropServices.Marshal.FreeHGlobal(nativeLoggerName); if (_nativeLogger == IntPtr.Zero) throw ExceptionUtil.CreateExceptionFromCoreLib(); } #endregion // Ctor #region properties: loggerName, enabled, enabledLogFileInfo /// <summary> /// logger name. /// </summary> public string loggerName { get { return _loggerName; } } /// <summary> /// Check log enabled or not. /// </summary> public bool enabled { get { return _enabled; } set { _enabled = value; } } /// <summary> /// Enabled log file info or not. /// </summary> public bool enabledLogFileInfo { get { return _enabledLogFileInfo; } set { _enabledLogFileInfo = value; } } #endregion #region Dbg/Info/Warn/Err/Fatal /// <summary> /// Log Debug level message. /// </summary> /// <param name="fmt">log message format</param> /// <param name="args">log message arguments</param> public void Dbg(string fmt, params object[] args) { _Log(null, LogLevel.Debug, _baseSkipFrames, fmt, args); } /// <summary> /// Log Debug level message. /// </summary> /// <param name="skipFrames">skip frames count</param> /// <param name="fmt">log message format</param> /// <param name="args">log message arguments</param> public void Dbg(int skipFrames, string fmt, params object[] args) { _Log(null, LogLevel.Debug, _baseSkipFrames + skipFrames, fmt, args); } /// <summary> /// Log Info level message. /// </summary> /// <param name="fmt">log message format</param> /// <param name="args">log message arguments</param> public void Info(string fmt, params object[] args) { _Log(null, LogLevel.Info, _baseSkipFrames, fmt, args); } /// <summary> /// Log Info level message. /// </summary> /// <param name="skipFrames">skip frames count</param> /// <param name="fmt">log message format</param> /// <param name="args">log message arguments</param> public void Info(int skipFrames, string fmt, params object[] args) { _Log(null, LogLevel.Info, _baseSkipFrames + skipFrames, fmt, args); } /// <summary> /// Log Warn level message. /// </summary> /// <param name="fmt">log message format</param> /// <param name="args">log message arguments</param> public void Warn(string fmt, params object[] args) { _Log(null, LogLevel.Warn, _baseSkipFrames, fmt, args); } /// <summary> /// Log Warn level message. /// </summary> /// <param name="skipFrames">skip frames count</param> /// <param name="fmt">log message format</param> /// <param name="args">log message arguments</param> public void Warn(int skipFrames, string fmt, params object[] args) { _Log(null, LogLevel.Warn, _baseSkipFrames + skipFrames, fmt, args); } /// <summary> /// Log Error level message. /// </summary> /// <param name="fmt">log message format</param> /// <param name="args">log message arguments</param> public void Err(string fmt, params object[] args) { _Log(null, LogLevel.Error, _baseSkipFrames, fmt, args); } /// <summary> /// Log Error level message. /// </summary> /// <param name="skipFrames">skip frames count</param> /// <param name="fmt">log message format</param> /// <param name="args">log message arguments</param> public void Err(int skipFrames, string fmt, params object[] args) { _Log(null, LogLevel.Error, _baseSkipFrames + skipFrames, fmt, args); } /// <summary> /// Log Fatal level message. /// </summary> /// <param name="fmt">log message format</param> /// <param name="args">log message arguments</param> public void Fatal(string fmt, params object[] args) { _Log(null, LogLevel.Fatal, _baseSkipFrames, fmt, args); } /// <summary> /// Log Fatal level message. /// </summary> /// <param name="skipFrames">skip frames count</param> /// <param name="fmt">log message format</param> /// <param name="args">log message arguments</param> public void Fatal(int skipFrames, string fmt, params object[] args) { _Log(null, LogLevel.Fatal, _baseSkipFrames + skipFrames, fmt, args); } #endregion // Dbg/Info/Warn/Err/Fatal #region Dbg<Tag>/Info<Tag>/Warn<Tag>/Err<Tag>/Fatal<Tag> /// <summary> /// Log Debug level message with tag. /// </summary> /// <param name="fmt">log message format</param> /// <param name="args">log message arguments</param> public void Dbg<Tag>(string fmt, params object[] args) { _Log(typeof(Tag), LogLevel.Debug, _baseSkipFrames, fmt, args); } /// <summary> /// Log Debug level message with tag. /// </summary> /// <param name="skipFrames">skip frames count</param> /// <param name="fmt">log message format</param> /// <param name="args">log message arguments</param> public void Dbg<Tag>(int skipFrames, string fmt, params object[] args) { _Log(typeof(Tag), LogLevel.Debug, _baseSkipFrames + skipFrames, fmt, args); } /// <summary> /// Log Info level message with tag. /// </summary> /// <param name="fmt">log message format</param> /// <param name="args">log message arguments</param> public void Info<Tag>(string fmt, params object[] args) { _Log(typeof(Tag), LogLevel.Info, _baseSkipFrames, fmt, args); } /// <summary> /// Log Info level message with tag. /// </summary> /// <param name="skipFrames">skip frames count</param> /// <param name="fmt">log message format</param> /// <param name="args">log message arguments</param> public void Info<Tag>(int skipFrames, string fmt, params object[] args) { _Log(typeof(Tag), LogLevel.Info, _baseSkipFrames + skipFrames, fmt, args); } /// <summary> /// Log Warn level message with tag. /// </summary> /// <param name="fmt">log message format</param> /// <param name="args">log message arguments</param> public void Warn<Tag>(string fmt, params object[] args) { _Log(typeof(Tag), LogLevel.Warn, _baseSkipFrames, fmt, args); } /// <summary> /// Log Warn level message with tag. /// </summary> /// <param name="skipFrames">skip frames count</param> /// <param name="fmt">log message format</param> /// <param name="args">log message arguments</param> public void Warn<Tag>(int skipFrames, string fmt, params object[] args) { _Log(typeof(Tag), LogLevel.Warn, _baseSkipFrames + skipFrames, fmt, args); } /// <summary> /// Log Error level message with tag. /// </summary> /// <param name="fmt">log message format</param> /// <param name="args">log message arguments</param> public void Err<Tag>(string fmt, params object[] args) { _Log(typeof(Tag), LogLevel.Error, _baseSkipFrames, fmt, args); } /// <summary> /// Log Error level message with tag. /// </summary> /// <param name="skipFrames">skip frames count</param> /// <param name="fmt">log message format</param> /// <param name="args">log message arguments</param> public void Err<Tag>(int skipFrames, string fmt, params object[] args) { _Log(typeof(Tag), LogLevel.Error, _baseSkipFrames + skipFrames, fmt, args); } /// <summary> /// Log Fatal level message with tag. /// </summary> /// <param name="fmt">log message format</param> /// <param name="args">log message arguments</param> public void Fatal<Tag>(string fmt, params object[] args) { _Log(typeof(Tag), LogLevel.Fatal, _baseSkipFrames, fmt, args); } /// <summary> /// Log Fatal level message with tag. /// </summary> /// <param name="skipFrames">skip frames count</param> /// <param name="fmt">log message format</param> /// <param name="args">log message arguments</param> public void Fatal<Tag>(int skipFrames, string fmt, params object[] args) { _Log(typeof(Tag), LogLevel.Fatal, _baseSkipFrames + skipFrames, fmt, args); } #endregion // Dbg<Tag>/Info<Tag>/Warn<Tag>/Err<Tag>/Fatal<Tag> #region Dbg2/Info2/Warn2/Err2/Fatal2 /// <summary> /// Log Debug level message with tag. /// </summary> /// <param name="fmt">log message format</param> /// <param name="args">log message arguments</param> public void Dbg2(object tag, string fmt, params object[] args) { _Log(tag, LogLevel.Debug, _baseSkipFrames, fmt, args); } /// <summary> /// Log Debug level message with tag. /// </summary> /// <param name="skipFrames">skip frames count</param> /// <param name="fmt">log message format</param> /// <param name="args">log message arguments</param> public void Dbg2(object tag, int skipFrames, string fmt, params object[] args) { _Log(tag, LogLevel.Debug, _baseSkipFrames + skipFrames, fmt, args); } /// <summary> /// Log Info level message with tag. /// </summary> /// <param name="fmt">log message format</param> /// <param name="args">log message arguments</param> public void Info2(object tag, string fmt, params object[] args) { _Log(tag, LogLevel.Info, _baseSkipFrames, fmt, args); } /// <summary> /// Log Info level message with tag. /// </summary> /// <param name="skipFrames">skip frames count</param> /// <param name="fmt">log message format</param> /// <param name="args">log message arguments</param> public void Info2(object tag, int skipFrames, string fmt, params object[] args) { _Log(tag, LogLevel.Info, _baseSkipFrames + skipFrames, fmt, args); } /// <summary> /// Log Warn level message with tag. /// </summary> /// <param name="fmt">log message format</param> /// <param name="args">log message arguments</param> public void Warn2(object tag, string fmt, params object[] args) { _Log(tag, LogLevel.Warn, _baseSkipFrames, fmt, args); } /// <summary> /// Log Warn level message with tag. /// </summary> /// <param name="skipFrames">skip frames count</param> /// <param name="fmt">log message format</param> /// <param name="args">log message arguments</param> public void Warn2(object tag, int skipFrames, string fmt, params object[] args) { _Log(tag, LogLevel.Warn, _baseSkipFrames + skipFrames, fmt, args); } /// <summary> /// Log Error level message with tag. /// </summary> /// <param name="fmt">log message format</param> /// <param name="args">log message arguments</param> public void Err2(object tag, string fmt, params object[] args) { _Log(tag, LogLevel.Error, _baseSkipFrames, fmt, args); } /// <summary> /// Log Error level message with tag. /// </summary> /// <param name="skipFrames">skip frames count</param> /// <param name="fmt">log message format</param> /// <param name="args">log message arguments</param> public void Err2(object tag, int skipFrames, string fmt, params object[] args) { _Log(tag, LogLevel.Error, _baseSkipFrames + skipFrames, fmt, args); } /// <summary> /// Log Fatal level message with tag. /// </summary> /// <param name="fmt">log message format</param> /// <param name="args">log message arguments</param> public void Fatal2(object tag, string fmt, params object[] args) { _Log(tag, LogLevel.Fatal, _baseSkipFrames, fmt, args); } /// <summary> /// Log Fatal level message with tag. /// </summary> /// <param name="fmt">log message format</param> /// <param name="args">log message arguments</param> public void Fatal2(object tag, int skipFrames, string fmt, params object[] args) { _Log(tag, LogLevel.Fatal, _baseSkipFrames + skipFrames, fmt, args); } #endregion // Dbg2/Info2/Warn2/Err2/Fatal2 #region Internal methods private void _Log(object tag, LogLevel level, int skipFrames, string fmt, params object[] args) { if (!enabled) return; IntPtr fileName = IntPtr.Zero; IntPtr funcName = IntPtr.Zero; // Get filename, lineno, funcName, if enabled. int lineNo = -1; if (_enabledLogFileInfo) { var st = new System.Diagnostics.StackTrace(true); var frame = st.GetFrame(skipFrames); if (frame != null) { lineNo = frame.GetFileLineNumber(); fileName = LibUtil.CreateNativeStr(frame.GetFileName()); funcName = LibUtil.CreateNativeStr(frame.GetMethod().Name); } } IntPtr nativeTag = IntPtr.Zero; IntPtr nativeMsg = IntPtr.Zero; try { // Get log tag. if (tag is Type) nativeTag = LibUtil.CreateNativeStr((tag as Type).Name); else if (tag != null) nativeTag = LibUtil.CreateNativeStr(tag.ToString()); // Build log message. nativeMsg = LibUtil.CreateNativeStr(string.Format(fmt, args)); LLBCNative.csllbc_Log_LogMsg(_nativeLogger, fileName, lineNo, funcName, (int)level, nativeMsg, nativeTag); } catch (Exception e) { // Firstly, free nativeMsg. System.Runtime.InteropServices.Marshal.FreeHGlobal(nativeMsg); // Simply format error message and dump it. string errMsg = string.Format("Log [{0}] failed, exception:{1}, stacktrace:\n{2}", fmt, e.Message, new System.Diagnostics.StackTrace().ToString()); nativeMsg = LibUtil.CreateNativeStr(errMsg); LLBCNative.csllbc_Log_LogMsg(_nativeLogger, fileName, lineNo, funcName, (int)LogLevel.Fatal, nativeMsg, nativeTag); } finally { System.Runtime.InteropServices.Marshal.FreeHGlobal(nativeTag); System.Runtime.InteropServices.Marshal.FreeHGlobal(nativeMsg); } System.Runtime.InteropServices.Marshal.FreeHGlobal(fileName); System.Runtime.InteropServices.Marshal.FreeHGlobal(funcName); } #endregion // Internal methods private string _loggerName; private IntPtr _nativeLogger; private volatile bool _enabled = true; private volatile bool _enabledLogFileInfo; private const int _baseSkipFrames = 2; } }
using System; using System.ComponentModel; using System.Text; using System.Xml; using System.Xml.Serialization; using System.Net.Sockets; using System.Runtime.Serialization.Formatters.Binary; using System.Threading; namespace Hydra.Framework.AsyncSockets { // //********************************************************************** /// <summary> /// <c>Client</c> is a advanced implementation of the .NET Winsock TCP\IP Client, /// It has almost everything build in. /// It was developeed and designed with the <c>Server</c> class (Although they work /// excellent together and advice to do so, it can workwith any other server implementation). /// </summary> //********************************************************************** // public sealed class Client : IDisposable { #region private members // //********************************************************************** /// <summary> /// Holds the status of the last communiation test with the server. /// </summary> //********************************************************************** // private TestingStatusType m_ComTestStatus = TestingStatusType.NotTested; // //********************************************************************** /// <summary> /// The socket to be use during connection and data /// transmission wth the server /// </summary> //********************************************************************** // private Socket m_ClientSocket = null; // //********************************************************************** /// <summary> /// Holds both the IP end point and the port number of the target server. /// (<c>Server</c>'s objects listens by default on port 2222). /// </summary> //********************************************************************** // private ServerInfo m_TargetServerInfo = null; // //********************************************************************** /// <summary> /// Holds the name of the <c>Client</c> object; /// </summary> //********************************************************************** // private string m_ClientName = "Anonymous"; // //********************************************************************** /// <summary> /// Holds the float value of the <c>Client</c> process priority. /// Controls the response time of the <c>Client</c> to some events. /// View the <c>GeneralPriority</c> propertie for more info. /// </summary> //********************************************************************** // private float m_GeneralPriority = 1; // //********************************************************************** /// <summary> /// The actual priority of executing new data scan, over other system threads. /// </summary> /// <remarks>Default value is 'Normal'</remarks> //********************************************************************** // private ThreadPriority m_DataScanPriority = ThreadPriority.Normal; // //********************************************************************** /// <summary> /// The <c>Networkstream</c> of the client's socket. /// </summary> //********************************************************************** // private NetworkStream m_NetStream; // //********************************************************************** /// <summary> /// A serialize tool to write objects to the m_NetStream member. /// </summary> //********************************************************************** // private BinaryFormatter m_BinaryCaster = new BinaryFormatter(); private System.Runtime.Serialization.Formatters.Soap.SoapFormatter m_SoapCaster = new System.Runtime.Serialization.Formatters.Soap.SoapFormatter(); // //********************************************************************** /// <summary> /// Keeps track of the last time a message was sent to the server. /// </summary> //********************************************************************** // private DateTime m_LastDataSentTime = DateTime.Now; // //********************************************************************** /// <summary> /// This thread scans for data arrival from the server. /// </summary> //********************************************************************** // private Thread m_NewDataScanner = null; // //********************************************************************** /// <summary> /// Reffrence to object that is used in the <c>SendData</c> async overloads /// functions. This is used to pass data to the <c>SendDataByPass</c> function /// without arguments (To activate as a separate thread). /// </summary> //********************************************************************** // private Object m_ByPassDataToSend = null; // //********************************************************************** /// <summary> /// Indicates for function is here current call is asynchronic. /// </summary> /// <remarks>By defalut is false and get so after every async call.</remarks> //********************************************************************** // private bool m_IsAsyncMode = false; // //********************************************************************** /// <summary> /// When this flag is off, all the user defined threads, calling <c>Abort()</c> /// on them selfs. This is done from <c>Dispose()</c>; /// </summary> //********************************************************************** // private bool m_DoThreads = true; // //********************************************************************** /// <summary> /// Flag is on when using the <c>TestCommunication()</c> asynchroniclly, /// and marks it not to throw exceptions but to use the proper event handler instead. /// </summary> //********************************************************************** // private bool m_IsTestComAsyncOn = false; #endregion #region Event Handlers // //********************************************************************** /// <summary> /// Data arrived event handlers delegate. /// </summary> //********************************************************************** // private DataArrived2Client_EventHandler OnDataArrived; // //********************************************************************** /// <summary> /// Data sent event handlers delegate. /// </summary> //********************************************************************** // private DataSent_EventHandler OnDataSent; // //********************************************************************** /// <summary> /// Connecting to server event handlers delegate. /// </summary> //********************************************************************** // private Connecting_EventHandler OnConnecting; // //********************************************************************** /// <summary> /// Connected to server event handlers delegate. /// </summary> //********************************************************************** // private Connected_EventHandler OnConnected; // //********************************************************************** /// <summary> /// Disconnecting from server event handlers delegate. /// </summary> //********************************************************************** // private Disconnecting_EventHandler OnDisconnecting; // //********************************************************************** /// <summary> /// Disconnected from server event handlers delegate. /// </summary> //********************************************************************** // private Disconnected_EventHandler OnDisconnected; // //********************************************************************** /// <summary> /// Communication test start event handlers delegate. /// </summary> //********************************************************************** // private ComTestStart_EventHandler OnComTestStarted; // //********************************************************************** /// <summary> /// Communication ends start event handlers delegate. /// </summary> //********************************************************************** // private ComTestEnd_EventHandler OnComTestEnded; // //********************************************************************** /// <summary> /// Connection attempt TimeOut event handler. /// </summary> //********************************************************************** // private ConnectionTimeOutError_EventHandler OnConnectionTimeOut; // //********************************************************************** /// <summary> /// Been called when error accures while sending data using <c>DataSendAsync</c>. /// </summary> //********************************************************************** // private DataSendAsyncError_EventHandler OnDataSendAsyncError; // //********************************************************************** /// <summary> /// Been called when error accures while testing communication asynchroniclly <c>TestCommunicationAsync</c>. /// </summary> //********************************************************************** // private TestComAsyncError_EventHandler OnTestComAsyncError; #endregion #region IDisposable Members // //********************************************************************** /// <summary> /// Releasing resources /// </summary> //********************************************************************** // public void Dispose() { // // If this object was disposed before skip disposing. // if (m_DoThreads == false) return; m_BinaryCaster = null; m_SoapCaster = null; if (m_NetStream != null) { m_NetStream.Close(); m_NetStream = null; } if (m_ClientSocket != null && m_ClientSocket.Connected) { m_ClientSocket.Shutdown(SocketShutdown.Both); m_ClientSocket.Close(); } // // Closing the threads // if (m_NewDataScanner != null) CloseThread(); m_TargetServerInfo.Dispose(); m_TargetServerInfo = null; m_ClientName = null; m_ClientSocket = null; m_ByPassDataToSend = null; } // //********************************************************************** /// <summary> /// This function keep on going till it's make sure all /// the threads are fully stoped. /// </summary> //********************************************************************** // private void CloseThread() { // // Stoping the infinite threads. // m_DoThreads = false; // // Making the priority of th threads high so that they will // execute the Abort command as soone as possible. // m_GeneralPriority = 100000; // // If the ThreadState is comb' of suspend requested & WaitSleepJoin // while ((byte)m_NewDataScanner.ThreadState == 34) Thread.Sleep(100); // // Before aborting the threads I must be sure non of them is in suspend mode // if (m_NewDataScanner.ThreadState == ThreadState.Suspended || (byte)m_NewDataScanner.ThreadState == 96) m_NewDataScanner.Resume(); } #endregion #region Properties // //********************************************************************** /// <summary> /// Indicated weather the <c>Client</c> is ready to connect the server. /// If not, the server info is unset or illegal. Use <c>TargetServerInfo</c> /// property to solve this problem. /// </summary> /// <value> /// <c>true</c> if this instance is ready to connect; otherwise, <c>false</c>. /// </value> //********************************************************************** // [Category("Misc"), Description("Indicated weather the Client is ready to connect the server.")] public bool IsReadyToConnect { get { return (m_TargetServerInfo != null && m_TargetServerInfo.IsLegal); } } // //********************************************************************** /// <summary> /// Gets the status of the communication test (Runs from the function <c>TestCommunication</c>) /// This test isn't runs by by itself and it is intended only for communication with /// <c>Server</c> server type. /// </summary> /// <value>The COM test status.</value> //********************************************************************** // [Category("Misc"), Description("Gets the status of the communication test.")] public TestingStatusType ComTestStatus { get { return m_ComTestStatus; } } // //********************************************************************** /// <summary> /// Gets the last time the client sent data to the server or the time that the /// <c>Client</c> object created (if no data was sent). /// </summary> /// <value>The last time data sent.</value> //********************************************************************** // [Category("Misc"), Description("Gets the last time the client sent data to the server or the time that the Client object created (if no data was sent).")] public DateTime LastTimeDataSent { get { return m_LastDataSentTime; } } // //********************************************************************** /// <summary> /// Gets or sets the information on the server that this /// <c>Client</c> will connect to. /// </summary> /// <value>The target server info.</value> /// <exception cref="SocketException"> /// When setting non legal ServerInfo. /// </exception> //********************************************************************** // [Category("Configurations"), Description("Gets or sets the information on the server that this Client will connect to.")] public ServerInfo TargetServerInfo { get { return m_TargetServerInfo; } set { if (!value.IsLegal) throw new SocketException("The server's IP address or name isn't legal."); m_TargetServerInfo = value; } } // //********************************************************************** /// <summary> /// Gets or sets the general <c>Priority</c> of this <c>Client</c> process /// and controls the response time of the <c>Client</c> to some events. /// </summary> /// <value>The general priority.</value> /// <remarks> /// This priority isn't actually priority over other process instead, /// it's controls the number of times, the proccess will call during a time sequence. /// </remarks> //********************************************************************** // [Category("Configurations"), Description("Gets or sets the general priority of this Client process " + "and controls the respoce time of the Client to some events.")] public SocketPriorityType GeneralPriority { get { return PriorityTool.Resolve(m_GeneralPriority); } set { m_GeneralPriority = PriorityTool.GetValue(value); } } // //********************************************************************** /// <summary> /// Gets or sets the actual priority of executing new data scan process /// over other system threads. /// </summary> /// <value>The data scan priority.</value> //********************************************************************** // [Category("Configurations"), Description("Gets or sets the actual priority of executing new data scan process" + " over other system threads..")] public ThreadPriority DataScanPriority { get { return m_DataScanPriority; } set { m_DataScanPriority = value; if (m_NewDataScanner != null) m_NewDataScanner.Priority = value; } } // //********************************************************************** /// <summary> /// Gets or sets the name of this <c>Client</c> object. /// </summary> /// <value>The name.</value> //********************************************************************** // [Category("Misc"), Description("Gets or sets the name of this Client object.")] public string Name { get { return m_ClientName; } set { if (value == null) throw new SocketException("Client name cannot be null."); m_ClientName = value; } } // //********************************************************************** /// <summary> /// Gets the <c>Socket</c> of this <c>Client</c> object. /// </summary> /// <value>The client socket.</value> //********************************************************************** // [Category("Data"), Description("Gets the socket of this <c>Client</c> object.")] public Socket ClientSocket { get { return m_ClientSocket; } } // //********************************************************************** /// <summary> /// Gets the <c>NetworkStream</c> of the <c>Client</c>'s socket. /// </summary> /// <value>The network stream.</value> //********************************************************************** // [Category("Data"), Description("Gets the <c>NetworkStream</c> of the <c>Client</c>'s socket.")] public NetworkStream NetworkStream { get { return m_NetStream; } } // //********************************************************************** /// <summary> /// Indicated whether the <c>Client</c> is connected to a server. /// This info is reffrenced to the last data was /// send\received\connection was made so don't trust on it right away /// unless you've just send\received\connection was made /// (Alternative is to call <c>ConnectionTest</c> function) /// </summary> /// <value> /// <c>true</c> if this instance is connected; otherwise, <c>false</c>. /// </value> //********************************************************************** // [Category("Misc"), Description("Indicated whether the Client is connected to a server.")] public bool IsConnected { get { return m_ClientSocket != null && m_ClientSocket.Connected && m_NetStream != null; } } #endregion #region Public events // //********************************************************************** /// <summary> /// Invoked when data is sent from the client to the server. /// </summary> //********************************************************************** // [Description("Invoked when data is sent from the client to the server."), Category("Misc")] public event DataSent_EventHandler DataSent { add { OnDataSent += value; } remove { OnDataSent -= value; } } // //********************************************************************** /// <summary> /// Invoked when data is arriving from the client to the client. /// </summary> //********************************************************************** // [Description("Invoked when data is arriving from the client to the client."), Category("Misc")] public event DataArrived2Client_EventHandler DataArrived { add { OnDataArrived += value; } remove { OnDataArrived -= value; } } // //********************************************************************** /// <summary> /// Invoked when a function communication test function starts. /// </summary> //********************************************************************** // [Description("Invoked when a fuction communication test function starts."), Category("Misc")] public event ComTestStart_EventHandler ComTestStarted { add { OnComTestStarted += value; } remove { OnComTestStarted -= value; } } // //********************************************************************** /// <summary> /// Invoked when a function communication test function ends. /// </summary> //********************************************************************** // [Description("Invoked when a fuction communication test function ends."), Category("Misc")] public event ComTestEnd_EventHandler ComTestEnded { add { OnComTestEnded += value; } remove { OnComTestEnded -= value; } } // //********************************************************************** /// <summary> /// Invoked when the client attempts to connect the server. /// </summary> //********************************************************************** // [Description("Invoked when the client attempts to connect the server."), Category("Misc")] public event Connecting_EventHandler Connecting { add { OnConnecting = value; } remove { OnConnecting -= value; } } // //********************************************************************** /// <summary> /// Invoked when the client is successfully connected to the server. /// </summary> //********************************************************************** // [Description("Invoked when the client is successfully connected to the server."), Category("Misc")] public event Connected_EventHandler Connected { add { OnConnected = value; } remove { OnConnected -= value; } } // //********************************************************************** /// <summary> /// Invoked when the client is begins disconnecting from the server. /// </summary> //********************************************************************** // [Description("Invoked when the client is begins disconnecting from the server."), Category("Misc")] public event Disconnecting_EventHandler Disconnecting { add { OnDisconnecting = value; } remove { OnDisconnecting -= value; } } // //********************************************************************** /// <summary> /// Invoked when the client is begins disconnecting from the server. /// </summary> //********************************************************************** // [Description("Invoked when the client is begins disconnecting from the server."), Category("Misc")] public event Disconnected_EventHandler Disconnected { add { OnDisconnected = value; } remove { OnDisconnected -= value; } } // //********************************************************************** /// <summary> /// Involed when a connection attempt to the server is failed, /// (Attempted to connect to server for some time without results). /// </summary> //********************************************************************** // [Description("Involed when a connection attempt to the server is failed (Attempted to connect to server for some time without results)."), Category("Misc")] public event ConnectionTimeOutError_EventHandler ConnectionTimeOut { add { OnConnectionTimeOut = value; } remove { OnConnectionTimeOut -= value; } } // //********************************************************************** /// <summary> /// Invoked when error accures while sending data asynchroniclly using /// <c>DataSendAsync</c> only. /// </summary> //********************************************************************** // [Description("Invoked when error accures while sending data asynchroniclly using DataSendAsync only."), Category("Misc")] public event DataSendAsyncError_EventHandler DataSendAsyncError { add { OnDataSendAsyncError = value; } remove { OnDataSendAsyncError -= value; } } // //********************************************************************** /// <summary> /// Invoked when error accures while testing communication asynchroniclly using /// <c>TestCommunicationAsync</c> only. /// </summary> //********************************************************************** // [Description("Invoked when error accures while testing communication asynchroniclly using TestCommunicationAsync only."), Category("Misc")] public event TestComAsyncError_EventHandler TestComAsyncError { add { OnTestComAsyncError = value; } remove { OnTestComAsyncError -= value; } } #endregion #region Public functions // //********************************************************************** /// <summary> /// Creates new instance of anonymous <c>Client</c>. /// </summary> //********************************************************************** // public Client() { // // No data on server to connect to. // m_TargetServerInfo = null; } // //********************************************************************** /// <summary> /// Creates new instance of <c>Client</c> with a name. /// </summary> /// <param name="m_ClientName">The name of this Client</param> //********************************************************************** // public Client(string m_ClientName) { // // No data on server to connect to. // m_TargetServerInfo = null; Name = m_ClientName; } // //********************************************************************** /// <summary> /// Creates new instance of anonymous <c>Client</c>. /// </summary> /// <param name="TargetServer">The server to connect to.</param> //********************************************************************** // public Client(Server TargetServer) { m_TargetServerInfo = TargetServer.ServerInfo; } // //********************************************************************** /// <summary> /// Creates new instance of <c>Client</c> with a name. /// </summary> /// <param name="TargetServer">The server to connect to.</param> /// <param name="m_ClientName">The name of this Client</param> //********************************************************************** // public Client(Server TargetServer, string m_ClientName) { m_TargetServerInfo = TargetServer.ServerInfo; Name = m_ClientName; } // //********************************************************************** /// <summary> /// Creates new instance of anonymous <c>Client</c>. /// </summary> /// <param name="TargetServerInfo">Information about the server to connect to.</param> /// <exception cref="SocketException"> /// When the given ServerInfo isn't legal. /// </exception> //********************************************************************** // public Client(ServerInfo TargetServerInfo) { if (!TargetServerInfo.IsLegal) throw new SocketException("The server's IP address or name isn't legal."); m_TargetServerInfo = TargetServerInfo; } // //********************************************************************** /// <summary> /// Creates new instance of <c>Client</c> with a name. /// </summary> /// <param name="TargetServerInfo">Information about the server to connect to.</param> /// <param name="m_ClientName">The name of this <c>Client</c></param> /// <exception cref="SocketException"> /// When the given ServerInfo isn't legal. /// </exception> //********************************************************************** // public Client(ServerInfo TargetServerInfo, string m_ClientName) { if (!TargetServerInfo.IsLegal) throw new SocketException("The server's IP address or name isn't legal."); m_TargetServerInfo = TargetServerInfo; Name = m_ClientName; } // //********************************************************************** /// <summary> /// Attempts to create a connection to the server if not connected already. /// This function isn't synchronized so the client will not be connected right after /// the function (using the <c>SendData()</c> functions is safe though and taking /// it under consideration). Any way you can always use the <c>IsConnected</c> property. /// </summary> /// <exception cref="SocketException"> /// Thrown when the information about the server is /// incorrect or unset and on general connection errors. /// </exception> /// <remarks> /// This function calls another asynchronic function that attempts to establish /// a connection. Within this function, if no connection made, event handler /// named <c>OnConnectionTimeOut()</c> is called instead of using Exceptions /// (you better use this one). /// </remarks> //********************************************************************** // public void ConnectToServerAsync() { // // If the connection was disconnect before, create new socket. // if (m_ClientSocket == null) m_ClientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); // // No need to connect again. // if (m_ClientSocket.Connected) return; if (m_TargetServerInfo == null) throw new SocketException("Client Cannot connect a server, " + "(Set the target server info first)."); if (!m_TargetServerInfo.IsLegal) throw new SocketException("Client Cannot connect a server, " + "(target server info is illegal)."); AsyncCallback CallBack = new AsyncCallback(ConnectingToServer); try { m_ClientSocket.BeginConnect(TargetServerInfo.IPAddress, TargetServerInfo.PortNumner, CallBack, m_ClientSocket); } catch (Exception ex) { throw new SocketException("Error, cannot connect to server " + TargetServerInfo, ex); } } // //********************************************************************** /// <summary> /// Disconnect from server and closes the client <c>Socket</c> if connected. /// </summary> //********************************************************************** // public void DisconnectFromServer() { // // Calling event handler // if (OnDisconnecting != null) OnDisconnecting(); if (!IsConnected) return; // // Stop scanning for new data (Thread restarts when new connection is made) // if (m_NewDataScanner != null) m_NewDataScanner.Suspend(); // // Send Special Signal to tell the server to release the socket // only if the server is a Server type. // try { if (TargetServerInfo.IsServer) SendCommand(SocketCommandType.Disconnecting); } catch (Exception) { } // // Give the server least 4 second to handle the last data we sent. // while ((DateTime.Now - m_LastDataSentTime).TotalSeconds < 4) Thread.Sleep(200); try { m_NetStream.Close(); m_ClientSocket.Shutdown(SocketShutdown.Both); m_ClientSocket.Close(); } catch (Exception) { } finally { m_ClientSocket = null; m_NetStream = null; m_NetStream = null; } // // Calling event handler // if (OnDisconnected != null) OnDisconnected(); } // //********************************************************************** /// <summary> /// This is the asynchronic overload of the function(Not waiting for results). /// Disconnect from server and closes the client socket if connected. /// </summary> //********************************************************************** // public void DisconnectFromServerAsync() { // // Run a separate thread to disconnect // new Thread(new ThreadStart(DisconnectFromServer)).Start(); } // //********************************************************************** /// <summary> /// Sending an object to the server. /// </summary> /// <param name="DataToSend">The object to send to the server.</param> /// <remarks>The <c>DataToSend</c> object must be serializable</remarks> /// <exception cref="SocketException"> /// Thrown on attempt to send data when client is disconneted, or when /// connection was made during attempt to send data. /// </exception> //********************************************************************** // public void SendData(Object DataToSend) { m_ByPassDataToSend = null; //Reseting to default value and getting ready to re-initilezed. lock (this) // Not allowing 2 async data sending simultaneously { // // No connection attempt was made. // if (m_ClientSocket == null) { // // If this is asynchronic call from m_ByPassDataToSend() call evet handler instead of exception // if (m_IsAsyncMode) { m_IsAsyncMode = false; //Returning to default mode. //Is there event handler call it if (OnDataSendAsyncError != null) OnDataSendAsyncError("Error on attempt to send data when the client is disconnected."); return; } else throw new SocketException("Error on attempt to send data when the client is disconnected."); } // // In case we're during connection establishment wait 5 sec' for connection // for (short i = 0; !IsConnected && i < 25; ++i) Thread.Sleep(200); // // If still not connected throw exception // if (!IsConnected) { // // If this is asynchronic call from m_ByPassDataToSend() // if (m_IsAsyncMode) { // // Returning to default mode. // m_IsAsyncMode = false; // // If there is event handler call it // if (OnDataSendAsyncError != null) OnDataSendAsyncError("Error on attempt to send data during connection establishment."); return; } else throw new SocketException("Error on attempt to send data during connection establishment."); } if (IsConnected) { // // convert to bytes // Byte[] bytes = Encoding.UTF8.GetBytes(DataToSend.ToString()); m_NetStream.Write(bytes, 0, bytes.Length); m_NetStream.Flush(); //m_BinaryCaster.Serialize(m_NetStream, DataToSend); //m_SoapCaster.Serialize(m_NetStream, DataToSend); } // // Updating last send time // m_LastDataSentTime = DateTime.Now; } // // don't invoke if the data was special command // if (IsConnected && OnDataSent != null && DataToSend.GetType().Name != "SocketCommandType") { OnDataSent(DataToSend); } } // //********************************************************************** /// <summary> /// This is the asynchronic overload of the function(Not waiting for results). /// </summary> /// <param name="DataToSend">The object to send to the server.</param> /// <remarks> /// Since this function is asynchronic, no exceptions are thrown /// Instead use the <c>OnDataSendAsyncError</c> event handler. /// The send object must be serializable. Sending nulled object will take no action. /// </remarks> //********************************************************************** // public void SendDataAsync(object DataToSend) { if (DataToSend == null) return; while (m_ByPassDataToSend != null) Thread.Sleep(15); // Sleep till ready to use m_ByPassDataToSend // // Run a separate thread to send data // m_ByPassDataToSend = DataToSend; new Thread(new ThreadStart(SendDataByPass)).Start(); } // //********************************************************************** /// <summary> /// Testing the comunication with an <c>Server</c> type server by /// sending a message and waiting for conformation from the server. /// </summary> /// <remarks> /// This function should be used only when connecting to <c>Server</c> type. /// In addition the <c>ComTestStatus</c> is been updated(use it to get the test results). /// Use this only when needed cos' it cost alot of time. /// </remarks> //********************************************************************** // public void TestCommunication() { // // At start assum that test is failed. // m_ComTestStatus = TestingStatusType.TestFailed; if (!m_TargetServerInfo.IsServer)//Faild { // // If this is asynchronic call // if (m_IsTestComAsyncOn && OnTestComAsyncError != null) { OnTestComAsyncError("Cannot use 'TestCommunication' funcion when the target server isn't Server."); m_IsTestComAsyncOn = false; return; } throw new SocketException("Cannot use 'TestCommunication' funcion when the target server isn't Server."); } if (!IsReadyToConnect) return;//Failed try { // // Testing for real and changing status // m_ComTestStatus = TestingStatusType.Testing; SendCommand(SocketCommandType.TestCom); } catch (Exception) { // // On comm exception Faild, rechange status to Failed. // m_ComTestStatus = TestingStatusType.TestFailed; return; } // // Give the server 15 sec' to come up with an answer(look at ScanForData function) // DateTime TestStartTime = DateTime.Now; if (OnComTestStarted != null) OnComTestStarted(); while ((DateTime.Now - TestStartTime).Seconds < 15 && m_ComTestStatus == TestingStatusType.Testing) Thread.Sleep(200); if (m_ComTestStatus == TestingStatusType.TestedOK) { if (OnComTestEnded != null) OnComTestEnded(); return; } else { // // If time out and no response set to failed // m_ComTestStatus = TestingStatusType.TestFailed; if (OnComTestEnded != null) OnComTestEnded(); return; } } // //********************************************************************** /// <summary> /// This is the asynchronic overload of the function(Not waiting for test results). /// Testing the comunication with an <c>Server</c> type server by /// sending a message and waiting for conformation from the server. /// This function should be used only when connecting to <c>Server</c> type. /// In addition the <c>ComTestStatus</c> is updated. /// </summary> /// <remarks> /// Since this function is asynchronic, no exceptions are thrown /// Instead use the <c>OnTestComAsyncError</c> event handler. /// </remarks> //********************************************************************** // public void TestCommunicationAsync() { // // Run a separate thread to test // m_IsTestComAsyncOn = true; new Thread(new ThreadStart(TestCommunication)).Start(); } // //********************************************************************** /// <summary> /// Returns the string representation of the <c>Client</c> Object. /// </summary> /// <returns> /// string representation of the <c>Client</c> Object. /// </returns> //********************************************************************** // public override string ToString() { if (IsReadyToConnect) { return (Name != "Anonymous") ? "Client: " + Name + " set on server: " + TargetServerInfo.ToString() : "Anonymous client set on server: " + TargetServerInfo.ToString(); } else { return (Name != "Anonymous") ? "Client: " + Name + " target server isn't set." : "Anonymous client " + "target server isn't set."; } } #endregion #region Private functions // //********************************************************************** /// <summary> /// Called when a connection attempt with the server is made. /// </summary> /// <param name="ConnectionStatus">Information about the connection attempt.</param> //********************************************************************** // private void ConnectingToServer(IAsyncResult ConnectionStatus) { if (OnConnecting != null) OnConnecting(); for (byte i = 0; i < 10 && !ConnectionStatus.IsCompleted; ++i) Thread.Sleep(500); // // If connection failed, call the proper event // if (!m_ClientSocket.Connected) { try { m_ClientSocket.Close(); } catch (System.Exception) { } m_ClientSocket = null; if (OnConnectionTimeOut != null) OnConnectionTimeOut(); return; } // // Set the networkStream (Socket must be connected by now) // m_NetStream = new NetworkStream(m_ClientSocket); // // creates new thread to handle new data comming from server. // if (m_NewDataScanner == null) { m_NewDataScanner = new Thread(new ThreadStart(ScanForData)); m_NewDataScanner.Priority = m_DataScanPriority; m_NewDataScanner.Start(); } else { // if the thread cannot be resume, recreate it try { m_NewDataScanner.Resume(); } catch (Exception) { m_NewDataScanner = new Thread(new ThreadStart(ScanForData)); m_NewDataScanner.Priority = m_DataScanPriority; m_NewDataScanner.Start(); } } if (OnConnected != null) OnConnected(); } // //********************************************************************** /// <summary> /// Sending a spechial command or message to the server with /// the <c>SendData</c> function. /// </summary> /// <param name="Command">The command\message to the server.</param> /// <remarks> /// This should be used only when communicating with <c>Server</c> server type. /// </remarks> //********************************************************************** // private void SendCommand(SocketCommandType Command) { SendData(Command); } // //********************************************************************** /// <summary> /// This function scans for data dispached from server machine constantly. /// </summary> //********************************************************************** // private void ScanForData() { while (true) { // // Requesting to close the thread(when Dispose() is called) // if (!m_DoThreads) Thread.CurrentThread.Abort(); // // If Socket isn't connected suspend this thread (resume on reconnect) // if (!m_ClientSocket.Connected) m_NewDataScanner.Suspend(); // // Is there data for us? // if (m_ClientSocket.Available > 0) { // // If IOexceprion is thrown here, it's probably cos' the server sent data // and closed the connection right away.(To fix let the server wait a bit // before closing the connection. // byte[] recieveArray = new byte[m_ClientSocket.Available]; StringBuilder completeMessage = new StringBuilder(); completeMessage.Capacity = recieveArray.Length; // // Incoming message may be larger than the buffer size. // do { int numberOfBytesRead = m_NetStream.Read(recieveArray, 0, recieveArray.Length); completeMessage.AppendFormat("{0}", Encoding.ASCII.GetString(recieveArray, 0, numberOfBytesRead)); } while (m_NetStream.DataAvailable); m_NetStream.Flush(); Object Data = completeMessage.ToString(); // // If the data is a special command\msg from Server // if (Data.GetType().Name == "SocketCommandType") { switch ((SocketCommandType)Data) { // // f the data was sent as a response for this Client // test communication request, update the testing status. // case SocketCommandType.TestComOK: if (m_ComTestStatus == TestingStatusType.Testing) m_ComTestStatus = TestingStatusType.TestedOK; break; // // If the data was sent to test communication, do nothing. // case SocketCommandType.TestCom: break; // // If the server disconnecting us, lets close our socket) // case SocketCommandType.Disconnecting: try { m_NetStream.Close(); m_ClientSocket.Shutdown(SocketShutdown.Both); m_ClientSocket.Close(); } catch (Exception) { } finally { m_ClientSocket = null; m_NetStream = null; m_NetStream = null; m_NewDataScanner.Suspend(); } break; } } //I f data isn't special command, send is to the user else if (OnDataArrived != null) OnDataArrived(Data); } // // Give the CPU a break // Thread.Sleep((int)(150 / m_GeneralPriority)); } } // //********************************************************************** /// <summary> /// This function calls the <c>SendData</c> function and sends as an argument /// the <c>m_ByPassDataToSend</c> private member. It's should run as a separate /// thraed and by so cating asynchronic version of <c>SendData.</c> /// </summary> /// <remarks> /// <c>m_ByPassDataToSend</c> should refer the data to be sent. /// </remarks> //********************************************************************** // private void SendDataByPass() { SendData(m_ByPassDataToSend); m_IsAsyncMode = false; // Returning to default mode. } #endregion } }
using Lucene.Net.Support; using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.IO; namespace Lucene.Net.Util.Fst { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /// <summary> /// Static helper methods. /// <para/> /// @lucene.experimental /// </summary> public sealed class Util // LUCENENET TODO: Fix naming conflict with containing namespace { private Util() { } /// <summary> /// Looks up the output for this input, or <c>null</c> if the /// input is not accepted. /// </summary> public static T Get<T>(FST<T> fst, Int32sRef input) { // TODO: would be nice not to alloc this on every lookup var arc = fst.GetFirstArc(new FST.Arc<T>()); var fstReader = fst.GetBytesReader(); // Accumulate output as we go T output = fst.Outputs.NoOutput; for (int i = 0; i < input.Length; i++) { if (fst.FindTargetArc(input.Int32s[input.Offset + i], arc, arc, fstReader) == null) { return default(T); } output = fst.Outputs.Add(output, arc.Output); } if (arc.IsFinal) { return fst.Outputs.Add(output, arc.NextFinalOutput); } else { return default(T); } } // TODO: maybe a CharsRef version for BYTE2 /// <summary> /// Looks up the output for this input, or <c>null</c> if the /// input is not accepted /// </summary> public static T Get<T>(FST<T> fst, BytesRef input) { Debug.Assert(fst.InputType == FST.INPUT_TYPE.BYTE1); var fstReader = fst.GetBytesReader(); // TODO: would be nice not to alloc this on every lookup var arc = fst.GetFirstArc(new FST.Arc<T>()); // Accumulate output as we go T output = fst.Outputs.NoOutput; for (int i = 0; i < input.Length; i++) { if (fst.FindTargetArc(input.Bytes[i + input.Offset] & 0xFF, arc, arc, fstReader) == null) { return default(T); } output = fst.Outputs.Add(output, arc.Output); } if (arc.IsFinal) { return fst.Outputs.Add(output, arc.NextFinalOutput); } else { return default(T); } } /// <summary> /// Reverse lookup (lookup by output instead of by input), /// in the special case when your FSTs outputs are /// strictly ascending. This locates the input/output /// pair where the output is equal to the target, and will /// return <c>null</c> if that output does not exist. /// /// <para/>NOTE: this only works with <see cref="T:FST{long?}"/>, only /// works when the outputs are ascending in order with /// the inputs. /// For example, simple ordinals (0, 1, /// 2, ...), or file offets (when appending to a file) /// fit this. /// </summary> public static Int32sRef GetByOutput(FST<long?> fst, long targetOutput) { var @in = fst.GetBytesReader(); // TODO: would be nice not to alloc this on every lookup FST.Arc<long?> arc = fst.GetFirstArc(new FST.Arc<long?>()); FST.Arc<long?> scratchArc = new FST.Arc<long?>(); Int32sRef result = new Int32sRef(); return GetByOutput(fst, targetOutput, @in, arc, scratchArc, result); } /// <summary> /// Expert: like <see cref="Util.GetByOutput(FST{long?}, long)"/> except reusing /// <see cref="FST.BytesReader"/>, initial and scratch Arc, and result. /// </summary> public static Int32sRef GetByOutput(FST<long?> fst, long targetOutput, FST.BytesReader @in, FST.Arc<long?> arc, FST.Arc<long?> scratchArc, Int32sRef result) { long output = arc.Output.Value; int upto = 0; //System.out.println("reverseLookup output=" + targetOutput); while (true) { //System.out.println("loop: output=" + output + " upto=" + upto + " arc=" + arc); if (arc.IsFinal) { long finalOutput = output + arc.NextFinalOutput.Value; //System.out.println(" isFinal finalOutput=" + finalOutput); if (finalOutput == targetOutput) { result.Length = upto; //System.out.println(" found!"); return result; } else if (finalOutput > targetOutput) { //System.out.println(" not found!"); return null; } } if (FST<long?>.TargetHasArcs(arc)) { //System.out.println(" targetHasArcs"); if (result.Int32s.Length == upto) { result.Grow(1 + upto); } fst.ReadFirstRealTargetArc(arc.Target, arc, @in); if (arc.BytesPerArc != 0) { int low = 0; int high = arc.NumArcs - 1; int mid = 0; //System.out.println("bsearch: numArcs=" + arc.numArcs + " target=" + targetOutput + " output=" + output); bool exact = false; while (low <= high) { mid = (int)((uint)(low + high) >> 1); @in.Position = arc.PosArcsStart; @in.SkipBytes(arc.BytesPerArc * mid); var flags = (sbyte)@in.ReadByte(); fst.ReadLabel(@in); long minArcOutput; if ((flags & FST.BIT_ARC_HAS_OUTPUT) != 0) { long arcOutput = fst.Outputs.Read(@in).Value; minArcOutput = output + arcOutput; } else { minArcOutput = output; } if (minArcOutput == targetOutput) { exact = true; break; } else if (minArcOutput < targetOutput) { low = mid + 1; } else { high = mid - 1; } } if (high == -1) { return null; } else if (exact) { arc.ArcIdx = mid - 1; } else { arc.ArcIdx = low - 2; } fst.ReadNextRealArc(arc, @in); result.Int32s[upto++] = arc.Label; output += arc.Output.Value; } else { FST.Arc<long?> prevArc = null; while (true) { //System.out.println(" cycle label=" + arc.label + " output=" + arc.output); // this is the min output we'd hit if we follow // this arc: long minArcOutput = output + arc.Output.Value; if (minArcOutput == targetOutput) { // Recurse on this arc: //System.out.println(" match! break"); output = minArcOutput; result.Int32s[upto++] = arc.Label; break; } else if (minArcOutput > targetOutput) { if (prevArc == null) { // Output doesn't exist return null; } else { // Recurse on previous arc: arc.CopyFrom(prevArc); result.Int32s[upto++] = arc.Label; output += arc.Output.Value; //System.out.println(" recurse prev label=" + (char) arc.label + " output=" + output); break; } } else if (arc.IsLast) { // Recurse on this arc: output = minArcOutput; //System.out.println(" recurse last label=" + (char) arc.label + " output=" + output); result.Int32s[upto++] = arc.Label; break; } else { // Read next arc in this node: prevArc = scratchArc; prevArc.CopyFrom(arc); //System.out.println(" after copy label=" + (char) prevArc.label + " vs " + (char) arc.label); fst.ReadNextRealArc(arc, @in); } } } } else { //System.out.println(" no target arcs; not found!"); return null; } } } /// <summary> /// Represents a path in TopNSearcher. /// <para/> /// @lucene.experimental /// </summary> public class FSTPath<T> { public FST.Arc<T> Arc { get; set; } public T Cost { get; set; } public Int32sRef Input { get; private set; } /// <summary> /// Sole constructor </summary> public FSTPath(T cost, FST.Arc<T> arc, Int32sRef input) { this.Arc = (new FST.Arc<T>()).CopyFrom(arc); this.Cost = cost; this.Input = input; } public override string ToString() { return "input=" + Input + " cost=" + Cost; } } /// <summary> /// Compares first by the provided comparer, and then /// tie breaks by <see cref="FSTPath{T}.Input"/>. /// </summary> private class TieBreakByInputComparer<T> : IComparer<FSTPath<T>> { internal readonly IComparer<T> comparer; public TieBreakByInputComparer(IComparer<T> comparer) { this.comparer = comparer; } public virtual int Compare(FSTPath<T> a, FSTPath<T> b) { int cmp = comparer.Compare(a.Cost, b.Cost); if (cmp == 0) { return a.Input.CompareTo(b.Input); } else { return cmp; } } } /// <summary> /// Utility class to find top N shortest paths from start /// point(s). /// </summary> public class TopNSearcher<T> { private readonly FST<T> fst; private readonly FST.BytesReader bytesReader; private readonly int topN; private readonly int maxQueueDepth; private readonly FST.Arc<T> scratchArc = new FST.Arc<T>(); internal readonly IComparer<T> comparer; internal SortedSet<FSTPath<T>> queue = null; private object syncLock = new object(); /// <summary> /// Creates an unbounded TopNSearcher </summary> /// <param name="fst"> the <see cref="Lucene.Net.Util.Fst.FST{T}"/> to search on </param> /// <param name="topN"> the number of top scoring entries to retrieve </param> /// <param name="maxQueueDepth"> the maximum size of the queue of possible top entries </param> /// <param name="comparer"> the comparer to select the top N </param> public TopNSearcher(FST<T> fst, int topN, int maxQueueDepth, IComparer<T> comparer) { this.fst = fst; this.bytesReader = fst.GetBytesReader(); this.topN = topN; this.maxQueueDepth = maxQueueDepth; this.comparer = comparer; queue = new SortedSet<FSTPath<T>>(new TieBreakByInputComparer<T>(comparer)); } /// <summary> /// If back plus this arc is competitive then add to queue: /// </summary> protected virtual void AddIfCompetitive(FSTPath<T> path) { Debug.Assert(queue != null); T cost = fst.Outputs.Add(path.Cost, path.Arc.Output); //System.out.println(" addIfCompetitive queue.size()=" + queue.size() + " path=" + path + " + label=" + path.arc.label); if (queue.Count == maxQueueDepth) { FSTPath<T> bottom = queue.Max; int comp = comparer.Compare(cost, bottom.Cost); if (comp > 0) { // Doesn't compete return; } else if (comp == 0) { // Tie break by alpha sort on the input: path.Input.Grow(path.Input.Length + 1); path.Input.Int32s[path.Input.Length++] = path.Arc.Label; int cmp = bottom.Input.CompareTo(path.Input); path.Input.Length--; // We should never see dups: Debug.Assert(cmp != 0); if (cmp < 0) { // Doesn't compete return; } } // Competes } else { // Queue isn't full yet, so any path we hit competes: } // copy over the current input to the new input // and add the arc.label to the end Int32sRef newInput = new Int32sRef(path.Input.Length + 1); Array.Copy(path.Input.Int32s, 0, newInput.Int32s, 0, path.Input.Length); newInput.Int32s[path.Input.Length] = path.Arc.Label; newInput.Length = path.Input.Length + 1; FSTPath<T> newPath = new FSTPath<T>(cost, path.Arc, newInput); queue.Add(newPath); if (queue.Count == maxQueueDepth + 1) { // LUCENENET NOTE: SortedSet doesn't have atomic operations, // so we need to add some thread safety just in case. // Perhaps it might make sense to wrap SortedSet into a type // that provides thread safety. lock (syncLock) { queue.Remove(queue.Max); } } } /// <summary> /// Adds all leaving arcs, including 'finished' arc, if /// the node is final, from this node into the queue. /// </summary> public virtual void AddStartPaths(FST.Arc<T> node, T startOutput, bool allowEmptyString, Int32sRef input) { // De-dup NO_OUTPUT since it must be a singleton: if (startOutput.Equals(fst.Outputs.NoOutput)) { startOutput = fst.Outputs.NoOutput; } FSTPath<T> path = new FSTPath<T>(startOutput, node, input); fst.ReadFirstTargetArc(node, path.Arc, bytesReader); //System.out.println("add start paths"); // Bootstrap: find the min starting arc while (true) { if (allowEmptyString || path.Arc.Label != FST.END_LABEL) { AddIfCompetitive(path); } if (path.Arc.IsLast) { break; } fst.ReadNextArc(path.Arc, bytesReader); } } public virtual TopResults<T> Search() { IList<Result<T>> results = new List<Result<T>>(); //System.out.println("search topN=" + topN); var fstReader = fst.GetBytesReader(); T NO_OUTPUT = fst.Outputs.NoOutput; // TODO: we could enable FST to sorting arcs by weight // as it freezes... can easily do this on first pass // (w/o requiring rewrite) // TODO: maybe we should make an FST.INPUT_TYPE.BYTE0.5!? // (nibbles) int rejectCount = 0; // For each top N path: while (results.Count < topN) { //System.out.println("\nfind next path: queue.size=" + queue.size()); FSTPath<T> path; if (queue == null) { // Ran out of paths //System.out.println(" break queue=null"); break; } // Remove top path since we are now going to // pursue it: // LUCENENET NOTE: SortedSet doesn't have atomic operations, // so we need to add some thread safety just in case. // Perhaps it might make sense to wrap SortedSet into a type // that provides thread safety. lock (syncLock) { path = queue.Min; if (path != null) { queue.Remove(path); } } if (path == null) { // There were less than topN paths available: //System.out.println(" break no more paths"); break; } if (path.Arc.Label == FST.END_LABEL) { //System.out.println(" empty string! cost=" + path.cost); // Empty string! path.Input.Length--; results.Add(new Result<T>(path.Input, path.Cost)); continue; } if (results.Count == topN - 1 && maxQueueDepth == topN) { // Last path -- don't bother w/ queue anymore: queue = null; } //System.out.println(" path: " + path); // We take path and find its "0 output completion", // ie, just keep traversing the first arc with // NO_OUTPUT that we can find, since this must lead // to the minimum path that completes from // path.arc. // For each input letter: while (true) { //System.out.println("\n cycle path: " + path); fst.ReadFirstTargetArc(path.Arc, path.Arc, fstReader); // For each arc leaving this node: bool foundZero = false; while (true) { //System.out.println(" arc=" + (char) path.arc.label + " cost=" + path.arc.output); // tricky: instead of comparing output == 0, we must // express it via the comparer compare(output, 0) == 0 if (comparer.Compare(NO_OUTPUT, path.Arc.Output) == 0) { if (queue == null) { foundZero = true; break; } else if (!foundZero) { scratchArc.CopyFrom(path.Arc); foundZero = true; } else { AddIfCompetitive(path); } } else if (queue != null) { AddIfCompetitive(path); } if (path.Arc.IsLast) { break; } fst.ReadNextArc(path.Arc, fstReader); } Debug.Assert(foundZero); if (queue != null) { // TODO: maybe we can save this copyFrom if we // are more clever above... eg on finding the // first NO_OUTPUT arc we'd switch to using // scratchArc path.Arc.CopyFrom(scratchArc); } if (path.Arc.Label == FST.END_LABEL) { // Add final output: //Debug.WriteLine(" done!: " + path); T finalOutput = fst.Outputs.Add(path.Cost, path.Arc.Output); if (AcceptResult(path.Input, finalOutput)) { //Debug.WriteLine(" add result: " + path); results.Add(new Result<T>(path.Input, finalOutput)); } else { rejectCount++; } break; } else { path.Input.Grow(1 + path.Input.Length); path.Input.Int32s[path.Input.Length] = path.Arc.Label; path.Input.Length++; path.Cost = fst.Outputs.Add(path.Cost, path.Arc.Output); } } } return new TopResults<T>(rejectCount + topN <= maxQueueDepth, results); } protected virtual bool AcceptResult(Int32sRef input, T output) { return true; } } /// <summary> /// Holds a single input (<see cref="Int32sRef"/>) + output, returned by /// <see cref="ShortestPaths"/>. /// </summary> public sealed class Result<T> { public Int32sRef Input { get; private set; } public T Output { get; private set; } public Result(Int32sRef input, T output) { this.Input = input; this.Output = output; } } /// <summary> /// Holds the results for a top N search using <see cref="TopNSearcher{T}"/> /// </summary> public sealed class TopResults<T> : IEnumerable<Result<T>> { /// <summary> /// <c>true</c> iff this is a complete result ie. if /// the specified queue size was large enough to find the complete list of results. this might /// be <c>false</c> if the <see cref="TopNSearcher{T}"/> rejected too many results. /// </summary> public bool IsComplete { get; private set; } /// <summary> /// The top results /// </summary> public IList<Result<T>> TopN { get; private set; } internal TopResults(bool isComplete, IList<Result<T>> topN) { this.TopN = topN; this.IsComplete = isComplete; } public IEnumerator<Result<T>> GetEnumerator() { return TopN.GetEnumerator(); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return GetEnumerator(); } } /// <summary> /// Starting from node, find the top N min cost /// completions to a final node. /// </summary> public static TopResults<T> ShortestPaths<T>(FST<T> fst, FST.Arc<T> fromNode, T startOutput, IComparer<T> comparer, int topN, bool allowEmptyString) { // All paths are kept, so we can pass topN for // maxQueueDepth and the pruning is admissible: TopNSearcher<T> searcher = new TopNSearcher<T>(fst, topN, topN, comparer); // since this search is initialized with a single start node // it is okay to start with an empty input path here searcher.AddStartPaths(fromNode, startOutput, allowEmptyString, new Int32sRef()); return searcher.Search(); } /// <summary> /// Dumps an <see cref="FST{T}"/> to a GraphViz's <c>dot</c> language description /// for visualization. Example of use: /// /// <code> /// using (TextWriter sw = new StreamWriter(&quot;out.dot&quot;)) /// { /// Util.ToDot(fst, sw, true, true); /// } /// </code> /// /// and then, from command line: /// /// <code> /// dot -Tpng -o out.png out.dot /// </code> /// /// <para/> /// Note: larger FSTs (a few thousand nodes) won't even /// render, don't bother. If the FST is &gt; 2.1 GB in size /// then this method will throw strange exceptions. /// <para/> /// See also <a href="http://www.graphviz.org/">http://www.graphviz.org/</a>. /// </summary> /// <param name="sameRank"> /// If <c>true</c>, the resulting <c>dot</c> file will try /// to order states in layers of breadth-first traversal. This may /// mess up arcs, but makes the output FST's structure a bit clearer. /// </param> /// <param name="labelStates"> /// If <c>true</c> states will have labels equal to their offsets in their /// binary format. Expands the graph considerably. /// </param> public static void ToDot<T>(FST<T> fst, TextWriter @out, bool sameRank, bool labelStates) { const string expandedNodeColor = "blue"; // this is the start arc in the automaton (from the epsilon state to the first state // with outgoing transitions. FST.Arc<T> startArc = fst.GetFirstArc(new FST.Arc<T>()); // A queue of transitions to consider for the next level. IList<FST.Arc<T>> thisLevelQueue = new List<FST.Arc<T>>(); // A queue of transitions to consider when processing the next level. IList<FST.Arc<T>> nextLevelQueue = new List<FST.Arc<T>>(); nextLevelQueue.Add(startArc); //System.out.println("toDot: startArc: " + startArc); // A list of states on the same level (for ranking). IList<int?> sameLevelStates = new List<int?>(); // A bitset of already seen states (target offset). BitArray seen = new BitArray(32); seen.SafeSet((int)startArc.Target, true); // Shape for states. const string stateShape = "circle"; const string finalStateShape = "doublecircle"; // Emit DOT prologue. @out.Write("digraph FST {\n"); @out.Write(" rankdir = LR; splines=true; concentrate=true; ordering=out; ranksep=2.5; \n"); if (!labelStates) { @out.Write(" node [shape=circle, width=.2, height=.2, style=filled]\n"); } EmitDotState(@out, "initial", "point", "white", ""); T NO_OUTPUT = fst.Outputs.NoOutput; var r = fst.GetBytesReader(); // final FST.Arc<T> scratchArc = new FST.Arc<>(); { string stateColor; if (fst.IsExpandedTarget(startArc, r)) { stateColor = expandedNodeColor; } else { stateColor = null; } bool isFinal; T finalOutput; if (startArc.IsFinal) { isFinal = true; finalOutput = startArc.NextFinalOutput.Equals(NO_OUTPUT) ? default(T) : startArc.NextFinalOutput; } else { isFinal = false; finalOutput = default(T); } EmitDotState(@out, Convert.ToString(startArc.Target), isFinal ? finalStateShape : stateShape, stateColor, finalOutput == null ? "" : fst.Outputs.OutputToString(finalOutput)); } @out.Write(" initial -> " + startArc.Target + "\n"); int level = 0; while (nextLevelQueue.Count > 0) { // we could double buffer here, but it doesn't matter probably. //System.out.println("next level=" + level); thisLevelQueue.AddRange(nextLevelQueue); nextLevelQueue.Clear(); level++; @out.Write("\n // Transitions and states at level: " + level + "\n"); while (thisLevelQueue.Count > 0) { FST.Arc<T> arc = thisLevelQueue[thisLevelQueue.Count - 1]; thisLevelQueue.RemoveAt(thisLevelQueue.Count - 1); //System.out.println(" pop: " + arc); if (FST<T>.TargetHasArcs(arc)) { // scan all target arcs //System.out.println(" readFirstTarget..."); long node = arc.Target; fst.ReadFirstRealTargetArc(arc.Target, arc, r); //System.out.println(" firstTarget: " + arc); while (true) { //System.out.println(" cycle arc=" + arc); // Emit the unseen state and add it to the queue for the next level. if (arc.Target >= 0 && !seen.SafeGet((int)arc.Target)) { /* boolean isFinal = false; T finalOutput = null; fst.readFirstTargetArc(arc, scratchArc); if (scratchArc.isFinal() && fst.targetHasArcs(scratchArc)) { // target is final isFinal = true; finalOutput = scratchArc.output == NO_OUTPUT ? null : scratchArc.output; System.out.println("dot hit final label=" + (char) scratchArc.label); } */ string stateColor; if (fst.IsExpandedTarget(arc, r)) { stateColor = expandedNodeColor; } else { stateColor = null; } string finalOutput; if (arc.NextFinalOutput != null && !arc.NextFinalOutput.Equals(NO_OUTPUT)) { finalOutput = fst.Outputs.OutputToString(arc.NextFinalOutput); } else { finalOutput = ""; } EmitDotState(@out, Convert.ToString(arc.Target), stateShape, stateColor, finalOutput); // To see the node address, use this instead: //emitDotState(out, Integer.toString(arc.target), stateShape, stateColor, String.valueOf(arc.target)); seen.SafeSet((int)arc.Target, true); nextLevelQueue.Add((new FST.Arc<T>()).CopyFrom(arc)); sameLevelStates.Add((int)arc.Target); } string outs; if (!arc.Output.Equals(NO_OUTPUT)) { outs = "/" + fst.Outputs.OutputToString(arc.Output); } else { outs = ""; } if (!FST<T>.TargetHasArcs(arc) && arc.IsFinal && !arc.NextFinalOutput.Equals(NO_OUTPUT)) { // Tricky special case: sometimes, due to // pruning, the builder can [sillily] produce // an FST with an arc into the final end state // (-1) but also with a next final output; in // this case we pull that output up onto this // arc outs = outs + "/[" + fst.Outputs.OutputToString(arc.NextFinalOutput) + "]"; } string arcColor; if (arc.Flag(FST.BIT_TARGET_NEXT)) { arcColor = "red"; } else { arcColor = "black"; } Debug.Assert(arc.Label != FST.END_LABEL); @out.Write(" " + node + " -> " + arc.Target + " [label=\"" + PrintableLabel(arc.Label) + outs + "\"" + (arc.IsFinal ? " style=\"bold\"" : "") + " color=\"" + arcColor + "\"]\n"); // Break the loop if we're on the last arc of this state. if (arc.IsLast) { //System.out.println(" break"); break; } fst.ReadNextRealArc(arc, r); } } } // Emit state ranking information. if (sameRank && sameLevelStates.Count > 1) { @out.Write(" {rank=same; "); foreach (int state in sameLevelStates) { @out.Write(state + "; "); } @out.Write(" }\n"); } sameLevelStates.Clear(); } // Emit terminating state (always there anyway). @out.Write(" -1 [style=filled, color=black, shape=doublecircle, label=\"\"]\n\n"); @out.Write(" {rank=sink; -1 }\n"); @out.Write("}\n"); @out.Flush(); } /// <summary> /// Emit a single state in the <c>dot</c> language. /// </summary> private static void EmitDotState(TextWriter @out, string name, string shape, string color, string label) { @out.Write(" " + name + " [" + (shape != null ? "shape=" + shape : "") + " " + (color != null ? "color=" + color : "") + " " + (label != null ? "label=\"" + label + "\"" : "label=\"\"") + " " + "]\n"); } /// <summary> /// Ensures an arc's label is indeed printable (dot uses US-ASCII). /// </summary> private static string PrintableLabel(int label) { // Any ordinary ascii character, except for " or \, are // printed as the character; else, as a hex string: if (label >= 0x20 && label <= 0x7d && label != 0x22 && label != 0x5c) // " OR \ { return char.ToString((char)label); } return "0x" + label.ToString("x"); } /// <summary> /// Just maps each UTF16 unit (char) to the <see cref="int"/>s in an /// <see cref="Int32sRef"/>. /// </summary> public static Int32sRef ToUTF16(string s, Int32sRef scratch) { int charLimit = s.Length; scratch.Offset = 0; scratch.Length = charLimit; scratch.Grow(charLimit); for (int idx = 0; idx < charLimit; idx++) { scratch.Int32s[idx] = (int)s[idx]; } return scratch; } /// <summary> /// Decodes the Unicode codepoints from the provided /// <see cref="ICharSequence"/> and places them in the provided scratch /// <see cref="Int32sRef"/>, which must not be <c>null</c>, returning it. /// </summary> public static Int32sRef ToUTF32(string s, Int32sRef scratch) { int charIdx = 0; int intIdx = 0; int charLimit = s.Length; while (charIdx < charLimit) { scratch.Grow(intIdx + 1); int utf32 = Character.CodePointAt(s, charIdx); scratch.Int32s[intIdx] = utf32; charIdx += Character.CharCount(utf32); intIdx++; } scratch.Length = intIdx; return scratch; } /// <summary> /// Decodes the Unicode codepoints from the provided /// <see cref="T:char[]"/> and places them in the provided scratch /// <see cref="Int32sRef"/>, which must not be <c>null</c>, returning it. /// </summary> public static Int32sRef ToUTF32(char[] s, int offset, int length, Int32sRef scratch) { int charIdx = offset; int intIdx = 0; int charLimit = offset + length; while (charIdx < charLimit) { scratch.Grow(intIdx + 1); int utf32 = Character.CodePointAt(s, charIdx, charLimit); scratch.Int32s[intIdx] = utf32; charIdx += Character.CharCount(utf32); intIdx++; } scratch.Length = intIdx; return scratch; } /// <summary> /// Just takes unsigned byte values from the <see cref="BytesRef"/> and /// converts into an <see cref="Int32sRef"/>. /// <para/> /// NOTE: This was toIntsRef() in Lucene /// </summary> public static Int32sRef ToInt32sRef(BytesRef input, Int32sRef scratch) { scratch.Grow(input.Length); for (int i = 0; i < input.Length; i++) { scratch.Int32s[i] = input.Bytes[i + input.Offset] & 0xFF; } scratch.Length = input.Length; return scratch; } /// <summary> /// Just converts <see cref="Int32sRef"/> to <see cref="BytesRef"/>; you must ensure the /// <see cref="int"/> values fit into a <see cref="byte"/>. /// </summary> public static BytesRef ToBytesRef(Int32sRef input, BytesRef scratch) { scratch.Grow(input.Length); for (int i = 0; i < input.Length; i++) { int value = input.Int32s[i + input.Offset]; // NOTE: we allow -128 to 255 Debug.Assert(value >= sbyte.MinValue && value <= 255, "value " + value + " doesn't fit into byte"); scratch.Bytes[i] = (byte)value; } scratch.Length = input.Length; return scratch; } // Uncomment for debugging: /* public static <T> void dotToFile(FST<T> fst, String filePath) throws IOException { Writer w = new OutputStreamWriter(new FileOutputStream(filePath)); toDot(fst, w, true, true); w.Dispose(); } */ /// <summary> /// Reads the first arc greater or equal that the given label into the provided /// arc in place and returns it iff found, otherwise return <c>null</c>. /// </summary> /// <param name="label"> the label to ceil on </param> /// <param name="fst"> the fst to operate on </param> /// <param name="follow"> the arc to follow reading the label from </param> /// <param name="arc"> the arc to read into in place </param> /// <param name="in"> the fst's <see cref="FST.BytesReader"/> </param> public static FST.Arc<T> ReadCeilArc<T>(int label, FST<T> fst, FST.Arc<T> follow, FST.Arc<T> arc, FST.BytesReader @in) { // TODO maybe this is a useful in the FST class - we could simplify some other code like FSTEnum? if (label == FST.END_LABEL) { if (follow.IsFinal) { if (follow.Target <= 0) { arc.Flags = (sbyte)FST.BIT_LAST_ARC; } else { arc.Flags = 0; // NOTE: nextArc is a node (not an address!) in this case: arc.NextArc = follow.Target; arc.Node = follow.Target; } arc.Output = follow.NextFinalOutput; arc.Label = FST.END_LABEL; return arc; } else { return null; } } if (!FST<T>.TargetHasArcs(follow)) { return null; } fst.ReadFirstTargetArc(follow, arc, @in); if (arc.BytesPerArc != 0 && arc.Label != FST.END_LABEL) { // Arcs are fixed array -- use binary search to find // the target. int low = arc.ArcIdx; int high = arc.NumArcs - 1; int mid = 0; // System.out.println("do arc array low=" + low + " high=" + high + // " targetLabel=" + targetLabel); while (low <= high) { mid = (int)((uint)(low + high) >> 1); @in.Position = arc.PosArcsStart; @in.SkipBytes(arc.BytesPerArc * mid + 1); int midLabel = fst.ReadLabel(@in); int cmp = midLabel - label; // System.out.println(" cycle low=" + low + " high=" + high + " mid=" + // mid + " midLabel=" + midLabel + " cmp=" + cmp); if (cmp < 0) { low = mid + 1; } else if (cmp > 0) { high = mid - 1; } else { arc.ArcIdx = mid - 1; return fst.ReadNextRealArc(arc, @in); } } if (low == arc.NumArcs) { // DEAD END! return null; } arc.ArcIdx = (low > high ? high : low); return fst.ReadNextRealArc(arc, @in); } // Linear scan fst.ReadFirstRealTargetArc(follow.Target, arc, @in); while (true) { // System.out.println(" non-bs cycle"); // TODO: we should fix this code to not have to create // object for the output of every arc we scan... only // for the matching arc, if found if (arc.Label >= label) { // System.out.println(" found!"); return arc; } else if (arc.IsLast) { return null; } else { fst.ReadNextRealArc(arc, @in); } } } } }
// 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.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.ExtractMethod { internal abstract partial class MethodExtractor { protected abstract partial class Analyzer { private readonly SemanticDocument _semanticDocument; protected readonly CancellationToken CancellationToken; protected readonly SelectionResult SelectionResult; protected Analyzer(SelectionResult selectionResult, CancellationToken cancellationToken) { Contract.ThrowIfNull(selectionResult); this.SelectionResult = selectionResult; _semanticDocument = selectionResult.SemanticDocument; this.CancellationToken = cancellationToken; } /// <summary> /// convert text span to node range for the flow analysis API /// </summary> protected abstract Tuple<SyntaxNode, SyntaxNode> GetFlowAnalysisNodeRange(); /// <summary> /// check whether selection contains return statement or not /// </summary> protected abstract bool ContainsReturnStatementInSelectedCode(IEnumerable<SyntaxNode> jumpOutOfRegionStatements); /// <summary> /// create VariableInfo type /// </summary> protected abstract VariableInfo CreateFromSymbol(Compilation compilation, ISymbol symbol, ITypeSymbol type, VariableStyle variableStyle, bool variableDeclared); /// <summary> /// among variables that will be used as parameters at the extracted method, check whether one of the parameter can be used as return /// </summary> protected abstract int GetIndexOfVariableInfoToUseAsReturnValue(IList<VariableInfo> variableInfo); /// <summary> /// get type of the range variable symbol /// </summary> protected abstract ITypeSymbol GetRangeVariableType(SemanticModel model, IRangeVariableSymbol symbol); /// <summary> /// check whether the selection is at the placed where read-only field is allowed to be extracted out /// </summary> /// <returns></returns> protected abstract bool ReadOnlyFieldAllowed(); public async Task<AnalyzerResult> AnalyzeAsync() { // do data flow analysis var model = _semanticDocument.SemanticModel; var dataFlowAnalysisData = GetDataFlowAnalysisData(model); // build symbol map for the identifiers used inside of the selection var symbolMap = GetSymbolMap(model); // gather initial local or parameter variable info var variableInfoMap = GenerateVariableInfoMap(model, dataFlowAnalysisData, symbolMap); // check whether instance member is used inside of the selection var instanceMemberIsUsed = IsInstanceMemberUsedInSelectedCode(dataFlowAnalysisData); // check whether end of selection is reachable var endOfSelectionReachable = IsEndOfSelectionReachable(model); // collects various variable informations // extracted code contains return value var isInExpressionOrHasReturnStatement = IsInExpressionOrHasReturnStatement(model); var signatureTuple = GetSignatureInformation(dataFlowAnalysisData, variableInfoMap, isInExpressionOrHasReturnStatement); var parameters = signatureTuple.Item1; var returnType = signatureTuple.Item2; var variableToUseAsReturnValue = signatureTuple.Item3; var unsafeAddressTakenUsed = signatureTuple.Item4; var returnTypeTuple = AdjustReturnType(model, returnType); returnType = returnTypeTuple.Item1; bool returnTypeHasAnonymousType = returnTypeTuple.Item2; bool awaitTaskReturn = returnTypeTuple.Item3; // create new document var newDocument = await CreateDocumentWithAnnotationsAsync(_semanticDocument, parameters, CancellationToken).ConfigureAwait(false); // collect method type variable used in selected code var sortedMap = new SortedDictionary<int, ITypeParameterSymbol>(); var typeParametersInConstraintList = GetMethodTypeParametersInConstraintList(model, variableInfoMap, symbolMap, sortedMap); var typeParametersInDeclaration = GetMethodTypeParametersInDeclaration(returnType, sortedMap); // check various error cases var operationStatus = GetOperationStatus(model, symbolMap, parameters, unsafeAddressTakenUsed, returnTypeHasAnonymousType); return new AnalyzerResult( newDocument, typeParametersInDeclaration, typeParametersInConstraintList, parameters, variableToUseAsReturnValue, returnType, awaitTaskReturn, instanceMemberIsUsed, endOfSelectionReachable, operationStatus); } private Tuple<ITypeSymbol, bool, bool> AdjustReturnType(SemanticModel model, ITypeSymbol returnType) { // check whether return type contains anonymous type and if it does, fix it up by making it object var returnTypeHasAnonymousType = returnType.ContainsAnonymousType(); returnType = returnTypeHasAnonymousType ? returnType.RemoveAnonymousTypes(model.Compilation) : returnType; // if selection contains await which is not under async lambda or anonymous delegate, // change return type to be wrapped in Task var shouldPutAsyncModifier = this.SelectionResult.ShouldPutAsyncModifier(); if (shouldPutAsyncModifier) { WrapReturnTypeInTask(model, ref returnType, out var awaitTaskReturn); return Tuple.Create(returnType, returnTypeHasAnonymousType, awaitTaskReturn); } // unwrap task if needed UnwrapTaskIfNeeded(model, ref returnType); return Tuple.Create(returnType, returnTypeHasAnonymousType, false); } private void UnwrapTaskIfNeeded(SemanticModel model, ref ITypeSymbol returnType) { // nothing to unwrap if (!this.SelectionResult.ContainingScopeHasAsyncKeyword() || !this.ContainsReturnStatementInSelectedCode(model)) { return; } var originalDefinition = returnType.OriginalDefinition; // see whether it needs to be unwrapped var taskType = model.Compilation.TaskType(); if (originalDefinition.Equals(taskType)) { returnType = model.Compilation.GetSpecialType(SpecialType.System_Void); return; } var genericTaskType = model.Compilation.TaskOfTType(); if (originalDefinition.Equals(genericTaskType)) { returnType = ((INamedTypeSymbol)returnType).TypeArguments[0]; return; } // nothing to unwrap return; } private void WrapReturnTypeInTask(SemanticModel model, ref ITypeSymbol returnType, out bool awaitTaskReturn) { awaitTaskReturn = false; var genericTaskType = model.Compilation.TaskOfTType(); var taskType = model.Compilation.TaskType(); if (returnType.Equals(model.Compilation.GetSpecialType(SpecialType.System_Void))) { // convert void to Task type awaitTaskReturn = true; returnType = taskType; return; } if (this.SelectionResult.SelectionInExpression) { returnType = genericTaskType.Construct(returnType); return; } if (ContainsReturnStatementInSelectedCode(model)) { // check whether we will use return type as it is or not. awaitTaskReturn = returnType.Equals(taskType); return; } // okay, wrap the return type in Task<T> returnType = genericTaskType.Construct(returnType); } private Tuple<IList<VariableInfo>, ITypeSymbol, VariableInfo, bool> GetSignatureInformation( DataFlowAnalysis dataFlowAnalysisData, IDictionary<ISymbol, VariableInfo> variableInfoMap, bool isInExpressionOrHasReturnStatement) { var model = _semanticDocument.SemanticModel; var compilation = model.Compilation; if (isInExpressionOrHasReturnStatement) { // check whether current selection contains return statement var parameters = GetMethodParameters(variableInfoMap.Values); var returnType = SelectionResult.GetContainingScopeType() ?? compilation.GetSpecialType(SpecialType.System_Object); var unsafeAddressTakenUsed = ContainsVariableUnsafeAddressTaken(dataFlowAnalysisData, variableInfoMap.Keys); return Tuple.Create(parameters, returnType, default(VariableInfo), unsafeAddressTakenUsed); } else { // no return statement var parameters = MarkVariableInfoToUseAsReturnValueIfPossible(GetMethodParameters(variableInfoMap.Values)); var variableToUseAsReturnValue = parameters.FirstOrDefault(v => v.UseAsReturnValue); var returnType = variableToUseAsReturnValue != null ? variableToUseAsReturnValue.GetVariableType(_semanticDocument) : compilation.GetSpecialType(SpecialType.System_Void); var unsafeAddressTakenUsed = ContainsVariableUnsafeAddressTaken(dataFlowAnalysisData, variableInfoMap.Keys); return Tuple.Create(parameters, returnType, variableToUseAsReturnValue, unsafeAddressTakenUsed); } } private bool IsInExpressionOrHasReturnStatement(SemanticModel model) { var isInExpressionOrHasReturnStatement = this.SelectionResult.SelectionInExpression; if (!isInExpressionOrHasReturnStatement) { var containsReturnStatement = ContainsReturnStatementInSelectedCode(model); isInExpressionOrHasReturnStatement |= containsReturnStatement; } return isInExpressionOrHasReturnStatement; } private OperationStatus GetOperationStatus( SemanticModel model, Dictionary<ISymbol, List<SyntaxToken>> symbolMap, IList<VariableInfo> parameters, bool unsafeAddressTakenUsed, bool returnTypeHasAnonymousType) { var readonlyFieldStatus = CheckReadOnlyFields(model, symbolMap); var namesWithAnonymousTypes = parameters.Where(v => v.OriginalTypeHadAnonymousTypeOrDelegate).Select(v => v.Name ?? string.Empty); if (returnTypeHasAnonymousType) { namesWithAnonymousTypes = namesWithAnonymousTypes.Concat("return type"); } var anonymousTypeStatus = namesWithAnonymousTypes.Any() ? new OperationStatus(OperationStatusFlag.BestEffort, string.Format(FeaturesResources.Parameters_type_or_return_type_cannot_be_an_anonymous_type_colon_bracket_0_bracket, string.Join(", ", namesWithAnonymousTypes))) : OperationStatus.Succeeded; var unsafeAddressStatus = unsafeAddressTakenUsed ? OperationStatus.UnsafeAddressTaken : OperationStatus.Succeeded; var asyncRefOutParameterStatue = CheckAsyncMethodRefOutParameters(parameters); return readonlyFieldStatus.With(anonymousTypeStatus).With(unsafeAddressStatus).With(asyncRefOutParameterStatue); } private OperationStatus CheckAsyncMethodRefOutParameters(IList<VariableInfo> parameters) { if (this.SelectionResult.ShouldPutAsyncModifier()) { var names = parameters.Where(v => !v.UseAsReturnValue && (v.ParameterModifier == ParameterBehavior.Out || v.ParameterModifier == ParameterBehavior.Ref)) .Select(p => p.Name ?? string.Empty); if (names.Any()) { return new OperationStatus(OperationStatusFlag.BestEffort, string.Format(FeaturesResources.Asynchronous_method_cannot_have_ref_out_parameters_colon_bracket_0_bracket, string.Join(", ", names))); } } return OperationStatus.Succeeded; } private Task<SemanticDocument> CreateDocumentWithAnnotationsAsync(SemanticDocument document, IList<VariableInfo> variables, CancellationToken cancellationToken) { var annotations = new List<Tuple<SyntaxToken, SyntaxAnnotation>>(variables.Count); variables.Do(v => v.AddIdentifierTokenAnnotationPair(annotations, cancellationToken)); if (annotations.Count == 0) { return Task.FromResult(document); } return document.WithSyntaxRootAsync(document.Root.AddAnnotations(annotations), cancellationToken); } private Dictionary<ISymbol, List<SyntaxToken>> GetSymbolMap(SemanticModel model) { var syntaxFactsService = _semanticDocument.Document.Project.LanguageServices.GetService<ISyntaxFactsService>(); var context = this.SelectionResult.GetContainingScope(); var symbolMap = SymbolMapBuilder.Build(syntaxFactsService, model, context, this.SelectionResult.FinalSpan, CancellationToken); return symbolMap; } private bool ContainsVariableUnsafeAddressTaken(DataFlowAnalysis dataFlowAnalysisData, IEnumerable<ISymbol> symbols) { // check whether the selection contains "&" over a symbol exist var map = new HashSet<ISymbol>(dataFlowAnalysisData.UnsafeAddressTaken); return symbols.Any(s => map.Contains(s)); } private DataFlowAnalysis GetDataFlowAnalysisData(SemanticModel model) { if (this.SelectionResult.SelectionInExpression) { return model.AnalyzeDataFlow(this.SelectionResult.GetContainingScope()); } var pair = GetFlowAnalysisNodeRange(); return model.AnalyzeDataFlow(pair.Item1, pair.Item2); } private bool IsEndOfSelectionReachable(SemanticModel model) { if (this.SelectionResult.SelectionInExpression) { return true; } var pair = GetFlowAnalysisNodeRange(); var analysis = model.AnalyzeControlFlow(pair.Item1, pair.Item2); return analysis.EndPointIsReachable; } private IList<VariableInfo> MarkVariableInfoToUseAsReturnValueIfPossible(IList<VariableInfo> variableInfo) { var variableToUseAsReturnValueIndex = GetIndexOfVariableInfoToUseAsReturnValue(variableInfo); if (variableToUseAsReturnValueIndex >= 0) { variableInfo[variableToUseAsReturnValueIndex] = VariableInfo.CreateReturnValue(variableInfo[variableToUseAsReturnValueIndex]); } return variableInfo; } private IList<VariableInfo> GetMethodParameters(ICollection<VariableInfo> variableInfo) { var list = new List<VariableInfo>(variableInfo); VariableInfo.SortVariables(_semanticDocument.SemanticModel.Compilation, list); return list; } private IDictionary<ISymbol, VariableInfo> GenerateVariableInfoMap( SemanticModel model, DataFlowAnalysis dataFlowAnalysisData, Dictionary<ISymbol, List<SyntaxToken>> symbolMap) { Contract.ThrowIfNull(model); Contract.ThrowIfNull(dataFlowAnalysisData); var variableInfoMap = new Dictionary<ISymbol, VariableInfo>(); // create map of each data var capturedMap = new HashSet<ISymbol>(dataFlowAnalysisData.Captured); var dataFlowInMap = new HashSet<ISymbol>(dataFlowAnalysisData.DataFlowsIn); var dataFlowOutMap = new HashSet<ISymbol>(dataFlowAnalysisData.DataFlowsOut); var alwaysAssignedMap = new HashSet<ISymbol>(dataFlowAnalysisData.AlwaysAssigned); var variableDeclaredMap = new HashSet<ISymbol>(dataFlowAnalysisData.VariablesDeclared); var readInsideMap = new HashSet<ISymbol>(dataFlowAnalysisData.ReadInside); var writtenInsideMap = new HashSet<ISymbol>(dataFlowAnalysisData.WrittenInside); var readOutsideMap = new HashSet<ISymbol>(dataFlowAnalysisData.ReadOutside); var writtenOutsideMap = new HashSet<ISymbol>(dataFlowAnalysisData.WrittenOutside); var unsafeAddressTakenMap = new HashSet<ISymbol>(dataFlowAnalysisData.UnsafeAddressTaken); // gather all meaningful symbols for the span. var candidates = new HashSet<ISymbol>(readInsideMap); candidates.UnionWith(writtenInsideMap); candidates.UnionWith(variableDeclaredMap); foreach (var symbol in candidates) { if (IsThisParameter(symbol) || IsInteractiveSynthesizedParameter(symbol)) { continue; } var captured = capturedMap.Contains(symbol); var dataFlowIn = dataFlowInMap.Contains(symbol); var dataFlowOut = dataFlowOutMap.Contains(symbol); var alwaysAssigned = alwaysAssignedMap.Contains(symbol); var variableDeclared = variableDeclaredMap.Contains(symbol); var readInside = readInsideMap.Contains(symbol); var writtenInside = writtenInsideMap.Contains(symbol); var readOutside = readOutsideMap.Contains(symbol); var writtenOutside = writtenOutsideMap.Contains(symbol); var unsafeAddressTaken = unsafeAddressTakenMap.Contains(symbol); // if it is static local, make sure it is not defined inside if (symbol.IsStatic) { dataFlowIn = dataFlowIn && !variableDeclared; } // make sure readoutside is true when dataflowout is true (bug #3790) // when a variable is only used inside of loop, a situation where dataflowout == true and readOutside == false // can happen. but for extract method's point of view, this is not an information that would affect output. // so, here we adjust flags to follow predefined assumption. readOutside = readOutside || dataFlowOut; // make sure data flow out is true when declared inside/written inside/read outside/not written outside are true (bug #6277) dataFlowOut = dataFlowOut || (variableDeclared && writtenInside && readOutside && !writtenOutside); // variable that is declared inside but never referenced outside. just ignore it and move to next one. if (variableDeclared && !dataFlowOut && !readOutside && !writtenOutside) { continue; } // parameter defined inside of the selection (such as lambda parameter) will be ignored (bug # 10964) if (symbol is IParameterSymbol && variableDeclared) { continue; } var type = GetSymbolType(model, symbol); if (type == null) { continue; } var variableStyle = GetVariableStyle(symbolMap, symbol, model, type, captured, dataFlowIn, dataFlowOut, alwaysAssigned, variableDeclared, readInside, writtenInside, readOutside, writtenOutside, unsafeAddressTaken); AddVariableToMap(variableInfoMap, symbol, CreateFromSymbol(model.Compilation, symbol, type, variableStyle, variableDeclared)); } return variableInfoMap; } private void AddVariableToMap(IDictionary<ISymbol, VariableInfo> variableInfoMap, ISymbol localOrParameter, VariableInfo variableInfo) { variableInfoMap.Add(localOrParameter, variableInfo); } private VariableStyle GetVariableStyle( Dictionary<ISymbol, List<SyntaxToken>> symbolMap, ISymbol symbol, SemanticModel model, ITypeSymbol type, bool captured, bool dataFlowIn, bool dataFlowOut, bool alwaysAssigned, bool variableDeclared, bool readInside, bool writtenInside, bool readOutside, bool writtenOutside, bool unsafeAddressTaken) { Contract.ThrowIfNull(model); Contract.ThrowIfNull(type); var style = ExtractMethodMatrix.GetVariableStyle(captured, dataFlowIn, dataFlowOut, alwaysAssigned, variableDeclared, readInside, writtenInside, readOutside, writtenOutside, unsafeAddressTaken); if (SelectionContainsOnlyIdentifierWithSameType(type)) { return style; } if (UserDefinedValueType(model.Compilation, type) && !this.SelectionResult.DontPutOutOrRefOnStruct) { return AlwaysReturn(style); } // for captured variable, never try to move the decl into extracted method if (captured && (style == VariableStyle.MoveIn)) { return VariableStyle.Out; } // check special value type cases if (type.IsValueType && !IsWrittenInsideForFrameworkValueType(symbolMap, model, symbol, writtenInside)) { return style; } // don't blindly always return. make sure there is a write inside of the selection if (this.SelectionResult.AllowMovingDeclaration || !writtenInside) { return style; } return AlwaysReturn(style); } private bool IsWrittenInsideForFrameworkValueType( Dictionary<ISymbol, List<SyntaxToken>> symbolMap, SemanticModel model, ISymbol symbol, bool writtenInside) { if (!symbolMap.TryGetValue(symbol, out var tokens)) { return writtenInside; } // this relies on the fact that our IsWrittenTo only cares about syntax to figure out whether // something is written to or not. but not semantic. // we probably need to move the API to syntaxFact service not semanticFact. // // if one wants to get result that also considers semantic, he should use data control flow analysis API. var semanticFacts = _semanticDocument.Document.GetLanguageService<ISemanticFactsService>(); return tokens.Any(t => semanticFacts.IsWrittenTo(model, t.Parent, CancellationToken.None)); } private bool SelectionContainsOnlyIdentifierWithSameType(ITypeSymbol type) { if (!this.SelectionResult.SelectionInExpression) { return false; } var firstToken = this.SelectionResult.GetFirstTokenInSelection(); var lastToken = this.SelectionResult.GetLastTokenInSelection(); if (!firstToken.Equals(lastToken)) { return false; } return type.Equals(this.SelectionResult.GetContainingScopeType()); } private bool UserDefinedValueType(Compilation compilation, ITypeSymbol type) { if (!type.IsValueType || type.IsPointerType() || type.IsEnumType()) { return false; } return type.OriginalDefinition.SpecialType == SpecialType.None && !WellKnownFrameworkValueType(compilation, type); } private bool WellKnownFrameworkValueType(Compilation compilation, ITypeSymbol type) { if (!type.IsValueType) { return false; } var cancellationTokenType = compilation.GetTypeByMetadataName("System.Threading.CancellationToken"); if (cancellationTokenType != null && cancellationTokenType.Equals(type)) { return true; } return false; } private ITypeSymbol GetSymbolType(SemanticModel model, ISymbol symbol) { var local = symbol as ILocalSymbol; if (local != null) { return local.Type; } var parameter = symbol as IParameterSymbol; if (parameter != null) { return parameter.Type; } var rangeVariable = symbol as IRangeVariableSymbol; if (rangeVariable != null) { return GetRangeVariableType(model, rangeVariable); } return Contract.FailWithReturn<ITypeSymbol>("Shouldn't reach here"); } protected VariableStyle AlwaysReturn(VariableStyle style) { if (style == VariableStyle.InputOnly) { return VariableStyle.Ref; } if (style == VariableStyle.MoveIn) { return VariableStyle.Out; } if (style == VariableStyle.SplitIn) { return VariableStyle.Out; } if (style == VariableStyle.SplitOut) { return VariableStyle.OutWithMoveOut; } return style; } private bool IsParameterUsedOutside(ISymbol localOrParameter) { var parameter = localOrParameter as IParameterSymbol; if (parameter == null) { return false; } return parameter.RefKind != RefKind.None; } private bool IsParameterAssigned(ISymbol localOrParameter) { // hack for now. var parameter = localOrParameter as IParameterSymbol; if (parameter == null) { return false; } return parameter.RefKind != RefKind.Out; } private bool IsThisParameter(ISymbol localOrParameter) { var parameter = localOrParameter as IParameterSymbol; if (parameter == null) { return false; } return parameter.IsThis; } private bool IsInteractiveSynthesizedParameter(ISymbol localOrParameter) { var parameter = localOrParameter as IParameterSymbol; if (parameter == null) { return false; } return parameter.IsImplicitlyDeclared && parameter.ContainingAssembly.IsInteractive && parameter.ContainingSymbol != null && parameter.ContainingSymbol.ContainingType != null && parameter.ContainingSymbol.ContainingType.IsScriptClass; } private bool ContainsReturnStatementInSelectedCode(SemanticModel model) { Contract.ThrowIfTrue(this.SelectionResult.SelectionInExpression); var pair = GetFlowAnalysisNodeRange(); var controlFlowAnalysisData = model.AnalyzeControlFlow(pair.Item1, pair.Item2); return ContainsReturnStatementInSelectedCode(controlFlowAnalysisData.ExitPoints); } private void AddTypeParametersToMap(IEnumerable<ITypeParameterSymbol> typeParameters, IDictionary<int, ITypeParameterSymbol> sortedMap) { foreach (var typeParameter in typeParameters) { AddTypeParameterToMap(typeParameter, sortedMap); } } private void AddTypeParameterToMap(ITypeParameterSymbol typeParameter, IDictionary<int, ITypeParameterSymbol> sortedMap) { if (typeParameter == null || typeParameter.DeclaringMethod == null || sortedMap.ContainsKey(typeParameter.Ordinal)) { return; } sortedMap[typeParameter.Ordinal] = typeParameter; } private void AppendMethodTypeVariableFromDataFlowAnalysis( SemanticModel model, IDictionary<ISymbol, VariableInfo> variableInfoMap, IDictionary<int, ITypeParameterSymbol> sortedMap) { foreach (var symbol in variableInfoMap.Keys) { var parameter = symbol as IParameterSymbol; if (parameter != null) { AddTypeParametersToMap(TypeParameterCollector.Collect(parameter.Type), sortedMap); continue; } var local = symbol as ILocalSymbol; if (local != null) { AddTypeParametersToMap(TypeParameterCollector.Collect(local.Type), sortedMap); continue; } var rangeVariable = symbol as IRangeVariableSymbol; if (rangeVariable != null) { var type = GetRangeVariableType(model, rangeVariable); AddTypeParametersToMap(TypeParameterCollector.Collect(type), sortedMap); continue; } Contract.Fail(FeaturesResources.Unknown_symbol_kind); } } private void AppendMethodTypeParameterFromConstraint(SortedDictionary<int, ITypeParameterSymbol> sortedMap) { var typeParametersInConstraint = new List<ITypeParameterSymbol>(); // collect all type parameter appears in constraint foreach (var typeParameter in sortedMap.Values) { var constraintTypes = typeParameter.ConstraintTypes; if (constraintTypes.IsDefaultOrEmpty) { continue; } foreach (var type in constraintTypes) { // constraint itself is type parameter typeParametersInConstraint.AddRange(TypeParameterCollector.Collect(type)); } } // pick up only valid type parameter and add them to the map foreach (var typeParameter in typeParametersInConstraint) { AddTypeParameterToMap(typeParameter, sortedMap); } } private void AppendMethodTypeParameterUsedDirectly(IDictionary<ISymbol, List<SyntaxToken>> symbolMap, IDictionary<int, ITypeParameterSymbol> sortedMap) { foreach (var pair in symbolMap.Where(p => p.Key.Kind == SymbolKind.TypeParameter)) { var typeParameter = pair.Key as ITypeParameterSymbol; if (typeParameter.DeclaringMethod == null || sortedMap.ContainsKey(typeParameter.Ordinal)) { continue; } sortedMap[typeParameter.Ordinal] = typeParameter; } } private IEnumerable<ITypeParameterSymbol> GetMethodTypeParametersInConstraintList( SemanticModel model, IDictionary<ISymbol, VariableInfo> variableInfoMap, IDictionary<ISymbol, List<SyntaxToken>> symbolMap, SortedDictionary<int, ITypeParameterSymbol> sortedMap) { // find starting points AppendMethodTypeVariableFromDataFlowAnalysis(model, variableInfoMap, sortedMap); AppendMethodTypeParameterUsedDirectly(symbolMap, sortedMap); // recursively dive into constraints to find all constraints needed AppendTypeParametersInConstraintsUsedByConstructedTypeWithItsOwnConstraints(sortedMap); return sortedMap.Values.ToList(); } private void AppendTypeParametersInConstraintsUsedByConstructedTypeWithItsOwnConstraints(SortedDictionary<int, ITypeParameterSymbol> sortedMap) { var visited = new HashSet<ITypeSymbol>(); var candidates = SpecializedCollections.EmptyEnumerable<ITypeParameterSymbol>(); // collect all type parameter appears in constraint foreach (var typeParameter in sortedMap.Values) { var constraintTypes = typeParameter.ConstraintTypes; if (constraintTypes.IsDefaultOrEmpty) { continue; } foreach (var type in constraintTypes) { candidates = candidates.Concat(AppendTypeParametersInConstraintsUsedByConstructedTypeWithItsOwnConstraints(type, visited)); } } // pick up only valid type parameter and add them to the map foreach (var typeParameter in candidates) { AddTypeParameterToMap(typeParameter, sortedMap); } } private IEnumerable<ITypeParameterSymbol> AppendTypeParametersInConstraintsUsedByConstructedTypeWithItsOwnConstraints( ITypeSymbol type, HashSet<ITypeSymbol> visited) { if (visited.Contains(type)) { return SpecializedCollections.EmptyEnumerable<ITypeParameterSymbol>(); } visited.Add(type); if (type.OriginalDefinition.Equals(type)) { return SpecializedCollections.EmptyEnumerable<ITypeParameterSymbol>(); } var constructedType = type as INamedTypeSymbol; if (constructedType == null) { return SpecializedCollections.EmptyEnumerable<ITypeParameterSymbol>(); } var parameters = constructedType.GetAllTypeParameters().ToList(); var arguments = constructedType.GetAllTypeArguments().ToList(); Contract.ThrowIfFalse(parameters.Count == arguments.Count); var typeParameters = new List<ITypeParameterSymbol>(); for (int i = 0; i < parameters.Count; i++) { var parameter = parameters[i]; var argument = arguments[i] as ITypeParameterSymbol; if (argument != null) { // no constraint, nothing to do if (!parameter.HasConstructorConstraint && !parameter.HasReferenceTypeConstraint && !parameter.HasValueTypeConstraint && parameter.ConstraintTypes.IsDefaultOrEmpty) { continue; } typeParameters.Add(argument); continue; } var candidate = arguments[i] as INamedTypeSymbol; if (candidate == null) { continue; } typeParameters.AddRange(AppendTypeParametersInConstraintsUsedByConstructedTypeWithItsOwnConstraints(candidate, visited)); } return typeParameters; } private IEnumerable<ITypeParameterSymbol> GetMethodTypeParametersInDeclaration(ITypeSymbol returnType, SortedDictionary<int, ITypeParameterSymbol> sortedMap) { // add return type to the map AddTypeParametersToMap(TypeParameterCollector.Collect(returnType), sortedMap); AppendMethodTypeParameterFromConstraint(sortedMap); return sortedMap.Values.ToList(); } private OperationStatus CheckReadOnlyFields(SemanticModel semanticModel, Dictionary<ISymbol, List<SyntaxToken>> symbolMap) { if (ReadOnlyFieldAllowed()) { return OperationStatus.Succeeded; } List<string> names = null; var semanticFacts = _semanticDocument.Document.GetLanguageService<ISemanticFactsService>(); foreach (var pair in symbolMap.Where(p => p.Key.Kind == SymbolKind.Field)) { var field = (IFieldSymbol)pair.Key; if (!field.IsReadOnly) { continue; } var tokens = pair.Value; if (tokens.All(t => !semanticFacts.IsWrittenTo(semanticModel, t.Parent, CancellationToken))) { continue; } names = names ?? new List<string>(); names.Add(field.Name ?? string.Empty); } if (names != null) { return new OperationStatus(OperationStatusFlag.BestEffort, string.Format(FeaturesResources.Assigning_to_readonly_fields_must_be_done_in_a_constructor_colon_bracket_0_bracket, string.Join(", ", names))); } return OperationStatus.Succeeded; } private bool IsInstanceMemberUsedInSelectedCode(DataFlowAnalysis dataFlowAnalysisData) { Contract.ThrowIfNull(dataFlowAnalysisData); // "this" can be used as a lvalue in a struct, check WrittenInside as well return dataFlowAnalysisData.ReadInside.Any(s => IsThisParameter(s)) || dataFlowAnalysisData.WrittenInside.Any(s => IsThisParameter(s)); } protected VariableInfo CreateFromSymbolCommon<T>( Compilation compilation, ISymbol symbol, ITypeSymbol type, VariableStyle style, HashSet<int> nonNoisySyntaxKindSet) where T : SyntaxNode { var local = symbol as ILocalSymbol; if (local != null) { return new VariableInfo( new LocalVariableSymbol<T>(compilation, local, type, nonNoisySyntaxKindSet), style); } var parameter = symbol as IParameterSymbol; if (parameter != null) { return new VariableInfo(new ParameterVariableSymbol(compilation, parameter, type), style); } var rangeVariable = symbol as IRangeVariableSymbol; if (rangeVariable != null) { return new VariableInfo(new QueryVariableSymbol(compilation, rangeVariable, type), style); } return Contract.FailWithReturn<VariableInfo>(FeaturesResources.Unknown); } } } }
namespace Microsoft.Protocols.TestSuites.MS_OXWSBTRF { using System.Collections.ObjectModel; using Microsoft.Protocols.TestSuites.Common; using Microsoft.Protocols.TestTools; using Microsoft.VisualStudio.TestTools.UnitTesting; /// <summary> /// This scenario is designed to test export items from a mailbox server and upload items to a mailbox server. /// </summary> [TestClass] public class S01_ExportAndUploadItems : TestSuiteBase { #region Class initialize and clean up. /// <summary> /// Initializes the test class. /// </summary> /// <param name="testContext">Context to initialize.</param> [ClassInitialize] public static void ClassInitialize(TestContext testContext) { TestClassBase.Initialize(testContext); } /// <summary> /// Clean up the test class. /// </summary> [ClassCleanup] public static void ClassCleanup() { TestClassBase.Cleanup(); } #endregion #region Test cases /// <summary> /// This test case is designed to validate the successful response returned by ExportItems and UploadItems operations /// when the CreateActionType is CreateNew. /// </summary> [TestCategory("MSOXWSBTRF"), TestMethod()] public void MSOXWSBTRF_S01_TC01_ExportAndUploadItems_CreateNew_Success() { #region Prerequisites. // In the initialize step, multiple items in the specified parent folder have been created. // If that step executes successfully, the count of CreatedItemId list should be equal to the count of OriginalFolderId list. Site.Assert.AreEqual<int>( this.CreatedItemId.Count, this.OriginalFolderId.Count, string.Format( "The exportedItemIds array should contain {0} item ids, actually, it contains {1}", this.OriginalFolderId.Count, this.CreatedItemId.Count)); #endregion #region Call ExportItems operation to export the items from the server. // Initialize three ExportItemsType instances. ExportItemsType exportItems = new ExportItemsType(); // Initialize four ItemIdType instances with three different situations to cover the case: // 1. The ChangeKey is not present; // 2. If the ChangeKey attribute of the ItemIdType complex type is present, its value MUST be either valid or NULL. exportItems.ItemIds = new ItemIdType[4] { new ItemIdType { // The ChangeKey is not present. Id = this.CreatedItemId[0].Id, }, new ItemIdType { // The ChangeKey is null. Id = this.CreatedItemId[1].Id, ChangeKey = null }, new ItemIdType { // The ChangeKey is valid. Id = this.CreatedItemId[2].Id, ChangeKey = this.CreatedItemId[2].ChangeKey }, new ItemIdType { // The ChangeKey is not present. Id = this.CreatedItemId[3].Id, } }; // Call ExportItems operation. ExportItemsResponseType exportItemsResponse = this.BTRFAdapter.ExportItems(exportItems); Site.Assert.IsNotNull(exportItemsResponse, "The ExportItems response should not be null."); // Check whether the ExportItems operation is executed successfully. foreach (ExportItemsResponseMessageType responseMessage in exportItemsResponse.ResponseMessages.Items) { Site.Assert.AreEqual<ResponseClassType>( ResponseClassType.Success, responseMessage.ResponseClass, string.Format( @"The ExportItems operation should be successful. Expected response code: {0}, actual response code: {1}", ResponseClassType.Success, responseMessage.ResponseClass)); } // If the operation executes successfully, the count of items in ExportItems response should be equal to the items in ExportItems request. Site.Assert.AreEqual<int>( exportItemsResponse.ResponseMessages.Items.Length, exportItems.ItemIds.Length, string.Format( "The exportItems response should contain {0} items, actually, it contains {1}", exportItems.ItemIds.Length, exportItemsResponse.ResponseMessages.Items.Length)); // Verify ManagementRole part of ExportItems operation this.VerifyManagementRolePart(); #endregion #region Verify the ExportItems response related requirements // Verify the ExportItemsResponseType related requirements. this.VerifyExportItemsSuccessResponse(exportItemsResponse); // If the id in ExportItems request is same with the id in ExportItems response, then MS-OXWSBTRF_R169 and MS-OXWSBTRF_R182 can be captured. bool isSameItemId = false; for (int i = 0; i < exportItemsResponse.ResponseMessages.Items.Length; i++) { Site.Log.Add( LogEntryKind.Debug, "The exported item's id: '{0}' should be same with the created item's id: {1}.", (exportItemsResponse.ResponseMessages.Items[i] as ExportItemsResponseMessageType).ItemId.Id, this.CreatedItemId[i].Id); if ((exportItemsResponse.ResponseMessages.Items[i] as ExportItemsResponseMessageType).ItemId.Id == this.CreatedItemId[i].Id) { isSameItemId = true; } else { isSameItemId = false; break; } } // Add the debug information. Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXWSBTRF_R169."); // Verify requirement MS-OXWSBTRF_R169 Site.CaptureRequirementIfIsTrue( isSameItemId, 169, @"[In m:ExportItemsResponseMessageType Complex Type][ItemId] specifies the item identifier of a single exported item."); // Add the debug information. Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXWSBTRF_R182."); // Verify requirement MS-OXWSBTRF_R182 Site.CaptureRequirementIfIsTrue( isSameItemId, 182, @"[In t:NonEmptyArrayOfItemIdsType Complex Type][ItemId] specifies the item identifier of an item to export from a mailbox."); #endregion #region Call UploadItems operation and set the CreateAction element to CreateNew to upload the items that exported in last step. ExportItemsResponseMessageType[] exportItemsResponseMessages = TestSuiteHelper.GetResponseMessages<ExportItemsResponseMessageType>(exportItemsResponse); // Initialize the upload items using the data of previous export items and set the item CreateAction to CreateNew. UploadItemsResponseMessageType[] uploadItemsResponse = this.UploadItems(exportItemsResponseMessages, this.OriginalFolderId, CreateActionType.CreateNew, true, true, false); #endregion #region Verify the UploadItems response related requirements when the CreateAction is CreateNew. // If the UploadItems response item's ID is not the same as the previous exported item's ID, then MS-OXWSBTRF_R228 can be captured. bool isNotSameItemId = false; for (int i = 0; i < uploadItemsResponse.Length; i++) { // Log the expected and actual value Site.Log.Add( LogEntryKind.Debug, "The uploaded item's id: '{0}' should not be same with the exported item's id when the CreateAction is set to CreateNew: {1}.", uploadItemsResponse[i].ItemId.Id, exportItemsResponseMessages[i].ItemId.Id); if (exportItemsResponseMessages[i].ItemId.Id != uploadItemsResponse[i].ItemId.Id) { isNotSameItemId = true; } else { isNotSameItemId = false; break; } } // Add the debug information. Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXWSBTRF_R228."); // Verify Requirement: MS-OXWSBTRF_R228. Site.CaptureRequirementIfIsTrue( isNotSameItemId, 228, @"[In CreateActionType Simple Type][CreateNew] The <ItemId> element that is returned in the UploadItemsResponseMessageType complex type, as specified in section 3.1.4.2.3.2, MUST contain the new item identifier."); // Call getItem to get the items that was uploaded ItemIdType[] itemIds = new ItemIdType[uploadItemsResponse.Length]; for (int i = 0; i < uploadItemsResponse.Length; i++) { itemIds[i] = uploadItemsResponse[i].ItemId; } ItemType[] getItems = this.GetItems(itemIds); // Verify the array of items uploaded to a mailbox this.VerifyItemsUploadedToMailbox(getItems); // If the verification of the items uploaded to mailbox is successful, then this requirement can be captured. // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXWSBTRF_R226"); // Verify requirement MS-OXWSBTRF_R226 Site.CaptureRequirement( 226, @"[In CreateActionType Simple Type]The Value of CreateNew specifies that a new copy of the original item is uploaded to the mailbox."); // If the value of IsAssociated attribute in getItem response is same with the value in uploadItems request, // then requirement MS-OXWSBTRF_R222 can be captured. bool isSameIsAssociated = false; for (int i = 0; i < getItems.Length; i++) { // Log the expected and actual value Site.Log.Add( LogEntryKind.Debug, "The value of IsAssociated attribute: {0} in getItem response should be: true", getItems[i].IsAssociated); if (true == getItems[i].IsAssociated) { isSameIsAssociated = true; } else { isSameIsAssociated = false; break; } } // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXWSBTRF_R222"); // Verify requirement MS-OXWSBTRF_R222 Site.CaptureRequirementIfIsTrue( isSameIsAssociated, 222, @"[In m:UploadItemType Complex Type]If it [IsAssociated] is present, it indicates that the item is a folder associated item."); #endregion } /// <summary> /// This test case is designed to validate the successful response returned by ExportItems and UploadItems operations /// when the CreateActionType is Update. /// </summary> [TestCategory("MSOXWSBTRF"), TestMethod()] public void MSOXWSBTRF_S01_TC02_ExportAndUploadItems_Update_Success() { #region Get the exported items. // Get the exported items which are prepared for uploading. // And set the parameter to true to configure the SOAP header before calling ExportItems operation. ExportItemsResponseMessageType[] exportedItems = this.ExportItems(true); #endregion #region Call UploadItems operation to upload the items that exported to the server in last step. // Initialize the upload items using the previous exported data, and set that item CreateAction to Update. // Call UploadItems operation with the isAssociated attribute setting to true UploadItemsResponseMessageType[] uploadItemsResponse = this.UploadItems(exportedItems, this.OriginalFolderId, CreateActionType.Update, false, false, false); #endregion #region Verify the UploadItems response related requirements when the CreateAction is Update. // If the itemId in uploadItems response is same with it in the uploadItems request, // then MS-OXWSBTRF_R200 and MS-OXWSBTRF_R214 can be captured. bool isSameItemId = false; for (int i = 0; i < uploadItemsResponse.Length; i++) { // Log the expected and actual value. Site.Log.Add( LogEntryKind.Debug, "The item's id: '{0}' in UploadItems request should be same with the item's id: {1} in UploadItems response when the CreateAction is set to Update.", exportedItems[i].ItemId.Id, uploadItemsResponse[i].ItemId.Id); if (exportedItems[i].ItemId.Id == uploadItemsResponse[i].ItemId.Id) { isSameItemId = true; } else { isSameItemId = false; break; } } // Add the debug information. Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXWSBTRF_R200."); // Verify requirement MS-OXWSBTRF_R200 Site.CaptureRequirementIfIsTrue( isSameItemId, 200, @"[In m:UploadItemsResponseMessageType Complex Type] The ItemId element specifies the item identifier of an item that was uploaded into a mailbox."); // Add the debug information. Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXWSBTRF_R214."); // Verify requirement MS-OXWSBTRF_R200 Site.CaptureRequirementIfIsTrue( isSameItemId, 214, @"[In m:UploadItemType Complex Type][ItemId] specifies the item identifier of the upload item."); // Call getItem to get the items that was uploaded. ItemIdType[] itemIds = new ItemIdType[uploadItemsResponse.Length]; for (int i = 0; i < uploadItemsResponse.Length; i++) { itemIds[i] = uploadItemsResponse[i].ItemId; } ItemType[] getItems = this.GetItems(itemIds); // Verify the array of items uploaded to a mailbox this.VerifyItemsUploadedToMailbox(getItems); // If the ParentFolderId in GetItem response is same with it in UploadItem request, then requirement MS-OXWSBTRF_R211 can be captured. bool isSameParentFolderId = false; for (int i = 0; i < getItems.Length; i++) { // Log the expected and actual value. Site.Log.Add( LogEntryKind.Debug, "The ParentFolderId: {0} in GetItem response should be same with the ParentFolderId: {1} in UploadItems request the items are updated successfully.", getItems[i].ParentFolderId.Id, this.OriginalFolderId[i]); if (this.OriginalFolderId[i] == getItems[i].ParentFolderId.Id) { isSameParentFolderId = true; } else { isSameParentFolderId = false; break; } } // Add the debug information. Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXWSBTRF_R211"); // Verify requirement MS-OXWSBTRF_R211 Site.CaptureRequirementIfIsTrue( isSameParentFolderId, 211, @"[In m:UploadItemType Complex Type][ParentFolderId] specifies the target folder in which to place the upload item."); // Call exportItems again after update to verify whether the items are updated or not. ExportItemsResponseMessageType[] exportedItemsAfterUpload = this.ExportItems(false); // If the value of Data element is different, then requirement MS-OXWSBTRF_R229 can be captured. bool isNotSameData = false; for (int i = 0; i < exportedItemsAfterUpload.Length; i++) { // Log the expected and actual value. Site.Log.Add( LogEntryKind.Debug, "The Data: {0} before UploadItems should not be same with the Data: {1} that after UploadItems when the CreateAction is set to Update.", exportedItems[i].Data, exportedItemsAfterUpload[i].Data); if (exportedItems[i].Data != exportedItemsAfterUpload[i].Data) { isNotSameData = true; } else { isNotSameData = false; break; } } // Add the debug information. Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXWSBTRF_R229"); // Verify requirement MS-OXWSBTRF_R229 Site.CaptureRequirementIfIsTrue( isNotSameData, 229, @"[In CreateActionType Simple Type]The Value of Update specifies that the upload will update an item that is already present in the mailbox."); #endregion } /// <summary> /// This test case is designed to validate the successful response returned by ExportItems and UploadItems operations when the CreateActionType is UpdateOrCreate. /// </summary> [TestCategory("MSOXWSBTRF"), TestMethod()] public void MSOXWSBTRF_S01_TC03_ExportAndUploadItems_UpdateOrCreate_Success() { #region Get the exported items. // Get the exported items which is prepared for uploading. ExportItemsResponseMessageType[] exportedItems = this.ExportItems(false); #endregion #region Call UploadItems operation and set the CreateAction element to UpdateorCreate and the parent folder to the original one to upload the items that exported in last step. // Initialize the uploaded items using the information of previous exported items, set that item's CreateAction to UpdateOrCreate and the ParentFolderId to the same as the parent folder. // Set the last parameter to true to configure the SOAP header before calling UploadItems operation UploadItemsResponseMessageType[] uploadItemsResponse = this.UploadItems(exportedItems, this.OriginalFolderId, CreateActionType.UpdateOrCreate, true, false, true); // Call getItem to get the items that was uploaded. ItemIdType[] itemIds = new ItemIdType[uploadItemsResponse.Length]; for (int i = 0; i < uploadItemsResponse.Length; i++) { itemIds[i] = uploadItemsResponse[i].ItemId; } ItemType[] getItems = this.GetItems(itemIds); // Verify the array of items uploaded to a mailbox this.VerifyItemsUploadedToMailbox(getItems); #endregion #region Call ExportItems again to verify the value of Data after update. ExportItemsResponseMessageType[] exportedItemsAfterUpload = this.ExportItems(false); // If the value of Data element is different, then requirement MS-OXWSBTRF_R2321 can be captured. bool isNotSameData = false; for (int i = 0; i < exportedItemsAfterUpload.Length; i++) { // Log the expected and actual value. Site.Log.Add( LogEntryKind.Debug, "The Data: {0} before upload should not be same with the Data: {1} that after upload when the criteria meets to Update.", exportedItems[i].Data, exportedItemsAfterUpload[i].Data); if (exportedItems[i].Data != exportedItemsAfterUpload[i].Data) { isNotSameData = true; } else { isNotSameData = false; break; } } // Add the debug information. Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXWSBTRF_R2321"); // Verify requirement MS-OXWSBTRF_R3221 Site.CaptureRequirementIfIsTrue( isNotSameData, 2321, @"[In CreateActionType Simple Type][UpdateOrCreate]If the criteria for a successful update are met, the target item is updated."); #endregion #region Create another sub folder in the specified parent folder. // Create another sub folder in the specified parent folder. Collection<string> subFolderIds = new Collection<string>(); for (int i = 0; i < this.ParentFolderType.Count; i++) { // Generate the folder name. string folderName = Common.GenerateResourceName(this.Site, this.ParentFolderType[i] + "NewFolder"); // Create another sub folder in the specified parent folder subFolderIds.Add(this.CreateSubFolder(this.ParentFolderType[i], folderName)); Site.Assert.IsNotNull( subFolderIds[i], string.Format( "The sub folder named '{0}' under '{1}' should be created successfully.", folderName, this.ParentFolderType[i].ToString())); } #endregion #region Call UploadItems operation and set the CreateAction element to UpdateorCreate and the parent folder to the new created one to upload the items that exported in last step to a new folder. // Initialize the uploaded items using the previous exported items, set the item's CreateAction to UpdateOrCreate and the ParentFolderId to the sub folder ID. UploadItemsResponseMessageType[] uploadItemsWithChangedParentFolderIdResponseMessages = this.UploadItems(exportedItemsAfterUpload, subFolderIds, CreateActionType.UpdateOrCreate, true, false, false); #endregion #region Verify the UploadItemsResponseType related requirements // Call getItem to get the items that was uploaded. ItemIdType[] newItemIds = new ItemIdType[uploadItemsWithChangedParentFolderIdResponseMessages.Length]; for (int i = 0; i < uploadItemsWithChangedParentFolderIdResponseMessages.Length; i++) { newItemIds[i] = uploadItemsWithChangedParentFolderIdResponseMessages[i].ItemId; } ItemType[] getUpdatedItems = this.GetItems(newItemIds); // Verify the array of items uploaded to a mailbox this.VerifyItemsUploadedToMailbox(getUpdatedItems); // Check the parent folder id is not the original one. bool isNotSameParentFolderId = false; for (int i = 0; i < getUpdatedItems.Length; i++) { // Log the expected and actual value. Site.Log.Add( LogEntryKind.Debug, "The ParentFolderId: {0} in GetItems response should not be same with the original ParentFolderId: {1} when uploading items to sub folders", getUpdatedItems[i].ParentFolderId.Id, this.OriginalFolderId[i]); if (this.OriginalFolderId[i] != getUpdatedItems[i].ParentFolderId.Id) { isNotSameParentFolderId = true; } else { isNotSameParentFolderId = false; break; } } // If requirement MS-OXWSBTRF_R195 and MS-OXWSBTRF_R207 are captured and the ParentFolderId is not the original one, then requirement MS-OXWSBTRF_R235 can be captured. // Add the debug information. Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXWSBTRF_R235"); // Verify requirement MS-OXWSBTRF_R235 Site.CaptureRequirementIfIsTrue( isNotSameParentFolderId, 235, @"[In CreateActionType Simple Type][UpdateOrCreate]If the target item is not in the original folder specified by the <ParentFolderId> element in the UploadItemType complex type, a new copy of the original item is uploaded to the mailbox associated with the folder specified by the <ParentFolderId> element."); // Check the item id is a new one. bool isNotSameItemId = false; for (int i = 0; i < uploadItemsWithChangedParentFolderIdResponseMessages.Length; i++) { // Log the expected and actual value. Site.Log.Add( LogEntryKind.Debug, "The Item's id: {0} in UploadItems response should not be same with the Item's id: {1} in ExportItems response when the criteria meets CreateNew", uploadItemsWithChangedParentFolderIdResponseMessages[i].ItemId.Id, exportedItems[i].ItemId.Id); if (exportedItems[i].ItemId.Id != uploadItemsWithChangedParentFolderIdResponseMessages[i].ItemId.Id) { isNotSameItemId = true; } else { isNotSameItemId = false; break; } } // If the items' ID in UploadItems response is not the same as the previous exported item's ID and the ParentFolderId in GetItem response is not same with it in UploadItem request. // Then MS-OXWSBTRF_R2351 can be captured. bool isNotSameItemIdAndParentFolderId = isNotSameParentFolderId && isNotSameItemId; // Add the debug information. Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXWSBTRF_R2351."); // Verify Requirement: MS-OXWSBTRF_R2351. Site.CaptureRequirementIfIsTrue( isNotSameItemIdAndParentFolderId, 2351, @"[In CreateActionType Simple Type][UpdateOrCreate][If the target item is not in the original folder specified by the <ParentFolderId> element in the UploadItemType complex type]The <ItemId> element that is returned in the UploadItemsResponseMessageType complex type, as specified in section 3.1.4.2.3.2, MUST contain the new item identifier."); #endregion } /// <summary> /// This test case is designed to validate the unsuccessful response returned by ExportItems operation when the request is unsuccessful. /// There are three kinds of situation: /// 1 The ID attribute of ItemId is empty. /// 2 The ChangeKey attribute of ItemId is invalid. /// 3 The ID attribute of ItemId is invalid. /// </summary> [TestCategory("MSOXWSBTRF"), TestMethod()] public void MSOXWSBTRF_S01_TC04_ExportItems_Fail() { #region Get the exported items. // In the initialize step, multiple items in the specified parent folder have been created. // If that step executes successfully, the count of CreatedItemId list should be equal to the count of OriginalFolderId list. Site.Assert.AreEqual<int>( this.CreatedItemId.Count, this.OriginalFolderId.Count, string.Format( "The exportedItemIds array should contain {0} item ids, actually, it contains {1}.", this.OriginalFolderId.Count, this.CreatedItemId.Count)); #endregion #region Call ExportItems operation to export the items from the server. // Initialize three ExportItemsType instances. ExportItemsType exportItems = new ExportItemsType(); // Initialize ItemIdType instances with three different situations: // 1.The ID attribute of ItemId is empty; // 2.The ID attribute of ItemId is valid and the ChangeKey is invalid; // 3.The ID attribute of ItemId is invalid and the ChangeKey is null. exportItems.ItemIds = new ItemIdType[3] { new ItemIdType { Id = string.Empty, ChangeKey = null }, new ItemIdType { Id = this.CreatedItemId[1].Id, ChangeKey = InvalidChangeKey }, new ItemIdType { Id = InvalidItemId, ChangeKey = null } }; // Call ExportItems operation. ExportItemsResponseType exportItemsResponse = this.BTRFAdapter.ExportItems(exportItems); // Check whether the ExportItems operation is executed successfully. foreach (ExportItemsResponseMessageType responseMessage in exportItemsResponse.ResponseMessages.Items) { Site.Assert.AreEqual<ResponseClassType>( ResponseClassType.Error, responseMessage.ResponseClass, string.Format( @"The ExportItems operation should be unsuccessful. Expected response code: {0}, actual response code: {1}", ResponseClassType.Error, responseMessage.ResponseClass)); } #endregion #region Verify ExportItems fail related requirements. this.VerifyExportItemsErrorResponse(exportItemsResponse); #endregion } /// <summary> /// This test case is designed to validate the unsuccessful response returned by UploadItems operation when the request is unsuccessful and the CreateActionType is Update. /// There are four kinds of this situation: /// 1 The target item is not in the original folder specified by the ParentFolderId element in the UploadItemType. /// 2 The ID attribute of ItemId is empty. /// 3 The ChangeKey attribute of ItemId is invalid. /// 4 The ID attribute of ItemId is invalid. /// </summary> [TestCategory("MSOXWSBTRF"), TestMethod()] public void MSOXWSBTRF_S01_TC05_ExportAndUploadItems_Update_Fail() { #region Get the exported items. // Get the exported items which are prepared for uploading. ExportItemsResponseMessageType[] exportedItem = this.ExportItems(false); #endregion #region Create a new folder to place the upload item. // Create another sub folder. string[] subFolderIds = new string[this.ParentFolderType.Count]; for (int i = 0; i < subFolderIds.Length; i++) { // Generate the folder name. string folderName = Common.GenerateResourceName(this.Site, this.ParentFolderType[i] + "NewFolder"); // Create sub folder in the specified parent folder subFolderIds[i] = this.CreateSubFolder(this.ParentFolderType[i], folderName); Site.Assert.IsNotNull( subFolderIds[i], string.Format( "The sub folder named '{0}' under '{1}' should be created successfully.", folderName, this.ParentFolderType[i].ToString())); } #endregion #region Call UploadItems operation with CreateAction set to Update and the ParentFolderId set to the new created sub folder. // Initialize the uploaded items using the previous exported items, set the item's CreateAction to Update and the ParentFolderId to the sub folder. UploadItemsType uploadItemsWithChangedParentFolderId = new UploadItemsType(); uploadItemsWithChangedParentFolderId.Items = new UploadItemType[this.ItemCount]; for (int i = 0; i < uploadItemsWithChangedParentFolderId.Items.Length; i++) { uploadItemsWithChangedParentFolderId.Items[i] = TestSuiteHelper.GenerateUploadItem( exportedItem[i].ItemId.Id, exportedItem[i].ItemId.ChangeKey, exportedItem[i].Data, subFolderIds[i], CreateActionType.Update); } // Call UploadItems operation. UploadItemsResponseType uploadItemsWithChangedParentFolderIdResponse = this.BTRFAdapter.UploadItems(uploadItemsWithChangedParentFolderId); // Check whether the ExportItems operation is executed successfully. foreach (UploadItemsResponseMessageType responseMessage in uploadItemsWithChangedParentFolderIdResponse.ResponseMessages.Items) { Site.Assert.AreEqual<ResponseClassType>( ResponseClassType.Error, responseMessage.ResponseClass, string.Format( @"The ExportItems operation should be unsuccessful. Expected response code: {0}, actual response code: {1}", ResponseClassType.Error, responseMessage.ResponseClass)); } #endregion #region Verify UploadItems related requirements. // Verify UploadItems related requirements. this.VerifyUploadItemsErrorResponse(uploadItemsWithChangedParentFolderIdResponse); // If the ResponseClass property equals Error, then MS-OXWSBTRF_R231 can be captured // Add the debug information. Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXWSBTRF_R231."); // Verify MS-OXWSBTRF requirement: MS-OXWSBTRF_R231 Site.CaptureRequirementIfAreEqual<ResponseCodeType>( ResponseCodeType.ErrorItemNotFound, uploadItemsWithChangedParentFolderIdResponse.ResponseMessages.Items[0].ResponseCode, 231, @"[In CreateActionType Simple Type][Update] if the target item is not in the original folder specified by the <ParentFolderId> element in the UploadItemType complex type, an ErrorItemNotFound error code MUST be returned in the UploadItemsResponseMessageType complex type."); #endregion #region Call UploadItems operation with CreateAction set to Update and the ItemId set to invalid value. // Call UploadItemsFail method to upload three kinds of items and set the CreateAction to Update: // 1.The ID attribute of ItemId is empty; // 2.The ID attribute of ItemId is valid and the ChangeKey is invalid; // 3.The ID attribute of ItemId is invalid and the ChangeKey is null. this.UploadInvalidItems(this.OriginalFolderId, CreateActionType.Update); #endregion } /// <summary> /// This test case is designed to validate unsuccessful response returned by UploadItems operation when the request is unsuccessful and the CreateActionType is CreateOrUpdate. /// There are three kinds of this situation: /// 1 The id attribute of ItemId is empty. /// 2 The ChangeKey attribute of ItemId is invalid. /// 3 The id attribute of ItemId is invalid. /// </summary> [TestCategory("MSOXWSBTRF"), TestMethod()] public void MSOXWSBTRF_S01_TC06_ExportAndUploadItems_UpdateOrCreate_Fail() { #region Call UploadItems operation to upload the items. // Call UploadItemsFail method to upload three kinds of items and set the CreateAction to UpdateOrCreate: // 1.The ID attribute of ItemId is empty; // 2.The ID attribute of ItemId is valid and the ChangeKey is invalid; // 3.The ID attribute of ItemId is invalid and the ChangeKey is null. this.UploadInvalidItems(this.OriginalFolderId, CreateActionType.UpdateOrCreate); #endregion } #endregion } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Diagnostics; namespace Microsoft.CSharp.RuntimeBinder.Semantics { /* // =========================================================================== Defines structs that package an aggregate member together with generic type argument information. // ===========================================================================*/ /****************************************************************************** SymWithType and its cousins. These package an aggregate member (field, prop, event, or meth) together with the particular instantiation of the aggregate (the AggregateType). The default constructor does nothing so these are not safe to use uninitialized. Note that when they are used as member of an EXPR they are automatically zero filled by newExpr. ******************************************************************************/ internal class SymWithType { private AggregateType _ats; private Symbol _sym; public SymWithType() { } public SymWithType(Symbol sym, AggregateType ats) { Set(sym, ats); } public virtual void Clear() { _sym = null; _ats = null; } public AggregateType Ats { get { return _ats; } } public Symbol Sym { get { return _sym; } } public new AggregateType GetType() { // This conflicts with object.GetType. Turn every usage of this // into a get on Ats. return Ats; } public static bool operator ==(SymWithType swt1, SymWithType swt2) { if (object.ReferenceEquals(swt1, swt2)) { return true; } else if (object.ReferenceEquals(swt1, null)) { return swt2._sym == null; } else if (object.ReferenceEquals(swt2, null)) { return swt1._sym == null; } return swt1.Sym == swt2.Sym && swt1.Ats == swt2.Ats; } public static bool operator !=(SymWithType swt1, SymWithType swt2) { if (object.ReferenceEquals(swt1, swt2)) { return false; } else if (object.ReferenceEquals(swt1, null)) { return swt2._sym != null; } else if (object.ReferenceEquals(swt2, null)) { return swt1._sym != null; } return swt1.Sym != swt2.Sym || swt1.Ats != swt2.Ats; } public override bool Equals(object obj) { SymWithType other = obj as SymWithType; if (other == null) return false; return this.Sym == other.Sym && this.Ats == other.Ats; } public override int GetHashCode() { return (this.Sym != null ? this.Sym.GetHashCode() : 0) + (this.Ats != null ? this.Ats.GetHashCode() : 0); } // The SymWithType is considered NULL iff the Symbol is NULL. public static implicit operator bool (SymWithType swt) { return swt != null; } // These assert that the Symbol is of the correct type. public MethodOrPropertySymbol MethProp() { return this.Sym as MethodOrPropertySymbol; } public MethodSymbol Meth() { return this.Sym as MethodSymbol; } public PropertySymbol Prop() { return this.Sym as PropertySymbol; } public FieldSymbol Field() { return this.Sym as FieldSymbol; } public EventSymbol Event() { return this.Sym as EventSymbol; } public void Set(Symbol sym, AggregateType ats) { if (sym == null) ats = null; Debug.Assert(ats == null || sym.parent == ats.getAggregate()); _sym = sym; _ats = ats; } } internal class MethPropWithType : SymWithType { public MethPropWithType() { } public MethPropWithType(MethodOrPropertySymbol mps, AggregateType ats) { Set(mps, ats); } } internal class MethWithType : MethPropWithType { public MethWithType() { } public MethWithType(MethodSymbol meth, AggregateType ats) { Set(meth, ats); } } internal class PropWithType : MethPropWithType { public PropWithType() { } public PropWithType(PropertySymbol prop, AggregateType ats) { Set(prop, ats); } public PropWithType(SymWithType swt) { Set(swt.Sym as PropertySymbol, swt.Ats); } } internal class EventWithType : SymWithType { public EventWithType() { } public EventWithType(EventSymbol @event, AggregateType ats) { Set(@event, ats); } } internal class FieldWithType : SymWithType { public FieldWithType() { } public FieldWithType(FieldSymbol field, AggregateType ats) { Set(field, ats); } } /****************************************************************************** MethPropWithInst and MethWithInst. These extend MethPropWithType with the method type arguments. Properties will never have type args, but methods and properties share a lot of code so it's convenient to allow both here. The default constructor does nothing so these are not safe to use uninitialized. Note that when they are used as member of an EXPR they are automatically zero filled by newExpr. ******************************************************************************/ internal class MethPropWithInst : MethPropWithType { public TypeArray TypeArgs { get; private set; } public MethPropWithInst() { Set(null, null, null); } public MethPropWithInst(MethodOrPropertySymbol mps, AggregateType ats) : this(mps, ats, null) { } public MethPropWithInst(MethodOrPropertySymbol mps, AggregateType ats, TypeArray typeArgs) { Set(mps, ats, typeArgs); } public override void Clear() { base.Clear(); TypeArgs = null; } public void Set(MethodOrPropertySymbol mps, AggregateType ats, TypeArray typeArgs) { if (mps == null) { ats = null; typeArgs = null; } Debug.Assert(ats == null || mps != null && mps.getClass() == ats.getAggregate()); base.Set(mps, ats); this.TypeArgs = typeArgs; } } internal class MethWithInst : MethPropWithInst { public MethWithInst() { } public MethWithInst(MethodSymbol meth, AggregateType ats) : this(meth, ats, null) { } public MethWithInst(MethodSymbol meth, AggregateType ats, TypeArray typeArgs) { Set(meth, ats, typeArgs); } public MethWithInst(MethPropWithInst mpwi) { Set(mpwi.Sym.AsMethodSymbol(), mpwi.Ats, mpwi.TypeArgs); } } }
using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using JetBrains.Annotations; using JsonApiDotNetCore.Configuration; using JsonApiDotNetCore.Diagnostics; using JsonApiDotNetCore.Queries.Expressions; using JsonApiDotNetCore.Resources; using JsonApiDotNetCore.Resources.Annotations; namespace JsonApiDotNetCore.Queries.Internal { /// <inheritdoc /> [PublicAPI] public class QueryLayerComposer : IQueryLayerComposer { private readonly CollectionConverter _collectionConverter = new(); private readonly IEnumerable<IQueryConstraintProvider> _constraintProviders; private readonly IResourceGraph _resourceGraph; private readonly IResourceDefinitionAccessor _resourceDefinitionAccessor; private readonly IJsonApiOptions _options; private readonly IPaginationContext _paginationContext; private readonly ITargetedFields _targetedFields; private readonly IEvaluatedIncludeCache _evaluatedIncludeCache; private readonly SparseFieldSetCache _sparseFieldSetCache; public QueryLayerComposer(IEnumerable<IQueryConstraintProvider> constraintProviders, IResourceGraph resourceGraph, IResourceDefinitionAccessor resourceDefinitionAccessor, IJsonApiOptions options, IPaginationContext paginationContext, ITargetedFields targetedFields, IEvaluatedIncludeCache evaluatedIncludeCache) { ArgumentGuard.NotNull(constraintProviders, nameof(constraintProviders)); ArgumentGuard.NotNull(resourceGraph, nameof(resourceGraph)); ArgumentGuard.NotNull(resourceDefinitionAccessor, nameof(resourceDefinitionAccessor)); ArgumentGuard.NotNull(options, nameof(options)); ArgumentGuard.NotNull(paginationContext, nameof(paginationContext)); ArgumentGuard.NotNull(targetedFields, nameof(targetedFields)); ArgumentGuard.NotNull(evaluatedIncludeCache, nameof(evaluatedIncludeCache)); _constraintProviders = constraintProviders; _resourceGraph = resourceGraph; _resourceDefinitionAccessor = resourceDefinitionAccessor; _options = options; _paginationContext = paginationContext; _targetedFields = targetedFields; _evaluatedIncludeCache = evaluatedIncludeCache; _sparseFieldSetCache = new SparseFieldSetCache(_constraintProviders, resourceDefinitionAccessor); } /// <inheritdoc /> public FilterExpression GetTopFilterFromConstraints(ResourceContext resourceContext) { ExpressionInScope[] constraints = _constraintProviders.SelectMany(provider => provider.GetConstraints()).ToArray(); // @formatter:wrap_chained_method_calls chop_always // @formatter:keep_existing_linebreaks true FilterExpression[] filtersInTopScope = constraints .Where(constraint => constraint.Scope == null) .Select(constraint => constraint.Expression) .OfType<FilterExpression>() .ToArray(); // @formatter:keep_existing_linebreaks restore // @formatter:wrap_chained_method_calls restore return GetFilter(filtersInTopScope, resourceContext); } /// <inheritdoc /> public QueryLayer ComposeFromConstraints(ResourceContext requestResource) { ArgumentGuard.NotNull(requestResource, nameof(requestResource)); ExpressionInScope[] constraints = _constraintProviders.SelectMany(provider => provider.GetConstraints()).ToArray(); QueryLayer topLayer = ComposeTopLayer(constraints, requestResource); topLayer.Include = ComposeChildren(topLayer, constraints); _evaluatedIncludeCache.Set(topLayer.Include); return topLayer; } private QueryLayer ComposeTopLayer(IEnumerable<ExpressionInScope> constraints, ResourceContext resourceContext) { using IDisposable _ = CodeTimingSessionManager.Current.Measure("Top-level query composition"); // @formatter:wrap_chained_method_calls chop_always // @formatter:keep_existing_linebreaks true QueryExpression[] expressionsInTopScope = constraints .Where(constraint => constraint.Scope == null) .Select(constraint => constraint.Expression) .ToArray(); // @formatter:keep_existing_linebreaks restore // @formatter:wrap_chained_method_calls restore PaginationExpression topPagination = GetPagination(expressionsInTopScope, resourceContext); if (topPagination != null) { _paginationContext.PageSize = topPagination.PageSize; _paginationContext.PageNumber = topPagination.PageNumber; } return new QueryLayer(resourceContext) { Filter = GetFilter(expressionsInTopScope, resourceContext), Sort = GetSort(expressionsInTopScope, resourceContext), Pagination = ((JsonApiOptions)_options).DisableTopPagination ? null : topPagination, Projection = GetProjectionForSparseAttributeSet(resourceContext) }; } private IncludeExpression ComposeChildren(QueryLayer topLayer, ICollection<ExpressionInScope> constraints) { using IDisposable _ = CodeTimingSessionManager.Current.Measure("Nested query composition"); // @formatter:wrap_chained_method_calls chop_always // @formatter:keep_existing_linebreaks true IncludeExpression include = constraints .Where(constraint => constraint.Scope == null) .Select(constraint => constraint.Expression) .OfType<IncludeExpression>() .FirstOrDefault() ?? IncludeExpression.Empty; // @formatter:keep_existing_linebreaks restore // @formatter:wrap_chained_method_calls restore IImmutableList<IncludeElementExpression> includeElements = ProcessIncludeSet(include.Elements, topLayer, new List<RelationshipAttribute>(), constraints); return !ReferenceEquals(includeElements, include.Elements) ? includeElements.Any() ? new IncludeExpression(includeElements) : IncludeExpression.Empty : include; } private IImmutableList<IncludeElementExpression> ProcessIncludeSet(IImmutableList<IncludeElementExpression> includeElements, QueryLayer parentLayer, ICollection<RelationshipAttribute> parentRelationshipChain, ICollection<ExpressionInScope> constraints) { IImmutableList<IncludeElementExpression> includeElementsEvaluated = GetIncludeElements(includeElements, parentLayer.ResourceContext) ?? ImmutableArray<IncludeElementExpression>.Empty; var updatesInChildren = new Dictionary<IncludeElementExpression, IImmutableList<IncludeElementExpression>>(); foreach (IncludeElementExpression includeElement in includeElementsEvaluated) { parentLayer.Projection ??= new Dictionary<ResourceFieldAttribute, QueryLayer>(); if (!parentLayer.Projection.ContainsKey(includeElement.Relationship)) { var relationshipChain = new List<RelationshipAttribute>(parentRelationshipChain) { includeElement.Relationship }; // @formatter:wrap_chained_method_calls chop_always // @formatter:keep_existing_linebreaks true QueryExpression[] expressionsInCurrentScope = constraints .Where(constraint => constraint.Scope != null && constraint.Scope.Fields.SequenceEqual(relationshipChain)) .Select(constraint => constraint.Expression) .ToArray(); // @formatter:keep_existing_linebreaks restore // @formatter:wrap_chained_method_calls restore ResourceContext resourceContext = _resourceGraph.GetResourceContext(includeElement.Relationship.RightType); bool isToManyRelationship = includeElement.Relationship is HasManyAttribute; var child = new QueryLayer(resourceContext) { Filter = isToManyRelationship ? GetFilter(expressionsInCurrentScope, resourceContext) : null, Sort = isToManyRelationship ? GetSort(expressionsInCurrentScope, resourceContext) : null, Pagination = isToManyRelationship ? ((JsonApiOptions)_options).DisableChildrenPagination ? null : GetPagination(expressionsInCurrentScope, resourceContext) : null, Projection = GetProjectionForSparseAttributeSet(resourceContext) }; parentLayer.Projection.Add(includeElement.Relationship, child); if (includeElement.Children.Any()) { IImmutableList<IncludeElementExpression> updatedChildren = ProcessIncludeSet(includeElement.Children, child, relationshipChain, constraints); if (!ReferenceEquals(includeElement.Children, updatedChildren)) { updatesInChildren.Add(includeElement, updatedChildren); } } } } return !updatesInChildren.Any() ? includeElementsEvaluated : ApplyIncludeElementUpdates(includeElementsEvaluated, updatesInChildren); } private static IImmutableList<IncludeElementExpression> ApplyIncludeElementUpdates(IImmutableList<IncludeElementExpression> includeElements, IDictionary<IncludeElementExpression, IImmutableList<IncludeElementExpression>> updatesInChildren) { ImmutableArray<IncludeElementExpression>.Builder newElementsBuilder = ImmutableArray.CreateBuilder<IncludeElementExpression>(includeElements.Count); newElementsBuilder.AddRange(includeElements); foreach ((IncludeElementExpression existingElement, IImmutableList<IncludeElementExpression> updatedChildren) in updatesInChildren) { int existingIndex = newElementsBuilder.IndexOf(existingElement); newElementsBuilder[existingIndex] = new IncludeElementExpression(existingElement.Relationship, updatedChildren); } return newElementsBuilder.ToImmutable(); } /// <inheritdoc /> public QueryLayer ComposeForGetById<TId>(TId id, ResourceContext resourceContext, TopFieldSelection fieldSelection) { ArgumentGuard.NotNull(resourceContext, nameof(resourceContext)); AttrAttribute idAttribute = GetIdAttribute(resourceContext); QueryLayer queryLayer = ComposeFromConstraints(resourceContext); queryLayer.Sort = null; queryLayer.Pagination = null; queryLayer.Filter = CreateFilterByIds(id.AsArray(), idAttribute, queryLayer.Filter); if (fieldSelection == TopFieldSelection.OnlyIdAttribute) { queryLayer.Projection = new Dictionary<ResourceFieldAttribute, QueryLayer> { [idAttribute] = null }; } else if (fieldSelection == TopFieldSelection.WithAllAttributes && queryLayer.Projection != null) { // Discard any top-level ?fields[]= or attribute exclusions from resource definition, because we need the full database row. while (queryLayer.Projection.Any(pair => pair.Key is AttrAttribute)) { queryLayer.Projection.Remove(queryLayer.Projection.First(pair => pair.Key is AttrAttribute)); } } return queryLayer; } /// <inheritdoc /> public QueryLayer ComposeSecondaryLayerForRelationship(ResourceContext secondaryResourceContext) { ArgumentGuard.NotNull(secondaryResourceContext, nameof(secondaryResourceContext)); QueryLayer secondaryLayer = ComposeFromConstraints(secondaryResourceContext); secondaryLayer.Projection = GetProjectionForRelationship(secondaryResourceContext); secondaryLayer.Include = null; return secondaryLayer; } private IDictionary<ResourceFieldAttribute, QueryLayer> GetProjectionForRelationship(ResourceContext secondaryResourceContext) { IImmutableSet<AttrAttribute> secondaryAttributeSet = _sparseFieldSetCache.GetIdAttributeSetForRelationshipQuery(secondaryResourceContext); return secondaryAttributeSet.ToDictionary(key => (ResourceFieldAttribute)key, _ => (QueryLayer)null); } /// <inheritdoc /> public QueryLayer WrapLayerForSecondaryEndpoint<TId>(QueryLayer secondaryLayer, ResourceContext primaryResourceContext, TId primaryId, RelationshipAttribute secondaryRelationship) { ArgumentGuard.NotNull(secondaryLayer, nameof(secondaryLayer)); ArgumentGuard.NotNull(primaryResourceContext, nameof(primaryResourceContext)); ArgumentGuard.NotNull(secondaryRelationship, nameof(secondaryRelationship)); IncludeExpression innerInclude = secondaryLayer.Include; secondaryLayer.Include = null; IImmutableSet<AttrAttribute> primaryAttributeSet = _sparseFieldSetCache.GetIdAttributeSetForRelationshipQuery(primaryResourceContext); Dictionary<ResourceFieldAttribute, QueryLayer> primaryProjection = primaryAttributeSet.ToDictionary(key => (ResourceFieldAttribute)key, _ => (QueryLayer)null); primaryProjection[secondaryRelationship] = secondaryLayer; FilterExpression primaryFilter = GetFilter(Array.Empty<QueryExpression>(), primaryResourceContext); AttrAttribute primaryIdAttribute = GetIdAttribute(primaryResourceContext); return new QueryLayer(primaryResourceContext) { Include = RewriteIncludeForSecondaryEndpoint(innerInclude, secondaryRelationship), Filter = CreateFilterByIds(primaryId.AsArray(), primaryIdAttribute, primaryFilter), Projection = primaryProjection }; } private IncludeExpression RewriteIncludeForSecondaryEndpoint(IncludeExpression relativeInclude, RelationshipAttribute secondaryRelationship) { IncludeElementExpression parentElement = relativeInclude != null ? new IncludeElementExpression(secondaryRelationship, relativeInclude.Elements) : new IncludeElementExpression(secondaryRelationship); return new IncludeExpression(ImmutableArray.Create(parentElement)); } private FilterExpression CreateFilterByIds<TId>(IReadOnlyCollection<TId> ids, AttrAttribute idAttribute, FilterExpression existingFilter) { var idChain = new ResourceFieldChainExpression(idAttribute); FilterExpression filter = null; if (ids.Count == 1) { var constant = new LiteralConstantExpression(ids.Single().ToString()); filter = new ComparisonExpression(ComparisonOperator.Equals, idChain, constant); } else if (ids.Count > 1) { ImmutableHashSet<LiteralConstantExpression> constants = ids.Select(id => new LiteralConstantExpression(id.ToString())).ToImmutableHashSet(); filter = new AnyExpression(idChain, constants); } return filter == null ? existingFilter : existingFilter == null ? filter : new LogicalExpression(LogicalOperator.And, filter, existingFilter); } /// <inheritdoc /> public QueryLayer ComposeForUpdate<TId>(TId id, ResourceContext primaryResource) { ArgumentGuard.NotNull(primaryResource, nameof(primaryResource)); ImmutableArray<IncludeElementExpression> includeElements = _targetedFields.Relationships .Select(relationship => new IncludeElementExpression(relationship)).ToImmutableArray(); AttrAttribute primaryIdAttribute = GetIdAttribute(primaryResource); QueryLayer primaryLayer = ComposeTopLayer(Array.Empty<ExpressionInScope>(), primaryResource); primaryLayer.Include = includeElements.Any() ? new IncludeExpression(includeElements) : IncludeExpression.Empty; primaryLayer.Sort = null; primaryLayer.Pagination = null; primaryLayer.Filter = CreateFilterByIds(id.AsArray(), primaryIdAttribute, primaryLayer.Filter); primaryLayer.Projection = null; return primaryLayer; } /// <inheritdoc /> public IEnumerable<(QueryLayer, RelationshipAttribute)> ComposeForGetTargetedSecondaryResourceIds(IIdentifiable primaryResource) { ArgumentGuard.NotNull(primaryResource, nameof(primaryResource)); foreach (RelationshipAttribute relationship in _targetedFields.Relationships) { object rightValue = relationship.GetValue(primaryResource); ICollection<IIdentifiable> rightResourceIds = _collectionConverter.ExtractResources(rightValue); if (rightResourceIds.Any()) { QueryLayer queryLayer = ComposeForGetRelationshipRightIds(relationship, rightResourceIds); yield return (queryLayer, relationship); } } } /// <inheritdoc /> public QueryLayer ComposeForGetRelationshipRightIds(RelationshipAttribute relationship, ICollection<IIdentifiable> rightResourceIds) { ArgumentGuard.NotNull(relationship, nameof(relationship)); ArgumentGuard.NotNull(rightResourceIds, nameof(rightResourceIds)); ResourceContext rightResourceContext = _resourceGraph.GetResourceContext(relationship.RightType); AttrAttribute rightIdAttribute = GetIdAttribute(rightResourceContext); object[] typedIds = rightResourceIds.Select(resource => resource.GetTypedId()).ToArray(); FilterExpression baseFilter = GetFilter(Array.Empty<QueryExpression>(), rightResourceContext); FilterExpression filter = CreateFilterByIds(typedIds, rightIdAttribute, baseFilter); return new QueryLayer(rightResourceContext) { Include = IncludeExpression.Empty, Filter = filter, Projection = new Dictionary<ResourceFieldAttribute, QueryLayer> { [rightIdAttribute] = null } }; } /// <inheritdoc /> public QueryLayer ComposeForHasMany<TId>(HasManyAttribute hasManyRelationship, TId leftId, ICollection<IIdentifiable> rightResourceIds) { ArgumentGuard.NotNull(hasManyRelationship, nameof(hasManyRelationship)); ArgumentGuard.NotNull(rightResourceIds, nameof(rightResourceIds)); ResourceContext leftResourceContext = _resourceGraph.GetResourceContext(hasManyRelationship.LeftType); AttrAttribute leftIdAttribute = GetIdAttribute(leftResourceContext); ResourceContext rightResourceContext = _resourceGraph.GetResourceContext(hasManyRelationship.RightType); AttrAttribute rightIdAttribute = GetIdAttribute(rightResourceContext); object[] rightTypedIds = rightResourceIds.Select(resource => resource.GetTypedId()).ToArray(); FilterExpression leftFilter = CreateFilterByIds(leftId.AsArray(), leftIdAttribute, null); FilterExpression rightFilter = CreateFilterByIds(rightTypedIds, rightIdAttribute, null); return new QueryLayer(leftResourceContext) { Include = new IncludeExpression(ImmutableArray.Create(new IncludeElementExpression(hasManyRelationship))), Filter = leftFilter, Projection = new Dictionary<ResourceFieldAttribute, QueryLayer> { [hasManyRelationship] = new(rightResourceContext) { Filter = rightFilter, Projection = new Dictionary<ResourceFieldAttribute, QueryLayer> { [rightIdAttribute] = null } }, [leftIdAttribute] = null } }; } protected virtual IImmutableList<IncludeElementExpression> GetIncludeElements(IImmutableList<IncludeElementExpression> includeElements, ResourceContext resourceContext) { ArgumentGuard.NotNull(resourceContext, nameof(resourceContext)); return _resourceDefinitionAccessor.OnApplyIncludes(resourceContext.ResourceType, includeElements); } protected virtual FilterExpression GetFilter(IReadOnlyCollection<QueryExpression> expressionsInScope, ResourceContext resourceContext) { ArgumentGuard.NotNull(expressionsInScope, nameof(expressionsInScope)); ArgumentGuard.NotNull(resourceContext, nameof(resourceContext)); ImmutableArray<FilterExpression> filters = expressionsInScope.OfType<FilterExpression>().ToImmutableArray(); FilterExpression filter = filters.Length > 1 ? new LogicalExpression(LogicalOperator.And, filters) : filters.FirstOrDefault(); return _resourceDefinitionAccessor.OnApplyFilter(resourceContext.ResourceType, filter); } protected virtual SortExpression GetSort(IReadOnlyCollection<QueryExpression> expressionsInScope, ResourceContext resourceContext) { ArgumentGuard.NotNull(expressionsInScope, nameof(expressionsInScope)); ArgumentGuard.NotNull(resourceContext, nameof(resourceContext)); SortExpression sort = expressionsInScope.OfType<SortExpression>().FirstOrDefault(); sort = _resourceDefinitionAccessor.OnApplySort(resourceContext.ResourceType, sort); if (sort == null) { AttrAttribute idAttribute = GetIdAttribute(resourceContext); var idAscendingSort = new SortElementExpression(new ResourceFieldChainExpression(idAttribute), true); sort = new SortExpression(ImmutableArray.Create(idAscendingSort)); } return sort; } protected virtual PaginationExpression GetPagination(IReadOnlyCollection<QueryExpression> expressionsInScope, ResourceContext resourceContext) { ArgumentGuard.NotNull(expressionsInScope, nameof(expressionsInScope)); ArgumentGuard.NotNull(resourceContext, nameof(resourceContext)); PaginationExpression pagination = expressionsInScope.OfType<PaginationExpression>().FirstOrDefault(); pagination = _resourceDefinitionAccessor.OnApplyPagination(resourceContext.ResourceType, pagination); pagination ??= new PaginationExpression(PageNumber.ValueOne, _options.DefaultPageSize); return pagination; } protected virtual IDictionary<ResourceFieldAttribute, QueryLayer> GetProjectionForSparseAttributeSet(ResourceContext resourceContext) { ArgumentGuard.NotNull(resourceContext, nameof(resourceContext)); IImmutableSet<ResourceFieldAttribute> fieldSet = _sparseFieldSetCache.GetSparseFieldSetForQuery(resourceContext); if (!fieldSet.Any()) { return null; } HashSet<AttrAttribute> attributeSet = fieldSet.OfType<AttrAttribute>().ToHashSet(); AttrAttribute idAttribute = GetIdAttribute(resourceContext); attributeSet.Add(idAttribute); return attributeSet.ToDictionary(key => (ResourceFieldAttribute)key, _ => (QueryLayer)null); } private static AttrAttribute GetIdAttribute(ResourceContext resourceContext) { return resourceContext.GetAttributeByPropertyName(nameof(Identifiable.Id)); } } }
/* ==================================================================== 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.Xml; using System.IO; using System.Collections; using System.Collections.Generic; namespace fyiReporting.RDL { ///<summary> /// DataRegion base class definition and processing. /// Warning if you inherit from DataRegion look at Expression.cs first. ///</summary> [Serializable] internal class DataRegion : ReportItem { bool _KeepTogether; // Indicates the entire data region (all // repeated sections) should be kept // together on one page if possible. Expression _NoRows; // (string) Message to display in the DataRegion // (instead of the region layout) when // no rows of data are available. // Note: Style information on the data region applies to this text string _DataSetName; // Indicates which data set to use for this data region. //Mandatory for top level DataRegions //(not contained within another //DataRegion) if there is not exactly //one data set in the report. If there is //exactly one data set in the report, the //data region uses that data set. (Note: //If there are zero data sets in the //report, data regions can not be used, //as there is no valid DataSetName to //use) Ignored for DataRegions that are //not top level. DataSetDefn _DataSetDefn; // resolved data set name; bool _PageBreakAtStart; // Indicates the report should page break // at the start of the data region. bool _PageBreakAtEnd; // Indicates the report should page break // at the end of the data region. Filters _Filters; // Filters to apply to each row of data in the data region. DataRegion _ParentDataRegion; // when DataRegions are nested; the nested regions have the parent set internal DataRegion(ReportDefn r, ReportLink p, XmlNode xNode):base(r,p,xNode) { _KeepTogether=false; _NoRows=null; _DataSetName=null; _DataSetDefn=null; _PageBreakAtStart=false; _PageBreakAtEnd=false; _Filters=null; } internal bool DataRegionElement(XmlNode xNodeLoop) { switch (xNodeLoop.Name) { case "KeepTogether": _KeepTogether = XmlUtil.Boolean(xNodeLoop.InnerText, OwnerReport.rl); break; case "NoRows": _NoRows = new Expression(OwnerReport, this, xNodeLoop, ExpressionType.String); break; case "DataSetName": _DataSetName = xNodeLoop.InnerText; break; case "PageBreakAtStart": _PageBreakAtStart = XmlUtil.Boolean(xNodeLoop.InnerText, OwnerReport.rl); break; case "PageBreakAtEnd": _PageBreakAtEnd = XmlUtil.Boolean(xNodeLoop.InnerText, OwnerReport.rl); break; case "Filters": _Filters = new Filters(OwnerReport, this, xNodeLoop); break; default: // Will get many that are handled by the specific // type of data region: ie list,chart,matrix,table if (ReportItemElement(xNodeLoop)) // try at ReportItem level break; return false; } return true; } // Handle parsing of function in final pass override internal void FinalPass() { base.FinalPass(); if (this is Table) { // Grids don't have any data responsibilities Table t = this as Table; if (t.IsGrid) return; } // DataRegions aren't allowed in PageHeader or PageFooter; if (this.InPageHeaderOrFooter()) OwnerReport.rl.LogError(8, String.Format("The DataRegion '{0}' is not allowed in a PageHeader or PageFooter", this.Name == null? "unknown": Name.Nm) ); ResolveNestedDataRegions(); if (_ParentDataRegion != null) // when nested we use the dataset of the parent { _DataSetDefn = _ParentDataRegion.DataSetDefn; } else if (_DataSetName != null) { if (OwnerReport.DataSetsDefn != null) _DataSetDefn = (DataSetDefn) OwnerReport.DataSetsDefn.Items[_DataSetName]; if (_DataSetDefn == null) { OwnerReport.rl.LogError(8, String.Format("DataSetName '{0}' not specified in DataSets list.", _DataSetName)); } } else { // No name but maybe we can default to a single Dataset if (_DataSetDefn == null && OwnerReport.DataSetsDefn != null && OwnerReport.DataSetsDefn.Items.Count == 1) { foreach (DataSetDefn d in OwnerReport.DataSetsDefn.Items.Values) { _DataSetDefn = d; break; // since there is only 1 this will obtain it } } if (_DataSetDefn == null) OwnerReport.rl.LogError(8, string.Format("{0} must specify a DataSetName.",this.Name == null? "DataRegions": this.Name.Nm)); } if (_NoRows != null) _NoRows.FinalPass(); if (_Filters != null) _Filters.FinalPass(); return; } void ResolveNestedDataRegions() { ReportLink rl = this.Parent; while (rl != null) { if (rl is DataRegion) { this._ParentDataRegion = rl as DataRegion; break; } rl = rl.Parent; } return; } override internal void Run(IPresent ip, Row row) { base.Run(ip, row); } internal void RunPageRegionBegin(Pages pgs) { if (this.TC == null && this.PageBreakAtStart && !pgs.CurrentPage.IsEmpty()) { // force page break at beginning of dataregion pgs.NextOrNew(); pgs.CurrentPage.YOffset = OwnerReport.TopOfPage; } } internal void RunPageRegionEnd(Pages pgs) { if (this.TC == null && this.PageBreakAtEnd && !pgs.CurrentPage.IsEmpty()) { // force page break at beginning of dataregion pgs.NextOrNew(); pgs.CurrentPage.YOffset = OwnerReport.TopOfPage; } } internal bool AnyRows(IPresent ip, Rows data) { if (data == null || data.Data == null || data.Data.Count <= 0) { string msg; if (this.NoRows != null) msg = this.NoRows.EvaluateString(ip.Report(), null); else msg = null; ip.DataRegionNoRows(this, msg); return false; } return true; } internal bool AnyRowsPage(Pages pgs, Rows data) { if (data != null && data.Data != null && data.Data.Count > 0) return true; string msg; if (this.NoRows != null) msg = this.NoRows.EvaluateString(pgs.Report, null); else msg = null; if (msg == null) return false; // OK we have a message we need to put out RunPageRegionBegin(pgs); // still perform page break if needed PageText pt = new PageText(msg); SetPagePositionAndStyle(pgs.Report, pt, null); if (pt.SI.BackgroundImage != null) pt.SI.BackgroundImage.H = pt.H; // and in the background image pgs.CurrentPage.AddObject(pt); RunPageRegionEnd(pgs); // perform end page break if needed SetPagePositionEnd(pgs, pt.Y + pt.H); return false; } internal Rows GetFilteredData(Report rpt, Row row) { try { Rows data; if (this._Filters == null) { if (this._ParentDataRegion == null) { data = DataSetDefn.Query.GetMyData(rpt); return data == null? null: new Rows(rpt, data); // We need to copy in case DataSet is shared by multiple DataRegions } else return GetNestedData(rpt, row); } if (this._ParentDataRegion == null) { data = DataSetDefn.Query.GetMyData(rpt); if (data != null) data = new Rows(rpt, data); } else data = GetNestedData(rpt, row); if (data == null) return null; List<Row> ar = new List<Row>(); foreach (Row r in data.Data) { if (_Filters.Apply(rpt, r)) ar.Add(r); } ar.TrimExcess(); data.Data = ar; _Filters.ApplyFinalFilters(rpt, data, true); // Adjust the rowcount int rCount = 0; foreach (Row r in ar) { r.RowNumber = rCount++; } return data; } catch (Exception e) { this.OwnerReport.rl.LogError(8, e.Message); return null; } } Rows GetNestedData(Report rpt, Row row) { if (row == null) return null; ReportLink rl = this.Parent; while (rl != null) { if (rl is TableGroup || rl is List || rl is MatrixCell) break; rl = rl.Parent; } if (rl == null) return null; // should have been caught as an error Grouping g=null; if (rl is TableGroup) { TableGroup tg = rl as TableGroup; g = tg.Grouping; } else if (rl is List) { List l = rl as List; g = l.Grouping; } else if (rl is MatrixCell) { MatrixCellEntry mce = this.GetMC(rpt); return new Rows(rpt, mce.Data); } if (g == null) return null; GroupEntry ge = row.R.CurrentGroups[g.GetIndex(rpt)]; return new Rows(rpt, row.R, ge.StartRow, ge.EndRow, null); } internal void DataRegionFinish() { // All dataregion names need to be saved! if (this.Name != null) { try { OwnerReport.LUAggrScope.Add(this.Name.Nm, this); // add to referenceable regions } catch // wish duplicate had its own exception { OwnerReport.rl.LogError(8, "Duplicate name '" + this.Name.Nm + "'."); } } return; } internal bool KeepTogether { get { return _KeepTogether; } set { _KeepTogether = value; } } internal Expression NoRows { get { return _NoRows; } set { _NoRows = value; } } internal string DataSetName { get { return _DataSetName; } set { _DataSetName = value; } } internal DataSetDefn DataSetDefn { get { return _DataSetDefn; } set { _DataSetDefn = value; } } internal bool PageBreakAtStart { get { return _PageBreakAtStart; } set { _PageBreakAtStart = value; } } internal bool PageBreakAtEnd { get { return _PageBreakAtEnd; } set { _PageBreakAtEnd = value; } } internal Filters Filters { get { return _Filters; } set { _Filters = value; } } } }
// 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.Globalization; using System.IO; using System.Reflection; using System.Runtime.Remoting; using System.Security; using System.Security.Permissions; using Microsoft.DotNet.RemoteExecutor; using Xunit; namespace System.Tests { class AGenericClass<T> { } public partial class AppDomainTests { [Fact] public void GetSetupInformation() { RemoteExecutor.Invoke(() => { Assert.Equal(AppContext.BaseDirectory, AppDomain.CurrentDomain.SetupInformation.ApplicationBase); Assert.Equal(AppContext.TargetFrameworkName, AppDomain.CurrentDomain.SetupInformation.TargetFrameworkName); return RemoteExecutor.SuccessExitCode; }).Dispose(); } [Fact] public static void GetPermissionSet() { RemoteExecutor.Invoke(() => { Assert.Equal(new PermissionSet(PermissionState.Unrestricted), AppDomain.CurrentDomain.PermissionSet); return RemoteExecutor.SuccessExitCode; }).Dispose(); } [Theory] [MemberData(nameof(TestingCreateInstanceFromObjectHandleData))] public static void TestingCreateInstanceFromObjectHandle(string physicalFileName, string assemblyFile, string type, string returnedFullNameType, Type exceptionType) { ObjectHandle oh = null; object obj = null; if (exceptionType != null) { Assert.Throws(exceptionType, () => AppDomain.CurrentDomain.CreateInstanceFrom(assemblyFile: assemblyFile, typeName: type)); Assert.Throws(exceptionType, () => AppDomain.CurrentDomain.CreateInstanceFromAndUnwrap(assemblyFile: assemblyFile, typeName: type)); } else { oh = AppDomain.CurrentDomain.CreateInstanceFrom(assemblyFile: assemblyFile, typeName: type); CheckValidity(oh, returnedFullNameType); obj = AppDomain.CurrentDomain.CreateInstanceFromAndUnwrap(assemblyFile: assemblyFile, typeName: type); CheckValidity(obj, returnedFullNameType); } if (exceptionType != null) { Assert.Throws(exceptionType, () => AppDomain.CurrentDomain.CreateInstanceFrom(assemblyFile: assemblyFile, typeName: type, null)); Assert.Throws(exceptionType, () => AppDomain.CurrentDomain.CreateInstanceFromAndUnwrap(assemblyFile: assemblyFile, typeName: type, null)); } else { oh = AppDomain.CurrentDomain.CreateInstanceFrom(assemblyFile: assemblyFile, typeName: type, null); CheckValidity(oh, returnedFullNameType); obj = AppDomain.CurrentDomain.CreateInstanceFromAndUnwrap(assemblyFile: assemblyFile, typeName: type, null); CheckValidity(obj, returnedFullNameType); } Assert.True(File.Exists(physicalFileName)); } public static TheoryData<string, string, string, string, Type> TestingCreateInstanceFromObjectHandleData => new TheoryData<string, string, string, string, Type> { // string physicalFileName, string assemblyFile, string typeName, returnedFullNameType, expectedException { "AssemblyResolveTestApp.dll", "AssemblyResolveTestApp.dll", "AssemblyResolveTestApp.PublicClassSample", "AssemblyResolveTestApp.PublicClassSample", null }, { "AssemblyResolveTestApp.dll", "assemblyresolvetestapp.dll", "assemblyresolvetestapp.publicclasssample", "AssemblyResolveTestApp.PublicClassSample", typeof(TypeLoadException) }, { "AssemblyResolveTestApp.dll", "AssemblyResolveTestApp.dll", "AssemblyResolveTestApp.PrivateClassSample", "AssemblyResolveTestApp.PrivateClassSample", null }, { "AssemblyResolveTestApp.dll", "assemblyresolvetestapp.dll", "assemblyresolvetestapp.privateclasssample", "AssemblyResolveTestApp.PrivateClassSample", typeof(TypeLoadException) }, { "AssemblyResolveTestApp.dll", "AssemblyResolveTestApp.dll", "AssemblyResolveTestApp.PublicClassNoDefaultConstructorSample", "AssemblyResolveTestApp.PublicClassNoDefaultConstructorSample", typeof(MissingMethodException) }, { "AssemblyResolveTestApp.dll", "assemblyresolvetestapp.dll", "assemblyresolvetestapp.publicclassnodefaultconstructorsample", "AssemblyResolveTestApp.PublicClassNoDefaultConstructorSample", typeof(TypeLoadException) } }; [Theory] [MemberData(nameof(TestingCreateInstanceObjectHandleData))] public static void TestingCreateInstanceObjectHandle(string assemblyName, string type, string returnedFullNameType, Type exceptionType) { ObjectHandle oh = null; object obj = null; if (exceptionType != null) { Assert.Throws(exceptionType, () => AppDomain.CurrentDomain.CreateInstance(assemblyName: assemblyName, typeName: type)); Assert.Throws(exceptionType, () => AppDomain.CurrentDomain.CreateInstanceAndUnwrap(assemblyName: assemblyName, typeName: type)); } else { oh = AppDomain.CurrentDomain.CreateInstance(assemblyName: assemblyName, typeName: type); CheckValidity(oh, returnedFullNameType); obj = AppDomain.CurrentDomain.CreateInstanceAndUnwrap(assemblyName: assemblyName, typeName: type); CheckValidity(obj, returnedFullNameType); } if (exceptionType != null) { Assert.Throws(exceptionType, () => AppDomain.CurrentDomain.CreateInstance(assemblyName: assemblyName, typeName: type, null)); Assert.Throws(exceptionType, () => AppDomain.CurrentDomain.CreateInstanceAndUnwrap(assemblyName: assemblyName, typeName: type, null)); } else { oh = AppDomain.CurrentDomain.CreateInstance(assemblyName: assemblyName, typeName: type, null); CheckValidity(oh, returnedFullNameType); obj = AppDomain.CurrentDomain.CreateInstanceAndUnwrap(assemblyName: assemblyName, typeName: type, null); CheckValidity(obj, returnedFullNameType); } } public static TheoryData<string, string, string, Type> TestingCreateInstanceObjectHandleData => new TheoryData<string, string, string, Type>() { // string assemblyName, string typeName, returnedFullNameType, expectedException { "AssemblyResolveTestApp", "AssemblyResolveTestApp.PublicClassSample", "AssemblyResolveTestApp.PublicClassSample", null }, { "assemblyresolvetestapp", "assemblyresolvetestapp.publicclasssample", "AssemblyResolveTestApp.PublicClassSample", typeof(TypeLoadException) }, { "AssemblyResolveTestApp", "AssemblyResolveTestApp.PrivateClassSample", "AssemblyResolveTestApp.PrivateClassSample", null }, { "assemblyresolvetestapp", "assemblyresolvetestapp.privateclasssample", "AssemblyResolveTestApp.PrivateClassSample", typeof(TypeLoadException) }, { "AssemblyResolveTestApp", "AssemblyResolveTestApp.PublicClassNoDefaultConstructorSample", "AssemblyResolveTestApp.PublicClassNoDefaultConstructorSample", typeof(MissingMethodException) }, { "assemblyresolvetestapp", "assemblyresolvetestapp.publicclassnodefaultconstructorsample", "AssemblyResolveTestApp.PublicClassNoDefaultConstructorSample", typeof(TypeLoadException) } }; [Theory] [MemberData(nameof(TestingCreateInstanceFromObjectHandleFullSignatureData))] public static void TestingCreateInstanceFromObjectHandleFullSignature(string physicalFileName, string assemblyFile, string type, bool ignoreCase, BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture, object[] activationAttributes, string returnedFullNameType) { ObjectHandle oh = AppDomain.CurrentDomain.CreateInstanceFrom(assemblyFile: assemblyFile, typeName: type, ignoreCase: ignoreCase, bindingAttr: bindingAttr, binder: binder, args: args, culture: culture, activationAttributes: activationAttributes); CheckValidity(oh, returnedFullNameType); object obj = AppDomain.CurrentDomain.CreateInstanceFromAndUnwrap(assemblyFile: assemblyFile, typeName: type, ignoreCase: ignoreCase, bindingAttr: bindingAttr, binder: binder, args: args, culture: culture, activationAttributes: activationAttributes); CheckValidity(obj, returnedFullNameType); Assert.True(File.Exists(physicalFileName)); } public static IEnumerable<object[]> TestingCreateInstanceFromObjectHandleFullSignatureData() { // string physicalFileName, string assemblyFile, string typeName, bool ignoreCase, BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture, object[] activationAttributes, returnedFullNameType yield return new object[] { "AssemblyResolveTestApp.dll", "AssemblyResolveTestApp.dll", "AssemblyResolveTestApp.PublicClassSample", false, BindingFlags.Public | BindingFlags.Instance, Type.DefaultBinder, new object[0], CultureInfo.InvariantCulture, null, "AssemblyResolveTestApp.PublicClassSample" }; yield return new object[] { "AssemblyResolveTestApp.dll", "assemblyresolvetestapp.dll", "assemblyresolvetestapp.publicclasssample", true, BindingFlags.Public | BindingFlags.Instance, Type.DefaultBinder, new object[0], CultureInfo.InvariantCulture, null, "AssemblyResolveTestApp.PublicClassSample" }; yield return new object[] { "AssemblyResolveTestApp.dll", "AssemblyResolveTestApp.dll", "AssemblyResolveTestApp.PublicClassSample", false, BindingFlags.Public | BindingFlags.Instance, Type.DefaultBinder, new object[1] { 1 }, CultureInfo.InvariantCulture, null, "AssemblyResolveTestApp.PublicClassSample" }; yield return new object[] { "AssemblyResolveTestApp.dll", "assemblyresolvetestapp.dll", "assemblyresolvetestapp.publicclasssample", true, BindingFlags.Public | BindingFlags.Instance, Type.DefaultBinder, new object[1] { 1 }, CultureInfo.InvariantCulture, null, "AssemblyResolveTestApp.PublicClassSample" }; yield return new object[] { "AssemblyResolveTestApp.dll", "AssemblyResolveTestApp.dll", "AssemblyResolveTestApp.PrivateClassSample", false, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance, Type.DefaultBinder, new object[0], CultureInfo.InvariantCulture, null, "AssemblyResolveTestApp.PrivateClassSample" }; yield return new object[] { "AssemblyResolveTestApp.dll", "assemblyresolvetestapp.dll", "assemblyresolvetestapp.privateclasssample", true, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance, Type.DefaultBinder, new object[0], CultureInfo.InvariantCulture, null, "AssemblyResolveTestApp.PrivateClassSample" }; yield return new object[] { "AssemblyResolveTestApp.dll", "AssemblyResolveTestApp.dll", "AssemblyResolveTestApp.PrivateClassSample", false, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance, Type.DefaultBinder, new object[1] { 1 }, CultureInfo.InvariantCulture, null, "AssemblyResolveTestApp.PrivateClassSample" }; yield return new object[] { "AssemblyResolveTestApp.dll", "assemblyresolvetestapp.dll", "assemblyresolvetestapp.privateclasssample", true, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance, Type.DefaultBinder, new object[1] { 1 }, CultureInfo.InvariantCulture, null, "AssemblyResolveTestApp.PrivateClassSample" }; } [Theory] [MemberData(nameof(TestingCreateInstanceObjectHandleFullSignatureData))] public static void TestingCreateInstanceObjectHandleFullSignature(string assemblyName, string type, bool ignoreCase, BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture, object[] activationAttributes, string returnedFullNameType) { ObjectHandle oh = AppDomain.CurrentDomain.CreateInstance(assemblyName: assemblyName, typeName: type, ignoreCase: ignoreCase, bindingAttr: bindingAttr, binder: binder, args: args, culture: culture, activationAttributes: activationAttributes); CheckValidity(oh, returnedFullNameType); object obj = AppDomain.CurrentDomain.CreateInstanceAndUnwrap(assemblyName: assemblyName, typeName: type, ignoreCase: ignoreCase, bindingAttr: bindingAttr, binder: binder, args: args, culture: culture, activationAttributes: activationAttributes); CheckValidity(obj, returnedFullNameType); } private static void CheckValidity(object instance, string expected) { Assert.NotNull(instance); Assert.Equal(expected, instance.GetType().FullName); } private static void CheckValidity(ObjectHandle instance, string expected) { Assert.NotNull(instance); Assert.Equal(expected, instance.Unwrap().GetType().FullName); } public static IEnumerable<object[]> TestingCreateInstanceObjectHandleFullSignatureData() { // string assemblyName, string typeName, bool ignoreCase, BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture, object[] activationAttributes, returnedFullNameType yield return new object[] { "AssemblyResolveTestApp", "AssemblyResolveTestApp.PublicClassSample", false, BindingFlags.Public | BindingFlags.Instance, Type.DefaultBinder, new object[0], CultureInfo.InvariantCulture, null, "AssemblyResolveTestApp.PublicClassSample" }; yield return new object[] { "assemblyresolvetestapp", "assemblyresolvetestapp.publicclasssample", true, BindingFlags.Public | BindingFlags.Instance, Type.DefaultBinder, new object[0], CultureInfo.InvariantCulture, null, "AssemblyResolveTestApp.PublicClassSample" }; yield return new object[] { "AssemblyResolveTestApp", "AssemblyResolveTestApp.PublicClassSample", false, BindingFlags.Public | BindingFlags.Instance, Type.DefaultBinder, new object[1] { 1 }, CultureInfo.InvariantCulture, null, "AssemblyResolveTestApp.PublicClassSample" }; yield return new object[] { "assemblyresolvetestapp", "assemblyresolvetestapp.publicclasssample", true, BindingFlags.Public | BindingFlags.Instance, Type.DefaultBinder, new object[1] { 1 }, CultureInfo.InvariantCulture, null, "AssemblyResolveTestApp.PublicClassSample" }; yield return new object[] { "AssemblyResolveTestApp", "AssemblyResolveTestApp.PrivateClassSample", false, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance, Type.DefaultBinder, new object[0], CultureInfo.InvariantCulture, null, "AssemblyResolveTestApp.PrivateClassSample" }; yield return new object[] { "assemblyresolvetestapp", "assemblyresolvetestapp.privateclasssample", true, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance, Type.DefaultBinder, new object[0], CultureInfo.InvariantCulture, null, "AssemblyResolveTestApp.PrivateClassSample" }; yield return new object[] { "AssemblyResolveTestApp", "AssemblyResolveTestApp.PrivateClassSample", false, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance, Type.DefaultBinder, new object[1] { 1 }, CultureInfo.InvariantCulture, null, "AssemblyResolveTestApp.PrivateClassSample" }; yield return new object[] { "assemblyresolvetestapp", "assemblyresolvetestapp.privateclasssample", true, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance, Type.DefaultBinder, new object[1] { 1 }, CultureInfo.InvariantCulture, null, "AssemblyResolveTestApp.PrivateClassSample" }; } [Fact] public void AssemblyResolve_FirstChanceException() { RemoteExecutor.Invoke(() => { Assembly assembly = typeof(AppDomainTests).Assembly; Exception firstChanceExceptionThrown = null; EventHandler<System.Runtime.ExceptionServices.FirstChanceExceptionEventArgs> firstChanceHandler = (source, args) => { firstChanceExceptionThrown = args.Exception; }; AppDomain.CurrentDomain.FirstChanceException += firstChanceHandler; ResolveEventHandler assemblyResolveHandler = (sender, e) => { Assert.Equal(assembly, e.RequestingAssembly); Assert.Null(firstChanceExceptionThrown); return null; }; AppDomain.CurrentDomain.AssemblyResolve += assemblyResolveHandler; Func<System.Runtime.Loader.AssemblyLoadContext, AssemblyName, Assembly> resolvingHandler = (context, name) => { return null; }; // The issue resolved by coreclr#24450, was only reproduced when there was a Resolving handler present System.Runtime.Loader.AssemblyLoadContext.Default.Resolving += resolvingHandler; assembly.GetType("System.Tests.AGenericClass`1[[Bogus, BogusAssembly]]", false); Assert.Null(firstChanceExceptionThrown); Exception thrown = Assert.Throws<FileNotFoundException>(() => assembly.GetType("System.Tests.AGenericClass`1[[Bogus, AnotherBogusAssembly]]", true)); Assert.Same(firstChanceExceptionThrown, thrown); return RemoteExecutor.SuccessExitCode; }).Dispose(); } } }
// // API.AI Unity SDK - Unity libraries for API.AI // ================================================= // // Copyright (C) 2015 by Speaktoit, Inc. (https://www.speaktoit.com) // https://www.api.ai // // *********************************************************************************************************************** // // 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 UnityEngine; using ApiAiSDK; using ApiAiSDK.Model; using System.Threading; using System.Linq; using System.ComponentModel; #if UNITY_ANDROID using ApiAiSDK.Unity.Android; #endif namespace ApiAiSDK.Unity { public class ApiAiUnity { private ApiAi apiAi; private AIConfiguration config; private AudioSource audioSource; private volatile bool recordingActive; private readonly object thisLock = new object(); #if UNITY_ANDROID private ResultWrapper androidResultWrapper; private AndroidRecognizer androidRecognizer; #endif public event EventHandler<AIResponseEventArgs> OnResult; public event EventHandler<AIErrorEventArgs> OnError; public event EventHandler<EventArgs> OnListeningStarted; public event EventHandler<EventArgs> OnListeningFinished; public ApiAiUnity() { } public void Initialize(AIConfiguration config) { this.config = config; apiAi = new ApiAi(this.config); #if UNITY_ANDROID if(Application.platform == RuntimePlatform.Android) { InitializeAndroid(); } #endif } #if UNITY_ANDROID private void InitializeAndroid(){ androidRecognizer = new AndroidRecognizer(); androidRecognizer.Initialize(); } #endif public void Update() { #if UNITY_ANDROID if (androidResultWrapper != null) { UpdateAndroidResult(); } #endif } #if UNITY_ANDROID private void UpdateAndroidResult(){ Debug.Log("UpdateAndroidResult"); var wrapper = androidResultWrapper; if (wrapper.IsReady) { var recognitionResult = wrapper.GetResult(); androidResultWrapper = null; androidRecognizer.Clean(); if (recognitionResult.IsError) { FireOnError(new Exception(recognitionResult.ErrorMessage)); } else { var request = new AIRequest { Query = recognitionResult.RecognitionResults, Confidence = recognitionResult.Confidence }; var aiResponse = apiAi.TextRequest(request); ProcessResult(aiResponse); } } } #endif public void StartListening(AudioSource audioSource) { lock (thisLock) { if (!recordingActive) { this.audioSource = audioSource; StartRecording(); } else { Debug.LogWarning("Can't start new recording session while another recording session active"); } } } public void StartNativeRecognition(){ if (Application.platform != RuntimePlatform.Android) { throw new InvalidOperationException("Now only Android supported"); } #if UNITY_ANDROID if (androidResultWrapper == null) { androidResultWrapper = androidRecognizer.Recognize(config.Language.code); } #endif } public void StopListening() { if (recordingActive) { float[] samples = null; lock (thisLock) { if (recordingActive) { StopRecording(); samples = new float[audioSource.clip.samples]; audioSource.clip.GetData(samples, 0); audioSource = null; } } new Thread(StartVoiceRequest).Start(samples); } } private void StartVoiceRequest(object parameter){ float[] samples = (float[])parameter; if (samples != null) { try { var aiResponse = apiAi.VoiceRequest(samples); ProcessResult(aiResponse); } catch (Exception ex) { FireOnError(ex); } } } private void ProcessResult(AIResponse aiResponse) { if (aiResponse != null) { FireOnResult(aiResponse); } else { FireOnError(new Exception("API.AI Service returns null")); } } private void StartRecording() { // audioSource.clip = Microphone.Start(null, true, 20, 16000); // recordingActive = true; // FireOnListeningStarted(); } private void StopRecording() { // Microphone.End(null); // recordingActive = false; // FireOnListeningFinished(); } private void FireOnResult(AIResponse aiResponse){ var onResult = OnResult; if (onResult != null) { onResult(this, new AIResponseEventArgs(aiResponse)); } } private void FireOnError(Exception e){ var onError = OnError; if (onError != null) { onError(this, new AIErrorEventArgs(e)); } } private void FireOnListeningStarted(){ var onListeningStarted = OnListeningStarted; if (onListeningStarted != null) { onListeningStarted(this, EventArgs.Empty); } } private void FireOnListeningFinished(){ var onListeningFinished = OnListeningFinished; if (onListeningFinished != null) { onListeningFinished(this, EventArgs.Empty); } } public AIResponse TextRequest(string request) { return apiAi.TextRequest(request); } private void ResetContexts() { // TODO } } public class AIResponseEventArgs : EventArgs { private readonly AIResponse response; public AIResponse Response { get { return response; } } public AIResponseEventArgs(AIResponse response) { this.response = response; } } public class AIErrorEventArgs : EventArgs { private readonly Exception exception; public Exception Exception { get { return exception; } } public AIErrorEventArgs(Exception ex) { exception = ex; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.Net; using Azure.Data.Tables.Sas; using NUnit.Framework; namespace Azure.Data.Tables.Tests { public class TableUriBuilderTests { [Test] public void TableUriBuilder_RegularUrl_AccountTest() { // Arrange var uriString = "https://account.core.table.windows.net?comp=list"; var originalUri = new UriBuilder(uriString); // Act var tableuribuilder = new TableUriBuilder(originalUri.Uri); Uri newUri = tableuribuilder.ToUri(); // Assert Assert.AreEqual("https", tableuribuilder.Scheme); Assert.AreEqual("account.core.table.windows.net", tableuribuilder.Host); Assert.AreEqual(443, tableuribuilder.Port); Assert.IsNull(tableuribuilder.Sas); Assert.AreEqual("comp=list", tableuribuilder.Query); Assert.AreEqual(originalUri, newUri); } [Test] public void TableUriBuilder_RegularUrl_TableTest() { // Arrange var uriString = "https://account.core.table.windows.net/table"; var originalUri = new UriBuilder(uriString); // Act var tableuribuilder = new TableUriBuilder(originalUri.Uri); Uri newUri = tableuribuilder.ToUri(); // Assert Assert.AreEqual("https", tableuribuilder.Scheme); Assert.AreEqual("account.core.table.windows.net", tableuribuilder.Host); Assert.AreEqual(443, tableuribuilder.Port); Assert.IsNull(tableuribuilder.Sas); Assert.AreEqual("", tableuribuilder.Query); Assert.AreEqual(originalUri, newUri); } [Test] public void TableUriBuilder_RegularUrl_PortTest() { // Arrange var uriString = "https://account.core.table.windows.net:8080/table"; var originalUri = new UriBuilder(uriString); // Act var tableuribuilder = new TableUriBuilder(originalUri.Uri); Uri newUri = tableuribuilder.ToUri(); // Assert Assert.AreEqual("https", tableuribuilder.Scheme); Assert.AreEqual("account.core.table.windows.net", tableuribuilder.Host); Assert.AreEqual(8080, tableuribuilder.Port); Assert.IsNull(tableuribuilder.Sas); Assert.AreEqual("", tableuribuilder.Query); Assert.AreEqual(originalUri, newUri); } [Test] public void TableUriBuilder_RegularUrl_SasTest() { // Arrange var uriString = "https://account.core.table.windows.net/table?tn=table&sv=2015-04-05&spr=https&st=2015-04-29T22%3A18%3A26Z&se=2015-04-30T02%3A23%3A26Z&sip=168.1.5.60-168.1.5.70&sr=b&sp=rw&sig=Z%2FRHIX5Xcg0Mq2rqI3OlWTjEg2tYkboXr1P9ZUXDtkk%3D"; var originalUri = new UriBuilder(uriString); // Act var tableuribuilder = new TableUriBuilder(originalUri.Uri); Uri newUri = tableuribuilder.ToUri(); // Assert Assert.AreEqual("https", tableuribuilder.Scheme); Assert.AreEqual("account.core.table.windows.net", tableuribuilder.Host); Assert.AreEqual(443, tableuribuilder.Port); Assert.AreEqual(new DateTimeOffset(2015, 4, 30, 2, 23, 26, TimeSpan.Zero), tableuribuilder.Sas.ExpiresOn); Assert.AreEqual("", tableuribuilder.Sas.Identifier); Assert.AreEqual(TableSasIPRange.Parse("168.1.5.60-168.1.5.70"), tableuribuilder.Sas.IPRange); Assert.AreEqual("rw", tableuribuilder.Sas.Permissions); Assert.AreEqual(TableSasProtocol.Https, tableuribuilder.Sas.Protocol); Assert.AreEqual("b", tableuribuilder.Sas.Resource); Assert.IsNull(tableuribuilder.Sas.ResourceTypes); Assert.AreEqual("Z/RHIX5Xcg0Mq2rqI3OlWTjEg2tYkboXr1P9ZUXDtkk=", tableuribuilder.Sas.Signature); Assert.AreEqual(new DateTimeOffset(2015, 4, 29, 22, 18, 26, TimeSpan.Zero), tableuribuilder.Sas.StartsOn); Assert.AreEqual("2015-04-05", tableuribuilder.Sas.Version); Assert.AreEqual("", tableuribuilder.Query); Assert.That(newUri.ToString(), Is.EqualTo(originalUri.Uri.ToString())); } [Test] public void TableUriBuilder_IPStyleUrl_AccountTest() { // Arrange var uriString = "https://127.0.0.1/account?comp=list"; var originalUri = new UriBuilder(uriString); // Act var tableuribuilder = new TableUriBuilder(originalUri.Uri); Uri newUri = tableuribuilder.ToUri(); // Assert Assert.AreEqual("https", tableuribuilder.Scheme); Assert.AreEqual("127.0.0.1", tableuribuilder.Host); Assert.AreEqual(443, tableuribuilder.Port); Assert.AreEqual("account", tableuribuilder.AccountName); Assert.IsNull(tableuribuilder.Sas); Assert.AreEqual("comp=list", tableuribuilder.Query); Assert.AreEqual(originalUri, newUri); } [Test] public void TableUriBuilder_IPStyleUrl_TableTest() { // Arrange var uriString = "https://127.0.0.1/account/table"; var originalUri = new UriBuilder(uriString); // Act var tableuribuilder = new TableUriBuilder(originalUri.Uri); Uri newUri = tableuribuilder.ToUri(); // Assert Assert.AreEqual("https", tableuribuilder.Scheme); Assert.AreEqual("127.0.0.1", tableuribuilder.Host); Assert.AreEqual(443, tableuribuilder.Port); Assert.AreEqual("account", tableuribuilder.AccountName); Assert.IsNull(tableuribuilder.Sas); Assert.AreEqual("", tableuribuilder.Query); Assert.AreEqual(originalUri, newUri); } [Test] public void TableUriBuilder_IPStyleUrl_PortTest() { // Arrange var uriString = "https://127.0.0.1:8080/account/table"; var originalUri = new UriBuilder(uriString); // Act var tableuribuilder = new TableUriBuilder(originalUri.Uri); Uri newUri = tableuribuilder.ToUri(); // Assert Assert.AreEqual("https", tableuribuilder.Scheme); Assert.AreEqual("127.0.0.1", tableuribuilder.Host); Assert.AreEqual(8080, tableuribuilder.Port); Assert.AreEqual("account", tableuribuilder.AccountName); Assert.IsNull(tableuribuilder.Sas); Assert.AreEqual("", tableuribuilder.Query); Assert.AreEqual(originalUri, newUri); } [Test] public void TableUriBuilder_IPStyleUrl_AccountOnlyTest() { // Arrange var uriString = "https://127.0.0.1/account"; var originalUri = new UriBuilder(uriString); // Act var tableuribuilder = new TableUriBuilder(originalUri.Uri); Uri newUri = tableuribuilder.ToUri(); // Assert Assert.AreEqual("https", tableuribuilder.Scheme); Assert.AreEqual("127.0.0.1", tableuribuilder.Host); Assert.AreEqual(443, tableuribuilder.Port); Assert.AreEqual("account", tableuribuilder.AccountName); Assert.IsNull(tableuribuilder.Sas); Assert.AreEqual("", tableuribuilder.Query); Assert.AreEqual(originalUri, newUri); } [Test] public void TableUriBuilder_IPStyleUrl_SasTest() { // Arrange var uriString = "https://127.0.0.1/account/table?tn=table&sv=2015-04-05&spr=https&st=2015-04-29T22%3A18%3A26Z&se=2015-04-30T02%3A23%3A26Z&sip=168.1.5.60-168.1.5.70&sr=b&sp=rw&sig=Z%2FRHIX5Xcg0Mq2rqI3OlWTjEg2tYkboXr1P9ZUXDtkk%3D"; var originalUri = new UriBuilder(uriString); // Act var tableuribuilder = new TableUriBuilder(originalUri.Uri); Uri newUri = tableuribuilder.ToUri(); // Assert Assert.AreEqual("https", tableuribuilder.Scheme); Assert.AreEqual("127.0.0.1", tableuribuilder.Host); Assert.AreEqual(443, tableuribuilder.Port); Assert.AreEqual("account", tableuribuilder.AccountName); Assert.AreEqual(new DateTimeOffset(2015, 4, 30, 2, 23, 26, TimeSpan.Zero), tableuribuilder.Sas.ExpiresOn); Assert.AreEqual("", tableuribuilder.Sas.Identifier); Assert.AreEqual(TableSasIPRange.Parse("168.1.5.60-168.1.5.70"), tableuribuilder.Sas.IPRange); Assert.AreEqual("rw", tableuribuilder.Sas.Permissions); Assert.AreEqual(TableSasProtocol.Https, tableuribuilder.Sas.Protocol); Assert.AreEqual("b", tableuribuilder.Sas.Resource); Assert.IsNull(tableuribuilder.Sas.ResourceTypes); Assert.AreEqual("Z/RHIX5Xcg0Mq2rqI3OlWTjEg2tYkboXr1P9ZUXDtkk=", tableuribuilder.Sas.Signature); Assert.AreEqual(new DateTimeOffset(2015, 4, 29, 22, 18, 26, TimeSpan.Zero), tableuribuilder.Sas.StartsOn); Assert.AreEqual("2015-04-05", tableuribuilder.Sas.Version); Assert.AreEqual("", tableuribuilder.Query); Assert.AreEqual(originalUri, newUri); } [Test] [TestCase("2020-10-27", "2020-10-28")] [TestCase("2020-10-27T12:10Z", "2020-10-28T13:20Z")] [TestCase("2020-10-27T12:10:11Z", "2020-10-28T13:20:14Z")] [TestCase("2020-10-27T12:10:11.1234567Z", "2020-10-28T13:20:14.7654321Z")] public void TableBuilder_SasStartExpiryTimeFormats(string startTime, string expiryTime) { // Arrange Uri initialUri = new Uri($"https://account.table.core.windows.net/table?tn=tablename&sv=2020-04-08&st={WebUtility.UrlEncode(startTime)}&se={WebUtility.UrlEncode(expiryTime)}&sr=b&sp=racwd&sig=jQetX8odiJoZ7Yo0X8vWgh%2FMqRv9WE3GU%2Fr%2BLNMK3GU%3D"); TableUriBuilder tableuribuilder = new TableUriBuilder(initialUri); // Act Uri resultUri = tableuribuilder.ToUri(); // Assert Assert.That(resultUri.ToString(), Is.EqualTo(initialUri.ToString())); Assert.IsTrue(resultUri.PathAndQuery.Contains($"st={WebUtility.UrlEncode(startTime)}")); Assert.IsTrue(resultUri.PathAndQuery.Contains($"se={WebUtility.UrlEncode(expiryTime)}")); } [Test] public void TableUriBuilder_SasInvalidStartExpiryTimeFormat() { // Arrange string startTime = "2020-10-27T12Z"; string expiryTime = "2020-10-28T13Z"; Uri initialUri = new Uri($"https://account.table.core.windows.net/table?sv=2020-04-08&st={WebUtility.UrlEncode(startTime)}&se={WebUtility.UrlEncode(expiryTime)}&sr=b&sp=racwd&sig=jQetX8odiJoZ7Yo0X8vWgh%2FMqRv9WE3GU%2Fr%2BLNMK3GU%3D"); // Act try { new TableUriBuilder(initialUri); } catch (FormatException e) { Assert.IsTrue(e.Message.Contains("was not recognized as a valid DateTime.")); } } } }
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved. // Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information. using IdentityServer4.ResponseHandling; using IdentityServer4.Services; using IdentityServer4.Stores; using IdentityServer4.Validation; using Microsoft.Extensions.DependencyInjection.Extensions; using System; using System.Net.Http; using IdentityServer4; using IdentityServer4.Configuration; using Microsoft.Extensions.Logging; namespace Microsoft.Extensions.DependencyInjection { /// <summary> /// Builder extension methods for registering additional services /// </summary> public static class IdentityServerBuilderExtensionsAdditional { /// <summary> /// Adds the extension grant validator. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="builder">The builder.</param> /// <returns></returns> public static IIdentityServerBuilder AddExtensionGrantValidator<T>(this IIdentityServerBuilder builder) where T : class, IExtensionGrantValidator { builder.Services.AddTransient<IExtensionGrantValidator, T>(); return builder; } /// <summary> /// Adds a redirect URI validator. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="builder">The builder.</param> /// <returns></returns> public static IIdentityServerBuilder AddRedirectUriValidator<T>(this IIdentityServerBuilder builder) where T : class, IRedirectUriValidator { builder.Services.AddTransient<IRedirectUriValidator, T>(); return builder; } /// <summary> /// Adds a an "AppAuth" (OAuth 2.0 for Native Apps) compliant redirect URI validator (does strict validation but also allows http://127.0.0.1 with random port) /// </summary> /// <param name="builder">The builder.</param> /// <returns></returns> public static IIdentityServerBuilder AddAppAuthRedirectUriValidator(this IIdentityServerBuilder builder) { return builder.AddRedirectUriValidator<StrictRedirectUriValidatorAppAuth>(); } /// <summary> /// Adds the resource owner validator. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="builder">The builder.</param> /// <returns></returns> public static IIdentityServerBuilder AddResourceOwnerValidator<T>(this IIdentityServerBuilder builder) where T : class, IResourceOwnerPasswordValidator { builder.Services.AddTransient<IResourceOwnerPasswordValidator, T>(); return builder; } /// <summary> /// Adds the profile service. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="builder">The builder.</param> /// <returns></returns> public static IIdentityServerBuilder AddProfileService<T>(this IIdentityServerBuilder builder) where T : class, IProfileService { builder.Services.AddTransient<IProfileService, T>(); return builder; } /// <summary> /// Adds a resource validator. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="builder">The builder.</param> /// <returns></returns> public static IIdentityServerBuilder AddResourceValidator<T>(this IIdentityServerBuilder builder) where T : class, IResourceValidator { builder.Services.AddTransient<IResourceValidator, T>(); return builder; } /// <summary> /// Adds a scope parser. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="builder">The builder.</param> /// <returns></returns> public static IIdentityServerBuilder AddScopeParser<T>(this IIdentityServerBuilder builder) where T : class, IScopeParser { builder.Services.AddTransient<IScopeParser, T>(); return builder; } /// <summary> /// Adds a client store. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="builder">The builder.</param> /// <returns></returns> public static IIdentityServerBuilder AddClientStore<T>(this IIdentityServerBuilder builder) where T : class, IClientStore { builder.Services.TryAddTransient(typeof(T)); builder.Services.AddTransient<IClientStore, ValidatingClientStore<T>>(); return builder; } /// <summary> /// Adds a resource store. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="builder">The builder.</param> /// <returns></returns> public static IIdentityServerBuilder AddResourceStore<T>(this IIdentityServerBuilder builder) where T : class, IResourceStore { builder.Services.AddTransient<IResourceStore, T>(); return builder; } /// <summary> /// Adds a device flow store. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="builder">The builder.</param> public static IIdentityServerBuilder AddDeviceFlowStore<T>(this IIdentityServerBuilder builder) where T : class, IDeviceFlowStore { builder.Services.AddTransient<IDeviceFlowStore, T>(); return builder; } /// <summary> /// Adds a persisted grant store. /// </summary> /// <typeparam name="T">The type of the concrete grant store that is registered in DI.</typeparam> /// <param name="builder">The builder.</param> /// <returns>The builder.</returns> public static IIdentityServerBuilder AddPersistedGrantStore<T>(this IIdentityServerBuilder builder) where T : class, IPersistedGrantStore { builder.Services.AddTransient<IPersistedGrantStore, T>(); return builder; } /// <summary> /// Adds a CORS policy service. /// </summary> /// <typeparam name="T">The type of the concrete scope store class that is registered in DI.</typeparam> /// <param name="builder">The builder.</param> /// <returns></returns> public static IIdentityServerBuilder AddCorsPolicyService<T>(this IIdentityServerBuilder builder) where T : class, ICorsPolicyService { builder.Services.AddTransient<ICorsPolicyService, T>(); return builder; } /// <summary> /// Adds a CORS policy service cache. /// </summary> /// <typeparam name="T">The type of the concrete CORS policy service that is registered in DI.</typeparam> /// <param name="builder">The builder.</param> /// <returns></returns> public static IIdentityServerBuilder AddCorsPolicyCache<T>(this IIdentityServerBuilder builder) where T : class, ICorsPolicyService { builder.Services.TryAddTransient(typeof(T)); builder.Services.AddTransient<ICorsPolicyService, CachingCorsPolicyService<T>>(); return builder; } /// <summary> /// Adds the secret parser. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="builder">The builder.</param> /// <returns></returns> public static IIdentityServerBuilder AddSecretParser<T>(this IIdentityServerBuilder builder) where T : class, ISecretParser { builder.Services.AddTransient<ISecretParser, T>(); return builder; } /// <summary> /// Adds the secret validator. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="builder">The builder.</param> /// <returns></returns> public static IIdentityServerBuilder AddSecretValidator<T>(this IIdentityServerBuilder builder) where T : class, ISecretValidator { builder.Services.AddTransient<ISecretValidator, T>(); return builder; } /// <summary> /// Adds the client store cache. /// </summary> /// <typeparam name="T">The type of the concrete client store class that is registered in DI.</typeparam> /// <param name="builder">The builder.</param> /// <returns></returns> public static IIdentityServerBuilder AddClientStoreCache<T>(this IIdentityServerBuilder builder) where T : IClientStore { builder.Services.TryAddTransient(typeof(T)); builder.Services.AddTransient<ValidatingClientStore<T>>(); builder.Services.AddTransient<IClientStore, CachingClientStore<ValidatingClientStore<T>>>(); return builder; } /// <summary> /// Adds the client store cache. /// </summary> /// <typeparam name="T">The type of the concrete scope store class that is registered in DI.</typeparam> /// <param name="builder">The builder.</param> /// <returns></returns> public static IIdentityServerBuilder AddResourceStoreCache<T>(this IIdentityServerBuilder builder) where T : IResourceStore { builder.Services.TryAddTransient(typeof(T)); builder.Services.AddTransient<IResourceStore, CachingResourceStore<T>>(); return builder; } /// <summary> /// Adds the authorize interaction response generator. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="builder">The builder.</param> /// <returns></returns> public static IIdentityServerBuilder AddAuthorizeInteractionResponseGenerator<T>(this IIdentityServerBuilder builder) where T : class, IAuthorizeInteractionResponseGenerator { builder.Services.AddTransient<IAuthorizeInteractionResponseGenerator, T>(); return builder; } /// <summary> /// Adds the custom authorize request validator. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="builder">The builder.</param> /// <returns></returns> public static IIdentityServerBuilder AddCustomAuthorizeRequestValidator<T>(this IIdentityServerBuilder builder) where T : class, ICustomAuthorizeRequestValidator { builder.Services.AddTransient<ICustomAuthorizeRequestValidator, T>(); return builder; } /// <summary> /// Adds the custom authorize request validator. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="builder">The builder.</param> /// <returns></returns> public static IIdentityServerBuilder AddCustomTokenRequestValidator<T>(this IIdentityServerBuilder builder) where T : class, ICustomTokenRequestValidator { builder.Services.AddTransient<ICustomTokenRequestValidator, T>(); return builder; } /// <summary> /// Adds support for client authentication using JWT bearer assertions. /// </summary> /// <param name="builder">The builder.</param> /// <returns></returns> public static IIdentityServerBuilder AddJwtBearerClientAuthentication(this IIdentityServerBuilder builder) { builder.Services.TryAddTransient<IReplayCache, DefaultReplayCache>(); builder.AddSecretParser<JwtBearerClientAssertionSecretParser>(); builder.AddSecretValidator<PrivateKeyJwtSecretValidator>(); return builder; } /// <summary> /// Adds a client configuration validator. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="builder">The builder.</param> /// <returns></returns> public static IIdentityServerBuilder AddClientConfigurationValidator<T>(this IIdentityServerBuilder builder) where T : class, IClientConfigurationValidator { builder.Services.AddTransient<IClientConfigurationValidator, T>(); return builder; } /// <summary> /// Adds the X509 secret validators for mutual TLS. /// </summary> /// <param name="builder">The builder.</param> /// <returns></returns> public static IIdentityServerBuilder AddMutualTlsSecretValidators(this IIdentityServerBuilder builder) { builder.AddSecretParser<MutualTlsSecretParser>(); builder.AddSecretValidator<X509ThumbprintSecretValidator>(); builder.AddSecretValidator<X509NameSecretValidator>(); return builder; } /// <summary> /// Adds a custom back-channel logout service. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="builder">The builder.</param> /// <returns></returns> public static IIdentityServerBuilder AddBackChannelLogoutService<T>(this IIdentityServerBuilder builder) where T : class, IBackChannelLogoutService { builder.Services.AddTransient<IBackChannelLogoutService, T>(); return builder; } // todo: check with later previews of ASP.NET Core if this is still required /// <summary> /// Adds configuration for the HttpClient used for back-channel logout notifications. /// </summary> /// <param name="builder">The builder.</param> /// <param name="configureClient">The configruation callback.</param> /// <returns></returns> public static IHttpClientBuilder AddBackChannelLogoutHttpClient(this IIdentityServerBuilder builder, Action<HttpClient> configureClient = null) { const string name = IdentityServerConstants.HttpClients.BackChannelLogoutHttpClient; IHttpClientBuilder httpBuilder; if (configureClient != null) { httpBuilder = builder.Services.AddHttpClient(name, configureClient); } else { httpBuilder = builder.Services.AddHttpClient(name) .ConfigureHttpClient(client => { client.Timeout = TimeSpan.FromSeconds(IdentityServerConstants.HttpClients.DefaultTimeoutSeconds); }); } builder.Services.AddTransient<IBackChannelLogoutHttpClient>(s => { var httpClientFactory = s.GetRequiredService<IHttpClientFactory>(); var httpClient = httpClientFactory.CreateClient(name); var loggerFactory = s.GetRequiredService<ILoggerFactory>(); return new DefaultBackChannelLogoutHttpClient(httpClient, loggerFactory); }); return httpBuilder; } // todo: check with later previews of ASP.NET Core if this is still required /// <summary> /// Adds configuration for the HttpClient used for JWT request_uri requests. /// </summary> /// <param name="builder">The builder.</param> /// <param name="configureClient">The configruation callback.</param> /// <returns></returns> public static IHttpClientBuilder AddJwtRequestUriHttpClient(this IIdentityServerBuilder builder, Action<HttpClient> configureClient = null) { const string name = IdentityServerConstants.HttpClients.JwtRequestUriHttpClient; IHttpClientBuilder httpBuilder; if (configureClient != null) { httpBuilder = builder.Services.AddHttpClient(name, configureClient); } else { httpBuilder = builder.Services.AddHttpClient(name) .ConfigureHttpClient(client => { client.Timeout = TimeSpan.FromSeconds(IdentityServerConstants.HttpClients.DefaultTimeoutSeconds); }); } builder.Services.AddTransient<IJwtRequestUriHttpClient, DefaultJwtRequestUriHttpClient>(s => { var httpClientFactory = s.GetRequiredService<IHttpClientFactory>(); var httpClient = httpClientFactory.CreateClient(name); var loggerFactory = s.GetRequiredService<ILoggerFactory>(); var options = s.GetRequiredService<IdentityServerOptions>(); return new DefaultJwtRequestUriHttpClient(httpClient, options, loggerFactory); }); return httpBuilder; } /// <summary> /// Adds a custom authorization request parameter store. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="builder">The builder.</param> /// <returns></returns> public static IIdentityServerBuilder AddAuthorizationParametersMessageStore<T>(this IIdentityServerBuilder builder) where T : class, IAuthorizationParametersMessageStore { builder.Services.AddTransient<IAuthorizationParametersMessageStore, T>(); return builder; } /// <summary> /// Adds a custom user session. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="builder">The builder.</param> /// <returns></returns> public static IIdentityServerBuilder AddUserSession<T>(this IIdentityServerBuilder builder) where T : class, IUserSession { // This is added as scoped due to the note regarding the AuthenticateAsync // method in the IdentityServer4.Services.DefaultUserSession implementation. builder.Services.AddScoped<IUserSession, T>(); return builder; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Security.Cryptography.X509Certificates; using Glass.Mapper.Configuration; using Glass.Mapper.Diagnostics; using Glass.Mapper.IoC; using Glass.Mapper.Pipelines.ObjectConstruction; using Glass.Mapper.Pipelines.ObjectSaving; using Glass.Mapper.Pipelines.ConfigurationResolver; using Glass.Mapper.Profilers; namespace Glass.Mapper { /// <summary> /// AbstractService /// </summary> public abstract class AbstractService : IAbstractService { private IPerformanceProfiler _profiler; /// <summary> /// Gets or sets the profiler. /// </summary> /// <value> /// The profiler. /// </value> public IPerformanceProfiler Profiler { get { return _profiler; } set { _configurationResolver.Profiler = value; _objectConstruction.Profiler = value; _objectSaving.Profiler = value; _profiler = value; } } /// <summary> /// Gets the glass context. /// </summary> /// <value> /// The glass context. /// </value> public Context GlassContext { get; private set; } private ConfigurationResolver _configurationResolver; private ObjectConstruction _objectConstruction; private ObjectSaving _objectSaving; private bool _disposed; /// <summary> /// Initializes a new instance of the <see cref="AbstractService"/> class. /// </summary> protected AbstractService() : this(Context.Default) { } /// <summary> /// Initializes a new instance of the <see cref="AbstractService"/> class. /// </summary> /// <param name="glassContext">The glass context.</param> /// <exception cref="System.NullReferenceException">Context is null</exception> protected AbstractService(Context glassContext) { GlassContext = glassContext; if (GlassContext == null) throw new NullReferenceException("Context is null"); var objectConstructionTasks = glassContext.DependencyResolver.ObjectConstructionFactory.GetItems(); _objectConstruction = new ObjectConstruction(objectConstructionTasks); var configurationResolverTasks = glassContext.DependencyResolver.ConfigurationResolverFactory.GetItems(); _configurationResolver = new ConfigurationResolver(configurationResolverTasks); var objectSavingTasks = glassContext.DependencyResolver.ObjectSavingFactory.GetItems(); _objectSaving = new ObjectSaving(objectSavingTasks); Profiler = NullProfiler.Instance; Initiate(glassContext.DependencyResolver); } public virtual void Initiate(IDependencyResolver resolver) { CacheEnabled = true; } /// <summary> /// Instantiates the object. /// </summary> /// <param name="abstractTypeCreationContext">The abstract type creation context.</param> /// <returns></returns> /// <exception cref="System.NullReferenceException">Configuration Resolver pipeline did not return a type. Has the type been loaded by Glass.Mapper. Type: {0}.Formatted(abstractTypeCreationContext.RequestedType.FullName)</exception> public object InstantiateObject(AbstractTypeCreationContext abstractTypeCreationContext) { using (new Monitor()) { string profilerKey = "Creating {0}".Formatted(abstractTypeCreationContext.Options.Type.FullName); try { Profiler.IndentIncrease(); Profiler.Start(profilerKey); if (this._disposed) { throw new MapperException("Service has been disposed, cannot create object"); } //run the pipeline to get the configuration to load var configurationArgs = RunConfigurationPipeline(abstractTypeCreationContext); if (configurationArgs.Result == null) throw new NullReferenceException( "Configuration Resolver pipeline did not return a type. Has the type been loaded by Glass.Mapper. Type: {0}" .Formatted(abstractTypeCreationContext.Options.Type)); //Run the object construction var objectArgs = new ObjectConstructionArgs( GlassContext, abstractTypeCreationContext, configurationArgs.Result, this ); objectArgs.Parameters = configurationArgs.Parameters; _objectConstruction.Run(objectArgs); ModelCounter.Instance.ModelsRequested++; return objectArgs.Result; } finally { //we clear the lazy loader disable to avoid problems with //stack overflows on the next request Profiler.End(profilerKey); Profiler.IndentDecrease(); } } } public ConfigurationResolverArgs RunConfigurationPipeline(AbstractTypeCreationContext abstractTypeCreationContext) { var configurationArgs = new ConfigurationResolverArgs(GlassContext, abstractTypeCreationContext, this); configurationArgs.Parameters = abstractTypeCreationContext.Parameters; _configurationResolver.Run(configurationArgs); return configurationArgs; } /// <summary> /// Saves the object. /// </summary> /// <param name="abstractTypeSavingContext">The abstract type saving context.</param> public virtual void SaveObject(AbstractTypeSavingContext abstractTypeSavingContext) { //Run the object construction var savingArgs = new ObjectSavingArgs(GlassContext, abstractTypeSavingContext.Object, abstractTypeSavingContext, this); _objectSaving.Run(savingArgs); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (disposing) { this._disposed = true; if (_configurationResolver != null) { _configurationResolver.Dispose(); } if (_objectConstruction != null) { _objectConstruction.Dispose(); } if (_objectSaving != null) { _objectSaving.Dispose(); } _configurationResolver = null; _objectConstruction = null; _objectSaving = null; } } public bool CacheEnabled { get; set; } } /// <summary> /// IAbstractService /// </summary> public interface IAbstractService : IDisposable { /// <summary> /// Gets the glass context. /// </summary> /// <value> /// The glass context. /// </value> Context GlassContext { get; } /// <summary> /// Instantiates the object. /// </summary> /// <param name="abstractTypeCreationContext">The abstract type creation context.</param> /// <returns></returns> object InstantiateObject(AbstractTypeCreationContext abstractTypeCreationContext); ConfigurationResolverArgs RunConfigurationPipeline(AbstractTypeCreationContext abstractTypeCreationContext); /// <summary> /// Indicates if the cache should be enable when using this service. /// </summary> bool CacheEnabled { 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.Collections; using System.Security.Authentication; namespace System.Net.Security { // Implements SSL session caching mechanism based on a static table of SSL credentials. internal static class SslSessionsCache { private const int CheckExpiredModulo = 32; private static Hashtable s_CachedCreds = new Hashtable(32); // // Uses certificate thumb-print comparison. // private struct SslCredKey { private byte[] _CertThumbPrint; private int _AllowedProtocols; private bool _isServerMode; private EncryptionPolicy _EncryptionPolicy; private readonly int _HashCode; // // SECURITY: X509Certificate.GetCertHash() is virtual hence before going here, // the caller of this ctor has to ensure that a user cert object was inspected and // optionally cloned. // internal SslCredKey(byte[] thumbPrint, int allowedProtocols, bool serverMode, EncryptionPolicy encryptionPolicy) { _CertThumbPrint = thumbPrint == null ? Array.Empty<byte>() : thumbPrint; _HashCode = 0; if (thumbPrint != null) { _HashCode ^= _CertThumbPrint[0]; if (1 < _CertThumbPrint.Length) { _HashCode ^= (_CertThumbPrint[1] << 8); } if (2 < _CertThumbPrint.Length) { _HashCode ^= (_CertThumbPrint[2] << 16); } if (3 < _CertThumbPrint.Length) { _HashCode ^= (_CertThumbPrint[3] << 24); } } _HashCode ^= allowedProtocols; _HashCode ^= (int)encryptionPolicy; _HashCode ^= serverMode ? 5 : 7; //TODO (Issue #3362) used a prime number here as it's a XOR. Figure out appropriate value. _AllowedProtocols = allowedProtocols; _EncryptionPolicy = encryptionPolicy; _isServerMode = serverMode; } public override int GetHashCode() { return _HashCode; } public static bool operator ==(SslCredKey sslCredKey1, SslCredKey sslCredKey2) { return sslCredKey1.Equals(sslCredKey2); } public static bool operator !=(SslCredKey sslCredKey1, SslCredKey sslCredKey2) { return !sslCredKey1.Equals(sslCredKey2); } public override bool Equals(Object y) { SslCredKey other = (SslCredKey)y; if (_CertThumbPrint.Length != other._CertThumbPrint.Length) { return false; } if (_HashCode != other._HashCode) { return false; } if (_EncryptionPolicy != other._EncryptionPolicy) { return false; } if (_AllowedProtocols != other._AllowedProtocols) { return false; } if (_isServerMode != other._isServerMode) { return false; } for (int i = 0; i < _CertThumbPrint.Length; ++i) { if (_CertThumbPrint[i] != other._CertThumbPrint[i]) { return false; } } return true; } } // // Returns null or previously cached cred handle. // // ATTN: The returned handle can be invalid, the callers of InitializeSecurityContext and AcceptSecurityContext // must be prepared to execute a back-out code if the call fails. // internal static SafeFreeCredentials TryCachedCredential(byte[] thumbPrint, SslProtocols sslProtocols, bool isServer, EncryptionPolicy encryptionPolicy) { if (s_CachedCreds.Count == 0) { GlobalLog.Print("TryCachedCredential() Not found, Current Cache Count = " + s_CachedCreds.Count); return null; } object key = new SslCredKey(thumbPrint, (int)sslProtocols, isServer, encryptionPolicy); SafeCredentialReference cached = s_CachedCreds[key] as SafeCredentialReference; if (cached == null || cached.IsClosed || cached.Target.IsInvalid) { GlobalLog.Print("TryCachedCredential() Not found or invalid, Current Cache Count = " + s_CachedCreds.Count); return null; } GlobalLog.Print("TryCachedCredential() Found a cached Handle = " + cached.Target.ToString()); return cached.Target; } // // The app is calling this method after starting an SSL handshake. // // ATTN: The thumbPrint must be from inspected and possibly cloned user Cert object or we get a security hole in SslCredKey ctor. // internal static void CacheCredential(SafeFreeCredentials creds, byte[] thumbPrint, SslProtocols sslProtocols, bool isServer, EncryptionPolicy encryptionPolicy) { GlobalLog.Assert(creds != null, "CacheCredential|creds == null"); if (creds.IsInvalid) { GlobalLog.Print("CacheCredential() Refused to cache an Invalid Handle = " + creds.ToString() + ", Current Cache Count = " + s_CachedCreds.Count); return; } object key = new SslCredKey(thumbPrint, (int)sslProtocols, isServer, encryptionPolicy); SafeCredentialReference cached = s_CachedCreds[key] as SafeCredentialReference; if (cached == null || cached.IsClosed || cached.Target.IsInvalid) { lock (s_CachedCreds) { cached = s_CachedCreds[key] as SafeCredentialReference; if (cached == null || cached.IsClosed) { cached = SafeCredentialReference.CreateReference(creds); if (cached == null) { // Means the handle got closed in between, return it back and let caller deal with the issue. return; } s_CachedCreds[key] = cached; GlobalLog.Print("CacheCredential() Caching New Handle = " + creds.ToString() + ", Current Cache Count = " + s_CachedCreds.Count); // // A simplest way of preventing infinite cache grows. // // Security relief (DoS): // A number of active creds is never greater than a number of _outstanding_ // security sessions, i.e. SSL connections. // So we will try to shrink cache to the number of active creds once in a while. // // We won't shrink cache in the case when NO new handles are coming to it. // if ((s_CachedCreds.Count % CheckExpiredModulo) == 0) { DictionaryEntry[] toRemoveAttempt = new DictionaryEntry[s_CachedCreds.Count]; s_CachedCreds.CopyTo(toRemoveAttempt, 0); for (int i = 0; i < toRemoveAttempt.Length; ++i) { cached = toRemoveAttempt[i].Value as SafeCredentialReference; if (cached != null) { creds = cached.Target; cached.Dispose(); if (!creds.IsClosed && !creds.IsInvalid && (cached = SafeCredentialReference.CreateReference(creds)) != null) { s_CachedCreds[toRemoveAttempt[i].Key] = cached; } else { s_CachedCreds.Remove(toRemoveAttempt[i].Key); } } } GlobalLog.Print("Scavenged cache, New Cache Count = " + s_CachedCreds.Count); } } else { GlobalLog.Print("CacheCredential() (locked retry) Found already cached Handle = " + cached.Target.ToString()); } } } else { GlobalLog.Print("CacheCredential() Ignoring incoming handle = " + creds.ToString() + " since found already cached Handle = " + cached.Target.ToString()); } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // ReSharper disable ConvertToAutoProperty namespace DotNetty.Buffers { using System; using System.Diagnostics.Contracts; using System.IO; using System.Threading; using System.Threading.Tasks; using DotNetty.Common.Internal; public class UnpooledHeapByteBuffer : AbstractReferenceCountedByteBuffer { readonly IByteBufferAllocator allocator; byte[] array; protected internal UnpooledHeapByteBuffer(IByteBufferAllocator alloc, int initialCapacity, int maxCapacity) : base(maxCapacity) { Contract.Requires(alloc != null); Contract.Requires(initialCapacity <= maxCapacity); this.allocator = alloc; this.SetArray(this.NewArray(initialCapacity)); this.SetIndex0(0, 0); } protected internal UnpooledHeapByteBuffer(IByteBufferAllocator alloc, byte[] initialArray, int maxCapacity) : base(maxCapacity) { Contract.Requires(alloc != null); Contract.Requires(initialArray != null); if (initialArray.Length > maxCapacity) { throw new ArgumentException($"initialCapacity({initialArray.Length}) > maxCapacity({maxCapacity})"); } this.allocator = alloc; this.SetArray(initialArray); this.SetIndex0(0, initialArray.Length); } protected virtual byte[] AllocateArray(int initialCapacity) => this.NewArray(initialCapacity); protected byte[] NewArray(int initialCapacity) => new byte[initialCapacity]; protected virtual void FreeArray(byte[] bytes) { // NOOP } protected void SetArray(byte[] initialArray) => this.array = initialArray; public override IByteBufferAllocator Allocator => this.allocator; public override bool IsDirect => false; public override int Capacity { get { this.EnsureAccessible(); return this.array.Length; } } public override IByteBuffer AdjustCapacity(int newCapacity) { this.CheckNewCapacity(newCapacity); int oldCapacity = this.array.Length; byte[] oldArray = this.array; if (newCapacity > oldCapacity) { byte[] newArray = this.AllocateArray(newCapacity); PlatformDependent.CopyMemory(this.array, 0, newArray, 0, oldCapacity); this.SetArray(newArray); this.FreeArray(oldArray); } else if (newCapacity < oldCapacity) { byte[] newArray = this.AllocateArray(newCapacity); int readerIndex = this.ReaderIndex; if (readerIndex < newCapacity) { int writerIndex = this.WriterIndex; if (writerIndex > newCapacity) { this.SetWriterIndex0(writerIndex = newCapacity); } PlatformDependent.CopyMemory(this.array, readerIndex, newArray, 0, writerIndex - readerIndex); } else { this.SetIndex(newCapacity, newCapacity); } this.SetArray(newArray); this.FreeArray(oldArray); } return this; } public override bool HasArray => true; public override byte[] Array { get { this.EnsureAccessible(); return this.array; } } public override int ArrayOffset => 0; public override bool HasMemoryAddress => true; public override ref byte GetPinnableMemoryAddress() { this.EnsureAccessible(); return ref this.array[0]; } public override IntPtr AddressOfPinnedMemory() => IntPtr.Zero; public override IByteBuffer GetBytes(int index, IByteBuffer dst, int dstIndex, int length) { this.CheckDstIndex(index, length, dstIndex, dst.Capacity); if (dst.HasArray) { this.GetBytes(index, dst.Array, dst.ArrayOffset + dstIndex, length); } else { dst.SetBytes(dstIndex, this.array, index, length); } return this; } public override IByteBuffer GetBytes(int index, byte[] dst, int dstIndex, int length) { this.CheckDstIndex(index, length, dstIndex, dst.Length); PlatformDependent.CopyMemory(this.array, index, dst, dstIndex, length); return this; } public override IByteBuffer GetBytes(int index, Stream destination, int length) { this.EnsureAccessible(); destination.Write(this.Array, this.ArrayOffset + index, length); return this; } public override IByteBuffer SetBytes(int index, IByteBuffer src, int srcIndex, int length) { this.CheckSrcIndex(index, length, srcIndex, src.Capacity); if (src.HasArray) { this.SetBytes(index, src.Array, src.ArrayOffset + srcIndex, length); } else { src.GetBytes(srcIndex, this.array, index, length); } return this; } public override IByteBuffer SetBytes(int index, byte[] src, int srcIndex, int length) { this.CheckSrcIndex(index, length, srcIndex, src.Length); PlatformDependent.CopyMemory(src, srcIndex, this.array, index, length); return this; } public override async Task<int> SetBytesAsync(int index, Stream src, int length, CancellationToken cancellationToken) { this.EnsureAccessible(); int readTotal = 0; int read; int offset = this.ArrayOffset + index; do { read = await src.ReadAsync(this.Array, offset + readTotal, length - readTotal, cancellationToken); readTotal += read; } while (read > 0 && readTotal < length); return readTotal; } public override int IoBufferCount => 1; public override ArraySegment<byte> GetIoBuffer(int index, int length) { this.EnsureAccessible(); return new ArraySegment<byte>(this.array, index, length); } public override ArraySegment<byte>[] GetIoBuffers(int index, int length) => new[] { this.GetIoBuffer(index, length) }; public override byte GetByte(int index) { this.EnsureAccessible(); return this._GetByte(index); } protected internal override byte _GetByte(int index) => HeapByteBufferUtil.GetByte(this.array, index); public override IByteBuffer SetZero(int index, int length) { this.CheckIndex(index, length); PlatformDependent.Clear(this.array, index, length); return this; } public override short GetShort(int index) { this.EnsureAccessible(); return this._GetShort(index); } protected internal override short _GetShort(int index) => HeapByteBufferUtil.GetShort(this.array, index); public override short GetShortLE(int index) { this.EnsureAccessible(); return this._GetShortLE(index); } protected internal override short _GetShortLE(int index) => HeapByteBufferUtil.GetShortLE(this.array, index); public override int GetUnsignedMedium(int index) { this.EnsureAccessible(); return this._GetUnsignedMedium(index); } protected internal override int _GetUnsignedMedium(int index) => HeapByteBufferUtil.GetUnsignedMedium(this.array, index); public override int GetUnsignedMediumLE(int index) { this.EnsureAccessible(); return this._GetUnsignedMediumLE(index); } protected internal override int _GetUnsignedMediumLE(int index) => HeapByteBufferUtil.GetUnsignedMediumLE(this.array, index); public override int GetInt(int index) { this.EnsureAccessible(); return this._GetInt(index); } protected internal override int _GetInt(int index) => HeapByteBufferUtil.GetInt(this.array, index); public override int GetIntLE(int index) { this.EnsureAccessible(); return this._GetIntLE(index); } protected internal override int _GetIntLE(int index) => HeapByteBufferUtil.GetIntLE(this.array, index); public override long GetLong(int index) { this.EnsureAccessible(); return this._GetLong(index); } protected internal override long _GetLong(int index) => HeapByteBufferUtil.GetLong(this.array, index); public override long GetLongLE(int index) { this.EnsureAccessible(); return this._GetLongLE(index); } protected internal override long _GetLongLE(int index) => HeapByteBufferUtil.GetLongLE(this.array, index); public override IByteBuffer SetByte(int index, int value) { this.EnsureAccessible(); this._SetByte(index, value); return this; } protected internal override void _SetByte(int index, int value) => HeapByteBufferUtil.SetByte(this.array, index, value); public override IByteBuffer SetShort(int index, int value) { this.EnsureAccessible(); this._SetShort(index, value); return this; } protected internal override void _SetShort(int index, int value) => HeapByteBufferUtil.SetShort(this.array, index, value); public override IByteBuffer SetShortLE(int index, int value) { this.EnsureAccessible(); this._SetShortLE(index, value); return this; } protected internal override void _SetShortLE(int index, int value) => HeapByteBufferUtil.SetShortLE(this.array, index, value); public override IByteBuffer SetMedium(int index, int value) { this.EnsureAccessible(); this._SetMedium(index, value); return this; } protected internal override void _SetMedium(int index, int value) => HeapByteBufferUtil.SetMedium(this.array, index, value); public override IByteBuffer SetMediumLE(int index, int value) { this.EnsureAccessible(); this._SetMediumLE(index, value); return this; } protected internal override void _SetMediumLE(int index, int value) => HeapByteBufferUtil.SetMediumLE(this.array, index, value); public override IByteBuffer SetInt(int index, int value) { this.EnsureAccessible(); this._SetInt(index, value); return this; } protected internal override void _SetInt(int index, int value) => HeapByteBufferUtil.SetInt(this.array, index, value); public override IByteBuffer SetIntLE(int index, int value) { this.EnsureAccessible(); this._SetIntLE(index, value); return this; } protected internal override void _SetIntLE(int index, int value) => HeapByteBufferUtil.SetIntLE(this.array, index, value); public override IByteBuffer SetLong(int index, long value) { this.EnsureAccessible(); this._SetLong(index, value); return this; } protected internal override void _SetLong(int index, long value) => HeapByteBufferUtil.SetLong(this.array, index, value); public override IByteBuffer SetLongLE(int index, long value) { this.EnsureAccessible(); this._SetLongLE(index, value); return this; } protected internal override void _SetLongLE(int index, long value) => HeapByteBufferUtil.SetLongLE(this.array, index, value); public override IByteBuffer Copy(int index, int length) { this.CheckIndex(index, length); var copiedArray = new byte[length]; PlatformDependent.CopyMemory(this.array, index, copiedArray, 0, length); return new UnpooledHeapByteBuffer(this.Allocator, copiedArray, this.MaxCapacity); } protected internal override void Deallocate() { this.FreeArray(this.array); this.array = null; } public override IByteBuffer Unwrap() => null; } }
#region /* Copyright (c) 2002-2012, Bas Geertsema, Xih Solutions (http://www.xihsolutions.net), Thiago.Sayao, Pang Wu, Ethem Evlice, Andy Phan, Chang Liu. All rights reserved. http://code.google.com/p/msnp-sharp/ 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 names of Bas Geertsema or Xih Solutions nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #endregion using System; using System.Text; using System.Threading; using System.Collections; using System.Diagnostics; namespace MSNPSharp { using MSNPSharp.Core; public class NSMessageEventArgs : EventArgs { private NSMessage nsMessage; public NSMessageEventArgs(NSMessage nsMessage) { this.nsMessage = nsMessage; } public NSMessage NSMessage { get { return nsMessage; } } }; public class NSMessageProcessor : IMessageProcessor { #region Events public event EventHandler<EventArgs> ConnectionEstablished; protected virtual void OnConnectionEstablished(object sender, EventArgs e) { if (ConnectionEstablished != null) ConnectionEstablished(sender, e); } public event EventHandler<EventArgs> ConnectionClosed; protected virtual void OnConnectionClosed(object sender, EventArgs e) { if (ConnectionClosed != null) ConnectionClosed(sender, e); } public event EventHandler<ExceptionEventArgs> ConnectingException; protected virtual void OnConnectingException(object sender, ExceptionEventArgs e) { if (ConnectingException != null) ConnectingException(sender, e); } public event EventHandler<ExceptionEventArgs> ConnectionException; protected virtual void OnConnectionException(object sender, ExceptionEventArgs e) { if (ConnectionException != null) ConnectionException(sender, e); } public event EventHandler<NSMessageEventArgs> NSMessageReceived; protected virtual void OnNSMessageReceived(object sender, NSMessageEventArgs e) { if (NSMessageReceived != null) NSMessageReceived(sender, e); } public event EventHandler<ObjectEventArgs> SendCompleted; protected virtual void OnSendCompleted(object sender, ObjectEventArgs e) { if (SendCompleted != null) SendCompleted(sender, e); } public event EventHandler<ExceptionEventArgs> HandlerException; protected virtual void OnHandlerException(object sender, ExceptionEventArgs e) { if (HandlerException != null) HandlerException(sender, e); } #endregion private int transactionID = 0; private SocketMessageProcessor processor; protected internal NSMessageProcessor(ConnectivitySettings connectivitySettings) { if (connectivitySettings.HttpPoll) { Processor = new HttpSocketMessageProcessor(connectivitySettings, new NSMessagePool()); } else { Processor = new TcpSocketMessageProcessor(connectivitySettings, new NSMessagePool()); } } public int TransactionID { get { return transactionID; } } public bool Connected { get { return (processor.Connected); } } public SocketMessageProcessor Processor { get { return processor; } set { if (processor != null) { processor.ConnectionEstablished -= OnConnectionEstablished; processor.ConnectionClosed -= OnConnectionClosed; processor.ConnectingException -= OnConnectingException; processor.ConnectionException -= OnConnectionException; processor.SendCompleted -= OnSendCompleted; processor.MessageReceived -= OnMessageReceived; } processor = value; if (processor != null) { processor.ConnectionEstablished += OnConnectionEstablished; processor.ConnectionClosed += OnConnectionClosed; processor.ConnectingException += OnConnectingException; processor.ConnectionException += OnConnectionException; processor.SendCompleted += OnSendCompleted; processor.MessageReceived += OnMessageReceived; } } } public ConnectivitySettings ConnectivitySettings { get { return Processor.ConnectivitySettings; } set { Processor.ConnectivitySettings = value; } } /// <summary> /// Reset the transactionID to zero. /// </summary> internal void ResetTransactionID() { Interlocked.Exchange(ref transactionID, 0); } protected internal int IncreaseTransactionID() { return Interlocked.Increment(ref transactionID); } protected void OnMessageReceived(object sender, ByteEventArgs e) { Trace.WriteLineIf(Settings.TraceSwitch.TraceVerbose, "Parsing incoming NS command...", GetType().Name); try { NSMessage nsMessage = new NSMessage(); nsMessage.ParseBytes(e.Bytes); OnNSMessageReceived(this, new NSMessageEventArgs(nsMessage)); } catch (Exception exc) { OnHandlerException(this, new ExceptionEventArgs(new MSNPSharpException( "An exception occured while handling a nameserver message. See inner exception for more details.", exc))); } } public void SendMessage(NetworkMessage message) { SendMessage(message, IncreaseTransactionID()); } public virtual void SendMessage(NetworkMessage message, int transactionID) { NSMessage nsMessage = message as NSMessage; if (nsMessage == null) { Trace.WriteLineIf(Settings.TraceSwitch.TraceError, "Cannot use this Message Processor to send a " + message.GetType().ToString() + " message.", GetType().Name); return; } nsMessage.TransactionID = transactionID; nsMessage.PrepareMessage(); Trace.WriteLineIf(Settings.TraceSwitch.TraceVerbose, "Outgoing message:\r\n" + nsMessage.ToDebugString() + "\r\n", GetType().Name); // convert to bytes and send it over the socket Processor.Send(nsMessage.GetBytes(), transactionID); } public void Connect() { Processor.Connect(); } public void Disconnect() { if (Connected) SendMessage(new NSMessage("OUT", new string[] { })); // OUT disconnects // Processor.Disconnect(); } } };
using UnityEngine; using System.Collections; // Orb controller (position and fire) public class OrbController : MonoBehaviour { public Transform turret; public Transform muzzleFlash; public Transform fireTrail; public GameObject player; // How fast the turret can turn and aim towards the player public float aimSpeed = 50; public AudioClip fireSound; public AudioClip foldoutSound; public AudioClip foldinSound; // Variable to be animated public float flyLerp = 0; // Is the turret folded out? private bool unfolded = false; public bool IsUnfolded () { return unfolded; } // Position A and B and how to fly between them private Vector3 oldFlyTarget = Vector3.zero; private Vector3 flyTarget = Vector3.zero; private bool gotBehindYet = false; private LayerMask mask; private AudioSource gunAudioSource; private int hitsThisRound = 0; private Vector3 aimTarget { get { return player.transform.position + new Vector3(0, 1.4f, 0); } } // Use this for initialization void Start () { // Add orb's own layer to mask mask = 1 << gameObject.layer; // Add Igbore Raycast layer to mask mask |= 1 << LayerMask.NameToLayer("Ignore Raycast"); // Invert mask mask = ~mask; flyTarget = transform.position; oldFlyTarget = flyTarget; animation["FightSequence"].layer = -1; animation.Play("FightSequence"); //muzzleFlash.enabled = false; muzzleFlash.gameObject.SetActiveRecursively(false); gunAudioSource = audio; } void FixedUpdate () { if (Time.deltaTime == 0 || Time.timeScale == 0) return; // Variables for positional and rotational stabilization float prediction = 0.35f; float force = 300.0f; float torque = 100.0f; // Move orb target position from old position to new Vector3 position = oldFlyTarget * (1-flyLerp) + flyTarget * flyLerp; // Add slight up and down motion position += Mathf.Sin(Time.time * 2) * Vector3.up * 0.05f; // Add force to control position Vector3 forceVector = (position - (transform.position + rigidbody.velocity * prediction )); rigidbody.AddForce(forceVector * force); Debug.DrawLine(position, transform.position); // Calculate what the transform.up direction will be in a little while, // given the current angular velocity Vector3 predictedUp = Quaternion.AngleAxis( rigidbody.angularVelocity.magnitude * Mathf.Rad2Deg * prediction, rigidbody.angularVelocity.normalized ) * transform.up; // Apply torque to seek towards target up direction in a stable manner Vector3 bankedUp = (Vector3.up + forceVector * 0.3f).normalized; rigidbody.AddTorque(Vector3.Cross(predictedUp, bankedUp) * torque); Vector3 targetForwardDir = (aimTarget - turret.position); targetForwardDir.y = 0; targetForwardDir.Normalize(); // Calculate what the transform.forward direction will be in a little while, // given the current angular velocity Vector3 predictedForward = Quaternion.AngleAxis( rigidbody.angularVelocity.magnitude * Mathf.Rad2Deg * prediction, rigidbody.angularVelocity.normalized ) * transform.forward; // Apply torque to seek towards target forward direction in a stable manner rigidbody.AddTorque(Vector3.Cross(predictedForward, targetForwardDir) * torque); // Update aiming // Set orb turret transform while it is folded out and not controlled by animation if (unfolded && animation["Take 001"].enabled == false) { // Find the global direction towards the target and convert it into local space Vector3 aimDirInLocalSpace = transform.InverseTransformDirection(aimTarget - turret.position); // Find a rotation that points at that target Quaternion aimRot = Quaternion.LookRotation(aimDirInLocalSpace); // Smoothly rotate the turret towards the target rotation float newEulerX = TurnTowards(turret.transform.localEulerAngles.x, aimRot.eulerAngles.x, aimSpeed * Time.deltaTime); turret.transform.localEulerAngles = new Vector3(newEulerX, 0, 0); } } public bool TestPositionCloseToPlayer (float maxDist) { // Get random vector flyTarget = Quaternion.Euler(0, Random.Range(0f, 360f), 0) * new Vector3(0, Random.Range(1f, 5f), Random.Range(3f, maxDist)); // Set position to be the vector relative to the player position flyTarget += player.transform.position; // Ensure a minimum height above the ground RaycastHit hit; float minHeightAbove = 1.5f; if (Physics.Raycast(flyTarget+5*Vector3.up, -Vector3.up, out hit, 10)) { if (hit.point.y > flyTarget.y - minHeightAbove) flyTarget = hit.point + Vector3.up * minHeightAbove; } LayerMask mask = new LayerMask(); mask.value = 1; if (Physics.CheckCapsule(oldFlyTarget, flyTarget, 1.2f, mask)) return false; return true; } public IEnumerator FlyToRandomPosition () { oldFlyTarget = flyTarget; // Try up to 100 random positions close to player bool success = false; for (int i=0; i<100; i++) { // Make a position and test if there's a clear path towards it if (TestPositionCloseToPlayer(5 + 0.1f*i)) { // We have a clear path success = true; // If we can also shoot the player from the found position, // we don't need to test any more positions. if (CanShootTargetFromPosition(flyTarget)) break; } // yield a frame for every 10 tests if ((i % 10) == 0) yield return 0; } // If we can't find a clear path, just stay at the same place for now. // The player will probably move to a better location later if (!success) { Debug.LogWarning("Couldn't find clear path"); flyTarget = oldFlyTarget; } flyLerp = 0; } public void FoldoutTurret () { animation["Take 001"].normalizedTime = 0; animation["Take 001"].speed = 1; animation.Play("Take 001"); gunAudioSource.PlayOneShot(foldoutSound); unfolded = true; if (TargetIsInFront() && CanShootTarget()) { player.SendMessage("OnPanic"); gotBehindYet = false; hitsThisRound = 0; StartCoroutine(MonitorPlayer()); } } public IEnumerator FoldinTurret () { unfolded = false; // Smoothly set turret to neutral position before starting animation float eulerX = turret.transform.localEulerAngles.x; while (eulerX != 0) { if (Time.deltaTime > 0 && Time.timeScale > 0) { eulerX = TurnTowards(eulerX, 0, aimSpeed * Time.deltaTime); turret.transform.localEulerAngles = new Vector3(eulerX, 0, 0); } yield return 0; } animation["Take 001"].normalizedTime = 1; animation["Take 001"].speed = -1; animation.Play("Take 001"); gunAudioSource.PlayOneShot(foldinSound); if (hitsThisRound > 8) player.SendMessage("OnPain", SendMessageOptions.DontRequireReceiver); hitsThisRound = 0; } public bool TargetIsInFront () { Vector3 playerDir = player.transform.position-transform.position; playerDir.y = 0; playerDir.Normalize(); return (Vector3.Dot(transform.forward, playerDir) > 0.4f); } public bool TargetIsBehind () { Vector3 playerDir = player.transform.position-transform.position; playerDir.y = 0; playerDir.Normalize(); return (Vector3.Dot(transform.forward, playerDir) < 0.0f); } public bool CanShootTarget () { return CanShootTargetFromPosition(turret.position); } public bool CanShootTargetFromPosition (Vector3 fromPosition) { Vector3 target = player.transform.position + new Vector3(0, 1.4f, 0); Vector3 shootDir = (target - fromPosition).normalized; Ray ray = new Ray(fromPosition, shootDir); RaycastHit hit; if (Physics.Raycast(ray, out hit, 1000, mask)) { if (hit.transform.root.gameObject == player) return true; } return false; } public void Shoot () { StartCoroutine(ShowMuzzleFlash()); gunAudioSource.PlayOneShot(fireSound); Vector3 shootDir = turret.up; shootDir += Random.insideUnitSphere * 0.01f; Ray ray = new Ray(turret.position, shootDir); RaycastHit hit; if (Physics.Raycast(ray, out hit, 1000, mask)) { hit.transform.root.SendMessage("OnHit", new RayAndHit(ray, hit), SendMessageOptions.DontRequireReceiver); muzzleFlash.localRotation = Quaternion.Euler(0, 0, Random.Range(-360, 360)); muzzleFlash.forward = shootDir; fireTrail.localScale = new Vector3(0.2f, 0.2f, hit.distance*2.4f); // If player got shot, he obviously isn't in a safe spot anymore if (hit.transform.gameObject == player) { gotBehindYet = false; hitsThisRound++; StartCoroutine(MonitorPlayer()); } } } void OnHit (RayAndHit rayAndHit) { // Add a big force impact from the bullet hit rigidbody.AddForce(rayAndHit.ray.direction * 200, ForceMode.Impulse); // Sometimes, also AddForceAtPosition - this adds some rotation as well. // We don't want to allow this too often, otherwise the orb, when being hit constantly, // will aim so bad that it's too easy to win. if (Random.value < 0.2f) rigidbody.AddForceAtPosition(rayAndHit.ray.direction * 15, rayAndHit.hit.point, ForceMode.Impulse); } // Function to monitor if player is in a safe spot yet IEnumerator MonitorPlayer () { while (unfolded && !gotBehindYet) { if (TargetIsBehind() || !CanShootTarget()) { if (hitsThisRound > 8) player.SendMessage("OnPain", SendMessageOptions.DontRequireReceiver); else player.SendMessage("OnSafe", SendMessageOptions.DontRequireReceiver); gotBehindYet = true; hitsThisRound = 0; yield return 1; } yield return new WaitForSeconds(1.0f/6); } } // Make an angle go maxDegreesDelta closer to a target angle public static float TurnTowards (float current, float target, float maxDegreesDelta) { float angleDifference = Mathf.Repeat (target - current + 180, 360) - 180; float turnAngle = maxDegreesDelta * Mathf.Sign (angleDifference); if (Mathf.Abs (turnAngle) > Mathf.Abs (angleDifference)) { return target; } return current + turnAngle; } // Show muzzle flash for a brief moment IEnumerator ShowMuzzleFlash () { // Show muzzle flash when firing muzzleFlash.gameObject.SetActiveRecursively(true); yield return new WaitForSeconds(0.05f); muzzleFlash.gameObject.SetActiveRecursively(false); } }
// // 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.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using Hyak.Common; using Microsoft.Azure; using Microsoft.WindowsAzure.Management.Network; namespace Microsoft.WindowsAzure.Management.Network { /// <summary> /// The Network Management API includes operations for managing the Virtual /// IPs for your deployment. /// </summary> internal partial class VirtualIPOperations : IServiceOperations<NetworkManagementClient>, IVirtualIPOperations { /// <summary> /// Initializes a new instance of the VirtualIPOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal VirtualIPOperations(NetworkManagementClient client) { this._client = client; } private NetworkManagementClient _client; /// <summary> /// Gets a reference to the /// Microsoft.WindowsAzure.Management.Network.NetworkManagementClient. /// </summary> public NetworkManagementClient Client { get { return this._client; } } /// <summary> /// The Add Virtual IP operation adds a logical Virtual IP to the /// deployment. /// </summary> /// <param name='serviceName'> /// Required. The name of the hosted service that contains the given /// deployment. /// </param> /// <param name='deploymentName'> /// Required. The name of the deployment where the logical Virtual IP /// is to be added. /// </param> /// <param name='virtualIPName'> /// Required. The name of the logical Virtual IP to be added. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is inprogress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request, and also includes error /// information regarding the failure. /// </returns> public async Task<OperationStatusResponse> AddAsync(string serviceName, string deploymentName, string virtualIPName, CancellationToken cancellationToken) { NetworkManagementClient 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("serviceName", serviceName); tracingParameters.Add("deploymentName", deploymentName); tracingParameters.Add("virtualIPName", virtualIPName); TracingAdapter.Enter(invocationId, this, "AddAsync", tracingParameters); } cancellationToken.ThrowIfCancellationRequested(); OperationStatusResponse response = await client.VirtualIPs.BeginAddingAsync(serviceName, deploymentName, virtualIPName, cancellationToken).ConfigureAwait(false); if (response.Status == OperationStatus.Succeeded) { return response; } cancellationToken.ThrowIfCancellationRequested(); OperationStatusResponse result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false); int 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.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false); delayInSeconds = 30; if (client.LongRunningOperationRetryTimeout >= 0) { delayInSeconds = client.LongRunningOperationRetryTimeout; } } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } if (result.Status != OperationStatus.Succeeded) { if (result.Error != null) { CloudException ex = new CloudException(result.Error.Code + " : " + result.Error.Message); ex.Error = new CloudError(); ex.Error.Code = result.Error.Code; ex.Error.Message = result.Error.Message; if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } else { CloudException ex = new CloudException(""); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } } return result; } /// <summary> /// The Begin Adding Virtual IP operation adds a logical Virtual IP to /// the deployment. /// </summary> /// <param name='serviceName'> /// Required. The name of the hosted service that contains the given /// deployment. /// </param> /// <param name='deploymentName'> /// Required. The name of the deployment where the logical Virtual IP /// is to be added. /// </param> /// <param name='virtualIPName'> /// Required. The name of the logical Virtual IP to be added. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is inprogress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request, and also includes error /// information regarding the failure. /// </returns> public async Task<OperationStatusResponse> BeginAddingAsync(string serviceName, string deploymentName, string virtualIPName, CancellationToken cancellationToken) { // Validate if (serviceName == null) { throw new ArgumentNullException("serviceName"); } if (deploymentName == null) { throw new ArgumentNullException("deploymentName"); } if (virtualIPName == null) { throw new ArgumentNullException("virtualIPName"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("serviceName", serviceName); tracingParameters.Add("deploymentName", deploymentName); tracingParameters.Add("virtualIPName", virtualIPName); TracingAdapter.Enter(invocationId, this, "BeginAddingAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/services/hostedservices/"; url = url + Uri.EscapeDataString(serviceName); url = url + "/deployments/"; url = url + Uri.EscapeDataString(deploymentName); url = url + "/"; url = url + Uri.EscapeDataString(virtualIPName); 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.Post; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-version", "2015-04-01"); // 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.Accepted) { 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 OperationStatusResponse result = null; // Deserialize Response result = new OperationStatusResponse(); 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> /// The Begin Removing Virtual IP operation removes a logical Virtual /// IP from the deployment. /// </summary> /// <param name='serviceName'> /// Required. The name of the hosted service that contains the given /// deployment. /// </param> /// <param name='deploymentName'> /// Required. The name of the deployment whose logical Virtual IP is to /// be removed. /// </param> /// <param name='virtualIPName'> /// Required. The name of the logical Virtual IP to be added. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is inprogress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request, and also includes error /// information regarding the failure. /// </returns> public async Task<OperationStatusResponse> BeginRemovingAsync(string serviceName, string deploymentName, string virtualIPName, CancellationToken cancellationToken) { // Validate if (serviceName == null) { throw new ArgumentNullException("serviceName"); } if (deploymentName == null) { throw new ArgumentNullException("deploymentName"); } if (virtualIPName == null) { throw new ArgumentNullException("virtualIPName"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("serviceName", serviceName); tracingParameters.Add("deploymentName", deploymentName); tracingParameters.Add("virtualIPName", virtualIPName); TracingAdapter.Enter(invocationId, this, "BeginRemovingAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/services/hostedservices/"; url = url + Uri.EscapeDataString(serviceName); url = url + "/deployments/"; url = url + Uri.EscapeDataString(deploymentName); url = url + "/virtualIPs/"; url = url + Uri.EscapeDataString(virtualIPName); 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 httpRequest.Headers.Add("x-ms-version", "2015-04-01"); // 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.Accepted) { 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 OperationStatusResponse result = null; // Deserialize Response result = new OperationStatusResponse(); 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> /// The Remove Virtual IP operation removes a logical Virtual IP from /// the deployment. /// </summary> /// <param name='serviceName'> /// Required. The name of the hosted service that contains the given /// deployment. /// </param> /// <param name='deploymentName'> /// Required. The name of the deployment whose logical Virtual IP is to /// be removed. /// </param> /// <param name='virtualIPName'> /// Required. The name of the logical Virtual IP to be removed. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is inprogress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request, and also includes error /// information regarding the failure. /// </returns> public async Task<OperationStatusResponse> RemoveAsync(string serviceName, string deploymentName, string virtualIPName, CancellationToken cancellationToken) { NetworkManagementClient 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("serviceName", serviceName); tracingParameters.Add("deploymentName", deploymentName); tracingParameters.Add("virtualIPName", virtualIPName); TracingAdapter.Enter(invocationId, this, "RemoveAsync", tracingParameters); } cancellationToken.ThrowIfCancellationRequested(); OperationStatusResponse response = await client.VirtualIPs.BeginRemovingAsync(serviceName, deploymentName, virtualIPName, cancellationToken).ConfigureAwait(false); if (response.Status == OperationStatus.Succeeded) { return response; } cancellationToken.ThrowIfCancellationRequested(); OperationStatusResponse result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false); int 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.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false); delayInSeconds = 30; if (client.LongRunningOperationRetryTimeout >= 0) { delayInSeconds = client.LongRunningOperationRetryTimeout; } } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } if (result.Status != OperationStatus.Succeeded) { if (result.Error != null) { CloudException ex = new CloudException(result.Error.Code + " : " + result.Error.Message); ex.Error = new CloudError(); ex.Error.Code = result.Error.Code; ex.Error.Message = result.Error.Message; if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } else { CloudException ex = new CloudException(""); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } } return result; } } }
// Copyright (c) 2015, Outercurve Foundation. // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // - Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // - Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // - Neither the name of the Outercurve Foundation nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON // ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace WebsitePanel.Portal.ProviderControls { public partial class hMailServer43_EditAccount { /// <summary> /// secPersonalInfo control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::WebsitePanel.Portal.CollapsiblePanel secPersonalInfo; /// <summary> /// PersonalInfoPanel control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Panel PersonalInfoPanel; /// <summary> /// lblFirstName control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Label lblFirstName; /// <summary> /// txtFirstName control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.TextBox txtFirstName; /// <summary> /// lblLastName control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Label lblLastName; /// <summary> /// txtLastName control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.TextBox txtLastName; /// <summary> /// secAutoresponder control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::WebsitePanel.Portal.CollapsiblePanel secAutoresponder; /// <summary> /// AutoresponderPanel control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Panel AutoresponderPanel; /// <summary> /// lblResponderEnabled control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Label lblResponderEnabled; /// <summary> /// chkResponderEnabled control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.CheckBox chkResponderEnabled; /// <summary> /// lblSubject control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Label lblSubject; /// <summary> /// txtSubject control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.TextBox txtSubject; /// <summary> /// lblMessage control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Label lblMessage; /// <summary> /// txtMessage control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.TextBox txtMessage; /// <summary> /// secForwarding control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::WebsitePanel.Portal.CollapsiblePanel secForwarding; /// <summary> /// ForwardingPanel control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Panel ForwardingPanel; /// <summary> /// lblForwardTo control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Label lblForwardTo; /// <summary> /// txtForward control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.TextBox txtForward; /// <summary> /// chkOriginalMessage control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.CheckBox chkOriginalMessage; /// <summary> /// Signature control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::WebsitePanel.Portal.CollapsiblePanel Signature; /// <summary> /// SignaturePanel control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Panel SignaturePanel; /// <summary> /// lblSignatureEnabled control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Label lblSignatureEnabled; /// <summary> /// cbSignatureEnabled control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.CheckBox cbSignatureEnabled; /// <summary> /// lblPlainSignature control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Label lblPlainSignature; /// <summary> /// txtPlainSignature control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.TextBox txtPlainSignature; /// <summary> /// lblHtmlSignature control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Label lblHtmlSignature; /// <summary> /// txtHtmlSignature control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.TextBox txtHtmlSignature; } }
/* Farsi Library - Working with Dates, Calendars, and DatePickers * http://www.codeproject.com/KB/selection/FarsiLibrary.aspx * * Copyright (C) Hadi Eskandari * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT * LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ namespace FarsiLibrary { using System; using System.Globalization; using FarsiLibrary.Exceptions; using FarsiLibrary.Resources; /// <summary> /// PersianCalendar calendar. Persian calendar, also named Jalaali calendar, was first based on Solar year by Omar Khayyam, the great Iranian poet, astrologer and scientist. /// Jalaali calendar is approximately 365 days. Each of the first six months in the Jalaali calendar has 31 days, each of the next five months has 30 days, and the last month has 29 days in a common year and 30 days in a leap year. A leap year is a year that, when divided by 33, has a remainder of 1, 5, 9, 13, 17, 22, 26, or 30. For example, the year 1370 is a leap year because dividing it by 33 yields a remainder of 17. There are approximately 8 leap years in every 33 year cycle. /// </summary> [Serializable] public class PersianCalendar : Calendar { #region Fields private int twoDigitYearMax = 1409; #endregion #region Const internal const long MaxDateTimeTicks = 196036416000000000L; /// <summary> /// Maximum amount of month that can be added or /// removed to / from a DateTime instance. /// </summary> internal const int MaxMonthDifference = 120000; /// <summary> /// Represents the current era. /// </summary> /// <remarks>The Persian calendar recognizes only A.P (Anno Persarum) era.</remarks> public const int PersianEra = 1; #endregion #region Methods /// <summary> /// Returns a DateTime that is the specified number of months away from the specified DateTime. /// </summary> /// <param name="time">The DateTime instance to add.</param> /// <param name="months">The number of months to add.</param> /// <returns>The DateTime that results from adding the specified number of months to the specified DateTime.</returns> /// <remarks> /// The year part of the resulting DateTime is affected if the resulting month is beyond the last month of the current year. The day part of the resulting DateTime is also affected if the resulting day is not a valid day in the resulting month of the resulting year; it is changed to the last valid day in the resulting month of the resulting year. The time-of-day part of the resulting DateTime remains the same as the specified DateTime. /// /// For example, if the specified month is Ordibehesht, which is the 2nd month and has 31 days, the specified day is the 31th day of that month, and the value of the months parameter is -3, the resulting year is one less than the specified year, the resulting month is Bahman, and the resulting day is the 30th day, which is the last day in Bahman. /// /// If the value of the months parameter is negative, the resulting DateTime would be earlier than the specified DateTime. /// </remarks> public override DateTime AddMonths(DateTime time, int months) { if (Math.Abs(months) > MaxMonthDifference) { throw new InvalidPersianDateException(FALocalizeManager.Instance.GetLocalizer().GetLocalizedString(StringID.PersianDate_InvalidMonth)); } var year = GetYear(true, time); var month = GetMonth(false, time); var day = GetDayOfMonth(false, time); month += (year - 1) * 12 + months; year = (month - 1) / 12 + 1; month -= (year - 1) * 12; if (day > 29) { var maxday = GetDaysInMonth(false, year, month, 0); if (maxday < day) day = maxday; } DateTime dateTime; try { dateTime = ToDateTime(year, month, day, 0, 0, 0, 0) + time.TimeOfDay; } catch (Exception) { throw new InvalidPersianDateException(FALocalizeManager.Instance.GetLocalizer().GetLocalizedString(StringID.PersianDate_InvalidDateTime)); } return dateTime; } /// <summary> /// Algorithm Type /// </summary> public override CalendarAlgorithmType AlgorithmType { get { return CalendarAlgorithmType.SolarCalendar; } } /// <summary> /// Maximum supported date time by this calendar. /// </summary> public override DateTime MaxSupportedDateTime { get { return PersianDate.MaxValue; } } /// <summary> /// Minimum supported date time by this calendar. /// </summary> public override DateTime MinSupportedDateTime { get { return PersianDate.MinValue; } } /// <summary> /// Returns a DateTime that is the specified number of years away from the specified DateTime. /// </summary> /// <param name="time">The DateTime instance to add.</param> /// <param name="years">The number of years to add.</param> /// <returns>The DateTime that results from adding the specified number of years to the specified DateTime.</returns> /// <remarks> /// The day part of the resulting DateTime is affected if the resulting day is not a valid day in the resulting month of the resulting year; it is changed to the last valid day in the resulting month of the resulting year. The time-of-day part of the resulting DateTime remains the same as the specified DateTime. /// /// For example, Esfand has 29 days, except during leap years when it has 30 days. If the specified Date is the 30th day of Esfand in a leap year and the value of years is 1, the resulting Date will be the 29th day of Esfand in the following year. /// /// If years is negative, the resulting DateTime would be earlier than the specified DateTime. /// </remarks> public override DateTime AddYears(DateTime time, int years) { var year = GetYear(true, time); var month = GetMonth(false, time); var day = GetDayOfMonth(false, time); year += years; if (day == 30 && month == 12) { if (!IsLeapYear(false, year, 0)) day = 29; } try { return ToDateTime(year, month, day, 0, 0, 0, 0) + time.TimeOfDay; } catch (Exception) { throw new InvalidPersianDateException(FALocalizeManager.Instance.GetLocalizer().GetLocalizedString(StringID.PersianDate_InvalidDateTime)); } } /// <summary> /// Gets the day of the month in the specified DateTime. /// </summary> /// <param name="time">The DateTime instance to read.</param> /// <returns>An integer from 1 to 31 that represents the day of the month in time.</returns> public override int GetDayOfMonth(DateTime time) { return GetDayOfMonth(true, time); } private static int GetDayOfMonth(bool validate, DateTime time) { var days = GetDayOfYear(validate, time); for (var i = 0; i < 6; i++) { if (days <= 31) return days; days -= 31; } for (var i = 0; i < 5; i++) { if (days <= 30) return days; days -= 30; } return days; } /// <summary> /// Gets the day of the week in the specified DateTime. /// </summary> /// <param name="time">The DateTime instance to read.</param> /// <returns>A DayOfWeek value that represents the day of the week in time.</returns> /// <remarks>The DayOfWeek values are Sunday which indicates YekShanbe', Monday which indicates DoShanbe', Tuesday which indicates SeShanbe', Wednesday which indicates ChaharShanbe', Thursday which indicates PanjShanbe', Friday which indicates Jom'e, and Saturday which indicates Shanbe'.</remarks> public override DayOfWeek GetDayOfWeek(DateTime time) { return time.DayOfWeek; } /// <summary> /// Gets the day of the year in the specified DateTime. /// </summary> /// <param name="time">The DateTime instance to read.</param> /// <returns>An integer from 1 to 366 that represents the day of the year in time.</returns> public override int GetDayOfYear(DateTime time) { return GetDayOfYear(true, time); } private static int GetDayOfYear(bool validate, DateTime time) { int year; int days; GetYearAndRemainingDays(validate, time, out year, out days); return days; } /// <summary> /// Gets the number of days in the specified month. /// </summary> /// <param name="year">An integer that represents the year.</param> /// <param name="month">An integer that represents the month.</param> /// <param name="era">An integer that represents the era.</param> /// <returns>The number of days in the specified month in the specified year in the specified era.</returns> /// <remarks>For example, this method might return 29 or 30 for Esfand (month = 12), depending on whether year is a leap year.</remarks> public override int GetDaysInMonth(int year, int month, int era) { return GetDaysInMonth(true, year, month, era); } private static int GetDaysInMonth(bool validate, int year, int month, int era) { CheckEraRange(validate, era); CheckYearRange(validate, year); CheckMonthRange(validate, month); if (month < 7) return 31; if (month < 12) return 30; if (IsLeapYear(false, year, 0)) return 30; return 29; } /// <summary> /// Gets the number of days in the year specified by the year and era parameters. /// </summary> /// <param name="year">An integer that represents the year.</param> /// <param name="era">An integer that represents the era.</param> /// <returns>The number of days in the specified year in the specified era.</returns> /// <remarks>For example, this method might return 365 or 366, depending on whether year is a leap year.</remarks> public override int GetDaysInYear(int year, int era) { return GetDaysInYear(true, year, era); } private static int GetDaysInYear(bool validate, int year, int era) { return IsLeapYear(validate, year, era) ? 366 : 365; } /// <summary> /// Gets the era in the specified DateTime. /// </summary> /// <param name="time">The DateTime instance to read.</param> /// <returns>An integer that represents the era in time.</returns> /// <remarks>The Persian calendar recognizes one era: A.P. (Latin "Anno Persarum", which means "the year of/for Persians").</remarks> public override int GetEra(DateTime time) { CheckTicksRange(true, time); return PersianEra; } /// <summary> /// Gets the month in the specified DateTime. /// </summary> /// <param name="time">The DateTime instance to read.</param> /// <returns>An integer between 1 and 12 that represents the month in time.</returns> /// <remarks>Month 1 indicates Farvardin, month 2 indicates Ordibehesht, month 3 indicates Khordad, month 4 indicates Tir, month 5 indicates Amordad, month 6 indicates Shahrivar, month 7 indicates Mehr, month 8 indicates Aban, month 9 indicates Azar, month 10 indicates Dey, month 11 indicates Bahman, and month 12 indicates Esfand.</remarks> public override int GetMonth(DateTime time) { return GetMonth(true, time); } private static int GetMonth(bool validate, DateTime time) { var days = GetDayOfYear(validate, time); if (days <= 31) return 1; if (days <= 62) return 2; if (days <= 93) return 3; if (days <= 124) return 4; if (days <= 155) return 5; if (days <= 186) return 6; if (days <= 216) return 7; if (days <= 246) return 8; if (days <= 276) return 9; if (days <= 306) return 10; if (days <= 336) return 11; return 12; } /// <summary> /// Gets the number of months in the year specified by the year and era parameters. /// </summary> /// <param name="year">An integer that represents the year.</param> /// <param name="era">An integer that represents the era.</param> /// <returns>The number of months in the specified year in the specified era.</returns> public override int GetMonthsInYear(int year, int era) { CheckEraRange(true, era); CheckYearRange(true, year); return 12; } /// <summary> /// Gets the year in the specified DateTime. /// </summary> /// <param name="time">The DateTime instance to read.</param> /// <returns>An integer between 1 and 9378 that represents the year in time.</returns> public override int GetYear(DateTime time) { return GetYear(true, time); } private static int GetYear(bool validate, DateTime time) { int days; int year; GetYearAndRemainingDays(validate, time, out year, out days); return year; } /// <summary> /// Determines whether the Date specified by the year, month, day, and era parameters is a leap day. /// </summary> /// <param name="year">An integer that represents the year.</param> /// <param name="month">An integer that represents the month.</param> /// <param name="day">An integer that represents the day.</param> /// <param name="era">An integer that represents the era.</param> /// <returns>true if the specified day is a leap day; otherwise, false.</returns> /// <remarks> /// In the Persian calendar leap years are applied every 4 or 5 years according to a certain pattern that iterates in a 2820-year cycle. A common year has 365 days and a leap year has 366 days. /// /// A leap day is a day that occurs only in a leap year. In the Persian calendar, the 30th day of Esfand (month 12) is the only leap day. /// </remarks> public override bool IsLeapDay(int year, int month, int day, int era) { CheckEraRange(true, era); CheckYearRange(true, year); CheckMonthRange(true, month); if (day == 30 && month == 12 && IsLeapYear(false, year, 0)) return true; return false; } /// <summary> /// Determines whether the month specified by the year, month, and era parameters is a leap month. /// </summary> /// <param name="year">An integer that represents the year.</param> /// <param name="month">An integer that represents the month.</param> /// <param name="era">An integer that represents the era.</param> /// <returns>This method always returns false, unless overridden by a derived class.</returns> /// <remarks> /// In the Persian calendar leap years are applied every 4 or 5 years according to a certain pattern that iterates in a 2820-year cycle. A common year has 365 days and a leap year has 366 days. /// /// A leap month is an entire month that occurs only in a leap year. The Persian calendar does not have any leap months. /// </remarks> public override bool IsLeapMonth(int year, int month, int era) { CheckEraRange(true, era); CheckYearRange(true, year); CheckMonthRange(true, month); return month == 12 && IsLeapYear(year); } /// <summary> /// Determines whether the month specified by the year, month, and era parameters is a leap month. /// </summary> /// <param name="year">An integer that represents the year.</param> /// <param name="month">An integer that represents the month.</param> /// <returns>This method always returns false, unless overridden by a derived class.</returns> /// <remarks> /// In the Persian calendar leap years are applied every 4 or 5 years according to a certain pattern that iterates in a 2820-year cycle. A common year has 365 days and a leap year has 366 days. /// /// A leap month is an entire month that occurs only in a leap year. The Persian calendar does not have any leap months. /// </remarks> public override bool IsLeapMonth(int year, int month) { return IsLeapMonth(year, month, PersianEra); } /// <summary> /// Determines whether the year specified by the year and era parameters is a leap year. /// </summary> /// <param name="year">An integer that represents the year.</param> /// <param name="era">An integer that represents the era.</param> /// <returns>true if the specified year is a leap year; otherwise, false.</returns> /// <remarks>In the Persian calendar leap years are applied every 4 or 5 years according to a certain pattern that iterates in a 2820-year cycle. A common year has 365 days and a leap year has 366 days.</remarks> public override bool IsLeapYear(int year, int era) { return IsLeapYear(true, year, era); } private static bool IsLeapYear(bool validate, int year, int era) { CheckEraRange(validate, era); CheckYearRange(validate, year); return PersianDateConverter.IsJLeapYear(year); } /// <summary> /// Returns a DateTime that is set to the specified Date and time in the specified era. /// </summary> /// <param name="year">An integer that represents the year.</param> /// <param name="month">An integer that represents the month.</param> /// <param name="day">An integer that represents the day.</param> /// <param name="hour">An integer that represents the hour.</param> /// <param name="minute">An integer that represents the minute.</param> /// <param name="second">An integer that represents the second.</param> /// <param name="millisecond">An integer that represents the millisecond.</param> /// <param name="era">An integer that represents the era.</param> /// <returns>The DateTime instance set to the specified Date and time in the current era.</returns> public override DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era) { CheckEraRange(true, era); CheckDateRange(true, year, month, day); int days = day; for (int i = 1; i < month; i++) { if (i < 7) { days += 31; } else if (i < 12) { days += 30; } } //Total number of passed days from the start of the calendar days += 365 * year + NumberOfLeapYearsUntil(false, year); // following line validates the arguments of time var timePart = new DateTime(1, 1, 1, hour, minute, second, millisecond); var ticks = days * 864000000000L + timePart.Ticks + 195721056000000000L; DateTime dateTime; try { dateTime = new DateTime(ticks); } catch (Exception) { // If ticks go greater than DateTime.MaxValue.Ticks, this exception will be caught throw new InvalidPersianDateException(FALocalizeManager.Instance.GetLocalizer().GetLocalizedString(StringID.PersianDate_InvalidMonthDay)); } return dateTime; } /// <summary> /// Converts the specified two-digit year to a four-digit year by using the Globalization.PersianCalendar.TwoDigitYearMax property to determine the appropriate century. /// </summary> /// <param name="year">A two-digit integer that represents the year to convert.</param> /// <returns>An integer that contains the four-digit representation of year.</returns> /// <remarks>TwoDigitYearMax is the last year in the 100-year /// range that can be represented by a two-digit year. The century is determined by finding the sole occurrence of the two-digit year within that 100-year range. For example, if TwoDigitYearMax is set to 1429, the 100-year range is from 1330 to 1429; therefore, a 2-digit value of 30 is interpreted as 1330, while a 2-digit value of 29 is interpreted as 1429.</remarks> public override int ToFourDigitYear(int year) { if (year != 0) { try { CheckYearRange(true, year); } catch (Exception) { //throw new System.ArgumentOutOfRangeException("Year", year, ResourceLibrary.GetString(CalendarKeys.InvalidYear, CalendarKeys.Root)); throw new InvalidPersianDateException(FALocalizeManager.Instance.GetLocalizer().GetLocalizedString(StringID.PersianDate_InvalidFourDigitYear)); } } if (year > 99) return year; int a = TwoDigitYearMax / 100; if (year > TwoDigitYearMax - a * 100) a--; return a * 100 + year; } /// <summary> /// Gets the list of eras in the PersianCalendar. /// </summary> /// <remarks>The Persian calendar recognizes one era: A.P. (Latin "Anno Persarum", which means "the year of/for Persians").</remarks> public override int[] Eras { get { return new[] { PersianEra }; } } /// <summary> /// Gets and sets the last year of a 100-year range that can be represented by a 2-digit year. /// </summary> /// <property_value>The last year of a 100-year range that can be represented by a 2-digit year.</property_value> /// <remarks>This property allows a 2-digit year to be properly translated to a 4-digit year. For example, if this property is set to 1429, the 100-year range is from 1330 to 1429; therefore, a 2-digit value of 30 is interpreted as 1330, while a 2-digit value of 29 is interpreted as 1429.</remarks> public override int TwoDigitYearMax { get { return twoDigitYearMax; } set { if (value < 100 || 9378 < value) throw new InvalidOperationException("value should be between 100 and 9378"); twoDigitYearMax = value; } } /// <summary> /// Gets the century of the specified DateTime. /// </summary> /// <param name="time">An instance of the DateTime class to read.</param> /// <returns>An integer from 1 to 94 that represents the century.</returns> /// <remarks>A century is a whole 100-year period. So the century 14 for example, represents years 1301 through 1400.</remarks> public int GetCentury(DateTime time) { return (GetYear(true, time) - 1) / 100 + 1; } /// <summary> /// Calculates the number of leap years until -but not including- the specified year. /// </summary> /// <param name="year">An integer between 1 and 9378</param> /// <returns>An integer representing the number of leap years that have occured by the year specified.</returns> /// <remarks>In the Persian calendar leap years are applied every 4 or 5 years according to a certain pattern that iterates in a 2820-year cycle. A common year has 365 days and a leap year has 366 days.</remarks> public int NumberOfLeapYearsUntil(int year) { return NumberOfLeapYearsUntil(true, year); } private static int NumberOfLeapYearsUntil(bool validate, int year) { CheckYearRange(validate, year); var count = 0; for (var i = 4; i < year; i++) { if (IsLeapYear(false, i, 0)) { count++; i += 3; } } return count; } private static void CheckEraRange(bool validate, int era) { if (validate) { if (era < 0 || era > 1) { throw new InvalidPersianDateException(FALocalizeManager.Instance.GetLocalizer().GetLocalizedString(StringID.PersianDate_InvalidEra)); } } } private static void CheckYearRange(bool validate, int year) { if (validate) { if (year < 1 || year > 9378) { throw new InvalidPersianDateException(FALocalizeManager.Instance.GetLocalizer().GetLocalizedString(StringID.PersianDate_InvalidYear)); } } } private static void CheckMonthRange(bool validate, int month) { if (validate) { if (month < 1 || month > 12) { throw new InvalidPersianDateException(FALocalizeManager.Instance.GetLocalizer().GetLocalizedString(StringID.PersianDate_InvalidMonth)); } } } private static void CheckDateRange(bool validate, int year, int month, int day) { if (validate) { var maxday = GetDaysInMonth(true, year, month, 0); if (day < 1 || maxday < day) { if (day == 30 && month == 12) { throw new InvalidPersianDateException(FALocalizeManager.Instance.GetLocalizer().GetLocalizedString(StringID.PersianDate_InvalidLeapYear)); } throw new InvalidPersianDateException(FALocalizeManager.Instance.GetLocalizer().GetLocalizedString(StringID.PersianDate_InvalidDay)); } } } private static void CheckTicksRange(bool validate, DateTime time) { // Valid ticks represent times between 12:00:00.000 AM, 22/03/0622 CE and 11:59:59.999 PM, 31/12/9999 CE. if (validate) { var ticks = time.Ticks; if (ticks < 196037280000000000L) { throw new InvalidPersianDateException(FALocalizeManager.Instance.GetLocalizer().GetLocalizedString(StringID.PersianDate_InvalidDateTime)); } } } private static void GetYearAndRemainingDays(bool validate, DateTime time, out int year, out int days) { CheckTicksRange(validate, time); days = (time - new DateTime(196036416000000000L)).Days; year = 1; var daysInNextYear = 365; while (days > daysInNextYear) { days -= daysInNextYear; year++; daysInNextYear = GetDaysInYear(false, year, 0); } } #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; using System.Collections.Generic; using System.Xml; //Required for Content Type File manipulation using System.Diagnostics; using System.IO.Compression; namespace System.IO.Packaging { /// <summary> /// ZipPackage is a specific implementation for the abstract Package /// class, corresponding to the Zip file format. /// This is a part of the Packaging Layer APIs. /// </summary> public sealed class ZipPackage : Package { #region Public Methods #region PackagePart Methods /// <summary> /// This method is for custom implementation for the underlying file format /// Adds a new item to the zip archive corresponding to the PackagePart in the package. /// </summary> /// <param name="partUri">PartName</param> /// <param name="contentType">Content type of the part</param> /// <param name="compressionOption">Compression option for this part</param> /// <returns></returns> /// <exception cref="ArgumentNullException">If partUri parameter is null</exception> /// <exception cref="ArgumentNullException">If contentType parameter is null</exception> /// <exception cref="ArgumentException">If partUri parameter does not conform to the valid partUri syntax</exception> /// <exception cref="ArgumentOutOfRangeException">If CompressionOption enumeration [compressionOption] does not have one of the valid values</exception> protected override PackagePart CreatePartCore(Uri partUri, string contentType, CompressionOption compressionOption) { //Validating the PartUri - this method will do the argument checking required for uri. partUri = PackUriHelper.ValidatePartUri(partUri); if (contentType == null) throw new ArgumentNullException(nameof(contentType)); Package.ThrowIfCompressionOptionInvalid(compressionOption); // Convert Metro CompressionOption to Zip CompressionMethodEnum. CompressionLevel level; GetZipCompressionMethodFromOpcCompressionOption(compressionOption, out level); // Create new Zip item. // We need to remove the leading "/" character at the beginning of the part name. // The partUri object must be a ValidatedPartUri string zipItemName = ((PackUriHelper.ValidatedPartUri)partUri).PartUriString.Substring(1); ZipArchiveEntry zipArchiveEntry = _zipArchive.CreateEntry(zipItemName, level); //Store the content type of this part in the content types stream. _contentTypeHelper.AddContentType((PackUriHelper.ValidatedPartUri)partUri, new ContentType(contentType), level); return new ZipPackagePart(this, zipArchiveEntry.Archive, zipArchiveEntry, _zipStreamManager, (PackUriHelper.ValidatedPartUri)partUri, contentType, compressionOption); } /// <summary> /// This method is for custom implementation specific to the file format. /// Returns the part after reading the actual physical bits. The method /// returns a null to indicate that the part corresponding to the specified /// Uri was not found in the container. /// This method does not throw an exception if a part does not exist. /// </summary> /// <param name="partUri"></param> /// <returns></returns> protected override PackagePart GetPartCore(Uri partUri) { //Currently the design has two aspects which makes it possible to return //a null from this method - // 1. All the parts are loaded at Package.Open time and as such, this // method would not be invoked, unless the user is asking for - // i. a part that does not exist - we can safely return null // ii.a part(interleaved/non-interleaved) that was added to the // underlying package by some other means, and the user wants to // access the updated part. This is currently not possible as the // underlying zip i/o layer does not allow for FileShare.ReadWrite. // 2. Also, its not a straightforward task to determine if a new part was // added as we need to look for atomic as well as interleaved parts and // this has to be done in a case sensitive manner. So, effectively // we will have to go through the entire list of zip items to determine // if there are any updates. // If ever the design changes, then this method must be updated accordingly return null; } /// <summary> /// This method is for custom implementation specific to the file format. /// Deletes the part corresponding to the uri specified. Deleting a part that does not /// exists is not an error and so we do not throw an exception in that case. /// </summary> /// <param name="partUri"></param> /// <exception cref="ArgumentNullException">If partUri parameter is null</exception> /// <exception cref="ArgumentException">If partUri parameter does not conform to the valid partUri syntax</exception> protected override void DeletePartCore(Uri partUri) { //Validating the PartUri - this method will do the argument checking required for uri. partUri = PackUriHelper.ValidatePartUri(partUri); string partZipName = GetZipItemNameFromOpcName(PackUriHelper.GetStringForPartUri(partUri)); ZipArchiveEntry zipArchiveEntry = _zipArchive.GetEntry(partZipName); if (zipArchiveEntry != null) { // Case of an atomic part. zipArchiveEntry.Delete(); } //Delete the content type for this part if it was specified as an override _contentTypeHelper.DeleteContentType((PackUriHelper.ValidatedPartUri)partUri); } /// <summary> /// This method is for custom implementation specific to the file format. /// This is the method that knows how to get the actual parts from the underlying /// zip archive. /// </summary> /// <remarks> /// <para> /// Some or all of the parts may be interleaved. The Part object for an interleaved part encapsulates /// the Uri of the proper part name and the ZipFileInfo of the initial piece. /// This function does not go through the extra work of checking piece naming validity /// throughout the package. /// </para> /// <para> /// This means that interleaved parts without an initial piece will be silently ignored. /// Other naming anomalies get caught at the Stream level when an I/O operation involves /// an anomalous or missing piece. /// </para> /// <para> /// This function reads directly from the underlying IO layer and is supposed to be called /// just once in the lifetime of a package (at init time). /// </para> /// </remarks> /// <returns>An array of ZipPackagePart.</returns> protected override PackagePart[] GetPartsCore() { List<PackagePart> parts = new List<PackagePart>(InitialPartListSize); // The list of files has to be searched linearly (1) to identify the content type // stream, and (2) to identify parts. System.Collections.ObjectModel.ReadOnlyCollection<ZipArchiveEntry> zipArchiveEntries = _zipArchive.Entries; // We have already identified the [ContentTypes].xml pieces if any are present during // the initialization of ZipPackage object // Record parts and ignored items. foreach (ZipArchiveEntry zipArchiveEntry in zipArchiveEntries) { //Returns false if - // a. its a content type item // b. items that have either a leading or trailing slash. if (IsZipItemValidOpcPartOrPiece(zipArchiveEntry.FullName)) { Uri partUri = new Uri(GetOpcNameFromZipItemName(zipArchiveEntry.FullName), UriKind.Relative); PackUriHelper.ValidatedPartUri validatedPartUri; if (PackUriHelper.TryValidatePartUri(partUri, out validatedPartUri)) { ContentType contentType = _contentTypeHelper.GetContentType(validatedPartUri); if (contentType != null) { // In case there was some redundancy between pieces and/or the atomic // part, it will be detected at this point because the part's Uri (which // is independent of interleaving) will already be in the dictionary. parts.Add(new ZipPackagePart(this, zipArchiveEntry.Archive, zipArchiveEntry, _zipStreamManager, validatedPartUri, contentType.ToString(), GetCompressionOptionFromZipFileInfo(zipArchiveEntry))); } } //If not valid part uri we can completely ignore this zip file item. Even if later someone adds //a new part, the corresponding zip item can never map to one of these items } // If IsZipItemValidOpcPartOrPiece returns false, it implies that either the zip file Item // starts or ends with a "/" and as such we can completely ignore this zip file item. Even if later // a new part gets added, its corresponding zip item cannot map to one of these items. } return parts.ToArray(); } #endregion PackagePart Methods #region Other Methods /// <summary> /// This method is for custom implementation corresponding to the underlying zip file format. /// </summary> protected override void FlushCore() { //Save the content type file to the archive. _contentTypeHelper.SaveToFile(); } /// <summary> /// Closes the underlying ZipArchive object for this container /// </summary> /// <param name="disposing">True if called during Dispose, false if called during Finalize</param> protected override void Dispose(bool disposing) { try { if (disposing) { if (_contentTypeHelper != null) { _contentTypeHelper.SaveToFile(); } if (_zipStreamManager != null) { _zipStreamManager.Dispose(); } if (_zipArchive != null) { _zipArchive.Dispose(); } // _containerStream may be opened given a file name, in which case it should be closed here. // _containerStream may be passed into the constructor, in which case, it should not be closed here. if (_shouldCloseContainerStream) { _containerStream.Dispose(); } else { } _containerStream = null; } } finally { base.Dispose(disposing); } } #endregion Other Methods #endregion Public Methods #region Internal Constructors /// <summary> /// Internal constructor that is called by the OpenOnFile static method. /// </summary> /// <param name="path">File path to the container.</param> /// <param name="packageFileMode">Container is opened in the specified mode if possible</param> /// <param name="packageFileAccess">Container is opened with the specified access if possible</param> /// <param name="share">Container is opened with the specified share if possible</param> internal ZipPackage(string path, FileMode packageFileMode, FileAccess packageFileAccess, FileShare share) : base(packageFileAccess) { ZipArchive zipArchive = null; ContentTypeHelper contentTypeHelper = null; _packageFileMode = packageFileMode; _packageFileAccess = packageFileAccess; try { _containerStream = new FileStream(path, _packageFileMode, _packageFileAccess, share); _shouldCloseContainerStream = true; ZipArchiveMode zipArchiveMode = ZipArchiveMode.Update; if (packageFileAccess == FileAccess.Read) zipArchiveMode = ZipArchiveMode.Read; else if (packageFileAccess == FileAccess.Write) zipArchiveMode = ZipArchiveMode.Create; else if (packageFileAccess == FileAccess.ReadWrite) zipArchiveMode = ZipArchiveMode.Update; zipArchive = new ZipArchive(_containerStream, zipArchiveMode, true, Text.Encoding.UTF8); _zipStreamManager = new ZipStreamManager(zipArchive, _packageFileMode, _packageFileAccess); contentTypeHelper = new ContentTypeHelper(zipArchive, _packageFileMode, _packageFileAccess, _zipStreamManager); } catch { if (zipArchive != null) { zipArchive.Dispose(); } throw; } _zipArchive = zipArchive; _contentTypeHelper = contentTypeHelper; } /// <summary> /// Internal constructor that is called by the Open(Stream) static methods. /// </summary> /// <param name="s"></param> /// <param name="packageFileMode"></param> /// <param name="packageFileAccess"></param> internal ZipPackage(Stream s, FileMode packageFileMode, FileAccess packageFileAccess) : base(packageFileAccess) { ZipArchive zipArchive = null; ContentTypeHelper contentTypeHelper = null; _packageFileMode = packageFileMode; _packageFileAccess = packageFileAccess; try { ZipArchiveMode zipArchiveMode = ZipArchiveMode.Update; if (packageFileAccess == FileAccess.Read) zipArchiveMode = ZipArchiveMode.Read; else if (packageFileAccess == FileAccess.Write) zipArchiveMode = ZipArchiveMode.Create; else if (packageFileAccess == FileAccess.ReadWrite) zipArchiveMode = ZipArchiveMode.Update; zipArchive = new ZipArchive(s, zipArchiveMode, true, Text.Encoding.UTF8); _zipStreamManager = new ZipStreamManager(zipArchive, packageFileMode, packageFileAccess); contentTypeHelper = new ContentTypeHelper(zipArchive, packageFileMode, packageFileAccess, _zipStreamManager); } catch (InvalidDataException) { throw new FileFormatException("File contains corrupted data."); } catch { if (zipArchive != null) { zipArchive.Dispose(); } throw; } _containerStream = s; _shouldCloseContainerStream = false; _zipArchive = zipArchive; _contentTypeHelper = contentTypeHelper; } #endregion Internal Constructors #region Internal Methods // More generic function than GetZipItemNameFromPartName. In particular, it will handle piece names. internal static string GetZipItemNameFromOpcName(string opcName) { Debug.Assert(opcName != null && opcName.Length > 0); return opcName.Substring(1); } // More generic function than GetPartNameFromZipItemName. In particular, it will handle piece names. internal static string GetOpcNameFromZipItemName(string zipItemName) { return String.Concat(ForwardSlashString, zipItemName); } // Convert from Metro CompressionOption to ZipFileInfo compression properties. internal static void GetZipCompressionMethodFromOpcCompressionOption( CompressionOption compressionOption, out CompressionLevel compressionLevel) { switch (compressionOption) { case CompressionOption.NotCompressed: { compressionLevel = CompressionLevel.NoCompression; } break; case CompressionOption.Normal: { compressionLevel = CompressionLevel.Optimal; } break; case CompressionOption.Maximum: { compressionLevel = CompressionLevel.Optimal; } break; case CompressionOption.Fast: { compressionLevel = CompressionLevel.Fastest; } break; case CompressionOption.SuperFast: { compressionLevel = CompressionLevel.Fastest; } break; // fall-through is not allowed default: { Debug.Assert(false, "Encountered an invalid CompressionOption enum value"); goto case CompressionOption.NotCompressed; } } } #endregion Internal Methods internal FileMode PackageFileMode { get { return _packageFileMode; } } #region Private Methods //returns a boolean indicating if the underlying zip item is a valid metro part or piece // This mainly excludes the content type item, as well as entries with leading or trailing // slashes. private bool IsZipItemValidOpcPartOrPiece(string zipItemName) { Debug.Assert(zipItemName != null, "The parameter zipItemName should not be null"); //check if the zip item is the Content type item -case sensitive comparison // The following test will filter out an atomic content type file, with name // "[Content_Types].xml", as well as an interleaved one, with piece names such as // "[Content_Types].xml/[0].piece" or "[Content_Types].xml/[5].last.piece". if (zipItemName.StartsWith(ContentTypeHelper.ContentTypeFileName, StringComparison.OrdinalIgnoreCase)) return false; else { //Could be an empty zip folder //We decided to ignore zip items that contain a "/" as this could be a folder in a zip archive //Some of the tools support this and some don't. There is no way ensure that the zip item never have //a leading "/", although this is a requirement we impose on items created through our API //Therefore we ignore them at the packaging api level. if (zipItemName.StartsWith(ForwardSlashString, StringComparison.Ordinal)) return false; //This will ignore the folder entries found in the zip package created by some zip tool //PartNames ending with a "/" slash is also invalid so we are skipping these entries, //this will also prevent the PackUriHelper.CreatePartUri from throwing when it encounters a // partname ending with a "/" if (zipItemName.EndsWith(ForwardSlashString, StringComparison.Ordinal)) return false; else return true; } } // convert from Zip CompressionMethodEnum and DeflateOptionEnum to Metro CompressionOption static private CompressionOption GetCompressionOptionFromZipFileInfo(ZipArchiveEntry zipFileInfo) { // Note: we can't determine compression method / level from the ZipArchiveEntry. CompressionOption result = CompressionOption.Normal; return result; } #endregion Private Methods #region Private Members private const int InitialPartListSize = 50; private const int InitialPieceNameListSize = 50; private ZipArchive _zipArchive; private Stream _containerStream; // stream we are opened in if Open(Stream) was called private bool _shouldCloseContainerStream; private ContentTypeHelper _contentTypeHelper; // manages the content types for all the parts in the container private ZipStreamManager _zipStreamManager; // manages streams for all parts, avoiding opening streams multiple times private FileAccess _packageFileAccess; private FileMode _packageFileMode; private const string ForwardSlashString = "/"; //Required for creating a part name from a zip item name //IEqualityComparer for extensions private static readonly ExtensionEqualityComparer s_extensionEqualityComparer = new ExtensionEqualityComparer(); #endregion Private Members /// <summary> /// ExtensionComparer /// The Extensions are stored in the Default Dictionary in their original form, /// however they are compared in a normalized manner. /// Equivalence for extensions in the content type stream, should follow /// the same rules as extensions of partnames. Also, by the time this code is invoked, /// we have already validated, that the extension is in the correct format as per the /// part name rules.So we are simplifying the logic here to just convert the extensions /// to Upper invariant form and then compare them. /// </summary> private sealed class ExtensionEqualityComparer : IEqualityComparer<string> { bool IEqualityComparer<string>.Equals(string extensionA, string extensionB) { Debug.Assert(extensionA != null, "extension should not be null"); Debug.Assert(extensionB != null, "extension should not be null"); //Important Note: any change to this should be made in accordance //with the rules for comparing/normalizing partnames. //Refer to PackUriHelper.ValidatedPartUri.GetNormalizedPartUri method. //Currently normalization just involves upper-casing ASCII and hence the simplification. return (String.CompareOrdinal(extensionA.ToUpperInvariant(), extensionB.ToUpperInvariant()) == 0); } int IEqualityComparer<string>.GetHashCode(string extension) { Debug.Assert(extension != null, "extension should not be null"); //Important Note: any change to this should be made in accordance //with the rules for comparing/normalizing partnames. //Refer to PackUriHelper.ValidatedPartUri.GetNormalizedPartUri method. //Currently normalization just involves upper-casing ASCII and hence the simplification. return extension.ToUpperInvariant().GetHashCode(); } } /// <summary> /// This is a helper class that maintains the Content Types File related to /// this ZipPackage. /// </summary> private class ContentTypeHelper { /// <summary> /// Initialize the object without uploading any information from the package. /// Complete initialization in read mode also involves calling ParseContentTypesFile /// to deserialize content type information. /// </summary> internal ContentTypeHelper(ZipArchive zipArchive, FileMode packageFileMode, FileAccess packageFileAccess, ZipStreamManager zipStreamManager) { _zipArchive = zipArchive; //initialized in the ZipPackage constructor _packageFileMode = packageFileMode; _packageFileAccess = packageFileAccess; _zipStreamManager = zipStreamManager; //initialized in the ZipPackage constructor // The extensions are stored in the default Dictionary in their original form , but they are compared // in a normalized manner using the ExtensionComparer. _defaultDictionary = new Dictionary<string, ContentType>(s_defaultDictionaryInitialSize, s_extensionEqualityComparer); // Identify the content type file or files before identifying parts and piece sequences. // This is necessary because the name of the content type stream is not a part name and // the information it contains is needed to recognize valid parts. if (_zipArchive.Mode == ZipArchiveMode.Read || _zipArchive.Mode == ZipArchiveMode.Update) ParseContentTypesFile(_zipArchive.Entries); //No contents to persist to the disk - _dirty = false; //by default //Lazy initialize these members as required //_overrideDictionary - Overrides should be rare //_contentTypeFileInfo - We will either find an atomin part, or //_contentTypeStreamPieces - an interleaved part //_contentTypeStreamExists - defaults to false - not yet found } internal static string ContentTypeFileName { get { return s_contentTypesFile; } } //Adds the Default entry if it is the first time we come across //the extension for the partUri, does nothing if the content type //corresponding to the default entry for the extension matches or //adds a override corresponding to this part and content type. //This call is made when a new part is being added to the package. // This method assumes the partUri is valid. internal void AddContentType(PackUriHelper.ValidatedPartUri partUri, ContentType contentType, CompressionLevel compressionLevel) { //save the compressionOption and deflateOption that should be used //to create the content type item later if (!_contentTypeStreamExists) { _cachedCompressionLevel = compressionLevel; } // Figure out whether the mapping matches a default entry, can be made into a new // default entry, or has to be entered as an override entry. bool foundMatchingDefault = false; string extension = partUri.PartUriExtension; // Need to create an override entry? if (extension.Length == 0 || (_defaultDictionary.ContainsKey(extension) && !(foundMatchingDefault = _defaultDictionary[extension].AreTypeAndSubTypeEqual(contentType)))) { AddOverrideElement(partUri, contentType); } // Else, either there is already a mapping from extension to contentType, // or one needs to be created. else if (!foundMatchingDefault) { AddDefaultElement(extension, contentType); } } //Returns the content type for the part, if present, else returns null. internal ContentType GetContentType(PackUriHelper.ValidatedPartUri partUri) { //Step 1: Check if there is an override entry present corresponding to the //partUri provided. Override takes precedence over the default entries if (_overrideDictionary != null) { if (_overrideDictionary.ContainsKey(partUri)) return _overrideDictionary[partUri]; } //Step 2: Check if there is a default entry corresponding to the //extension of the partUri provided. string extension = partUri.PartUriExtension; if (_defaultDictionary.ContainsKey(extension)) return _defaultDictionary[extension]; //Step 3: If we did not find an entry in the override and the default //dictionaries, this is an error condition return null; } //Deletes the override entry corresponding to the partUri, if it exists internal void DeleteContentType(PackUriHelper.ValidatedPartUri partUri) { if (_overrideDictionary != null) { if (_overrideDictionary.Remove(partUri)) _dirty = true; } } internal void SaveToFile() { if (_dirty) { //Lazy init: Initialize when the first part is added. if (!_contentTypeStreamExists) { _contentTypeZipArchiveEntry = _zipArchive.CreateEntry(s_contentTypesFile, _cachedCompressionLevel); _contentTypeStreamExists = true; } // delete and re-create entry for content part. When writing this, the stream will not truncate the content // if the XML is shorter than the existing content part. var contentTypefullName = _contentTypeZipArchiveEntry.FullName; var thisArchive = _contentTypeZipArchiveEntry.Archive; _zipStreamManager.Close(_contentTypeZipArchiveEntry); _contentTypeZipArchiveEntry.Delete(); _contentTypeZipArchiveEntry = thisArchive.CreateEntry(contentTypefullName); using (Stream s = _zipStreamManager.Open(_contentTypeZipArchiveEntry, _packageFileMode, FileAccess.ReadWrite)) { // use UTF-8 encoding by default using (XmlWriter writer = XmlWriter.Create(s, new XmlWriterSettings { Encoding = System.Text.Encoding.UTF8 })) { writer.WriteStartDocument(); // write root element tag - Types writer.WriteStartElement(s_typesTagName, s_typesNamespaceUri); // for each default entry foreach (string key in _defaultDictionary.Keys) { WriteDefaultElement(writer, key, _defaultDictionary[key]); } if (_overrideDictionary != null) { // for each override entry foreach (PackUriHelper.ValidatedPartUri key in _overrideDictionary.Keys) { WriteOverrideElement(writer, key, _overrideDictionary[key]); } } // end of Types tag writer.WriteEndElement(); // close the document writer.WriteEndDocument(); _dirty = false; } } } } private void EnsureOverrideDictionary() { // The part Uris are stored in the Override Dictionary in their original form , but they are compared // in a normalized manner using the PartUriComparer if (_overrideDictionary == null) _overrideDictionary = new Dictionary<PackUriHelper.ValidatedPartUri, ContentType>(s_overrideDictionaryInitialSize); } private void ParseContentTypesFile(System.Collections.ObjectModel.ReadOnlyCollection<ZipArchiveEntry> zipFiles) { // Find the content type stream, allowing for interleaving. Naming collisions // (as between an atomic and an interleaved part) will result in an exception being thrown. Stream s = OpenContentTypeStream(zipFiles); // Allow non-existent content type stream. if (s == null) return; XmlReaderSettings xrs = new XmlReaderSettings(); xrs.IgnoreWhitespace = true; using (s) using (XmlReader reader = XmlReader.Create(s, xrs)) { //This method expects the reader to be in ReadState.Initial. //It will make the first read call. PackagingUtilities.PerformInitialReadAndVerifyEncoding(reader); //Note: After the previous method call the reader should be at the first tag in the markup. //MoveToContent - Skips over the following - ProcessingInstruction, DocumentType, Comment, Whitespace, or SignificantWhitespace //If the reader is currently at a content node then this function call is a no-op reader.MoveToContent(); // look for our root tag and namespace pair - ignore others in case of version changes // Make sure that the current node read is an Element if ((reader.NodeType == XmlNodeType.Element) && (reader.Depth == 0) && (String.CompareOrdinal(reader.NamespaceURI, s_typesNamespaceUri) == 0) && (String.CompareOrdinal(reader.Name, s_typesTagName) == 0)) { //There should be a namespace Attribute present at this level. //Also any other attribute on the <Types> tag is an error including xml: and xsi: attributes if (PackagingUtilities.GetNonXmlnsAttributeCount(reader) > 0) { throw new XmlException(SR.TypesTagHasExtraAttributes, null, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition); } // start tag encountered // now parse individual Default and Override tags while (reader.Read()) { //Skips over the following - ProcessingInstruction, DocumentType, Comment, Whitespace, or SignificantWhitespace //If the reader is currently at a content node then this function call is a no-op reader.MoveToContent(); //If MoveToContent() takes us to the end of the content if (reader.NodeType == XmlNodeType.None) continue; // Make sure that the current node read is an element // Currently we expect the Default and Override Tag at Depth 1 if (reader.NodeType == XmlNodeType.Element && reader.Depth == 1 && (String.CompareOrdinal(reader.NamespaceURI, s_typesNamespaceUri) == 0) && (String.CompareOrdinal(reader.Name, s_defaultTagName) == 0)) { ProcessDefaultTagAttributes(reader); } else if (reader.NodeType == XmlNodeType.Element && reader.Depth == 1 && (String.CompareOrdinal(reader.NamespaceURI, s_typesNamespaceUri) == 0) && (String.CompareOrdinal(reader.Name, s_overrideTagName) == 0)) { ProcessOverrideTagAttributes(reader); } else if (reader.NodeType == XmlNodeType.EndElement && reader.Depth == 0 && String.CompareOrdinal(reader.Name, s_typesTagName) == 0) continue; else { throw new XmlException(SR.TypesXmlDoesNotMatchSchema, null, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition); } } } else { throw new XmlException(SR.TypesElementExpected, null, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition); } } } /// <summary> /// Find the content type stream, allowing for interleaving. Naming collisions /// (as between an atomic and an interleaved part) will result in an exception being thrown. /// Return null if no content type stream has been found. /// </summary> /// <remarks> /// The input array is lexicographically sorted /// </remarks> private Stream OpenContentTypeStream(System.Collections.ObjectModel.ReadOnlyCollection<ZipArchiveEntry> zipFiles) { foreach (ZipArchiveEntry zipFileInfo in zipFiles) { if (zipFileInfo.Name.ToUpperInvariant().StartsWith(s_contentTypesFileUpperInvariant, StringComparison.Ordinal)) { // Atomic name. if (zipFileInfo.Name.Length == ContentTypeFileName.Length) { // Record the file info. _contentTypeZipArchiveEntry = zipFileInfo; } } } // If an atomic file was found, open a stream on it. if (_contentTypeZipArchiveEntry != null) { _contentTypeStreamExists = true; return _zipStreamManager.Open(_contentTypeZipArchiveEntry, _packageFileMode, FileAccess.ReadWrite); } // No content type stream was found. return null; } // Process the attributes for the Default tag private void ProcessDefaultTagAttributes(XmlReader reader) { //There could be a namespace Attribute present at this level. //Also any other attribute on the <Default> tag is an error including xml: and xsi: attributes if (PackagingUtilities.GetNonXmlnsAttributeCount(reader) != 2) throw new XmlException(SR.DefaultTagDoesNotMatchSchema, null, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition); // get the required Extension and ContentType attributes string extensionAttributeValue = reader.GetAttribute(s_extensionAttributeName); ValidateXmlAttribute(s_extensionAttributeName, extensionAttributeValue, s_defaultTagName, reader); string contentTypeAttributeValue = reader.GetAttribute(s_contentTypeAttributeName); ThrowIfXmlAttributeMissing(s_contentTypeAttributeName, contentTypeAttributeValue, s_defaultTagName, reader); // The extensions are stored in the Default Dictionary in their original form , but they are compared // in a normalized manner using the ExtensionComparer. PackUriHelper.ValidatedPartUri temporaryUri = PackUriHelper.ValidatePartUri( new Uri(s_temporaryPartNameWithoutExtension + extensionAttributeValue, UriKind.Relative)); _defaultDictionary.Add(temporaryUri.PartUriExtension, new ContentType(contentTypeAttributeValue)); //Skip the EndElement for Default Tag if (!reader.IsEmptyElement) ProcessEndElement(reader, s_defaultTagName); } // Process the attributes for the Default tag private void ProcessOverrideTagAttributes(XmlReader reader) { //There could be a namespace Attribute present at this level. //Also any other attribute on the <Override> tag is an error including xml: and xsi: attributes if (PackagingUtilities.GetNonXmlnsAttributeCount(reader) != 2) throw new XmlException(SR.OverrideTagDoesNotMatchSchema, null, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition); // get the required Extension and ContentType attributes string partNameAttributeValue = reader.GetAttribute(s_partNameAttributeName); ValidateXmlAttribute(s_partNameAttributeName, partNameAttributeValue, s_overrideTagName, reader); string contentTypeAttributeValue = reader.GetAttribute(s_contentTypeAttributeName); ThrowIfXmlAttributeMissing(s_contentTypeAttributeName, contentTypeAttributeValue, s_overrideTagName, reader); PackUriHelper.ValidatedPartUri partUri = PackUriHelper.ValidatePartUri(new Uri(partNameAttributeValue, UriKind.Relative)); //Lazy initializing - ensure that the override dictionary has been initialized EnsureOverrideDictionary(); // The part Uris are stored in the Override Dictionary in their original form , but they are compared // in a normalized manner using PartUriComparer. _overrideDictionary.Add(partUri, new ContentType(contentTypeAttributeValue)); //Skip the EndElement for Override Tag if (!reader.IsEmptyElement) ProcessEndElement(reader, s_overrideTagName); } //If End element is present for Relationship then we process it private void ProcessEndElement(XmlReader reader, string elementName) { Debug.Assert(!reader.IsEmptyElement, "This method should only be called it the Relationship Element is not empty"); reader.Read(); //Skips over the following - ProcessingInstruction, DocumentType, Comment, Whitespace, or SignificantWhitespace reader.MoveToContent(); if (reader.NodeType == XmlNodeType.EndElement && String.CompareOrdinal(elementName, reader.LocalName) == 0) return; else throw new XmlException(SR.Format(SR.ElementIsNotEmptyElement, elementName), null, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition); } private void AddOverrideElement(PackUriHelper.ValidatedPartUri partUri, ContentType contentType) { //Delete any entry corresponding in the Override dictionary //corresponding to the PartUri for which the contentType is being added. //This is to compensate for dead override entries in the content types file. DeleteContentType(partUri); //Lazy initializing - ensure that the override dictionary has been initialized EnsureOverrideDictionary(); // The part Uris are stored in the Override Dictionary in their original form , but they are compared // in a normalized manner using PartUriComparer. _overrideDictionary.Add(partUri, contentType); _dirty = true; } private void AddDefaultElement(string extension, ContentType contentType) { // The extensions are stored in the Default Dictionary in their original form , but they are compared // in a normalized manner using the ExtensionComparer. _defaultDictionary.Add(extension, contentType); _dirty = true; } private void WriteOverrideElement(XmlWriter xmlWriter, PackUriHelper.ValidatedPartUri partUri, ContentType contentType) { xmlWriter.WriteStartElement(s_overrideTagName); xmlWriter.WriteAttributeString(s_partNameAttributeName, partUri.PartUriString); xmlWriter.WriteAttributeString(s_contentTypeAttributeName, contentType.ToString()); xmlWriter.WriteEndElement(); } private void WriteDefaultElement(XmlWriter xmlWriter, string extension, ContentType contentType) { xmlWriter.WriteStartElement(s_defaultTagName); xmlWriter.WriteAttributeString(s_extensionAttributeName, extension); xmlWriter.WriteAttributeString(s_contentTypeAttributeName, contentType.ToString()); xmlWriter.WriteEndElement(); } //Validate if the required XML attribute is present and not an empty string private void ValidateXmlAttribute(string attributeName, string attributeValue, string tagName, XmlReader reader) { ThrowIfXmlAttributeMissing(attributeName, attributeValue, tagName, reader); //Checking for empty attribute if (attributeValue == String.Empty) throw new XmlException(SR.Format(SR.RequiredAttributeEmpty, tagName, attributeName), null, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition); } //Validate if the required Content type XML attribute is present //Content type of a part can be empty private void ThrowIfXmlAttributeMissing(string attributeName, string attributeValue, string tagName, XmlReader reader) { if (attributeValue == null) throw new XmlException(SR.Format(SR.RequiredAttributeMissing, tagName, attributeName), null, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition); } private Dictionary<PackUriHelper.ValidatedPartUri, ContentType> _overrideDictionary; private Dictionary<string, ContentType> _defaultDictionary; private ZipArchive _zipArchive; private FileMode _packageFileMode; private FileAccess _packageFileAccess; private ZipStreamManager _zipStreamManager; private ZipArchiveEntry _contentTypeZipArchiveEntry; private bool _contentTypeStreamExists; private bool _dirty; private CompressionLevel _cachedCompressionLevel; private static readonly string s_contentTypesFile = "[Content_Types].xml"; private static readonly string s_contentTypesFileUpperInvariant = "[CONTENT_TYPES].XML"; private static readonly int s_defaultDictionaryInitialSize = 16; private static readonly int s_overrideDictionaryInitialSize = 8; //Xml tag specific strings for the Content Type file private static readonly string s_typesNamespaceUri = "http://schemas.openxmlformats.org/package/2006/content-types"; private static readonly string s_typesTagName = "Types"; private static readonly string s_defaultTagName = "Default"; private static readonly string s_extensionAttributeName = "Extension"; private static readonly string s_contentTypeAttributeName = "ContentType"; private static readonly string s_overrideTagName = "Override"; private static readonly string s_partNameAttributeName = "PartName"; private static readonly string s_temporaryPartNameWithoutExtension = "/tempfiles/sample."; } } }
// 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.Globalization; using System.Text; using System.Runtime.InteropServices; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; namespace System { public partial class Uri { // // All public ctors go through here // private void CreateThis(string? uri, bool dontEscape, UriKind uriKind) { // if (!Enum.IsDefined(typeof(UriKind), uriKind)) -- We currently believe that Enum.IsDefined() is too slow // to be used here. if ((int)uriKind < (int)UriKind.RelativeOrAbsolute || (int)uriKind > (int)UriKind.Relative) { throw new ArgumentException(SR.Format(SR.net_uri_InvalidUriKind, uriKind)); } _string = uri == null ? string.Empty : uri; if (dontEscape) _flags |= Flags.UserEscaped; ParsingError err = ParseScheme(_string, ref _flags, ref _syntax!); UriFormatException? e; InitializeUri(err, uriKind, out e); if (e != null) throw e; } private void InitializeUri(ParsingError err, UriKind uriKind, out UriFormatException? e) { if (err == ParsingError.None) { if (IsImplicitFile) { // V1 compat // A relative Uri wins over implicit UNC path unless the UNC path is of the form "\\something" and // uriKind != Absolute // A relative Uri wins over implicit Unix path unless uriKind == Absolute if (NotAny(Flags.DosPath) && uriKind != UriKind.Absolute && ((uriKind == UriKind.Relative || (_string.Length >= 2 && (_string[0] != '\\' || _string[1] != '\\'))) || (!IsWindowsSystem && InFact(Flags.UnixPath)))) { _syntax = null!; //make it be relative Uri _flags &= Flags.UserEscaped; // the only flag that makes sense for a relative uri e = null; return; // Otherwise an absolute file Uri wins when it's of the form "\\something" } // // V1 compat issue // We should support relative Uris of the form c:\bla or c:/bla // else if (uriKind == UriKind.Relative && InFact(Flags.DosPath)) { _syntax = null!; //make it be relative Uri _flags &= Flags.UserEscaped; // the only flag that makes sense for a relative uri e = null; return; // Otherwise an absolute file Uri wins when it's of the form "c:\something" } } } else if (err > ParsingError.LastRelativeUriOkErrIndex) { //This is a fatal error based solely on scheme name parsing _string = null!; // make it be invalid Uri e = GetException(err); return; } bool hasUnicode = false; _iriParsing = (s_IriParsing && ((_syntax == null) || _syntax.InFact(UriSyntaxFlags.AllowIriParsing))); if (_iriParsing && (CheckForUnicode(_string) || CheckForEscapedUnreserved(_string))) { _flags |= Flags.HasUnicode; hasUnicode = true; // switch internal strings _originalUnicodeString = _string; // original string location changed } if (_syntax != null) { if (_syntax.IsSimple) { if ((err = PrivateParseMinimal()) != ParsingError.None) { if (uriKind != UriKind.Absolute && err <= ParsingError.LastRelativeUriOkErrIndex) { // RFC 3986 Section 5.4.2 - http:(relativeUri) may be considered a valid relative Uri. _syntax = null!; // convert to relative uri e = null; _flags &= Flags.UserEscaped; // the only flag that makes sense for a relative uri return; } else e = GetException(err); } else if (uriKind == UriKind.Relative) { // Here we know that we can create an absolute Uri, but the user has requested only a relative one e = GetException(ParsingError.CannotCreateRelative); } else e = null; // will return from here if (_iriParsing && hasUnicode) { // In this scenario we need to parse the whole string try { EnsureParseRemaining(); } catch (UriFormatException ex) { e = ex; return; } } } else { // offer custom parser to create a parsing context _syntax = _syntax.InternalOnNewUri(); // in case they won't call us _flags |= Flags.UserDrivenParsing; // Ask a registered type to validate this uri _syntax.InternalValidate(this, out e); if (e != null) { // Can we still take it as a relative Uri? if (uriKind != UriKind.Absolute && err != ParsingError.None && err <= ParsingError.LastRelativeUriOkErrIndex) { _syntax = null!; // convert it to relative e = null; _flags &= Flags.UserEscaped; // the only flag that makes sense for a relative uri } } else // e == null { if (err != ParsingError.None || InFact(Flags.ErrorOrParsingRecursion)) { // User parser took over on an invalid Uri SetUserDrivenParsing(); } else if (uriKind == UriKind.Relative) { // Here we know that custom parser can create an absolute Uri, but the user has requested only a // relative one e = GetException(ParsingError.CannotCreateRelative); } if (_iriParsing && hasUnicode) { // In this scenario we need to parse the whole string try { EnsureParseRemaining(); } catch (UriFormatException ex) { e = ex; return; } } } // will return from here } } // If we encountered any parsing errors that indicate this may be a relative Uri, // and we'll allow relative Uri's, then create one. else if (err != ParsingError.None && uriKind != UriKind.Absolute && err <= ParsingError.LastRelativeUriOkErrIndex) { e = null; _flags &= (Flags.UserEscaped | Flags.HasUnicode); // the only flags that makes sense for a relative uri if (_iriParsing && hasUnicode) { // Iri'ze and then normalize relative uris _string = EscapeUnescapeIri(_originalUnicodeString, 0, _originalUnicodeString.Length, (UriComponents)0); if (_string.Length > ushort.MaxValue) { err = ParsingError.SizeLimit; return; } } } else { _string = null!; // make it be invalid Uri e = GetException(err); } } // // Unescapes entire string and checks if it has unicode chars // private bool CheckForUnicode(string data) { for (int i = 0; i < data.Length; i++) { char c = data[i]; if (c == '%') { if (i + 2 < data.Length) { if (UriHelper.EscapedAscii(data[i + 1], data[i + 2]) > 0x7F) { return true; } i += 2; } } else if (c > 0x7F) { return true; } } return false; } // Does this string have any %6A sequences that are 3986 Unreserved characters? These should be un-escaped. private unsafe bool CheckForEscapedUnreserved(string data) { fixed (char* tempPtr = data) { for (int i = 0; i < data.Length - 2; ++i) { if (tempPtr[i] == '%' && IsHexDigit(tempPtr[i + 1]) && IsHexDigit(tempPtr[i + 2]) && tempPtr[i + 1] >= '0' && tempPtr[i + 1] <= '7') // max 0x7F { char ch = UriHelper.EscapedAscii(tempPtr[i + 1], tempPtr[i + 2]); if (ch != c_DummyChar && UriHelper.Is3986Unreserved(ch)) { return true; } } } } return false; } // // Returns true if the string represents a valid argument to the Uri ctor // If uriKind != AbsoluteUri then certain parsing errors are ignored but Uri usage is limited // public static bool TryCreate(string? uriString, UriKind uriKind, [NotNullWhen(true)] out Uri? result) { if ((object?)uriString == null) { result = null; return false; } UriFormatException? e = null; result = CreateHelper(uriString, false, uriKind, ref e); return (object?)e == null && result != null; } public static bool TryCreate(Uri? baseUri, string? relativeUri, [NotNullWhen(true)] out Uri? result) { Uri? relativeLink; if (TryCreate(relativeUri, UriKind.RelativeOrAbsolute, out relativeLink)) { if (!relativeLink.IsAbsoluteUri) return TryCreate(baseUri, relativeLink, out result); result = relativeLink; return true; } result = null; return false; } public static bool TryCreate(Uri? baseUri, Uri? relativeUri, [NotNullWhen(true)] out Uri? result) { result = null; if ((object?)baseUri == null || (object?)relativeUri == null) return false; if (baseUri.IsNotAbsoluteUri) return false; UriFormatException? e; string? newUriString = null; bool dontEscape; if (baseUri.Syntax.IsSimple) { dontEscape = relativeUri.UserEscaped; result = ResolveHelper(baseUri, relativeUri, ref newUriString, ref dontEscape, out e); } else { dontEscape = false; newUriString = baseUri.Syntax.InternalResolve(baseUri, relativeUri, out e); } if (e != null) return false; if ((object?)result == null) result = CreateHelper(newUriString!, dontEscape, UriKind.Absolute, ref e); return (object?)e == null && result != null && result.IsAbsoluteUri; } public string GetComponents(UriComponents components, UriFormat format) { if (((components & UriComponents.SerializationInfoString) != 0) && components != UriComponents.SerializationInfoString) throw new ArgumentOutOfRangeException(nameof(components), components, SR.net_uri_NotJustSerialization); if ((format & ~UriFormat.SafeUnescaped) != 0) throw new ArgumentOutOfRangeException(nameof(format)); if (IsNotAbsoluteUri) { if (components == UriComponents.SerializationInfoString) return GetRelativeSerializationString(format); else throw new InvalidOperationException(SR.net_uri_NotAbsolute); } if (Syntax.IsSimple) return GetComponentsHelper(components, format); return Syntax.InternalGetComponents(this, components, format); } // // This is for languages that do not support == != operators overloading // // Note that Uri.Equals will get an optimized path but is limited to true/false result only // public static int Compare(Uri? uri1, Uri? uri2, UriComponents partsToCompare, UriFormat compareFormat, StringComparison comparisonType) { if ((object?)uri1 == null) { if (uri2 == null) return 0; // Equal return -1; // null < non-null } if ((object?)uri2 == null) return 1; // non-null > null // a relative uri is always less than an absolute one if (!uri1.IsAbsoluteUri || !uri2.IsAbsoluteUri) return uri1.IsAbsoluteUri ? 1 : uri2.IsAbsoluteUri ? -1 : string.Compare(uri1.OriginalString, uri2.OriginalString, comparisonType); return string.Compare( uri1.GetParts(partsToCompare, compareFormat), uri2.GetParts(partsToCompare, compareFormat), comparisonType ); } public bool IsWellFormedOriginalString() { if (IsNotAbsoluteUri || Syntax.IsSimple) return InternalIsWellFormedOriginalString(); return Syntax.InternalIsWellFormedOriginalString(this); } public static bool IsWellFormedUriString(string? uriString, UriKind uriKind) { Uri? result; if (!Uri.TryCreate(uriString, uriKind, out result)) return false; return result.IsWellFormedOriginalString(); } // // Internal stuff // // Returns false if OriginalString value // (1) is not correctly escaped as per URI spec excluding intl UNC name case // (2) or is an absolute Uri that represents implicit file Uri "c:\dir\file" // (3) or is an absolute Uri that misses a slash before path "file://c:/dir/file" // (4) or contains unescaped backslashes even if they will be treated // as forward slashes like http:\\host/path\file or file:\\\c:\path // internal unsafe bool InternalIsWellFormedOriginalString() { if (UserDrivenParsing) throw new InvalidOperationException(SR.Format(SR.net_uri_UserDrivenParsing, this.GetType())); fixed (char* str = _string) { ushort idx = 0; // // For a relative Uri we only care about escaping and backslashes // if (!IsAbsoluteUri) { // my:scheme/path?query is not well formed because the colon is ambiguous if (CheckForColonInFirstPathSegment(_string)) { return false; } return (CheckCanonical(str, ref idx, (ushort)_string.Length, c_EOL) & (Check.BackslashInPath | Check.EscapedCanonical)) == Check.EscapedCanonical; } // // (2) or is an absolute Uri that represents implicit file Uri "c:\dir\file" // if (IsImplicitFile) return false; //This will get all the offsets, a Host name will be checked separately below EnsureParseRemaining(); Flags nonCanonical = (_flags & (Flags.E_CannotDisplayCanonical | Flags.IriCanonical)); // Cleanup canonical IRI from nonCanonical if ((nonCanonical & (Flags.UserIriCanonical | Flags.PathIriCanonical | Flags.QueryIriCanonical | Flags.FragmentIriCanonical)) != 0) { if ((nonCanonical & (Flags.E_UserNotCanonical | Flags.UserIriCanonical)) == (Flags.E_UserNotCanonical | Flags.UserIriCanonical)) { nonCanonical = nonCanonical & ~(Flags.E_UserNotCanonical | Flags.UserIriCanonical); } if ((nonCanonical & (Flags.E_PathNotCanonical | Flags.PathIriCanonical)) == (Flags.E_PathNotCanonical | Flags.PathIriCanonical)) { nonCanonical = nonCanonical & ~(Flags.E_PathNotCanonical | Flags.PathIriCanonical); } if ((nonCanonical & (Flags.E_QueryNotCanonical | Flags.QueryIriCanonical)) == (Flags.E_QueryNotCanonical | Flags.QueryIriCanonical)) { nonCanonical = nonCanonical & ~(Flags.E_QueryNotCanonical | Flags.QueryIriCanonical); } if ((nonCanonical & (Flags.E_FragmentNotCanonical | Flags.FragmentIriCanonical)) == (Flags.E_FragmentNotCanonical | Flags.FragmentIriCanonical)) { nonCanonical = nonCanonical & ~(Flags.E_FragmentNotCanonical | Flags.FragmentIriCanonical); } } // User, Path, Query or Fragment may have some non escaped characters if (((nonCanonical & Flags.E_CannotDisplayCanonical & (Flags.E_UserNotCanonical | Flags.E_PathNotCanonical | Flags.E_QueryNotCanonical | Flags.E_FragmentNotCanonical)) != Flags.Zero)) { return false; } // checking on scheme:\\ or file://// if (InFact(Flags.AuthorityFound)) { idx = (ushort)(_info.Offset.Scheme + _syntax.SchemeName.Length + 2); if (idx >= _info.Offset.User || _string[idx - 1] == '\\' || _string[idx] == '\\') return false; if (InFact(Flags.UncPath | Flags.DosPath)) { while (++idx < _info.Offset.User && (_string[idx] == '/' || _string[idx] == '\\')) return false; } } // (3) or is an absolute Uri that misses a slash before path "file://c:/dir/file" // Note that for this check to be more general we assert that if Path is non empty and if it requires a first slash // (which looks absent) then the method has to fail. // Today it's only possible for a Dos like path, i.e. file://c:/bla would fail below check. if (InFact(Flags.FirstSlashAbsent) && _info.Offset.Query > _info.Offset.Path) return false; // (4) or contains unescaped backslashes even if they will be treated // as forward slashes like http:\\host/path\file or file:\\\c:\path // Note we do not check for Flags.ShouldBeCompressed i.e. allow // /./ and alike as valid if (InFact(Flags.BackslashInPath)) return false; // Capturing a rare case like file:///c|/dir if (IsDosPath && _string[_info.Offset.Path + SecuredPathIndex - 1] == '|') return false; // // May need some real CPU processing to answer the request // // // Check escaping for authority // // IPv6 hosts cannot be properly validated by CheckCannonical if ((_flags & Flags.CanonicalDnsHost) == 0 && HostType != Flags.IPv6HostType) { idx = _info.Offset.User; Check result = CheckCanonical(str, ref idx, (ushort)_info.Offset.Path, '/'); if (((result & (Check.ReservedFound | Check.BackslashInPath | Check.EscapedCanonical)) != Check.EscapedCanonical) && (!_iriParsing || (_iriParsing && ((result & (Check.DisplayCanonical | Check.FoundNonAscii | Check.NotIriCanonical)) != (Check.DisplayCanonical | Check.FoundNonAscii))))) { return false; } } // Want to ensure there are slashes after the scheme if ((_flags & (Flags.SchemeNotCanonical | Flags.AuthorityFound)) == (Flags.SchemeNotCanonical | Flags.AuthorityFound)) { idx = (ushort)_syntax.SchemeName.Length; while (str[idx++] != ':') ; if (idx + 1 >= _string.Length || str[idx] != '/' || str[idx + 1] != '/') return false; } } // // May be scheme, host, port or path need some canonicalization but still the uri string is found to be a // "well formed" one // return true; } public static string UnescapeDataString(string stringToUnescape) { if ((object)stringToUnescape == null) throw new ArgumentNullException(nameof(stringToUnescape)); if (stringToUnescape.Length == 0) return string.Empty; unsafe { fixed (char* pStr = stringToUnescape) { int position; for (position = 0; position < stringToUnescape.Length; ++position) if (pStr[position] == '%') break; if (position == stringToUnescape.Length) return stringToUnescape; UnescapeMode unescapeMode = UnescapeMode.Unescape | UnescapeMode.UnescapeAll; position = 0; char[] dest = new char[stringToUnescape.Length]; dest = UriHelper.UnescapeString(stringToUnescape, 0, stringToUnescape.Length, dest, ref position, c_DummyChar, c_DummyChar, c_DummyChar, unescapeMode, null, false); return new string(dest, 0, position); } } } // // Where stringToEscape is intended to be a completely unescaped URI string. // This method will escape any character that is not a reserved or unreserved character, including percent signs. // Note that EscapeUriString will also do not escape a '#' sign. // public static string EscapeUriString(string stringToEscape) { if ((object)stringToEscape == null) throw new ArgumentNullException(nameof(stringToEscape)); if (stringToEscape.Length == 0) return string.Empty; int position = 0; char[]? dest = UriHelper.EscapeString(stringToEscape, 0, stringToEscape.Length, null, ref position, true, c_DummyChar, c_DummyChar, c_DummyChar); if ((object?)dest == null) return stringToEscape; return new string(dest, 0, position); } // // Where stringToEscape is intended to be URI data, but not an entire URI. // This method will escape any character that is not an unreserved character, including percent signs. // public static string EscapeDataString(string stringToEscape) { if ((object)stringToEscape == null) throw new ArgumentNullException(nameof(stringToEscape)); if (stringToEscape.Length == 0) return string.Empty; int position = 0; char[]? dest = UriHelper.EscapeString(stringToEscape, 0, stringToEscape.Length, null, ref position, false, c_DummyChar, c_DummyChar, c_DummyChar); if (dest == null) return stringToEscape; return new string(dest, 0, position); } // // Cleans up the specified component according to Iri rules // a) Chars allowed by iri in a component are unescaped if found escaped // b) Bidi chars are stripped // // should be called only if IRI parsing is switched on internal unsafe string EscapeUnescapeIri(string input, int start, int end, UriComponents component) { fixed (char* pInput = input) { return IriHelper.EscapeUnescapeIri(pInput, start, end, component); } } // Should never be used except by the below method private Uri(Flags flags, UriParser? uriParser, string uri) { _flags = flags; _syntax = uriParser!; _string = uri; } // // a Uri.TryCreate() method goes through here. // internal static Uri? CreateHelper(string uriString, bool dontEscape, UriKind uriKind, ref UriFormatException? e) { // if (!Enum.IsDefined(typeof(UriKind), uriKind)) -- We currently believe that Enum.IsDefined() is too slow // to be used here. if ((int)uriKind < (int)UriKind.RelativeOrAbsolute || (int)uriKind > (int)UriKind.Relative) { throw new ArgumentException(SR.Format(SR.net_uri_InvalidUriKind, uriKind)); } UriParser? syntax = null; Flags flags = Flags.Zero; ParsingError err = ParseScheme(uriString, ref flags, ref syntax); if (dontEscape) flags |= Flags.UserEscaped; // We won't use User factory for these errors if (err != ParsingError.None) { // If it looks as a relative Uri, custom factory is ignored if (uriKind != UriKind.Absolute && err <= ParsingError.LastRelativeUriOkErrIndex) return new Uri((flags & Flags.UserEscaped), null, uriString); return null; } // Cannot be relative Uri if came here Uri result = new Uri(flags, syntax, uriString); // Validate instance using ether built in or a user Parser try { result.InitializeUri(err, uriKind, out e); if (e == null) return result; return null; } catch (UriFormatException ee) { Debug.Assert(!syntax!.IsSimple, "A UriPraser threw on InitializeAndValidate."); e = ee; // A precaution since custom Parser should never throw in this case. return null; } } // // Resolves into either baseUri or relativeUri according to conditions OR if not possible it uses newUriString // to return combined URI strings from both Uris // otherwise if e != null on output the operation has failed // internal static Uri? ResolveHelper(Uri baseUri, Uri? relativeUri, ref string? newUriString, ref bool userEscaped, out UriFormatException? e) { Debug.Assert(!baseUri.IsNotAbsoluteUri && !baseUri.UserDrivenParsing, "Uri::ResolveHelper()|baseUri is not Absolute or is controlled by User Parser."); e = null; string relativeStr = string.Empty; if ((object?)relativeUri != null) { if (relativeUri.IsAbsoluteUri) return relativeUri; relativeStr = relativeUri.OriginalString; userEscaped = relativeUri.UserEscaped; } else relativeStr = string.Empty; // Here we can assert that passed "relativeUri" is indeed a relative one if (relativeStr.Length > 0 && (UriHelper.IsLWS(relativeStr[0]) || UriHelper.IsLWS(relativeStr[relativeStr.Length - 1]))) relativeStr = relativeStr.Trim(UriHelper.s_WSchars); if (relativeStr.Length == 0) { newUriString = baseUri.GetParts(UriComponents.AbsoluteUri, baseUri.UserEscaped ? UriFormat.UriEscaped : UriFormat.SafeUnescaped); return null; } // Check for a simple fragment in relative part if (relativeStr[0] == '#' && !baseUri.IsImplicitFile && baseUri.Syntax!.InFact(UriSyntaxFlags.MayHaveFragment)) { newUriString = baseUri.GetParts(UriComponents.AbsoluteUri & ~UriComponents.Fragment, UriFormat.UriEscaped) + relativeStr; return null; } // Check for a simple query in relative part if (relativeStr[0] == '?' && !baseUri.IsImplicitFile && baseUri.Syntax!.InFact(UriSyntaxFlags.MayHaveQuery)) { newUriString = baseUri.GetParts(UriComponents.AbsoluteUri & ~UriComponents.Query & ~UriComponents.Fragment, UriFormat.UriEscaped) + relativeStr; return null; } // Check on the DOS path in the relative Uri (a special case) if (relativeStr.Length >= 3 && (relativeStr[1] == ':' || relativeStr[1] == '|') && UriHelper.IsAsciiLetter(relativeStr[0]) && (relativeStr[2] == '\\' || relativeStr[2] == '/')) { if (baseUri.IsImplicitFile) { // It could have file:/// prepended to the result but we want to keep it as *Implicit* File Uri newUriString = relativeStr; return null; } else if (baseUri.Syntax!.InFact(UriSyntaxFlags.AllowDOSPath)) { // The scheme is not changed just the path gets replaced string prefix; if (baseUri.InFact(Flags.AuthorityFound)) prefix = baseUri.Syntax.InFact(UriSyntaxFlags.PathIsRooted) ? ":///" : "://"; else prefix = baseUri.Syntax.InFact(UriSyntaxFlags.PathIsRooted) ? ":/" : ":"; newUriString = baseUri.Scheme + prefix + relativeStr; return null; } // If we are here then input like "http://host/path/" + "C:\x" will produce the result http://host/path/c:/x } ParsingError err = GetCombinedString(baseUri, relativeStr, userEscaped, ref newUriString); if (err != ParsingError.None) { e = GetException(err); return null; } if ((object?)newUriString == (object)baseUri._string) return baseUri; return null; } private unsafe string GetRelativeSerializationString(UriFormat format) { if (format == UriFormat.UriEscaped) { if (_string.Length == 0) return string.Empty; int position = 0; char[]? dest = UriHelper.EscapeString(_string, 0, _string.Length, null, ref position, true, c_DummyChar, c_DummyChar, '%'); if ((object?)dest == null) return _string; return new string(dest, 0, position); } else if (format == UriFormat.Unescaped) return UnescapeDataString(_string); else if (format == UriFormat.SafeUnescaped) { if (_string.Length == 0) return string.Empty; char[] dest = new char[_string.Length]; int position = 0; dest = UriHelper.UnescapeString(_string, 0, _string.Length, dest, ref position, c_DummyChar, c_DummyChar, c_DummyChar, UnescapeMode.EscapeUnescape, null, false); return new string(dest, 0, position); } else throw new ArgumentOutOfRangeException(nameof(format)); } // // UriParser helpers methods // internal string GetComponentsHelper(UriComponents uriComponents, UriFormat uriFormat) { if (uriComponents == UriComponents.Scheme) return _syntax.SchemeName; // A serialization info is "almost" the same as AbsoluteUri except for IPv6 + ScopeID hostname case if ((uriComponents & UriComponents.SerializationInfoString) != 0) uriComponents |= UriComponents.AbsoluteUri; //This will get all the offsets, HostString will be created below if needed EnsureParseRemaining(); if ((uriComponents & UriComponents.NormalizedHost) != 0) { // Down the path we rely on Host to be ON for NormalizedHost uriComponents |= UriComponents.Host; } //Check to see if we need the host/authority string if ((uriComponents & UriComponents.Host) != 0) EnsureHostString(true); //This, single Port request is always processed here if (uriComponents == UriComponents.Port || uriComponents == UriComponents.StrongPort) { if (((_flags & Flags.NotDefaultPort) != 0) || (uriComponents == UriComponents.StrongPort && _syntax.DefaultPort != UriParser.NoDefaultPort)) { // recreate string from the port value return _info.Offset.PortValue.ToString(CultureInfo.InvariantCulture); } return string.Empty; } if ((uriComponents & UriComponents.StrongPort) != 0) { // Down the path we rely on Port to be ON for StrongPort uriComponents |= UriComponents.Port; } //This request sometime is faster to process here if (uriComponents == UriComponents.Host && (uriFormat == UriFormat.UriEscaped || ((_flags & (Flags.HostNotCanonical | Flags.E_HostNotCanonical)) == 0))) { EnsureHostString(false); return _info.Host!; } switch (uriFormat) { case UriFormat.UriEscaped: return GetEscapedParts(uriComponents); case V1ToStringUnescape: case UriFormat.SafeUnescaped: case UriFormat.Unescaped: return GetUnescapedParts(uriComponents, uriFormat); default: throw new ArgumentOutOfRangeException(nameof(uriFormat)); } } public bool IsBaseOf(Uri uri) { if ((object)uri == null) throw new ArgumentNullException(nameof(uri)); if (!IsAbsoluteUri) return false; if (Syntax.IsSimple) return IsBaseOfHelper(uri); return Syntax.InternalIsBaseOf(this, uri); } internal bool IsBaseOfHelper(Uri uriLink) { if (!IsAbsoluteUri || UserDrivenParsing) return false; if (!uriLink.IsAbsoluteUri) { //a relative uri could have quite tricky form, it's better to fix it now. string? newUriString = null; UriFormatException? e; bool dontEscape = false; uriLink = ResolveHelper(this, uriLink, ref newUriString, ref dontEscape, out e)!; if (e != null) return false; if ((object?)uriLink == null) uriLink = CreateHelper(newUriString!, dontEscape, UriKind.Absolute, ref e)!; if (e != null) return false; } if (Syntax.SchemeName != uriLink.Syntax.SchemeName) return false; // Canonicalize and test for substring match up to the last path slash string self = GetParts(UriComponents.AbsoluteUri & ~UriComponents.Fragment, UriFormat.SafeUnescaped); string other = uriLink.GetParts(UriComponents.AbsoluteUri & ~UriComponents.Fragment, UriFormat.SafeUnescaped); unsafe { fixed (char* selfPtr = self) { fixed (char* otherPtr = other) { return UriHelper.TestForSubPath(selfPtr, (ushort)self.Length, otherPtr, (ushort)other.Length, IsUncOrDosPath || uriLink.IsUncOrDosPath); } } } } // // Only a ctor time call // private void CreateThisFromUri(Uri otherUri) { // Clone the other guy but develop own UriInfo member _info = null!; _flags = otherUri._flags; if (InFact(Flags.MinimalUriInfoSet)) { _flags &= ~(Flags.MinimalUriInfoSet | Flags.AllUriInfoSet | Flags.IndexMask); // Port / Path offset int portIndex = otherUri._info.Offset.Path; if (InFact(Flags.NotDefaultPort)) { // Find the start of the port. Account for non-canonical ports like :00123 while (otherUri._string[portIndex] != ':' && portIndex > otherUri._info.Offset.Host) { portIndex--; } if (otherUri._string[portIndex] != ':') { // Something wrong with the NotDefaultPort flag. Reset to path index Debug.Fail("Uri failed to locate custom port at index: " + portIndex); portIndex = otherUri._info.Offset.Path; } } _flags |= (Flags)portIndex; // Port or path } _syntax = otherUri._syntax; _string = otherUri._string; _iriParsing = otherUri._iriParsing; if (otherUri.OriginalStringSwitched) { _originalUnicodeString = otherUri._originalUnicodeString; } if (otherUri.AllowIdn && (otherUri.InFact(Flags.IdnHost) || otherUri.InFact(Flags.UnicodeHost))) { _dnsSafeHost = otherUri._dnsSafeHost; } } } }
// Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Linq; using Microsoft.TemplateEngine.Abstractions; using Microsoft.TemplateEngine.Cli.CommandParsing; using Microsoft.TemplateEngine.Cli.UnitTests.CliMocks; using Microsoft.TemplateEngine.Edge.Settings; using Microsoft.TemplateEngine.Edge.Template; using Microsoft.TemplateEngine.Utils; using Xunit; namespace Microsoft.TemplateEngine.Cli.UnitTests { // Implementation notes: // If a test is going to hit the secondary matching in the resolver, make sure to initialize the Tags & CacheParameters, // otherwise an exception will be thrown in TemplateInfo.Parameters getter // MockNewCommandInput doesn't support everything in the interface, just enough for this type of testing. public class TemplateListResolverTests { [Fact(DisplayName = nameof(TestFindHighestPrecedenceTemplateIfAllSameGroupIdentity))] public void TestFindHighestPrecedenceTemplateIfAllSameGroupIdentity() { List<IFilteredTemplateInfo> templatesToCheck = new List<IFilteredTemplateInfo>(); templatesToCheck.Add(new FilteredTemplateInfo( new TemplateInfo() { Precedence = 10, Name = "Template1", Identity = "Template1", GroupIdentity = "TestGroup" } , null)); templatesToCheck.Add(new FilteredTemplateInfo( new TemplateInfo() { Precedence = 20, Name = "Template2", Identity = "Template2", GroupIdentity = "TestGroup" } , null)); templatesToCheck.Add(new FilteredTemplateInfo( new TemplateInfo() { Precedence = 0, Name = "Template3", Identity = "Template3", GroupIdentity = "TestGroup" } , null)); IFilteredTemplateInfo highestPrecedenceTemplate = TemplateListResolver.FindHighestPrecedenceTemplateIfAllSameGroupIdentity(templatesToCheck); Assert.NotNull(highestPrecedenceTemplate); Assert.Equal("Template2", highestPrecedenceTemplate.Info.Identity); Assert.Equal(20, highestPrecedenceTemplate.Info.Precedence); } [Fact(DisplayName = nameof(TestFindHighestPrecedenceTemplateIfAllSameGroupIdentity_ReturnsNullIfGroupsAreDifferent))] public void TestFindHighestPrecedenceTemplateIfAllSameGroupIdentity_ReturnsNullIfGroupsAreDifferent() { List<IFilteredTemplateInfo> templatesToCheck = new List<IFilteredTemplateInfo>(); templatesToCheck.Add(new FilteredTemplateInfo( new TemplateInfo() { Precedence = 10, Name = "Template1", Identity = "Template1", GroupIdentity = "TestGroup" } , null)); templatesToCheck.Add(new FilteredTemplateInfo( new TemplateInfo() { Precedence = 20, Name = "Template2", Identity = "Template2", GroupIdentity = "RealGroup" } , null)); IFilteredTemplateInfo highestPrecedenceTemplate = TemplateListResolver.FindHighestPrecedenceTemplateIfAllSameGroupIdentity(templatesToCheck); Assert.Null(highestPrecedenceTemplate); } [Fact(DisplayName = nameof(TestPerformAllTemplatesInContextQuery))] public void TestPerformAllTemplatesInContextQuery() { List<ITemplateInfo> templatesToSearch = new List<ITemplateInfo>(); templatesToSearch.Add(new TemplateInfo() { Name = "Template1", Identity = "Template1", Tags = new Dictionary<string, ICacheTag>(StringComparer.OrdinalIgnoreCase) { { "type", CreateTestCacheTag("project") } } }); templatesToSearch.Add(new TemplateInfo() { Name = "Template2", Identity = "Template2", Tags = new Dictionary<string, ICacheTag>(StringComparer.OrdinalIgnoreCase) { { "type", CreateTestCacheTag("item") } } }); templatesToSearch.Add(new TemplateInfo() { Name = "Template3", Identity = "Template3", Tags = new Dictionary<string, ICacheTag>(StringComparer.OrdinalIgnoreCase) { { "type", CreateTestCacheTag("myType") } } }); templatesToSearch.Add(new TemplateInfo() { Name = "Template4", Identity = "Template4", Tags = new Dictionary<string, ICacheTag>(StringComparer.OrdinalIgnoreCase) { { "type", CreateTestCacheTag("project") } } }); templatesToSearch.Add(new TemplateInfo() { Name = "Template5", Identity = "Template5", Tags = new Dictionary<string, ICacheTag>(StringComparer.OrdinalIgnoreCase) { { "type", CreateTestCacheTag("project") } } }); IHostSpecificDataLoader hostDataLoader = new MockHostSpecificDataLoader(); IReadOnlyCollection<IFilteredTemplateInfo> projectTemplates = TemplateListResolver.PerformAllTemplatesInContextQuery(templatesToSearch, hostDataLoader, "project"); Assert.Equal(3, projectTemplates.Count); Assert.True(projectTemplates.Where(x => string.Equals(x.Info.Identity, "Template1", StringComparison.Ordinal)).Any()); Assert.True(projectTemplates.Where(x => string.Equals(x.Info.Identity, "Template4", StringComparison.Ordinal)).Any()); Assert.True(projectTemplates.Where(x => string.Equals(x.Info.Identity, "Template5", StringComparison.Ordinal)).Any()); IReadOnlyCollection<IFilteredTemplateInfo> itemTemplates = TemplateListResolver.PerformAllTemplatesInContextQuery(templatesToSearch, hostDataLoader, "item"); Assert.Equal(1, itemTemplates.Count); Assert.True(itemTemplates.Where(x => string.Equals(x.Info.Identity, "Template2", StringComparison.Ordinal)).Any()); IReadOnlyCollection<IFilteredTemplateInfo> otherTemplates = TemplateListResolver.PerformAllTemplatesInContextQuery(templatesToSearch, hostDataLoader, "other"); Assert.Equal(1, otherTemplates.Count); Assert.True(otherTemplates.Where(x => string.Equals(x.Info.Identity, "Template3", StringComparison.Ordinal)).Any()); } [Fact(DisplayName = nameof(TestPerformCoreTemplateQuery_UniqueNameMatchesCorrectly))] public void TestPerformCoreTemplateQuery_UniqueNameMatchesCorrectly() { List<ITemplateInfo> templatesToSearch = new List<ITemplateInfo>(); templatesToSearch.Add(new TemplateInfo() { ShortName = "Template1", Name = "Long name of Template1", Identity = "Template1", }); templatesToSearch.Add(new TemplateInfo() { ShortName = "Template2", Name = "Long name of Template2", Identity = "Template2", }); INewCommandInput userInputs = new MockNewCommandInput() { TemplateName = "Template2" }; TemplateListResolutionResult matchResult = TemplateListResolver.PerformCoreTemplateQuery(templatesToSearch, new MockHostSpecificDataLoader(), userInputs, null); Assert.Equal(null, matchResult.MatchedTemplatesWithSecondaryMatchInfo); Assert.Equal(1, matchResult.CoreMatchedTemplates.Count); Assert.Equal(1, matchResult.UnambiguousTemplateGroupToUse.Count); Assert.Equal("Template2", matchResult.CoreMatchedTemplates[0].Info.Identity); Assert.Equal("Template2", matchResult.UnambiguousTemplateGroupToUse[0].Info.Identity); } [Fact(DisplayName = nameof(TestPerformCoreTemplateQuery_DefaultLanguageDisambiguates))] public void TestPerformCoreTemplateQuery_DefaultLanguageDisambiguates() { List<ITemplateInfo> templatesToSearch = new List<ITemplateInfo>(); templatesToSearch.Add(new TemplateInfo() { ShortName = "foo", Name = "Description of foo Perl template", Identity = "foo.test.Perl", GroupIdentity = "foo.test.template", Tags = new Dictionary<string, ICacheTag>(StringComparer.OrdinalIgnoreCase) { { "language", CreateTestCacheTag("Perl") } } }); templatesToSearch.Add(new TemplateInfo() { ShortName = "foo", Name = "Description of foo LISP template", Identity = "foo.test.Lisp", GroupIdentity = "foo.test.template", Tags = new Dictionary<string, ICacheTag>(StringComparer.OrdinalIgnoreCase) { { "language", CreateTestCacheTag("LISP") } } }); INewCommandInput userInputs = new MockNewCommandInput() { TemplateName = "foo" }; TemplateListResolutionResult matchResult = TemplateListResolver.PerformCoreTemplateQuery(templatesToSearch, new MockHostSpecificDataLoader(), userInputs, "Perl"); Assert.Equal(null, matchResult.MatchedTemplatesWithSecondaryMatchInfo); Assert.Equal(2, matchResult.CoreMatchedTemplates.Count); // they both match the initial query. Default language is secondary Assert.Equal(1, matchResult.UnambiguousTemplateGroupToUse.Count); Assert.Equal("foo.test.Perl", matchResult.UnambiguousTemplateGroupToUse[0].Info.Identity); } [Fact(DisplayName = nameof(TestPerformCoreTemplateQuery_InputLanguageIsPreferredOverDefault))] public void TestPerformCoreTemplateQuery_InputLanguageIsPreferredOverDefault() { List<ITemplateInfo> templatesToSearch = new List<ITemplateInfo>(); templatesToSearch.Add(new TemplateInfo() { ShortName = "foo", Name = "Description of foo Perl template", Identity = "foo.test.Perl", GroupIdentity = "foo.test.template", Tags = new Dictionary<string, ICacheTag>(StringComparer.OrdinalIgnoreCase) { { "language", CreateTestCacheTag("Perl") } } }); templatesToSearch.Add(new TemplateInfo() { ShortName = "foo", Name = "Description of foo LISP template", Identity = "foo.test.Lisp", GroupIdentity = "foo.test.template", Tags = new Dictionary<string, ICacheTag>(StringComparer.OrdinalIgnoreCase) { { "language", CreateTestCacheTag("LISP") } } }); INewCommandInput userInputs = new MockNewCommandInput() { TemplateName = "foo", Language = "LISP" }; TemplateListResolutionResult matchResult = TemplateListResolver.PerformCoreTemplateQuery(templatesToSearch, new MockHostSpecificDataLoader(), userInputs, "Perl"); Assert.Equal(null, matchResult.MatchedTemplatesWithSecondaryMatchInfo); Assert.Equal(1, matchResult.CoreMatchedTemplates.Count); // Input language is part of the initial checks. Assert.Equal(1, matchResult.UnambiguousTemplateGroupToUse.Count); Assert.Equal("foo.test.Lisp", matchResult.UnambiguousTemplateGroupToUse[0].Info.Identity); } [Fact(DisplayName = nameof(TestPerformCoreTemplateQuery_GroupIsFound))] public void TestPerformCoreTemplateQuery_GroupIsFound() { List<ITemplateInfo> templatesToSearch = new List<ITemplateInfo>(); templatesToSearch.Add(new TemplateInfo() { ShortName = "foo", Name = "Foo template old", Identity = "foo.test.old", GroupIdentity = "foo.test.template", Precedence = 100 }); templatesToSearch.Add(new TemplateInfo() { ShortName = "foo", Name = "Foo template new", Identity = "foo.test.new", GroupIdentity = "foo.test.template", Precedence = 200 }); templatesToSearch.Add(new TemplateInfo() { ShortName = "bar", Name = "Bar template", Identity = "bar.test", GroupIdentity = "bar.test.template", Precedence = 100 }); INewCommandInput userInputs = new MockNewCommandInput() { TemplateName = "foo" }; TemplateListResolutionResult matchResult = TemplateListResolver.PerformCoreTemplateQuery(templatesToSearch, new MockHostSpecificDataLoader(), userInputs, null); Assert.Equal(2, matchResult.MatchedTemplatesWithSecondaryMatchInfo.Count); Assert.Equal(2, matchResult.CoreMatchedTemplates.Count); Assert.Equal(2, matchResult.UnambiguousTemplateGroupToUse.Count); Assert.True(matchResult.UnambiguousTemplateGroupToUse.Any(x => string.Equals(x.Info.Identity, "foo.test.old"))); Assert.True(matchResult.UnambiguousTemplateGroupToUse.Any(x => string.Equals(x.Info.Identity, "foo.test.new"))); } [Fact(DisplayName = nameof(TestPerformCoreTemplateQuery_ParameterNameDisambiguates))] public void TestPerformCoreTemplateQuery_ParameterNameDisambiguates() { List<ITemplateInfo> templatesToSearch = new List<ITemplateInfo>(); templatesToSearch.Add(new TemplateInfo() { ShortName = "foo", Name = "Foo template", Identity = "foo.test.old", GroupIdentity = "foo.test.template", Tags = new Dictionary<string, ICacheTag>(StringComparer.OrdinalIgnoreCase), CacheParameters = new Dictionary<string, ICacheParameter>(StringComparer.OrdinalIgnoreCase) { { "bar", new CacheParameter() }, } }); templatesToSearch.Add(new TemplateInfo() { ShortName = "foo", Name = "Foo template", Identity = "foo.test.new", GroupIdentity = "foo.test.template", Tags = new Dictionary<string, ICacheTag>(StringComparer.OrdinalIgnoreCase), CacheParameters = new Dictionary<string, ICacheParameter>(StringComparer.OrdinalIgnoreCase) { { "baz", new CacheParameter() }, } }); INewCommandInput userInputs = new MockNewCommandInput( new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase) { { "baz", "whatever" } } ) { TemplateName = "foo" }; TemplateListResolutionResult matchResult = TemplateListResolver.PerformCoreTemplateQuery(templatesToSearch, new MockHostSpecificDataLoader(), userInputs, null); Assert.Equal(2, matchResult.MatchedTemplatesWithSecondaryMatchInfo.Count); Assert.Equal(1, matchResult.UnambiguousTemplateGroupToUse.Count); Assert.Equal("foo.test.new", matchResult.UnambiguousTemplateGroupToUse[0].Info.Identity); } [Fact(DisplayName = nameof(TestPerformCoreTemplateQuery_ParameterValueDisambiguates))] public void TestPerformCoreTemplateQuery_ParameterValueDisambiguates() { List<ITemplateInfo> templatesToSearch = new List<ITemplateInfo>(); templatesToSearch.Add(new TemplateInfo() { ShortName = "foo", Name = "Foo template old", Identity = "foo.test.old", GroupIdentity = "foo.test.template", Precedence = 100, Tags = new Dictionary<string, ICacheTag>(StringComparer.OrdinalIgnoreCase) { { "framework", CreateTestCacheTag(new List<string>() { "netcoreapp1.0", "netcoreapp1.1" }) } }, CacheParameters = new Dictionary<string, ICacheParameter>() }); templatesToSearch.Add(new TemplateInfo() { ShortName = "foo", Name = "Foo template new", Identity = "foo.test.new", GroupIdentity = "foo.test.template", Precedence = 200, Tags = new Dictionary<string, ICacheTag>(StringComparer.OrdinalIgnoreCase) { { "framework", CreateTestCacheTag(new List<string>() { "netcoreapp2.0" }) } }, CacheParameters = new Dictionary<string, ICacheParameter>() }); INewCommandInput userInputs = new MockNewCommandInput( new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase) { { "framework", "netcoreapp1.0" } } ) { TemplateName = "foo" }; TemplateListResolutionResult matchResult = TemplateListResolver.PerformCoreTemplateQuery(templatesToSearch, new MockHostSpecificDataLoader(), userInputs, null); Assert.Equal(2, matchResult.MatchedTemplatesWithSecondaryMatchInfo.Count); Assert.Equal(1, matchResult.UnambiguousTemplateGroupToUse.Count); Assert.Equal("foo.test.old", matchResult.UnambiguousTemplateGroupToUse[0].Info.Identity); } [Fact(DisplayName = nameof(TestPerformCoreTemplateQuery_UnknownParameterNameInvalidatesMatch))] public void TestPerformCoreTemplateQuery_UnknownParameterNameInvalidatesMatch() { List<ITemplateInfo> templatesToSearch = new List<ITemplateInfo>(); templatesToSearch.Add(new TemplateInfo() { ShortName = "foo", Name = "Foo template", Identity = "foo.test", GroupIdentity = "foo.test.template", Precedence = 100, Tags = new Dictionary<string, ICacheTag>(StringComparer.OrdinalIgnoreCase), CacheParameters = new Dictionary<string, ICacheParameter>() { { "bar", new CacheParameter() }, } }); INewCommandInput userInputs = new MockNewCommandInput( new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase) { { "baz", null } } ) { TemplateName = "foo" }; IHostSpecificDataLoader hostSpecificDataLoader = new MockHostSpecificDataLoader(); TemplateListResolutionResult matchResult = TemplateListResolver.PerformCoreTemplateQuery(templatesToSearch, hostSpecificDataLoader, userInputs, null); Assert.Equal(null, matchResult.MatchedTemplatesWithSecondaryMatchInfo); Assert.Equal(1, matchResult.UnambiguousTemplateGroupToUse.Count); // TODO: // These 2 lines are the analogues of what happens in New3Command.EnterSingularTemplateManipulationFlowAsync() // as a final verification for the template. // This is really a shortcoming of the resolver, this check should get factored into it. // But we'll need to add a new match category so we know that the unambiguous template "matched", except the extra user parameters. HostSpecificTemplateData hostTemplateData = hostSpecificDataLoader.ReadHostSpecificTemplateData(matchResult.UnambiguousTemplateGroupToUse[0].Info); userInputs.ReparseForTemplate(matchResult.UnambiguousTemplateGroupToUse[0].Info, hostTemplateData); Assert.False(TemplateListResolver.ValidateRemainingParameters(userInputs, out IReadOnlyList<string> invalidParams)); Assert.Equal(1, invalidParams.Count); Assert.Equal("baz", invalidParams[0]); } [Fact(DisplayName = nameof(TestPerformCoreTemplateQuery_InvalidChoiceValueInvalidatesMatch))] public void TestPerformCoreTemplateQuery_InvalidChoiceValueInvalidatesMatch() { List<ITemplateInfo> templatesToSearch = new List<ITemplateInfo>(); templatesToSearch.Add(new TemplateInfo() { ShortName = "foo", Name = "Foo template", Identity = "foo.test.1x", GroupIdentity = "foo.test.template", Precedence = 100, Tags = new Dictionary<string, ICacheTag>(StringComparer.OrdinalIgnoreCase) { { "framework", CreateTestCacheTag(new List<string>() { "netcoreapp1.0", "netcoreapp1.1" }) } }, CacheParameters = new Dictionary<string, ICacheParameter>() }); templatesToSearch.Add(new TemplateInfo() { ShortName = "foo", Name = "Foo template", Identity = "foo.test.2x", GroupIdentity = "foo.test.template", Precedence = 200, Tags = new Dictionary<string, ICacheTag>(StringComparer.OrdinalIgnoreCase) { { "framework", CreateTestCacheTag(new List<string>() { "netcoreapp2.0" }) } }, CacheParameters = new Dictionary<string, ICacheParameter>() }); INewCommandInput userInputs = new MockNewCommandInput( new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase) { { "framework", "netcoreapp3.0" } } ) { TemplateName = "foo" }; IHostSpecificDataLoader hostSpecificDataLoader = new MockHostSpecificDataLoader(); TemplateListResolutionResult matchResult = TemplateListResolver.PerformCoreTemplateQuery(templatesToSearch, hostSpecificDataLoader, userInputs, null); Assert.Equal(2, matchResult.MatchedTemplatesWithSecondaryMatchInfo.Count); Assert.Equal(2, matchResult.UnambiguousTemplateGroupToUse.Count); Assert.Equal(2, matchResult.CoreMatchedTemplates.Count); Assert.True(matchResult.UnambiguousTemplateGroupToUse[0].MatchDisposition.Any(x => x.Kind == MatchKind.InvalidParameterValue)); Assert.True(matchResult.UnambiguousTemplateGroupToUse[1].MatchDisposition.Any(x => x.Kind == MatchKind.InvalidParameterValue)); } private static ICacheTag CreateTestCacheTag(string choice, string description = null, string defaultValue = null) { return new CacheTag(null, new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase) { { choice, description } }, defaultValue); } private static ICacheTag CreateTestCacheTag(IReadOnlyList<string> choiceList, string description = null, string defaultValue = null) { Dictionary<string, string> choicesDict = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); foreach(string choice in choiceList) { choicesDict.Add(choice, null); }; return new CacheTag(null, choicesDict, defaultValue); } } }
/* Copyright 2013 Esri Licensed under the Apache License, Version 2.0 (the "License"); You may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.Net; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Ink; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Shapes; namespace ESRI.ArcGIS.SilverlightMapApp { /// <summary> /// Draggable Window Panel /// </summary> [TemplateVisualState(Name = "Opened", GroupName = "CommonStates")] [TemplateVisualState(Name = "Closed", GroupName = "CommonStates")] public class WindowPanel : ContentControl { private bool isTrackingMouse = false; private Point mouseOffset; private UIElement WidgetContent; private TranslateTransform renderTransform; /// <summary> /// Initializes a new instance of the <see cref="WindowPanel"/> class. /// </summary> public WindowPanel() { DefaultStyleKey = typeof(WindowPanel); } /// <summary> /// When overridden in a derived class, is invoked whenever application /// code or internal processes (such as a rebuilding layout pass) call /// <see cref="M:System.Windows.Controls.Control.ApplyTemplate"/>. /// In simplest terms, this means the method is called just before a UI /// element displays in an application. For more information, see Remarks. /// </summary> public override void OnApplyTemplate() { base.OnApplyTemplate(); WidgetContent = GetTemplateChild("WidgetContent") as UIElement; this.RenderTransform = renderTransform = new TranslateTransform(); UIElement headerDragRectangle = GetTemplateChild("headerDragRectangle") as UIElement; UIElement imgClose = GetTemplateChild("imgClose") as UIElement; if (headerDragRectangle != null) { headerDragRectangle.MouseLeftButtonDown += headerDragRectangle_MouseLeftButtonDown; headerDragRectangle.MouseLeftButtonUp += headerDragRectangle_MouseLeftButtonUp; headerDragRectangle.MouseMove += headerDragRectangle_MouseMove; } if (imgClose != null) imgClose.MouseLeftButtonDown += imgClose_MouseLeftButtonDown; ChangeVisualState(false); } #region Properties /// <summary> /// Gets or sets a value indicating whether this control is visible. /// </summary> /// <value> /// <c>true</c> if this instance is visible; otherwise, <c>false</c>. /// </value> public bool IsOpen { get { return (bool)GetValue(IsOpenProperty); } set { SetValue(IsOpenProperty, value); } } /// <summary> /// Identifies the <see cref="ContentTitle"/> dependency property. /// </summary> public static readonly DependencyProperty IsOpenProperty = DependencyProperty.Register("IsOpen", typeof(bool), typeof(WindowPanel), new PropertyMetadata(true, OnIsOpenPropertyChanged)); private static void OnIsOpenPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { WindowPanel panel = d as WindowPanel; panel.ChangeVisualState(true); } /// <summary> /// Gets or sets a value indicating whether this instance is expanded. /// </summary> /// <value> /// <c>true</c> if this instance is expanded; otherwise, <c>false</c>. /// </value> public bool IsExpanded { get { return WidgetContent.Visibility == Visibility.Visible; } set { if (value == true) WidgetContent.Visibility = Visibility.Visible; else WidgetContent.Visibility = Visibility.Collapsed; } } /// <summary> /// Gets or sets the content title. /// </summary> public object ContentTitle { get { return (object)GetValue(ContentTitleProperty); } set { SetValue(ContentTitleProperty, value); } } /// <summary> /// Identifies the <see cref="ContentTitle"/> dependency property. /// </summary> public static readonly DependencyProperty ContentTitleProperty = DependencyProperty.Register("ContentTitle", typeof(object), typeof(WindowPanel), null); #endregion /// <summary> /// Hides the window. /// </summary> private void ChangeVisualState(bool useTransitions) { if(IsOpen || System.ComponentModel.DesignerProperties.IsInDesignTool) VisualStateManager.GoToState(this, "Opened", useTransitions); else VisualStateManager.GoToState(this, "Closed", useTransitions); } #region Public Methods /// <summary> /// Toggles this show/hide state. /// </summary> public void Toggle() { IsOpen = !IsOpen; } #endregion #region Event Handlers for dragging the window /// <summary> /// Handles the MouseLeftButtonDown event of the imgClose control /// and collapses the control /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.Windows.Input.MouseButtonEventArgs"/> /// instance containing the event data.</param> private void imgClose_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) { IsOpen = false; } /// <summary> /// Handles the MouseLeftButtonDown event of the headerDragRectangle control. /// This is fired when the user starts to drag the window. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.Windows.Input.MouseButtonEventArgs"/> /// instance containing the event data.</param> private void headerDragRectangle_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) { Rectangle rect = sender as Rectangle; mouseOffset = e.GetPosition(null); rect.CaptureMouse(); isTrackingMouse = true; } /// <summary> /// Handles the MouseLeftButtonUp event of the headerDragRectangle control. /// This is fired when the user stopped dragging the window. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.Windows.Input.MouseButtonEventArgs"/> /// instance containing the event data.</param> private void headerDragRectangle_MouseLeftButtonUp(object sender, MouseButtonEventArgs e) { Rectangle rect = sender as Rectangle; rect.ReleaseMouseCapture(); isTrackingMouse = false; } /// <summary> /// Handles the MouseMove event of the headerDragRectangle control. /// This is fired when the user is dragging the window. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.Windows.Input.MouseEventArgs"/> /// instance containing the event data.</param> private void headerDragRectangle_MouseMove(object sender, MouseEventArgs e) { if (isTrackingMouse) { Rectangle rect = sender as Rectangle; Point point = e.GetPosition(null); double x0 = this.renderTransform.X; double y0 = this.renderTransform.Y; double sign = 1; if (FlowDirection == System.Windows.FlowDirection.RightToLeft) sign = -1; this.renderTransform.X = x0 + (point.X - mouseOffset.X) * sign; this.renderTransform.Y = y0 + point.Y - mouseOffset.Y; mouseOffset = point; } } #endregion } }
// 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.Diagnostics; using System.IO; using System.Linq; using JetBrains.Annotations; using osu.Framework.Audio.Sample; using osu.Framework.Bindables; using osu.Framework.Graphics; using osu.Framework.Graphics.OpenGL.Textures; using osu.Framework.Graphics.Textures; using osu.Framework.IO.Stores; using osu.Game.Audio; using osu.Game.Beatmaps.Formats; using osu.Game.IO; using osu.Game.Rulesets.Objects.Types; using osu.Game.Rulesets.Scoring; using osu.Game.Screens.Play; using osu.Game.Screens.Play.HUD; using osu.Game.Screens.Play.HUD.HitErrorMeters; using osuTK.Graphics; namespace osu.Game.Skinning { public class LegacySkin : Skin { [CanBeNull] protected TextureStore Textures; [CanBeNull] protected ISampleStore Samples; /// <summary> /// Whether texture for the keys exists. /// Used to determine if the mania ruleset is skinned. /// </summary> private readonly Lazy<bool> hasKeyTexture; protected virtual bool AllowManiaSkin => hasKeyTexture.Value; /// <summary> /// Whether this skin can use samples with a custom bank (custom sample set in stable terminology). /// Added in order to match sample lookup logic from stable (in stable, only the beatmap skin could use samples with a custom sample bank). /// </summary> protected virtual bool UseCustomSampleBanks => false; public new LegacySkinConfiguration Configuration { get => base.Configuration as LegacySkinConfiguration; set => base.Configuration = value; } private readonly Dictionary<int, LegacyManiaSkinConfiguration> maniaConfigurations = new Dictionary<int, LegacyManiaSkinConfiguration>(); [UsedImplicitly(ImplicitUseKindFlags.InstantiatedWithFixedConstructorSignature)] public LegacySkin(SkinInfo skin, IStorageResourceProvider resources) : this(skin, new LegacySkinResourceStore<SkinFileInfo>(skin, resources.Files), resources, "skin.ini") { } /// <summary> /// Construct a new legacy skin instance. /// </summary> /// <param name="skin">The model for this skin.</param> /// <param name="storage">A storage for looking up files within this skin using user-facing filenames.</param> /// <param name="resources">Access to raw game resources.</param> /// <param name="configurationFilename">The user-facing filename of the configuration file to be parsed. Can accept an .osu or skin.ini file.</param> protected LegacySkin(SkinInfo skin, [CanBeNull] IResourceStore<byte[]> storage, [CanBeNull] IStorageResourceProvider resources, string configurationFilename) : base(skin, resources) { using (var stream = storage?.GetStream(configurationFilename)) { if (stream != null) { using (LineBufferedReader reader = new LineBufferedReader(stream, true)) Configuration = new LegacySkinDecoder().Decode(reader); stream.Seek(0, SeekOrigin.Begin); using (LineBufferedReader reader = new LineBufferedReader(stream)) { var maniaList = new LegacyManiaSkinDecoder().Decode(reader); foreach (var config in maniaList) maniaConfigurations[config.Keys] = config; } } else Configuration = new LegacySkinConfiguration(); } if (storage != null) { var samples = resources?.AudioManager?.GetSampleStore(storage); if (samples != null) samples.PlaybackConcurrency = OsuGameBase.SAMPLE_CONCURRENCY; Samples = samples; Textures = new TextureStore(resources?.CreateTextureLoaderStore(storage)); (storage as ResourceStore<byte[]>)?.AddExtension("ogg"); } // todo: this shouldn't really be duplicated here (from ManiaLegacySkinTransformer). we need to come up with a better solution. hasKeyTexture = new Lazy<bool>(() => this.GetAnimation( lookupForMania<string>(new LegacyManiaSkinConfigurationLookup(4, LegacyManiaSkinConfigurationLookups.KeyImage, 0))?.Value ?? "mania-key1", true, true) != null); } public override IBindable<TValue> GetConfig<TLookup, TValue>(TLookup lookup) { switch (lookup) { case GlobalSkinColours colour: switch (colour) { case GlobalSkinColours.ComboColours: var comboColours = Configuration.ComboColours; if (comboColours != null) return SkinUtils.As<TValue>(new Bindable<IReadOnlyList<Color4>>(comboColours)); break; default: return SkinUtils.As<TValue>(getCustomColour(Configuration, colour.ToString())); } break; case SkinComboColourLookup comboColour: return SkinUtils.As<TValue>(GetComboColour(Configuration, comboColour.ColourIndex, comboColour.Combo)); case SkinCustomColourLookup customColour: return SkinUtils.As<TValue>(getCustomColour(Configuration, customColour.Lookup.ToString())); case LegacyManiaSkinConfigurationLookup maniaLookup: if (!AllowManiaSkin) break; var result = lookupForMania<TValue>(maniaLookup); if (result != null) return result; break; case LegacySkinConfiguration.LegacySetting legacy: return legacySettingLookup<TValue>(legacy); default: return genericLookup<TLookup, TValue>(lookup); } return null; } private IBindable<TValue> lookupForMania<TValue>(LegacyManiaSkinConfigurationLookup maniaLookup) { if (!maniaConfigurations.TryGetValue(maniaLookup.Keys, out var existing)) maniaConfigurations[maniaLookup.Keys] = existing = new LegacyManiaSkinConfiguration(maniaLookup.Keys); switch (maniaLookup.Lookup) { case LegacyManiaSkinConfigurationLookups.ColumnWidth: Debug.Assert(maniaLookup.TargetColumn != null); return SkinUtils.As<TValue>(new Bindable<float>(existing.ColumnWidth[maniaLookup.TargetColumn.Value])); case LegacyManiaSkinConfigurationLookups.ColumnSpacing: Debug.Assert(maniaLookup.TargetColumn != null); return SkinUtils.As<TValue>(new Bindable<float>(existing.ColumnSpacing[maniaLookup.TargetColumn.Value])); case LegacyManiaSkinConfigurationLookups.HitPosition: return SkinUtils.As<TValue>(new Bindable<float>(existing.HitPosition)); case LegacyManiaSkinConfigurationLookups.ScorePosition: return SkinUtils.As<TValue>(new Bindable<float>(existing.ScorePosition)); case LegacyManiaSkinConfigurationLookups.LightPosition: return SkinUtils.As<TValue>(new Bindable<float>(existing.LightPosition)); case LegacyManiaSkinConfigurationLookups.ShowJudgementLine: return SkinUtils.As<TValue>(new Bindable<bool>(existing.ShowJudgementLine)); case LegacyManiaSkinConfigurationLookups.ExplosionImage: return SkinUtils.As<TValue>(getManiaImage(existing, "LightingN")); case LegacyManiaSkinConfigurationLookups.ExplosionScale: Debug.Assert(maniaLookup.TargetColumn != null); if (GetConfig<LegacySkinConfiguration.LegacySetting, decimal>(LegacySkinConfiguration.LegacySetting.Version)?.Value < 2.5m) return SkinUtils.As<TValue>(new Bindable<float>(1)); if (existing.ExplosionWidth[maniaLookup.TargetColumn.Value] != 0) return SkinUtils.As<TValue>(new Bindable<float>(existing.ExplosionWidth[maniaLookup.TargetColumn.Value] / LegacyManiaSkinConfiguration.DEFAULT_COLUMN_SIZE)); return SkinUtils.As<TValue>(new Bindable<float>(existing.ColumnWidth[maniaLookup.TargetColumn.Value] / LegacyManiaSkinConfiguration.DEFAULT_COLUMN_SIZE)); case LegacyManiaSkinConfigurationLookups.ColumnLineColour: return SkinUtils.As<TValue>(getCustomColour(existing, "ColourColumnLine")); case LegacyManiaSkinConfigurationLookups.JudgementLineColour: return SkinUtils.As<TValue>(getCustomColour(existing, "ColourJudgementLine")); case LegacyManiaSkinConfigurationLookups.ColumnBackgroundColour: Debug.Assert(maniaLookup.TargetColumn != null); return SkinUtils.As<TValue>(getCustomColour(existing, $"Colour{maniaLookup.TargetColumn + 1}")); case LegacyManiaSkinConfigurationLookups.ColumnLightColour: Debug.Assert(maniaLookup.TargetColumn != null); return SkinUtils.As<TValue>(getCustomColour(existing, $"ColourLight{maniaLookup.TargetColumn + 1}")); case LegacyManiaSkinConfigurationLookups.MinimumColumnWidth: return SkinUtils.As<TValue>(new Bindable<float>(existing.MinimumColumnWidth)); case LegacyManiaSkinConfigurationLookups.NoteImage: Debug.Assert(maniaLookup.TargetColumn != null); return SkinUtils.As<TValue>(getManiaImage(existing, $"NoteImage{maniaLookup.TargetColumn}")); case LegacyManiaSkinConfigurationLookups.HoldNoteHeadImage: Debug.Assert(maniaLookup.TargetColumn != null); return SkinUtils.As<TValue>(getManiaImage(existing, $"NoteImage{maniaLookup.TargetColumn}H")); case LegacyManiaSkinConfigurationLookups.HoldNoteTailImage: Debug.Assert(maniaLookup.TargetColumn != null); return SkinUtils.As<TValue>(getManiaImage(existing, $"NoteImage{maniaLookup.TargetColumn}T")); case LegacyManiaSkinConfigurationLookups.HoldNoteBodyImage: Debug.Assert(maniaLookup.TargetColumn != null); return SkinUtils.As<TValue>(getManiaImage(existing, $"NoteImage{maniaLookup.TargetColumn}L")); case LegacyManiaSkinConfigurationLookups.HoldNoteLightImage: return SkinUtils.As<TValue>(getManiaImage(existing, "LightingL")); case LegacyManiaSkinConfigurationLookups.HoldNoteLightScale: Debug.Assert(maniaLookup.TargetColumn != null); if (GetConfig<LegacySkinConfiguration.LegacySetting, decimal>(LegacySkinConfiguration.LegacySetting.Version)?.Value < 2.5m) return SkinUtils.As<TValue>(new Bindable<float>(1)); if (existing.HoldNoteLightWidth[maniaLookup.TargetColumn.Value] != 0) return SkinUtils.As<TValue>(new Bindable<float>(existing.HoldNoteLightWidth[maniaLookup.TargetColumn.Value] / LegacyManiaSkinConfiguration.DEFAULT_COLUMN_SIZE)); return SkinUtils.As<TValue>(new Bindable<float>(existing.ColumnWidth[maniaLookup.TargetColumn.Value] / LegacyManiaSkinConfiguration.DEFAULT_COLUMN_SIZE)); case LegacyManiaSkinConfigurationLookups.KeyImage: Debug.Assert(maniaLookup.TargetColumn != null); return SkinUtils.As<TValue>(getManiaImage(existing, $"KeyImage{maniaLookup.TargetColumn}")); case LegacyManiaSkinConfigurationLookups.KeyImageDown: Debug.Assert(maniaLookup.TargetColumn != null); return SkinUtils.As<TValue>(getManiaImage(existing, $"KeyImage{maniaLookup.TargetColumn}D")); case LegacyManiaSkinConfigurationLookups.LeftStageImage: return SkinUtils.As<TValue>(getManiaImage(existing, "StageLeft")); case LegacyManiaSkinConfigurationLookups.RightStageImage: return SkinUtils.As<TValue>(getManiaImage(existing, "StageRight")); case LegacyManiaSkinConfigurationLookups.BottomStageImage: return SkinUtils.As<TValue>(getManiaImage(existing, "StageBottom")); case LegacyManiaSkinConfigurationLookups.LightImage: return SkinUtils.As<TValue>(getManiaImage(existing, "StageLight")); case LegacyManiaSkinConfigurationLookups.HitTargetImage: return SkinUtils.As<TValue>(getManiaImage(existing, "StageHint")); case LegacyManiaSkinConfigurationLookups.LeftLineWidth: Debug.Assert(maniaLookup.TargetColumn != null); return SkinUtils.As<TValue>(new Bindable<float>(existing.ColumnLineWidth[maniaLookup.TargetColumn.Value])); case LegacyManiaSkinConfigurationLookups.RightLineWidth: Debug.Assert(maniaLookup.TargetColumn != null); return SkinUtils.As<TValue>(new Bindable<float>(existing.ColumnLineWidth[maniaLookup.TargetColumn.Value + 1])); case LegacyManiaSkinConfigurationLookups.Hit0: case LegacyManiaSkinConfigurationLookups.Hit50: case LegacyManiaSkinConfigurationLookups.Hit100: case LegacyManiaSkinConfigurationLookups.Hit200: case LegacyManiaSkinConfigurationLookups.Hit300: case LegacyManiaSkinConfigurationLookups.Hit300g: return SkinUtils.As<TValue>(getManiaImage(existing, maniaLookup.Lookup.ToString())); case LegacyManiaSkinConfigurationLookups.KeysUnderNotes: return SkinUtils.As<TValue>(new Bindable<bool>(existing.KeysUnderNotes)); } return null; } /// <summary> /// Retrieves the correct combo colour for a given colour index and information on the combo. /// </summary> /// <param name="source">The source to retrieve the combo colours from.</param> /// <param name="colourIndex">The preferred index for retrieving the combo colour with.</param> /// <param name="combo">Information on the combo whose using the returned colour.</param> protected virtual IBindable<Color4> GetComboColour(IHasComboColours source, int colourIndex, IHasComboInformation combo) { var colour = source.ComboColours?[colourIndex % source.ComboColours.Count]; return colour.HasValue ? new Bindable<Color4>(colour.Value) : null; } private IBindable<Color4> getCustomColour(IHasCustomColours source, string lookup) => source.CustomColours.TryGetValue(lookup, out var col) ? new Bindable<Color4>(col) : null; private IBindable<string> getManiaImage(LegacyManiaSkinConfiguration source, string lookup) => source.ImageLookups.TryGetValue(lookup, out var image) ? new Bindable<string>(image) : null; [CanBeNull] private IBindable<TValue> legacySettingLookup<TValue>(LegacySkinConfiguration.LegacySetting legacySetting) { switch (legacySetting) { case LegacySkinConfiguration.LegacySetting.Version: return SkinUtils.As<TValue>(new Bindable<decimal>(Configuration.LegacyVersion ?? LegacySkinConfiguration.LATEST_VERSION)); default: return genericLookup<LegacySkinConfiguration.LegacySetting, TValue>(legacySetting); } } [CanBeNull] private IBindable<TValue> genericLookup<TLookup, TValue>(TLookup lookup) { try { if (Configuration.ConfigDictionary.TryGetValue(lookup.ToString(), out var val)) { // special case for handling skins which use 1 or 0 to signify a boolean state. if (typeof(TValue) == typeof(bool)) val = val == "1" ? "true" : "false"; var bindable = new Bindable<TValue>(); if (val != null) bindable.Parse(val); return bindable; } } catch { } return null; } public override Drawable GetDrawableComponent(ISkinComponent component) { if (base.GetDrawableComponent(component) is Drawable c) return c; switch (component) { case SkinnableTargetComponent target: switch (target.Target) { case SkinnableTarget.MainHUDComponents: var skinnableTargetWrapper = new SkinnableTargetComponentsContainer(container => { var score = container.OfType<LegacyScoreCounter>().FirstOrDefault(); var accuracy = container.OfType<GameplayAccuracyCounter>().FirstOrDefault(); var combo = container.OfType<LegacyComboCounter>().FirstOrDefault(); if (score != null && accuracy != null) { accuracy.Y = container.ToLocalSpace(score.ScreenSpaceDrawQuad.BottomRight).Y; } var songProgress = container.OfType<SongProgress>().FirstOrDefault(); var hitError = container.OfType<HitErrorMeter>().FirstOrDefault(); if (hitError != null) { hitError.Anchor = Anchor.BottomCentre; hitError.Origin = Anchor.CentreLeft; hitError.Rotation = -90; } if (songProgress != null) { if (hitError != null) hitError.Y -= SongProgress.MAX_HEIGHT; if (combo != null) combo.Y -= SongProgress.MAX_HEIGHT; } }) { Children = this.HasFont(LegacyFont.Score) ? new Drawable[] { new LegacyComboCounter(), new LegacyScoreCounter(), new LegacyAccuracyCounter(), new LegacyHealthDisplay(), new SongProgress(), new BarHitErrorMeter(), } : new Drawable[] { // TODO: these should fallback to using osu!classic skin textures, rather than doing this. new DefaultComboCounter(), new DefaultScoreCounter(), new DefaultAccuracyCounter(), new DefaultHealthDisplay(), new SongProgress(), new BarHitErrorMeter(), } }; return skinnableTargetWrapper; } return null; case GameplaySkinComponent<HitResult> resultComponent: // TODO: this should be inside the judgement pieces. Func<Drawable> createDrawable = () => getJudgementAnimation(resultComponent.Component); // kind of wasteful that we throw this away, but should do for now. if (createDrawable() != null) { var particle = getParticleTexture(resultComponent.Component); if (particle != null) return new LegacyJudgementPieceNew(resultComponent.Component, createDrawable, particle); else return new LegacyJudgementPieceOld(resultComponent.Component, createDrawable); } break; } return this.GetAnimation(component.LookupName, false, false); } private Texture getParticleTexture(HitResult result) { switch (result) { case HitResult.Meh: return GetTexture("particle50"); case HitResult.Ok: return GetTexture("particle100"); case HitResult.Great: return GetTexture("particle300"); } return null; } private Drawable getJudgementAnimation(HitResult result) { switch (result) { case HitResult.Miss: return this.GetAnimation("hit0", true, false); case HitResult.Meh: return this.GetAnimation("hit50", true, false); case HitResult.Ok: return this.GetAnimation("hit100", true, false); case HitResult.Great: return this.GetAnimation("hit300", true, false); } return null; } public override Texture GetTexture(string componentName, WrapMode wrapModeS, WrapMode wrapModeT) { foreach (var name in getFallbackNames(componentName)) { float ratio = 2; var texture = Textures?.Get($"{name}@2x", wrapModeS, wrapModeT); if (texture == null) { ratio = 1; texture = Textures?.Get(name, wrapModeS, wrapModeT); } if (texture == null) continue; texture.ScaleAdjust = ratio; return texture; } return null; } public override ISample GetSample(ISampleInfo sampleInfo) { IEnumerable<string> lookupNames; if (sampleInfo is HitSampleInfo hitSample) lookupNames = getLegacyLookupNames(hitSample); else { lookupNames = sampleInfo.LookupNames.SelectMany(getFallbackNames); } foreach (var lookup in lookupNames) { var sample = Samples?.Get(lookup); if (sample != null) { return sample; } } return null; } private IEnumerable<string> getLegacyLookupNames(HitSampleInfo hitSample) { var lookupNames = hitSample.LookupNames.SelectMany(getFallbackNames); if (!UseCustomSampleBanks && !string.IsNullOrEmpty(hitSample.Suffix)) { // for compatibility with stable, exclude the lookup names with the custom sample bank suffix, if they are not valid for use in this skin. // using .EndsWith() is intentional as it ensures parity in all edge cases // (see LegacyTaikoSampleInfo for an example of one - prioritising the taiko prefix should still apply, but the sample bank should not). lookupNames = lookupNames.Where(name => !name.EndsWith(hitSample.Suffix, StringComparison.Ordinal)); } foreach (var l in lookupNames) yield return l; // also for compatibility, try falling back to non-bank samples (so-called "universal" samples) as the last resort. // going forward specifying banks shall always be required, even for elements that wouldn't require it on stable, // which is why this is done locally here. yield return hitSample.Name; } private IEnumerable<string> getFallbackNames(string componentName) { // May be something like "Gameplay/osu/approachcircle" from lazer, or "Arrows/note1" from a user skin. yield return componentName; // Fall back to using the last piece for components coming from lazer (e.g. "Gameplay/osu/approachcircle" -> "approachcircle"). yield return componentName.Split('/').Last(); } protected override void Dispose(bool isDisposing) { base.Dispose(isDisposing); Textures?.Dispose(); Samples?.Dispose(); } } }
// 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.Globalization; using System.Runtime.InteropServices; namespace System.Numerics { [StructLayout(LayoutKind.Sequential)] public struct Complex : IEquatable<Complex>, IFormattable { private const double LOG_10_INV = 0.43429448190325; public static readonly Complex Zero; public static readonly Complex One; public static readonly Complex ImaginaryOne; public double Real { get; } public double Imaginary { get; } public double Magnitude => Abs(this); public double Phase => Math.Atan2(Imaginary, Real); public Complex(double real, double imaginary) { Real = real; Imaginary = imaginary; } public static Complex FromPolarCoordinates(double magnitude, double phase) { return new Complex(magnitude * Math.Cos(phase), magnitude * Math.Sin(phase)); } public static Complex Negate(Complex value) => -value; public static Complex Add(Complex left, Complex right) => (left + right); public static Complex Subtract(Complex left, Complex right) => (left - right); public static Complex Multiply(Complex left, Complex right) => (left * right); public static Complex Divide(Complex dividend, Complex divisor) => (dividend / divisor); public static Complex operator -(Complex value) => new Complex(-value.Real, -value.Imaginary); public static Complex operator +(Complex left, Complex right) => new Complex(left.Real + right.Real, left.Imaginary + right.Imaginary); public static Complex operator -(Complex left, Complex right) => new Complex(left.Real - right.Real, left.Imaginary - right.Imaginary); public static Complex operator *(Complex left, Complex right) { double real = (left.Real * right.Real) - (left.Imaginary * right.Imaginary); return new Complex(real, (left.Imaginary * right.Real) + (left.Real * right.Imaginary)); } public static Complex operator /(Complex left, Complex right) { double real = left.Real; double imaginary = left.Imaginary; double num3 = right.Real; double num4 = right.Imaginary; if (Math.Abs(num4) < Math.Abs(num3)) { return new Complex((real + (imaginary * (num4 / num3))) / (num3 + (num4 * (num4 / num3))), (imaginary - (real * (num4 / num3))) / (num3 + (num4 * (num4 / num3)))); } return new Complex((imaginary + (real * (num3 / num4))) / (num4 + (num3 * (num3 / num4))), (-real + (imaginary * (num3 / num4))) / (num4 + (num3 * (num3 / num4)))); } public static double Abs(Complex value) { if (double.IsInfinity(value.Real) || double.IsInfinity(value.Imaginary)) { return double.PositiveInfinity; } double num = Math.Abs(value.Real); double num2 = Math.Abs(value.Imaginary); if (num > num2) { double num3 = num2 / num; return (num * Math.Sqrt(1.0 + (num3 * num3))); } if (num2 == 0.0) { return num; } double num4 = num / num2; return (num2 * Math.Sqrt(1.0 + (num4 * num4))); } public static Complex Conjugate(Complex value) => new Complex(value.Real, -value.Imaginary); public static Complex Reciprocal(Complex value) => (value.Real == 0.0) && (value.Imaginary == 0.0) ? Zero : One / value; public static bool operator ==(Complex left, Complex right) => ((left.Real == right.Real) && (left.Imaginary == right.Imaginary)); public static bool operator !=(Complex left, Complex right) => left.Real == right.Real ? !(left.Imaginary == right.Imaginary) : true; public override bool Equals(object obj) => ((obj is Complex) && (this == ((Complex)obj))); public bool Equals(Complex value) => Real.Equals(value.Real) && Imaginary.Equals(value.Imaginary); public static implicit operator Complex(short value) => new Complex(value, 0.0); public static implicit operator Complex(int value) => new Complex(value, 0.0); public static implicit operator Complex(long value) => new Complex(value, 0.0); public static implicit operator Complex(ushort value) => new Complex(value, 0.0); public static implicit operator Complex(uint value) => new Complex(value, 0.0); public static implicit operator Complex(ulong value) => new Complex(value, 0.0); public static implicit operator Complex(sbyte value) => new Complex(value, 0.0); public static implicit operator Complex(byte value) => new Complex(value, 0.0); public static implicit operator Complex(float value) => new Complex(value, 0.0); public static implicit operator Complex(double value) => new Complex(value, 0.0); public static explicit operator Complex(BigInteger value) => new Complex((double)value, 0.0); public static explicit operator Complex(decimal value) => new Complex((double)value, 0.0); public override string ToString() => string.Format(CultureInfo.CurrentCulture, "({0}, {1})", new object[] { Real, Imaginary }); public string ToString(string format) => string.Format(CultureInfo.CurrentCulture, "({0}, {1})", new object[] { Real.ToString(format, CultureInfo.CurrentCulture), Imaginary.ToString(format, CultureInfo.CurrentCulture) }); public string ToString(IFormatProvider provider) => string.Format(provider, "({0}, {1})", new object[] { Real, Imaginary }); public string ToString(string format, IFormatProvider provider) => string.Format(provider, "({0}, {1})", new object[] { Real.ToString(format, provider), Imaginary.ToString(format, provider) }); public override int GetHashCode() { int num = 0x5f5e0fd; int num2 = Real.GetHashCode() % num; int hashCode = Imaginary.GetHashCode(); return (num2 ^ hashCode); } public static Complex Sin(Complex value) { double real = value.Real; double imaginary = value.Imaginary; return new Complex(Math.Sin(real) * Math.Cosh(imaginary), Math.Cos(real) * Math.Sinh(imaginary)); } public static Complex Sinh(Complex value) { double real = value.Real; double imaginary = value.Imaginary; return new Complex(Math.Sinh(real) * Math.Cos(imaginary), Math.Cosh(real) * Math.Sin(imaginary)); } public static Complex Asin(Complex value) { return (-ImaginaryOne * Log((ImaginaryOne * value) + Sqrt(One - (value * value)))); } public static Complex Cos(Complex value) { double real = value.Real; double imaginary = value.Imaginary; return new Complex(Math.Cos(real) * Math.Cosh(imaginary), -(Math.Sin(real) * Math.Sinh(imaginary))); } public static Complex Cosh(Complex value) { double real = value.Real; double imaginary = value.Imaginary; return new Complex(Math.Cosh(real) * Math.Cos(imaginary), Math.Sinh(real) * Math.Sin(imaginary)); } public static Complex Acos(Complex value) => (-ImaginaryOne * Log(value + (ImaginaryOne * Sqrt(One - (value * value))))); public static Complex Tan(Complex value) => (Sin(value) / Cos(value)); public static Complex Tanh(Complex value) => (Sinh(value) / Cosh(value)); public static Complex Atan(Complex value) { Complex complex = new Complex(2.0, 0.0); return ((ImaginaryOne / complex) * (Log(One - (ImaginaryOne * value)) - Log(One + (ImaginaryOne * value)))); } public static Complex Log(Complex value) => new Complex(Math.Log(Abs(value)), Math.Atan2(value.Imaginary, value.Real)); public static Complex Log(Complex value, double baseValue) => (Log(value) / Log(baseValue)); public static Complex Log10(Complex value) => Scale(Log(value), 0.43429448190325); public static Complex Exp(Complex value) { double num = Math.Exp(value.Real); double real = num * Math.Cos(value.Imaginary); return new Complex(real, num * Math.Sin(value.Imaginary)); } public static Complex Sqrt(Complex value) => FromPolarCoordinates(Math.Sqrt(value.Magnitude), value.Phase / 2.0); public static Complex Pow(Complex value, Complex power) { if (power == Zero) { return One; } if (value == Zero) { return Zero; } double real = value.Real; double imaginary = value.Imaginary; double y = power.Real; double num4 = power.Imaginary; double d = Abs(value); double num6 = Math.Atan2(imaginary, real); double num7 = (y * num6) + (num4 * Math.Log(d)); double num8 = Math.Pow(d, y) * Math.Pow(2.7182818284590451, -num4 * num6); return new Complex(num8 * Math.Cos(num7), num8 * Math.Sin(num7)); } public static Complex Pow(Complex value, double power) => Pow(value, new Complex(power, 0.0)); private static Complex Scale(Complex value, double factor) { double real = factor * value.Real; return new Complex(real, factor * value.Imaginary); } static Complex() { Zero = new Complex(0.0, 0.0); One = new Complex(1.0, 0.0); ImaginaryOne = new Complex(0.0, 1.0); } } }
// 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.Composition; using System.Runtime.CompilerServices; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.CodeAnalysis.Editor.Implementation.Workspaces { [ExportWorkspaceServiceFactory(typeof(IProjectCacheHostService), ServiceLayer.Editor)] [Shared] internal class ProjectCacheHostServiceFactory : IWorkspaceServiceFactory { public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices) { var projectCacheService = new ProjectCacheService(); var documentTrackingService = workspaceServices.GetService<IDocumentTrackingService>(); // Subscribe to events so that we can cache items from the active document's project var manager = new ActiveProjectCacheManager(documentTrackingService, projectCacheService); // Subscribe to requests to clear the cache var workspaceCacheService = workspaceServices.GetService<IWorkspaceCacheService>(); if (workspaceCacheService != null) { workspaceCacheService.CacheFlushRequested += (s, e) => manager.Clear(); } // Also clear the cache when the solution is cleared or removed. workspaceServices.Workspace.WorkspaceChanged += (s, e) => { if (e.Kind == WorkspaceChangeKind.SolutionCleared || e.Kind == WorkspaceChangeKind.SolutionRemoved) { manager.Clear(); } }; return projectCacheService; } internal class ProjectCacheService : IProjectCacheHostService { private readonly object _gate = new object(); private readonly Dictionary<object, Cache> _activeCaches = new Dictionary<object, Cache>(); private readonly Queue<object> _implicitCache = new Queue<object>(); internal const int ImplicitCacheSize = 3; public IDisposable EnableCaching(ProjectId key) { lock (_gate) { Cache cache; if (!_activeCaches.TryGetValue(key, out cache)) { cache = new Cache(this, key); _activeCaches.Add(key, cache); } cache.Count++; return cache; } } public T CacheObjectIfCachingEnabledForKey<T>(ProjectId key, object owner, T instance) where T : class { lock (_gate) { Cache cache; if (_activeCaches.TryGetValue(key, out cache)) { cache.CreateStrongReference(owner, instance); } else { if (!_implicitCache.Contains(instance)) { if (_implicitCache.Count == ImplicitCacheSize) { _implicitCache.Dequeue(); } _implicitCache.Enqueue(instance); } } return instance; } } public T CacheObjectIfCachingEnabledForKey<T>(ProjectId key, ICachedObjectOwner owner, T instance) where T : class { lock (_gate) { Cache cache; if (owner.CachedObject == null && _activeCaches.TryGetValue(key, out cache)) { owner.CachedObject = instance; cache.CreateOwnerEntry(owner); } return instance; } } private void DisableCaching(object key, Cache cache) { lock (_gate) { cache.Count--; if (cache.Count == 0) { _activeCaches.Remove(key); cache.FreeOwnerEntries(); } } } private class Cache : IDisposable { internal int Count; private readonly ProjectCacheService _cacheService; private readonly object _key; private readonly ConditionalWeakTable<object, object> _cache = new ConditionalWeakTable<object, object>(); private readonly List<WeakReference<ICachedObjectOwner>> _ownerObjects = new List<WeakReference<ICachedObjectOwner>>(); public Cache(ProjectCacheService cacheService, object key) { _cacheService = cacheService; _key = key; } public void Dispose() { _cacheService.DisableCaching(_key, this); } internal void CreateStrongReference(object key, object instance) { object o; if (!_cache.TryGetValue(key, out o)) { _cache.Add(key, instance); } } internal void CreateOwnerEntry(ICachedObjectOwner owner) { _ownerObjects.Add(new WeakReference<ICachedObjectOwner>(owner)); } internal void FreeOwnerEntries() { foreach (var entry in _ownerObjects) { ICachedObjectOwner owner; if (entry.TryGetTarget(out owner)) { owner.CachedObject = null; } } } } } private class ActiveProjectCacheManager { private readonly IDocumentTrackingService _documentTrackingService; private readonly ProjectCacheService _projectCacheService; private readonly object _guard = new object(); private ProjectId _mostRecentActiveProjectId; private IDisposable _mostRecentCache; public ActiveProjectCacheManager(IDocumentTrackingService documentTrackingService, ProjectCacheService projectCacheService) { _documentTrackingService = documentTrackingService; _projectCacheService = projectCacheService; if (documentTrackingService != null) { documentTrackingService.ActiveDocumentChanged += UpdateCache; UpdateCache(null, documentTrackingService.GetActiveDocument()); } } private void UpdateCache(object sender, DocumentId activeDocument) { lock (_guard) { if (activeDocument != null && activeDocument.ProjectId != _mostRecentActiveProjectId) { Clear_NoLock(); _mostRecentCache = _projectCacheService.EnableCaching(activeDocument.ProjectId); _mostRecentActiveProjectId = activeDocument.ProjectId; } } } public void Clear() { lock (_guard) { Clear_NoLock(); } } private void Clear_NoLock() { if (_mostRecentCache != null) { _mostRecentCache.Dispose(); _mostRecentCache = null; } _mostRecentActiveProjectId = null; } } } }
// // Copyright (c) 2012 Krueger Systems, 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.Collections; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; namespace SQLite { public class SQLiteAsyncConnection { SQLiteConnectionString _connectionString; public SQLiteAsyncConnection (string databasePath, bool storeDateTimeAsTicks = false) { _connectionString = new SQLiteConnectionString (databasePath, storeDateTimeAsTicks); } SQLiteConnectionWithLock GetConnection () { return SQLiteConnectionPool.Shared.GetConnection (_connectionString); } public Task<CreateTablesResult> CreateTableAsync<T> () where T : new () { return CreateTablesAsync (typeof (T)); } public Task<CreateTablesResult> CreateTablesAsync<T, T2> () where T : new () where T2 : new () { return CreateTablesAsync (typeof (T), typeof (T2)); } public Task<CreateTablesResult> CreateTablesAsync<T, T2, T3> () where T : new () where T2 : new () where T3 : new () { return CreateTablesAsync (typeof (T), typeof (T2), typeof (T3)); } public Task<CreateTablesResult> CreateTablesAsync<T, T2, T3, T4> () where T : new () where T2 : new () where T3 : new () where T4 : new () { return CreateTablesAsync (typeof (T), typeof (T2), typeof (T3), typeof (T4)); } public Task<CreateTablesResult> CreateTablesAsync<T, T2, T3, T4, T5> () where T : new () where T2 : new () where T3 : new () where T4 : new () where T5 : new () { return CreateTablesAsync (typeof (T), typeof (T2), typeof (T3), typeof (T4), typeof (T5)); } public Task<CreateTablesResult> CreateTablesAsync (params Type[] types) { return Task.Factory.StartNew (() => { CreateTablesResult result = new CreateTablesResult (); var conn = GetConnection (); using (conn.Lock ()) { foreach (Type type in types) { int aResult = conn.CreateTable (type); result.Results[type] = aResult; } } return result; }); } public Task<int> DropTableAsync<T> () where T : new () { return Task.Factory.StartNew (() => { var conn = GetConnection (); using (conn.Lock ()) { return conn.DropTable<T> (); } }); } public Task<int> InsertAsync (object item) { return Task.Factory.StartNew (() => { var conn = GetConnection (); using (conn.Lock ()) { return conn.Insert (item); } }); } public Task<int> UpdateAsync (object item) { return Task.Factory.StartNew (() => { var conn = GetConnection (); using (conn.Lock ()) { return conn.Update (item); } }); } public Task<int> DeleteAsync (object item) { return Task.Factory.StartNew (() => { var conn = GetConnection (); using (conn.Lock ()) { return conn.Delete (item); } }); } public Task<T> GetAsync<T>(object pk) where T : new() { return Task.Factory.StartNew(() => { var conn = GetConnection(); using (conn.Lock()) { return conn.Get<T>(pk); } }); } public Task<T> FindAsync<T> (object pk) where T : new () { return Task.Factory.StartNew (() => { var conn = GetConnection (); using (conn.Lock ()) { return conn.Find<T> (pk); } }); } public Task<T> GetAsync<T> (Expression<Func<T, bool>> predicate) where T : new() { return Task.Factory.StartNew(() => { var conn = GetConnection(); using (conn.Lock()) { return conn.Get<T> (predicate); } }); } public Task<T> FindAsync<T> (Expression<Func<T, bool>> predicate) where T : new () { return Task.Factory.StartNew (() => { var conn = GetConnection (); using (conn.Lock ()) { return conn.Find<T> (predicate); } }); } public Task<int> ExecuteAsync (string query, params object[] args) { return Task<int>.Factory.StartNew (() => { var conn = GetConnection (); using (conn.Lock ()) { return conn.Execute (query, args); } }); } public Task<int> InsertAllAsync (IEnumerable items) { return Task.Factory.StartNew (() => { var conn = GetConnection (); using (conn.Lock ()) { return conn.InsertAll (items); } }); } [Obsolete("Will cause a deadlock if any call in action ends up in a different thread. Use RunInTransactionAsync(Action<SQLiteConnection>) instead.")] public Task RunInTransactionAsync (Action<SQLiteAsyncConnection> action) { return Task.Factory.StartNew (() => { var conn = this.GetConnection (); using (conn.Lock ()) { conn.BeginTransaction (); try { action (this); conn.Commit (); } catch (Exception) { conn.Rollback (); throw; } } }); } public Task RunInTransactionAsync(Action<SQLiteConnection> action) { return Task.Factory.StartNew(() => { var conn = this.GetConnection(); using (conn.Lock()) { conn.BeginTransaction(); try { action(conn); conn.Commit(); } catch (Exception) { conn.Rollback(); throw; } } }); } public AsyncTableQuery<T> Table<T> () where T : new () { // // This isn't async as the underlying connection doesn't go out to the database // until the query is performed. The Async methods are on the query iteself. // var conn = GetConnection (); return new AsyncTableQuery<T> (conn.Table<T> ()); } public Task<T> ExecuteScalarAsync<T> (string sql, params object[] args) { return Task<T>.Factory.StartNew (() => { var conn = GetConnection (); using (conn.Lock ()) { var command = conn.CreateCommand (sql, args); return command.ExecuteScalar<T> (); } }); } public Task<List<T>> QueryAsync<T> (string sql, params object[] args) where T : new () { return Task<List<T>>.Factory.StartNew (() => { var conn = GetConnection (); using (conn.Lock ()) { return conn.Query<T> (sql, args); } }); } } // // TODO: Bind to AsyncConnection.GetConnection instead so that delayed // execution can still work after a Pool.Reset. // public class AsyncTableQuery<T> where T : new () { TableQuery<T> _innerQuery; public AsyncTableQuery (TableQuery<T> innerQuery) { _innerQuery = innerQuery; } public AsyncTableQuery<T> Where (Expression<Func<T, bool>> predExpr) { return new AsyncTableQuery<T> (_innerQuery.Where (predExpr)); } public AsyncTableQuery<T> Skip (int n) { return new AsyncTableQuery<T> (_innerQuery.Skip (n)); } public AsyncTableQuery<T> Take (int n) { return new AsyncTableQuery<T> (_innerQuery.Take (n)); } public AsyncTableQuery<T> OrderBy<U> (Expression<Func<T, U>> orderExpr) { return new AsyncTableQuery<T> (_innerQuery.OrderBy<U> (orderExpr)); } public AsyncTableQuery<T> OrderByDescending<U> (Expression<Func<T, U>> orderExpr) { return new AsyncTableQuery<T> (_innerQuery.OrderByDescending<U> (orderExpr)); } public Task<List<T>> ToListAsync () { return Task.Factory.StartNew (() => { using (((SQLiteConnectionWithLock)_innerQuery.Connection).Lock ()) { return _innerQuery.ToList (); } }); } public Task<int> CountAsync () { return Task.Factory.StartNew (() => { using (((SQLiteConnectionWithLock)_innerQuery.Connection).Lock ()) { return _innerQuery.Count (); } }); } public Task<T> ElementAtAsync (int index) { return Task.Factory.StartNew (() => { using (((SQLiteConnectionWithLock)_innerQuery.Connection).Lock ()) { return _innerQuery.ElementAt (index); } }); } public Task<T> FirstAsync () { return Task<T>.Factory.StartNew(() => { using (((SQLiteConnectionWithLock)_innerQuery.Connection).Lock ()) { return _innerQuery.First (); } }); } public Task<T> FirstOrDefaultAsync () { return Task<T>.Factory.StartNew(() => { using (((SQLiteConnectionWithLock)_innerQuery.Connection).Lock ()) { return _innerQuery.FirstOrDefault (); } }); } } public class CreateTablesResult { public Dictionary<Type, int> Results { get; private set; } internal CreateTablesResult () { this.Results = new Dictionary<Type, int> (); } } class SQLiteConnectionPool { class Entry { public SQLiteConnectionString ConnectionString { get; private set; } public SQLiteConnectionWithLock Connection { get; private set; } public Entry (SQLiteConnectionString connectionString) { ConnectionString = connectionString; Connection = new SQLiteConnectionWithLock (connectionString); } public void OnApplicationSuspended () { Connection.Dispose (); Connection = null; } } readonly Dictionary<string, Entry> _entries = new Dictionary<string, Entry> (); readonly object _entriesLock = new object (); static readonly SQLiteConnectionPool _shared = new SQLiteConnectionPool (); /// <summary> /// Gets the singleton instance of the connection tool. /// </summary> public static SQLiteConnectionPool Shared { get { return _shared; } } public SQLiteConnectionWithLock GetConnection (SQLiteConnectionString connectionString) { lock (_entriesLock) { Entry entry; string key = connectionString.ConnectionString; if (!_entries.TryGetValue (key, out entry)) { entry = new Entry (connectionString); _entries[key] = entry; } return entry.Connection; } } /// <summary> /// Closes all connections managed by this pool. /// </summary> public void Reset () { lock (_entriesLock) { foreach (var entry in _entries.Values) { entry.OnApplicationSuspended (); } _entries.Clear (); } } /// <summary> /// Call this method when the application is suspended. /// </summary> /// <remarks>Behaviour here is to close any open connections.</remarks> public void ApplicationSuspended () { Reset (); } } class SQLiteConnectionWithLock : SQLiteConnection { readonly object _lockPoint = new object (); public SQLiteConnectionWithLock (SQLiteConnectionString connectionString) : base (connectionString.DatabasePath, connectionString.StoreDateTimeAsTicks) { } public IDisposable Lock () { return new LockWrapper (_lockPoint); } private class LockWrapper : IDisposable { object _lockPoint; public LockWrapper (object lockPoint) { _lockPoint = lockPoint; Monitor.Enter (_lockPoint); } public void Dispose () { Monitor.Exit (_lockPoint); } } } }
using System; using System.CodeDom.Compiler; using System.ComponentModel; using System.Diagnostics; using System.Xml.Serialization; namespace ExportImportPromotion.StoreMarketingWebService { #if MS [GeneratedCode("System.Xml", "4.0.30319.1"), DesignerCategory("code"), DebuggerStepThrough, XmlType(Namespace = "http://schemas.microsoft.com/CommerceServer/2006/06/MarketingWebService")] #else [GeneratedCode("System.Xml", "4.0.30319.1"), DesignerCategory("code"), DebuggerStepThrough, XmlType(Namespace = "http://schemas.commerceserver.net/2013/01/Marketing/MarketingWebService")] #endif [Serializable] public class CustomerData { private int idField; private string nameField; private string descriptionField; private string contactNameField; private string contactAddressField; private string contactPhoneField; private string contactFaxField; private string contactEmailField; private string defaultUrlField; private string industryField; private CustomerType typeField; private DateTime createdDateField; private DateTime lastModifiedDateField; private string lastModifiedByField; private DateTime deletedDateField; public int Id { get { return this.idField; } set { this.idField = value; } } [XmlElement(IsNullable = true)] public string Name { get { return this.nameField; } set { this.nameField = value; } } [XmlElement(IsNullable = true)] public string Description { get { return this.descriptionField; } set { this.descriptionField = value; } } [XmlElement(IsNullable = true)] public string ContactName { get { return this.contactNameField; } set { this.contactNameField = value; } } [XmlElement(IsNullable = true)] public string ContactAddress { get { return this.contactAddressField; } set { this.contactAddressField = value; } } [XmlElement(IsNullable = true)] public string ContactPhone { get { return this.contactPhoneField; } set { this.contactPhoneField = value; } } [XmlElement(IsNullable = true)] public string ContactFax { get { return this.contactFaxField; } set { this.contactFaxField = value; } } [XmlElement(IsNullable = true)] public string ContactEmail { get { return this.contactEmailField; } set { this.contactEmailField = value; } } [XmlElement(IsNullable = true)] public string DefaultUrl { get { return this.defaultUrlField; } set { this.defaultUrlField = value; } } public string Industry { get { return this.industryField; } set { this.industryField = value; } } public CustomerType Type { get { return this.typeField; } set { this.typeField = value; } } public DateTime CreatedDate { get { return this.createdDateField; } set { this.createdDateField = value; } } public DateTime LastModifiedDate { get { return this.lastModifiedDateField; } set { this.lastModifiedDateField = value; } } [XmlElement(IsNullable = true)] public string LastModifiedBy { get { return this.lastModifiedByField; } set { this.lastModifiedByField = value; } } public DateTime DeletedDate { get { return this.deletedDateField; } set { this.deletedDateField = value; } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace ITN.Felicity.Api.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { internal const int DefaultCollectionSize = 2; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.Collections.Generic; using System.Globalization; using System.Text; using Azure.Core; using Azure.Messaging.ServiceBus.Primitives; namespace Azure.Messaging.ServiceBus.Management { /// <summary> /// Represents the correlation rule filter expression. /// </summary> /// <remarks> /// <para> /// A CorrelationRuleFilter holds a set of conditions that are matched against one of more of an arriving message's user and system properties. /// A common use is a match against the <see cref="ServiceBusMessage.CorrelationId"/> property, but the application can also choose to match against /// <see cref="ServiceBusMessage.ContentType"/>, <see cref="ServiceBusMessage.Label"/>, <see cref="ServiceBusMessage.MessageId"/>, <see cref="ServiceBusMessage.ReplyTo"/>, /// <see cref="ServiceBusMessage.ReplyToSessionId"/>, <see cref="ServiceBusMessage.SessionId"/>, <see cref="ServiceBusMessage.To"/>, and any user-defined properties. /// A match exists when an arriving message's value for a property is equal to the value specified in the correlation filter. For string expressions, /// the comparison is case-sensitive. When specifying multiple match properties, the filter combines them as a logical AND condition, /// meaning all conditions must match for the filter to match. /// </para> /// <para> /// The CorrelationRuleFilter provides an efficient shortcut for declarations of filters that deal only with correlation equality. /// In this case the cost of the lexigraphical analysis of the expression can be avoided. /// Not only will correlation filters be optimized at declaration time, but they will also be optimized at runtime. /// Correlation filter matching can be reduced to a hashtable lookup, which aggregates the complexity of the set of defined correlation filters to O(1). /// </para> /// </remarks> public sealed class CorrelationRuleFilter : RuleFilter { internal PropertyDictionary properties; /// <summary> /// Initializes a new instance of the <see cref="CorrelationRuleFilter" /> class with default values. /// </summary> public CorrelationRuleFilter() { } /// <summary> /// Initializes a new instance of the <see cref="CorrelationRuleFilter" /> class with the specified correlation identifier. /// </summary> /// <param name="correlationId">The identifier for the correlation.</param> /// <exception cref="System.ArgumentException">Thrown when the <paramref name="correlationId" /> is null or empty.</exception> public CorrelationRuleFilter(string correlationId) : this() { Argument.AssertNotNullOrWhiteSpace(correlationId, nameof(correlationId)); CorrelationId = correlationId; } /// <summary> /// Identifier of the correlation. /// </summary> /// <value>The identifier of the correlation.</value> public string CorrelationId { get; set; } /// <summary> /// Identifier of the message. /// </summary> /// <value>The identifier of the message.</value> /// <remarks>Max MessageId size is 128 chars.</remarks> public string MessageId { get; set; } /// <summary> /// Address to send to. /// </summary> /// <value>The address to send to.</value> public string To { get; set; } /// <summary> /// Address of the queue to reply to. /// </summary> /// <value>The address of the queue to reply to.</value> public string ReplyTo { get; set; } /// <summary> /// Application specific label. /// </summary> /// <value>The application specific label.</value> public string Label { get; set; } /// <summary> /// Session identifier. /// </summary> /// <value>The session identifier.</value> /// <remarks>Max size of sessionId is 128 chars.</remarks> public string SessionId { get; set; } /// <summary> /// Session identifier to reply to. /// </summary> /// <value>The session identifier to reply to.</value> /// <remarks>Max size of ReplyToSessionId is 128.</remarks> public string ReplyToSessionId { get; set; } /// <summary> /// Content type of the message. /// </summary> /// <value>The content type of the message.</value> public string ContentType { get; set; } /// <summary> /// Application specific properties of the message. /// </summary> /// <value>The application specific properties of the message.</value> /// <remarks> /// Only following value types are supported: /// byte, sbyte, char, short, ushort, int, uint, long, ulong, float, double, decimal, /// bool, Guid, string, Uri, DateTime, DateTimeOffset, TimeSpan, Stream, byte[], /// and IList / IDictionary of supported types /// </remarks> public IDictionary<string, object> Properties => properties ?? (properties = new PropertyDictionary()); /// <summary> /// Converts the value of the current instance to its equivalent string representation. /// </summary> /// <returns>A string representation of the current instance.</returns> public override string ToString() { var stringBuilder = new StringBuilder(); stringBuilder.Append("CorrelationRuleFilter: "); var isFirstExpression = true; AppendPropertyExpression(ref isFirstExpression, stringBuilder, "sys.CorrelationId", CorrelationId); AppendPropertyExpression(ref isFirstExpression, stringBuilder, "sys.MessageId", MessageId); AppendPropertyExpression(ref isFirstExpression, stringBuilder, "sys.To", To); AppendPropertyExpression(ref isFirstExpression, stringBuilder, "sys.ReplyTo", ReplyTo); AppendPropertyExpression(ref isFirstExpression, stringBuilder, "sys.Label", Label); AppendPropertyExpression(ref isFirstExpression, stringBuilder, "sys.SessionId", SessionId); AppendPropertyExpression(ref isFirstExpression, stringBuilder, "sys.ReplyToSessionId", ReplyToSessionId); AppendPropertyExpression(ref isFirstExpression, stringBuilder, "sys.ContentType", ContentType); foreach (var pair in Properties) { string propertyName = pair.Key; object propertyValue = pair.Value; AppendPropertyExpression(ref isFirstExpression, stringBuilder, propertyName, propertyValue); } return stringBuilder.ToString(); } private static void AppendPropertyExpression(ref bool firstExpression, StringBuilder builder, string propertyName, object value) { if (value != null) { if (firstExpression) { firstExpression = false; } else { builder.Append(" AND "); } builder.AppendFormat(CultureInfo.InvariantCulture, "{0} = '{1}'", propertyName, value); } } /// <inheritdoc/> public override int GetHashCode() { int hash = 13; unchecked { hash = (hash * 7) + CorrelationId?.GetHashCode() ?? 0; hash = (hash * 7) + MessageId?.GetHashCode() ?? 0; hash = (hash * 7) + SessionId?.GetHashCode() ?? 0; } return hash; } /// <inheritdoc/> public override bool Equals(object obj) { var other = obj as CorrelationRuleFilter; return Equals(other); } /// <inheritdoc/> public override bool Equals(RuleFilter other) { if (other is CorrelationRuleFilter correlationRuleFilter) { if (string.Equals(CorrelationId, correlationRuleFilter.CorrelationId, StringComparison.OrdinalIgnoreCase) && string.Equals(MessageId, correlationRuleFilter.MessageId, StringComparison.OrdinalIgnoreCase) && string.Equals(To, correlationRuleFilter.To, StringComparison.OrdinalIgnoreCase) && string.Equals(ReplyTo, correlationRuleFilter.ReplyTo, StringComparison.OrdinalIgnoreCase) && string.Equals(Label, correlationRuleFilter.Label, StringComparison.OrdinalIgnoreCase) && string.Equals(SessionId, correlationRuleFilter.SessionId, StringComparison.OrdinalIgnoreCase) && string.Equals(ReplyToSessionId, correlationRuleFilter.ReplyToSessionId, StringComparison.OrdinalIgnoreCase) && string.Equals(ContentType, correlationRuleFilter.ContentType, StringComparison.OrdinalIgnoreCase) && (properties != null && correlationRuleFilter.properties != null || properties == null && correlationRuleFilter.properties == null)) { if (properties != null) { if (properties.Count != correlationRuleFilter.properties.Count) { return false; } foreach (var param in properties) { if (!correlationRuleFilter.properties.TryGetValue(param.Key, out var otherParamValue) || (param.Value == null ^ otherParamValue == null) || (param.Value != null && !param.Value.Equals(otherParamValue))) { return false; } } } return true; } } return false; } /// <summary> /// /// </summary> /// <param name="left"></param> /// <param name="right"></param> /// <returns></returns> public static bool operator ==(CorrelationRuleFilter left, CorrelationRuleFilter right) { if (ReferenceEquals(left, right)) { return true; } if (ReferenceEquals(left, null) || ReferenceEquals(right, null)) { return false; } return left.Equals(right); } /// <summary> /// /// </summary> /// <param name="left"></param> /// <param name="right"></param> /// <returns></returns> public static bool operator !=(CorrelationRuleFilter left, CorrelationRuleFilter right) { return !(left == right); } } }
using System; using System.Collections.Concurrent; using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.Connections; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Orleans.Configuration; using Orleans.Internal; namespace Orleans.Runtime.Messaging { internal sealed class ConnectionManager { [ThreadStatic] private static int nextConnection; private readonly ConcurrentDictionary<SiloAddress, ConnectionEntry> connections = new ConcurrentDictionary<SiloAddress, ConnectionEntry>(); private readonly ConnectionOptions connectionOptions; private readonly ConnectionFactory connectionFactory; private readonly INetworkingTrace trace; private readonly CancellationTokenSource cancellation = new CancellationTokenSource(); private readonly object lockObj = new object(); private readonly TaskCompletionSource<int> closedTaskCompletionSource = new TaskCompletionSource<int>(TaskCreationOptions.RunContinuationsAsynchronously); public ConnectionManager( IOptions<ConnectionOptions> connectionOptions, ConnectionFactory connectionFactory, INetworkingTrace trace) { this.connectionOptions = connectionOptions.Value; this.connectionFactory = connectionFactory; this.trace = trace; } public int ConnectionCount { get { var count = 0; foreach (var entry in this.connections) { var values = entry.Value.Connections; if (values.IsDefault) continue; count += values.Length; } return count; } } public Task Closed => this.closedTaskCompletionSource.Task; public ImmutableArray<SiloAddress> GetConnectedAddresses() => this.connections.Keys.ToImmutableArray(); public ValueTask<Connection> GetConnection(SiloAddress endpoint) { if (this.connections.TryGetValue(endpoint, out var entry) && entry.TryGetConnection(out var connection)) { var pendingAttempt = entry.PendingConnection; if (!entry.HasSufficientConnections && (pendingAttempt is null || pendingAttempt.IsCompleted)) { this.GetConnectionAsync(entry.Endpoint).Ignore(); } // Return the existing connection. return new ValueTask<Connection>(connection); } // Start a new connection attempt since there are no suitable connections. return new ValueTask<Connection>(this.GetConnectionAsync(endpoint)); } private async Task<Connection> GetConnectionAsync(SiloAddress endpoint) { RequestContext.Clear(); while (true) { await Task.Yield(); this.cancellation.Token.ThrowIfCancellationRequested(); ConnectionEntry entry; Task pendingAttempt; lock (this.lockObj) { entry = this.GetOrCreateEntry(endpoint); // Remove defunct connections. foreach (var c in entry.Connections) { if (!c.IsValid) entry.Connections = entry.Connections.Remove(c); } // If there are sufficient connections available then return an existing connection. if (entry.HasSufficientConnections && entry.TryGetConnection(out var connection)) { return connection; } entry.ThrowIfRecentConnectionFailure(); pendingAttempt = entry.PendingConnection; // If there is no pending attempt then start one, otherwise the pending attempt will be awaited before reevaluating. if (pendingAttempt is null) { // Initiate a new connection. pendingAttempt = entry.PendingConnection = this.ConnectAsync(endpoint); } } try { await pendingAttempt; } finally { lock (this.lockObj) { // Clear the completed attempt. if (ReferenceEquals(pendingAttempt, entry.PendingConnection)) { entry.PendingConnection = null; } } } } } private void OnConnectionFailed(SiloAddress address, DateTime lastFailure) { lock (this.lockObj) { var entry = this.GetOrCreateEntry(address); if (entry.LastFailure.HasValue) { var ticks = Math.Max(lastFailure.Ticks, entry.LastFailure.Value.Ticks); lastFailure = new DateTime(ticks, DateTimeKind.Utc); } // Remove defunct connections. var connections = entry.Connections; foreach (var c in connections) { if (!c.IsValid) connections = connections.Remove(c); } entry.LastFailure = lastFailure; entry.Connections = connections; } } public void OnConnected(SiloAddress address, Connection connection) { lock (this.lockObj) { var entry = this.GetOrCreateEntry(address); var newConnections = entry.Connections.Contains(connection) ? entry.Connections : entry.Connections.Add(connection); entry.LastFailure = default; entry.Connections = newConnections; } this.trace.LogInformation("Connection {Connection} established with {Silo}", connection, address); } public void OnConnectionTerminated(SiloAddress address, Connection connection, Exception exception) { if (connection is null) return; lock (this.lockObj) { if (this.connections.TryGetValue(address, out var entry)) { entry.Connections = entry.Connections.Remove(connection); if (entry.Connections.Length == 0 && entry.PendingConnection is null) { // Remove the entire entry. this.connections.TryRemove(address, out _); } foreach (var c in entry.Connections) { if (!c.IsValid) entry.Connections = entry.Connections.Remove(c); } } } if (exception != null) { this.trace.LogWarning( "Connection {Connection} to endpoint {EndPoint} terminated with exception {Exception}", connection, address, exception); } else { this.trace.LogDebug( "Connection {Connection} to endpoint {EndPoint} closed", connection, address); } } private ConnectionEntry GetOrCreateEntry(SiloAddress address) { lock (this.lockObj) { if (!this.connections.TryGetValue(address, out var entry)) { // Initialize the entry for this endpoint. entry = new ConnectionEntry(this.connectionOptions, address, ImmutableArray<Connection>.Empty, default); this.connections[address] = entry; } return entry; } } private async Task<Connection> ConnectAsync(SiloAddress address) { await Task.Yield(); CancellationTokenSource openConnectionCancellation = default; try { if (this.trace.IsEnabled(LogLevel.Information)) { this.trace.LogInformation( "Establishing connection to endpoint {EndPoint}", address); } // Cancel pending connection attempts either when the host terminates or after the configured time limit. openConnectionCancellation = CancellationTokenSource.CreateLinkedTokenSource(this.cancellation.Token); openConnectionCancellation.CancelAfter(this.connectionOptions.OpenConnectionTimeout); var connection = await this.connectionFactory.ConnectAsync(address, openConnectionCancellation.Token) .AsTask() .WithCancellation(openConnectionCancellation.Token); if (this.trace.IsEnabled(LogLevel.Information)) { this.trace.LogInformation( "Connected to endpoint {EndPoint}", address); } this.StartConnection(address, connection); this.OnConnected(address, connection); return connection; } catch (Exception exception) { this.OnConnectionFailed(address, DateTime.UtcNow); this.trace.LogWarning( "Connection attempt to endpoint {EndPoint} failed with exception {Exception}", address, exception); throw new ConnectionFailedException( $"Unable to connect to endpoint {address}. See {nameof(exception.InnerException)}", exception); } finally { openConnectionCancellation?.Dispose(); } } public void Abort(SiloAddress endpoint) { ConnectionEntry entry; lock (this.lockObj) { if (!this.connections.TryGetValue(endpoint, out entry)) { return; } lock (this.lockObj) { if (entry.PendingConnection is null) { this.connections.TryRemove(endpoint, out _); } } } if (entry is ConnectionEntry && !entry.Connections.IsDefault) { var exception = new ConnectionAbortedException($"Aborting connection to {endpoint}"); foreach (var connection in entry.Connections) { try { connection.Close(exception); } catch { } } } } public async Task Close(CancellationToken ct) { try { this.cancellation.Cancel(throwOnFirstException: false); var connectionAbortedException = new ConnectionAbortedException("Stopping"); var cycles = 0; while (this.ConnectionCount > 0) { foreach (var entry in this.connections.Values.ToImmutableList()) { if (entry.Connections.IsDefaultOrEmpty) continue; foreach (var connection in entry.Connections) { try { connection.Close(connectionAbortedException); } catch { } } } if (ct.IsCancellationRequested) break; await Task.Delay(10); if (++cycles > 100 && cycles % 500 == 0 && this.ConnectionCount > 0) { this.trace?.LogWarning("Waiting for {NumRemaining} connections to terminate", this.ConnectionCount); } } } catch (Exception exception) { this.trace?.LogWarning("Exception during shutdown: {Exception}", exception); } finally { this.closedTaskCompletionSource.TrySetResult(0); } } private void StartConnection(SiloAddress address, Connection connection) { ThreadPool.UnsafeQueueUserWorkItem(this.StartConnectionCore, (address, connection)); } private void StartConnectionCore(object state) { var (address, connection) = ((SiloAddress, Connection))state; _ = this.RunConnectionAsync(address, connection); } private async Task RunConnectionAsync(SiloAddress address, Connection connection) { Exception error = default; try { using (this.BeginConnectionScope(connection)) { await connection.Run(); } } catch (Exception exception) { error = exception; } finally { this.OnConnectionTerminated(address, connection, error); } } private IDisposable BeginConnectionScope(Connection connection) { if (this.trace.IsEnabled(LogLevel.Critical)) { return this.trace.BeginScope(new ConnectionLogScope(connection)); } return null; } private class ConnectionEntry { private readonly ConnectionOptions connectionOptions; public ConnectionEntry( ConnectionOptions connectionOptions, SiloAddress endpoint, ImmutableArray<Connection> connections, DateTime? lastFailure) { this.connectionOptions = connectionOptions; this.Endpoint = endpoint; this.Connections = connections; this.LastFailure = lastFailure; } public Task PendingConnection { get; set; } public DateTime? LastFailure { get; set; } public ImmutableArray<Connection> Connections { get; set; } public SiloAddress Endpoint { get; } public TimeSpan RemainingRetryDelay { get { var lastFailure = this.LastFailure; if (lastFailure.HasValue) { var now = DateTime.UtcNow; var retryAfter = lastFailure.Value.Add(this.connectionOptions.ConnectionRetryDelay); var remainingDelay = retryAfter.Subtract(now); if (remainingDelay > TimeSpan.Zero) { return remainingDelay; } } return TimeSpan.Zero; } } public bool HasSufficientConnections { get { var connections = this.Connections; return !connections.IsDefaultOrEmpty && connections.Length >= this.connectionOptions.ConnectionsPerEndpoint; } } public bool TryGetConnection(out Connection connection) { connection = default; var connections = this.Connections; if (connections.IsDefaultOrEmpty) { return false; } nextConnection = (nextConnection + 1) % connections.Length; var result = connections[nextConnection]; if (result.IsValid) { connection = result; return true; } return false; } public void ThrowIfRecentConnectionFailure() { var remainingDelay = this.RemainingRetryDelay; if (remainingDelay > TimeSpan.Zero) { throw new ConnectionFailedException($"Unable to connect to {this.Endpoint}, will retry after {remainingDelay.TotalMilliseconds}ms"); } } } } }
/* * 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; using System.Collections.Generic; /** * @brief Collection of variable/function/method definitions */ namespace OpenSim.Region.ScriptEngine.Yengine { public class VarDict: IEnumerable { public VarDict outerVarDict; // next outer VarDict to search public TokenDeclSDTypeClass thisClass; // this VarDict is for members of thisClass private struct ArgTypes { public TokenType[] argTypes; public bool CanBeCalledBy(TokenType[] calledBy) { if((argTypes == null) && (calledBy == null)) return true; if((argTypes == null) || (calledBy == null)) return false; if(argTypes.Length != calledBy.Length) return false; for(int i = argTypes.Length; --i >= 0;) { if(!TypeCast.IsAssignableFrom(argTypes[i], calledBy[i])) return false; } return true; } public override bool Equals(Object that) { if(that == null) return false; if(that.GetType() != typeof(ArgTypes)) return false; TokenType[] at = this.argTypes; TokenType[] bt = ((ArgTypes)that).argTypes; if((at == null) && (bt == null)) return true; if((at == null) || (bt == null)) return false; if(at.Length != bt.Length) return false; for(int i = at.Length; --i >= 0;) { if(at[i].ToString() != bt[i].ToString()) return false; } return true; } public override int GetHashCode() { TokenType[] at = this.argTypes; if(at == null) return -1; int hc = 0; for(int i = at.Length; --i >= 0;) { int c = (hc < 0) ? 1 : 0; hc = hc * 2 + c; hc ^= at[i].ToString().GetHashCode(); } return hc; } } private struct TDVEntry { public int count; public TokenDeclVar var; } private bool isFrozen = false; private bool locals; private Dictionary<string, Dictionary<ArgTypes, TDVEntry>> master = new Dictionary<string, Dictionary<ArgTypes, TDVEntry>>(); private int count = 0; private VarDict frozenLocals = null; /** * @brief Constructor. * @param locals = false: cannot be frozen, allows forward references * true: can be frozen, thus forbidding forward references */ public VarDict(bool locals) { this.locals = locals; } /** * @brief Add new variable to the dictionary. */ public bool AddEntry(TokenDeclVar var) { if(isFrozen) { throw new Exception("var dict is frozen"); } // Make sure we have a sub-dictionary based on the bare name (ie, no signature) Dictionary<ArgTypes, TDVEntry> typedic; if(!master.TryGetValue(var.name.val, out typedic)) { typedic = new Dictionary<ArgTypes, TDVEntry>(); master.Add(var.name.val, typedic); } // See if there is an entry in the sub-dictionary that matches the argument signature. // Note that fields have null argument lists. // Methods always have a non-null argument list, even if only 0 entries long. ArgTypes types; types.argTypes = (var.argDecl == null) ? null : KeyTypesToStringTypes(var.argDecl.types); if(typedic.ContainsKey(types)) return false; // It is unique, add to its name-specific sub-dictionary. TDVEntry entry; entry.count = ++count; entry.var = var; typedic.Add(types, entry); return true; } public int Count { get { return count; } } /** * @brief If this is not a local variable frame, just return the frame as is. * If this is a local variable frame, return a version that is frozen, * ie, one that does not contain any future additions. */ public VarDict FreezeLocals() { // If not local var frame, return original frame as is. // This will allow forward references as the future additions // will be seen by lookups done in this dictionary. if(!locals) return this; // If local var frame, return a copy frozen at this point. // This disallows forward referenes as those future additions // will not be seen by lookups done in the frozen dictionary. if((frozenLocals == null) || (frozenLocals.count != this.count)) { // Make a copy of the current var dictionary frame. // We copy a reference to the dictionary, and though it may // contain additions made after this point, those additions // will have a count .gt. frozen count and will be ignored. frozenLocals = new VarDict(true); frozenLocals.outerVarDict = this.outerVarDict; frozenLocals.thisClass = this.thisClass; frozenLocals.master = this.master; frozenLocals.count = this.count; frozenLocals.frozenLocals = frozenLocals; // Mark it as being frozen. // - assert fail if any attempt is made to add to it // - ignore any additions to the dictionary with greater count frozenLocals.isFrozen = true; } return frozenLocals; } /** * @brief Find all functions/variables that are callable * @param name = name of function/variable to look for * @param argTypes = the argument types the function is being called with * null to look for a variable * @returns null: no matching function/variable found * else: list of matching functions/variables * for variables, always of length 1 */ private List<TokenDeclVar> found = new List<TokenDeclVar>(); public TokenDeclVar[] FindCallables(string name, TokenType[] argTypes) { argTypes = KeyTypesToStringTypes(argTypes); TokenDeclVar var = FindExact(name, argTypes); if(var != null) return new TokenDeclVar[] { var }; Dictionary<ArgTypes, TDVEntry> typedic; if(!master.TryGetValue(name, out typedic)) return null; found.Clear(); foreach(KeyValuePair<ArgTypes, TDVEntry> kvp in typedic) { if((kvp.Value.count <= this.count) && kvp.Key.CanBeCalledBy(argTypes)) { found.Add(kvp.Value.var); } } return (found.Count > 0) ? found.ToArray() : null; } /** * @brief Find exact matching function/variable * @param name = name of function to look for * @param argTypes = argument types the function was declared with * null to look for a variable * @returns null: no matching function/variable found * else: the matching function/variable */ public TokenDeclVar FindExact(string name, TokenType[] argTypes) { // Look for list of stuff that matches the given name. Dictionary<ArgTypes, TDVEntry> typedic; if(!master.TryGetValue(name, out typedic)) return null; // Loop through all fields/methods declared by that name, regardless of arg signature. foreach(TDVEntry entry in typedic.Values) { if(entry.count > this.count) continue; TokenDeclVar var = entry.var; // Get argument types of declaration. // fields are always null // methods are always non-null, though may be zero-length TokenType[] declArgs = (var.argDecl == null) ? null : var.argDecl.types; // Convert any key args to string args. declArgs = KeyTypesToStringTypes(declArgs); // If both are null, they are signature-less (ie, both are fields), and so match. if((declArgs == null) && (argTypes == null)) return var; // If calling a delegate, it is a match, regardless of delegate arg types. // If it turns out the arg types do not match, the compiler will give an error // trying to cast the arguments to the delegate arg types. // We don't allow overloading same field name with different delegate types. if((declArgs == null) && (argTypes != null)) { TokenType fieldType = var.type; if(fieldType is TokenTypeSDTypeDelegate) return var; } // If not both null, no match, keep looking. if((declArgs == null) || (argTypes == null)) continue; // Both not null, match argument types to make sure we have correct overload. int i = declArgs.Length; if(i != argTypes.Length) continue; while(--i >= 0) { string da = declArgs[i].ToString(); string ga = argTypes[i].ToString(); if(da == "key") da = "string"; if(ga == "key") ga = "string"; if(da != ga) break; } if(i < 0) return var; } // No match. return null; } /** * @brief Replace any TokenTypeKey elements with TokenTypeStr so that * it doesn't matter if functions are declared with key or string, * they will accept either. * @param argTypes = argument types as declared in source code * @returns argTypes with any key replaced by string */ private static TokenType[] KeyTypesToStringTypes(TokenType[] argTypes) { if(argTypes != null) { int i; int nats = argTypes.Length; for(i = nats; --i >= 0;) { if(argTypes[i] is TokenTypeKey) break; } if(i >= 0) { TokenType[] at = new TokenType[nats]; for(i = nats; --i >= 0;) { at[i] = argTypes[i]; if(argTypes[i] is TokenTypeKey) { at[i] = new TokenTypeStr(argTypes[i]); } } return at; } } return argTypes; } // foreach goes through all the TokenDeclVars that were added // IEnumerable public IEnumerator GetEnumerator() { return new VarDictEnumerator(this.master, this.count); } private class VarDictEnumerator: IEnumerator { private IEnumerator masterEnum; private IEnumerator typedicEnum; private int count; public VarDictEnumerator(Dictionary<string, Dictionary<ArgTypes, TDVEntry>> master, int count) { masterEnum = master.Values.GetEnumerator(); this.count = count; } // IEnumerator public void Reset() { masterEnum.Reset(); typedicEnum = null; } // IEnumerator public bool MoveNext() { while(true) { if(typedicEnum != null) { while(typedicEnum.MoveNext()) { if(((TDVEntry)typedicEnum.Current).count <= this.count) return true; } typedicEnum = null; } if(!masterEnum.MoveNext()) return false; Dictionary<ArgTypes, TDVEntry> ctd; ctd = (Dictionary<ArgTypes, TDVEntry>)masterEnum.Current; typedicEnum = ctd.Values.GetEnumerator(); } } // IEnumerator public object Current { get { return ((TDVEntry)typedicEnum.Current).var; } } } } }
/* **************************************************************************** * * Copyright (c) Microsoft Corporation. * * This source code is subject to terms and conditions of the Apache License, Version 2.0. A * copy of the license can be found in the License.html file at the root of this distribution. If * you cannot locate the Apache License, Version 2.0, please send an email to * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound * by the terms of the Apache License, Version 2.0. * * You must not remove this notice, or any other, from this software. * * * ***************************************************************************/ using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Dynamic; using System.Dynamic.Utils; using System.Runtime.CompilerServices; #if CLR2 namespace Microsoft.Scripting.Ast.Compiler { using Microsoft.Scripting.Utils; #else namespace System.Linq.Expressions.Compiler { #endif internal static partial class DelegateHelpers { private static TypeInfo _DelegateCache = new TypeInfo(); #region Generated Maximum Delegate Arity // *** BEGIN GENERATED CODE *** // generated by function: gen_max_delegate_arity from: generate_dynsites.py private const int MaximumArity = 17; // *** END GENERATED CODE *** #endregion internal class TypeInfo { public Type DelegateType; public Dictionary<Type, TypeInfo> TypeChain; public Type MakeDelegateType(Type retType, params Expression[] args) { return MakeDelegateType(retType, (IList<Expression>)args); } public Type MakeDelegateType(Type retType, IList<Expression> args) { // nope, go ahead and create it and spend the // cost of creating the array. Type[] paramTypes = new Type[args.Count + 2]; paramTypes[0] = typeof(CallSite); paramTypes[paramTypes.Length - 1] = retType; for (int i = 0; i < args.Count; i++) { paramTypes[i + 1] = args[i].Type; } return DelegateType = MakeNewDelegate(paramTypes); } } /// <summary> /// Finds a delegate type using the types in the array. /// We use the cache to avoid copying the array, and to cache the /// created delegate type /// </summary> internal static Type MakeDelegateType(Type[] types) { lock (_DelegateCache) { TypeInfo curTypeInfo = _DelegateCache; // arguments & return type for (int i = 0; i < types.Length; i++) { curTypeInfo = NextTypeInfo(types[i], curTypeInfo); } // see if we have the delegate already if (curTypeInfo.DelegateType == null) { // clone because MakeCustomDelegate can hold onto the array. curTypeInfo.DelegateType = MakeNewDelegate((Type[])types.Clone()); } return curTypeInfo.DelegateType; } } /// <summary> /// Finds a delegate type for a CallSite using the types in the ReadOnlyCollection of Expression. /// /// We take the readonly collection of Expression explicitly to avoid allocating memory (an array /// of types) on lookup of delegate types. /// </summary> internal static Type MakeCallSiteDelegate(ReadOnlyCollection<Expression> types, Type returnType) { lock (_DelegateCache) { TypeInfo curTypeInfo = _DelegateCache; // CallSite curTypeInfo = NextTypeInfo(typeof(CallSite), curTypeInfo); // arguments for (int i = 0; i < types.Count; i++) { curTypeInfo = NextTypeInfo(types[i].Type, curTypeInfo); } // return type curTypeInfo = NextTypeInfo(returnType, curTypeInfo); // see if we have the delegate already if (curTypeInfo.DelegateType == null) { curTypeInfo.MakeDelegateType(returnType, types); } return curTypeInfo.DelegateType; } } /// <summary> /// Finds a delegate type for a CallSite using the MetaObject array. /// /// We take the array of MetaObject explicitly to avoid allocating memory (an array of types) on /// lookup of delegate types. /// </summary> internal static Type MakeDeferredSiteDelegate(DynamicMetaObject[] args, Type returnType) { lock (_DelegateCache) { TypeInfo curTypeInfo = _DelegateCache; // CallSite curTypeInfo = NextTypeInfo(typeof(CallSite), curTypeInfo); // arguments for (int i = 0; i < args.Length; i++) { DynamicMetaObject mo = args[i]; Type paramType = mo.Expression.Type; if (IsByRef(mo)) { paramType = paramType.MakeByRefType(); } curTypeInfo = NextTypeInfo(paramType, curTypeInfo); } // return type curTypeInfo = NextTypeInfo(returnType, curTypeInfo); // see if we have the delegate already if (curTypeInfo.DelegateType == null) { // nope, go ahead and create it and spend the // cost of creating the array. Type[] paramTypes = new Type[args.Length + 2]; paramTypes[0] = typeof(CallSite); paramTypes[paramTypes.Length - 1] = returnType; for (int i = 0; i < args.Length; i++) { DynamicMetaObject mo = args[i]; Type paramType = mo.Expression.Type; if (IsByRef(mo)) { paramType = paramType.MakeByRefType(); } paramTypes[i + 1] = paramType; } curTypeInfo.DelegateType = MakeNewDelegate(paramTypes); } return curTypeInfo.DelegateType; } } private static bool IsByRef(DynamicMetaObject mo) { ParameterExpression pe = mo.Expression as ParameterExpression; return pe != null && pe.IsByRef; } internal static TypeInfo NextTypeInfo(Type initialArg) { lock (_DelegateCache) { return NextTypeInfo(initialArg, _DelegateCache); } } internal static TypeInfo GetNextTypeInfo(Type initialArg, TypeInfo curTypeInfo) { lock (_DelegateCache) { return NextTypeInfo(initialArg, curTypeInfo); } } private static TypeInfo NextTypeInfo(Type initialArg, TypeInfo curTypeInfo) { Type lookingUp = initialArg; TypeInfo nextTypeInfo; if (curTypeInfo.TypeChain == null) { curTypeInfo.TypeChain = new Dictionary<Type, TypeInfo>(); } if (!curTypeInfo.TypeChain.TryGetValue(lookingUp, out nextTypeInfo)) { nextTypeInfo = new TypeInfo(); if (TypeUtils.CanCache(lookingUp)) { curTypeInfo.TypeChain[lookingUp] = nextTypeInfo; } } return nextTypeInfo; } /// <summary> /// Creates a new delegate, or uses a func/action /// Note: this method does not cache /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")] private static Type MakeNewDelegate(Type[] types) { Debug.Assert(types != null && types.Length > 0); // Can only used predefined delegates if we have no byref types and // the arity is small enough to fit in Func<...> or Action<...> if (types.Length > MaximumArity || types.Any(t => t.IsByRef)) { return MakeNewCustomDelegate(types); } Type result; if (types[types.Length - 1] == typeof(void)) { result = GetActionType(types.RemoveLast()); } else { result = GetFuncType(types); } Debug.Assert(result != null); return result; } internal static Type GetFuncType(Type[] types) { switch (types.Length) { #region Generated Delegate Func Types // *** BEGIN GENERATED CODE *** // generated by function: gen_delegate_func from: generate_dynsites.py case 1: return typeof(Func<>).MakeGenericType(types); case 2: return typeof(Func<,>).MakeGenericType(types); case 3: return typeof(Func<,,>).MakeGenericType(types); case 4: return typeof(Func<,,,>).MakeGenericType(types); case 5: return typeof(Func<,,,,>).MakeGenericType(types); case 6: return typeof(Func<,,,,,>).MakeGenericType(types); case 7: return typeof(Func<,,,,,,>).MakeGenericType(types); case 8: return typeof(Func<,,,,,,,>).MakeGenericType(types); case 9: return typeof(Func<,,,,,,,,>).MakeGenericType(types); case 10: return typeof(Func<,,,,,,,,,>).MakeGenericType(types); case 11: return typeof(Func<,,,,,,,,,,>).MakeGenericType(types); case 12: return typeof(Func<,,,,,,,,,,,>).MakeGenericType(types); case 13: return typeof(Func<,,,,,,,,,,,,>).MakeGenericType(types); case 14: return typeof(Func<,,,,,,,,,,,,,>).MakeGenericType(types); case 15: return typeof(Func<,,,,,,,,,,,,,,>).MakeGenericType(types); case 16: return typeof(Func<,,,,,,,,,,,,,,,>).MakeGenericType(types); case 17: return typeof(Func<,,,,,,,,,,,,,,,,>).MakeGenericType(types); // *** END GENERATED CODE *** #endregion default: return null; } } internal static Type GetActionType(Type[] types) { switch (types.Length) { case 0: return typeof(Action); #region Generated Delegate Action Types // *** BEGIN GENERATED CODE *** // generated by function: gen_delegate_action from: generate_dynsites.py case 1: return typeof(Action<>).MakeGenericType(types); case 2: return typeof(Action<,>).MakeGenericType(types); case 3: return typeof(Action<,,>).MakeGenericType(types); case 4: return typeof(Action<,,,>).MakeGenericType(types); case 5: return typeof(Action<,,,,>).MakeGenericType(types); case 6: return typeof(Action<,,,,,>).MakeGenericType(types); case 7: return typeof(Action<,,,,,,>).MakeGenericType(types); case 8: return typeof(Action<,,,,,,,>).MakeGenericType(types); case 9: return typeof(Action<,,,,,,,,>).MakeGenericType(types); case 10: return typeof(Action<,,,,,,,,,>).MakeGenericType(types); case 11: return typeof(Action<,,,,,,,,,,>).MakeGenericType(types); case 12: return typeof(Action<,,,,,,,,,,,>).MakeGenericType(types); case 13: return typeof(Action<,,,,,,,,,,,,>).MakeGenericType(types); case 14: return typeof(Action<,,,,,,,,,,,,,>).MakeGenericType(types); case 15: return typeof(Action<,,,,,,,,,,,,,,>).MakeGenericType(types); case 16: return typeof(Action<,,,,,,,,,,,,,,,>).MakeGenericType(types); // *** END GENERATED CODE *** #endregion default: return null; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Orleans.Streams; using Orleans.Runtime.Scheduler; using Orleans.Runtime.Versions; using Orleans.Versions; using Orleans.Versions.Compatibility; using Orleans.Versions.Selector; namespace Orleans.Runtime { internal class TypeManager : SystemTarget, IClusterTypeManager, ISiloTypeManager, ISiloStatusListener, IDisposable { private readonly ILogger logger; private readonly GrainTypeManager grainTypeManager; private readonly ISiloStatusOracle statusOracle; private readonly ImplicitStreamSubscriberTable implicitStreamSubscriberTable; private readonly IInternalGrainFactory grainFactory; private readonly CachedVersionSelectorManager versionSelectorManager; private readonly OrleansTaskScheduler scheduler; private readonly TimeSpan refreshClusterMapInterval; private bool hasToRefreshClusterGrainInterfaceMap; private IDisposable refreshClusterGrainInterfaceMapTimer; private IVersionStore versionStore; internal TypeManager( SiloAddress myAddr, GrainTypeManager grainTypeManager, ISiloStatusOracle oracle, OrleansTaskScheduler scheduler, TimeSpan refreshClusterMapInterval, ImplicitStreamSubscriberTable implicitStreamSubscriberTable, IInternalGrainFactory grainFactory, CachedVersionSelectorManager versionSelectorManager, ILoggerFactory loggerFactory) : base(Constants.TypeManagerId, myAddr, loggerFactory) { if (grainTypeManager == null) throw new ArgumentNullException(nameof(grainTypeManager)); if (oracle == null) throw new ArgumentNullException(nameof(oracle)); if (scheduler == null) throw new ArgumentNullException(nameof(scheduler)); if (implicitStreamSubscriberTable == null) throw new ArgumentNullException(nameof(implicitStreamSubscriberTable)); this.logger = loggerFactory.CreateLogger<TypeManager>(); this.grainTypeManager = grainTypeManager; this.statusOracle = oracle; this.implicitStreamSubscriberTable = implicitStreamSubscriberTable; this.grainFactory = grainFactory; this.versionSelectorManager = versionSelectorManager; this.scheduler = scheduler; this.refreshClusterMapInterval = refreshClusterMapInterval; // We need this so we can place needed local activations this.grainTypeManager.SetInterfaceMapsBySilo(new Dictionary<SiloAddress, GrainInterfaceMap> { {this.Silo, grainTypeManager.GetTypeCodeMap()} }); } internal async Task Initialize(IVersionStore store) { this.versionStore = store; this.hasToRefreshClusterGrainInterfaceMap = true; await this.OnRefreshClusterMapTimer(null); this.refreshClusterGrainInterfaceMapTimer = this.RegisterTimer( OnRefreshClusterMapTimer, null, this.refreshClusterMapInterval, this.refreshClusterMapInterval); } public Task<IGrainTypeResolver> GetClusterGrainTypeResolver() { return Task.FromResult<IGrainTypeResolver>(grainTypeManager.GrainTypeResolver); } public Task<GrainInterfaceMap> GetSiloTypeCodeMap() { return Task.FromResult(grainTypeManager.GetTypeCodeMap()); } public Task<ImplicitStreamSubscriberTable> GetImplicitStreamSubscriberTable(SiloAddress silo) { return Task.FromResult(implicitStreamSubscriberTable); } public void SiloStatusChangeNotification(SiloAddress updatedSilo, SiloStatus status) { hasToRefreshClusterGrainInterfaceMap = true; } private async Task OnRefreshClusterMapTimer(object _) { // Check if we have to refresh if (!hasToRefreshClusterGrainInterfaceMap) { logger.Trace("OnRefreshClusterMapTimer: no refresh required"); return; } hasToRefreshClusterGrainInterfaceMap = false; logger.Info("OnRefreshClusterMapTimer: refresh start"); var activeSilos = statusOracle.GetApproximateSiloStatuses(onlyActive: true); var knownSilosClusterGrainInterfaceMap = grainTypeManager.GrainInterfaceMapsBySilo; // Build the new map. Always start by himself var newSilosClusterGrainInterfaceMap = new Dictionary<SiloAddress, GrainInterfaceMap> { {this.Silo, grainTypeManager.GetTypeCodeMap()} }; var getGrainInterfaceMapTasks = new List<Task<KeyValuePair<SiloAddress, GrainInterfaceMap>>>(); foreach (var siloAddress in activeSilos.Keys) { if (siloAddress.Equals(this.Silo)) continue; GrainInterfaceMap value; if (knownSilosClusterGrainInterfaceMap.TryGetValue(siloAddress, out value)) { logger.Trace($"OnRefreshClusterMapTimer: value already found locally for {siloAddress}"); newSilosClusterGrainInterfaceMap[siloAddress] = value; } else { // Value not found, let's get it logger.Trace($"OnRefreshClusterMapTimer: value not found locally for {siloAddress}"); getGrainInterfaceMapTasks.Add(GetTargetSiloGrainInterfaceMap(siloAddress)); } } if (getGrainInterfaceMapTasks.Any()) { foreach (var keyValuePair in await Task.WhenAll(getGrainInterfaceMapTasks)) { if (keyValuePair.Value != null) newSilosClusterGrainInterfaceMap.Add(keyValuePair.Key, keyValuePair.Value); } } grainTypeManager.SetInterfaceMapsBySilo(newSilosClusterGrainInterfaceMap); if (this.versionStore.IsEnabled) { await this.GetAndSetDefaultCompatibilityStrategy(); foreach (var kvp in await GetStoredCompatibilityStrategies()) { this.versionSelectorManager.CompatibilityDirectorManager.SetStrategy(kvp.Key, kvp.Value); } await this.GetAndSetDefaultSelectorStrategy(); foreach (var kvp in await GetSelectorStrategies()) { this.versionSelectorManager.VersionSelectorManager.SetSelector(kvp.Key, kvp.Value); } } versionSelectorManager.ResetCache(); } private async Task GetAndSetDefaultSelectorStrategy() { try { var strategy = await this.versionStore.GetSelectorStrategy(); this.versionSelectorManager.VersionSelectorManager.SetSelector(strategy); } catch (Exception) { hasToRefreshClusterGrainInterfaceMap = true; } } private async Task GetAndSetDefaultCompatibilityStrategy() { try { var strategy = await this.versionStore.GetCompatibilityStrategy(); this.versionSelectorManager.CompatibilityDirectorManager.SetStrategy(strategy); } catch (Exception) { hasToRefreshClusterGrainInterfaceMap = true; } } private async Task<Dictionary<int, CompatibilityStrategy>> GetStoredCompatibilityStrategies() { try { return await this.versionStore.GetCompatibilityStrategies(); } catch (Exception) { hasToRefreshClusterGrainInterfaceMap = true; return new Dictionary<int, CompatibilityStrategy>(); } } private async Task<Dictionary<int, VersionSelectorStrategy>> GetSelectorStrategies() { try { return await this.versionStore.GetSelectorStrategies(); } catch (Exception) { hasToRefreshClusterGrainInterfaceMap = true; return new Dictionary<int, VersionSelectorStrategy>(); } } private async Task<KeyValuePair<SiloAddress, GrainInterfaceMap>> GetTargetSiloGrainInterfaceMap(SiloAddress siloAddress) { try { var remoteTypeManager = this.grainFactory.GetSystemTarget<ISiloTypeManager>(Constants.TypeManagerId, siloAddress); var siloTypeCodeMap = await scheduler.QueueTask(() => remoteTypeManager.GetSiloTypeCodeMap(), SchedulingContext); return new KeyValuePair<SiloAddress, GrainInterfaceMap>(siloAddress, siloTypeCodeMap); } catch (Exception ex) { // Will be retried on the next timer hit logger.Error(ErrorCode.TypeManager_GetSiloGrainInterfaceMapError, $"Exception when trying to get GrainInterfaceMap for silos {siloAddress}", ex); hasToRefreshClusterGrainInterfaceMap = true; return new KeyValuePair<SiloAddress, GrainInterfaceMap>(siloAddress, null); } } public void Dispose() { if (this.refreshClusterGrainInterfaceMapTimer != null) { this.refreshClusterGrainInterfaceMapTimer.Dispose(); } } } }
/* * Copyright (c) Contributors, http://aurora-sim.org/, 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 Aurora-Sim 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.IO; using System.Linq; using System.Reflection; using System.Text.RegularExpressions; using System.Threading; using OpenMetaverse; using OpenMetaverse.Assets; using Aurora.Framework; using OpenSim.Region.Framework.Scenes.Serialization; using OpenSim.Services.Interfaces; namespace OpenSim.Region.Framework.Scenes { ///<summary> /// Gather uuids for a given entity. ///</summary> ///This does a deep inspection of the entity to retrieve all the assets it uses (whether as textures, as scripts ///contained in inventory, as scripts contained in objects contained in another object's inventory, etc. Assets ///are only retrieved when they are necessary to carry out the inspection (i.e. a serialized object needs to be ///retrieved to work out which assets it references). public class UuidGatherer { /// <summary> /// Asset cache used for gathering assets /// </summary> protected IAssetService m_assetCache; /// <summary> /// Used as a temporary store of an asset which represents an object. This can be a null if no appropriate /// asset was found by the asset service. /// </summary> protected AssetBase m_requestedObjectAsset; /// <summary> /// Signal whether we are currently waiting for the asset service to deliver an asset. /// </summary> protected bool m_waitingForObjectAsset; public UuidGatherer(IAssetService assetCache) { m_assetCache = assetCache; } /// <summary> /// Gather all the asset uuids associated with the asset referenced by a given uuid /// </summary> /// This includes both those directly associated with /// it (e.g. face textures) and recursively, those of items within it's inventory (e.g. objects contained /// within this object). /// <param name = "assetUuid">The uuid of the asset for which to gather referenced assets</param> /// <param name = "assetType">The type of the asset for the uuid given</param> /// <param name = "assetUuids">The assets gathered</param> public void GatherAssetUuids(UUID assetUuid, AssetType assetType, IDictionary<UUID, AssetType> assetUuids, IRegistryCore scene) { // avoid infinite loops if (assetUuids.ContainsKey(assetUuid)) return; assetUuids[assetUuid] = assetType; if (AssetType.Bodypart == assetType || AssetType.Clothing == assetType) { GetWearableAssetUuids(assetUuid, assetUuids); } else if (AssetType.Gesture == assetType) { GetGestureAssetUuids(assetUuid, assetUuids); } else if (AssetType.LSLText == assetType) { GetScriptAssetUuids(assetUuid, assetUuids); } else if (AssetType.Object == assetType) { GetSceneObjectAssetUuids(assetUuid, assetUuids, scene); } } /// <summary> /// Gather all the asset uuids associated with a given object. /// </summary> /// This includes both those directly associated with /// it (e.g. face textures) and recursively, those of items within it's inventory (e.g. objects contained /// within this object). /// <param name = "sceneObject">The scene object for which to gather assets</param> /// <param name = "assetUuids">The assets gathered</param> public void GatherAssetUuids(ISceneEntity sceneObject, IDictionary<UUID, AssetType> assetUuids, IRegistryCore scene) { // MainConsole.Instance.DebugFormat( // "[ASSET GATHERER]: Getting assets for object {0}, {1}", sceneObject.Name, sceneObject.UUID); ISceneChildEntity[] parts = sceneObject.ChildrenEntities().ToArray(); foreach (ISceneChildEntity part in parts) { // MainConsole.Instance.DebugFormat( // "[ARCHIVER]: Getting part {0}, {1} for object {2}", part.Name, part.UUID, sceneObject.UUID); try { Primitive.TextureEntry textureEntry = part.Shape.Textures; if (textureEntry != null) { // Get the prim's default texture. This will be used for faces which don't have their own texture if (textureEntry.DefaultTexture != null) assetUuids[textureEntry.DefaultTexture.TextureID] = AssetType.Texture; if (textureEntry.FaceTextures != null) { // Loop through the rest of the texture faces (a non-null face means the face is different from DefaultTexture) #if (!ISWIN) foreach (Primitive.TextureEntryFace texture in textureEntry.FaceTextures) { if (texture != null) { assetUuids[texture.TextureID] = AssetType.Texture; } } #else foreach (Primitive.TextureEntryFace texture in textureEntry.FaceTextures.Where(texture => texture != null)) { assetUuids[texture.TextureID] = AssetType.Texture; } #endif } } // If the prim is a sculpt then preserve this information too if (part.Shape.SculptTexture != UUID.Zero) assetUuids[part.Shape.SculptTexture] = AssetType.Texture; TaskInventoryDictionary taskDictionary = (TaskInventoryDictionary) part.TaskInventory.Clone(); // Now analyze this prim's inventory items to preserve all the uuids that they reference #if (!ISWIN) foreach (TaskInventoryItem tii in taskDictionary.Values) { if (!assetUuids.ContainsKey(tii.AssetID)) { GatherAssetUuids(tii.AssetID, (AssetType) tii.Type, assetUuids, scene); } } #else foreach (TaskInventoryItem tii in taskDictionary.Values.Where(tii => !assetUuids.ContainsKey(tii.AssetID))) { GatherAssetUuids(tii.AssetID, (AssetType) tii.Type, assetUuids, scene); } #endif } catch (Exception e) { MainConsole.Instance.ErrorFormat("[UUID GATHERER]: Failed to get part - {0}", e); MainConsole.Instance.DebugFormat( "[UUID GATHERER]: Texture entry length for prim was {0} (min is 46)", part.Shape.TextureEntry.Length); } } } /// <summary> /// The callback made when we request the asset for an object from the asset service. /// </summary> protected void AssetReceived(string id, Object sender, AssetBase asset) { lock (this) { m_requestedObjectAsset = asset; m_waitingForObjectAsset = false; Monitor.Pulse(this); } } /// <summary> /// Get an asset synchronously, potentially using an asynchronous callback. If the /// asynchronous callback is used, we will wait for it to complete. /// </summary> /// <param name = "uuid"></param> /// <returns></returns> protected virtual AssetBase GetAsset(UUID uuid) { m_waitingForObjectAsset = true; m_assetCache.Get(uuid.ToString(), this, AssetReceived); // The asset cache callback can either // // 1. Complete on the same thread (if the asset is already in the cache) or // 2. Come in via a different thread (if we need to go fetch it). // // The code below handles both these alternatives. lock (this) { if (m_waitingForObjectAsset) { Monitor.Wait(this); m_waitingForObjectAsset = false; } } return m_requestedObjectAsset; } /// <summary> /// Record the asset uuids embedded within the given script. /// </summary> /// <param name = "scriptUuid"></param> /// <param name = "assetUuids">Dictionary in which to record the references</param> protected void GetScriptAssetUuids(UUID scriptUuid, IDictionary<UUID, AssetType> assetUuids) { AssetBase scriptAsset = GetAsset(scriptUuid); if (null != scriptAsset) { string script = Utils.BytesToString(scriptAsset.Data); //MainConsole.Instance.DebugFormat("[ARCHIVER]: Script {0}", script); MatchCollection uuidMatches = Util.UUIDPattern.Matches(script); //MainConsole.Instance.DebugFormat("[ARCHIVER]: Found {0} matches in script", uuidMatches.Count); foreach (UUID uuid in from Match uuidMatch in uuidMatches select new UUID(uuidMatch.Value)) { //MainConsole.Instance.DebugFormat("[ARCHIVER]: Recording {0} in script", uuid); // Assume AssetIDs embedded in scripts are textures assetUuids[uuid] = AssetType.Texture; } } } /// <summary> /// Record the uuids referenced by the given wearable asset /// </summary> /// <param name = "wearableAssetUuid"></param> /// <param name = "assetUuids">Dictionary in which to record the references</param> protected void GetWearableAssetUuids(UUID wearableAssetUuid, IDictionary<UUID, AssetType> assetUuids) { AssetBase assetBase = GetAsset(wearableAssetUuid); if (null != assetBase) { //MainConsole.Instance.Debug(new System.Text.ASCIIEncoding().GetString(bodypartAsset.Data)); AssetWearable wearableAsset = new AssetBodypart(wearableAssetUuid, assetBase.Data); wearableAsset.Decode(); //MainConsole.Instance.DebugFormat( // "[ARCHIVER]: Wearable asset {0} references {1} assets", wearableAssetUuid, wearableAsset.Textures.Count); foreach (UUID uuid in wearableAsset.Textures.Values) { assetUuids[uuid] = AssetType.Texture; } } } /// <summary> /// Get all the asset uuids associated with a given object. This includes both those directly associated with /// it (e.g. face textures) and recursively, those of items within it's inventory (e.g. objects contained /// within this object). /// </summary> /// <param name = "sceneObject"></param> /// <param name = "assetUuids"></param> protected void GetSceneObjectAssetUuids(UUID sceneObjectUuid, IDictionary<UUID, AssetType> assetUuids, IRegistryCore scene) { AssetBase objectAsset = GetAsset(sceneObjectUuid); if (null != objectAsset) { string xml = Utils.BytesToString(objectAsset.Data); SceneObjectGroup group = SceneObjectSerializer.FromOriginalXmlFormat(xml, scene); if (group == null) return; GatherAssetUuids(group, assetUuids, scene); } } /// <summary> /// Get the asset uuid associated with a gesture /// </summary> /// <param name = "gestureUuid"></param> /// <param name = "assetUuids"></param> protected void GetGestureAssetUuids(UUID gestureUuid, IDictionary<UUID, AssetType> assetUuids) { AssetBase assetBase = GetAsset(gestureUuid); if (null == assetBase) return; MemoryStream ms = new MemoryStream(assetBase.Data); StreamReader sr = new StreamReader(ms); sr.ReadLine(); // Unknown (Version?) sr.ReadLine(); // Unknown sr.ReadLine(); // Unknown sr.ReadLine(); // Name sr.ReadLine(); // Comment ? int count = Convert.ToInt32(sr.ReadLine()); // Item count for (int i = 0; i < count; i++) { string type = sr.ReadLine(); if (type == null) break; string name = sr.ReadLine(); if (name == null) break; string id = sr.ReadLine(); if (id == null) break; string unknown = sr.ReadLine(); if (unknown == null) break; // If it can be parsed as a UUID, it is an asset ID UUID uuid; if (UUID.TryParse(id, out uuid)) assetUuids[uuid] = AssetType.Animation; } } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Description; using Infopulse.EDemocracy.Web.Areas.HelpPage.ModelDescriptions; using Infopulse.EDemocracy.Web.Areas.HelpPage.Models; namespace Infopulse.EDemocracy.Web.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } // Example: // [TypeConverter(typeof(PointConverter))] // public class Point // { // public Point(int x, int y) // { // X = x; // Y = y; // } // public int X { get; set; } // public int Y { get; set; } // } // Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection. // // public class Point // { // public int X { get; set; } // public int Y { get; set; } // } // Regular complex class Point will have properties X and Y added to UriParameters collection. if (complexTypeDescription != null && !IsBindableWithTypeConverter(parameterType)) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static bool IsBindableWithTypeConverter(Type parameterType) { if (parameterType == null) { return false; } return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string)); } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
#region Copyright notice and license // Copyright 2015, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #endregion using System; using System.Collections.Generic; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using CommandLine; using Google.Apis.Auth.OAuth2; using Google.Protobuf; using Grpc.Auth; using Grpc.Core; using Grpc.Core.Utils; using Grpc.Testing; using NUnit.Framework; using CommandLine.Text; using System.IO; namespace Grpc.IntegrationTesting { public class InteropClient { private class ClientOptions { [Option("server_host", DefaultValue = "127.0.0.1")] public string ServerHost { get; set; } [Option("server_host_override", DefaultValue = TestCredentials.DefaultHostOverride)] public string ServerHostOverride { get; set; } [Option("server_port", Required = true)] public int ServerPort { get; set; } [Option("test_case", DefaultValue = "large_unary")] public string TestCase { get; set; } [Option("use_tls")] public bool UseTls { get; set; } [Option("use_test_ca")] public bool UseTestCa { get; set; } [Option("default_service_account", Required = false)] public string DefaultServiceAccount { get; set; } [Option("oauth_scope", Required = false)] public string OAuthScope { get; set; } [Option("service_account_key_file", Required = false)] public string ServiceAccountKeyFile { get; set; } [HelpOption] public string GetUsage() { var help = new HelpText { Heading = "gRPC C# interop testing client", AddDashesToOption = true }; help.AddPreOptionsLine("Usage:"); help.AddOptions(this); return help; } } ClientOptions options; private InteropClient(ClientOptions options) { this.options = options; } public static void Run(string[] args) { var options = new ClientOptions(); if (!Parser.Default.ParseArguments(args, options)) { Environment.Exit(1); } var interopClient = new InteropClient(options); interopClient.Run().Wait(); } private async Task Run() { var credentials = options.UseTls ? TestCredentials.CreateTestClientCredentials(options.UseTestCa) : Credentials.Insecure; List<ChannelOption> channelOptions = null; if (!string.IsNullOrEmpty(options.ServerHostOverride)) { channelOptions = new List<ChannelOption> { new ChannelOption(ChannelOptions.SslTargetNameOverride, options.ServerHostOverride) }; } Console.WriteLine(options.ServerHost); Console.WriteLine(options.ServerPort); var channel = new Channel(options.ServerHost, options.ServerPort, credentials, channelOptions); TestService.TestServiceClient client = new TestService.TestServiceClient(channel); await RunTestCaseAsync(client, options); await channel.ShutdownAsync(); } private async Task RunTestCaseAsync(TestService.TestServiceClient client, ClientOptions options) { switch (options.TestCase) { case "empty_unary": RunEmptyUnary(client); break; case "large_unary": RunLargeUnary(client); break; case "client_streaming": await RunClientStreamingAsync(client); break; case "server_streaming": await RunServerStreamingAsync(client); break; case "ping_pong": await RunPingPongAsync(client); break; case "empty_stream": await RunEmptyStreamAsync(client); break; case "compute_engine_creds": await RunComputeEngineCredsAsync(client, options.DefaultServiceAccount, options.OAuthScope); break; case "jwt_token_creds": await RunJwtTokenCredsAsync(client, options.DefaultServiceAccount); break; case "oauth2_auth_token": await RunOAuth2AuthTokenAsync(client, options.DefaultServiceAccount, options.OAuthScope); break; case "per_rpc_creds": await RunPerRpcCredsAsync(client, options.DefaultServiceAccount, options.OAuthScope); break; case "cancel_after_begin": await RunCancelAfterBeginAsync(client); break; case "cancel_after_first_response": await RunCancelAfterFirstResponseAsync(client); break; case "timeout_on_sleeping_server": await RunTimeoutOnSleepingServerAsync(client); break; case "benchmark_empty_unary": RunBenchmarkEmptyUnary(client); break; default: throw new ArgumentException("Unknown test case " + options.TestCase); } } public static void RunEmptyUnary(TestService.ITestServiceClient client) { Console.WriteLine("running empty_unary"); var response = client.EmptyCall(new Empty()); Assert.IsNotNull(response); Console.WriteLine("Passed!"); } public static void RunLargeUnary(TestService.ITestServiceClient client) { Console.WriteLine("running large_unary"); var request = new SimpleRequest { ResponseType = PayloadType.COMPRESSABLE, ResponseSize = 314159, Payload = CreateZerosPayload(271828) }; var response = client.UnaryCall(request); Assert.AreEqual(PayloadType.COMPRESSABLE, response.Payload.Type); Assert.AreEqual(314159, response.Payload.Body.Length); Console.WriteLine("Passed!"); } public static async Task RunClientStreamingAsync(TestService.ITestServiceClient client) { Console.WriteLine("running client_streaming"); var bodySizes = new List<int> { 27182, 8, 1828, 45904 }.ConvertAll((size) => new StreamingInputCallRequest { Payload = CreateZerosPayload(size) }); using (var call = client.StreamingInputCall()) { await call.RequestStream.WriteAllAsync(bodySizes); var response = await call.ResponseAsync; Assert.AreEqual(74922, response.AggregatedPayloadSize); } Console.WriteLine("Passed!"); } public static async Task RunServerStreamingAsync(TestService.ITestServiceClient client) { Console.WriteLine("running server_streaming"); var bodySizes = new List<int> { 31415, 9, 2653, 58979 }; var request = new StreamingOutputCallRequest { ResponseType = PayloadType.COMPRESSABLE, ResponseParameters = { bodySizes.ConvertAll((size) => new ResponseParameters { Size = size }) } }; using (var call = client.StreamingOutputCall(request)) { var responseList = await call.ResponseStream.ToListAsync(); foreach (var res in responseList) { Assert.AreEqual(PayloadType.COMPRESSABLE, res.Payload.Type); } CollectionAssert.AreEqual(bodySizes, responseList.ConvertAll((item) => item.Payload.Body.Length)); } Console.WriteLine("Passed!"); } public static async Task RunPingPongAsync(TestService.ITestServiceClient client) { Console.WriteLine("running ping_pong"); using (var call = client.FullDuplexCall()) { await call.RequestStream.WriteAsync(new StreamingOutputCallRequest { ResponseType = PayloadType.COMPRESSABLE, ResponseParameters = { new ResponseParameters { Size = 31415 } }, Payload = CreateZerosPayload(27182) }); Assert.IsTrue(await call.ResponseStream.MoveNext()); Assert.AreEqual(PayloadType.COMPRESSABLE, call.ResponseStream.Current.Payload.Type); Assert.AreEqual(31415, call.ResponseStream.Current.Payload.Body.Length); await call.RequestStream.WriteAsync(new StreamingOutputCallRequest { ResponseType = PayloadType.COMPRESSABLE, ResponseParameters = { new ResponseParameters { Size = 9 } }, Payload = CreateZerosPayload(8) }); Assert.IsTrue(await call.ResponseStream.MoveNext()); Assert.AreEqual(PayloadType.COMPRESSABLE, call.ResponseStream.Current.Payload.Type); Assert.AreEqual(9, call.ResponseStream.Current.Payload.Body.Length); await call.RequestStream.WriteAsync(new StreamingOutputCallRequest { ResponseType = PayloadType.COMPRESSABLE, ResponseParameters = { new ResponseParameters { Size = 2653 } }, Payload = CreateZerosPayload(1828) }); Assert.IsTrue(await call.ResponseStream.MoveNext()); Assert.AreEqual(PayloadType.COMPRESSABLE, call.ResponseStream.Current.Payload.Type); Assert.AreEqual(2653, call.ResponseStream.Current.Payload.Body.Length); await call.RequestStream.WriteAsync(new StreamingOutputCallRequest { ResponseType = PayloadType.COMPRESSABLE, ResponseParameters = { new ResponseParameters { Size = 58979 } }, Payload = CreateZerosPayload(45904) }); Assert.IsTrue(await call.ResponseStream.MoveNext()); Assert.AreEqual(PayloadType.COMPRESSABLE, call.ResponseStream.Current.Payload.Type); Assert.AreEqual(58979, call.ResponseStream.Current.Payload.Body.Length); await call.RequestStream.CompleteAsync(); Assert.IsFalse(await call.ResponseStream.MoveNext()); } Console.WriteLine("Passed!"); } public static async Task RunEmptyStreamAsync(TestService.ITestServiceClient client) { Console.WriteLine("running empty_stream"); using (var call = client.FullDuplexCall()) { await call.RequestStream.CompleteAsync(); var responseList = await call.ResponseStream.ToListAsync(); Assert.AreEqual(0, responseList.Count); } Console.WriteLine("Passed!"); } public static async Task RunComputeEngineCredsAsync(TestService.TestServiceClient client, string defaultServiceAccount, string oauthScope) { Console.WriteLine("running compute_engine_creds"); var credential = await GoogleCredential.GetApplicationDefaultAsync(); Assert.IsFalse(credential.IsCreateScopedRequired); client.HeaderInterceptor = AuthInterceptors.FromCredential(credential); var request = new SimpleRequest { ResponseType = PayloadType.COMPRESSABLE, ResponseSize = 314159, Payload = CreateZerosPayload(271828), FillUsername = true, FillOauthScope = true }; var response = client.UnaryCall(request); Assert.AreEqual(PayloadType.COMPRESSABLE, response.Payload.Type); Assert.AreEqual(314159, response.Payload.Body.Length); Assert.False(string.IsNullOrEmpty(response.OauthScope)); Assert.True(oauthScope.Contains(response.OauthScope)); Assert.AreEqual(defaultServiceAccount, response.Username); Console.WriteLine("Passed!"); } public static async Task RunJwtTokenCredsAsync(TestService.TestServiceClient client, string defaultServiceAccount) { Console.WriteLine("running jwt_token_creds"); var credential = await GoogleCredential.GetApplicationDefaultAsync(); Assert.IsTrue(credential.IsCreateScopedRequired); client.HeaderInterceptor = AuthInterceptors.FromCredential(credential); var request = new SimpleRequest { ResponseType = PayloadType.COMPRESSABLE, ResponseSize = 314159, Payload = CreateZerosPayload(271828), FillUsername = true, }; var response = client.UnaryCall(request); Assert.AreEqual(PayloadType.COMPRESSABLE, response.Payload.Type); Assert.AreEqual(314159, response.Payload.Body.Length); Assert.AreEqual(defaultServiceAccount, response.Username); Console.WriteLine("Passed!"); } public static async Task RunOAuth2AuthTokenAsync(TestService.TestServiceClient client, string defaultServiceAccount, string oauthScope) { Console.WriteLine("running oauth2_auth_token"); ITokenAccess credential = (await GoogleCredential.GetApplicationDefaultAsync()).CreateScoped(new[] { oauthScope }); string oauth2Token = await credential.GetAccessTokenForRequestAsync(); client.HeaderInterceptor = AuthInterceptors.FromAccessToken(oauth2Token); var request = new SimpleRequest { FillUsername = true, FillOauthScope = true }; var response = client.UnaryCall(request); Assert.False(string.IsNullOrEmpty(response.OauthScope)); Assert.True(oauthScope.Contains(response.OauthScope)); Assert.AreEqual(defaultServiceAccount, response.Username); Console.WriteLine("Passed!"); } public static async Task RunPerRpcCredsAsync(TestService.TestServiceClient client, string defaultServiceAccount, string oauthScope) { Console.WriteLine("running per_rpc_creds"); ITokenAccess credential = (await GoogleCredential.GetApplicationDefaultAsync()).CreateScoped(new[] { oauthScope }); string accessToken = await credential.GetAccessTokenForRequestAsync(); var headerInterceptor = AuthInterceptors.FromAccessToken(accessToken); var request = new SimpleRequest { FillUsername = true, }; var headers = new Metadata(); headerInterceptor(null, "", headers); var response = client.UnaryCall(request, headers: headers); Assert.AreEqual(defaultServiceAccount, response.Username); Console.WriteLine("Passed!"); } public static async Task RunCancelAfterBeginAsync(TestService.ITestServiceClient client) { Console.WriteLine("running cancel_after_begin"); var cts = new CancellationTokenSource(); using (var call = client.StreamingInputCall(cancellationToken: cts.Token)) { // TODO(jtattermusch): we need this to ensure call has been initiated once we cancel it. await Task.Delay(1000); cts.Cancel(); var ex = Assert.Throws<RpcException>(async () => await call.ResponseAsync); Assert.AreEqual(StatusCode.Cancelled, ex.Status.StatusCode); } Console.WriteLine("Passed!"); } public static async Task RunCancelAfterFirstResponseAsync(TestService.ITestServiceClient client) { Console.WriteLine("running cancel_after_first_response"); var cts = new CancellationTokenSource(); using (var call = client.FullDuplexCall(cancellationToken: cts.Token)) { await call.RequestStream.WriteAsync(new StreamingOutputCallRequest { ResponseType = PayloadType.COMPRESSABLE, ResponseParameters = { new ResponseParameters { Size = 31415 } }, Payload = CreateZerosPayload(27182) }); Assert.IsTrue(await call.ResponseStream.MoveNext()); Assert.AreEqual(PayloadType.COMPRESSABLE, call.ResponseStream.Current.Payload.Type); Assert.AreEqual(31415, call.ResponseStream.Current.Payload.Body.Length); cts.Cancel(); var ex = Assert.Throws<RpcException>(async () => await call.ResponseStream.MoveNext()); Assert.AreEqual(StatusCode.Cancelled, ex.Status.StatusCode); } Console.WriteLine("Passed!"); } public static async Task RunTimeoutOnSleepingServerAsync(TestService.ITestServiceClient client) { Console.WriteLine("running timeout_on_sleeping_server"); var deadline = DateTime.UtcNow.AddMilliseconds(1); using (var call = client.FullDuplexCall(deadline: deadline)) { try { await call.RequestStream.WriteAsync(new StreamingOutputCallRequest { Payload = CreateZerosPayload(27182) }); } catch (InvalidOperationException) { // Deadline was reached before write has started. Eat the exception and continue. } var ex = Assert.Throws<RpcException>(async () => await call.ResponseStream.MoveNext()); Assert.AreEqual(StatusCode.DeadlineExceeded, ex.Status.StatusCode); } Console.WriteLine("Passed!"); } // This is not an official interop test, but it's useful. public static void RunBenchmarkEmptyUnary(TestService.ITestServiceClient client) { BenchmarkUtil.RunBenchmark(10000, 10000, () => { client.EmptyCall(new Empty()); }); } private static Payload CreateZerosPayload(int size) { return new Payload { Body = ByteString.CopyFrom(new byte[size]) }; } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using EnvDTE; using EnvDTE80; using Microsoft.Win32; using VSLangProj; using System.Globalization; using Microsoft.VisualStudio.Shell.Interop; using System.IO; using System.Text; using BuildVision.UI; using BuildVision.UI.Common.Logging; using BuildVision.Contracts; namespace BuildVision.Helpers { public static class ProjectExtensions { private static readonly HashSet<string> _hiddenProjectsUniqueNames = new HashSet<string> { null, string.Empty, "<MiscFiles>" }; #region ProjectTypes fields private static readonly Dictionary<string, string> _knownProjectTypes = new Dictionary<string, string> { {"{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}", "Windows"}, // C# {"{F184B08F-C81C-45F6-A57F-5ABD9991F28F}", "Windows"}, // VB.NET {"{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}", "Windows"}, // C++ {"{F2A71F9B-5D33-465A-A702-920D77279786}", "Windows"}, // F# {"{349C5851-65DF-11DA-9384-00065B846F21}", "Web Application"}, {"{E24C65DC-7377-472B-9ABA-BC803B73C61A}", "Web Site"}, {"{603c0e0b-db56-11dc-be95-000d561079b0}", "ASP.NET MVC1"}, {"{F85E285D-A4E0-4152-9332-AB1D724D3325}", "ASP.NET MVC2"}, {"{E53F8FEA-EAE0-44A6-8774-FFD645390401}", "ASP.NET MVC3"}, {"{E3E379DF-F4C6-4180-9B81-6769533ABE47}", "ASP.NET MVC4"}, {"{F135691A-BF7E-435D-8960-F99683D2D49C}", "Distributed System"}, {"{3D9AD99F-2412-4246-B90B-4EAA41C64699}", "WCF"}, {"{60DC8134-EBA5-43B8-BCC9-BB4BC16C2548}", "WPF"}, {"{C252FEB5-A946-4202-B1D4-9916A0590387}", "Visual DB Tools"}, {"{A9ACE9BB-CECE-4E62-9AA4-C7E7C5BD2124}", "Database"}, {"{4F174C21-8C12-11D0-8340-0000F80270F8}", "Database"}, {"{3AC096D0-A1C2-E12C-1390-A8335801FDAB}", "Test"}, {"{20D4826A-C6FA-45DB-90F4-C717570B9F32}", "Legacy (2003) Smart Device"}, {"{CB4CE8C6-1BDB-4DC7-A4D3-65A1999772F8}", "Legacy (2003) Smart Device"}, {"{4D628B5B-2FBC-4AA6-8C16-197242AEB884}", "Smart Device"}, {"{68B1623D-7FB9-47D8-8664-7ECEA3297D4F}", "Smart Device"}, {"{14822709-B5A1-4724-98CA-57A101D1B079}", "Workflow"}, {"{D59BE175-2ED0-4C54-BE3D-CDAA9F3214C8}", "Workflow"}, {"{06A35CCD-C46D-44D5-987B-CF40FF872267}", "Deployment Merge Module"}, {"{3EA9E505-35AC-4774-B492-AD1749C4943A}", "Deployment Cab"}, {"{978C614F-708E-4E1A-B201-565925725DBA}", "Deployment Setup"}, {"{AB322303-2255-48EF-A496-5904EB18DA55}", "Deployment Smart Device Cab"}, {"{A860303F-1F3F-4691-B57E-529FC101A107}", "VSTA"}, {"{BAA0C2D2-18E2-41B9-852F-F413020CAA33}", "VSTO"}, {"{F8810EC1-6754-47FC-A15F-DFABD2E3FA90}", "SharePoint Workflow"}, {"{6D335F3A-9D43-41b4-9D22-F6F17C4BE596}", "XNA (Windows)"}, {"{2DF5C3F4-5A5F-47a9-8E94-23B4456F55E2}", "XNA (XBox)"}, {"{D399B71A-8929-442a-A9AC-8BEC78BB2433}", "XNA (Zune)"}, {"{EC05E597-79D4-47f3-ADA0-324C4F7C7484}", "SharePoint"}, {"{593B0543-81F6-4436-BA1E-4747859CAAE2}", "SharePoint"}, {"{A1591282-1198-4647-A2B1-27E5FF5F6F3B}", "Silverlight"}, {"{F088123C-0E9E-452A-89E6-6BA2F21D5CAC}", "Modeling"}, {"{82B43B9B-A64C-4715-B499-D71E9CA2BD60}", "Extensibility"} }; private const string UnknownProjectTypeLabel = "Unknown"; #endregion #region Languages fields private static readonly Dictionary<string, string> _knownLanguages = new Dictionary<string, string> { { CodeModelLanguageConstants.vsCMLanguageCSharp, "C#" }, { CodeModelLanguageConstants.vsCMLanguageIDL, "IDL" }, { CodeModelLanguageConstants.vsCMLanguageMC, "MC++" }, // Managed C++ { CodeModelLanguageConstants.vsCMLanguageVB, "VB.NET" }, { CodeModelLanguageConstants.vsCMLanguageVC, "VC++" }, // Visual C++ { CodeModelLanguageConstants2.vsCMLanguageJSharp, "J#" }, { "{F2A71F9B-5D33-465A-A702-920D77279786}", "F#" }, }; private const string UnknownLanguageLabel = "Unknown"; #endregion public static Property GetPropertyOrDefault(this Project project, string propertyName) { return project.Properties.GetPropertyOrDefault(propertyName); } public static object TryGetPropertyValueOrDefault(this Project project, string propertyName) { return project.Properties.TryGetPropertyValueOrDefault(propertyName); } public static IEnumerable<string> GetBuildOutputFilePaths(this Project project, BuildOutputFileTypes fileTypes, string configuration = null, string platform = null) { Configuration targetConfig; if (configuration != null && platform != null) targetConfig = project.ConfigurationManager.Item(configuration, platform); else targetConfig = project.ConfigurationManager.ActiveConfiguration; var groups = new List<string>(); if (fileTypes.LocalizedResourceDlls) groups.Add(BuildOutputGroup.LocalizedResourceDlls); if (fileTypes.XmlSerializer) groups.Add("XmlSerializer"); if (fileTypes.ContentFiles) groups.Add(BuildOutputGroup.ContentFiles); if (fileTypes.Built) groups.Add(BuildOutputGroup.Built); if (fileTypes.SourceFiles) groups.Add(BuildOutputGroup.SourceFiles); if (fileTypes.Symbols) groups.Add(BuildOutputGroup.Symbols); if (fileTypes.Documentation) groups.Add(BuildOutputGroup.Documentation); var filePaths = new List<string>(); foreach (string groupName in groups) { try { var group = targetConfig.OutputGroups.Item(groupName); var fileUrls = (object[])group.FileURLs; filePaths.AddRange(fileUrls.Select(x => new Uri(x.ToString()).LocalPath)); } catch (ArgumentException ex) { var msg = $"Build Output Group \"{groupName}\" not found (Project Kind is \"{project.Kind}\")."; ex.Trace(msg, EventLogEntryType.Warning); } } return filePaths.Distinct(); } /// <summary> /// Find file in the Project. /// </summary> /// <param name="project">The project.</param> /// <param name="filePath">File path, relative to the <paramref name="project"/> root.</param> /// <returns>The found file or <c>null</c>.</returns> private static ProjectItem FindProjectItem(this Project project, string filePath) { return project.ProjectItems.FindProjectItem(filePath); } public static string GetFrameworkString(this Project project) { try { var framMonikerProperty = project.GetPropertyOrDefault("TargetFrameworkMoniker"); if (framMonikerProperty != null) { var framMonikerValue = (string)framMonikerProperty.Value; if (string.IsNullOrWhiteSpace(framMonikerValue)) return Resources.GridCellNoneText; framMonikerValue = framMonikerValue.Replace(",Version=v", " "); return framMonikerValue; } else { var framVersionProperty = project.GetPropertyOrDefault("TargetFrameworkVersion") ?? project.GetPropertyOrDefault("TargetFramework"); if (framVersionProperty == null || framVersionProperty.Value == null) return Resources.GridCellNoneText; var version = Convert.ToInt32(framVersionProperty.Value); string versionStr; switch (version) { case 0x10000: versionStr = "1.0"; break; case 0x10001: versionStr = "1.1"; break; case 0x20000: versionStr = "2.0"; break; case 0x30000: versionStr = "3.0"; break; case 0x30005: versionStr = "3.5"; break; case 0x40000: versionStr = "4.0"; break; case 0x40005: versionStr = "4.5"; break; case 0: return Resources.GridCellNoneText; default: { try { string hexVersion = version.ToString("X"); if (hexVersion.Length == 5) { int v1 = int.Parse(hexVersion[0].ToString(CultureInfo.InvariantCulture)); int v2 = int.Parse(hexVersion.Substring(1)); versionStr = string.Format("{0}.{1}", v1, v2); } else { versionStr = string.Format("[0x{0:X}]", version); } } catch (Exception ex) { ex.TraceUnknownException(); return Resources.GridCellNAText; } } break; } versionStr = string.Format("Unknown {0}", versionStr); return versionStr; } } catch (ArgumentException) { return Resources.GridCellNoneText; } catch (Exception ex) { ex.TraceUnknownException(); return Resources.GridCellNAText; } } public static string GetProjectTypeGuids(this Project proj) { string projectTypeGuids = string.Empty; var service = SolutionProjectsExtensions.GetService(proj.DTE, typeof(IVsSolution)); var solution = (IVsSolution)service; IVsHierarchy hierarchy; int result = solution.GetProjectOfUniqueName(proj.UniqueName, out hierarchy); if (!string.IsNullOrEmpty(proj.Kind)) { return proj.Kind; } if (result == 0) { var aggregatableProject = hierarchy as IVsAggregatableProject; aggregatableProject?.GetAggregateProjectTypeGuids(out projectTypeGuids); } return projectTypeGuids; } public static string GetLanguageName(this Project project) { try { if (project.CodeModel == null) { var kind = project.Kind.ToUpper(); return _knownLanguages.ContainsKey(kind) ? _knownLanguages[kind] : Resources.GridCellNoneText; } string codeModelLanguageKind = project.CodeModel.Language; return _knownLanguages.ContainsKey(codeModelLanguageKind) ? _knownLanguages[codeModelLanguageKind] : UnknownLanguageLabel; } catch (NotImplementedException /*throws on project.CodeModel getter*/) { return Resources.GridCellNoneText; } catch (Exception ex) { ex.TraceUnknownException(); return Resources.GridCellNAText; } } public static IEnumerable<string> GetFlavourTypes(this Project project) { try { var flavourTypes = new List<string>(); string guidsStr = project.GetProjectTypeGuids(); if (!string.IsNullOrWhiteSpace(guidsStr)) { string[] typeGuids = guidsStr.Trim(';').Split(';'); flavourTypes.AddRange(typeGuids.Select(prjKind => GetProjectType(prjKind, project.DTE.Version))); } var myType = project.TryGetPropertyValueOrDefault("MyType"); // for VB.NET projects if (myType != null && myType.ToString() != "Empty") flavourTypes.Add(myType.ToString()); var keyword = project.TryGetPropertyValueOrDefault("keyword"); // for C++ projects if (keyword != null) flavourTypes.Add(keyword.ToString()); var filteredValues = flavourTypes.Where(str => !string.IsNullOrWhiteSpace(str)).Distinct(); return filteredValues; } catch (Exception ex) { ex.TraceUnknownException(); return Enumerable.Empty<string>(); } } public static string GetOutputType(this Project project) { try { string prjObjTypeName = project.Object.GetType().Name; if (prjObjTypeName == "VCProjectShim" || prjObjTypeName == "VCProject") { dynamic prj = project.Object; dynamic configs = prj.Configurations; dynamic config = configs.Item(project.ConfigurationManager.ActiveConfiguration.ConfigurationName); string configType = config.ConfigurationType.ToString(); switch (configType) { case "typeUnknown": return "Unknown"; case "typeApplication": return "WinExe"; case "typeDynamicLibrary": return "Library (dynamic)"; case "typeStaticLibrary": return "Library (static)"; case "typeGeneric": return "Makefile"; default: throw new ArgumentOutOfRangeException(); } } else { var property = project.GetPropertyOrDefault("OutputType"); if (property == null || property.Value == null) return Resources.GridCellNoneText; if (!Enum.TryParse(property.Value.ToString(), out prjOutputType outputType)) { return property.Value.ToString(); } switch (outputType) { case prjOutputType.prjOutputTypeWinExe: return "WinExe"; case prjOutputType.prjOutputTypeExe: return "WinExe (console)"; case prjOutputType.prjOutputTypeLibrary: return "Library"; default: throw new ArgumentOutOfRangeException(); } } } catch(ArgumentException) { // We are catching this seperatly because in the current VS2017 Version // there is a bug that makes it impossible for us to retrieve the extenders // for specific projects (https://github.com/dotnet/project-system/issues/2686) return Resources.GridCellNAText; } catch (Exception ex) { ex.TraceUnknownException(); return Resources.GridCellNAText; } } public static string GetExtenderNames(this Project project) { try { var extenderNames = (object[])project.ExtenderNames; if (extenderNames == null || extenderNames.Length == 0) return Resources.GridCellNoneText; return string.Join("; ", extenderNames); } catch (ArgumentException) { return ""; // Leaving this in for now until visual studio team fixes the issue with extendernames } catch (Exception ex) { ex.TraceUnknownException(); return Resources.GridCellNAText; } } /// <summary> /// Get user-friendly type of the project. /// </summary> /// <param name="projectKind">The <see cref="Project.Kind"/>.</param> /// <param name="version">The <see cref="_DTE.Version"/>. For Visual Studio 2012 is "12.0".</param> /// <returns>User-friendly type of the project.</returns> public static string GetProjectType(string projectKind, string version) { return GetKnownProjectType(projectKind) ?? GetProjectTypeFromRegistry(projectKind, version) ?? UnknownProjectTypeLabel; } private static string GetKnownProjectType(string projectKind) { projectKind = projectKind.ToUpper(); return _knownProjectTypes.ContainsKey(projectKind) ? _knownProjectTypes[projectKind] : null; } private static string GetProjectTypeFromRegistry(string projectKind, string version) { try { string key = string.Format(@"SOFTWARE\Microsoft\VisualStudio\{0}\Projects\{1}", version, projectKind); var subKey = Registry.LocalMachine.OpenSubKey(key); var type = (subKey != null) ? subKey.GetValue(string.Empty, string.Empty).ToString() : string.Empty; if (type.StartsWith("#")) { Debug.Assert(subKey != null, "subKey != null"); type = string.Format("{0} project", subKey.GetValue("Language(VsTemplate)", string.Empty)); } // Types usually have "Project Factory" and "ProjectFactory" postfixes: Web MVC Project Factory, ExtensibilityProjectFactory. var typeProjectFactoryPostfixes = new[] { " Project Factory", "ProjectFactory" }; foreach (var postfix in typeProjectFactoryPostfixes) { if (type.EndsWith(postfix)) { type = type.Remove(type.LastIndexOf(postfix, StringComparison.InvariantCulture)); break; } } TraceManager.Trace( string.Format("Project type is taken from the registry: Kind={0}, DTEVersion={1}, Type={2}", projectKind, version, type), EventLogEntryType.Warning); if (string.IsNullOrWhiteSpace(type)) return null; _knownProjectTypes[projectKind] = type; return type; } catch (Exception ex) { ex.Trace(string.Format("Unable to get project type from registry: (Kind={0}, DTEVersion={1})", projectKind, version)); return null; } } public static string GetRootNamespace(this Project project) { var val = project.TryGetPropertyValueOrDefault("RootNamespace") ?? project.TryGetPropertyValueOrDefault("DefaultNamespace"); return (val != null) ? val.ToString() : null; } /// <summary> /// Gets the project or at least one of his children is dirty. /// </summary> public static bool IsDirty(this Project project) { if (project.IsDirty) return true; if (project.ProjectItems != null && project.ProjectItems.Cast<ProjectItem>().Any(x => x.ProjectItemIsDirty())) return true; return false; } /// <summary> /// Navigate to the Error Item in the Visual Studio Editor. /// </summary> /// <param name="project">The project - owner of the Error Item.</param> /// <param name="errorItem">The Error Item.</param> public static bool NavigateToErrorItem(this Project project, BuildVision.Contracts.ErrorItem errorItem) { try { if (project == null) throw new ArgumentNullException("project"); if (errorItem == null) throw new ArgumentNullException("errorItem"); if (!errorItem.CanNavigateTo) return false; if (string.IsNullOrEmpty(errorItem.File)) return false; string fullPath; // Check if path is absolute. if (Path.IsPathRooted(errorItem.File)) { // Foo VC++ projects errorItem.File contains full path. fullPath = errorItem.File; } else { var projectItemFile = project.FindProjectItem(errorItem.File); if (projectItemFile == null) return false; fullPath = projectItemFile.Properties.GetPropertyOrDefault<string>("FullPath"); if (fullPath == null) throw new KeyNotFoundException("FullPath property not found."); } try { var window = project.DTE.ItemOperations.OpenFile(fullPath, EnvDTE.Constants.vsViewKindAny); if (window == null) throw new NullReferenceException("Associated window is null reference."); window.Activate(); var selection = (TextSelection)window.Selection; selection.MoveToLineAndOffset(errorItem.LineNumber, errorItem.ColumnNumber); selection.MoveToLineAndOffset(errorItem.EndLineNumber, errorItem.EndColumnNumber, true /*select text*/); } catch (Exception ex) { var msg = string.Format("Navigate to error item exception (fullPath='{0}').", fullPath); ex.Trace(msg); } } catch (Exception ex) { ex.Trace("Navigate to error item exception."); } return true; } public static string GetTreePath(this Project project, bool includeSelfProjectName = true) { var path = new StringBuilder(); try { if (includeSelfProjectName) path.Append(project.Name); var parent = project; while (true) { parent = TryGetParentProject(parent); if (parent == null || parent == project) break; if (path.Length != 0) path.Insert(0, '\\'); path.Insert(0, parent.Name); } } catch (Exception ex) { ex.TraceUnknownException(); } return (path.Length != 0) ? path.ToString() : null; } public static Project TryGetParentProject(this Project project) { try { var parentItem = project.ParentProjectItem; return (parentItem != null) ? parentItem.ContainingProject : null; } catch (Exception ex) { ex.TraceUnknownException(); return null; } } public static Project GetSubProject(this Project solutionFolder, Func<Project, bool> cond) { for (int i = 1; i <= solutionFolder.ProjectItems.Count; i++) { Project subProject = solutionFolder.ProjectItems.Item(i).SubProject; if (subProject == null) continue; // If this is another solution folder, do a recursive call, otherwise add if (subProject.Kind == ProjectKinds.vsProjectKindSolutionFolder) { Project sub = GetSubProject(subProject, cond); if (sub != null) return sub; } else if (!IsHidden(subProject)) { if (cond(subProject)) return subProject; } } return null; } public static IEnumerable<Project> GetSubProjects(this Project solutionFolder) { var list = new List<Project>(); for (int i = 1; i <= solutionFolder.ProjectItems.Count; i++) { Project subProject = solutionFolder.ProjectItems.Item(i).SubProject; if (subProject == null) continue; // If this is another solution folder, do a recursive call, otherwise add if (subProject.Kind == ProjectKinds.vsProjectKindSolutionFolder) list.AddRange(GetSubProjects(subProject)); else if (!subProject.IsHidden()) list.Add(subProject); } return list; } public static bool IsHidden(this Project project) { try { if (_hiddenProjectsUniqueNames.Contains(project.UniqueName)) return true; // Solution Folder. if (project.Kind == EnvDTE.Constants.vsProjectKindSolutionItems) return true; // If projectIsInitialized == false then NotImplementedException will be occured // in project.FullName or project.FileName getters. bool projectIsInitialized = (project.Object != null); if (projectIsInitialized && project.FullName.EndsWith(".tmp_proj")) return true; return false; } catch (Exception ex) { ex.TraceUnknownException(); return true; } } public static bool IsProjectHidden(string projectFileName) { try { if (_hiddenProjectsUniqueNames.Contains(projectFileName)) return true; if (projectFileName.EndsWith(".tmp_proj")) return true; return false; } catch (Exception ex) { ex.TraceUnknownException(); return true; } } public static Microsoft.Build.Evaluation.Project GetMsBuildProject(this Project project) { var root = Microsoft.Build.Construction.ProjectRootElement.Open(project.FullName); return new Microsoft.Build.Evaluation.Project(root); } } }
namespace Projections { partial class MiscPanel { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); this.m_toolTip = new System.Windows.Forms.ToolTip(this.components); this.label1 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.m_longitudeDMSTextBox = new System.Windows.Forms.TextBox(); this.label4 = new System.Windows.Forms.Label(); this.m_latitudeDMSTextBox = new System.Windows.Forms.TextBox(); this.m_LongitudeTextBox = new System.Windows.Forms.TextBox(); this.m_latitudeTextBox = new System.Windows.Forms.TextBox(); this.m_geohashTextBox = new System.Windows.Forms.TextBox(); this.button1 = new System.Windows.Forms.Button(); this.button2 = new System.Windows.Forms.Button(); this.button3 = new System.Windows.Forms.Button(); this.button4 = new System.Windows.Forms.Button(); this.m_comboBox = new System.Windows.Forms.ComboBox(); this.SuspendLayout(); // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(13, 33); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(54, 13); this.label1.TabIndex = 0; this.label1.Text = "Longitude"; // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(120, 4); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(31, 13); this.label2.TabIndex = 1; this.label2.Text = "DMS"; // // label3 // this.label3.AutoSize = true; this.label3.Location = new System.Drawing.Point(229, 4); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(88, 13); this.label3.TabIndex = 2; this.label3.Text = "Decimal Degrees"; // // m_longitudeDMSTextBox // this.m_longitudeDMSTextBox.Location = new System.Drawing.Point(86, 29); this.m_longitudeDMSTextBox.Name = "m_longitudeDMSTextBox"; this.m_longitudeDMSTextBox.Size = new System.Drawing.Size(100, 20); this.m_longitudeDMSTextBox.TabIndex = 3; // // label4 // this.label4.AutoSize = true; this.label4.Location = new System.Drawing.Point(13, 63); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(45, 13); this.label4.TabIndex = 4; this.label4.Text = "Latitude"; // // m_latitudeDMSTextBox // this.m_latitudeDMSTextBox.Location = new System.Drawing.Point(86, 56); this.m_latitudeDMSTextBox.Name = "m_latitudeDMSTextBox"; this.m_latitudeDMSTextBox.Size = new System.Drawing.Size(100, 20); this.m_latitudeDMSTextBox.TabIndex = 5; // // m_LongitudeTextBox // this.m_LongitudeTextBox.Location = new System.Drawing.Point(203, 29); this.m_LongitudeTextBox.Name = "m_LongitudeTextBox"; this.m_LongitudeTextBox.Size = new System.Drawing.Size(137, 20); this.m_LongitudeTextBox.TabIndex = 6; // // m_latitudeTextBox // this.m_latitudeTextBox.Location = new System.Drawing.Point(203, 55); this.m_latitudeTextBox.Name = "m_latitudeTextBox"; this.m_latitudeTextBox.Size = new System.Drawing.Size(137, 20); this.m_latitudeTextBox.TabIndex = 7; // // m_geohashTextBox // this.m_geohashTextBox.Location = new System.Drawing.Point(360, 43); this.m_geohashTextBox.Name = "m_geohashTextBox"; this.m_geohashTextBox.Size = new System.Drawing.Size(155, 20); this.m_geohashTextBox.TabIndex = 8; // // button1 // this.button1.Location = new System.Drawing.Point(96, 83); this.button1.Name = "button1"; this.button1.Size = new System.Drawing.Size(75, 23); this.button1.TabIndex = 10; this.button1.Text = "Convert ->"; this.button1.UseVisualStyleBackColor = true; this.button1.Click += new System.EventHandler(this.OnConvertDMS); // // button2 // this.button2.Location = new System.Drawing.Point(229, 83); this.button2.Name = "button2"; this.button2.Size = new System.Drawing.Size(85, 23); this.button2.TabIndex = 11; this.button2.Text = "<- Convert ->"; this.button2.UseVisualStyleBackColor = true; this.button2.Click += new System.EventHandler(this.OnConvert); // // button3 // this.button3.Location = new System.Drawing.Point(400, 83); this.button3.Name = "button3"; this.button3.Size = new System.Drawing.Size(75, 23); this.button3.TabIndex = 12; this.button3.Text = "<- Convert"; this.button3.UseVisualStyleBackColor = true; this.button3.Click += new System.EventHandler(this.OnConvertGeohash); // // button4 // this.button4.Location = new System.Drawing.Point(541, 4); this.button4.Name = "button4"; this.button4.Size = new System.Drawing.Size(75, 23); this.button4.TabIndex = 13; this.button4.Text = "Validate"; this.button4.UseVisualStyleBackColor = true; this.button4.Click += new System.EventHandler(this.OnValidate); // // m_comboBox // this.m_comboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.m_comboBox.FormattingEnabled = true; this.m_comboBox.Items.AddRange(new object[] { "Geohash", "GARS", "Georef"}); this.m_comboBox.Location = new System.Drawing.Point(376, 4); this.m_comboBox.Name = "m_comboBox"; this.m_comboBox.Size = new System.Drawing.Size(121, 21); this.m_comboBox.TabIndex = 14; this.m_toolTip.SetToolTip(this.m_comboBox, "Select the reference system"); // // MiscPanel // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.Controls.Add(this.m_comboBox); this.Controls.Add(this.button4); this.Controls.Add(this.button3); this.Controls.Add(this.button2); this.Controls.Add(this.button1); this.Controls.Add(this.m_geohashTextBox); this.Controls.Add(this.m_latitudeTextBox); this.Controls.Add(this.m_LongitudeTextBox); this.Controls.Add(this.m_latitudeDMSTextBox); this.Controls.Add(this.label4); this.Controls.Add(this.m_longitudeDMSTextBox); this.Controls.Add(this.label3); this.Controls.Add(this.label2); this.Controls.Add(this.label1); this.Name = "MiscPanel"; this.Size = new System.Drawing.Size(977, 389); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.ToolTip m_toolTip; private System.Windows.Forms.Label label1; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label3; private System.Windows.Forms.TextBox m_longitudeDMSTextBox; private System.Windows.Forms.Label label4; private System.Windows.Forms.TextBox m_latitudeDMSTextBox; private System.Windows.Forms.TextBox m_LongitudeTextBox; private System.Windows.Forms.TextBox m_latitudeTextBox; private System.Windows.Forms.TextBox m_geohashTextBox; private System.Windows.Forms.Button button1; private System.Windows.Forms.Button button2; private System.Windows.Forms.Button button3; private System.Windows.Forms.Button button4; private System.Windows.Forms.ComboBox m_comboBox; } }
#pragma warning disable 1591 using System; using System.Collections.Generic; using System.Text; namespace Braintree { public class WebhookTestingGateway : IWebhookTestingGateway { private readonly BraintreeService service; protected internal WebhookTestingGateway(BraintreeGateway gateway) { gateway.Configuration.AssertHasAccessTokenOrKeys(); service = new BraintreeService(gateway.Configuration); } public virtual Dictionary<string, string> SampleNotification(WebhookKind kind, string id) { var response = new Dictionary<string, string>(); string payload = BuildPayload(kind, id); response["bt_payload"] = payload; response["bt_signature"] = BuildSignature(payload); return response; } private string BuildPayload(WebhookKind kind, string id) { var currentTime = DateTime.Now.ToUniversalTime().ToString("u"); var payload = string.Format("<notification><timestamp type=\"datetime\">{0}</timestamp><kind>{1}</kind><subject>{2}</subject></notification>", currentTime, kind, SubjectSampleXml(kind, id)); return Convert.ToBase64String(Encoding.Default.GetBytes(payload)) + '\n'; } private string BuildSignature(string payload) { return string.Format("{0}|{1}", service.PublicKey, new Sha1Hasher().HmacHash(service.PrivateKey, payload).Trim().ToLower()); } private string SubjectSampleXml(WebhookKind kind, string id) { if (kind == WebhookKind.SUB_MERCHANT_ACCOUNT_APPROVED) { return MerchantAccountApprovedSampleXml(id); } else if (kind == WebhookKind.SUB_MERCHANT_ACCOUNT_DECLINED) { return MerchantAccountDeclinedSampleXml(id); } else if (kind == WebhookKind.TRANSACTION_DISBURSED) { return TransactionDisbursedSampleXml(id); } else if (kind == WebhookKind.DISBURSEMENT_EXCEPTION) { return DisbursementExceptionSampleXml(id); } else if (kind == WebhookKind.DISBURSEMENT) { return DisbursementSampleXml(id); } else if (kind == WebhookKind.PARTNER_MERCHANT_CONNECTED) { return PartnerMerchantConnectedSampleXml(id); } else if (kind == WebhookKind.PARTNER_MERCHANT_DISCONNECTED) { return PartnerMerchantDisconnectedSampleXml(id); } else if (kind == WebhookKind.PARTNER_MERCHANT_DECLINED) { return PartnerMerchantDeclinedSampleXml(id); } else if (kind == WebhookKind.DISPUTE_OPENED) { return DisputeOpenedSampleXml(id); } else if (kind == WebhookKind.DISPUTE_LOST) { return DisputeLostSampleXml(id); } else if (kind == WebhookKind.DISPUTE_WON) { return DisputeWonSampleXml(id); } else if (kind == WebhookKind.SUBSCRIPTION_CHARGED_SUCCESSFULLY) { return SubscriptionChargedSuccessfullySampleXml(id); } else { return SubscriptionXml(id); } } private const string TYPE_DATE = "type=\"date\""; private const string TYPE_ARRAY = "type=\"array\""; private const string TYPE_SYMBOL = "type=\"symbol\""; private const string NIL_TRUE = "nil=\"true\""; private const string TYPE_BOOLEAN = "type=\"boolean\""; private string MerchantAccountDeclinedSampleXml(string id) { return Node("api-error-response", Node("message", "Applicant declined due to OFAC."), NodeAttr("errors", TYPE_ARRAY, Node("merchant-account", NodeAttr("errors", TYPE_ARRAY, Node("error", Node("code", "82621"), Node("message", "Applicant declined due to OFAC."), NodeAttr("attribute", TYPE_SYMBOL, "base") ) ) ) ), Node("merchant-account", Node("id", id), Node("status", "suspended"), Node("master-merchant-account", Node("id", "master_ma_for_" + id), Node("status", "suspended") ) ) ); } private string TransactionDisbursedSampleXml(string id) { return Node("transaction", Node("id", id), Node("amount", "100.00"), Node("disbursement-details", NodeAttr("disbursement-date", TYPE_DATE, "2013-07-09") ), Node("billing"), Node("credit-card"), Node("customer"), Node("descriptor"), Node("shipping"), Node("subscription") ); } private string DisbursementExceptionSampleXml(string id) { return Node("disbursement", Node("id", id), Node("amount", "100.00"), Node("exception-message", "bank_rejected"), NodeAttr("disbursement-date", TYPE_DATE, "2014-02-10"), Node("follow-up-action", "update_funding_information"), NodeAttr("success", TYPE_BOOLEAN, "false"), NodeAttr("retry", TYPE_BOOLEAN, "false"), Node("merchant-account", Node("id", "merchant_account_id"), Node("master-merchant-account", Node("id", "master_ma"), Node("status", "active") ), Node("status", "active") ), NodeAttr("transaction-ids", TYPE_ARRAY, Node("item", "asdf"), Node("item", "qwer") ) ); } private string DisbursementSampleXml(string id) { return Node("disbursement", Node("id", id), Node("amount", "100.00"), NodeAttr("exception-message", NIL_TRUE, ""), NodeAttr("disbursement-date", TYPE_DATE, "2014-02-10"), NodeAttr("follow-up-action", NIL_TRUE, ""), NodeAttr("success", TYPE_BOOLEAN, "true"), NodeAttr("retry", TYPE_BOOLEAN, "false"), Node("merchant-account", Node("id", "merchant_account_id"), Node("master-merchant-account", Node("id", "master_ma"), Node("status", "active") ), Node("status", "active") ), NodeAttr("transaction-ids", TYPE_ARRAY, Node("item", "asdf"), Node("item", "qwer") ) ); } private string DisputeOpenedSampleXml(string id) { return Node("dispute", Node("id", id), Node("amount", "250.00"), NodeAttr("received-date", TYPE_DATE, "2014-03-21"), NodeAttr("repy-by-date", TYPE_DATE, "2014-03-21"), Node("currency-iso-code", "USD"), Node("status", "open"), Node("reason", "fraud"), Node("transaction", Node("id", id), Node("amount", "250.00") ) ); } private string DisputeLostSampleXml(string id) { return Node("dispute", Node("id", id), Node("amount", "250.00"), NodeAttr("received-date", TYPE_DATE, "2014-03-21"), NodeAttr("repy-by-date", TYPE_DATE, "2014-03-21"), Node("currency-iso-code", "USD"), Node("status", "lost"), Node("reason", "fraud"), Node("transaction", Node("id", id), Node("amount", "250.00") ) ); } private string DisputeWonSampleXml(string id) { return Node("dispute", Node("id", id), Node("amount", "250.00"), NodeAttr("received-date", TYPE_DATE, "2014-03-21"), NodeAttr("repy-by-date", TYPE_DATE, "2014-03-21"), Node("currency-iso-code", "USD"), Node("status", "won"), Node("reason", "fraud"), Node("transaction", Node("id", id), Node("amount", "250.00") ) ); } private string SubscriptionXml(string id) { return Node("subscription", Node("id", id), NodeAttr("transactions", TYPE_ARRAY), NodeAttr("add_ons", TYPE_ARRAY), NodeAttr("discounts", TYPE_ARRAY) ); } private string SubscriptionChargedSuccessfullySampleXml(string id) { return Node("subscription", Node("id", id), Node("transactions", Node("transaction", Node("id", id), Node("amount", "49.99"), Node("status", "submitted_for_settlement"), Node("disbursement-details", NodeAttr("disbursement-date", TYPE_DATE, "2013-07-09") ), Node("billing"), Node("credit-card"), Node("customer"), Node("descriptor"), Node("shipping"), Node("subscription") ) ), NodeAttr("add_ons", TYPE_ARRAY), NodeAttr("discounts", TYPE_ARRAY) ); } private string MerchantAccountApprovedSampleXml(string id) { return Node("merchant-account", Node("id", id), Node("master-merchant-account", Node("id", "master_ma_for_" + id), Node("status", "active") ), Node("status", "active") ); } private string PartnerMerchantConnectedSampleXml(string id) { return Node("partner-merchant", Node("partner-merchant-id", "abc123"), Node("merchant-public-id", "public_id"), Node("public-key", "public_key"), Node("private-key", "private_key"), Node("client-side-encryption-key", "cse_key") ); } private string PartnerMerchantDisconnectedSampleXml(string id) { return Node("partner-merchant", Node("partner-merchant-id", "abc123") ); } private string PartnerMerchantDeclinedSampleXml(string id) { return Node("partner-merchant", Node("partner-merchant-id", "abc123") ); } private static string Node(string name, params string[] contents) { return NodeAttr(name, null, contents); } private static string NodeAttr(string name, string attributes, params string[] contents) { StringBuilder buffer = new StringBuilder(); buffer.Append('<').Append(name); if (attributes != null) { buffer.Append(" ").Append(attributes); } buffer.Append('>'); foreach (string content in contents) { buffer.Append(content); } buffer.Append("</").Append(name).Append('>'); return buffer.ToString(); } } }
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using Microsoft.AspNetCore.Diagnostics; using Microsoft.AspNetCore.Mvc.Razor.Compilation; using Microsoft.AspNetCore.Razor.Language; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Text; using Microsoft.Extensions.Caching.Memory; using Microsoft.Extensions.FileProviders; using Microsoft.Extensions.Logging; namespace Microsoft.AspNetCore.Mvc.Razor.Internal { /// <summary> /// Caches the result of runtime compilation of Razor files for the duration of the application lifetime. /// </summary> public class SharedRazorViewCompiler : IViewCompiler { private readonly static object _cacheLock = new object(); private readonly Dictionary<string, Task<CompiledViewDescriptor>> _precompiledViewLookup; private readonly ConcurrentDictionary<string, string> _normalizedPathLookup; private readonly IFileProvider _fileProvider; private readonly RazorTemplateEngine _templateEngine; private readonly Action<RoslynCompilationContext> _compilationCallback; private readonly ILogger _logger; private readonly CSharpCompiler _csharpCompiler; private readonly static IMemoryCache _cache = new MemoryCache(new MemoryCacheOptions()); public SharedRazorViewCompiler( IFileProvider fileProvider, RazorTemplateEngine templateEngine, CSharpCompiler csharpCompiler, Action<RoslynCompilationContext> compilationCallback, IList<CompiledViewDescriptor> precompiledViews, ILogger logger) { if (fileProvider == null) { throw new ArgumentNullException(nameof(fileProvider)); } if (templateEngine == null) { throw new ArgumentNullException(nameof(templateEngine)); } if (csharpCompiler == null) { throw new ArgumentNullException(nameof(csharpCompiler)); } if (compilationCallback == null) { throw new ArgumentNullException(nameof(compilationCallback)); } if (precompiledViews == null) { throw new ArgumentNullException(nameof(precompiledViews)); } if (logger == null) { throw new ArgumentNullException(nameof(logger)); } _fileProvider = fileProvider; _templateEngine = templateEngine; _csharpCompiler = csharpCompiler; _compilationCallback = compilationCallback; _logger = logger; _normalizedPathLookup = new ConcurrentDictionary<string, string>(StringComparer.Ordinal); _precompiledViewLookup = new Dictionary<string, Task<CompiledViewDescriptor>>( precompiledViews.Count, StringComparer.OrdinalIgnoreCase); foreach (var precompiledView in precompiledViews) { if (_precompiledViewLookup.TryGetValue(precompiledView.RelativePath, out var otherValue)) { throw new InvalidOperationException("A precompiled view with the same name already exists: " + otherValue.Result.RelativePath); } _precompiledViewLookup.Add(precompiledView.RelativePath, Task.FromResult(precompiledView)); } } /// <inheritdoc /> public Task<CompiledViewDescriptor> CompileAsync(string relativePath) { if (relativePath == null) { throw new ArgumentNullException(nameof(relativePath)); } // Lookup precompiled views first. // Attempt to lookup the cache entry using the passed in path. This will succeed if the path is already // normalized and a cache entry exists. string normalizedPath = null; Task<CompiledViewDescriptor> cachedResult; if (_precompiledViewLookup.Count > 0) { if (_precompiledViewLookup.TryGetValue(relativePath, out cachedResult)) { return cachedResult; } normalizedPath = GetNormalizedPath(relativePath); if (_precompiledViewLookup.TryGetValue(normalizedPath, out cachedResult)) { return cachedResult; } } if (_cache.TryGetValue(relativePath, out cachedResult)) { return cachedResult; } normalizedPath = normalizedPath ?? GetNormalizedPath(relativePath); if (_cache.TryGetValue(normalizedPath, out cachedResult)) { return cachedResult; } // Entry does not exist. Attempt to create one. cachedResult = CreateCacheEntry(normalizedPath); return cachedResult; } private Task<CompiledViewDescriptor> CreateCacheEntry(string normalizedPath) { TaskCompletionSource<CompiledViewDescriptor> compilationTaskSource = null; MemoryCacheEntryOptions cacheEntryOptions; Task<CompiledViewDescriptor> cacheEntry; // Safe races cannot be allowed when compiling Razor pages. To ensure only one compilation request succeeds // per file, we'll lock the creation of a cache entry. Creating the cache entry should be very quick. The // actual work for compiling files happens outside the critical section. lock (_cacheLock) { if (_cache.TryGetValue(normalizedPath, out cacheEntry)) { return cacheEntry; } cacheEntryOptions = new MemoryCacheEntryOptions(); cacheEntryOptions.ExpirationTokens.Add(_fileProvider.Watch(normalizedPath)); var projectItem = _templateEngine.Project.GetItem(normalizedPath); if (!projectItem.Exists) { cacheEntry = Task.FromResult(new CompiledViewDescriptor { RelativePath = normalizedPath, ExpirationTokens = cacheEntryOptions.ExpirationTokens, }); } else { // A file exists and needs to be compiled. compilationTaskSource = new TaskCompletionSource<CompiledViewDescriptor>(); foreach (var importItem in _templateEngine.GetImportItems(projectItem)) { cacheEntryOptions.ExpirationTokens.Add(_fileProvider.Watch(importItem.FilePath)); } cacheEntry = compilationTaskSource.Task; } cacheEntry = _cache.Set(normalizedPath, cacheEntry, cacheEntryOptions); } if (compilationTaskSource != null) { // Indicates that a file was found and needs to be compiled. Debug.Assert(cacheEntryOptions != null); try { var descriptor = CompileAndEmit(normalizedPath); descriptor.ExpirationTokens = cacheEntryOptions.ExpirationTokens; compilationTaskSource.SetResult(descriptor); } catch (Exception ex) { compilationTaskSource.SetException(ex); } } return cacheEntry; } protected virtual CompiledViewDescriptor CompileAndEmit(string relativePath) { var codeDocument = _templateEngine.CreateCodeDocument(relativePath); var cSharpDocument = _templateEngine.GenerateCode(codeDocument); if (cSharpDocument.Diagnostics.Count > 0) { throw CompilationFailedExceptionFactory.Create( codeDocument, cSharpDocument.Diagnostics); } var generatedAssembly = CompileAndEmit(codeDocument, cSharpDocument.GeneratedCode); var viewAttribute = generatedAssembly.GetCustomAttribute<RazorViewAttribute>(); return new CompiledViewDescriptor { ViewAttribute = viewAttribute, RelativePath = relativePath, }; } internal Assembly CompileAndEmit(RazorCodeDocument codeDocument, string generatedCode) { _logger.GeneratedCodeToAssemblyCompilationStart(codeDocument.Source.FilePath); var startTimestamp = _logger.IsEnabled(LogLevel.Debug) ? Stopwatch.GetTimestamp() : 0; var assemblyName = Path.GetRandomFileName(); var compilation = CreateCompilation(generatedCode, assemblyName); using (var assemblyStream = new MemoryStream()) using (var pdbStream = new MemoryStream()) { var result = compilation.Emit( assemblyStream, pdbStream, options: _csharpCompiler.EmitOptions); if (!result.Success) { throw CompilationFailedExceptionFactory.Create( codeDocument, generatedCode, assemblyName, result.Diagnostics); } assemblyStream.Seek(0, SeekOrigin.Begin); pdbStream.Seek(0, SeekOrigin.Begin); var assembly = Assembly.Load(assemblyStream.ToArray(), pdbStream.ToArray()); _logger.GeneratedCodeToAssemblyCompilationEnd(codeDocument.Source.FilePath, startTimestamp); return assembly; } } private CSharpCompilation CreateCompilation(string compilationContent, string assemblyName) { var sourceText = SourceText.From(compilationContent, Encoding.UTF8); var syntaxTree = _csharpCompiler.CreateSyntaxTree(sourceText).WithFilePath(assemblyName); var compilation = _csharpCompiler .CreateCompilation(assemblyName) .AddSyntaxTrees(syntaxTree); compilation = ExpressionRewriter.Rewrite(compilation); var compilationContext = new RoslynCompilationContext(compilation); _compilationCallback(compilationContext); compilation = compilationContext.Compilation; return compilation; } private string GetNormalizedPath(string relativePath) { Debug.Assert(relativePath != null); if (relativePath.Length == 0) { return relativePath; } if (!_normalizedPathLookup.TryGetValue(relativePath, out var normalizedPath)) { normalizedPath = ViewPath.NormalizePath(relativePath); _normalizedPathLookup[relativePath] = normalizedPath; } return normalizedPath; } private static class CompilationFailedExceptionFactory { // error CS0234: The type or namespace name 'C' does not exist in the namespace 'N' (are you missing // an assembly reference?) private const string CS0234 = nameof(CS0234); // error CS0246: The type or namespace name 'T' could not be found (are you missing a using directive // or an assembly reference?) private const string CS0246 = nameof(CS0246); public static CompilationFailedException Create( RazorCodeDocument codeDocument, IEnumerable<RazorDiagnostic> diagnostics) { // If a SourceLocation does not specify a file path, assume it is produced from parsing the current file. var messageGroups = diagnostics.GroupBy( razorError => razorError.Span.FilePath ?? codeDocument.Source.FilePath, StringComparer.Ordinal); var failures = new List<CompilationFailure>(); foreach (var group in messageGroups) { var filePath = group.Key; var fileContent = ReadContent(codeDocument, filePath); var compilationFailure = new CompilationFailure( filePath, fileContent, compiledContent: string.Empty, messages: group.Select(parserError => CreateDiagnosticMessage(parserError, filePath))); failures.Add(compilationFailure); } return new CompilationFailedException(failures); } public static CompilationFailedException Create( RazorCodeDocument codeDocument, string compilationContent, string assemblyName, IEnumerable<Diagnostic> diagnostics) { var diagnosticGroups = diagnostics .Where(diagnostic => diagnostic.IsWarningAsError || diagnostic.Severity == DiagnosticSeverity.Error) .GroupBy(diagnostic => GetFilePath(codeDocument, diagnostic), StringComparer.Ordinal); var failures = new List<CompilationFailure>(); foreach (var group in diagnosticGroups) { var sourceFilePath = group.Key; string sourceFileContent; if (string.Equals(assemblyName, sourceFilePath, StringComparison.Ordinal)) { // The error is in the generated code and does not have a mapping line pragma sourceFileContent = compilationContent; sourceFilePath = "Generated Code"; } else { sourceFileContent = ReadContent(codeDocument, sourceFilePath); } string additionalMessage = null; if (group.Any(g => string.Equals(CS0234, g.Id, StringComparison.OrdinalIgnoreCase) || string.Equals(CS0246, g.Id, StringComparison.OrdinalIgnoreCase))) { additionalMessage = "Dependency context not specified: Microsoft.NET.Sdk.Web, PreserveCompilationContext"; } var compilationFailure = new CompilationFailure( sourceFilePath, sourceFileContent, compilationContent, group.Select(GetDiagnosticMessage), additionalMessage); failures.Add(compilationFailure); } return new CompilationFailedException(failures); } private static string ReadContent(RazorCodeDocument codeDocument, string filePath) { RazorSourceDocument sourceDocument; if (string.IsNullOrEmpty(filePath) || string.Equals(codeDocument.Source.FilePath, filePath, StringComparison.Ordinal)) { sourceDocument = codeDocument.Source; } else { sourceDocument = codeDocument.Imports.FirstOrDefault(f => string.Equals(f.FilePath, filePath, StringComparison.Ordinal)); } if (sourceDocument != null) { var contentChars = new char[sourceDocument.Length]; sourceDocument.CopyTo(0, contentChars, 0, sourceDocument.Length); return new string(contentChars); } return string.Empty; } private static DiagnosticMessage GetDiagnosticMessage(Diagnostic diagnostic) { var mappedLineSpan = diagnostic.Location.GetMappedLineSpan(); return new DiagnosticMessage( diagnostic.GetMessage(), CSharpDiagnosticFormatter.Instance.Format(diagnostic), mappedLineSpan.Path, mappedLineSpan.StartLinePosition.Line + 1, mappedLineSpan.StartLinePosition.Character + 1, mappedLineSpan.EndLinePosition.Line + 1, mappedLineSpan.EndLinePosition.Character + 1); } private static DiagnosticMessage CreateDiagnosticMessage( RazorDiagnostic razorDiagnostic, string filePath) { var sourceSpan = razorDiagnostic.Span; var message = razorDiagnostic.GetMessage(); return new DiagnosticMessage( message: message, formattedMessage: razorDiagnostic.ToString(), filePath: filePath, startLine: sourceSpan.LineIndex + 1, startColumn: sourceSpan.CharacterIndex, endLine: sourceSpan.LineIndex + 1, endColumn: sourceSpan.CharacterIndex + sourceSpan.Length); } private static string GetFilePath(RazorCodeDocument codeDocument, Diagnostic diagnostic) { if (diagnostic.Location == Location.None) { return codeDocument.Source.FilePath; } return diagnostic.Location.GetMappedLineSpan().Path; } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace WebApi_Authorization_Demo.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { internal const int DefaultCollectionSize = 2; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
using System; using System.Collections.Generic; using System.Text; namespace PlayFab { /// <summary> /// Error codes returned by PlayFabAPIs /// </summary> public enum PlayFabErrorCode { Unknown = 1, Success = 0, InvalidParams = 1000, AccountNotFound = 1001, AccountBanned = 1002, InvalidUsernameOrPassword = 1003, InvalidTitleId = 1004, InvalidEmailAddress = 1005, EmailAddressNotAvailable = 1006, InvalidUsername = 1007, InvalidPassword = 1008, UsernameNotAvailable = 1009, InvalidSteamTicket = 1010, AccountAlreadyLinked = 1011, LinkedAccountAlreadyClaimed = 1012, InvalidFacebookToken = 1013, AccountNotLinked = 1014, FailedByPaymentProvider = 1015, CouponCodeNotFound = 1016, InvalidContainerItem = 1017, ContainerNotOwned = 1018, KeyNotOwned = 1019, InvalidItemIdInTable = 1020, InvalidReceipt = 1021, ReceiptAlreadyUsed = 1022, ReceiptCancelled = 1023, GameNotFound = 1024, GameModeNotFound = 1025, InvalidGoogleToken = 1026, UserIsNotPartOfDeveloper = 1027, InvalidTitleForDeveloper = 1028, TitleNameConflicts = 1029, UserisNotValid = 1030, ValueAlreadyExists = 1031, BuildNotFound = 1032, PlayerNotInGame = 1033, InvalidTicket = 1034, InvalidDeveloper = 1035, InvalidOrderInfo = 1036, RegistrationIncomplete = 1037, InvalidPlatform = 1038, UnknownError = 1039, SteamApplicationNotOwned = 1040, WrongSteamAccount = 1041, TitleNotActivated = 1042, RegistrationSessionNotFound = 1043, NoSuchMod = 1044, FileNotFound = 1045, DuplicateEmail = 1046, ItemNotFound = 1047, ItemNotOwned = 1048, ItemNotRecycleable = 1049, ItemNotAffordable = 1050, InvalidVirtualCurrency = 1051, WrongVirtualCurrency = 1052, WrongPrice = 1053, NonPositiveValue = 1054, InvalidRegion = 1055, RegionAtCapacity = 1056, ServerFailedToStart = 1057, NameNotAvailable = 1058, InsufficientFunds = 1059, InvalidDeviceID = 1060, InvalidPushNotificationToken = 1061, NoRemainingUses = 1062, InvalidPaymentProvider = 1063, PurchaseInitializationFailure = 1064, DuplicateUsername = 1065, InvalidBuyerInfo = 1066, NoGameModeParamsSet = 1067, BodyTooLarge = 1068, ReservedWordInBody = 1069, InvalidTypeInBody = 1070, InvalidRequest = 1071, ReservedEventName = 1072, InvalidUserStatistics = 1073, NotAuthenticated = 1074, StreamAlreadyExists = 1075, ErrorCreatingStream = 1076, StreamNotFound = 1077, InvalidAccount = 1078, PurchaseDoesNotExist = 1080, InvalidPurchaseTransactionStatus = 1081, APINotEnabledForGameClientAccess = 1082, NoPushNotificationARNForTitle = 1083, BuildAlreadyExists = 1084, BuildPackageDoesNotExist = 1085, CustomAnalyticsEventsNotEnabledForTitle = 1087, InvalidSharedGroupId = 1088, NotAuthorized = 1089, MissingTitleGoogleProperties = 1090, InvalidItemProperties = 1091, InvalidPSNAuthCode = 1092, InvalidItemId = 1093, PushNotEnabledForAccount = 1094, PushServiceError = 1095, ReceiptDoesNotContainInAppItems = 1096, ReceiptContainsMultipleInAppItems = 1097, InvalidBundleID = 1098, JavascriptException = 1099, InvalidSessionTicket = 1100, UnableToConnectToDatabase = 1101, InternalServerError = 1110, InvalidReportDate = 1111, ReportNotAvailable = 1112, DatabaseThroughputExceeded = 1113, InvalidGameTicket = 1115, ExpiredGameTicket = 1116, GameTicketDoesNotMatchLobby = 1117, LinkedDeviceAlreadyClaimed = 1118, DeviceAlreadyLinked = 1119, DeviceNotLinked = 1120, PartialFailure = 1121, PublisherNotSet = 1122, ServiceUnavailable = 1123, VersionNotFound = 1124, RevisionNotFound = 1125, InvalidPublisherId = 1126, DownstreamServiceUnavailable = 1127, APINotIncludedInTitleUsageTier = 1128, DAULimitExceeded = 1129, APIRequestLimitExceeded = 1130, InvalidAPIEndpoint = 1131, BuildNotAvailable = 1132, ConcurrentEditError = 1133, ContentNotFound = 1134, CharacterNotFound = 1135, CloudScriptNotFound = 1136, ContentQuotaExceeded = 1137, InvalidCharacterStatistics = 1138, PhotonNotEnabledForTitle = 1139, PhotonApplicationNotFound = 1140, PhotonApplicationNotAssociatedWithTitle = 1141, InvalidEmailOrPassword = 1142, FacebookAPIError = 1143, InvalidContentType = 1144, KeyLengthExceeded = 1145, DataLengthExceeded = 1146, TooManyKeys = 1147, FreeTierCannotHaveVirtualCurrency = 1148, MissingAmazonSharedKey = 1149, AmazonValidationError = 1150, InvalidPSNIssuerId = 1151, PSNInaccessible = 1152, ExpiredAuthToken = 1153, FailedToGetEntitlements = 1154, FailedToConsumeEntitlement = 1155, TradeAcceptingUserNotAllowed = 1156, TradeInventoryItemIsAssignedToCharacter = 1157, TradeInventoryItemIsBundle = 1158, TradeStatusNotValidForCancelling = 1159, TradeStatusNotValidForAccepting = 1160, TradeDoesNotExist = 1161, TradeCancelled = 1162, TradeAlreadyFilled = 1163, TradeWaitForStatusTimeout = 1164, TradeInventoryItemExpired = 1165, TradeMissingOfferedAndAcceptedItems = 1166, TradeAcceptedItemIsBundle = 1167, TradeAcceptedItemIsStackable = 1168, TradeInventoryItemInvalidStatus = 1169, TradeAcceptedCatalogItemInvalid = 1170, TradeAllowedUsersInvalid = 1171, TradeInventoryItemDoesNotExist = 1172, TradeInventoryItemIsConsumed = 1173, TradeInventoryItemIsStackable = 1174, TradeAcceptedItemsMismatch = 1175, InvalidKongregateToken = 1176, FeatureNotConfiguredForTitle = 1177, NoMatchingCatalogItemForReceipt = 1178, InvalidCurrencyCode = 1179, NoRealMoneyPriceForCatalogItem = 1180, TradeInventoryItemIsNotTradable = 1181, TradeAcceptedCatalogItemIsNotTradable = 1182, UsersAlreadyFriends = 1183, LinkedIdentifierAlreadyClaimed = 1184, CustomIdNotLinked = 1185, TotalDataSizeExceeded = 1186, DeleteKeyConflict = 1187, InvalidXboxLiveToken = 1188, ExpiredXboxLiveToken = 1189, ResettableStatisticVersionRequired = 1190, NotAuthorizedByTitle = 1191, NoPartnerEnabled = 1192, InvalidPartnerResponse = 1193, APINotEnabledForGameServerAccess = 1194, StatisticNotFound = 1195, StatisticNameConflict = 1196, StatisticVersionClosedForWrites = 1197, StatisticVersionInvalid = 1198, APIClientRequestRateLimitExceeded = 1199, InvalidJSONContent = 1200, InvalidDropTable = 1201, StatisticVersionAlreadyIncrementedForScheduledInterval = 1202, StatisticCountLimitExceeded = 1203, StatisticVersionIncrementRateExceeded = 1204, ContainerKeyInvalid = 1205, CloudScriptExecutionTimeLimitExceeded = 1206, NoWritePermissionsForEvent = 1207, CloudScriptFunctionArgumentSizeExceeded = 1208, CloudScriptAPIRequestCountExceeded = 1209, CloudScriptAPIRequestError = 1210, CloudScriptHTTPRequestError = 1211, InsufficientGuildRole = 1212, GuildNotFound = 1213, OverLimit = 1214, EventNotFound = 1215, InvalidEventField = 1216, InvalidEventName = 1217, CatalogNotConfigured = 1218, OperationNotSupportedForPlatform = 1219, SegmentNotFound = 1220, StoreNotFound = 1221, InvalidStatisticName = 1222, TitleNotQualifiedForLimit = 1223, InvalidServiceLimitLevel = 1224, ServiceLimitLevelInTransition = 1225, CouponAlreadyRedeemed = 1226, GameServerBuildSizeLimitExceeded = 1227, GameServerBuildCountLimitExceeded = 1228, VirtualCurrencyCountLimitExceeded = 1229, VirtualCurrencyCodeExists = 1230, TitleNewsItemCountLimitExceeded = 1231, InvalidTwitchToken = 1232, TwitchResponseError = 1233, ProfaneDisplayName = 1234, UserAlreadyAdded = 1235, InvalidVirtualCurrencyCode = 1236, VirtualCurrencyCannotBeDeleted = 1237, IdentifierAlreadyClaimed = 1238, IdentifierNotLinked = 1239, InvalidContinuationToken = 1240, ExpiredContinuationToken = 1241, InvalidSegment = 1242, InvalidSessionId = 1243, SessionLogNotFound = 1244, InvalidSearchTerm = 1245, TwoFactorAuthenticationTokenRequired = 1246, GameServerHostCountLimitExceeded = 1247, PlayerTagCountLimitExceeded = 1248, RequestAlreadyRunning = 1249, ActionGroupNotFound = 1250, MaximumSegmentBulkActionJobsRunning = 1251, NoActionsOnPlayersInSegmentJob = 1252, DuplicateStatisticName = 1253, ScheduledTaskNameConflict = 1254, ScheduledTaskCreateConflict = 1255, InvalidScheduledTaskName = 1256, InvalidTaskSchedule = 1257, SteamNotEnabledForTitle = 1258, LimitNotAnUpgradeOption = 1259, NoSecretKeyEnabledForCloudScript = 1260, TaskNotFound = 1261, TaskInstanceNotFound = 1262 } public delegate void ErrorCallback(PlayFabError error); public class PlayFabError { public int HttpCode; public string HttpStatus; public PlayFabErrorCode Error; public string ErrorMessage; public Dictionary<string, List<string> > ErrorDetails; public object CustomData; public override string ToString() { var sb = new System.Text.StringBuilder(); if (ErrorDetails != null) { foreach (var kv in ErrorDetails) { sb.Append(kv.Key); sb.Append(": "); sb.Append(string.Join(", ", kv.Value.ToArray())); sb.Append(" | "); } } return string.Format("PlayFabError({0}, {1}, {2} {3}", Error, ErrorMessage, HttpCode, HttpStatus) + (sb.Length > 0 ? " - Details: " + sb.ToString() + ")" : ")"); } [ThreadStatic] private static StringBuilder _tempSb; public string GenerateErrorReport() { if (_tempSb == null) _tempSb = new StringBuilder(); _tempSb.Length = 0; _tempSb.Append(ErrorMessage); if (ErrorDetails != null) foreach (var pair in ErrorDetails) foreach (var msg in pair.Value) _tempSb.Append("\n").Append(pair.Key).Append(": ").Append(msg); return _tempSb.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; namespace ILCompiler.DependencyAnalysis { public enum RelocType { IMAGE_REL_BASED_ABSOLUTE = 0x00, // No relocation required IMAGE_REL_BASED_ADDR32NB = 0x02, // The 32-bit address without an image base (RVA) IMAGE_REL_BASED_HIGHLOW = 0x03, // 32 bit address base IMAGE_REL_BASED_THUMB_MOV32 = 0x07, // Thumb2: based MOVW/MOVT IMAGE_REL_BASED_DIR64 = 0x0A, // 64 bit address base IMAGE_REL_BASED_REL32 = 0x10, // 32-bit relative address from byte following reloc IMAGE_REL_BASED_THUMB_BRANCH24 = 0x13, // Thumb2: based B, BL IMAGE_REL_BASED_ARM64_BRANCH26 = 0x14, // Arm64: B, BL IMAGE_REL_BASED_RELPTR32 = 0x7C, // 32-bit relative address from byte starting reloc // This is a special NGEN-specific relocation type // for relative pointer (used to make NGen relocation // section smaller) IMAGE_REL_SECREL = 0x80, // 32 bit offset from base of section containing target } public struct Relocation { public readonly RelocType RelocType; public readonly int Offset; public readonly ISymbolNode Target; //***************************************************************************** // Extract the 16-bit immediate from ARM Thumb2 Instruction (format T2_N) //***************************************************************************** private static unsafe ushort GetThumb2Imm16(ushort* p) { uint Opcode0 = (uint)p[0]; uint Opcode1 = (uint)p[1]; uint Result = ((Opcode0 << 12) & 0xf000) | ((Opcode0 << 1) & 0x0800) | ((Opcode1 >> 4) & 0x0700) | ((Opcode1 >> 0) & 0x00ff); return (ushort)Result; } //***************************************************************************** // Deposit the 16-bit immediate into ARM Thumb2 Instruction (format T2_N) //***************************************************************************** private static unsafe void PutThumb2Imm16(ushort* p, ushort imm16) { uint Opcode0 = (uint)p[0]; uint Opcode1 = (uint)p[1]; int val0 = (0xf000 >> 12); int val1 = (0x0800 >> 1); Opcode0 &= ~((uint)val0 | (uint)val1); int val3 = (0x0700 << 4); Opcode1 &= ~((uint)val3 | (0x00ff << 0)); Opcode0 |= ((uint)imm16 & 0xf000) >> 12; Opcode0 |= ((uint)imm16 & 0x0800) >> 1; Opcode1 |= ((uint)imm16 & 0x0700) << 4; Opcode1 |= ((uint)imm16 & 0x00ff) << 0; p[0] = (ushort)Opcode0; p[1] = (ushort)Opcode1; } //***************************************************************************** // Extract the 32-bit immediate from movw/movt sequence //***************************************************************************** private static unsafe int GetThumb2Mov32(ushort* p) { // Make sure we are decoding movw/movt sequence ushort Opcode0 = *(p + 0); ushort Opcode1 = *(p + 2); Debug.Assert(((uint)Opcode0 & 0xFBF0) == 0xF240); Debug.Assert(((uint)Opcode1 & 0xFBF0) == 0xF2C0); return (int)GetThumb2Imm16(p) + ((int)(GetThumb2Imm16(p + 2) << 16)); } //***************************************************************************** // Deposit the 32-bit immediate into movw/movt Thumb2 sequence //***************************************************************************** private static unsafe void PutThumb2Mov32(ushort* p, uint imm32) { // Make sure we are decoding movw/movt sequence ushort Opcode0 = *(p + 0); ushort Opcode1 = *(p + 2); Debug.Assert(((uint)Opcode0 & 0xFBF0) == 0xF240); Debug.Assert(((uint)Opcode1 & 0xFBF0) == 0xF2C0); ushort imm16 = (ushort)(imm32 & 0xffff); PutThumb2Imm16(p, imm16); imm16 = (ushort)(imm32 >> 16); PutThumb2Imm16(p + 2, imm16); Debug.Assert((uint)GetThumb2Mov32(p) == imm32); } //***************************************************************************** // Extract the 24-bit rel offset from bl instruction //***************************************************************************** private static unsafe int GetThumb2BlRel24(ushort* p) { uint Opcode0 = (uint)p[0]; uint Opcode1 = (uint)p[1]; uint S = Opcode0 >> 10; uint J2 = Opcode1 >> 11; uint J1 = Opcode1 >> 13; uint ret = ((S << 24) & 0x1000000) | (((J1 ^ S ^ 1) << 23) & 0x0800000) | (((J2 ^ S ^ 1) << 22) & 0x0400000) | ((Opcode0 << 12) & 0x03FF000) | ((Opcode1 << 1) & 0x0000FFE); // Sign-extend and return return (int)((ret << 7) >> 7); } //***************************************************************************** // Returns whether the offset fits into bl instruction //***************************************************************************** private static bool FitsInThumb2BlRel24(uint imm24) { return ((imm24 << 7) >> 7) == imm24; } //***************************************************************************** // Deposit the 24-bit rel offset into bl instruction //***************************************************************************** private static unsafe void PutThumb2BlRel24(ushort* p, uint imm24) { // Verify that we got a valid offset Debug.Assert(FitsInThumb2BlRel24(imm24)); // Ensure that the ThumbBit is not set on the offset // as it cannot be encoded. Debug.Assert((imm24 & 1/*THUMB_CODE*/) == 0); uint Opcode0 = (uint)p[0]; uint Opcode1 = (uint)p[1]; Opcode0 &= 0xF800; Opcode1 &= 0xD000; uint S = (imm24 & 0x1000000) >> 24; uint J1 = ((imm24 & 0x0800000) >> 23) ^ S ^ 1; uint J2 = ((imm24 & 0x0400000) >> 22) ^ S ^ 1; Opcode0 |= ((imm24 & 0x03FF000) >> 12) | (S << 10); Opcode1 |= ((imm24 & 0x0000FFE) >> 1) | (J1 << 13) | (J2 << 11); p[0] = (ushort)Opcode0; p[1] = (ushort)Opcode1; Debug.Assert((uint)GetThumb2BlRel24(p) == imm24); } public Relocation(RelocType relocType, int offset, ISymbolNode target) { RelocType = relocType; Offset = offset; Target = target; } public static unsafe void WriteValue(RelocType relocType, void* location, long value) { switch (relocType) { case RelocType.IMAGE_REL_BASED_ABSOLUTE: case RelocType.IMAGE_REL_BASED_HIGHLOW: case RelocType.IMAGE_REL_BASED_REL32: case RelocType.IMAGE_REL_BASED_ADDR32NB: *(int*)location = (int)value; break; case RelocType.IMAGE_REL_BASED_DIR64: *(long*)location = value; break; case RelocType.IMAGE_REL_BASED_THUMB_MOV32: PutThumb2Mov32((ushort*)location, (uint)value); break; case RelocType.IMAGE_REL_BASED_THUMB_BRANCH24: PutThumb2BlRel24((ushort*)location, (uint)value); break; default: Debug.Fail("Invalid RelocType: " + relocType); break; } } public static unsafe long ReadValue(RelocType relocType, void* location) { switch (relocType) { case RelocType.IMAGE_REL_BASED_ABSOLUTE: case RelocType.IMAGE_REL_BASED_ADDR32NB: case RelocType.IMAGE_REL_BASED_HIGHLOW: case RelocType.IMAGE_REL_BASED_REL32: case RelocType.IMAGE_REL_BASED_RELPTR32: case RelocType.IMAGE_REL_SECREL: return *(int*)location; case RelocType.IMAGE_REL_BASED_DIR64: return *(long*)location; case RelocType.IMAGE_REL_BASED_THUMB_MOV32: return (long)GetThumb2Mov32((ushort*)location); case RelocType.IMAGE_REL_BASED_THUMB_BRANCH24: return (long)GetThumb2BlRel24((ushort*)location); default: Debug.Fail("Invalid RelocType: " + relocType); return 0; } } public override string ToString() { return $"{Target} ({RelocType}, 0x{Offset:X})"; } } }
using EIDSS.Reports.Document.Lim.Transfer; namespace EIDSS.Reports.Document.ActiveSurveillance { partial class SessionReport { #region 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(SessionReport)); this.DetailReportTransfer = new DevExpress.XtraReports.UI.DetailReportBand(); this.DetailTransfer = new DevExpress.XtraReports.UI.DetailBand(); this.m_FarmSubreport = new DevExpress.XtraReports.UI.XRSubreport(); this.xrTableCell7 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell8 = new DevExpress.XtraReports.UI.XRTableCell(); this.DetailReport = new DevExpress.XtraReports.UI.DetailReportBand(); this.Detail1 = new DevExpress.XtraReports.UI.DetailBand(); this.xrLabel1 = new DevExpress.XtraReports.UI.XRLabel(); this.xrLabel2 = new DevExpress.XtraReports.UI.XRLabel(); this.xrLabel3 = new DevExpress.XtraReports.UI.XRLabel(); this.xrLabel4 = new DevExpress.XtraReports.UI.XRLabel(); this.xrLabel5 = new DevExpress.XtraReports.UI.XRLabel(); this.ReportFooter = new DevExpress.XtraReports.UI.ReportFooterBand(); this.xrTable1 = new DevExpress.XtraReports.UI.XRTable(); this.xrTableRow1 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell6 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell16 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell9 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell17 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell10 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableRow2 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell18 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell19 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell20 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell21 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell22 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableRow3 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell23 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell24 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell25 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell26 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell27 = new DevExpress.XtraReports.UI.XRTableCell(); this.m_SessionReportDataSet = new EIDSS.Reports.Document.ActiveSurveillance.SessionReportDataSet(); this.m_SessionAdapter = new EIDSS.Reports.Document.ActiveSurveillance.SessionReportDataSetTableAdapters.SessionAdapter(); this.xrLabel6 = new DevExpress.XtraReports.UI.XRLabel(); this.xrLabel7 = new DevExpress.XtraReports.UI.XRLabel(); this.xrLabel8 = new DevExpress.XtraReports.UI.XRLabel(); this.xrLabel9 = new DevExpress.XtraReports.UI.XRLabel(); this.xrLabel10 = new DevExpress.XtraReports.UI.XRLabel(); ((System.ComponentModel.ISupportInitialize)(this.m_BaseDataSet)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.tableBaseHeader)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.xrTable1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.m_SessionReportDataSet)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this)).BeginInit(); // // cellLanguage // this.cellLanguage.StylePriority.UseTextAlignment = false; // // lblReportName // resources.ApplyResources(this.lblReportName, "lblReportName"); this.lblReportName.StylePriority.UseBorders = false; this.lblReportName.StylePriority.UseBorderWidth = false; this.lblReportName.StylePriority.UseFont = false; this.lblReportName.StylePriority.UseTextAlignment = false; // // Detail // this.Detail.Expanded = false; this.Detail.StylePriority.UseFont = false; this.Detail.StylePriority.UsePadding = false; // // PageHeader // this.PageHeader.Borders = ((DevExpress.XtraPrinting.BorderSide)((((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top) | DevExpress.XtraPrinting.BorderSide.Right) | DevExpress.XtraPrinting.BorderSide.Bottom))); this.PageHeader.Expanded = false; resources.ApplyResources(this.PageHeader, "PageHeader"); this.PageHeader.StylePriority.UseBorders = false; this.PageHeader.StylePriority.UseFont = false; this.PageHeader.StylePriority.UsePadding = false; this.PageHeader.StylePriority.UseTextAlignment = false; // // PageFooter // resources.ApplyResources(this.PageFooter, "PageFooter"); this.PageFooter.StylePriority.UseBorders = false; // // ReportHeader // this.ReportHeader.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] { this.xrLabel10, this.xrLabel9, this.xrLabel8, this.xrLabel7, this.xrLabel6, this.xrLabel5, this.xrLabel4, this.xrLabel3, this.xrLabel2, this.xrLabel1}); resources.ApplyResources(this.ReportHeader, "ReportHeader"); this.ReportHeader.Controls.SetChildIndex(this.tableBaseHeader, 0); this.ReportHeader.Controls.SetChildIndex(this.xrLabel1, 0); this.ReportHeader.Controls.SetChildIndex(this.xrLabel2, 0); this.ReportHeader.Controls.SetChildIndex(this.xrLabel3, 0); this.ReportHeader.Controls.SetChildIndex(this.xrLabel4, 0); this.ReportHeader.Controls.SetChildIndex(this.xrLabel5, 0); this.ReportHeader.Controls.SetChildIndex(this.xrLabel6, 0); this.ReportHeader.Controls.SetChildIndex(this.xrLabel7, 0); this.ReportHeader.Controls.SetChildIndex(this.xrLabel8, 0); this.ReportHeader.Controls.SetChildIndex(this.xrLabel9, 0); this.ReportHeader.Controls.SetChildIndex(this.xrLabel10, 0); // // xrPageInfo1 // resources.ApplyResources(this.xrPageInfo1, "xrPageInfo1"); this.xrPageInfo1.StylePriority.UseBorders = false; // // cellReportHeader // this.cellReportHeader.StylePriority.UseBorders = false; this.cellReportHeader.StylePriority.UseFont = false; this.cellReportHeader.StylePriority.UseTextAlignment = false; resources.ApplyResources(this.cellReportHeader, "cellReportHeader"); // // cellBaseSite // this.cellBaseSite.StylePriority.UseBorders = false; this.cellBaseSite.StylePriority.UseFont = false; this.cellBaseSite.StylePriority.UseTextAlignment = false; resources.ApplyResources(this.cellBaseSite, "cellBaseSite"); // // tableBaseHeader // resources.ApplyResources(this.tableBaseHeader, "tableBaseHeader"); this.tableBaseHeader.StylePriority.UseBorders = false; this.tableBaseHeader.StylePriority.UseBorderWidth = false; this.tableBaseHeader.StylePriority.UseFont = false; this.tableBaseHeader.StylePriority.UsePadding = false; this.tableBaseHeader.StylePriority.UseTextAlignment = false; // // DetailReportTransfer // this.DetailReportTransfer.Bands.AddRange(new DevExpress.XtraReports.UI.Band[] { this.DetailTransfer}); resources.ApplyResources(this.DetailReportTransfer, "DetailReportTransfer"); this.DetailReportTransfer.Level = 0; this.DetailReportTransfer.Name = "DetailReportTransfer"; this.DetailReportTransfer.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 2, 2, 100F); // // DetailTransfer // this.DetailTransfer.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Right) | DevExpress.XtraPrinting.BorderSide.Bottom))); this.DetailTransfer.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] { this.m_FarmSubreport}); resources.ApplyResources(this.DetailTransfer, "DetailTransfer"); this.DetailTransfer.Name = "DetailTransfer"; this.DetailTransfer.StylePriority.UseBorders = false; this.DetailTransfer.StylePriority.UseTextAlignment = false; // // m_FarmSubreport // resources.ApplyResources(this.m_FarmSubreport, "m_FarmSubreport"); this.m_FarmSubreport.Name = "m_FarmSubreport"; this.m_FarmSubreport.ReportSource = new EIDSS.Reports.Document.ActiveSurveillance.SessionFarmReport(); // // xrTableCell7 // this.xrTableCell7.Name = "xrTableCell7"; resources.ApplyResources(this.xrTableCell7, "xrTableCell7"); // // xrTableCell8 // this.xrTableCell8.Borders = DevExpress.XtraPrinting.BorderSide.Bottom; this.xrTableCell8.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepLimSampleTransferForm.DateSent", "{0:dd/MM/yyyy}")}); this.xrTableCell8.Name = "xrTableCell8"; this.xrTableCell8.StylePriority.UseBorders = false; resources.ApplyResources(this.xrTableCell8, "xrTableCell8"); // // DetailReport // this.DetailReport.Bands.AddRange(new DevExpress.XtraReports.UI.Band[] { this.Detail1}); this.DetailReport.Level = 1; this.DetailReport.Name = "DetailReport"; // // Detail1 // resources.ApplyResources(this.Detail1, "Detail1"); this.Detail1.Name = "Detail1"; // // xrLabel1 // resources.ApplyResources(this.xrLabel1, "xrLabel1"); this.xrLabel1.Multiline = true; this.xrLabel1.Name = "xrLabel1"; this.xrLabel1.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F); this.xrLabel1.StylePriority.UseTextAlignment = false; // // xrLabel2 // resources.ApplyResources(this.xrLabel2, "xrLabel2"); this.xrLabel2.Name = "xrLabel2"; this.xrLabel2.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F); this.xrLabel2.StylePriority.UseTextAlignment = false; // // xrLabel3 // resources.ApplyResources(this.xrLabel3, "xrLabel3"); this.xrLabel3.Name = "xrLabel3"; this.xrLabel3.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F); this.xrLabel3.StylePriority.UseTextAlignment = false; // // xrLabel4 // resources.ApplyResources(this.xrLabel4, "xrLabel4"); this.xrLabel4.Name = "xrLabel4"; this.xrLabel4.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F); this.xrLabel4.StylePriority.UseTextAlignment = false; // // xrLabel5 // resources.ApplyResources(this.xrLabel5, "xrLabel5"); this.xrLabel5.Multiline = true; this.xrLabel5.Name = "xrLabel5"; this.xrLabel5.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F); this.xrLabel5.StylePriority.UseTextAlignment = false; // // ReportFooter // this.ReportFooter.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] { this.xrTable1}); resources.ApplyResources(this.ReportFooter, "ReportFooter"); this.ReportFooter.Name = "ReportFooter"; // // xrTable1 // resources.ApplyResources(this.xrTable1, "xrTable1"); this.xrTable1.Name = "xrTable1"; this.xrTable1.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] { this.xrTableRow1, this.xrTableRow2, this.xrTableRow3}); // // xrTableRow1 // this.xrTableRow1.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell6, this.xrTableCell16, this.xrTableCell9, this.xrTableCell17, this.xrTableCell10}); this.xrTableRow1.Name = "xrTableRow1"; resources.ApplyResources(this.xrTableRow1, "xrTableRow1"); // // xrTableCell6 // this.xrTableCell6.Name = "xrTableCell6"; resources.ApplyResources(this.xrTableCell6, "xrTableCell6"); // // xrTableCell16 // this.xrTableCell16.Name = "xrTableCell16"; this.xrTableCell16.StylePriority.UseTextAlignment = false; resources.ApplyResources(this.xrTableCell16, "xrTableCell16"); // // xrTableCell9 // this.xrTableCell9.Borders = DevExpress.XtraPrinting.BorderSide.Bottom; this.xrTableCell9.Name = "xrTableCell9"; this.xrTableCell9.StylePriority.UseBorders = false; resources.ApplyResources(this.xrTableCell9, "xrTableCell9"); // // xrTableCell17 // this.xrTableCell17.Name = "xrTableCell17"; resources.ApplyResources(this.xrTableCell17, "xrTableCell17"); // // xrTableCell10 // this.xrTableCell10.Name = "xrTableCell10"; resources.ApplyResources(this.xrTableCell10, "xrTableCell10"); // // xrTableRow2 // this.xrTableRow2.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell18, this.xrTableCell19, this.xrTableCell20, this.xrTableCell21, this.xrTableCell22}); this.xrTableRow2.Name = "xrTableRow2"; resources.ApplyResources(this.xrTableRow2, "xrTableRow2"); // // xrTableCell18 // this.xrTableCell18.Name = "xrTableCell18"; resources.ApplyResources(this.xrTableCell18, "xrTableCell18"); // // xrTableCell19 // this.xrTableCell19.Name = "xrTableCell19"; this.xrTableCell19.StylePriority.UseTextAlignment = false; resources.ApplyResources(this.xrTableCell19, "xrTableCell19"); // // xrTableCell20 // this.xrTableCell20.Borders = DevExpress.XtraPrinting.BorderSide.Bottom; this.xrTableCell20.Name = "xrTableCell20"; this.xrTableCell20.StylePriority.UseBorders = false; resources.ApplyResources(this.xrTableCell20, "xrTableCell20"); // // xrTableCell21 // this.xrTableCell21.Name = "xrTableCell21"; resources.ApplyResources(this.xrTableCell21, "xrTableCell21"); // // xrTableCell22 // this.xrTableCell22.Name = "xrTableCell22"; resources.ApplyResources(this.xrTableCell22, "xrTableCell22"); // // xrTableRow3 // this.xrTableRow3.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell23, this.xrTableCell24, this.xrTableCell25, this.xrTableCell26, this.xrTableCell27}); this.xrTableRow3.Name = "xrTableRow3"; resources.ApplyResources(this.xrTableRow3, "xrTableRow3"); // // xrTableCell23 // this.xrTableCell23.Name = "xrTableCell23"; resources.ApplyResources(this.xrTableCell23, "xrTableCell23"); // // xrTableCell24 // this.xrTableCell24.Name = "xrTableCell24"; this.xrTableCell24.StylePriority.UseTextAlignment = false; resources.ApplyResources(this.xrTableCell24, "xrTableCell24"); // // xrTableCell25 // this.xrTableCell25.Borders = DevExpress.XtraPrinting.BorderSide.Bottom; this.xrTableCell25.Name = "xrTableCell25"; this.xrTableCell25.StylePriority.UseBorders = false; resources.ApplyResources(this.xrTableCell25, "xrTableCell25"); // // xrTableCell26 // this.xrTableCell26.Name = "xrTableCell26"; resources.ApplyResources(this.xrTableCell26, "xrTableCell26"); // // xrTableCell27 // this.xrTableCell27.Name = "xrTableCell27"; resources.ApplyResources(this.xrTableCell27, "xrTableCell27"); // // m_SessionReportDataSet // this.m_SessionReportDataSet.DataSetName = "SessionReportDataSet"; this.m_SessionReportDataSet.SchemaSerializationMode = System.Data.SchemaSerializationMode.IncludeSchema; // // m_SessionAdapter // this.m_SessionAdapter.ClearBeforeFill = true; // // xrLabel6 // this.xrLabel6.Borders = DevExpress.XtraPrinting.BorderSide.Bottom; this.xrLabel6.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", this.m_SessionReportDataSet, "Session.strRegion")}); resources.ApplyResources(this.xrLabel6, "xrLabel6"); this.xrLabel6.Name = "xrLabel6"; this.xrLabel6.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F); this.xrLabel6.StylePriority.UseBorders = false; this.xrLabel6.StylePriority.UseTextAlignment = false; // // xrLabel7 // this.xrLabel7.Borders = DevExpress.XtraPrinting.BorderSide.Bottom; this.xrLabel7.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", this.m_SessionReportDataSet, "Session.strRayon")}); resources.ApplyResources(this.xrLabel7, "xrLabel7"); this.xrLabel7.Name = "xrLabel7"; this.xrLabel7.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F); this.xrLabel7.StylePriority.UseBorders = false; this.xrLabel7.StylePriority.UseTextAlignment = false; // // xrLabel8 // this.xrLabel8.Borders = DevExpress.XtraPrinting.BorderSide.Bottom; this.xrLabel8.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", this.m_SessionReportDataSet, "Session.strSettlement")}); resources.ApplyResources(this.xrLabel8, "xrLabel8"); this.xrLabel8.Name = "xrLabel8"; this.xrLabel8.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F); this.xrLabel8.StylePriority.UseBorders = false; this.xrLabel8.StylePriority.UseTextAlignment = false; // // xrLabel9 // this.xrLabel9.Borders = DevExpress.XtraPrinting.BorderSide.Bottom; this.xrLabel9.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", this.m_SessionReportDataSet, "Session.datEnteredDate", "{0:dd/MM/yyyy}")}); resources.ApplyResources(this.xrLabel9, "xrLabel9"); this.xrLabel9.Name = "xrLabel9"; this.xrLabel9.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F); this.xrLabel9.StylePriority.UseBorders = false; this.xrLabel9.StylePriority.UseTextAlignment = false; // // xrLabel10 // this.xrLabel10.Borders = DevExpress.XtraPrinting.BorderSide.Bottom; this.xrLabel10.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", this.m_SessionReportDataSet, "Session.strDiseases")}); resources.ApplyResources(this.xrLabel10, "xrLabel10"); this.xrLabel10.Name = "xrLabel10"; this.xrLabel10.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F); this.xrLabel10.StylePriority.UseBorders = false; this.xrLabel10.StylePriority.UseTextAlignment = false; // // SessionReport // this.Bands.AddRange(new DevExpress.XtraReports.UI.Band[] { this.Detail, this.PageHeader, this.PageFooter, this.ReportHeader, this.DetailReportTransfer, this.DetailReport, this.ReportFooter}); resources.ApplyResources(this, "$this"); this.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 2, 2, 100F); this.Version = "14.1"; this.Controls.SetChildIndex(this.ReportFooter, 0); this.Controls.SetChildIndex(this.DetailReport, 0); this.Controls.SetChildIndex(this.DetailReportTransfer, 0); this.Controls.SetChildIndex(this.ReportHeader, 0); this.Controls.SetChildIndex(this.PageFooter, 0); this.Controls.SetChildIndex(this.PageHeader, 0); this.Controls.SetChildIndex(this.Detail, 0); ((System.ComponentModel.ISupportInitialize)(this.m_BaseDataSet)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.tableBaseHeader)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.xrTable1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.m_SessionReportDataSet)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this)).EndInit(); } #endregion private DevExpress.XtraReports.UI.DetailReportBand DetailReportTransfer; private DevExpress.XtraReports.UI.DetailBand DetailTransfer; private DevExpress.XtraReports.UI.XRTableCell xrTableCell7; private DevExpress.XtraReports.UI.XRTableCell xrTableCell8; private DevExpress.XtraReports.UI.DetailReportBand DetailReport; private DevExpress.XtraReports.UI.DetailBand Detail1; private DevExpress.XtraReports.UI.XRLabel xrLabel2; private DevExpress.XtraReports.UI.XRLabel xrLabel1; private DevExpress.XtraReports.UI.XRLabel xrLabel5; private DevExpress.XtraReports.UI.XRLabel xrLabel4; private DevExpress.XtraReports.UI.XRLabel xrLabel3; private DevExpress.XtraReports.UI.ReportFooterBand ReportFooter; private DevExpress.XtraReports.UI.XRTable xrTable1; private DevExpress.XtraReports.UI.XRTableRow xrTableRow1; private DevExpress.XtraReports.UI.XRTableCell xrTableCell6; private DevExpress.XtraReports.UI.XRTableCell xrTableCell16; private DevExpress.XtraReports.UI.XRTableCell xrTableCell9; private DevExpress.XtraReports.UI.XRTableCell xrTableCell17; private DevExpress.XtraReports.UI.XRTableCell xrTableCell10; private DevExpress.XtraReports.UI.XRTableRow xrTableRow2; private DevExpress.XtraReports.UI.XRTableCell xrTableCell18; private DevExpress.XtraReports.UI.XRTableCell xrTableCell19; private DevExpress.XtraReports.UI.XRTableCell xrTableCell20; private DevExpress.XtraReports.UI.XRTableCell xrTableCell21; private DevExpress.XtraReports.UI.XRTableCell xrTableCell22; private DevExpress.XtraReports.UI.XRTableRow xrTableRow3; private DevExpress.XtraReports.UI.XRTableCell xrTableCell23; private DevExpress.XtraReports.UI.XRTableCell xrTableCell24; private DevExpress.XtraReports.UI.XRTableCell xrTableCell25; private DevExpress.XtraReports.UI.XRTableCell xrTableCell26; private DevExpress.XtraReports.UI.XRTableCell xrTableCell27; private SessionReportDataSet m_SessionReportDataSet; private EIDSS.Reports.Document.ActiveSurveillance.SessionReportDataSetTableAdapters.SessionAdapter m_SessionAdapter; private DevExpress.XtraReports.UI.XRLabel xrLabel6; private DevExpress.XtraReports.UI.XRLabel xrLabel8; private DevExpress.XtraReports.UI.XRLabel xrLabel7; private DevExpress.XtraReports.UI.XRLabel xrLabel10; private DevExpress.XtraReports.UI.XRLabel xrLabel9; private DevExpress.XtraReports.UI.XRSubreport m_FarmSubreport; } }
/// This code was generated by /// \ / _ _ _| _ _ /// | (_)\/(_)(_|\/| |(/_ v1.0.0 /// / / using System; using System.Collections.Generic; using Twilio.Base; using Twilio.Converters; namespace Twilio.Rest.IpMessaging.V1.Service.Channel { /// <summary> /// FetchMessageOptions /// </summary> public class FetchMessageOptions : IOptions<MessageResource> { /// <summary> /// The service_sid /// </summary> public string PathServiceSid { get; } /// <summary> /// The channel_sid /// </summary> public string PathChannelSid { get; } /// <summary> /// The sid /// </summary> public string PathSid { get; } /// <summary> /// Construct a new FetchMessageOptions /// </summary> /// <param name="pathServiceSid"> The service_sid </param> /// <param name="pathChannelSid"> The channel_sid </param> /// <param name="pathSid"> The sid </param> public FetchMessageOptions(string pathServiceSid, string pathChannelSid, string pathSid) { PathServiceSid = pathServiceSid; PathChannelSid = pathChannelSid; PathSid = pathSid; } /// <summary> /// Generate the necessary parameters /// </summary> public List<KeyValuePair<string, string>> GetParams() { var p = new List<KeyValuePair<string, string>>(); return p; } } /// <summary> /// CreateMessageOptions /// </summary> public class CreateMessageOptions : IOptions<MessageResource> { /// <summary> /// The service_sid /// </summary> public string PathServiceSid { get; } /// <summary> /// The channel_sid /// </summary> public string PathChannelSid { get; } /// <summary> /// The body /// </summary> public string Body { get; } /// <summary> /// The from /// </summary> public string From { get; set; } /// <summary> /// The attributes /// </summary> public string Attributes { get; set; } /// <summary> /// Construct a new CreateMessageOptions /// </summary> /// <param name="pathServiceSid"> The service_sid </param> /// <param name="pathChannelSid"> The channel_sid </param> /// <param name="body"> The body </param> public CreateMessageOptions(string pathServiceSid, string pathChannelSid, string body) { PathServiceSid = pathServiceSid; PathChannelSid = pathChannelSid; Body = body; } /// <summary> /// Generate the necessary parameters /// </summary> public List<KeyValuePair<string, string>> GetParams() { var p = new List<KeyValuePair<string, string>>(); if (Body != null) { p.Add(new KeyValuePair<string, string>("Body", Body)); } if (From != null) { p.Add(new KeyValuePair<string, string>("From", From)); } if (Attributes != null) { p.Add(new KeyValuePair<string, string>("Attributes", Attributes)); } return p; } } /// <summary> /// ReadMessageOptions /// </summary> public class ReadMessageOptions : ReadOptions<MessageResource> { /// <summary> /// The service_sid /// </summary> public string PathServiceSid { get; } /// <summary> /// The channel_sid /// </summary> public string PathChannelSid { get; } /// <summary> /// The order /// </summary> public MessageResource.OrderTypeEnum Order { get; set; } /// <summary> /// Construct a new ReadMessageOptions /// </summary> /// <param name="pathServiceSid"> The service_sid </param> /// <param name="pathChannelSid"> The channel_sid </param> public ReadMessageOptions(string pathServiceSid, string pathChannelSid) { PathServiceSid = pathServiceSid; PathChannelSid = pathChannelSid; } /// <summary> /// Generate the necessary parameters /// </summary> public override List<KeyValuePair<string, string>> GetParams() { var p = new List<KeyValuePair<string, string>>(); if (Order != null) { p.Add(new KeyValuePair<string, string>("Order", Order.ToString())); } if (PageSize != null) { p.Add(new KeyValuePair<string, string>("PageSize", PageSize.ToString())); } return p; } } /// <summary> /// DeleteMessageOptions /// </summary> public class DeleteMessageOptions : IOptions<MessageResource> { /// <summary> /// The service_sid /// </summary> public string PathServiceSid { get; } /// <summary> /// The channel_sid /// </summary> public string PathChannelSid { get; } /// <summary> /// The sid /// </summary> public string PathSid { get; } /// <summary> /// Construct a new DeleteMessageOptions /// </summary> /// <param name="pathServiceSid"> The service_sid </param> /// <param name="pathChannelSid"> The channel_sid </param> /// <param name="pathSid"> The sid </param> public DeleteMessageOptions(string pathServiceSid, string pathChannelSid, string pathSid) { PathServiceSid = pathServiceSid; PathChannelSid = pathChannelSid; PathSid = pathSid; } /// <summary> /// Generate the necessary parameters /// </summary> public List<KeyValuePair<string, string>> GetParams() { var p = new List<KeyValuePair<string, string>>(); return p; } } /// <summary> /// UpdateMessageOptions /// </summary> public class UpdateMessageOptions : IOptions<MessageResource> { /// <summary> /// The service_sid /// </summary> public string PathServiceSid { get; } /// <summary> /// The channel_sid /// </summary> public string PathChannelSid { get; } /// <summary> /// The sid /// </summary> public string PathSid { get; } /// <summary> /// The body /// </summary> public string Body { get; set; } /// <summary> /// The attributes /// </summary> public string Attributes { get; set; } /// <summary> /// Construct a new UpdateMessageOptions /// </summary> /// <param name="pathServiceSid"> The service_sid </param> /// <param name="pathChannelSid"> The channel_sid </param> /// <param name="pathSid"> The sid </param> public UpdateMessageOptions(string pathServiceSid, string pathChannelSid, string pathSid) { PathServiceSid = pathServiceSid; PathChannelSid = pathChannelSid; PathSid = pathSid; } /// <summary> /// Generate the necessary parameters /// </summary> public List<KeyValuePair<string, string>> GetParams() { var p = new List<KeyValuePair<string, string>>(); if (Body != null) { p.Add(new KeyValuePair<string, string>("Body", Body)); } if (Attributes != null) { p.Add(new KeyValuePair<string, string>("Attributes", Attributes)); } return p; } } }
/* * 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 log4net; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; using System; using System.Collections.Generic; using System.IO; using System.Net.Sockets; using System.Reflection; using System.Text.RegularExpressions; using System.Threading; using System.Timers; namespace OpenSim.Region.OptionalModules.Avatar.Chat { public class IRCConnector { #region Global (static) state private const int WD_INTERVAL = 1000; // This computation is not the real region center if the region is larger than 256. // This computation isn't fixed because there is not a handle back to the region. private static readonly Vector3 CenterOfRegion = new Vector3(((int)Constants.RegionSize * 0.5f), ((int)Constants.RegionSize * 0.5f), 20); // Local constants private static readonly char[] CS_SPACE = { ' ' }; private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private static int _icc_ = ICCD_PERIOD; private static int _idk_ = 0; // core connector identifier private static int _pdk_ = 0; private static int ICCD_PERIOD = 10; // WD intervals between Connects private static int L_TIMEOUT = 25; private static List<IRCConnector> m_connectors = new List<IRCConnector>(); private static System.Timers.Timer m_watchdog = null; // base watchdog interval private static int PING_PERIOD = 15; // WD intervals per PING // Login time out interval // ping interval counter // IRC connect counter // List of configured connectors // Watchdog state // The watch-dog gets started as soon as the class is instantiated, and // ticks once every second (WD_INTERVAL) static IRCConnector() { m_log.DebugFormat("[IRC-Connector]: Static initialization started"); m_watchdog = new System.Timers.Timer(WD_INTERVAL); m_watchdog.Elapsed += new ElapsedEventHandler(WatchdogHandler); m_watchdog.AutoReset = true; m_watchdog.Start(); m_log.DebugFormat("[IRC-Connector]: Static initialization complete"); } #endregion Global (static) state #region Instance state // Connector identity internal string chanmod = String.Empty; internal int depends = 0; internal int idn = _idk_++; // How many regions depend upon this connection // This count is updated by the ChannelState object and reflects the sum // of the region clients associated with the set of associated channel // state instances. That's why it cannot be managed here. // This variable counts the number of resets that have been performed // on the connector. When a listener thread terminates, it checks to // see of the reset count has changed before it schedules another // reset. internal string m_baseNick = null; // base name for randomizing internal string m_nick = null; internal bool m_randomizeNick = true; internal int m_resetk = 0; // Working threads internal bool motd = false; internal string usermod = String.Empty; // Channel characteristic info (if available) internal string version = String.Empty; private bool m_connected = false; private bool m_enabled = false; private string m_ircChannel; private Thread m_listener = null; private string m_password = null; // connection status private bool m_pending = false; private uint m_port = 6667; private StreamReader m_reader; private string m_server = null; private NetworkStream m_stream = null; private TcpClient m_tcp; // login disposition private int m_timeout = L_TIMEOUT; private string m_user = "USER OpenSimBot 8 * :I'm an OpenSim to IRC bot"; // Network interface private StreamWriter m_writer; private Object msyncConnect = new Object(); // add random suffix // effective nickname public bool Connected { get { return m_connected; } } public bool Enabled { get { return m_enabled; } } public string IrcChannel { get { return m_ircChannel; } set { m_ircChannel = value; } } public string Nick // Public property { get { return m_nick; } set { m_nick = value; } } // connector enablement // login timeout counter // associated channel id // session port public string Password { get { return m_password; } set { m_password = value; } } public uint Port { get { return m_port; } set { m_port = value; } } // IRC server name public string Server { get { return m_server; } set { m_server = value; } } public string User { get { return m_user; } } #endregion Instance state #region connector instance management internal IRCConnector(ChannelState cs) { // Prepare network interface m_tcp = null; m_writer = null; m_reader = null; // Setup IRC session parameters m_server = cs.Server; m_password = cs.Password; m_baseNick = cs.BaseNickname; m_randomizeNick = cs.RandomizeNickname; m_ircChannel = cs.IrcChannel; m_port = cs.Port; m_user = cs.User; if (m_watchdog == null) { // Non-differentiating ICCD_PERIOD = cs.ConnectDelay; PING_PERIOD = cs.PingDelay; // Smaller values are not reasonable if (ICCD_PERIOD < 5) ICCD_PERIOD = 5; if (PING_PERIOD < 5) PING_PERIOD = 5; _icc_ = ICCD_PERIOD; // get started right away! } // The last line of defense if (m_server == null || m_baseNick == null || m_ircChannel == null || m_user == null) throw new Exception("Invalid connector configuration"); // Generate an initial nickname if (m_randomizeNick) m_nick = m_baseNick + Util.RandomClass.Next(1, 99); else m_nick = m_baseNick; m_log.InfoFormat("[IRC-Connector-{0}]: Initialization complete", idn); } ~IRCConnector() { m_watchdog.Stop(); Close(); } // Mark the connector as connectable. Harmless if already enabled. public void Close() { m_log.InfoFormat("[IRC-Connector-{0}] Closing", idn); lock (msyncConnect) { if ((depends == 0) && Enabled) { m_enabled = false; if (Connected) { m_log.DebugFormat("[IRC-Connector-{0}] Closing interface", idn); // Cleanup the IRC session try { m_writer.WriteLine(String.Format("QUIT :{0} to {1} wormhole to {2} closing", m_nick, m_ircChannel, m_server)); m_writer.Flush(); } catch (Exception) { } m_connected = false; try { m_writer.Close(); } catch (Exception) { } try { m_reader.Close(); } catch (Exception) { } try { m_stream.Close(); } catch (Exception) { } try { m_tcp.Close(); } catch (Exception) { } } lock (m_connectors) m_connectors.Remove(this); } } m_log.InfoFormat("[IRC-Connector-{0}] Closed", idn); } public void Open() { if (!m_enabled) { if (!Connected) { Connect(); } lock (m_connectors) m_connectors.Add(this); m_enabled = true; } } // Only close the connector if the dependency count is zero. #endregion connector instance management #region session management // Connect to the IRC server. A connector should always be connected, once enabled public void Connect() { if (!m_enabled) return; // Delay until next WD cycle if this is too close to the last start attempt while (_icc_ < ICCD_PERIOD) return; m_log.DebugFormat("[IRC-Connector-{0}]: Connection request for {1} on {2}:{3}", idn, m_nick, m_server, m_ircChannel); lock (msyncConnect) { _icc_ = 0; try { if (m_connected) return; m_connected = true; m_pending = true; m_timeout = L_TIMEOUT; m_tcp = new TcpClient(m_server, (int)m_port); m_stream = m_tcp.GetStream(); m_reader = new StreamReader(m_stream); m_writer = new StreamWriter(m_stream); m_log.InfoFormat("[IRC-Connector-{0}]: Connected to {1}:{2}", idn, m_server, m_port); m_listener = new Thread(new ThreadStart(ListenerRun)); m_listener.Name = "IRCConnectorListenerThread"; m_listener.IsBackground = true; m_listener.Start(); // This is the message order recommended by RFC 2812 if (m_password != null) m_writer.WriteLine(String.Format("PASS {0}", m_password)); m_writer.WriteLine(String.Format("NICK {0}", m_nick)); m_writer.Flush(); m_writer.WriteLine(m_user); m_writer.Flush(); m_writer.WriteLine(String.Format("JOIN {0}", m_ircChannel)); m_writer.Flush(); m_log.InfoFormat("[IRC-Connector-{0}]: {1} has asked to join {2}", idn, m_nick, m_ircChannel); } catch (Exception e) { m_log.ErrorFormat("[IRC-Connector-{0}] cannot connect {1} to {2}:{3}: {4}", idn, m_nick, m_server, m_port, e.Message); // It might seem reasonable to reset connected and pending status here // Seeing as we know that the login has failed, but if we do that, then // connection will be retried each time the interconnection interval // expires. By leaving them as they are, the connection will be retried // when the login timeout expires. Which is preferred. } } return; } // Reconnect is used to force a re-cycle of the IRC connection. Should generally // be a transparent event public void Reconnect() { m_log.DebugFormat("[IRC-Connector-{0}]: Reconnect request for {1} on {2}:{3}", idn, m_nick, m_server, m_ircChannel); // Don't do this if a Connect is in progress... lock (msyncConnect) { if (m_connected) { m_log.InfoFormat("[IRC-Connector-{0}] Resetting connector", idn); // Mark as disconnected. This will allow the listener thread // to exit if still in-flight. // The listener thread is not aborted - it *might* actually be // the thread that is running the Reconnect! Instead just close // the socket and it will disappear of its own accord, once this // processing is completed. try { m_writer.Close(); } catch (Exception) { } try { m_reader.Close(); } catch (Exception) { } try { m_tcp.Close(); } catch (Exception) { } m_connected = false; m_pending = false; m_resetk++; } } Connect(); } #endregion session management #region Outbound (to-IRC) message handlers public void PrivMsg(string pattern, string from, string region, string msg) { // m_log.DebugFormat("[IRC-Connector-{0}] PrivMsg to IRC from {1}: <{2}>", idn, from, // String.Format(pattern, m_ircChannel, from, region, msg)); // One message to the IRC server try { m_writer.WriteLine(pattern, m_ircChannel, from, region, msg); m_writer.Flush(); // m_log.DebugFormat("[IRC-Connector-{0}]: PrivMsg from {1} in {2}: {3}", idn, from, region, msg); } catch (IOException) { m_log.ErrorFormat("[IRC-Connector-{0}]: PrivMsg I/O Error: disconnected from IRC server", idn); Reconnect(); } catch (Exception ex) { m_log.ErrorFormat("[IRC-Connector-{0}]: PrivMsg exception : {1}", idn, ex.Message); m_log.Debug(ex); } } public void Send(string msg) { // m_log.DebugFormat("[IRC-Connector-{0}] Send to IRC : <{1}>", idn, msg); try { m_writer.WriteLine(msg); m_writer.Flush(); // m_log.DebugFormat("[IRC-Connector-{0}] Sent command string: {1}", idn, msg); } catch (IOException) { m_log.ErrorFormat("[IRC-Connector-{0}] Disconnected from IRC server.(Send)", idn); Reconnect(); } catch (Exception ex) { m_log.ErrorFormat("[IRC-Connector-{0}] Send exception trap: {0}", idn, ex.Message); m_log.Debug(ex); } } #endregion Outbound (to-IRC) message handlers private Regex RE = new Regex(@":(?<nick>[\w-]*)!(?<user>\S*) PRIVMSG (?<channel>\S+) :(?<msg>.*)", RegexOptions.Multiline); public void BroadcastSim(string sender, string format, params string[] args) { try { OSChatMessage c = new OSChatMessage(); c.From = sender; c.Message = String.Format(format, args); c.Type = ChatTypeEnum.Region; // ChatTypeEnum.Say; c.Position = CenterOfRegion; c.Sender = null; c.SenderUUID = UUID.Zero; ChannelState.OSChat(this, c, true); } catch (Exception ex) // IRC gate should not crash Sim { m_log.ErrorFormat("[IRC-Connector-{0}]: BroadcastSim Exception Trap: {1}\n{2}", idn, ex.Message, ex.StackTrace); } } public void ListenerRun() { string inputLine; int resetk = m_resetk; try { while (m_enabled && m_connected) { if ((inputLine = m_reader.ReadLine()) == null) throw new Exception("Listener input socket closed"); // m_log.Info("[IRCConnector]: " + inputLine); if (inputLine.Contains("PRIVMSG")) { Dictionary<string, string> data = ExtractMsg(inputLine); // Any chat ??? if (data != null) { OSChatMessage c = new OSChatMessage(); c.Message = data["msg"]; c.Type = ChatTypeEnum.Region; c.Position = CenterOfRegion; c.From = data["nick"]; c.Sender = null; c.SenderUUID = UUID.Zero; // Is message "\001ACTION foo bar\001"? // Then change to: "/me foo bar" if ((1 == c.Message[0]) && c.Message.Substring(1).StartsWith("ACTION")) c.Message = String.Format("/me {0}", c.Message.Substring(8, c.Message.Length - 9)); ChannelState.OSChat(this, c, false); } } else { ProcessIRCCommand(inputLine); } } } catch (Exception /*e*/) { // m_log.ErrorFormat("[IRC-Connector-{0}]: ListenerRun exception trap: {1}", idn, e.Message); // m_log.Debug(e); } // This is potentially circular, but harmless if so. // The connection is marked as not connected the first time // through reconnect. if (m_enabled && (m_resetk == resetk)) Reconnect(); } private Dictionary<string, string> ExtractMsg(string input) { //examines IRC commands and extracts any private messages // which will then be reboadcast in the Sim // m_log.InfoFormat("[IRC-Connector-{0}]: ExtractMsg: {1}", idn, input); Dictionary<string, string> result = null; MatchCollection matches = RE.Matches(input); // Get some direct matches $1 $4 is a if ((matches.Count == 0) || (matches.Count != 1) || (matches[0].Groups.Count != 5)) { // m_log.Info("[IRCConnector]: Number of matches: " + matches.Count); // if (matches.Count > 0) // { // m_log.Info("[IRCConnector]: Number of groups: " + matches[0].Groups.Count); // } return null; } result = new Dictionary<string, string>(); result.Add("nick", matches[0].Groups[1].Value); result.Add("user", matches[0].Groups[2].Value); result.Add("channel", matches[0].Groups[3].Value); result.Add("msg", matches[0].Groups[4].Value); return result; } #region IRC Command Handlers public void eventIrcJoin(string prefix, string command, string parms) { string[] args = parms.Split(CS_SPACE, 2); string IrcUser = prefix.Split('!')[0]; string IrcChannel = args[0]; if (IrcChannel.StartsWith(":")) IrcChannel = IrcChannel.Substring(1); m_log.DebugFormat("[IRC-Connector-{0}] Event: IRCJoin {1}:{2}", idn, m_server, m_ircChannel); BroadcastSim(IrcUser, "/me joins {0}", IrcChannel); } public void eventIrcKick(string prefix, string command, string parms) { string[] args = parms.Split(CS_SPACE, 3); string UserKicker = prefix.Split('!')[0]; string IrcChannel = args[0]; string UserKicked = args[1]; string KickMessage = args[2]; m_log.DebugFormat("[IRC-Connector-{0}] Event: IRCKick {1}:{2}", idn, m_server, m_ircChannel); BroadcastSim(UserKicker, "/me kicks kicks {0} off {1} saying \"{2}\"", UserKicked, IrcChannel, KickMessage); if (UserKicked == m_nick) { BroadcastSim(m_nick, "Hey, that was me!!!"); } } public void eventIrcMode(string prefix, string command, string parms) { string[] args = parms.Split(CS_SPACE, 2); string UserMode = args[1]; m_log.DebugFormat("[IRC-Connector-{0}] Event: IRCMode {1}:{2}", idn, m_server, m_ircChannel); if (UserMode.Substring(0, 1) == ":") { UserMode = UserMode.Remove(0, 1); } } public void eventIrcNickChange(string prefix, string command, string parms) { string[] args = parms.Split(CS_SPACE, 2); string UserOldNick = prefix.Split('!')[0]; string UserNewNick = args[0].Remove(0, 1); m_log.DebugFormat("[IRC-Connector-{0}] Event: IRCNickChange {1}:{2}", idn, m_server, m_ircChannel); BroadcastSim(UserOldNick, "/me is now known as {0}", UserNewNick); } public void eventIrcPart(string prefix, string command, string parms) { string[] args = parms.Split(CS_SPACE, 2); string IrcUser = prefix.Split('!')[0]; string IrcChannel = args[0]; m_log.DebugFormat("[IRC-Connector-{0}] Event: IRCPart {1}:{2}", idn, m_server, m_ircChannel); BroadcastSim(IrcUser, "/me parts {0}", IrcChannel); } public void eventIrcQuit(string prefix, string command, string parms) { string IrcUser = prefix.Split('!')[0]; string QuitMessage = parms; m_log.DebugFormat("[IRC-Connector-{0}] Event: IRCQuit {1}:{2}", idn, m_server, m_ircChannel); BroadcastSim(IrcUser, "/me quits saying \"{0}\"", QuitMessage); } public void ProcessIRCCommand(string command) { string[] commArgs; string c_server = m_server; string pfx = String.Empty; string cmd = String.Empty; string parms = String.Empty; // ":" indicates that a prefix is present // There are NEVER more than 17 real // fields. A parameter that starts with // ":" indicates that the remainder of the // line is a single parameter value. commArgs = command.Split(CS_SPACE, 2); if (commArgs[0].StartsWith(":")) { pfx = commArgs[0].Substring(1); commArgs = commArgs[1].Split(CS_SPACE, 2); } cmd = commArgs[0]; parms = commArgs[1]; // m_log.DebugFormat("[IRC-Connector-{0}] prefix = <{1}> cmd = <{2}>", idn, pfx, cmd); switch (cmd) { // Messages 001-004 are always sent // following signon. case "001": // Welcome ... case "002": // Server information case "003": // Welcome ... break; case "004": // Server information m_log.DebugFormat("[IRC-Connector-{0}] [{1}] parms = <{2}>", idn, cmd, parms); commArgs = parms.Split(CS_SPACE); c_server = commArgs[1]; m_server = c_server; version = commArgs[2]; usermod = commArgs[3]; chanmod = commArgs[4]; break; case "005": // Server information break; case "042": case "250": case "251": case "252": case "254": case "255": case "265": case "266": case "332": // Subject case "333": // Subject owner (?) case "353": // Name list case "366": // End-of-Name list marker case "372": // MOTD body case "375": // MOTD start // m_log.InfoFormat("[IRC-Connector-{0}] [{1}] {2}", idn, cmd, parms.Split(CS_SPACE,2)[1]); break; case "376": // MOTD end // m_log.InfoFormat("[IRC-Connector-{0}] [{1}] {2}", idn, cmd, parms.Split(CS_SPACE,2)[1]); motd = true; break; case "451": // Not registered break; case "433": // Nickname in use // Gen a new name m_nick = m_baseNick + Util.RandomClass.Next(1, 99); m_log.ErrorFormat("[IRC-Connector-{0}]: [{1}] IRC SERVER reports NicknameInUse, trying {2}", idn, cmd, m_nick); // Retry m_writer.WriteLine(String.Format("NICK {0}", m_nick)); m_writer.Flush(); m_writer.WriteLine(m_user); m_writer.Flush(); m_writer.WriteLine(String.Format("JOIN {0}", m_ircChannel)); m_writer.Flush(); break; case "479": // Bad channel name, etc. This will never work, so disable the connection m_log.ErrorFormat("[IRC-Connector-{0}] [{1}] {2}", idn, cmd, parms.Split(CS_SPACE, 2)[1]); m_log.ErrorFormat("[IRC-Connector-{0}] [{1}] Connector disabled", idn, cmd); m_enabled = false; m_connected = false; m_pending = false; break; case "NOTICE": // m_log.WarnFormat("[IRC-Connector-{0}] [{1}] {2}", idn, cmd, parms.Split(CS_SPACE,2)[1]); break; case "ERROR": m_log.ErrorFormat("[IRC-Connector-{0}] [{1}] {2}", idn, cmd, parms.Split(CS_SPACE, 2)[1]); if (parms.Contains("reconnect too fast")) ICCD_PERIOD++; m_pending = false; Reconnect(); break; case "PING": m_log.DebugFormat("[IRC-Connector-{0}] [{1}] parms = <{2}>", idn, cmd, parms); m_writer.WriteLine(String.Format("PONG {0}", parms)); m_writer.Flush(); break; case "PONG": break; case "JOIN": if (m_pending) { m_log.InfoFormat("[IRC-Connector-{0}] [{1}] Connected", idn, cmd); m_pending = false; } m_log.DebugFormat("[IRC-Connector-{0}] [{1}] parms = <{2}>", idn, cmd, parms); eventIrcJoin(pfx, cmd, parms); break; case "PART": m_log.DebugFormat("[IRC-Connector-{0}] [{1}] parms = <{2}>", idn, cmd, parms); eventIrcPart(pfx, cmd, parms); break; case "MODE": m_log.DebugFormat("[IRC-Connector-{0}] [{1}] parms = <{2}>", idn, cmd, parms); eventIrcMode(pfx, cmd, parms); break; case "NICK": m_log.DebugFormat("[IRC-Connector-{0}] [{1}] parms = <{2}>", idn, cmd, parms); eventIrcNickChange(pfx, cmd, parms); break; case "KICK": m_log.DebugFormat("[IRC-Connector-{0}] [{1}] parms = <{2}>", idn, cmd, parms); eventIrcKick(pfx, cmd, parms); break; case "QUIT": m_log.DebugFormat("[IRC-Connector-{0}] [{1}] parms = <{2}>", idn, cmd, parms); eventIrcQuit(pfx, cmd, parms); break; default: m_log.DebugFormat("[IRC-Connector-{0}] Command '{1}' ignored, parms = {2}", idn, cmd, parms); break; } // m_log.DebugFormat("[IRC-Connector-{0}] prefix = <{1}> cmd = <{2}> complete", idn, pfx, cmd); } #endregion IRC Command Handlers #region Connector Watch Dog // A single watch dog monitors extant connectors and makes sure that they // are re-connected as necessary. If a connector IS connected, then it is // pinged, but only if a PING period has elapsed. protected static void WatchdogHandler(Object source, ElapsedEventArgs args) { // m_log.InfoFormat("[IRC-Watchdog] Status scan, pdk = {0}, icc = {1}", _pdk_, _icc_); _pdk_ = (_pdk_ + 1) % PING_PERIOD; // cycle the ping trigger _icc_++; // increment the inter-consecutive-connect-delay counter lock (m_connectors) foreach (IRCConnector connector in m_connectors) { // m_log.InfoFormat("[IRC-Watchdog] Scanning {0}", connector); if (connector.Enabled) { if (!connector.Connected) { try { // m_log.DebugFormat("[IRC-Watchdog] Connecting {1}:{2}", connector.idn, connector.m_server, connector.m_ircChannel); connector.Connect(); } catch (Exception e) { m_log.ErrorFormat("[IRC-Watchdog] Exception on connector {0}: {1} ", connector.idn, e.Message); } } else { if (connector.m_pending) { if (connector.m_timeout == 0) { m_log.ErrorFormat("[IRC-Watchdog] Login timed-out for connector {0}, reconnecting", connector.idn); connector.Reconnect(); } else connector.m_timeout--; } // Being marked connected is not enough to ping. Socket establishment can sometimes take a long // time, in which case the watch dog might try to ping the server before the socket has been // set up, with nasty side-effects. else if (_pdk_ == 0) { try { connector.m_writer.WriteLine(String.Format("PING :{0}", connector.m_server)); connector.m_writer.Flush(); } catch (Exception e) { m_log.ErrorFormat("[IRC-PingRun] Exception on connector {0}: {1} ", connector.idn, e.Message); m_log.Debug(e); connector.Reconnect(); } } } } } // m_log.InfoFormat("[IRC-Watchdog] Status scan completed"); } #endregion Connector Watch Dog } }
/* * Qa full api * * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) * * OpenAPI spec version: all * * Generated by: https://github.com/swagger-api/swagger-codegen.git * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Linq; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.ComponentModel.DataAnnotations; namespace HostMe.Sdk.Model { /// <summary> /// PaymentSettings /// </summary> [DataContract] public partial class PaymentSettings : IEquatable<PaymentSettings>, IValidatableObject { /// <summary> /// Initializes a new instance of the <see cref="PaymentSettings" /> class. /// </summary> /// <param name="PartiesFromWaitings">PartiesFromWaitings.</param> /// <param name="PartiesFromReservations">PartiesFromReservations.</param> /// <param name="PartiesFromTables">PartiesFromTables.</param> /// <param name="LastWeekParties">LastWeekParties.</param> /// <param name="LimitsExceededDate">LimitsExceededDate.</param> /// <param name="Plans">Plans.</param> public PaymentSettings(int? PartiesFromWaitings = null, int? PartiesFromReservations = null, int? PartiesFromTables = null, int? LastWeekParties = null, DateTimeOffset? LimitsExceededDate = null, List<PaymentPlan> Plans = null) { this.PartiesFromWaitings = PartiesFromWaitings; this.PartiesFromReservations = PartiesFromReservations; this.PartiesFromTables = PartiesFromTables; this.LastWeekParties = LastWeekParties; this.LimitsExceededDate = LimitsExceededDate; this.Plans = Plans; } /// <summary> /// Gets or Sets PartiesFromWaitings /// </summary> [DataMember(Name="partiesFromWaitings", EmitDefaultValue=true)] public int? PartiesFromWaitings { get; set; } /// <summary> /// Gets or Sets PartiesFromReservations /// </summary> [DataMember(Name="partiesFromReservations", EmitDefaultValue=true)] public int? PartiesFromReservations { get; set; } /// <summary> /// Gets or Sets PartiesFromTables /// </summary> [DataMember(Name="partiesFromTables", EmitDefaultValue=true)] public int? PartiesFromTables { get; set; } /// <summary> /// Gets or Sets LastWeekParties /// </summary> [DataMember(Name="lastWeekParties", EmitDefaultValue=true)] public int? LastWeekParties { get; set; } /// <summary> /// Gets or Sets LimitsExceededDate /// </summary> [DataMember(Name="limitsExceededDate", EmitDefaultValue=true)] public DateTimeOffset? LimitsExceededDate { get; set; } /// <summary> /// Gets or Sets Plans /// </summary> [DataMember(Name="plans", EmitDefaultValue=true)] public List<PaymentPlan> Plans { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class PaymentSettings {\n"); sb.Append(" PartiesFromWaitings: ").Append(PartiesFromWaitings).Append("\n"); sb.Append(" PartiesFromReservations: ").Append(PartiesFromReservations).Append("\n"); sb.Append(" PartiesFromTables: ").Append(PartiesFromTables).Append("\n"); sb.Append(" LastWeekParties: ").Append(LastWeekParties).Append("\n"); sb.Append(" LimitsExceededDate: ").Append(LimitsExceededDate).Append("\n"); sb.Append(" Plans: ").Append(Plans).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="obj">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object obj) { // credit: http://stackoverflow.com/a/10454552/677735 return this.Equals(obj as PaymentSettings); } /// <summary> /// Returns true if PaymentSettings instances are equal /// </summary> /// <param name="other">Instance of PaymentSettings to be compared</param> /// <returns>Boolean</returns> public bool Equals(PaymentSettings other) { // credit: http://stackoverflow.com/a/10454552/677735 if (other == null) return false; return ( this.PartiesFromWaitings == other.PartiesFromWaitings || this.PartiesFromWaitings != null && this.PartiesFromWaitings.Equals(other.PartiesFromWaitings) ) && ( this.PartiesFromReservations == other.PartiesFromReservations || this.PartiesFromReservations != null && this.PartiesFromReservations.Equals(other.PartiesFromReservations) ) && ( this.PartiesFromTables == other.PartiesFromTables || this.PartiesFromTables != null && this.PartiesFromTables.Equals(other.PartiesFromTables) ) && ( this.LastWeekParties == other.LastWeekParties || this.LastWeekParties != null && this.LastWeekParties.Equals(other.LastWeekParties) ) && ( this.LimitsExceededDate == other.LimitsExceededDate || this.LimitsExceededDate != null && this.LimitsExceededDate.Equals(other.LimitsExceededDate) ) && ( this.Plans == other.Plans || this.Plans != null && this.Plans.SequenceEqual(other.Plans) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { // credit: http://stackoverflow.com/a/263416/677735 unchecked // Overflow is fine, just wrap { int hash = 41; // Suitable nullity checks etc, of course :) if (this.PartiesFromWaitings != null) hash = hash * 59 + this.PartiesFromWaitings.GetHashCode(); if (this.PartiesFromReservations != null) hash = hash * 59 + this.PartiesFromReservations.GetHashCode(); if (this.PartiesFromTables != null) hash = hash * 59 + this.PartiesFromTables.GetHashCode(); if (this.LastWeekParties != null) hash = hash * 59 + this.LastWeekParties.GetHashCode(); if (this.LimitsExceededDate != null) hash = hash * 59 + this.LimitsExceededDate.GetHashCode(); if (this.Plans != null) hash = hash * 59 + this.Plans.GetHashCode(); return hash; } } public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) { yield break; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Security; using System.Runtime.CompilerServices; using System.Security.Cryptography.X509Certificates; using System.Text; using System.Text.Json; using Azure.Core; using Azure.Core.Pipeline; using Azure.Core.TestFramework; using NUnit.Framework; namespace Azure.Security.ConfidentialLedger.Tests.samples { public class HelloWorldSamples : SamplesBase<ConfidentialLedgerEnvironment> { [Test] public void HelloWorld() { #region Snippet:GetIdentity #if SNIPPET Uri identityServiceEndpoint = new("https://identity.confidential-ledger.core.azure.com") // The hostname from the identityServiceUri #else Uri identityServiceEndpoint = TestEnvironment.ConfidentialLedgerIdentityUrl; #endif var identityClient = new ConfidentialLedgerIdentityServiceClient(identityServiceEndpoint); // Get the ledger's TLS certificate for our ledger. #if SNIPPET string ledgerId = "<the ledger id>"; // ex. "my-ledger" from "https://my-ledger.eastus.cloudapp.azure.com" #else var ledgerId = TestEnvironment.ConfidentialLedgerUrl.Host; ledgerId = ledgerId.Substring(0, ledgerId.IndexOf('.')); #endif Response response = identityClient.GetLedgerIdentity(ledgerId); X509Certificate2 ledgerTlsCert = ConfidentialLedgerIdentityServiceClient.ParseCertificate(response); #endregion #region Snippet:CreateClient // Create a certificate chain rooted with our TLS cert. X509Chain certificateChain = new(); certificateChain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck; certificateChain.ChainPolicy.RevocationFlag = X509RevocationFlag.ExcludeRoot; certificateChain.ChainPolicy.VerificationFlags = X509VerificationFlags.AllowUnknownCertificateAuthority; certificateChain.ChainPolicy.VerificationTime = DateTime.Now; certificateChain.ChainPolicy.UrlRetrievalTimeout = new TimeSpan(0, 0, 0); certificateChain.ChainPolicy.ExtraStore.Add(ledgerTlsCert); var f = certificateChain.Build(ledgerTlsCert); // Define a validation function to ensure that the ledger certificate is trusted by the ledger identity TLS certificate. bool CertValidationCheck(HttpRequestMessage httpRequestMessage, X509Certificate2 cert, X509Chain x509Chain, SslPolicyErrors sslPolicyErrors) { bool isChainValid = certificateChain.Build(cert); if (!isChainValid) return false; var isCertSignedByTheTlsCert = certificateChain.ChainElements.Cast<X509ChainElement>() .Any(x => x.Certificate.Thumbprint == ledgerTlsCert.Thumbprint); return isCertSignedByTheTlsCert; } // Create an HttpClientHandler to use our certValidationCheck function. var httpHandler = new HttpClientHandler(); httpHandler.ServerCertificateCustomValidationCallback = CertValidationCheck; // Create the ledger client using a transport that uses our custom ServerCertificateCustomValidationCallback. var options = new ConfidentialLedgerClientOptions { Transport = new HttpClientTransport(httpHandler) }; #if SNIPPET var ledgerClient = new ConfidentialLedgerClient(TestEnvironment.ConfidentialLedgerUrl, new DefaultAzureCredential(), options); #else var ledgerClient = new ConfidentialLedgerClient(TestEnvironment.ConfidentialLedgerUrl, TestEnvironment.Credential, options); #endif #endregion #region Snippet:AppendToLedger PostLedgerEntryOperation postOperation = ledgerClient.PostLedgerEntry( RequestContent.Create( new { contents = "Hello world!" }), waitForCompletion: true); string transactionId = postOperation.Id; Console.WriteLine($"Appended transaction with Id: {transactionId}"); #endregion #region Snippet:GetStatus Response statusResponse = ledgerClient.GetTransactionStatus(transactionId); string status = JsonDocument.Parse(statusResponse.Content) .RootElement .GetProperty("state") .GetString(); Console.WriteLine($"Transaction status: {status}"); // Wait for the entry to be committed while (status == "Pending") { statusResponse = ledgerClient.GetTransactionStatus(transactionId); status = JsonDocument.Parse(statusResponse.Content) .RootElement .GetProperty("state") .GetString(); } Console.WriteLine($"Transaction status: {status}"); #endregion #region Snippet:GetReceipt Response receiptResponse = ledgerClient.GetReceipt(transactionId); string receiptJson = new StreamReader(receiptResponse.ContentStream).ReadToEnd(); Console.WriteLine(receiptJson); #endregion #region Snippet:SubLedger ledgerClient.PostLedgerEntry( RequestContent.Create( new { contents = "Hello from Chris!", subLedgerId = "Chris' messages" }), waitForCompletion: true); ledgerClient.PostLedgerEntry( RequestContent.Create( new { contents = "Hello from Allison!", subLedgerId = "Allison's messages" }), waitForCompletion: true); #endregion #region Snippet:NoSubLedgerId #if SNIPPET Response postResponse = ledgerClient.PostLedgerEntry( #else postOperation = ledgerClient.PostLedgerEntry( #endif RequestContent.Create( new { contents = "Hello world!" }), waitForCompletion: true); #if SNIPPET string transactionId = postOperation.Id; #else transactionId = postOperation.Id; #endif string subLedgerId = "subledger:0"; // Provide both the transactionId and subLedgerId. Response getBySubledgerResponse = ledgerClient.GetLedgerEntry(transactionId, subLedgerId); // Try until the entry is available. bool loaded = false; JsonElement element = default; string contents = null; while (!loaded) { loaded = JsonDocument.Parse(getBySubledgerResponse.Content) .RootElement .TryGetProperty("entry", out element); if (loaded) { contents = element.GetProperty("contents").GetString(); } else { getBySubledgerResponse = ledgerClient.GetLedgerEntry(transactionId, subLedgerId); } } Console.WriteLine(contents); // "Hello world!" // Now just provide the transactionId. getBySubledgerResponse = ledgerClient.GetLedgerEntry(transactionId); string subLedgerId2 = JsonDocument.Parse(getBySubledgerResponse.Content) .RootElement .GetProperty("entry") .GetProperty("subLedgerId") .GetString(); Console.WriteLine($"{subLedgerId} == {subLedgerId2}"); #endregion #region Snippet:GetEnteryWithNoTransactionId PostLedgerEntryOperation firstPostOperation = ledgerClient.PostLedgerEntry( RequestContent.Create(new { contents = "Hello world 0" }), waitForCompletion: true); ledgerClient.PostLedgerEntry( RequestContent.Create(new { contents = "Hello world 1" }), waitForCompletion: true); PostLedgerEntryOperation subLedgerPostOperation = ledgerClient.PostLedgerEntry( RequestContent.Create(new { contents = "Hello world sub-ledger 0" }), "my sub-ledger", waitForCompletion: true); ledgerClient.PostLedgerEntry( RequestContent.Create(new { contents = "Hello world sub-ledger 1" }), "my sub-ledger", waitForCompletion: true); #if SNIPPET string transactionId = firstPostOperation.Id; #else transactionId = firstPostOperation.Id; #endif // Wait for the entry to be committed status = "Pending"; while (status == "Pending") { statusResponse = ledgerClient.GetTransactionStatus(transactionId); status = JsonDocument.Parse(statusResponse.Content) .RootElement .GetProperty("state") .GetString(); } // The ledger entry written at the transactionId in firstResponse is retrieved from the default sub-ledger. Response getResponse = ledgerClient.GetLedgerEntry(transactionId); // Try until the entry is available. loaded = false; element = default; contents = null; while (!loaded) { loaded = JsonDocument.Parse(getResponse.Content) .RootElement .TryGetProperty("entry", out element); if (loaded) { contents = element.GetProperty("contents").GetString(); } else { getResponse = ledgerClient.GetLedgerEntry(transactionId, subLedgerId); } } string firstEntryContents = JsonDocument.Parse(getResponse.Content) .RootElement .GetProperty("entry") .GetProperty("contents") .GetString(); Console.WriteLine(firstEntryContents); // "Hello world 0" // This will return the latest entry available in the default sub-ledger. getResponse = ledgerClient.GetCurrentLedgerEntry(); // Try until the entry is available. loaded = false; element = default; string latestDefaultSubLedger = null; while (!loaded) { loaded = JsonDocument.Parse(getResponse.Content) .RootElement .TryGetProperty("contents", out element); if (loaded) { latestDefaultSubLedger = element.GetString(); } else { getResponse = ledgerClient.GetCurrentLedgerEntry(); } } Console.WriteLine($"The latest ledger entry from the default sub-ledger is {latestDefaultSubLedger}"); //"Hello world 1" // The ledger entry written at subLedgerTransactionId is retrieved from the sub-ledger 'sub-ledger'. string subLedgerTransactionId = subLedgerPostOperation.Id; getResponse = ledgerClient.GetLedgerEntry(subLedgerTransactionId, "my sub-ledger"); // Try until the entry is available. loaded = false; element = default; string subLedgerEntry = null; while (!loaded) { loaded = JsonDocument.Parse(getResponse.Content) .RootElement .TryGetProperty("entry", out element); if (loaded) { subLedgerEntry = element.GetProperty("contents").GetString(); } else { getResponse = ledgerClient.GetLedgerEntry(subLedgerTransactionId, "my sub-ledger"); } } Console.WriteLine(subLedgerEntry); // "Hello world sub-ledger 0" // This will return the latest entry available in the sub-ledger. getResponse = ledgerClient.GetCurrentLedgerEntry("my sub-ledger"); string latestSubLedger = JsonDocument.Parse(getResponse.Content) .RootElement .GetProperty("contents") .GetString(); Console.WriteLine($"The latest ledger entry from the sub-ledger is {latestSubLedger}"); // "Hello world sub-ledger 1" #endregion #region Snippet:RangedQuery ledgerClient.GetLedgerEntries(fromTransactionId: "2.1", toTransactionId: subLedgerTransactionId); #endregion #region Snippet:NewUser #if SNIPPET string newUserAadObjectId = "<some AAD user or service princpal object Id>"; #else string newUserAadObjectId = Guid.NewGuid().ToString(); #endif ledgerClient.CreateOrUpdateUser( newUserAadObjectId, RequestContent.Create(new { assignedRole = "Reader" })); #endregion #region Snippet:Consortium Response consortiumResponse = ledgerClient.GetConsortiumMembers(); string membersJson = new StreamReader(consortiumResponse.ContentStream).ReadToEnd(); // Consortium members can manage and alter the Confidential Ledger, such as by replacing unhealthy nodes. Console.WriteLine(membersJson); // The constitution is a collection of JavaScript code that defines actions available to members, // and vets proposals by members to execute those actions. Response constitutionResponse = ledgerClient.GetConstitution(); string constitutionJson = new StreamReader(constitutionResponse.ContentStream).ReadToEnd(); Console.WriteLine(constitutionJson); // Enclave quotes contain material that can be used to cryptographically verify the validity and contents of an enclave. Response enclavesResponse = ledgerClient.GetEnclaveQuotes(); string enclavesJson = new StreamReader(enclavesResponse.ContentStream).ReadToEnd(); Console.WriteLine(enclavesJson); #endregion } } }
using System; namespace Raksha.Asn1.Pkcs { public abstract class PkcsObjectIdentifiers { // // pkcs-1 OBJECT IDENTIFIER ::= { // iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1) 1 } // public const string Pkcs1 = "1.2.840.113549.1.1"; public static readonly DerObjectIdentifier RsaEncryption = new DerObjectIdentifier(Pkcs1 + ".1"); public static readonly DerObjectIdentifier MD2WithRsaEncryption = new DerObjectIdentifier(Pkcs1 + ".2"); public static readonly DerObjectIdentifier MD4WithRsaEncryption = new DerObjectIdentifier(Pkcs1 + ".3"); public static readonly DerObjectIdentifier MD5WithRsaEncryption = new DerObjectIdentifier(Pkcs1 + ".4"); public static readonly DerObjectIdentifier Sha1WithRsaEncryption = new DerObjectIdentifier(Pkcs1 + ".5"); public static readonly DerObjectIdentifier SrsaOaepEncryptionSet = new DerObjectIdentifier(Pkcs1 + ".6"); public static readonly DerObjectIdentifier IdRsaesOaep = new DerObjectIdentifier(Pkcs1 + ".7"); public static readonly DerObjectIdentifier IdMgf1 = new DerObjectIdentifier(Pkcs1 + ".8"); public static readonly DerObjectIdentifier IdPSpecified = new DerObjectIdentifier(Pkcs1 + ".9"); public static readonly DerObjectIdentifier IdRsassaPss = new DerObjectIdentifier(Pkcs1 + ".10"); public static readonly DerObjectIdentifier Sha256WithRsaEncryption = new DerObjectIdentifier(Pkcs1 + ".11"); public static readonly DerObjectIdentifier Sha384WithRsaEncryption = new DerObjectIdentifier(Pkcs1 + ".12"); public static readonly DerObjectIdentifier Sha512WithRsaEncryption = new DerObjectIdentifier(Pkcs1 + ".13"); public static readonly DerObjectIdentifier Sha224WithRsaEncryption = new DerObjectIdentifier(Pkcs1 + ".14"); // // pkcs-3 OBJECT IDENTIFIER ::= { // iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1) 3 } // public const string Pkcs3 = "1.2.840.113549.1.3"; public static readonly DerObjectIdentifier DhKeyAgreement = new DerObjectIdentifier(Pkcs3 + ".1"); // // pkcs-5 OBJECT IDENTIFIER ::= { // iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1) 5 } // public const string Pkcs5 = "1.2.840.113549.1.5"; public static readonly DerObjectIdentifier PbeWithMD2AndDesCbc = new DerObjectIdentifier(Pkcs5 + ".1"); public static readonly DerObjectIdentifier PbeWithMD2AndRC2Cbc = new DerObjectIdentifier(Pkcs5 + ".4"); public static readonly DerObjectIdentifier PbeWithMD5AndDesCbc = new DerObjectIdentifier(Pkcs5 + ".3"); public static readonly DerObjectIdentifier PbeWithMD5AndRC2Cbc = new DerObjectIdentifier(Pkcs5 + ".6"); public static readonly DerObjectIdentifier PbeWithSha1AndDesCbc = new DerObjectIdentifier(Pkcs5 + ".10"); public static readonly DerObjectIdentifier PbeWithSha1AndRC2Cbc = new DerObjectIdentifier(Pkcs5 + ".11"); public static readonly DerObjectIdentifier IdPbeS2 = new DerObjectIdentifier(Pkcs5 + ".13"); public static readonly DerObjectIdentifier IdPbkdf2 = new DerObjectIdentifier(Pkcs5 + ".12"); // // encryptionAlgorithm OBJECT IDENTIFIER ::= { // iso(1) member-body(2) us(840) rsadsi(113549) 3 } // public const string EncryptionAlgorithm = "1.2.840.113549.3"; public static readonly DerObjectIdentifier DesEde3Cbc = new DerObjectIdentifier(EncryptionAlgorithm + ".7"); public static readonly DerObjectIdentifier RC2Cbc = new DerObjectIdentifier(EncryptionAlgorithm + ".2"); // // object identifiers for digests // public const string DigestAlgorithm = "1.2.840.113549.2"; // // md2 OBJECT IDENTIFIER ::= // {iso(1) member-body(2) US(840) rsadsi(113549) DigestAlgorithm(2) 2} // public static readonly DerObjectIdentifier MD2 = new DerObjectIdentifier(DigestAlgorithm + ".2"); // // md4 OBJECT IDENTIFIER ::= // {iso(1) member-body(2) US(840) rsadsi(113549) DigestAlgorithm(2) 4} // public static readonly DerObjectIdentifier MD4 = new DerObjectIdentifier(DigestAlgorithm + ".4"); // // md5 OBJECT IDENTIFIER ::= // {iso(1) member-body(2) US(840) rsadsi(113549) DigestAlgorithm(2) 5} // public static readonly DerObjectIdentifier MD5 = new DerObjectIdentifier(DigestAlgorithm + ".5"); public static readonly DerObjectIdentifier IdHmacWithSha1 = new DerObjectIdentifier(DigestAlgorithm + ".7"); public static readonly DerObjectIdentifier IdHmacWithSha224 = new DerObjectIdentifier(DigestAlgorithm + ".8"); public static readonly DerObjectIdentifier IdHmacWithSha256 = new DerObjectIdentifier(DigestAlgorithm + ".9"); public static readonly DerObjectIdentifier IdHmacWithSha384 = new DerObjectIdentifier(DigestAlgorithm + ".10"); public static readonly DerObjectIdentifier IdHmacWithSha512 = new DerObjectIdentifier(DigestAlgorithm + ".11"); // // pkcs-7 OBJECT IDENTIFIER ::= { // iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1) 7 } // public const string Pkcs7 = "1.2.840.113549.1.7"; public static readonly DerObjectIdentifier Data = new DerObjectIdentifier(Pkcs7 + ".1"); public static readonly DerObjectIdentifier SignedData = new DerObjectIdentifier(Pkcs7 + ".2"); public static readonly DerObjectIdentifier EnvelopedData = new DerObjectIdentifier(Pkcs7 + ".3"); public static readonly DerObjectIdentifier SignedAndEnvelopedData = new DerObjectIdentifier(Pkcs7 + ".4"); public static readonly DerObjectIdentifier DigestedData = new DerObjectIdentifier(Pkcs7 + ".5"); public static readonly DerObjectIdentifier EncryptedData = new DerObjectIdentifier(Pkcs7 + ".6"); // // pkcs-9 OBJECT IDENTIFIER ::= { // iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1) 9 } // public const string Pkcs9 = "1.2.840.113549.1.9"; public static readonly DerObjectIdentifier Pkcs9AtEmailAddress = new DerObjectIdentifier(Pkcs9 + ".1"); public static readonly DerObjectIdentifier Pkcs9AtUnstructuredName = new DerObjectIdentifier(Pkcs9 + ".2"); public static readonly DerObjectIdentifier Pkcs9AtContentType = new DerObjectIdentifier(Pkcs9 + ".3"); public static readonly DerObjectIdentifier Pkcs9AtMessageDigest = new DerObjectIdentifier(Pkcs9 + ".4"); public static readonly DerObjectIdentifier Pkcs9AtSigningTime = new DerObjectIdentifier(Pkcs9 + ".5"); public static readonly DerObjectIdentifier Pkcs9AtCounterSignature = new DerObjectIdentifier(Pkcs9 + ".6"); public static readonly DerObjectIdentifier Pkcs9AtChallengePassword = new DerObjectIdentifier(Pkcs9 + ".7"); public static readonly DerObjectIdentifier Pkcs9AtUnstructuredAddress = new DerObjectIdentifier(Pkcs9 + ".8"); public static readonly DerObjectIdentifier Pkcs9AtExtendedCertificateAttributes = new DerObjectIdentifier(Pkcs9 + ".9"); public static readonly DerObjectIdentifier Pkcs9AtSigningDescription = new DerObjectIdentifier(Pkcs9 + ".13"); public static readonly DerObjectIdentifier Pkcs9AtExtensionRequest = new DerObjectIdentifier(Pkcs9 + ".14"); public static readonly DerObjectIdentifier Pkcs9AtSmimeCapabilities = new DerObjectIdentifier(Pkcs9 + ".15"); public static readonly DerObjectIdentifier Pkcs9AtFriendlyName = new DerObjectIdentifier(Pkcs9 + ".20"); public static readonly DerObjectIdentifier Pkcs9AtLocalKeyID = new DerObjectIdentifier(Pkcs9 + ".21"); [Obsolete("Use X509Certificate instead")] public static readonly DerObjectIdentifier X509CertType = new DerObjectIdentifier(Pkcs9 + ".22.1"); public const string CertTypes = Pkcs9 + ".22"; public static readonly DerObjectIdentifier X509Certificate = new DerObjectIdentifier(CertTypes + ".1"); public static readonly DerObjectIdentifier SdsiCertificate = new DerObjectIdentifier(CertTypes + ".2"); public const string CrlTypes = Pkcs9 + ".23"; public static readonly DerObjectIdentifier X509Crl = new DerObjectIdentifier(CrlTypes + ".1"); public static readonly DerObjectIdentifier IdAlgPwriKek = new DerObjectIdentifier(Pkcs9 + ".16.3.9"); // // SMIME capability sub oids. // public static readonly DerObjectIdentifier PreferSignedData = new DerObjectIdentifier(Pkcs9 + ".15.1"); public static readonly DerObjectIdentifier CannotDecryptAny = new DerObjectIdentifier(Pkcs9 + ".15.2"); public static readonly DerObjectIdentifier SmimeCapabilitiesVersions = new DerObjectIdentifier(Pkcs9 + ".15.3"); // // other SMIME attributes // public static readonly DerObjectIdentifier IdAAReceiptRequest = new DerObjectIdentifier(Pkcs9 + ".16.2.1"); // // id-ct OBJECT IDENTIFIER ::= {iso(1) member-body(2) usa(840) // rsadsi(113549) pkcs(1) pkcs-9(9) smime(16) ct(1)} // public const string IdCT = "1.2.840.113549.1.9.16.1"; public static readonly DerObjectIdentifier IdCTAuthData = new DerObjectIdentifier(IdCT + ".2"); public static readonly DerObjectIdentifier IdCTTstInfo = new DerObjectIdentifier(IdCT + ".4"); public static readonly DerObjectIdentifier IdCTCompressedData = new DerObjectIdentifier(IdCT + ".9"); public static readonly DerObjectIdentifier IdCTAuthEnvelopedData = new DerObjectIdentifier(IdCT + ".23"); public static readonly DerObjectIdentifier IdCTTimestampedData = new DerObjectIdentifier(IdCT + ".31"); // // id-cti OBJECT IDENTIFIER ::= {iso(1) member-body(2) usa(840) // rsadsi(113549) pkcs(1) pkcs-9(9) smime(16) cti(6)} // public const string IdCti = "1.2.840.113549.1.9.16.6"; public static readonly DerObjectIdentifier IdCtiEtsProofOfOrigin = new DerObjectIdentifier(IdCti + ".1"); public static readonly DerObjectIdentifier IdCtiEtsProofOfReceipt = new DerObjectIdentifier(IdCti + ".2"); public static readonly DerObjectIdentifier IdCtiEtsProofOfDelivery = new DerObjectIdentifier(IdCti + ".3"); public static readonly DerObjectIdentifier IdCtiEtsProofOfSender = new DerObjectIdentifier(IdCti + ".4"); public static readonly DerObjectIdentifier IdCtiEtsProofOfApproval = new DerObjectIdentifier(IdCti + ".5"); public static readonly DerObjectIdentifier IdCtiEtsProofOfCreation = new DerObjectIdentifier(IdCti + ".6"); // // id-aa OBJECT IDENTIFIER ::= {iso(1) member-body(2) usa(840) // rsadsi(113549) pkcs(1) pkcs-9(9) smime(16) attributes(2)} // public const string IdAA = "1.2.840.113549.1.9.16.2"; public static readonly DerObjectIdentifier IdAAContentHint = new DerObjectIdentifier(IdAA + ".4"); // See RFC 2634 public static readonly DerObjectIdentifier IdAAMsgSigDigest = new DerObjectIdentifier(IdAA + ".5"); public static readonly DerObjectIdentifier IdAAContentReference = new DerObjectIdentifier(IdAA + ".10"); /* * id-aa-encrypKeyPref OBJECT IDENTIFIER ::= {id-aa 11} * */ public static readonly DerObjectIdentifier IdAAEncrypKeyPref = new DerObjectIdentifier(IdAA + ".11"); public static readonly DerObjectIdentifier IdAASigningCertificate = new DerObjectIdentifier(IdAA + ".12"); public static readonly DerObjectIdentifier IdAASigningCertificateV2 = new DerObjectIdentifier(IdAA + ".47"); public static readonly DerObjectIdentifier IdAAContentIdentifier = new DerObjectIdentifier(IdAA + ".7"); // See RFC 2634 /* * RFC 3126 */ public static readonly DerObjectIdentifier IdAASignatureTimeStampToken = new DerObjectIdentifier(IdAA + ".14"); public static readonly DerObjectIdentifier IdAAEtsSigPolicyID = new DerObjectIdentifier(IdAA + ".15"); public static readonly DerObjectIdentifier IdAAEtsCommitmentType = new DerObjectIdentifier(IdAA + ".16"); public static readonly DerObjectIdentifier IdAAEtsSignerLocation = new DerObjectIdentifier(IdAA + ".17"); public static readonly DerObjectIdentifier IdAAEtsSignerAttr = new DerObjectIdentifier(IdAA + ".18"); public static readonly DerObjectIdentifier IdAAEtsOtherSigCert = new DerObjectIdentifier(IdAA + ".19"); public static readonly DerObjectIdentifier IdAAEtsContentTimestamp = new DerObjectIdentifier(IdAA + ".20"); public static readonly DerObjectIdentifier IdAAEtsCertificateRefs = new DerObjectIdentifier(IdAA + ".21"); public static readonly DerObjectIdentifier IdAAEtsRevocationRefs = new DerObjectIdentifier(IdAA + ".22"); public static readonly DerObjectIdentifier IdAAEtsCertValues = new DerObjectIdentifier(IdAA + ".23"); public static readonly DerObjectIdentifier IdAAEtsRevocationValues = new DerObjectIdentifier(IdAA + ".24"); public static readonly DerObjectIdentifier IdAAEtsEscTimeStamp = new DerObjectIdentifier(IdAA + ".25"); public static readonly DerObjectIdentifier IdAAEtsCertCrlTimestamp = new DerObjectIdentifier(IdAA + ".26"); public static readonly DerObjectIdentifier IdAAEtsArchiveTimestamp = new DerObjectIdentifier(IdAA + ".27"); [Obsolete("Use 'IdAAEtsSigPolicyID' instead")] public static readonly DerObjectIdentifier IdAASigPolicyID = IdAAEtsSigPolicyID; [Obsolete("Use 'IdAAEtsCommitmentType' instead")] public static readonly DerObjectIdentifier IdAACommitmentType = IdAAEtsCommitmentType; [Obsolete("Use 'IdAAEtsSignerLocation' instead")] public static readonly DerObjectIdentifier IdAASignerLocation = IdAAEtsSignerLocation; [Obsolete("Use 'IdAAEtsOtherSigCert' instead")] public static readonly DerObjectIdentifier IdAAOtherSigCert = IdAAEtsOtherSigCert; // // id-spq OBJECT IDENTIFIER ::= {iso(1) member-body(2) usa(840) // rsadsi(113549) pkcs(1) pkcs-9(9) smime(16) id-spq(5)} // public const string IdSpq = "1.2.840.113549.1.9.16.5"; public static readonly DerObjectIdentifier IdSpqEtsUri = new DerObjectIdentifier(IdSpq + ".1"); public static readonly DerObjectIdentifier IdSpqEtsUNotice = new DerObjectIdentifier(IdSpq + ".2"); // // pkcs-12 OBJECT IDENTIFIER ::= { // iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1) 12 } // public const string Pkcs12 = "1.2.840.113549.1.12"; public const string BagTypes = Pkcs12 + ".10.1"; public static readonly DerObjectIdentifier KeyBag = new DerObjectIdentifier(BagTypes + ".1"); public static readonly DerObjectIdentifier Pkcs8ShroudedKeyBag = new DerObjectIdentifier(BagTypes + ".2"); public static readonly DerObjectIdentifier CertBag = new DerObjectIdentifier(BagTypes + ".3"); public static readonly DerObjectIdentifier CrlBag = new DerObjectIdentifier(BagTypes + ".4"); public static readonly DerObjectIdentifier SecretBag = new DerObjectIdentifier(BagTypes + ".5"); public static readonly DerObjectIdentifier SafeContentsBag = new DerObjectIdentifier(BagTypes + ".6"); public const string Pkcs12PbeIds = Pkcs12 + ".1"; public static readonly DerObjectIdentifier PbeWithShaAnd128BitRC4 = new DerObjectIdentifier(Pkcs12PbeIds + ".1"); public static readonly DerObjectIdentifier PbeWithShaAnd40BitRC4 = new DerObjectIdentifier(Pkcs12PbeIds + ".2"); public static readonly DerObjectIdentifier PbeWithShaAnd3KeyTripleDesCbc = new DerObjectIdentifier(Pkcs12PbeIds + ".3"); public static readonly DerObjectIdentifier PbeWithShaAnd2KeyTripleDesCbc = new DerObjectIdentifier(Pkcs12PbeIds + ".4"); public static readonly DerObjectIdentifier PbeWithShaAnd128BitRC2Cbc = new DerObjectIdentifier(Pkcs12PbeIds + ".5"); public static readonly DerObjectIdentifier PbewithShaAnd40BitRC2Cbc = new DerObjectIdentifier(Pkcs12PbeIds + ".6"); public static readonly DerObjectIdentifier IdAlgCms3DesWrap = new DerObjectIdentifier("1.2.840.113549.1.9.16.3.6"); public static readonly DerObjectIdentifier IdAlgCmsRC2Wrap = new DerObjectIdentifier("1.2.840.113549.1.9.16.3.7"); } }
// 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. // The Regex class represents a single compiled instance of a regular // expression. using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Reflection; using System.Reflection.Emit; using System.Runtime.Serialization; using System.Threading; namespace Flatbox.RegularExpressions { /// <summary> /// Represents an immutable, compiled regular expression. Also /// contains static methods that allow use of regular expressions without instantiating /// a Regex explicitly. /// </summary> public class Regex : ISerializable { protected internal string pattern; // The string pattern provided protected internal RegexOptions roptions; // the top-level options from the options string // *********** Match timeout fields { *********** // We need this because time is queried using Environment.TickCount for performance reasons // (Environment.TickCount returns milliseconds as an int and cycles): private static readonly TimeSpan MaximumMatchTimeout = TimeSpan.FromMilliseconds(int.MaxValue - 1); // InfiniteMatchTimeout specifies that match timeout is switched OFF. It allows for faster code paths // compared to simply having a very large timeout. // We do not want to ask users to use System.Threading.Timeout.InfiniteTimeSpan as a parameter because: // (1) We do not want to imply any relation between having using a RegEx timeout and using multi-threading. // (2) We do not want to require users to take ref to a contract assembly for threading just to use RegEx. // There may in theory be a SKU that has RegEx, but no multithreading. // We create a public Regex.InfiniteMatchTimeout constant, which for consistency uses the save underlying // value as Timeout.InfiniteTimeSpan creating an implementation detail dependency only. public static readonly TimeSpan InfiniteMatchTimeout = Timeout.InfiniteTimeSpan; protected internal TimeSpan internalMatchTimeout; // timeout for the execution of this regex // DefaultMatchTimeout specifies the match timeout to use if no other timeout was specified // by one means or another. Typically, it is set to InfiniteMatchTimeout. internal static readonly TimeSpan DefaultMatchTimeout = InfiniteMatchTimeout; // *********** } match timeout fields *********** protected internal RegexRunnerFactory factory; protected internal Hashtable caps; // if captures are sparse, this is the hashtable capnum->index protected internal Hashtable capnames; // if named captures are used, this maps names->index protected internal string[] capslist; // if captures are sparse or named captures are used, this is the sorted list of names protected internal int capsize; // the size of the capture array protected IDictionary Caps { get { return caps; } set { if (value == null) throw new ArgumentNullException(nameof(value)); caps = value as Hashtable; if (caps == null) { caps = new Hashtable(value); } } } protected IDictionary CapNames { get { return capnames; } set { if (value == null) throw new ArgumentNullException(nameof(value)); capnames = value as Hashtable; if (capnames == null) { capnames = new Hashtable(value); } } } internal ExclusiveReference _runnerref; // cached runner internal SharedReference _replref; // cached parsed replacement pattern internal RegexCode _code; // if interpreted, this is the code for RegexInterpreter internal bool _refsInitialized = false; internal static LinkedList<CachedCodeEntry> s_livecode = new LinkedList<CachedCodeEntry>();// the cache of code and factories that are currently loaded internal static int s_cacheSize = 15; internal const int MaxOptionShift = 10; protected Regex() { internalMatchTimeout = DefaultMatchTimeout; } /// <summary> /// Creates and compiles a regular expression object for the specified regular /// expression. /// </summary> public Regex(string pattern) : this(pattern, RegexOptions.None, DefaultMatchTimeout, false) { } /// <summary> /// Creates and compiles a regular expression object for the /// specified regular expression with options that modify the pattern. /// </summary> public Regex(string pattern, RegexOptions options) : this(pattern, options, DefaultMatchTimeout, false) { } public Regex(string pattern, RegexOptions options, TimeSpan matchTimeout) : this(pattern, options, matchTimeout, false) { } protected Regex(SerializationInfo info, StreamingContext context) : this(info.GetString("pattern"), (RegexOptions)info.GetInt32("options")) { throw new PlatformNotSupportedException(); } void ISerializable.GetObjectData(SerializationInfo si, StreamingContext context) { throw new PlatformNotSupportedException(); } private Regex(string pattern, RegexOptions options, TimeSpan matchTimeout, bool useCache) { RegexTree tree; CachedCodeEntry cached = null; string cultureKey = null; if (pattern == null) throw new ArgumentNullException(nameof(pattern)); if (options < RegexOptions.None || (((int)options) >> MaxOptionShift) != 0) throw new ArgumentOutOfRangeException(nameof(options)); if ((options & RegexOptions.ECMAScript) != 0 && (options & ~(RegexOptions.ECMAScript | RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.Compiled | RegexOptions.CultureInvariant #if DEBUG | RegexOptions.Debug #endif )) != 0) throw new ArgumentOutOfRangeException(nameof(options)); ValidateMatchTimeout(matchTimeout); // Try to look up this regex in the cache. We do this regardless of whether useCache is true since there's // really no reason not to. if ((options & RegexOptions.CultureInvariant) != 0) cultureKey = CultureInfo.InvariantCulture.ToString(); // "English (United States)" else cultureKey = CultureInfo.CurrentCulture.ToString(); var key = new CachedCodeEntryKey(options, cultureKey, pattern); cached = LookupCachedAndUpdate(key); this.pattern = pattern; roptions = options; internalMatchTimeout = matchTimeout; if (cached == null) { // Parse the input tree = RegexParser.Parse(pattern, roptions); // Extract the relevant information capnames = tree._capnames; capslist = tree._capslist; _code = RegexWriter.Write(tree); caps = _code._caps; capsize = _code._capsize; InitializeReferences(); tree = null; if (useCache) cached = CacheCode(key); } else { caps = cached._caps; capnames = cached._capnames; capslist = cached._capslist; capsize = cached._capsize; _code = cached._code; _runnerref = cached._runnerref; _replref = cached._replref; _refsInitialized = true; } // if the compile option is set, then compile the code if it's not already if (UseOptionC() && factory == null) { factory = RegexCompiler.Compile(_code, roptions); if (useCache && cached != null) cached.AddCompiled(factory); _code = null; } } // Note: "&lt;" is the XML entity for smaller ("<"). /// <summary> /// Validates that the specified match timeout value is valid. /// The valid range is <code>TimeSpan.Zero &lt; matchTimeout &lt;= Regex.MaximumMatchTimeout</code>. /// </summary> /// <param name="matchTimeout">The timeout value to validate.</param> /// <exception cref="ArgumentOutOfRangeException">If the specified timeout is not within a valid range. /// </exception> protected internal static void ValidateMatchTimeout(TimeSpan matchTimeout) { if (InfiniteMatchTimeout == matchTimeout) return; // Change this to make sure timeout is not longer then Environment.Ticks cycle length: if (TimeSpan.Zero < matchTimeout && matchTimeout <= MaximumMatchTimeout) return; throw new ArgumentOutOfRangeException(nameof(matchTimeout)); } /// <summary> /// Escapes a minimal set of metacharacters (\, *, +, ?, |, {, [, (, ), ^, $, ., #, and /// whitespace) by replacing them with their \ codes. This converts a string so that /// it can be used as a constant within a regular expression safely. (Note that the /// reason # and whitespace must be escaped is so the string can be used safely /// within an expression parsed with x mode. If future Regex features add /// additional metacharacters, developers should depend on Escape to escape those /// characters as well.) /// </summary> public static string Escape(string str) { if (str == null) throw new ArgumentNullException(nameof(str)); return RegexParser.Escape(str); } /// <summary> /// Unescapes any escaped characters in the input string. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Unescape", Justification = "Already shipped since v1 - can't fix without causing a breaking change")] public static string Unescape(string str) { if (str == null) throw new ArgumentNullException(nameof(str)); return RegexParser.Unescape(str); } [SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "Reviewed for thread-safety")] public static int CacheSize { get { return s_cacheSize; } set { if (value < 0) throw new ArgumentOutOfRangeException(nameof(value)); s_cacheSize = value; if (s_livecode.Count > s_cacheSize) { lock (s_livecode) { while (s_livecode.Count > s_cacheSize) s_livecode.RemoveLast(); } } } } /// <summary> /// Returns the options passed into the constructor /// </summary> public RegexOptions Options { get { return roptions; } } /// <summary> /// The match timeout used by this Regex instance. /// </summary> public TimeSpan MatchTimeout { get { return internalMatchTimeout; } } /// <summary> /// Indicates whether the regular expression matches from right to left. /// </summary> public bool RightToLeft { get { return UseOptionR(); } } /// <summary> /// Returns the regular expression pattern passed into the constructor /// </summary> public override string ToString() { return pattern; } /* * Returns an array of the group names that are used to capture groups * in the regular expression. Only needed if the regex is not known until * runtime, and one wants to extract captured groups. (Probably unusual, * but supplied for completeness.) */ /// <summary> /// Returns the GroupNameCollection for the regular expression. This collection contains the /// set of strings used to name capturing groups in the expression. /// </summary> public string[] GetGroupNames() { string[] result; if (capslist == null) { int max = capsize; result = new string[max]; for (int i = 0; i < max; i++) { result[i] = Convert.ToString(i, CultureInfo.InvariantCulture); } } else { result = new string[capslist.Length]; Array.Copy(capslist, 0, result, 0, capslist.Length); } return result; } /* * Returns an array of the group numbers that are used to capture groups * in the regular expression. Only needed if the regex is not known until * runtime, and one wants to extract captured groups. (Probably unusual, * but supplied for completeness.) */ /// <summary> /// Returns the integer group number corresponding to a group name. /// </summary> public int[] GetGroupNumbers() { int[] result; if (caps == null) { int max = capsize; result = new int[max]; for (int i = 0; i < result.Length; i++) { result[i] = i; } } else { result = new int[caps.Count]; // Manual use of IDictionaryEnumerator instead of foreach to avoid DictionaryEntry box allocations. IDictionaryEnumerator de = caps.GetEnumerator(); while (de.MoveNext()) { result[(int)de.Value] = (int)de.Key; } } return result; } /* * Given a group number, maps it to a group name. Note that numbered * groups automatically get a group name that is the decimal string * equivalent of its number. * * Returns null if the number is not a recognized group number. */ /// <summary> /// Retrieves a group name that corresponds to a group number. /// </summary> public string GroupNameFromNumber(int i) { if (capslist == null) { if (i >= 0 && i < capsize) return i.ToString(CultureInfo.InvariantCulture); return string.Empty; } else { if (caps != null) { if (!caps.TryGetValue(i, out i)) return string.Empty; } if (i >= 0 && i < capslist.Length) return capslist[i]; return string.Empty; } } /* * Given a group name, maps it to a group number. Note that numbered * groups automatically get a group name that is the decimal string * equivalent of its number. * * Returns -1 if the name is not a recognized group name. */ /// <summary> /// Returns a group number that corresponds to a group name. /// </summary> public int GroupNumberFromName(string name) { int result = -1; if (name == null) throw new ArgumentNullException(nameof(name)); // look up name if we have a hashtable of names if (capnames != null) { if (!capnames.TryGetValue(name, out result)) return -1; return result; } // convert to an int if it looks like a number result = 0; for (int i = 0; i < name.Length; i++) { char ch = name[i]; if (ch > '9' || ch < '0') return -1; result *= 10; result += (ch - '0'); } // return int if it's in range if (result >= 0 && result < capsize) return result; return -1; } /* * Static version of simple IsMatch call */ /// <summary> /// Searches the input string for one or more occurrences of the text supplied in the given pattern. /// </summary> public static bool IsMatch(string input, string pattern) { return IsMatch(input, pattern, RegexOptions.None, DefaultMatchTimeout); } /* * Static version of simple IsMatch call */ /// <summary> /// Searches the input string for one or more occurrences of the text /// supplied in the pattern parameter with matching options supplied in the options /// parameter. /// </summary> public static bool IsMatch(string input, string pattern, RegexOptions options) { return IsMatch(input, pattern, options, DefaultMatchTimeout); } public static bool IsMatch(string input, string pattern, RegexOptions options, TimeSpan matchTimeout) { return new Regex(pattern, options, matchTimeout, true).IsMatch(input); } /* * Returns true if the regex finds a match within the specified string */ /// <summary> /// Searches the input string for one or more matches using the previous pattern, /// options, and starting position. /// </summary> public bool IsMatch(string input) { if (input == null) throw new ArgumentNullException(nameof(input)); return IsMatch(input, UseOptionR() ? input.Length : 0); } /* * Returns true if the regex finds a match after the specified position * (proceeding leftward if the regex is leftward and rightward otherwise) */ /// <summary> /// Searches the input string for one or more matches using the previous pattern and options, /// with a new starting position. /// </summary> public bool IsMatch(string input, int startat) { if (input == null) throw new ArgumentNullException(nameof(input)); return (null == Run(true, -1, input, 0, input.Length, startat)); } /* * Static version of simple Match call */ /// <summary> /// Searches the input string for one or more occurrences of the text /// supplied in the pattern parameter. /// </summary> public static Match Match(string input, string pattern) { return Match(input, pattern, RegexOptions.None, DefaultMatchTimeout); } /* * Static version of simple Match call */ /// <summary> /// Searches the input string for one or more occurrences of the text /// supplied in the pattern parameter. Matching is modified with an option /// string. /// </summary> public static Match Match(string input, string pattern, RegexOptions options) { return Match(input, pattern, options, DefaultMatchTimeout); } public static Match Match(string input, string pattern, RegexOptions options, TimeSpan matchTimeout) { return new Regex(pattern, options, matchTimeout, true).Match(input); } /* * Finds the first match for the regular expression starting at the beginning * of the string (or at the end of the string if the regex is leftward) */ /// <summary> /// Matches a regular expression with a string and returns /// the precise result as a RegexMatch object. /// </summary> public Match Match(string input) { if (input == null) throw new ArgumentNullException(nameof(input)); return Match(input, UseOptionR() ? input.Length : 0); } /* * Finds the first match, starting at the specified position */ /// <summary> /// Matches a regular expression with a string and returns /// the precise result as a RegexMatch object. /// </summary> public Match Match(string input, int startat) { if (input == null) throw new ArgumentNullException(nameof(input)); return Run(false, -1, input, 0, input.Length, startat); } /* * Finds the first match, restricting the search to the specified interval of * the char array. */ /// <summary> /// Matches a regular expression with a string and returns the precise result as a /// RegexMatch object. /// </summary> public Match Match(string input, int beginning, int length) { if (input == null) throw new ArgumentNullException(nameof(input)); return Run(false, -1, input, beginning, length, UseOptionR() ? beginning + length : beginning); } /* * Static version of simple Matches call */ /// <summary> /// Returns all the successful matches as if Match were called iteratively numerous times. /// </summary> public static MatchCollection Matches(string input, string pattern) { return Matches(input, pattern, RegexOptions.None, DefaultMatchTimeout); } /* * Static version of simple Matches call */ /// <summary> /// Returns all the successful matches as if Match were called iteratively numerous times. /// </summary> public static MatchCollection Matches(string input, string pattern, RegexOptions options) { return Matches(input, pattern, options, DefaultMatchTimeout); } public static MatchCollection Matches(string input, string pattern, RegexOptions options, TimeSpan matchTimeout) { return new Regex(pattern, options, matchTimeout, true).Matches(input); } /* * Finds the first match for the regular expression starting at the beginning * of the string Enumerator(or at the end of the string if the regex is leftward) */ /// <summary> /// Returns all the successful matches as if Match was called iteratively numerous times. /// </summary> public MatchCollection Matches(string input) { if (input == null) throw new ArgumentNullException(nameof(input)); return Matches(input, UseOptionR() ? input.Length : 0); } /* * Finds the first match, starting at the specified position */ /// <summary> /// Returns all the successful matches as if Match was called iteratively numerous times. /// </summary> public MatchCollection Matches(string input, int startat) { if (input == null) throw new ArgumentNullException(nameof(input)); return new MatchCollection(this, input, 0, input.Length, startat); } /// <summary> /// Replaces all occurrences of the pattern with the <paramref name="replacement"/> pattern, starting at /// the first character in the input string. /// </summary> public static string Replace(string input, string pattern, string replacement) { return Replace(input, pattern, replacement, RegexOptions.None, DefaultMatchTimeout); } /// <summary> /// Replaces all occurrences of /// the <paramref name="pattern "/>with the <paramref name="replacement "/> /// pattern, starting at the first character in the input string. /// </summary> public static string Replace(string input, string pattern, string replacement, RegexOptions options) { return Replace(input, pattern, replacement, options, DefaultMatchTimeout); } public static string Replace(string input, string pattern, string replacement, RegexOptions options, TimeSpan matchTimeout) { return new Regex(pattern, options, matchTimeout, true).Replace(input, replacement); } /// <summary> /// Replaces all occurrences of the previously defined pattern with the /// <paramref name="replacement"/> pattern, starting at the first character in the /// input string. /// </summary> public string Replace(string input, string replacement) { if (input == null) throw new ArgumentNullException(nameof(input)); return Replace(input, replacement, -1, UseOptionR() ? input.Length : 0); } /// <summary> /// Replaces all occurrences of the previously defined pattern with the /// <paramref name="replacement"/> pattern, starting at the first character in the /// input string. /// </summary> public string Replace(string input, string replacement, int count) { if (input == null) throw new ArgumentNullException(nameof(input)); return Replace(input, replacement, count, UseOptionR() ? input.Length : 0); } /// <summary> /// Replaces all occurrences of the previously defined pattern with the /// <paramref name="replacement"/> pattern, starting at the character position /// <paramref name="startat"/>. /// </summary> public string Replace(string input, string replacement, int count, int startat) { if (input == null) throw new ArgumentNullException(nameof(input)); if (replacement == null) throw new ArgumentNullException(nameof(replacement)); // a little code to grab a cached parsed replacement object RegexReplacement repl = (RegexReplacement)_replref.Get(); if (repl == null || !repl.Pattern.Equals(replacement)) { repl = RegexParser.ParseReplacement(replacement, caps, capsize, capnames, roptions); _replref.Cache(repl); } return repl.Replace(this, input, count, startat); } /// <summary> /// Replaces all occurrences of the <paramref name="pattern"/> with the recent /// replacement pattern. /// </summary> public static string Replace(string input, string pattern, MatchEvaluator evaluator) { return Replace(input, pattern, evaluator, RegexOptions.None, DefaultMatchTimeout); } /// <summary> /// Replaces all occurrences of the <paramref name="pattern"/> with the recent /// replacement pattern, starting at the first character. /// </summary> public static string Replace(string input, string pattern, MatchEvaluator evaluator, RegexOptions options) { return Replace(input, pattern, evaluator, options, DefaultMatchTimeout); } public static string Replace(string input, string pattern, MatchEvaluator evaluator, RegexOptions options, TimeSpan matchTimeout) { return new Regex(pattern, options, matchTimeout, true).Replace(input, evaluator); } /// <summary> /// Replaces all occurrences of the previously defined pattern with the recent /// replacement pattern, starting at the first character position. /// </summary> public string Replace(string input, MatchEvaluator evaluator) { if (input == null) throw new ArgumentNullException(nameof(input)); return Replace(input, evaluator, -1, UseOptionR() ? input.Length : 0); } /// <summary> /// Replaces all occurrences of the previously defined pattern with the recent /// replacement pattern, starting at the first character position. /// </summary> public string Replace(string input, MatchEvaluator evaluator, int count) { if (input == null) throw new ArgumentNullException(nameof(input)); return Replace(input, evaluator, count, UseOptionR() ? input.Length : 0); } /// <summary> /// Replaces all occurrences of the previously defined pattern with the recent /// replacement pattern, starting at the character position /// <paramref name="startat"/>. /// </summary> public string Replace(string input, MatchEvaluator evaluator, int count, int startat) { if (input == null) throw new ArgumentNullException(nameof(input)); return RegexReplacement.Replace(evaluator, this, input, count, startat); } /// <summary> /// Splits the <paramref name="input "/>string at the position defined /// by <paramref name="pattern"/>. /// </summary> public static string[] Split(string input, string pattern) { return Split(input, pattern, RegexOptions.None, DefaultMatchTimeout); } /// <summary> /// Splits the <paramref name="input "/>string at the position defined by <paramref name="pattern"/>. /// </summary> public static string[] Split(string input, string pattern, RegexOptions options) { return Split(input, pattern, options, DefaultMatchTimeout); } public static string[] Split(string input, string pattern, RegexOptions options, TimeSpan matchTimeout) { return new Regex(pattern, options, matchTimeout, true).Split(input); } /// <summary> /// Splits the <paramref name="input"/> string at the position defined by a /// previous pattern. /// </summary> public string[] Split(string input) { if (input == null) throw new ArgumentNullException(nameof(input)); return Split(input, 0, UseOptionR() ? input.Length : 0); } /// <summary> /// Splits the <paramref name="input"/> string at the position defined by a /// previous pattern. /// </summary> public string[] Split(string input, int count) { if (input == null) throw new ArgumentNullException(nameof(input)); return RegexReplacement.Split(this, input, count, UseOptionR() ? input.Length : 0); } /// <summary> /// Splits the <paramref name="input"/> string at the position defined by a /// previous pattern. /// </summary> public string[] Split(string input, int count, int startat) { if (input == null) throw new ArgumentNullException(nameof(input)); return RegexReplacement.Split(this, input, count, startat); } protected void InitializeReferences() { if (_refsInitialized) throw new NotSupportedException(""); _refsInitialized = true; _runnerref = new ExclusiveReference(); _replref = new SharedReference(); } /* * Internal worker called by all the public APIs */ internal Match Run(bool quick, int prevlen, string input, int beginning, int length, int startat) { Match match; RegexRunner runner = null; if (startat < 0 || startat > input.Length) throw new ArgumentOutOfRangeException(nameof(startat), ""); if (length < 0 || length > input.Length) throw new ArgumentOutOfRangeException(nameof(length), ""); // There may be a cached runner; grab ownership of it if we can. runner = (RegexRunner)_runnerref.Get(); // Create a RegexRunner instance if we need to if (runner == null) { if (factory != null) runner = factory.CreateInstance(); else runner = new RegexInterpreter(_code, UseOptionInvariant() ? CultureInfo.InvariantCulture : CultureInfo.CurrentCulture); } try { // Do the scan starting at the requested position match = runner.Scan(this, input, beginning, beginning + length, startat, prevlen, quick, internalMatchTimeout); } finally { // Release or fill the cache slot _runnerref.Release(runner); } #if DEBUG if (Debug && match != null) match.Dump(); #endif return match; } /* * Find code cache based on options+pattern */ private static CachedCodeEntry LookupCachedAndUpdate(CachedCodeEntryKey key) { lock (s_livecode) { for (LinkedListNode<CachedCodeEntry> current = s_livecode.First; current != null; current = current.Next) { if (current.Value._key == key) { // If we find an entry in the cache, move it to the head at the same time. s_livecode.Remove(current); s_livecode.AddFirst(current); return current.Value; } } } return null; } /* * Add current code to the cache */ private CachedCodeEntry CacheCode(CachedCodeEntryKey key) { CachedCodeEntry newcached = null; lock (s_livecode) { // first look for it in the cache and move it to the head for (LinkedListNode<CachedCodeEntry> current = s_livecode.First; current != null; current = current.Next) { if (current.Value._key == key) { s_livecode.Remove(current); s_livecode.AddFirst(current); return current.Value; } } // it wasn't in the cache, so we'll add a new one. Shortcut out for the case where cacheSize is zero. if (s_cacheSize != 0) { newcached = new CachedCodeEntry(key, capnames, capslist, _code, caps, capsize, _runnerref, _replref); s_livecode.AddFirst(newcached); if (s_livecode.Count > s_cacheSize) s_livecode.RemoveLast(); } } return newcached; } protected bool UseOptionC() { return (roptions & RegexOptions.Compiled) != 0; } /* * True if the L option was set */ protected internal bool UseOptionR() { return (roptions & RegexOptions.RightToLeft) != 0; } internal bool UseOptionInvariant() { return (roptions & RegexOptions.CultureInvariant) != 0; } /*// <summary> /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// /// </summary> public static void CompileToAssembly(RegexCompilationInfo[] regexinfos, AssemblyName assemblyname) { CompileToAssemblyInternal(regexinfos, assemblyname, null, null); } public static void CompileToAssembly(RegexCompilationInfo[] regexinfos, AssemblyName assemblyname, CustomAttributeBuilder[] attributes) { CompileToAssemblyInternal(regexinfos, assemblyname, attributes, null); } public static void CompileToAssembly(RegexCompilationInfo[] regexinfos, AssemblyName assemblyname, CustomAttributeBuilder[] attributes, String resourceFile) { CompileToAssemblyInternal(regexinfos, assemblyname, attributes, resourceFile); } private static void CompileToAssemblyInternal(RegexCompilationInfo[] regexinfos, AssemblyName assemblyname, CustomAttributeBuilder[] attributes, String resourceFile) { if (assemblyname == null) throw new ArgumentNullException("assemblyname"); if (regexinfos == null) throw new ArgumentNullException("regexinfos"); RegexCompiler.CompileToAssembly(regexinfos, assemblyname, attributes, resourceFile); } /// <summary> /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// /// </summary>//*/ #if DEBUG /* * True if the regex has debugging enabled */ internal bool Debug { get { return (roptions & RegexOptions.Debug) != 0; } } #endif } /* * Callback class */ public delegate string MatchEvaluator(Match match); /* * Used as a key for CacheCodeEntry */ internal struct CachedCodeEntryKey : IEquatable<CachedCodeEntryKey> { private readonly RegexOptions _options; private readonly string _cultureKey; private readonly string _pattern; internal CachedCodeEntryKey(RegexOptions options, string cultureKey, string pattern) { _options = options; _cultureKey = cultureKey; _pattern = pattern; } public override bool Equals(object obj) { return obj is CachedCodeEntryKey && Equals((CachedCodeEntryKey)obj); } public bool Equals(CachedCodeEntryKey other) { return this == other; } public static bool operator ==(CachedCodeEntryKey left, CachedCodeEntryKey right) { return left._options == right._options && left._cultureKey == right._cultureKey && left._pattern == right._pattern; } public static bool operator !=(CachedCodeEntryKey left, CachedCodeEntryKey right) { return !(left == right); } public override int GetHashCode() { return ((int)_options) ^ _cultureKey.GetHashCode() ^ _pattern.GetHashCode(); } } /* * Used to cache byte codes */ internal sealed class CachedCodeEntry { internal CachedCodeEntryKey _key; internal RegexCode _code; internal Hashtable _caps; internal Hashtable _capnames; internal string[] _capslist; internal int _capsize; internal ExclusiveReference _runnerref; internal SharedReference _replref; internal RegexRunnerFactory _factory; internal CachedCodeEntry(CachedCodeEntryKey key, Hashtable capnames, string[] capslist, RegexCode code, Hashtable caps, int capsize, ExclusiveReference runner, SharedReference repl) { _key = key; _capnames = capnames; _capslist = capslist; _code = code; _caps = caps; _capsize = capsize; _runnerref = runner; _replref = repl; } internal void AddCompiled(RegexRunnerFactory factory) { _factory = factory; _code = null; } } /* * Used to cache one exclusive runner reference */ internal sealed class ExclusiveReference { private RegexRunner _ref; private object _obj; private int _locked; /* * Return an object and grab an exclusive lock. * * If the exclusive lock can't be obtained, null is returned; * if the object can't be returned, the lock is released. * */ internal object Get() { // try to obtain the lock if (0 == Interlocked.Exchange(ref _locked, 1)) { // grab reference object obj = _ref; // release the lock and return null if no reference if (obj == null) { _locked = 0; return null; } // remember the reference and keep the lock _obj = obj; return obj; } return null; } /* * Release an object back to the cache * * If the object is the one that's under lock, the lock * is released. * * If there is no cached object, then the lock is obtained * and the object is placed in the cache. * */ internal void Release(object obj) { if (obj == null) throw new ArgumentNullException(nameof(obj)); // if this reference owns the lock, release it if (_obj == obj) { _obj = null; _locked = 0; return; } // if no reference owns the lock, try to cache this reference if (_obj == null) { // try to obtain the lock if (0 == Interlocked.Exchange(ref _locked, 1)) { // if there's really no reference, cache this reference if (_ref == null) _ref = (RegexRunner)obj; // release the lock _locked = 0; return; } } } } /* * Used to cache a weak reference in a threadsafe way */ internal sealed class SharedReference { private WeakReference _ref = new WeakReference(null); private int _locked; /* * Return an object from a weakref, protected by a lock. * * If the exclusive lock can't be obtained, null is returned; * * Note that _ref.Target is referenced only under the protection * of the lock. (Is this necessary?) */ internal object Get() { if (0 == Interlocked.Exchange(ref _locked, 1)) { object obj = _ref.Target; _locked = 0; return obj; } return null; } /* * Suggest an object into a weakref, protected by a lock. * * Note that _ref.Target is referenced only under the protection * of the lock. (Is this necessary?) */ internal void Cache(object obj) { if (0 == Interlocked.Exchange(ref _locked, 1)) { _ref.Target = obj; _locked = 0; } } } }
// // Copyright (C) 2010 Jackson Harper (jackson@manosdemono.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // // using System; using NUnit.Framework; using System.IO; using Manos.ShouldExt; namespace Manos.Http.Tests { [TestFixture()] public class HttpResponseStreamTest { [Test] public void Write_SingleSegment_SetsLength () { var stream = new HttpResponseStream (); var buffer = new byte [10]; stream.Write (buffer, 0, 10); long len = stream.Length; Assert.AreEqual (10, len); } [Test] public void Write_OffsetSegment_SetsLength () { var stream = new HttpResponseStream (); var buffer = new byte [10]; stream.Write (buffer, 5, 5); long len = stream.Length; Assert.AreEqual (5, len); } [Test] public void Write_TruncatedSegment_SetsLength () { var stream = new HttpResponseStream (); var buffer = new byte [10]; stream.Write (buffer, 0, 5); long len = stream.Length; Assert.AreEqual (5, len); } [Test] public void Write_TwoSegments_SetsLength () { var stream = new HttpResponseStream (); var buffer = new byte [10]; stream.Write (buffer, 0, 10); stream.Write (buffer, 0, 10); long len = stream.Length; Assert.AreEqual (20, len); } [Test] public void Write_TwoSegments_SetsPosition () { var stream = new HttpResponseStream (); var buffer = new byte [10]; stream.Write (buffer, 0, 10); stream.Write (buffer, 0, 10); long pos = stream.Position; Assert.AreEqual (20, pos); } [Test] public void Seek_SeekToBeginningOfEmptyStream_SetsPosition () { var stream = new HttpResponseStream (); stream.Seek (0, SeekOrigin.Begin); var position = stream.Position; Assert.AreEqual (0, position); } [Test] public void SeekOrigin_NegativePastBeginning_Throws () { var stream = new HttpResponseStream (); var buffer = new byte [10]; stream.Write (buffer, 0, 10); Should.Throw<ArgumentException> (() => stream.Seek (-1, SeekOrigin.Begin)); } [Test] public void SeekOrigin_PositivePastEnd_Throws () { var stream = new HttpResponseStream (); var buffer = new byte [10]; stream.Write (buffer, 0, 10); Should.Throw<ArgumentException> (() => stream.Seek (11, SeekOrigin.Begin)); } [Test] public void Seek_FromBeginning_SetsPosition () { var stream = new HttpResponseStream (); var buffer = new byte [10]; stream.Write (buffer, 0, 10); stream.Seek (5, SeekOrigin.Begin); long pos = stream.Position; Assert.AreEqual (5, pos); } [Test] public void Seek_FromBeginningMultipleSegments_SetsPosition () { var stream = new HttpResponseStream (); var buffer = new byte [10]; stream.Write (buffer, 0, 10); stream.Write (buffer, 0, 10); stream.Write (buffer, 0, 10); stream.Seek (25, SeekOrigin.Begin); long pos = stream.Position; Assert.AreEqual (25, pos); } [Test] public void Seek_FromBeginningLastIndexOfSegment_SetsPosition () { var stream = new HttpResponseStream (); var buffer = new byte [10]; stream.Write (buffer, 0, 10); stream.Write (buffer, 0, 10); stream.Seek (10, SeekOrigin.Begin); long pos = stream.Position; Assert.AreEqual (10, pos); } [Test] public void Seek_FromEnd_SetsPosition () { var stream = new HttpResponseStream (); var buffer = new byte [10]; stream.Write (buffer, 0, 10); stream.Seek (-3, SeekOrigin.End); long pos = stream.Position; Assert.AreEqual (7, pos); } [Test] public void Seek_FromEndMultipleBuffersAcrossBoundries_SetsPosition () { var stream = new HttpResponseStream (); var buffer = new byte [10]; stream.Write (buffer, 0, 10); stream.Write (buffer, 0, 10); stream.Write (buffer, 0, 10); stream.Seek (-25, SeekOrigin.End); long pos = stream.Position; Assert.AreEqual (5, pos); } [Test] public void Seek_FromEndMultipleBuffers_SetsPosition () { var stream = new HttpResponseStream (); var buffer = new byte [10]; stream.Write (buffer, 0, 10); stream.Write (buffer, 0, 10); stream.Write (buffer, 0, 10); stream.Seek (-5, SeekOrigin.End); long pos = stream.Position; Assert.AreEqual (25, pos); } [Test] public void Seek_FromEndLastIndexOfBuffer_SetsPosition () { var stream = new HttpResponseStream (); var buffer = new byte [10]; stream.Write (buffer, 0, 10); stream.Write (buffer, 0, 10); stream.Seek (-10, SeekOrigin.End); long pos = stream.Position; Assert.AreEqual (10, pos); } [Test] public void Seek_FromCurrentBackwards_SetsPosition () { var stream = new HttpResponseStream (); var buffer = new byte [10]; stream.Write (buffer, 0, 10); stream.Write (buffer, 0, 10); stream.Seek (-5, SeekOrigin.Current); long pos = stream.Position; Assert.AreEqual (15, pos); } [Test] public void Write_SeekedBackInLastSegment_SetsPosition () { var stream = new HttpResponseStream (); var buffer = new byte [10]; stream.Write (buffer, 0, 10); stream.Write (buffer, 0, 10); stream.Seek (-5, SeekOrigin.Current); stream.Write (buffer, 0, 10); long pos = stream.Position; Assert.AreEqual (25, pos); } [Test] public void Write_SeekedBackPastLastSegmentWriteOverAll_SetsPosition () { var stream = new HttpResponseStream (); var buffer = new byte [10]; var buffer_big = new byte [25]; stream.Write (buffer, 0, 10); stream.Write (buffer, 0, 10); stream.Seek (-15, SeekOrigin.Current); Assert.AreEqual (5, stream.Position); stream.Write (buffer_big, 0, 25); long pos = stream.Position; Assert.AreEqual (30, pos); } [Test] public void SetLength_LessThanSingleBuffer_Truncates () { var stream = new HttpResponseStream (); var buffer = new byte [10]; stream.Write (buffer, 0, 10); stream.SetLength (5); long length = stream.Length; Assert.AreEqual (5, length); } [Test] public void SetLength_LessThanMultiBuffer_Truncates () { var stream = new HttpResponseStream (); var buffer = new byte [10]; stream.Write (buffer, 0, 10); stream.Write (buffer, 0, 10); stream.Write (buffer, 0, 10); stream.SetLength (5); long length = stream.Length; Assert.AreEqual (5, length); } [Test] public void SetLength_LongerThanSingleBuffer_AddsFiller () { var stream = new HttpResponseStream (); var buffer = new byte [10]; stream.Write (buffer, 0, 10); stream.SetLength (25); long length = stream.Length; Assert.AreEqual (25, length); } [Test] public void SetLength_MultiBuffer_AddsFiller () { var stream = new HttpResponseStream (); var buffer = new byte [10]; stream.Write (buffer, 0, 10); stream.Write (buffer, 0, 10); stream.SetLength (25); long length = stream.Length; Assert.AreEqual (25, length); } [Test] public void SetLength_EqualToCurrentLength_LengthStaysTheSame () { var stream = new HttpResponseStream (); var buffer = new byte [10]; stream.Write (buffer, 0, 10); stream.Write (buffer, 0, 10); stream.SetLength (20); long length = stream.Length; Assert.AreEqual (20, length); } [Test] public void Read_SingleBuffer_UpdatesPosition () { var stream = new HttpResponseStream (); var buffer = new byte [10]; stream.Write (buffer, 0, 10); stream.Seek (0, SeekOrigin.Begin); stream.Read (buffer, 0, 5); long position = stream.Position; Assert.AreEqual (5, position); } [Test] public void Read_MultipleBuffers_UpdatesPosition () { var stream = new HttpResponseStream (); var buffer = new byte [10]; stream.Write (buffer, 0, 10); stream.Write (buffer, 0, 10); stream.Write (buffer, 0, 10); stream.Seek (15, SeekOrigin.Begin); stream.Read (buffer, 0, 5); long position = stream.Position; Assert.AreEqual (20, position); } [Test] public void Read_ReadLastItem_UpdatesPosition () { var stream = new HttpResponseStream (); var buffer = new byte [10]; stream.Write (buffer, 0, 10); stream.Seek (-1, SeekOrigin.End); stream.Read (buffer, 0, 1); long position = stream.Position; Assert.AreEqual (10, position); } [Test] public void Read_PastEndOfStream_ReturnsAmountRead () { var stream = new HttpResponseStream (); var buffer = new byte [10]; stream.Write (buffer, 0, 10); stream.Seek (-1, SeekOrigin.End); int amount_read = stream.Read (buffer, 0, 2); Assert.AreEqual (1, amount_read); } [Test] public void Read_SingleBuffer_CorrectData () { var stream = new HttpResponseStream (); var write_buffer = new byte [3]; var read_buffer = new byte [1]; write_buffer [2] = 0xFA; stream.Write (write_buffer, 0, 3); stream.Seek (-1, SeekOrigin.End); stream.Read (read_buffer, 0, 1); byte read_byte = read_buffer [0]; Assert.AreEqual (0xFA, read_byte); } [Test] public void Read_MultipleBuffers_CorrectData () { var stream = new HttpResponseStream (); var write_buffer1 = new byte [3]; var write_buffer2 = new byte [3]; var read_buffer = new byte [6]; stream.Write (write_buffer1, 0, 3); write_buffer2 [0] = 0xFA; stream.Write (write_buffer2, 0, 3); stream.Seek (0, SeekOrigin.Begin); stream.Read (read_buffer, 0, 6); byte read_byte = read_buffer [3]; Assert.AreEqual (0xFA, read_byte); } [Test] public void Write_LongerThanBufferInSingleBuffer_SetsCorrectLength () { var stream = new HttpResponseStream (); var write_buffer = new byte [5]; stream.Write (write_buffer, 0, 5); stream.Position = 2; stream.Write (write_buffer, 0, 5); var length = stream.Length; Assert.AreEqual (7, length); } [Test] public void Write_ShorterThanBufferInSingleBuffer_SetsCorrectLength () { var stream = new HttpResponseStream (); var write_buffer = new byte [5]; stream.Write (write_buffer, 0, 5); stream.Position = 2; stream.Write (write_buffer, 0, 2); var length = stream.Length; Assert.AreEqual (5, length); } [Test] public void Write_InFirstBufferOfTwoBufferStream_SetsCorrectLength () { var stream = new HttpResponseStream (); var write_buffer = new byte [5]; stream.Write (write_buffer, 0, 5); stream.Write (write_buffer, 0, 5); stream.Seek (-6, SeekOrigin.End); stream.Write (write_buffer, 0, 5); var length = stream.Length; Assert.AreEqual (10, length); } [Test] public void Write_AcrossEntireMiddleBufferOfThreeBufferStream_SetsCorrectLength () { var stream = new HttpResponseStream (); var write_buffer = new byte [5]; var write_buffer2 = new byte [6]; stream.Write (write_buffer, 0, 5); stream.Write (write_buffer, 0, 5); stream.Write (write_buffer, 0, 5); stream.Seek (2, SeekOrigin.Begin); stream.Write (write_buffer2, 0, 6); var length = stream.Length; Assert.AreEqual (15, length); } [Test] public void Insert_BeginningOfStream_SetsCorrectLength () { var stream = new HttpResponseStream (); var write_buffer = new byte [10]; stream.Write (write_buffer, 0, 10); stream.Position = 0; stream.Insert (write_buffer, 0, 10); var length = stream.Length; Assert.AreEqual (20, length); } [Test] public void Insert_BeginningOfStream_SetsCorrectPosition () { var stream = new HttpResponseStream (); var write_buffer = new byte [10]; stream.Write (write_buffer, 0, 10); stream.Position = 0; stream.Insert (write_buffer, 0, 5); var position = stream.Position; Assert.AreEqual (5, position); } [Test] public void Insert_BeginningOfStream_SetsCorrectData () { var stream = new HttpResponseStream (); var write_buffer = new byte [10]; var write_buffer2 = new byte [10]; stream.Write (write_buffer, 0, 10); stream.Position = 0; write_buffer2 [2] = 0xFA; stream.Insert (write_buffer2, 0, 10); stream.Position = 2; var data = stream.ReadByte (); Assert.AreEqual (0xFA, data); } } }
// 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.Diagnostics.CodeAnalysis; using System.Globalization; namespace System.ComponentModel.Design { /// <summary> /// Provides access to get and set option values for a designer. /// </summary> public abstract class DesignerOptionService : IDesignerOptionService { private DesignerOptionCollection _options; private static readonly char[] s_slash = { '\\' }; /// <summary> /// Returns the options collection for this service. There is /// always a global options collection that contains child collections. /// </summary> public DesignerOptionCollection Options { get => _options ?? (_options = new DesignerOptionCollection(this, null, string.Empty, null)); } /// <summary> /// Creates a new DesignerOptionCollection with the given name, and adds it to /// the given parent. The "value" parameter specifies an object whose public /// properties will be used in the Properties collection of the option collection. /// The value parameter can be null if this options collection does not offer /// any properties. Properties will be wrapped in such a way that passing /// anything into the component parameter of the property descriptor will be /// ignored and the value object will be substituted. /// </summary> protected DesignerOptionCollection CreateOptionCollection(DesignerOptionCollection parent, string name, object value) { if (parent == null) { throw new ArgumentNullException(nameof(parent)); } if (name == null) { throw new ArgumentNullException(nameof(name)); } if (name.Length == 0) { throw new ArgumentException(SR.Format(SR.InvalidArgumentValue, name.Length.ToString(), "0"), "name.Length"); } return new DesignerOptionCollection(this, parent, name, value); } /// <summary> /// Retrieves the property descriptor for the given page / value name. Returns /// null if the property couldn't be found. /// </summary> private PropertyDescriptor GetOptionProperty(string pageName, string valueName) { if (pageName == null) { throw new ArgumentNullException(nameof(pageName)); } if (valueName == null) { throw new ArgumentNullException(nameof(valueName)); } string[] optionNames = pageName.Split(s_slash); DesignerOptionCollection options = Options; foreach (string optionName in optionNames) { options = options[optionName]; if (options == null) { return null; } } return options.Properties[valueName]; } /// <summary> /// This method is called on demand the first time a user asks for child /// options or properties of an options collection. /// </summary> protected virtual void PopulateOptionCollection(DesignerOptionCollection options) { } /// <summary> /// This method must be implemented to show the options dialog UI for the given object. /// </summary> protected virtual bool ShowDialog(DesignerOptionCollection options, object optionObject) => false; /// <summary> /// Gets the value of an option defined in this package. /// </summary> object IDesignerOptionService.GetOptionValue(string pageName, string valueName) { PropertyDescriptor optionProp = GetOptionProperty(pageName, valueName); return optionProp?.GetValue(null); } /// <summary> /// Sets the value of an option defined in this package. /// </summary> void IDesignerOptionService.SetOptionValue(string pageName, string valueName, object value) { PropertyDescriptor optionProp = GetOptionProperty(pageName, valueName); optionProp?.SetValue(null, value); } /// <summary> /// The DesignerOptionCollection class is a collection that contains /// other DesignerOptionCollection objects. This forms a tree of options, /// with each branch of the tree having a name and a possible collection of /// properties. Each parent branch of the tree contains a union of the /// properties if all the branch's children. /// </summary> [TypeConverter(typeof(DesignerOptionConverter))] public sealed class DesignerOptionCollection : IList { private readonly DesignerOptionService _service; private readonly object _value; private ArrayList _children; private PropertyDescriptorCollection _properties; /// <summary> /// Creates a new DesignerOptionCollection. /// </summary> internal DesignerOptionCollection(DesignerOptionService service, DesignerOptionCollection parent, string name, object value) { _service = service; Parent = parent; Name = name; _value = value; if (Parent != null) { parent._properties = null; if (Parent._children == null) { Parent._children = new ArrayList(1); } Parent._children.Add(this); } } /// <summary> /// The count of child options collections this collection contains. /// </summary> public int Count { get { EnsurePopulated(); return _children.Count; } } /// <summary> /// The name of this collection. Names are programmatic names and are not /// localized. A name search is case insensitive. /// </summary> public string Name { get; } /// <summary> /// Returns the parent collection object, or null if there is no parent. /// </summary> public DesignerOptionCollection Parent { get; } /// <summary> /// The collection of properties that this OptionCollection, along with all of /// its children, offers. PropertyDescriptors are taken directly from the /// value passed to CreateObjectCollection and wrapped in an additional property /// descriptor that hides the value object from the user. This means that any /// value may be passed into the "component" parameter of the various /// PropertyDescriptor methods. The value is ignored and is replaced with /// the correct value internally. /// </summary> public PropertyDescriptorCollection Properties { get { if (_properties == null) { ArrayList propList; if (_value != null) { PropertyDescriptorCollection props = TypeDescriptor.GetProperties(_value); propList = new ArrayList(props.Count); foreach (PropertyDescriptor prop in props) { propList.Add(new WrappedPropertyDescriptor(prop, _value)); } } else { propList = new ArrayList(1); } EnsurePopulated(); foreach (DesignerOptionCollection child in _children) { propList.AddRange(child.Properties); } PropertyDescriptor[] propArray = (PropertyDescriptor[])propList.ToArray(typeof(PropertyDescriptor)); _properties = new PropertyDescriptorCollection(propArray, true); } return _properties; } } /// <summary> /// Retrieves the child collection at the given index. /// </summary> public DesignerOptionCollection this[int index] { [SuppressMessage("Microsoft.Globalization", "CA1303:DoNotPassLiteralsAsLocalizedParameters")] get { EnsurePopulated(); if (index < 0 || index >= _children.Count) { throw new IndexOutOfRangeException(nameof(index)); } return (DesignerOptionCollection)_children[index]; } } /// <summary> /// Retrieves the child collection at the given name. The name search is case /// insensitive. /// </summary> public DesignerOptionCollection this[string name] { get { EnsurePopulated(); foreach (DesignerOptionCollection child in _children) { if (string.Compare(child.Name, name, true, CultureInfo.InvariantCulture) == 0) { return child; } } return null; } } /// <summary> /// Copies this collection to an array. /// </summary> public void CopyTo(Array array, int index) { EnsurePopulated(); _children.CopyTo(array, index); } /// <summary> /// Called before any access to our collection to force it to become populated. /// </summary> private void EnsurePopulated() { if (_children == null) { _service.PopulateOptionCollection(this); if (_children == null) { _children = new ArrayList(1); } } } /// <summary> /// Returns an enumerator that can be used to iterate this collection. /// </summary> public IEnumerator GetEnumerator() { EnsurePopulated(); return _children.GetEnumerator(); } /// <summary> /// Returns the numerical index of the given value. /// </summary> public int IndexOf(DesignerOptionCollection value) { EnsurePopulated(); return _children.IndexOf(value); } /// <summary> /// Locates the value object to use for getting or setting a property. /// </summary> private static object RecurseFindValue(DesignerOptionCollection options) { if (options._value != null) { return options._value; } foreach (DesignerOptionCollection child in options) { object value = RecurseFindValue(child); if (value != null) { return value; } } return null; } /// <summary> /// Displays a dialog-based user interface that allows the user to /// configure the various options. /// </summary> public bool ShowDialog() { object value = RecurseFindValue(this); if (value == null) { return false; } return _service.ShowDialog(this, value); } /// <summary> /// Private ICollection implementation. /// </summary> bool ICollection.IsSynchronized => false; /// <summary> /// Private ICollection implementation. /// </summary> object ICollection.SyncRoot => this; /// <summary> /// Private IList implementation. /// </summary> bool IList.IsFixedSize => true; /// <summary> /// Private IList implementation. /// </summary> bool IList.IsReadOnly => true; /// <summary> /// Private IList implementation. /// </summary> object IList.this[int index] { get => this[index]; set => throw new NotSupportedException(); } /// <summary> /// Private IList implementation. /// </summary> int IList.Add(object value) => throw new NotSupportedException(); /// <summary> /// Private IList implementation. /// </summary> void IList.Clear() => throw new NotSupportedException(); /// <summary> /// Private IList implementation. /// </summary> bool IList.Contains(object value) { EnsurePopulated(); return _children.Contains(value); } /// <summary> /// Private IList implementation. /// </summary> int IList.IndexOf(object value) { EnsurePopulated(); return _children.IndexOf(value); } /// <summary> /// Private IList implementation. /// </summary> void IList.Insert(int index, object value) => throw new NotSupportedException(); /// <summary> /// Private IList implementation. /// </summary> void IList.Remove(object value) => throw new NotSupportedException(); /// <summary> /// Private IList implementation. /// </summary> void IList.RemoveAt(int index) => throw new NotSupportedException(); /// <summary> /// A special property descriptor that forwards onto a base /// property descriptor but allows any value to be used for the /// "component" parameter. /// </summary> private sealed class WrappedPropertyDescriptor : PropertyDescriptor { private readonly object _target; private readonly PropertyDescriptor _property; internal WrappedPropertyDescriptor(PropertyDescriptor property, object target) : base(property.Name, null) { _property = property; _target = target; } public override AttributeCollection Attributes => _property.Attributes; public override Type ComponentType => _property.ComponentType; public override bool IsReadOnly => _property.IsReadOnly; public override Type PropertyType => _property.PropertyType; public override bool CanResetValue(object component) => _property.CanResetValue(_target); public override object GetValue(object component) => _property.GetValue(_target); public override void ResetValue(object component) => _property.ResetValue(_target); public override void SetValue(object component, object value) => _property.SetValue(_target, value); public override bool ShouldSerializeValue(object component) => _property.ShouldSerializeValue(_target); } } /// <summary> /// The type converter for the designer option collection. /// </summary> internal sealed class DesignerOptionConverter : TypeConverter { public override bool GetPropertiesSupported(ITypeDescriptorContext cxt) => true; public override PropertyDescriptorCollection GetProperties(ITypeDescriptorContext cxt, object value, Attribute[] attributes) { PropertyDescriptorCollection props = new PropertyDescriptorCollection(null); if (!(value is DesignerOptionCollection options)) { return props; } foreach (DesignerOptionCollection option in options) { props.Add(new OptionPropertyDescriptor(option)); } foreach (PropertyDescriptor p in options.Properties) { props.Add(p); } return props; } public override object ConvertTo(ITypeDescriptorContext cxt, CultureInfo culture, object value, Type destinationType) { if (destinationType == typeof(string)) { return SR.CollectionConverterText; } return base.ConvertTo(cxt, culture, value, destinationType); } private class OptionPropertyDescriptor : PropertyDescriptor { private readonly DesignerOptionCollection _option; internal OptionPropertyDescriptor(DesignerOptionCollection option) : base(option.Name, null) { _option = option; } public override Type ComponentType => _option.GetType(); public override bool IsReadOnly => true; public override Type PropertyType => _option.GetType(); public override bool CanResetValue(object component) => false; public override object GetValue(object component) => _option; public override void ResetValue(object component) { } public override void SetValue(object component, object value) { } public override bool ShouldSerializeValue(object component) => false; } } } }
// // InfoBox.cs // // Author: // Ruben Vermeersch <ruben@savanne.be> // Stephane Delcroix <sdelcroix@novell.com> // Mike Gemuende <mike@gemuende.de> // // Copyright (C) 2008-2010 Novell, Inc. // Copyright (C) 2008, 2010 Ruben Vermeersch // Copyright (C) 2008 Stephane Delcroix // Copyright (C) 2010 Mike Gemuende // // 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 Mono.Unix; using FSpot.Core; using FSpot.Imaging; using FSpot.Utils; using Gtk; using GLib; using GFile = GLib.File; using GFileInfo = GLib.FileInfo; // FIXME TODO: We want to use something like EClippedLabel here throughout so it handles small sizes // gracefully using ellipsis. namespace FSpot.Widgets { public class InfoBox : VBox { DelayedOperation update_delay; public struct InfoEntry { public bool TwoColumns; public bool AlwaysVisible; public bool DefaultVisibility; public string Id; public string Description; public Widget LabelWidget; public Widget InfoWidget; public Action<Widget, IPhoto, TagLib.Image.File> SetSingle; public Action<Widget, IPhoto[]> SetMultiple; } private List<InfoEntry> entries = new List<InfoEntry> (); private void AddEntry (string id, string name, string description, Widget info_widget, float label_y_align, bool default_visibility, Action<Widget, IPhoto, TagLib.Image.File> set_single, Action<Widget, IPhoto[]> set_multiple) { entries.Add (new InfoEntry { TwoColumns = (name == null), AlwaysVisible = (id == null) || (description == null), DefaultVisibility = default_visibility, Id = id, Description = description, LabelWidget = CreateRightAlignedLabel (String.Format ("<b>{0}</b>", name), label_y_align), InfoWidget = info_widget, SetSingle = set_single, SetMultiple = set_multiple }); } private void AddEntry (string id, string name, string description, Widget info_widget, float label_y_align, Action<Widget, IPhoto, TagLib.Image.File> set_single, Action<Widget, IPhoto[]> set_multiple) { AddEntry (id, name, description, info_widget, label_y_align, true, set_single, set_multiple); } private void AddEntry (string id, string name, string description, Widget info_widget, bool default_visibility, Action<Widget, IPhoto, TagLib.Image.File> set_single, Action<Widget, IPhoto[]> set_multiple) { AddEntry (id, name, description, info_widget, 0.0f, default_visibility, set_single, set_multiple); } private void AddEntry (string id, string name, string description, Widget info_widget, Action<Widget, IPhoto, TagLib.Image.File> set_single, Action<Widget, IPhoto[]> set_multiple) { AddEntry (id, name, description, info_widget, 0.0f, set_single, set_multiple); } private void AddLabelEntry (string id, string name, string description, Func<IPhoto, TagLib.Image.File, string> single_string, Func<IPhoto[], string> multiple_string) { AddLabelEntry (id, name, description, true, single_string, multiple_string); } private void AddLabelEntry (string id, string name, string description, bool default_visibility, Func<IPhoto, TagLib.Image.File, string> single_string, Func<IPhoto[], string> multiple_string) { Action<Widget, IPhoto, TagLib.Image.File> set_single = (widget, photo, metadata) => { if (metadata != null) (widget as Label).Text = single_string (photo, metadata); else (widget as Label).Text = Catalog.GetString ("(Unknown)"); }; Action<Widget, IPhoto[]> set_multiple = (widget, photos) => { (widget as Label).Text = multiple_string (photos); }; AddEntry (id, name, description, CreateLeftAlignedLabel (String.Empty), default_visibility, single_string == null ? null : set_single, multiple_string == null ? null : set_multiple); } private IPhoto[] photos = new IPhoto[0]; public IPhoto[] Photos { private get { return photos; } set { photos = value; update_delay.Start (); } } public IPhoto Photo { set { if (value != null) { Photos = new IPhoto[] { value }; } } } private bool show_tags = false; public bool ShowTags { get { return show_tags; } set { if (show_tags == value) return; show_tags = value; // tag_view.Visible = show_tags; } } private bool show_rating = false; public bool ShowRating { get { return show_rating; } set { if (show_rating == value) return; show_rating = value; // rating_label.Visible = show_rating; // rating_view.Visible = show_rating; } } public delegate void VersionChangedHandler (InfoBox info_box, IPhotoVersion version); public event VersionChangedHandler VersionChanged; private Expander info_expander; private Expander histogram_expander; private Gtk.Image histogram_image; private Histogram histogram; private DelayedOperation histogram_delay; // Context switching (toggles visibility). public event EventHandler ContextChanged; private ViewContext view_context = ViewContext.Unknown; public ViewContext Context { get { return view_context; } set { view_context = value; if (ContextChanged != null) ContextChanged (this, null); } } private readonly InfoBoxContextSwitchStrategy ContextSwitchStrategy; // Widgetry. private ListStore version_list; private ComboBox version_combo; private void HandleRatingChanged (object o, EventArgs e) { App.Instance.Organizer.HandleRatingMenuSelected ((o as Widgets.RatingEntry).Value); } private Label CreateRightAlignedLabel (string text, float yalign) { Label label = new Label (); label.UseMarkup = true; label.Markup = text; label.Xalign = 1.0f; label.Yalign = yalign; return label; } private Label CreateLeftAlignedLabel (string text) { Label label = new Label (); label.UseMarkup = true; label.Markup = text; label.Xalign = 0.0f; label.Yalign = 0.0f; label.Selectable = true; label.Ellipsize = Pango.EllipsizeMode.End; return label; } private Table info_table; private void AttachRow (int row, InfoEntry entry) { if (!entry.TwoColumns) { info_table.Attach (entry.LabelWidget, 0, 1, (uint)row, (uint)row + 1, AttachOptions.Fill, AttachOptions.Fill, TABLE_XPADDING, TABLE_YPADDING); } info_table.Attach (entry.InfoWidget, entry.TwoColumns ? 0u : 1u, 2, (uint)row, (uint)row + 1, AttachOptions.Expand | AttachOptions.Fill, AttachOptions.Expand | AttachOptions.Fill, TABLE_XPADDING, TABLE_YPADDING); var info_label = entry.InfoWidget as Label; if (info_label != null) info_label.PopulatePopup += HandlePopulatePopup; var info_entry = entry.InfoWidget as Entry; if (info_entry != null) info_entry.PopulatePopup += HandlePopulatePopup; ; } private void UpdateTable () { info_table.Resize ((uint)(head_rows + entries.Count), 2); int i = 0; foreach (var entry in entries) { AttachRow (head_rows + i, entry); i++; } } private void SetEntryWidgetVisibility (InfoEntry entry, bool def) { entry.InfoWidget.Visible = ContextSwitchStrategy.InfoEntryVisible (Context, entry) && def; entry.LabelWidget.Visible = ContextSwitchStrategy.InfoEntryVisible (Context, entry) && def; } private void UpdateEntries () { } const int TABLE_XPADDING = 3; const int TABLE_YPADDING = 3; private Label AttachLabel (Table table, int row_num, Widget entry) { Label label = new Label (String.Empty); label.Xalign = 0; label.Selectable = true; label.Ellipsize = Pango.EllipsizeMode.End; label.Show (); label.PopulatePopup += HandlePopulatePopup; table.Attach (label, 1, 2, (uint)row_num, (uint)row_num + 1, AttachOptions.Expand | AttachOptions.Fill, AttachOptions.Expand | AttachOptions.Fill, (uint)entry.Style.XThickness + TABLE_XPADDING, (uint)entry.Style.YThickness); return label; } private const int head_rows = 0; private void SetupWidgets () { histogram_expander = new Expander (Catalog.GetString ("Histogram")); histogram_expander.Activated += delegate(object sender, EventArgs e) { ContextSwitchStrategy.SetHistogramVisible (Context, histogram_expander.Expanded); UpdateHistogram (); }; histogram_expander.StyleSet += delegate(object sender, StyleSetArgs args) { Gdk.Color c = this.Toplevel.Style.Backgrounds[(int)Gtk.StateType.Active]; histogram.RedColorHint = (byte)(c.Red / 0xff); histogram.GreenColorHint = (byte)(c.Green / 0xff); histogram.BlueColorHint = (byte)(c.Blue / 0xff); histogram.BackgroundColorHint = 0xff; UpdateHistogram (); }; histogram_image = new Gtk.Image (); histogram = new Histogram (); histogram_expander.Add (histogram_image); Add (histogram_expander); info_expander = new Expander (Catalog.GetString ("Image Information")); info_expander.Activated += (sender, e) => { ContextSwitchStrategy.SetInfoBoxVisible (Context, info_expander.Expanded); }; info_table = new Table (head_rows, 2, false) { BorderWidth = 0 }; AddLabelEntry (null, null, null, null, photos => { return String.Format (Catalog.GetString ("{0} Photos"), photos.Length); }); AddLabelEntry (null, Catalog.GetString ("Name"), null, (photo, file) => { return photo.Name ?? String.Empty; }, null); version_list = new ListStore (typeof(IPhotoVersion), typeof(string), typeof(bool)); version_combo = new ComboBox (); CellRendererText version_name_cell = new CellRendererText (); version_name_cell.Ellipsize = Pango.EllipsizeMode.End; version_combo.PackStart (version_name_cell, true); version_combo.SetCellDataFunc (version_name_cell, new CellLayoutDataFunc (VersionNameCellFunc)); version_combo.Model = version_list; version_combo.Changed += OnVersionComboChanged; AddEntry (null, Catalog.GetString ("Version"), null, version_combo, 0.5f, (widget, photo, file) => { version_list.Clear (); version_combo.Changed -= OnVersionComboChanged; int count = 0; foreach (IPhotoVersion version in photo.Versions) { version_list.AppendValues (version, version.Name, true); if (version == photo.DefaultVersion) version_combo.Active = count; count++; } if (count <= 1) { version_combo.Sensitive = false; version_combo.TooltipText = Catalog.GetString ("(No Edits)"); } else { version_combo.Sensitive = true; version_combo.TooltipText = String.Format (Catalog.GetPluralString ("(One Edit)", "({0} Edits)", count - 1), count - 1); } version_combo.Changed += OnVersionComboChanged; }, null); AddLabelEntry ("date", Catalog.GetString ("Date"), Catalog.GetString ("Show Date"), (photo, file) => { return String.Format ("{0}{2}{1}", photo.Time.ToShortDateString (), photo.Time.ToShortTimeString (), Environment.NewLine); }, photos => { IPhoto first = photos[photos.Length - 1]; IPhoto last = photos[0]; if (first.Time.Date == last.Time.Date) { //Note for translators: {0} is a date, {1} and {2} are times. return String.Format (Catalog.GetString ("On {0} between \n{1} and {2}"), first.Time.ToShortDateString (), first.Time.ToShortTimeString (), last.Time.ToShortTimeString ()); } else { return String.Format (Catalog.GetString ("Between {0} \nand {1}"), first.Time.ToShortDateString (), last.Time.ToShortDateString ()); } }); AddLabelEntry ("size", Catalog.GetString ("Size"), Catalog.GetString ("Show Size"), (photo, metadata) => { int width = 0; int height = 0; if (null != metadata.Properties) { width = metadata.Properties.PhotoWidth; height = metadata.Properties.PhotoHeight; } if (width != 0 && height != 0) return String.Format ("{0}x{1}", width, height); return Catalog.GetString ("(Unknown)"); }, null); AddLabelEntry ("exposure", Catalog.GetString ("Exposure"), Catalog.GetString ("Show Exposure"), (photo, metadata) => { var fnumber = metadata.ImageTag.FNumber; var exposure_time = metadata.ImageTag.ExposureTime; var iso_speed = metadata.ImageTag.ISOSpeedRatings; string info = String.Empty; if (fnumber.HasValue && fnumber.Value != 0.0) { info += String.Format ("f/{0:.0} ", fnumber.Value); } if (exposure_time.HasValue) { if (Math.Abs (exposure_time.Value) >= 1.0) { info += String.Format ("{0} sec ", exposure_time.Value); } else { info += String.Format ("1/{0} sec ", (int)(1 / exposure_time.Value)); } } if (iso_speed.HasValue) { info += String.Format ("{0}ISO {1}", Environment.NewLine, iso_speed.Value); } var exif = metadata.ImageTag.Exif; if (exif != null) { var flash = exif.ExifIFD.GetLongValue (0, (ushort)TagLib.IFD.Tags.ExifEntryTag.Flash); if (flash.HasValue) { if ((flash.Value & 0x01) == 0x01) info += String.Format (", {0}", Catalog.GetString ("flash fired")); else info += String.Format (", {0}", Catalog.GetString ("flash didn't fire")); } } if (info == String.Empty) return Catalog.GetString ("(None)"); return info; }, null); AddLabelEntry ("focal_length", Catalog.GetString ("Focal Length"), Catalog.GetString ("Show Focal Length"), false, (photo, metadata) => { var focal_length = metadata.ImageTag.FocalLength; if (focal_length == null) return Catalog.GetString ("(Unknown)"); return String.Format ("{0} mm", focal_length.Value); }, null); AddLabelEntry ("camera", Catalog.GetString ("Camera"), Catalog.GetString ("Show Camera"), false, (photo, metadata) => { return metadata.ImageTag.Model ?? Catalog.GetString ("(Unknown)"); }, null); AddLabelEntry ("creator", Catalog.GetString ("Creator"), Catalog.GetString ("Show Creator"), (photo, metadata) => { return metadata.ImageTag.Creator ?? Catalog.GetString ("(Unknown)"); }, null); AddLabelEntry ("file_size", Catalog.GetString ("File Size"), Catalog.GetString ("Show File Size"), false, (photo, metadata) => { try { GFile file = FileFactory.NewForUri (photo.DefaultVersion.Uri); GFileInfo file_info = file.QueryInfo ("standard::size", FileQueryInfoFlags.None, null); return Format.SizeForDisplay (file_info.Size); } catch (GLib.GException e) { Hyena.Log.DebugException (e); return Catalog.GetString ("(File read error)"); } }, null); var rating_entry = new RatingEntry { HasFrame = false, AlwaysShowEmptyStars = true }; rating_entry.Changed += HandleRatingChanged; var rating_align = new Gtk.Alignment (0, 0, 0, 0); rating_align.Add (rating_entry); AddEntry ("rating", Catalog.GetString ("Rating"), Catalog.GetString ("Show Rating"), rating_align, false, (widget, photo, metadata) => { ((widget as Alignment).Child as RatingEntry).Value = (int) photo.Rating; }, null); AddEntry ("tag", null, Catalog.GetString ("Show Tags"), new TagView (), false, (widget, photo, metadata) => { (widget as TagView).Current = photo; }, null); UpdateTable (); EventBox eb = new EventBox (); eb.Add (info_table); info_expander.Add (eb); eb.ButtonPressEvent += HandleButtonPressEvent; Add (info_expander); } public bool Update () { if (Photos == null || Photos.Length == 0) { Hide (); } else if (Photos.Length == 1) { var photo = Photos[0]; histogram_expander.Visible = true; UpdateHistogram(); using (var metadata = Metadata.Parse (photo.DefaultVersion.Uri)) { foreach (var entry in entries) { bool is_single = (entry.SetSingle != null); if (is_single) entry.SetSingle (entry.InfoWidget, photo, metadata); SetEntryWidgetVisibility (entry, is_single); } } Show (); } else if (Photos.Length > 1) { foreach (var entry in entries) { bool is_multiple = (entry.SetMultiple != null); if (is_multiple) entry.SetMultiple (entry.InfoWidget, Photos); SetEntryWidgetVisibility (entry, is_multiple); } histogram_expander.Visible = false; Show (); } return false; } void VersionNameCellFunc (CellLayout cell_layout, CellRenderer cell, TreeModel tree_model, TreeIter iter) { string name = (string)tree_model.GetValue (iter, 1); (cell as CellRendererText).Text = name; cell.Sensitive = (bool)tree_model.GetValue (iter, 2); } void OnVersionComboChanged (object o, EventArgs e) { ComboBox combo = o as ComboBox; if (combo == null) return; TreeIter iter; if (combo.GetActiveIter (out iter)) VersionChanged (this, (IPhotoVersion)version_list.GetValue (iter, 0)); } private Gdk.Pixbuf histogram_hint; private void UpdateHistogram () { if (histogram_expander.Expanded) histogram_delay.Start (); } public void UpdateHistogram (Gdk.Pixbuf pixbuf) { histogram_hint = pixbuf; UpdateHistogram (); } private bool DelayedUpdateHistogram () { if (Photos.Length == 0) return false; IPhoto photo = Photos[0]; Gdk.Pixbuf hint = histogram_hint; histogram_hint = null; int max = histogram_expander.Allocation.Width; try { if (hint == null) using (var img = ImageFile.Create (photo.DefaultVersion.Uri)) { hint = img.Load (256, 256); } histogram_image.Pixbuf = histogram.Generate (hint, max); hint.Dispose (); } catch (System.Exception e) { Hyena.Log.Debug (e.StackTrace); using (Gdk.Pixbuf empty = new Gdk.Pixbuf (Gdk.Colorspace.Rgb, true, 8, 256, 256)) { empty.Fill (0x0); histogram_image.Pixbuf = histogram.Generate (empty, max); } } return false; } // Context switching private void HandleContextChanged (object sender, EventArgs args) { bool infobox_visible = ContextSwitchStrategy.InfoBoxVisible (Context); info_expander.Expanded = infobox_visible; bool histogram_visible = ContextSwitchStrategy.HistogramVisible (Context); histogram_expander.Expanded = histogram_visible; if (infobox_visible) update_delay.Start (); } public void HandleMainWindowViewModeChanged (object o, EventArgs args) { MainWindow.ModeType mode = App.Instance.Organizer.ViewMode; if (mode == MainWindow.ModeType.IconView) Context = ViewContext.Library; else if (mode == MainWindow.ModeType.PhotoView) { Context = ViewContext.Edit; } } void HandleButtonPressEvent (object sender, ButtonPressEventArgs args) { if (args.Event.Button == 3) { Menu popup_menu = new Menu (); AddMenuItems (popup_menu); if (args.Event != null) popup_menu.Popup (null, null, null, args.Event.Button, args.Event.Time); else popup_menu.Popup (null, null, null, 0, Gtk.Global.CurrentEventTime); args.RetVal = true; } } void HandlePopulatePopup (object sender, PopulatePopupArgs args) { AddMenuItems (args.Menu); args.RetVal = true; } private void AddMenuItems (Menu popup_menu) { var items = new Dictionary <MenuItem, InfoEntry> (); if (popup_menu.Children.Length > 0 && entries.Count > 0) { GtkUtil.MakeMenuSeparator (popup_menu); } foreach (var entry in entries) { if (entry.AlwaysVisible) continue; var item = GtkUtil.MakeCheckMenuItem (popup_menu, entry.Description, (sender, args) => { ContextSwitchStrategy.SetInfoEntryVisible (Context, items [sender as CheckMenuItem], (sender as CheckMenuItem).Active); Update (); }, true, ContextSwitchStrategy.InfoEntryVisible (Context, entry), false); items.Add (item, entry); } } private void HandleMenuItemSelected (object sender, EventArgs args) { } #region Constructor public InfoBox () : base(false, 0) { ContextSwitchStrategy = new MRUInfoBoxContextSwitchStrategy (); ContextChanged += HandleContextChanged; SetupWidgets (); update_delay = new DelayedOperation (Update); update_delay.Start (); histogram_delay = new DelayedOperation (DelayedUpdateHistogram); BorderWidth = 2; Hide (); } #endregion } // Decides whether infobox / histogram should be shown for each context. Implemented // using the Strategy pattern, to make it swappable easily, in case the // default MRUInfoBoxContextSwitchStrategy is not sufficiently usable. public abstract class InfoBoxContextSwitchStrategy { public abstract bool InfoBoxVisible (ViewContext context); public abstract bool HistogramVisible (ViewContext context); public abstract bool InfoEntryVisible (ViewContext context, InfoBox.InfoEntry entry); public abstract void SetInfoBoxVisible (ViewContext context, bool visible); public abstract void SetHistogramVisible (ViewContext context, bool visible); public abstract void SetInfoEntryVisible (ViewContext context, InfoBox.InfoEntry entry, bool visible); } // Values are stored as strings, because bool is not nullable through Preferences. public class MRUInfoBoxContextSwitchStrategy : InfoBoxContextSwitchStrategy { public const string PREF_PREFIX = Preferences.APP_FSPOT + "ui"; private string PrefKeyForContext (ViewContext context, string item) { return String.Format ("{0}/{1}_visible/{2}", PREF_PREFIX, item, context); } private string PrefKeyForContext (ViewContext context, string parent, string item) { return String.Format ("{0}/{1}_visible/{2}/{3}", PREF_PREFIX, parent, item, context); } private bool VisibilityForContext (ViewContext context, string item, bool default_value) { string visible = Preferences.Get<string> (PrefKeyForContext (context, item)); if (visible == null) return default_value; else return visible == "1"; } private bool VisibilityForContext (ViewContext context, string parent, string item, bool default_value) { string visible = Preferences.Get<string> (PrefKeyForContext (context, parent, item)); if (visible == null) return default_value; else return visible == "1"; } private void SetVisibilityForContext (ViewContext context, string item, bool visible) { Preferences.Set (PrefKeyForContext (context, item), visible ? "1" : "0"); } private void SetVisibilityForContext (ViewContext context, string parent, string item, bool visible) { Preferences.Set (PrefKeyForContext (context, parent, item), visible ? "1" : "0"); } public override bool InfoBoxVisible (ViewContext context) { return VisibilityForContext (context, "infobox", true); } public override bool HistogramVisible (ViewContext context) { return VisibilityForContext (context, "histogram", true); } public override bool InfoEntryVisible (ViewContext context, InfoBox.InfoEntry entry) { if (entry.AlwaysVisible) return true; return VisibilityForContext (context, "infobox", entry.Id, true); } public override void SetInfoBoxVisible (ViewContext context, bool visible) { SetVisibilityForContext (context, "infobox", visible); } public override void SetHistogramVisible (ViewContext context, bool visible) { SetVisibilityForContext (context, "histogram", visible); } public override void SetInfoEntryVisible (ViewContext context, InfoBox.InfoEntry entry, bool visible) { Hyena.Log.DebugFormat ("Set Visibility for Entry {0} to {1}", entry.Id, visible); if (entry.AlwaysVisible) throw new Exception ("entry visibility cannot be set"); SetVisibilityForContext (context, "infobox", entry.Id, visible); } } }
#if ENABLE_PLAYFABADMIN_API using System; using PlayFab.AdminModels; using PlayFab.Internal; using PlayFab.Json; namespace PlayFab { /// <summary> /// APIs for managing title configurations, uploaded Game Server code executables, and user data /// </summary> public static class PlayFabAdminAPI { /// <summary> /// Bans users by PlayFab ID with optional IP address, or MAC address for the provided game. /// </summary> public static void BanUsers(BanUsersRequest request, Action<BanUsersResult> resultCallback, Action<PlayFabError> errorCallback, object customData = null) { if (PlayFabSettings.DeveloperSecretKey == null) throw new Exception("Must have PlayFabSettings.DeveloperSecretKey set to call this method"); PlayFabHttp.MakeApiCall("/Admin/BanUsers", request, AuthType.DevSecretKey, resultCallback, errorCallback, customData); } /// <summary> /// Retrieves the relevant details for a specified user, based upon a match against a supplied unique identifier /// </summary> public static void GetUserAccountInfo(LookupUserAccountInfoRequest request, Action<LookupUserAccountInfoResult> resultCallback, Action<PlayFabError> errorCallback, object customData = null) { if (PlayFabSettings.DeveloperSecretKey == null) throw new Exception("Must have PlayFabSettings.DeveloperSecretKey set to call this method"); PlayFabHttp.MakeApiCall("/Admin/GetUserAccountInfo", request, AuthType.DevSecretKey, resultCallback, errorCallback, customData); } /// <summary> /// Gets all bans for a user. /// </summary> public static void GetUserBans(GetUserBansRequest request, Action<GetUserBansResult> resultCallback, Action<PlayFabError> errorCallback, object customData = null) { if (PlayFabSettings.DeveloperSecretKey == null) throw new Exception("Must have PlayFabSettings.DeveloperSecretKey set to call this method"); PlayFabHttp.MakeApiCall("/Admin/GetUserBans", request, AuthType.DevSecretKey, resultCallback, errorCallback, customData); } /// <summary> /// Resets all title-specific information about a particular account, including user data, virtual currency balances, inventory, purchase history, and statistics /// </summary> public static void ResetUsers(ResetUsersRequest request, Action<BlankResult> resultCallback, Action<PlayFabError> errorCallback, object customData = null) { if (PlayFabSettings.DeveloperSecretKey == null) throw new Exception("Must have PlayFabSettings.DeveloperSecretKey set to call this method"); PlayFabHttp.MakeApiCall("/Admin/ResetUsers", request, AuthType.DevSecretKey, resultCallback, errorCallback, customData); } /// <summary> /// Revoke all active bans for a user. /// </summary> public static void RevokeAllBansForUser(RevokeAllBansForUserRequest request, Action<RevokeAllBansForUserResult> resultCallback, Action<PlayFabError> errorCallback, object customData = null) { if (PlayFabSettings.DeveloperSecretKey == null) throw new Exception("Must have PlayFabSettings.DeveloperSecretKey set to call this method"); PlayFabHttp.MakeApiCall("/Admin/RevokeAllBansForUser", request, AuthType.DevSecretKey, resultCallback, errorCallback, customData); } /// <summary> /// Revoke all active bans specified with BanId. /// </summary> public static void RevokeBans(RevokeBansRequest request, Action<RevokeBansResult> resultCallback, Action<PlayFabError> errorCallback, object customData = null) { if (PlayFabSettings.DeveloperSecretKey == null) throw new Exception("Must have PlayFabSettings.DeveloperSecretKey set to call this method"); PlayFabHttp.MakeApiCall("/Admin/RevokeBans", request, AuthType.DevSecretKey, resultCallback, errorCallback, customData); } /// <summary> /// Forces an email to be sent to the registered email address for the specified account, with a link allowing the user to change the password /// </summary> public static void SendAccountRecoveryEmail(SendAccountRecoveryEmailRequest request, Action<SendAccountRecoveryEmailResult> resultCallback, Action<PlayFabError> errorCallback, object customData = null) { if (PlayFabSettings.DeveloperSecretKey == null) throw new Exception("Must have PlayFabSettings.DeveloperSecretKey set to call this method"); PlayFabHttp.MakeApiCall("/Admin/SendAccountRecoveryEmail", request, AuthType.DevSecretKey, resultCallback, errorCallback, customData); } /// <summary> /// Updates information of a list of existing bans specified with Ban Ids. /// </summary> public static void UpdateBans(UpdateBansRequest request, Action<UpdateBansResult> resultCallback, Action<PlayFabError> errorCallback, object customData = null) { if (PlayFabSettings.DeveloperSecretKey == null) throw new Exception("Must have PlayFabSettings.DeveloperSecretKey set to call this method"); PlayFabHttp.MakeApiCall("/Admin/UpdateBans", request, AuthType.DevSecretKey, resultCallback, errorCallback, customData); } /// <summary> /// Updates the title specific display name for a user /// </summary> public static void UpdateUserTitleDisplayName(UpdateUserTitleDisplayNameRequest request, Action<UpdateUserTitleDisplayNameResult> resultCallback, Action<PlayFabError> errorCallback, object customData = null) { if (PlayFabSettings.DeveloperSecretKey == null) throw new Exception("Must have PlayFabSettings.DeveloperSecretKey set to call this method"); PlayFabHttp.MakeApiCall("/Admin/UpdateUserTitleDisplayName", request, AuthType.DevSecretKey, resultCallback, errorCallback, customData); } /// <summary> /// Adds a new player statistic configuration to the title, optionally allowing the developer to specify a reset interval and an aggregation method. /// </summary> public static void CreatePlayerStatisticDefinition(CreatePlayerStatisticDefinitionRequest request, Action<CreatePlayerStatisticDefinitionResult> resultCallback, Action<PlayFabError> errorCallback, object customData = null) { if (PlayFabSettings.DeveloperSecretKey == null) throw new Exception("Must have PlayFabSettings.DeveloperSecretKey set to call this method"); PlayFabHttp.MakeApiCall("/Admin/CreatePlayerStatisticDefinition", request, AuthType.DevSecretKey, resultCallback, errorCallback, customData); } /// <summary> /// Deletes the users for the provided game. Deletes custom data, all account linkages, and statistics. This method does not remove the player's event history, login history, inventory items, nor virtual currencies. /// </summary> public static void DeleteUsers(DeleteUsersRequest request, Action<DeleteUsersResult> resultCallback, Action<PlayFabError> errorCallback, object customData = null) { if (PlayFabSettings.DeveloperSecretKey == null) throw new Exception("Must have PlayFabSettings.DeveloperSecretKey set to call this method"); PlayFabHttp.MakeApiCall("/Admin/DeleteUsers", request, AuthType.DevSecretKey, resultCallback, errorCallback, customData); } /// <summary> /// Retrieves a download URL for the requested report /// </summary> public static void GetDataReport(GetDataReportRequest request, Action<GetDataReportResult> resultCallback, Action<PlayFabError> errorCallback, object customData = null) { if (PlayFabSettings.DeveloperSecretKey == null) throw new Exception("Must have PlayFabSettings.DeveloperSecretKey set to call this method"); PlayFabHttp.MakeApiCall("/Admin/GetDataReport", request, AuthType.DevSecretKey, resultCallback, errorCallback, customData); } /// <summary> /// Retrieves the configuration information for all player statistics defined in the title, regardless of whether they have a reset interval. /// </summary> public static void GetPlayerStatisticDefinitions(GetPlayerStatisticDefinitionsRequest request, Action<GetPlayerStatisticDefinitionsResult> resultCallback, Action<PlayFabError> errorCallback, object customData = null) { if (PlayFabSettings.DeveloperSecretKey == null) throw new Exception("Must have PlayFabSettings.DeveloperSecretKey set to call this method"); PlayFabHttp.MakeApiCall("/Admin/GetPlayerStatisticDefinitions", request, AuthType.DevSecretKey, resultCallback, errorCallback, customData); } /// <summary> /// Retrieves the information on the available versions of the specified statistic. /// </summary> public static void GetPlayerStatisticVersions(GetPlayerStatisticVersionsRequest request, Action<GetPlayerStatisticVersionsResult> resultCallback, Action<PlayFabError> errorCallback, object customData = null) { if (PlayFabSettings.DeveloperSecretKey == null) throw new Exception("Must have PlayFabSettings.DeveloperSecretKey set to call this method"); PlayFabHttp.MakeApiCall("/Admin/GetPlayerStatisticVersions", request, AuthType.DevSecretKey, resultCallback, errorCallback, customData); } /// <summary> /// Retrieves the title-specific custom data for the user which is readable and writable by the client /// </summary> public static void GetUserData(GetUserDataRequest request, Action<GetUserDataResult> resultCallback, Action<PlayFabError> errorCallback, object customData = null) { if (PlayFabSettings.DeveloperSecretKey == null) throw new Exception("Must have PlayFabSettings.DeveloperSecretKey set to call this method"); PlayFabHttp.MakeApiCall("/Admin/GetUserData", request, AuthType.DevSecretKey, resultCallback, errorCallback, customData); } /// <summary> /// Retrieves the title-specific custom data for the user which cannot be accessed by the client /// </summary> public static void GetUserInternalData(GetUserDataRequest request, Action<GetUserDataResult> resultCallback, Action<PlayFabError> errorCallback, object customData = null) { if (PlayFabSettings.DeveloperSecretKey == null) throw new Exception("Must have PlayFabSettings.DeveloperSecretKey set to call this method"); PlayFabHttp.MakeApiCall("/Admin/GetUserInternalData", request, AuthType.DevSecretKey, resultCallback, errorCallback, customData); } /// <summary> /// Retrieves the publisher-specific custom data for the user which is readable and writable by the client /// </summary> public static void GetUserPublisherData(GetUserDataRequest request, Action<GetUserDataResult> resultCallback, Action<PlayFabError> errorCallback, object customData = null) { if (PlayFabSettings.DeveloperSecretKey == null) throw new Exception("Must have PlayFabSettings.DeveloperSecretKey set to call this method"); PlayFabHttp.MakeApiCall("/Admin/GetUserPublisherData", request, AuthType.DevSecretKey, resultCallback, errorCallback, customData); } /// <summary> /// Retrieves the publisher-specific custom data for the user which cannot be accessed by the client /// </summary> public static void GetUserPublisherInternalData(GetUserDataRequest request, Action<GetUserDataResult> resultCallback, Action<PlayFabError> errorCallback, object customData = null) { if (PlayFabSettings.DeveloperSecretKey == null) throw new Exception("Must have PlayFabSettings.DeveloperSecretKey set to call this method"); PlayFabHttp.MakeApiCall("/Admin/GetUserPublisherInternalData", request, AuthType.DevSecretKey, resultCallback, errorCallback, customData); } /// <summary> /// Retrieves the publisher-specific custom data for the user which can only be read by the client /// </summary> public static void GetUserPublisherReadOnlyData(GetUserDataRequest request, Action<GetUserDataResult> resultCallback, Action<PlayFabError> errorCallback, object customData = null) { if (PlayFabSettings.DeveloperSecretKey == null) throw new Exception("Must have PlayFabSettings.DeveloperSecretKey set to call this method"); PlayFabHttp.MakeApiCall("/Admin/GetUserPublisherReadOnlyData", request, AuthType.DevSecretKey, resultCallback, errorCallback, customData); } /// <summary> /// Retrieves the title-specific custom data for the user which can only be read by the client /// </summary> public static void GetUserReadOnlyData(GetUserDataRequest request, Action<GetUserDataResult> resultCallback, Action<PlayFabError> errorCallback, object customData = null) { if (PlayFabSettings.DeveloperSecretKey == null) throw new Exception("Must have PlayFabSettings.DeveloperSecretKey set to call this method"); PlayFabHttp.MakeApiCall("/Admin/GetUserReadOnlyData", request, AuthType.DevSecretKey, resultCallback, errorCallback, customData); } /// <summary> /// Resets the indicated statistic, removing all player entries for it and backing up the old values. /// </summary> public static void IncrementPlayerStatisticVersion(IncrementPlayerStatisticVersionRequest request, Action<IncrementPlayerStatisticVersionResult> resultCallback, Action<PlayFabError> errorCallback, object customData = null) { if (PlayFabSettings.DeveloperSecretKey == null) throw new Exception("Must have PlayFabSettings.DeveloperSecretKey set to call this method"); PlayFabHttp.MakeApiCall("/Admin/IncrementPlayerStatisticVersion", request, AuthType.DevSecretKey, resultCallback, errorCallback, customData); } /// <summary> /// Attempts to process an order refund through the original real money payment provider. /// </summary> public static void RefundPurchase(RefundPurchaseRequest request, Action<RefundPurchaseResponse> resultCallback, Action<PlayFabError> errorCallback, object customData = null) { if (PlayFabSettings.DeveloperSecretKey == null) throw new Exception("Must have PlayFabSettings.DeveloperSecretKey set to call this method"); PlayFabHttp.MakeApiCall("/Admin/RefundPurchase", request, AuthType.DevSecretKey, resultCallback, errorCallback, customData); } /// <summary> /// Completely removes all statistics for the specified user, for the current game /// </summary> public static void ResetUserStatistics(ResetUserStatisticsRequest request, Action<ResetUserStatisticsResult> resultCallback, Action<PlayFabError> errorCallback, object customData = null) { if (PlayFabSettings.DeveloperSecretKey == null) throw new Exception("Must have PlayFabSettings.DeveloperSecretKey set to call this method"); PlayFabHttp.MakeApiCall("/Admin/ResetUserStatistics", request, AuthType.DevSecretKey, resultCallback, errorCallback, customData); } /// <summary> /// Attempts to resolve a dispute with the original order's payment provider. /// </summary> public static void ResolvePurchaseDispute(ResolvePurchaseDisputeRequest request, Action<ResolvePurchaseDisputeResponse> resultCallback, Action<PlayFabError> errorCallback, object customData = null) { if (PlayFabSettings.DeveloperSecretKey == null) throw new Exception("Must have PlayFabSettings.DeveloperSecretKey set to call this method"); PlayFabHttp.MakeApiCall("/Admin/ResolvePurchaseDispute", request, AuthType.DevSecretKey, resultCallback, errorCallback, customData); } /// <summary> /// Updates a player statistic configuration for the title, optionally allowing the developer to specify a reset interval. /// </summary> public static void UpdatePlayerStatisticDefinition(UpdatePlayerStatisticDefinitionRequest request, Action<UpdatePlayerStatisticDefinitionResult> resultCallback, Action<PlayFabError> errorCallback, object customData = null) { if (PlayFabSettings.DeveloperSecretKey == null) throw new Exception("Must have PlayFabSettings.DeveloperSecretKey set to call this method"); PlayFabHttp.MakeApiCall("/Admin/UpdatePlayerStatisticDefinition", request, AuthType.DevSecretKey, resultCallback, errorCallback, customData); } /// <summary> /// Updates the title-specific custom data for the user which is readable and writable by the client /// </summary> public static void UpdateUserData(UpdateUserDataRequest request, Action<UpdateUserDataResult> resultCallback, Action<PlayFabError> errorCallback, object customData = null) { if (PlayFabSettings.DeveloperSecretKey == null) throw new Exception("Must have PlayFabSettings.DeveloperSecretKey set to call this method"); PlayFabHttp.MakeApiCall("/Admin/UpdateUserData", request, AuthType.DevSecretKey, resultCallback, errorCallback, customData); } /// <summary> /// Updates the title-specific custom data for the user which cannot be accessed by the client /// </summary> public static void UpdateUserInternalData(UpdateUserInternalDataRequest request, Action<UpdateUserDataResult> resultCallback, Action<PlayFabError> errorCallback, object customData = null) { if (PlayFabSettings.DeveloperSecretKey == null) throw new Exception("Must have PlayFabSettings.DeveloperSecretKey set to call this method"); PlayFabHttp.MakeApiCall("/Admin/UpdateUserInternalData", request, AuthType.DevSecretKey, resultCallback, errorCallback, customData); } /// <summary> /// Updates the publisher-specific custom data for the user which is readable and writable by the client /// </summary> public static void UpdateUserPublisherData(UpdateUserDataRequest request, Action<UpdateUserDataResult> resultCallback, Action<PlayFabError> errorCallback, object customData = null) { if (PlayFabSettings.DeveloperSecretKey == null) throw new Exception("Must have PlayFabSettings.DeveloperSecretKey set to call this method"); PlayFabHttp.MakeApiCall("/Admin/UpdateUserPublisherData", request, AuthType.DevSecretKey, resultCallback, errorCallback, customData); } /// <summary> /// Updates the publisher-specific custom data for the user which cannot be accessed by the client /// </summary> public static void UpdateUserPublisherInternalData(UpdateUserInternalDataRequest request, Action<UpdateUserDataResult> resultCallback, Action<PlayFabError> errorCallback, object customData = null) { if (PlayFabSettings.DeveloperSecretKey == null) throw new Exception("Must have PlayFabSettings.DeveloperSecretKey set to call this method"); PlayFabHttp.MakeApiCall("/Admin/UpdateUserPublisherInternalData", request, AuthType.DevSecretKey, resultCallback, errorCallback, customData); } /// <summary> /// Updates the publisher-specific custom data for the user which can only be read by the client /// </summary> public static void UpdateUserPublisherReadOnlyData(UpdateUserDataRequest request, Action<UpdateUserDataResult> resultCallback, Action<PlayFabError> errorCallback, object customData = null) { if (PlayFabSettings.DeveloperSecretKey == null) throw new Exception("Must have PlayFabSettings.DeveloperSecretKey set to call this method"); PlayFabHttp.MakeApiCall("/Admin/UpdateUserPublisherReadOnlyData", request, AuthType.DevSecretKey, resultCallback, errorCallback, customData); } /// <summary> /// Updates the title-specific custom data for the user which can only be read by the client /// </summary> public static void UpdateUserReadOnlyData(UpdateUserDataRequest request, Action<UpdateUserDataResult> resultCallback, Action<PlayFabError> errorCallback, object customData = null) { if (PlayFabSettings.DeveloperSecretKey == null) throw new Exception("Must have PlayFabSettings.DeveloperSecretKey set to call this method"); PlayFabHttp.MakeApiCall("/Admin/UpdateUserReadOnlyData", request, AuthType.DevSecretKey, resultCallback, errorCallback, customData); } /// <summary> /// Adds a new news item to the title's news feed /// </summary> public static void AddNews(AddNewsRequest request, Action<AddNewsResult> resultCallback, Action<PlayFabError> errorCallback, object customData = null) { if (PlayFabSettings.DeveloperSecretKey == null) throw new Exception("Must have PlayFabSettings.DeveloperSecretKey set to call this method"); PlayFabHttp.MakeApiCall("/Admin/AddNews", request, AuthType.DevSecretKey, resultCallback, errorCallback, customData); } /// <summary> /// Adds one or more virtual currencies to the set defined for the title. Virtual Currencies have a maximum value of 2,147,483,647 when granted to a player. Any value over that will be discarded. /// </summary> public static void AddVirtualCurrencyTypes(AddVirtualCurrencyTypesRequest request, Action<BlankResult> resultCallback, Action<PlayFabError> errorCallback, object customData = null) { if (PlayFabSettings.DeveloperSecretKey == null) throw new Exception("Must have PlayFabSettings.DeveloperSecretKey set to call this method"); PlayFabHttp.MakeApiCall("/Admin/AddVirtualCurrencyTypes", request, AuthType.DevSecretKey, resultCallback, errorCallback, customData); } /// <summary> /// Deletes an existing virtual item store /// </summary> public static void DeleteStore(DeleteStoreRequest request, Action<DeleteStoreResult> resultCallback, Action<PlayFabError> errorCallback, object customData = null) { if (PlayFabSettings.DeveloperSecretKey == null) throw new Exception("Must have PlayFabSettings.DeveloperSecretKey set to call this method"); PlayFabHttp.MakeApiCall("/Admin/DeleteStore", request, AuthType.DevSecretKey, resultCallback, errorCallback, customData); } /// <summary> /// Retrieves the specified version of the title's catalog of virtual goods, including all defined properties /// </summary> public static void GetCatalogItems(GetCatalogItemsRequest request, Action<GetCatalogItemsResult> resultCallback, Action<PlayFabError> errorCallback, object customData = null) { if (PlayFabSettings.DeveloperSecretKey == null) throw new Exception("Must have PlayFabSettings.DeveloperSecretKey set to call this method"); PlayFabHttp.MakeApiCall("/Admin/GetCatalogItems", request, AuthType.DevSecretKey, resultCallback, errorCallback, customData); } /// <summary> /// Retrieves the key-value store of custom publisher settings /// </summary> public static void GetPublisherData(GetPublisherDataRequest request, Action<GetPublisherDataResult> resultCallback, Action<PlayFabError> errorCallback, object customData = null) { if (PlayFabSettings.DeveloperSecretKey == null) throw new Exception("Must have PlayFabSettings.DeveloperSecretKey set to call this method"); PlayFabHttp.MakeApiCall("/Admin/GetPublisherData", request, AuthType.DevSecretKey, resultCallback, errorCallback, customData); } /// <summary> /// Retrieves the random drop table configuration for the title /// </summary> public static void GetRandomResultTables(GetRandomResultTablesRequest request, Action<GetRandomResultTablesResult> resultCallback, Action<PlayFabError> errorCallback, object customData = null) { if (PlayFabSettings.DeveloperSecretKey == null) throw new Exception("Must have PlayFabSettings.DeveloperSecretKey set to call this method"); PlayFabHttp.MakeApiCall("/Admin/GetRandomResultTables", request, AuthType.DevSecretKey, resultCallback, errorCallback, customData); } /// <summary> /// Retrieves the set of items defined for the specified store, including all prices defined /// </summary> public static void GetStoreItems(GetStoreItemsRequest request, Action<GetStoreItemsResult> resultCallback, Action<PlayFabError> errorCallback, object customData = null) { if (PlayFabSettings.DeveloperSecretKey == null) throw new Exception("Must have PlayFabSettings.DeveloperSecretKey set to call this method"); PlayFabHttp.MakeApiCall("/Admin/GetStoreItems", request, AuthType.DevSecretKey, resultCallback, errorCallback, customData); } /// <summary> /// Retrieves the key-value store of custom title settings which can be read by the client /// </summary> public static void GetTitleData(GetTitleDataRequest request, Action<GetTitleDataResult> resultCallback, Action<PlayFabError> errorCallback, object customData = null) { if (PlayFabSettings.DeveloperSecretKey == null) throw new Exception("Must have PlayFabSettings.DeveloperSecretKey set to call this method"); PlayFabHttp.MakeApiCall("/Admin/GetTitleData", request, AuthType.DevSecretKey, resultCallback, errorCallback, customData); } /// <summary> /// Retrieves the key-value store of custom title settings which cannot be read by the client /// </summary> public static void GetTitleInternalData(GetTitleDataRequest request, Action<GetTitleDataResult> resultCallback, Action<PlayFabError> errorCallback, object customData = null) { if (PlayFabSettings.DeveloperSecretKey == null) throw new Exception("Must have PlayFabSettings.DeveloperSecretKey set to call this method"); PlayFabHttp.MakeApiCall("/Admin/GetTitleInternalData", request, AuthType.DevSecretKey, resultCallback, errorCallback, customData); } /// <summary> /// Retuns the list of all defined virtual currencies for the title /// </summary> public static void ListVirtualCurrencyTypes(ListVirtualCurrencyTypesRequest request, Action<ListVirtualCurrencyTypesResult> resultCallback, Action<PlayFabError> errorCallback, object customData = null) { if (PlayFabSettings.DeveloperSecretKey == null) throw new Exception("Must have PlayFabSettings.DeveloperSecretKey set to call this method"); PlayFabHttp.MakeApiCall("/Admin/ListVirtualCurrencyTypes", request, AuthType.DevSecretKey, resultCallback, errorCallback, customData); } /// <summary> /// Removes one or more virtual currencies from the set defined for the title. /// </summary> public static void RemoveVirtualCurrencyTypes(RemoveVirtualCurrencyTypesRequest request, Action<BlankResult> resultCallback, Action<PlayFabError> errorCallback, object customData = null) { if (PlayFabSettings.DeveloperSecretKey == null) throw new Exception("Must have PlayFabSettings.DeveloperSecretKey set to call this method"); PlayFabHttp.MakeApiCall("/Admin/RemoveVirtualCurrencyTypes", request, AuthType.DevSecretKey, resultCallback, errorCallback, customData); } /// <summary> /// Creates the catalog configuration of all virtual goods for the specified catalog version /// </summary> public static void SetCatalogItems(UpdateCatalogItemsRequest request, Action<UpdateCatalogItemsResult> resultCallback, Action<PlayFabError> errorCallback, object customData = null) { if (PlayFabSettings.DeveloperSecretKey == null) throw new Exception("Must have PlayFabSettings.DeveloperSecretKey set to call this method"); PlayFabHttp.MakeApiCall("/Admin/SetCatalogItems", request, AuthType.DevSecretKey, resultCallback, errorCallback, customData); } /// <summary> /// Sets all the items in one virtual store /// </summary> public static void SetStoreItems(UpdateStoreItemsRequest request, Action<UpdateStoreItemsResult> resultCallback, Action<PlayFabError> errorCallback, object customData = null) { if (PlayFabSettings.DeveloperSecretKey == null) throw new Exception("Must have PlayFabSettings.DeveloperSecretKey set to call this method"); PlayFabHttp.MakeApiCall("/Admin/SetStoreItems", request, AuthType.DevSecretKey, resultCallback, errorCallback, customData); } /// <summary> /// Creates and updates the key-value store of custom title settings which can be read by the client /// </summary> public static void SetTitleData(SetTitleDataRequest request, Action<SetTitleDataResult> resultCallback, Action<PlayFabError> errorCallback, object customData = null) { if (PlayFabSettings.DeveloperSecretKey == null) throw new Exception("Must have PlayFabSettings.DeveloperSecretKey set to call this method"); PlayFabHttp.MakeApiCall("/Admin/SetTitleData", request, AuthType.DevSecretKey, resultCallback, errorCallback, customData); } /// <summary> /// Updates the key-value store of custom title settings which cannot be read by the client /// </summary> public static void SetTitleInternalData(SetTitleDataRequest request, Action<SetTitleDataResult> resultCallback, Action<PlayFabError> errorCallback, object customData = null) { if (PlayFabSettings.DeveloperSecretKey == null) throw new Exception("Must have PlayFabSettings.DeveloperSecretKey set to call this method"); PlayFabHttp.MakeApiCall("/Admin/SetTitleInternalData", request, AuthType.DevSecretKey, resultCallback, errorCallback, customData); } /// <summary> /// Sets the Amazon Resource Name (ARN) for iOS and Android push notifications. Documentation on the exact restrictions can be found at: http://docs.aws.amazon.com/sns/latest/api/API_CreatePlatformApplication.html. Currently, Amazon device Messaging is not supported. /// </summary> public static void SetupPushNotification(SetupPushNotificationRequest request, Action<SetupPushNotificationResult> resultCallback, Action<PlayFabError> errorCallback, object customData = null) { if (PlayFabSettings.DeveloperSecretKey == null) throw new Exception("Must have PlayFabSettings.DeveloperSecretKey set to call this method"); PlayFabHttp.MakeApiCall("/Admin/SetupPushNotification", request, AuthType.DevSecretKey, resultCallback, errorCallback, customData); } /// <summary> /// Updates the catalog configuration for virtual goods in the specified catalog version /// </summary> public static void UpdateCatalogItems(UpdateCatalogItemsRequest request, Action<UpdateCatalogItemsResult> resultCallback, Action<PlayFabError> errorCallback, object customData = null) { if (PlayFabSettings.DeveloperSecretKey == null) throw new Exception("Must have PlayFabSettings.DeveloperSecretKey set to call this method"); PlayFabHttp.MakeApiCall("/Admin/UpdateCatalogItems", request, AuthType.DevSecretKey, resultCallback, errorCallback, customData); } /// <summary> /// Updates the random drop table configuration for the title /// </summary> public static void UpdateRandomResultTables(UpdateRandomResultTablesRequest request, Action<UpdateRandomResultTablesResult> resultCallback, Action<PlayFabError> errorCallback, object customData = null) { if (PlayFabSettings.DeveloperSecretKey == null) throw new Exception("Must have PlayFabSettings.DeveloperSecretKey set to call this method"); PlayFabHttp.MakeApiCall("/Admin/UpdateRandomResultTables", request, AuthType.DevSecretKey, resultCallback, errorCallback, customData); } /// <summary> /// Updates an existing virtual item store with new or modified items /// </summary> public static void UpdateStoreItems(UpdateStoreItemsRequest request, Action<UpdateStoreItemsResult> resultCallback, Action<PlayFabError> errorCallback, object customData = null) { if (PlayFabSettings.DeveloperSecretKey == null) throw new Exception("Must have PlayFabSettings.DeveloperSecretKey set to call this method"); PlayFabHttp.MakeApiCall("/Admin/UpdateStoreItems", request, AuthType.DevSecretKey, resultCallback, errorCallback, customData); } /// <summary> /// Increments the specified virtual currency by the stated amount /// </summary> public static void AddUserVirtualCurrency(AddUserVirtualCurrencyRequest request, Action<ModifyUserVirtualCurrencyResult> resultCallback, Action<PlayFabError> errorCallback, object customData = null) { if (PlayFabSettings.DeveloperSecretKey == null) throw new Exception("Must have PlayFabSettings.DeveloperSecretKey set to call this method"); PlayFabHttp.MakeApiCall("/Admin/AddUserVirtualCurrency", request, AuthType.DevSecretKey, resultCallback, errorCallback, customData); } /// <summary> /// Retrieves the specified user's current inventory of virtual goods /// </summary> public static void GetUserInventory(GetUserInventoryRequest request, Action<GetUserInventoryResult> resultCallback, Action<PlayFabError> errorCallback, object customData = null) { if (PlayFabSettings.DeveloperSecretKey == null) throw new Exception("Must have PlayFabSettings.DeveloperSecretKey set to call this method"); PlayFabHttp.MakeApiCall("/Admin/GetUserInventory", request, AuthType.DevSecretKey, resultCallback, errorCallback, customData); } /// <summary> /// Adds the specified items to the specified user inventories /// </summary> public static void GrantItemsToUsers(GrantItemsToUsersRequest request, Action<GrantItemsToUsersResult> resultCallback, Action<PlayFabError> errorCallback, object customData = null) { if (PlayFabSettings.DeveloperSecretKey == null) throw new Exception("Must have PlayFabSettings.DeveloperSecretKey set to call this method"); PlayFabHttp.MakeApiCall("/Admin/GrantItemsToUsers", request, AuthType.DevSecretKey, resultCallback, errorCallback, customData); } /// <summary> /// Revokes access to an item in a user's inventory /// </summary> public static void RevokeInventoryItem(RevokeInventoryItemRequest request, Action<RevokeInventoryResult> resultCallback, Action<PlayFabError> errorCallback, object customData = null) { if (PlayFabSettings.DeveloperSecretKey == null) throw new Exception("Must have PlayFabSettings.DeveloperSecretKey set to call this method"); PlayFabHttp.MakeApiCall("/Admin/RevokeInventoryItem", request, AuthType.DevSecretKey, resultCallback, errorCallback, customData); } /// <summary> /// Decrements the specified virtual currency by the stated amount /// </summary> public static void SubtractUserVirtualCurrency(SubtractUserVirtualCurrencyRequest request, Action<ModifyUserVirtualCurrencyResult> resultCallback, Action<PlayFabError> errorCallback, object customData = null) { if (PlayFabSettings.DeveloperSecretKey == null) throw new Exception("Must have PlayFabSettings.DeveloperSecretKey set to call this method"); PlayFabHttp.MakeApiCall("/Admin/SubtractUserVirtualCurrency", request, AuthType.DevSecretKey, resultCallback, errorCallback, customData); } /// <summary> /// Retrieves the details for a specific completed session, including links to standard out and standard error logs /// </summary> public static void GetMatchmakerGameInfo(GetMatchmakerGameInfoRequest request, Action<GetMatchmakerGameInfoResult> resultCallback, Action<PlayFabError> errorCallback, object customData = null) { if (PlayFabSettings.DeveloperSecretKey == null) throw new Exception("Must have PlayFabSettings.DeveloperSecretKey set to call this method"); PlayFabHttp.MakeApiCall("/Admin/GetMatchmakerGameInfo", request, AuthType.DevSecretKey, resultCallback, errorCallback, customData); } /// <summary> /// Retrieves the details of defined game modes for the specified game server executable /// </summary> public static void GetMatchmakerGameModes(GetMatchmakerGameModesRequest request, Action<GetMatchmakerGameModesResult> resultCallback, Action<PlayFabError> errorCallback, object customData = null) { if (PlayFabSettings.DeveloperSecretKey == null) throw new Exception("Must have PlayFabSettings.DeveloperSecretKey set to call this method"); PlayFabHttp.MakeApiCall("/Admin/GetMatchmakerGameModes", request, AuthType.DevSecretKey, resultCallback, errorCallback, customData); } /// <summary> /// Updates the game server mode details for the specified game server executable /// </summary> public static void ModifyMatchmakerGameModes(ModifyMatchmakerGameModesRequest request, Action<ModifyMatchmakerGameModesResult> resultCallback, Action<PlayFabError> errorCallback, object customData = null) { if (PlayFabSettings.DeveloperSecretKey == null) throw new Exception("Must have PlayFabSettings.DeveloperSecretKey set to call this method"); PlayFabHttp.MakeApiCall("/Admin/ModifyMatchmakerGameModes", request, AuthType.DevSecretKey, resultCallback, errorCallback, customData); } /// <summary> /// Adds the game server executable specified (previously uploaded - see GetServerBuildUploadUrl) to the set of those a client is permitted to request in a call to StartGame /// </summary> public static void AddServerBuild(AddServerBuildRequest request, Action<AddServerBuildResult> resultCallback, Action<PlayFabError> errorCallback, object customData = null) { if (PlayFabSettings.DeveloperSecretKey == null) throw new Exception("Must have PlayFabSettings.DeveloperSecretKey set to call this method"); PlayFabHttp.MakeApiCall("/Admin/AddServerBuild", request, AuthType.DevSecretKey, resultCallback, errorCallback, customData); } /// <summary> /// Retrieves the build details for the specified game server executable /// </summary> public static void GetServerBuildInfo(GetServerBuildInfoRequest request, Action<GetServerBuildInfoResult> resultCallback, Action<PlayFabError> errorCallback, object customData = null) { if (PlayFabSettings.DeveloperSecretKey == null) throw new Exception("Must have PlayFabSettings.DeveloperSecretKey set to call this method"); PlayFabHttp.MakeApiCall("/Admin/GetServerBuildInfo", request, AuthType.DevSecretKey, resultCallback, errorCallback, customData); } /// <summary> /// Retrieves the pre-authorized URL for uploading a game server package containing a build (does not enable the build for use - see AddServerBuild) /// </summary> public static void GetServerBuildUploadUrl(GetServerBuildUploadURLRequest request, Action<GetServerBuildUploadURLResult> resultCallback, Action<PlayFabError> errorCallback, object customData = null) { if (PlayFabSettings.DeveloperSecretKey == null) throw new Exception("Must have PlayFabSettings.DeveloperSecretKey set to call this method"); PlayFabHttp.MakeApiCall("/Admin/GetServerBuildUploadUrl", request, AuthType.DevSecretKey, resultCallback, errorCallback, customData); } /// <summary> /// Retrieves the build details for all game server executables which are currently defined for the title /// </summary> public static void ListServerBuilds(ListBuildsRequest request, Action<ListBuildsResult> resultCallback, Action<PlayFabError> errorCallback, object customData = null) { if (PlayFabSettings.DeveloperSecretKey == null) throw new Exception("Must have PlayFabSettings.DeveloperSecretKey set to call this method"); PlayFabHttp.MakeApiCall("/Admin/ListServerBuilds", request, AuthType.DevSecretKey, resultCallback, errorCallback, customData); } /// <summary> /// Updates the build details for the specified game server executable /// </summary> public static void ModifyServerBuild(ModifyServerBuildRequest request, Action<ModifyServerBuildResult> resultCallback, Action<PlayFabError> errorCallback, object customData = null) { if (PlayFabSettings.DeveloperSecretKey == null) throw new Exception("Must have PlayFabSettings.DeveloperSecretKey set to call this method"); PlayFabHttp.MakeApiCall("/Admin/ModifyServerBuild", request, AuthType.DevSecretKey, resultCallback, errorCallback, customData); } /// <summary> /// Removes the game server executable specified from the set of those a client is permitted to request in a call to StartGame /// </summary> public static void RemoveServerBuild(RemoveServerBuildRequest request, Action<RemoveServerBuildResult> resultCallback, Action<PlayFabError> errorCallback, object customData = null) { if (PlayFabSettings.DeveloperSecretKey == null) throw new Exception("Must have PlayFabSettings.DeveloperSecretKey set to call this method"); PlayFabHttp.MakeApiCall("/Admin/RemoveServerBuild", request, AuthType.DevSecretKey, resultCallback, errorCallback, customData); } /// <summary> /// Updates the key-value store of custom publisher settings /// </summary> public static void SetPublisherData(SetPublisherDataRequest request, Action<SetPublisherDataResult> resultCallback, Action<PlayFabError> errorCallback, object customData = null) { if (PlayFabSettings.DeveloperSecretKey == null) throw new Exception("Must have PlayFabSettings.DeveloperSecretKey set to call this method"); PlayFabHttp.MakeApiCall("/Admin/SetPublisherData", request, AuthType.DevSecretKey, resultCallback, errorCallback, customData); } /// <summary> /// Gets the contents and information of a specific Cloud Script revision. /// </summary> public static void GetCloudScriptRevision(GetCloudScriptRevisionRequest request, Action<GetCloudScriptRevisionResult> resultCallback, Action<PlayFabError> errorCallback, object customData = null) { if (PlayFabSettings.DeveloperSecretKey == null) throw new Exception("Must have PlayFabSettings.DeveloperSecretKey set to call this method"); PlayFabHttp.MakeApiCall("/Admin/GetCloudScriptRevision", request, AuthType.DevSecretKey, resultCallback, errorCallback, customData); } /// <summary> /// Lists all the current cloud script versions. For each version, information about the current published and latest revisions is also listed. /// </summary> public static void GetCloudScriptVersions(GetCloudScriptVersionsRequest request, Action<GetCloudScriptVersionsResult> resultCallback, Action<PlayFabError> errorCallback, object customData = null) { if (PlayFabSettings.DeveloperSecretKey == null) throw new Exception("Must have PlayFabSettings.DeveloperSecretKey set to call this method"); PlayFabHttp.MakeApiCall("/Admin/GetCloudScriptVersions", request, AuthType.DevSecretKey, resultCallback, errorCallback, customData); } /// <summary> /// Sets the currently published revision of a title Cloud Script /// </summary> public static void SetPublishedRevision(SetPublishedRevisionRequest request, Action<SetPublishedRevisionResult> resultCallback, Action<PlayFabError> errorCallback, object customData = null) { if (PlayFabSettings.DeveloperSecretKey == null) throw new Exception("Must have PlayFabSettings.DeveloperSecretKey set to call this method"); PlayFabHttp.MakeApiCall("/Admin/SetPublishedRevision", request, AuthType.DevSecretKey, resultCallback, errorCallback, customData); } /// <summary> /// Creates a new Cloud Script revision and uploads source code to it. Note that at this time, only one file should be submitted in the revision. /// </summary> public static void UpdateCloudScript(UpdateCloudScriptRequest request, Action<UpdateCloudScriptResult> resultCallback, Action<PlayFabError> errorCallback, object customData = null) { if (PlayFabSettings.DeveloperSecretKey == null) throw new Exception("Must have PlayFabSettings.DeveloperSecretKey set to call this method"); PlayFabHttp.MakeApiCall("/Admin/UpdateCloudScript", request, AuthType.DevSecretKey, resultCallback, errorCallback, customData); } /// <summary> /// Delete a content file from the title /// </summary> public static void DeleteContent(DeleteContentRequest request, Action<BlankResult> resultCallback, Action<PlayFabError> errorCallback, object customData = null) { if (PlayFabSettings.DeveloperSecretKey == null) throw new Exception("Must have PlayFabSettings.DeveloperSecretKey set to call this method"); PlayFabHttp.MakeApiCall("/Admin/DeleteContent", request, AuthType.DevSecretKey, resultCallback, errorCallback, customData); } /// <summary> /// List all contents of the title and get statistics such as size /// </summary> public static void GetContentList(GetContentListRequest request, Action<GetContentListResult> resultCallback, Action<PlayFabError> errorCallback, object customData = null) { if (PlayFabSettings.DeveloperSecretKey == null) throw new Exception("Must have PlayFabSettings.DeveloperSecretKey set to call this method"); PlayFabHttp.MakeApiCall("/Admin/GetContentList", request, AuthType.DevSecretKey, resultCallback, errorCallback, customData); } /// <summary> /// Retrieves the pre-signed URL for uploading a content file. A subsequent HTTP PUT to the returned URL uploads the content. /// </summary> public static void GetContentUploadUrl(GetContentUploadUrlRequest request, Action<GetContentUploadUrlResult> resultCallback, Action<PlayFabError> errorCallback, object customData = null) { if (PlayFabSettings.DeveloperSecretKey == null) throw new Exception("Must have PlayFabSettings.DeveloperSecretKey set to call this method"); PlayFabHttp.MakeApiCall("/Admin/GetContentUploadUrl", request, AuthType.DevSecretKey, resultCallback, errorCallback, customData); } /// <summary> /// Completely removes all statistics for the specified character, for the current game /// </summary> public static void ResetCharacterStatistics(ResetCharacterStatisticsRequest request, Action<ResetCharacterStatisticsResult> resultCallback, Action<PlayFabError> errorCallback, object customData = null) { if (PlayFabSettings.DeveloperSecretKey == null) throw new Exception("Must have PlayFabSettings.DeveloperSecretKey set to call this method"); PlayFabHttp.MakeApiCall("/Admin/ResetCharacterStatistics", request, AuthType.DevSecretKey, resultCallback, errorCallback, customData); } /// <summary> /// Adds a given tag to a player profile. The tag's namespace is automatically generated based on the source of the tag. /// </summary> public static void AddPlayerTag(AddPlayerTagRequest request, Action<AddPlayerTagResult> resultCallback, Action<PlayFabError> errorCallback, object customData = null) { if (PlayFabSettings.DeveloperSecretKey == null) throw new Exception("Must have PlayFabSettings.DeveloperSecretKey set to call this method"); PlayFabHttp.MakeApiCall("/Admin/AddPlayerTag", request, AuthType.DevSecretKey, resultCallback, errorCallback, customData); } /// <summary> /// Retrieve a list of all PlayStream actions groups. /// </summary> public static void GetAllActionGroups(GetAllActionGroupsRequest request, Action<GetAllActionGroupsResult> resultCallback, Action<PlayFabError> errorCallback, object customData = null) { if (PlayFabSettings.DeveloperSecretKey == null) throw new Exception("Must have PlayFabSettings.DeveloperSecretKey set to call this method"); PlayFabHttp.MakeApiCall("/Admin/GetAllActionGroups", request, AuthType.DevSecretKey, resultCallback, errorCallback, customData); } /// <summary> /// Retrieves an array of player segment definitions. Results from this can be used in subsequent API calls such as GetPlayersInSegment which requires a Segment ID. While segment names can change the ID for that segment will not change. /// </summary> public static void GetAllSegments(GetAllSegmentsRequest request, Action<GetAllSegmentsResult> resultCallback, Action<PlayFabError> errorCallback, object customData = null) { if (PlayFabSettings.DeveloperSecretKey == null) throw new Exception("Must have PlayFabSettings.DeveloperSecretKey set to call this method"); PlayFabHttp.MakeApiCall("/Admin/GetAllSegments", request, AuthType.DevSecretKey, resultCallback, errorCallback, customData); } /// <summary> /// List all segments that a player currently belongs to at this moment in time. /// </summary> public static void GetPlayerSegments(GetPlayersSegmentsRequest request, Action<GetPlayerSegmentsResult> resultCallback, Action<PlayFabError> errorCallback, object customData = null) { if (PlayFabSettings.DeveloperSecretKey == null) throw new Exception("Must have PlayFabSettings.DeveloperSecretKey set to call this method"); PlayFabHttp.MakeApiCall("/Admin/GetPlayerSegments", request, AuthType.DevSecretKey, resultCallback, errorCallback, customData); } /// <summary> /// Allows for paging through all players in a given segment. This API creates a snapshot of all player profiles that match the segment definition at the time of its creation and lives through the Total Seconds to Live, refreshing its life span on each subsequent use of the Continuation Token. Profiles that change during the course of paging will not be reflected in the results. AB Test segments are currently not supported by this operation. /// </summary> public static void GetPlayersInSegment(GetPlayersInSegmentRequest request, Action<GetPlayersInSegmentResult> resultCallback, Action<PlayFabError> errorCallback, object customData = null) { if (PlayFabSettings.DeveloperSecretKey == null) throw new Exception("Must have PlayFabSettings.DeveloperSecretKey set to call this method"); PlayFabHttp.MakeApiCall("/Admin/GetPlayersInSegment", request, AuthType.DevSecretKey, resultCallback, errorCallback, customData); } /// <summary> /// Get all tags with a given Namespace (optional) from a player profile. /// </summary> public static void GetPlayerTags(GetPlayerTagsRequest request, Action<GetPlayerTagsResult> resultCallback, Action<PlayFabError> errorCallback, object customData = null) { if (PlayFabSettings.DeveloperSecretKey == null) throw new Exception("Must have PlayFabSettings.DeveloperSecretKey set to call this method"); PlayFabHttp.MakeApiCall("/Admin/GetPlayerTags", request, AuthType.DevSecretKey, resultCallback, errorCallback, customData); } /// <summary> /// Remove a given tag from a player profile. The tag's namespace is automatically generated based on the source of the tag. /// </summary> public static void RemovePlayerTag(RemovePlayerTagRequest request, Action<RemovePlayerTagResult> resultCallback, Action<PlayFabError> errorCallback, object customData = null) { if (PlayFabSettings.DeveloperSecretKey == null) throw new Exception("Must have PlayFabSettings.DeveloperSecretKey set to call this method"); PlayFabHttp.MakeApiCall("/Admin/RemovePlayerTag", request, AuthType.DevSecretKey, resultCallback, errorCallback, customData); } } } #endif
using System; using System.Globalization; using System.Collections.Generic; using Sasoma.Utils; using Sasoma.Microdata.Interfaces; using Sasoma.Languages.Core; using Sasoma.Microdata.Properties; namespace Sasoma.Microdata.Types { /// <summary> /// A notary. /// </summary> public class Notary_Core : TypeCore, IProfessionalService { public Notary_Core() { this._TypeId = 186; this._Id = "Notary"; this._Schema_Org_Url = "http://schema.org/Notary"; string label = ""; GetLabel(out label, "Notary", typeof(Notary_Core)); this._Label = label; this._Ancestors = new int[]{266,193,155,216}; this._SubTypes = new int[0]; this._SuperTypes = new int[]{216}; this._Properties = new int[]{67,108,143,229,5,10,49,85,91,98,115,135,159,199,196,47,75,77,94,95,130,137,36,60,152,156,167}; } /// <summary> /// Physical address of the item. /// </summary> private Address_Core address; public Address_Core Address { get { return address; } set { address = value; SetPropertyInstance(address); } } /// <summary> /// The overall rating, based on a collection of reviews or ratings, of the item. /// </summary> private Properties.AggregateRating_Core aggregateRating; public Properties.AggregateRating_Core AggregateRating { get { return aggregateRating; } set { aggregateRating = value; SetPropertyInstance(aggregateRating); } } /// <summary> /// The larger organization that this local business is a branch of, if any. /// </summary> private BranchOf_Core branchOf; public BranchOf_Core BranchOf { get { return branchOf; } set { branchOf = value; SetPropertyInstance(branchOf); } } /// <summary> /// A contact point for a person or organization. /// </summary> private ContactPoints_Core contactPoints; public ContactPoints_Core ContactPoints { get { return contactPoints; } set { contactPoints = value; SetPropertyInstance(contactPoints); } } /// <summary> /// The basic containment relation between places. /// </summary> private ContainedIn_Core containedIn; public ContainedIn_Core ContainedIn { get { return containedIn; } set { containedIn = value; SetPropertyInstance(containedIn); } } /// <summary> /// The currency accepted (in <a href=\http://en.wikipedia.org/wiki/ISO_4217\ target=\new\>ISO 4217 currency format</a>). /// </summary> private CurrenciesAccepted_Core currenciesAccepted; public CurrenciesAccepted_Core CurrenciesAccepted { get { return currenciesAccepted; } set { currenciesAccepted = value; SetPropertyInstance(currenciesAccepted); } } /// <summary> /// A short description of the item. /// </summary> private Description_Core description; public Description_Core Description { get { return description; } set { description = value; SetPropertyInstance(description); } } /// <summary> /// Email address. /// </summary> private Email_Core email; public Email_Core Email { get { return email; } set { email = value; SetPropertyInstance(email); } } /// <summary> /// People working for this organization. /// </summary> private Employees_Core employees; public Employees_Core Employees { get { return employees; } set { employees = value; SetPropertyInstance(employees); } } /// <summary> /// Upcoming or past events associated with this place or organization. /// </summary> private Events_Core events; public Events_Core Events { get { return events; } set { events = value; SetPropertyInstance(events); } } /// <summary> /// The fax number. /// </summary> private FaxNumber_Core faxNumber; public FaxNumber_Core FaxNumber { get { return faxNumber; } set { faxNumber = value; SetPropertyInstance(faxNumber); } } /// <summary> /// A person who founded this organization. /// </summary> private Founders_Core founders; public Founders_Core Founders { get { return founders; } set { founders = value; SetPropertyInstance(founders); } } /// <summary> /// The date that this organization was founded. /// </summary> private FoundingDate_Core foundingDate; public FoundingDate_Core FoundingDate { get { return foundingDate; } set { foundingDate = value; SetPropertyInstance(foundingDate); } } /// <summary> /// The geo coordinates of the place. /// </summary> private Geo_Core geo; public Geo_Core Geo { get { return geo; } set { geo = value; SetPropertyInstance(geo); } } /// <summary> /// URL of an image of the item. /// </summary> private Image_Core image; public Image_Core Image { get { return image; } set { image = value; SetPropertyInstance(image); } } /// <summary> /// A count of a specific user interactions with this item\u2014for example, <code>20 UserLikes</code>, <code>5 UserComments</code>, or <code>300 UserDownloads</code>. The user interaction type should be one of the sub types of <a href=\http://schema.org/UserInteraction\>UserInteraction</a>. /// </summary> private InteractionCount_Core interactionCount; public InteractionCount_Core InteractionCount { get { return interactionCount; } set { interactionCount = value; SetPropertyInstance(interactionCount); } } /// <summary> /// The location of the event or organization. /// </summary> private Location_Core location; public Location_Core Location { get { return location; } set { location = value; SetPropertyInstance(location); } } /// <summary> /// A URL to a map of the place. /// </summary> private Maps_Core maps; public Maps_Core Maps { get { return maps; } set { maps = value; SetPropertyInstance(maps); } } /// <summary> /// A member of this organization. /// </summary> private Members_Core members; public Members_Core Members { get { return members; } set { members = value; SetPropertyInstance(members); } } /// <summary> /// The name of the item. /// </summary> private Name_Core name; public Name_Core Name { get { return name; } set { name = value; SetPropertyInstance(name); } } /// <summary> /// The opening hours for a business. Opening hours can be specified as a weekly time range, starting with days, then times per day. Multiple days can be listed with commas ',' separating each day. Day or time ranges are specified using a hyphen '-'.<br/>- Days are specified using the following two-letter combinations: <code>Mo</code>, <code>Tu</code>, <code>We</code>, <code>Th</code>, <code>Fr</code>, <code>Sa</code>, <code>Su</code>.<br/>- Times are specified using 24:00 time. For example, 3pm is specified as <code>15:00</code>. <br/>- Here is an example: <code>&lt;time itemprop=\openingHours\ datetime=\Tu,Th 16:00-20:00\&gt;Tuesdays and Thursdays 4-8pm&lt;/time&gt;</code>. <br/>- If a business is open 7 days a week, then it can be specified as <code>&lt;time itemprop=\openingHours\ datetime=\Mo-Su\&gt;Monday through Sunday, all day&lt;/time&gt;</code>. /// </summary> private OpeningHours_Core openingHours; public OpeningHours_Core OpeningHours { get { return openingHours; } set { openingHours = value; SetPropertyInstance(openingHours); } } /// <summary> /// Cash, credit card, etc. /// </summary> private PaymentAccepted_Core paymentAccepted; public PaymentAccepted_Core PaymentAccepted { get { return paymentAccepted; } set { paymentAccepted = value; SetPropertyInstance(paymentAccepted); } } /// <summary> /// Photographs of this place. /// </summary> private Photos_Core photos; public Photos_Core Photos { get { return photos; } set { photos = value; SetPropertyInstance(photos); } } /// <summary> /// The price range of the business, for example <code>$$$</code>. /// </summary> private PriceRange_Core priceRange; public PriceRange_Core PriceRange { get { return priceRange; } set { priceRange = value; SetPropertyInstance(priceRange); } } /// <summary> /// Review of the item. /// </summary> private Reviews_Core reviews; public Reviews_Core Reviews { get { return reviews; } set { reviews = value; SetPropertyInstance(reviews); } } /// <summary> /// The telephone number. /// </summary> private Telephone_Core telephone; public Telephone_Core Telephone { get { return telephone; } set { telephone = value; SetPropertyInstance(telephone); } } /// <summary> /// URL of the item. /// </summary> private Properties.URL_Core uRL; public Properties.URL_Core URL { get { return uRL; } set { uRL = value; SetPropertyInstance(uRL); } } } }
using System; using System.Collections.Generic; using System.IO; using System.Security.AccessControl; /// <summary> /// Base namespace for %Dokan. /// </summary> namespace DokanNet { /// <summary> /// %Dokan API callbacks interface. /// /// A interface of callbacks that describe all %Dokan API operation /// that will be called when Windows access to the file system. /// /// All this callbacks can return <see cref="NtStatus.NotImplemented"/> /// if you dont want to support one of them. Be aware that returning such value to important callbacks /// such <see cref="CreateFile"/>/<see cref="ReadFile"/>/... would make the filesystem not working or unstable. /// </summary> /// <remarks>This is the same struct as <c>DOKAN_OPERATIONS</c> (dokan.h) in the C++ version of Dokan.</remarks> public interface IDokanOperations { /// <summary> /// CreateFile is called each time a request is made on a file system object. /// /// In case <paramref name="mode"/> is <c><see cref="FileMode.OpenOrCreate"/></c> and /// <c><see cref="FileMode.Create"/></c> and CreateFile are successfully opening a already /// existing file, you have to return <see cref="DokanResult.AlreadyExists"/> instead of <see cref="NtStatus.Success"/>. /// /// If the file is a directory, CreateFile is also called. /// In this case, CreateFile should return <see cref="NtStatus.Success"/> when that directory /// can be opened and <see cref="DokanFileInfo.IsDirectory"/> has to be set to <c>true</c>. /// On the other hand, if <see cref="DokanFileInfo.IsDirectory"/> is set to <c>true</c> /// but the path target a file, you need to return <see cref="NtStatus.NotADirectory"/> /// /// <see cref="DokanFileInfo.Context"/> can be used to store data (like <c><see cref="FileStream"/></c>) /// that can be retrieved in all other request related to the context. /// </summary> /// <param name="fileName">File path requested by the Kernel on the FileSystem.</param> /// <param name="access">A <see cref="FileAccess"/> with permissions for file or directory.</param> /// <param name="share">Type of share access to other threads, which is specified as /// <see cref="FileShare.None"/> or any combination of <see cref="FileShare"/>. /// Device and intermediate drivers usually set ShareAccess to zero, /// which gives the caller exclusive access to the open file.</param> /// <param name="mode">Specifies how the operating system should open a file. See <a href="https://msdn.microsoft.com/en-us/library/system.io.filemode(v=vs.110).aspx">FileMode Enumeration (MSDN)</a>.</param> /// <param name="options">Represents advanced options for creating a FileStream object. See <a href="https://msdn.microsoft.com/en-us/library/system.io.fileoptions(v=vs.110).aspx">FileOptions Enumeration (MSDN)</a>.</param> /// <param name="attributes">Provides attributes for files and directories. See <a href="https://msdn.microsoft.com/en-us/library/system.io.fileattributes(v=vs.110).aspx">FileAttributes Enumeration (MSDN></a>.</param> /// <param name="info">An <see cref="DokanFileInfo"/> with information about the file or directory.</param> /// <returns><see cref="NtStatus"/> or <see cref="DokanResult"/> appropriate to the request result.</returns> /// \see See <a href="https://msdn.microsoft.com/en-us/library/windows/hardware/ff566424(v=vs.85).aspx">ZwCreateFile (MSDN)</a> for more information about the parameters of this callback. NtStatus CreateFile( string fileName, FileAccess access, FileShare share, FileMode mode, FileOptions options, FileAttributes attributes, DokanFileInfo info); /// <summary> /// Receipt of this request indicates that the last handle for a file object that is associated /// with the target device object has been closed (but, due to outstanding I/O requests, /// might not have been released). /// /// Cleanup is requested before <see cref="CloseFile"/> is called. /// </summary> /// <remarks> /// When <see cref="DokanFileInfo.DeleteOnClose"/> is <c>true</c>, you must delete the file in Cleanup. /// Refer to <see cref="DeleteFile"/> and <see cref="DeleteDirectory"/> for explanation. /// </remarks> /// <param name="fileName">File path requested by the Kernel on the FileSystem.</param> /// <param name="info">An <see cref="DokanFileInfo"/> with information about the file or directory.</param> /// <seealso cref="DeleteFile"/> /// <seealso cref="DeleteDirectory"/> /// <seealso cref="CloseFile"/> void Cleanup(string fileName, DokanFileInfo info); /// <summary> /// CloseFile is called at the end of the life of the context. /// /// Receipt of this request indicates that the last handle of the file object that is associated /// with the target device object has been closed and released. All outstanding I/O requests /// have been completed or canceled. /// /// CloseFile is requested after <see cref="Cleanup"/> is called. /// /// Remainings in <see cref="DokanFileInfo.Context"/> has to be cleared before return. /// </summary> /// <param name="fileName">File path requested by the Kernel on the FileSystem.</param> /// <param name="info">An <see cref="DokanFileInfo"/> with information about the file or directory.</param> /// <seealso cref="Cleanup"/> void CloseFile(string fileName, DokanFileInfo info); /// <summary> /// ReadFile callback on the file previously opened in <see cref="CreateFile"/>. /// It can be called by different thread at the same time, /// therefor the read has to be thread safe. /// </summary> /// <param name="fileName">File path requested by the Kernel on the FileSystem.</param> /// <param name="buffer">Read buffer that has to be fill with the read result. /// The buffer size depend of the read size requested by the kernel.</param> /// <param name="bytesRead">Total number of bytes that has been read.</param> /// <param name="offset">Offset from where the read has to be proceed.</param> /// <param name="info">An <see cref="DokanFileInfo"/> with information about the file or directory.</param> /// <returns><see cref="NtStatus"/> or <see cref="DokanResult"/> appropriate to the request result.</returns> /// <seealso cref="WriteFile"/> NtStatus ReadFile(string fileName, byte[] buffer, out int bytesRead, long offset, DokanFileInfo info); /// <summary> /// WriteFile callback on the file previously opened in <see cref="CreateFile"/> /// It can be called by different thread at the same time, /// therefor the write/context has to be thread safe. /// </summary> /// <param name="fileName">File path requested by the Kernel on the FileSystem.</param> /// <param name="buffer">Data that has to be written.</param> /// <param name="bytesWritten">Total number of bytes that has been write.</param> /// <param name="offset">Offset from where the write has to be proceed.</param> /// <param name="info">An <see cref="DokanFileInfo"/> with information about the file or directory.</param> /// <returns><see cref="NtStatus"/> or <see cref="DokanResult"/> appropriate to the request result.</returns> /// <seealso cref="ReadFile"/> NtStatus WriteFile(string fileName, byte[] buffer, out int bytesWritten, long offset, DokanFileInfo info); /// <summary> /// Clears buffers for this context and causes any buffered data to be written to the file. /// </summary> /// <param name="fileName">File path requested by the Kernel on the FileSystem.</param> /// <param name="info">An <see cref="DokanFileInfo"/> with information about the file or directory.</param> /// <returns><see cref="NtStatus"/> or <see cref="DokanResult"/> appropriate to the request result.</returns> NtStatus FlushFileBuffers(string fileName, DokanFileInfo info); /// <summary> /// Get specific informations on a file. /// </summary> /// <param name="fileName">File path requested by the Kernel on the FileSystem.</param> /// <param name="fileInfo"><see cref="FileInformation"/> struct to fill</param> /// <param name="info">An <see cref="DokanFileInfo"/> with information about the file or directory.</param> /// <returns><see cref="NtStatus"/> or <see cref="DokanResult"/> appropriate to the request result.</returns> NtStatus GetFileInformation(string fileName, out FileInformation fileInfo, DokanFileInfo info); /// <summary> /// List all files in the path requested /// /// <see cref="FindFilesWithPattern"/> is checking first. If it is not implemented or /// returns <see cref="NtStatus.NotImplemented"/>, then FindFiles is called. /// </summary> /// <param name="fileName">File path requested by the Kernel on the FileSystem.</param> /// <param name="files">A list of <see cref="FileInformation"/> to return.</param> /// <param name="info">An <see cref="DokanFileInfo"/> with information about the file or directory.</param> /// <returns><see cref="NtStatus"/> or <see cref="DokanResult"/> appropriate to the request result.</returns> /// <seealso cref="FindFilesWithPattern"/> NtStatus FindFiles(string fileName, out IList<FileInformation> files, DokanFileInfo info); /// <summary> /// Same as <see cref="FindFiles"/> but with a search pattern to filter the result. /// </summary> /// <param name="fileName">Path requested by the Kernel on the FileSystem.</param> /// <param name="searchPattern">Search pattern</param> /// <param name="files">A list of <see cref="FileInformation"/> to return.</param> /// <param name="info">An <see cref="DokanFileInfo"/> with information about the file or directory.</param> /// <returns><see cref="NtStatus"/> or <see cref="DokanResult"/> appropriate to the request result.</returns> /// <seealso cref="FindFiles"/> NtStatus FindFilesWithPattern( string fileName, string searchPattern, out IList<FileInformation> files, DokanFileInfo info); /// <summary> /// Set file attributes on a specific file. /// </summary> /// <remarks>SetFileAttributes and <see cref="SetFileTime"/> are called only if both of them are implemented.</remarks> /// <param name="fileName">File path requested by the Kernel on the FileSystem.</param> /// <param name="attributes"><see cref="FileAttributes"/> to set on file</param> /// <param name="info">An <see cref="DokanFileInfo"/> with information about the file or directory.</param> /// <returns><see cref="NtStatus"/> or <see cref="DokanResult"/> appropriate to the request result.</returns> NtStatus SetFileAttributes(string fileName, FileAttributes attributes, DokanFileInfo info); /// <summary> /// Set file times on a specific file. /// If <see cref="DateTime"/> is <c>null</c>, this should not be updated. /// </summary> /// <remarks><see cref="SetFileAttributes"/> and SetFileTime are called only if both of them are implemented.</remarks> /// <param name="fileName">File or directory name.</param> /// <param name="creationTime"><see cref="DateTime"/> when the file was created.</param> /// <param name="lastAccessTime"><see cref="DateTime"/> when the file was last accessed.</param> /// <param name="lastWriteTime"><see cref="DateTime"/> when the file was last written to.</param> /// <param name="info">An <see cref="DokanFileInfo"/> with information about the file or directory.</param> /// <returns><see cref="NtStatus"/> or <see cref="DokanResult"/> appropriate to the request result.</returns> NtStatus SetFileTime( string fileName, DateTime? creationTime, DateTime? lastAccessTime, DateTime? lastWriteTime, DokanFileInfo info); /// <summary> /// Check if it is possible to delete a file. /// </summary> /// <remarks> /// You should NOT delete the file in DeleteFile, but instead /// you must only check whether you can delete the file or not, /// and return <see cref="NtStatus.Success"/> (when you can delete it) or appropriate error /// codes such as <see cref="NtStatus.AccessDenied"/>, <see cref="NtStatus.ObjectNameNotFound"/>. /// /// DeleteFile will also be called with <see cref="DokanFileInfo.DeleteOnClose"/> set to <c>false</c> /// to notify the driver when the file is no longer requested to be deleted. /// /// When you return <see cref="NtStatus.Success"/>, you get a <see cref="Cleanup"/> call afterwards with /// <see cref="DokanFileInfo.DeleteOnClose"/> set to <c>true</c> and only then you have to actually /// delete the file being closed. /// </remarks> /// <param name="fileName">File path requested by the Kernel on the FileSystem.</param> /// <param name="info">An <see cref="DokanFileInfo"/> with information about the file or directory.</param> /// <returns>Return <see cref="DokanResult.Success"/> if file can be delete or <see cref="NtStatus"/> appropriate.</returns> /// <seealso cref="DeleteDirectory"/> /// <seealso cref="Cleanup"/> NtStatus DeleteFile(string fileName, DokanFileInfo info); /// <summary> /// Check if it is possible to delete a directory. /// </summary> /// <remarks> /// You should NOT delete the file in <see cref="DeleteDirectory"/>, but instead /// you must only check whether you can delete the file or not, /// and return <see cref="NtStatus.Success"/> (when you can delete it) or appropriate error /// codes such as <see cref="NtStatus.AccessDenied"/>, <see cref="NtStatus.ObjectPathNotFound"/>, /// <see cref="NtStatus.ObjectNameNotFound"/>. /// /// DeleteFile will also be called with <see cref="DokanFileInfo.DeleteOnClose"/> set to <c>false</c> /// to notify the driver when the file is no longer requested to be deleted. /// /// When you return <see cref="NtStatus.Success"/>, you get a <see cref="Cleanup"/> call afterwards with /// <see cref="DokanFileInfo.DeleteOnClose"/> set to <c>true</c> and only then you have to actually /// delete the file being closed. /// </remarks> /// <param name="fileName">File path requested by the Kernel on the FileSystem.</param> /// <param name="info">An <see cref="DokanFileInfo"/> with information about the file or directory.</param> /// <returns>Return <see cref="DokanResult.Success"/> if file can be delete or <see cref="NtStatus"/> appropriate.</returns> /// <seealso cref="DeleteFile"/> /// <seealso cref="Cleanup"/> NtStatus DeleteDirectory(string fileName, DokanFileInfo info); /// <summary> /// Move a file or directory to a new location. /// </summary> /// <param name="oldName">Path to the file to move.</param> /// <param name="newName">Path to the new location for the file.</param> /// <param name="replace">If the file should be replaced if it already exist a file with path <paramref name="newName"/>.</param> /// <param name="info">An <see cref="DokanFileInfo"/> with information about the file or directory.</param> /// <returns><see cref="NtStatus"/> or <see cref="DokanResult"/> appropriate to the request result.</returns> NtStatus MoveFile(string oldName, string newName, bool replace, DokanFileInfo info); /// <summary> /// SetEndOfFile is used to truncate or extend a file (physical file size). /// </summary> /// <param name="fileName">File path requested by the Kernel on the FileSystem.</param> /// <param name="length">File length to set</param> /// <param name="info">An <see cref="DokanFileInfo"/> with information about the file or directory.</param> /// <returns><see cref="NtStatus"/> or <see cref="DokanResult"/> appropriate to the request result.</returns> NtStatus SetEndOfFile(string fileName, long length, DokanFileInfo info); /// <summary> /// SetAllocationSize is used to truncate or extend a file. /// </summary> /// <param name="fileName">File path requested by the Kernel on the FileSystem.</param> /// <param name="length">File length to set</param> /// <param name="info">An <see cref="DokanFileInfo"/> with information about the file or directory.</param> /// <returns><see cref="NtStatus"/> or <see cref="DokanResult"/> appropriate to the request result.</returns> NtStatus SetAllocationSize(string fileName, long length, DokanFileInfo info); /// <summary> /// Lock file at a specific offset and data length. /// This is only used if <see cref="DokanOptions.UserModeLock"/> is enabled. /// </summary> /// <param name="fileName">File path requested by the Kernel on the FileSystem.</param> /// <param name="offset">Offset from where the lock has to be proceed.</param> /// <param name="length">Data length to lock.</param> /// <param name="info">An <see cref="DokanFileInfo"/> with information about the file or directory.</param> /// <returns><see cref="NtStatus"/> or <see cref="DokanResult"/> appropriate to the request result.</returns> /// <seealso cref="UnlockFile"/> NtStatus LockFile(string fileName, long offset, long length, DokanFileInfo info); /// <summary> /// Unlock file at a specific offset and data length. /// This is only used if <see cref="DokanOptions.UserModeLock"/> is enabled. /// </summary> /// <param name="fileName">File path requested by the Kernel on the FileSystem.</param> /// <param name="offset">Offset from where the unlock has to be proceed.</param> /// <param name="length">Data length to lock.</param> /// <param name="info">An <see cref="DokanFileInfo"/> with information about the file or directory.</param> /// <returns><see cref="NtStatus"/> or <see cref="DokanResult"/> appropriate to the request result.</returns> /// <seealso cref="LockFile"/> NtStatus UnlockFile(string fileName, long offset, long length, DokanFileInfo info); /// <summary> /// Retrieves information about the amount of space that is available on a disk volume, which is the total amount of space, /// the total amount of free space, and the total amount of free space available to the user that is associated with the calling thread. /// </summary> /// <remarks> /// Neither GetDiskFreeSpace nor <see cref="GetVolumeInformation"/> save the <see cref="DokanFileInfo.Context"/>. /// Before these methods are called, <see cref="CreateFile"/> may not be called. (ditto <see cref="CloseFile"/> and <see cref="Cleanup"/>). /// </remarks> /// <param name="freeBytesAvailable">Amount of available space.</param> /// <param name="totalNumberOfBytes">Total size of storage space.</param> /// <param name="totalNumberOfFreeBytes">Amount of free space.</param> /// <param name="info">An <see cref="DokanFileInfo"/> with information about the file or directory.</param> /// <returns><see cref="NtStatus"/> or <see cref="DokanResult"/> appropriate to the request result.</returns> /// \see <a href="https://msdn.microsoft.com/en-us/library/windows/desktop/aa364937(v=vs.85).aspx"> GetDiskFreeSpaceEx function (MSDN)</a> /// <seealso cref="GetVolumeInformation"/> NtStatus GetDiskFreeSpace( out long freeBytesAvailable, out long totalNumberOfBytes, out long totalNumberOfFreeBytes, DokanFileInfo info); /// <summary> /// Retrieves information about the file system and volume associated with the specified root directory. /// </summary> /// <remarks> /// Neither GetVolumeInformation nor <see cref="GetDiskFreeSpace"/> save the <see cref="DokanFileInfo.Context"/>. /// Before these methods are called, <see cref="CreateFile"/> may not be called. (ditto <see cref="CloseFile"/> and <see cref="Cleanup"/>). /// /// <see cref="FileSystemFeatures.ReadOnlyVolume"/> is automatically added to the <paramref name="features"/> if <see cref="DokanOptions.WriteProtection"/> was /// specified when the volume was mounted. /// /// If <see cref="NtStatus.NotImplemented"/> is returned, the %Dokan kernel driver use following settings by default: /// | Parameter | Default value | /// |------------------------------|--------------------------------------------------------------------------------------------------| /// | \a rawVolumeNameBuffer | <c>"DOKAN"</c> | /// | \a rawVolumeSerialNumber | <c>0x19831116</c> | /// | \a rawMaximumComponentLength | <c>256</c> | /// | \a rawFileSystemFlags | <c>CaseSensitiveSearch \|\| CasePreservedNames \|\| SupportsRemoteStorage \|\| UnicodeOnDisk</c> | /// | \a rawFileSystemNameBuffer | <c>"NTFS"</c> | /// </remarks> /// <param name="volumeLabel">Volume name</param> /// <param name="features"><see cref="FileSystemFeatures"/> with features enabled on the volume.</param> /// <param name="fileSystemName">The name of the specified volume.</param> /// <param name="info">An <see cref="DokanFileInfo"/> with information about the file or directory.</param> /// <returns><see cref="NtStatus"/> or <see cref="DokanResult"/> appropriate to the request result.</returns> /// \see <a href="https://msdn.microsoft.com/en-us/library/windows/desktop/aa364993(v=vs.85).aspx"> GetVolumeInformation function (MSDN)</a> NtStatus GetVolumeInformation( out string volumeLabel, out FileSystemFeatures features, out string fileSystemName, DokanFileInfo info); /// <summary> /// Get specified information about the security of a file or directory. /// </summary> /// \since Supported since version 0.6.0. You must specify the version in <see cref="Dokan.Mount(IDokanOperations, string, DokanOptions,int, int, TimeSpan, string, int,int, Logging.ILogger)"/>. /// /// <param name="fileName">File or directory name.</param> /// <param name="security">A <see cref="FileSystemSecurity"/> with security information to return.</param> /// <param name="sections">A <see cref="AccessControlSections"/> with access sections to return.</param> /// <param name="info">An <see cref="DokanFileInfo"/> with information about the file or directory.</param> /// <returns><see cref="NtStatus"/> or <see cref="DokanResult"/> appropriate to the request result.</returns> /// <seealso cref="SetFileSecurity"/> /// \see <a href="https://msdn.microsoft.com/en-us/library/windows/desktop/aa446639(v=vs.85).aspx">GetFileSecurity function (MSDN)</a> NtStatus GetFileSecurity( string fileName, out FileSystemSecurity security, AccessControlSections sections, DokanFileInfo info); /// <summary> /// Sets the security of a file or directory object. /// </summary> /// \since Supported since version 0.6.0. You must specify the version in <see cref="Dokan.Mount(IDokanOperations, string, DokanOptions,int, int, TimeSpan, string, int,int, Logging.ILogger)"/>. /// /// <param name="fileName">File path requested by the Kernel on the FileSystem.</param> /// <param name="security">A <see cref="FileSystemSecurity"/> with security information to set.</param> /// <param name="sections">A <see cref="AccessControlSections"/> with access sections on which.</param> /// <param name="info">An <see cref="DokanFileInfo"/> with information about the file or directory.</param> /// <returns><see cref="NtStatus"/> or <see cref="DokanResult"/> appropriate to the request result.</returns> /// <seealso cref="GetFileSecurity"/> /// \see <a href="https://msdn.microsoft.com/en-us/library/windows/desktop/aa379577(v=vs.85).aspx">SetFileSecurity function (MSDN)</a> NtStatus SetFileSecurity( string fileName, FileSystemSecurity security, AccessControlSections sections, DokanFileInfo info); /// <summary> /// Is called when %Dokan succeed to mount the volume. /// </summary> /// <param name="info">An <see cref="DokanFileInfo"/> with information about the file or directory.</param> /// <returns><see cref="NtStatus"/> or <see cref="DokanResult"/> appropriate to the request result.</returns> /// <see cref="Unmounted"/> NtStatus Mounted(DokanFileInfo info); /// <summary> /// Is called when %Dokan is unmounting the volume. /// </summary> /// <param name="info">An <see cref="DokanFileInfo"/> with information about the file or directory.</param> /// <returns><see cref="NtStatus"/> or <see cref="DokanResult"/> appropriate to the request result.</returns> /// <seealso cref="Mounted"/> NtStatus Unmounted(DokanFileInfo info); /// <summary> /// Retrieve all NTFS Streams informations on the file. /// This is only called if <see cref="DokanOptions.AltStream"/> is enabled. /// </summary> /// <remarks>For files, the first item in <paramref name="streams"/> is information about the /// default data stream <c>"::$DATA"</c>.</remarks> /// \since Supported since version 0.8.0. You must specify the version in <see cref="Dokan.Mount(IDokanOperations, string, DokanOptions,int, int, TimeSpan, string, int,int, Logging.ILogger)"/>. /// /// <param name="fileName">File path requested by the Kernel on the FileSystem.</param> /// <param name="streams">List of <see cref="FileInformation"/> for each streams present on the file.</param> /// <param name="info">An <see cref="DokanFileInfo"/> with information about the file or directory.</param> /// <returns>Return <see cref="NtStatus"/> or <see cref="DokanResult"/> appropriate to the request result.</returns> /// \see <a href="https://msdn.microsoft.com/en-us/library/windows/desktop/aa364424(v=vs.85).aspx">FindFirstStreamW function (MSDN)</a> /// \see <a href="https://msdn.microsoft.com/en-us/library/windows/desktop/aa365993(v=vs.85).aspx">About KTM (MSDN)</a> NtStatus FindStreams(string fileName, out IList<FileInformation> streams, DokanFileInfo info); } } /// <summary> /// Namespace for AssemblyInfo and resource strings /// </summary> namespace DokanNet.Properties { // This is only for documentation of the DokanNet.Properties namespace. }
// Deflater.cs // // Copyright (C) 2001 Mike Krueger // Copyright (C) 2004 John Reilly // // This file was translated from java, it was part of the GNU Classpath // Copyright (C) 2001 Free Software Foundation, Inc. // // 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. // // Linking this library statically or dynamically with other modules is // making a combined work based on this library. Thus, the terms and // conditions of the GNU General Public License cover the whole // combination. // // As a special exception, the copyright holders of this library give you // permission to link this library with independent modules to produce an // executable, regardless of the license terms of these independent // modules, and to copy and distribute the resulting executable under // terms of your choice, provided that you also meet, for each linked // independent module, the terms and conditions of the license of that // module. An independent module is a module which is not derived from // or based on this library. If you modify this library, you may extend // this exception to your version of the library, but you are not // obligated to do so. If you do not wish to do so, delete this // exception statement from your version. using System; namespace PdfSharp.SharpZipLib.Zip.Compression { /// <summary> /// This is the Deflater class. The deflater class compresses input /// with the deflate algorithm described in RFC 1951. It has several /// compression levels and three different strategies described below. /// /// This class is <i>not</i> thread safe. This is inherent in the API, due /// to the split of deflate and setInput. /// /// Author of the original java version: Jochen Hoenicke /// </summary> internal class Deflater { #region Deflater Documentation /* * The Deflater can do the following state transitions: * * (1) -> INIT_STATE ----> INIT_FINISHING_STATE ---. * / | (2) (5) | * / v (5) | * (3)| SETDICT_STATE ---> SETDICT_FINISHING_STATE |(3) * \ | (3) | ,--------' * | | | (3) / * v v (5) v v * (1) -> BUSY_STATE ----> FINISHING_STATE * | (6) * v * FINISHED_STATE * \_____________________________________/ * | (7) * v * CLOSED_STATE * * (1) If we should produce a header we start in INIT_STATE, otherwise * we start in BUSY_STATE. * (2) A dictionary may be set only when we are in INIT_STATE, then * we change the state as indicated. * (3) Whether a dictionary is set or not, on the first call of deflate * we change to BUSY_STATE. * (4) -- intentionally left blank -- :) * (5) FINISHING_STATE is entered, when flush() is called to indicate that * there is no more INPUT. There are also states indicating, that * the header wasn't written yet. * (6) FINISHED_STATE is entered, when everything has been flushed to the * internal pending output buffer. * (7) At any time (7) * */ #endregion #region Public Constants /// <summary> /// The best and slowest compression level. This tries to find very /// long and distant string repetitions. /// </summary> public const int BEST_COMPRESSION = 9; /// <summary> /// The worst but fastest compression level. /// </summary> public const int BEST_SPEED = 1; /// <summary> /// The default compression level. /// </summary> public const int DEFAULT_COMPRESSION = -1; /// <summary> /// This level won't compress at all but output uncompressed blocks. /// </summary> public const int NO_COMPRESSION = 0; /// <summary> /// The compression method. This is the only method supported so far. /// There is no need to use this constant at all. /// </summary> public const int DEFLATED = 8; #endregion #region Local Constants private const int IS_SETDICT = 0x01; private const int IS_FLUSHING = 0x04; private const int IS_FINISHING = 0x08; private const int INIT_STATE = 0x00; private const int SETDICT_STATE = 0x01; // private static int INIT_FINISHING_STATE = 0x08; // private static int SETDICT_FINISHING_STATE = 0x09; private const int BUSY_STATE = 0x10; private const int FLUSHING_STATE = 0x14; private const int FINISHING_STATE = 0x1c; private const int FINISHED_STATE = 0x1e; private const int CLOSED_STATE = 0x7f; #endregion #region Constructors /// <summary> /// Creates a new deflater with default compression level. /// </summary> public Deflater() : this(DEFAULT_COMPRESSION, false) { } /// <summary> /// Creates a new deflater with given compression level. /// </summary> /// <param name="level"> /// the compression level, a value between NO_COMPRESSION /// and BEST_COMPRESSION, or DEFAULT_COMPRESSION. /// </param> /// <exception cref="System.ArgumentOutOfRangeException">if lvl is out of range.</exception> public Deflater(int level) : this(level, false) { } /// <summary> /// Creates a new deflater with given compression level. /// </summary> /// <param name="level"> /// the compression level, a value between NO_COMPRESSION /// and BEST_COMPRESSION. /// </param> /// <param name="noZlibHeaderOrFooter"> /// true, if we should suppress the Zlib/RFC1950 header at the /// beginning and the adler checksum at the end of the output. This is /// useful for the GZIP/PKZIP formats. /// </param> /// <exception cref="System.ArgumentOutOfRangeException">if lvl is out of range.</exception> public Deflater(int level, bool noZlibHeaderOrFooter) { if (level == DEFAULT_COMPRESSION) { level = 6; } else if (level < NO_COMPRESSION || level > BEST_COMPRESSION) { throw new ArgumentOutOfRangeException("level"); } pending = new DeflaterPending(); engine = new DeflaterEngine(pending); this.noZlibHeaderOrFooter = noZlibHeaderOrFooter; SetStrategy(DeflateStrategy.Default); SetLevel(level); Reset(); } #endregion /// <summary> /// Resets the deflater. The deflater acts afterwards as if it was /// just created with the same compression level and strategy as it /// had before. /// </summary> public void Reset() { state = (noZlibHeaderOrFooter ? BUSY_STATE : INIT_STATE); totalOut = 0; pending.Reset(); engine.Reset(); } /// <summary> /// Gets the current adler checksum of the data that was processed so far. /// </summary> public int Adler { get { return engine.Adler; } } /// <summary> /// Gets the number of input bytes processed so far. /// </summary> public long TotalIn { get { return engine.TotalIn; } } /// <summary> /// Gets the number of output bytes so far. /// </summary> public long TotalOut { get { return totalOut; } } /// <summary> /// Flushes the current input block. Further calls to deflate() will /// produce enough output to inflate everything in the current input /// block. This is not part of Sun's JDK so I have made it package /// private. It is used by DeflaterOutputStream to implement /// flush(). /// </summary> public void Flush() { state |= IS_FLUSHING; } /// <summary> /// Finishes the deflater with the current input block. It is an error /// to give more input after this method was called. This method must /// be called to force all bytes to be flushed. /// </summary> public void Finish() { state |= (IS_FLUSHING | IS_FINISHING); } /// <summary> /// Returns true if the stream was finished and no more output bytes /// are available. /// </summary> public bool IsFinished { get { return (state == FINISHED_STATE) && pending.IsFlushed; } } /// <summary> /// Returns true, if the input buffer is empty. /// You should then call setInput(). /// NOTE: This method can also return true when the stream /// was finished. /// </summary> public bool IsNeedingInput { get { return engine.NeedsInput(); } } /// <summary> /// Sets the data which should be compressed next. This should be only /// called when needsInput indicates that more input is needed. /// If you call setInput when needsInput() returns false, the /// previous input that is still pending will be thrown away. /// The given byte array should not be changed, before needsInput() returns /// true again. /// This call is equivalent to <code>setInput(input, 0, input.length)</code>. /// </summary> /// <param name="input"> /// the buffer containing the input data. /// </param> /// <exception cref="System.InvalidOperationException"> /// if the buffer was finished() or ended(). /// </exception> public void SetInput(byte[] input) { SetInput(input, 0, input.Length); } /// <summary> /// Sets the data which should be compressed next. This should be /// only called when needsInput indicates that more input is needed. /// The given byte array should not be changed, before needsInput() returns /// true again. /// </summary> /// <param name="input"> /// the buffer containing the input data. /// </param> /// <param name="offset"> /// the start of the data. /// </param> /// <param name="count"> /// the number of data bytes of input. /// </param> /// <exception cref="System.InvalidOperationException"> /// if the buffer was Finish()ed or if previous input is still pending. /// </exception> public void SetInput(byte[] input, int offset, int count) { if ((state & IS_FINISHING) != 0) { throw new InvalidOperationException("Finish() already called"); } engine.SetInput(input, offset, count); } /// <summary> /// Sets the compression level. There is no guarantee of the exact /// position of the change, but if you call this when needsInput is /// true the change of compression level will occur somewhere near /// before the end of the so far given input. /// </summary> /// <param name="level"> /// the new compression level. /// </param> public void SetLevel(int level) { if (level == DEFAULT_COMPRESSION) { level = 6; } else if (level < NO_COMPRESSION || level > BEST_COMPRESSION) { throw new ArgumentOutOfRangeException("level"); } if (this.level != level) { this.level = level; engine.SetLevel(level); } } /// <summary> /// Get current compression level /// </summary> /// <returns>Returns the current compression level</returns> public int GetLevel() { return level; } /// <summary> /// Sets the compression strategy. Strategy is one of /// DEFAULT_STRATEGY, HUFFMAN_ONLY and FILTERED. For the exact /// position where the strategy is changed, the same as for /// SetLevel() applies. /// </summary> /// <param name="strategy"> /// The new compression strategy. /// </param> public void SetStrategy(DeflateStrategy strategy) { engine.Strategy = strategy; } /// <summary> /// Deflates the current input block with to the given array. /// </summary> /// <param name="output"> /// The buffer where compressed data is stored /// </param> /// <returns> /// The number of compressed bytes added to the output, or 0 if either /// IsNeedingInput() or IsFinished returns true or length is zero. /// </returns> public int Deflate(byte[] output) { return Deflate(output, 0, output.Length); } /// <summary> /// Deflates the current input block to the given array. /// </summary> /// <param name="output"> /// Buffer to store the compressed data. /// </param> /// <param name="offset"> /// Offset into the output array. /// </param> /// <param name="length"> /// The maximum number of bytes that may be stored. /// </param> /// <returns> /// The number of compressed bytes added to the output, or 0 if either /// needsInput() or finished() returns true or length is zero. /// </returns> /// <exception cref="System.InvalidOperationException"> /// If Finish() was previously called. /// </exception> /// <exception cref="System.ArgumentOutOfRangeException"> /// If offset or length don't match the array length. /// </exception> public int Deflate(byte[] output, int offset, int length) { int origLength = length; if (state == CLOSED_STATE) { throw new InvalidOperationException("Deflater closed"); } if (state < BUSY_STATE) { // output header int header = (DEFLATED + ((DeflaterConstants.MAX_WBITS - 8) << 4)) << 8; int level_flags = (level - 1) >> 1; if (level_flags < 0 || level_flags > 3) { level_flags = 3; } header |= level_flags << 6; if ((state & IS_SETDICT) != 0) { // Dictionary was set header |= DeflaterConstants.PRESET_DICT; } header += 31 - (header % 31); pending.WriteShortMSB(header); if ((state & IS_SETDICT) != 0) { int chksum = engine.Adler; engine.ResetAdler(); pending.WriteShortMSB(chksum >> 16); pending.WriteShortMSB(chksum & 0xffff); } state = BUSY_STATE | (state & (IS_FLUSHING | IS_FINISHING)); } for (; ; ) { int count = pending.Flush(output, offset, length); offset += count; totalOut += count; length -= count; if (length == 0 || state == FINISHED_STATE) { break; } if (!engine.Deflate((state & IS_FLUSHING) != 0, (state & IS_FINISHING) != 0)) { if (state == BUSY_STATE) { // We need more input now return origLength - length; } else if (state == FLUSHING_STATE) { if (level != NO_COMPRESSION) { /* We have to supply some lookahead. 8 bit lookahead * is needed by the zlib inflater, and we must fill * the next byte, so that all bits are flushed. */ int neededbits = 8 + ((-pending.BitCount) & 7); while (neededbits > 0) { /* write a static tree block consisting solely of * an EOF: */ pending.WriteBits(2, 10); neededbits -= 10; } } state = BUSY_STATE; } else if (state == FINISHING_STATE) { pending.AlignToByte(); // Compressed data is complete. Write footer information if required. if (!noZlibHeaderOrFooter) { int adler = engine.Adler; pending.WriteShortMSB(adler >> 16); pending.WriteShortMSB(adler & 0xffff); } state = FINISHED_STATE; } } } return origLength - length; } /// <summary> /// Sets the dictionary which should be used in the deflate process. /// This call is equivalent to <code>setDictionary(dict, 0, dict.Length)</code>. /// </summary> /// <param name="dictionary"> /// the dictionary. /// </param> /// <exception cref="System.InvalidOperationException"> /// if SetInput () or Deflate () were already called or another dictionary was already set. /// </exception> public void SetDictionary(byte[] dictionary) { SetDictionary(dictionary, 0, dictionary.Length); } /// <summary> /// Sets the dictionary which should be used in the deflate process. /// The dictionary is a byte array containing strings that are /// likely to occur in the data which should be compressed. The /// dictionary is not stored in the compressed output, only a /// checksum. To decompress the output you need to supply the same /// dictionary again. /// </summary> /// <param name="dictionary"> /// The dictionary data /// </param> /// <param name="index"> /// The index where dictionary information commences. /// </param> /// <param name="count"> /// The number of bytes in the dictionary. /// </param> /// <exception cref="System.InvalidOperationException"> /// If SetInput () or Deflate() were already called or another dictionary was already set. /// </exception> public void SetDictionary(byte[] dictionary, int index, int count) { if (state != INIT_STATE) { throw new InvalidOperationException(); } state = SETDICT_STATE; engine.SetDictionary(dictionary, index, count); } #region Instance Fields /// <summary> /// Compression level. /// </summary> int level; /// <summary> /// If true no Zlib/RFC1950 headers or footers are generated /// </summary> bool noZlibHeaderOrFooter; /// <summary> /// The current state. /// </summary> int state; /// <summary> /// The total bytes of output written. /// </summary> long totalOut; /// <summary> /// The pending output. /// </summary> DeflaterPending pending; /// <summary> /// The deflater engine. /// </summary> DeflaterEngine engine; #endregion } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Drawing; using System.Globalization; using System.IO; using System.Reflection; namespace GodLesZ.Library.Controls.Html { public static class CssValue { /// <summary> /// Evals a number and returns it. If number is a percentage, it will be multiplied by <see cref="hundredPercent"/> /// </summary> /// <param name="number">Number to be parsed</param> /// <param name="factor">Number that represents the 100% if parsed number is a percentage</param> /// <returns>Parsed number. Zero if error while parsing.</returns> public static float ParseNumber(string number, float hundredPercent) { if (string.IsNullOrEmpty(number)) { return 0f; } string toParse = number; bool isPercent = number.EndsWith("%"); float result = 0f; if (isPercent) toParse = number.Substring(0, number.Length - 1); if (!float.TryParse(toParse, NumberStyles.Number, NumberFormatInfo.InvariantInfo, out result)) { return 0f; } if (isPercent) { result = (result / 100f) * hundredPercent; } return result; } /// <summary> /// Parses a length. Lengths are followed by an unit identifier (e.g. 10px, 3.1em) /// </summary> /// <param name="length">Specified length</param> /// <param name="hundredPercent">Equivalent to 100 percent when length is percentage</param> /// <param name="box"></param> /// <returns></returns> public static float ParseLength(string length, float hundredPercent, CssBox box) { return ParseLength(length, hundredPercent, box, box.GetEmHeight(), false); } /// <summary> /// Parses a length. Lengths are followed by an unit identifier (e.g. 10px, 3.1em) /// </summary> /// <param name="length">Specified length</param> /// <param name="hundredPercent">Equivalent to 100 percent when length is percentage</param> /// <param name="box"></param> /// <param name="useParentsEm"></param> /// <param name="returnPoints">Allows the return float to be in points. If false, result will be pixels</param> /// <returns></returns> public static float ParseLength(string length, float hundredPercent, CssBox box, float emFactor, bool returnPoints) { //Return zero if no length specified, zero specified if (string.IsNullOrEmpty(length) || length == "0") return 0f; //If percentage, use ParseNumber if (length.EndsWith("%")) return ParseNumber(length, hundredPercent); //If no units, return zero if (length.Length < 3) return 0f; //Get units of the length string unit = length.Substring(length.Length - 2, 2); //Factor will depend on the unit float factor = 1f; //Number of the length string number = length.Substring(0, length.Length - 2); //TODO: Units behave different in paper and in screen! switch (unit) { case CssConstants.Em: factor = emFactor; break; case CssConstants.Px: factor = 1f; break; case CssConstants.Mm: factor = 3f; //3 pixels per millimeter break; case CssConstants.Cm: factor = 37f; //37 pixels per centimeter break; case CssConstants.In: factor = 96f; //96 pixels per inch break; case CssConstants.Pt: factor = 96f / 72f; // 1 point = 1/72 of inch if (returnPoints) { return ParseNumber(number, hundredPercent); } break; case CssConstants.Pc: factor = 96f / 72f * 12f; // 1 pica = 12 points break; default: factor = 0f; break; } return factor * ParseNumber(number, hundredPercent); } /// <summary> /// Parses a color value in CSS style; e.g. #ff0000, red, rgb(255,0,0), rgb(100%, 0, 0) /// </summary> /// <param name="colorValue">Specified color value; e.g. #ff0000, red, rgb(255,0,0), rgb(100%, 0, 0)</param> /// <returns>System.Drawing.Color value</returns> public static Color GetActualColor(string colorValue) { int r = 0; int g = 0; int b = 0; Color onError = Color.Empty; if (string.IsNullOrEmpty(colorValue)) return onError; colorValue = colorValue.ToLower().Trim(); if (colorValue.StartsWith("#")) { #region hexadecimal forms string hex = colorValue.Substring(1); if (hex.Length == 6) { r = int.Parse(hex.Substring(0, 2), System.Globalization.NumberStyles.HexNumber); g = int.Parse(hex.Substring(2, 2), System.Globalization.NumberStyles.HexNumber); b = int.Parse(hex.Substring(4, 2), System.Globalization.NumberStyles.HexNumber); } else if (hex.Length == 3) { r = int.Parse(new String(hex.Substring(0, 1)[0], 2), System.Globalization.NumberStyles.HexNumber); g = int.Parse(new String(hex.Substring(1, 1)[0], 2), System.Globalization.NumberStyles.HexNumber); b = int.Parse(new String(hex.Substring(2, 1)[0], 2), System.Globalization.NumberStyles.HexNumber); } else { return onError; } #endregion } else if (colorValue.StartsWith("rgb(") && colorValue.EndsWith(")")) { #region RGB forms string rgb = colorValue.Substring(4, colorValue.Length - 5); string[] chunks = rgb.Split(','); if (chunks.Length == 3) { unchecked { r = Convert.ToInt32(ParseNumber(chunks[0].Trim(), 255f)); g = Convert.ToInt32(ParseNumber(chunks[1].Trim(), 255f)); b = Convert.ToInt32(ParseNumber(chunks[2].Trim(), 255f)); } } else { return onError; } #endregion } else { #region Color Constants string hex = string.Empty; switch (colorValue) { case CssConstants.Maroon: hex = "#800000"; break; case CssConstants.Red: hex = "#ff0000"; break; case CssConstants.Orange: hex = "#ffA500"; break; case CssConstants.Olive: hex = "#808000"; break; case CssConstants.Purple: hex = "#800080"; break; case CssConstants.Fuchsia: hex = "#ff00ff"; break; case CssConstants.White: hex = "#ffffff"; break; case CssConstants.Lime: hex = "#00ff00"; break; case CssConstants.Green: hex = "#008000"; break; case CssConstants.Navy: hex = "#000080"; break; case CssConstants.Blue: hex = "#0000ff"; break; case CssConstants.Aqua: hex = "#00ffff"; break; case CssConstants.Teal: hex = "#008080"; break; case CssConstants.Black: hex = "#000000"; break; case CssConstants.Silver: hex = "#c0c0c0"; break; case CssConstants.Gray: hex = "#808080"; break; case CssConstants.Yellow: hex = "#FFFF00"; break; } if (string.IsNullOrEmpty(hex)) { return onError; } else { Color c = GetActualColor(hex); r = c.R; g = c.G; b = c.B; } #endregion } return Color.FromArgb(r, g, b); } /// <summary> /// Parses a border value in CSS style; e.g. 1px, 1, thin, thick, medium /// </summary> /// <param name="borderValue"></param> /// <returns></returns> public static float GetActualBorderWidth(string borderValue, CssBox b) { if (string.IsNullOrEmpty(borderValue)) { return GetActualBorderWidth(CssConstants.Medium, b); } switch (borderValue) { case CssConstants.Thin: return 1f; case CssConstants.Medium: return 2f; case CssConstants.Thick: return 4f; default: return Math.Abs(ParseLength(borderValue, 1, b)); } } /// <summary> /// Split the value by spaces; e.g. Useful in values like 'padding:5 4 3 inherit' /// </summary> /// <param name="value">Value to be splitted</param> /// <returns>Splitted and trimmed values</returns> public static string[] SplitValues(string value) { return SplitValues(value, ' '); } /// <summary> /// Split the value by the specified separator; e.g. Useful in values like 'padding:5 4 3 inherit' /// </summary> /// <param name="value">Value to be splitted</param> /// <returns>Splitted and trimmed values</returns> public static string[] SplitValues(string value, char separator) { //TODO: CRITICAL! Don't split values on parenthesis (like rgb(0, 0, 0)) or quotes ("strings") if (string.IsNullOrEmpty(value)) return new string[] { }; string[] values = value.Split(separator); List<string> result = new List<string>(); for (int i = 0; i < values.Length; i++) { string val = values[i].Trim(); if (!string.IsNullOrEmpty(val)) { result.Add(val); } } return result.ToArray(); } /// <summary> /// Detects the type name in a path. /// E.g. Gets System.Drawing.Graphics from a path like System.Drawing.Graphics.Clear /// </summary> /// <param name="path"></param> /// <returns></returns> private static Type GetTypeInfo(string path, ref string moreInfo) { int lastDot = path.LastIndexOf('.'); if (lastDot < 0) return null; string type = path.Substring(0, lastDot); moreInfo = path.Substring(lastDot + 1); moreInfo = moreInfo.Replace("(", string.Empty).Replace(")", string.Empty); foreach (Assembly a in HtmlRenderer.References) { Type t = a.GetType(type, false, true); if (t != null) return t; } return null; } /// <summary> /// Returns the object specific to the path /// </summary> /// <param name="path"></param> /// <returns>One of the following possible objects: FileInfo, MethodInfo, PropertyInfo</returns> private static object DetectSource(string path) { if (path.StartsWith("method:", StringComparison.CurrentCultureIgnoreCase)) { string methodName = string.Empty; Type t = GetTypeInfo(path.Substring(7), ref methodName); if (t == null) return null; MethodInfo method = t.GetMethod(methodName); if (!method.IsStatic || method.GetParameters().Length > 0) { return null; } return method; } else if (path.StartsWith("property:", StringComparison.CurrentCultureIgnoreCase)) { string propName = string.Empty; Type t = GetTypeInfo(path.Substring(9), ref propName); if (t == null) return null; PropertyInfo prop = t.GetProperty(propName); return prop; } else if (Uri.IsWellFormedUriString(path, UriKind.RelativeOrAbsolute)) { return new Uri(path); } else { return new FileInfo(path); } } /// <summary> /// Gets the image of the specified path /// </summary> /// <param name="path"></param> /// <returns></returns> public static Image GetImage(string path) { object source = DetectSource(path); FileInfo finfo = source as FileInfo; PropertyInfo prop = source as PropertyInfo; MethodInfo method = source as MethodInfo; try { if (finfo != null) { if (!finfo.Exists) return null; return Image.FromFile(finfo.FullName); } else if (prop != null) { if (!prop.PropertyType.IsSubclassOf(typeof(Image)) && !prop.PropertyType.Equals(typeof(Image))) return null; return prop.GetValue(null, null) as Image; } else if (method != null) { if (!method.ReturnType.IsSubclassOf(typeof(Image))) return null; return method.Invoke(null, null) as Image; } else { return null; } } catch { return new Bitmap(50, 50); //TODO: Return error image } } /// <summary> /// Gets the content of the stylesheet specified in the path /// </summary> /// <param name="path"></param> /// <returns></returns> public static string GetStyleSheet(string path) { object source = DetectSource(path); FileInfo finfo = source as FileInfo; PropertyInfo prop = source as PropertyInfo; MethodInfo method = source as MethodInfo; try { if (finfo != null) { if (!finfo.Exists) return null; StreamReader sr = new StreamReader(finfo.FullName); string result = sr.ReadToEnd(); sr.Dispose(); return result; } else if (prop != null) { if (!prop.PropertyType.Equals(typeof(string))) return null; return prop.GetValue(null, null) as string; } else if (method != null) { if (!method.ReturnType.Equals(typeof(string))) return null; return method.Invoke(null, null) as string; } else { return string.Empty; } } catch { return string.Empty; } } /// <summary> /// Executes the desired action when the user clicks a link /// </summary> /// <param name="href"></param> public static void GoLink(string href) { object source = DetectSource(href); FileInfo finfo = source as FileInfo; PropertyInfo prop = source as PropertyInfo; MethodInfo method = source as MethodInfo; Uri uri = source as Uri; try { if (finfo != null || uri != null) { ProcessStartInfo nfo = new ProcessStartInfo(href); nfo.UseShellExecute = true; Process.Start(nfo); } else if (method != null) { method.Invoke(null, null); } else { //Nothing to do. } } catch { throw; } } } }
// // 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.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using Hyak.Common; using Microsoft.Azure.Management.Automation; using Microsoft.Azure.Management.Automation.Models; using Newtonsoft.Json.Linq; namespace Microsoft.Azure.Management.Automation { /// <summary> /// Service operation for automation usages. (see /// http://aka.ms/azureautomationsdk/usageoperations for more information) /// </summary> internal partial class UsageOperations : IServiceOperations<AutomationManagementClient>, IUsageOperations { /// <summary> /// Initializes a new instance of the UsageOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal UsageOperations(AutomationManagementClient client) { this._client = client; } private AutomationManagementClient _client; /// <summary> /// Gets a reference to the /// Microsoft.Azure.Management.Automation.AutomationManagementClient. /// </summary> public AutomationManagementClient Client { get { return this._client; } } /// <summary> /// Retrieve the usage for the account id. (see /// http://aka.ms/azureautomationsdk/usageoperations for more /// information) /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response model for the get usage operation. /// </returns> public async Task<UsageListResponse> ListAsync(string resourceGroupName, string automationAccount, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (automationAccount == null) { throw new ArgumentNullException("automationAccount"); } // 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("automationAccount", automationAccount); 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/"; if (this.Client.ResourceNamespace != null) { url = url + Uri.EscapeDataString(this.Client.ResourceNamespace); } url = url + "/automationAccounts/"; url = url + Uri.EscapeDataString(automationAccount); url = url + "/usages"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2015-01-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 httpRequest.Headers.Add("Accept", "application/json"); httpRequest.Headers.Add("x-ms-version", "2014-06-01"); // 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 UsageListResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new UsageListResponse(); 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)) { Usage usageInstance = new Usage(); result.Usage.Add(usageInstance); JToken nameValue = valueValue["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { UsageCounterName nameInstance = new UsageCounterName(); usageInstance.Name = nameInstance; JToken valueValue2 = nameValue["value"]; if (valueValue2 != null && valueValue2.Type != JTokenType.Null) { string valueInstance = ((string)valueValue2); nameInstance.Value = valueInstance; } JToken localizedValueValue = nameValue["localizedValue"]; if (localizedValueValue != null && localizedValueValue.Type != JTokenType.Null) { string localizedValueInstance = ((string)localizedValueValue); nameInstance.LocalizedValue = localizedValueInstance; } } JToken unitValue = valueValue["unit"]; if (unitValue != null && unitValue.Type != JTokenType.Null) { string unitInstance = ((string)unitValue); usageInstance.Unit = unitInstance; } JToken currentValueValue = valueValue["currentValue"]; if (currentValueValue != null && currentValueValue.Type != JTokenType.Null) { long currentValueInstance = ((long)currentValueValue); usageInstance.CurrentValue = currentValueInstance; } JToken limitValue = valueValue["limit"]; if (limitValue != null && limitValue.Type != JTokenType.Null) { long limitInstance = ((long)limitValue); usageInstance.Limit = limitInstance; } } } } } 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(); } } } } }