context
stringlengths
2.52k
185k
gt
stringclasses
1 value
// 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.Immutable; using System.Linq; using System.Reflection.Metadata; using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.CSharp.UnitTests; using Microsoft.CodeAnalysis.ExpressionEvaluator; using Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests; using Microsoft.VisualStudio.Debugger.Evaluation; using Roslyn.Test.PdbUtilities; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; using Resources = Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests.Resources; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.UnitTests { public class WinMdTests : ExpressionCompilerTestBase { /// <summary> /// Handle runtime assemblies rather than Windows.winmd /// (compile-time assembly) since those are the assemblies /// loaded in the debuggee. /// </summary> [WorkItem(981104, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/981104")] [ConditionalFact(typeof(OSVersionWin8))] public void Win8RuntimeAssemblies() { var source = @"class C { static void M(Windows.Storage.StorageFolder f, Windows.Foundation.Collections.PropertySet p) { } }"; var compilation0 = CreateStandardCompilation( source, options: TestOptions.DebugDll, assemblyName: ExpressionCompilerUtilities.GenerateUniqueName(), references: WinRtRefs); var runtimeAssemblies = ExpressionCompilerTestHelpers.GetRuntimeWinMds("Windows.Storage", "Windows.Foundation.Collections"); Assert.True(runtimeAssemblies.Length >= 2); // no reference to Windows.winmd WithRuntimeInstance(compilation0, new[] { MscorlibRef }.Concat(runtimeAssemblies), runtime => { var context = CreateMethodContext(runtime, "C.M"); string error; var testData = new CompilationTestData(); context.CompileExpression("(p == null) ? f : null", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.1 IL_0001: brfalse.s IL_0005 IL_0003: ldnull IL_0004: ret IL_0005: ldarg.0 IL_0006: ret }"); }); } [ConditionalFact(typeof(OSVersionWin8))] public void Win8RuntimeAssemblies_ExternAlias() { var source = @"extern alias X; class C { static void M(X::Windows.Storage.StorageFolder f) { } }"; var compilation0 = CreateStandardCompilation( source, options: TestOptions.DebugDll, assemblyName: ExpressionCompilerUtilities.GenerateUniqueName(), references: WinRtRefs.Select(r => r.Display == "Windows" ? r.WithAliases(new[] { "X" }) : r)); var runtimeAssemblies = ExpressionCompilerTestHelpers.GetRuntimeWinMds("Windows.Storage"); Assert.True(runtimeAssemblies.Length >= 1); // no reference to Windows.winmd WithRuntimeInstance(compilation0, new[] { MscorlibRef }.Concat(runtimeAssemblies), runtime => { var context = CreateMethodContext(runtime, "C.M"); string error; var testData = new CompilationTestData(); context.CompileExpression("X::Windows.Storage.FileProperties.PhotoOrientation.Unspecified", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 2 (0x2) .maxstack 1 IL_0000: ldc.i4.0 IL_0001: ret }"); }); } [Fact] public void Win8OnWin8() { CompileTimeAndRuntimeAssemblies( ImmutableArray.Create( MscorlibRef, AssemblyMetadata.CreateFromImage(ToVersion1_3(Resources.Windows)).GetReference(), AssemblyMetadata.CreateFromImage(ToVersion1_3(Resources.LibraryA)).GetReference(), AssemblyMetadata.CreateFromImage(Resources.LibraryB).GetReference()), ImmutableArray.Create( MscorlibRef, AssemblyMetadata.CreateFromImage(ToVersion1_3(Resources.Windows_Data)).GetReference(), AssemblyMetadata.CreateFromImage(ToVersion1_3(Resources.Windows_Storage)).GetReference(), AssemblyMetadata.CreateFromImage(ToVersion1_3(Resources.LibraryA)).GetReference(), AssemblyMetadata.CreateFromImage(Resources.LibraryB).GetReference()), "Windows.Storage"); } [Fact] public void Win8OnWin10() { CompileTimeAndRuntimeAssemblies( ImmutableArray.Create( MscorlibRef, AssemblyMetadata.CreateFromImage(ToVersion1_3(Resources.Windows)).GetReference(), AssemblyMetadata.CreateFromImage(ToVersion1_3(Resources.LibraryA)).GetReference(), AssemblyMetadata.CreateFromImage(Resources.LibraryB).GetReference()), ImmutableArray.Create( MscorlibRef, AssemblyMetadata.CreateFromImage(ToVersion1_4(Resources.Windows_Data)).GetReference(), AssemblyMetadata.CreateFromImage(ToVersion1_4(Resources.Windows_Storage)).GetReference(), AssemblyMetadata.CreateFromImage(ToVersion1_3(Resources.LibraryA)).GetReference(), AssemblyMetadata.CreateFromImage(Resources.LibraryB).GetReference()), "Windows.Storage"); } [WorkItem(1108135, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1108135")] [Fact] public void Win10OnWin10() { CompileTimeAndRuntimeAssemblies( ImmutableArray.Create( MscorlibRef, AssemblyMetadata.CreateFromImage(ToVersion1_4(Resources.Windows_Data)).GetReference(), AssemblyMetadata.CreateFromImage(ToVersion1_4(Resources.Windows_Storage)).GetReference(), AssemblyMetadata.CreateFromImage(ToVersion1_4(Resources.LibraryA)).GetReference(), AssemblyMetadata.CreateFromImage(Resources.LibraryB).GetReference()), ImmutableArray.Create( MscorlibRef, AssemblyMetadata.CreateFromImage(ToVersion1_4(Resources.Windows)).GetReference(), AssemblyMetadata.CreateFromImage(ToVersion1_4(Resources.LibraryA)).GetReference(), AssemblyMetadata.CreateFromImage(Resources.LibraryB).GetReference()), "Windows"); } private void CompileTimeAndRuntimeAssemblies( ImmutableArray<MetadataReference> compileReferences, ImmutableArray<MetadataReference> runtimeReferences, string storageAssemblyName) { var source = @"class C { static void M(LibraryA.A a, LibraryB.B b, Windows.Data.Text.TextSegment t, Windows.Storage.StorageFolder f) { } }"; var compilation0 = CreateStandardCompilation(source, compileReferences, TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtimeReferences, runtime => { var context = CreateMethodContext(runtime, "C.M"); string error; var testData = new CompilationTestData(); context.CompileExpression("(object)a ?? (object)b ?? (object)t ?? f", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 17 (0x11) .maxstack 2 IL_0000: ldarg.0 IL_0001: dup IL_0002: brtrue.s IL_0010 IL_0004: pop IL_0005: ldarg.1 IL_0006: dup IL_0007: brtrue.s IL_0010 IL_0009: pop IL_000a: ldarg.2 IL_000b: dup IL_000c: brtrue.s IL_0010 IL_000e: pop IL_000f: ldarg.3 IL_0010: ret }"); testData = new CompilationTestData(); var result = context.CompileExpression("default(Windows.Storage.StorageFolder)", out error, testData); Assert.Null(error); var methodData = testData.GetMethodData("<>x.<>m0"); methodData.VerifyIL( @"{ // Code size 2 (0x2) .maxstack 1 IL_0000: ldnull IL_0001: ret }"); // Check return type is from runtime assembly. var assemblyReference = AssemblyMetadata.CreateFromImage(result.Assembly).GetReference(); var compilation = CSharpCompilation.Create( assemblyName: ExpressionCompilerUtilities.GenerateUniqueName(), references: runtimeReferences.Concat(ImmutableArray.Create<MetadataReference>(assemblyReference))); var assembly = ImmutableArray.CreateRange(result.Assembly); using (var metadata = ModuleMetadata.CreateFromImage(ImmutableArray.CreateRange(assembly))) { var reader = metadata.MetadataReader; var typeDef = reader.GetTypeDef("<>x"); var methodHandle = reader.GetMethodDefHandle(typeDef, "<>m0"); var module = (PEModuleSymbol)compilation.GetMember("<>x").ContainingModule; var metadataDecoder = new MetadataDecoder(module); SignatureHeader signatureHeader; BadImageFormatException metadataException; var parameters = metadataDecoder.GetSignatureForMethod(methodHandle, out signatureHeader, out metadataException); Assert.Equal(parameters.Length, 5); var actualReturnType = parameters[0].Type; Assert.Equal(actualReturnType.TypeKind, TypeKind.Class); // not error var expectedReturnType = compilation.GetMember("Windows.Storage.StorageFolder"); Assert.Equal(expectedReturnType, actualReturnType); Assert.Equal(storageAssemblyName, actualReturnType.ContainingAssembly.Name); } }); } /// <summary> /// Assembly-qualified name containing "ContentType=WindowsRuntime", /// and referencing runtime assembly. /// </summary> [WorkItem(1116143, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1116143")] [ConditionalFact(typeof(OSVersionWin8))] public void AssemblyQualifiedName() { var source = @"class C { static void M(Windows.Storage.StorageFolder f, Windows.Foundation.Collections.PropertySet p) { } }"; var compilation = CreateStandardCompilation(source, WinRtRefs, TestOptions.DebugDll); WithRuntimeInstance(compilation, new[] { MscorlibRef }.Concat(ExpressionCompilerTestHelpers.GetRuntimeWinMds("Windows.Storage", "Windows.Foundation.Collections")), runtime => { var context = CreateMethodContext(runtime, "C.M"); var aliases = ImmutableArray.Create( VariableAlias("s", "Windows.Storage.StorageFolder, Windows.Storage, Version=255.255.255.255, Culture=neutral, PublicKeyToken=null, ContentType=WindowsRuntime"), VariableAlias("d", "Windows.Foundation.DateTime, Windows.Foundation, Version=255.255.255.255, Culture=neutral, PublicKeyToken=null, ContentType=WindowsRuntime")); string error; var testData = new CompilationTestData(); context.CompileExpression( "(object)s.Attributes ?? d.UniversalTime", DkmEvaluationFlags.TreatAsExpression, aliases, out error, testData); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 55 (0x37) .maxstack 2 IL_0000: ldstr ""s"" IL_0005: call ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(string)"" IL_000a: castclass ""Windows.Storage.StorageFolder"" IL_000f: callvirt ""Windows.Storage.FileAttributes Windows.Storage.StorageFolder.Attributes.get"" IL_0014: box ""Windows.Storage.FileAttributes"" IL_0019: dup IL_001a: brtrue.s IL_0036 IL_001c: pop IL_001d: ldstr ""d"" IL_0022: call ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(string)"" IL_0027: unbox.any ""Windows.Foundation.DateTime"" IL_002c: ldfld ""long Windows.Foundation.DateTime.UniversalTime"" IL_0031: box ""long"" IL_0036: ret }"); }); } [WorkItem(1117084, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1117084")] [Fact] public void OtherFrameworkAssembly() { var source = @"class C { static void M(Windows.UI.Xaml.FrameworkElement f) { } }"; var compilation = CreateStandardCompilation(source, WinRtRefs, TestOptions.DebugDll); WithRuntimeInstance(compilation, new[] { MscorlibRef }.Concat(ExpressionCompilerTestHelpers.GetRuntimeWinMds("Windows.Foundation", "Windows.UI", "Windows.UI.Xaml")), runtime => { var context = CreateMethodContext(runtime, "C.M"); string error; ResultProperties resultProperties; ImmutableArray<AssemblyIdentity> missingAssemblyIdentities; var testData = new CompilationTestData(); var result = context.CompileExpression( "f.RenderSize", DkmEvaluationFlags.TreatAsExpression, NoAliases, DebuggerDiagnosticFormatter.Instance, out resultProperties, out error, out missingAssemblyIdentities, EnsureEnglishUICulture.PreferredOrNull, testData); var expectedAssemblyIdentity = WinRtRefs.Single(r => r.Display == "System.Runtime.WindowsRuntime.dll").GetAssemblyIdentity(); Assert.Equal(expectedAssemblyIdentity, missingAssemblyIdentities.Single()); }); } [WorkItem(1154988, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1154988")] [ConditionalFact(typeof(OSVersionWin8))] public void WinMdAssemblyReferenceRequiresRedirect() { var source = @"class C : Windows.UI.Xaml.Controls.UserControl { static void M(C c) { } }"; var compilation = CreateStandardCompilation(source, WinRtRefs, TestOptions.DebugDll); WithRuntimeInstance(compilation, new[] { MscorlibRef }.Concat(ExpressionCompilerTestHelpers.GetRuntimeWinMds("Windows.UI", "Windows.UI.Xaml")), runtime => { string errorMessage; var testData = new CompilationTestData(); ExpressionCompilerTestHelpers.CompileExpressionWithRetry( runtime.Modules.SelectAsArray(m => m.MetadataBlock), "c.Dispatcher", ImmutableArray<Alias>.Empty, (metadataBlocks, _) => { return CreateMethodContext(runtime, "C.M"); }, (AssemblyIdentity assembly, out uint size) => { // Compilation should succeed without retry if we redirect assembly refs correctly. // Throwing so that we don't loop forever (as we did before fix)... throw ExceptionUtilities.Unreachable; }, out errorMessage, out testData); Assert.Null(errorMessage); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: callvirt ""Windows.UI.Core.CoreDispatcher Windows.UI.Xaml.DependencyObject.Dispatcher.get"" IL_0006: ret }"); }); } private static byte[] ToVersion1_3(byte[] bytes) { return ExpressionCompilerTestHelpers.ToVersion1_3(bytes); } private static byte[] ToVersion1_4(byte[] bytes) { return ExpressionCompilerTestHelpers.ToVersion1_4(bytes); } } }
//*********************************************************// // Copyright (c) Microsoft. All rights reserved. // // Apache 2.0 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.Diagnostics.CodeAnalysis; using System.Globalization; using System.Runtime.InteropServices; using Microsoft.VisualStudio.Designer.Interfaces; using Microsoft.VisualStudio.OLE.Interop; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.TextManager.Interop; using ErrorHandler = Microsoft.VisualStudio.ErrorHandler; using IOleServiceProvider = Microsoft.VisualStudio.OLE.Interop.IServiceProvider; using VSConstants = Microsoft.VisualStudio.VSConstants; namespace Microsoft.VisualStudioTools.Project { /// <summary> /// Common factory for creating our editor /// </summary> [SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable")] public abstract class CommonEditorFactory : IVsEditorFactory { private Package _package; private ServiceProvider _serviceProvider; private readonly bool _promptEncodingOnLoad; public CommonEditorFactory(Package package) { _package = package; } public CommonEditorFactory(Package package, bool promptEncodingOnLoad) { _package = package; _promptEncodingOnLoad = promptEncodingOnLoad; } #region IVsEditorFactory Members public virtual int SetSite(Microsoft.VisualStudio.OLE.Interop.IServiceProvider psp) { _serviceProvider = new ServiceProvider(psp); return VSConstants.S_OK; } public virtual object GetService(Type serviceType) { return _serviceProvider.GetService(serviceType); } // This method is called by the Environment (inside IVsUIShellOpenDocument:: // OpenStandardEditor and OpenSpecificEditor) to map a LOGICAL view to a // PHYSICAL view. A LOGICAL view identifies the purpose of the view that is // desired (e.g. a view appropriate for Debugging [LOGVIEWID_Debugging], or a // view appropriate for text view manipulation as by navigating to a find // result [LOGVIEWID_TextView]). A PHYSICAL view identifies an actual type // of view implementation that an IVsEditorFactory can create. // // NOTE: Physical views are identified by a string of your choice with the // one constraint that the default/primary physical view for an editor // *MUST* use a NULL string as its physical view name (*pbstrPhysicalView = NULL). // // NOTE: It is essential that the implementation of MapLogicalView properly // validates that the LogicalView desired is actually supported by the editor. // If an unsupported LogicalView is requested then E_NOTIMPL must be returned. // // NOTE: The special Logical Views supported by an Editor Factory must also // be registered in the local registry hive. LOGVIEWID_Primary is implicitly // supported by all editor types and does not need to be registered. // For example, an editor that supports a ViewCode/ViewDesigner scenario // might register something like the following: // HKLM\Software\Microsoft\VisualStudio\9.0\Editors\ // {...guidEditor...}\ // LogicalViews\ // {...LOGVIEWID_TextView...} = s '' // {...LOGVIEWID_Code...} = s '' // {...LOGVIEWID_Debugging...} = s '' // {...LOGVIEWID_Designer...} = s 'Form' // public virtual int MapLogicalView(ref Guid logicalView, out string physicalView) { // initialize out parameter physicalView = null; bool isSupportedView = false; // Determine the physical view if (VSConstants.LOGVIEWID_Primary == logicalView || VSConstants.LOGVIEWID_Debugging == logicalView || VSConstants.LOGVIEWID_Code == logicalView || VSConstants.LOGVIEWID_TextView == logicalView) { // primary view uses NULL as pbstrPhysicalView isSupportedView = true; } else if (VSConstants.LOGVIEWID_Designer == logicalView) { physicalView = "Design"; isSupportedView = true; } if (isSupportedView) return VSConstants.S_OK; else { // E_NOTIMPL must be returned for any unrecognized rguidLogicalView values return VSConstants.E_NOTIMPL; } } public virtual int Close() { return VSConstants.S_OK; } /// <summary> /// /// </summary> /// <param name="grfCreateDoc"></param> /// <param name="pszMkDocument"></param> /// <param name="pszPhysicalView"></param> /// <param name="pvHier"></param> /// <param name="itemid"></param> /// <param name="punkDocDataExisting"></param> /// <param name="ppunkDocView"></param> /// <param name="ppunkDocData"></param> /// <param name="pbstrEditorCaption"></param> /// <param name="pguidCmdUI"></param> /// <param name="pgrfCDW"></param> /// <returns></returns> public virtual int CreateEditorInstance( uint createEditorFlags, string documentMoniker, string physicalView, IVsHierarchy hierarchy, uint itemid, System.IntPtr docDataExisting, out System.IntPtr docView, out System.IntPtr docData, out string editorCaption, out Guid commandUIGuid, out int createDocumentWindowFlags) { // Initialize output parameters docView = IntPtr.Zero; docData = IntPtr.Zero; commandUIGuid = Guid.Empty; createDocumentWindowFlags = 0; editorCaption = null; // Validate inputs if ((createEditorFlags & (VSConstants.CEF_OPENFILE | VSConstants.CEF_SILENT)) == 0) { return VSConstants.E_INVALIDARG; } if (_promptEncodingOnLoad && docDataExisting != IntPtr.Zero) { return VSConstants.VS_E_INCOMPATIBLEDOCDATA; } // Get a text buffer IVsTextLines textLines = GetTextBuffer(docDataExisting); // Assign docData IntPtr to either existing docData or the new text buffer if (docDataExisting != IntPtr.Zero) { docData = docDataExisting; Marshal.AddRef(docData); } else { docData = Marshal.GetIUnknownForObject(textLines); } try { docView = CreateDocumentView(documentMoniker, physicalView, hierarchy, itemid, textLines, out editorCaption, out commandUIGuid); } finally { if (docView == IntPtr.Zero) { if (docDataExisting != docData && docData != IntPtr.Zero) { // Cleanup the instance of the docData that we have addref'ed Marshal.Release(docData); docData = IntPtr.Zero; } } } return VSConstants.S_OK; } #endregion #region Helper methods private IVsTextLines GetTextBuffer(System.IntPtr docDataExisting) { IVsTextLines textLines; if (docDataExisting == IntPtr.Zero) { // Create a new IVsTextLines buffer. Type textLinesType = typeof(IVsTextLines); Guid riid = textLinesType.GUID; Guid clsid = typeof(VsTextBufferClass).GUID; textLines = _package.CreateInstance(ref clsid, ref riid, textLinesType) as IVsTextLines; // set the buffer's site ((IObjectWithSite)textLines).SetSite(_serviceProvider.GetService(typeof(IOleServiceProvider))); } else { // Use the existing text buffer Object dataObject = Marshal.GetObjectForIUnknown(docDataExisting); textLines = dataObject as IVsTextLines; if (textLines == null) { // Try get the text buffer from textbuffer provider IVsTextBufferProvider textBufferProvider = dataObject as IVsTextBufferProvider; if (textBufferProvider != null) { textBufferProvider.GetTextBuffer(out textLines); } } if (textLines == null) { // Unknown docData type then, so we have to force VS to close the other editor. ErrorHandler.ThrowOnFailure((int)VSConstants.VS_E_INCOMPATIBLEDOCDATA); } } return textLines; } private IntPtr CreateDocumentView(string documentMoniker, string physicalView, IVsHierarchy hierarchy, uint itemid, IVsTextLines textLines, out string editorCaption, out Guid cmdUI) { //Init out params editorCaption = string.Empty; cmdUI = Guid.Empty; if (string.IsNullOrEmpty(physicalView)) { // create code window as default physical view return CreateCodeView(documentMoniker, textLines, ref editorCaption, ref cmdUI); } else if (string.Compare(physicalView, "design", true, CultureInfo.InvariantCulture) == 0) { // Create Form view return CreateFormView(hierarchy, itemid, textLines, ref editorCaption, ref cmdUI); } // We couldn't create the view // Return special error code so VS can try another editor factory. ErrorHandler.ThrowOnFailure((int)VSConstants.VS_E_UNSUPPORTEDFORMAT); return IntPtr.Zero; } private IntPtr CreateFormView(IVsHierarchy hierarchy, uint itemid, IVsTextLines textLines, ref string editorCaption, ref Guid cmdUI) { // Request the Designer Service IVSMDDesignerService designerService = (IVSMDDesignerService)GetService(typeof(IVSMDDesignerService)); // Create loader for the designer IVSMDDesignerLoader designerLoader = (IVSMDDesignerLoader)designerService.CreateDesignerLoader("Microsoft.VisualStudio.Designer.Serialization.VSDesignerLoader"); bool loaderInitalized = false; try { IOleServiceProvider provider = _serviceProvider.GetService(typeof(IOleServiceProvider)) as IOleServiceProvider; // Initialize designer loader designerLoader.Initialize(provider, hierarchy, (int)itemid, textLines); loaderInitalized = true; // Create the designer IVSMDDesigner designer = designerService.CreateDesigner(provider, designerLoader); // Get editor caption editorCaption = designerLoader.GetEditorCaption((int)READONLYSTATUS.ROSTATUS_Unknown); // Get view from designer object docView = designer.View; // Get command guid from designer cmdUI = designer.CommandGuid; return Marshal.GetIUnknownForObject(docView); } catch { // The designer loader may have created a reference to the shell or the text buffer. // In case we fail to create the designer we should manually dispose the loader // in order to release the references to the shell and the textbuffer if (loaderInitalized) { designerLoader.Dispose(); } throw; } } private IntPtr CreateCodeView(string documentMoniker, IVsTextLines textLines, ref string editorCaption, ref Guid cmdUI) { Type codeWindowType = typeof(IVsCodeWindow); Guid riid = codeWindowType.GUID; Guid clsid = typeof(VsCodeWindowClass).GUID; IVsCodeWindow window = (IVsCodeWindow)_package.CreateInstance(ref clsid, ref riid, codeWindowType); ErrorHandler.ThrowOnFailure(window.SetBuffer(textLines)); ErrorHandler.ThrowOnFailure(window.SetBaseEditorCaption(null)); ErrorHandler.ThrowOnFailure(window.GetEditorCaption(READONLYSTATUS.ROSTATUS_Unknown, out editorCaption)); IVsUserData userData = textLines as IVsUserData; if (userData != null) { if (_promptEncodingOnLoad) { var guid = VSConstants.VsTextBufferUserDataGuid.VsBufferEncodingPromptOnLoad_guid; userData.SetData(ref guid, (uint)1); } } InitializeLanguageService(textLines); cmdUI = VSConstants.GUID_TextEditorFactory; return Marshal.GetIUnknownForObject(window); } /// <summary> /// Initializes the language service for the given file. This allows files with different /// extensions to be opened by the editor type and get correct highlighting and intellisense /// controllers. /// /// New in 1.1 /// </summary> protected virtual void InitializeLanguageService(IVsTextLines textLines) { } #endregion protected void InitializeLanguageService(IVsTextLines textLines, Guid langSid) { IVsUserData userData = textLines as IVsUserData; if (userData != null) { if (langSid != Guid.Empty) { Guid vsCoreSid = new Guid("{8239bec4-ee87-11d0-8c98-00c04fc2ab22}"); Guid currentSid; ErrorHandler.ThrowOnFailure(textLines.GetLanguageServiceID(out currentSid)); // If the language service is set to the default SID, then // set it to our language if (currentSid == vsCoreSid) { ErrorHandler.ThrowOnFailure(textLines.SetLanguageServiceID(ref langSid)); } else if (currentSid != langSid) { // Some other language service has it, so return VS_E_INCOMPATIBLEDOCDATA throw new COMException("Incompatible doc data", VSConstants.VS_E_INCOMPATIBLEDOCDATA); } Guid bufferDetectLang = VSConstants.VsTextBufferUserDataGuid.VsBufferDetectLangSID_guid; ErrorHandler.ThrowOnFailure(userData.SetData(ref bufferDetectLang, false)); } } } } }
// Copyright (c) 2011, Eric Maupin // 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 Gablarski nor the names of its // contributors may be used to endorse or promote products // or services derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS // AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED // WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE // GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF // THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH // DAMAGE. using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Runtime.InteropServices; using System.Security; using Gablarski.Audio; using Gablarski.OpenAL; namespace Gablarski.OpenAL { [SuppressUnmanagedCodeSecurity] public static class OpenAL { static OpenAL () { #if DEBUG OpenAL.ErrorChecking = true; #endif Log = log4net.LogManager.GetLogger ("OpenAL"); DebugLogging = Log.IsDebugEnabled; IsCaptureSupported = GetIsExtensionPresent ("ALC_EXT_CAPTURE"); } /// <summary> /// Sets the distance model for OpenAL. /// </summary> public static DistanceModel DistanceModel { set { alDistanceModel (value); OpenAL.ErrorCheck (); } } /// <summary> /// Sets the speed of sound for OpenAL. /// </summary> public static float SpeedOfSound { set { alSpeedOfSound (value); OpenAL.ErrorCheck (); } } /// <summary> /// Sets the doppler factor for OpenAL. /// </summary> public static float DopplerFactor { set { alDopplerFactor (value); OpenAL.ErrorCheck (); } } /// <summary> /// Gets whether capture support is available. /// </summary> public static bool IsCaptureSupported { get; private set; } /// <summary> /// Gets or sets whether error checking is enabled. /// </summary> public static bool ErrorChecking { get; private set; } /// <summary> /// Gets the underlying OpenAL provider version. /// </summary> public static string Version { get { return Marshal.PtrToStringAnsi (alGetString (AL_VERSION)); } } public static PlaybackDevice GetDefaultPlaybackDevice() { PlaybackDevice defaultDevice; GetPlaybackDevices (out defaultDevice); return defaultDevice; } public static IEnumerable<PlaybackDevice> GetPlaybackDevices() { PlaybackDevice defaultDevice; return GetPlaybackDevices (out defaultDevice); } public static IEnumerable<PlaybackDevice> GetPlaybackDevices (out PlaybackDevice defaultDevice) { defaultDevice = null; OpenAL.Debug ("Getting playback devices"); string defaultName = null; string[] strings = new string[0]; if (GetIsExtensionPresent ("ALC_ENUMERATE_ALL_EXT")) { defaultName = Marshal.PtrToStringAnsi (alcGetString (IntPtr.Zero, ALC_DEFAULT_ALL_DEVICES_SPECIFIER)); strings = ReadStringsFromMemory (alcGetString (IntPtr.Zero, ALC_ALL_DEVICES_SPECIFIER)); } else if (GetIsExtensionPresent ("ALC_ENUMERATION_EXT")) { defaultName = Marshal.PtrToStringAnsi (alcGetString (IntPtr.Zero, ALC_DEFAULT_DEVICE_SPECIFIER)); strings = ReadStringsFromMemory (alcGetString (IntPtr.Zero, ALC_DEVICE_SPECIFIER)); } PlaybackDevice[] devices = new PlaybackDevice[strings.Length]; for (int i = 0; i < strings.Length; ++i) { string s = strings[i]; devices[i] = new PlaybackDevice (s); if (s == defaultName) defaultDevice = devices[i]; OpenAL.DebugFormat ("Found playback device {0}{1}", s, (s == defaultName) ? " (Default)" : String.Empty); } return devices; } public static CaptureDevice GetDefaultCaptureDevice() { //if (!IsCaptureSupported) // throw new NotSupportedException(); CaptureDevice defaultDevice; GetCaptureDevices (out defaultDevice); return defaultDevice; } public static IEnumerable<CaptureDevice> GetCaptureDevices() { CaptureDevice def; return GetCaptureDevices (out def); } public static IEnumerable<CaptureDevice> GetCaptureDevices (out CaptureDevice defaultDevice) { //if (!IsCaptureSupported) // throw new NotSupportedException(); OpenAL.Debug ("Getting capture devices"); defaultDevice = null; string defaultName = Marshal.PtrToStringAnsi (alcGetString (IntPtr.Zero, ALC_CAPTURE_DEFAULT_DEVICE_SPECIFIER)); var strings = ReadStringsFromMemory (alcGetString (IntPtr.Zero, ALC_CAPTURE_DEVICE_SPECIFIER)); CaptureDevice[] devices = new CaptureDevice[strings.Length]; for (int i = 0; i < strings.Length; ++i) { string s = strings[i]; devices[i] = new CaptureDevice (s); if (s == defaultName) defaultDevice = devices[i]; OpenAL.DebugFormat ("Found capture device {0}{1}", s, (s == defaultName) ? " (Default)" : String.Empty); } return devices; } #region OpenALAudioFormat Extensions public static OpenALAudioFormat ToOpenALFormat (this AudioFormat format) { OpenALAudioFormat oalFormat = OpenALAudioFormat.Unknown; if (format.Channels == 1) { if (format.BitsPerSample == 8) oalFormat = OpenALAudioFormat.Mono8Bit; else if (format.BitsPerSample == 16) oalFormat = OpenALAudioFormat.Mono16Bit; } else if (format.Channels == 2) { if (format.BitsPerSample == 8) oalFormat = OpenALAudioFormat.Stereo8Bit; else if (format.BitsPerSample == 16) oalFormat = OpenALAudioFormat.Stereo16Bit; } return oalFormat; } public static uint GetBytesPerSample (this OpenALAudioFormat self) { switch (self) { default: case OpenALAudioFormat.Mono8Bit: return 1; case OpenALAudioFormat.Mono16Bit: case OpenALAudioFormat.Stereo8Bit: return 2; case OpenALAudioFormat.Stereo16Bit: return 4; } } public static uint GetBytes (this OpenALAudioFormat self, uint samples) { return self.GetBytesPerSample () * samples; } public static uint GetSamplesPerSecond (this OpenALAudioFormat self, uint frequency) { switch (self) { default: case OpenALAudioFormat.Mono8Bit: case OpenALAudioFormat.Mono16Bit: return frequency; case OpenALAudioFormat.Stereo8Bit: case OpenALAudioFormat.Stereo16Bit: return (frequency * 2); } } #endregion internal static IntPtr NullDevice = IntPtr.Zero; #region Imports // ReSharper disable InconsistentNaming [DllImport ("OpenAL32.dll", CallingConvention = CallingConvention.Cdecl)] internal static extern void alDopplerFactor (float value); [DllImport ("OpenAL32.dll", CallingConvention = CallingConvention.Cdecl)] internal static extern void alSpeedOfSound (float value); [DllImport ("OpenAL32.dll", CallingConvention = CallingConvention.Cdecl)] internal static extern void alcGetIntegerv (IntPtr device, ALCEnum param, int size, out int data); [DllImport ("OpenAL32.dll", CallingConvention = CallingConvention.Cdecl)] internal static extern IntPtr alGetString (int name); [DllImport ("OpenAL32.dll", CallingConvention=CallingConvention.Cdecl)] internal static extern IntPtr alcGetString ([In] IntPtr device, int name); [DllImport ("OpenAL32.dll", CallingConvention=CallingConvention.Cdecl)] internal static extern int alGetError (); [DllImport ("OpenAL32.dll", CallingConvention=CallingConvention.Cdecl)] internal static extern int alcGetError ([In] IntPtr device); [DllImport ("OpenAL32.dll", CallingConvention = CallingConvention.Cdecl)] internal static extern sbyte alcIsExtensionPresent ([In] IntPtr device, string extensionName); [DllImport ("OpenAL32.dll", CallingConvention = CallingConvention.Cdecl)] internal static extern sbyte alIsExtensionPresent (string extensionName); [DllImport ("OpenAL32.dll", CallingConvention = CallingConvention.Cdecl)] internal static extern void alDistanceModel (DistanceModel model); // ReSharper restore InconsistentNaming #endregion internal static bool DebugLogging { get; private set; } internal static log4net.ILog Log { get; private set; } internal static void Debug (string message) { if (DebugLogging) Log.Debug (message); } internal static void DebugFormat (string format, params object[] args) { if (DebugLogging) Log.DebugFormat (format, args); } internal static bool GetIsExtensionPresent (string extension) { sbyte result; if (extension.StartsWith ("ALC")) { result = alcIsExtensionPresent (IntPtr.Zero, extension); } else { result = alIsExtensionPresent (extension); OpenAL.ErrorCheck (); } return (result == 1); } internal static bool GetIsExtensionPresent (Device device, string extension) { sbyte result; if (extension.StartsWith ("ALC")) { result = alcIsExtensionPresent (device.Handle, extension); OpenAL.ErrorCheck (device); } else { result = alIsExtensionPresent (extension); OpenAL.ErrorCheck (); } return (result == 1); } internal static string[] ReadStringsFromMemory (IntPtr location) { List<string> strings = new List<string> (); bool lastNull = false; int i = -1; byte c; while (!((c = Marshal.ReadByte (location, ++i)) == '\0' && lastNull)) { if (c == '\0') { lastNull = true; strings.Add (Marshal.PtrToStringAnsi (location, i)); location = new IntPtr ((long)location + i + 1); i = -1; } else lastNull = false; } return strings.ToArray(); } [DebuggerStepThrough] internal static void ErrorCheck () { if (!ErrorChecking) return; int err = alGetError (); switch ((ALError)err) { case ALError.AL_NO_ERROR: return; case ALError.AL_OUT_OF_MEMORY: throw new OutOfMemoryException ("OpenAL (AL) out of memory."); case ALError.AL_INVALID_ENUM: throw new ArgumentException ("Invalid enum"); case ALError.AL_INVALID_NAME: throw new ArgumentException ("Invalid name"); case ALError.AL_INVALID_VALUE: throw new ArgumentException ("Invalid value"); case ALError.AL_INVALID_OPERATION: throw new InvalidOperationException (); } } [DebuggerStepThrough] internal static void ErrorCheck (Device device) { int error = alcGetError (device.Handle); switch ((ALCError)error) { case ALCError.ALC_NO_ERROR: return; case ALCError.ALC_INVALID_ENUM: throw new ArgumentException ("Invalid enum"); case ALCError.ALC_INVALID_VALUE: throw new ArgumentException ("Invalid value"); case ALCError.ALC_INVALID_CONTEXT: throw new ArgumentException ("Invalid context"); case ALCError.ALC_INVALID_DEVICE: throw new ArgumentException ("Invalid device"); case ALCError.ALC_OUT_OF_MEMORY: throw new OutOfMemoryException ("OpenAL (ALC) out of memory."); } } // ReSharper disable InconsistentNaming internal const int AL_VERSION = 0xB002; internal const int ALC_DEFAULT_DEVICE_SPECIFIER = 0x1004; internal const int ALC_DEVICE_SPECIFIER = 0x1005; internal const int ALC_CAPTURE_DEVICE_SPECIFIER = 0x310; internal const int ALC_CAPTURE_DEFAULT_DEVICE_SPECIFIER = 0x311; internal const int ALC_ALL_DEVICES_SPECIFIER = 0x1013; internal const int ALC_DEFAULT_ALL_DEVICES_SPECIFIER = 0x1012; // ReSharper restore InconsistentNaming } // ReSharper disable InconsistentNaming internal enum ALError { AL_NO_ERROR = 0, AL_INVALID_NAME = 0xA001, AL_INVALID_ENUM = 0xA002, AL_INVALID_VALUE = 0xA003, AL_INVALID_OPERATION = 0xA004, AL_OUT_OF_MEMORY = 0xA005, } internal enum ALCError { ALC_NO_ERROR = 0, ALC_INVALID_DEVICE = 0xA001, ALC_INVALID_CONTEXT = 0xA002, ALC_INVALID_ENUM = 0xA003, ALC_INVALID_VALUE = 0xA004, ALC_OUT_OF_MEMORY = 0xA005 } internal enum ALEnum { AL_GAIN = 0x100A, AL_FREQUENCY = 0x2001, AL_BITS = 0x2002, AL_CHANNELS = 0x2003, AL_SIZE = 0x2004, } internal enum ALCEnum { ALC_MAJOR_VERSION = 0x1000, ALC_MINOR_VERSION = 0x1001, ALC_ATTRIBUTES_SIZE = 0x1002, ALC_ALL_ATTRIBUTES = 0x1003, ALC_CAPTURE_SAMPLES = 0x312, ALC_CONNECTED = 0x313, ALC_FREQUENCY = 0x1007, ALC_REFRESH = 0x1008, ALC_SYNC = 0x1009, ALC_MONO_SOURCES = 0x1010, ALC_STEREO_SOURCES = 0x1011, } public enum DistanceModel { None = 0 } public enum OpenALAudioFormat { Unknown = 0, Mono8Bit = 0x1100, Mono16Bit = 0x1101, Stereo8Bit = 0x1102, Stereo16Bit = 0x1103 } // ReSharper restore InconsistentNaming }
/* * MindTouch Core - open source enterprise collaborative networking * Copyright (c) 2006-2010 MindTouch Inc. * www.mindtouch.com oss@mindtouch.com * * For community documentation and downloads visit www.opengarden.org; * please review the licensing section. * * 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. * http://www.gnu.org/copyleft/gpl.html */ using System; using System.Globalization; using System.Collections.Generic; using System.Text; using MindTouch.Dream; using MindTouch.Dream.Test; using MindTouch.Xml; using MindTouch.Tasking; using NUnit.Framework; namespace MindTouch.Deki.Tests { public static class PageUtils { public static string GenerateUniquePageName() { string prefix = "tests/"; prefix += DateTime.Now.ToString("yyyy-MM-dd/HH-mm", CultureInfo.InvariantCulture); prefix += "/p"; return Utils.GenerateUniqueName(prefix); } public static DreamMessage CreateRandomPage(Plug p) { return CreateRandomPage(p, GenerateUniquePageName()); } public static DreamMessage CreateRandomPage(Plug p, string pageTitle) { return PageUtils.SavePage(p, pageTitle, Utils.GetSmallRandomText()); } public static DreamMessage CreateRandomPage(Plug p, out string id) { string path = null; string title = GenerateUniquePageName(); return PageUtils.SavePage(p, string.Empty, title, Utils.GetSmallRandomText(), out id, out path); } public static DreamMessage CreateRandomPage(Plug p, string pageTitle, out string id, out string path) { return PageUtils.SavePage(p, string.Empty, pageTitle, Utils.GetSmallRandomText(), out id, out path); } public static DreamMessage CreateRandomPage(Plug p, out string id, out string path) { string pageTitle = GenerateUniquePageName(); return PageUtils.SavePage(p, string.Empty, pageTitle, Utils.GetSmallRandomText(), Utils.DateToString(DateTime.MinValue), out id, out path); } public static DreamMessage SavePage(Plug p, string pageTitle, string content) { string id = null; string path = null; return PageUtils.SavePage(p, string.Empty, pageTitle, content, out id, out path); } public static DreamMessage SavePage(Plug p, string parentPath, string pageTitle, string content, out string id, out string path) { string sEditTime = null; DreamMessage msg = PageUtils.GetPage(p, parentPath + pageTitle); if (msg.Status == DreamStatus.Ok) { DateTime edittime = msg.ToDocument()["/page/date.edited"].AsDate ?? DateTime.MinValue; sEditTime = Utils.DateToString(edittime); } return SavePage(p, parentPath, pageTitle, content, sEditTime, out id, out path); } public static DreamMessage SavePage(Plug p, string parentPath, string pageTitle, string content, string edittime, out string id, out string path) { string title = pageTitle; if (parentPath != string.Empty) title = parentPath + pageTitle; title = "=" + XUri.DoubleEncode(title); p = p.At("pages", title, "contents"); if (!string.IsNullOrEmpty(edittime)) p = p.With("edittime", edittime); DreamMessage msg = p.PostAsync(DreamMessage.Ok(MimeType.TEXT_UTF8, content)).Wait(); Assert.AreEqual(DreamStatus.Ok, msg.Status, "Page creation failed!"); id = msg.ToDocument()["page/@id"].AsText; path = msg.ToDocument()["page/path"].AsText; Assert.IsTrue(!string.IsNullOrEmpty(path), "Page path is null!"); Assert.IsTrue(!string.IsNullOrEmpty(id), "Page ID is null!"); return msg; } public static DreamMessage DeletePageByID(Plug p, string id, bool recurse) { var msg = p.At("pages", id).WithQuery("recursive=" + recurse.ToString()).DeleteAsync().Wait(); Assert.IsTrue(msg.IsSuccessful, "Page delete by ID failed!"); return msg; } public static DreamMessage DeletePageByName(Plug p, string path, bool recurse) { path = "=" + XUri.DoubleEncode(path); var msg = p.At("pages", path).WithQuery("recursive=" + recurse.ToString()).DeleteAsync().Wait(); Assert.IsTrue(msg.IsSuccessful, "Page delete by name failed!"); return msg; } public static string BuildPageTree(Plug p) { // A // A/B // A/B/C // A/B/D // A/E string treeRoot = null; string id = null; CreateRandomPage(p, out id, out treeRoot); string pathToA = treeRoot + "/A"; PageUtils.SavePage(p, pathToA, string.Empty); string pathToB = pathToA + "/B"; PageUtils.SavePage(p, pathToB, string.Empty); string pathToC = pathToB + "/C"; PageUtils.SavePage(p, pathToC, string.Empty); string pathToD = pathToB + "/D"; PageUtils.SavePage(p, pathToD, string.Empty); string pathToE = pathToA + "/E"; PageUtils.SavePage(p, pathToE, string.Empty); return treeRoot; } public static DreamMessage MovePage(Plug p, string path, string targetPath) { path = "=" + XUri.DoubleEncode(path); DreamMessage msg = p.At("pages", path, "move").With("to", targetPath).Post(); Assert.AreEqual(DreamStatus.Ok, msg.Status, "Page move failed!"); return msg; } public static DreamMessage GetPage(Plug p, string path) { path = "=" + XUri.DoubleEncode(path); DreamMessage msg = null; msg = p.At("pages", path).GetAsync().Wait(); Assert.IsTrue(msg.Status == DreamStatus.Ok || msg.Status == DreamStatus.NotFound, string.Format("Unexpected status: {0}", msg.Status)); return msg; } public static DreamMessage RestrictPage(Plug p, string path, string cascade, string restriction) { path = "=" + XUri.DoubleEncode(path); XDoc securityDoc = new XDoc("security"); if (!string.IsNullOrEmpty(restriction)) securityDoc.Start("permissions.page").Start("restriction").Value(restriction).End().End(); //if (userIdGrantsHash != null && userIdGrantsHash.Keys.Count > 0) //{ // x.Start("grants"); // foreach (KeyValuePair<int, List<string>> grantsForUser in userIdGrantsHash) // { // foreach (string grant in grantsForUser.Value) // { // x.Start("grant").Start("permissions").Start("role").Value(grant).End().End().Start("user").Attr("id", grantsForUser.Key).End().End(); // } // } // x.End(); //} DreamMessage msg = p.At("pages", path, "security").WithQuery("cascade=" + cascade).Put(securityDoc); Assert.AreEqual(DreamStatus.Ok, msg.Status); return msg; } public static string GetPageName(Plug p, string pageid) // name == final path segment { DreamMessage msg = p.At("pages", pageid).Get(new Result<DreamMessage>()).Wait(); Assert.AreEqual(DreamStatus.Ok, msg.Status, "Page retrieval failed"); string uri = msg.ToDocument()["uri.ui"].AsText ?? String.Empty; int lastSlashIndex = uri.LastIndexOf("/"); if (lastSlashIndex == -1) { return String.Empty; } string name = XUri.DoubleDecode(uri.Substring(lastSlashIndex + 1)); return name; } public static DreamMessage CreateRandomUnlinkedPage(Plug p, out string title, out string id, out string path) { string pageid = GenerateUniquePageName(); string content = Utils.GetSmallRandomText(); title = Utils.GenerateUniqueName(); DreamMessage msg = p.At("pages", "=" + XUri.DoubleEncode(pageid), "contents") .With("title", title).Post(DreamMessage.Ok(MimeType.TEXT_UTF8, content), new Result<DreamMessage>()).Wait(); Assert.AreEqual(DreamStatus.Ok, msg.Status, "Unlinked page create failed!"); id = msg.ToDocument()["page/@id"].AsText ?? String.Empty; path = msg.ToDocument()["page/path"].AsText ?? String.Empty; Assert.IsTrue(!string.IsNullOrEmpty(path), "Page path is null!"); Assert.IsTrue(!string.IsNullOrEmpty(id), "Page ID is null!"); Assert.AreEqual(msg.ToDocument()["page/path/@type"].AsText, "custom", "Path type is not custom!"); return msg; } public static DreamMessage MovePage(Plug p) { DreamMessage msg = p.Post(new Result<DreamMessage>()).Wait(); Assert.AreEqual(DreamStatus.Ok, msg.Status, "Page move failed"); return msg; } public static DreamMessage MovePageAndWait(Plug p, string oldpath) { DreamMessage msg = MovePage(p); Assert.IsTrue(Wait.For(() => { msg = PageUtils.GetPage(Utils.BuildPlugForAdmin(), oldpath); return (!msg.ToDocument()["path"].IsEmpty && (msg.ToDocument()["path"].AsText != oldpath)); }, TimeSpan.FromSeconds(10)), "unable to find redirect"); return msg; } public static bool IsLinked(DreamMessage pageMsg) { if (pageMsg.ToDocument()["path/@type"].IsEmpty) { return true; } return false; } public static bool IsUnlinked(DreamMessage pageMsg) { if ((pageMsg.ToDocument()["path/@type"].AsText ?? String.Empty) == "custom") { return true; } return false; } public static bool IsFixed(DreamMessage pageMsg) { if ((pageMsg.ToDocument()["path/@type"].AsText ?? String.Empty) == "fixed") { return true; } return false; } public static DreamMessage CreateTalkPage(Plug p, string pagepath, out string talkid, out string talkpath) { talkpath = "Talk:" + pagepath; DreamMessage msg = p.At("pages", "=" + XUri.DoubleEncode(talkpath), "contents"). Post(DreamMessage.Ok(MimeType.TEXT_UTF8, "test talk page"), new Result<DreamMessage>()).Wait(); Assert.AreEqual(DreamStatus.Ok, msg.Status, "Talk page creation failed"); talkid = msg.ToDocument()["page/@id"].AsText ?? String.Empty; talkpath = msg.ToDocument()["page/path"].AsText ?? String.Empty; Assert.IsTrue(!string.IsNullOrEmpty(talkpath), "Page path is null!"); Assert.IsTrue(!string.IsNullOrEmpty(talkid), "Page ID is null!"); return msg; } public static DreamMessage CreatePageWithNamespace(Plug p, string name_space, out string id, out string path) { path = name_space + ":" + PageUtils.GenerateUniquePageName(); DreamMessage msg = p.At("pages", "=" + XUri.DoubleEncode(path), "contents"). Post(DreamMessage.Ok(MimeType.TEXT_UTF8, "test talk page"), new Result<DreamMessage>()).Wait(); Assert.AreEqual(DreamStatus.Ok, msg.Status, name_space + " page creation failed"); id = msg.ToDocument()["page/@id"].AsText ?? String.Empty; path = msg.ToDocument()["page/path"].AsText ?? String.Empty; Assert.IsTrue(!string.IsNullOrEmpty(path), "Page path is null!"); Assert.IsTrue(!string.IsNullOrEmpty(id), "Page ID is null!"); return msg; } public static DreamMessage CreatePageAndTalkPage(Plug p, out string pageid, out string pagepath, out string talkid, out string talkpath) { CreateRandomPage(p, out pageid, out pagepath); return CreateTalkPage(p, pagepath, out talkid, out talkpath); } } }
// 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.Collections.Generic; namespace System.Security.Cryptography.X509Certificates { public partial class X509CertificateCollection : ICollection, IEnumerable, IList { private readonly List<X509Certificate> _list; public X509CertificateCollection() { _list = new List<X509Certificate>(); } public X509CertificateCollection(X509Certificate[] value) : this() { AddRange(value); } public X509CertificateCollection(X509CertificateCollection value) : this() { AddRange(value); } public int Count { get { return _list.Count; } } bool ICollection.IsSynchronized { get { return false; } } object ICollection.SyncRoot { get { return NonGenericList.SyncRoot; } } bool IList.IsFixedSize { get { return false; } } bool IList.IsReadOnly { get { return false; } } object IList.this[int index] { get { return NonGenericList[index]; } set { if (value == null) throw new ArgumentNullException("value"); NonGenericList[index] = value; } } public X509Certificate this[int index] { get { return _list[index]; } set { if (value == null) throw new ArgumentNullException("value"); _list[index] = value; } } public int Add(X509Certificate value) { if (value == null) throw new ArgumentNullException("value"); int index = _list.Count; _list.Add(value); return index; } public void AddRange(X509Certificate[] value) { if (value == null) throw new ArgumentNullException("value"); for (int i = 0; i < value.Length; i++) { Add(value[i]); } } public void AddRange(X509CertificateCollection value) { if (value == null) throw new ArgumentNullException("value"); for (int i = 0; i < value.Count; i++) { Add(value[i]); } } public void Clear() { _list.Clear(); } public bool Contains(X509Certificate value) { return _list.Contains(value); } public void CopyTo(X509Certificate[] array, int index) { _list.CopyTo(array, index); } public X509CertificateEnumerator GetEnumerator() { return new X509CertificateEnumerator(this); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public override int GetHashCode() { int hashCode = 0; foreach (X509Certificate cert in _list) { hashCode += cert.GetHashCode(); } return hashCode; } public int IndexOf(X509Certificate value) { return _list.IndexOf(value); } public void Insert(int index, X509Certificate value) { if (value == null) throw new ArgumentNullException("value"); _list.Insert(index, value); } public void Remove(X509Certificate value) { if (value == null) throw new ArgumentNullException("value"); _list.Remove(value); } public void RemoveAt(int index) { _list.RemoveAt(index); } void ICollection.CopyTo(Array array, int index) { NonGenericList.CopyTo(array, index); } int IList.Add(object value) { if (value == null) throw new ArgumentNullException("value"); return NonGenericList.Add(value); } bool IList.Contains(object value) { return NonGenericList.Contains(value); } int IList.IndexOf(object value) { return NonGenericList.IndexOf(value); } void IList.Insert(int index, object value) { if (value == null) throw new ArgumentNullException("value"); NonGenericList.Insert(index, value); } void IList.Remove(object value) { if (value == null) throw new ArgumentNullException("value"); NonGenericList.Remove(value); } private IList NonGenericList { get { return _list; } } internal void GetEnumerator(out List<X509Certificate>.Enumerator enumerator) { enumerator = _list.GetEnumerator(); } } }
// 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.Diagnostics.Contracts; using RuntimeTypeCache = System.RuntimeType.RuntimeTypeCache; namespace System.Reflection { internal unsafe sealed class RuntimeEventInfo : EventInfo { #region Private Data Members private int m_token; private EventAttributes m_flags; private string m_name; private void* m_utf8name; private RuntimeTypeCache m_reflectedTypeCache; private RuntimeMethodInfo m_addMethod; private RuntimeMethodInfo m_removeMethod; private RuntimeMethodInfo m_raiseMethod; private MethodInfo[] m_otherMethod; private RuntimeType m_declaringType; private BindingFlags m_bindingFlags; #endregion #region Constructor internal RuntimeEventInfo() { // Used for dummy head node during population } internal RuntimeEventInfo(int tkEvent, RuntimeType declaredType, RuntimeTypeCache reflectedTypeCache, out bool isPrivate) { Contract.Requires(declaredType != null); Contract.Requires(reflectedTypeCache != null); Debug.Assert(!reflectedTypeCache.IsGlobal); MetadataImport scope = declaredType.GetRuntimeModule().MetadataImport; m_token = tkEvent; m_reflectedTypeCache = reflectedTypeCache; m_declaringType = declaredType; RuntimeType reflectedType = reflectedTypeCache.GetRuntimeType(); scope.GetEventProps(tkEvent, out m_utf8name, out m_flags); RuntimeMethodInfo dummy; Associates.AssignAssociates(scope, tkEvent, declaredType, reflectedType, out m_addMethod, out m_removeMethod, out m_raiseMethod, out dummy, out dummy, out m_otherMethod, out isPrivate, out m_bindingFlags); } #endregion #region Internal Members internal override bool CacheEquals(object o) { RuntimeEventInfo m = o as RuntimeEventInfo; if ((object)m == null) return false; return m.m_token == m_token && RuntimeTypeHandle.GetModule(m_declaringType).Equals( RuntimeTypeHandle.GetModule(m.m_declaringType)); } internal BindingFlags BindingFlags { get { return m_bindingFlags; } } #endregion #region Object Overrides public override String ToString() { if (m_addMethod == null || m_addMethod.GetParametersNoCopy().Length == 0) throw new InvalidOperationException(SR.InvalidOperation_NoPublicAddMethod); return m_addMethod.GetParametersNoCopy()[0].ParameterType.FormatTypeName() + " " + Name; } #endregion #region ICustomAttributeProvider public override Object[] GetCustomAttributes(bool inherit) { return CustomAttribute.GetCustomAttributes(this, typeof(object) as RuntimeType); } public override Object[] GetCustomAttributes(Type attributeType, bool inherit) { if (attributeType == null) throw new ArgumentNullException(nameof(attributeType)); Contract.EndContractBlock(); RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; if (attributeRuntimeType == null) throw new ArgumentException(SR.Arg_MustBeType, nameof(attributeType)); return CustomAttribute.GetCustomAttributes(this, attributeRuntimeType); } public override bool IsDefined(Type attributeType, bool inherit) { if (attributeType == null) throw new ArgumentNullException(nameof(attributeType)); Contract.EndContractBlock(); RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; if (attributeRuntimeType == null) throw new ArgumentException(SR.Arg_MustBeType, nameof(attributeType)); return CustomAttribute.IsDefined(this, attributeRuntimeType); } public override IList<CustomAttributeData> GetCustomAttributesData() { return CustomAttributeData.GetCustomAttributesInternal(this); } #endregion #region MemberInfo Overrides public override MemberTypes MemberType { get { return MemberTypes.Event; } } public override String Name { get { if (m_name == null) m_name = new Utf8String(m_utf8name).ToString(); return m_name; } } public override Type DeclaringType { get { return m_declaringType; } } public sealed override bool HasSameMetadataDefinitionAs(MemberInfo other) => HasSameMetadataDefinitionAsCore<RuntimeEventInfo>(other); public override Type ReflectedType { get { return ReflectedTypeInternal; } } private RuntimeType ReflectedTypeInternal { get { return m_reflectedTypeCache.GetRuntimeType(); } } public override int MetadataToken { get { return m_token; } } public override Module Module { get { return GetRuntimeModule(); } } internal RuntimeModule GetRuntimeModule() { return m_declaringType.GetRuntimeModule(); } #endregion #region EventInfo Overrides public override MethodInfo[] GetOtherMethods(bool nonPublic) { List<MethodInfo> ret = new List<MethodInfo>(); if ((object)m_otherMethod == null) return new MethodInfo[0]; for (int i = 0; i < m_otherMethod.Length; i++) { if (Associates.IncludeAccessor((MethodInfo)m_otherMethod[i], nonPublic)) ret.Add(m_otherMethod[i]); } return ret.ToArray(); } public override MethodInfo GetAddMethod(bool nonPublic) { if (!Associates.IncludeAccessor(m_addMethod, nonPublic)) return null; return m_addMethod; } public override MethodInfo GetRemoveMethod(bool nonPublic) { if (!Associates.IncludeAccessor(m_removeMethod, nonPublic)) return null; return m_removeMethod; } public override MethodInfo GetRaiseMethod(bool nonPublic) { if (!Associates.IncludeAccessor(m_raiseMethod, nonPublic)) return null; return m_raiseMethod; } public override EventAttributes Attributes { get { return m_flags; } } #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. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void ConvertToVector128Int32Byte() { var test = new SimpleUnaryOpTest__ConvertToVector128Int32Byte(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); // Validates basic functionality works, using the pointer overload test.RunBasicScenario_Ptr(); if (Sse2.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); // Validates calling via reflection works, using the pointer overload test.RunReflectionScenario_Ptr(); if (Sse2.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local works test.RunLclFldScenario(); // Validates passing an instance member works test.RunFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleUnaryOpTest__ConvertToVector128Int32Byte { private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Byte>>() / sizeof(Byte); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32); private static Byte[] _data = new Byte[Op1ElementCount]; private static Vector128<Byte> _clsVar; private Vector128<Byte> _fld; private SimpleUnaryOpTest__DataTable<Int32, Byte> _dataTable; static SimpleUnaryOpTest__ConvertToVector128Int32Byte() { var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (byte)(random.Next(0, byte.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _clsVar), ref Unsafe.As<Byte, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); } public SimpleUnaryOpTest__ConvertToVector128Int32Byte() { Succeeded = true; var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (byte)(random.Next(0, byte.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _fld), ref Unsafe.As<Byte, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (byte)(random.Next(0, byte.MaxValue)); } _dataTable = new SimpleUnaryOpTest__DataTable<Int32, Byte>(_data, new Int32[RetElementCount], LargestVectorSize); } public bool IsSupported => Sse41.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { var result = Sse41.ConvertToVector128Int32( Unsafe.Read<Vector128<Byte>>(_dataTable.inArrayPtr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_Ptr() { var result = Sse41.ConvertToVector128Int32( (Byte*)(_dataTable.inArrayPtr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { var result = Sse41.ConvertToVector128Int32( Sse2.LoadVector128((Byte*)(_dataTable.inArrayPtr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { var result = Sse41.ConvertToVector128Int32( Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArrayPtr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { var result = typeof(Sse41).GetMethod(nameof(Sse41.ConvertToVector128Int32), new Type[] { typeof(Vector128<Byte>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Byte>>(_dataTable.inArrayPtr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Ptr() { var result = typeof(Sse41).GetMethod(nameof(Sse41.ConvertToVector128Int32), new Type[] { typeof(Byte*) }) .Invoke(null, new object[] { Pointer.Box(_dataTable.inArrayPtr, typeof(Byte*)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { var result = typeof(Sse41).GetMethod(nameof(Sse41.ConvertToVector128Int32), new Type[] { typeof(Vector128<Byte>) }) .Invoke(null, new object[] { Sse2.LoadVector128((Byte*)(_dataTable.inArrayPtr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { var result = typeof(Sse41).GetMethod(nameof(Sse41.ConvertToVector128Int32), new Type[] { typeof(Vector128<Byte>) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArrayPtr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { var result = Sse41.ConvertToVector128Int32( _clsVar ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { var firstOp = Unsafe.Read<Vector128<Byte>>(_dataTable.inArrayPtr); var result = Sse41.ConvertToVector128Int32(firstOp); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { var firstOp = Sse2.LoadVector128((Byte*)(_dataTable.inArrayPtr)); var result = Sse41.ConvertToVector128Int32(firstOp); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { var firstOp = Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArrayPtr)); var result = Sse41.ConvertToVector128Int32(firstOp); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclFldScenario() { var test = new SimpleUnaryOpTest__ConvertToVector128Int32Byte(); var result = Sse41.ConvertToVector128Int32(test._fld); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunFldScenario() { var result = Sse41.ConvertToVector128Int32(_fld); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld, _dataTable.outArrayPtr); } public void RunUnsupportedScenario() { Succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { Succeeded = true; } } private void ValidateResult(Vector128<Byte> firstOp, void* result, [CallerMemberName] string method = "") { Byte[] inArray = new Byte[Op1ElementCount]; Int32[] outArray = new Int32[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray[0]), firstOp); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int32>>()); ValidateResult(inArray, outArray, method); } private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "") { Byte[] inArray = new Byte[Op1ElementCount]; Int32[] outArray = new Int32[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector128<Byte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int32>>()); ValidateResult(inArray, outArray, method); } private void ValidateResult(Byte[] firstOp, Int32[] result, [CallerMemberName] string method = "") { if (result[0] != firstOp[0]) { Succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != firstOp[i]) { Succeeded = false; break; } } } if (!Succeeded) { Console.WriteLine($"{nameof(Sse41)}.{nameof(Sse41.ConvertToVector128Int32)}<Int32>(Vector128<Byte>): {method} failed:"); Console.WriteLine($" firstOp: ({string.Join(", ", firstOp)})"); Console.WriteLine($" result: ({string.Join(", ", result)})"); Console.WriteLine(); } } } }
// Copyright (c) 2008 CodeToast.com and Nicholas Brookins //This code is free to use in any application for any use if this notice is left intact. //Just don't sue me if it gets you fired. Enjoy! using System; using System.Collections.Generic; using System.Reflection; using System.Text; using System.Runtime.Remoting.Messaging; using System.Threading; using System.Windows.Forms; namespace CodeToast { public static class Async { static Dictionary<string, object> methodLocks = new Dictionary<string, object>(); #region Async 'Do' overloads, for ease of use /// <summary> /// Fires off your delegate asyncronously, using the threadpool or a full managed thread if needed. /// This overload always tries the ThreadPool and DOES NOT check for reentrance. /// </summary> /// <param name="d">A delegate with a return value of some sort - can be cast to (DlgR) from an anonymous delgate with a return: Async.Do((DlgR)MyMethod);</param> /// <param name="getRetVal">If true, and the method/delgete returns something, it is included in the AsyncRes returned (after the method completes)</param> /// <returns>AsyncRes with all kind o' goodies for waiting, etc.</returns> public static AsyncRes Do(DlgR d, bool getRetVal) { return Do(d, getRetVal, ReenteranceMode.Allow); } /// <summary> /// Fires off your delegate asyncronously, using the threadpool or a full managed thread if needed. /// This overload always tries the ThreadPool and DOES NOT check for reentrance. /// </summary> /// <param name="d">A void delegate - can be cast to (Dlg) from an anonymous delgate or method: Async.Do((Dlg)MyVoidMethod)</param> /// <returns>AsyncRes with all kind o' goodies for waiting, etc.</returns> public static AsyncRes Do(Dlg d) { return Do(d, ReenteranceMode.Allow); } /// <summary> /// Fires off your delegate asyncronously, using the threadpool or a full managed thread if needed. /// </summary> /// <param name="d">A delegate with a return value of some sort - can be cast to (DlgR) from an anonymous delgate with a return: Async.Do((DlgR)MyMethod);</param> /// <param name="rMode">If true, will make sure no other instances are running your method.</param> /// <param name="getRetVal">If true, and the method/delgete returns something, it is included in the AsyncRes returned (after the method completes)</param> /// <returns>AsyncRes with all kind o' goodies for waiting, resturn and result values, etc.</returns> public static AsyncRes Do(DlgR d, bool getRetVal, ReenteranceMode rMode) { return Do(d, null, getRetVal, null, true, rMode, null, true); } /// <summary> /// Fires off your delegate asyncronously, using the threadpool or a full managed thread if needed. /// </summary> /// <param name="d">A void delegate - can be cast to (Dlg) from an anonymous delgate or method: Async.Do((Dlg)MyVoidMethod);</param> /// <param name="rMode">If true, will make sure no other instances are running your method.</param> /// <returns>AsyncRes with all kind o' goodies for waiting, result values, etc.</returns> public static AsyncRes Do(Dlg d, ReenteranceMode rMode) { return Do(null, d, false, null, true, rMode, null, true); } /// <summary> /// Fires off your delegate asyncronously, using the threadpool or a full managed thread if needed. /// </summary> /// <param name="d">A delegate with a return value of some sort - can be cast to (DlgR) from an anonymous delgate with a return: Async.Do((DlgR)MyMethod);</param> /// <param name="state">A user object that can be tracked through the returned result</param> /// <param name="tryThreadPool">True to use the TP, otherwise just go to a ful lthread - good for long running tasks.</param> /// <param name="rMode">If true, will make sure no other instances are running your method.</param> /// <param name="getRetVal">If true, and the method/delgete returns something, it is included in the AsyncRes returned (after the method completes)</param> /// <returns>AsyncRes with all kind o' goodies for waiting, resturn and result values, etc.</returns> public static AsyncRes Do(DlgR d, bool getRetVal, object state, bool tryThreadPool, ReenteranceMode rMode) { return Do(d, null, getRetVal, state, tryThreadPool, rMode, null, true); } /// <summary> /// Fires off your delegate asyncronously, using the threadpool or a full managed thread if needed. /// </summary> /// <param name="d">A void delegate - can be cast to (Dlg) from an anonymous delgate or method: Async.Do((Dlg)MyVoidMethod);</param> /// <param name="state">A user object that can be tracked through the returned result</param> /// <param name="tryThreadPool">True to use the TP, otherwise just go to a ful lthread - good for long running tasks.</param> /// <param name="rMode">If true, will make sure no other instances are running your method.</param> /// <returns>AsyncRes with all kind o' goodies for waiting, result values, etc.</returns> public static AsyncRes Do(Dlg d, object state, bool tryThreadPool, ReenteranceMode rMode) { return Do(null, d, false, state, tryThreadPool, rMode, null, true); } #endregion #region The Big Main private 'Do' method - called by all overloads. /// <summary> /// Fires off your delegate asyncronously, using the threadpool or a full managed thread if needed. /// </summary> /// <param name="d">A void delegate - can be cast to (Dlg) from an anonymous delgate.</param> /// <param name="dr">A delegate with a return value of some sort - can be cast to (DlgR) from an anonymous delgate with a return.</param> /// <param name="state">A user object that can be tracked through the returned result</param> /// <param name="getRetVal">If true, and the method/delgete returns something, it is included in the AsyncRes returned (after the method completes)</param> /// <param name="tryThreadPool">True to use the TP, otherwise just go to a ful lthread - good for long running tasks.</param> /// <param name="rMode">If true, will make sure no other instances are running your method.</param> /// <returns>AsyncRes with all kind o' goodies for waiting, result values, etc.</returns> private static AsyncRes Do(DlgR dr, Dlg d, bool getRetVal, object state, bool tryThreadPool, ReenteranceMode rMode, Control control, bool async) { //get a generic MethodInfo for checks.. MethodInfo mi = ((dr != null) ? dr.Method : d.Method); //make a unique key for output usage string key = string.Format("{0}{1}{2}{3}", ((getRetVal) ? "<-" : ""), mi.DeclaringType, ((mi.IsStatic) ? ":" : "."), mi.Name); //our custom return value, holds our delegate, state, key, etc. AsyncRes res = new AsyncRes(state, ((dr != null) ? (Delegate)dr : (Delegate)d), key, rMode); //Create a delegate wrapper for what we will actually invoke.. Dlg dlg = (Dlg)delegate { if (!BeforeInvoke(res)) return; //checks for reentrance issues and sets us up try { if (res.IsCompleted) return; if (dr != null) { res.retVal = dr();//use this one if theres a return } else { d();//otherwise the simpler dlg } } catch (Exception ex) { //we never want a rogue exception on a random thread, it can't bubble up anywhere Console.WriteLine("Async Exception:" + ex); } finally { FinishInvoke(res);//this will fire our callback if they used it, and clean up } }; if (control != null) { res.control = control; res.result = AsyncAction.ControlInvoked; if (!async) { if (!control.InvokeRequired) { res.completedSynchronously = true; dlg(); } else { control.Invoke(dlg); } } else { control.BeginInvoke(dlg); } return res; } //don't catch these errors - if this fails, we shouldn't try a real thread or threadpool! if (tryThreadPool) { //we are going to use the .NET threadpool try { //get some stats - much better than trying and silently failing or throwing an expensive exception int minThreads, minIO, threads, ioThreads, totalThreads, totalIO; ThreadPool.GetMinThreads(out minThreads, out minIO); ThreadPool.GetAvailableThreads(out threads, out ioThreads); ThreadPool.GetMaxThreads(out totalThreads, out totalIO); //check for at least our thread plus one more in ThreadPool if (threads > minThreads) { //this is what actually fires this task off.. bool result = ThreadPool.QueueUserWorkItem((WaitCallback)delegate { dlg(); }); if (result) { res.result = AsyncAction.ThreadPool; //this means success in queueing and running the item return res; } else { //according to docs, this "won't ever happen" - exception instead, but just for kicks. Console.WriteLine( "Failed to queue in threadpool.", "Method: " + key); } } else { Console.WriteLine(String.Format("Insufficient idle threadpool threads: {0} of {1} - min {2}, Method: {3}", threads, totalThreads, minThreads, key)); } } catch (Exception ex) { Console.WriteLine("Failed to queue in threadpool: " + ex.Message, "Method: " + key); } } //if we got this far, then something up there failed, or they wanted a dedicated thread Thread t = new Thread((ThreadStart)delegate { dlg(); }); t.IsBackground = true; //this or threadpriority are candidates for additional settings t.Name = "Async_" + key; res.result = AsyncAction.Thread; t.Start(); return res; } #endregion #region Before and after - helper methods private static bool BeforeInvoke(AsyncRes res) { //if marked as completed then we abort. if (res.IsCompleted) return false; //if mode is 'allow' there is nothing to check. Otherwise... if (res.RMode != ReenteranceMode.Allow) { //be threadsafe with our one and only member field lock (methodLocks) { if (!methodLocks.ContainsKey(res.Method)) { //make sure we have a generic locking object in the collection, it will already be there if we are reentering methodLocks.Add(res.Method, new object()); } //if bypass mode and we can't get or lock, we dump out. if (res.RMode == ReenteranceMode.Bypass) { if (!Monitor.TryEnter(methodLocks[res.Method])) { res.result = AsyncAction.Reenterant; return false; } } else { //Otherwise in 'stack' mode, we just wait until someone else releases it... Monitor.Enter(methodLocks[res.Method]); } //if we are here, all is good. //Set some properties on the result class to show when we started, and what thread we are on res.isStarted = true; res.startTime = DateTime.Now; res.thread = Thread.CurrentThread; } } return true; } private static void FinishInvoke(AsyncRes res) { if (res == null) return; try { //finish a few more properties res.isCompleted = true; res.completeTime = DateTime.Now; //set the resetevent, in case someone is using the waithandle to know when we have completed. res.mre.Set(); } catch (Exception ex) { Console.WriteLine("Error setting wait handle on " + (res.Method ?? "NULL") + ex); } if (res.RMode != ReenteranceMode.Allow) { //if mode is bypass or stack, then we must have a lock that needs releasing try { if (methodLocks.ContainsKey(res.Method)) { Monitor.Exit(methodLocks[res.Method]); } } catch (Exception ex) { Console.WriteLine("Error releasing reentrant lock on " + (res.Method ?? "NULL")+ ex); } } } #endregion #region UI Overloads /// <summary> /// Fires off your delegate, carefully using the correct UI thread /// </summary> /// <param name="d">A void delegate - can be cast to (Dlg) from an anonymous delgate or method: Async.Do((Dlg)MyVoidMethod);</param> /// <param name="async">Whether to run async, or try on current thread if invoke is not required.</param> /// <param name="c">A control to Invoke upon GUI thread of, if needed. Null if unused.</param> /// <returns>AsyncRes with all kind o' goodies for waiting, result values, etc.</returns> public static AsyncRes UI(Dlg d, Control c, bool async) { return Do(null, d, false, null, false, ReenteranceMode.Allow, c, async); } /// <summary> /// Fires off your delegate, carefully using the correct UI thread /// </summary> /// <param name="d">A delegate with a return value of some sort - can be cast to (DlgR) from an anonymous delgate with a return: Async.Do((DlgR)MyMethod);</param> /// <param name="async">Whether to run async, or try on current thread if invoke is not required.</param> /// <param name="getRetVal">If true, and the method/delgete returns something, it is included in the AsyncRes returned (after the method completes)</param> /// <param name="c">A control to Invoke upon GUI thread of, if needed. Null if unused.</param> /// <returns>AsyncRes with all kind o' goodies for waiting, result values, etc.</returns> public static AsyncRes UI(DlgR d, bool getRetVal, Control c, bool async) { return Do(d, null, getRetVal, null, false, ReenteranceMode.Allow, c, async); } /// <summary> /// Fires off your delegate, carefully using the correct UI thread /// </summary> /// <param name="d">A delegate with a return value of some sort - can be cast to (DlgR) from an anonymous delgate with a return: Async.Do((DlgR)MyMethod);</param> /// <param name="state">A user object that can be tracked through the returned result</param> /// <param name="async">Whether to run async, or try on current thread if invoke is not required.</param> /// <param name="getRetVal">If true, and the method/delgete returns something, it is included in the AsyncRes returned (after the method completes)</param> /// <param name="rMode">If true, will make sure no other instances are running your method.</param> /// <param name="c">A control to Invoke upon GUI thread of, if needed. Null if unused.</param> /// <returns>AsyncRes with all kind o' goodies for waiting, result values, etc.</returns> public static AsyncRes UI(DlgR d, bool getRetVal, Control c, object state, bool async, ReenteranceMode rMode) { return Do(d, null, getRetVal, state, false, rMode, c, async); } #endregion } #region AsyncRes class /// <summary> /// Used with the Async helper class, This class is mostly a holder for a lot of tracking fields and properties, with a few things mandated by the IAsyncResult interface. /// </summary> public class AsyncRes : IAsyncResult { internal AsyncRes(object state, Delegate d, string key, ReenteranceMode rMode) { this.state = state; this.asyncDelegate = d; this.key = key; this.RMode = rMode; } internal ReenteranceMode RMode = ReenteranceMode.Allow; internal Thread thread = null; private string key = null; public string Method { get { return key; } } private Delegate asyncDelegate = null; public Delegate AsyncDelegate { get { return asyncDelegate; } } internal AsyncAction result = AsyncAction.Unknown; public AsyncAction Result { get { return result; } } internal Control control = null; public Control Control { get { return control; } } internal DateTime createTime = DateTime.Now; public DateTime TimeCreated { get { return createTime; } } internal DateTime completeTime = DateTime.MinValue; public DateTime TimeCompleted { get { return completeTime; } } internal DateTime startTime = DateTime.Now; public DateTime TimeStarted { get { return startTime; } } public TimeSpan TimeElapsed { get { return ((completeTime > DateTime.MinValue) ? completeTime : DateTime.Now) - createTime; } } public TimeSpan TimeRunning { get {return (startTime == DateTime.MinValue) ? TimeSpan.Zero : ((completeTime > DateTime.MinValue) ? completeTime : DateTime.Now) - startTime;} } internal object retVal = null; public object ReturnValue { get { return retVal; } } internal bool isStarted = false; public bool IsStarted { get { return isStarted; } } private object state = null; public object AsyncState { get { return state; } } /// <summary> /// Aborts a running associated thread. If possible it will cancel if not yet started /// </summary> /// <returns>True if the thread could be cancelled before it started.</returns> public bool CancelOrAbort() { isCompleted = true; if (!isStarted) return true;//cancelled if (thread != null && thread.IsAlive) { thread.Abort(); } return false; } internal ManualResetEvent mre = new ManualResetEvent(false); public WaitHandle AsyncWaitHandle { get { return mre; } } internal bool completedSynchronously = false; public bool CompletedSynchronously { get { return completedSynchronously; } } internal bool isCompleted = false; public bool IsCompleted { get { return isCompleted; } } } #endregion #region Definitions of enums and delegates /// <summary> /// Abreviated Empty Delegate for use in anonymous casting /// </summary> public delegate void Dlg(); /// <summary> /// Abreviated Empty Delegate for use in anonymous methods when a return is needed /// </summary> /// <returns>Umm, anything you want.</returns> public delegate object DlgR(); public enum AsyncAction { Unknown = 0, ThreadPool = 1, Thread = 2, Failed = 4, Reenterant = 8, ControlInvoked = 16 } public enum ReenteranceMode { Allow = 1, Bypass = 2, Stack = 4, } #endregion }
using Microsoft.CodeAnalysis.CSharp; using SqlConsole.Host.Infrastructure; using System.Collections.Concurrent; using System.CommandLine; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.Reflection; using System.Xml.Linq; namespace SqlConsole.Host; using static SqlConsole.Host.Extension.State; public static class Extension { #pragma warning disable CA2211 // Non-constant fields should not be visible public static Action<string> Log = s => { }; #pragma warning restore CA2211 // Non-constant fields should not be visible // argument list is used for type inference // ReSharper disable once UnusedParameter.Local #pragma warning disable IDE0060 // Remove unused parameter static LambdaComparer<T> CompareBy<T>(this IEnumerable<T> list, Func<T?, int> f) #pragma warning restore IDE0060 // Remove unused parameter => new(f); public static Dictionary<DataColumn, int> ColumnLengths(this DataTable dt, int totalWidth, int separatorSize) { var maxLengths = ( from column in dt.Columns.OfType<DataColumn>() let rows = dt.Rows.OfType<DataRow>().Select(row => row[column].ToString()).ToList() let maxLength = new[] { column.ColumnName }.Concat(rows).Select(s => s.Length).DefaultIfEmpty().Max() select (column, maxLength) ).ToList(); var comparer = maxLengths.CompareBy(x => -x.maxLength); maxLengths.Sort(comparer); while (maxLengths[0].maxLength >= 10 && maxLengths.Sum(x => x.maxLength) + (dt.Columns.Count - 1) * separatorSize > totalWidth - 1) { var (column, maxLength) = maxLengths[0]; maxLengths[0] = (column, maxLength - 1); maxLengths.Sort(comparer); } return maxLengths.ToDictionary(x => x.column, x => x.maxLength); } public static string OfLength(this string s, int l) { s ??= string.Empty; var result = s.PadRight(l).Substring(0, l); if (result.Length < s.Length && result.Length > 3) { result = result[0..^3] + "..."; } return result; } public static string SafeSubstring(this string s, int startIndex, int length) { startIndex = Math.Min(startIndex, s.Length); length = Math.Min(length, s.Length - startIndex); return s.Substring(startIndex, length); } public static IEnumerable<string> SplitOnGo(this string s) => new ScriptSplitter(s).Split(); public static string ToCSharpLiteral<T>(this T s) => SymbolDisplay.FormatLiteral(s?.ToString() ?? string.Empty, false); public static string ToCSharpLiteral(this string s) => SymbolDisplay.FormatLiteral(s, false); public static string ToCSharpLiteral(this char c) => SymbolDisplay.FormatLiteral(c, false); internal enum State { UpperCase, LowerCase, Digit, WhiteSpace } record struct Char(char Value) { public bool IsLower => char.IsLower(Value); public bool IsUpper => char.IsUpper(Value); public bool IsDigit => char.IsDigit(Value); public bool IsLetter => char.IsLetter(Value); public bool IsLetterOrDigit => char.IsLetterOrDigit(Value); public bool IsWhiteSpace => char.IsWhiteSpace(Value); public bool IsUnderscore => Value == '_'; } public static string ToHyphenedString(this string input) { var sb = new StringBuilder(); var state = UpperCase; foreach (var c in input) { (state, sb) = (state, new Char(c)) switch { (UpperCase or Digit, { IsLower: true }) => (LowerCase, sb), (UpperCase or LowerCase, { IsDigit: true }) => (Digit, sb), (LowerCase or Digit, { IsUpper: true }) => (UpperCase, sb.Append('-')), _ => (state, sb) }; if (char.IsLetterOrDigit(c)) { sb.Append(char.ToLowerInvariant(c)); } } return sb.ToString(); } private static StringBuilder ToLower(this StringBuilder sb) { for (int i = 0; i < sb.Length; i++) { if (char.IsUpper(sb[i])) sb[i] = char.ToLower(sb[i]); } return sb; } public static string ToSentence(this string input) { var sb = new StringBuilder(); var buffer = new StringBuilder(); var state = UpperCase; foreach (var c in input) { var inputstate = state; (state, sb, buffer) = (state, new Char(c)) switch { // although State is always UpperCase, the first char could be lowercase (UpperCase, _) when sb.Length == 0 => (state, sb.Append(char.ToUpper(c)), buffer), // when one character buffered and next char is lowercase, make the buffer lower case and transition to lowercase (UpperCase or WhiteSpace, { IsLower: true }) when buffer.Length == 1 => (LowerCase, sb.Append(buffer.ToLower()).Append(c), buffer.Clear()), // multiple uppercase characters should be preserved (UpperCase, { IsLower: true }) when buffer.Length > 1 => (LowerCase, sb.Append(buffer).Append(c), buffer.Clear()), // while buffering digits, when next char is uppercase: consider this next word (Digit, { IsUpper: true }) => (UpperCase, sb.Append(buffer), buffer.Clear().Append(' ').Append(char.ToLower(c))), // while buffering uppercase, next char is digit: keep buffering (UpperCase, { IsDigit: true }) => (Digit, sb, buffer.Append(c)), // while in lowercase, if next char is underscore or whitespace: append a space and transition to whitespace (LowerCase, { IsUnderscore: true } or { IsWhiteSpace: true }) => (WhiteSpace, sb.Append(' '), buffer), // while in lowercase, if next char is a digit or uppercase: start a new word (LowerCase, { IsDigit: true } or { IsUpper: true }) => (WhiteSpace, sb.Append(' '), buffer.Append(c)), // while in whitespace, if next char is uppercase: start buffering (WhiteSpace, { IsUpper: true }) => (UpperCase, sb, buffer.Append(c)), // while in whitespace, if next char is digit: start buffering (WhiteSpace, { IsDigit: true }) => (Digit, sb, buffer.Append(c)), // buffering (uppercase or digit) (UpperCase or Digit, _) => (state, sb, buffer.Append(c)), // adding characters in lowercase (LowerCase, _) => (state, sb.Append(c), buffer), _ => (state, sb, buffer) }; Log($"{inputstate} -> {c} -> {state}"); } if (buffer.Length > 0) sb.Append(buffer); return sb.ToString(); } public static T? GetAttribute<T>(this ICustomAttributeProvider prop) => prop.GetCustomAttributes(false).OfType<T>().FirstOrDefault(); public static DbConnectionStringBuilder WithoutSensitiveInformation(this DbConnectionStringBuilder b) { foreach (var v in new[] { "password", "Password", "PWD", "Pwd", "pwd", "PASSWORD" }) { if (b.ContainsKey(v)) b[v] = "******"; } return b; } static readonly ConcurrentDictionary<Type, bool> IsSimpleTypeCache = new(); public static bool IsSimpleType(this Type type) { return IsSimpleTypeCache.GetOrAdd(type, t => type.IsPrimitive || type.IsEnum || type == typeof(string) || type == typeof(decimal) || type == typeof(DateTime) || type == typeof(DateTimeOffset) || type == typeof(TimeSpan) || type == typeof(Guid) || IsNullableSimpleType(type)); static bool IsNullableSimpleType(Type t) { var underlyingType = Nullable.GetUnderlyingType(t); return underlyingType != null && IsSimpleType(underlyingType); } } static bool IsNullableType(this Type t) { return Nullable.GetUnderlyingType(t) != null; } public static IEnumerable<Option> GetOptions(this Type type, bool nonNullableMeansRequired = false) => type.GetProperties(BindingFlags.Instance | BindingFlags.Public).ToOptions(nonNullableMeansRequired); public static IEnumerable<Option> ToOptions(this IEnumerable<PropertyInfo> properties, bool nonNullableMeansRequired = false) { try { return from property in properties let description = property.GetAttribute<DescriptionAttribute>()?.Description ?? property.GetDescriptionFromDocumentation() ?? property.Name.ToSentence() let required = property.GetAttribute<RequiredAttribute>() != null || (nonNullableMeansRequired && property.PropertyType.IsValueType && !property.PropertyType.IsNullableType()) select new Option($"--{property.Name.ToHyphenedString()}", description, argumentType: property.PropertyType) { IsRequired = required, }; } finally { XmlDocumentation.Clear(); } } public static Command WithChildCommand(this Command parent, Command child) { parent.AddCommand(child); return parent; } public static Command WithChildCommands(this Command parent, params Command[] children) { foreach (var child in children) parent.AddCommand(child); return parent; } public static Command WithArgument(this Command command, Argument argument) { command.AddArgument(argument); return command; } public static Command WithOptions(this Command command, IEnumerable<Option> options) { foreach (var o in options) command.AddOption(o); return command; } public static string? GetDescriptionFromDocumentation(this PropertyInfo p) { var doc = p.GetDocumentation(); if (doc != null) { var xdoc = XDocument.Parse("<root>" + doc + "</root>"); var value = xdoc.Descendants("summary").First().Value.Trim(); return Cleanup(value); } return null; } enum CleanupState { Whitespace, Nonwhitespace } static string Cleanup(string value) { if (string.IsNullOrWhiteSpace(value)) return string.Empty; var sb = new StringBuilder(); var state = CleanupState.Nonwhitespace; var start = value.StartsWith("Gets or sets ", StringComparison.OrdinalIgnoreCase) ? "Gets or sets ".Length : 0; for (int i = start; i < value.Length; i++) { var c = value[i]; (state, sb) = (state, new Char(c)) switch { (CleanupState.Whitespace, { IsWhiteSpace: true }) => (state, sb), (CleanupState.Whitespace, { IsWhiteSpace: false }) => (CleanupState.Nonwhitespace, sb.Append(c)), (CleanupState.Nonwhitespace, { IsWhiteSpace: true }) => (CleanupState.Whitespace, sb.Append(' ')), (CleanupState.Nonwhitespace, { IsWhiteSpace: false }) => (state, sb.Append(c)), _ => throw new Exception("Unhandled switch case") }; } sb[0] = char.ToUpper(sb[0]); return sb.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 Microsoft.Build.Framework; using Microsoft.Build.Utilities; using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; using System.Xml.Linq; using System.Text; namespace Microsoft.DotNet.Build.Tasks { public class GenerateResourcesCode : BuildTask { private TargetLanguage _targetLanguage = TargetLanguage.CSharp; private StreamWriter _targetStream; private string _resourcesName; private string _srClassName; private string _srNamespace; [Required] public string ResxFilePath { get; set; } [Required] public string OutputSourceFilePath { get; set; } [Required] public string AssemblyName { get; set; } /// <summary> /// Defines the namespace in which the generated SR class is defined. If not specified defaults to System. /// </summary> public string SRNamespace { get; set; } /// <summary> /// Defines the class in which the ResourceType property is generated. If not specified defaults to SR. /// </summary> public string SRClassName { get; set; } /// <summary> /// Defines the namespace in which the generated resources class is defined. If not specified defaults to SRNamespace. /// </summary> public string ResourcesNamespace { get; set; } /// <summary> /// Defines the class in which the resource properties/constants are generated. If not specified defaults to SRClassName. /// </summary> public string ResourcesClassName { get; set; } /// <summary> /// Emit constant key strings instead of properties that retrieve values. /// </summary> public bool AsConstants { get; set; } public override bool Execute() { try { _resourcesName = "FxResources." + AssemblyName; _srNamespace = String.IsNullOrEmpty(SRNamespace) ? "System" : SRNamespace; _srClassName = String.IsNullOrEmpty(SRClassName) ? "SR" : SRClassName; using (_targetStream = File.CreateText(OutputSourceFilePath)) { if (String.Equals(Path.GetExtension(OutputSourceFilePath), ".vb", StringComparison.OrdinalIgnoreCase)) { _targetLanguage = TargetLanguage.VB; } WriteSR(); WriteResources(); } } catch (Exception e) { Log.LogError("Failed to generate the resource code with error:\n" + e.Message); return false; // fail the task } return true; } private void WriteSR() { string commentPrefix = _targetLanguage == TargetLanguage.CSharp ? "// " : "' "; _targetStream.WriteLine(commentPrefix + "Do not edit this file manually it is auto-generated during the build based on the .resx file for this project."); if (_targetLanguage == TargetLanguage.CSharp) { _targetStream.WriteLine($"namespace {_srNamespace}"); _targetStream.WriteLine("{"); _targetStream.WriteLine(""); _targetStream.WriteLine($" internal static partial class {_srClassName}"); _targetStream.WriteLine(" {"); _targetStream.WriteLine($" internal static Type ResourceType {{ get; }} = typeof({_resourcesName}.SR); "); _targetStream.WriteLine(" }"); _targetStream.WriteLine("}"); _targetStream.WriteLine(""); _targetStream.WriteLine($"namespace {_resourcesName}"); _targetStream.WriteLine("{"); _targetStream.WriteLine(" // The type of this class is used to create the ResourceManager instance as the type name matches the name of the embedded resources file"); _targetStream.WriteLine(" internal static class SR"); _targetStream.WriteLine(" {"); _targetStream.WriteLine(" }"); _targetStream.WriteLine("}"); _targetStream.WriteLine(""); } else { _targetStream.WriteLine($"Namespace {_srNamespace}"); _targetStream.WriteLine(""); _targetStream.WriteLine($" Friend Partial Class {_srClassName}"); _targetStream.WriteLine($" Friend Shared ReadOnly Property ResourceType As Type = GetType({_resourcesName}.SR)"); _targetStream.WriteLine(" End Class"); _targetStream.WriteLine("End Namespace"); _targetStream.WriteLine(""); _targetStream.WriteLine($"Namespace {_resourcesName}"); _targetStream.WriteLine(" ' The type of this class is used to create the ResourceManager instance as the type name matches the name of the embedded resources file"); _targetStream.WriteLine(" Friend Class SR"); _targetStream.WriteLine(" "); _targetStream.WriteLine(" End Class"); _targetStream.WriteLine("End Namespace"); _targetStream.WriteLine(""); } } private void WriteResources() { var resources = GetResources(ResxFilePath); var accessorNamespace = String.IsNullOrEmpty(ResourcesNamespace) ? _srNamespace : ResourcesNamespace; var accessorClassName = String.IsNullOrEmpty(ResourcesClassName) ? _srClassName : ResourcesClassName; if (_targetLanguage == TargetLanguage.CSharp) { _targetStream.WriteLine($"namespace {accessorNamespace}"); _targetStream.WriteLine("{"); _targetStream.WriteLine(""); _targetStream.WriteLine($" internal static partial class {accessorClassName}"); _targetStream.WriteLine(" {"); _targetStream.WriteLine(""); } else { _targetStream.WriteLine($"Namespace {accessorNamespace}"); _targetStream.WriteLine(""); _targetStream.WriteLine($" Friend Partial Class {accessorClassName}"); _targetStream.WriteLine(""); } if (AsConstants) { foreach (var resourcePair in resources) { WriteResourceConstant((string)resourcePair.Key); } } else { _targetStream.WriteLine(_targetLanguage == TargetLanguage.CSharp ? "#if !DEBUGRESOURCES" : "#If Not DEBUGRESOURCES Then"); foreach (var resourcePair in resources) { WriteResourceProperty(resourcePair.Key, _targetLanguage == TargetLanguage.CSharp ? "null" : "Nothing"); } _targetStream.WriteLine(_targetLanguage == TargetLanguage.CSharp ? "#else" : "#Else"); foreach (var resourcePair in resources) { WriteResourceProperty(resourcePair.Key, CreateStringLiteral(resourcePair.Value)); } _targetStream.WriteLine(_targetLanguage == TargetLanguage.CSharp ? "#endif" : "#End If"); } if (_targetLanguage == TargetLanguage.CSharp) { _targetStream.WriteLine(" }"); _targetStream.WriteLine("}"); } else { _targetStream.WriteLine(" End Class"); _targetStream.WriteLine("End Namespace"); } } private string CreateStringLiteral(string original) { StringBuilder stringLiteral = new StringBuilder(original.Length + 3); if (_targetLanguage == TargetLanguage.CSharp) { stringLiteral.Append('@'); } stringLiteral.Append('\"'); for (var i = 0; i < original.Length; i++) { // duplicate '"' for VB and C# if (original[i] == '\"') { stringLiteral.Append("\""); } stringLiteral.Append(original[i]); } stringLiteral.Append('\"'); return stringLiteral.ToString(); } private void WriteResourceProperty(string resourceId, string resourceValueLiteral) { if (_targetLanguage == TargetLanguage.CSharp) { _targetStream.WriteLine($" internal static string {resourceId} {{"); _targetStream.WriteLine($" get {{ return {_srNamespace}.{_srClassName}.GetResourceString(\"{resourceId}\", {resourceValueLiteral}); }}"); _targetStream.WriteLine($" }}"); } else { _targetStream.WriteLine($" Friend Shared ReadOnly Property {resourceId} As String"); _targetStream.WriteLine($" Get"); _targetStream.WriteLine($" Return {_srNamespace}.{_srClassName}.GetResourceString(\"{resourceId}\", {resourceValueLiteral})"); _targetStream.WriteLine($" End Get"); _targetStream.WriteLine($" End Property"); } } private void WriteResourceConstant(string resourceId) { if (_targetLanguage == TargetLanguage.CSharp) { _targetStream.WriteLine($" internal const string {resourceId} = \"{resourceId}\";"); } else { _targetStream.WriteLine($" Friend Const {resourceId} As String = \"{resourceId}\""); } } private enum TargetLanguage { CSharp, VB } internal Dictionary<string, string> GetResources(string fileName) { Dictionary<string, string> resources = new Dictionary<string, string>(); XDocument doc = XDocument.Load(fileName, LoadOptions.PreserveWhitespace); foreach (XElement dataElem in doc.Element("root").Elements("data")) { string name = dataElem.Attribute("name").Value; string value = dataElem.Element("value").Value; if (resources.ContainsKey(name)) { Log.LogError($"Duplicate resource id \"{name}\""); } else { resources[name] = value; } } return resources; } } }
// 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.Threading; using System.Collections.Generic; using System.Runtime; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Reflection.Runtime.General; using Internal.Runtime; using Internal.Runtime.Augments; using Internal.Runtime.CompilerServices; using Internal.Metadata.NativeFormat; using Internal.NativeFormat; using Internal.TypeSystem; using Internal.TypeSystem.NativeFormat; using Debug = System.Diagnostics.Debug; namespace Internal.Runtime.TypeLoader { internal class Callbacks : TypeLoaderCallbacks { public override bool TryGetConstructedGenericTypeForComponents(RuntimeTypeHandle genericTypeDefinitionHandle, RuntimeTypeHandle[] genericTypeArgumentHandles, out RuntimeTypeHandle runtimeTypeHandle) { return TypeLoaderEnvironment.Instance.TryGetConstructedGenericTypeForComponents(genericTypeDefinitionHandle, genericTypeArgumentHandles, out runtimeTypeHandle); } public override int GetThreadStaticsSizeForDynamicType(int index, out int numTlsCells) { return TypeLoaderEnvironment.Instance.TryGetThreadStaticsSizeForDynamicType(index, out numTlsCells); } public override IntPtr GenericLookupFromContextAndSignature(IntPtr context, IntPtr signature, out IntPtr auxResult) { return TypeLoaderEnvironment.Instance.GenericLookupFromContextAndSignature(context, signature, out auxResult); } public override bool GetRuntimeMethodHandleComponents(RuntimeMethodHandle runtimeMethodHandle, out RuntimeTypeHandle declaringTypeHandle, out MethodNameAndSignature nameAndSignature, out RuntimeTypeHandle[] genericMethodArgs) { return TypeLoaderEnvironment.Instance.TryGetRuntimeMethodHandleComponents(runtimeMethodHandle, out declaringTypeHandle, out nameAndSignature, out genericMethodArgs); } public override bool CompareMethodSignatures(RuntimeSignature signature1, RuntimeSignature signature2) { return TypeLoaderEnvironment.Instance.CompareMethodSignatures(signature1, signature2); } public override IntPtr TryGetDefaultConstructorForType(RuntimeTypeHandle runtimeTypeHandle) { return TypeLoaderEnvironment.Instance.TryGetDefaultConstructorForType(runtimeTypeHandle); } public override IntPtr GetDelegateThunk(Delegate delegateObject, int thunkKind) { return CallConverterThunk.GetDelegateThunk(delegateObject, thunkKind); } public override bool TryGetGenericVirtualTargetForTypeAndSlot(RuntimeTypeHandle targetHandle, ref RuntimeTypeHandle declaringType, RuntimeTypeHandle[] genericArguments, ref string methodName, ref RuntimeSignature methodSignature, out IntPtr methodPointer, out IntPtr dictionaryPointer, out bool slotUpdated) { return TypeLoaderEnvironment.Instance.TryGetGenericVirtualTargetForTypeAndSlot(targetHandle, ref declaringType, genericArguments, ref methodName, ref methodSignature, out methodPointer, out dictionaryPointer, out slotUpdated); } public override bool GetRuntimeFieldHandleComponents(RuntimeFieldHandle runtimeFieldHandle, out RuntimeTypeHandle declaringTypeHandle, out string fieldName) { return TypeLoaderEnvironment.Instance.TryGetRuntimeFieldHandleComponents(runtimeFieldHandle, out declaringTypeHandle, out fieldName); } public override IntPtr ConvertUnboxingFunctionPointerToUnderlyingNonUnboxingPointer(IntPtr unboxingFunctionPointer, RuntimeTypeHandle declaringType) { return TypeLoaderEnvironment.ConvertUnboxingFunctionPointerToUnderlyingNonUnboxingPointer(unboxingFunctionPointer, declaringType); } public override bool TryGetPointerTypeForTargetType(RuntimeTypeHandle pointeeTypeHandle, out RuntimeTypeHandle pointerTypeHandle) { return TypeLoaderEnvironment.Instance.TryGetPointerTypeForTargetType(pointeeTypeHandle, out pointerTypeHandle); } public override bool TryGetArrayTypeForElementType(RuntimeTypeHandle elementTypeHandle, bool isMdArray, int rank, out RuntimeTypeHandle arrayTypeHandle) { return TypeLoaderEnvironment.Instance.TryGetArrayTypeForElementType(elementTypeHandle, isMdArray, rank, out arrayTypeHandle); } public override IntPtr UpdateFloatingDictionary(IntPtr context, IntPtr dictionaryPtr) { return TypeLoaderEnvironment.Instance.UpdateFloatingDictionary(context, dictionaryPtr); } /// <summary> /// Register a new runtime-allocated code thunk in the diagnostic stream. /// </summary> /// <param name="thunkAddress">Address of thunk to register</param> public override void RegisterThunk(IntPtr thunkAddress) { SerializedDebugData.RegisterTailCallThunk(thunkAddress); } } public static class RuntimeSignatureExtensions { public static IntPtr NativeLayoutSignature(this RuntimeSignature signature) { if (!signature.IsNativeLayoutSignature) Environment.FailFast("Not a valid native layout signature"); NativeReader reader = TypeLoaderEnvironment.Instance.GetNativeLayoutInfoReader(signature); return reader.OffsetToAddress(signature.NativeLayoutOffset); } } public sealed partial class TypeLoaderEnvironment { [ThreadStatic] private static bool t_isReentrant; public static TypeLoaderEnvironment Instance { get; private set; } /// <summary> /// List of loaded binary modules is typically used to locate / process various metadata blobs /// and other per-module information. /// </summary> public readonly ModuleList ModuleList; // Cache the NativeReader in each module to avoid looking up the NativeLayoutInfo blob each // time we call GetNativeLayoutInfoReader(). The dictionary is a thread static variable to ensure // thread safety. Using ThreadStatic instead of a lock is ok as long as the NativeReader class is // small enough in size (which is the case today). [ThreadStatic] private static LowLevelDictionary<TypeManagerHandle, NativeReader> t_moduleNativeReaders; // Eager initialization called from LibraryInitializer for the assembly. internal static void Initialize() { Instance = new TypeLoaderEnvironment(); RuntimeAugments.InitializeLookups(new Callbacks()); NoStaticsData = (IntPtr)1; } public TypeLoaderEnvironment() { ModuleList = new ModuleList(); } // To keep the synchronization simple, we execute all type loading under a global lock private Lock _typeLoaderLock = new Lock(); public void VerifyTypeLoaderLockHeld() { if (!_typeLoaderLock.IsAcquired) Environment.FailFast("TypeLoaderLock not held"); } public void RunUnderTypeLoaderLock(Action action) { using (LockHolder.Hold(_typeLoaderLock)) { action(); } } public IntPtr GenericLookupFromContextAndSignature(IntPtr context, IntPtr signature, out IntPtr auxResult) { IntPtr result; using (LockHolder.Hold(_typeLoaderLock)) { try { if (t_isReentrant) Environment.FailFast("Reentrant lazy generic lookup"); t_isReentrant = true; result = TypeBuilder.BuildGenericLookupTarget(context, signature, out auxResult); t_isReentrant = false; } catch { // Catch and rethrow any exceptions instead of using finally block. Otherwise, filters that are run during // the first pass of exception unwind may hit the re-entrancy fail fast above. // TODO: Convert this to filter for better diagnostics once we switch to Roslyn t_isReentrant = false; throw; } } return result; } private bool EnsureTypeHandleForType(TypeDesc type) { if (type.RuntimeTypeHandle.IsNull()) { using (LockHolder.Hold(_typeLoaderLock)) { // Now that we hold the lock, we may find that existing types can now find // their associated RuntimeTypeHandle. Flush the type builder states as a way // to force the reresolution of RuntimeTypeHandles which couldn't be found before. type.Context.FlushTypeBuilderStates(); try { new TypeBuilder().BuildType(type); } catch (TypeBuilder.MissingTemplateException) { return false; } } } // Returned type has to have a valid type handle value Debug.Assert(!type.RuntimeTypeHandle.IsNull()); return !type.RuntimeTypeHandle.IsNull(); } internal TypeDesc GetConstructedTypeFromParserAndNativeLayoutContext(ref NativeParser parser, NativeLayoutInfoLoadContext nativeLayoutContext) { TypeDesc parsedType = nativeLayoutContext.GetType(ref parser); if (parsedType == null) return null; if (!EnsureTypeHandleForType(parsedType)) return null; return parsedType; } // // Parse a native layout signature pointed to by "signature" in the executable image, optionally using // "typeArgs" and "methodArgs" for generic type parameter substitution. The first field in "signature" // must be an encoded type but any data beyond that is user-defined and returned in "remainingSignature" // internal bool GetTypeFromSignatureAndContext(RuntimeSignature signature, RuntimeTypeHandle[] typeArgs, RuntimeTypeHandle[] methodArgs, out RuntimeTypeHandle createdType, out RuntimeSignature remainingSignature) { NativeReader reader = GetNativeLayoutInfoReader(signature); NativeParser parser = new NativeParser(reader, signature.NativeLayoutOffset); bool result = GetTypeFromSignatureAndContext(ref parser, new TypeManagerHandle(signature.ModuleHandle), typeArgs, methodArgs, out createdType); remainingSignature = RuntimeSignature.CreateFromNativeLayoutSignature(signature, parser.Offset); return result; } internal bool GetTypeFromSignatureAndContext(ref NativeParser parser, TypeManagerHandle moduleHandle, RuntimeTypeHandle[] typeArgs, RuntimeTypeHandle[] methodArgs, out RuntimeTypeHandle createdType) { createdType = default(RuntimeTypeHandle); TypeSystemContext context = TypeSystemContextFactory.Create(); TypeDesc parsedType = TryParseNativeSignatureWorker(context, moduleHandle, ref parser, typeArgs, methodArgs, false) as TypeDesc; if (parsedType == null) return false; if (!EnsureTypeHandleForType(parsedType)) return false; createdType = parsedType.RuntimeTypeHandle; TypeSystemContextFactory.Recycle(context); return true; } // // Parse a native layout signature pointed to by "signature" in the executable image, optionally using // "typeArgs" and "methodArgs" for generic type parameter substitution. The first field in "signature" // must be an encoded method but any data beyond that is user-defined and returned in "remainingSignature" // public bool GetMethodFromSignatureAndContext(RuntimeSignature signature, RuntimeTypeHandle[] typeArgs, RuntimeTypeHandle[] methodArgs, out RuntimeTypeHandle createdType, out MethodNameAndSignature nameAndSignature, out RuntimeTypeHandle[] genericMethodTypeArgumentHandles, out RuntimeSignature remainingSignature) { NativeReader reader = GetNativeLayoutInfoReader(signature); NativeParser parser = new NativeParser(reader, signature.NativeLayoutOffset); bool result = GetMethodFromSignatureAndContext(ref parser, new TypeManagerHandle(signature.ModuleHandle), typeArgs, methodArgs, out createdType, out nameAndSignature, out genericMethodTypeArgumentHandles); remainingSignature = RuntimeSignature.CreateFromNativeLayoutSignature(signature, parser.Offset); return result; } internal bool GetMethodFromSignatureAndContext(ref NativeParser parser, TypeManagerHandle moduleHandle, RuntimeTypeHandle[] typeArgs, RuntimeTypeHandle[] methodArgs, out RuntimeTypeHandle createdType, out MethodNameAndSignature nameAndSignature, out RuntimeTypeHandle[] genericMethodTypeArgumentHandles) { createdType = default(RuntimeTypeHandle); nameAndSignature = null; genericMethodTypeArgumentHandles = null; TypeSystemContext context = TypeSystemContextFactory.Create(); MethodDesc parsedMethod = TryParseNativeSignatureWorker(context, moduleHandle, ref parser, typeArgs, methodArgs, true) as MethodDesc; if (parsedMethod == null) return false; if (!EnsureTypeHandleForType(parsedMethod.OwningType)) return false; createdType = parsedMethod.OwningType.RuntimeTypeHandle; nameAndSignature = parsedMethod.NameAndSignature; if (!parsedMethod.IsMethodDefinition && parsedMethod.Instantiation.Length > 0) { genericMethodTypeArgumentHandles = new RuntimeTypeHandle[parsedMethod.Instantiation.Length]; for (int i = 0; i < parsedMethod.Instantiation.Length; ++i) { if (!EnsureTypeHandleForType(parsedMethod.Instantiation[i])) return false; genericMethodTypeArgumentHandles[i] = parsedMethod.Instantiation[i].RuntimeTypeHandle; } } TypeSystemContextFactory.Recycle(context); return true; } // // Returns the native layout info reader // internal unsafe NativeReader GetNativeLayoutInfoReader(NativeFormatModuleInfo module) { return GetNativeLayoutInfoReader(module.Handle); } // // Returns the native layout info reader // internal unsafe NativeReader GetNativeLayoutInfoReader(RuntimeSignature signature) { Debug.Assert(signature.IsNativeLayoutSignature); return GetNativeLayoutInfoReader(new TypeManagerHandle(signature.ModuleHandle)); } // // Returns the native layout info reader // internal unsafe NativeReader GetNativeLayoutInfoReader(TypeManagerHandle moduleHandle) { Debug.Assert(!moduleHandle.IsNull); if (t_moduleNativeReaders == null) t_moduleNativeReaders = new LowLevelDictionary<TypeManagerHandle, NativeReader>(); NativeReader result = null; if (t_moduleNativeReaders.TryGetValue(moduleHandle, out result)) return result; byte* pBlob; uint cbBlob; if (RuntimeAugments.FindBlob(moduleHandle, (int)ReflectionMapBlob.NativeLayoutInfo, new IntPtr(&pBlob), new IntPtr(&cbBlob))) result = new NativeReader(pBlob, cbBlob); t_moduleNativeReaders.Add(moduleHandle, result); return result; } private static RuntimeTypeHandle[] GetTypeSequence(ref ExternalReferencesTable extRefs, ref NativeParser parser) { uint count = parser.GetUnsigned(); RuntimeTypeHandle[] result = new RuntimeTypeHandle[count]; for (uint i = 0; i < count; i++) result[i] = extRefs.GetRuntimeTypeHandleFromIndex(parser.GetUnsigned()); return result; } private static RuntimeTypeHandle[] TypeDescsToRuntimeHandles(Instantiation types) { var result = new RuntimeTypeHandle[types.Length]; for (int i = 0; i < types.Length; i++) result[i] = types[i].RuntimeTypeHandle; return result; } public bool TryGetConstructedGenericTypeForComponents(RuntimeTypeHandle genericTypeDefinitionHandle, RuntimeTypeHandle[] genericTypeArgumentHandles, out RuntimeTypeHandle runtimeTypeHandle) { if (TryLookupConstructedGenericTypeForComponents(genericTypeDefinitionHandle, genericTypeArgumentHandles, out runtimeTypeHandle)) return true; using (LockHolder.Hold(_typeLoaderLock)) { return TypeBuilder.TryBuildGenericType(genericTypeDefinitionHandle, genericTypeArgumentHandles, out runtimeTypeHandle); } } // Get an array RuntimeTypeHandle given an element's RuntimeTypeHandle and rank. Pass false for isMdArray, and rank == -1 for SzArrays public bool TryGetArrayTypeForElementType(RuntimeTypeHandle elementTypeHandle, bool isMdArray, int rank, out RuntimeTypeHandle arrayTypeHandle) { if (TryGetArrayTypeForElementType_LookupOnly(elementTypeHandle, isMdArray, rank, out arrayTypeHandle)) { return true; } using (LockHolder.Hold(_typeLoaderLock)) { if (isMdArray && (rank < MDArray.MinRank) && (rank > MDArray.MaxRank)) { arrayTypeHandle = default(RuntimeTypeHandle); return false; } if (TypeSystemContext.GetArrayTypesCache(isMdArray, rank).TryGetValue(elementTypeHandle, out arrayTypeHandle)) return true; return TypeBuilder.TryBuildArrayType(elementTypeHandle, isMdArray, rank, out arrayTypeHandle); } } // Looks up an array RuntimeTypeHandle given an element's RuntimeTypeHandle and rank. A rank of -1 indicates SzArray internal bool TryGetArrayTypeForElementType_LookupOnly(RuntimeTypeHandle elementTypeHandle, bool isMdArray, int rank, out RuntimeTypeHandle arrayTypeHandle) { if (isMdArray && (rank < MDArray.MinRank) && (rank > MDArray.MaxRank)) { arrayTypeHandle = default(RuntimeTypeHandle); return false; } if (TypeSystemContext.GetArrayTypesCache(isMdArray, rank).TryGetValue(elementTypeHandle, out arrayTypeHandle)) return true; if (!isMdArray && !RuntimeAugments.IsDynamicType(elementTypeHandle) && TryGetArrayTypeForNonDynamicElementType(elementTypeHandle, out arrayTypeHandle)) { TypeSystemContext.GetArrayTypesCache(isMdArray, rank).AddOrGetExisting(arrayTypeHandle); return true; } return false; } public bool TryGetPointerTypeForTargetType(RuntimeTypeHandle pointeeTypeHandle, out RuntimeTypeHandle pointerTypeHandle) { // There are no lookups for pointers in static modules. All pointer EETypes will be created at this level. // It's possible to have multiple pointer EETypes representing the same pointer type with the same element type // The caching of pointer types is done at the reflection layer (in the RuntimeTypeUnifier) and // here in the TypeSystemContext layer if (TypeSystemContext.PointerTypesCache.TryGetValue(pointeeTypeHandle, out pointerTypeHandle)) return true; using (LockHolder.Hold(_typeLoaderLock)) { return TypeBuilder.TryBuildPointerType(pointeeTypeHandle, out pointerTypeHandle); } } public bool TryGetByRefTypeForTargetType(RuntimeTypeHandle pointeeTypeHandle, out RuntimeTypeHandle byRefTypeHandle) { // There are no lookups for ByRefs in static modules. All ByRef EETypes will be created at this level. // It's possible to have multiple ByRef EETypes representing the same ByRef type with the same element type // The caching of ByRef types is done at the reflection layer (in the RuntimeTypeUnifier) and // here in the TypeSystemContext layer if (TypeSystemContext.ByRefTypesCache.TryGetValue(pointeeTypeHandle, out byRefTypeHandle)) return true; using (LockHolder.Hold(_typeLoaderLock)) { return TypeBuilder.TryBuildByRefType(pointeeTypeHandle, out byRefTypeHandle); } } public int GetCanonicalHashCode(RuntimeTypeHandle typeHandle, CanonicalFormKind kind) { TypeSystemContext context = TypeSystemContextFactory.Create(); TypeDesc type = context.ResolveRuntimeTypeHandle(typeHandle); int hashCode = type.ConvertToCanonForm(kind).GetHashCode(); TypeSystemContextFactory.Recycle(context); return hashCode; } private object TryParseNativeSignatureWorker(TypeSystemContext typeSystemContext, TypeManagerHandle moduleHandle, ref NativeParser parser, RuntimeTypeHandle[] typeGenericArgumentHandles, RuntimeTypeHandle[] methodGenericArgumentHandles, bool isMethodSignature) { Instantiation typeGenericArguments = typeSystemContext.ResolveRuntimeTypeHandles(typeGenericArgumentHandles ?? Array.Empty<RuntimeTypeHandle>()); Instantiation methodGenericArguments = typeSystemContext.ResolveRuntimeTypeHandles(methodGenericArgumentHandles ?? Array.Empty<RuntimeTypeHandle>()); NativeLayoutInfoLoadContext nativeLayoutContext = new NativeLayoutInfoLoadContext(); nativeLayoutContext._module = ModuleList.GetModuleInfoByHandle(moduleHandle); nativeLayoutContext._typeSystemContext = typeSystemContext; nativeLayoutContext._typeArgumentHandles = typeGenericArguments; nativeLayoutContext._methodArgumentHandles = methodGenericArguments; if (isMethodSignature) return nativeLayoutContext.GetMethod(ref parser); else return nativeLayoutContext.GetType(ref parser); } public bool TryGetGenericMethodDictionaryForComponents(RuntimeTypeHandle declaringTypeHandle, RuntimeTypeHandle[] genericMethodArgHandles, MethodNameAndSignature nameAndSignature, out IntPtr methodDictionary) { if (TryLookupGenericMethodDictionaryForComponents(declaringTypeHandle, nameAndSignature, genericMethodArgHandles, out methodDictionary)) return true; using (LockHolder.Hold(_typeLoaderLock)) { return TypeBuilder.TryBuildGenericMethod(declaringTypeHandle, genericMethodArgHandles, nameAndSignature, out methodDictionary); } } public bool TryGetFieldOffset(RuntimeTypeHandle declaringTypeHandle, uint fieldOrdinal, out int fieldOffset) { fieldOffset = int.MinValue; // No use going further for non-generic types... TypeLoader doesn't have offset answers for non-generic types! if (!declaringTypeHandle.IsGenericType()) return false; using (LockHolder.Hold(_typeLoaderLock)) { return TypeBuilder.TryGetFieldOffset(declaringTypeHandle, fieldOrdinal, out fieldOffset); } } public unsafe IntPtr UpdateFloatingDictionary(IntPtr context, IntPtr dictionaryPtr) { IntPtr newFloatingDictionary; bool isNewlyAllocatedDictionary; bool isTypeContext = context != dictionaryPtr; if (isTypeContext) { EEType* pEEType = (EEType*)context.ToPointer(); IntPtr curDictPtr = EETypeCreator.GetDictionary(pEEType); // Look for the exact base type that owns the dictionary. We may be having // a virtual method run on a derived type and the generic lookup are performed // on the base type's dictionary. while (curDictPtr != dictionaryPtr) { pEEType = pEEType->BaseType; Debug.Assert(pEEType != null); curDictPtr = EETypeCreator.GetDictionary(pEEType); Debug.Assert(curDictPtr != IntPtr.Zero); } context = (IntPtr)pEEType; } using (LockHolder.Hold(_typeLoaderLock)) { // Check if some other thread already allocated a floating dictionary and updated the fixed portion if(*(IntPtr*)dictionaryPtr != IntPtr.Zero) return *(IntPtr*)dictionaryPtr; try { if (t_isReentrant) Environment.FailFast("Reentrant update to floating dictionary"); t_isReentrant = true; newFloatingDictionary = TypeBuilder.TryBuildFloatingDictionary(context, isTypeContext, dictionaryPtr, out isNewlyAllocatedDictionary); t_isReentrant = false; } catch { // Catch and rethrow any exceptions instead of using finally block. Otherwise, filters that are run during // the first pass of exception unwind may hit the re-entrancy fail fast above. // TODO: Convert this to filter for better diagnostics once we switch to Roslyn t_isReentrant = false; throw; } } if (newFloatingDictionary == IntPtr.Zero) { Environment.FailFast("Unable to update floating dictionary"); return IntPtr.Zero; } // The pointer to the floating dictionary is the first slot of the fixed dictionary. if (Interlocked.CompareExchange(ref *(IntPtr*)dictionaryPtr, newFloatingDictionary, IntPtr.Zero) != IntPtr.Zero) { // Some other thread beat us and updated the pointer to the floating dictionary. // Free the one allocated by the current thread if (isNewlyAllocatedDictionary) MemoryHelpers.FreeMemory(newFloatingDictionary); } return *(IntPtr*)dictionaryPtr; } public bool CanInstantiationsShareCode(RuntimeTypeHandle[] genericArgHandles1, RuntimeTypeHandle[] genericArgHandles2, CanonicalFormKind kind) { if (genericArgHandles1.Length != genericArgHandles2.Length) return false; bool match = true; TypeSystemContext context = TypeSystemContextFactory.Create(); for (int i = 0; i < genericArgHandles1.Length; i++) { TypeDesc genericArg1 = context.ResolveRuntimeTypeHandle(genericArgHandles1[i]); TypeDesc genericArg2 = context.ResolveRuntimeTypeHandle(genericArgHandles2[i]); if (context.ConvertToCanon(genericArg1, kind) != context.ConvertToCanon(genericArg2, kind)) { match = false; break; } } TypeSystemContextFactory.Recycle(context); return match; } public bool ConversionToCanonFormIsAChange(RuntimeTypeHandle[] genericArgHandles, CanonicalFormKind kind) { // Todo: support for universal canon type? TypeSystemContext context = TypeSystemContextFactory.Create(); Instantiation genericArgs = context.ResolveRuntimeTypeHandles(genericArgHandles); bool result; context.ConvertInstantiationToCanonForm(genericArgs, kind, out result); TypeSystemContextFactory.Recycle(context); return result; } // get the generics hash table and external references table for a module // TODO multi-file: consider whether we want to cache this info private unsafe bool GetHashtableFromBlob(NativeFormatModuleInfo module, ReflectionMapBlob blobId, out NativeHashtable hashtable, out ExternalReferencesTable externalReferencesLookup) { byte* pBlob; uint cbBlob; hashtable = default(NativeHashtable); externalReferencesLookup = default(ExternalReferencesTable); if (!module.TryFindBlob(blobId, out pBlob, out cbBlob)) return false; NativeReader reader = new NativeReader(pBlob, cbBlob); NativeParser parser = new NativeParser(reader, 0); hashtable = new NativeHashtable(parser); return externalReferencesLookup.InitializeNativeReferences(module); } public static unsafe void GetFieldAlignmentAndSize(RuntimeTypeHandle fieldType, out int alignment, out int size) { EEType* typePtr = fieldType.ToEETypePtr(); if (typePtr->IsValueType) { size = (int)typePtr->ValueTypeSize; } else { size = IntPtr.Size; } alignment = (int)typePtr->FieldAlignmentRequirement; } [StructLayout(LayoutKind.Sequential)] private struct UnboxingAndInstantiatingStubMapEntry { public uint StubMethodRva; public uint MethodRva; } public static unsafe bool TryGetTargetOfUnboxingAndInstantiatingStub(IntPtr maybeInstantiatingAndUnboxingStub, out IntPtr targetMethod) { targetMethod = RuntimeAugments.GetTargetOfUnboxingAndInstantiatingStub(maybeInstantiatingAndUnboxingStub); if (targetMethod != IntPtr.Zero) { return true; } // TODO: The rest of the code in this function is specific to ProjectN only. When we kill the binder, get rid of this // linear search code (the only API that should be used for the lookup is the one above) // Get module IntPtr associatedModule = RuntimeAugments.GetOSModuleFromPointer(maybeInstantiatingAndUnboxingStub); if (associatedModule == IntPtr.Zero) { return false; } // Get UnboxingAndInstantiatingTable UnboxingAndInstantiatingStubMapEntry* pBlob; uint cbBlob; if (!RuntimeAugments.FindBlob(new TypeManagerHandle(associatedModule), (int)ReflectionMapBlob.UnboxingAndInstantiatingStubMap, (IntPtr)(&pBlob), (IntPtr)(&cbBlob))) { return false; } uint cStubs = cbBlob / (uint)sizeof(UnboxingAndInstantiatingStubMapEntry); for (uint i = 0; i < cStubs; ++i) { if (RvaToFunctionPointer(new TypeManagerHandle(associatedModule), pBlob[i].StubMethodRva) == maybeInstantiatingAndUnboxingStub) { // We found a match, create pointer from RVA and move on. targetMethod = RvaToFunctionPointer(new TypeManagerHandle(associatedModule), pBlob[i].MethodRva); return true; } } // Stub not found. return false; } public bool TryComputeHasInstantiationDeterminedSize(RuntimeTypeHandle typeHandle, out bool hasInstantiationDeterminedSize) { TypeSystemContext context = TypeSystemContextFactory.Create(); bool success = TryComputeHasInstantiationDeterminedSize(typeHandle, context, out hasInstantiationDeterminedSize); TypeSystemContextFactory.Recycle(context); return success; } public bool TryComputeHasInstantiationDeterminedSize(RuntimeTypeHandle typeHandle, TypeSystemContext context, out bool hasInstantiationDeterminedSize) { Debug.Assert(RuntimeAugments.IsGenericType(typeHandle) || RuntimeAugments.IsGenericTypeDefinition(typeHandle)); DefType type = (DefType)context.ResolveRuntimeTypeHandle(typeHandle); return TryComputeHasInstantiationDeterminedSize(type, out hasInstantiationDeterminedSize); } internal bool TryComputeHasInstantiationDeterminedSize(DefType type, out bool hasInstantiationDeterminedSize) { Debug.Assert(type.HasInstantiation); NativeLayoutInfoLoadContext loadContextUniversal; NativeLayoutInfo universalLayoutInfo; NativeParser parser = type.GetOrCreateTypeBuilderState().GetParserForUniversalNativeLayoutInfo(out loadContextUniversal, out universalLayoutInfo); if (parser.IsNull) { hasInstantiationDeterminedSize = false; #if SUPPORTS_NATIVE_METADATA_TYPE_LOADING MetadataType typeDefinition = type.GetTypeDefinition() as MetadataType; if (typeDefinition != null) { TypeDesc [] universalCanonInstantiation = new TypeDesc[type.Instantiation.Length]; TypeSystemContext context = type.Context; TypeDesc universalCanonType = context.UniversalCanonType; for (int i = 0 ; i < universalCanonInstantiation.Length; i++) universalCanonInstantiation[i] = universalCanonType; DefType universalCanonForm = typeDefinition.MakeInstantiatedType(universalCanonInstantiation); hasInstantiationDeterminedSize = universalCanonForm.InstanceFieldSize.IsIndeterminate; return true; } #endif return false; } int? flags = (int?)parser.GetUnsignedForBagElementKind(BagElementKind.TypeFlags); hasInstantiationDeterminedSize = flags.HasValue ? (((NativeFormat.TypeFlags)flags) & NativeFormat.TypeFlags.HasInstantiationDeterminedSize) != 0 : false; return true; } public bool TryResolveSingleMetadataFixup(ModuleInfo module, int metadataToken, MetadataFixupKind fixupKind, out IntPtr fixupResolution) { #if SUPPORTS_NATIVE_METADATA_TYPE_LOADING using (LockHolder.Hold(_typeLoaderLock)) { try { return TypeBuilder.TryResolveSingleMetadataFixup((NativeFormatModuleInfo)module, metadataToken, fixupKind, out fixupResolution); } catch (Exception ex) { Environment.FailFast("Failed to resolve metadata token " + ((uint)metadataToken).LowLevelToString() + ": " + ex.Message); #else Environment.FailFast("Failed to resolve metadata token " + ((uint)metadataToken).LowLevelToString()); #endif fixupResolution = IntPtr.Zero; return false; #if SUPPORTS_NATIVE_METADATA_TYPE_LOADING } } #endif } public bool TryDispatchMethodOnTarget(NativeFormatModuleInfo module, int metadataToken, RuntimeTypeHandle targetInstanceType, out IntPtr methodAddress) { using (LockHolder.Hold(_typeLoaderLock)) { return TryDispatchMethodOnTarget_Inner( module, metadataToken, targetInstanceType, out methodAddress); } } #if SUPPORTS_NATIVE_METADATA_TYPE_LOADING internal DispatchCellInfo ConvertDispatchCellInfo(NativeFormatModuleInfo module, DispatchCellInfo cellInfo) { using (LockHolder.Hold(_typeLoaderLock)) { return ConvertDispatchCellInfo_Inner( module, cellInfo); } } #endif internal bool TryResolveTypeSlotDispatch(IntPtr targetTypeAsIntPtr, IntPtr interfaceTypeAsIntPtr, ushort slot, out IntPtr methodAddress) { using (LockHolder.Hold(_typeLoaderLock)) { return TryResolveTypeSlotDispatch_Inner(targetTypeAsIntPtr, interfaceTypeAsIntPtr, slot, out methodAddress); } } public unsafe bool TryGetOrCreateNamedTypeForMetadata( QTypeDefinition qTypeDefinition, out RuntimeTypeHandle runtimeTypeHandle) { if (TryGetNamedTypeForMetadata(qTypeDefinition, out runtimeTypeHandle)) { return true; } #if SUPPORTS_NATIVE_METADATA_TYPE_LOADING using (LockHolder.Hold(_typeLoaderLock)) { IntPtr runtimeTypeHandleAsIntPtr; TypeBuilder.ResolveSingleTypeDefinition(qTypeDefinition, out runtimeTypeHandleAsIntPtr); runtimeTypeHandle = *(RuntimeTypeHandle*)&runtimeTypeHandleAsIntPtr; return true; } #else return false; #endif } public static IntPtr ConvertUnboxingFunctionPointerToUnderlyingNonUnboxingPointer(IntPtr unboxingFunctionPointer, RuntimeTypeHandle declaringType) { if (FunctionPointerOps.IsGenericMethodPointer(unboxingFunctionPointer)) { // Handle shared generic methods unsafe { GenericMethodDescriptor* functionPointerDescriptor = FunctionPointerOps.ConvertToGenericDescriptor(unboxingFunctionPointer); IntPtr nonUnboxingTarget = RuntimeAugments.GetCodeTarget(functionPointerDescriptor->MethodFunctionPointer); Debug.Assert(nonUnboxingTarget != functionPointerDescriptor->MethodFunctionPointer); Debug.Assert(nonUnboxingTarget == RuntimeAugments.GetCodeTarget(nonUnboxingTarget)); return FunctionPointerOps.GetGenericMethodFunctionPointer(nonUnboxingTarget, functionPointerDescriptor->InstantiationArgument); } } // GetCodeTarget will look through simple unboxing stubs (ones that consist of adjusting the this pointer and then // jumping to the target. IntPtr exactTarget = RuntimeAugments.GetCodeTarget(unboxingFunctionPointer); if (RuntimeAugments.IsGenericType(declaringType)) { IntPtr fatFunctionPointerTarget; // This check looks for unboxing and instantiating stubs generated via the compiler backend if (TypeLoaderEnvironment.TryGetTargetOfUnboxingAndInstantiatingStub(exactTarget, out fatFunctionPointerTarget)) { // If this is an unboxing and instantiating stub, use seperate table, find target, and create fat function pointer exactTarget = FunctionPointerOps.GetGenericMethodFunctionPointer(fatFunctionPointerTarget, declaringType.ToIntPtr()); } else { IntPtr newExactTarget; // This check looks for unboxing and instantiating stubs generated dynamically as thunks in the calling convention converter if (CallConverterThunk.TryGetNonUnboxingFunctionPointerFromUnboxingAndInstantiatingStub(exactTarget, declaringType, out newExactTarget)) { // CallingConventionConverter determined non-unboxing stub exactTarget = newExactTarget; } else { // Target method was a method on a generic, but it wasn't a shared generic, and thus none of the above // complex unboxing stub digging logic was necessary. Do nothing, and use exactTarget as discovered // from GetCodeTarget } } } return exactTarget; } } }
// **************************************************************** // Copyright 2007, Charlie Poole // This is free software licensed under the NUnit license. You may // obtain a copy of the license at http://nunit.org // **************************************************************** using System; using System.Collections; #if NET_2_0 using System.Collections.Generic; #endif namespace NUnit.Framework.Constraints { #region ComparisonTest public abstract class ComparisonConstraintTest : ConstraintTestBaseWithArgumentException { protected ComparisonConstraint comparisonConstraint; [Test] public void UsesProvidedIComparer() { MyComparer comparer = new MyComparer(); comparisonConstraint.Using(comparer).Matches(0); Assert.That(comparer.Called, "Comparer was not called"); } class MyComparer : IComparer { public bool Called; public int Compare(object x, object y) { Called = true; return Comparer.Default.Compare(x, y); } } #if NET_2_0 [Test] public void UsesProvidedComparerOfT() { MyComparer<int> comparer = new MyComparer<int>(); comparisonConstraint.Using(comparer).Matches(0); Assert.That(comparer.Called, "Comparer was not called"); } class MyComparer<T> : IComparer<T> { public bool Called; public int Compare(T x, T y) { Called = true; return Comparer<T>.Default.Compare(x, y); } } [Test] public void UsesProvidedComparisonOfT() { MyComparison<int> comparer = new MyComparison<int>(); comparisonConstraint.Using(new Comparison<int>(comparer.Compare)).Matches(0); Assert.That(comparer.Called, "Comparer was not called"); } class MyComparison<T> { public bool Called; public int Compare(T x, T y) { Called = true; return Comparer<T>.Default.Compare(x, y); } } #if CS_3_0 [Test] public void UsesProvidedLambda() { Comparison<int> comparer = (x, y) => x.CompareTo(y); comparisonConstraint.Using(comparer).Matches(0); } #endif #endif } #endregion #region GreaterThan [TestFixture] public class GreaterThanTest : ComparisonConstraintTest { [SetUp] public void SetUp() { theConstraint = comparisonConstraint = new GreaterThanConstraint(5); expectedDescription = "greater than 5"; stringRepresentation = "<greaterthan 5>"; } internal object[] SuccessData = new object[] { 6, 5.001 }; internal object[] FailureData = new object[] { 4, 5 }; internal string[] ActualValues = new string[] { "4", "5" }; internal object[] InvalidData = new object[] { null, "xxx" }; [Test] public void CanCompareIComparables() { ClassWithIComparable expected = new ClassWithIComparable(0); ClassWithIComparable actual = new ClassWithIComparable(42); Assert.That(actual, Is.GreaterThan(expected)); } #if NET_2_0 [Test] public void CanCompareIComparablesOfT() { ClassWithIComparableOfT expected = new ClassWithIComparableOfT(0); ClassWithIComparableOfT actual = new ClassWithIComparableOfT(42); Assert.That(actual, Is.GreaterThan(expected)); } #endif } #endregion #region GreaterThanOrEqual [TestFixture] public class GreaterThanOrEqualTest : ComparisonConstraintTest { [SetUp] public void SetUp() { theConstraint = comparisonConstraint = new GreaterThanOrEqualConstraint(5); expectedDescription = "greater than or equal to 5"; stringRepresentation = "<greaterthanorequal 5>"; } internal object[] SuccessData = new object[] { 6, 5 }; internal object[] FailureData = new object[] { 4 }; internal string[] ActualValues = new string[] { "4" }; internal object[] InvalidData = new object[] { null, "xxx" }; [Test] public void CanCompareIComparables() { ClassWithIComparable expected = new ClassWithIComparable(0); ClassWithIComparable actual = new ClassWithIComparable(42); Assert.That(actual, Is.GreaterThanOrEqualTo(expected)); } #if NET_2_0 [Test] public void CanCompareIComparablesOfT() { ClassWithIComparableOfT expected = new ClassWithIComparableOfT(0); ClassWithIComparableOfT actual = new ClassWithIComparableOfT(42); Assert.That(actual, Is.GreaterThanOrEqualTo(expected)); } #endif } #endregion #region LessThan [TestFixture] public class LessThanTest : ComparisonConstraintTest { [SetUp] public void SetUp() { theConstraint = comparisonConstraint = new LessThanConstraint(5); expectedDescription = "less than 5"; stringRepresentation = "<lessthan 5>"; } internal object[] SuccessData = new object[] { 4, 4.999 }; internal object[] FailureData = new object[] { 6, 5 }; internal string[] ActualValues = new string[] { "6", "5" }; internal object[] InvalidData = new object[] { null, "xxx" }; [Test] public void CanCompareIComparables() { ClassWithIComparable expected = new ClassWithIComparable(42); ClassWithIComparable actual = new ClassWithIComparable(0); Assert.That(actual, Is.LessThan(expected)); } #if NET_2_0 [Test] public void CanCompareIComparablesOfT() { ClassWithIComparableOfT expected = new ClassWithIComparableOfT(42); ClassWithIComparableOfT actual = new ClassWithIComparableOfT(0); Assert.That(actual, Is.LessThan(expected)); } #endif } #endregion #region LessThanOrEqual [TestFixture] public class LessThanOrEqualTest : ComparisonConstraintTest { [SetUp] public void SetUp() { theConstraint = comparisonConstraint = new LessThanOrEqualConstraint(5); expectedDescription = "less than or equal to 5"; stringRepresentation = "<lessthanorequal 5>"; } internal object[] SuccessData = new object[] { 4, 5 }; internal object[] FailureData = new object[] { 6 }; internal string[] ActualValues = new string[] { "6" }; internal object[] InvalidData = new object[] { null, "xxx" }; [Test] public void CanCompareIComparables() { ClassWithIComparable expected = new ClassWithIComparable(42); ClassWithIComparable actual = new ClassWithIComparable(0); Assert.That(actual, Is.LessThanOrEqualTo(expected)); } #if NET_2_0 [Test] public void CanCompareIComparablesOfT() { ClassWithIComparableOfT expected = new ClassWithIComparableOfT(42); ClassWithIComparableOfT actual = new ClassWithIComparableOfT(0); Assert.That(actual, Is.LessThanOrEqualTo(expected)); } #endif } #endregion #region RangeConstraint [TestFixture] public class RangeConstraintTest : ConstraintTestBaseWithArgumentException { RangeConstraint rangeConstraint; [SetUp] public void SetUp() { theConstraint = rangeConstraint = new RangeConstraint(5, 42); expectedDescription = "in range (5,42)"; stringRepresentation = "<range 5 42>"; } internal object[] SuccessData = new object[] { 5, 23, 42 }; internal object[] FailureData = new object[] { 4, 43 }; internal string[] ActualValues = new string[] { "4", "43" }; internal object[] InvalidData = new object[] { null, "xxx" }; [Test] public void UsesProvidedIComparer() { MyComparer comparer = new MyComparer(); Assert.That(rangeConstraint.Using(comparer).Matches(19)); Assert.That(comparer.Called, "Comparer was not called"); } class MyComparer : IComparer { public bool Called; public int Compare(object x, object y) { Called = true; return Comparer.Default.Compare(x, y); } } #if NET_2_0 [Test] public void UsesProvidedComparerOfT() { MyComparer<int> comparer = new MyComparer<int>(); Assert.That(rangeConstraint.Using(comparer).Matches(19)); Assert.That(comparer.Called, "Comparer was not called"); } class MyComparer<T> : IComparer<T> { public bool Called; public int Compare(T x, T y) { Called = true; return Comparer<T>.Default.Compare(x, y); } } [Test] public void UsesProvidedComparisonOfT() { MyComparison<int> comparer = new MyComparison<int>(); Assert.That(rangeConstraint.Using(new Comparison<int>(comparer.Compare)).Matches(19)); Assert.That(comparer.Called, "Comparer was not called"); } class MyComparison<T> { public bool Called; public int Compare(T x, T y) { Called = true; return Comparer<T>.Default.Compare(x, y); } } #if CS_3_0 [Test] public void UsesProvidedLambda() { Comparison<int> comparer = (x, y) => x.CompareTo(y); Assert.That(rangeConstraint.Using(comparer).Matches(19)); } #endif #endif } #endregion #region Test Classes class ClassWithIComparable : IComparable { private int val; public ClassWithIComparable(int val) { this.val = val; } public int CompareTo(object x) { ClassWithIComparable other = x as ClassWithIComparable; if (x is ClassWithIComparable) return val.CompareTo(other.val); throw new ArgumentException(); } } #if NET_2_0 class ClassWithIComparableOfT : IComparable<ClassWithIComparableOfT> { private int val; public ClassWithIComparableOfT(int val) { this.val = val; } public int CompareTo(ClassWithIComparableOfT other) { return val.CompareTo(other.val); } } #endif #endregion }
using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Runtime.InteropServices; using Umbraco.Core; using Umbraco.Core.Cache; using Umbraco.Core.Logging; using umbraco.BusinessLogic; using umbraco.BusinessLogic.Actions; using umbraco.cms.businesslogic.cache; using Umbraco.Core.Models; using umbraco.interfaces; using umbraco.DataLayer; using System.Runtime.CompilerServices; using Language = umbraco.cms.businesslogic.language.Language; namespace umbraco.cms.businesslogic.web { /// <summary> /// Summary description for Domain. /// </summary> [Obsolete("Use Umbraco.Core.Models.IDomain and Umbraco.Core.Services.IDomainService instead")] public class Domain { public IDomain DomainEntity { get; set; } /// <summary> /// Empty ctor used for unit tests to create a custom domain /// </summary> internal Domain() { } internal Domain(IDomain domain) { DomainEntity = domain; } public Domain(int Id) { DomainEntity = ApplicationContext.Current.Services.DomainService.GetById(Id); if (DomainEntity == null) { throw new Exception(string.Format("Domain name '{0}' does not exists", Id)); } } public Domain(string DomainName) { DomainEntity = ApplicationContext.Current.Services.DomainService.GetByName(DomainName); if (DomainEntity == null) { throw new Exception(string.Format("Domain name '{0}' does not exists", DomainName)); } } public string Name { get { return DomainEntity.DomainName; } set { DomainEntity.DomainName = value; } } public Language Language { get { if (DomainEntity.LanguageId.HasValue == false) return null; var lang = ApplicationContext.Current.Services.LocalizationService.GetLanguageById(DomainEntity.LanguageId.Value); if (lang == null) throw new InvalidOperationException("No language exists with id " + DomainEntity.LanguageId.Value); return new Language(lang); } set { DomainEntity.LanguageId = value.LanguageEntity.Id; } } public int RootNodeId { get { return DomainEntity.RootContentId ?? -1; } set { DomainEntity.RootContentId = value; } } public int Id { get { return DomainEntity.Id; } } public void Delete() { var e = new DeleteEventArgs(); FireBeforeDelete(e); if (!e.Cancel) { ApplicationContext.Current.Services.DomainService.Delete(DomainEntity); FireAfterDelete(e); } } public void Save(){ var e = new SaveEventArgs(); FireBeforeSave(e); if (!e.Cancel) { if (ApplicationContext.Current.Services.DomainService.Save(DomainEntity)) { FireAfterSave(e); } } } #region Statics public static IEnumerable<Domain> GetDomains() { return GetDomains(false); } public static IEnumerable<Domain> GetDomains(bool includeWildcards) { return ApplicationContext.Current.Services.DomainService.GetAll(includeWildcards) .Select(x => new Domain(x)); } public static Domain GetDomain(string DomainName) { var found = ApplicationContext.Current.Services.DomainService.GetByName(DomainName); return found == null ? null : new Domain(found); } public static int GetRootFromDomain(string DomainName) { var found = ApplicationContext.Current.Services.DomainService.GetByName(DomainName); return found == null ? -1 : found.RootContentId ?? -1; } public static Domain[] GetDomainsById(int nodeId) { return ApplicationContext.Current.Services.DomainService.GetAssignedDomains(nodeId, true) .Select(x => new Domain(x)) .ToArray(); } public static Domain[] GetDomainsById(int nodeId, bool includeWildcards) { return ApplicationContext.Current.Services.DomainService.GetAssignedDomains(nodeId, includeWildcards) .Select(x => new Domain(x)) .ToArray(); } public static bool Exists(string DomainName) { return ApplicationContext.Current.Services.DomainService.Exists(DomainName); } public static void MakeNew(string DomainName, int RootNodeId, int LanguageId) { var domain = new UmbracoDomain(DomainName) { RootContentId = RootNodeId, LanguageId = LanguageId }; if (ApplicationContext.Current.Services.DomainService.Save(domain)) { var e = new NewEventArgs(); var legacyModel = new Domain(domain); legacyModel.OnNew(e); } } #endregion //EVENTS public delegate void SaveEventHandler(Domain sender, SaveEventArgs e); public delegate void NewEventHandler(Domain sender, NewEventArgs e); public delegate void DeleteEventHandler(Domain sender, DeleteEventArgs e); /// <summary> /// Occurs when a macro is saved. /// </summary> public static event SaveEventHandler BeforeSave; protected virtual void FireBeforeSave(SaveEventArgs e) { if (BeforeSave != null) BeforeSave(this, e); } public static event SaveEventHandler AfterSave; protected virtual void FireAfterSave(SaveEventArgs e) { if (AfterSave != null) AfterSave(this, e); } public static event NewEventHandler New; protected virtual void OnNew(NewEventArgs e) { if (New != null) New(this, e); } public static event DeleteEventHandler BeforeDelete; protected virtual void FireBeforeDelete(DeleteEventArgs e) { if (BeforeDelete != null) BeforeDelete(this, e); } public static event DeleteEventHandler AfterDelete; protected virtual void FireAfterDelete(DeleteEventArgs e) { if (AfterDelete != null) AfterDelete(this, e); } #region Pipeline Refactoring // NOTE: the wildcard name thing should be managed by the Domain class // internally but that would break too much backward compatibility, so // we don't do it now. Will do it when the Domain class migrates to the // new Core.Models API. /// <summary> /// Gets a value indicating whether the domain is a wildcard domain. /// </summary> /// <returns>A value indicating whether the domain is a wildcard domain.</returns> public bool IsWildcard { get { return DomainEntity.IsWildcard; } } #endregion } }
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Threading.Tasks; using Orleans.Runtime; using Orleans.Runtime.Configuration; using Orleans.Providers; using Orleans.Hosting; using Microsoft.Extensions.Options; using Orleans.Configuration; using Microsoft.Extensions.DependencyInjection; namespace Orleans.Streams { /// <summary> /// DeploymentBasedQueueBalancer is a stream queue balancer that uses deployment information to /// help balance queue distribution. /// DeploymentBasedQueueBalancer uses the deployment configuration to determine how many silos /// to expect and uses a silo status oracle to determine which of the silos are available. With /// this information it tries to balance the queues using a best fit resource balancing algorithm. /// </summary> public class DeploymentBasedQueueBalancer : QueueBalancerBase, ISiloStatusListener, IStreamQueueBalancer { private readonly ISiloStatusOracle siloStatusOracle; private readonly IDeploymentConfiguration deploymentConfig; private ReadOnlyCollection<QueueId> allQueues; private readonly ConcurrentDictionary<SiloAddress, bool> immatureSilos; private readonly DeploymentBasedQueueBalancerOptions options; private bool isStarting; public DeploymentBasedQueueBalancer( ISiloStatusOracle siloStatusOracle, IDeploymentConfiguration deploymentConfig, DeploymentBasedQueueBalancerOptions options) { if (siloStatusOracle == null) { throw new ArgumentNullException("siloStatusOracle"); } if (deploymentConfig == null) { throw new ArgumentNullException("deploymentConfig"); } this.siloStatusOracle = siloStatusOracle; this.deploymentConfig = deploymentConfig; immatureSilos = new ConcurrentDictionary<SiloAddress, bool>(); this.options = options; isStarting = true; // register for notification of changes to silo status for any silo in the cluster this.siloStatusOracle.SubscribeToSiloStatusEvents(this); // record all already active silos as already mature. // Even if they are not yet, they will be mature by the time I mature myself (after I become !isStarting). foreach (var silo in siloStatusOracle.GetApproximateSiloStatuses(true).Keys.Where(s => !s.Equals(siloStatusOracle.SiloAddress))) { immatureSilos[silo] = false; // record as mature } } public static IStreamQueueBalancer Create(IServiceProvider services, string name, IDeploymentConfiguration deploymentConfiguration) { var options = services.GetRequiredService<IOptionsMonitor<DeploymentBasedQueueBalancerOptions>>().Get(name); return ActivatorUtilities.CreateInstance<DeploymentBasedQueueBalancer>(services, options, deploymentConfiguration); } public override Task Initialize(IStreamQueueMapper queueMapper) { if (queueMapper == null) { throw new ArgumentNullException("queueMapper"); } this.allQueues = new ReadOnlyCollection<QueueId>(queueMapper.GetAllQueues().ToList()); NotifyAfterStart().Ignore(); return Task.CompletedTask; } private async Task NotifyAfterStart() { await Task.Delay(this.options.SiloMaturityPeriod); isStarting = false; await NotifyListeners(); } /// <summary> /// Called when the status of a silo in the cluster changes. /// - Notify listeners /// </summary> /// <param name="updatedSilo">Silo which status has changed</param> /// <param name="status">new silo status</param> public void SiloStatusChangeNotification(SiloAddress updatedSilo, SiloStatus status) { if (status == SiloStatus.Dead) { // just clean up garbage from immatureSilos. bool ignore; immatureSilos.TryRemove(updatedSilo, out ignore); } SiloStatusChangeNotification().Ignore(); } private async Task SiloStatusChangeNotification() { List<Task> tasks = new List<Task>(); // look at all currently active silos not including myself foreach (var silo in siloStatusOracle.GetApproximateSiloStatuses(true).Keys.Where(s => !s.Equals(siloStatusOracle.SiloAddress))) { bool ignore; if (!immatureSilos.TryGetValue(silo, out ignore)) { tasks.Add(RecordImmatureSilo(silo)); } } if (!isStarting) { // notify, uncoditionaly, and deal with changes in GetMyQueues() NotifyListeners().Ignore(); } if (tasks.Count > 0) { await Task.WhenAll(tasks); await NotifyListeners(); // notify, uncoditionaly, and deal with changes it in GetMyQueues() } } private async Task RecordImmatureSilo(SiloAddress updatedSilo) { immatureSilos[updatedSilo] = true; // record as immature await Task.Delay(this.options.SiloMaturityPeriod); immatureSilos[updatedSilo] = false; // record as mature } public override IEnumerable<QueueId> GetMyQueues() { BestFitBalancer<string, QueueId> balancer = GetBalancer(); bool useIdealDistribution = this.options.IsFixed || isStarting; Dictionary<string, List<QueueId>> distribution = useIdealDistribution ? balancer.IdealDistribution : balancer.GetDistribution(GetActiveSilos(siloStatusOracle, immatureSilos)); List<QueueId> myQueues; if (distribution.TryGetValue(siloStatusOracle.SiloName, out myQueues)) { if (!useIdealDistribution) { HashSet<QueueId> queuesOfImmatureSilos = GetQueuesOfImmatureSilos(siloStatusOracle, immatureSilos, balancer.IdealDistribution); // filter queues that belong to immature silos myQueues.RemoveAll(queue => queuesOfImmatureSilos.Contains(queue)); } return myQueues; } return Enumerable.Empty<QueueId>(); } private static List<string> GetActiveSilos(ISiloStatusOracle siloStatusOracle, ConcurrentDictionary<SiloAddress, bool> immatureSilos) { var activeSiloNames = new List<string>(); foreach (var kvp in siloStatusOracle.GetApproximateSiloStatuses(true)) { bool immatureBit; if (!(immatureSilos.TryGetValue(kvp.Key, out immatureBit) && immatureBit)) // if not immature now or any more { string siloName; if (siloStatusOracle.TryGetSiloName(kvp.Key, out siloName)) { activeSiloNames.Add(siloName); } } } return activeSiloNames; } /// <summary> /// Checks to see if deployment configuration has changed, by adding or removing silos. /// If so, it updates the list of all silo names and creates a new resource balancer. /// This should occur rarely. /// </summary> private BestFitBalancer<string, QueueId> GetBalancer() { var allSiloNames = deploymentConfig.GetAllSiloNames(); // rebuild balancer with new list of instance names return new BestFitBalancer<string, QueueId>(allSiloNames, allQueues); } private static HashSet<QueueId> GetQueuesOfImmatureSilos(ISiloStatusOracle siloStatusOracle, ConcurrentDictionary<SiloAddress, bool> immatureSilos, Dictionary<string, List<QueueId>> idealDistribution) { HashSet<QueueId> queuesOfImmatureSilos = new HashSet<QueueId>(); foreach (var silo in immatureSilos.Where(s => s.Value)) // take only those from immature set that have their immature status bit set { string siloName; if (siloStatusOracle.TryGetSiloName(silo.Key, out siloName)) { List<QueueId> queues; if (idealDistribution.TryGetValue(siloName, out queues)) { queuesOfImmatureSilos.UnionWith(queues); } } } return queuesOfImmatureSilos; } private Task NotifyListeners() { List<IStreamQueueBalanceListener> queueBalanceListenersCopy; lock (queueBalanceListeners) { queueBalanceListenersCopy = queueBalanceListeners.ToList(); // make copy } var notificatioTasks = new List<Task>(queueBalanceListenersCopy.Count); foreach (IStreamQueueBalanceListener listener in queueBalanceListenersCopy) { notificatioTasks.Add(listener.QueueDistributionChangeNotification()); } return Task.WhenAll(notificatioTasks); } } }
using System; using System.Data; using System.Configuration; using System.Collections; using System.Collections.Generic; using System.Text; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using TABS_UserControls.resources.code.BAL; using TABS_UserControls.resources.code.DAL; namespace TABS_UserControls.usercontrols { /// <summary> /// /// </summary> public partial class proposal_conference : System.Web.UI.UserControl { #region Variable Declarations private ConferenceClass ConferenceBAL = new ConferenceClass(); private tabs_admin TabsAdminBAL = new tabs_admin(); private Encryption64 EncryptionBAL = new Encryption64(); #endregion #region Event Handlers /// <summary> /// Handles the Load event of the Page control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { // Get current conference ConferencesDataset._tabs_ConferencesDataTable dt = ConferenceBAL.GetCurrentConference(); if (dt.Rows.Count > 0) { int conferenceId = dt[0].ConferenceId; litConferenceProposalId.Text = conferenceId.ToString(); // Build presentationTypes BuildProposalTypes(conferenceId); // Build topic areas BuildTopicAreas(conferenceId); // Build the countries BuildCountries(); if (Request.QueryString["mode"] == "e") { // Edit an existing proposal // Get the ConferenceProposalId if (!String.IsNullOrEmpty(Request.QueryString["cid"])) { string encrypted = Request.QueryString["cid"]; // The plus signs were stripped out, add them back encrypted = encrypted.Replace(" ", "+"); int conferenceProposalId = 0; int.TryParse(EncryptionBAL.Decrypt(encrypted, "secretTABS"), out conferenceProposalId); if (conferenceProposalId > 0) { // Bind the Data BindData(conferenceProposalId); } } } } } } /// <summary> /// Handles the SelectedIndexChanged event of the rblHavePresentedBefore control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> protected void rblHavePresentedBefore_SelectedIndexChanged(object sender, EventArgs e) { RadioButtonList rbl = (RadioButtonList)sender; if (rbl.SelectedValue.Equals("1")) { tbSpeaker1OtherConferences.Enabled = true; } else { tbSpeaker1OtherConferences.Enabled = false; tbSpeaker1OtherConferences.Text = string.Empty; } Page.SetFocus(tbSpeaker1OtherConferences); } /// <summary> /// Handles the SelectedIndexChanged event of the rblSpeaker2HasPresented control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> protected void rblSpeaker2HasPresented_SelectedIndexChanged(object sender, EventArgs e) { RadioButtonList rbl = (RadioButtonList)sender; if (rbl.SelectedValue.Equals("1")) { tbSpeaker2OtherConferences.Enabled = true; } else { tbSpeaker2OtherConferences.Enabled = false; tbSpeaker2OtherConferences.Text = string.Empty; } Page.SetFocus(tbSpeaker2OtherConferences); } /// <summary> /// Handles the SelectedIndexChanged event of the rblSpeaker3HasPresented control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> protected void rblSpeaker3HasPresented_SelectedIndexChanged(object sender, EventArgs e) { RadioButtonList rbl = (RadioButtonList)sender; if (rbl.SelectedValue.Equals("1")) { tbSpeaker3OtherConferences.Enabled = true; } else { tbSpeaker3OtherConferences.Enabled = false; tbSpeaker3OtherConferences.Text = string.Empty; } Page.SetFocus(tbSpeaker3OtherConferences); } /// <summary> /// Handles the Click event of the btnSubmit control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> protected void btnSubmit_Click(object sender, EventArgs e) { // Validate the page Page.Validate(); if (Page.IsValid) { // Submit the data to the database SubmitData(); // Send Email Confirmation SendEmail(); // Redirect to the thank you page Response.Redirect("/for-schools/professional-development/conferences/proposal-thankyou.aspx", true); } } protected void ddlCountry_SelectedIndexChanged(object sender, EventArgs e) { // Determine which country dropdown is calling DropDownList ddl = (DropDownList)sender; if (ddl.ID.Equals("ddlSpeaker1Country")) { if (ddlSpeaker1Country.SelectedValue.Equals("0")) { ddlSpeaker1State.Items.Clear(); ddlSpeaker1State.Enabled = false; } else { // Populate the state/province based on the country selection SchoolManagerClass smlogic = new SchoolManagerClass(); SchoolManageDataset._tabs_statesDataTable dt = smlogic.getStatesByCountryId(int.Parse(ddlSpeaker1Country.SelectedValue)); ddlSpeaker1State.DataSource = dt; ddlSpeaker1State.DataBind(); ddlSpeaker1State.Items.Insert(0, new ListItem("-- Please Select --", "0")); ddlSpeaker1State.Enabled = true; Page.SetFocus(ddlSpeaker1State); } } else { if (ddl.ID.Equals("ddlSpeaker2Country")) { if (ddlSpeaker2Country.SelectedValue.Equals("0")) { ddlSpeaker2State.Items.Clear(); ddlSpeaker2State.Enabled = false; } else { // Populate the state/province based on the country selection SchoolManagerClass smlogic = new SchoolManagerClass(); SchoolManageDataset._tabs_statesDataTable dt = smlogic.getStatesByCountryId(int.Parse(ddlSpeaker2Country.SelectedValue)); ddlSpeaker2State.DataSource = dt; ddlSpeaker2State.DataBind(); ddlSpeaker2State.Items.Insert(0, new ListItem("-- Please Select --", "0")); ddlSpeaker2State.Enabled = true; Page.SetFocus(ddlSpeaker2State); } } else { if (ddl.ID.Equals("ddlSpeaker3Country")) { if (ddlSpeaker3Country.SelectedValue.Equals("0")) { ddlSpeaker3State.Items.Clear(); ddlSpeaker3State.Enabled = false; } else { // Populate the state/province based on the country selection SchoolManagerClass smlogic = new SchoolManagerClass(); SchoolManageDataset._tabs_statesDataTable dt = smlogic.getStatesByCountryId(int.Parse(ddlSpeaker3Country.SelectedValue)); ddlSpeaker3State.DataSource = dt; ddlSpeaker3State.DataBind(); ddlSpeaker3State.Items.Insert(0, new ListItem("-- Please Select --", "0")); ddlSpeaker3State.Enabled = true; Page.SetFocus(ddlSpeaker3State); } } } } } public void cvAgreement1_ServerValidate(object source, ServerValidateEventArgs args) { args.IsValid = (cbAgreement1.Checked == true); } public void cvAgreement2_ServerValidate(object source, ServerValidateEventArgs args) { args.IsValid = (cbAgreement2.Checked == true); } #endregion #region Methods /// <summary> /// Builds the proposal types radio buttons. /// </summary> /// <param name="conferenceId">The conference id.</param> private void BuildProposalTypes(int conferenceId) { ConferencesDataset._tabs_ConferenceProposalTypesDataTable dt = ConferenceBAL.GetProposalTypes(conferenceId); if (dt.Rows.Count > 0) { DataTable dtCopy = dt.Copy(); rptProposalTypesLeft.DataSource = GetHalfofData(dt, true); rptProposalTypesLeft.DataBind(); rptProposalTypesRight.DataSource = GetHalfofData(dtCopy, false); rptProposalTypesRight.DataBind(); } } /// <summary> /// Builds the topic areas radio buttons. /// </summary> /// <param name="conferenceId">The conference id.</param> private void BuildTopicAreas(int conferenceId) { ConferencesDataset._tabs_ConferenceTopicAreasDataTable dt = ConferenceBAL.GetTopicAreas(conferenceId); if (dt.Rows.Count > 0) { DataTable dtCopy = dt.Copy(); rptTopicAreaLeft.DataSource = GetHalfofData(dt, true); rptTopicAreaLeft.DataBind(); DataTable dtRight = GetHalfofData(dtCopy, false); // Always add the "other" option last DataRow dr = dtRight.NewRow(); dr["ConferenceTopicAreaId"] = "0"; dr["ConferenceId"] = conferenceId; dr["TopicArea"] = "Multidisciplinary/Other (please specify below)"; dtRight.Rows.Add(dr); rptTopicAreaRight.DataSource = dtRight; rptTopicAreaRight.DataBind(); } } private void BuildCountries() { // Countries tabs_admin_dataset._tabs_countryDataTable dt = TabsAdminBAL.getCountry(); ddlSpeaker1Country.DataSource = dt; ddlSpeaker1Country.DataBind(); ddlSpeaker1Country.Items.Insert(0, new ListItem("-- Please Select --", "0")); // Just bind while we already have the data ddlSpeaker2Country.DataSource = dt; ddlSpeaker2Country.DataBind(); ddlSpeaker2Country.Items.Insert(0, new ListItem("-- Please Select --", "0")); // Just bind while we already have the data ddlSpeaker3Country.DataSource = dt; ddlSpeaker3Country.DataBind(); ddlSpeaker3Country.Items.Insert(0, new ListItem("-- Please Select --", "0")); } /// <summary> /// Gets half of a secified data table. /// </summary> /// <param name="dt">The DataTable.</param> /// <param name="firstHalf">if set to <c>true</c> [first half].</param> /// <returns></returns> private DataTable GetHalfofData(DataTable dt, bool firstHalf) { if (dt.Rows.Count > 0) { int half = dt.Rows.Count / 2; int count = dt.Rows.Count; if (firstHalf) { // Remove the last half of the rows for (int i = 0; i < half; i++) { dt.Rows.RemoveAt(0 + half); } return dt; } else { // Remove the first half of the rows for (int i = 0; i < half; i++) { dt.Rows.RemoveAt(0); } return dt; } } return null; } private void SubmitData() { int conferenceId = int.Parse(litConferenceProposalId.Text); int proposalType = int.Parse(Request.Form["radioproposalType"]); int topicAreaId = int.Parse(Request.Form["radioTopicArea"]); string otherTopicArea = string.Empty; if (topicAreaId.Equals(0)) { otherTopicArea = Utility.GetCleanString(tbOtherTopicArea.Text); } else { otherTopicArea = null; } string presentedOtherConferences1 = Utility.GetCleanString(tbConference1.Text); string presentedOtherConferences2 = Utility.GetCleanString(tbConference2.Text); string audioVisualOther = Utility.GetCleanString(tbAudioVisualOther.Text); bool existingConferenceProposal = false; if (litConferenceProposalId.Text.Length > 0) { existingConferenceProposal = true; } int conferenceProposalId = 0; int result = 0; if (!existingConferenceProposal) { // Insert the proposal conferenceProposalId = ConferenceBAL.InsertConferenceProposal(conferenceId, proposalType, topicAreaId, otherTopicArea, tbTitle.Text, tbDescription.Text, presentedOtherConferences1, presentedOtherConferences2, cbFlipChart.Checked, audioVisualOther); // Insert the Submitter info result = ConferenceBAL.InsertConferenceProposalSubmitter(conferenceProposalId, tbSpeaker1EmailAddress.Text, tbPassword1.Text); } else { // Update the proposal conferenceProposalId = int.Parse(litConferenceProposalId.Text); conferenceProposalId = ConferenceBAL.UpdateConferenceProposal(conferenceProposalId, proposalType, topicAreaId, otherTopicArea, tbTitle.Text, tbDescription.Text, presentedOtherConferences1, presentedOtherConferences2, cbFlipChart.Checked, audioVisualOther); // Update the Submitter info int conferenceProposalSubmitterId = int.Parse(litConferenceProposalSubmitterId.Text); result = ConferenceBAL.UpdateConferenceProposalSubmitter(conferenceProposalSubmitterId, tbSpeaker1EmailAddress.Text, tbPassword1.Text); } // Insert the Speakers // 1st speaker always required string speakerMiddleInitial = Utility.GetCleanString(tbSpeaker1MiddleInitial.Text); string speakerAddress2 = Utility.GetCleanString(tbSpeaker1Address2.Text); string speakerZip = Utility.GetCleanString(tbSpeaker1Zip.Text); string speakerFax = Utility.GetCleanString(tbSpeaker1Fax.Text); string speakerOtherConferences = Utility.GetCleanString(tbSpeaker1OtherConferences.Text); int conferenceProposalSpeakerId = 0; if (!existingConferenceProposal) { conferenceProposalSpeakerId = ConferenceBAL.InsertConferenceProposalSpeaker(1, tbSpeaker1FirstName.Text, speakerMiddleInitial, tbSpeaker1LastName.Text, tbSpeaker1Title.Text, tbSpeaker1Organization.Text, tbSpeaker1EmailAddress.Text, tbSpeaker1Address1.Text, speakerAddress2, tbSpeaker1City.Text, int.Parse(ddlSpeaker1State.SelectedValue), int.Parse(ddlSpeaker1Country.SelectedValue), speakerZip, tbSpeaker1Phone.Text, speakerFax, speakerOtherConferences, true, Convert.ToBoolean(int.Parse(rblSpeaker1ResponsibleForFees.SelectedValue)), Convert.ToBoolean(int.Parse(rblSpeaker1MustBePaidRegistrant.SelectedValue))); } else { conferenceProposalSpeakerId = int.Parse(litConferenceProposalSpeaker1Id.Text); conferenceProposalSpeakerId = ConferenceBAL.UpdateConferenceProposalSpeaker(conferenceProposalSpeakerId, tbSpeaker1FirstName.Text, speakerMiddleInitial, tbSpeaker1LastName.Text, tbSpeaker1Title.Text, tbSpeaker1Organization.Text, tbSpeaker1EmailAddress.Text, tbSpeaker1Address1.Text, speakerAddress2, tbSpeaker1City.Text, int.Parse(ddlSpeaker1State.SelectedValue), int.Parse(ddlSpeaker1Country.SelectedValue), speakerZip, tbSpeaker1Phone.Text, speakerFax, speakerOtherConferences, true, Convert.ToBoolean(int.Parse(rblSpeaker1ResponsibleForFees.SelectedValue)), Convert.ToBoolean(int.Parse(rblSpeaker1MustBePaidRegistrant.SelectedValue))); } // Now insert into the ConferenceProposalsToConferenceProposalSpeakers table // Note: no need to update the link. if (!existingConferenceProposal) { result = ConferenceBAL.InsertConferenceProposalToConferenceProposalSpeakers(conferenceProposalId, conferenceProposalSpeakerId); } // Check the other speakers if (!String.IsNullOrEmpty(tbSpeaker2FirstName.Text) && !String.IsNullOrEmpty(tbSpeaker2LastName.Text)) { // Insert #2 speaker speakerMiddleInitial = Utility.GetCleanString(tbSpeaker2MiddleInitial.Text); speakerAddress2 = Utility.GetCleanString(tbSpeaker2Address2.Text); speakerZip = Utility.GetCleanString(tbSpeaker2Zip.Text); speakerFax = Utility.GetCleanString(tbSpeaker2Fax.Text); speakerOtherConferences = Utility.GetCleanString(tbSpeaker2OtherConferences.Text); int? stateId = null; if (ddlSpeaker2State.SelectedIndex > 0) { stateId = int.Parse(ddlSpeaker2State.SelectedValue); } int? countryId = null; if (ddlSpeaker2Country.SelectedIndex > 0) { countryId = int.Parse(ddlSpeaker2Country.SelectedValue); } // Now insert into the ConferenceProposalsToConferenceProposalSpeakers table // Note: no need to update the link. if (!existingConferenceProposal) { conferenceProposalSpeakerId = ConferenceBAL.InsertConferenceProposalSpeaker(2, tbSpeaker2FirstName.Text, speakerMiddleInitial, tbSpeaker2LastName.Text, tbSpeaker2Title.Text, tbSpeaker2Organization.Text, tbSpeaker2EmailAddress.Text, tbSpeaker2Address1.Text, speakerAddress2, tbSpeaker2City.Text, stateId, countryId, speakerZip, tbSpeaker2Phone.Text, speakerFax, speakerOtherConferences, Convert.ToBoolean(int.Parse(rblSpeaker2SpeakerIsAware.SelectedValue)), Convert.ToBoolean(int.Parse(rblSpeaker2ResponsibleForFees.SelectedValue)), Convert.ToBoolean(int.Parse(rblSpeaker2MustBePaidRegistrant.SelectedValue))); result = ConferenceBAL.InsertConferenceProposalToConferenceProposalSpeakers(conferenceProposalId, conferenceProposalSpeakerId); } else { conferenceProposalSpeakerId = int.Parse(litConferenceProposalSpeaker2Id.Text); conferenceProposalSpeakerId = ConferenceBAL.UpdateConferenceProposalSpeaker(conferenceProposalSpeakerId, tbSpeaker2FirstName.Text, speakerMiddleInitial, tbSpeaker2LastName.Text, tbSpeaker2Title.Text, tbSpeaker2Organization.Text, tbSpeaker2EmailAddress.Text, tbSpeaker2Address1.Text, speakerAddress2, tbSpeaker2City.Text, stateId, countryId, speakerZip, tbSpeaker2Phone.Text, speakerFax, speakerOtherConferences, Convert.ToBoolean(int.Parse(rblSpeaker2SpeakerIsAware.SelectedValue)), Convert.ToBoolean(int.Parse(rblSpeaker2ResponsibleForFees.SelectedValue)), Convert.ToBoolean(int.Parse(rblSpeaker2MustBePaidRegistrant.SelectedValue))); } } if (!String.IsNullOrEmpty(tbSpeaker3FirstName.Text) && !String.IsNullOrEmpty(tbSpeaker3LastName.Text)) { // Insert #3 speaker speakerMiddleInitial = Utility.GetCleanString(tbSpeaker3MiddleInitial.Text); speakerAddress2 = Utility.GetCleanString(tbSpeaker3Address2.Text); speakerZip = Utility.GetCleanString(tbSpeaker3Zip.Text); speakerFax = Utility.GetCleanString(tbSpeaker3Fax.Text); speakerOtherConferences = Utility.GetCleanString(tbSpeaker3OtherConferences.Text); int? stateId = null; if (ddlSpeaker3State.SelectedIndex > 0) { stateId = int.Parse(ddlSpeaker3State.SelectedValue); } int? countryId = null; if (ddlSpeaker3Country.SelectedIndex > 0) { countryId = int.Parse(ddlSpeaker3Country.SelectedValue); } // Now insert into the ConferenceProposalsToConferenceProposalSpeakers table // Note: no need to update the link. if (!existingConferenceProposal) { conferenceProposalSpeakerId = ConferenceBAL.InsertConferenceProposalSpeaker(3, tbSpeaker3FirstName.Text, speakerMiddleInitial, tbSpeaker3LastName.Text, tbSpeaker3Title.Text, tbSpeaker3Organization.Text, tbSpeaker3EmailAddress.Text, tbSpeaker3Address1.Text, speakerAddress2, tbSpeaker3City.Text, stateId, countryId, speakerZip, tbSpeaker3Phone.Text, speakerFax, speakerOtherConferences, Convert.ToBoolean(int.Parse(rblSpeaker3SpeakerIsAware.SelectedValue)), Convert.ToBoolean(int.Parse(rblSpeaker3ResponsibleForFees.SelectedValue)), Convert.ToBoolean(int.Parse(rblSpeaker3MustBePaidRegistrant.SelectedValue))); result = ConferenceBAL.InsertConferenceProposalToConferenceProposalSpeakers(conferenceProposalId, conferenceProposalSpeakerId); } else { conferenceProposalSpeakerId = int.Parse(litConferenceProposalSpeaker3Id.Text); conferenceProposalSpeakerId = ConferenceBAL.InsertConferenceProposalSpeaker(conferenceProposalSpeakerId, tbSpeaker3FirstName.Text, speakerMiddleInitial, tbSpeaker3LastName.Text, tbSpeaker3Title.Text, tbSpeaker3Organization.Text, tbSpeaker3EmailAddress.Text, tbSpeaker3Address1.Text, speakerAddress2, tbSpeaker3City.Text, stateId, countryId, speakerZip, tbSpeaker3Phone.Text, speakerFax, speakerOtherConferences, Convert.ToBoolean(int.Parse(rblSpeaker3SpeakerIsAware.SelectedValue)), Convert.ToBoolean(int.Parse(rblSpeaker3ResponsibleForFees.SelectedValue)), Convert.ToBoolean(int.Parse(rblSpeaker3MustBePaidRegistrant.SelectedValue))); } } } private void BindData(int conferenceProposalId) { // Hold on to the existing conferenceId litConferenceProposalId.Text = conferenceProposalId.ToString(); // Set the conference proposal items ConferencesDataset._tabs_ConferenceProposalsDataTable dtProposal = ConferenceBAL.GetConferenceProposal(conferenceProposalId); ConferencesDataset._tabs_ConferenceProposalsRow drProposal = dtProposal[0]; // Set the proposal Type //TODO: CRAIG; Get script from Morrow for this //int proposalType = int.Parse(Request.Form["radioproposalType"]); // Set the topic area //TODO: Craig; Get script from Morrow for this //int topicAreaId = int.Parse(Request.Form["radioTopicArea"]); tbTitle.Text = drProposal.Title; tbDescription.Text = drProposal.Description; tbOtherTopicArea.Text = drProposal.TopicAreaOther; tbConference1.Text = drProposal.PresentedOtherConferences1; tbConference2.Text = drProposal.PresentedOtherConferences2; tbAudioVisualOther.Text = drProposal.AudioVisualOther; // Set the Submitter info ConferencesDataset._tabs_ConferenceProposalSubmittersDataTable dtSubmitter = ConferenceBAL.GetConferenceProposalSubmitterByConferenceProposalId(conferenceProposalId); ConferencesDataset._tabs_ConferenceProposalSubmittersRow drSubmitter = dtSubmitter[0]; litConferenceProposalSubmitterId.Text = drSubmitter.ConferenceProposalSubmitterId.ToString(); tbSpeaker1EmailAddress.Text = drSubmitter.EmailAddress; tbPassword1.Text = drSubmitter.Password; tbPassword2.Text = drSubmitter.Password; // Set the speakers ConferencesDataset._tabs_ConferenceProposalsToConferenceProposalSpeakersDataTable dtProposalsToSpeakers = ConferenceBAL.GetConferenceProposalsToConferenceProposalSpeakers(conferenceProposalId); ConferencesDataset._tabs_ConferenceProposalSpeakersDataTable dtProposalSpeaker = null; ConferencesDataset._tabs_ConferenceProposalSpeakersRow drProposalSpeaker = null; for(int i = 0; i < dtProposalsToSpeakers.Rows.Count; i++) { dtProposalSpeaker = ConferenceBAL.GetConferenceProposalSpeaker(int.Parse(dtProposalsToSpeakers[i]["conferenceProposalSpeakerId"].ToString())); drProposalSpeaker = dtProposalSpeaker[0]; SchoolManagerClass smlogic = new SchoolManagerClass(); SchoolManageDataset._tabs_statesDataTable dtStates = new SchoolManageDataset._tabs_statesDataTable(); switch (drProposalSpeaker.SpeakerNumber) { case 1: litConferenceProposalSpeaker1Id.Text = drProposalSpeaker.ConferenceProposalSpeakerId.ToString(); tbSpeaker1FirstName.Text = drProposalSpeaker.FirstName; tbSpeaker1MiddleInitial.Text = drProposalSpeaker.MiddileInitial; tbSpeaker1LastName.Text = drProposalSpeaker.LastName; tbSpeaker1Title.Text = drProposalSpeaker.Title; tbSpeaker1Organization.Text = drProposalSpeaker.Organization; tbSpeaker1EmailAddress.Text = drProposalSpeaker.EmailAddress; tbSpeaker1Address1.Text = drProposalSpeaker.Address1; tbSpeaker1Address2.Text = drProposalSpeaker.Address2; tbSpeaker1City.Text = drProposalSpeaker.City; ddlSpeaker1Country.ClearSelection(); ddlSpeaker1Country.SelectedIndex = (ddlSpeaker1Country.Items.IndexOf((ListItem)ddlSpeaker1Country.Items.FindByValue(drProposalSpeaker.CountryId.ToString()))); // Bind the states // Populate the state/province based on the country selection dtStates = smlogic.getStatesByCountryId(int.Parse(ddlSpeaker1Country.SelectedValue)); ddlSpeaker1State.DataSource = dtStates; ddlSpeaker1State.DataBind(); ddlSpeaker1State.Items.Insert(0, new ListItem("-- Please Select --", "0")); ddlSpeaker1State.Enabled = true; ddlSpeaker1State.ClearSelection(); ddlSpeaker1State.SelectedIndex = (ddlSpeaker1State.Items.IndexOf((ListItem)ddlSpeaker1State.Items.FindByValue(drProposalSpeaker.StateId.ToString()))); tbSpeaker1Zip.Text = drProposalSpeaker.Zipcode; tbSpeaker1Phone.Text = drProposalSpeaker.Phone; tbSpeaker1Fax.Text = drProposalSpeaker.Fax; tbSpeaker1OtherConferences.Text = drProposalSpeaker.SpeakerOtherConferences; rblSpeaker1ResponsibleForFees.SelectedIndex = rblSpeaker1ResponsibleForFees.Items.IndexOf((ListItem)rblSpeaker1ResponsibleForFees.Items.FindByValue((Convert.ToInt32(drProposalSpeaker.ObtainedFinancialSupport)).ToString())); rblSpeaker1MustBePaidRegistrant.SelectedIndex = rblSpeaker1MustBePaidRegistrant.Items.IndexOf((ListItem)rblSpeaker1MustBePaidRegistrant.Items.FindByValue((Convert.ToInt32(drProposalSpeaker.AwareMustBePaidRegistrant)).ToString())); break; case 2: litConferenceProposalSpeaker2Id.Text = drProposalSpeaker.ConferenceProposalSpeakerId.ToString(); tbSpeaker2FirstName.Text = drProposalSpeaker.FirstName; tbSpeaker2MiddleInitial.Text = drProposalSpeaker.MiddileInitial; tbSpeaker2LastName.Text = drProposalSpeaker.LastName; tbSpeaker2Title.Text = drProposalSpeaker.Title; tbSpeaker2Organization.Text = drProposalSpeaker.Organization; tbSpeaker2EmailAddress.Text = drProposalSpeaker.EmailAddress; tbSpeaker2Address1.Text = drProposalSpeaker.Address1; tbSpeaker2Address2.Text = drProposalSpeaker.Address2; tbSpeaker2City.Text = drProposalSpeaker.City; try { ddlSpeaker2Country.ClearSelection(); ddlSpeaker2Country.SelectedIndex = (ddlSpeaker2Country.Items.IndexOf((ListItem)ddlSpeaker2Country.Items.FindByValue(drProposalSpeaker.CountryId.ToString()))); } catch (System.Data.StrongTypingException) { ddlSpeaker2Country.ClearSelection(); } if(ddlSpeaker2Country.SelectedIndex > 0) { try { // Bind the states // Populate the state/province based on the country selection dtStates = smlogic.getStatesByCountryId(int.Parse(ddlSpeaker2Country.SelectedValue)); ddlSpeaker2State.DataSource = dtStates; ddlSpeaker2State.DataBind(); ddlSpeaker2State.Items.Insert(0, new ListItem("-- Please Select --", "0")); ddlSpeaker2State.Enabled = true; ddlSpeaker2State.ClearSelection(); ddlSpeaker2State.SelectedIndex = (ddlSpeaker2State.Items.IndexOf((ListItem)ddlSpeaker2State.Items.FindByValue(drProposalSpeaker.StateId.ToString()))); } catch (System.Data.StrongTypingException) { ddlSpeaker2State.ClearSelection(); } } tbSpeaker2Zip.Text = drProposalSpeaker.Zipcode; tbSpeaker2Phone.Text = drProposalSpeaker.Phone; tbSpeaker2Fax.Text = drProposalSpeaker.Fax; tbSpeaker2OtherConferences.Text = drProposalSpeaker.SpeakerOtherConferences; rblSpeaker2ResponsibleForFees.SelectedIndex = rblSpeaker2ResponsibleForFees.Items.IndexOf((ListItem)rblSpeaker2ResponsibleForFees.Items.FindByValue((Convert.ToInt32(drProposalSpeaker.ObtainedFinancialSupport)).ToString())); rblSpeaker2MustBePaidRegistrant.SelectedIndex = rblSpeaker2MustBePaidRegistrant.Items.IndexOf((ListItem)rblSpeaker2MustBePaidRegistrant.Items.FindByValue((Convert.ToInt32(drProposalSpeaker.AwareMustBePaidRegistrant)).ToString())); break; case 3: litConferenceProposalSpeaker3Id.Text = drProposalSpeaker.ConferenceProposalSpeakerId.ToString(); tbSpeaker3FirstName.Text = drProposalSpeaker.FirstName; tbSpeaker3MiddleInitial.Text = drProposalSpeaker.MiddileInitial; tbSpeaker3LastName.Text = drProposalSpeaker.LastName; tbSpeaker3Title.Text = drProposalSpeaker.Title; tbSpeaker3Organization.Text = drProposalSpeaker.Organization; tbSpeaker3EmailAddress.Text = drProposalSpeaker.EmailAddress; tbSpeaker3Address1.Text = drProposalSpeaker.Address1; tbSpeaker3Address2.Text = drProposalSpeaker.Address2; tbSpeaker3City.Text = drProposalSpeaker.City; try { ddlSpeaker3Country.ClearSelection(); ddlSpeaker3Country.SelectedIndex = (ddlSpeaker3Country.Items.IndexOf((ListItem)ddlSpeaker3Country.Items.FindByValue(drProposalSpeaker.CountryId.ToString()))); } catch (System.Data.StrongTypingException) { ddlSpeaker3Country.ClearSelection(); } if(ddlSpeaker3Country.SelectedIndex > 0) { try { // Bind the states // Populate the state/province based on the country selection dtStates = smlogic.getStatesByCountryId(int.Parse(ddlSpeaker3Country.SelectedValue)); ddlSpeaker3State.DataSource = dtStates; ddlSpeaker3State.DataBind(); ddlSpeaker3State.Items.Insert(0, new ListItem("-- Please Select --", "0")); ddlSpeaker3State.Enabled = true; ddlSpeaker3State.ClearSelection(); ddlSpeaker3State.SelectedIndex = (ddlSpeaker3State.Items.IndexOf((ListItem)ddlSpeaker3State.Items.FindByValue(drProposalSpeaker.StateId.ToString()))); } catch (System.Data.StrongTypingException) { ddlSpeaker3State.ClearSelection(); } } tbSpeaker3Zip.Text = drProposalSpeaker.Zipcode; tbSpeaker3Phone.Text = drProposalSpeaker.Phone; tbSpeaker3Fax.Text = drProposalSpeaker.Fax; tbSpeaker3OtherConferences.Text = drProposalSpeaker.SpeakerOtherConferences; rblSpeaker3ResponsibleForFees.SelectedIndex = rblSpeaker3ResponsibleForFees.Items.IndexOf((ListItem)rblSpeaker3ResponsibleForFees.Items.FindByValue((Convert.ToInt32(drProposalSpeaker.ObtainedFinancialSupport)).ToString())); rblSpeaker3MustBePaidRegistrant.SelectedIndex = rblSpeaker3MustBePaidRegistrant.Items.IndexOf((ListItem)rblSpeaker3MustBePaidRegistrant.Items.FindByValue((Convert.ToInt32(drProposalSpeaker.AwareMustBePaidRegistrant)).ToString())); break; } } } private void SendEmail() { InfrastructureClass infrastructure = new InfrastructureClass(); List<string> to = new List<string>(); List<string> cc = new List<string>(); List<string> bc = new List<string>(); to.Add(tbSpeaker1EmailAddress.Text); string from = System.Configuration.ConfigurationManager.AppSettings["fromEmailAddress"].ToString(); StringBuilder sb = new StringBuilder(); sb.Append("Dear ").Append(tbSpeaker1FirstName.Text).Append(" ").Append(tbSpeaker1LastName.Text).Append(",").Append("<br/><br/>"); sb.Append("Hi! We received your conference proposal! Thank you for your submission. We are currently reviewing proposals and are looking forward to another great conference this year. Remember, you can log in to the conference website at any time to edit your proposal before the proposal closing date.<br/><br/>"); sb.Append("For now, best wishes for a wonderful week! <br/><br/>"); sb.Append("Thank you, <br/><br/>"); sb.Append("The TABS Staff"); infrastructure.SendEmail(from, to, cc, bc, "TABS Conference Proposal Received", sb.ToString(), true); } #endregion } }
using System; using System.Linq; using System.Text.Json; using NUnit.Framework; using Hps.Construction; using Hps.Serialisation; namespace Hps.Tests.UnitTests.Serialisation { [TestFixture] public class JsonFactoryTests { [Test] public void ReadValue_test() { using var json = JsonDocument.Parse(@"{ ""double"": 1.5, ""integer"": 1, ""boolean"": true, ""string"": ""test"", ""array"": [1.5, 1, true, ""test"", [ 1, 2, 3 ], { ""test"": ""pass"" } ], ""object"": { ""number"": 2, ""double"": 2.5 } }"); var value = Json.ReadValue( "", json.RootElement, LoadingContext.Default()); Assert.That(value is { Type: ValueDataType.Collection, Integer: 0, Double: 0, Boolean: false, String: "", Name: "" }, Is.True); Assert.That(value["double"] is { Type: ValueDataType.Double, Integer: 0, Double: 1.5, Boolean: false, String: "", Name: "double" }, Is.True); Assert.That(value["integer"] is { Type: ValueDataType.Integer, Integer: 1, Double: 1.0, Boolean: false, String: "", Name: "integer" }, Is.True); Assert.That(value["boolean"] is { Type: ValueDataType.Boolean, Integer: 0, Double: 0, Boolean: true, String: "", Name: "boolean" }, Is.True); Assert.That(value["string"] is { Type: ValueDataType.String, Integer: 0, Double: 0, Boolean: false, String: "test", Name: "string" }, Is.True); Assert.That(value["array"][0] is { Type: ValueDataType.Double, Integer: 0, Double: 1.5, Boolean: false, String: "", Name: "" }, Is.True); Assert.That(value["object"][0] is { Type: ValueDataType.Integer, Integer: 2, Double: 2.0, Boolean: false, String: "", Name: "number" }, Is.True); Assert.That(value["object"][1] is { Type: ValueDataType.Double, Integer: 0, Double: 2.5, Boolean: false, String: "", Name: "double" }, Is.True); } [Test] public void ReadValue_fails_if_text_contains_null() { using var json = JsonDocument.Parse(@"{ ""object"": null }"); Assert.Throws<Exception>(() => Json.ReadValue( "", json.RootElement, LoadingContext.Default())); } [Test] public void ReadInstanceProperties_test() { using var json = JsonDocument.Parse(@"{ ""property1"": ""ok"", ""property2"": 1, ""property3"": { ""number1"": 2, ""number2"": 2.5 } }"); var value = Json.ReadInstanceProperties( json.RootElement, LoadingContext.Default()); Assert.That(value.ElementAt(0) is { Name: "property1", Value: { String: "ok" } }); Assert.That(value.ElementAt(1) is { Name: "property2", Value: { Integer: 1 } }); var property3 = value.ElementAt(2); Assert.That(property3.Value.Items.ElementAt(0) is { Name: "number1", Integer: 2 }); Assert.That(property3.Value.Items.ElementAt(1) is { Name: "number2", Double: 2.5 }); } [Test] public void ReadInstance_fails_when_name_is_not_present() { using var json = JsonDocument.Parse(@"{ ""machine"": ""example"" }"); Assert.Throws<Exception>(() => Json.ReadInstance( json.RootElement, LoadingContext.Default())); } [Test] public void ReadInstance_fails_when_machine_is_not_present() { using var json = JsonDocument.Parse(@"{ ""name"": ""example"" }"); Assert.Throws<Exception>(() => Json.ReadInstance( json.RootElement, LoadingContext.Default())); } [Test] public void ReadInstance_test() { using var json = JsonDocument.Parse(@"{ ""name"": ""example"", ""machine"": ""example"" }"); var instance = Json.ReadInstance( json.RootElement, LoadingContext.Default()); Assert.That(instance is { Name: "example" }); } [Test] public void ReadInstance_test_with_properties() { using var json = JsonDocument.Parse(@"{ ""name"": ""example"", ""machine"": ""example"", ""properties"": { ""name"" : ""alex"" } }"); var instance = Json.ReadInstance( json.RootElement, LoadingContext.Default()); Assert.That(instance is { Name: "example" }); } [Test] public void ReadInstances_test() { using var json = JsonDocument.Parse(@"[ { ""name"": ""example"", ""machine"": ""example"" } ]"); var instances = Json.ReadInstances( json.RootElement, LoadingContext.Default()); Assert.That(instances.Count, Is.EqualTo(1)); } [Test] public void ReadNetwork_test() { using var json = JsonDocument.Parse(@"{ ""name"": ""example"", ""machines"": [ { ""name"": ""m1"", ""machine"" : ""test1"" }, { ""name"": ""m2"", ""machine"" : ""test2"" } ] }"); var network = Json.ReadNetwork( json.RootElement, LoadingContext.Default()); Assert.That(network.Machines.Count, Is.EqualTo(2)); } [Test] public void ReadNetworks_test() { using var json = JsonDocument.Parse(@"[ { ""name"": ""example1"", ""machines"": [ { ""name"": ""m1"", ""machine"" : ""test1"" } ] }, { ""name"": ""example1"", ""machines"": [ { ""name"": ""m2"", ""machine"" : ""test2"" } ] } ]"); var networks = Json.ReadNetworks( json.RootElement, LoadingContext.Default()); Assert.That(networks.Count, Is.EqualTo(2)); } [Test] public void ReadProperty_test() { using var json = JsonDocument.Parse(@"{ ""name"" : { ""type"" : ""String"", ""comment"" : ""test"" } }"); var property = Json.ReadProperty( json.RootElement.EnumerateObject().First(), LoadingContext.Default()); Assert.That(property.Name, Is.EqualTo("name")); Assert.That(property.Type, Is.EqualTo("String")); Assert.That(property.Comment, Is.EqualTo("test")); } [Test] public void ReadProperties_test() { using var json = JsonDocument.Parse(@"{ ""name"" : { ""type"" : ""String"", ""comment"" : ""test"" } }"); var properties = Json.ReadProperties( json.RootElement, LoadingContext.Default()); var name = properties.First(); Assert.That(name.Name, Is.EqualTo("name")); Assert.That(name.Type, Is.EqualTo("String")); Assert.That(name.Comment, Is.EqualTo("test")); } } }
namespace XenAdmin.Controls.Ballooning { partial class VMMemoryControlsBasic { /// <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() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(VMMemoryControlsBasic)); this.spinnerPanel = new System.Windows.Forms.TableLayoutPanel(); this.memorySpinnerDynMin = new XenAdmin.Controls.Ballooning.MemorySpinner(); this.memorySpinnerDynMax = new XenAdmin.Controls.Ballooning.MemorySpinner(); this.vmShinyBar = new XenAdmin.Controls.Ballooning.VMShinyBar(); this.pictureBoxDynMin = new System.Windows.Forms.PictureBox(); this.pictureBoxDynMax = new System.Windows.Forms.PictureBox(); this.labelDynMin = new System.Windows.Forms.Label(); this.labelDynMax = new System.Windows.Forms.Label(); this.radioFixed = new System.Windows.Forms.RadioButton(); this.radioDynamic = new System.Windows.Forms.RadioButton(); this.groupBoxOn = new System.Windows.Forms.GroupBox(); this.iconDMCUnavailable = new System.Windows.Forms.PictureBox(); this.labelDMCUnavailable = new System.Windows.Forms.Label(); this.linkInstallTools = new System.Windows.Forms.LinkLabel(); this.memorySpinnerFixed = new XenAdmin.Controls.Ballooning.MemorySpinner(); this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel(); this.tableLayoutPanel2 = new System.Windows.Forms.TableLayoutPanel(); this.spinnerPanel.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.pictureBoxDynMin)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.pictureBoxDynMax)).BeginInit(); this.groupBoxOn.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.iconDMCUnavailable)).BeginInit(); this.tableLayoutPanel1.SuspendLayout(); this.tableLayoutPanel2.SuspendLayout(); this.SuspendLayout(); // // spinnerPanel // resources.ApplyResources(this.spinnerPanel, "spinnerPanel"); this.spinnerPanel.Controls.Add(this.memorySpinnerDynMin, 2, 1); this.spinnerPanel.Controls.Add(this.memorySpinnerDynMax, 2, 2); this.spinnerPanel.Controls.Add(this.vmShinyBar, 0, 0); this.spinnerPanel.Controls.Add(this.pictureBoxDynMin, 0, 1); this.spinnerPanel.Controls.Add(this.pictureBoxDynMax, 0, 2); this.spinnerPanel.Controls.Add(this.labelDynMin, 1, 1); this.spinnerPanel.Controls.Add(this.labelDynMax, 1, 2); this.spinnerPanel.Name = "spinnerPanel"; // // memorySpinnerDynMin // resources.ApplyResources(this.memorySpinnerDynMin, "memorySpinnerDynMin"); this.memorySpinnerDynMin.Increment = 0.1D; this.memorySpinnerDynMin.Name = "memorySpinnerDynMin"; this.memorySpinnerDynMin.SpinnerValueChanged += new System.EventHandler(this.DynamicSpinners_ValueChanged); // // memorySpinnerDynMax // resources.ApplyResources(this.memorySpinnerDynMax, "memorySpinnerDynMax"); this.memorySpinnerDynMax.Increment = 0.1D; this.memorySpinnerDynMax.Name = "memorySpinnerDynMax"; this.memorySpinnerDynMax.SpinnerValueChanged += new System.EventHandler(this.DynamicSpinners_ValueChanged); // // vmShinyBar // this.spinnerPanel.SetColumnSpan(this.vmShinyBar, 3); this.vmShinyBar.Increment = 0D; resources.ApplyResources(this.vmShinyBar, "vmShinyBar"); this.vmShinyBar.Name = "vmShinyBar"; this.vmShinyBar.TabStop = false; this.vmShinyBar.SliderDragged += new System.EventHandler(this.vmShinyBar_SliderDragged); // // pictureBoxDynMin // resources.ApplyResources(this.pictureBoxDynMin, "pictureBoxDynMin"); this.pictureBoxDynMin.Image = global::XenAdmin.Properties.Resources.memory_dynmin_slider_small; this.pictureBoxDynMin.Name = "pictureBoxDynMin"; this.pictureBoxDynMin.TabStop = false; // // pictureBoxDynMax // resources.ApplyResources(this.pictureBoxDynMax, "pictureBoxDynMax"); this.pictureBoxDynMax.Image = global::XenAdmin.Properties.Resources.memory_dynmax_slider_small; this.pictureBoxDynMax.Name = "pictureBoxDynMax"; this.pictureBoxDynMax.TabStop = false; // // labelDynMin // resources.ApplyResources(this.labelDynMin, "labelDynMin"); this.labelDynMin.Name = "labelDynMin"; // // labelDynMax // resources.ApplyResources(this.labelDynMax, "labelDynMax"); this.labelDynMax.Name = "labelDynMax"; // // radioFixed // resources.ApplyResources(this.radioFixed, "radioFixed"); this.radioFixed.Name = "radioFixed"; this.radioFixed.TabStop = true; this.radioFixed.UseVisualStyleBackColor = true; // // radioDynamic // resources.ApplyResources(this.radioDynamic, "radioDynamic"); this.tableLayoutPanel1.SetColumnSpan(this.radioDynamic, 2); this.radioDynamic.Name = "radioDynamic"; this.radioDynamic.TabStop = true; this.radioDynamic.UseVisualStyleBackColor = true; // // groupBoxOn // resources.ApplyResources(this.groupBoxOn, "groupBoxOn"); this.tableLayoutPanel1.SetColumnSpan(this.groupBoxOn, 2); this.groupBoxOn.Controls.Add(this.spinnerPanel); this.groupBoxOn.Name = "groupBoxOn"; this.groupBoxOn.TabStop = false; // // iconDMCUnavailable // resources.ApplyResources(this.iconDMCUnavailable, "iconDMCUnavailable"); this.iconDMCUnavailable.Image = global::XenAdmin.Properties.Resources._000_Info3_h32bit_16; this.iconDMCUnavailable.Name = "iconDMCUnavailable"; this.iconDMCUnavailable.TabStop = false; // // labelDMCUnavailable // resources.ApplyResources(this.labelDMCUnavailable, "labelDMCUnavailable"); this.labelDMCUnavailable.Name = "labelDMCUnavailable"; // // linkInstallTools // resources.ApplyResources(this.linkInstallTools, "linkInstallTools"); this.linkInstallTools.Name = "linkInstallTools"; this.linkInstallTools.TabStop = true; this.linkInstallTools.VisitedLinkColor = System.Drawing.Color.Blue; this.linkInstallTools.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.InstallTools_LinkClicked); // // memorySpinnerFixed // resources.ApplyResources(this.memorySpinnerFixed, "memorySpinnerFixed"); this.memorySpinnerFixed.Increment = 0.1D; this.memorySpinnerFixed.Name = "memorySpinnerFixed"; this.memorySpinnerFixed.SpinnerValueChanged += new System.EventHandler(this.FixedSpinner_ValueChanged); // // tableLayoutPanel1 // resources.ApplyResources(this.tableLayoutPanel1, "tableLayoutPanel1"); this.tableLayoutPanel1.Controls.Add(this.memorySpinnerFixed, 1, 0); this.tableLayoutPanel1.Controls.Add(this.groupBoxOn, 0, 2); this.tableLayoutPanel1.Controls.Add(this.radioFixed, 0, 0); this.tableLayoutPanel1.Controls.Add(this.radioDynamic, 0, 1); this.tableLayoutPanel1.Controls.Add(this.tableLayoutPanel2, 0, 3); this.tableLayoutPanel1.Name = "tableLayoutPanel1"; // // tableLayoutPanel2 // resources.ApplyResources(this.tableLayoutPanel2, "tableLayoutPanel2"); this.tableLayoutPanel1.SetColumnSpan(this.tableLayoutPanel2, 2); this.tableLayoutPanel2.Controls.Add(this.labelDMCUnavailable, 1, 0); this.tableLayoutPanel2.Controls.Add(this.iconDMCUnavailable, 0, 0); this.tableLayoutPanel2.Controls.Add(this.linkInstallTools, 1, 1); this.tableLayoutPanel2.Name = "tableLayoutPanel2"; // // VMMemoryControlsBasic // resources.ApplyResources(this, "$this"); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi; this.Controls.Add(this.tableLayoutPanel1); this.DoubleBuffered = true; this.Name = "VMMemoryControlsBasic"; this.spinnerPanel.ResumeLayout(false); this.spinnerPanel.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.pictureBoxDynMin)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.pictureBoxDynMax)).EndInit(); this.groupBoxOn.ResumeLayout(false); this.groupBoxOn.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.iconDMCUnavailable)).EndInit(); this.tableLayoutPanel1.ResumeLayout(false); this.tableLayoutPanel1.PerformLayout(); this.tableLayoutPanel2.ResumeLayout(false); this.tableLayoutPanel2.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private VMShinyBar vmShinyBar; private System.Windows.Forms.TableLayoutPanel spinnerPanel; private MemorySpinner memorySpinnerDynMin; private System.Windows.Forms.RadioButton radioFixed; private System.Windows.Forms.RadioButton radioDynamic; private System.Windows.Forms.GroupBox groupBoxOn; private System.Windows.Forms.PictureBox iconDMCUnavailable; private System.Windows.Forms.Label labelDMCUnavailable; private System.Windows.Forms.LinkLabel linkInstallTools; private MemorySpinner memorySpinnerFixed; private MemorySpinner memorySpinnerDynMax; private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1; private System.Windows.Forms.PictureBox pictureBoxDynMin; private System.Windows.Forms.PictureBox pictureBoxDynMax; private System.Windows.Forms.Label labelDynMin; private System.Windows.Forms.Label labelDynMax; private System.Windows.Forms.TableLayoutPanel tableLayoutPanel2; } }
// // JsonDeserializer.cs // // Author: // Marek Habersack <mhabersack@novell.com> // // (C) 2008 Novell, Inc. http://novell.com/ // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // // Code is based on JSON_checker (http://www.json.org/JSON_checker/) and JSON_parser // (http://fara.cs.uni-potsdam.de/~jsg/json_parser/) C sources. License for the original code // follows: #region Original License /* Copyright (c) 2005 JSON.org 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 shall be used for Good, not Evil. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #endregion namespace Nancy.Json { using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; internal sealed class JsonDeserializer { /* Universal error constant */ const int __ = -1; const int UNIVERSAL_ERROR = __; /* Characters are mapped into these 31 character classes. This allows for a significant reduction in the size of the state transition table. */ const int C_SPACE = 0x00; /* space */ const int C_WHITE = 0x01; /* other whitespace */ const int C_LCURB = 0x02; /* { */ const int C_RCURB = 0x03; /* } */ const int C_LSQRB = 0x04; /* [ */ const int C_RSQRB = 0x05; /* ] */ const int C_COLON = 0x06; /* : */ const int C_COMMA = 0x07; /* , */ const int C_QUOTE = 0x08; /* " */ const int C_BACKS = 0x09; /* \ */ const int C_SLASH = 0x0A; /* / */ const int C_PLUS = 0x0B; /* + */ const int C_MINUS = 0x0C; /* - */ const int C_POINT = 0x0D; /* . */ const int C_ZERO = 0x0E; /* 0 */ const int C_DIGIT = 0x0F; /* 123456789 */ const int C_LOW_A = 0x10; /* a */ const int C_LOW_B = 0x11; /* b */ const int C_LOW_C = 0x12; /* c */ const int C_LOW_D = 0x13; /* d */ const int C_LOW_E = 0x14; /* e */ const int C_LOW_F = 0x15; /* f */ const int C_LOW_L = 0x16; /* l */ const int C_LOW_N = 0x17; /* n */ const int C_LOW_R = 0x18; /* r */ const int C_LOW_S = 0x19; /* s */ const int C_LOW_T = 0x1A; /* t */ const int C_LOW_U = 0x1B; /* u */ const int C_ABCDF = 0x1C; /* ABCDF */ const int C_E = 0x1D; /* E */ const int C_ETC = 0x1E; /* everything else */ const int C_STAR = 0x1F; /* * */ const int C_I = 0x20; /* I */ const int C_LOW_I = 0x21; /* i */ const int C_LOW_Y = 0x22; /* y */ const int C_N = 0x23; /* N */ /* The state codes. */ const int GO = 0x00; /* start */ const int OK = 0x01; /* ok */ const int OB = 0x02; /* object */ const int KE = 0x03; /* key */ const int CO = 0x04; /* colon */ const int VA = 0x05; /* value */ const int AR = 0x06; /* array */ const int ST = 0x07; /* string */ const int ES = 0x08; /* escape */ const int U1 = 0x09; /* u1 */ const int U2 = 0x0A; /* u2 */ const int U3 = 0x0B; /* u3 */ const int U4 = 0x0C; /* u4 */ const int MI = 0x0D; /* minus */ const int ZE = 0x0E; /* zero */ const int IN = 0x0F; /* integer */ const int FR = 0x10; /* fraction */ const int E1 = 0x11; /* e */ const int E2 = 0x12; /* ex */ const int E3 = 0x13; /* exp */ const int T1 = 0x14; /* tr */ const int T2 = 0x15; /* tru */ const int T3 = 0x16; /* true */ const int F1 = 0x17; /* fa */ const int F2 = 0x18; /* fal */ const int F3 = 0x19; /* fals */ const int F4 = 0x1A; /* false */ const int N1 = 0x1B; /* nu */ const int N2 = 0x1C; /* nul */ const int N3 = 0x1D; /* null */ const int FX = 0x1E; /* *.* *eE* */ const int IV = 0x1F; /* invalid input */ const int UK = 0x20; /* unquoted key name */ const int UI = 0x21; /* ignore during unquoted key name construction */ const int I1 = 0x22; /* In */ const int I2 = 0x23; /* Inf */ const int I3 = 0x24; /* Infi */ const int I4 = 0x25; /* Infin */ const int I5 = 0x26; /* Infini */ const int I6 = 0x27; /* Infinit */ const int I7 = 0x28; /* Infinity */ const int V1 = 0x29; /* Na */ const int V2 = 0x2A; /* NaN */ /* Actions */ const int FA = -10; /* false */ const int TR = -11; /* false */ const int NU = -12; /* null */ const int DE = -13; /* double detected by exponent e E */ const int DF = -14; /* double detected by fraction . */ const int SB = -15; /* string begin */ const int MX = -16; /* integer detected by minus */ const int ZX = -17; /* integer detected by zero */ const int IX = -18; /* integer detected by 1-9 */ const int EX = -19; /* next char is escaped */ const int UC = -20; /* Unicode character read */ const int SE = -4; /* string end */ const int AB = -5; /* array begin */ const int AE = -7; /* array end */ const int OS = -6; /* object start */ const int OE = -8; /* object end */ const int EO = -9; /* empty object */ const int CM = -3; /* comma */ const int CA = -2; /* colon action */ const int PX = -21; /* integer detected by plus */ const int KB = -22; /* unquoted key name begin */ const int UE = -23; /* unquoted key name end */ const int IF = -25; /* Infinity */ const int NN = -26; /* NaN */ enum JsonMode { NONE, ARRAY, DONE, KEY, OBJECT }; enum JsonType { NONE = 0, ARRAY_BEGIN, ARRAY_END, OBJECT_BEGIN, OBJECT_END, INTEGER, FLOAT, NULL, TRUE, FALSE, STRING, KEY, MAX }; /* This array maps the 128 ASCII characters into character classes. The remaining Unicode characters should be mapped to C_ETC. Non-whitespace control characters are errors. */ static readonly int[] ascii_class = { __, __, __, __, __, __, __, __, __, C_WHITE, C_WHITE, __, __, C_WHITE, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, C_SPACE, C_ETC, C_QUOTE, C_ETC, C_ETC, C_ETC, C_ETC, C_QUOTE, C_ETC, C_ETC, C_STAR, C_PLUS, C_COMMA, C_MINUS, C_POINT, C_SLASH, C_ZERO, C_DIGIT, C_DIGIT, C_DIGIT, C_DIGIT, C_DIGIT, C_DIGIT, C_DIGIT, C_DIGIT, C_DIGIT, C_COLON, C_ETC, C_ETC, C_ETC, C_ETC, C_ETC, C_ETC, C_ABCDF, C_ABCDF, C_ABCDF, C_ABCDF, C_E, C_ABCDF, C_ETC, C_ETC, C_I, C_ETC, C_ETC, C_ETC, C_ETC, C_N, C_ETC, C_ETC, C_ETC, C_ETC, C_ETC, C_ETC, C_ETC, C_ETC, C_ETC, C_ETC, C_ETC, C_ETC, C_LSQRB, C_BACKS, C_RSQRB, C_ETC, C_ETC, C_ETC, C_LOW_A, C_LOW_B, C_LOW_C, C_LOW_D, C_LOW_E, C_LOW_F, C_ETC, C_ETC, C_LOW_I, C_ETC, C_ETC, C_LOW_L, C_ETC, C_LOW_N, C_ETC, C_ETC, C_ETC, C_LOW_R, C_LOW_S, C_LOW_T, C_LOW_U, C_ETC, C_ETC, C_ETC, C_LOW_Y, C_ETC, C_LCURB, C_ETC, C_RCURB, C_ETC, C_ETC }; static readonly int[,] state_transition_table = { /* The state transition table takes the current state and the current symbol, and returns either a new state or an action. An action is represented as a negative number. A JSON text is accepted if at the end of the text the state is OK and if the mode is MODE_DONE. white ' 1-9 ABCDF etc space | { } [ ] : , " \ / + - . 0 | a b c d e f l n r s t u | E | * I i y N */ /*start GO*/ {GO,GO,OS,__,AB,__,__,__,SB,__,__,PX,MX,__,ZX,IX,__,__,__,__,__,FA,__,__,__,__,TR,__,__,__,__,__,I1,__,__,V1}, /*ok OK*/ {OK,OK,__,OE,__,AE,__,CM,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__}, /*object OB*/ {OB,OB,__,EO,__,__,__,__,SB,__,__,__,KB,__,KB,KB,KB,KB,KB,KB,KB,KB,KB,KB,KB,KB,KB,KB,KB,KB,KB,__,KB,KB,KB,KB}, /*key KE*/ {KE,KE,__,__,__,__,__,__,SB,__,__,__,KB,__,KB,KB,KB,KB,KB,KB,KB,KB,KB,KB,KB,KB,KB,KB,KB,KB,KB,__,KB,KB,KB,KB}, /*colon CO*/ {CO,CO,__,__,__,__,CA,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__}, /*value VA*/ {VA,VA,OS,__,AB,__,__,__,SB,__,__,PX,MX,__,ZX,IX,__,__,__,__,__,FA,__,NU,__,__,TR,__,__,__,__,__,I1,__,__,V1}, /*array AR*/ {AR,AR,OS,__,AB,AE,__,__,SB,__,__,PX,MX,__,ZX,IX,__,__,__,__,__,FA,__,NU,__,__,TR,__,__,__,__,__,I1,__,__,V1}, /*string ST*/ {ST,__,ST,ST,ST,ST,ST,ST,SE,EX,ST,ST,ST,ST,ST,ST,ST,ST,ST,ST,ST,ST,ST,ST,ST,ST,ST,ST,ST,ST,ST,ST,ST,ST,ST,ST}, /*escape ES*/ {__,__,__,__,__,__,__,__,ST,ST,ST,__,__,__,__,__,__,ST,__,__,__,ST,__,ST,ST,__,ST,U1,__,__,__,__,__,__,__,__}, /*u1 U1*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,U2,U2,U2,U2,U2,U2,U2,U2,__,__,__,__,__,__,U2,U2,__,__,__,__,__,__}, /*u2 U2*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,U3,U3,U3,U3,U3,U3,U3,U3,__,__,__,__,__,__,U3,U3,__,__,__,__,__,__}, /*u3 U3*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,U4,U4,U4,U4,U4,U4,U4,U4,__,__,__,__,__,__,U4,U4,__,__,__,__,__,__}, /*u4 U4*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,UC,UC,UC,UC,UC,UC,UC,UC,__,__,__,__,__,__,UC,UC,__,__,__,__,__,__}, /*minus MI*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,ZE,IN,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,I1,__,__,__}, /*zero ZE*/ {OK,OK,__,OE,__,AE,__,CM,__,__,__,__,__,DF,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__}, /*int IN*/ {OK,OK,__,OE,__,AE,__,CM,__,__,__,__,__,DF,IN,IN,__,__,__,__,DE,__,__,__,__,__,__,__,__,DE,__,__,__,__,__,__}, /*frac FR*/ {OK,OK,__,OE,__,AE,__,CM,__,__,__,__,__,__,FR,FR,__,__,__,__,E1,__,__,__,__,__,__,__,__,E1,__,__,__,__,__,__}, /*e E1*/ {__,__,__,__,__,__,__,__,__,__,__,E2,E2,__,E3,E3,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__}, /*ex E2*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,E3,E3,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__}, /*exp E3*/ {OK,OK,__,OE,__,AE,__,CM,__,__,__,__,__,__,E3,E3,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__}, /*tr T1*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,T2,__,__,__,__,__,__,__,__,__,__,__}, /*tru T2*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,T3,__,__,__,__,__,__,__,__}, /*true T3*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,OK,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__}, /*fa F1*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,F2,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__}, /*fal F2*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,F3,__,__,__,__,__,__,__,__,__,__,__,__,__}, /*fals F3*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,F4,__,__,__,__,__,__,__,__,__,__}, /*false F4*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,OK,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__}, /*nu N1*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,N2,__,__,__,__,__,__,__,__}, /*nul N2*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,N3,__,__,__,__,__,__,__,__,__,__,__,__,__}, /*null N3*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,OK,__,__,__,__,__,__,__,__,__,__,__,__,__}, /*_. FX*/ {OK,OK,__,OE,__,AE,__,CM,__,__,__,__,__,__,FR,FR,__,__,__,__,E1,__,__,__,__,__,__,__,__,E1,__,__,__,__,__,__}, /*inval. IV*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__}, /*unq.key UK*/ {UI,UI,__,__,__,__,UE,__,__,__,__,UK,UK,UK,UK,UK,UK,UK,UK,UK,UK,UK,UK,UK,UK,UK,UK,UK,UK,UK,UK,__,UK,UK,UK,UK}, /*unq.ign. UI*/ {UI,UI,__,__,__,__,UE,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__}, /*i1 I1*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,I2,__,__,__,__,__,__,__,__,__,__,__,__}, /*i2 I2*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,I3,__,__,__,__,__,__,__,__,__,__,__,__,__,__}, /*i3 I3*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,I4,__,__}, /*i4 I4*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,I5,__,__,__,__,__,__,__,__,__,__,__,__}, /*i5 I5*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,I6,__,__}, /*i6 I6*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,I7,__,__,__,__,__,__,__,__,__}, /*i7 I7*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,IF,__}, /*v1 V1*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,V2,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__}, /*v2 V2*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,NN}, }; JavaScriptSerializer serializer; JavaScriptTypeResolver typeResolver; int maxJsonLength; int currentPosition; int recursionLimit; int recursionDepth; Stack <JsonMode> modes; Stack <object> returnValue; JsonType jsonType; bool escaped; int state; Stack <string> currentKey; StringBuilder buffer; char quoteChar; public JsonDeserializer (JavaScriptSerializer serializer) { this.serializer = serializer; this.maxJsonLength = serializer.MaxJsonLength; this.recursionLimit = serializer.RecursionLimit; this.typeResolver = serializer.TypeResolver; this.modes = new Stack <JsonMode> (); this.currentKey = new Stack <string> (); this.returnValue = new Stack <object> (); this.state = GO; this.currentPosition = 0; this.recursionDepth = 0; } public object Deserialize (string input) { if (input == null) throw new ArgumentNullException ("input"); return Deserialize (new StringReader (input)); } public object Deserialize (TextReader input) { if (input == null) throw new ArgumentNullException ("input"); int value; buffer = new StringBuilder (); while (true) { value = input.Read (); if (value < 0) break; currentPosition++; if (currentPosition > maxJsonLength) throw new ArgumentException ("Maximum JSON input length has been exceeded."); if (!ProcessCharacter ((char) value)) throw new InvalidOperationException ("JSON syntax error."); } object topObject = PeekObject (); if (buffer.Length > 0) { object result; if (ParseBuffer (out result)) { if (topObject != null) StoreValue (result); else PushObject (result); } } if (returnValue.Count > 1) throw new InvalidOperationException ("JSON syntax error."); object ret = PopObject (); return ret; } #if DEBUG void DumpObject (string indent, object obj) { if (obj is Dictionary <string, object>) { Console.WriteLine (indent + "{"); foreach (KeyValuePair <string, object> kvp in (Dictionary <string, object>)obj) { Console.WriteLine (indent + "\t\"{0}\": ", kvp.Key); DumpObject (indent + "\t\t", kvp.Value); } Console.WriteLine (indent + "}"); } else if (obj is object[]) { Console.WriteLine (indent + "["); foreach (object o in (object[])obj) DumpObject (indent + "\t", o); Console.WriteLine (indent + "]"); } else if (obj != null) Console.WriteLine (indent + obj.ToString ()); else Console.WriteLine ("null"); } #endif void DecodeUnicodeChar () { int len = buffer.Length; if (len < 6) throw new ArgumentException ("Invalid escaped unicode character specification (" + currentPosition + ")"); int code = Int32.Parse (buffer.ToString ().Substring (len - 4), NumberStyles.HexNumber); buffer.Length = len - 6; buffer.Append ((char)code); } string GetModeMessage (JsonMode expectedMode) { switch (expectedMode) { case JsonMode.ARRAY: return "Invalid array passed in, ',' or ']' expected (" + currentPosition + ")"; case JsonMode.KEY: return "Invalid object passed in, key name or ':' expected (" + currentPosition + ")"; case JsonMode.OBJECT: return "Invalid object passed in, key value expected (" + currentPosition + ")"; default: return "Invalid JSON string"; } } void PopMode (JsonMode expectedMode) { JsonMode mode = PeekMode (); if (mode != expectedMode) throw new ArgumentException (GetModeMessage (mode)); modes.Pop (); } void PushMode (JsonMode newMode) { modes.Push (newMode); } JsonMode PeekMode () { if (modes.Count == 0) return JsonMode.NONE; return modes.Peek (); } void PushObject (object o) { returnValue.Push (o); } object PopObject (bool notIfLast) { int count = returnValue.Count; if (count == 0) return null; if (notIfLast && count == 1) return null; return returnValue.Pop (); } object PopObject () { return PopObject (false); } object PeekObject () { if (returnValue.Count == 0) return null; return returnValue.Peek (); } void RemoveLastCharFromBuffer () { int len = buffer.Length; if (len == 0) return; buffer.Length = len - 1; } bool ParseBuffer (out object result) { result = null; if (jsonType == JsonType.NONE) { buffer.Length = 0; return false; } string s = buffer.ToString (); bool converted = true; int intValue; long longValue; decimal decimalValue; double doubleValue; if (jsonType != JsonType.STRING) { s = s.TrimEnd(new[] { '\n', '\r' }); } switch (jsonType) { case JsonType.INTEGER: /* MS AJAX.NET JSON parser promotes big integers to double */ if (Int32.TryParse (s, out intValue)) result = intValue; else if (Int64.TryParse (s, out longValue)) result = longValue; else if (Decimal.TryParse (s, out decimalValue)) result = decimalValue; else if (Double.TryParse (s, out doubleValue)) result = doubleValue; else converted = false; break; case JsonType.FLOAT: if (Decimal.TryParse(s,NumberStyles.Any, Json.DefaultNumberFormatInfo, out decimalValue)) result = decimalValue; else if (Double.TryParse (s,NumberStyles.Any, Json.DefaultNumberFormatInfo, out doubleValue)) result = doubleValue; else converted = false; break; case JsonType.TRUE: if (String.Compare (s, "true", StringComparison.Ordinal) == 0) result = true; else converted = false; break; case JsonType.FALSE: if (String.Compare (s, "false", StringComparison.Ordinal) == 0) result = false; else converted = false; break; case JsonType.NULL: if (String.Compare (s, "null", StringComparison.Ordinal) != 0) converted = false; break; case JsonType.STRING: if (s.StartsWith("/Date(", StringComparison.Ordinal) && s.EndsWith(")/", StringComparison.Ordinal)) { int tzCharIndex = s.IndexOfAny(new char[] { '+', '-' }, 7); long javaScriptTicks = Convert.ToInt64(s.Substring(6, (tzCharIndex > 0) ? tzCharIndex - 6 : s.Length - 8)); DateTime time = new DateTime((javaScriptTicks * 10000) + JsonSerializer.InitialJavaScriptDateTicks, DateTimeKind.Utc); if (tzCharIndex > 0) { time = time.ToLocalTime(); } result = time; } else result = s; break; default: throw new InvalidOperationException (String.Format ("Internal error: unexpected JsonType ({0})", jsonType)); } if (!converted) throw new ArgumentException ("Invalid JSON primitive: " + s); buffer.Length = 0; return true; } bool ProcessCharacter (char ch) { int next_class, next_state; if (ch >= 128) next_class = C_ETC; else { next_class = ascii_class [ch]; if (next_class <= UNIVERSAL_ERROR) return false; } if (escaped) { escaped = false; RemoveLastCharFromBuffer (); switch (ch) { case 'b': buffer.Append ('\b'); break; case 'f': buffer.Append ('\f'); break; case 'n': buffer.Append ('\n'); break; case 'r': buffer.Append ('\r'); break; case 't': buffer.Append ('\t'); break; case '"': case '\\': case '/': buffer.Append (ch); break; case 'u': buffer.Append ("\\u"); break; default: return false; } } else if (jsonType != JsonType.NONE || !(next_class == C_SPACE || next_class == C_WHITE)) buffer.Append (ch); next_state = state_transition_table [state, next_class]; if (next_state >= 0) { state = next_state; return true; } object result; /* An action to perform */ switch (next_state) { case UC: /* Unicode character */ DecodeUnicodeChar (); state = ST; break; case EX: /* Escaped character */ escaped = true; state = ES; break; case MX: /* integer detected by minus */ jsonType = JsonType.INTEGER; state = MI; break; case PX: /* integer detected by plus */ jsonType = JsonType.INTEGER; state = MI; break; case ZX: /* integer detected by zero */ jsonType = JsonType.INTEGER; state = ZE; break; case IX: /* integer detected by 1-9 */ jsonType = JsonType.INTEGER; state = IN; break; case DE: /* floating point number detected by exponent*/ jsonType = JsonType.FLOAT; state = E1; break; case DF: /* floating point number detected by fraction */ jsonType = JsonType.FLOAT; state = FX; break; case SB: /* string begin " or ' */ buffer.Length = 0; quoteChar = ch; jsonType = JsonType.STRING; state = ST; break; case KB: /* unquoted key name begin */ jsonType = JsonType.STRING; state = UK; break; case UE: /* unquoted key name end ':' */ RemoveLastCharFromBuffer (); if (ParseBuffer (out result)) StoreKey (result); jsonType = JsonType.NONE; PopMode (JsonMode.KEY); PushMode (JsonMode.OBJECT); state = VA; buffer.Length = 0; break; case NU: /* n */ jsonType = JsonType.NULL; state = N1; break; case FA: /* f */ jsonType = JsonType.FALSE; state = F1; break; case TR: /* t */ jsonType = JsonType.TRUE; state = T1; break; case EO: /* empty } */ result = PopObject (true); if (result != null) StoreValue (result); PopMode (JsonMode.KEY); state = OK; break; case OE: /* } */ RemoveLastCharFromBuffer (); if (ParseBuffer (out result)) StoreValue (result); result = PopObject (true); if (result != null) StoreValue (result); PopMode (JsonMode.OBJECT); jsonType = JsonType.NONE; state = OK; break; case AE: /* ] */ RemoveLastCharFromBuffer (); if (ParseBuffer (out result)) StoreValue (result); PopMode (JsonMode.ARRAY); result = PopObject (true); if (result != null) StoreValue (result); jsonType = JsonType.NONE; state = OK; break; case OS: /* { */ RemoveLastCharFromBuffer (); CreateObject (); PushMode (JsonMode.KEY); state = OB; break; case AB: /* [ */ RemoveLastCharFromBuffer (); CreateArray (); PushMode (JsonMode.ARRAY); state = AR; break; case SE: /* string end " or ' */ if (ch == quoteChar) { RemoveLastCharFromBuffer (); switch (PeekMode ()) { case JsonMode.KEY: if (ParseBuffer (out result)) StoreKey (result); jsonType = JsonType.NONE; state = CO; buffer.Length = 0; break; case JsonMode.ARRAY: case JsonMode.OBJECT: if (ParseBuffer (out result)) StoreValue (result); jsonType = JsonType.NONE; state = OK; break; case JsonMode.NONE: /* A stand-alone string */ jsonType = JsonType.STRING; state = IV; /* the rest of input is invalid */ if (ParseBuffer (out result)) PushObject (result); break; default: throw new ArgumentException ("Syntax error: string in unexpected place."); } } break; case CM: /* , */ RemoveLastCharFromBuffer (); // With MS.AJAX, a comma resets the recursion depth recursionDepth = 0; bool doStore = ParseBuffer (out result); switch (PeekMode ()) { case JsonMode.OBJECT: if (doStore) StoreValue (result); PopMode (JsonMode.OBJECT); PushMode (JsonMode.KEY); jsonType = JsonType.NONE; state = KE; break; case JsonMode.ARRAY: jsonType = JsonType.NONE; state = VA; if (doStore) StoreValue (result); break; default: throw new ArgumentException ("Syntax error: unexpected comma."); } break; case CA: /* : */ RemoveLastCharFromBuffer (); // With MS.AJAX a colon increases recursion depth if (++recursionDepth >= recursionLimit) throw new ArgumentException ("Recursion limit has been reached on parsing input."); PopMode (JsonMode.KEY); PushMode (JsonMode.OBJECT); state = VA; break; case IF: /* Infinity */ case NN: /* NaN */ jsonType = JsonType.FLOAT; switch (PeekMode ()) { case JsonMode.ARRAY: case JsonMode.OBJECT: if (ParseBuffer (out result)) StoreValue (result); jsonType = JsonType.NONE; state = OK; break; case JsonMode.NONE: /* A stand-alone NaN/Infinity */ jsonType = JsonType.FLOAT; state = IV; /* the rest of input is invalid */ if (ParseBuffer (out result)) PushObject (result); break; default: throw new ArgumentException ("Syntax error: misplaced NaN/Infinity."); } buffer.Length = 0; break; default: throw new ArgumentException (GetModeMessage (PeekMode ())); } return true; } void CreateArray () { var arr = new ArrayList (); PushObject (arr); } void CreateObject () { var dict = new Dictionary <string, object> (); PushObject (dict); } void StoreKey (object o) { string key = o as string; if (key != null) key = key.Trim (); if (String.IsNullOrEmpty (key)) throw new InvalidOperationException ("Internal error: key is null, empty or not a string."); currentKey.Push (key); Dictionary <string, object> dict = PeekObject () as Dictionary <string, object>; if (dict == null) throw new InvalidOperationException ("Internal error: current object is not a dictionary."); /* MS AJAX.NET silently overwrites existing currentKey value */ dict [key] = null; } void StoreValue (object o) { Dictionary <string, object> dict = PeekObject () as Dictionary <string, object>; if (dict == null) { ArrayList arr = PeekObject () as ArrayList; if (arr == null) throw new InvalidOperationException ("Internal error: current object is not a dictionary or an array."); arr.Add (o); return; } string key; if (currentKey.Count == 0) key = null; else key = currentKey.Pop (); if (String.IsNullOrEmpty (key)) throw new InvalidOperationException ("Internal error: object is a dictionary, but no key present."); dict [key] = o; } } }
using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Threading.Tasks; using JetBrains.Annotations; using JoinRpg.Data.Write.Interfaces; using JoinRpg.DataModel; using JoinRpg.Domain; using JoinRpg.Interfaces; using JoinRpg.Services.Interfaces; using JoinRpg.Services.Interfaces.Notification; namespace JoinRpg.Services.Impl { [UsedImplicitly] public class AccommodationServiceImpl : DbServiceImplBase, IAccommodationService { private IEmailService EmailService { get; } public async Task<ProjectAccommodationType?> SaveRoomTypeAsync(ProjectAccommodationType roomType) { if (roomType.ProjectId == 0) { throw new ArgumentException("Inconsistent state. ProjectId can't be 0"); } ProjectAccommodationType result; if (roomType.Id != 0) { result = await UnitOfWork.GetDbSet<ProjectAccommodationType>().FindAsync(roomType.Id).ConfigureAwait(false); if (result?.ProjectId != roomType.ProjectId) { return null; } result.Name = roomType.Name; result.Cost = roomType.Cost; result.Capacity = roomType.Capacity; result.Description = roomType.Description; result.IsAutoFilledAccommodation = roomType.IsAutoFilledAccommodation; result.IsInfinite = roomType.IsInfinite; result.IsPlayerSelectable = roomType.IsPlayerSelectable; } else { result = UnitOfWork.GetDbSet<ProjectAccommodationType>().Add(roomType); } await UnitOfWork.SaveChangesAsync().ConfigureAwait(false); return result; } public async Task<IReadOnlyCollection<ProjectAccommodationType>> GetRoomTypesAsync(int projectId) => await AccomodationRepository.GetAccommodationForProject(projectId).ConfigureAwait(false); public async Task<ProjectAccommodationType> GetRoomTypeAsync(int roomTypeId) { return await UnitOfWork.GetDbSet<ProjectAccommodationType>() .Include(x => x.ProjectAccommodations) .Include(x => x.Desirous) .FirstOrDefaultAsync(x => x.Id == roomTypeId); } public async Task OccupyRoom(OccupyRequest request) { var room = await UnitOfWork.GetDbSet<ProjectAccommodation>() .Include(r => r.Inhabitants) .Include(r => r.ProjectAccommodationType) .Where(r => r.ProjectId == request.ProjectId && r.Id == request.RoomId) .FirstOrDefaultAsync(); var accommodationRequests = await UnitOfWork.GetDbSet<AccommodationRequest>() .Include(r => r.Subjects.Select(s => s.Player)) .Include(r => r.Project) .Where(r => r.ProjectId == request.ProjectId && request.AccommodationRequestIds.Contains(r.Id)) .ToListAsync(); _ = room.Project.RequestMasterAccess(CurrentUserId, acl => acl.CanSetPlayersAccommodations); foreach (var accommodationRequest in accommodationRequests) { var freeSpace = room.GetRoomFreeSpace(); if (freeSpace < accommodationRequest.Subjects.Count) { throw new JoinRpgInsufficientRoomSpaceException(room); } accommodationRequest.AccommodationId = room.Id; accommodationRequest.Accommodation = room; } await UnitOfWork.SaveChangesAsync(); await EmailService.Email(await CreateRoomEmail<OccupyRoomEmail>(room, accommodationRequests.SelectMany(ar => ar.Subjects).ToArray())); } private async Task<T> CreateRoomEmail<T>(ProjectAccommodation room, Claim[] changed) where T : RoomEmailBase, new() { return new T() { Changed = changed, Initiator = await GetCurrentUser(), ProjectName = room.Project.ProjectName, Recipients = room.GetSubscriptions().ToList(), Room = room, Text = new MarkdownString(), }; } public async Task UnOccupyRoom(UnOccupyRequest request) { var accommodationRequest = await UnitOfWork.GetDbSet<AccommodationRequest>() .Include(r => r.Subjects.Select(s => s.Player)) .Include(r => r.Project) .Where(r => r.ProjectId == request.ProjectId && r.Id == request.AccommodationRequestId) .FirstOrDefaultAsync(); var room = await UnitOfWork.GetDbSet<ProjectAccommodation>() .Include(r => r.Inhabitants) .Include(r => r.ProjectAccommodationType) .Where(r => r.ProjectId == request.ProjectId && r.Id == accommodationRequest.AccommodationId) .FirstOrDefaultAsync(); await UnOccupyRoomImpl(room, new[] { accommodationRequest }); } private async Task UnOccupyRoomImpl(ProjectAccommodation room, IReadOnlyCollection<AccommodationRequest> accommodationRequests) { _ = room.Project.RequestMasterAccess(CurrentUserId, acl => acl.CanSetPlayersAccommodations); foreach (var request in accommodationRequests) { request.AccommodationId = null; request.Accommodation = null; } await UnitOfWork.SaveChangesAsync(); await EmailService.Email( await CreateRoomEmail<UnOccupyRoomEmail>(room, accommodationRequests.SelectMany(x => x.Subjects).ToArray())); } public async Task UnOccupyRoomAll(UnOccupyAllRequest request) { var room = await GetRoomQuery(request.ProjectId) .Where(r => r.Id == request.RoomId) .FirstOrDefaultAsync(); await UnOccupyRoomImpl(room, room.Inhabitants.ToList()); } private IQueryable<ProjectAccommodation> GetRoomQuery(int projectId) { return UnitOfWork.GetDbSet<ProjectAccommodation>() .Include(r => r.Project) .Include(r => r.Inhabitants) .Include(r => r.ProjectAccommodationType) .Include(r => r.Inhabitants.Select(i => i.Subjects.Select(c => c.Player))) .Where(r => r.ProjectId == projectId); } public async Task UnOccupyRoomType(int projectId, int roomTypeId) { var rooms = await GetRoomQuery(projectId) .Where(r => r.Inhabitants.Any()) .Where(r => r.AccommodationTypeId == roomTypeId) .ToListAsync(); foreach (var room in rooms) { await UnOccupyRoomImpl(room, room.Inhabitants.ToList()); } } public async Task UnOccupyAll(int projectId) { var rooms = await GetRoomQuery(projectId) .Where(r => r.Inhabitants.Any()) .ToListAsync(); foreach (var room in rooms) { await UnOccupyRoomImpl(room, room.Inhabitants.ToList()); } } public async Task RemoveRoomType(int accomodationTypeId) { var entity = UnitOfWork.GetDbSet<ProjectAccommodationType>().Find(accomodationTypeId); if (entity == null) { throw new JoinRpgEntityNotFoundException(accomodationTypeId, "ProjectAccommodationType"); } var occupiedRoom = entity.ProjectAccommodations.FirstOrDefault(pa => pa.IsOccupied()); if (occupiedRoom != null) { throw new RoomIsOccupiedException(occupiedRoom); } _ = UnitOfWork.GetDbSet<ProjectAccommodationType>().Remove(entity); await UnitOfWork.SaveChangesAsync().ConfigureAwait(false); } public async Task<IEnumerable<ProjectAccommodation>> AddRooms(int projectId, int roomTypeId, string rooms) { //TODO: Implement rooms names checking ProjectAccommodationType roomType = UnitOfWork.GetDbSet<ProjectAccommodationType>().Find(roomTypeId); if (roomType == null) { throw new JoinRpgEntityNotFoundException(roomTypeId, typeof(ProjectAccommodationType).Name); } if (roomType.ProjectId != projectId) { throw new ArgumentException($@"Room type {roomTypeId} is from another project than specified", nameof(roomTypeId)); } // Internal function // Creates new room using name and parameters from given room info ProjectAccommodation CreateRoom(string name) => new() { Name = name, AccommodationTypeId = roomTypeId, ProjectId = projectId, ProjectAccommodationType = roomType, }; // Internal function // Iterates through rooms list and creates object for each room from a list IEnumerable<ProjectAccommodation> CreateRooms(string r) { foreach (var roomCandidate in r.Split(',')) { var rangePos = roomCandidate.IndexOf('-'); if (rangePos > -1) { if (int.TryParse(roomCandidate.Substring(0, rangePos).Trim(), out var roomsRangeStart) && int.TryParse(roomCandidate.Substring(rangePos + 1).Trim(), out var roomsRangeEnd) && roomsRangeStart < roomsRangeEnd) { while (roomsRangeStart <= roomsRangeEnd) { yield return CreateRoom(roomsRangeStart.ToString()); roomsRangeStart++; } // Range was defined correctly, we can continue to next item continue; } } yield return CreateRoom(roomCandidate.Trim()); } } IEnumerable<ProjectAccommodation> result = UnitOfWork.GetDbSet<ProjectAccommodation>().AddRange(CreateRooms(rooms)); await UnitOfWork.SaveChangesAsync(); return result; } private ProjectAccommodation GetRoom(int roomId, int? projectId = null, int? roomTypeId = null) { var result = UnitOfWork.GetDbSet<ProjectAccommodation>().Find(roomId); if (result == null) { throw new JoinRpgEntityNotFoundException(roomId, typeof(ProjectAccommodation).Name); } if (projectId.HasValue) { if (result.ProjectId != projectId.Value) { throw new ArgumentException($@"Room {roomId} is from different project than specified", nameof(projectId)); } } if (roomTypeId.HasValue) { if (result.AccommodationTypeId != roomTypeId.Value) { throw new ArgumentException($@"Room {roomId} is from different room type than specified", nameof(projectId)); } } return result; } public async Task EditRoom(int roomId, string name, int? projectId = null, int? roomTypeId = null) { var entity = GetRoom(roomId, projectId, roomTypeId); entity.Name = name; await UnitOfWork.SaveChangesAsync().ConfigureAwait(false); } public async Task DeleteRoom(int roomId, int? projectId = null, int? roomTypeId = null) { var entity = GetRoom(roomId, projectId, roomTypeId); if (entity.IsOccupied()) { throw new RoomIsOccupiedException(entity); } _ = UnitOfWork.GetDbSet<ProjectAccommodation>().Remove(entity); await UnitOfWork.SaveChangesAsync().ConfigureAwait(false); } public AccommodationServiceImpl(IUnitOfWork unitOfWork, IEmailService emailService, ICurrentUserAccessor currentUserAccessor) : base(unitOfWork, currentUserAccessor) => EmailService = emailService; } }
namespace Microsoft.Protocols.TestSuites.MS_ASNOTE { using System; using System.Collections.Generic; using System.Collections.ObjectModel; using Microsoft.Protocols.TestSuites.Common; using Microsoft.Protocols.TestSuites.Common.DataStructures; using Microsoft.Protocols.TestTools; using Request = Microsoft.Protocols.TestSuites.Common.Request; /// <summary> /// The base class of scenario class. /// </summary> public class TestSuiteBase : TestClassBase { #region Variables /// <summary> /// Gets the list of existing notes' subjects /// </summary> protected Collection<string> ExistingNoteSubjects { get; private set; } /// <summary> /// Gets protocol interface of MS-ASNOTE /// </summary> protected IMS_ASNOTEAdapter NOTEAdapter { get; private set; } /// <summary> /// Gets or sets the related information of User. /// </summary> protected UserInformation UserInformation { get; set; } #endregion #region Test suite initialize and clean up /// <summary> /// Clean up the environment. /// </summary> protected override void TestCleanup() { // If implementation doesn't support this specification [MS-ASNOTE], the case will not start. if (bool.Parse(Common.GetConfigurationPropertyValue("MS-ASNOTE_Supported", this.Site))) { if (this.ExistingNoteSubjects != null && this.ExistingNoteSubjects.Count > 0) { SyncStore changesResult = this.SyncChanges(1); foreach (string subject in this.ExistingNoteSubjects) { string serverId = null; foreach (Sync add in changesResult.AddElements) { if (add.Note.Subject == subject) { serverId = add.ServerId; break; } } this.Site.Assert.IsNotNull(serverId, "The note with subject {0} should be found.", subject); SyncStore deleteResult = this.SyncDelete(changesResult.SyncKey, serverId); this.Site.Assert.AreEqual<byte>( 1, deleteResult.CollectionStatus, "The server should return a status code of 1 in the Sync command response indicate sync command succeed."); } this.ExistingNoteSubjects.Clear(); } } base.TestCleanup(); } /// <summary> /// Initialize the Test suite. /// </summary> protected override void TestInitialize() { base.TestInitialize(); if (this.NOTEAdapter == null) { this.NOTEAdapter = this.Site.GetAdapter<IMS_ASNOTEAdapter>(); } // If implementation doesn't support this specification [MS-ASNOTE], the case will not start. if (!bool.Parse(Common.GetConfigurationPropertyValue("MS-ASNOTE_Supported", this.Site))) { this.Site.Assert.Inconclusive("This test suite is not supported under current SUT, because MS-ASNOTE_Supported value is set to false in MS-ASNOTE_{0}_SHOULDMAY.deployment.ptfconfig file.", Common.GetSutVersion(this.Site)); } Site.Assume.AreNotEqual<string>("12.1", Common.GetConfigurationPropertyValue("ActiveSyncProtocolVersion", this.Site), "The Notes class is not supported when the MS-ASProtocolVersion header is set to 12.1. MS-ASProtocolVersion header value is determined using Common PTFConfig property named ActiveSyncProtocolVersion."); this.ExistingNoteSubjects = new Collection<string>(); // Set the information of user. this.UserInformation = new UserInformation { UserName = Common.GetConfigurationPropertyValue("UserName", this.Site), UserPassword = Common.GetConfigurationPropertyValue("UserPassword", this.Site), UserDomain = Common.GetConfigurationPropertyValue("Domain", this.Site) }; if (Common.GetSutVersion(this.Site) != SutVersion.ExchangeServer2007 || string.Equals(Common.GetConfigurationPropertyValue("ActiveSyncProtocolVersion", this.Site), "12.1")) { FolderSyncResponse folderSyncResponse = this.NOTEAdapter.FolderSync(Common.CreateFolderSyncRequest("0")); // Get the CollectionId from FolderSync command response. if (string.IsNullOrEmpty(this.UserInformation.NotesCollectionId)) { this.UserInformation.NotesCollectionId = Common.GetDefaultFolderServerId(folderSyncResponse, FolderType.Notes, this.Site); } } } #endregion /// <summary> /// Create the elements of a note /// </summary> /// <returns>The dictionary of value and name for note's elements to be created</returns> protected Dictionary<Request.ItemsChoiceType8, object> CreateNoteElements() { Dictionary<Request.ItemsChoiceType8, object> addElements = new Dictionary<Request.ItemsChoiceType8, object>(); string subject = Common.GenerateResourceName(this.Site, "subject"); addElements.Add(Request.ItemsChoiceType8.Subject1, subject); Request.Body noteBody = new Request.Body { Type = 1, Data = "Content of the body." }; addElements.Add(Request.ItemsChoiceType8.Body, noteBody); Request.Categories3 categories = new Request.Categories3 { Category = new string[] { "blue category" } }; addElements.Add(Request.ItemsChoiceType8.Categories2, categories); addElements.Add(Request.ItemsChoiceType8.MessageClass, "IPM.StickyNote"); return addElements; } #region Call Sync command to fetch the notes /// <summary> /// Call Sync command to fetch all notes /// </summary> /// <param name="bodyType">The type of the body</param> /// <returns>Return change result</returns> protected SyncStore SyncChanges(byte bodyType) { SyncRequest syncInitialRequest = TestSuiteHelper.CreateInitialSyncRequest(this.UserInformation.NotesCollectionId); SyncStore syncInitialResult = this.NOTEAdapter.Sync(syncInitialRequest, false); // Verify sync change result this.Site.Assert.AreEqual<byte>( 1, syncInitialResult.CollectionStatus, "The server returns a Status 1 in the Sync command response indicate sync command success.", syncInitialResult.Status); SyncStore syncResult = this.SyncChanges(syncInitialResult.SyncKey, bodyType); this.Site.Assert.AreEqual<byte>( 1, syncResult.CollectionStatus, "The server should return a Status 1 in the Sync command response indicate sync command succeed."); this.Site.Assert.IsNotNull( syncResult.AddElements, "The server should return Add elements in response"); Collection<Sync> expectedCommands = new Collection<Sync>(); foreach (Sync sync in syncResult.AddElements) { this.Site.Assert.IsNotNull( sync, @"The Add element in response should not be null."); this.Site.Assert.IsNotNull( sync.Note, @"The note class in response should not be null."); if (this.ExistingNoteSubjects.Contains(sync.Note.Subject)) { expectedCommands.Add(sync); } } this.Site.Assert.AreEqual<int>( this.ExistingNoteSubjects.Count, expectedCommands.Count, @"The number of Add elements returned in response should be equal to the number of expected notes' subjects"); syncResult.AddElements.Clear(); foreach (Sync sync in expectedCommands) { syncResult.AddElements.Add(sync); } return syncResult; } /// <summary> /// Call Sync command to fetch the change of the notes from previous syncKey /// </summary> /// <param name="syncKey">The sync key</param> /// <param name="bodyType">The type of the body</param> /// <returns>Return change result</returns> protected SyncStore SyncChanges(string syncKey, byte bodyType) { Request.BodyPreference bodyPreference = new Request.BodyPreference { Type = bodyType }; SyncRequest syncRequest = TestSuiteHelper.CreateSyncRequest(syncKey, this.UserInformation.NotesCollectionId, bodyPreference); SyncStore syncResult = this.NOTEAdapter.Sync(syncRequest, true); return syncResult; } #endregion #region Call Sync command to add a note /// <summary> /// Call Sync command to add a note /// </summary> /// <param name="addElements">The elements of a note item to be added</param> /// <param name="count">The number of the note</param> /// <returns>Return the sync add result</returns> protected SyncStore SyncAdd(Dictionary<Request.ItemsChoiceType8, object> addElements, int count) { SyncRequest syncRequest = TestSuiteHelper.CreateInitialSyncRequest(this.UserInformation.NotesCollectionId); SyncStore syncResult = this.NOTEAdapter.Sync(syncRequest, false); // Verify sync change result this.Site.Assert.AreEqual<byte>( 1, syncResult.CollectionStatus, "The server should return a status code 1 in the Sync command response indicate sync command success."); List<object> addData = new List<object>(); string[] subjects = new string[count]; // Construct every note for (int i = 0; i < count; i++) { Request.SyncCollectionAdd add = new Request.SyncCollectionAdd { ClientId = System.Guid.NewGuid().ToString(), ApplicationData = new Request.SyncCollectionAddApplicationData { ItemsElementName = new Request.ItemsChoiceType8[addElements.Count], Items = new object[addElements.Count] } }; // Since only one subject is generated in addElement, if there are multiple notes, generate unique subjects with index for every note. if (count > 1) { addElements[Request.ItemsChoiceType8.Subject1] = Common.GenerateResourceName(this.Site, "subject", (uint)(i + 1)); } subjects[i] = addElements[Request.ItemsChoiceType8.Subject1].ToString(); addElements.Keys.CopyTo(add.ApplicationData.ItemsElementName, 0); addElements.Values.CopyTo(add.ApplicationData.Items, 0); addData.Add(add); } syncRequest = TestSuiteHelper.CreateSyncRequest(syncResult.SyncKey, this.UserInformation.NotesCollectionId, addData); SyncStore addResult = this.NOTEAdapter.Sync(syncRequest, false); this.Site.Assert.AreEqual<byte>( 1, addResult.CollectionStatus, "The server should return a Status 1 in the Sync command response indicate sync command succeed."); this.Site.Assert.IsNotNull( addResult.AddResponses, @"The Add elements in Responses element of the Sync response should not be null."); this.Site.Assert.AreEqual<int>( count, addResult.AddResponses.Count, @"The actual number of note items should be returned in Sync response as the expected number."); for (int i = 0; i < count; i++) { this.Site.Assert.IsNotNull( addResult.AddResponses[i], @"The Add element in response should not be null."); this.Site.Assert.AreEqual<int>( 1, int.Parse(addResult.AddResponses[i].Status), "The server should return a Status 1 in the Sync command response indicate sync command succeed."); this.ExistingNoteSubjects.Add(subjects[i]); } return addResult; } #endregion #region Call Sync command to change a note /// <summary> /// Call Sync command to change a note /// </summary> /// <param name="syncKey">The sync key</param> /// <param name="serverId">The server Id of the note</param> /// <param name="changedElements">The changed elements of the note</param> /// <returns>Return the sync change result</returns> protected SyncStore SyncChange(string syncKey, string serverId, Dictionary<Request.ItemsChoiceType7, object> changedElements) { Request.SyncCollectionChange change = new Request.SyncCollectionChange { ServerId = serverId, ApplicationData = new Request.SyncCollectionChangeApplicationData { ItemsElementName = new Request.ItemsChoiceType7[changedElements.Count], Items = new object[changedElements.Count] } }; changedElements.Keys.CopyTo(change.ApplicationData.ItemsElementName, 0); changedElements.Values.CopyTo(change.ApplicationData.Items, 0); List<object> changeData = new List<object> { change }; SyncRequest syncRequest = TestSuiteHelper.CreateSyncRequest(syncKey, this.UserInformation.NotesCollectionId, changeData); return this.NOTEAdapter.Sync(syncRequest, false); } #endregion #region Call Sync command to delete a note /// <summary> /// Call Sync command to delete a note /// </summary> /// <param name="syncKey">The sync key</param> /// <param name="serverId">The server id of the note, which is returned by server</param> /// <returns>Return the sync delete result</returns> private SyncStore SyncDelete(string syncKey, string serverId) { List<object> deleteData = new List<object> { new Request.SyncCollectionDelete { ServerId = serverId } }; SyncRequest syncRequest = TestSuiteHelper.CreateSyncRequest(syncKey, this.UserInformation.NotesCollectionId, deleteData); SyncStore result = this.NOTEAdapter.Sync(syncRequest, false); return result; } #endregion } }
/* * Copyright 2011 Google 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 System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using BitSharper.IO; using log4net; namespace BitSharper.Store { /// <summary> /// Stores the block chain to disk but still holds it in memory. This is intended for desktop apps and tests. /// Constrained environments like mobile phones probably won't want to or be able to store all the block headers in RAM. /// </summary> public class DiskBlockStore : IBlockStore { private static readonly ILog _log = LogManager.GetLogger(typeof (DiskBlockStore)); private FileStream _stream; private readonly IDictionary<Sha256Hash, StoredBlock> _blockMap; private Sha256Hash _chainHead; private readonly NetworkParameters _params; /// <exception cref="BlockStoreException"/> public DiskBlockStore(NetworkParameters @params, FileInfo file) { _params = @params; _blockMap = new Dictionary<Sha256Hash, StoredBlock>(); try { Load(file); if (_stream != null) { _stream.Dispose(); } _stream = file.Open(FileMode.Append, FileAccess.Write); // Do append. } catch (IOException e) { _log.Error("failed to load block store from file", e); CreateNewStore(@params, file); } } /// <exception cref="BlockStoreException"/> private void CreateNewStore(NetworkParameters @params, FileInfo file) { // Create a new block store if the file wasn't found or anything went wrong whilst reading. _blockMap.Clear(); try { if (_stream != null) { _stream.Dispose(); } _stream = file.OpenWrite(); // Do not append, create fresh. _stream.Write(1); // Version. } catch (IOException e1) { // We could not load a block store nor could we create a new one! throw new BlockStoreException(e1); } try { // Set up the genesis block. When we start out fresh, it is by definition the top of the chain. var genesis = @params.GenesisBlock.CloneAsHeader(); var storedGenesis = new StoredBlock(genesis, genesis.GetWork(), 0); _chainHead = storedGenesis.Header.Hash; _stream.Write(_chainHead.Bytes); Put(storedGenesis); } catch (IOException e) { throw new BlockStoreException(e); } } /// <exception cref="IOException"/> /// <exception cref="BlockStoreException"/> private void Load(FileInfo file) { _log.InfoFormat("Reading block store from {0}", file); using (var input = file.OpenRead()) { // Read a version byte. var version = input.Read(); if (version == -1) { // No such file or the file was empty. throw new FileNotFoundException(file.Name + " does not exist or is empty"); } if (version != 1) { throw new BlockStoreException("Bad version number: " + version); } // Chain head pointer is the first thing in the file. var chainHeadHash = new byte[32]; if (input.Read(chainHeadHash) < chainHeadHash.Length) throw new BlockStoreException("Truncated block store: cannot read chain head hash"); _chainHead = new Sha256Hash(chainHeadHash); _log.InfoFormat("Read chain head from disk: {0}", _chainHead); var now = Environment.TickCount; // Rest of file is raw block headers. var headerBytes = new byte[Block.HeaderSize]; try { while (true) { // Read a block from disk. if (input.Read(headerBytes) < 80) { // End of file. break; } // Parse it. var b = new Block(_params, headerBytes); // Look up the previous block it connects to. var prev = Get(b.PrevBlockHash); StoredBlock s; if (prev == null) { // First block in the stored chain has to be treated specially. if (b.Equals(_params.GenesisBlock)) { s = new StoredBlock(_params.GenesisBlock.CloneAsHeader(), _params.GenesisBlock.GetWork(), 0); } else { throw new BlockStoreException("Could not connect " + b.Hash + " to " + b.PrevBlockHash); } } else { // Don't try to verify the genesis block to avoid upsetting the unit tests. b.VerifyHeader(); // Calculate its height and total chain work. s = prev.Build(b); } // Save in memory. _blockMap[b.Hash] = s; } } catch (ProtocolException e) { // Corrupted file. throw new BlockStoreException(e); } catch (VerificationException e) { // Should not be able to happen unless the file contains bad blocks. throw new BlockStoreException(e); } var elapsed = Environment.TickCount - now; _log.InfoFormat("Block chain read complete in {0}ms", elapsed); } } /// <exception cref="BlockStoreException"/> public void Put(StoredBlock block) { lock (this) { try { var hash = block.Header.Hash; Debug.Assert(!_blockMap.ContainsKey(hash), "Attempt to insert duplicate"); // Append to the end of the file. The other fields in StoredBlock will be recalculated when it's reloaded. var bytes = block.Header.BitcoinSerialize(); _stream.Write(bytes); _stream.Flush(); _blockMap[hash] = block; } catch (IOException e) { throw new BlockStoreException(e); } } } /// <exception cref="BlockStoreException"/> public StoredBlock Get(Sha256Hash hash) { lock (this) { StoredBlock block; _blockMap.TryGetValue(hash, out block); return block; } } /// <exception cref="BlockStoreException"/> public StoredBlock GetChainHead() { lock (this) { StoredBlock block; _blockMap.TryGetValue(_chainHead, out block); return block; } } /// <exception cref="BlockStoreException"/> public void SetChainHead(StoredBlock chainHead) { lock (this) { try { _chainHead = chainHead.Header.Hash; // Write out new hash to the first 32 bytes of the file past one (first byte is version number). _stream.Seek(1, SeekOrigin.Begin); var bytes = _chainHead.Bytes; _stream.Write(bytes, 0, bytes.Length); } catch (IOException e) { throw new BlockStoreException(e); } } } #region IDisposable Members public void Dispose() { if (_stream != null) { _stream.Dispose(); _stream = null; } } #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.IO; using System.Threading; using System.Runtime.Serialization; using System.Threading.Tasks; namespace System.Net { public class FileWebRequest : WebRequest, ISerializable { private readonly WebHeaderCollection _headers = new WebHeaderCollection(); private string _method = WebRequestMethods.File.DownloadFile; private FileAccess _fileAccess = FileAccess.Read; private ManualResetEventSlim _blockReaderUntilRequestStreamDisposed; private WebResponse _response; private WebFileStream _stream; private Uri _uri; private long _contentLength; private int _timeout = DefaultTimeoutMilliseconds; private bool _readPending; private bool _writePending; private bool _writing; private bool _syncHint; private int _aborted; internal FileWebRequest(Uri uri) { if (uri.Scheme != (object)Uri.UriSchemeFile) { throw new ArgumentOutOfRangeException(nameof(uri)); } _uri = uri; } [Obsolete("Serialization is obsoleted for this type. http://go.microsoft.com/fwlink/?linkid=14202")] protected FileWebRequest(SerializationInfo serializationInfo, StreamingContext streamingContext) : base(serializationInfo, streamingContext) { _headers = (WebHeaderCollection)serializationInfo.GetValue("headers", typeof(WebHeaderCollection)); Proxy = (IWebProxy)serializationInfo.GetValue("proxy", typeof(IWebProxy)); _uri = (Uri)serializationInfo.GetValue("uri", typeof(Uri)); ConnectionGroupName = serializationInfo.GetString("connectionGroupName"); _method = serializationInfo.GetString("method"); _contentLength = serializationInfo.GetInt64("contentLength"); _timeout = serializationInfo.GetInt32("timeout"); _fileAccess = (FileAccess)serializationInfo.GetInt32("fileAccess"); } void ISerializable.GetObjectData(SerializationInfo serializationInfo, StreamingContext streamingContext) => GetObjectData(serializationInfo, streamingContext); protected override void GetObjectData(SerializationInfo serializationInfo, StreamingContext streamingContext) { serializationInfo.AddValue("headers", _headers, typeof(WebHeaderCollection)); serializationInfo.AddValue("proxy", Proxy, typeof(IWebProxy)); serializationInfo.AddValue("uri", _uri, typeof(Uri)); serializationInfo.AddValue("connectionGroupName", ConnectionGroupName); serializationInfo.AddValue("method", _method); serializationInfo.AddValue("contentLength", _contentLength); serializationInfo.AddValue("timeout", _timeout); serializationInfo.AddValue("fileAccess", _fileAccess); serializationInfo.AddValue("preauthenticate", false); base.GetObjectData(serializationInfo, streamingContext); } internal bool Aborted => _aborted != 0; public override string ConnectionGroupName { get; set; } public override long ContentLength { get { return _contentLength; } set { if (value < 0) { throw new ArgumentException(SR.net_clsmall, nameof(value)); } _contentLength = value; } } public override string ContentType { get { return _headers["Content-Type"]; } set { _headers["Content-Type"] = value; } } public override ICredentials Credentials { get; set; } public override WebHeaderCollection Headers => _headers; public override string Method { get { return _method; } set { if (string.IsNullOrEmpty(value)) { throw new ArgumentException(SR.net_badmethod, nameof(value)); } _method = value; } } public override bool PreAuthenticate { get; set; } public override IWebProxy Proxy { get; set; } public override int Timeout { get { return _timeout; } set { if (value < 0 && value != System.Threading.Timeout.Infinite) { throw new ArgumentOutOfRangeException(nameof(value), SR.net_io_timeout_use_ge_zero); } _timeout = value; } } public override Uri RequestUri => _uri; private static Exception CreateRequestAbortedException() => new WebException(SR.Format(SR.net_requestaborted, WebExceptionStatus.RequestCanceled), WebExceptionStatus.RequestCanceled); private void CheckAndMarkAsyncGetRequestStreamPending() { if (Aborted) { throw CreateRequestAbortedException(); } if (string.Equals(_method, "GET", StringComparison.OrdinalIgnoreCase) || string.Equals(_method, "HEAD", StringComparison.OrdinalIgnoreCase)) { throw new ProtocolViolationException(SR.net_nouploadonget); } if (_response != null) { throw new InvalidOperationException(SR.net_reqsubmitted); } lock (this) { if (_writePending) { throw new InvalidOperationException(SR.net_repcall); } _writePending = true; } } private Stream CreateWriteStream() { try { if (_stream == null) { _stream = new WebFileStream(this, _uri.LocalPath, FileMode.Create, FileAccess.Write, FileShare.Read); _fileAccess = FileAccess.Write; _writing = true; } return _stream; } catch (Exception e) { throw new WebException(e.Message, e); } } public override IAsyncResult BeginGetRequestStream(AsyncCallback callback, object state) { CheckAndMarkAsyncGetRequestStreamPending(); Task<Stream> t = Task.Factory.StartNew(s => ((FileWebRequest)s).CreateWriteStream(), this, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); return TaskToApm.Begin(t, callback, state); } public override Task<Stream> GetRequestStreamAsync() { CheckAndMarkAsyncGetRequestStreamPending(); return Task.Factory.StartNew(s => { FileWebRequest thisRef = (FileWebRequest)s; Stream writeStream = thisRef.CreateWriteStream(); thisRef._writePending = false; return writeStream; }, this, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); } private void CheckAndMarkAsyncGetResponsePending() { if (Aborted) { throw CreateRequestAbortedException(); } lock (this) { if (_readPending) { throw new InvalidOperationException(SR.net_repcall); } _readPending = true; } } private WebResponse CreateResponse() { if (_writePending || _writing) { lock (this) { if (_writePending || _writing) { _blockReaderUntilRequestStreamDisposed = new ManualResetEventSlim(); } } } _blockReaderUntilRequestStreamDisposed?.Wait(); try { return _response ?? (_response = new FileWebResponse(this, _uri, _fileAccess, !_syncHint)); } catch (Exception e) { throw new WebException(e.Message, e); } } public override IAsyncResult BeginGetResponse(AsyncCallback callback, object state) { CheckAndMarkAsyncGetResponsePending(); Task<WebResponse> t = Task.Factory.StartNew(s => ((FileWebRequest)s).CreateResponse(), this, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); return TaskToApm.Begin(t, callback, state); } public override Task<WebResponse> GetResponseAsync() { CheckAndMarkAsyncGetResponsePending(); return Task.Factory.StartNew(s => { var thisRef = (FileWebRequest)s; WebResponse response = thisRef.CreateResponse(); _readPending = false; return response; }, this, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); } public override Stream EndGetRequestStream(IAsyncResult asyncResult) { Stream stream = TaskToApm.End<Stream>(asyncResult); _writePending = false; return stream; } public override WebResponse EndGetResponse(IAsyncResult asyncResult) { WebResponse response = TaskToApm.End<WebResponse>(asyncResult); _readPending = false; return response; } public override Stream GetRequestStream() { IAsyncResult result = BeginGetRequestStream(null, null); if (Timeout != Threading.Timeout.Infinite && !result.IsCompleted && (!result.AsyncWaitHandle.WaitOne(Timeout, false) || !result.IsCompleted)) { _stream?.Close(); throw new WebException(SR.net_webstatus_Timeout, WebExceptionStatus.Timeout); } return EndGetRequestStream(result); } public override WebResponse GetResponse() { _syncHint = true; IAsyncResult result = BeginGetResponse(null, null); if (Timeout != Threading.Timeout.Infinite && !result.IsCompleted && (!result.AsyncWaitHandle.WaitOne(Timeout, false) || !result.IsCompleted)) { _response?.Close(); throw new WebException(SR.net_webstatus_Timeout, WebExceptionStatus.Timeout); } return EndGetResponse(result); } internal void UnblockReader() { lock (this) { _blockReaderUntilRequestStreamDisposed?.Set(); } _writing = false; } public override bool UseDefaultCredentials { get { throw new NotSupportedException(SR.net_PropertyNotSupportedException); } set { throw new NotSupportedException(SR.net_PropertyNotSupportedException); } } public override void Abort() { if (Interlocked.Increment(ref _aborted) == 1) { _stream?.Abort(); _response?.Close(); } } } internal sealed class FileWebRequestCreator : IWebRequestCreate { public WebRequest Create(Uri uri) => new FileWebRequest(uri); } internal sealed class WebFileStream : FileStream { private readonly FileWebRequest _request; public WebFileStream(FileWebRequest request, string path, FileMode mode, FileAccess access, FileShare sharing) : base(path, mode, access, sharing) { _request = request; } public WebFileStream(FileWebRequest request, string path, FileMode mode, FileAccess access, FileShare sharing, int length, bool async) : base(path, mode, access, sharing, length, async) { _request = request; } protected override void Dispose(bool disposing) { try { if (disposing) { _request?.UnblockReader(); } } finally { base.Dispose(disposing); } } internal void Abort() => SafeFileHandle.Close(); public override int Read(byte[] buffer, int offset, int size) { CheckAborted(); try { return base.Read(buffer, offset, size); } catch { CheckAborted(); throw; } } public override void Write(byte[] buffer, int offset, int size) { CheckAborted(); try { base.Write(buffer, offset, size); } catch { CheckAborted(); throw; } } public override IAsyncResult BeginRead(byte[] buffer, int offset, int size, AsyncCallback callback, object state) { CheckAborted(); try { return base.BeginRead(buffer, offset, size, callback, state); } catch { CheckAborted(); throw; } } public override int EndRead(IAsyncResult ar) { try { return base.EndRead(ar); } catch { CheckAborted(); throw; } } public override IAsyncResult BeginWrite(byte[] buffer, int offset, int size, AsyncCallback callback, object state) { CheckAborted(); try { return base.BeginWrite(buffer, offset, size, callback, state); } catch { CheckAborted(); throw; } } public override void EndWrite(IAsyncResult ar) { try { base.EndWrite(ar); } catch { CheckAborted(); throw; } } public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { CheckAborted(); try { return base.ReadAsync(buffer, offset, count, cancellationToken); } catch { CheckAborted(); throw; } } public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { CheckAborted(); try { return base.WriteAsync(buffer, offset, count, cancellationToken); } catch { CheckAborted(); throw; } } public override Task CopyToAsync(Stream destination, int bufferSize, CancellationToken cancellationToken) { CheckAborted(); try { return base.CopyToAsync(destination, bufferSize, cancellationToken); } catch { CheckAborted(); throw; } } private void CheckAborted() { if (_request.Aborted) { throw new WebException(SR.Format(SR.net_requestaborted, WebExceptionStatus.RequestCanceled), WebExceptionStatus.RequestCanceled); } } } }
// 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.Linq; using System.Reflection; using System.Threading; namespace System.Composition.Convention { /// <summary> /// Entry point for defining rules that configure plain-old-CLR-objects as MEF parts. /// </summary> public class ConventionBuilder : AttributedModelProvider { private static readonly List<object> s_emptyList = new List<object>(); private readonly ReaderWriterLockSlim _lock = new ReaderWriterLockSlim(LockRecursionPolicy.NoRecursion); private readonly List<PartConventionBuilder> _conventions = new List<PartConventionBuilder>(); private readonly Dictionary<MemberInfo, List<Attribute>> _memberInfos = new Dictionary<MemberInfo, List<Attribute>>(); private readonly Dictionary<ParameterInfo, List<Attribute>> _parameters = new Dictionary<ParameterInfo, List<Attribute>>(); /// <summary> /// Construct a new <see cref="ConventionBuilder"/>. /// </summary> public ConventionBuilder() { } /// <summary> /// Define a rule that will apply to all types that /// derive from (or implement) the specified type. /// </summary> /// <typeparam name="T">The type from which matching types derive.</typeparam> /// <returns>A <see cref="PartConventionBuilder{T}"/> that must be used to specify the rule.</returns> public PartConventionBuilder<T> ForTypesDerivedFrom<T>() { var partBuilder = new PartConventionBuilder<T>((t) => IsDescendentOf(t, typeof(T))); _conventions.Add(partBuilder); return partBuilder; } /// <summary> /// Define a rule that will apply to all types that /// derive from (or implement) the specified type. /// </summary> /// <param name="type">The type from which matching types derive.</param> /// <returns>A <see cref="PartConventionBuilder"/> that must be used to specify the rule.</returns> public PartConventionBuilder ForTypesDerivedFrom(Type type) { if (type == null) { throw new ArgumentNullException(nameof(type)); } var partBuilder = new PartConventionBuilder((t) => IsDescendentOf(t, type)); _conventions.Add(partBuilder); return partBuilder; } /// <summary> /// Define a rule that will apply to the types <typeparamref name="T"/>. /// </summary> /// <typeparam name="T">The type to which the rule applies.</typeparam> /// <returns>A <see cref="PartConventionBuilder{T}"/> that must be used to specify the rule.</returns> public PartConventionBuilder<T> ForType<T>() { var partBuilder = new PartConventionBuilder<T>((t) => t == typeof(T)); _conventions.Add(partBuilder); return partBuilder; } /// <summary> /// Define a rule that will apply to the types <paramref name="type"/>. /// </summary> /// <param name="type">The type to which the rule applies.</param> /// <returns>A <see cref="PartConventionBuilder"/> that must be used to specify the rule.</returns> public PartConventionBuilder ForType(Type type) { if (type == null) { throw new ArgumentNullException(nameof(type)); } var partBuilder = new PartConventionBuilder((t) => t == type); _conventions.Add(partBuilder); return partBuilder; } /// <summary> /// Define a rule that will apply to types assignable to <typeparamref name="T"/> that /// match the supplied predicate. /// </summary> /// <param name="typeFilter">A predicate that selects matching types.</param> /// <typeparam name="T">The type to which the rule applies.</typeparam> /// <returns>A <see cref="PartConventionBuilder{T}"/> that must be used to specify the rule.</returns> public PartConventionBuilder<T> ForTypesMatching<T>(Predicate<Type> typeFilter) { if (typeFilter == null) { throw new ArgumentNullException(nameof(typeFilter)); } var partBuilder = new PartConventionBuilder<T>(typeFilter); _conventions.Add(partBuilder); return partBuilder; } /// <summary> /// Define a rule that will apply to types that /// match the supplied predicate. /// </summary> /// <param name="typeFilter">A predicate that selects matching types.</param> /// <returns>A <see cref="PartConventionBuilder{T}"/> that must be used to specify the rule.</returns> public PartConventionBuilder ForTypesMatching(Predicate<Type> typeFilter) { if (typeFilter == null) { throw new ArgumentNullException(nameof(typeFilter)); } var partBuilder = new PartConventionBuilder(typeFilter); _conventions.Add(partBuilder); return partBuilder; } private IEnumerable<Tuple<object, List<Attribute>>> EvaluateThisTypeInfoAgainstTheConvention(TypeInfo typeInfo) { List<Tuple<object, List<Attribute>>> results = new List<Tuple<object, List<Attribute>>>(); List<Attribute> attributes = new List<Attribute>(); var configuredMembers = new List<Tuple<object, List<Attribute>>>(); bool specifiedConstructor = false; bool matchedConvention = false; Type type = typeInfo.AsType(); foreach (PartConventionBuilder builder in _conventions.Where(c => c.SelectType(type))) { attributes.AddRange(builder.BuildTypeAttributes(type)); specifiedConstructor |= builder.BuildConstructorAttributes(type, ref configuredMembers); builder.BuildPropertyAttributes(type, ref configuredMembers); builder.BuildOnImportsSatisfiedNotification(type, ref configuredMembers); matchedConvention = true; } if (matchedConvention && !specifiedConstructor) { // DefaultConstructor PartConventionBuilder.BuildDefaultConstructorAttributes(type, ref configuredMembers); } configuredMembers.Add(Tuple.Create((object)type.GetTypeInfo(), attributes)); return configuredMembers; } /// <summary> /// Provide the list of attributes applied to the specified member. /// </summary> /// <param name="reflectedType">The reflectedType the type used to retrieve the memberInfo.</param> /// <param name="member">The member to supply attributes for.</param> /// <returns>The list of applied attributes.</returns> public override IEnumerable<Attribute> GetCustomAttributes(Type reflectedType, System.Reflection.MemberInfo member) { if (member == null) { throw new ArgumentNullException(nameof(member)); } // Now edit the attributes returned from the base type List<Attribute> cachedAttributes = null; var typeInfo = member as TypeInfo; if (typeInfo != null) { var memberInfo = typeInfo as MemberInfo; _lock.EnterReadLock(); try { _memberInfos.TryGetValue(memberInfo, out cachedAttributes); } finally { _lock.ExitReadLock(); } if (cachedAttributes == null) { _lock.EnterWriteLock(); try { //Double check locking another thread may have inserted one while we were away. if (!_memberInfos.TryGetValue(memberInfo, out cachedAttributes)) { List<Attribute> attributeList; foreach (Tuple<object, List<Attribute>> element in EvaluateThisTypeInfoAgainstTheConvention(typeInfo)) { attributeList = element.Item2; if (attributeList != null) { var mi = element.Item1 as MemberInfo; if (mi != null) { if (mi != null && (mi is ConstructorInfo || mi is TypeInfo || mi is PropertyInfo || mi is MethodInfo)) { if (!_memberInfos.TryGetValue(mi, out List<Attribute> memberAttributes)) { _memberInfos.Add(mi, element.Item2); } } } else { var pi = element.Item1 as ParameterInfo; if (pi == null) { throw new Exception(SR.Diagnostic_InternalExceptionMessage); } // Item contains as Constructor parameter to configure if (!_parameters.TryGetValue(pi, out List<Attribute> parameterAttributes)) { _parameters.Add(pi, element.Item2); } } } } } // We will have updated all of the MemberInfos by now so lets reload cachedAttributes with the current store _memberInfos.TryGetValue(memberInfo, out cachedAttributes); } finally { _lock.ExitWriteLock(); } } } else if (member is PropertyInfo || member is ConstructorInfo || member is MethodInfo) { cachedAttributes = ReadMemberCustomAttributes(reflectedType, member); } IEnumerable<Attribute> appliedAttributes; if (!(member is TypeInfo) && member.DeclaringType != reflectedType) appliedAttributes = Enumerable.Empty<Attribute>(); else appliedAttributes = member.GetCustomAttributes<Attribute>(false); return cachedAttributes == null ? appliedAttributes : appliedAttributes.Concat(cachedAttributes); } private List<Attribute> ReadMemberCustomAttributes(Type reflectedType, System.Reflection.MemberInfo member) { List<Attribute> cachedAttributes = null; bool getMemberAttributes = false; // Now edit the attributes returned from the base type _lock.EnterReadLock(); try { if (!_memberInfos.TryGetValue(member, out cachedAttributes)) { // If there is nothing for this member Cache any attributes for the DeclaringType if (reflectedType != null && !_memberInfos.TryGetValue(member.DeclaringType.GetTypeInfo() as MemberInfo, out cachedAttributes)) { // If there is nothing for this parameter look to see if the declaring Member has been cached yet? // need to do it outside of the lock, so set the flag we'll check it in a bit getMemberAttributes = true; } cachedAttributes = null; } } finally { _lock.ExitReadLock(); } if (getMemberAttributes) { GetCustomAttributes(null, reflectedType.GetTypeInfo() as MemberInfo); // We should have run the rules for the enclosing parameter so we can again _lock.EnterReadLock(); try { _memberInfos.TryGetValue(member, out cachedAttributes); } finally { _lock.ExitReadLock(); } } return cachedAttributes; } /// <summary> /// Provide the list of attributes applied to the specified parameter. /// </summary> /// <param name="reflectedType">The reflectedType the type used to retrieve the parameterInfo.</param> /// <param name="parameter">The parameter to supply attributes for.</param> /// <returns>The list of applied attributes.</returns> public override IEnumerable<Attribute> GetCustomAttributes(Type reflectedType, System.Reflection.ParameterInfo parameter) { if (parameter == null) { throw new ArgumentNullException(nameof(parameter)); } IEnumerable<Attribute> attributes = parameter.GetCustomAttributes<Attribute>(false); List<Attribute> cachedAttributes = ReadParameterCustomAttributes(reflectedType, parameter); return cachedAttributes == null ? attributes : attributes.Concat(cachedAttributes); } private List<Attribute> ReadParameterCustomAttributes(Type reflectedType, System.Reflection.ParameterInfo parameter) { List<Attribute> cachedAttributes = null; bool getMemberAttributes = false; // Now edit the attributes returned from the base type _lock.EnterReadLock(); try { if (!_parameters.TryGetValue(parameter, out cachedAttributes)) { // If there is nothing for this parameter Cache any attributes for the DeclaringType if (reflectedType != null && !_memberInfos.TryGetValue(reflectedType.GetTypeInfo() as MemberInfo, out cachedAttributes)) { // If there is nothing for this parameter look to see if the declaring Member has been cached yet? // need to do it outside of the lock, so set the flag we'll check it in a bit getMemberAttributes = true; } cachedAttributes = null; } } finally { _lock.ExitReadLock(); } if (getMemberAttributes) { GetCustomAttributes(null, reflectedType.GetTypeInfo() as MemberInfo); // We should have run the rules for the enclosing parameter so we can again _lock.EnterReadLock(); try { _parameters.TryGetValue(parameter, out cachedAttributes); } finally { _lock.ExitReadLock(); } } return cachedAttributes; } private static bool IsGenericDescendentOf(TypeInfo derivedType, TypeInfo baseType) { if (derivedType.BaseType == null) return false; if (derivedType.BaseType == baseType.AsType()) return true; foreach (Type iface in derivedType.ImplementedInterfaces) { if (iface.IsConstructedGenericType && iface.GetGenericTypeDefinition() == baseType.AsType()) return true; } return IsGenericDescendentOf(derivedType.BaseType.GetTypeInfo(), baseType); } private static bool IsDescendentOf(Type type, Type baseType) { if (type == baseType || type == typeof(object) || type == null) { return false; } TypeInfo ti = type.GetTypeInfo(); TypeInfo bti = baseType.GetTypeInfo(); // The baseType can be an open generic, in that case this ensures // that the derivedType is checked against it if (ti.IsGenericTypeDefinition || bti.IsGenericTypeDefinition) { return IsGenericDescendentOf(ti, bti); } return bti.IsAssignableFrom(ti); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace ExporterWeb.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.Collections.Immutable; using System.Linq; using System.Reflection; using ProGaudi.MsgPack.Light.Converters; using ProGaudi.MsgPack.Light.Converters.Generation; namespace ProGaudi.MsgPack.Light { public class MsgPackContext { private readonly bool _convertEnumsAsStrings; private static readonly IMsgPackConverter<object> SharedNullConverter = new NullConverter(); private readonly ConverterGenerationContext _generatorContext = new ConverterGenerationContext(); private readonly Dictionary<Type, IMsgPackConverter> _converters; private readonly Dictionary<Type, Type> _genericConverters = new Dictionary<Type, Type>(); private readonly Dictionary<Type, Func<object>> _objectActivators = new Dictionary<Type, Func<object>>(); public MsgPackContext(bool strictParseOfFloat = false, bool convertEnumsAsStrings = true, bool binaryCompatibilityMode = false) { _convertEnumsAsStrings = convertEnumsAsStrings; var numberConverter = new NumberConverter(strictParseOfFloat); _converters = new Dictionary<Type, IMsgPackConverter> { {typeof(MsgPackToken), new MsgPackTokenConverter()}, {typeof (bool), new BoolConverter()}, {typeof (string), new StringConverter()}, {typeof (byte[]), new BinaryConverter(binaryCompatibilityMode)}, {typeof (float), numberConverter}, {typeof (double), numberConverter}, {typeof (byte), numberConverter}, {typeof (sbyte), numberConverter}, {typeof (short), numberConverter}, {typeof (ushort), numberConverter}, {typeof (int), numberConverter}, {typeof (uint), numberConverter}, {typeof (long), numberConverter}, {typeof (ulong), numberConverter}, {typeof (DateTime), new DateTimeConverter()}, {typeof (DateTimeOffset), new DateTimeConverter()}, {typeof (TimeSpan), new TimeSpanConverter() }, {typeof (bool?), new NullableConverter<bool>()}, {typeof (float?), new NullableConverter<float>()}, {typeof (double?), new NullableConverter<double>()}, {typeof (byte?), new NullableConverter<byte>()}, {typeof (sbyte?), new NullableConverter<sbyte>()}, {typeof (short?), new NullableConverter<short>()}, {typeof (ushort?), new NullableConverter<ushort>()}, {typeof (int?), new NullableConverter<int>()}, {typeof (uint?), new NullableConverter<uint>()}, {typeof (long?), new NullableConverter<long>()}, {typeof (ulong?), new NullableConverter<ulong>()}, {typeof (DateTime?), new NullableConverter<DateTime>()}, {typeof (DateTimeOffset?), new NullableConverter<DateTimeOffset>()} }; foreach (var converter in _converters) { converter.Value.Initialize(this); } } public IMsgPackConverter<object> NullConverter => SharedNullConverter; #if !NETSTANDARD1_1 public void DiscoverConverters() { foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies()) { DiscoverConverters(assembly); } } #endif public void DiscoverConverters<T>() { DiscoverConverters(typeof(T).GetTypeInfo().Assembly); } public void DiscoverConverters(Assembly assembly) { var generateMapConverter = GetType().GetTypeInfo().GetGenericMethod(nameof(GenerateAndRegisterMapConverter), 1); var generateArrayConverter = GetType().GetTypeInfo().GetGenericMethod(nameof(GenerateAndRegisterArrayConverter), 1); foreach (var type in assembly.ExportedTypes.Where(x => x.GetTypeInfo().GetCustomAttribute<MsgPackMapAttribute>() != null)) { generateMapConverter.MakeGenericMethod(type).Invoke(this, null); } foreach (var type in assembly.ExportedTypes.Where(x => x.GetTypeInfo().GetCustomAttribute<MsgPackArrayAttribute>() != null)) { generateArrayConverter.MakeGenericMethod(type).Invoke(this, null); } } public void GenerateAndRegisterMapConverter<T>() { var generator = _generatorContext.GenerateMapConverter(typeof(T)); RegisterConverter((IMsgPackConverter<T>) generator); } public void GenerateAndRegisterMapConverter<TInterface, TImplementation>() where TImplementation : TInterface { var generator = _generatorContext.GenerateMapConverter(typeof(TInterface), typeof(TImplementation)); RegisterConverter((IMsgPackConverter<TInterface>)generator); RegisterConverter((IMsgPackConverter<TImplementation>)generator); } public void GenerateAndRegisterArrayConverter<T>() { var generator = _generatorContext.GenerateArrayConverter(typeof(T)); RegisterConverter((IMsgPackConverter<T>)generator); } public void GenerateAndRegisterArrayConverter<TInterface, TImplementation>() where TImplementation : TInterface { var generator = _generatorContext.GenerateArrayConverter(typeof(TInterface), typeof(TImplementation)); RegisterConverter((IMsgPackConverter<TInterface>)generator); RegisterConverter((IMsgPackConverter<TImplementation>)generator); } public void GenerateAndRegisterEnumConverter<T>() { var generator = _generatorContext.GenerateEnumConverter<T>(typeof(T), _convertEnumsAsStrings); RegisterConverter((IMsgPackConverter<T>)generator); } public void RegisterConverter<T>(IMsgPackConverter<T> converter) { converter.Initialize(this); _converters[typeof(T)] = converter; } public void RegisterGenericConverter(Type type) { var converterType = GetGenericInterface(type, typeof(IMsgPackConverter<>)); if (converterType == null) { throw new ArgumentException($"Error registering generic converter. Expected IMsgPackConverter<> implementation, but got {type}"); } var convertedType = converterType.GenericTypeArguments.Single().GetGenericTypeDefinition(); _genericConverters.Add(convertedType, type); } public IMsgPackConverter<T> GetConverter<T>() { var type = typeof(T); var result = (IMsgPackConverter<T>)GetConverterFromCache<T>(); if (result != null) return result; result = (IMsgPackConverter<T>)( TryGenerateEnumConverter<T>(type) ?? TryGenerateConverterFromGenericConverter(type) ?? TryGenerateArrayConverter(type) ?? TryGenerateMapConverter(type) ?? TryGenerateNullableConverter(type)); if (result == null) { throw ExceptionUtils.ConverterNotFound(type); } return result; } private IMsgPackConverter TryGenerateEnumConverter<T>(Type type) { var enumTypeInfo = typeof(T).GetTypeInfo(); if (!enumTypeInfo.IsEnum) { return null; } return _converters .GetOrAdd(type, x => CreateAndInializeConverter(()=>_generatorContext.GenerateEnumConverter<T>(type, _convertEnumsAsStrings))); } public Func<object> GetObjectActivator(Type type) => _objectActivators.GetOrAdd(type, CompiledLambdaActivatorFactory.GetActivator); public ImmutableDictionary<Type, IMsgPackConverter> DumpConvertersCache() => _converters.ToImmutableDictionary(x => x.Key, x => x.Value); private IMsgPackConverter CreateAndInializeConverter(Func<object> converterActivator) { var converter = (IMsgPackConverter)converterActivator(); converter.Initialize(this); return converter; } private IMsgPackConverter TryGenerateConverterFromGenericConverter(Type type) { if (!type.GetTypeInfo().IsGenericType) { return null; } var genericType = type.GetGenericTypeDefinition(); if (!_genericConverters.TryGetValue(genericType, out var genericConverterType)) { return null; } var converterType = genericConverterType.MakeGenericType(type.GenericTypeArguments); return _converters.GetOrAdd(type, x => CreateAndInializeConverter(GetObjectActivator(converterType))); } private IMsgPackConverter TryGenerateMapConverter(Type type) { var mapInterface = GetGenericInterface(type, typeof(IDictionary<,>)); if (mapInterface != null) { return _converters.GetOrAdd(type, x => CreateAndInializeConverter(GetObjectActivator(typeof(MapConverter<,,>).MakeGenericType( x, mapInterface.GenericTypeArguments[0], mapInterface.GenericTypeArguments[1])))); } mapInterface = GetGenericInterface(type, typeof(IReadOnlyDictionary<,>)); if (mapInterface != null) { return _converters.GetOrAdd(type, x => CreateAndInializeConverter(GetObjectActivator(typeof(ReadOnlyMapConverter<,,>).MakeGenericType( x, mapInterface.GenericTypeArguments[0], mapInterface.GenericTypeArguments[1])))); } return null; } private IMsgPackConverter TryGenerateNullableConverter(Type type) { var typeInfo = type.GetTypeInfo(); if (!typeInfo.IsGenericType || typeInfo.GetGenericTypeDefinition() != typeof(Nullable<>)) { return null; } return _converters.GetOrAdd(type, x => CreateAndInializeConverter(GetObjectActivator(typeof(NullableConverter<>).MakeGenericType(x.GetTypeInfo().GenericTypeArguments[0])))); } private IMsgPackConverter TryGenerateArrayConverter(Type type) { var arrayInterface = GetGenericInterface(type, typeof(IList<>)); if (arrayInterface != null) { return _converters.GetOrAdd(type, x => CreateAndInializeConverter(GetObjectActivator(typeof(ArrayConverter<,>).MakeGenericType(x, arrayInterface.GenericTypeArguments[0])))); } arrayInterface = GetGenericInterface(type, typeof(IReadOnlyList<>)); return arrayInterface != null ? _converters.GetOrAdd(type, x => CreateAndInializeConverter(GetObjectActivator(typeof(ReadOnlyListConverter<,>).MakeGenericType(x, arrayInterface.GenericTypeArguments[0])))) : null; } private IMsgPackConverter GetConverterFromCache<T>() { return _converters.TryGetValue(typeof(T), out var temp) ? temp : null; } private static TypeInfo GetGenericInterface(Type type, Type genericInterfaceType) { var info = type.GetTypeInfo(); if (info.IsInterface && info.IsGenericType && info.GetGenericTypeDefinition() == genericInterfaceType) { return info; } return info .ImplementedInterfaces .Select(x => x.GetTypeInfo()) .FirstOrDefault(x => x.IsGenericType && x.GetGenericTypeDefinition() == genericInterfaceType); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // using System; public struct ValX0 { } public struct ValY0 { } public struct ValX1<T> { } public struct ValY1<T> { } public struct ValX2<T, U> { } public struct ValY2<T, U> { } public struct ValX3<T, U, V> { } public struct ValY3<T, U, V> { } public class RefX0 { } public class RefY0 { } public class RefX1<T> { } public class RefY1<T> { } public class RefX2<T, U> { } public class RefY2<T, U> { } public class RefX3<T, U, V> { } public class RefY3<T, U, V> { } public interface IGen<T> { void _Init(T fld1); bool InstVerify(System.Type t1); } public interface IGenSub<T> : IGen<T> { } public class GenInt : IGenSub<int> { int Fld1; public void _Init(int fld1) { Fld1 = fld1; } public bool InstVerify(System.Type t1) { bool result = true; if (!(Fld1.GetType().Equals(t1))) { result = false; Console.WriteLine("Failed to verify type of Fld1 in: " + typeof(IGen<int>)); } return result; } } public class GenDouble : IGen<double> { double Fld1; public void _Init(double fld1) { Fld1 = fld1; } public bool InstVerify(System.Type t1) { bool result = true; if (!(Fld1.GetType().Equals(t1))) { result = false; Console.WriteLine("Failed to verify type of Fld1 in: " + typeof(IGen<double>)); } return result; } } public class GenString : IGen<String> { string Fld1; public void _Init(string fld1) { Fld1 = fld1; } public bool InstVerify(System.Type t1) { bool result = true; if (!(Fld1.GetType().Equals(t1))) { result = false; Console.WriteLine("Failed to verify type of Fld1 in: " + typeof(IGen<string>)); } return result; } } public class GenObject : IGen<object> { object Fld1; public void _Init(object fld1) { Fld1 = fld1; } public bool InstVerify(System.Type t1) { bool result = true; if (!(Fld1.GetType().Equals(t1))) { result = false; Console.WriteLine("Failed to verify type of Fld1 in: " + typeof(IGen<object>)); } return result; } } public class GenGuid : IGen<Guid> { Guid Fld1; public void _Init(Guid fld1) { Fld1 = fld1; } public bool InstVerify(System.Type t1) { bool result = true; if (!(Fld1.GetType().Equals(t1))) { result = false; Console.WriteLine("Failed to verify type of Fld1 in: " + typeof(IGen<Guid>)); } return result; } } public class GenConstructedReference : IGen<RefX1<int>> { RefX1<int> Fld1; public void _Init(RefX1<int> fld1) { Fld1 = fld1; } public bool InstVerify(System.Type t1) { bool result = true; if (!(Fld1.GetType().Equals(t1))) { result = false; Console.WriteLine("Failed to verify type of Fld1 in: " + typeof(IGen<RefX1<int>>)); } return result; } } public class GenConstructedValue : IGen<ValX1<string>> { ValX1<string> Fld1; public void _Init(ValX1<string> fld1) { Fld1 = fld1; } public bool InstVerify(System.Type t1) { bool result = true; if (!(Fld1.GetType().Equals(t1))) { result = false; Console.WriteLine("Failed to verify type of Fld1 in: " + typeof(IGen<ValX1<string>>)); } return result; } } public class Gen1DIntArray : IGen<int[]> { int[] Fld1; public void _Init(int[] fld1) { Fld1 = fld1; } public bool InstVerify(System.Type t1) { bool result = true; if (!(Fld1.GetType().Equals(t1))) { result = false; Console.WriteLine("Failed to verify type of Fld1 in: " + typeof(IGen<int[]>)); } return result; } } public class Gen2DStringArray : IGen<string[,]> { string[,] Fld1; public void _Init(string[,] fld1) { Fld1 = fld1; } public bool InstVerify(System.Type t1) { bool result = true; if (!(Fld1.GetType().Equals(t1))) { result = false; Console.WriteLine("Failed to verify type of Fld1 in: " + typeof(IGen<string[,]>)); } return result; } } public class GenJaggedObjectArray : IGen<object[][]> { object[][] Fld1; public void _Init(object[][] fld1) { Fld1 = fld1; } public bool InstVerify(System.Type t1) { bool result = true; if (!(Fld1.GetType().Equals(t1))) { result = false; Console.WriteLine("Failed to verify type of Fld1 in: " + typeof(IGen<object[][]>)); } return result; } } public class Test { public static int counter = 0; public static bool result = true; public static void Eval(bool exp) { counter++; if (!exp) { result = exp; Console.WriteLine("Test Failed at location: " + counter); } } public static int Main() { IGen<int> IGenInt = new GenInt(); IGenInt._Init(new int()); Eval(IGenInt.InstVerify(typeof(int))); IGen<double> IGenDouble = new GenDouble(); IGenDouble._Init(new double()); Eval(IGenDouble.InstVerify(typeof(double))); IGen<string> IGenString = new GenString(); IGenString._Init("string"); Eval(IGenString.InstVerify(typeof(string))); IGen<object> IGenObject = new GenObject(); IGenObject._Init(new object()); Eval(IGenObject.InstVerify(typeof(object))); IGen<Guid> IGenGuid = new GenGuid(); IGenGuid._Init(new Guid()); Eval(IGenGuid.InstVerify(typeof(Guid))); IGen<RefX1<int>> IGenConstructedReference = new GenConstructedReference(); IGenConstructedReference._Init(new RefX1<int>()); Eval(IGenConstructedReference.InstVerify(typeof(RefX1<int>))); IGen<ValX1<string>> IGenConstructedValue = new GenConstructedValue(); IGenConstructedValue._Init(new ValX1<string>()); Eval(IGenConstructedValue.InstVerify(typeof(ValX1<string>))); IGen<int[]> IGen1DIntArray = new Gen1DIntArray(); IGen1DIntArray._Init(new int[1]); Eval(IGen1DIntArray.InstVerify(typeof(int[]))); IGen<string[,]> IGen2DStringArray = new Gen2DStringArray(); IGen2DStringArray._Init(new string[1, 1]); Eval(IGen2DStringArray.InstVerify(typeof(string[,]))); IGen<object[][]> IGenJaggedObjectArray = new GenJaggedObjectArray(); IGenJaggedObjectArray._Init(new object[1][]); Eval(IGenJaggedObjectArray.InstVerify(typeof(object[][]))); if (result) { Console.WriteLine("Test Passed"); return 100; } else { Console.WriteLine("Test Failed"); return 1; } } }
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 LangChat.Areas.HelpPage.ModelDescriptions; using LangChat.Areas.HelpPage.Models; namespace LangChat.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); } } } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gax = Google.Api.Gax; using gagr = Google.Api.Gax.ResourceNames; using gcrv = Google.Cloud.Redis.V1; using sys = System; namespace Google.Cloud.Redis.V1 { /// <summary>Resource name for the <c>Instance</c> resource.</summary> public sealed partial class InstanceName : gax::IResourceName, sys::IEquatable<InstanceName> { /// <summary>The possible contents of <see cref="InstanceName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern <c>projects/{project}/locations/{location}/instances/{instance}</c>. /// </summary> ProjectLocationInstance = 1, } private static gax::PathTemplate s_projectLocationInstance = new gax::PathTemplate("projects/{project}/locations/{location}/instances/{instance}"); /// <summary>Creates a <see cref="InstanceName"/> containing an unparsed resource name.</summary> /// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param> /// <returns> /// A new instance of <see cref="InstanceName"/> containing the provided <paramref name="unparsedResourceName"/> /// . /// </returns> public static InstanceName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new InstanceName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="InstanceName"/> with the pattern /// <c>projects/{project}/locations/{location}/instances/{instance}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="instanceId">The <c>Instance</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="InstanceName"/> constructed from the provided ids.</returns> public static InstanceName FromProjectLocationInstance(string projectId, string locationId, string instanceId) => new InstanceName(ResourceNameType.ProjectLocationInstance, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), instanceId: gax::GaxPreconditions.CheckNotNullOrEmpty(instanceId, nameof(instanceId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="InstanceName"/> with pattern /// <c>projects/{project}/locations/{location}/instances/{instance}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="instanceId">The <c>Instance</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="InstanceName"/> with pattern /// <c>projects/{project}/locations/{location}/instances/{instance}</c>. /// </returns> public static string Format(string projectId, string locationId, string instanceId) => FormatProjectLocationInstance(projectId, locationId, instanceId); /// <summary> /// Formats the IDs into the string representation of this <see cref="InstanceName"/> with pattern /// <c>projects/{project}/locations/{location}/instances/{instance}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="instanceId">The <c>Instance</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="InstanceName"/> with pattern /// <c>projects/{project}/locations/{location}/instances/{instance}</c>. /// </returns> public static string FormatProjectLocationInstance(string projectId, string locationId, string instanceId) => s_projectLocationInstance.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(instanceId, nameof(instanceId))); /// <summary>Parses the given resource name string into a new <see cref="InstanceName"/> instance.</summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>projects/{project}/locations/{location}/instances/{instance}</c></description></item> /// </list> /// </remarks> /// <param name="instanceName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="InstanceName"/> if successful.</returns> public static InstanceName Parse(string instanceName) => Parse(instanceName, false); /// <summary> /// Parses the given resource name string into a new <see cref="InstanceName"/> instance; optionally allowing an /// unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>projects/{project}/locations/{location}/instances/{instance}</c></description></item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="instanceName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <returns>The parsed <see cref="InstanceName"/> if successful.</returns> public static InstanceName Parse(string instanceName, bool allowUnparsed) => TryParse(instanceName, allowUnparsed, out InstanceName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern."); /// <summary> /// Tries to parse the given resource name string into a new <see cref="InstanceName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>projects/{project}/locations/{location}/instances/{instance}</c></description></item> /// </list> /// </remarks> /// <param name="instanceName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="InstanceName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string instanceName, out InstanceName result) => TryParse(instanceName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="InstanceName"/> instance; optionally /// allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>projects/{project}/locations/{location}/instances/{instance}</c></description></item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="instanceName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <param name="result"> /// When this method returns, the parsed <see cref="InstanceName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string instanceName, bool allowUnparsed, out InstanceName result) { gax::GaxPreconditions.CheckNotNull(instanceName, nameof(instanceName)); gax::TemplatedResourceName resourceName; if (s_projectLocationInstance.TryParseName(instanceName, out resourceName)) { result = FromProjectLocationInstance(resourceName[0], resourceName[1], resourceName[2]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(instanceName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private InstanceName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string instanceId = null, string locationId = null, string projectId = null) { Type = type; UnparsedResource = unparsedResourceName; InstanceId = instanceId; LocationId = locationId; ProjectId = projectId; } /// <summary> /// Constructs a new instance of a <see cref="InstanceName"/> class from the component parts of pattern /// <c>projects/{project}/locations/{location}/instances/{instance}</c> /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="instanceId">The <c>Instance</c> ID. Must not be <c>null</c> or empty.</param> public InstanceName(string projectId, string locationId, string instanceId) : this(ResourceNameType.ProjectLocationInstance, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), instanceId: gax::GaxPreconditions.CheckNotNullOrEmpty(instanceId, nameof(instanceId))) { } /// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary> public ResourceNameType Type { get; } /// <summary> /// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an /// unparsed resource name. /// </summary> public gax::UnparsedResourceName UnparsedResource { get; } /// <summary> /// The <c>Instance</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string InstanceId { get; } /// <summary> /// The <c>Location</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string LocationId { get; } /// <summary> /// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string ProjectId { get; } /// <summary>Whether this instance contains a resource name with a known pattern.</summary> public bool IsKnownPattern => Type != ResourceNameType.Unparsed; /// <summary>The string representation of the resource name.</summary> /// <returns>The string representation of the resource name.</returns> public override string ToString() { switch (Type) { case ResourceNameType.Unparsed: return UnparsedResource.ToString(); case ResourceNameType.ProjectLocationInstance: return s_projectLocationInstance.Expand(ProjectId, LocationId, InstanceId); default: throw new sys::InvalidOperationException("Unrecognized resource-type."); } } /// <summary>Returns a hash code for this resource name.</summary> public override int GetHashCode() => ToString().GetHashCode(); /// <inheritdoc/> public override bool Equals(object obj) => Equals(obj as InstanceName); /// <inheritdoc/> public bool Equals(InstanceName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(InstanceName a, InstanceName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(InstanceName a, InstanceName b) => !(a == b); } public partial class Instance { /// <summary> /// <see cref="gcrv::InstanceName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcrv::InstanceName InstanceName { get => string.IsNullOrEmpty(Name) ? null : gcrv::InstanceName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class ListInstancesRequest { /// <summary> /// <see cref="gagr::LocationName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public gagr::LocationName ParentAsLocationName { get => string.IsNullOrEmpty(Parent) ? null : gagr::LocationName.Parse(Parent, allowUnparsed: true); set => Parent = value?.ToString() ?? ""; } } public partial class GetInstanceRequest { /// <summary> /// <see cref="gcrv::InstanceName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcrv::InstanceName InstanceName { get => string.IsNullOrEmpty(Name) ? null : gcrv::InstanceName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class CreateInstanceRequest { /// <summary> /// <see cref="gagr::LocationName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public gagr::LocationName ParentAsLocationName { get => string.IsNullOrEmpty(Parent) ? null : gagr::LocationName.Parse(Parent, allowUnparsed: true); set => Parent = value?.ToString() ?? ""; } } public partial class UpgradeInstanceRequest { /// <summary> /// <see cref="gcrv::InstanceName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcrv::InstanceName InstanceName { get => string.IsNullOrEmpty(Name) ? null : gcrv::InstanceName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class DeleteInstanceRequest { /// <summary> /// <see cref="gcrv::InstanceName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcrv::InstanceName InstanceName { get => string.IsNullOrEmpty(Name) ? null : gcrv::InstanceName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class FailoverInstanceRequest { /// <summary> /// <see cref="gcrv::InstanceName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcrv::InstanceName InstanceName { get => string.IsNullOrEmpty(Name) ? null : gcrv::InstanceName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } }
/* * 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 Mono.Addins; using System; using System.Collections; using System.Collections.Generic; using System.Reflection; using Nini.Config; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Services.Connectors; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Server.Base; using OpenSim.Services.Interfaces; using GridRegion = OpenSim.Services.Interfaces.GridRegion; namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Grid { [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "RemoteGridServicesConnector")] public class RemoteGridServicesConnector : ISharedRegionModule, IGridService { private static readonly ILog m_log = LogManager.GetLogger( MethodBase.GetCurrentMethod().DeclaringType); private bool m_Enabled = false; private IGridService m_LocalGridService; private IGridService m_RemoteGridService; private RegionInfoCache m_RegionInfoCache = new RegionInfoCache(); public RemoteGridServicesConnector() { } public RemoteGridServicesConnector(IConfigSource source) { InitialiseServices(source); } #region ISharedRegionmodule public Type ReplaceableInterface { get { return null; } } public string Name { get { return "RemoteGridServicesConnector"; } } public void Initialise(IConfigSource source) { IConfig moduleConfig = source.Configs["Modules"]; if (moduleConfig != null) { string name = moduleConfig.GetString("GridServices", ""); if (name == Name) { InitialiseServices(source); m_Enabled = true; m_log.Info("[REMOTE GRID CONNECTOR]: Remote grid enabled"); } } } private void InitialiseServices(IConfigSource source) { IConfig gridConfig = source.Configs["GridService"]; if (gridConfig == null) { m_log.Error("[REMOTE GRID CONNECTOR]: GridService missing from OpenSim.ini"); return; } string networkConnector = gridConfig.GetString("NetworkConnector", string.Empty); if (networkConnector == string.Empty) { m_log.Error("[REMOTE GRID CONNECTOR]: Please specify a network connector under [GridService]"); return; } Object[] args = new Object[] { source }; m_RemoteGridService = ServerUtils.LoadPlugin<IGridService>(networkConnector, args); m_LocalGridService = new LocalGridServicesConnector(source); } public void PostInitialise() { if (m_LocalGridService != null) ((ISharedRegionModule)m_LocalGridService).PostInitialise(); } public void Close() { } public void AddRegion(Scene scene) { if (m_Enabled) scene.RegisterModuleInterface<IGridService>(this); if (m_LocalGridService != null) ((ISharedRegionModule)m_LocalGridService).AddRegion(scene); } public void RemoveRegion(Scene scene) { if (m_LocalGridService != null) ((ISharedRegionModule)m_LocalGridService).RemoveRegion(scene); } public void RegionLoaded(Scene scene) { } #endregion #region IGridService public string RegisterRegion(UUID scopeID, GridRegion regionInfo) { string msg = m_LocalGridService.RegisterRegion(scopeID, regionInfo); if (msg == String.Empty) return m_RemoteGridService.RegisterRegion(scopeID, regionInfo); return msg; } public bool DeregisterRegion(UUID regionID) { if (m_LocalGridService.DeregisterRegion(regionID)) return m_RemoteGridService.DeregisterRegion(regionID); return false; } public List<GridRegion> GetNeighbours(UUID scopeID, UUID regionID) { return m_RemoteGridService.GetNeighbours(scopeID, regionID); } public GridRegion GetRegionByUUID(UUID scopeID, UUID regionID) { bool inCache = false; GridRegion rinfo = m_RegionInfoCache.Get(scopeID,regionID,out inCache); if (inCache) return rinfo; rinfo = m_LocalGridService.GetRegionByUUID(scopeID, regionID); if (rinfo == null) rinfo = m_RemoteGridService.GetRegionByUUID(scopeID, regionID); m_RegionInfoCache.Cache(scopeID,regionID,rinfo); return rinfo; } // Get a region given its base world coordinates (in meters). // NOTE: this is NOT 'get a region by some point in the region'. The coordinate MUST // be the base coordinate of the region. // The coordinates are world coords (meters), NOT region units. public GridRegion GetRegionByPosition(UUID scopeID, int x, int y) { ulong regionHandle = Util.RegionWorldLocToHandle((uint)x, (uint)y); uint regionX = Util.WorldToRegionLoc((uint)x); uint regionY = Util.WorldToRegionLoc((uint)y); // Sanity check if ((Util.RegionToWorldLoc(regionX) != (uint)x) || (Util.RegionToWorldLoc(regionY) != (uint)y)) { m_log.WarnFormat("[REMOTE GRID CONNECTOR]: GetRegionByPosition. Bad position requested: not the base of the region. Requested Pos=<{0},{1}>, Should Be=<{2},{3}>", x, y, Util.RegionToWorldLoc(regionX), Util.RegionToWorldLoc(regionY)); } bool inCache = false; GridRegion rinfo = m_RegionInfoCache.Get(scopeID, regionHandle, out inCache); if (inCache) { m_log.DebugFormat("[REMOTE GRID CONNECTOR]: GetRegionByPosition. Found region {0} in cache. Pos=<{1},{2}>, RegionHandle={3}", (rinfo == null) ? "<missing>" : rinfo.RegionName, regionX, regionY, (rinfo == null) ? regionHandle : rinfo.RegionHandle); return rinfo; } rinfo = m_LocalGridService.GetRegionByPosition(scopeID, x, y); if (rinfo == null) rinfo = m_RemoteGridService.GetRegionByPosition(scopeID, x, y); m_RegionInfoCache.Cache(rinfo); m_log.DebugFormat("[REMOTE GRID CONNECTOR]: GetRegionByPosition. Added region {0} to the cache. Pos=<{1},{2}>, RegionHandle={3}", (rinfo == null) ? "<missing>" : rinfo.RegionName, regionX, regionY, (rinfo == null) ? regionHandle : rinfo.RegionHandle); return rinfo; } public GridRegion GetRegionByName(UUID scopeID, string regionName) { bool inCache = false; GridRegion rinfo = m_RegionInfoCache.Get(scopeID,regionName, out inCache); if (inCache) return rinfo; rinfo = m_LocalGridService.GetRegionByName(scopeID, regionName); if (rinfo == null) rinfo = m_RemoteGridService.GetRegionByName(scopeID, regionName); // can't cache negative results for name lookups m_RegionInfoCache.Cache(rinfo); return rinfo; } public List<GridRegion> GetRegionsByName(UUID scopeID, string name, int maxNumber) { List<GridRegion> rinfo = m_LocalGridService.GetRegionsByName(scopeID, name, maxNumber); //m_log.DebugFormat("[REMOTE GRID CONNECTOR]: Local GetRegionsByName {0} found {1} regions", name, rinfo.Count); List<GridRegion> grinfo = m_RemoteGridService.GetRegionsByName(scopeID, name, maxNumber); if (grinfo != null) { //m_log.DebugFormat("[REMOTE GRID CONNECTOR]: Remote GetRegionsByName {0} found {1} regions", name, grinfo.Count); foreach (GridRegion r in grinfo) { m_RegionInfoCache.Cache(r); if (rinfo.Find(delegate(GridRegion gr) { return gr.RegionID == r.RegionID; }) == null) rinfo.Add(r); } } return rinfo; } public virtual List<GridRegion> GetRegionRange(UUID scopeID, int xmin, int xmax, int ymin, int ymax) { List<GridRegion> rinfo = m_LocalGridService.GetRegionRange(scopeID, xmin, xmax, ymin, ymax); //m_log.DebugFormat("[REMOTE GRID CONNECTOR]: Local GetRegionRange {0} found {1} regions", name, rinfo.Count); List<GridRegion> grinfo = m_RemoteGridService.GetRegionRange(scopeID, xmin, xmax, ymin, ymax); if (grinfo != null) { //m_log.DebugFormat("[REMOTE GRID CONNECTOR]: Remote GetRegionRange {0} found {1} regions", name, grinfo.Count); foreach (GridRegion r in grinfo) { m_RegionInfoCache.Cache(r); if (rinfo.Find(delegate(GridRegion gr) { return gr.RegionID == r.RegionID; }) == null) rinfo.Add(r); } } return rinfo; } public List<GridRegion> GetDefaultRegions(UUID scopeID) { List<GridRegion> rinfo = m_LocalGridService.GetDefaultRegions(scopeID); //m_log.DebugFormat("[REMOTE GRID CONNECTOR]: Local GetDefaultRegions {0} found {1} regions", name, rinfo.Count); List<GridRegion> grinfo = m_RemoteGridService.GetDefaultRegions(scopeID); if (grinfo != null) { //m_log.DebugFormat("[REMOTE GRID CONNECTOR]: Remote GetDefaultRegions {0} found {1} regions", name, grinfo.Count); foreach (GridRegion r in grinfo) { m_RegionInfoCache.Cache(r); if (rinfo.Find(delegate(GridRegion gr) { return gr.RegionID == r.RegionID; }) == null) rinfo.Add(r); } } return rinfo; } public List<GridRegion> GetDefaultHypergridRegions(UUID scopeID) { List<GridRegion> rinfo = m_LocalGridService.GetDefaultHypergridRegions(scopeID); //m_log.DebugFormat("[REMOTE GRID CONNECTOR]: Local GetDefaultHypergridRegions {0} found {1} regions", name, rinfo.Count); List<GridRegion> grinfo = m_RemoteGridService.GetDefaultHypergridRegions(scopeID); if (grinfo != null) { //m_log.DebugFormat("[REMOTE GRID CONNECTOR]: Remote GetDefaultHypergridRegions {0} found {1} regions", name, grinfo.Count); foreach (GridRegion r in grinfo) { m_RegionInfoCache.Cache(r); if (rinfo.Find(delegate(GridRegion gr) { return gr.RegionID == r.RegionID; }) == null) rinfo.Add(r); } } return rinfo; } public List<GridRegion> GetFallbackRegions(UUID scopeID, int x, int y) { List<GridRegion> rinfo = m_LocalGridService.GetFallbackRegions(scopeID, x, y); //m_log.DebugFormat("[REMOTE GRID CONNECTOR]: Local GetFallbackRegions {0} found {1} regions", name, rinfo.Count); List<GridRegion> grinfo = m_RemoteGridService.GetFallbackRegions(scopeID, x, y); if (grinfo != null) { //m_log.DebugFormat("[REMOTE GRID CONNECTOR]: Remote GetFallbackRegions {0} found {1} regions", name, grinfo.Count); foreach (GridRegion r in grinfo) { m_RegionInfoCache.Cache(r); if (rinfo.Find(delegate(GridRegion gr) { return gr.RegionID == r.RegionID; }) == null) rinfo.Add(r); } } return rinfo; } public List<GridRegion> GetHyperlinks(UUID scopeID) { List<GridRegion> rinfo = m_LocalGridService.GetHyperlinks(scopeID); //m_log.DebugFormat("[REMOTE GRID CONNECTOR]: Local GetHyperlinks {0} found {1} regions", name, rinfo.Count); List<GridRegion> grinfo = m_RemoteGridService.GetHyperlinks(scopeID); if (grinfo != null) { //m_log.DebugFormat("[REMOTE GRID CONNECTOR]: Remote GetHyperlinks {0} found {1} regions", name, grinfo.Count); foreach (GridRegion r in grinfo) { m_RegionInfoCache.Cache(r); if (rinfo.Find(delegate(GridRegion gr) { return gr.RegionID == r.RegionID; }) == null) rinfo.Add(r); } } return rinfo; } public int GetRegionFlags(UUID scopeID, UUID regionID) { int flags = m_LocalGridService.GetRegionFlags(scopeID, regionID); if (flags == -1) flags = m_RemoteGridService.GetRegionFlags(scopeID, regionID); return flags; } public Dictionary<string, object> GetExtraFeatures() { Dictionary<string, object> extraFeatures; extraFeatures = m_LocalGridService.GetExtraFeatures(); if (extraFeatures.Count == 0) extraFeatures = m_RemoteGridService.GetExtraFeatures(); return extraFeatures; } #endregion } }
// Copyright (c) 2021 Alachisoft // // 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 Alachisoft.NCache.ServiceControl; using Alachisoft.NCache.Runtime.Exceptions; using Alachisoft.NCache.Common; using Alachisoft.NCache.Management.ServiceControl; using Alachisoft.NCache.Management.ClientConfiguration.Dom; using System.Collections.Generic; using Alachisoft.NCache.Config.Dom; using System.Collections; using Alachisoft.NCache.Common.Monitoring; using Alachisoft.NCache.Common.CacheManagement; using Alachisoft.NCache.Caching.Statistics; using Alachisoft.NCache.Common.Net; using Alachisoft.NCache.Common.Topologies.Clustered; using System.Net; using Alachisoft.NCache.Common.ErrorHandling; namespace Alachisoft.NCache.Management { /// <summary> /// Provides the public interface for the CacheServer. /// </summary> /// public class CacheServerModerator { static string config="client.ncconf"; private static string LOCALCACHE = "local-cache"; private static string CLUSTEREDCACHE = "clustered-cache"; public static void StartCache(string cacheId, string serverName, int port, string userId, string password) { ICacheServer cs = null; CacheService cacheService = new NCacheRPCService(null); CacheServerConfig config = null; try { cacheService.ServerName = serverName; cacheService.Port = port; cs = cacheService.GetCacheServer(new TimeSpan(0, 0, 0, 30)); if (cs != null) { config = cs.GetCacheConfiguration(cacheId); if (config != null) { if (!config.InProc) cs.StartCache(cacheId); } else throw new ManagementException("Unable to Start Cache. Specified cache is not registered."); } } catch (SecurityException ex) { if (cs != null) { cs.Dispose(); cs = null; } throw ex; } catch (Exception ex) { if (cs != null) { cs.Dispose(); cs = null; } throw new ManagementException(ex.Message); } finally { if (cs != null) cs.Dispose(); cacheService.Dispose(); } } public static void StopCache(string cacheId, string serverName, int port, string userId, string password) { ICacheServer cs = null; CacheService cacheService = new NCacheRPCService(null); try { cacheService.ServerName = serverName; cacheService.Port = port; cs = cacheService.GetCacheServer(new TimeSpan(0, 0, 0, 30)); if (cs != null) { cs.StopCache(cacheId); } } catch (SecurityException ex) { if (cs != null) { cs.Dispose(); cs = null; } throw ex; } catch (Exception ex) { if (cs != null) { cs.Dispose(); cs = null; } throw new ManagementException(ex.Message); } finally { if (cs != null) cs.Dispose(); cacheService.Dispose(); } } public static Dictionary<Runtime.CacheManagement.ServerNode, List<Runtime.Caching.ClientInfo>> GetCacheClients(string cacheName, string initialNodeName, Common.CacheManagement.CacheContext context, int port) { CacheService cacheService = GetCacheService(context); if (port != 0) cacheService.Port = port; string startingNode = initialNodeName; Alachisoft.NCache.Config.Dom.CacheServerConfig cacheServerConfig = null; Alachisoft.NCache.Management.ICacheServer cacheServer = null; Dictionary<Runtime.CacheManagement.ServerNode, List<Runtime.Caching.ClientInfo>> clientList = new Dictionary<Runtime.CacheManagement.ServerNode, List<Runtime.Caching.ClientInfo>>(); try { if (initialNodeName.Equals(string.Empty)) { cacheServerConfig = GetCacheConfigThroughClientConfig(cacheName,port,context); if (cacheServerConfig == null) throw new ManagementException("cache with name " + cacheName + " not found in " + config); } else { cacheService.ServerName = initialNodeName; cacheServer = cacheService.GetCacheServer(new TimeSpan(0, 0, 0, 30)); if (cacheServer == null) throw new ManagementException("provided initial node not available"); cacheServerConfig = cacheServer.GetCacheConfiguration(cacheName); if (cacheServerConfig == null) throw new ManagementException(ErrorCodes.CacheInit.CACHE_NOT_REGISTERED_ON_NODE,ErrorMessages.GetErrorMessage(ErrorCodes.CacheInit.CACHE_NOT_REGISTERED_ON_NODE,cacheName)); } //Copied Code from NCManager //For Local Cache if (cacheServerConfig.CacheType.Equals(LOCALCACHE, StringComparison.OrdinalIgnoreCase)) { if (cacheServerConfig.InProc) throw new ArgumentException("API is not supported for Local Inproc Cache"); cacheService.ServerName = Environment.MachineName; cacheServer = cacheService.GetCacheServer(new TimeSpan(0, 0, 0, 30)); if (cacheServer != null) { if (cacheServer.IsRunning(cacheName)) { Runtime.CacheManagement.ServerNode serverNode = new Runtime.CacheManagement.ServerNode(); serverNode.ServerIP = Environment.MachineName; List<Alachisoft.NCache.Common.Monitoring.ClientProcessStats> clients = cacheServer.GetClientProcessStats(cacheServerConfig.Name); List<Runtime.Caching.ClientInfo> list = new List<Runtime.Caching.ClientInfo>(); foreach (Alachisoft.NCache.Common.Monitoring.ClientProcessStats clientNode in clients) { Runtime.Caching.ClientInfo clientInfo = new Runtime.Caching.ClientInfo(); clientInfo.IPAddress = clientNode.Address.IpAddress; clientInfo.ProcessID = Int32.Parse(clientNode.ProcessID); list.Add(clientInfo); } clientList.Add(serverNode, list); } } return clientList; } //For Clustered Cache else { ArrayList initialHost = InitialHostList(cacheServerConfig.Cluster.Channel.InitialHosts); foreach (object host in initialHost) { try { cacheService.ServerName = (string)host; cacheServer = cacheService.GetCacheServer(new TimeSpan(0, 0, 0, 30)); if (cacheServer.IsRunning(cacheName)) { Runtime.CacheManagement.ServerNode serverNode = new Runtime.CacheManagement.ServerNode(); serverNode.ServerIP = host as string; serverNode.Port = cacheServerConfig.Cluster.Channel.TcpPort; List<Alachisoft.NCache.Common.Monitoring.ClientProcessStats> clients = cacheServer.GetClientProcessStats(cacheServerConfig.Name); List<Runtime.Caching.ClientInfo> list = new List<Runtime.Caching.ClientInfo>(); foreach (Alachisoft.NCache.Common.Monitoring.ClientProcessStats clientNode in clients) { Runtime.Caching.ClientInfo clientInfo = new Runtime.Caching.ClientInfo(); clientInfo.IPAddress = clientNode.Address.IpAddress; clientInfo.ProcessID = Int32.Parse(clientNode.ProcessID); list.Add(clientInfo); } clientList.Add(serverNode, list); } } catch (Exception e) { } } return clientList; } } catch (Exception ex) { throw new ManagementException(ex.Message); } finally { if (cacheServer != null) cacheServer.Dispose(); cacheService.Dispose(); } } private static CacheService GetCacheService(Common.CacheManagement.CacheContext context) { switch (context) { case Common.CacheManagement.CacheContext.TayzGrid: return new JvCacheRPCService(null); case Common.CacheManagement.CacheContext.NCache: return new NCacheRPCService(null); } return null; } private static CacheService GetCacheService(string initialNodeName, int port, CacheContext context) { CacheService cacheService = GetCacheService(context); if (port != 0) cacheService.Port = port; cacheService.ServerName = initialNodeName; return cacheService; } private static ArrayList InitialHostList(string initialHostsColl) { ArrayList list = new ArrayList(5); string[] commaSplit = initialHostsColl.Split(','); foreach (string initialHost in commaSplit) { string[] split = initialHost.Split('[', ']'); list.Add(split[0]); } return list; } private static Runtime.CacheManagement.CacheTopology GetCacheTopology(string topologyType) { switch (topologyType) { case "replicated": case "replicated-server": return Runtime.CacheManagement.CacheTopology.Replicated; case "partitioned": case "partitioned-server": return Runtime.CacheManagement.CacheTopology.Partitioned; default: return Runtime.CacheManagement.CacheTopology.Local; } } private static CacheServerConfig GetCacheConfigThroughClientConfig(string cacheName, int port, Common.CacheManagement.CacheContext context) { CacheServerConfig cacheServerConfig = null; ClientConfiguration.Dom.CacheServer[] serverNodes = null; ICacheServer cacheServer = null; CacheService cacheService = GetCacheService(context); if (port != 0) cacheService.Port = port; try { //Get Server Info from Client.nconf for specified cacheName ClientConfiguration.Dom.ClientConfiguration clientConfiguration = ClientConfiguration.ClientConfigManager.GetClientConfiguration(cacheName); if (clientConfiguration != null) { Dictionary<string, CacheConfiguration> cacheConfigurationMap = clientConfiguration.CacheConfigurationsMap; CacheConfiguration cacheClientConfiguration = null; try { cacheClientConfiguration = cacheConfigurationMap[cacheName]; } catch (System.Collections.Generic.KeyNotFoundException ex) { } if (cacheClientConfiguration == null) throw new ManagementException("cache not found in " + config); serverNodes = cacheClientConfiguration.Servers; foreach (ClientConfiguration.Dom.CacheServer node in serverNodes) { try { cacheService.ServerName = node.ServerName; cacheServer = cacheService.GetCacheServer(new TimeSpan(0, 0, 0, 30)); if (cacheServer != null) { cacheServerConfig = cacheServer.GetCacheConfiguration(cacheName); cacheServer.Dispose(); cacheServer = null; if (cacheServerConfig != null) break; } } catch (Exception ex) { } } } else { throw new ManagementException("error while fetching info from " + config); } } finally { if ( cacheServer !=null ) cacheServer.Dispose(); if( cacheService !=null) cacheService.Dispose(); } return cacheServerConfig; } internal static Dictionary<string, TopicStats> GetTopicStat(string cacheName, string initialNodeName, Common.CacheManagement.CacheContext context, int port) { CacheService cacheService = GetCacheService(context); if (port != 0) cacheService.Port = port; string startingNode = initialNodeName; CacheServerConfig cacheServerConfig = null; ICacheServer cacheServer = null; try { if (initialNodeName.Equals(string.Empty)) { cacheServerConfig = GetCacheConfigThroughClientConfig(cacheName, port, context); if (cacheServerConfig == null) throw new ManagementException("cache with name " + cacheName + " not found in " + config); } else { cacheService.ServerName = initialNodeName; cacheServer = cacheService.GetCacheServer(new TimeSpan(0, 0, 0, 30)); if (cacheServer == null) throw new ManagementException("provided initial node not available"); cacheServerConfig = cacheServer.GetCacheConfiguration(cacheName); if (cacheServerConfig == null) throw new ManagementException(ErrorCodes.CacheInit.CACHE_NOT_REGISTERED_ON_NODE, ErrorMessages.GetErrorMessage(ErrorCodes.CacheInit.CACHE_NOT_REGISTERED_ON_NODE, cacheName)); } //For Local Cache if (cacheServerConfig.CacheType.Equals(LOCALCACHE, StringComparison.OrdinalIgnoreCase)) { if (cacheServerConfig.InProc) throw new ArgumentException("API is not supported for Local Inproc Cache"); cacheService.ServerName = Environment.MachineName; cacheServer = cacheService.GetCacheServer(new TimeSpan(0, 0, 0, 30)); if (cacheServer != null && cacheServer.IsRunning(cacheName)) { return cacheServer.GetTopicStats(cacheServerConfig.Name); } } //For Clustered Cache else { Dictionary<string, TopicStats> topicWiseStat = new Dictionary<string, TopicStats>(); ArrayList initialHost = InitialHostList(cacheServerConfig.Cluster.Channel.InitialHosts); foreach (object host in initialHost) { try { cacheService.ServerName = (string)host; cacheServer = cacheService.GetCacheServer(new TimeSpan(0, 0, 0, 30)); if (cacheServer.IsRunning(cacheName)) { Dictionary<string, TopicStats> NodeWisetopicStat = cacheServer.GetTopicStats(cacheServerConfig.Name); if (NodeWisetopicStat != null) { foreach (var item in NodeWisetopicStat) { if (!topicWiseStat.ContainsKey(item.Key)) { item.Value.TopicName = item.Key; topicWiseStat.Add(item.Key, ((TopicStats)item.Value.Clone())); } else { TopicStats topicStat = topicWiseStat[item.Key]; topicStat.CurrentMessageCount += item.Value.CurrentMessageCount; } } } } } catch (Exception e) { } } return topicWiseStat; } } catch (Exception ex) { throw new ManagementException(ex.Message); } finally { if (cacheServer != null) cacheServer.Dispose(); cacheService.Dispose(); } return null; } } }
// ----------------------------------------------------------------------------------------- // <copyright file="ExpressionWriter.cs" company="Microsoft"> // Copyright 2013 Microsoft 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. // </copyright> // ----------------------------------------------------------------------------------------- namespace Sandboxable.Microsoft.WindowsAzure.Storage.Table.Queryable { #region Namespaces. using Sandboxable.Microsoft.WindowsAzure.Storage.Core; using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Linq.Expressions; using System.Reflection; using System.Text; #endregion Namespaces. internal class ExpressionWriter : DataServiceALinqExpressionVisitor { #region Private fields. private readonly StringBuilder builder; private readonly Stack<Expression> expressionStack; private bool cantTranslateExpression; private Expression parent; #endregion Private fields. private ExpressionWriter() { this.builder = new StringBuilder(); this.expressionStack = new Stack<Expression>(); this.expressionStack.Push(null); } internal static string ExpressionToString(Expression e) { ExpressionWriter ew = new ExpressionWriter(); string serialized = null; serialized = ew.Translate(e); if (ew.cantTranslateExpression) { throw new NotSupportedException(string.Format(CultureInfo.CurrentCulture, SR.ALinqCantTranslateExpression, e.ToString())); } return serialized; } internal override Expression Visit(Expression exp) { this.parent = this.expressionStack.Peek(); this.expressionStack.Push(exp); Expression result = base.Visit(exp); this.expressionStack.Pop(); return result; } internal override Expression VisitConditional(ConditionalExpression c) { this.cantTranslateExpression = true; return c; } internal override Expression VisitLambda(LambdaExpression lambda) { this.cantTranslateExpression = true; return lambda; } internal override NewExpression VisitNew(NewExpression nex) { this.cantTranslateExpression = true; return nex; } internal override Expression VisitMemberInit(MemberInitExpression init) { this.cantTranslateExpression = true; return init; } internal override Expression VisitListInit(ListInitExpression init) { this.cantTranslateExpression = true; return init; } internal override Expression VisitNewArray(NewArrayExpression na) { this.cantTranslateExpression = true; return na; } internal override Expression VisitInvocation(InvocationExpression iv) { this.cantTranslateExpression = true; return iv; } internal override Expression VisitInputReferenceExpression(InputReferenceExpression ire) { Debug.Assert(ire != null, "ire != null"); if (this.parent == null || this.parent.NodeType != ExpressionType.MemberAccess) { string expressionText = (this.parent != null) ? this.parent.ToString() : ire.ToString(); throw new NotSupportedException(string.Format(CultureInfo.CurrentCulture, SR.ALinqCantTranslateExpression, expressionText)); } return ire; } internal override Expression VisitMethodCall(MethodCallExpression m) { string methodName; if (TypeSystem.TryGetQueryOptionMethod(m.Method, out methodName)) { this.builder.Append(methodName); this.builder.Append(UriHelper.LEFTPAREN); if (methodName == "substringof") { Debug.Assert(m.Method.Name == "Contains", "m.Method.Name == 'Contains'"); Debug.Assert(m.Object != null, "m.Object != null"); Debug.Assert(m.Arguments.Count == 1, "m.Arguments.Count == 1"); this.Visit(m.Arguments[0]); this.builder.Append(UriHelper.COMMA); this.Visit(m.Object); } else { if (m.Object != null) { this.Visit(m.Object); } if (m.Arguments.Count > 0) { if (m.Object != null) { this.builder.Append(UriHelper.COMMA); } for (int ii = 0; ii < m.Arguments.Count; ii++) { this.Visit(m.Arguments[ii]); if (ii < m.Arguments.Count - 1) { this.builder.Append(UriHelper.COMMA); } } } } this.builder.Append(UriHelper.RIGHTPAREN); } else { this.cantTranslateExpression = true; } return m; } internal override Expression VisitMemberAccess(MemberExpression m) { if (m.Member is FieldInfo) { throw new NotSupportedException(string.Format(CultureInfo.CurrentCulture, SR.ALinqCantReferToPublicField, m.Member.Name)); } if (m.Member.DeclaringType == typeof(EntityProperty)) { MethodCallExpression mce = m.Expression as MethodCallExpression; if (mce != null && mce.Arguments.Count == 1 && mce.Method == ReflectionUtil.DictionaryGetItemMethodInfo) { MemberExpression me = mce.Object as MemberExpression; if (me != null && me.Member.DeclaringType == typeof(DynamicTableEntity) && me.Member.Name == "Properties") { // Append Property name arg to string ConstantExpression ce = mce.Arguments[0] as ConstantExpression; if (ce == null || !(ce.Value is string)) { throw new NotSupportedException(SR.TableQueryDynamicPropertyAccess); } this.builder.Append((string)ce.Value); return ce; } } throw new NotSupportedException(SR.TableQueryEntityPropertyInQueryNotSupported); } Expression e = this.Visit(m.Expression); if (m.Member.Name == "Value" && m.Member.DeclaringType.IsGenericType && m.Member.DeclaringType.GetGenericTypeDefinition() == typeof(Nullable<>)) { return m; } if (!IsInputReference(e) && e.NodeType != ExpressionType.Convert && e.NodeType != ExpressionType.ConvertChecked) { this.builder.Append(UriHelper.FORWARDSLASH); } this.builder.Append(m.Member.Name); return m; } internal override Expression VisitConstant(ConstantExpression c) { string result = null; if (c.Value == null) { this.builder.Append(UriHelper.NULL); return c; } else if (!ClientConvert.TryKeyPrimitiveToString(c.Value, out result)) { throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, SR.ALinqCouldNotConvert, c.Value)); } Debug.Assert(result != null, "result != null"); // A Difference from WCF Data Services is that we will escape later when we execute the fully parsed query. this.builder.Append(result); return c; } internal override Expression VisitUnary(UnaryExpression u) { switch (u.NodeType) { case ExpressionType.Not: this.builder.Append(UriHelper.NOT); this.builder.Append(UriHelper.SPACE); this.VisitOperand(u.Operand); break; case ExpressionType.Negate: case ExpressionType.NegateChecked: this.builder.Append(UriHelper.SPACE); this.builder.Append(UriHelper.NEGATE); this.VisitOperand(u.Operand); break; case ExpressionType.Convert: case ExpressionType.ConvertChecked: case ExpressionType.UnaryPlus: break; default: this.cantTranslateExpression = true; break; } return u; } internal override Expression VisitBinary(BinaryExpression b) { this.VisitOperand(b.Left); this.builder.Append(UriHelper.SPACE); switch (b.NodeType) { case ExpressionType.AndAlso: case ExpressionType.And: this.builder.Append(UriHelper.AND); break; case ExpressionType.OrElse: case ExpressionType.Or: this.builder.Append(UriHelper.OR); break; case ExpressionType.Equal: this.builder.Append(UriHelper.EQ); break; case ExpressionType.NotEqual: this.builder.Append(UriHelper.NE); break; case ExpressionType.LessThan: this.builder.Append(UriHelper.LT); break; case ExpressionType.LessThanOrEqual: this.builder.Append(UriHelper.LE); break; case ExpressionType.GreaterThan: this.builder.Append(UriHelper.GT); break; case ExpressionType.GreaterThanOrEqual: this.builder.Append(UriHelper.GE); break; case ExpressionType.Add: case ExpressionType.AddChecked: this.builder.Append(UriHelper.ADD); break; case ExpressionType.Subtract: case ExpressionType.SubtractChecked: this.builder.Append(UriHelper.SUB); break; case ExpressionType.Multiply: case ExpressionType.MultiplyChecked: this.builder.Append(UriHelper.MUL); break; case ExpressionType.Divide: this.builder.Append(UriHelper.DIV); break; case ExpressionType.Modulo: this.builder.Append(UriHelper.MOD); break; case ExpressionType.ArrayIndex: case ExpressionType.Power: case ExpressionType.Coalesce: case ExpressionType.ExclusiveOr: case ExpressionType.LeftShift: case ExpressionType.RightShift: default: this.cantTranslateExpression = true; break; } this.builder.Append(UriHelper.SPACE); this.VisitOperand(b.Right); return b; } internal override Expression VisitTypeIs(TypeBinaryExpression b) { this.builder.Append(UriHelper.ISOF); this.builder.Append(UriHelper.LEFTPAREN); if (!IsInputReference(b.Expression)) { this.Visit(b.Expression); this.builder.Append(UriHelper.COMMA); this.builder.Append(UriHelper.SPACE); } this.builder.Append(UriHelper.QUOTE); this.builder.Append(this.TypeNameForUri(b.TypeOperand)); this.builder.Append(UriHelper.QUOTE); this.builder.Append(UriHelper.RIGHTPAREN); return b; } internal override Expression VisitParameter(ParameterExpression p) { return p; } private static bool IsInputReference(Expression exp) { return exp is InputReferenceExpression || exp is ParameterExpression; } private string TypeNameForUri(Type type) { Debug.Assert(type != null, "type != null"); type = Nullable.GetUnderlyingType(type) ?? type; if (ClientConvert.IsKnownType(type)) { if (ClientConvert.IsSupportedPrimitiveTypeForUri(type)) { return ClientConvert.ToTypeName(type); } throw new NotSupportedException(string.Format(CultureInfo.CurrentCulture, SR.ALinqCantCastToUnsupportedPrimitive, type.Name)); } else { return null; // return this.context.ResolveNameFromType(type) ?? type.FullName; } } private void VisitOperand(Expression e) { if (e is BinaryExpression || e is UnaryExpression) { this.builder.Append(UriHelper.LEFTPAREN); this.Visit(e); this.builder.Append(UriHelper.RIGHTPAREN); } else { this.Visit(e); } } private string Translate(Expression e) { this.Visit(e); return this.builder.ToString(); } } }
/* * 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 { using System; using System.Collections.Generic; using Apache.Ignite.Core.Cache; using Apache.Ignite.Core.Impl; using Apache.Ignite.Core.Portable; using Apache.Ignite.Core.Tests.Query; using NUnit.Framework; /// <summary> /// Tests for dynamic a cache start. /// </summary> public class CacheDynamicStartTest { /** Grid name: data. */ private const string GridData = "d"; /** Grid name: data, no configuration. */ private const string GridDataNoCfg = "dnc"; /** Grid name: client. */ private const string GridClient = "c"; /** Cache name: partitioned, transactional. */ private const string CacheTx = "p"; /** Cache name: atomic. */ private const string CacheAtomic = "pa"; /** Cache name: dummy. */ private const string CacheDummy = "dummy"; /// <summary> /// Set up routine. /// </summary> [SetUp] public void SetUp() { TestUtils.KillProcesses(); Ignition.Start(CreateConfiguration(GridData, @"config/dynamic/dynamic-data.xml")); Ignition.Start(CreateConfiguration(GridDataNoCfg, @"config/dynamic/dynamic-data-no-cfg.xml")); Ignition.Start(CreateConfiguration(GridClient, @"config/dynamic/dynamic-client.xml")); } /// <summary> /// Tear down routine. /// </summary> [TearDown] public void StopGrids() { Ignition.Stop(GridData, true); Ignition.Stop(GridDataNoCfg, true); Ignition.Stop(GridClient, true); } /// <summary> /// Create configuration. /// </summary> /// <param name="name">Grid name.</param> /// <param name="springCfg">Spring configuration.</param> /// <returns>Configuration.</returns> private static IgniteConfigurationEx CreateConfiguration(string name, string springCfg) { IgniteConfigurationEx cfg = new IgniteConfigurationEx(); PortableConfiguration portCfg = new PortableConfiguration(); ICollection<PortableTypeConfiguration> portTypeCfgs = new List<PortableTypeConfiguration>(); portTypeCfgs.Add(new PortableTypeConfiguration(typeof(DynamicTestKey))); portTypeCfgs.Add(new PortableTypeConfiguration(typeof(DynamicTestValue))); portCfg.TypeConfigurations = portTypeCfgs; cfg.GridName = name; cfg.PortableConfiguration = portCfg; cfg.JvmClasspath = TestUtils.CreateTestClasspath(); cfg.JvmOptions = TestUtils.TestJavaOptions(); cfg.SpringConfigUrl = springCfg; return cfg; } /// <summary> /// Try getting not configured cache. /// </summary> [Test] public void TestNoStarted() { Assert.Throws<ArgumentException>(() => { Ignition.GetIgnite(GridData).Cache<CacheTestKey, PortablePerson>(CacheDummy); }); Assert.Throws<ArgumentException>(() => { Ignition.GetIgnite(GridDataNoCfg).Cache<CacheTestKey, PortablePerson>(CacheDummy); }); Assert.Throws<ArgumentException>(() => { Ignition.GetIgnite(GridClient).Cache<CacheTestKey, PortablePerson>(CacheDummy); }); } /// <summary> /// Test TX cache. /// </summary> [Test] public void TestTransactional() { Check(CacheTx); } /// <summary> /// Test ATOMIC cache. /// </summary> [Test] public void TestAtomic() { Check(CacheAtomic); } /// <summary> /// Check routine. /// </summary> /// <param name="cacheName">Cache name.</param> private void Check(string cacheName) { ICache<DynamicTestKey, DynamicTestValue> cacheData = Ignition.GetIgnite(GridData).Cache<DynamicTestKey, DynamicTestValue>(cacheName); ICache<DynamicTestKey, DynamicTestValue> cacheDataNoCfg = Ignition.GetIgnite(GridDataNoCfg).Cache<DynamicTestKey, DynamicTestValue>(cacheName); ICache<DynamicTestKey, DynamicTestValue> cacheClient = Ignition.GetIgnite(GridClient).Cache<DynamicTestKey, DynamicTestValue>(cacheName); DynamicTestKey key1 = new DynamicTestKey(1); DynamicTestKey key2 = new DynamicTestKey(2); DynamicTestKey key3 = new DynamicTestKey(3); DynamicTestValue val1 = new DynamicTestValue(1); DynamicTestValue val2 = new DynamicTestValue(2); DynamicTestValue val3 = new DynamicTestValue(3); cacheData.Put(key1, val1); Assert.AreEqual(val1, cacheData.Get(key1)); Assert.AreEqual(val1, cacheDataNoCfg.Get(key1)); Assert.AreEqual(val1, cacheClient.Get(key1)); cacheDataNoCfg.Put(key2, val2); Assert.AreEqual(val2, cacheData.Get(key2)); Assert.AreEqual(val2, cacheDataNoCfg.Get(key2)); Assert.AreEqual(val2, cacheClient.Get(key2)); cacheClient.Put(key3, val3); Assert.AreEqual(val3, cacheData.Get(key3)); Assert.AreEqual(val3, cacheDataNoCfg.Get(key3)); Assert.AreEqual(val3, cacheClient.Get(key3)); for (int i = 0; i < 10000; i++) cacheClient.Put(new DynamicTestKey(i), new DynamicTestValue(1)); int sizeClient = cacheClient.LocalSize(); Assert.AreEqual(0, sizeClient); } } /// <summary> /// Key for dynamic cache start tests. /// </summary> class DynamicTestKey { /// <summary> /// Default constructor. /// </summary> public DynamicTestKey() { // No-op. } /// <summary> /// Constructor. /// </summary> /// <param name="id">ID.</param> public DynamicTestKey(int id) { Id = id; } /// <summary> /// ID. /// </summary> public int Id { get; set; } /** <inheritdoc /> */ public override bool Equals(object obj) { DynamicTestKey other = obj as DynamicTestKey; return other != null && Id == other.Id; } /** <inheritdoc /> */ public override int GetHashCode() { return Id; } } /// <summary> /// Value for dynamic cache start tests. /// </summary> class DynamicTestValue { /// <summary> /// Default constructor. /// </summary> public DynamicTestValue() { // No-op. } /// <summary> /// Constructor. /// </summary> /// <param name="id">ID.</param> public DynamicTestValue(int id) { Id = id; } /// <summary> /// ID. /// </summary> public int Id { get; set; } /** <inheritdoc /> */ public override bool Equals(object obj) { DynamicTestValue other = obj as DynamicTestValue; return other != null && Id == other.Id; } /** <inheritdoc /> */ public override int GetHashCode() { return Id; } } }
// **************************************************************** // Copyright 2008, Charlie Poole // This is free software licensed under the NUnit license. You may // obtain a copy of the license at http://nunit.org // **************************************************************** using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using NUnit.Util; namespace NUnit.UiKit { /// <summary> /// Summary description for OptionsDialogBase. /// </summary> public class SettingsDialogBase : NUnitFormBase { #region Instance Fields protected System.Windows.Forms.Button cancelButton; protected System.Windows.Forms.Button okButton; private SettingsPageCollection pageList; /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; private bool reloadProjectOnClose; #endregion #region Construction and Disposal public SettingsDialogBase() { // // Required for Windows Form Designer support // InitializeComponent(); // // TODO: Add any constructor code after InitializeComponent call // pageList = new SettingsPageCollection( ); } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if(components != null) { components.Dispose(); } } base.Dispose( disposing ); } #endregion #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.cancelButton = new System.Windows.Forms.Button(); this.okButton = new System.Windows.Forms.Button(); this.SuspendLayout(); // // cancelButton // this.cancelButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.cancelButton.CausesValidation = false; this.cancelButton.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.cancelButton.Location = new System.Drawing.Point(256, 424); this.cancelButton.Name = "cancelButton"; this.cancelButton.Size = new System.Drawing.Size(72, 24); this.cancelButton.TabIndex = 18; this.cancelButton.Text = "Cancel"; // // okButton // this.okButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.okButton.Location = new System.Drawing.Point(168, 424); this.okButton.Name = "okButton"; this.okButton.Size = new System.Drawing.Size(72, 24); this.okButton.TabIndex = 17; this.okButton.Text = "OK"; this.okButton.Click += new System.EventHandler(this.okButton_Click); // // SettingsDialogBase // this.ClientSize = new System.Drawing.Size(336, 458); this.Controls.Add(this.cancelButton); this.Controls.Add(this.okButton); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.HelpButton = true; this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "SettingsDialogBase"; this.ShowInTaskbar = false; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; this.Text = "Settings"; this.Closed += new System.EventHandler(this.SettingsDialogBase_Closed); this.ResumeLayout(false); } #endregion #region Properties public SettingsPageCollection SettingsPages { get { return pageList; } } #endregion #region Public Methods public void ApplySettings() { foreach( SettingsPage page in pageList ) if ( page.SettingsLoaded ) page.ApplySettings(); } #endregion #region Event Handlers private void SettingsDialogBase_Closed(object sender, System.EventArgs e) { if (this.reloadProjectOnClose) Services.TestLoader.ReloadTest(); } private void okButton_Click(object sender, System.EventArgs e) { if ( Services.TestLoader.IsTestLoaded && this.HasChangesRequiringReload ) { DialogResult answer = MessageDisplay.Ask( "Some changes will only take effect when you reload the test project. Do you want to reload now?"); if ( answer == DialogResult.Yes ) this.reloadProjectOnClose = true; } ApplySettings(); DialogResult = DialogResult.OK; Close(); } #endregion #region Helper Methods private bool HasChangesRequiringReload { get { foreach( SettingsPage page in pageList ) if ( page.SettingsLoaded && page.HasChangesRequiringReload ) return true; return false; } } #endregion #region Nested SettingsPageCollection Class public class SettingsPageCollection : CollectionBase { public void Add( SettingsPage page ) { this.InnerList.Add( page ); } public void AddRange( params SettingsPage[] pages ) { this.InnerList.AddRange( pages ); } public SettingsPage this[int index] { get { return (SettingsPage)InnerList[index]; } } public SettingsPage this[string key] { get { foreach( SettingsPage page in InnerList ) if ( page.Key == key ) return page; return null; } } } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Reactive.Disposables; using System.Reactive.Linq; using Avalonia.Controls.Primitives; using Avalonia.Input; using Avalonia.VisualTree; namespace Avalonia.Controls.Presenters { /// <summary> /// Presents a scrolling view of content inside a <see cref="ScrollViewer"/>. /// </summary> public class ScrollContentPresenter : ContentPresenter, IPresenter, IScrollable, IScrollAnchorProvider { private const double EdgeDetectionTolerance = 0.1; /// <summary> /// Defines the <see cref="CanHorizontallyScroll"/> property. /// </summary> public static readonly DirectProperty<ScrollContentPresenter, bool> CanHorizontallyScrollProperty = AvaloniaProperty.RegisterDirect<ScrollContentPresenter, bool>( nameof(CanHorizontallyScroll), o => o.CanHorizontallyScroll, (o, v) => o.CanHorizontallyScroll = v); /// <summary> /// Defines the <see cref="CanVerticallyScroll"/> property. /// </summary> public static readonly DirectProperty<ScrollContentPresenter, bool> CanVerticallyScrollProperty = AvaloniaProperty.RegisterDirect<ScrollContentPresenter, bool>( nameof(CanVerticallyScroll), o => o.CanVerticallyScroll, (o, v) => o.CanVerticallyScroll = v); /// <summary> /// Defines the <see cref="Extent"/> property. /// </summary> public static readonly DirectProperty<ScrollContentPresenter, Size> ExtentProperty = ScrollViewer.ExtentProperty.AddOwner<ScrollContentPresenter>( o => o.Extent, (o, v) => o.Extent = v); /// <summary> /// Defines the <see cref="Offset"/> property. /// </summary> public static readonly DirectProperty<ScrollContentPresenter, Vector> OffsetProperty = ScrollViewer.OffsetProperty.AddOwner<ScrollContentPresenter>( o => o.Offset, (o, v) => o.Offset = v); /// <summary> /// Defines the <see cref="Viewport"/> property. /// </summary> public static readonly DirectProperty<ScrollContentPresenter, Size> ViewportProperty = ScrollViewer.ViewportProperty.AddOwner<ScrollContentPresenter>( o => o.Viewport, (o, v) => o.Viewport = v); /// <summary> /// Defines the <see cref="IsScrollChainingEnabled"/> property. /// </summary> public static readonly StyledProperty<bool> IsScrollChainingEnabledProperty = ScrollViewer.IsScrollChainingEnabledProperty.AddOwner<ScrollContentPresenter>(); private bool _canHorizontallyScroll; private bool _canVerticallyScroll; private bool _arranging; private Size _extent; private Vector _offset; private IDisposable? _logicalScrollSubscription; private Size _viewport; private Dictionary<int, Vector>? _activeLogicalGestureScrolls; private List<IControl>? _anchorCandidates; private IControl? _anchorElement; private Rect _anchorElementBounds; private bool _isAnchorElementDirty; /// <summary> /// Initializes static members of the <see cref="ScrollContentPresenter"/> class. /// </summary> static ScrollContentPresenter() { ClipToBoundsProperty.OverrideDefaultValue(typeof(ScrollContentPresenter), true); ChildProperty.Changed.AddClassHandler<ScrollContentPresenter>((x, e) => x.ChildChanged(e)); } /// <summary> /// Initializes a new instance of the <see cref="ScrollContentPresenter"/> class. /// </summary> public ScrollContentPresenter() { AddHandler(RequestBringIntoViewEvent, BringIntoViewRequested); AddHandler(Gestures.ScrollGestureEvent, OnScrollGesture); this.GetObservable(ChildProperty).Subscribe(UpdateScrollableSubscription); } /// <summary> /// Gets or sets a value indicating whether the content can be scrolled horizontally. /// </summary> public bool CanHorizontallyScroll { get { return _canHorizontallyScroll; } set { SetAndRaise(CanHorizontallyScrollProperty, ref _canHorizontallyScroll, value); } } /// <summary> /// Gets or sets a value indicating whether the content can be scrolled horizontally. /// </summary> public bool CanVerticallyScroll { get { return _canVerticallyScroll; } set { SetAndRaise(CanVerticallyScrollProperty, ref _canVerticallyScroll, value); } } /// <summary> /// Gets the extent of the scrollable content. /// </summary> public Size Extent { get { return _extent; } private set { SetAndRaise(ExtentProperty, ref _extent, value); } } /// <summary> /// Gets or sets the current scroll offset. /// </summary> public Vector Offset { get { return _offset; } set { SetAndRaise(OffsetProperty, ref _offset, ScrollViewer.CoerceOffset(Extent, Viewport, value)); } } /// <summary> /// Gets the size of the viewport on the scrollable content. /// </summary> public Size Viewport { get { return _viewport; } private set { SetAndRaise(ViewportProperty, ref _viewport, value); } } /// <summary> /// Gets or sets if scroll chaining is enabled. The default value is true. /// </summary> /// <remarks> /// After a user hits a scroll limit on an element that has been nested within another scrollable element, /// you can specify whether that parent element should continue the scrolling operation begun in its child element. /// This is called scroll chaining. /// </remarks> public bool IsScrollChainingEnabled { get => GetValue(IsScrollChainingEnabledProperty); set => SetValue(IsScrollChainingEnabledProperty, value); } /// <inheritdoc/> IControl? IScrollAnchorProvider.CurrentAnchor { get { EnsureAnchorElementSelection(); return _anchorElement; } } /// <summary> /// Attempts to bring a portion of the target visual into view by scrolling the content. /// </summary> /// <param name="target">The target visual.</param> /// <param name="targetRect">The portion of the target visual to bring into view.</param> /// <returns>True if the scroll offset was changed; otherwise false.</returns> public bool BringDescendantIntoView(IVisual target, Rect targetRect) { if (Child?.IsEffectivelyVisible != true) { return false; } var scrollable = Child as ILogicalScrollable; var control = target as IControl; if (scrollable?.IsLogicalScrollEnabled == true && control != null) { return scrollable.BringIntoView(control, targetRect); } var transform = target.TransformToVisual(Child); if (transform == null) { return false; } var rect = targetRect.TransformToAABB(transform.Value); var offset = Offset; var result = false; if (rect.Bottom > offset.Y + Viewport.Height) { offset = offset.WithY((rect.Bottom - Viewport.Height) + Child.Margin.Top); result = true; } if (rect.Y < offset.Y) { offset = offset.WithY(rect.Y); result = true; } if (rect.Right > offset.X + Viewport.Width) { offset = offset.WithX((rect.Right - Viewport.Width) + Child.Margin.Left); result = true; } if (rect.X < offset.X) { offset = offset.WithX(rect.X); result = true; } if (result) { Offset = offset; } return result; } /// <inheritdoc/> void IScrollAnchorProvider.RegisterAnchorCandidate(IControl element) { if (!this.IsVisualAncestorOf(element)) { throw new InvalidOperationException( "An anchor control must be a visual descendent of the ScrollContentPresenter."); } _anchorCandidates ??= new List<IControl>(); _anchorCandidates.Add(element); _isAnchorElementDirty = true; } /// <inheritdoc/> void IScrollAnchorProvider.UnregisterAnchorCandidate(IControl element) { _anchorCandidates?.Remove(element); _isAnchorElementDirty = true; if (_anchorElement == element) { _anchorElement = null; } } /// <inheritdoc/> protected override Size MeasureOverride(Size availableSize) { if (_logicalScrollSubscription != null || Child == null) { return base.MeasureOverride(availableSize); } var constraint = new Size( CanHorizontallyScroll ? double.PositiveInfinity : availableSize.Width, CanVerticallyScroll ? double.PositiveInfinity : availableSize.Height); Child.Measure(constraint); return Child.DesiredSize.Constrain(availableSize); } /// <inheritdoc/> protected override Size ArrangeOverride(Size finalSize) { if (_logicalScrollSubscription != null || Child == null) { return base.ArrangeOverride(finalSize); } return ArrangeWithAnchoring(finalSize); } private Size ArrangeWithAnchoring(Size finalSize) { var size = new Size( CanHorizontallyScroll ? Math.Max(Child!.DesiredSize.Width, finalSize.Width) : finalSize.Width, CanVerticallyScroll ? Math.Max(Child!.DesiredSize.Height, finalSize.Height) : finalSize.Height); Vector TrackAnchor() { // If we have an anchor and its position relative to Child has changed during the // arrange then that change wasn't just due to scrolling (as scrolling doesn't adjust // relative positions within Child). if (_anchorElement != null && TranslateBounds(_anchorElement, Child!, out var updatedBounds) && updatedBounds.Position != _anchorElementBounds.Position) { var offset = updatedBounds.Position - _anchorElementBounds.Position; return offset; } return default; } var isAnchoring = Offset.X >= EdgeDetectionTolerance || Offset.Y >= EdgeDetectionTolerance; if (isAnchoring) { // Calculate the new anchor element if necessary. EnsureAnchorElementSelection(); // Do the arrange. ArrangeOverrideImpl(size, -Offset); // If the anchor moved during the arrange, we need to adjust the offset and do another arrange. var anchorShift = TrackAnchor(); if (anchorShift != default) { var newOffset = Offset + anchorShift; var newExtent = Extent; var maxOffset = new Vector(Extent.Width - Viewport.Width, Extent.Height - Viewport.Height); if (newOffset.X > maxOffset.X) { newExtent = newExtent.WithWidth(newOffset.X + Viewport.Width); } if (newOffset.Y > maxOffset.Y) { newExtent = newExtent.WithHeight(newOffset.Y + Viewport.Height); } Extent = newExtent; try { _arranging = true; Offset = newOffset; } finally { _arranging = false; } ArrangeOverrideImpl(size, -Offset); } } else { ArrangeOverrideImpl(size, -Offset); } Viewport = finalSize; Extent = Child!.Bounds.Size.Inflate(Child.Margin); _isAnchorElementDirty = true; return finalSize; } private void OnScrollGesture(object? sender, ScrollGestureEventArgs e) { if (Extent.Height > Viewport.Height || Extent.Width > Viewport.Width) { var scrollable = Child as ILogicalScrollable; var isLogical = scrollable?.IsLogicalScrollEnabled == true; var logicalScrollItemSize = new Vector(1, 1); double x = Offset.X; double y = Offset.Y; Vector delta = default; if (isLogical) _activeLogicalGestureScrolls?.TryGetValue(e.Id, out delta); delta += e.Delta; if (isLogical && scrollable is object) { logicalScrollItemSize = Bounds.Size / scrollable.Viewport; } if (Extent.Height > Viewport.Height) { double dy; if (isLogical) { var logicalUnits = delta.Y / logicalScrollItemSize.Y; delta = delta.WithY(delta.Y - logicalUnits * logicalScrollItemSize.Y); dy = logicalUnits * scrollable!.ScrollSize.Height; } else dy = delta.Y; y += dy; y = Math.Max(y, 0); y = Math.Min(y, Extent.Height - Viewport.Height); } if (Extent.Width > Viewport.Width) { double dx; if (isLogical) { var logicalUnits = delta.X / logicalScrollItemSize.X; delta = delta.WithX(delta.X - logicalUnits * logicalScrollItemSize.X); dx = logicalUnits * scrollable!.ScrollSize.Width; } else dx = delta.X; x += dx; x = Math.Max(x, 0); x = Math.Min(x, Extent.Width - Viewport.Width); } if (isLogical) { if (_activeLogicalGestureScrolls == null) _activeLogicalGestureScrolls = new Dictionary<int, Vector>(); _activeLogicalGestureScrolls[e.Id] = delta; } Vector newOffset = new Vector(x, y); bool offsetChanged = newOffset != Offset; Offset = newOffset; e.Handled = !IsScrollChainingEnabled || offsetChanged; } } private void OnScrollGestureEnded(object? sender, ScrollGestureEndedEventArgs e) => _activeLogicalGestureScrolls?.Remove(e.Id); /// <inheritdoc/> protected override void OnPointerWheelChanged(PointerWheelEventArgs e) { if (Extent.Height > Viewport.Height || Extent.Width > Viewport.Width) { var scrollable = Child as ILogicalScrollable; bool isLogical = scrollable?.IsLogicalScrollEnabled == true; double x = Offset.X; double y = Offset.Y; if (Extent.Height > Viewport.Height) { double height = isLogical ? scrollable!.ScrollSize.Height : 50; y += -e.Delta.Y * height; y = Math.Max(y, 0); y = Math.Min(y, Extent.Height - Viewport.Height); } if (Extent.Width > Viewport.Width) { double width = isLogical ? scrollable!.ScrollSize.Width : 50; x += -e.Delta.X * width; x = Math.Max(x, 0); x = Math.Min(x, Extent.Width - Viewport.Width); } Vector newOffset = new Vector(x, y); bool offsetChanged = newOffset != Offset; Offset = newOffset; e.Handled = !IsScrollChainingEnabled || offsetChanged; } } protected override void OnPropertyChanged<T>(AvaloniaPropertyChangedEventArgs<T> change) { if (change.Property == OffsetProperty && !_arranging) { InvalidateArrange(); } base.OnPropertyChanged(change); } private void BringIntoViewRequested(object? sender, RequestBringIntoViewEventArgs e) { if (e.TargetObject is not null) e.Handled = BringDescendantIntoView(e.TargetObject, e.TargetRect); } private void ChildChanged(AvaloniaPropertyChangedEventArgs e) { UpdateScrollableSubscription((IControl?)e.NewValue); if (e.OldValue != null) { Offset = default(Vector); } } private void UpdateScrollableSubscription(IControl? child) { var scrollable = child as ILogicalScrollable; _logicalScrollSubscription?.Dispose(); _logicalScrollSubscription = null; if (scrollable != null) { scrollable.ScrollInvalidated += ScrollInvalidated; if (scrollable.IsLogicalScrollEnabled) { _logicalScrollSubscription = new CompositeDisposable( this.GetObservable(CanHorizontallyScrollProperty) .Subscribe(x => scrollable.CanHorizontallyScroll = x), this.GetObservable(CanVerticallyScrollProperty) .Subscribe(x => scrollable.CanVerticallyScroll = x), this.GetObservable(OffsetProperty) .Skip(1).Subscribe(x => scrollable.Offset = x), Disposable.Create(() => scrollable.ScrollInvalidated -= ScrollInvalidated)); UpdateFromScrollable(scrollable); } } } private void ScrollInvalidated(object? sender, EventArgs e) { UpdateFromScrollable((ILogicalScrollable)sender!); } private void UpdateFromScrollable(ILogicalScrollable scrollable) { var logicalScroll = _logicalScrollSubscription != null; if (logicalScroll != scrollable.IsLogicalScrollEnabled) { UpdateScrollableSubscription(Child); Offset = default(Vector); InvalidateMeasure(); } else if (scrollable.IsLogicalScrollEnabled) { Viewport = scrollable.Viewport; Extent = scrollable.Extent; Offset = scrollable.Offset; } } private void EnsureAnchorElementSelection() { if (!_isAnchorElementDirty || _anchorCandidates is null) { return; } _anchorElement = null; _anchorElementBounds = default; _isAnchorElementDirty = false; var bestCandidate = default(IControl); var bestCandidateDistance = double.MaxValue; // Find the anchor candidate that is scrolled closest to the top-left of this // ScrollContentPresenter. foreach (var element in _anchorCandidates) { if (element.IsVisible && GetViewportBounds(element, out var bounds)) { var distance = (Vector)bounds.Position; var candidateDistance = Math.Abs(distance.Length); if (candidateDistance < bestCandidateDistance) { bestCandidate = element; bestCandidateDistance = candidateDistance; } } } if (bestCandidate != null) { // We have a candidate, calculate its bounds relative to Child. Because these // bounds aren't relative to the ScrollContentPresenter itself, if they change // then we know it wasn't just due to scrolling. var unscrolledBounds = TranslateBounds(bestCandidate, Child!); _anchorElement = bestCandidate; _anchorElementBounds = unscrolledBounds; } } private bool GetViewportBounds(IControl element, out Rect bounds) { if (TranslateBounds(element, Child!, out var childBounds)) { // We want the bounds relative to the new Offset, regardless of whether the child // control has actually been arranged to this offset yet, so translate first to the // child control and then apply Offset rather than translating directly to this // control. var thisBounds = new Rect(Bounds.Size); bounds = new Rect(childBounds.Position - Offset, childBounds.Size); return bounds.Intersects(thisBounds); } bounds = default; return false; } private Rect TranslateBounds(IControl control, IControl to) { if (TranslateBounds(control, to, out var bounds)) { return bounds; } throw new InvalidOperationException("The control's bounds could not be translated to the requested control."); } private bool TranslateBounds(IControl control, IControl to, out Rect bounds) { if (!control.IsVisible) { bounds = default; return false; } var p = control.TranslatePoint(default, to); bounds = p.HasValue ? new Rect(p.Value, control.Bounds.Size) : default; return p.HasValue; } } }
/*============================================================================ * Copyright (C) Microsoft Corporation, All rights reserved. *============================================================================ */ #region Using directives using System; using System.Globalization; using System.Management.Automation; using System.Threading; #endregion namespace Microsoft.Management.Infrastructure.CimCmdlets { /// <summary> /// <para> /// Subscription result event args /// </para> /// </summary> internal abstract class CimSubscriptionEventArgs : EventArgs { /// <summary> /// <para> /// Returns an Object value for an operation context /// </para> /// </summary> public Object Context { get { return context; } } protected Object context; } /// <summary> /// <para> /// Subscription result event args /// </para> /// </summary> internal class CimSubscriptionResultEventArgs : CimSubscriptionEventArgs { /// <summary> /// <para> /// subscription result /// </para> /// </summary> public CimSubscriptionResult Result { get { return result; } } private CimSubscriptionResult result; /// <summary> /// <para>Constructor</para> /// </summary> /// <param name="theResult"></param> public CimSubscriptionResultEventArgs( CimSubscriptionResult theResult) { this.context = null; this.result = theResult; } } /// <summary> /// <para> /// Subscription result event args /// </para> /// </summary> internal class CimSubscriptionExceptionEventArgs : CimSubscriptionEventArgs { /// <summary> /// <para> /// subscription result /// </para> /// </summary> public Exception Exception { get { return exception; } } private Exception exception; /// <summary> /// <para>Constructor</para> /// </summary> /// <param name="theResult"></param> public CimSubscriptionExceptionEventArgs( Exception theException) { this.context = null; this.exception = theException; } } /// <summary> /// <para> /// Implements operations of register-cimindication cmdlet. /// </para> /// </summary> internal sealed class CimRegisterCimIndication : CimAsyncOperation { /// <summary> /// <para> /// New subscription result event /// </para> /// </summary> public event EventHandler<CimSubscriptionEventArgs> OnNewSubscriptionResult; /// <summary> /// <para> /// Constructor /// </para> /// </summary> public CimRegisterCimIndication() : base() { this.ackedEvent = new ManualResetEventSlim(false); } /// <summary> /// Start an indication subscription target to the given computer. /// </summary> /// <param name="computerName">null stands for localhost</param> /// <param name="nameSpace"></param> /// <param name="queryDialect"></param> /// <param name="queryExpression"></param> /// <param name="operationTimeout"></param> public void RegisterCimIndication( string computerName, string nameSpace, string queryDialect, string queryExpression, UInt32 operationTimeout) { DebugHelper.WriteLogEx("queryDialect = '{0}'; queryExpression = '{1}'", 0, queryDialect, queryExpression); this.TargetComputerName = computerName; CimSessionProxy proxy = CreateSessionProxy(computerName, operationTimeout); proxy.SubscribeAsync(nameSpace, queryDialect, queryExpression); WaitForAckMessage(); } /// <summary> /// Start an indication subscription through a given <see cref="CimSession"/>. /// </summary> /// <param name="cimSession">Cannot be null</param> /// <param name="nameSpace"></param> /// <param name="queryDialect"></param> /// <param name="queryExpression"></param> /// <param name="operationTimeout"></param> /// <exception cref="ArgumentNullException">throw if cimSession is null</exception> public void RegisterCimIndication( CimSession cimSession, string nameSpace, string queryDialect, string queryExpression, UInt32 operationTimeout) { DebugHelper.WriteLogEx("queryDialect = '{0}'; queryExpression = '{1}'", 0, queryDialect, queryExpression); if (cimSession == null) { throw new ArgumentNullException(String.Format(CultureInfo.CurrentUICulture, Strings.NullArgument, @"cimSession")); } this.TargetComputerName = cimSession.ComputerName; CimSessionProxy proxy = CreateSessionProxy(cimSession, operationTimeout); proxy.SubscribeAsync(nameSpace, queryDialect, queryExpression); WaitForAckMessage(); } #region override methods /// <summary> /// <para> /// Subscribe to the events issued by <see cref="CimSessionProxy"/>. /// </para> /// </summary> /// <param name="proxy"></param> protected override void SubscribeToCimSessionProxyEvent(CimSessionProxy proxy) { DebugHelper.WriteLog("SubscribeToCimSessionProxyEvent", 4); // Raise event instead of write object to ps proxy.OnNewCmdletAction += this.CimIndicationHandler; proxy.OnOperationCreated += this.OperationCreatedHandler; proxy.OnOperationDeleted += this.OperationDeletedHandler; proxy.EnableMethodResultStreaming = false; } /// <summary> /// <para> /// Handler used to handle new action event from /// <seealso cref="CimSessionProxy"/> object. /// </para> /// </summary> /// <param name="cimSession"> /// <seealso cref="CimSession"/> object raised the event /// </param> /// <param name="actionArgs">event argument</param> private void CimIndicationHandler(object cimSession, CmdletActionEventArgs actionArgs) { DebugHelper.WriteLogEx("action is {0}. Disposed {1}", 0, actionArgs.Action, this.Disposed); if (this.Disposed) { return; } // NOTES: should move after this.Disposed, but need to log the exception CimWriteError cimWriteError = actionArgs.Action as CimWriteError; if (cimWriteError != null) { this.exception = cimWriteError.Exception; if (!this.ackedEvent.IsSet) { // an exception happened DebugHelper.WriteLogEx("an exception happened", 0); this.ackedEvent.Set(); return; } EventHandler<CimSubscriptionEventArgs> temp = this.OnNewSubscriptionResult; if (temp != null) { DebugHelper.WriteLog("Raise an exception event", 2); temp(this, new CimSubscriptionExceptionEventArgs(this.exception)); } DebugHelper.WriteLog("Got an exception: {0}", 2, exception); } CimWriteResultObject cimWriteResultObject = actionArgs.Action as CimWriteResultObject; if (cimWriteResultObject != null) { CimSubscriptionResult result = cimWriteResultObject.Result as CimSubscriptionResult; if (result != null) { EventHandler<CimSubscriptionEventArgs> temp = this.OnNewSubscriptionResult; if (temp != null) { DebugHelper.WriteLog("Raise an result event", 2); temp(this, new CimSubscriptionResultEventArgs(result)); } } else { if (!this.ackedEvent.IsSet) { // an ACK message returned DebugHelper.WriteLogEx("an ack message happened", 0); this.ackedEvent.Set(); return; } else { DebugHelper.WriteLogEx("an ack message should not happen here", 0); } } } } /// <summary> /// block the ps thread until ACK message or Error happened. /// </summary> private void WaitForAckMessage() { DebugHelper.WriteLogEx(); this.ackedEvent.Wait(); if (this.exception != null) { DebugHelper.WriteLogEx("error happened", 0); if (this.Cmdlet != null) { DebugHelper.WriteLogEx("Throw Terminating error", 1); // throw terminating error ErrorRecord errorRecord = ErrorToErrorRecord.ErrorRecordFromAnyException( new InvocationContext(this.TargetComputerName, null), this.exception, null); this.Cmdlet.ThrowTerminatingError(errorRecord); } else { DebugHelper.WriteLogEx("Throw exception", 1); // throw exception out throw this.exception; } } DebugHelper.WriteLogEx("ACK happened", 0); } #endregion #region internal property /// <summary> /// The cmdlet object who issue this subscription, /// to throw ThrowTerminatingError /// in case there is a subscription failure /// </summary> /// <param name="cmdlet"></param> internal Cmdlet Cmdlet { set; get; } /// <summary> /// target computername /// </summary> internal String TargetComputerName { set; get; } #endregion #region private methods /// <summary> /// <para> /// Create <see cref="CimSessionProxy"/> and set properties /// </para> /// </summary> /// <param name="computerName"></param> /// <param name="timeout"></param> /// <returns></returns> private CimSessionProxy CreateSessionProxy( string computerName, UInt32 timeout) { CimSessionProxy proxy = CreateCimSessionProxy(computerName); proxy.OperationTimeout = timeout; return proxy; } /// <summary> /// Create <see cref="CimSessionProxy"/> and set properties /// </summary> /// <param name="session"></param> /// <param name="timeout"></param> /// <returns></returns> private CimSessionProxy CreateSessionProxy( CimSession session, UInt32 timeout) { CimSessionProxy proxy = CreateCimSessionProxy(session); proxy.OperationTimeout = timeout; return proxy; } #endregion #region private members /// <summary> /// Exception occurred while start the subscription /// </summary> internal Exception Exception { get { return exception; } } private Exception exception; #endregion }//End Class }//End namespace
// 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.IO; using System.Net.Http.Functional.Tests; using System.Net.Security; using System.Net.Sockets; using System.Text; using System.Threading; using System.Threading.Tasks; using Xunit; namespace System.Net.Test.Common { public class Http2LoopbackConnection : GenericLoopbackConnection { private Socket _connectionSocket; private Stream _connectionStream; private TaskCompletionSource<bool> _ignoredSettingsAckPromise; private bool _ignoreWindowUpdates; public static TimeSpan Timeout => Http2LoopbackServer.Timeout; private int _lastStreamId; private readonly byte[] _prefix; public string PrefixString => Encoding.UTF8.GetString(_prefix, 0, _prefix.Length); public bool IsInvalid => _connectionSocket == null; public Http2LoopbackConnection(Socket socket, Http2Options httpOptions) { _connectionSocket = socket; _connectionStream = new NetworkStream(_connectionSocket, true); if (httpOptions.UseSsl) { var sslStream = new SslStream(_connectionStream, false, delegate { return true; }); using (var cert = Configuration.Certificates.GetServerCertificate()) { SslServerAuthenticationOptions options = new SslServerAuthenticationOptions(); options.EnabledSslProtocols = httpOptions.SslProtocols; var protocols = new List<SslApplicationProtocol>(); protocols.Add(SslApplicationProtocol.Http2); protocols.Add(SslApplicationProtocol.Http11); options.ApplicationProtocols = protocols; options.ServerCertificate = cert; options.ClientCertificateRequired = false; sslStream.AuthenticateAsServerAsync(options, CancellationToken.None).Wait(); } _connectionStream = sslStream; } _prefix = new byte[24]; if (!FillBufferAsync(_prefix).Result) { throw new Exception("Connection stream closed while attempting to read connection preface."); } } public async Task SendConnectionPrefaceAsync() { // Send the initial server settings frame. Frame emptySettings = new Frame(0, FrameType.Settings, FrameFlags.None, 0); await WriteFrameAsync(emptySettings).ConfigureAwait(false); // Receive and ACK the client settings frame. Frame clientSettings = await ReadFrameAsync(Timeout).ConfigureAwait(false); clientSettings.Flags = clientSettings.Flags | FrameFlags.Ack; await WriteFrameAsync(clientSettings).ConfigureAwait(false); // Receive the client ACK of the server settings frame. clientSettings = await ReadFrameAsync(Timeout).ConfigureAwait(false); } public async Task WriteFrameAsync(Frame frame) { byte[] writeBuffer = new byte[Frame.FrameHeaderLength + frame.Length]; frame.WriteTo(writeBuffer); await _connectionStream.WriteAsync(writeBuffer, 0, writeBuffer.Length).ConfigureAwait(false); } // Read until the buffer is full // Return false on EOF, throw on partial read private async Task<bool> FillBufferAsync(Memory<byte> buffer, CancellationToken cancellationToken = default(CancellationToken)) { int readBytes = await _connectionStream.ReadAsync(buffer, cancellationToken).ConfigureAwait(false); if (readBytes == 0) { return false; } buffer = buffer.Slice(readBytes); while (buffer.Length > 0) { readBytes = await _connectionStream.ReadAsync(buffer, cancellationToken).ConfigureAwait(false); if (readBytes == 0) { throw new Exception("Connection closed when expecting more data."); } buffer = buffer.Slice(readBytes); } return true; } public async Task<Frame> ReadFrameAsync(TimeSpan timeout) { using CancellationTokenSource timeoutCts = new CancellationTokenSource(timeout); return await ReadFrameAsync(timeoutCts.Token).ConfigureAwait(false); } private async Task<Frame> ReadFrameAsync(CancellationToken cancellationToken) { // First read the frame headers, which should tell us how long the rest of the frame is. byte[] headerBytes = new byte[Frame.FrameHeaderLength]; try { if (!await FillBufferAsync(headerBytes, cancellationToken).ConfigureAwait(false)) { return null; } } catch (IOException) { // eat errors when client aborts connection and return null. return null; } Frame header = Frame.ReadFrom(headerBytes); // Read the data segment of the frame, if it is present. byte[] data = new byte[header.Length]; if (header.Length > 0 && !await FillBufferAsync(data, cancellationToken).ConfigureAwait(false)) { throw new Exception("Connection stream closed while attempting to read frame body."); } if (_ignoredSettingsAckPromise != null && header.Type == FrameType.Settings && header.Flags == FrameFlags.Ack) { _ignoredSettingsAckPromise.TrySetResult(false); _ignoredSettingsAckPromise = null; return await ReadFrameAsync(cancellationToken).ConfigureAwait(false); } if (_ignoreWindowUpdates && header.Type == FrameType.WindowUpdate) { return await ReadFrameAsync(cancellationToken).ConfigureAwait(false); } // Construct the correct frame type and return it. switch (header.Type) { case FrameType.Settings: return SettingsFrame.ReadFrom(header, data); case FrameType.Data: return DataFrame.ReadFrom(header, data); case FrameType.Headers: return HeadersFrame.ReadFrom(header, data); case FrameType.Priority: return PriorityFrame.ReadFrom(header, data); case FrameType.RstStream: return RstStreamFrame.ReadFrom(header, data); case FrameType.Ping: return PingFrame.ReadFrom(header, data); case FrameType.GoAway: return GoAwayFrame.ReadFrom(header, data); default: return header; } } // Reset and return underlying networking objects. public (Socket, Stream) ResetNetwork() { Socket oldSocket = _connectionSocket; Stream oldStream = _connectionStream; _connectionSocket = null; _connectionStream = null; _ignoredSettingsAckPromise = null; return (oldSocket, oldStream); } // Set up loopback server to silently ignore the next inbound settings ack frame. // If there already is a pending ack frame, wait until it has been read. public async Task ExpectSettingsAckAsync(int timeoutMs = 5000) { // The timing of when we receive the settings ack is not guaranteed. // To simplify frame processing, just record that we are expecting one, // and then filter it out in ReadFrameAsync above. Task currentTask = _ignoredSettingsAckPromise?.Task; if (currentTask != null) { var timeout = TimeSpan.FromMilliseconds(timeoutMs); await currentTask.TimeoutAfter(timeout); } _ignoredSettingsAckPromise = new TaskCompletionSource<bool>(); } public void IgnoreWindowUpdates() { _ignoreWindowUpdates = true; } public async Task ReadRstStreamAsync(int streamId) { Frame frame = await ReadFrameAsync(Timeout); if (frame == null) { throw new Exception($"Expected RST_STREAM, saw EOF"); } if (frame.Type != FrameType.RstStream) { throw new Exception($"Expected RST_STREAM, saw {frame.Type}"); } if (frame.StreamId != streamId) { throw new Exception($"Expected RST_STREAM on stream {streamId}, actual streamId={frame.StreamId}"); } } // Wait for the client to close the connection, e.g. after the HttpClient is disposed. public async Task WaitForClientDisconnectAsync(bool ignoreUnexpectedFrames = false) { IgnoreWindowUpdates(); Frame frame = await ReadFrameAsync(Timeout).ConfigureAwait(false); if (frame != null) { if (!ignoreUnexpectedFrames) { throw new Exception($"Unexpected frame received while waiting for client disconnect: {frame}"); } } _connectionStream.Close(); _connectionSocket = null; _connectionStream = null; _ignoredSettingsAckPromise = null; _ignoreWindowUpdates = false; } public void ShutdownSend() { _connectionSocket.Shutdown(SocketShutdown.Send); } // This will cause a server-initiated shutdown of the connection. // For normal operation, you should send a GOAWAY and complete any remaining streams // before calling this method. public async Task WaitForConnectionShutdownAsync(bool ignoreUnexpectedFrames = false) { // Shutdown our send side, so the client knows there won't be any more frames coming. ShutdownSend(); await WaitForClientDisconnectAsync(ignoreUnexpectedFrames: ignoreUnexpectedFrames); } // This is similar to WaitForConnectionShutdownAsync but will send GOAWAY for you // and will ignore any errors if client has already shutdown public async Task ShutdownIgnoringErrorsAsync(int lastStreamId, ProtocolErrors errorCode = ProtocolErrors.NO_ERROR) { try { await SendGoAway(lastStreamId, errorCode).ConfigureAwait(false); await WaitForConnectionShutdownAsync(ignoreUnexpectedFrames: true).ConfigureAwait(false); } catch (IOException) { // Ignore connection errors } catch (SocketException) { // Ignore connection errors } } public async Task<int> ReadRequestHeaderAsync() { // Receive HEADERS frame for request. Frame frame = await ReadFrameAsync(Timeout).ConfigureAwait(false); if (frame == null) { throw new IOException("Failed to read Headers frame."); } Assert.Equal(FrameType.Headers, frame.Type); Assert.Equal(FrameFlags.EndHeaders | FrameFlags.EndStream, frame.Flags); return frame.StreamId; } public async Task<HeadersFrame> ReadRequestHeaderFrameAsync() { // Receive HEADERS frame for request. Frame frame = await ReadFrameAsync(Timeout).ConfigureAwait(false); if (frame == null) { throw new IOException("Failed to read Headers frame."); } Assert.Equal(FrameType.Headers, frame.Type); Assert.Equal(FrameFlags.EndHeaders | FrameFlags.EndStream, frame.Flags); return (HeadersFrame)frame; } private static (int bytesConsumed, int value) DecodeInteger(ReadOnlySpan<byte> headerBlock, byte prefixMask) { int value = headerBlock[0] & prefixMask; if (value != prefixMask) { return (1, value); } byte b = headerBlock[1]; if ((b & 0b10000000) != 0) { throw new Exception("long integers currently not supported"); } return (2, prefixMask + b); } private static int EncodeInteger(int value, byte prefix, byte prefixMask, Span<byte> headerBlock) { byte prefixLimit = (byte)(~prefixMask); if (value < prefixLimit) { headerBlock[0] = (byte)(prefix | value); return 1; } headerBlock[0] = (byte)(prefix | prefixLimit); int bytesGenerated = 1; value -= prefixLimit; while (value >= 0x80) { headerBlock[bytesGenerated] = (byte)((value & 0x7F) | 0x80); value = value >> 7; bytesGenerated++; } headerBlock[bytesGenerated] = (byte)value; bytesGenerated++; return bytesGenerated; } private static (int bytesConsumed, string value) DecodeString(ReadOnlySpan<byte> headerBlock) { (int bytesConsumed, int stringLength) = DecodeInteger(headerBlock, 0b01111111); if ((headerBlock[0] & 0b10000000) != 0) { // Huffman encoded byte[] buffer = new byte[stringLength * 2]; int bytesDecoded = HuffmanDecoder.Decode(headerBlock.Slice(bytesConsumed, stringLength), buffer); string value = Encoding.ASCII.GetString(buffer, 0, bytesDecoded); return (bytesConsumed + stringLength, value); } else { string value = Encoding.ASCII.GetString(headerBlock.Slice(bytesConsumed, stringLength)); return (bytesConsumed + stringLength, value); } } private static int EncodeString(string value, Span<byte> headerBlock, bool huffmanEncode, bool latin1 = false) { byte[] data = (latin1 ? HttpHeaderData.Latin1Encoding : Encoding.ASCII).GetBytes(value); byte prefix; if (!huffmanEncode) { prefix = 0; } else { int len = HuffmanEncoder.GetEncodedLength(data); byte[] huffmanData = new byte[len]; HuffmanEncoder.Encode(data, huffmanData); data = huffmanData; prefix = 0x80; } int bytesGenerated = 0; bytesGenerated += EncodeInteger(data.Length, prefix, 0x80, headerBlock); data.AsSpan().CopyTo(headerBlock.Slice(bytesGenerated)); bytesGenerated += data.Length; return bytesGenerated; } private static readonly HttpHeaderData[] s_staticTable = new HttpHeaderData[] { new HttpHeaderData(":authority", ""), new HttpHeaderData(":method", "GET"), new HttpHeaderData(":method", "POST"), new HttpHeaderData(":path", "/"), new HttpHeaderData(":path", "/index.html"), new HttpHeaderData(":scheme", "http"), new HttpHeaderData(":scheme", "https"), new HttpHeaderData(":status", "200"), new HttpHeaderData(":status", "204"), new HttpHeaderData(":status", "206"), new HttpHeaderData(":status", "304"), new HttpHeaderData(":status", "400"), new HttpHeaderData(":status", "404"), new HttpHeaderData(":status", "500"), new HttpHeaderData("accept-charset", ""), new HttpHeaderData("accept-encoding", "gzip, deflate"), new HttpHeaderData("accept-language", ""), new HttpHeaderData("accept-ranges", ""), new HttpHeaderData("accept", ""), new HttpHeaderData("access-control-allow-origin", ""), new HttpHeaderData("age", ""), new HttpHeaderData("allow", ""), new HttpHeaderData("authorization", ""), new HttpHeaderData("cache-control", ""), new HttpHeaderData("content-disposition", ""), new HttpHeaderData("content-encoding", ""), new HttpHeaderData("content-language", ""), new HttpHeaderData("content-length", ""), new HttpHeaderData("content-location", ""), new HttpHeaderData("content-range", ""), new HttpHeaderData("content-type", ""), new HttpHeaderData("cookie", ""), new HttpHeaderData("date", ""), new HttpHeaderData("etag", ""), new HttpHeaderData("expect", ""), new HttpHeaderData("expires", ""), new HttpHeaderData("from", ""), new HttpHeaderData("host", ""), new HttpHeaderData("if-match", ""), new HttpHeaderData("if-modified-since", ""), new HttpHeaderData("if-none-match", ""), new HttpHeaderData("if-range", ""), new HttpHeaderData("if-unmodified-since", ""), new HttpHeaderData("last-modified", ""), new HttpHeaderData("link", ""), new HttpHeaderData("location", ""), new HttpHeaderData("max-forwards", ""), new HttpHeaderData("proxy-authenticate", ""), new HttpHeaderData("proxy-authorization", ""), new HttpHeaderData("range", ""), new HttpHeaderData("referer", ""), new HttpHeaderData("refresh", ""), new HttpHeaderData("retry-after", ""), new HttpHeaderData("server", ""), new HttpHeaderData("set-cookie", ""), new HttpHeaderData("strict-transport-security", ""), new HttpHeaderData("transfer-encoding", ""), new HttpHeaderData("user-agent", ""), new HttpHeaderData("vary", ""), new HttpHeaderData("via", ""), new HttpHeaderData("www-authenticate", "") }; private static HttpHeaderData GetHeaderForIndex(int index) { return s_staticTable[index - 1]; } private static (int bytesConsumed, HttpHeaderData headerData) DecodeLiteralHeader(ReadOnlySpan<byte> headerBlock, byte prefixMask) { int i = 0; (int bytesConsumed, int index) = DecodeInteger(headerBlock, prefixMask); i += bytesConsumed; string name; if (index == 0) { (bytesConsumed, name) = DecodeString(headerBlock.Slice(i)); i += bytesConsumed; } else { name = GetHeaderForIndex(index).Name; } string value; (bytesConsumed, value) = DecodeString(headerBlock.Slice(i)); i += bytesConsumed; return (i, new HttpHeaderData(name, value)); } private static (int bytesConsumed, HttpHeaderData headerData) DecodeHeader(ReadOnlySpan<byte> headerBlock) { int i = 0; byte b = headerBlock[0]; if ((b & 0b10000000) != 0) { // Indexed header (int bytesConsumed, int index) = DecodeInteger(headerBlock, 0b01111111); i += bytesConsumed; return (i, GetHeaderForIndex(index)); } else if ((b & 0b11000000) == 0b01000000) { // Literal with indexing return DecodeLiteralHeader(headerBlock, 0b00111111); } else if ((b & 0b11100000) == 0b00100000) { // Table size update throw new Exception("table size update not supported"); } else { // Literal, never indexed return DecodeLiteralHeader(headerBlock, 0b00001111); } } public static int EncodeHeader(HttpHeaderData headerData, Span<byte> headerBlock, bool latin1 = false) { // Always encode as literal, no indexing. int bytesGenerated = EncodeInteger(0, 0, 0b11110000, headerBlock); bytesGenerated += EncodeString(headerData.Name, headerBlock.Slice(bytesGenerated), headerData.HuffmanEncoded); bytesGenerated += EncodeString(headerData.Value, headerBlock.Slice(bytesGenerated), headerData.HuffmanEncoded, latin1); return bytesGenerated; } public async Task<byte[]> ReadBodyAsync() { byte[] body = null; Frame frame; do { frame = await ReadFrameAsync(Timeout).ConfigureAwait(false); if (frame == null || frame.Type == FrameType.RstStream) { throw new IOException( frame == null ? "End of stream" : "Got RST"); } Assert.Equal(FrameType.Data, frame.Type); if (frame.Length > 1) { DataFrame dataFrame = (DataFrame)frame; if (body == null) { body = dataFrame.Data.ToArray(); } else { byte[] newBuffer = new byte[body.Length + dataFrame.Data.Length]; body.CopyTo(newBuffer, 0); dataFrame.Data.Span.CopyTo(newBuffer.AsSpan().Slice(body.Length)); body= newBuffer; } } } while ((frame.Flags & FrameFlags.EndStream) == 0); return body; } public async Task<(int streamId, HttpRequestData requestData)> ReadAndParseRequestHeaderAsync(bool readBody = true) { HttpRequestData requestData = new HttpRequestData(); // Receive HEADERS frame for request. Frame frame = await ReadFrameAsync(Timeout).ConfigureAwait(false); if (frame == null) { throw new IOException("Failed to read Headers frame."); } Assert.Equal(FrameType.Headers, frame.Type); HeadersFrame headersFrame = (HeadersFrame) frame; // TODO CONTINUATION support Assert.Equal(FrameFlags.EndHeaders, FrameFlags.EndHeaders & headersFrame.Flags); int streamId = headersFrame.StreamId; requestData.RequestId = streamId; Memory<byte> data = headersFrame.Data; int i = 0; while (i < data.Length) { (int bytesConsumed, HttpHeaderData headerData) = DecodeHeader(data.Span.Slice(i)); byte[] headerRaw = data.Span.Slice(i, bytesConsumed).ToArray(); headerData = new HttpHeaderData(headerData.Name, headerData.Value, headerData.HuffmanEncoded, headerRaw); requestData.Headers.Add(headerData); i += bytesConsumed; } // Extract method and path requestData.Method = requestData.GetSingleHeaderValue(":method"); requestData.Path = requestData.GetSingleHeaderValue(":path"); if (readBody && (frame.Flags & FrameFlags.EndStream) == 0) { // Read body until end of stream if needed. requestData.Body = await ReadBodyAsync().ConfigureAwait(false); } return (streamId, requestData); } public async Task SendGoAway(int lastStreamId, ProtocolErrors errorCode = ProtocolErrors.NO_ERROR) { GoAwayFrame frame = new GoAwayFrame(lastStreamId, (int)errorCode, new byte[] { }, 0); await WriteFrameAsync(frame).ConfigureAwait(false); } public async Task PingPong() { byte[] pingData = new byte[8] { 1, 2, 3, 4, 50, 60, 70, 80 }; PingFrame ping = new PingFrame(pingData, FrameFlags.None, 0); await WriteFrameAsync(ping).ConfigureAwait(false); PingFrame pingAck = (PingFrame)await ReadFrameAsync(Timeout).ConfigureAwait(false); if (pingAck == null || pingAck.Type != FrameType.Ping || !pingAck.AckFlag) { throw new Exception("Expected PING ACK"); } Assert.Equal(pingData, pingAck.Data); } public async Task SendDefaultResponseHeadersAsync(int streamId) { byte[] headers = new byte[] { 0x88 }; // Encoding for ":status: 200" HeadersFrame headersFrame = new HeadersFrame(headers, FrameFlags.EndHeaders, 0, 0, 0, streamId); await WriteFrameAsync(headersFrame).ConfigureAwait(false); } public async Task SendDefaultResponseAsync(int streamId) { byte[] headers = new byte[] { 0x88 }; // Encoding for ":status: 200" HeadersFrame headersFrame = new HeadersFrame(headers, FrameFlags.EndHeaders | FrameFlags.EndStream, 0, 0, 0, streamId); await WriteFrameAsync(headersFrame).ConfigureAwait(false); } public async Task SendResponseHeadersAsync(int streamId, bool endStream = true, HttpStatusCode statusCode = HttpStatusCode.OK, bool isTrailingHeader = false, bool endHeaders = true, IList<HttpHeaderData> headers = null) { // For now, only support headers that fit in a single frame byte[] headerBlock = new byte[Frame.MaxFrameLength]; int bytesGenerated = 0; if (!isTrailingHeader) { string statusCodeString = ((int)statusCode).ToString(); bytesGenerated += EncodeHeader(new HttpHeaderData(":status", statusCodeString), headerBlock.AsSpan()); } if (headers != null) { foreach (HttpHeaderData headerData in headers) { bytesGenerated += EncodeHeader(headerData, headerBlock.AsSpan().Slice(bytesGenerated), headerData.Latin1); } } FrameFlags flags = endHeaders ? FrameFlags.EndHeaders : FrameFlags.None; if (endStream) { flags |= FrameFlags.EndStream; } HeadersFrame headersFrame = new HeadersFrame(headerBlock.AsMemory().Slice(0, bytesGenerated), flags, 0, 0, 0, streamId); await WriteFrameAsync(headersFrame).ConfigureAwait(false); } public async Task SendResponseDataAsync(int streamId, ReadOnlyMemory<byte> responseData, bool endStream) { DataFrame dataFrame = new DataFrame(responseData, endStream ? FrameFlags.EndStream : FrameFlags.None, 0, streamId); await WriteFrameAsync(dataFrame).ConfigureAwait(false); } public async Task SendResponseBodyAsync(int streamId, ReadOnlyMemory<byte> responseBody, bool isFinal = true) { // Only support response body if it fits in a single frame, for now // In the future we should separate the body into chunks as needed, // and if it's larger than the default window size, we will need to process window updates as well. if (responseBody.Length > Frame.MaxFrameLength) { throw new Exception("Response body too long"); } await SendResponseDataAsync(streamId, responseBody, isFinal).ConfigureAwait(false); } public override void Dispose() { ShutdownIgnoringErrorsAsync(_lastStreamId).GetAwaiter().GetResult(); } // // GenericLoopbackServer implementation // public override async Task<HttpRequestData> ReadRequestDataAsync(bool readBody = true) { (int streamId, HttpRequestData requestData) = await ReadAndParseRequestHeaderAsync(readBody).ConfigureAwait(false); _lastStreamId = streamId; return requestData; } public override Task<Byte[]> ReadRequestBodyAsync() { return ReadBodyAsync(); } public override async Task SendResponseAsync(HttpStatusCode? statusCode = null, IList<HttpHeaderData> headers = null, string body = null, bool isFinal = true, int requestId = 0) { // TODO: Header continuation support. Assert.NotNull(statusCode); if (headers != null) { bool hasDate = false; bool stripContentLength = false; foreach (HttpHeaderData headerData in headers) { // Check if we should inject Date header to match HTTP/1. if (headerData.Name.Equals("Date", StringComparison.OrdinalIgnoreCase)) { hasDate = true; } else if (headerData.Name.Equals("Content-Length") && headerData.Value == null) { // Hack used for Http/1 to avoid sending content-length header. stripContentLength = true; } } if (!hasDate || stripContentLength) { var newHeaders = new List<HttpHeaderData>(); foreach (HttpHeaderData headerData in headers) { if (headerData.Name.Equals("Content-Length") && headerData.Value == null) { continue; } newHeaders.Add(headerData); } newHeaders.Add(new HttpHeaderData("Date", $"{DateTimeOffset.UtcNow:R}")); headers = newHeaders; } } int streamId = requestId == 0 ? _lastStreamId : requestId; bool endHeaders = body != null || isFinal; if (string.IsNullOrEmpty(body)) { await SendResponseHeadersAsync(streamId, endStream: isFinal, (HttpStatusCode)statusCode, endHeaders: endHeaders, headers: headers); } else { await SendResponseHeadersAsync(streamId, endStream: false, (HttpStatusCode)statusCode, endHeaders: endHeaders, headers: headers); await SendResponseBodyAsync(body, isFinal: isFinal, requestId: streamId); } } public override Task SendResponseHeadersAsync(HttpStatusCode statusCode = HttpStatusCode.OK, IList<HttpHeaderData> headers = null, int requestId = 0) { int streamId = requestId == 0 ? _lastStreamId : requestId; return SendResponseHeadersAsync(streamId, endStream: false, statusCode, isTrailingHeader: false, endHeaders: true, headers); } public override Task SendResponseBodyAsync(byte[] body, bool isFinal = true, int requestId = 0) { int streamId = requestId == 0 ? _lastStreamId : requestId; return SendResponseBodyAsync(streamId, body, isFinal); } public override async Task WaitForCancellationAsync(bool ignoreIncomingData = true, int requestId = 0) { int streamId = requestId == 0 ? _lastStreamId : requestId; Frame frame; do { frame = await ReadFrameAsync(TimeSpan.FromMilliseconds(TestHelper.PassingTestTimeoutMilliseconds)); Assert.NotNull(frame); // We should get Rst before closing connection. Assert.Equal(0, (int)(frame.Flags & FrameFlags.EndStream)); if (ignoreIncomingData) { Assert.True(frame.Type == FrameType.Data || frame.Type == FrameType.RstStream, $"Expected Data or RstStream, got {frame.Type}"); } else { Assert.Equal(FrameType.RstStream, frame.Type); } } while (frame.Type != FrameType.RstStream); Assert.Equal(streamId, frame.StreamId); } } }
namespace android.preference { [global::MonoJavaBridge.JavaClass(typeof(global::android.preference.DialogPreference_))] public abstract partial class DialogPreference : android.preference.Preference, android.content.DialogInterface_OnClickListener, android.content.DialogInterface_OnDismissListener, android.preference.PreferenceManager.OnActivityDestroyListener { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; protected DialogPreference(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } private static global::MonoJavaBridge.MethodId _m0; protected override void onClick() { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.preference.DialogPreference.staticClass, "onClick", "()V", ref global::android.preference.DialogPreference._m0); } private static global::MonoJavaBridge.MethodId _m1; public virtual void onClick(android.content.DialogInterface arg0, int arg1) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.preference.DialogPreference.staticClass, "onClick", "(Landroid/content/DialogInterface;I)V", ref global::android.preference.DialogPreference._m1, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m2; protected override void onRestoreInstanceState(android.os.Parcelable arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.preference.DialogPreference.staticClass, "onRestoreInstanceState", "(Landroid/os/Parcelable;)V", ref global::android.preference.DialogPreference._m2, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m3; protected override global::android.os.Parcelable onSaveInstanceState() { return global::MonoJavaBridge.JavaBridge.CallIJavaObjectMethod<android.os.Parcelable>(this, global::android.preference.DialogPreference.staticClass, "onSaveInstanceState", "()Landroid/os/Parcelable;", ref global::android.preference.DialogPreference._m3) as android.os.Parcelable; } private static global::MonoJavaBridge.MethodId _m4; protected virtual void showDialog(android.os.Bundle arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.preference.DialogPreference.staticClass, "showDialog", "(Landroid/os/Bundle;)V", ref global::android.preference.DialogPreference._m4, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m5; public virtual void onDismiss(android.content.DialogInterface arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.preference.DialogPreference.staticClass, "onDismiss", "(Landroid/content/DialogInterface;)V", ref global::android.preference.DialogPreference._m5, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m6; public virtual void setDialogTitle(java.lang.CharSequence arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.preference.DialogPreference.staticClass, "setDialogTitle", "(Ljava/lang/CharSequence;)V", ref global::android.preference.DialogPreference._m6, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } public void setDialogTitle(string arg0) { setDialogTitle((global::java.lang.CharSequence)(global::java.lang.String)arg0); } private static global::MonoJavaBridge.MethodId _m7; public virtual void setDialogTitle(int arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.preference.DialogPreference.staticClass, "setDialogTitle", "(I)V", ref global::android.preference.DialogPreference._m7, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m8; public virtual global::java.lang.CharSequence getDialogTitle() { return global::MonoJavaBridge.JavaBridge.CallIJavaObjectMethod<java.lang.CharSequence>(this, global::android.preference.DialogPreference.staticClass, "getDialogTitle", "()Ljava/lang/CharSequence;", ref global::android.preference.DialogPreference._m8) as java.lang.CharSequence; } private static global::MonoJavaBridge.MethodId _m9; public virtual void setDialogMessage(java.lang.CharSequence arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.preference.DialogPreference.staticClass, "setDialogMessage", "(Ljava/lang/CharSequence;)V", ref global::android.preference.DialogPreference._m9, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } public void setDialogMessage(string arg0) { setDialogMessage((global::java.lang.CharSequence)(global::java.lang.String)arg0); } private static global::MonoJavaBridge.MethodId _m10; public virtual void setDialogMessage(int arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.preference.DialogPreference.staticClass, "setDialogMessage", "(I)V", ref global::android.preference.DialogPreference._m10, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m11; public virtual global::java.lang.CharSequence getDialogMessage() { return global::MonoJavaBridge.JavaBridge.CallIJavaObjectMethod<java.lang.CharSequence>(this, global::android.preference.DialogPreference.staticClass, "getDialogMessage", "()Ljava/lang/CharSequence;", ref global::android.preference.DialogPreference._m11) as java.lang.CharSequence; } private static global::MonoJavaBridge.MethodId _m12; public virtual void setDialogIcon(android.graphics.drawable.Drawable arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.preference.DialogPreference.staticClass, "setDialogIcon", "(Landroid/graphics/drawable/Drawable;)V", ref global::android.preference.DialogPreference._m12, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m13; public virtual void setDialogIcon(int arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.preference.DialogPreference.staticClass, "setDialogIcon", "(I)V", ref global::android.preference.DialogPreference._m13, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m14; public virtual global::android.graphics.drawable.Drawable getDialogIcon() { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.preference.DialogPreference.staticClass, "getDialogIcon", "()Landroid/graphics/drawable/Drawable;", ref global::android.preference.DialogPreference._m14) as android.graphics.drawable.Drawable; } private static global::MonoJavaBridge.MethodId _m15; public virtual void setPositiveButtonText(int arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.preference.DialogPreference.staticClass, "setPositiveButtonText", "(I)V", ref global::android.preference.DialogPreference._m15, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m16; public virtual void setPositiveButtonText(java.lang.CharSequence arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.preference.DialogPreference.staticClass, "setPositiveButtonText", "(Ljava/lang/CharSequence;)V", ref global::android.preference.DialogPreference._m16, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } public void setPositiveButtonText(string arg0) { setPositiveButtonText((global::java.lang.CharSequence)(global::java.lang.String)arg0); } private static global::MonoJavaBridge.MethodId _m17; public virtual global::java.lang.CharSequence getPositiveButtonText() { return global::MonoJavaBridge.JavaBridge.CallIJavaObjectMethod<java.lang.CharSequence>(this, global::android.preference.DialogPreference.staticClass, "getPositiveButtonText", "()Ljava/lang/CharSequence;", ref global::android.preference.DialogPreference._m17) as java.lang.CharSequence; } private static global::MonoJavaBridge.MethodId _m18; public virtual void setNegativeButtonText(int arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.preference.DialogPreference.staticClass, "setNegativeButtonText", "(I)V", ref global::android.preference.DialogPreference._m18, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m19; public virtual void setNegativeButtonText(java.lang.CharSequence arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.preference.DialogPreference.staticClass, "setNegativeButtonText", "(Ljava/lang/CharSequence;)V", ref global::android.preference.DialogPreference._m19, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } public void setNegativeButtonText(string arg0) { setNegativeButtonText((global::java.lang.CharSequence)(global::java.lang.String)arg0); } private static global::MonoJavaBridge.MethodId _m20; public virtual global::java.lang.CharSequence getNegativeButtonText() { return global::MonoJavaBridge.JavaBridge.CallIJavaObjectMethod<java.lang.CharSequence>(this, global::android.preference.DialogPreference.staticClass, "getNegativeButtonText", "()Ljava/lang/CharSequence;", ref global::android.preference.DialogPreference._m20) as java.lang.CharSequence; } private static global::MonoJavaBridge.MethodId _m21; public virtual void setDialogLayoutResource(int arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.preference.DialogPreference.staticClass, "setDialogLayoutResource", "(I)V", ref global::android.preference.DialogPreference._m21, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m22; public virtual int getDialogLayoutResource() { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.preference.DialogPreference.staticClass, "getDialogLayoutResource", "()I", ref global::android.preference.DialogPreference._m22); } private static global::MonoJavaBridge.MethodId _m23; protected virtual void onPrepareDialogBuilder(android.app.AlertDialog.Builder arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.preference.DialogPreference.staticClass, "onPrepareDialogBuilder", "(Landroid/app/AlertDialog$Builder;)V", ref global::android.preference.DialogPreference._m23, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m24; protected virtual global::android.view.View onCreateDialogView() { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.preference.DialogPreference.staticClass, "onCreateDialogView", "()Landroid/view/View;", ref global::android.preference.DialogPreference._m24) as android.view.View; } private static global::MonoJavaBridge.MethodId _m25; protected virtual void onBindDialogView(android.view.View arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.preference.DialogPreference.staticClass, "onBindDialogView", "(Landroid/view/View;)V", ref global::android.preference.DialogPreference._m25, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m26; protected virtual void onDialogClosed(bool arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.preference.DialogPreference.staticClass, "onDialogClosed", "(Z)V", ref global::android.preference.DialogPreference._m26, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m27; public virtual global::android.app.Dialog getDialog() { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.preference.DialogPreference.staticClass, "getDialog", "()Landroid/app/Dialog;", ref global::android.preference.DialogPreference._m27) as android.app.Dialog; } private static global::MonoJavaBridge.MethodId _m28; public virtual void onActivityDestroy() { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.preference.DialogPreference.staticClass, "onActivityDestroy", "()V", ref global::android.preference.DialogPreference._m28); } private static global::MonoJavaBridge.MethodId _m29; public DialogPreference(android.content.Context arg0, android.util.AttributeSet arg1) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::android.preference.DialogPreference._m29.native == global::System.IntPtr.Zero) global::android.preference.DialogPreference._m29 = @__env.GetMethodIDNoThrow(global::android.preference.DialogPreference.staticClass, "<init>", "(Landroid/content/Context;Landroid/util/AttributeSet;)V"); global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.preference.DialogPreference.staticClass, global::android.preference.DialogPreference._m29, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); Init(@__env, handle); } private static global::MonoJavaBridge.MethodId _m30; public DialogPreference(android.content.Context arg0, android.util.AttributeSet arg1, int arg2) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::android.preference.DialogPreference._m30.native == global::System.IntPtr.Zero) global::android.preference.DialogPreference._m30 = @__env.GetMethodIDNoThrow(global::android.preference.DialogPreference.staticClass, "<init>", "(Landroid/content/Context;Landroid/util/AttributeSet;I)V"); global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.preference.DialogPreference.staticClass, global::android.preference.DialogPreference._m30, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); Init(@__env, handle); } static DialogPreference() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.preference.DialogPreference.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/preference/DialogPreference")); } } [global::MonoJavaBridge.JavaProxy(typeof(global::android.preference.DialogPreference))] internal sealed partial class DialogPreference_ : android.preference.DialogPreference { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; internal DialogPreference_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } static DialogPreference_() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.preference.DialogPreference_.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/preference/DialogPreference")); } } }
using System; namespace Skewworks.NETMF.Controls { [Serializable] public class MenuItem : Control { #region Variables private bool _expanded; private string _text; private rect _expandedBounds; private MenuItem[] _items; #endregion #region Constructor public MenuItem(string name, string text) { Name = name; _text = text; } #endregion #region Properties internal rect ExpandedBounds { get { return _expandedBounds; } set { _expandedBounds = value; } } internal void SetExpanded(bool value) { _expanded = value; } public bool Expanded { get { return _expanded; } set { if (_items == null || _items.Length == 0) return; _expanded = value; if (Parent != null) { Parent.TopLevelContainer.Invalidate(); } } } public int Length { get { if (_items == null) return 0; return _items.Length; } } public MenuItem[] Items { get { return _items; } } public string Text { get { return _text; } set { _text = value; } } #endregion #region Public Methods public void AddMenuItem(MenuItem value) { // Update Array Size if (_items == null) { _items = new[] { value }; } else { var tmp = new MenuItem[_items.Length + 1]; Array.Copy(_items, tmp, _items.Length); tmp[tmp.Length - 1] = value; _items = tmp; } Invalidate(); } public void AddMenuItems(MenuItem[] values) { if (_items == null) _items = values; else { var tmp = new MenuItem[_items.Length + values.Length]; Array.Copy(_items, tmp, _items.Length); Array.Copy(values, 0, tmp, 0, values.Length); } Invalidate(); } public void ClearMenuItems() { if (_items == null) return; _items = null; Invalidate(); } public void InsertMenuItemAt(MenuItem value, int index) { if (_items == null && index == 0) { AddMenuItem(value); return; } if (_items == null || index < 0 || index > _items.Length) throw new ArgumentOutOfRangeException(); var tmp = new MenuItem[_items.Length + 1]; int i; // Copy upper for (i = 0; i < index; i++) tmp[i] = _items[i]; // Insert tmp[index] = value; // Copy lower for (i = index; i < _items.Length; i++) tmp[i - 1] = _items[i]; // Update _items = tmp; Invalidate(); } /// <summary> /// Removes item by value /// </summary> /// <param name="item"></param> public void RemoveMenuItem(MenuItem item) { if (_items == null) return; for (int i = 0; i < _items.Length; i++) { if (ReferenceEquals(_items[i], item)) { RemoveMenuItemAt(i); return; } } } /// <summary> /// Removes item at specific point in array /// </summary> /// <param name="index"></param> public void RemoveMenuItemAt(int index) { if (_items.Length == 1) { ClearMenuItems(); return; } var tmp = new MenuItem[_items.Length - 1]; int c = 0; for (int i = 0; i < _items.Length; i++) { if (i != index) tmp[c++] = _items[i]; } _items = tmp; Invalidate(); } #endregion } }
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Threading.Tasks; using System.Linq; using Breeze.Sharp.Core; using Breeze.Sharp; using System.Collections.Generic; using Model.Inheritance.Produce; using System.Collections; namespace Breeze.Sharp.Tests { [TestClass] public class InheritanceProduceTests { private String _serviceName; // test("Skipping inherit produce tests - DB not yet avail", function () { // ok(true, "Skipped tests - Mongo"); // }); [TestInitialize] public void TestInitializeMethod() { Configuration.Instance.ProbeAssemblies(typeof(Apple).Assembly); TestFns.DefaultMetadataStore.NamingConvention = TestFns.DefaultMetadataStore.NamingConvention.WithClientServerNamespaceMapping("Model.Inheritance.Produce", "ProduceTPH"); _serviceName = TestFns.serviceRoot + "breeze/ProduceTPH/"; } [TestCleanup] public void TearDown() { } [TestMethod] public async Task FetchByKey() { var em1 = await TestFns.NewEm(_serviceName); var q = new EntityQuery<Fruit>().From("Fruits"); var r0 = await em1.ExecuteQuery(q); Assert.IsTrue(r0.Count() > 0); var fruit1 = r0.First(); var id = fruit1.Id; var ek = new EntityKey(typeof(Fruit), em1.MetadataStore, id); var r1 = await em1.ExecuteQuery(ek.ToQuery()); var fruits = r1.Cast<Fruit>(); Assert.IsTrue(fruits.First() == fruit1); } [TestMethod] public async Task FetchByKeyWithDefaultResource() { var em1 = await TestFns.NewEm(_serviceName); var rn = em1.MetadataStore.GetDefaultResourceName(typeof(Fruit)); Assert.IsTrue(rn != "Fruits"); em1.MetadataStore.SetResourceName("Fruits", typeof(Fruit), true); var rn2 = em1.MetadataStore.GetDefaultResourceName(typeof(Fruit)); Assert.IsTrue(rn2 == "Fruits"); var q = new EntityQuery<Fruit>(); var r0 = await em1.ExecuteQuery(q); Assert.IsTrue(r0.Count() > 0); var fruit1 = r0.First(); var id = fruit1.Id; var ek = new EntityKey(typeof(Fruit), em1.MetadataStore, id); var r1 = await em1.ExecuteQuery(ek.ToQuery()); var fruits = r1.Cast<Fruit>(); Assert.IsTrue(fruits.First() == fruit1); } [TestMethod] public async Task QueryAbstractWithOr() { var em1 = await TestFns.NewEm(_serviceName); var q = new EntityQuery<Fruit>().From("Fruits").Where(f => f.Name == "Apple" || f.Name == "Foo" || f.Name == "Papa"); var r0 = await em1.ExecuteQuery(q); Assert.IsTrue(r0.Count() > 0); var fruit1 = r0.First(); Assert.IsTrue(fruit1 is Apple, "fruit should be an Apple"); } [TestMethod] public async Task FetchByAbstractEntityKey() { var em1 = await TestFns.NewEm(_serviceName); var q = new EntityQuery<ItemOfProduce>().From("ItemsOfProduce"); var r0 = await em1.ExecuteQuery(q); Assert.IsTrue(r0.Count() > 0); var iop1 = r0.First(); var id = iop1.Id; var ek = new EntityKey(typeof(ItemOfProduce), em1.MetadataStore, id); var r1 = await em1.ExecuteQuery(ek.ToQuery()); var fruits = r1.Cast<ItemOfProduce>(); Assert.IsTrue(fruits.First() == iop1); } [TestMethod] public async Task LocalQueryFruits() { var em1 = await TestFns.NewEm(_serviceName); var q = new EntityQuery<Fruit>().From("Fruits"); var r0 = await em1.ExecuteQuery(q); Assert.IsTrue(r0.Count() > 0); var r1 = em1.ExecuteQueryLocally(q); Assert.IsTrue(r0.Count() == r1.Count()); Assert.IsTrue(r0.All(r => r1.Contains(r))); } [TestMethod] public async Task FetchEntityByKeyItemOfProduce() { var em1 = await TestFns.NewEm(_serviceName); var appleId = new Guid("13f1c9f5-3189-45fa-ba6e-13314fafaa92"); // var appleId = new Guid("D35E9669-2BAE-4D69-A27A-252B31800B74"); var ek = new EntityKey(typeof(ItemOfProduce), em1.MetadataStore, appleId); var fr = await em1.FetchEntityByKey(ek); Assert.IsTrue(fr.Entity != null && fr.Entity is Apple && !fr.FromCache); // and again var r0 = await em1.ExecuteQuery(ek.ToQuery<ItemOfProduce>()); Assert.IsTrue(r0.Count() > 0); Assert.IsTrue(r0.First().Id == appleId); } [TestMethod] public async Task FetchEntityByKeyLocalCache() { var em1 = await TestFns.NewEm(_serviceName); var appleId = new Guid("13f1c9f5-3189-45fa-ba6e-13314fafaa92"); // var appleId = new Guid("D35E9669-2BAE-4D69-A27A-252B31800B74"); var ek = new EntityKey(typeof(ItemOfProduce), em1.MetadataStore, appleId); var q = new EntityQuery<ItemOfProduce>(); var r0 = await em1.ExecuteQuery(q); Assert.IsTrue(r0.Count() > 30); var fr = await em1.FetchEntityByKey(ek, true); // should now be fromCache Assert.IsTrue(fr.Entity != null && fr.Entity is Apple && fr.FromCache); } [TestMethod] public async Task QueryAndModify() { var em1 = await TestFns.NewEm(_serviceName); var q = new EntityQuery<ItemOfProduce>().Take(2); var r0 = await em1.ExecuteQuery(q); Assert.IsTrue(r0.Count() == 2); Assert.IsTrue(r0.First().QuantityPerUnit != null); Assert.IsTrue(r0.ElementAt(1).QuantityPerUnit != null); r0.First().QuantityPerUnit = "ZZZ"; Assert.IsTrue(r0.First().QuantityPerUnit == "ZZZ"); } [TestMethod] public async Task QueryCheckUnique() { var em1 = await TestFns.NewEm(_serviceName); var q = new EntityQuery<ItemOfProduce>(); var r0 = await em1.ExecuteQuery(q); var hs = EnumerableFns.ToHashSet(r0.Select(r => r.QuantityPerUnit)); //.ToHashSet(); Assert.IsTrue(hs.Count() > 2, "should be more than 2 unique values"); } [TestMethod] public async Task InitializeTest() { var em1 = await TestFns.NewEm(_serviceName); var q = new EntityQuery<Fruit>().From("Fruits"); var r0 = await em1.ExecuteQuery(q); var apple = r0.First(r => r is Apple); Assert.IsTrue(apple.IsFruit); Assert.IsTrue(apple.InitializedTypes.Count == 3); Assert.IsTrue(apple.InitializedTypes[0] == "ItemOfProduce"); Assert.IsTrue(apple.InitializedTypes[1] == "Fruit"); Assert.IsTrue(apple.InitializedTypes[2] == "Apple"); } //test("query Fruits w/client ofType", function () { // var em = newEmX(); // ok(false, "Expected failure - OfType operator not yet supported - will be added later"); // return; // var q = EntityQuery.from("ItemsOfProduce") // .where(null, FilterQueryOp.IsTypeOf, "Fruit") // .using(em); // stop(); // var fruitType = em.metadataStore.getEntityType("Fruit"); // q.execute().then(function (data) { // var r = data.results; // ok(r.length > 0, "should have found some 'Fruits'"); // ok(r.every(function (f) { // return f.entityType.isSubtypeOf(fruitType); // })); // }).fail(testFns.handleFail).fin(start); //}); } }
#region LGPL License /* Axiom Game Engine Library Copyright (C) 2003 Axiom Project Team The overall design, and a majority of the core engine and rendering code contained within this library is a derivative of the open source Object Oriented Graphics Engine OGRE, which can be found at http://ogre.sourceforge.net. Many thanks to the OGRE team for maintaining such a high quality project. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #endregion using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using Axiom.Collections; using Axiom.MathLib; using Axiom.Graphics; using Axiom.Animating; namespace Axiom.Core { /// <summary> /// Utility class which defines the sub-parts of an Entity. /// </summary> /// <remarks> /// <para> /// Just as models are split into meshes, an Entity is made up of /// potentially multiple SubEntities. These are mainly here to provide the /// link between the Material which the SubEntity uses (which may be the /// default Material for the SubMesh or may have been changed for this /// object) and the SubMesh data. /// </para> /// <para> /// SubEntity instances are never created manually. They are created at /// the same time as their parent Entity by the SceneManager method /// CreateEntity. /// </para> /// </remarks> public class SubEntity : IRenderable { #region Fields /// <summary> /// Reference to the parent Entity. /// </summary> protected Entity parent; /// <summary> /// Name of the material being used. /// </summary> protected string materialName; /// <summary> /// Reference to the material being used by this SubEntity. /// </summary> protected Material material; /// <summary> /// Reference to the subMesh that represents the geometry for this SubEntity. /// </summary> protected SubMesh subMesh; /// <summary> /// The world AABB computed from the subMesh bounding box. /// </summary> protected AxisAlignedBox worldAABB = new AxisAlignedBox(); /// <summary> /// Detail to be used for rendering this sub entity. /// </summary> protected SceneDetailLevel renderDetail; /// <summary> /// Current LOD index to use. /// </summary> internal int materialLodIndex; /// <summary> /// Flag indicating whether this sub entity should be rendered or not. /// </summary> protected bool isVisible; /// <summary> /// Blend buffer details for dedicated geometry. /// </summary> protected internal VertexData skelAnimVertexData; /// <summary> /// Temp buffer details for software skeletal anim geometry /// </summary> protected internal TempBlendedBufferInfo tempSkelAnimInfo = new TempBlendedBufferInfo(); /// <summary> /// Temp buffer details for software Vertex anim geometry /// </summary> protected TempBlendedBufferInfo tempVertexAnimInfo = new TempBlendedBufferInfo(); /// <summary> /// Vertex data details for software Vertex anim of shared geometry /// </summary> /// Temp buffer details for software Vertex anim geometry protected VertexData softwareVertexAnimVertexData; /// <summary> /// Vertex data details for hardware Vertex anim of shared geometry /// - separate since we need to s/w anim for shadows whilst still altering /// the vertex data for hardware morphing (pos2 binding) /// </summary> protected VertexData hardwareVertexAnimVertexData; /// <summary> /// Have we applied any vertex animation to geometry? /// </summary> protected bool vertexAnimationAppliedThisFrame; /// <summary> /// Number of hardware blended poses supported by material /// </summary> protected ushort hardwarePoseCount; /// <summary> /// Flag indicating whether hardware skinning is supported by this subentity's materials. /// </summary> protected bool hardwareSkinningEnabled; /// <summary> /// Flag indicating whether vertex programs are used by this subentity's materials. /// </summary> protected bool useVertexProgram; protected Hashtable customParams = new Hashtable(); #endregion Fields #region Constructor /// <summary> /// Internal constructor, only allows creation of SubEntities within the engine core. /// </summary> internal SubEntity() { material = MaterialManager.Instance.GetByName("BaseWhite"); renderDetail = SceneDetailLevel.Solid; isVisible = true; } #endregion #region Properties /// <summary> /// Gets a flag indicating whether or not this sub entity should be rendered or not. /// </summary> public bool IsVisible { get { return isVisible; } set { isVisible = value; } } /// <summary> /// Gets/Sets the name of the material used for this SubEntity. /// </summary> public string MaterialName { get { return materialName; } set { if (value == null) throw new AxiomException("Cannot set the subentity material to be null"); materialName = value; // load the material from the material manager (it should already exist material = MaterialManager.Instance.GetByName(materialName); if(material == null) { LogManager.Instance.Write( "Cannot assign material '{0}' to SubEntity '{1}' because the material doesn't exist.", materialName, parent.Name); // give it base white so we can continue material = MaterialManager.Instance.GetByName("BaseWhite"); } // ensure the material is loaded. It will skip it if it already is material.Load(); // since the material has changed, re-evaulate its support of skeletal animation parent.ReevaluateVertexProcessing(); } } /// <summary> /// Gets/Sets the subMesh to be used for rendering this SubEntity. /// </summary> public SubMesh SubMesh { get { return subMesh; } set { subMesh = value; } } /// <summary> /// The world AABB computed from the subMesh bounding box. /// </summary> public AxisAlignedBox WorldAABB { get { return worldAABB; } set { worldAABB = value; } } /// <summary> /// Gets/Sets the parent entity of this SubEntity. /// </summary> public Entity Parent { get { return parent; } set { parent = value; } } public VertexData SkelAnimVertexData { get { return skelAnimVertexData; } } public TempBlendedBufferInfo TempSkelAnimInfo { get { return tempSkelAnimInfo; } } public TempBlendedBufferInfo TempVertexAnimInfo { get { return tempVertexAnimInfo; } } public VertexData SoftwareVertexAnimVertexData { get { return softwareVertexAnimVertexData; } } public VertexData HardwareVertexAnimVertexData { get { return hardwareVertexAnimVertexData; } } public ushort HardwarePoseCount { get { return hardwarePoseCount; } set { hardwarePoseCount = value; } } /// <summary> /// Are buffers already marked as vertex animated? /// </summary> public bool BuffersMarkedForAnimation { get { return vertexAnimationAppliedThisFrame; } } #endregion #region Methods /// <summary> /// Internal method for preparing this sub entity for use in animation. /// </summary> protected internal void PrepareTempBlendBuffers() { // Handle the case where we have no submesh vertex data (probably shared) if (subMesh.useSharedVertices) return; if (skelAnimVertexData != null) skelAnimVertexData = null; if (softwareVertexAnimVertexData != null) softwareVertexAnimVertexData = null; if (hardwareVertexAnimVertexData != null) hardwareVertexAnimVertexData = null; if (!subMesh.useSharedVertices) { if (subMesh.VertexAnimationType != VertexAnimationType.None) { // Create temporary vertex blend info // Prepare temp vertex data if needed // Clone without copying data, don't remove any blending info // (since if we skeletally animate too, we need it) softwareVertexAnimVertexData = subMesh.vertexData.Clone(false); parent.ExtractTempBufferInfo(softwareVertexAnimVertexData, tempVertexAnimInfo); // Also clone for hardware usage, don't remove blend info since we'll // need it if we also hardware skeletally animate hardwareVertexAnimVertexData = subMesh.vertexData.Clone(false); } if (parent.HasSkeleton) { // Create temporary vertex blend info // Prepare temp vertex data if needed // Clone without copying data, remove blending info // (since blend is performed in software) skelAnimVertexData = parent.CloneVertexDataRemoveBlendInfo(subMesh.vertexData); parent.ExtractTempBufferInfo(skelAnimVertexData, tempSkelAnimInfo); } } } #endregion Methods #region IRenderable Members public bool CastsShadows { get { return parent.CastShadows; } } /// <summary> /// Gets/Sets a reference to the material being used by this SubEntity. /// </summary> /// <remarks> /// By default, the SubEntity will use the material defined by the SubMesh. However, /// this can be overridden by the SubEntity in the case where several entities use the /// same SubMesh instance, but want to shade it different. /// This should probably call parent.ReevaluateVertexProcessing. /// </remarks> public Material Material { get { return material; } set { material = value; // We may have switched to a material with a vertex shader // or something similar. parent.ReevaluateVertexProcessing(); } } // ??? In the ogre version, it get the value of these from the parent Entity. public bool NormalizeNormals { get { return false; } } public Technique Technique { get { return material.GetBestTechnique(materialLodIndex); } } /// <summary> /// /// </summary> /// <param name="op"></param> public void GetRenderOperation(RenderOperation op) { // use LOD subMesh.GetRenderOperation(op, parent.MeshLodIndex); // Deal with any vertex data overrides // if (!hardwareSkinningEnabled) op.vertexData = GetVertexDataForBinding(); } public VertexData GetVertexDataForBinding() { if (subMesh.useSharedVertices) return parent.GetVertexDataForBinding(); else { VertexDataBindChoice c = parent.ChooseVertexDataForBinding( subMesh.VertexAnimationType != VertexAnimationType.None); switch(c) { case VertexDataBindChoice.Original: return subMesh.vertexData; case VertexDataBindChoice.HardwareMorph: return hardwareVertexAnimVertexData; case VertexDataBindChoice.SoftwareMorph: return softwareVertexAnimVertexData; case VertexDataBindChoice.SoftwareSkeletal: return skelAnimVertexData; }; // keep compiler happy return subMesh.vertexData; } } Material IRenderable.Material { get { return material; } } /// <summary> /// /// </summary> /// <param name="matrices"></param> public void GetWorldTransforms(Matrix4[] matrices) { if(parent.numBoneMatrices == 0 || !parent.IsHardwareAnimationEnabled) { matrices[0] = parent.ParentFullTransform; } else { // Hardware skinning, pass all actually used matrices List<ushort> indexMap = subMesh.useSharedVertices ? subMesh.Parent.SharedBlendIndexToBoneIndexMap : subMesh.BlendIndexToBoneIndexMap; Debug.Assert(indexMap.Count <= this.Parent.numBoneMatrices); if (parent.IsSkeletonAnimated) { // Bones, use cached matrices built when Entity::UpdateRenderQueue was called Debug.Assert(parent.boneMatrices != null); for (int i = 0; i < indexMap.Count; i++) { matrices[i] = parent.boneMatrices[indexMap[i]]; } } else { // All animations disabled, use parent entity world transform only for (int i = 0; i < indexMap.Count; i++) { matrices[i] = parent.ParentFullTransform; } } } } /// <summary> /// /// </summary> public ushort NumWorldTransforms { get { if (parent.numBoneMatrices == 0 || !parent.IsHardwareAnimationEnabled) { // No skeletal animation, or software skinning return 1; } else { // Hardware skinning, pass all actually used matrices List<ushort> indexMap = subMesh.useSharedVertices ? subMesh.Parent.SharedBlendIndexToBoneIndexMap : subMesh.BlendIndexToBoneIndexMap; Debug.Assert(indexMap.Count <= this.Parent.numBoneMatrices); return (ushort)indexMap.Count; } } } /// <summary> /// /// </summary> public bool UseIdentityProjection { get { return false; } } /// <summary> /// /// </summary> public bool UseIdentityView { get { return false; } } /// <summary> /// /// </summary> public SceneDetailLevel RenderDetail { get { return renderDetail; } set { renderDetail = value; } } /// <summary> /// /// </summary> /// <param name="camera"></param> /// <returns></returns> public float GetSquaredViewDepth(Camera camera) { // get the parent entitie's parent node Node node = parent.ParentNode; Debug.Assert(node != null); return node.GetSquaredViewDepth(camera); } /// <summary> /// /// </summary> public Quaternion WorldOrientation { get { // get the parent entitie's parent node Node node = parent.ParentNode; Debug.Assert(node != null); return parent.ParentNode.DerivedOrientation; } } /// <summary> /// /// </summary> public Vector3 WorldPosition { get { // get the parent entitie's parent node Node node = parent.ParentNode; Debug.Assert(node != null); return parent.ParentNode.DerivedPosition; } } /// <summary> /// /// </summary> public List<Light> Lights { get { // get the parent entitie's parent node Node node = parent.ParentNode; Debug.Assert(node != null); return parent.ParentNode.Lights; } } /// <summary> /// Returns whether or not hardware skinning is enabled. /// </summary> /// <remarks> /// Because fixed-function indexed vertex blending is rarely supported /// by existing graphics cards, hardware skinning can only be done if /// the vertex programs in the materials used to render an entity support /// it. Therefore, this method will only return true if all the materials /// assigned to this entity have vertex programs assigned, and all those /// vertex programs must support 'include_skeletal_animation true'. /// </remarks> public bool HardwareSkinningEnabled { get { return useVertexProgram && hardwareSkinningEnabled; } set { hardwareSkinningEnabled = value; } } public bool VertexProgramInUse { get { return useVertexProgram; } set { useVertexProgram = value; } } public Vector4 GetCustomParameter(int index) { if(customParams[index] == null) { throw new Exception("A parameter was not found at the given index"); } else { return (Vector4)customParams[index]; } } public void SetCustomParameter(int index, Vector4 val) { customParams[index] = val; } public void UpdateCustomGpuParameter(GpuProgramParameters.AutoConstantEntry entry, GpuProgramParameters gpuParams) { if (entry.type == AutoConstants.AnimationParametric) { // Set up to 4 values, or up to limit of hardware animation entries // Pack into 4-element constants offset based on constant data index // If there are more than 4 entries, this will be called more than once Vector4 val = Vector4.Zero; int animIndex = entry.data * 4; for (int i = 0; i < 4 && animIndex < hardwareVertexAnimVertexData.HWAnimationDataList.Count; ++i, ++animIndex) { val[i] = hardwareVertexAnimVertexData.HWAnimationDataList[animIndex].Parametric; } // set the parametric morph value gpuParams.SetConstant(entry.index, val); } else if (customParams[entry.data] != null) { gpuParams.SetConstant(entry.index, (Vector4)customParams[entry.data]); } } public void MarkBuffersUnusedForAnimation() { vertexAnimationAppliedThisFrame = false; } public void MarkBuffersUsedForAnimation() { vertexAnimationAppliedThisFrame = true; } public void RestoreBuffersForUnusedAnimation(bool hardwareAnimation) { // Rebind original positions if: // We didn't apply any animation and // We're morph animated (hardware binds keyframe, software is missing) // or we're pose animated and software (hardware is fine, still bound) if (subMesh.VertexAnimationType != VertexAnimationType.None && !subMesh.useSharedVertices && !vertexAnimationAppliedThisFrame && (!hardwareAnimation || subMesh.VertexAnimationType == VertexAnimationType.Morph)) { VertexElement srcPosElem = subMesh.vertexData.vertexDeclaration.FindElementBySemantic(VertexElementSemantic.Position); HardwareVertexBuffer srcBuf = subMesh.vertexData.vertexBufferBinding.GetBuffer(srcPosElem.Source); // Bind to software VertexElement destPosElem = softwareVertexAnimVertexData.vertexDeclaration.FindElementBySemantic(VertexElementSemantic.Position); softwareVertexAnimVertexData.vertexBufferBinding.SetBinding(destPosElem.Source, srcBuf); } } #endregion } }
using System; using System.Collections.Generic; using System.Data; using System.Linq; using NHibernate.Connection; using NHibernate.Dialect; using NHibernate.Driver; using NHibConfiguration = NHibernate.Cfg.Configuration; using NHibEnvironment = NHibernate.Cfg.Environment; namespace FluentNHibernate.Cfg.Db { public abstract class PersistenceConfiguration<TThisConfiguration> : PersistenceConfiguration<TThisConfiguration, ConnectionStringBuilder> where TThisConfiguration : PersistenceConfiguration<TThisConfiguration, ConnectionStringBuilder> {} public abstract class PersistenceConfiguration<TThisConfiguration, TConnectionString> : IPersistenceConfigurer where TThisConfiguration : PersistenceConfiguration<TThisConfiguration, TConnectionString> where TConnectionString : ConnectionStringBuilder, new() { protected const string DialectKey = NHibEnvironment.Dialect; // Newer one, but not supported by everything protected const string AltDialectKey = "hibernate.dialect"; // Some older NHib tools require this protected const string DefaultSchemaKey = "default_schema"; protected const string UseOuterJoinKey = "use_outer_join"; protected const string MaxFetchDepthKey = NHibEnvironment.MaxFetchDepth; protected const string UseReflectionOptimizerKey = NHibEnvironment.PropertyUseReflectionOptimizer; protected const string QuerySubstitutionsKey = NHibEnvironment.QuerySubstitutions; protected const string ShowSqlKey = NHibEnvironment.ShowSql; protected const string FormatSqlKey = NHibEnvironment.FormatSql; protected const string CollectionTypeFactoryClassKey = NHibernate.Cfg.Environment.CollectionTypeFactoryClass; protected const string ConnectionProviderKey = NHibEnvironment.ConnectionProvider; protected const string DefaultConnectionProviderClassName = "NHibernate.Connection.DriverConnectionProvider"; protected const string DriverClassKey = NHibEnvironment.ConnectionDriver; protected const string ConnectionStringKey = NHibEnvironment.ConnectionString; protected const string IsolationLevelKey = NHibEnvironment.Isolation; protected const string AdoNetBatchSizeKey = NHibEnvironment.BatchSize; protected const string CurrentSessionContextClassKey = "current_session_context_class"; private readonly Dictionary<string, string> values = new Dictionary<string, string>(); private bool nextBoolSettingValue = true; private readonly TConnectionString connectionString; private readonly CacheSettingsBuilder cache = new CacheSettingsBuilder(); protected PersistenceConfiguration() { values[ConnectionProviderKey] = DefaultConnectionProviderClassName; connectionString = new TConnectionString(); } protected virtual IDictionary<string, string> CreateProperties() { if (connectionString.IsDirty) Raw(ConnectionStringKey, connectionString.Create()); if (cache.IsDirty) { foreach (var pair in cache.Create()) { Raw(pair.Key, pair.Value); } } return values; } static IEnumerable<string> OverridenDefaults(IDictionary<string,string> settings) { if (settings[ConnectionProviderKey] != DefaultConnectionProviderClassName) yield return ConnectionProviderKey; } private static IEnumerable<string> KeysToPreserve(NHibConfiguration nhibernateConfig, IDictionary<string, string> settings) { var @default = new NHibConfiguration(); return nhibernateConfig.Properties .Except(@default.Properties) .Select(k => k.Key) .Except(OverridenDefaults(settings)); } public NHibConfiguration ConfigureProperties(NHibConfiguration nhibernateConfig) { var settings = CreateProperties(); var keepers = KeysToPreserve(nhibernateConfig, settings); foreach (var kv in settings.Where(s => !keepers.Contains(s.Key))) { nhibernateConfig.SetProperty(kv.Key, kv.Value); } return nhibernateConfig; } public IDictionary<string, string> ToProperties() { return CreateProperties(); } protected void ToggleBooleanSetting(string settingKey) { var value = nextBoolSettingValue.ToString().ToLowerInvariant(); values[settingKey] = value; nextBoolSettingValue = true; } /// <summary> /// Negates the next boolean option. /// </summary> public TThisConfiguration DoNot { get { nextBoolSettingValue = false; return (TThisConfiguration)this; } } /// <summary> /// Sets the database dialect. This shouldn't be necessary /// if you've used one of the provided database configurations. /// </summary> /// <returns>Configuration builder</returns> public TThisConfiguration Dialect(string dialect) { values[DialectKey] = dialect; values[AltDialectKey] = dialect; return (TThisConfiguration) this; } /// <summary> /// Sets the database dialect. This shouldn't be necessary /// if you've used one of the provided database configurations. /// </summary> /// <returns>Configuration builder</returns> public TThisConfiguration Dialect<T>() where T : Dialect { return Dialect(typeof (T).AssemblyQualifiedName); } /// <summary> /// Sets the default database schema /// </summary> /// <param name="schema">Default schema name</param> /// <returns>Configuration builder</returns> public TThisConfiguration DefaultSchema(string schema) { values[DefaultSchemaKey] = schema; return (TThisConfiguration) this; } /// <summary> /// Enables the outer-join option. /// </summary> /// <returns>Configuration builder</returns> public TThisConfiguration UseOuterJoin() { ToggleBooleanSetting(UseOuterJoinKey); return (TThisConfiguration) this; } /// <summary> /// Sets the max fetch depth. /// </summary> /// <param name="maxFetchDepth">Max fetch depth</param> /// <returns>Configuration builder</returns> public TThisConfiguration MaxFetchDepth(int maxFetchDepth) { values[MaxFetchDepthKey] = maxFetchDepth.ToString(); return (TThisConfiguration)this; } /// <summary> /// Enables the reflection optimizer. /// </summary> /// <returns>Configuration builder</returns> public TThisConfiguration UseReflectionOptimizer() { ToggleBooleanSetting(UseReflectionOptimizerKey); return (TThisConfiguration) this; } /// <summary> /// Sets any query stubstitutions that NHibernate should /// perform. /// </summary> /// <param name="substitutions">Substitutions</param> /// <returns>Configuration builder</returns> public TThisConfiguration QuerySubstitutions(string substitutions) { values[QuerySubstitutionsKey] = substitutions; return (TThisConfiguration)this; } /// <summary> /// Enables the show SQL option. /// </summary> /// <returns>Configuration builder</returns> public TThisConfiguration ShowSql() { ToggleBooleanSetting(ShowSqlKey); return (TThisConfiguration)this; } /// <summary> /// Enables the format SQL option. /// </summary> /// <returns>Configuration builder</returns> public TThisConfiguration FormatSql() { ToggleBooleanSetting(FormatSqlKey); return (TThisConfiguration)this; } /// <summary> /// Sets the database provider. This shouldn't be necessary /// if you're using one of the provided database configurations. /// </summary> /// <param name="provider">Provider type</param> /// <returns>Configuration builder</returns> public TThisConfiguration Provider(string provider) { values[ConnectionProviderKey] = provider; return (TThisConfiguration)this; } /// <summary> /// Sets the database provider. This shouldn't be necessary /// if you're using one of the provided database configurations. /// </summary> /// <typeparam name="T">Provider type</typeparam> /// <returns>Configuration builder</returns> public TThisConfiguration Provider<T>() where T : IConnectionProvider { return Provider(typeof(T).AssemblyQualifiedName); } /// <summary> /// Specify the database driver. This isn't necessary /// if you're using one of the provided database configurations. /// </summary> /// <param name="driverClass">Driver type</param> /// <returns>Configuration builder</returns> public TThisConfiguration Driver(string driverClass) { values[DriverClassKey] = driverClass; return (TThisConfiguration)this; } /// <summary> /// Specify the database driver. This isn't necessary /// if you're using one of the provided database configurations. /// </summary> /// <typeparam name="T">Driver type</typeparam> /// <returns>Configuration builder</returns> public TThisConfiguration Driver<T>() where T : IDriver { return Driver(typeof(T).AssemblyQualifiedName); } /// <summary> /// Configure the connection string /// </summary> /// <example> /// ConnectionString(x => /// { /// x.Server("db_server"); /// x.Database("Products"); /// }); /// </example> /// <param name="connectionStringExpression">Closure for building the connection string</param> /// <returns>Configuration builder</returns> public TThisConfiguration ConnectionString(Action<TConnectionString> connectionStringExpression) { connectionStringExpression(connectionString); return (TThisConfiguration)this; } /// <summary> /// Set the connection string. /// </summary> /// <param name="value">Connection string to use</param> /// <returns>Configuration builder</returns> public TThisConfiguration ConnectionString(string value) { connectionString.Is(value); return (TThisConfiguration)this; } /// <summary> /// Sets a raw property on the NHibernate configuration. Use this method /// if there isn't a specific option available in the API. /// </summary> /// <param name="key">Setting key</param> /// <param name="value">Setting value</param> /// <returns>Configuration builder</returns> public TThisConfiguration Raw(string key, string value) { values[key] = value; return (TThisConfiguration) this; } /// <summary> /// Sets the adonet.batch_size property. /// </summary> /// <param name="size">Batch size</param> /// <returns>Configuration</returns> public TThisConfiguration AdoNetBatchSize(int size) { values[AdoNetBatchSizeKey] = size.ToString(); return (TThisConfiguration)this; } /// <summary> /// Sets the connection isolation level. NHibernate setting: connection.isolation /// </summary> /// <param name="connectionIsolation">Isolation level</param> /// <returns>Configuration builder</returns> public TThisConfiguration IsolationLevel(IsolationLevel connectionIsolation) { return IsolationLevel(connectionIsolation.ToString()); } /// <summary> /// Sets the connection isolation level. NHibernate setting: connection.isolation /// </summary> /// <param name="connectionIsolation">Isolation level</param> /// <returns>Configuration builder</returns> public TThisConfiguration IsolationLevel(string connectionIsolation) { values[IsolationLevelKey] = connectionIsolation; return (TThisConfiguration)this; } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Web.Http.Description; using System.Xml.Linq; using Newtonsoft.Json; namespace PCBWayApi.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>> { DefaultSampleObjectFactory, }; } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order, /// stopping when the factory successfully returns a non-<see langref="null"/> object. /// </summary> /// <remarks> /// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use /// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and /// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames. // If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames. // If still not found, try to get the sample provided for the specified mediaType and type. // Finally, try to get the sample provided for the specified mediaType. if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create /// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other /// factories in <see cref="SampleObjectFactories"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")] public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // No specific object available, try our factories. foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories) { if (factory == null) { continue; } try { sampleObject = factory(this, type); if (sampleObject != null) { break; } } catch { // Ignore any problems encountered in the factory; go on to the next one (if any). } } } return sampleObject; } /// <summary> /// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The type.</returns> public virtual Type ResolveHttpRequestMessageType(ApiDescription api) { string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters); } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, UnwrapException(e).Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } internal static Exception UnwrapException(Exception exception) { AggregateException aggregateException = exception as AggregateException; if (aggregateException != null) { return aggregateException.Flatten().InnerException; } return exception; } // Default factory for sample objects private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type) { // Try to create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
using System; using System.IO; using System.ComponentModel; using System.Collections.Generic; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using ChargeBee.Internal; using ChargeBee.Api; using ChargeBee.Models.Enums; using ChargeBee.Filters.Enums; namespace ChargeBee.Models { public class CreditNote : Resource { public CreditNote() { } public CreditNote(Stream stream) { using (StreamReader reader = new StreamReader(stream)) { JObj = JToken.Parse(reader.ReadToEnd()); apiVersionCheck (JObj); } } public CreditNote(TextReader reader) { JObj = JToken.Parse(reader.ReadToEnd()); apiVersionCheck (JObj); } public CreditNote(String jsonString) { JObj = JToken.Parse(jsonString); apiVersionCheck (JObj); } #region Methods public static CreateRequest Create() { string url = ApiUtil.BuildUrl("credit_notes"); return new CreateRequest(url, HttpMethod.POST); } public static EntityRequest<Type> Retrieve(string id) { string url = ApiUtil.BuildUrl("credit_notes", CheckNull(id)); return new EntityRequest<Type>(url, HttpMethod.GET); } public static PdfRequest Pdf(string id) { string url = ApiUtil.BuildUrl("credit_notes", CheckNull(id), "pdf"); return new PdfRequest(url, HttpMethod.POST); } public static EntityRequest<Type> DownloadEinvoice(string id) { string url = ApiUtil.BuildUrl("credit_notes", CheckNull(id), "download_einvoice"); return new EntityRequest<Type>(url, HttpMethod.GET); } public static RefundRequest Refund(string id) { string url = ApiUtil.BuildUrl("credit_notes", CheckNull(id), "refund"); return new RefundRequest(url, HttpMethod.POST); } public static RecordRefundRequest RecordRefund(string id) { string url = ApiUtil.BuildUrl("credit_notes", CheckNull(id), "record_refund"); return new RecordRefundRequest(url, HttpMethod.POST); } public static VoidCreditNoteRequest VoidCreditNote(string id) { string url = ApiUtil.BuildUrl("credit_notes", CheckNull(id), "void"); return new VoidCreditNoteRequest(url, HttpMethod.POST); } public static CreditNoteListRequest List() { string url = ApiUtil.BuildUrl("credit_notes"); return new CreditNoteListRequest(url); } [Obsolete] public static ListRequest CreditNotesForCustomer(string id) { string url = ApiUtil.BuildUrl("customers", CheckNull(id), "credit_notes"); return new ListRequest(url); } public static DeleteRequest Delete(string id) { string url = ApiUtil.BuildUrl("credit_notes", CheckNull(id), "delete"); return new DeleteRequest(url, HttpMethod.POST); } #endregion #region Properties public string Id { get { return GetValue<string>("id", true); } } public string CustomerId { get { return GetValue<string>("customer_id", true); } } public string SubscriptionId { get { return GetValue<string>("subscription_id", false); } } public string ReferenceInvoiceId { get { return GetValue<string>("reference_invoice_id", true); } } public TypeEnum CreditNoteType { get { return GetEnum<TypeEnum>("type", true); } } public ReasonCodeEnum? ReasonCode { get { return GetEnum<ReasonCodeEnum>("reason_code", false); } } public StatusEnum Status { get { return GetEnum<StatusEnum>("status", true); } } public string VatNumber { get { return GetValue<string>("vat_number", false); } } public DateTime? Date { get { return GetDateTime("date", false); } } public PriceTypeEnum PriceType { get { return GetEnum<PriceTypeEnum>("price_type", true); } } public string CurrencyCode { get { return GetValue<string>("currency_code", true); } } public int? Total { get { return GetValue<int?>("total", false); } } public int? AmountAllocated { get { return GetValue<int?>("amount_allocated", false); } } public int? AmountRefunded { get { return GetValue<int?>("amount_refunded", false); } } public int? AmountAvailable { get { return GetValue<int?>("amount_available", false); } } public DateTime? RefundedAt { get { return GetDateTime("refunded_at", false); } } public DateTime? VoidedAt { get { return GetDateTime("voided_at", false); } } public DateTime? GeneratedAt { get { return GetDateTime("generated_at", false); } } public long? ResourceVersion { get { return GetValue<long?>("resource_version", false); } } public DateTime? UpdatedAt { get { return GetDateTime("updated_at", false); } } public CreditNoteEinvoice Einvoice { get { return GetSubResource<CreditNoteEinvoice>("einvoice"); } } public int SubTotal { get { return GetValue<int>("sub_total", true); } } public int? SubTotalInLocalCurrency { get { return GetValue<int?>("sub_total_in_local_currency", false); } } public int? TotalInLocalCurrency { get { return GetValue<int?>("total_in_local_currency", false); } } public string LocalCurrencyCode { get { return GetValue<string>("local_currency_code", false); } } public int? RoundOffAmount { get { return GetValue<int?>("round_off_amount", false); } } public int? FractionalCorrection { get { return GetValue<int?>("fractional_correction", false); } } public List<CreditNoteLineItem> LineItems { get { return GetResourceList<CreditNoteLineItem>("line_items"); } } public List<CreditNoteDiscount> Discounts { get { return GetResourceList<CreditNoteDiscount>("discounts"); } } public List<CreditNoteLineItemDiscount> LineItemDiscounts { get { return GetResourceList<CreditNoteLineItemDiscount>("line_item_discounts"); } } public List<CreditNoteLineItemTier> LineItemTiers { get { return GetResourceList<CreditNoteLineItemTier>("line_item_tiers"); } } public List<CreditNoteTax> Taxes { get { return GetResourceList<CreditNoteTax>("taxes"); } } public List<CreditNoteLineItemTax> LineItemTaxes { get { return GetResourceList<CreditNoteLineItemTax>("line_item_taxes"); } } public List<CreditNoteLinkedRefund> LinkedRefunds { get { return GetResourceList<CreditNoteLinkedRefund>("linked_refunds"); } } public List<CreditNoteAllocation> Allocations { get { return GetResourceList<CreditNoteAllocation>("allocations"); } } public bool Deleted { get { return GetValue<bool>("deleted", true); } } public string CreateReasonCode { get { return GetValue<string>("create_reason_code", false); } } public string VatNumberPrefix { get { return GetValue<string>("vat_number_prefix", false); } } #endregion #region Requests public class CreateRequest : EntityRequest<CreateRequest> { public CreateRequest(string url, HttpMethod method) : base(url, method) { } public CreateRequest ReferenceInvoiceId(string referenceInvoiceId) { m_params.Add("reference_invoice_id", referenceInvoiceId); return this; } public CreateRequest Total(int total) { m_params.AddOpt("total", total); return this; } public CreateRequest Type(CreditNote.TypeEnum type) { m_params.Add("type", type); return this; } public CreateRequest ReasonCode(CreditNote.ReasonCodeEnum reasonCode) { m_params.AddOpt("reason_code", reasonCode); return this; } public CreateRequest CreateReasonCode(string createReasonCode) { m_params.AddOpt("create_reason_code", createReasonCode); return this; } public CreateRequest Date(long date) { m_params.AddOpt("date", date); return this; } public CreateRequest CustomerNotes(string customerNotes) { m_params.AddOpt("customer_notes", customerNotes); return this; } public CreateRequest Comment(string comment) { m_params.AddOpt("comment", comment); return this; } public CreateRequest LineItemReferenceLineItemId(int index, string lineItemReferenceLineItemId) { m_params.Add("line_items[reference_line_item_id][" + index + "]", lineItemReferenceLineItemId); return this; } public CreateRequest LineItemUnitAmount(int index, int lineItemUnitAmount) { m_params.AddOpt("line_items[unit_amount][" + index + "]", lineItemUnitAmount); return this; } public CreateRequest LineItemUnitAmountInDecimal(int index, string lineItemUnitAmountInDecimal) { m_params.AddOpt("line_items[unit_amount_in_decimal][" + index + "]", lineItemUnitAmountInDecimal); return this; } public CreateRequest LineItemQuantity(int index, int lineItemQuantity) { m_params.AddOpt("line_items[quantity][" + index + "]", lineItemQuantity); return this; } public CreateRequest LineItemQuantityInDecimal(int index, string lineItemQuantityInDecimal) { m_params.AddOpt("line_items[quantity_in_decimal][" + index + "]", lineItemQuantityInDecimal); return this; } public CreateRequest LineItemAmount(int index, int lineItemAmount) { m_params.AddOpt("line_items[amount][" + index + "]", lineItemAmount); return this; } public CreateRequest LineItemDateFrom(int index, long lineItemDateFrom) { m_params.AddOpt("line_items[date_from][" + index + "]", lineItemDateFrom); return this; } public CreateRequest LineItemDateTo(int index, long lineItemDateTo) { m_params.AddOpt("line_items[date_to][" + index + "]", lineItemDateTo); return this; } public CreateRequest LineItemDescription(int index, string lineItemDescription) { m_params.AddOpt("line_items[description][" + index + "]", lineItemDescription); return this; } } public class PdfRequest : EntityRequest<PdfRequest> { public PdfRequest(string url, HttpMethod method) : base(url, method) { } public PdfRequest DispositionType(ChargeBee.Models.Enums.DispositionTypeEnum dispositionType) { m_params.AddOpt("disposition_type", dispositionType); return this; } } public class RefundRequest : EntityRequest<RefundRequest> { public RefundRequest(string url, HttpMethod method) : base(url, method) { } public RefundRequest RefundAmount(int refundAmount) { m_params.AddOpt("refund_amount", refundAmount); return this; } public RefundRequest CustomerNotes(string customerNotes) { m_params.AddOpt("customer_notes", customerNotes); return this; } public RefundRequest RefundReasonCode(string refundReasonCode) { m_params.AddOpt("refund_reason_code", refundReasonCode); return this; } } public class RecordRefundRequest : EntityRequest<RecordRefundRequest> { public RecordRefundRequest(string url, HttpMethod method) : base(url, method) { } public RecordRefundRequest RefundReasonCode(string refundReasonCode) { m_params.AddOpt("refund_reason_code", refundReasonCode); return this; } public RecordRefundRequest Comment(string comment) { m_params.AddOpt("comment", comment); return this; } public RecordRefundRequest TransactionAmount(int transactionAmount) { m_params.AddOpt("transaction[amount]", transactionAmount); return this; } public RecordRefundRequest TransactionPaymentMethod(ChargeBee.Models.Enums.PaymentMethodEnum transactionPaymentMethod) { m_params.Add("transaction[payment_method]", transactionPaymentMethod); return this; } public RecordRefundRequest TransactionReferenceNumber(string transactionReferenceNumber) { m_params.AddOpt("transaction[reference_number]", transactionReferenceNumber); return this; } public RecordRefundRequest TransactionDate(long transactionDate) { m_params.Add("transaction[date]", transactionDate); return this; } } public class VoidCreditNoteRequest : EntityRequest<VoidCreditNoteRequest> { public VoidCreditNoteRequest(string url, HttpMethod method) : base(url, method) { } public VoidCreditNoteRequest Comment(string comment) { m_params.AddOpt("comment", comment); return this; } } public class CreditNoteListRequest : ListRequestBase<CreditNoteListRequest> { public CreditNoteListRequest(string url) : base(url) { } public CreditNoteListRequest IncludeDeleted(bool includeDeleted) { m_params.AddOpt("include_deleted", includeDeleted); return this; } public StringFilter<CreditNoteListRequest> Id() { return new StringFilter<CreditNoteListRequest>("id", this).SupportsMultiOperators(true); } public StringFilter<CreditNoteListRequest> CustomerId() { return new StringFilter<CreditNoteListRequest>("customer_id", this).SupportsMultiOperators(true); } public StringFilter<CreditNoteListRequest> SubscriptionId() { return new StringFilter<CreditNoteListRequest>("subscription_id", this).SupportsMultiOperators(true).SupportsPresenceOperator(true); } public StringFilter<CreditNoteListRequest> ReferenceInvoiceId() { return new StringFilter<CreditNoteListRequest>("reference_invoice_id", this).SupportsMultiOperators(true); } public EnumFilter<CreditNote.TypeEnum, CreditNoteListRequest> Type() { return new EnumFilter<CreditNote.TypeEnum, CreditNoteListRequest>("type", this); } public EnumFilter<CreditNote.ReasonCodeEnum, CreditNoteListRequest> ReasonCode() { return new EnumFilter<CreditNote.ReasonCodeEnum, CreditNoteListRequest>("reason_code", this); } public StringFilter<CreditNoteListRequest> CreateReasonCode() { return new StringFilter<CreditNoteListRequest>("create_reason_code", this).SupportsMultiOperators(true); } public EnumFilter<CreditNote.StatusEnum, CreditNoteListRequest> Status() { return new EnumFilter<CreditNote.StatusEnum, CreditNoteListRequest>("status", this); } public TimestampFilter<CreditNoteListRequest> Date() { return new TimestampFilter<CreditNoteListRequest>("date", this); } public NumberFilter<int, CreditNoteListRequest> Total() { return new NumberFilter<int, CreditNoteListRequest>("total", this); } public EnumFilter<ChargeBee.Models.Enums.PriceTypeEnum, CreditNoteListRequest> PriceType() { return new EnumFilter<ChargeBee.Models.Enums.PriceTypeEnum, CreditNoteListRequest>("price_type", this); } public NumberFilter<int, CreditNoteListRequest> AmountAllocated() { return new NumberFilter<int, CreditNoteListRequest>("amount_allocated", this); } public NumberFilter<int, CreditNoteListRequest> AmountRefunded() { return new NumberFilter<int, CreditNoteListRequest>("amount_refunded", this); } public NumberFilter<int, CreditNoteListRequest> AmountAvailable() { return new NumberFilter<int, CreditNoteListRequest>("amount_available", this); } public TimestampFilter<CreditNoteListRequest> VoidedAt() { return new TimestampFilter<CreditNoteListRequest>("voided_at", this); } public TimestampFilter<CreditNoteListRequest> UpdatedAt() { return new TimestampFilter<CreditNoteListRequest>("updated_at", this); } public CreditNoteListRequest SortByDate(SortOrderEnum order) { m_params.AddOpt("sort_by["+order.ToString().ToLower()+"]","date"); return this; } } public class DeleteRequest : EntityRequest<DeleteRequest> { public DeleteRequest(string url, HttpMethod method) : base(url, method) { } public DeleteRequest Comment(string comment) { m_params.AddOpt("comment", comment); return this; } } #endregion public enum TypeEnum { UnKnown, /*Indicates unexpected value for this enum. You can get this when there is a dotnet-client version incompatibility. We suggest you to upgrade to the latest version */ [EnumMember(Value = "adjustment")] Adjustment, [EnumMember(Value = "refundable")] Refundable, } public enum ReasonCodeEnum { UnKnown, /*Indicates unexpected value for this enum. You can get this when there is a dotnet-client version incompatibility. We suggest you to upgrade to the latest version */ [EnumMember(Value = "write_off")] WriteOff, [EnumMember(Value = "subscription_change")] SubscriptionChange, [EnumMember(Value = "subscription_cancellation")] SubscriptionCancellation, [EnumMember(Value = "subscription_pause")] SubscriptionPause, [EnumMember(Value = "chargeback")] Chargeback, [EnumMember(Value = "product_unsatisfactory")] ProductUnsatisfactory, [EnumMember(Value = "service_unsatisfactory")] ServiceUnsatisfactory, [EnumMember(Value = "order_change")] OrderChange, [EnumMember(Value = "order_cancellation")] OrderCancellation, [EnumMember(Value = "waiver")] Waiver, [EnumMember(Value = "other")] Other, [EnumMember(Value = "fraudulent")] Fraudulent, } public enum StatusEnum { UnKnown, /*Indicates unexpected value for this enum. You can get this when there is a dotnet-client version incompatibility. We suggest you to upgrade to the latest version */ [EnumMember(Value = "adjusted")] Adjusted, [EnumMember(Value = "refunded")] Refunded, [EnumMember(Value = "refund_due")] RefundDue, [EnumMember(Value = "voided")] Voided, } #region Subclasses public class CreditNoteEinvoice : Resource { public enum StatusEnum { UnKnown, /*Indicates unexpected value for this enum. You can get this when there is a dotnet-client version incompatibility. We suggest you to upgrade to the latest version */ [EnumMember(Value = "scheduled")] Scheduled, [EnumMember(Value = "skipped")] Skipped, [EnumMember(Value = "in_progress")] InProgress, [EnumMember(Value = "success")] Success, [EnumMember(Value = "failed")] Failed, } public string Id { get { return GetValue<string>("id", true); } } public StatusEnum Status { get { return GetEnum<StatusEnum>("status", true); } } public string Message { get { return GetValue<string>("message", false); } } } public class CreditNoteLineItem : Resource { public enum EntityTypeEnum { UnKnown, /*Indicates unexpected value for this enum. You can get this when there is a dotnet-client version incompatibility. We suggest you to upgrade to the latest version */ [EnumMember(Value = "plan_setup")] PlanSetup, [EnumMember(Value = "plan")] Plan, [EnumMember(Value = "addon")] Addon, [EnumMember(Value = "adhoc")] Adhoc, [EnumMember(Value = "plan_item_price")] PlanItemPrice, [EnumMember(Value = "addon_item_price")] AddonItemPrice, [EnumMember(Value = "charge_item_price")] ChargeItemPrice, } public string Id { get { return GetValue<string>("id", false); } } public string SubscriptionId { get { return GetValue<string>("subscription_id", false); } } public DateTime DateFrom { get { return (DateTime)GetDateTime("date_from", true); } } public DateTime DateTo { get { return (DateTime)GetDateTime("date_to", true); } } public int UnitAmount { get { return GetValue<int>("unit_amount", true); } } public int? Quantity { get { return GetValue<int?>("quantity", false); } } public int? Amount { get { return GetValue<int?>("amount", false); } } public PricingModelEnum? PricingModel { get { return GetEnum<PricingModelEnum>("pricing_model", false); } } public bool IsTaxed { get { return GetValue<bool>("is_taxed", true); } } public int? TaxAmount { get { return GetValue<int?>("tax_amount", false); } } public double? TaxRate { get { return GetValue<double?>("tax_rate", false); } } public string UnitAmountInDecimal { get { return GetValue<string>("unit_amount_in_decimal", false); } } public string QuantityInDecimal { get { return GetValue<string>("quantity_in_decimal", false); } } public string AmountInDecimal { get { return GetValue<string>("amount_in_decimal", false); } } public int? DiscountAmount { get { return GetValue<int?>("discount_amount", false); } } public int? ItemLevelDiscountAmount { get { return GetValue<int?>("item_level_discount_amount", false); } } public string Description { get { return GetValue<string>("description", true); } } public string EntityDescription { get { return GetValue<string>("entity_description", true); } } public EntityTypeEnum EntityType { get { return GetEnum<EntityTypeEnum>("entity_type", true); } } public TaxExemptReasonEnum? TaxExemptReason { get { return GetEnum<TaxExemptReasonEnum>("tax_exempt_reason", false); } } public string EntityId { get { return GetValue<string>("entity_id", false); } } public string CustomerId { get { return GetValue<string>("customer_id", false); } } } public class CreditNoteDiscount : Resource { public enum EntityTypeEnum { UnKnown, /*Indicates unexpected value for this enum. You can get this when there is a dotnet-client version incompatibility. We suggest you to upgrade to the latest version */ [EnumMember(Value = "item_level_coupon")] ItemLevelCoupon, [EnumMember(Value = "document_level_coupon")] DocumentLevelCoupon, [EnumMember(Value = "promotional_credits")] PromotionalCredits, [EnumMember(Value = "prorated_credits")] ProratedCredits, [EnumMember(Value = "item_level_discount")] ItemLevelDiscount, [EnumMember(Value = "document_level_discount")] DocumentLevelDiscount, } public int Amount { get { return GetValue<int>("amount", true); } } public string Description { get { return GetValue<string>("description", false); } } public EntityTypeEnum EntityType { get { return GetEnum<EntityTypeEnum>("entity_type", true); } } public string EntityId { get { return GetValue<string>("entity_id", false); } } } public class CreditNoteLineItemDiscount : Resource { public enum DiscountTypeEnum { UnKnown, /*Indicates unexpected value for this enum. You can get this when there is a dotnet-client version incompatibility. We suggest you to upgrade to the latest version */ [EnumMember(Value = "item_level_coupon")] ItemLevelCoupon, [EnumMember(Value = "document_level_coupon")] DocumentLevelCoupon, [EnumMember(Value = "promotional_credits")] PromotionalCredits, [EnumMember(Value = "prorated_credits")] ProratedCredits, [EnumMember(Value = "item_level_discount")] ItemLevelDiscount, [EnumMember(Value = "document_level_discount")] DocumentLevelDiscount, } public string LineItemId { get { return GetValue<string>("line_item_id", true); } } public DiscountTypeEnum DiscountType { get { return GetEnum<DiscountTypeEnum>("discount_type", true); } } public string CouponId { get { return GetValue<string>("coupon_id", false); } } public string EntityId { get { return GetValue<string>("entity_id", false); } } public int DiscountAmount { get { return GetValue<int>("discount_amount", true); } } } public class CreditNoteLineItemTier : Resource { public string LineItemId { get { return GetValue<string>("line_item_id", false); } } public int StartingUnit { get { return GetValue<int>("starting_unit", true); } } public int? EndingUnit { get { return GetValue<int?>("ending_unit", false); } } public int QuantityUsed { get { return GetValue<int>("quantity_used", true); } } public int UnitAmount { get { return GetValue<int>("unit_amount", true); } } public string StartingUnitInDecimal { get { return GetValue<string>("starting_unit_in_decimal", false); } } public string EndingUnitInDecimal { get { return GetValue<string>("ending_unit_in_decimal", false); } } public string QuantityUsedInDecimal { get { return GetValue<string>("quantity_used_in_decimal", false); } } public string UnitAmountInDecimal { get { return GetValue<string>("unit_amount_in_decimal", false); } } } public class CreditNoteTax : Resource { public string Name { get { return GetValue<string>("name", true); } } public int Amount { get { return GetValue<int>("amount", true); } } public string Description { get { return GetValue<string>("description", false); } } } public class CreditNoteLineItemTax : Resource { public string LineItemId { get { return GetValue<string>("line_item_id", false); } } public string TaxName { get { return GetValue<string>("tax_name", true); } } public double TaxRate { get { return GetValue<double>("tax_rate", true); } } public bool? IsPartialTaxApplied { get { return GetValue<bool?>("is_partial_tax_applied", false); } } public bool? IsNonComplianceTax { get { return GetValue<bool?>("is_non_compliance_tax", false); } } public int TaxableAmount { get { return GetValue<int>("taxable_amount", true); } } public int TaxAmount { get { return GetValue<int>("tax_amount", true); } } public TaxJurisTypeEnum? TaxJurisType { get { return GetEnum<TaxJurisTypeEnum>("tax_juris_type", false); } } public string TaxJurisName { get { return GetValue<string>("tax_juris_name", false); } } public string TaxJurisCode { get { return GetValue<string>("tax_juris_code", false); } } public int? TaxAmountInLocalCurrency { get { return GetValue<int?>("tax_amount_in_local_currency", false); } } public string LocalCurrencyCode { get { return GetValue<string>("local_currency_code", false); } } } public class CreditNoteLinkedRefund : Resource { public string TxnId { get { return GetValue<string>("txn_id", true); } } public int AppliedAmount { get { return GetValue<int>("applied_amount", true); } } public DateTime AppliedAt { get { return (DateTime)GetDateTime("applied_at", true); } } public Transaction.StatusEnum? TxnStatus { get { return GetEnum<Transaction.StatusEnum>("txn_status", false); } } public DateTime? TxnDate { get { return GetDateTime("txn_date", false); } } public int? TxnAmount { get { return GetValue<int?>("txn_amount", false); } } public string RefundReasonCode { get { return GetValue<string>("refund_reason_code", false); } } } public class CreditNoteAllocation : Resource { public string InvoiceId { get { return GetValue<string>("invoice_id", true); } } public int AllocatedAmount { get { return GetValue<int>("allocated_amount", true); } } public DateTime AllocatedAt { get { return (DateTime)GetDateTime("allocated_at", true); } } public DateTime? InvoiceDate { get { return GetDateTime("invoice_date", false); } } public Invoice.StatusEnum InvoiceStatus { get { return GetEnum<Invoice.StatusEnum>("invoice_status", true); } } } #endregion } }
#region Copyright (c) 2003-2005, Luke T. Maxon /******************************************************************************************************************** ' ' Copyright (c) 2003-2005, Luke T. Maxon ' 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 author 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.Reflection; using System.Windows.Forms; using Xunit.Extensions.Forms.SendKey; using Xunit.Extensions.Forms.Win32Interop; using Xunit; namespace Xunit.Extensions.Forms { /// <summary> /// One of three base classes for your XunitForms tests. This one can be /// used by people who do not need or want "built-in" Assert functionality. /// /// This is the recommended base class for all unit tests that use XunitForms. /// </summary> /// <remarks> /// You should probably extend this class to create all of your test fixtures. The benefit is that /// this class implements setup and teardown methods that clean up after your test. Any forms that /// are created and displayed during your test are cleaned up by the tear down method. This base /// class also provides easy access to keyboard and mouse controllers. It has a method that allows /// you to set up a handler for modal dialog boxes. It allows your tests to run on a separate /// (usually hidden) desktop so that they are faster and do not interfere with your normal desktop /// activity. If you want custom setup and teardown behavior, you should override the virtual /// Setup and TearDown methods. Do not use the setup and teardown attributes in your child class. /// </remarks> public class XunitFormTest : IDisposable { private static readonly FieldInfo isUserInteractive = typeof (SystemInformation).GetField("isUserInteractive", BindingFlags.Static | BindingFlags.NonPublic); private KeyboardController keyboard = null; private ModalFormTester modal; private MouseController mouse = null; private Desktop testDesktop; /// <summary> /// True if the modal handlers for this test have been verified; else false. /// </summary> /// <remarks> /// It would be better form to make this private and provide a protected getter property, though /// that could break existing tests. /// </remarks> protected bool verified = false; /// <summary> /// This property controls whether the separate hidden desktop is displayed for the duration of /// this test. You will need to override and return true from this property if your test makes /// use of the keyboard or mouse controllers. (The hidden desktop cannot accept user input.) For /// tests that do not use the keyboard and mouse controller (most should not) you don't need to do /// anything with this. The default behavior is fine. /// </summary> public virtual bool DisplayHidden { get { return false; } } /// <summary> /// This property controls whether a separate desktop is used at all. Tests on the separate desktop /// are faster and safer (there is no danger of keyboard or mouse input going to your own separate /// running applications). However, it fails on some systems; also, it is not possible to unlock /// by hand a blocked test (e.g. due to a modal form). In order to enable it, you can override /// this method from your test class to return true. Or you can set an environment variable called /// "UseHiddenDesktop" and set that to "true". /// </summary> public virtual bool UseHidden { get { string useHiddenDesktop = Environment.GetEnvironmentVariable("UseHiddenDesktop"); if (useHiddenDesktop != null && useHiddenDesktop.ToUpper().Equals("TRUE")) { return true; } return false; } } /// <summary> /// Returns a reference to the current MouseController for doing Mouse tests. I recommend /// this only when you are writing your own custom controls and need to respond to actual /// mouse input to test them properly. In most other cases there is a better way to test /// the form's logic. /// </summary> public MouseController Mouse { get { return mouse; } } /// <summary> /// Returns a reference to the current KeyboardController for doing Keyboard tests. I recommend /// this only when you are writing your own custom controls and need to respond to actual /// keyboard input to test them properly. In most other cases there is a better way to test /// for the form's logic. /// </summary> public KeyboardController Keyboard { get { return keyboard; } } /// <summary> /// Records a single shot modal form handler. The handler receives as arguments the title of the window, /// its handle, and the corresponding form (null if it is not a form, i.e. a dialog box). The handler is /// single shot: it is removed after being run; therefore, if it is expected to trigger a new modal form, /// it should install a new handler before returning. The handler can work on dialog boxes by creating /// a message box tester or file dialog tester, passing the handle of the box (its second argument) to the /// tester's constructor. The tester constructors taking as argument the box title are unreliable and deprecated. /// </summary> public ModalFormHandler ModalFormHandler { get { return modal.FormHandler; } set { modal.FormHandler = value; } } /// <summary> /// Shorter version of ModalFormHandler without the form argument; meant for dialogs. /// </summary> public DialogBoxHandler DialogBoxHandler { set { if (value == null) { ModalFormHandler = null; return; } ModalFormHandler = delegate(string name, IntPtr hWnd, Form form) { value(name, hWnd); }; } } /// <summary> /// This is the base classes setup method. It will be called by Xunit before each test. /// You should not have anything to do with it. /// </summary> public XunitFormTest() { verified = false; if (!SystemInformation.UserInteractive) { isUserInteractive.SetValue(null, true); } if (UseHidden) { testDesktop = new Desktop("XunitForms Test Desktop", DisplayHidden); } modal = new ModalFormTester(); mouse = new MouseController(); keyboard = new KeyboardController(new OldSendKeysFactory()); Util.GetMessageHook.InstallHook(); Setup(); } /// <summary> /// A patch method to allow migration to an alternative SendKeys class instead /// of the dot Net SendKeys class. Once the new class is completed this method /// will be replaced by a method to allow use of the dot Net class. /// /// This method must only be called at the start of the test fixture's overriden /// SetUp(). /// </summary> protected void EmulateSendKeys() { keyboard = new KeyboardController(new SendKeysFactory(new SendKeysParserFactory(), new SendKeyboardInput())); } /// <summary> /// A patch method to allow migration to an alternative SendKeys class instead /// of the dot Net SendKeys class. Once the new class is completed this method /// will be replaced by a method to allow use of the dot Net class. /// /// This method must only be called at the start of the test fixture's overriden /// SetUp(). /// </summary> protected void EmulateWindowSpecificSendKeys() { keyboard = new KeyboardController( new SendKeysFactory(new SendKeysParserFactory(), new WindowSpecificSendKeyboardInput())); } /// <summary> /// Override this Setup method if you have custom behavior to execute before each test /// in your fixture. /// </summary> public virtual void Setup() { } /// <summary> /// This method is called by Xunit after each test runs. If you have custom /// behavior to run after each test, then override the TearDown method and do /// it there. That method is called at the beginning of this one. /// You should not need to do anything with it. Do not call it. /// If you do call it, call it as the last thing you do in your test. /// </summary> public void Verify() { try { TearDown(); Util.GetMessageHook.RemoveHook(); if (ModalFormHandler == null) { // Make an effort to ensure that no window message is left dangling // Such a message might cause an unexpected dialog box for (int i = 0; i < 10; ++i) { Application.DoEvents(); } } if (!verified) { verified = true; List<Form> allForms = new FormFinder().FindAll(); foreach (Form form in allForms) { if (!KeepAlive.ShouldKeepAlive(form)) { form.Dispose(); form.Hide(); } } string[] errors = new string[0]; ModalFormTester.Result modalResult = modal.Verify(); if (!modalResult.AllModalsShown) { throw new FormsTestAssertionException("Expected Modal Form did not show"); } if (modalResult.UnexpectedModalWasShown) { string msg = "Unexpected modals: "; foreach (string mod in modalResult.UnexpectedModals) { msg += mod + ", "; } throw new FormsTestAssertionException(msg); } modal.Dispose(); if (UseHidden) { testDesktop.Dispose(); } } } finally { modal.Dispose(); mouse.Dispose(); keyboard.Dispose(); } } /// <summary> /// Override this TearDown method if you have custom behavior to execute after each test /// in your fixture. /// </summary> public virtual void TearDown() { } // Deprecated modal handling interface /// <summary> /// Unreliable. Deprecated in favor of ModalFormHandler/ModalDialogHandler. /// </summary> [Obsolete] protected void ExpectFileDialog(string modalHandler) { ExpectModal(FileDialogTester.InitialFileDialogName, modalHandler); } /// <summary> /// Unreliable. Deprecated in favor of ModalFormHandler/ModalDialogHandler. /// </summary> [Obsolete] protected void ExpectFileDialog(string modalHandler, bool expected) { ExpectModal(FileDialogTester.InitialFileDialogName, modalHandler, expected); } /// <summary> /// Unreliable. Deprecated in favor of ModalFormHandler/ModalDialogHandler. /// </summary> [Obsolete] protected void ExpectFileDialog(ModalFormActivated handler) { modal.ExpectModal(FileDialogTester.InitialFileDialogName, handler, true); } /// <summary> /// Unreliable. Deprecated in favor of ModalFormHandler/ModalDialogHandler. /// </summary> [Obsolete] protected void ExpectFileDialog(ModalFormActivated handler, bool expected) { modal.ExpectModal(FileDialogTester.InitialFileDialogName, handler, true); } /// <summary> /// Deprecated in favor of ModalFormHandler/ModalDialogHandler. /// </summary> [Obsolete] protected void ExpectModal(string name, ModalFormActivated handler) { modal.ExpectModal(name, handler, true); } /// <summary> /// Deprecated in favor of ModalFormHandler/ModalDialogHandler. /// </summary> [Obsolete] protected void ExpectModal(string name, ModalFormActivated handler, bool expected) { modal.ExpectModal(name, handler, expected); } /// <summary> /// Deprecated in favor of ModalFormHandler/ModalDialogHandler. /// </summary> [Obsolete] protected void ExpectModal(string name, string handlerName, bool expected) { ExpectModal(name, (ModalFormActivated)Delegate.CreateDelegate(typeof(ModalFormActivated), this, handlerName), expected); } /// <summary> /// Deprecated in favor of ModalFormHandler/ModalDialogHandler. /// </summary> [Obsolete] protected void ExpectModal(string name, string handlerName) { ExpectModal(name, handlerName, true); } #region IDisposable Members public void Dispose() { Verify(); } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using UnityEngine; using UnityEngine.Networking; public class CaptainsMessNetworkManager : CaptainsMessLobbyManager { public string broadcastIdentifier = "CM"; public string deviceId; public string peerId; public float startHostingDelay = 2; // Look for a server for this many seconds before starting one ourself public float allReadyCountdownDuration = 4; // Wait for this many seconds after people are ready before starting the game public bool verboseLogging = false; public CaptainsMessServer discoveryServer; public CaptainsMessClient discoveryClient; public CaptainsMessListener listener; public CaptainsMessPlayer localPlayer; public float allReadyCountdown = 0; public bool forceServer = false; private string maybeStartHostingFunction; private bool gameHasStarted = false; private bool joinedLobby = false; public virtual void Start () { deviceId = GetUniqueDeviceId(); peerId = deviceId.Substring(0, 8); discoveryServer.Setup(this); discoveryClient.Setup(this); if (singleton != this) { Debug.LogWarning("#CaptainsMess# DUPLICATE CAPTAINS MESS!"); Destroy(gameObject); } Debug.Log(String.Format("#CaptainsMess# Initialized peer {0}, \'{1}\', {2}-{3} players", peerId, broadcastIdentifier, minPlayers, maxPlayers)); } string GetUniqueDeviceId() { // NOTE: Don't use SystemInfo.deviceUniqueIdentifier here because it causes Android // to ask for permission to "make and manage phone calls?" which sounds suspicious. // Using this alternate method means that the ID isn't truly unique. Each time the app is // uninstalled/reinstalled a new ID will be generated. // This won't matter for normal connections but might matter if you want to use the ID // to track unique players met (eg. Spaceteam has achievements for number of players met). string savedId = PlayerPrefs.GetString("CaptainsMessDeviceId"); if (string.IsNullOrEmpty(savedId)) { savedId = GenerateNewUniqueID(); PlayerPrefs.SetString("CaptainsMessDeviceId", savedId); } return savedId; } string GenerateNewUniqueID() { return Guid.NewGuid().ToString().Substring(0,8); } public void InitNetworkTransport() { NetworkTransport.Init(); } public void ShutdownNetworkTransport() { NetworkTransport.Shutdown(); } public void StartHosting() { if (verboseLogging) { Debug.Log("#CaptainsMess# StartHosting"); } // Stop the broadcast server so we can start a regular hosting server StopServer(); // Delay briefly to let things settle down CancelInvoke("StartHostingInternal"); Invoke("StartHostingInternal", 0.5f); discoveryServer.isOpen = true; discoveryServer.RestartBroadcast(); } private void StartHostingInternal() { if (StartHost() != null) { SendServerCreatedMessage(); } else { Debug.LogError("#CaptainsMess# Failed to start hosting!"); } } public void StartLocalGameForDebugging() { if (StartHost() != null) { SendServerCreatedMessage(); } else { Debug.LogError("#CaptainsMess# Failed to start hosting!"); } } public void StartBroadcasting() { if (!isNetworkActive) { // Must also start network server so the broadcast is sent properly if (!StartServer()) { Debug.LogError("#CaptainsMess# Failed to start broadcasting!"); return; } } const int HIGH_SERVER_SCORE = 999; discoveryServer.isOpen = false; discoveryServer.serverScore = forceServer ? HIGH_SERVER_SCORE : 1; discoveryServer.RestartBroadcast(); } public void StartJoining() { discoveryClient.StartJoining(); SendStartConnectingMessage(); } public void AutoConnect() { StartBroadcasting(); StartJoining(); // Start hosting if we don't find anything for a while... maybeStartHostingFunction = "MaybeStartHosting"; Invoke(maybeStartHostingFunction, startHostingDelay); } public void Cancel() { if (verboseLogging) { Debug.Log("#CaptainsMess# Cancelling!"); } if (gameHasStarted) { if (IsHost()) { SendAbortGameMessage(); } gameHasStarted = false; Invoke("Cancel", 0.1f); return; } // NOTE: Calling CancelInvoke(maybeStartHostingFunction) here crashes the game in certain cases // so I'm using the more general version instead. CancelInvoke(); if (discoveryClient.running && discoveryClient.hostId != -1) { discoveryClient.StopBroadcast(); } discoveryClient.Reset(); if (discoveryServer.running && discoveryServer.hostId != -1) { discoveryServer.StopBroadcast(); } discoveryServer.Reset(); StopClient(); StopServer(); if (NetworkServer.active) { NetworkServer.Reset(); } } public void FinishGame() { gameHasStarted = false; } public void OnReceivedBroadcast(string aFromAddress, string aData) { SendReceivedBroadcastMessage(aFromAddress, aData); } public void OnDiscoveredServer(DiscoveredServer aServer) { if (verboseLogging) { Debug.Log("#CaptainsMess# Discovered " + aServer.rawData); } if (discoveryServer.isOpen) { Debug.Log("#CaptainsMess# Already hosting a server, ignoring " + aServer.rawData); return; } SendDiscoveredServerMessage(aServer); bool shouldJoin = false; bool isMe = (aServer.peerId == peerId); if (!isMe) { if (aServer.isOpen && aServer.numPlayers < maxPlayers) { if (aServer.privateTeamKey == discoveryServer.privateTeamKey) { if (aServer.numPlayers > 0) { shouldJoin = true; // Pick the first server that already has players } else if (BestHostingCandidate() == aServer.peerId) { shouldJoin = true; } } } } if (shouldJoin) { if (verboseLogging) { Debug.Log("#CaptainsMess# Should join!"); } // We found something! Cancel hosting... CancelInvoke(maybeStartHostingFunction); if (client == null) { if (discoveryClient.autoJoin) { JoinServer(aServer.ipAddress, networkPort); } else { if (verboseLogging) { Debug.Log("#CaptainsMess# JOIN CANCELED: Auto join disabled."); } } } else { if (verboseLogging) { Debug.Log("#CaptainsMess# JOIN CANCELED: Already have client."); } } } else { if (verboseLogging) { Debug.Log("#CaptainsMess# Should NOT join."); } } } void MaybeStartHosting() { // If I'm the best candidate, start hosting! int numCandidates = GetHostingCandidates().Count; bool enoughPlayers = (numCandidates >= minPlayers); if (verboseLogging) { Debug.Log("#CaptainsMess# MaybeStartHosting? Found " + numCandidates + "/" + minPlayers + " candidates"); } if (enoughPlayers && BestHostingCandidate() == peerId) { StartHosting(); } else { // Wait, then try again... Invoke(maybeStartHostingFunction, startHostingDelay); } } List<DiscoveredServer> GetHostingCandidates() { var candidates = new List<DiscoveredServer>(); // Grab server peer IDs foreach (DiscoveredServer server in discoveryClient.discoveredServers.Values) { if (server.numPlayers < 2 && !server.isOpen && (server.privateTeamKey == discoveryServer.privateTeamKey)) { if (!candidates.Exists(x => x.peerId == server.peerId)) { candidates.Add(server); } else { if (verboseLogging) { Debug.LogWarning("#CaptainsMess# Discovered duplicate server!"); } } } } if (verboseLogging) { Debug.Log("#CaptainsMess# Hosting candidates: " + String.Join(",", candidates.Select(x => x.ToString()).ToArray())); } return candidates; } string BestHostingCandidate() { var allCandidates = GetHostingCandidates(); if (allCandidates.Count < minPlayers) { return ""; } allCandidates.Sort((x,y) => { if (x.serverScore != y.serverScore) { // Pick highest serverScore first return y.serverScore.CompareTo(x.serverScore); } else { // Otherwise, pick lowest peer ID (arbitrary, maybe change to fastest/best device?) return x.peerId.CompareTo(y.peerId); } }); string bestCandidate = allCandidates[0].peerId; if (verboseLogging) { Debug.Log("#CaptainsMess# Picked " + bestCandidate + " as best candidate"); } return bestCandidate; } void JoinServer(string aAddress, int aPort) { if (verboseLogging) { Debug.Log("#CaptainsMess# Joining " + aAddress + " : " + aPort); } // Stop being a server StopHost(); networkAddress = aAddress; networkPort = aPort; // Delay briefly to let things settle down CancelInvoke("JoinServerInternal"); Invoke("JoinServerInternal", 0.5f); } private void JoinServerInternal() { StartClient(); } public bool AreAllPlayersReady() { return (NumReadyPlayers() == NumPlayers() && NumPlayers() >= minPlayers); } public bool AreAllPlayersCompatible() { int highestVersion = HighestConnectedVersion(); foreach (var player in LobbyPlayers()) { if (player.version != highestVersion) { return false; } } return true; } public int HighestConnectedVersion() { int highestVersion = 0; foreach (CaptainsMessPlayer p in LobbyPlayers()) { highestVersion = Math.Max(highestVersion, p.version); } return highestVersion; } public List<CaptainsMessPlayer> LobbyPlayers() { var lobbyPlayers = new List<CaptainsMessPlayer>(); foreach (var player in lobbySlots) { if (player != null) { lobbyPlayers.Add(player); } } return lobbyPlayers; } public int NumReadyPlayers() { int readyCount = 0; foreach (var player in LobbyPlayers()) { if (player.ready) { readyCount += 1; } } return readyCount; } public int NumPlayers() { return LobbyPlayers().Count; } public bool IsHost() { if (localPlayer != null) { NetworkIdentity networkObject = localPlayer.GetComponent<NetworkIdentity>(); return (networkObject != null && networkObject.isServer && IsClientConnected() && NumPlayers() >= minPlayers); } else { return false; } } public void Update() { CheckAllReady(); } public void CheckAllReady() { if (!gameHasStarted && allReadyCountdown > 0) { if (AreAllPlayersReady() && AreAllPlayersCompatible()) { allReadyCountdown -= Time.deltaTime; if (allReadyCountdown <= 0) { // Stop the broadcast so no more players join if (discoveryServer.running) { discoveryServer.StopBroadcast(); } // Finalize player list gameHasStarted = true; if (IsHost()) { SendStartGameMessage(LobbyPlayers()); } } } else { // Cancel the countdown allReadyCountdown = 0; if (IsHost()) { SendCountdownCancelledMessage(); } } } } public bool IsBroadcasting() { return discoveryServer.running; } public bool IsJoining() { return discoveryClient.running; } public bool IsConnected() { return IsClientConnected(); } public void CheckReadyToBegin() { if (AreAllPlayersReady() && AreAllPlayersCompatible()) { OnLobbyServerPlayersReady(); } } public override bool HasGameStarted() { return gameHasStarted; } public void SetPrivateTeamKey(string key) { discoveryServer.privateTeamKey = key; } // ------------------------ lobby server virtuals ------------------------ public override void OnLobbyServerConnect(NetworkConnection conn) { if (verboseLogging) { Debug.Log("#CaptainsMess# OnLobbyServerConnect (num players = " + NumPlayers() + ")"); } // If we've reached max players, stop the broadcast if (NumPlayers()+1 >= maxPlayers) { if (verboseLogging) { Debug.Log("#CaptainsMess# Max players reached, stopping broadcast"); } if (discoveryServer.running) { discoveryServer.StopBroadcast(); } } else { // Update player count for broadcast discoveryServer.numPlayers = NumPlayers() + 1; discoveryServer.RestartBroadcast(); } } public override void OnLobbyServerDisconnect(NetworkConnection conn) { if (verboseLogging) { Debug.Log("#CaptainsMess# OnLobbyServerDisconnect (num players = " + NumPlayers() + ")"); } if (gameHasStarted) { // Always cancel the game if it has started. We don't support re-joining a game in progress. Cancel(); } else { // If we're below the minimum required players, close the lobby if (NumPlayers() < minPlayers) { if (verboseLogging) { Debug.Log("#CaptainsMess# Not enough players, cancelling game"); } Cancel(); } else { if (allReadyCountdown > 0) { // Cancel the countdown allReadyCountdown = 0; SendCountdownCancelledMessage(); } // Update player count for broadcast discoveryServer.numPlayers = NumPlayers(); discoveryServer.RestartBroadcast(); } } } public override GameObject OnLobbyServerCreateLobbyPlayer(NetworkConnection conn, short playerControllerId) { if (verboseLogging) { Debug.Log("#CaptainsMess# OnLobbyServerCreateLobbyPlayer (num players " + NumPlayers() + ")"); } GameObject newLobbyPlayer = Instantiate(playerPrefab.gameObject, Vector3.zero, Quaternion.identity) as GameObject; return newLobbyPlayer; } public override void OnLobbyServerPlayersReady() { if (verboseLogging) { Debug.Log("#CaptainsMess# OnLobbyServerPlayersReady (num players " + NumPlayers() + ")"); } if (AreAllPlayersReady() && AreAllPlayersCompatible()) { if (allReadyCountdownDuration > 0) { // Start all ready countdown allReadyCountdown = allReadyCountdownDuration; SendCountdownStartedMessage(); } else { // Stop the broadcast so no more players join if (discoveryServer.running) { discoveryServer.StopBroadcast(); } // Start game immediately gameHasStarted = true; SendStartGameMessage(LobbyPlayers()); } } } // ------------------------ lobby client virtuals ------------------------ public override void OnLobbyClientEnter() { if (verboseLogging) { Debug.Log("#CaptainsMess# OnLobbyClientEnter " + listener); } // Stop listening for other servers if (discoveryClient.running) { discoveryClient.StopBroadcast(); } // Stop broadcasting as a server if (discoveryServer.running) { discoveryServer.StopBroadcast(); } SendJoinedLobbyMessage(); joinedLobby = true; } public override void OnLobbyClientExit() { if (verboseLogging) { Debug.Log("#CaptainsMess# OnLobbyClientExit (num players = " + numPlayers + ")"); } if (gameHasStarted) { if (IsHost()) { SendAbortGameMessage(); } gameHasStarted = false; } // Check to see if we've actually joined a lobby if (joinedLobby) { SendLeftLobbyMessage(); } else { SendStopConnectingMessage(); } joinedLobby = false; } //////////////////////////////////////////////////////////////////////////////// // // API messages // public void SendServerCreatedMessage() { listener.OnServerCreated(); } public void SendStartConnectingMessage() { listener.OnStartConnecting(); } public void SendStopConnectingMessage() { listener.OnStopConnecting(); } public void SendReceivedBroadcastMessage(string aFromAddress, string aData) { listener.OnReceivedBroadcast(aFromAddress, aData); } public void SendDiscoveredServerMessage(DiscoveredServer aServer) { listener.OnDiscoveredServer(aServer); } public void SendJoinedLobbyMessage() { listener.OnJoinedLobby(); } public void SendLeftLobbyMessage() { listener.OnLeftLobby(); } public void SendCountdownStartedMessage() { listener.OnCountdownStarted(); } public void SendCountdownCancelledMessage() { listener.OnCountdownCancelled(); } public void SendStartGameMessage(List<CaptainsMessPlayer> aStartingPlayers) { listener.OnStartGame(aStartingPlayers); } public void SendAbortGameMessage() { listener.OnAbortGame(); } }
// GtkSharp.Generation.Method.cs - The Method Generatable. // // Author: Mike Kestner <mkestner@speakeasy.net> // // Copyright (c) 2001-2003 Mike Kestner // Copyright (c) 2003-2004 Novell, Inc. // // This program is free software; you can redistribute it and/or // modify it under the terms of version 2 of the GNU General Public // License as published by the Free Software Foundation. // // 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., 51 Franklin Street, Fifth Floor, // Boston, MA 02110-1301 namespace GtkSharp.Generation { using System; using System.Collections; using System.IO; using System.Xml; public class Method : MethodBase { private ReturnValue retval; private string call; private bool is_get, is_set; private bool deprecated = false; public Method (XmlElement elem, ClassBase container_type) : base (elem, container_type) { this.retval = new ReturnValue (elem["return-type"]); if (!container_type.IsDeprecated && elem.HasAttribute ("deprecated")) { string attr = elem.GetAttribute ("deprecated"); deprecated = attr == "1" || attr == "true"; } if (Name == "GetType") Name = "GetGType"; } public bool IsDeprecated { get { return deprecated; } } public bool IsGetter { get { return is_get; } } public bool IsSetter { get { return is_set; } } public string ReturnType { get { return retval.CSType; } } public override bool Validate () { if (!retval.Validate () || !base.Validate ()) { Console.Write(" in method " + Name + " "); return false; } Parameters parms = Parameters; is_get = ((((parms.IsAccessor && retval.IsVoid) || (parms.Count == 0 && !retval.IsVoid)) || (parms.Count == 0 && !retval.IsVoid)) && HasGetterName); is_set = ((parms.IsAccessor || (parms.VisibleCount == 1 && retval.IsVoid)) && HasSetterName); call = "(" + (IsStatic ? "" : container_type.CallByName () + (parms.Count > 0 ? ", " : "")) + Body.GetCallString (is_set) + ")"; return true; } private Method GetComplement () { char complement; if (is_get) complement = 'S'; else complement = 'G'; return container_type.GetMethod (complement + BaseName.Substring (1)); } public string Declaration { get { return retval.CSType + " " + Name + " (" + (Signature != null ? Signature.ToString() : "") + ");"; } } private void GenerateDeclCommon (StreamWriter sw, ClassBase implementor) { if (IsStatic) sw.Write("static "); sw.Write (Safety); Method dup = null; if (container_type != null) dup = container_type.GetMethodRecursively (Name); if (implementor != null) dup = implementor.GetMethodRecursively (Name); if (Name == "ToString" && Parameters.Count == 0) sw.Write("override "); else if (Name == "GetGType" && container_type is ObjectGen) sw.Write("new "); else if (Modifiers == "new " || (dup != null && ((dup.Signature != null && Signature != null && dup.Signature.ToString() == Signature.ToString()) || (dup.Signature == null && Signature == null)))) sw.Write("new "); if (is_get || is_set) { if (retval.IsVoid) sw.Write (Parameters.AccessorReturnType); else sw.Write(retval.CSType); sw.Write(" "); if (Name.StartsWith ("Get") || Name.StartsWith ("Set")) sw.Write (Name.Substring (3)); else { int dot = Name.LastIndexOf ('.'); if (dot != -1 && (Name.Substring (dot + 1, 3) == "Get" || Name.Substring (dot + 1, 3) == "Set")) sw.Write (Name.Substring (0, dot + 1) + Name.Substring (dot + 4)); else sw.Write (Name); } sw.WriteLine(" { "); } else if (IsAccessor) { sw.Write (Signature.AccessorType + " " + Name + "(" + Signature.AsAccessor + ")"); } else { sw.Write(retval.CSType + " " + Name + "(" + (Signature != null ? Signature.ToString() : "") + ")"); } } public void GenerateDecl (StreamWriter sw) { if (IsStatic) return; if (is_get || is_set) { Method comp = GetComplement (); if (comp != null && is_set) return; sw.Write("\t\t"); GenerateDeclCommon (sw, null); sw.Write("\t\t\t"); sw.Write ((is_get) ? "get;" : "set;"); if (comp != null && comp.is_set) sw.WriteLine (" set;"); else sw.WriteLine (); sw.WriteLine ("\t\t}"); } else { sw.Write("\t\t"); GenerateDeclCommon (sw, null); sw.WriteLine (";"); } Statistics.MethodCount++; } public void GenerateImport (StreamWriter sw) { string import_sig = IsStatic ? "" : container_type.MarshalType + " raw"; import_sig += !IsStatic && Parameters.Count > 0 ? ", " : ""; import_sig += Parameters.ImportSignature.ToString(); sw.WriteLine("\t\t[DllImport(\"" + LibraryName + "\")]"); if (retval.MarshalType.StartsWith ("[return:")) sw.WriteLine("\t\t" + retval.MarshalType + " static extern " + Safety + retval.CSType + " " + CName + "(" + import_sig + ");"); else sw.WriteLine("\t\tstatic extern " + Safety + retval.MarshalType + " " + CName + "(" + import_sig + ");"); sw.WriteLine(); } public void Generate (GenerationInfo gen_info, ClassBase implementor) { if (!Validate ()) return; Method comp = null; gen_info.CurrentMember = Name; /* we are generated by the get Method, if there is one */ if (is_set || is_get) { if (Modifiers != "new " && container_type.GetPropertyRecursively (Name.Substring (3)) != null) return; comp = GetComplement (); if (comp != null && is_set) { if (Parameters.AccessorReturnType == comp.ReturnType) return; else { is_set = false; call = "(Handle, " + Body.GetCallString (false) + ")"; comp = null; } } /* some setters take more than one arg */ if (comp != null && !comp.is_set) comp = null; } GenerateImport (gen_info.Writer); if (comp != null && retval.CSType == comp.Parameters.AccessorReturnType) comp.GenerateImport (gen_info.Writer); if (IsDeprecated) gen_info.Writer.WriteLine("\t\t[Obsolete]"); gen_info.Writer.Write("\t\t"); if (Protection != "") gen_info.Writer.Write("{0} ", Protection); GenerateDeclCommon (gen_info.Writer, implementor); if (is_get || is_set) { gen_info.Writer.Write ("\t\t\t"); gen_info.Writer.Write ((is_get) ? "get" : "set"); GenerateBody (gen_info, implementor, "\t"); } else GenerateBody (gen_info, implementor, ""); if (is_get || is_set) { if (comp != null && retval.CSType == comp.Parameters.AccessorReturnType) { gen_info.Writer.WriteLine (); gen_info.Writer.Write ("\t\t\tset"); comp.GenerateBody (gen_info, implementor, "\t"); } gen_info.Writer.WriteLine (); gen_info.Writer.WriteLine ("\t\t}"); } else gen_info.Writer.WriteLine(); gen_info.Writer.WriteLine(); Statistics.MethodCount++; } public void GenerateBody (GenerationInfo gen_info, ClassBase implementor, string indent) { StreamWriter sw = gen_info.Writer; sw.WriteLine(" {"); if (!IsStatic && implementor != null) implementor.Prepare (sw, indent + "\t\t\t"); if (IsAccessor) Body.InitAccessor (sw, Signature, indent); Body.Initialize(gen_info, is_get, is_set, indent); sw.Write(indent + "\t\t\t"); if (retval.IsVoid) sw.WriteLine(CName + call + ";"); else { sw.WriteLine(retval.MarshalType + " raw_ret = " + CName + call + ";"); sw.WriteLine(indent + "\t\t\t" + retval.CSType + " ret = " + retval.FromNative ("raw_ret") + ";"); } if (!IsStatic && implementor != null) implementor.Finish (sw, indent + "\t\t\t"); Body.Finish (sw, indent); Body.HandleException (sw, indent); if (is_get && Parameters.Count > 0) sw.WriteLine (indent + "\t\t\treturn " + Parameters.AccessorName + ";"); else if (!retval.IsVoid) sw.WriteLine (indent + "\t\t\treturn ret;"); else if (IsAccessor) Body.FinishAccessor (sw, Signature, indent); sw.Write(indent + "\t\t}"); } bool IsAccessor { get { return retval.IsVoid && Signature.IsAccessor; } } } }
using UnityEngine; using System.Collections; using Zeltex.Game; using Zeltex; namespace Zeltex.Skeletons { /// <summary> /// Basic IK script used for aiming. /// </summary> public class IKLimb: MonoBehaviour { [Header("Debug")] public bool DebugMode = true; public bool DebugLines = false; public KeyCode MyToggleKey = KeyCode.F; [Header("Options")] public float LerpSpeed = 0.25f; public float ReverseLerpSpeed = 0.1f; private bool IsOptimize = false; private bool IsEnabled = false; [Header("References")] public bool IsAnimatingBackwards = false; //public CustomAnimator MyAnimator; public Transform upperArm, forearm, hand; public Transform target, elbowTarget; private Quaternion upperArmStartRotation, forearmStartRotation, handStartRotation; private Vector3 targetRelativeStartPosition, elbowTargetRelativeStartPosition; //helper GOs that are reused every frame private GameObject upperArmAxisCorrection, forearmAxisCorrection, handAxisCorrection; //hold last positions so recalculation is only done if needed private Vector3 lastUpperArmPosition, lastTargetPosition, lastElbowTargetPosition; // For Animation Part private float TimeBegun; private Quaternion DesiredUpperArmRotation; private Quaternion DesiredForearmRotation; private Quaternion DesiredHandRotation; private Quaternion OriginalUpperArmRotation; private Quaternion OriginalForearmRotation; private Quaternion OriginalHandRotation; public Player MyPlayer; void Start() { BeginIK (); } void Update () { if (target == null || upperArm == null || elbowTarget == null) { return; } if (MyPlayer) { if (Input.GetKeyDown (MyToggleKey)) { ToggleAim (); } } if (IsEnabled) { CalculateIK (); AnimateRotations (); } else { if (IsAnimatingBackwards) AnimateRotationsBackwards (); } } void AnimateRotations() { float AnimationSpeed = LerpSpeed * Time.deltaTime * (1000f/60f); upperArm.rotation = Quaternion.Slerp(DesiredUpperArmRotation, upperArm.rotation, AnimationSpeed); forearm.rotation = Quaternion.Slerp(DesiredForearmRotation, forearm.rotation, AnimationSpeed); hand.rotation = Quaternion.Slerp(DesiredHandRotation, hand.rotation, AnimationSpeed); } void AnimateRotationsBackwards() { float AnimationSpeed = ReverseLerpSpeed * Time.deltaTime * (1000f/60f); upperArm.rotation = Quaternion.Slerp(upperArm.rotation, OriginalUpperArmRotation, AnimationSpeed); forearm.rotation = Quaternion.Slerp(forearm.rotation, OriginalForearmRotation, AnimationSpeed); hand.rotation = Quaternion.Slerp(hand.rotation, OriginalHandRotation, AnimationSpeed); } public void ToggleAim() { if (IsEnabled) { StopAiming (); } else { StartAiming (); } } public void StartAiming() { if (!IsEnabled) { //Debug.LogError ("Started aiming at: " + Time.time); IsEnabled = true; TimeBegun = Time.time; // Turn on Masking //MyAnimator.IsMasking = true; } } public void StopAiming() { if (IsEnabled) { //Debug.LogError ("Stopped aiming at: " + Time.time); IsEnabled = false; StartCoroutine (StartAnimator ()); } } public bool IsAiming() { if (IsEnabled && Time.time - TimeBegun > 0.5f) { return true; } else { return false; } } IEnumerator StartAnimator() { IsAnimatingBackwards = true; yield return new WaitForSeconds(1f); if (!IsEnabled) // if already enabled aiming again { //MyAnimator.IsMasking = false; // starts the arms animation tweening again } IsAnimatingBackwards = false; } private void BeginIK() { if (target == null || upperArm == null || elbowTarget == null) { return; } LerpSpeed = Mathf.Clamp01(LerpSpeed); OriginalUpperArmRotation = upperArm.rotation; OriginalForearmRotation = forearm.rotation; OriginalHandRotation = hand.rotation; upperArmStartRotation = upperArm.rotation; forearmStartRotation = forearm.rotation; handStartRotation = hand.rotation; //targetRelativeStartPosition = target.position - upperArm.position; elbowTargetRelativeStartPosition = elbowTarget.position - upperArm.position; //create helper GOs upperArmAxisCorrection = new GameObject("upperArmAxisCorrection"); forearmAxisCorrection = new GameObject("forearmAxisCorrection"); handAxisCorrection = new GameObject("handAxisCorrection"); //set helper hierarchy upperArmAxisCorrection.transform.parent = transform; forearmAxisCorrection.transform.parent = upperArmAxisCorrection.transform; handAxisCorrection.transform.parent = forearmAxisCorrection.transform; //guarantee first-frame update lastUpperArmPosition = upperArm.position + 5*Vector3.up; } private void CalculateIK() { if (target == null || upperArm == null || elbowTarget == null) { targetRelativeStartPosition = Vector3.zero; return; } float TimeBegin = Time.realtimeSinceStartup; if(targetRelativeStartPosition == Vector3.zero && target != null && upperArm != null) { targetRelativeStartPosition = target.position - upperArm.position; } if(IsOptimize && lastUpperArmPosition == upperArm.position && lastTargetPosition == target.position && lastElbowTargetPosition == elbowTarget.position) { if(DebugLines) { Debug.DrawLine(forearm.position, elbowTarget.position, Color.yellow); Debug.DrawLine(upperArm.position, target.position, Color.red); } return; } lastUpperArmPosition = upperArm.position; lastTargetPosition = target.position; lastElbowTargetPosition = elbowTarget.position; //Calculate ikAngle variable. float upperArmLength = Vector3.Distance(upperArm.position, forearm.position); float forearmLength = Vector3.Distance(forearm.position, hand.position); float armLength = upperArmLength + forearmLength; float hypotenuse = upperArmLength; float targetDistance = Vector3.Distance(upperArm.position, target.position); targetDistance = Mathf.Min(targetDistance, armLength - 0.0001f); //Do not allow target distance be further away than the arm's length. //var adjacent : float = (targetDistance * hypotenuse) / armLength; //var adjacent : float = (Mathf.Pow(hypotenuse,2) - Mathf.Pow(forearmLength,2) + Mathf.Pow(targetDistance,2))/(2*targetDistance); float adjacent = (hypotenuse*hypotenuse - forearmLength*forearmLength + targetDistance*targetDistance) /(2*targetDistance); float ikAngle = Mathf.Acos(adjacent/hypotenuse) * Mathf.Rad2Deg; //Store pre-ik info. Vector3 targetPosition = target.position; Vector3 elbowTargetPosition = elbowTarget.position; Transform upperArmParent = upperArm.parent; Transform forearmParent = forearm.parent; Transform handParent = hand.parent; Vector3 upperArmScale = upperArm.localScale; Vector3 forearmScale = forearm.localScale; Vector3 handScale = hand.localScale; Vector3 upperArmLocalPosition = upperArm.localPosition; Vector3 forearmLocalPosition = forearm.localPosition; Vector3 handLocalPosition = hand.localPosition; DesiredUpperArmRotation = upperArm.rotation; DesiredForearmRotation = forearm.rotation; DesiredHandRotation = hand.rotation; //Quaternion DesiredHandLocalRotation = hand.localRotation; //Reset arm. target.position = targetRelativeStartPosition + upperArm.position; elbowTarget.position = elbowTargetRelativeStartPosition + upperArm.position; upperArm.rotation = upperArmStartRotation; forearm.rotation = forearmStartRotation; hand.rotation = handStartRotation; //Work with temporaty game objects and align & parent them to the arm. transform.position = upperArm.position; transform.LookAt(targetPosition, elbowTargetPosition - transform.position); upperArmAxisCorrection.transform.position = upperArm.position; //upperArmAxisCorrection.transform.LookAt(forearm.position, transform.root.up); upperArmAxisCorrection.transform.LookAt(forearm.position, upperArm.up); upperArm.parent = upperArmAxisCorrection.transform; forearmAxisCorrection.transform.position = forearm.position; //forearmAxisCorrection.transform.LookAt(hand.position, transform.root.up); forearmAxisCorrection.transform.LookAt(hand.position, forearm.up); forearm.parent = forearmAxisCorrection.transform; handAxisCorrection.transform.position = hand.position; hand.parent = handAxisCorrection.transform; //Reset targets target.position = targetPosition; elbowTarget.position = elbowTargetPosition; //Apply rotation for temporary game objects upperArmAxisCorrection.transform.LookAt(target,elbowTarget.position - upperArmAxisCorrection.transform.position); upperArmAxisCorrection.transform.localRotation = //.x -= ikAngle; Quaternion.Euler(upperArmAxisCorrection.transform.localRotation.eulerAngles - new Vector3(ikAngle, 0, 0)); forearmAxisCorrection.transform.LookAt(target,elbowTarget.position - upperArmAxisCorrection.transform.position); handAxisCorrection.transform.rotation = target.rotation; //Restore limbs upperArm.parent = upperArmParent; forearm.parent = forearmParent; hand.parent = handParent; upperArm.localScale = upperArmScale; forearm.localScale = forearmScale; hand.localScale = handScale; upperArm.localPosition = upperArmLocalPosition; forearm.localPosition = forearmLocalPosition; hand.localPosition = handLocalPosition; //Debug. if (DebugLines) { Debug.DrawLine(forearm.position, elbowTarget.position, Color.yellow); Debug.DrawLine(upperArm.position, target.position, Color.red); Debug.Log("[IK Limb] adjacent: " + adjacent); Debug.LogError ("Time taken to calculate IK [" + (Time.realtimeSinceStartup - TimeBegin) + "]"); } } } } /*switch(handRotationPolicy) { case HandRotations.KeepLocalRotation: hand.localRotation = handLocalRotation; break; case HandRotations.KeepGlobalRotation: hand.rotation = handRotation; break; case HandRotations.UseTargetRotation: hand.rotation = target.rotation; break; }*/
using UnityEngine; using UnityEditor; using System.Collections.Generic; using System.Collections; using System.IO; using System.Linq; using System; [InitializeOnLoad] public class StartupUGUISimpleTextureModifier { static StartupUGUISimpleTextureModifier() { if (EditorApplication.timeSinceStartup < 10) { Debug.Log("Initialized TextureModifier"); EditorUserBuildSettings.activeBuildTargetChanged += OnChangePlatform; } } [UnityEditor.MenuItem("Assets/Texture Util/ReImport All Compress Texture", false, 1)] static void OnChangePlatform() { Debug.Log(" TextureModifier Convert Compress Texture"); string labels = "t:Texture"; foreach(var type in UGUISimpleTextureModifier.compressOutputs){ labels+=" l:"+type.ToString(); } var assets = AssetDatabase.FindAssets (labels,null); foreach (var asset in assets) { var path=AssetDatabase.GUIDToAssetPath(asset); if (!String.IsNullOrEmpty(path)) AssetDatabase.ImportAsset(path); } } } public class UGUISimpleTextureModifier : AssetPostprocessor { public static readonly string KEY = "SimpleTextureModifier Enable"; public enum TextureModifierType { None, PremultipliedAlpha, AlphaBleed, FloydSteinberg, Reduced16bits, C16bits, CCompressed, CCompressedNA, CCompressedWA, T32bits, T16bits, TCompressed, TCompressedNA, TCompressedWA, TPNG, TJPG, } static TextureFormat CompressionFormat { get { switch (EditorUserBuildSettings.activeBuildTarget) { case BuildTarget.Android: return TextureFormat.ETC_RGB4; case BuildTarget.iPhone: return TextureFormat.PVRTC_RGB4; default: return TextureFormat.DXT1; } } } static TextureFormat CompressionWithAlphaFormat { get { switch (EditorUserBuildSettings.activeBuildTarget) { case BuildTarget.Android: return TextureFormat.ETC_RGB4; case BuildTarget.iPhone: return TextureFormat.PVRTC_RGBA4; default: return TextureFormat.DXT5; } } } struct Position2 { public int x,y; public Position2(int p1, int p2) { x = p1; y = p2; } } readonly static List<List<Position2>> bleedTable; static UGUISimpleTextureModifier(){ bleedTable=new List<List<Position2>>(); for(int i=1;i<=12;i++){ var bT=new List<Position2>(); for(int x=-i;x<=i;x++){ bT.Add(new Position2(x,i)); bT.Add(new Position2(-x,-i)); } for(int y=-i+1;y<=i-1;y++){ bT.Add(new Position2(i,y)); bT.Add(new Position2(-i,-y)); } bleedTable.Add(bT); } } public readonly static List<TextureModifierType> effecters=new List<TextureModifierType>{TextureModifierType.PremultipliedAlpha,TextureModifierType.AlphaBleed}; public readonly static List<TextureModifierType> modifiers = new List<TextureModifierType> { TextureModifierType.FloydSteinberg, TextureModifierType.Reduced16bits }; public readonly static List<TextureModifierType> outputs = new List<TextureModifierType>{TextureModifierType.TJPG,TextureModifierType.TPNG,TextureModifierType.T32bits,TextureModifierType.T16bits,TextureModifierType.C16bits ,TextureModifierType.CCompressed,TextureModifierType.CCompressedNA,TextureModifierType.CCompressedWA ,TextureModifierType.TCompressed,TextureModifierType.TCompressedNA,TextureModifierType.TCompressedWA}; public readonly static List<TextureModifierType> compressOutputs = new List<TextureModifierType>{ TextureModifierType.CCompressed,TextureModifierType.CCompressedNA,TextureModifierType.CCompressedWA ,TextureModifierType.TCompressed,TextureModifierType.TCompressedNA,TextureModifierType.TCompressedWA}; static void ClearLabel(List<TextureModifierType> types, bool ImportAsset = true) { List<UnityEngine.Object> objs=new List<UnityEngine.Object>(Selection.objects); foreach(var obj in objs){ if(obj is Texture2D){ List<string> labels=new List<string>(AssetDatabase.GetLabels(obj)); var newLabels=new List<string>(); labels.ForEach((string l)=>{ if(Enum.IsDefined(typeof(TextureModifierType),l)){ if(!types.Contains((TextureModifierType)Enum.Parse(typeof(TextureModifierType),l))) newLabels.Add(l); } }); AssetDatabase.SetLabels(obj,newLabels.ToArray()); if(ImportAsset) AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(obj)); } } } static void SetLabel(string label,List<TextureModifierType> types){ ClearLabel(types,false); List<UnityEngine.Object> objs=new List<UnityEngine.Object>(Selection.objects); foreach(var obj in objs){ if(obj is Texture2D){ List<string> labels=new List<string>(AssetDatabase.GetLabels(obj)); labels.Add(label); AssetDatabase.SetLabels(obj,labels.ToArray()); EditorUtility.SetDirty(obj); AssetDatabase.WriteImportSettingsIfDirty(AssetDatabase.GetAssetPath(obj)); foreach(Editor ed in (Editor[])UnityEngine.Resources.FindObjectsOfTypeAll(typeof(Editor))){ if(ed.target==obj){ ed.Repaint(); EditorUtility.SetDirty(ed); } } } } } [UnityEditor.MenuItem("Assets/Texture Util/Clear Texture Effecter Label",false,20)] static void ClearTextureEffecterLabel(){ ClearLabel(effecters); } [UnityEditor.MenuItem("Assets/Texture Util/Set Label PremultipliedAlpha",false,20)] static void SetLabelPremultipliedAlpha(){ SetLabel(TextureModifierType.PremultipliedAlpha.ToString(),effecters); } [UnityEditor.MenuItem("Assets/Texture Util/Set Label AlphaBleed",false,20)] static void SetLabelAlphaBleed(){ SetLabel(TextureModifierType.AlphaBleed.ToString(),effecters); } [UnityEditor.MenuItem("Assets/Texture Util/Clear Texture Modifier Label",false,40)] static void ClearTextureModifierLabel(){ ClearLabel(modifiers); } [UnityEditor.MenuItem("Assets/Texture Util/Set Label FloydSteinberg",false,40)] static void SetLabelFloydSteinberg(){ SetLabel(TextureModifierType.FloydSteinberg.ToString(),modifiers); } [UnityEditor.MenuItem("Assets/Texture Util/Set Label Reduced16bits",false,40)] static void SetLabelReduced16bits(){ SetLabel(TextureModifierType.Reduced16bits.ToString(),modifiers); } [UnityEditor.MenuItem("Assets/Texture Util/Clear Texture Output Label",false,60)] static void ClearTextureOutputLabel(){ ClearLabel(outputs); } [UnityEditor.MenuItem("Assets/Texture Util/Set Label Convert 16bits", false, 60)] static void SetLabelC16bits() { SetLabel(TextureModifierType.C16bits.ToString(), outputs); } [UnityEditor.MenuItem("Assets/Texture Util/Set Label Convert Compressed", false, 60)] static void SetLabelCCompressed() { SetLabel(TextureModifierType.CCompressed.ToString(), outputs); } [UnityEditor.MenuItem("Assets/Texture Util/Set Label Convert Compressed no alpha", false, 60)] static void SetLabelCCompressedNA() { SetLabel(TextureModifierType.CCompressedNA.ToString(), outputs); } [UnityEditor.MenuItem("Assets/Texture Util/Set Label Convert Compressed with alpha", false, 60)] static void SetLabelCCompressedWA() { SetLabel(TextureModifierType.CCompressedWA.ToString(), outputs); } [UnityEditor.MenuItem("Assets/Texture Util/Set Label Texture 16bits", false, 60)] static void SetLabel16bits(){ SetLabel(TextureModifierType.T16bits.ToString(),outputs); } [UnityEditor.MenuItem("Assets/Texture Util/Set Label Texture 32bits",false,60)] static void SetLabel32bits(){ SetLabel(TextureModifierType.T32bits.ToString(),outputs); } [UnityEditor.MenuItem("Assets/Texture Util/Set Label Texture Compressed",false,60)] static void SetLabelCompressed(){ SetLabel(TextureModifierType.TCompressed.ToString(),outputs); } [UnityEditor.MenuItem("Assets/Texture Util/Set Label Texture Compressed no alpha", false, 60)] static void SetLabelCompressedNA() { SetLabel(TextureModifierType.TCompressedNA.ToString(), outputs); } [UnityEditor.MenuItem("Assets/Texture Util/Set Label Texture Compressed with alpha", false, 60)] static void SetLabelCompressedWA(){ SetLabel(TextureModifierType.TCompressedWA.ToString(),outputs); } [UnityEditor.MenuItem("Assets/Texture Util/Set Label Texture PNG",false,60)] static void SetLabelPNG(){ SetLabel(TextureModifierType.TPNG.ToString(),outputs); } [UnityEditor.MenuItem("Assets/Texture Util/Set Label Texture JPG",false,60)] static void SetLabelJPG(){ SetLabel(TextureModifierType.TJPG.ToString(),outputs); } TextureModifierType effecterType=TextureModifierType.None; TextureModifierType modifierType=TextureModifierType.None; TextureModifierType outputType=TextureModifierType.None; void OnPreprocessTexture(){ //return; var importer = (assetImporter as TextureImporter); UnityEngine.Object obj=AssetDatabase.LoadAssetAtPath(assetPath,typeof(Texture2D)); var labels=new List<string>(AssetDatabase.GetLabels(obj)); foreach(string label in labels){ if(Enum.IsDefined(typeof(TextureModifierType),label)){ TextureModifierType type=(TextureModifierType)Enum.Parse(typeof(TextureModifierType),label); if(effecters.Contains(type)){ effecterType=type; } if(modifiers.Contains(type)){ modifierType=type; } if(outputs.Contains(type)){ outputType=type; } } } if(effecterType!=TextureModifierType.None || modifierType!=TextureModifierType.None || outputType!=TextureModifierType.None){ importer.alphaIsTransparency=false; importer.compressionQuality = (int)TextureCompressionQuality.Best; if(importer.textureFormat==TextureImporterFormat.Automatic16bit) importer.textureFormat = TextureImporterFormat.AutomaticTruecolor; else if(importer.textureFormat==TextureImporterFormat.AutomaticCompressed) importer.textureFormat = TextureImporterFormat.AutomaticTruecolor; else if(importer.textureFormat==TextureImporterFormat.RGB16) importer.textureFormat = TextureImporterFormat.RGB24; else if(importer.textureFormat==TextureImporterFormat.RGBA16) importer.textureFormat = TextureImporterFormat.RGBA32; else if(importer.textureFormat==TextureImporterFormat.ARGB16) importer.textureFormat = TextureImporterFormat.ARGB32; } } void OnPostprocessTexture (Texture2D texture){ if(effecterType==TextureModifierType.None && modifierType==TextureModifierType.None && outputType==TextureModifierType.None) return; AssetDatabase.StartAssetEditing(); var pixels = texture.GetPixels (); switch (effecterType){ case TextureModifierType.PremultipliedAlpha:{ PremultipliedAlpha(ref pixels,texture); break; } case TextureModifierType.AlphaBleed:{ AlphaBleed(ref pixels,texture); break; }} switch (modifierType){ case TextureModifierType.FloydSteinberg:{ FloydSteinberg(ref pixels,texture); break; } case TextureModifierType.Reduced16bits:{ Reduced16bits(ref pixels,texture); break; }} //return; if (EditorPrefs.GetBool(KEY, false)) { switch (outputType) { case TextureModifierType.C16bits: { texture.SetPixels(pixels); texture.Apply(true, true); EditorUtility.CompressTexture(texture, TextureFormat.RGBA4444, TextureCompressionQuality.Best); break; } case TextureModifierType.CCompressed: { texture.SetPixels(pixels); texture.Apply(true, true); EditorUtility.CompressTexture(texture, CompressionWithAlphaFormat, TextureCompressionQuality.Best); break; } case TextureModifierType.CCompressedNA: { texture.SetPixels(pixels); texture.Apply(true, true); EditorUtility.CompressTexture(texture, CompressionFormat, TextureCompressionQuality.Best); break; } case TextureModifierType.CCompressedWA: { WriteAlphaTexture(pixels, texture); texture.SetPixels(pixels); texture.Apply(true, true); EditorUtility.CompressTexture(texture, CompressionFormat, TextureCompressionQuality.Best); break; } case TextureModifierType.TCompressed: { var tex = BuildTexture(texture, TextureFormat.RGBA32); tex.SetPixels(pixels); tex.Apply(true, true); WriteTexture(tex, CompressionWithAlphaFormat, assetPath, ".asset"); break; } case TextureModifierType.TCompressedNA: { var tex = BuildTexture(texture, TextureFormat.RGBA32); tex.SetPixels(pixels); tex.Apply(true, true); WriteTexture(tex, CompressionFormat, assetPath, ".asset"); break; } case TextureModifierType.TCompressedWA: { WriteAlphaTexture(pixels, texture); var tex = BuildTexture(texture, TextureFormat.RGBA32); tex.SetPixels(pixels); tex.Apply(true, true); WriteTexture(tex, CompressionFormat, assetPath, ".asset"); break; } case TextureModifierType.T16bits: { var tex = BuildTexture(texture, TextureFormat.RGBA32); tex.SetPixels(pixels); tex.Apply(true, true); WriteTexture(tex, TextureFormat.RGBA4444, assetPath, ".asset"); break; } case TextureModifierType.T32bits: { var tex = BuildTexture(texture, TextureFormat.RGBA32); tex.SetPixels(pixels); tex.Apply(true, true); WriteTexture(tex, TextureFormat.RGBA32, assetPath, ".asset"); break; } case TextureModifierType.TPNG: { var tex = BuildTexture(texture, TextureFormat.RGBA32); tex.SetPixels(pixels); tex.Apply(true); WritePNGTexture(tex, TextureFormat.RGBA32, assetPath, "RGBA.png"); break; } case TextureModifierType.TJPG: { var tex = BuildTexture(texture, TextureFormat.RGBA32); tex.SetPixels(pixels); tex.Apply(true); WriteJPGTexture(tex, TextureFormat.RGBA32, assetPath, "RGB.jpg"); break; } default: { if (effecterType != TextureModifierType.None || modifierType != TextureModifierType.None) { texture.SetPixels(pixels); texture.Apply(true); } break; } } } AssetDatabase.Refresh(); AssetDatabase.StopAssetEditing(); } Texture2D BuildTexture(Texture2D texture,TextureFormat format){ var tex = new Texture2D (texture.width, texture.height, format, texture.mipmapCount>1); tex.wrapMode = texture.wrapMode; tex.filterMode = texture.filterMode; tex.mipMapBias = texture.mipMapBias; tex.anisoLevel = texture.anisoLevel; return tex; } void WriteTexture(Texture2D texture,TextureFormat format,string path,string extension){ EditorUtility.CompressTexture (texture,format,TextureCompressionQuality.Best); var writePath = path.Substring(0,path.LastIndexOf('.'))+extension; var writeAsset = AssetDatabase.LoadAssetAtPath (writePath,typeof(Texture2D)) as Texture2D; if (writeAsset == null) { AssetDatabase.CreateAsset (texture, writePath); } else { EditorUtility.CopySerialized (texture, writeAsset); } } void WritePNGTexture(Texture2D texture,TextureFormat format,string path,string extension){ EditorUtility.CompressTexture (texture,format,TextureCompressionQuality.Best); byte[] pngData=texture.EncodeToPNG(); //var nPath=path.Substring(0,path.LastIndexOf('.'))+extension; var writePath = Application.dataPath+(path.Substring(0,path.LastIndexOf('.'))+extension).Substring(6); File.WriteAllBytes(writePath, pngData); AssetDatabase.SaveAssets(); AssetDatabase.Refresh(ImportAssetOptions.ForceSynchronousImport); } void WriteJPGTexture(Texture2D texture,TextureFormat format,string path,string extension){ EditorUtility.CompressTexture (texture,format,TextureCompressionQuality.Best); byte[] jpgData=texture.EncodeToJPG(); //var nPath=path.Substring(0,path.LastIndexOf('.'))+extension; var writePath = Application.dataPath+(path.Substring(0,path.LastIndexOf('.'))+extension).Substring(6); File.WriteAllBytes(writePath, jpgData); AssetDatabase.SaveAssets(); AssetDatabase.Refresh(ImportAssetOptions.ForceSynchronousImport); } void WriteCompressTexture(Color[] pixels,Texture2D texture,TextureFormat format){ var mask = BuildTexture(texture,TextureFormat.RGB24); for (int i = 0; i < pixels.Length; i++) { var a = pixels [i].a; pixels [i] = new Color (a, a, a); } mask.SetPixels (pixels); mask.Apply(true,true); WriteTexture(mask,CompressionFormat,assetPath,"Alpha.asset"); } void WriteAlphaTexture(Color[] pixels,Texture2D texture){ var mask = new Texture2D (texture.width, texture.height, TextureFormat.RGB24, false); mask.wrapMode = texture.wrapMode; mask.filterMode = texture.filterMode; mask.mipMapBias = texture.mipMapBias; mask.anisoLevel = texture.anisoLevel; var aPixels = new Color[pixels.Length]; for (int i = 0; i < pixels.Length; i++) { var a = pixels [i].a; aPixels [i] = new Color (a, a, a); } mask.SetPixels (aPixels); mask.Apply(true,true); WriteTexture(mask,CompressionFormat,assetPath,"Alpha.asset"); } void PremultipliedAlpha(ref Color[] pixels,Texture2D texture){ // var pixels = texture.GetPixels (); for (int i = 0; i < pixels.Length; i++) { var a = pixels [i].a; pixels [i] = new Color (pixels[i].r*a,pixels[i].g*a,pixels[i].b*a,a); } // texture.SetPixels (pixels); } void AlphaBleed(ref Color[] pixels,Texture2D texture){ // var pixels = texture.GetPixels (); var height = texture.height; var width = texture.width; // Debug.Log(texture.format); for (var y = 0; y < height; y++) { for (var x = 0; x < width; x++) { int position=y*width+x; if (pixels [position].a <= 0.125f) { float a=pixels[position].a; pixels[position]=new Color(0.5f,0.5f,0.5f,a); int index=1; foreach(var bt in bleedTable){ float r=0.0f; float g=0.0f; float b=0.0f; float c=0.0f; foreach(var pt in bt){ int xp=x+pt.x; int yp=y+pt.y; if (xp >= 0 && xp < width && yp >= 0 && yp < height) { int pos=yp*width+xp; float ad=pixels[pos].a; if(ad>0.125f){ r+=pixels[pos].r*ad; g+=pixels[pos].g*ad; b+=pixels[pos].b*ad; c+=ad; } } } if(c>0.0f){ float fac=Mathf.Min (1.0f,(float)(13-index)/6.0f); pixels[position]= new Color(r/c*fac+pixels[position].r*(1.0f-fac) ,g/c*fac+pixels[position].g*(1.0f-fac) ,b/c*fac+pixels[position].b*(1.0f-fac),a); break; } index++; } } } } // texture.SetPixels (pixels); } const float k1Per256 = 1.0f / 255.0f; const float k1Per16 = 1.0f / 15.0f; const float k3Per16 = 3.0f / 15.0f; const float k5Per16 = 5.0f / 15.0f; const float k7Per16 = 7.0f / 15.0f; void Reduced16bits(ref Color[] pixels,Texture2D texture){ var texw = texture.width; var texh = texture.height; // var pixels = texture.GetPixels (); var offs = 0; for (var y = 0; y < texh; y++) { for (var x = 0; x < texw; x++) { float a = pixels [offs].a; float r = pixels [offs].r; float g = pixels [offs].g; float b = pixels [offs].b; var a2 = Mathf.Round(a * 15.0f) * k1Per16; var r2 = Mathf.Round(r * 15.0f) * k1Per16; var g2 = Mathf.Round(g * 15.0f) * k1Per16; var b2 = Mathf.Round(b * 15.0f) * k1Per16; pixels [offs].a = a2; pixels [offs].r = r2; pixels [offs].g = g2; pixels [offs].b = b2; offs++; } } // texture.SetPixels (pixels); } void FloydSteinberg(ref Color[] pixels,Texture2D texture){ var texw = texture.width; var texh = texture.height; // var pixels = texture.GetPixels (); var offs = 0; for (var y = 0; y < texh; y++) { for (var x = 0; x < texw; x++) { float a = pixels [offs].a; float r = pixels [offs].r; float g = pixels [offs].g; float b = pixels [offs].b; var a2 = Mathf.Round(a * 15.0f) * k1Per16; var r2 = Mathf.Round(r * 15.0f) * k1Per16; var g2 = Mathf.Round(g * 15.0f) * k1Per16; var b2 = Mathf.Round(b * 15.0f) * k1Per16; var ae = Mathf.Round((a - a2)*255.0f)*k1Per256; var re = Mathf.Round((r - r2)*255.0f)*k1Per256; var ge = Mathf.Round((g - g2)*255.0f)*k1Per256; var be = Mathf.Round((b - b2)*255.0f)*k1Per256; pixels [offs].a = a2; pixels [offs].r = r2; pixels [offs].g = g2; pixels [offs].b = b2; var n1 = offs + 1; var n2 = offs + texw - 1; var n3 = offs + texw; var n4 = offs + texw + 1; if (x < texw - 1) { pixels [n1].a += ae * k7Per16; pixels [n1].r += re * k7Per16; pixels [n1].g += ge * k7Per16; pixels [n1].b += be * k7Per16; } if (y < texh - 1) { pixels [n3].a += ae * k5Per16; pixels [n3].r += re * k5Per16; pixels [n3].g += ge * k5Per16; pixels [n3].b += be * k5Per16; if (x > 0) { pixels [n2].a += ae * k3Per16; pixels [n2].r += re * k3Per16; pixels [n2].g += ge * k3Per16; pixels [n2].b += be * k3Per16; } if (x < texw - 1) { pixels [n4].a += ae * k1Per16; pixels [n4].r += re * k1Per16; pixels [n4].g += ge * k1Per16; pixels [n4].b += be * k1Per16; } } offs++; } } // texture.SetPixels (pixels); } }
// Copyright (c) 2010-2013 SharpDX - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #if !WIN8METRO using System; namespace SharpDX.Direct3D11 { public partial class EffectScalarVariable { /// <summary> /// Set a floating-point variable. /// </summary> /// <param name="value">A reference to the variable. </param> /// <returns>Returns one of the following {{Direct3D 10 Return Codes}}. </returns> /// <unmanaged>HRESULT ID3D10EffectScalarVariable::SetFloat([None] float Value)</unmanaged> public void Set(float value) { SetFloat(value); } /// <summary> /// Set an array of floating-point variables. /// </summary> /// <param name="dataRef">A reference to the start of the data to set. </param> /// <returns>Returns one of the following {{Direct3D 10 Return Codes}}. </returns> /// <unmanaged>HRESULT ID3D10EffectScalarVariable::SetFloatArray([In, Buffer] float* pData,[None] int Offset,[None] int Count)</unmanaged> public void Set(float[] dataRef) { Set(dataRef, 0); } /// <summary> /// Set an array of floating-point variables. /// </summary> /// <param name="dataRef">A reference to the start of the data to set. </param> /// <param name="offset">Must be set to 0; this is reserved for future use. </param> /// <returns>Returns one of the following {{Direct3D 10 Return Codes}}. </returns> /// <unmanaged>HRESULT ID3D10EffectScalarVariable::SetFloatArray([In, Buffer] float* pData,[None] int Offset,[None] int Count)</unmanaged> public void Set(float[] dataRef, int offset) { SetFloatArray(dataRef, offset, dataRef.Length); } /// <summary> /// Get an array of floating-point variables. /// </summary> /// <param name="count">The number of array elements to set. </param> /// <returns>Returns an array of floats. </returns> /// <unmanaged>HRESULT ID3D10EffectScalarVariable::GetFloatArray([Out, Buffer] float* pData,[None] int Offset,[None] int Count)</unmanaged> public float[] GetFloatArray(int count) { return GetFloatArray(0, count); } /// <summary> /// Get an array of floating-point variables. /// </summary> /// <param name="offset">Must be set to 0; this is reserved for future use. </param> /// <param name="count">The number of array elements to set. </param> /// <returns>Returns an array of floats. </returns> /// <unmanaged>HRESULT ID3D10EffectScalarVariable::GetFloatArray([Out, Buffer] float* pData,[None] int Offset,[None] int Count)</unmanaged> public float[] GetFloatArray(int offset, int count) { var temp = new float[count]; GetFloatArray(temp, offset, count); return temp; } /// <summary> /// Set an unsigned integer variable. /// </summary> /// <param name="value">A reference to the variable. </param> /// <returns>Returns one of the following {{Direct3D 10 Return Codes}}. </returns> /// <unmanaged>HRESULT ID3D10EffectScalarVariable::SetInt([None] int Value)</unmanaged> public void Set(uint value) { int temp = 0; unchecked { temp = (int)value; } SetInt(temp); } /// <summary> /// Set an array of unsigned integer variables. /// </summary> /// <param name="dataRef">A reference to the start of the data to set. </param> /// <returns>Returns one of the following {{Direct3D 10 Return Codes}}. </returns> /// <unmanaged>HRESULT ID3D10EffectScalarVariable::SetIntArray([In, Buffer] int* pData,[None] int Offset,[None] int Count)</unmanaged> public void Set(uint[] dataRef) { int[] temp = new int[dataRef.Length]; unchecked { for (int n = 0; n < dataRef.Length; n++) temp[n] = (int)dataRef[n]; } Set(temp, 0); } /// <summary> /// Set an integer variable. /// </summary> /// <param name="value">A reference to the variable. </param> /// <returns>Returns one of the following {{Direct3D 10 Return Codes}}. </returns> /// <unmanaged>HRESULT ID3D10EffectScalarVariable::SetInt([None] int Value)</unmanaged> public void Set(int value) { SetInt(value); } /// <summary> /// Set an array of integer variables. /// </summary> /// <param name="dataRef">A reference to the start of the data to set. </param> /// <returns>Returns one of the following {{Direct3D 10 Return Codes}}. </returns> /// <unmanaged>HRESULT ID3D10EffectScalarVariable::SetIntArray([In, Buffer] int* pData,[None] int Offset,[None] int Count)</unmanaged> public void Set(int[] dataRef) { Set(dataRef, 0); } /// <summary> /// Set an array of integer variables. /// </summary> /// <param name="dataRef">A reference to the start of the data to set. </param> /// <param name="offset">Must be set to 0; this is reserved for future use. </param> /// <returns>Returns one of the following {{Direct3D 10 Return Codes}}. </returns> /// <unmanaged>HRESULT ID3D10EffectScalarVariable::SetIntArray([In, Buffer] int* pData,[None] int Offset,[None] int Count)</unmanaged> public void Set(int[] dataRef, int offset) { SetIntArray(dataRef, offset, dataRef.Length); } /// <summary> /// Get an array of integer variables. /// </summary> /// <param name="count">The number of array elements to set. </param> /// <returns>Returns an array of integer variables. </returns> /// <unmanaged>HRESULT ID3D10EffectScalarVariable::GetIntArray([Out, Buffer] int* pData,[None] int Offset,[None] int Count)</unmanaged> public int[] GetIntArray(int count) { return GetIntArray(0, count); } /// <summary> /// Get an array of integer variables. /// </summary> /// <param name="offset">Must be set to 0; this is reserved for future use. </param> /// <param name="count">The number of array elements to set. </param> /// <returns>Returns an array of integer variables. </returns> /// <unmanaged>HRESULT ID3D10EffectScalarVariable::GetIntArray([Out, Buffer] int* pData,[None] int Offset,[None] int Count)</unmanaged> public int[] GetIntArray(int offset, int count) { var temp = new int[count]; GetIntArray(temp, offset, count); return temp; } /// <summary> /// Set a boolean variable. /// </summary> /// <param name="value">A reference to the variable. </param> /// <returns>Returns one of the following {{Direct3D 10 Return Codes}}. </returns> /// <unmanaged>HRESULT ID3D10EffectScalarVariable::SetBool([None] BOOL Value)</unmanaged> public void Set(bool value) { SetBool(value); } /// <summary> /// Get a boolean variable. /// </summary> /// <returns>Returns a boolean. </returns> /// <unmanaged>HRESULT ID3D10EffectScalarVariable::GetBool([Out] BOOL* pValue)</unmanaged> public bool GetBool() { Bool temp; GetBool(out temp); return temp; } /// <summary> /// Set an array of boolean variables. /// </summary> /// <param name="dataRef">A reference to the start of the data to set. </param> /// <returns>Returns one of the following {{Direct3D 10 Return Codes}}. </returns> /// <unmanaged>HRESULT ID3D10EffectScalarVariable::SetBoolArray([In, Buffer] BOOL* pData,[None] int Offset,[None] int Count)</unmanaged> public void Set(bool[] dataRef) { Set(dataRef, 0); } /// <summary> /// Set an array of boolean variables. /// </summary> /// <param name="dataRef">A reference to the start of the data to set. </param> /// <param name="offset">Must be set to 0; this is reserved for future use. </param> /// <returns>Returns one of the following {{Direct3D 10 Return Codes}}. </returns> /// <unmanaged>HRESULT ID3D10EffectScalarVariable::SetBoolArray([In, Buffer] BOOL* pData,[None] int Offset,[None] int Count)</unmanaged> public void Set(bool[] dataRef, int offset) { SetBoolArray(Utilities.ConvertToIntArray(dataRef), offset, dataRef.Length); } /// <summary> /// Get an array of boolean variables. /// </summary> /// <param name="offset">Must be set to 0; this is reserved for future use. </param> /// <param name="count">The number of array elements to set. </param> /// <returns>Returns one of the following {{Direct3D 10 Return Codes}}. </returns> /// <unmanaged>HRESULT ID3D10EffectScalarVariable::GetBoolArray([Out, Buffer] BOOL* pData,[None] int Offset,[None] int Count)</unmanaged> public bool[] GetBoolArray(int offset, int count) { Bool[] temp = new Bool[count]; GetBoolArray(temp, offset, count); return Utilities.ConvertToBoolArray(temp); } } } #endif
// 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. // Runtime Version:2.0.50727.1434 // // 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 PowerDNS_Settings { /// <summary> /// lblFirsttimeUserNote control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.HtmlControls.HtmlGenericControl lblFirsttimeUserNote; /// <summary> /// lblServerAddress 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 lblServerAddress; /// <summary> /// txtServerAddress 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 txtServerAddress; /// <summary> /// valRequireServerAddress 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.RequiredFieldValidator valRequireServerAddress; /// <summary> /// lblServerPort 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 lblServerPort; /// <summary> /// txtServerPort 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 txtServerPort; /// <summary> /// lblServerPortDefault 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 lblServerPortDefault; /// <summary> /// lblDatabase 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 lblDatabase; /// <summary> /// txtDatabase 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 txtDatabase; /// <summary> /// valRequireDatabase 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.RequiredFieldValidator valRequireDatabase; /// <summary> /// lblUsername 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 lblUsername; /// <summary> /// txtUsername 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 txtUsername; /// <summary> /// valRequireUsername 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.RequiredFieldValidator valRequireUsername; /// <summary> /// trCurrentPassword control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.HtmlControls.HtmlTableRow trCurrentPassword; /// <summary> /// lblCurrentPassword 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 lblCurrentPassword; /// <summary> /// lblCurrentPasswordText 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 lblCurrentPasswordText; /// <summary> /// trPassword control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.HtmlControls.HtmlTableRow trPassword; /// <summary> /// lblPassword 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 lblPassword; /// <summary> /// txtPassword 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 txtPassword; /// <summary> /// varRequirePassword 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.RequiredFieldValidator varRequirePassword; /// <summary> /// trPasswordConfirm control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.HtmlControls.HtmlTableRow trPasswordConfirm; /// <summary> /// lblConfirmPassword 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 lblConfirmPassword; /// <summary> /// txtConfirmPassword 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 txtConfirmPassword; /// <summary> /// passwordsIdentValidator 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.CompareValidator passwordsIdentValidator; /// <summary> /// valRequireConfirmPasswordNotEmpty 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.CustomValidator valRequireConfirmPasswordNotEmpty; /// <summary> /// lblResponsiblePerson 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 lblResponsiblePerson; /// <summary> /// txtResponsiblePerson 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 txtResponsiblePerson; /// <summary> /// lblRefreshInterval 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 lblRefreshInterval; /// <summary> /// intRefresh control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::WebsitePanel.Portal.ScheduleInterval intRefresh; /// <summary> /// lblRetryInterval 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 lblRetryInterval; /// <summary> /// intRetry control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::WebsitePanel.Portal.ScheduleInterval intRetry; /// <summary> /// lblExpireLimit 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 lblExpireLimit; /// <summary> /// intExpire control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::WebsitePanel.Portal.ScheduleInterval intExpire; /// <summary> /// lblMinimumTtl 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 lblMinimumTtl; /// <summary> /// intTtl control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::WebsitePanel.Portal.ScheduleInterval intTtl; /// <summary> /// lblIPAddresses 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 lblIPAddresses; /// <summary> /// iPAddressesList control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::WebsitePanel.Portal.ProviderControls.Common_IPAddressesList iPAddressesList; /// <summary> /// lblSecondaryDNS 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 lblSecondaryDNS; /// <summary> /// secondaryDNSServers control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::WebsitePanel.Portal.ProviderControls.Common_SecondaryDNSServers secondaryDNSServers; /// <summary> /// lblNameServers 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 lblNameServers; /// <summary> /// nameServers control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::WebsitePanel.Portal.UserControls.EditDomainsList nameServers; } }
using System; using System.Linq; using System.Numerics; using OpenSage.Data.Map; using OpenSage.Mathematics; namespace OpenSage.Terrain { public sealed class HeightMap { internal const int HorizontalScale = 10; private readonly float _verticalScale; private readonly HeightMapData _heightMapData; public int Width { get; } public int Height { get; } public int MaxXCoordinate => (Width - 2 * (int) _heightMapData.BorderWidth) * HorizontalScale; public int MaxYCoordinate => (Height - 2 * (int) _heightMapData.BorderWidth) * HorizontalScale; public float GetHeight(int x, int y) => _heightMapData.Elevations[x, y] * _verticalScale; public float GetUpperHeight(float x, float y) { var (nIntX0, nIntX1, _) = ConvertWorldCoordinates(x, Width); var (nIntY0, nIntY1, _) = ConvertWorldCoordinates(y, Height); var heights = new float[] { GetHeight(nIntX0, nIntY0), GetHeight(nIntX1, nIntY0), GetHeight(nIntX0, nIntY1), GetHeight(nIntX1, nIntY1), }; return heights.Max(); } /// <summary> /// Gets height at the given world space coordinate. /// Returns 0 if the coordinate is out of bounds. /// </summary> public float GetHeight(float x, float y) { var (nIntX0, nIntX1, fFractionalX) = ConvertWorldCoordinates(x, Width); var (nIntY0, nIntY1, fFractionalY) = ConvertWorldCoordinates(y, Height); // read 4 map values var f0 = GetHeight(nIntX0, nIntY0); var f1 = GetHeight(nIntX1, nIntY0); var f2 = GetHeight(nIntX0, nIntY1); var f3 = GetHeight(nIntX1, nIntY1); // calculate averages var fAverageLo = (f1 * fFractionalX) + (f0 * (1.0f - fFractionalX)); var fAverageHi = (f3 * fFractionalX) + (f2 * (1.0f - fFractionalX)); return (fAverageHi * fFractionalY) + (fAverageLo * (1.0f - fFractionalY)); } private (int p0, int p1, float fractional) ConvertWorldCoordinates(float p, int maxHeightmapScale) { // convert coordinates to heightmap scale p = p / HorizontalScale + _heightMapData.BorderWidth; p = Math.Clamp(p, 0, maxHeightmapScale - 1); // get integer and fractional parts of coordinate var nIntP0 = MathUtility.FloorToInt(p); var fFractionalP = p - nIntP0; // get coordinates for "other" side of quad var nIntP1 = Math.Clamp(nIntP0 + 1, 0, maxHeightmapScale - 1); return (nIntP0, nIntP1, fFractionalP); } public Vector3 GetNormal(float x, float y) { // convert coordinates to heightmap scale x = x / HorizontalScale + _heightMapData.BorderWidth; y = y / HorizontalScale + _heightMapData.BorderWidth; if (x >= Width || y >= Height || x < 0 || y < 0) { return Vector3.UnitZ; } return Normals[(int)x, (int)y]; } public Vector3 GetPosition(int x, int y) => new Vector3( (x - _heightMapData.BorderWidth) * HorizontalScale, (y - _heightMapData.BorderWidth) * HorizontalScale, GetHeight(x, y)); public (int X, int Y)? GetTilePosition(in Vector3 worldPosition) { var tilePosition = (worldPosition / HorizontalScale) + new Vector3(_heightMapData.BorderWidth, _heightMapData.BorderWidth, 0); var result = (X: (int) tilePosition.X, Y: (int) tilePosition.Y); if (result.X < 0 || result.X >= _heightMapData.Width || result.Y < 0 || result.Y >= _heightMapData.Height) { return null; } return result; } public Vector2 GetHeightMapPosition(in Vector3 worldPosition) { return ((worldPosition / HorizontalScale) + new Vector3(_heightMapData.BorderWidth, _heightMapData.BorderWidth, 0)) .Vector2XY(); } public Vector3[,] Normals { get; } public HeightMap(HeightMapData heightMapData) { _heightMapData = heightMapData; _verticalScale = heightMapData.VerticalScale; Width = (int) heightMapData.Width - 1; //last colum is not rendered (in worldbuilder) Height = (int) heightMapData.Height - 1;//last row is not rendered (in worldbuilder) Normals = new Vector3[Width, Height]; for (var x = 0; x < Width; ++x) { for (var y = 0; y < Height; ++y) { Normals[x, y] = CalculateNormal(x, y); } } } /// <summary> /// Function computes the normal for the xy'th quad. /// We take the quad normal as the average of the two /// triangles that make up the quad. /// /// u /// h0*-------*h1 /// | /| /// v| / |t /// | / | /// | / | /// h2*-------*h3 /// s /// </summary> private Vector3 CalculateQuadNormal(int x, int y) { var h0 = GetHeight(x, y); var h1 = GetHeight(x + 1, y); var h2 = GetHeight(x, y + 1); var h3 = GetHeight(x + 1, y + 1); var u = new Vector3(HorizontalScale, 0, h1 - h0); var v = new Vector3(0, HorizontalScale, h2 - h0); var s = new Vector3(-HorizontalScale, 0, h2 - h3); var t = new Vector3(0, -HorizontalScale, h1 - h3); var n1 = Vector3.Normalize(Vector3.Cross(u, v)); var n2 = Vector3.Normalize(Vector3.Cross(s, t)); return (n1 + n2) * 0.5f; } /// <summary> /// The vertex normal is found by averaging the normals of the four quads that surround the vertex /// </summary> private Vector3 CalculateNormal(int x, int y) { var avg = Vector3.Zero; float num = 0; for (var m = x - 1; m <= x; ++m) { for (var n = y - 1; n <= y; ++n) { // vertices on heightmap boundaries do not have // surrounding quads in some directions, so we just // average in a normal vector that is axis aligned // with the z-axis. if (m < 0 || n < 0 || m == Width - 1 || n == Height - 1) { avg += Vector3.UnitZ; num += 1.0f; } else { avg += CalculateQuadNormal(m, n); num += 1.0f; } } } avg /= num; return Vector3.Normalize(avg); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace System { using System; using System.Reflection; using System.Runtime; using System.Runtime.Serialization; using System.Diagnostics.Contracts; using System.Reflection.Emit; [Serializable] [System.Runtime.InteropServices.ComVisible(true)] public abstract class MulticastDelegate : Delegate { // This is set under 3 circumstances // 1. Multicast delegate // 2. Secure/Wrapper delegate // 3. Inner delegate of secure delegate where the secure delegate security context is a collectible method [System.Security.SecurityCritical] private Object _invocationList; [System.Security.SecurityCritical] private IntPtr _invocationCount; // This constructor is called from the class generated by the // compiler generated code (This must match the constructor // in Delegate protected MulticastDelegate(Object target, String method) : base(target, method) { } // This constructor is called from a class to generate a // delegate based upon a static method name and the Type object // for the class defining the method. protected MulticastDelegate(Type target, String method) : base(target, method) { } [System.Security.SecuritySafeCritical] internal bool IsUnmanagedFunctionPtr() { return (_invocationCount == (IntPtr)(-1)); } [System.Security.SecuritySafeCritical] internal bool InvocationListLogicallyNull() { return (_invocationList == null) || (_invocationList is LoaderAllocator) || (_invocationList is DynamicResolver); } [System.Security.SecurityCritical] public override void GetObjectData(SerializationInfo info, StreamingContext context) { int targetIndex = 0; Object[] invocationList = _invocationList as Object[]; if (invocationList == null) { MethodInfo method = Method; // A MethodInfo object can be a RuntimeMethodInfo, a RefEmit method (MethodBuilder, etc), or a DynamicMethod // One can only create delegates on RuntimeMethodInfo and DynamicMethod. // If it is not a RuntimeMethodInfo (must be a DynamicMethod) or if it is an unmanaged function pointer, throw if ( !(method is RuntimeMethodInfo) || IsUnmanagedFunctionPtr() ) throw new SerializationException(Environment.GetResourceString("Serialization_InvalidDelegateType")); // We can't deal with secure delegates either. if (!InvocationListLogicallyNull() && !_invocationCount.IsNull() && !_methodPtrAux.IsNull()) throw new SerializationException(Environment.GetResourceString("Serialization_InvalidDelegateType")); DelegateSerializationHolder.GetDelegateSerializationInfo(info, this.GetType(), Target, method, targetIndex); } else { DelegateSerializationHolder.DelegateEntry nextDe = null; int invocationCount = (int)_invocationCount; for (int i = invocationCount; --i >= 0; ) { MulticastDelegate d = (MulticastDelegate)invocationList[i]; MethodInfo method = d.Method; // If it is not a RuntimeMethodInfo (must be a DynamicMethod) or if it is an unmanaged function pointer, skip if ( !(method is RuntimeMethodInfo) || IsUnmanagedFunctionPtr() ) continue; // We can't deal with secure delegates either. if (!d.InvocationListLogicallyNull() && !d._invocationCount.IsNull() && !d._methodPtrAux.IsNull()) continue; DelegateSerializationHolder.DelegateEntry de = DelegateSerializationHolder.GetDelegateSerializationInfo(info, d.GetType(), d.Target, method, targetIndex++); if (nextDe != null) nextDe.Entry = de; nextDe = de; } // if nothing was serialized it is a delegate over a DynamicMethod, so just throw if (nextDe == null) throw new SerializationException(Environment.GetResourceString("Serialization_InvalidDelegateType")); } } // equals returns true IIF the delegate is not null and has the // same target, method and invocation list as this object [System.Security.SecuritySafeCritical] // auto-generated public override sealed bool Equals(Object obj) { if (obj == null || !InternalEqualTypes(this, obj)) return false; MulticastDelegate d = obj as MulticastDelegate; if (d == null) return false; if (_invocationCount != (IntPtr)0) { // there are 4 kind of delegate kinds that fall into this bucket // 1- Multicast (_invocationList is Object[]) // 2- Secure/Wrapper (_invocationList is Delegate) // 3- Unmanaged FntPtr (_invocationList == null) // 4- Open virtual (_invocationCount == MethodDesc of target, _invocationList == null, LoaderAllocator, or DynamicResolver) if (InvocationListLogicallyNull()) { if (IsUnmanagedFunctionPtr()) { if (!d.IsUnmanagedFunctionPtr()) return false; return CompareUnmanagedFunctionPtrs(this, d); } // now we know 'this' is not a special one, so we can work out what the other is if ((d._invocationList as Delegate) != null) // this is a secure/wrapper delegate so we need to unwrap and check the inner one return Equals(d._invocationList); return base.Equals(obj); } else { if ((_invocationList as Delegate) != null) { // this is a secure/wrapper delegate so we need to unwrap and check the inner one return _invocationList.Equals(obj); } else { Contract.Assert((_invocationList as Object[]) != null, "empty invocation list on multicast delegate"); return InvocationListEquals(d); } } } else { // among the several kind of delegates falling into this bucket one has got a non // empty _invocationList (open static with special sig) // to be equals we need to check that _invocationList matches (both null is fine) // and call the base.Equals() if (!InvocationListLogicallyNull()) { if (!_invocationList.Equals(d._invocationList)) return false; return base.Equals(d); } // now we know 'this' is not a special one, so we can work out what the other is if ((d._invocationList as Delegate) != null) // this is a secure/wrapper delegate so we need to unwrap and check the inner one return Equals(d._invocationList); // now we can call on the base return base.Equals(d); } } // Recursive function which will check for equality of the invocation list. [System.Security.SecuritySafeCritical] private bool InvocationListEquals(MulticastDelegate d) { Contract.Assert(d != null && (_invocationList as Object[]) != null, "bogus delegate in multicast list comparison"); Object[] invocationList = _invocationList as Object[]; if (d._invocationCount != _invocationCount) return false; int invocationCount = (int)_invocationCount; for (int i = 0; i < invocationCount; i++) { Delegate dd = (Delegate)invocationList[i]; Object[] dInvocationList = d._invocationList as Object[]; if (!dd.Equals(dInvocationList[i])) return false; } return true; } [System.Security.SecurityCritical] private bool TrySetSlot(Object[] a, int index, Object o) { if (a[index] == null && System.Threading.Interlocked.CompareExchange<Object>(ref a[index], o, null) == null) return true; // The slot may be already set because we have added and removed the same method before. // Optimize this case, because it's cheaper than copying the array. if (a[index] != null) { MulticastDelegate d = (MulticastDelegate)o; MulticastDelegate dd = (MulticastDelegate)a[index]; if (dd._methodPtr == d._methodPtr && dd._target == d._target && dd._methodPtrAux == d._methodPtrAux) { return true; } } return false; } [System.Security.SecurityCritical] private MulticastDelegate NewMulticastDelegate(Object[] invocationList, int invocationCount, bool thisIsMultiCastAlready) { // First, allocate a new multicast delegate just like this one, i.e. same type as the this object MulticastDelegate result = (MulticastDelegate)InternalAllocLike(this); // Performance optimization - if this already points to a true multicast delegate, // copy _methodPtr and _methodPtrAux fields rather than calling into the EE to get them if (thisIsMultiCastAlready) { result._methodPtr = this._methodPtr; result._methodPtrAux = this._methodPtrAux; } else { result._methodPtr = GetMulticastInvoke(); result._methodPtrAux = GetInvokeMethod(); } result._target = result; result._invocationList = invocationList; result._invocationCount = (IntPtr)invocationCount; return result; } [System.Security.SecurityCritical] internal MulticastDelegate NewMulticastDelegate(Object[] invocationList, int invocationCount) { return NewMulticastDelegate(invocationList, invocationCount, false); } [System.Security.SecurityCritical] internal void StoreDynamicMethod(MethodInfo dynamicMethod) { if (_invocationCount != (IntPtr)0) { Contract.Assert(!IsUnmanagedFunctionPtr(), "dynamic method and unmanaged fntptr delegate combined"); // must be a secure/wrapper one, unwrap and save MulticastDelegate d = (MulticastDelegate)_invocationList; d._methodBase = dynamicMethod; } else _methodBase = dynamicMethod; } // This method will combine this delegate with the passed delegate // to form a new delegate. [System.Security.SecuritySafeCritical] // auto-generated protected override sealed Delegate CombineImpl(Delegate follow) { if ((Object)follow == null) // cast to object for a more efficient test return this; // Verify that the types are the same... if (!InternalEqualTypes(this, follow)) throw new ArgumentException(Environment.GetResourceString("Arg_DlgtTypeMis")); MulticastDelegate dFollow = (MulticastDelegate)follow; Object[] resultList; int followCount = 1; Object[] followList = dFollow._invocationList as Object[]; if (followList != null) followCount = (int)dFollow._invocationCount; int resultCount; Object[] invocationList = _invocationList as Object[]; if (invocationList == null) { resultCount = 1 + followCount; resultList = new Object[resultCount]; resultList[0] = this; if (followList == null) { resultList[1] = dFollow; } else { for (int i = 0; i < followCount; i++) resultList[1 + i] = followList[i]; } return NewMulticastDelegate(resultList, resultCount); } else { int invocationCount = (int)_invocationCount; resultCount = invocationCount + followCount; resultList = null; if (resultCount <= invocationList.Length) { resultList = invocationList; if (followList == null) { if (!TrySetSlot(resultList, invocationCount, dFollow)) resultList = null; } else { for (int i = 0; i < followCount; i++) { if (!TrySetSlot(resultList, invocationCount + i, followList[i])) { resultList = null; break; } } } } if (resultList == null) { int allocCount = invocationList.Length; while (allocCount < resultCount) allocCount *= 2; resultList = new Object[allocCount]; for (int i = 0; i < invocationCount; i++) resultList[i] = invocationList[i]; if (followList == null) { resultList[invocationCount] = dFollow; } else { for (int i = 0; i < followCount; i++) resultList[invocationCount + i] = followList[i]; } } return NewMulticastDelegate(resultList, resultCount, true); } } [System.Security.SecurityCritical] private Object[] DeleteFromInvocationList(Object[] invocationList, int invocationCount, int deleteIndex, int deleteCount) { Object[] thisInvocationList = _invocationList as Object[]; int allocCount = thisInvocationList.Length; while (allocCount/2 >= invocationCount - deleteCount) allocCount /= 2; Object[] newInvocationList = new Object[allocCount]; for (int i = 0; i < deleteIndex; i++) newInvocationList[i] = invocationList[i]; for (int i = deleteIndex + deleteCount; i < invocationCount; i++) newInvocationList[i - deleteCount] = invocationList[i]; return newInvocationList; } private bool EqualInvocationLists(Object[] a, Object[] b, int start, int count) { for (int i = 0; i < count; i++) { if (!(a[start + i].Equals(b[i]))) return false; } return true; } // This method currently looks backward on the invocation list // for an element that has Delegate based equality with value. (Doesn't // look at the invocation list.) If this is found we remove it from // this list and return a new delegate. If its not found a copy of the // current list is returned. [System.Security.SecuritySafeCritical] // auto-generated protected override sealed Delegate RemoveImpl(Delegate value) { // There is a special case were we are removing using a delegate as // the value we need to check for this case // MulticastDelegate v = value as MulticastDelegate; if (v == null) return this; if (v._invocationList as Object[] == null) { Object[] invocationList = _invocationList as Object[]; if (invocationList == null) { // they are both not real Multicast if (this.Equals(value)) return null; } else { int invocationCount = (int)_invocationCount; for (int i = invocationCount; --i >= 0; ) { if (value.Equals(invocationList[i])) { if (invocationCount == 2) { // Special case - only one value left, either at the beginning or the end return (Delegate)invocationList[1-i]; } else { Object[] list = DeleteFromInvocationList(invocationList, invocationCount, i, 1); return NewMulticastDelegate(list, invocationCount-1, true); } } } } } else { Object[] invocationList = _invocationList as Object[]; if (invocationList != null) { int invocationCount = (int)_invocationCount; int vInvocationCount = (int)v._invocationCount; for (int i = invocationCount - vInvocationCount; i >= 0; i--) { if (EqualInvocationLists(invocationList, v._invocationList as Object[], i, vInvocationCount)) { if (invocationCount - vInvocationCount == 0) { // Special case - no values left return null; } else if (invocationCount - vInvocationCount == 1) { // Special case - only one value left, either at the beginning or the end return (Delegate)invocationList[i != 0 ? 0 : invocationCount-1]; } else { Object[] list = DeleteFromInvocationList(invocationList, invocationCount, i, vInvocationCount); return NewMulticastDelegate(list, invocationCount - vInvocationCount, true); } } } } } return this; } // This method returns the Invocation list of this multicast delegate. [System.Security.SecuritySafeCritical] public override sealed Delegate[] GetInvocationList() { Contract.Ensures(Contract.Result<Delegate[]>() != null); Delegate[] del; Object[] invocationList = _invocationList as Object[]; if (invocationList == null) { del = new Delegate[1]; del[0] = this; } else { // Create an array of delegate copies and each // element into the array int invocationCount = (int)_invocationCount; del = new Delegate[invocationCount]; for (int i = 0; i < invocationCount; i++) del[i] = (Delegate)invocationList[i]; } return del; } public static bool operator ==(MulticastDelegate d1, MulticastDelegate d2) { if ((Object)d1 == null) return (Object)d2 == null; return d1.Equals(d2); } public static bool operator !=(MulticastDelegate d1, MulticastDelegate d2) { if ((Object)d1 == null) return (Object)d2 != null; return !d1.Equals(d2); } [System.Security.SecuritySafeCritical] public override sealed int GetHashCode() { if (IsUnmanagedFunctionPtr()) return ValueType.GetHashCodeOfPtr(_methodPtr) ^ ValueType.GetHashCodeOfPtr(_methodPtrAux); Object[] invocationList = _invocationList as Object[]; if (invocationList == null) { return base.GetHashCode(); } else { int hash = 0; for (int i = 0; i < (int)_invocationCount; i++) { hash = hash*33 + invocationList[i].GetHashCode(); } return hash; } } [System.Security.SecuritySafeCritical] internal override Object GetTarget() { if (_invocationCount != (IntPtr)0) { // _invocationCount != 0 we are in one of these cases: // - Multicast -> return the target of the last delegate in the list // - Secure/wrapper delegate -> return the target of the inner delegate // - unmanaged function pointer - return null // - virtual open delegate - return null if (InvocationListLogicallyNull()) { // both open virtual and ftn pointer return null for the target return null; } else { Object[] invocationList = _invocationList as Object[]; if (invocationList != null) { int invocationCount = (int)_invocationCount; return ((Delegate)invocationList[invocationCount - 1]).GetTarget(); } else { Delegate receiver = _invocationList as Delegate; if (receiver != null) return receiver.GetTarget(); } } } return base.GetTarget(); } [System.Security.SecuritySafeCritical] protected override MethodInfo GetMethodImpl() { if (_invocationCount != (IntPtr)0 && _invocationList != null) { // multicast case Object[] invocationList = _invocationList as Object[]; if (invocationList != null) { int index = (int)_invocationCount - 1; return ((Delegate)invocationList[index]).Method; } MulticastDelegate innerDelegate = _invocationList as MulticastDelegate; if (innerDelegate != null) { // must be a secure/wrapper delegate return innerDelegate.GetMethodImpl(); } } else if (IsUnmanagedFunctionPtr()) { // we handle unmanaged function pointers here because the generic ones (used for WinRT) would otherwise // be treated as open delegates by the base implementation, resulting in failure to get the MethodInfo if ((_methodBase == null) || !(_methodBase is MethodInfo)) { IRuntimeMethodInfo method = FindMethodHandle(); RuntimeType declaringType = RuntimeMethodHandle.GetDeclaringType(method); // need a proper declaring type instance method on a generic type if (RuntimeTypeHandle.IsGenericTypeDefinition(declaringType) || RuntimeTypeHandle.HasInstantiation(declaringType)) { // we are returning the 'Invoke' method of this delegate so use this.GetType() for the exact type RuntimeType reflectedType = GetType() as RuntimeType; declaringType = reflectedType; } _methodBase = (MethodInfo)RuntimeType.GetMethodBase(declaringType, method); } return (MethodInfo)_methodBase; } // Otherwise, must be an inner delegate of a SecureDelegate of an open virtual method. In that case, call base implementation return base.GetMethodImpl(); } // this should help inlining [System.Diagnostics.DebuggerNonUserCode] private void ThrowNullThisInDelegateToInstance() { throw new ArgumentException(Environment.GetResourceString("Arg_DlgtNullInst")); } [System.Security.SecurityCritical] [System.Diagnostics.DebuggerNonUserCode] private void CtorClosed(Object target, IntPtr methodPtr) { if (target == null) ThrowNullThisInDelegateToInstance(); this._target = target; this._methodPtr = methodPtr; } [System.Security.SecurityCritical] [System.Diagnostics.DebuggerNonUserCode] private void CtorClosedStatic(Object target, IntPtr methodPtr) { this._target = target; this._methodPtr = methodPtr; } [System.Security.SecurityCritical] // auto-generated [System.Diagnostics.DebuggerNonUserCode] private void CtorRTClosed(Object target, IntPtr methodPtr) { this._target = target; this._methodPtr = AdjustTarget(target, methodPtr); } [System.Security.SecurityCritical] [System.Diagnostics.DebuggerNonUserCode] private void CtorOpened(Object target, IntPtr methodPtr, IntPtr shuffleThunk) { this._target = this; this._methodPtr = shuffleThunk; this._methodPtrAux = methodPtr; } [System.Security.SecurityCritical] // auto-generated [System.Diagnostics.DebuggerNonUserCode] private void CtorSecureClosed(Object target, IntPtr methodPtr, IntPtr callThunk, IntPtr creatorMethod) { MulticastDelegate realDelegate = (MulticastDelegate)Delegate.InternalAllocLike(this); realDelegate.CtorClosed(target, methodPtr); this._invocationList = realDelegate; this._target = this; this._methodPtr = callThunk; this._methodPtrAux = creatorMethod; this._invocationCount = GetInvokeMethod(); } [System.Security.SecurityCritical] // auto-generated [System.Diagnostics.DebuggerNonUserCode] private void CtorSecureClosedStatic(Object target, IntPtr methodPtr, IntPtr callThunk, IntPtr creatorMethod) { MulticastDelegate realDelegate = (MulticastDelegate)Delegate.InternalAllocLike(this); realDelegate.CtorClosedStatic(target, methodPtr); this._invocationList = realDelegate; this._target = this; this._methodPtr = callThunk; this._methodPtrAux = creatorMethod; this._invocationCount = GetInvokeMethod(); } [System.Security.SecurityCritical] // auto-generated [System.Diagnostics.DebuggerNonUserCode] private void CtorSecureRTClosed(Object target, IntPtr methodPtr, IntPtr callThunk, IntPtr creatorMethod) { MulticastDelegate realDelegate = Delegate.InternalAllocLike(this); realDelegate.CtorRTClosed(target, methodPtr); this._invocationList = realDelegate; this._target = this; this._methodPtr = callThunk; this._methodPtrAux = creatorMethod; this._invocationCount = GetInvokeMethod(); } [System.Security.SecurityCritical] // auto-generated [System.Diagnostics.DebuggerNonUserCode] private void CtorSecureOpened(Object target, IntPtr methodPtr, IntPtr shuffleThunk, IntPtr callThunk, IntPtr creatorMethod) { MulticastDelegate realDelegate = Delegate.InternalAllocLike(this); realDelegate.CtorOpened(target, methodPtr, shuffleThunk); this._invocationList = realDelegate; this._target = this; this._methodPtr = callThunk; this._methodPtrAux = creatorMethod; this._invocationCount = GetInvokeMethod(); } [System.Security.SecurityCritical] // auto-generated [System.Diagnostics.DebuggerNonUserCode] private void CtorVirtualDispatch(Object target, IntPtr methodPtr, IntPtr shuffleThunk) { this._target = this; this._methodPtr = shuffleThunk; this._methodPtrAux = GetCallStub(methodPtr); } [System.Security.SecurityCritical] // auto-generated [System.Diagnostics.DebuggerNonUserCode] private void CtorSecureVirtualDispatch(Object target, IntPtr methodPtr, IntPtr shuffleThunk, IntPtr callThunk, IntPtr creatorMethod) { MulticastDelegate realDelegate = Delegate.InternalAllocLike(this); realDelegate.CtorVirtualDispatch(target, methodPtr, shuffleThunk); this._invocationList = realDelegate; this._target = this; this._methodPtr = callThunk; this._methodPtrAux = creatorMethod; this._invocationCount = GetInvokeMethod(); } [System.Security.SecurityCritical] // auto-generated [System.Diagnostics.DebuggerNonUserCode] private void CtorCollectibleClosedStatic(Object target, IntPtr methodPtr, IntPtr gchandle) { this._target = target; this._methodPtr = methodPtr; this._methodBase = System.Runtime.InteropServices.GCHandle.InternalGet(gchandle); } [System.Security.SecurityCritical] // auto-generated [System.Diagnostics.DebuggerNonUserCode] private void CtorCollectibleOpened(Object target, IntPtr methodPtr, IntPtr shuffleThunk, IntPtr gchandle) { this._target = this; this._methodPtr = shuffleThunk; this._methodPtrAux = methodPtr; this._methodBase = System.Runtime.InteropServices.GCHandle.InternalGet(gchandle); } [System.Security.SecurityCritical] // auto-generated [System.Diagnostics.DebuggerNonUserCode] private void CtorCollectibleVirtualDispatch(Object target, IntPtr methodPtr, IntPtr shuffleThunk, IntPtr gchandle) { this._target = this; this._methodPtr = shuffleThunk; this._methodPtrAux = GetCallStub(methodPtr); this._methodBase = System.Runtime.InteropServices.GCHandle.InternalGet(gchandle); } } }
// DeflateStream.cs // ------------------------------------------------------------------ // // Copyright (c) 2009-2010 Dino Chiesa. // All rights reserved. // // This code module is part of DotNetZip, a zipfile class library. // // ------------------------------------------------------------------ // // This code is licensed under the Microsoft Public License. // See the file License.txt for the license details. // More info on: http://dotnetzip.codeplex.com // // ------------------------------------------------------------------ // // last saved (in emacs): // Time-stamp: <2011-July-31 14:48:11> // // ------------------------------------------------------------------ // // This module defines the DeflateStream class, which can be used as a replacement for // the System.IO.Compression.DeflateStream class in the .NET BCL. // // ------------------------------------------------------------------ using System; namespace BestHTTP.Decompression.Zlib { /// <summary> /// A class for compressing and decompressing streams using the Deflate algorithm. /// </summary> /// /// <remarks> /// /// <para> /// The DeflateStream is a <see /// href="http://en.wikipedia.org/wiki/Decorator_pattern">Decorator</see> on a <see /// cref="System.IO.Stream"/>. It adds DEFLATE compression or decompression to any /// stream. /// </para> /// /// <para> /// Using this stream, applications can compress or decompress data via stream /// <c>Read</c> and <c>Write</c> operations. Either compresssion or decompression /// can occur through either reading or writing. The compression format used is /// DEFLATE, which is documented in <see /// href="http://www.ietf.org/rfc/rfc1951.txt">IETF RFC 1951</see>, "DEFLATE /// Compressed Data Format Specification version 1.3.". /// </para> /// /// </remarks> /// /// <seealso cref="GZipStream" /> internal class DeflateStream : System.IO.Stream { internal ZlibBaseStream _baseStream; internal System.IO.Stream _innerStream; bool _disposed; /// <summary> /// Create a DeflateStream using the specified CompressionMode. /// </summary> /// /// <remarks> /// When mode is <c>CompressionMode.Compress</c>, the DeflateStream will use /// the default compression level. The "captive" stream will be closed when /// the DeflateStream is closed. /// </remarks> /// /// <example> /// This example uses a DeflateStream to compress data from a file, and writes /// the compressed data to another file. /// <code> /// using (System.IO.Stream input = System.IO.File.OpenRead(fileToCompress)) /// { /// using (var raw = System.IO.File.Create(fileToCompress + ".deflated")) /// { /// using (Stream compressor = new DeflateStream(raw, CompressionMode.Compress)) /// { /// byte[] buffer = new byte[WORKING_BUFFER_SIZE]; /// int n; /// while ((n= input.Read(buffer, 0, buffer.Length)) != 0) /// { /// compressor.Write(buffer, 0, n); /// } /// } /// } /// } /// </code> /// /// <code lang="VB"> /// Using input As Stream = File.OpenRead(fileToCompress) /// Using raw As FileStream = File.Create(fileToCompress &amp; ".deflated") /// Using compressor As Stream = New DeflateStream(raw, CompressionMode.Compress) /// Dim buffer As Byte() = New Byte(4096) {} /// Dim n As Integer = -1 /// Do While (n &lt;&gt; 0) /// If (n &gt; 0) Then /// compressor.Write(buffer, 0, n) /// End If /// n = input.Read(buffer, 0, buffer.Length) /// Loop /// End Using /// End Using /// End Using /// </code> /// </example> /// <param name="stream">The stream which will be read or written.</param> /// <param name="mode">Indicates whether the DeflateStream will compress or decompress.</param> public DeflateStream(System.IO.Stream stream, CompressionMode mode) : this(stream, mode, CompressionLevel.Default, false) { } /// <summary> /// Create a DeflateStream using the specified CompressionMode and the specified CompressionLevel. /// </summary> /// /// <remarks> /// /// <para> /// When mode is <c>CompressionMode.Decompress</c>, the level parameter is /// ignored. The "captive" stream will be closed when the DeflateStream is /// closed. /// </para> /// /// </remarks> /// /// <example> /// /// This example uses a DeflateStream to compress data from a file, and writes /// the compressed data to another file. /// /// <code> /// using (System.IO.Stream input = System.IO.File.OpenRead(fileToCompress)) /// { /// using (var raw = System.IO.File.Create(fileToCompress + ".deflated")) /// { /// using (Stream compressor = new DeflateStream(raw, /// CompressionMode.Compress, /// CompressionLevel.BestCompression)) /// { /// byte[] buffer = new byte[WORKING_BUFFER_SIZE]; /// int n= -1; /// while (n != 0) /// { /// if (n &gt; 0) /// compressor.Write(buffer, 0, n); /// n= input.Read(buffer, 0, buffer.Length); /// } /// } /// } /// } /// </code> /// /// <code lang="VB"> /// Using input As Stream = File.OpenRead(fileToCompress) /// Using raw As FileStream = File.Create(fileToCompress &amp; ".deflated") /// Using compressor As Stream = New DeflateStream(raw, CompressionMode.Compress, CompressionLevel.BestCompression) /// Dim buffer As Byte() = New Byte(4096) {} /// Dim n As Integer = -1 /// Do While (n &lt;&gt; 0) /// If (n &gt; 0) Then /// compressor.Write(buffer, 0, n) /// End If /// n = input.Read(buffer, 0, buffer.Length) /// Loop /// End Using /// End Using /// End Using /// </code> /// </example> /// <param name="stream">The stream to be read or written while deflating or inflating.</param> /// <param name="mode">Indicates whether the <c>DeflateStream</c> will compress or decompress.</param> /// <param name="level">A tuning knob to trade speed for effectiveness.</param> public DeflateStream(System.IO.Stream stream, CompressionMode mode, CompressionLevel level) : this(stream, mode, level, false) { } /// <summary> /// Create a <c>DeflateStream</c> using the specified /// <c>CompressionMode</c>, and explicitly specify whether the /// stream should be left open after Deflation or Inflation. /// </summary> /// /// <remarks> /// /// <para> /// This constructor allows the application to request that the captive stream /// remain open after the deflation or inflation occurs. By default, after /// <c>Close()</c> is called on the stream, the captive stream is also /// closed. In some cases this is not desired, for example if the stream is a /// memory stream that will be re-read after compression. Specify true for /// the <paramref name="leaveOpen"/> parameter to leave the stream open. /// </para> /// /// <para> /// The <c>DeflateStream</c> will use the default compression level. /// </para> /// /// <para> /// See the other overloads of this constructor for example code. /// </para> /// </remarks> /// /// <param name="stream"> /// The stream which will be read or written. This is called the /// "captive" stream in other places in this documentation. /// </param> /// /// <param name="mode"> /// Indicates whether the <c>DeflateStream</c> will compress or decompress. /// </param> /// /// <param name="leaveOpen">true if the application would like the stream to /// remain open after inflation/deflation.</param> public DeflateStream(System.IO.Stream stream, CompressionMode mode, bool leaveOpen) : this(stream, mode, CompressionLevel.Default, leaveOpen) { } /// <summary> /// Create a <c>DeflateStream</c> using the specified <c>CompressionMode</c> /// and the specified <c>CompressionLevel</c>, and explicitly specify whether /// the stream should be left open after Deflation or Inflation. /// </summary> /// /// <remarks> /// /// <para> /// When mode is <c>CompressionMode.Decompress</c>, the level parameter is ignored. /// </para> /// /// <para> /// This constructor allows the application to request that the captive stream /// remain open after the deflation or inflation occurs. By default, after /// <c>Close()</c> is called on the stream, the captive stream is also /// closed. In some cases this is not desired, for example if the stream is a /// <see cref="System.IO.MemoryStream"/> that will be re-read after /// compression. Specify true for the <paramref name="leaveOpen"/> parameter /// to leave the stream open. /// </para> /// /// </remarks> /// /// <example> /// /// This example shows how to use a <c>DeflateStream</c> to compress data from /// a file, and store the compressed data into another file. /// /// <code> /// using (var output = System.IO.File.Create(fileToCompress + ".deflated")) /// { /// using (System.IO.Stream input = System.IO.File.OpenRead(fileToCompress)) /// { /// using (Stream compressor = new DeflateStream(output, CompressionMode.Compress, CompressionLevel.BestCompression, true)) /// { /// byte[] buffer = new byte[WORKING_BUFFER_SIZE]; /// int n= -1; /// while (n != 0) /// { /// if (n &gt; 0) /// compressor.Write(buffer, 0, n); /// n= input.Read(buffer, 0, buffer.Length); /// } /// } /// } /// // can write additional data to the output stream here /// } /// </code> /// /// <code lang="VB"> /// Using output As FileStream = File.Create(fileToCompress &amp; ".deflated") /// Using input As Stream = File.OpenRead(fileToCompress) /// Using compressor As Stream = New DeflateStream(output, CompressionMode.Compress, CompressionLevel.BestCompression, True) /// Dim buffer As Byte() = New Byte(4096) {} /// Dim n As Integer = -1 /// Do While (n &lt;&gt; 0) /// If (n &gt; 0) Then /// compressor.Write(buffer, 0, n) /// End If /// n = input.Read(buffer, 0, buffer.Length) /// Loop /// End Using /// End Using /// ' can write additional data to the output stream here. /// End Using /// </code> /// </example> /// <param name="stream">The stream which will be read or written.</param> /// <param name="mode">Indicates whether the DeflateStream will compress or decompress.</param> /// <param name="leaveOpen">true if the application would like the stream to remain open after inflation/deflation.</param> /// <param name="level">A tuning knob to trade speed for effectiveness.</param> public DeflateStream(System.IO.Stream stream, CompressionMode mode, CompressionLevel level, bool leaveOpen) { _innerStream = stream; _baseStream = new ZlibBaseStream(stream, mode, level, ZlibStreamFlavor.DEFLATE, leaveOpen); } #region Zlib properties /// <summary> /// This property sets the flush behavior on the stream. /// </summary> /// <remarks> See the ZLIB documentation for the meaning of the flush behavior. /// </remarks> virtual public FlushType FlushMode { get { return (this._baseStream._flushMode); } set { if (_disposed) throw new ObjectDisposedException("DeflateStream"); this._baseStream._flushMode = value; } } /// <summary> /// The size of the working buffer for the compression codec. /// </summary> /// /// <remarks> /// <para> /// The working buffer is used for all stream operations. The default size is /// 1024 bytes. The minimum size is 128 bytes. You may get better performance /// with a larger buffer. Then again, you might not. You would have to test /// it. /// </para> /// /// <para> /// Set this before the first call to <c>Read()</c> or <c>Write()</c> on the /// stream. If you try to set it afterwards, it will throw. /// </para> /// </remarks> public int BufferSize { get { return this._baseStream._bufferSize; } set { if (_disposed) throw new ObjectDisposedException("DeflateStream"); if (this._baseStream._workingBuffer != null) throw new ZlibException("The working buffer is already set."); if (value < ZlibConstants.WorkingBufferSizeMin) throw new ZlibException(String.Format("Don't be silly. {0} bytes?? Use a bigger buffer, at least {1}.", value, ZlibConstants.WorkingBufferSizeMin)); this._baseStream._bufferSize = value; } } /// <summary> /// The ZLIB strategy to be used during compression. /// </summary> /// /// <remarks> /// By tweaking this parameter, you may be able to optimize the compression for /// data with particular characteristics. /// </remarks> public CompressionStrategy Strategy { get { return this._baseStream.Strategy; } set { if (_disposed) throw new ObjectDisposedException("DeflateStream"); this._baseStream.Strategy = value; } } /// <summary> Returns the total number of bytes input so far.</summary> virtual public long TotalIn { get { return this._baseStream._z.TotalBytesIn; } } /// <summary> Returns the total number of bytes output so far.</summary> virtual public long TotalOut { get { return this._baseStream._z.TotalBytesOut; } } #endregion #region System.IO.Stream methods /// <summary> /// Dispose the stream. /// </summary> /// <remarks> /// <para> /// This may or may not result in a <c>Close()</c> call on the captive /// stream. See the constructors that have a <c>leaveOpen</c> parameter /// for more information. /// </para> /// <para> /// Application code won't call this code directly. This method may be /// invoked in two distinct scenarios. If disposing == true, the method /// has been called directly or indirectly by a user's code, for example /// via the public Dispose() method. In this case, both managed and /// unmanaged resources can be referenced and disposed. If disposing == /// false, the method has been called by the runtime from inside the /// object finalizer and this method should not reference other objects; /// in that case only unmanaged resources must be referenced or /// disposed. /// </para> /// </remarks> /// <param name="disposing"> /// true if the Dispose method was invoked by user code. /// </param> protected override void Dispose(bool disposing) { try { if (!_disposed) { if (disposing && (this._baseStream != null)) this._baseStream.Close(); _disposed = true; } } finally { base.Dispose(disposing); } } /// <summary> /// Indicates whether the stream can be read. /// </summary> /// <remarks> /// The return value depends on whether the captive stream supports reading. /// </remarks> public override bool CanRead { get { if (_disposed) throw new ObjectDisposedException("DeflateStream"); return _baseStream._stream.CanRead; } } /// <summary> /// Indicates whether the stream supports Seek operations. /// </summary> /// <remarks> /// Always returns false. /// </remarks> public override bool CanSeek { get { return false; } } /// <summary> /// Indicates whether the stream can be written. /// </summary> /// <remarks> /// The return value depends on whether the captive stream supports writing. /// </remarks> public override bool CanWrite { get { if (_disposed) throw new ObjectDisposedException("DeflateStream"); return _baseStream._stream.CanWrite; } } /// <summary> /// Flush the stream. /// </summary> public override void Flush() { if (_disposed) throw new ObjectDisposedException("DeflateStream"); _baseStream.Flush(); } /// <summary> /// Reading this property always throws a <see cref="NotImplementedException"/>. /// </summary> public override long Length { get { throw new NotImplementedException(); } } /// <summary> /// The position of the stream pointer. /// </summary> /// /// <remarks> /// Setting this property always throws a <see /// cref="NotImplementedException"/>. Reading will return the total bytes /// written out, if used in writing, or the total bytes read in, if used in /// reading. The count may refer to compressed bytes or uncompressed bytes, /// depending on how you've used the stream. /// </remarks> public override long Position { get { if (this._baseStream._streamMode == BestHTTP.Decompression.Zlib.ZlibBaseStream.StreamMode.Writer) return this._baseStream._z.TotalBytesOut; if (this._baseStream._streamMode == BestHTTP.Decompression.Zlib.ZlibBaseStream.StreamMode.Reader) return this._baseStream._z.TotalBytesIn; return 0; } set { throw new NotImplementedException(); } } /// <summary> /// Read data from the stream. /// </summary> /// <remarks> /// /// <para> /// If you wish to use the <c>DeflateStream</c> to compress data while /// reading, you can create a <c>DeflateStream</c> with /// <c>CompressionMode.Compress</c>, providing an uncompressed data stream. /// Then call Read() on that <c>DeflateStream</c>, and the data read will be /// compressed as you read. If you wish to use the <c>DeflateStream</c> to /// decompress data while reading, you can create a <c>DeflateStream</c> with /// <c>CompressionMode.Decompress</c>, providing a readable compressed data /// stream. Then call Read() on that <c>DeflateStream</c>, and the data read /// will be decompressed as you read. /// </para> /// /// <para> /// A <c>DeflateStream</c> can be used for <c>Read()</c> or <c>Write()</c>, but not both. /// </para> /// /// </remarks> /// <param name="buffer">The buffer into which the read data should be placed.</param> /// <param name="offset">the offset within that data array to put the first byte read.</param> /// <param name="count">the number of bytes to read.</param> /// <returns>the number of bytes actually read</returns> public override int Read(byte[] buffer, int offset, int count) { if (_disposed) throw new ObjectDisposedException("DeflateStream"); return _baseStream.Read(buffer, offset, count); } /// <summary> /// Calling this method always throws a <see cref="NotImplementedException"/>. /// </summary> /// <param name="offset">this is irrelevant, since it will always throw!</param> /// <param name="origin">this is irrelevant, since it will always throw!</param> /// <returns>irrelevant!</returns> public override long Seek(long offset, System.IO.SeekOrigin origin) { throw new NotImplementedException(); } /// <summary> /// Calling this method always throws a <see cref="NotImplementedException"/>. /// </summary> /// <param name="value">this is irrelevant, since it will always throw!</param> public override void SetLength(long value) { throw new NotImplementedException(); } /// <summary> /// Write data to the stream. /// </summary> /// <remarks> /// /// <para> /// If you wish to use the <c>DeflateStream</c> to compress data while /// writing, you can create a <c>DeflateStream</c> with /// <c>CompressionMode.Compress</c>, and a writable output stream. Then call /// <c>Write()</c> on that <c>DeflateStream</c>, providing uncompressed data /// as input. The data sent to the output stream will be the compressed form /// of the data written. If you wish to use the <c>DeflateStream</c> to /// decompress data while writing, you can create a <c>DeflateStream</c> with /// <c>CompressionMode.Decompress</c>, and a writable output stream. Then /// call <c>Write()</c> on that stream, providing previously compressed /// data. The data sent to the output stream will be the decompressed form of /// the data written. /// </para> /// /// <para> /// A <c>DeflateStream</c> can be used for <c>Read()</c> or <c>Write()</c>, /// but not both. /// </para> /// /// </remarks> /// /// <param name="buffer">The buffer holding data to write to the stream.</param> /// <param name="offset">the offset within that data array to find the first byte to write.</param> /// <param name="count">the number of bytes to write.</param> public override void Write(byte[] buffer, int offset, int count) { if (_disposed) throw new ObjectDisposedException("DeflateStream"); _baseStream.Write(buffer, offset, count); } #endregion /// <summary> /// Compress a string into a byte array using DEFLATE (RFC 1951). /// </summary> /// /// <remarks> /// Uncompress it with <see cref="DeflateStream.UncompressString(byte[])"/>. /// </remarks> /// /// <seealso cref="DeflateStream.UncompressString(byte[])">DeflateStream.UncompressString(byte[])</seealso> /// <seealso cref="DeflateStream.CompressBuffer(byte[])">DeflateStream.CompressBuffer(byte[])</seealso> /// <seealso cref="GZipStream.CompressString(string)">GZipStream.CompressString(string)</seealso> /// /// <param name="s"> /// A string to compress. The string will first be encoded /// using UTF8, then compressed. /// </param> /// /// <returns>The string in compressed form</returns> public static byte[] CompressString(String s) { using (var ms = new System.IO.MemoryStream()) { System.IO.Stream compressor = new DeflateStream(ms, CompressionMode.Compress, CompressionLevel.BestCompression); ZlibBaseStream.CompressString(s, compressor); return ms.ToArray(); } } /// <summary> /// Compress a byte array into a new byte array using DEFLATE. /// </summary> /// /// <remarks> /// Uncompress it with <see cref="DeflateStream.UncompressBuffer(byte[])"/>. /// </remarks> /// /// <seealso cref="DeflateStream.CompressString(string)">DeflateStream.CompressString(string)</seealso> /// <seealso cref="DeflateStream.UncompressBuffer(byte[])">DeflateStream.UncompressBuffer(byte[])</seealso> /// <seealso cref="GZipStream.CompressBuffer(byte[])">GZipStream.CompressBuffer(byte[])</seealso> /// /// <param name="b"> /// A buffer to compress. /// </param> /// /// <returns>The data in compressed form</returns> public static byte[] CompressBuffer(byte[] b) { using (var ms = new System.IO.MemoryStream()) { System.IO.Stream compressor = new DeflateStream( ms, CompressionMode.Compress, CompressionLevel.BestCompression ); ZlibBaseStream.CompressBuffer(b, compressor); return ms.ToArray(); } } /// <summary> /// Uncompress a DEFLATE'd byte array into a single string. /// </summary> /// /// <seealso cref="DeflateStream.CompressString(String)">DeflateStream.CompressString(String)</seealso> /// <seealso cref="DeflateStream.UncompressBuffer(byte[])">DeflateStream.UncompressBuffer(byte[])</seealso> /// <seealso cref="GZipStream.UncompressString(byte[])">GZipStream.UncompressString(byte[])</seealso> /// /// <param name="compressed"> /// A buffer containing DEFLATE-compressed data. /// </param> /// /// <returns>The uncompressed string</returns> public static String UncompressString(byte[] compressed) { using (var input = new System.IO.MemoryStream(compressed)) { System.IO.Stream decompressor = new DeflateStream(input, CompressionMode.Decompress); return ZlibBaseStream.UncompressString(compressed, decompressor); } } /// <summary> /// Uncompress a DEFLATE'd byte array into a byte array. /// </summary> /// /// <seealso cref="DeflateStream.CompressBuffer(byte[])">DeflateStream.CompressBuffer(byte[])</seealso> /// <seealso cref="DeflateStream.UncompressString(byte[])">DeflateStream.UncompressString(byte[])</seealso> /// <seealso cref="GZipStream.UncompressBuffer(byte[])">GZipStream.UncompressBuffer(byte[])</seealso> /// /// <param name="compressed"> /// A buffer containing data that has been compressed with DEFLATE. /// </param> /// /// <returns>The data in uncompressed form</returns> public static byte[] UncompressBuffer(byte[] compressed) { using (var input = new System.IO.MemoryStream(compressed)) { System.IO.Stream decompressor = new DeflateStream( input, CompressionMode.Decompress ); return ZlibBaseStream.UncompressBuffer(compressed, decompressor); } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Xml; using OLEDB.Test.ModuleCore; namespace XmlReaderTest.Common { public partial class TCReadElementContentAsBinHex : TCXMLReaderBaseGeneral { // Type is XmlReaderTest.Common.TCReadElementContentAsBinHex // Test Case public override void AddChildren() { // for function TestReadBinHex_1 { this.AddChild(new CVariation(TestReadBinHex_1) { Attribute = new Variation("ReadBinHex Element with all valid value") }); } // for function TestReadBinHex_2 { this.AddChild(new CVariation(TestReadBinHex_2) { Attribute = new Variation("ReadBinHex Element with all valid Num value") { Pri = 0 } }); } // for function TestReadBinHex_3 { this.AddChild(new CVariation(TestReadBinHex_3) { Attribute = new Variation("ReadBinHex Element with all valid Text value") }); } // for function TestReadBinHex_4 { this.AddChild(new CVariation(TestReadBinHex_4) { Attribute = new Variation("ReadBinHex Element with Comments and PIs") { Pri = 0 } }); } // for function TestReadBinHex_5 { this.AddChild(new CVariation(TestReadBinHex_5) { Attribute = new Variation("ReadBinHex Element with all valid value (from concatenation), Pri=0") }); } // for function TestReadBinHex_6 { this.AddChild(new CVariation(TestReadBinHex_6) { Attribute = new Variation("ReadBinHex Element with all long valid value (from concatenation)") }); } // for function TestReadBinHex_7 { this.AddChild(new CVariation(TestReadBinHex_7) { Attribute = new Variation("ReadBinHex with count > buffer size") }); } // for function TestReadBinHex_8 { this.AddChild(new CVariation(TestReadBinHex_8) { Attribute = new Variation("ReadBinHex with count < 0") }); } // for function vReadBinHex_9 { this.AddChild(new CVariation(vReadBinHex_9) { Attribute = new Variation("ReadBinHex with index > buffer size") }); } // for function TestReadBinHex_10 { this.AddChild(new CVariation(TestReadBinHex_10) { Attribute = new Variation("ReadBinHex with index < 0") }); } // for function TestReadBinHex_11 { this.AddChild(new CVariation(TestReadBinHex_11) { Attribute = new Variation("ReadBinHex with index + count exceeds buffer") }); } // for function TestReadBinHex_12 { this.AddChild(new CVariation(TestReadBinHex_12) { Attribute = new Variation("ReadBinHex index & count =0") }); } // for function TestReadBinHex_13 { this.AddChild(new CVariation(TestReadBinHex_13) { Attribute = new Variation("ReadBinHex Element multiple into same buffer (using offset), Pri=0") }); } // for function TestReadBinHex_14 { this.AddChild(new CVariation(TestReadBinHex_14) { Attribute = new Variation("ReadBinHex with buffer == null") }); } // for function TestReadBinHex_16 { this.AddChild(new CVariation(TestReadBinHex_16) { Attribute = new Variation("Read after partial ReadBinHex") }); } // for function TestReadBinHex_18 { this.AddChild(new CVariation(TestReadBinHex_18) { Attribute = new Variation("No op node types") }); } // for function TestTextReadBinHex_21 { this.AddChild(new CVariation(TestTextReadBinHex_21) { Attribute = new Variation("ReadBinHex with whitespaces") }); } // for function TestTextReadBinHex_22 { this.AddChild(new CVariation(TestTextReadBinHex_22) { Attribute = new Variation("ReadBinHex with odd number of chars") }); } // for function TestTextReadBinHex_23 { this.AddChild(new CVariation(TestTextReadBinHex_23) { Attribute = new Variation("ReadBinHex when end tag doesn't exist") }); } // for function TestTextReadBinHex_24 { this.AddChild(new CVariation(TestTextReadBinHex_24) { Attribute = new Variation("WS:WireCompat:hex binary fails to send/return data after 1787 bytes") }); } // for function TestReadBinHex_430329 { this.AddChild(new CVariation(TestReadBinHex_430329) { Attribute = new Variation("SubtreeReader inserted attributes don't work with ReadContentAsBinHex") }); } // for function TestReadBinHex_27 { this.AddChild(new CVariation(TestReadBinHex_27) { Attribute = new Variation("ReadBinHex with = in the middle") }); } // for function TestReadBinHex_105376 { this.AddChild(new CVariation(TestReadBinHex_105376) { Attribute = new Variation("ReadBinHex runs into an Overflow") { Params = new object[] { "1000000" } } }); this.AddChild(new CVariation(TestReadBinHex_105376) { Attribute = new Variation("ReadBinHex runs into an Overflow") { Params = new object[] { "10000000" } } }); } // for function TestReadBinHex_28 { this.AddChild(new CVariation(TestReadBinHex_28) { Attribute = new Variation("call ReadContentAsBinHex on two or more nodes") }); } // for function TestReadBinHex_29 { this.AddChild(new CVariation(TestReadBinHex_29) { Attribute = new Variation("read BinHex over invalid text node") }); } // for function TestReadBinHex_30 { this.AddChild(new CVariation(TestReadBinHex_30) { Attribute = new Variation("goto to text node, ask got.Value, readcontentasBinHex") }); } // for function TestReadBinHex_31 { this.AddChild(new CVariation(TestReadBinHex_31) { Attribute = new Variation("goto to text node, readcontentasBinHex, ask got.Value") }); } // for function TestReadBinHex_32 { this.AddChild(new CVariation(TestReadBinHex_32) { Attribute = new Variation("goto to huge text node, read several chars with ReadContentAsBinHex and Move forward with .Read()") }); } // for function TestReadBinHex_33 { this.AddChild(new CVariation(TestReadBinHex_33) { Attribute = new Variation("goto to huge text node with invalid chars, read several chars with ReadContentAsBinHex and Move forward with .Read()") }); } // for function TestBinHex_34 { this.AddChild(new CVariation(TestBinHex_34) { Attribute = new Variation("ReadContentAsBinHex on an xmlns attribute") { Param = "<foo xmlns='default'> <bar > id='1'/> </foo>" } }); this.AddChild(new CVariation(TestBinHex_34) { Attribute = new Variation("ReadContentAsBinHex on an xmlns:k attribute") { Param = "<k:foo xmlns:k='default'> <k:bar id='1'/> </k:foo>" } }); this.AddChild(new CVariation(TestBinHex_34) { Attribute = new Variation("ReadContentAsBinHex on an xml:space attribute") { Param = "<foo xml:space='default'> <bar > id='1'/> </foo>" } }); this.AddChild(new CVariation(TestBinHex_34) { Attribute = new Variation("ReadContentAsBinHex on an xml:lang attribute") { Param = "<foo xml:lang='default'> <bar > id='1'/> </foo>" } }); } // for function TestReadBinHex_35 { this.AddChild(new CVariation(TestReadBinHex_35) { Attribute = new Variation("call ReadContentAsBinHex on two or more nodes and whitespace") }); } // for function TestReadBinHex_36 { this.AddChild(new CVariation(TestReadBinHex_36) { Attribute = new Variation("call ReadContentAsBinHex on two or more nodes and whitespace after call Value") }); } } } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gagvr = Google.Ads.GoogleAds.V9.Resources; using gax = Google.Api.Gax; using gaxgrpc = Google.Api.Gax.Grpc; using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore; using proto = Google.Protobuf; using grpccore = Grpc.Core; using grpcinter = Grpc.Core.Interceptors; using sys = System; using scg = System.Collections.Generic; using sco = System.Collections.ObjectModel; using st = System.Threading; using stt = System.Threading.Tasks; namespace Google.Ads.GoogleAds.V9.Services { /// <summary>Settings for <see cref="TopicViewServiceClient"/> instances.</summary> public sealed partial class TopicViewServiceSettings : gaxgrpc::ServiceSettingsBase { /// <summary>Get a new instance of the default <see cref="TopicViewServiceSettings"/>.</summary> /// <returns>A new instance of the default <see cref="TopicViewServiceSettings"/>.</returns> public static TopicViewServiceSettings GetDefault() => new TopicViewServiceSettings(); /// <summary>Constructs a new <see cref="TopicViewServiceSettings"/> object with default settings.</summary> public TopicViewServiceSettings() { } private TopicViewServiceSettings(TopicViewServiceSettings existing) : base(existing) { gax::GaxPreconditions.CheckNotNull(existing, nameof(existing)); GetTopicViewSettings = existing.GetTopicViewSettings; OnCopy(existing); } partial void OnCopy(TopicViewServiceSettings existing); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>TopicViewServiceClient.GetTopicView</c> and <c>TopicViewServiceClient.GetTopicViewAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>Initial retry delay: 5000 milliseconds.</description></item> /// <item><description>Retry delay multiplier: 1.3</description></item> /// <item><description>Retry maximum delay: 60000 milliseconds.</description></item> /// <item><description>Maximum attempts: Unlimited</description></item> /// <item> /// <description> /// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>, /// <see cref="grpccore::StatusCode.DeadlineExceeded"/>. /// </description> /// </item> /// <item><description>Timeout: 3600 seconds.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings GetTopicViewSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded))); /// <summary>Creates a deep clone of this object, with all the same property values.</summary> /// <returns>A deep clone of this <see cref="TopicViewServiceSettings"/> object.</returns> public TopicViewServiceSettings Clone() => new TopicViewServiceSettings(this); } /// <summary> /// Builder class for <see cref="TopicViewServiceClient"/> to provide simple configuration of credentials, endpoint /// etc. /// </summary> internal sealed partial class TopicViewServiceClientBuilder : gaxgrpc::ClientBuilderBase<TopicViewServiceClient> { /// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary> public TopicViewServiceSettings Settings { get; set; } /// <summary>Creates a new builder with default settings.</summary> public TopicViewServiceClientBuilder() { UseJwtAccessWithScopes = TopicViewServiceClient.UseJwtAccessWithScopes; } partial void InterceptBuild(ref TopicViewServiceClient client); partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<TopicViewServiceClient> task); /// <summary>Builds the resulting client.</summary> public override TopicViewServiceClient Build() { TopicViewServiceClient client = null; InterceptBuild(ref client); return client ?? BuildImpl(); } /// <summary>Builds the resulting client asynchronously.</summary> public override stt::Task<TopicViewServiceClient> BuildAsync(st::CancellationToken cancellationToken = default) { stt::Task<TopicViewServiceClient> task = null; InterceptBuildAsync(cancellationToken, ref task); return task ?? BuildAsyncImpl(cancellationToken); } private TopicViewServiceClient BuildImpl() { Validate(); grpccore::CallInvoker callInvoker = CreateCallInvoker(); return TopicViewServiceClient.Create(callInvoker, Settings); } private async stt::Task<TopicViewServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken) { Validate(); grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false); return TopicViewServiceClient.Create(callInvoker, Settings); } /// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary> protected override string GetDefaultEndpoint() => TopicViewServiceClient.DefaultEndpoint; /// <summary> /// Returns the default scopes for this builder type, used if no scopes are otherwise specified. /// </summary> protected override scg::IReadOnlyList<string> GetDefaultScopes() => TopicViewServiceClient.DefaultScopes; /// <summary>Returns the channel pool to use when no other options are specified.</summary> protected override gaxgrpc::ChannelPool GetChannelPool() => TopicViewServiceClient.ChannelPool; /// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary> protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance; } /// <summary>TopicViewService client wrapper, for convenient use.</summary> /// <remarks> /// Service to manage topic views. /// </remarks> public abstract partial class TopicViewServiceClient { /// <summary> /// The default endpoint for the TopicViewService service, which is a host of "googleads.googleapis.com" and a /// port of 443. /// </summary> public static string DefaultEndpoint { get; } = "googleads.googleapis.com:443"; /// <summary>The default TopicViewService scopes.</summary> /// <remarks> /// The default TopicViewService scopes are: /// <list type="bullet"><item><description>https://www.googleapis.com/auth/adwords</description></item></list> /// </remarks> public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[] { "https://www.googleapis.com/auth/adwords", }); internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes); internal static bool UseJwtAccessWithScopes { get { bool useJwtAccessWithScopes = true; MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes); return useJwtAccessWithScopes; } } static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes); /// <summary> /// Asynchronously creates a <see cref="TopicViewServiceClient"/> using the default credentials, endpoint and /// settings. To specify custom credentials or other settings, use <see cref="TopicViewServiceClientBuilder"/>. /// </summary> /// <param name="cancellationToken"> /// The <see cref="st::CancellationToken"/> to use while creating the client. /// </param> /// <returns>The task representing the created <see cref="TopicViewServiceClient"/>.</returns> public static stt::Task<TopicViewServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) => new TopicViewServiceClientBuilder().BuildAsync(cancellationToken); /// <summary> /// Synchronously creates a <see cref="TopicViewServiceClient"/> using the default credentials, endpoint and /// settings. To specify custom credentials or other settings, use <see cref="TopicViewServiceClientBuilder"/>. /// </summary> /// <returns>The created <see cref="TopicViewServiceClient"/>.</returns> public static TopicViewServiceClient Create() => new TopicViewServiceClientBuilder().Build(); /// <summary> /// Creates a <see cref="TopicViewServiceClient"/> which uses the specified call invoker for remote operations. /// </summary> /// <param name="callInvoker"> /// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null. /// </param> /// <param name="settings">Optional <see cref="TopicViewServiceSettings"/>.</param> /// <returns>The created <see cref="TopicViewServiceClient"/>.</returns> internal static TopicViewServiceClient Create(grpccore::CallInvoker callInvoker, TopicViewServiceSettings settings = null) { gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker)); grpcinter::Interceptor interceptor = settings?.Interceptor; if (interceptor != null) { callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor); } TopicViewService.TopicViewServiceClient grpcClient = new TopicViewService.TopicViewServiceClient(callInvoker); return new TopicViewServiceClientImpl(grpcClient, settings); } /// <summary> /// Shuts down any channels automatically created by <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not /// affected. /// </summary> /// <remarks> /// After calling this method, further calls to <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down /// by another call to this method. /// </remarks> /// <returns>A task representing the asynchronous shutdown operation.</returns> public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync(); /// <summary>The underlying gRPC TopicViewService client</summary> public virtual TopicViewService.TopicViewServiceClient GrpcClient => throw new sys::NotImplementedException(); /// <summary> /// Returns the requested topic view in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual gagvr::TopicView GetTopicView(GetTopicViewRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Returns the requested topic view in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::TopicView> GetTopicViewAsync(GetTopicViewRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Returns the requested topic view in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::TopicView> GetTopicViewAsync(GetTopicViewRequest request, st::CancellationToken cancellationToken) => GetTopicViewAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Returns the requested topic view in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the topic view to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual gagvr::TopicView GetTopicView(string resourceName, gaxgrpc::CallSettings callSettings = null) => GetTopicView(new GetTopicViewRequest { ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested topic view in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the topic view to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::TopicView> GetTopicViewAsync(string resourceName, gaxgrpc::CallSettings callSettings = null) => GetTopicViewAsync(new GetTopicViewRequest { ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested topic view in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the topic view to fetch. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::TopicView> GetTopicViewAsync(string resourceName, st::CancellationToken cancellationToken) => GetTopicViewAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Returns the requested topic view in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the topic view to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual gagvr::TopicView GetTopicView(gagvr::TopicViewName resourceName, gaxgrpc::CallSettings callSettings = null) => GetTopicView(new GetTopicViewRequest { ResourceNameAsTopicViewName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested topic view in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the topic view to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::TopicView> GetTopicViewAsync(gagvr::TopicViewName resourceName, gaxgrpc::CallSettings callSettings = null) => GetTopicViewAsync(new GetTopicViewRequest { ResourceNameAsTopicViewName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested topic view in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the topic view to fetch. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::TopicView> GetTopicViewAsync(gagvr::TopicViewName resourceName, st::CancellationToken cancellationToken) => GetTopicViewAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); } /// <summary>TopicViewService client wrapper implementation, for convenient use.</summary> /// <remarks> /// Service to manage topic views. /// </remarks> public sealed partial class TopicViewServiceClientImpl : TopicViewServiceClient { private readonly gaxgrpc::ApiCall<GetTopicViewRequest, gagvr::TopicView> _callGetTopicView; /// <summary> /// Constructs a client wrapper for the TopicViewService service, with the specified gRPC client and settings. /// </summary> /// <param name="grpcClient">The underlying gRPC client.</param> /// <param name="settings">The base <see cref="TopicViewServiceSettings"/> used within this client.</param> public TopicViewServiceClientImpl(TopicViewService.TopicViewServiceClient grpcClient, TopicViewServiceSettings settings) { GrpcClient = grpcClient; TopicViewServiceSettings effectiveSettings = settings ?? TopicViewServiceSettings.GetDefault(); gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings); _callGetTopicView = clientHelper.BuildApiCall<GetTopicViewRequest, gagvr::TopicView>(grpcClient.GetTopicViewAsync, grpcClient.GetTopicView, effectiveSettings.GetTopicViewSettings).WithGoogleRequestParam("resource_name", request => request.ResourceName); Modify_ApiCall(ref _callGetTopicView); Modify_GetTopicViewApiCall(ref _callGetTopicView); OnConstruction(grpcClient, effectiveSettings, clientHelper); } partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>; partial void Modify_GetTopicViewApiCall(ref gaxgrpc::ApiCall<GetTopicViewRequest, gagvr::TopicView> call); partial void OnConstruction(TopicViewService.TopicViewServiceClient grpcClient, TopicViewServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper); /// <summary>The underlying gRPC TopicViewService client</summary> public override TopicViewService.TopicViewServiceClient GrpcClient { get; } partial void Modify_GetTopicViewRequest(ref GetTopicViewRequest request, ref gaxgrpc::CallSettings settings); /// <summary> /// Returns the requested topic view in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public override gagvr::TopicView GetTopicView(GetTopicViewRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_GetTopicViewRequest(ref request, ref callSettings); return _callGetTopicView.Sync(request, callSettings); } /// <summary> /// Returns the requested topic view in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public override stt::Task<gagvr::TopicView> GetTopicViewAsync(GetTopicViewRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_GetTopicViewRequest(ref request, ref callSettings); return _callGetTopicView.Async(request, callSettings); } } }
/* * Copyright 2007 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using NUnit.Framework; namespace ZXing.Common.Test { /// <summary> /// <author>Sean Owen</author> /// </summary> [TestFixture] public sealed class BitArrayTestCase { [Test] public void testGetSet() { BitArray array = new BitArray(33); for (int i = 0; i < 33; i++) { Assert.IsFalse(array[i]); array[i] = true; Assert.IsTrue(array[i]); } } [Test] public void testGetNextSet1() { BitArray array = new BitArray(32); for (int i = 0; i < array.Size; i++) { Assert.AreEqual(32, array.getNextSet(i)); } array = new BitArray(33); for (int i = 0; i < array.Size; i++) { Assert.AreEqual(33, array.getNextSet(i)); } } [Test] public void testGetNextSet2() { BitArray array = new BitArray(33); array[31] = true; for (int i = 0; i < array.Size; i++) { Assert.AreEqual(i <= 31 ? 31 : 33, array.getNextSet(i)); } array = new BitArray(33); array[32] = true; for (int i = 0; i < array.Size; i++) { Assert.AreEqual(32, array.getNextSet(i)); } } [Test] public void testGetNextSet3() { BitArray array = new BitArray(63); array[31] = true; array[32] = true; for (int i = 0; i < array.Size; i++) { int expected; if (i <= 31) { expected = 31; } else if (i == 32) { expected = 32; } else { expected = 63; } Assert.AreEqual(expected, array.getNextSet(i)); } } [Test] public void testGetNextSet4() { BitArray array = new BitArray(63); array[33] = true; array[40] = true; for (int i = 0; i < array.Size; i++) { int expected; if (i <= 33) { expected = 33; } else if (i <= 40) { expected = 40; } else { expected = 63; } Assert.AreEqual(expected, array.getNextSet(i)); } } [Test] public void testGetNextSet5() { Random r = new Random(0x0EADBEEF); for (int i = 0; i < 10; i++) { BitArray array = new BitArray(1 + r.Next(100)); int numSet = r.Next(20); for (int j = 0; j < numSet; j++) { array[r.Next(array.Size)] = true; } int numQueries = r.Next(20); for (int j = 0; j < numQueries; j++) { int query = r.Next(array.Size); int expected = query; while (expected < array.Size && !array[expected]) { expected++; } int actual = array.getNextSet(query); Assert.AreEqual(expected, actual); } } } [Test] public void testSetBulk() { BitArray array = new BitArray(64); array.setBulk(32, -65536); for (int i = 0; i < 48; i++) { Assert.IsFalse(array[i]); } for (int i = 48; i < 64; i++) { Assert.IsTrue(array[i]); } } [Test] public void testClear() { BitArray array = new BitArray(32); for (int i = 0; i < 32; i++) { array[i] = true; } array.clear(); for (int i = 0; i < 32; i++) { Assert.IsFalse(array[i]); } } [Test] public void testGetArray() { BitArray array = new BitArray(64); array[0] = true; array[63] = true; var ints = array.Array; Assert.AreEqual(1, ints[0]); Assert.AreEqual(Int32.MinValue, ints[1]); } [Test] public void testIsRange() { BitArray array = new BitArray(64); Assert.IsTrue(array.isRange(0, 64, false)); Assert.IsFalse(array.isRange(0, 64, true)); array[32] = true; Assert.IsTrue(array.isRange(32, 33, true)); array[31] = true; Assert.IsTrue(array.isRange(31, 33, true)); array[34] = true; Assert.IsFalse(array.isRange(31, 35, true)); for (int i = 0; i < 31; i++) { array[i] = true; } Assert.IsTrue(array.isRange(0, 33, true)); for (int i = 33; i < 64; i++) { array[i] = true; } Assert.IsTrue(array.isRange(0, 64, true)); Assert.IsFalse(array.isRange(0, 64, false)); } #if !SILVERLIGHT [Test] public void ReverseAlgorithmTest() { var oldBits = new[] { 128, 256, 512, 6453324, 50934953 }; for (var size = 1; size < 160; size++) { var newBitsOriginal = reverseOriginal(oldBits, size); var newBitsNew = reverseNew(oldBits, size); if (!arrays_are_equal(newBitsOriginal, newBitsNew, size / 32 + 1)) { System.Diagnostics.Trace.WriteLine(size); System.Diagnostics.Trace.WriteLine(BitsToString(oldBits, size)); System.Diagnostics.Trace.WriteLine(BitsToString(newBitsOriginal, size)); System.Diagnostics.Trace.WriteLine(BitsToString(newBitsNew, size)); } Assert.IsTrue(arrays_are_equal(newBitsOriginal, newBitsNew, size / 32 + 1)); } } [Test] public void ReverseSpeedTest() { var size = 140; var oldBits = new[] {128, 256, 512, 6453324, 50934953}; var newBitsOriginal = reverseOriginal(oldBits, size); var newBitsNew = reverseNew(oldBits, size); System.Diagnostics.Trace.WriteLine(BitsToString(oldBits, size)); System.Diagnostics.Trace.WriteLine(BitsToString(newBitsOriginal, size)); System.Diagnostics.Trace.WriteLine(BitsToString(newBitsNew, size)); Assert.IsTrue(arrays_are_equal(newBitsOriginal, newBitsNew, newBitsNew.Length)); var startOld = DateTime.Now; for (int runs = 0; runs < 1000000; runs++) { reverseOriginal(oldBits, 140); } var endOld = DateTime.Now; var startNew = DateTime.Now; for (int runs = 0; runs < 1000000; runs++) { reverseNew(oldBits, 140); } var endNew = DateTime.Now; System.Diagnostics.Trace.WriteLine(endOld - startOld); System.Diagnostics.Trace.WriteLine(endNew - startNew); } /// <summary> Reverses all bits in the array.</summary> private int[] reverseOriginal(int[] oldBits, int oldSize) { int[] newBits = new int[oldBits.Length]; int size = oldSize; for (int i = 0; i < size; i++) { if (bits_index(oldBits, size - i - 1)) { newBits[i >> 5] |= 1 << (i & 0x1F); } } return newBits; } private bool bits_index(int[] bits, int i) { return (bits[i >> 5] & (1 << (i & 0x1F))) != 0; } /// <summary> Reverses all bits in the array.</summary> private int[] reverseNew(int[] oldBits, int oldSize) { // doesn't work if more ints are used as necessary int[] newBits = new int[oldBits.Length]; var oldBitsLen = (int)Math.Ceiling(oldSize / 32f); var len = oldBitsLen - 1; for (var i = 0; i < oldBitsLen; i++) { var x = (long)oldBits[i]; x = ((x >> 1) & 0x55555555u) | ((x & 0x55555555u) << 1); x = ((x >> 2) & 0x33333333u) | ((x & 0x33333333u) << 2); x = ((x >> 4) & 0x0f0f0f0fu) | ((x & 0x0f0f0f0fu) << 4); x = ((x >> 8) & 0x00ff00ffu) | ((x & 0x00ff00ffu) << 8); x = ((x >> 16) & 0xffffu) | ((x & 0xffffu) << 16); newBits[len - i] = (int)x; } if (oldSize != oldBitsLen * 32) { var leftOffset = oldBitsLen * 32 - oldSize; var mask = 1; for (var i = 0; i < 31 - leftOffset; i++ ) mask = (mask << 1) | 1; var currentInt = (newBits[0] >> leftOffset) & mask; for (var i = 1; i < oldBitsLen; i++) { var nextInt = newBits[i]; currentInt |= nextInt << (32 - leftOffset); newBits[i - 1] = currentInt; currentInt = (nextInt >> leftOffset) & mask; } newBits[oldBitsLen - 1] = currentInt; } return newBits; } private bool arrays_are_equal(int[] left, int[] right, int size) { for (var i = 0; i < size; i++) { if (left[i] != right[i]) return false; } return true; } private string BitsToString(int[] bits, int size) { var result = new System.Text.StringBuilder(size); for (int i = 0; i < size; i++) { if ((i & 0x07) == 0) { result.Append(' '); } result.Append(bits_index(bits, i) ? 'X' : '.'); } return result.ToString(); } [Test] public void testBitArrayNet() { var netArray = new System.Collections.BitArray(140, false); var zxingArray = new BitArray(140); var netVal = netArray[100]; var zxingVal = zxingArray[100]; Assert.AreEqual(netVal, zxingVal); var startOld = DateTime.Now; for (int runs = 0; runs < 1000000; runs++) { netVal = netArray[100]; netArray[100] = netVal; } var endOld = DateTime.Now; var startNew = DateTime.Now; for (int runs = 0; runs < 1000000; runs++) { zxingVal = zxingArray[100]; zxingArray[100] = zxingVal; } var endNew = DateTime.Now; System.Diagnostics.Trace.WriteLine(endOld - startOld); System.Diagnostics.Trace.WriteLine(endNew - startNew); } #endif } }
#region Header // // Copyright 2003-2019 by Autodesk, Inc. // // Permission to use, copy, modify, and distribute this software in // object code form for any purpose and without fee is hereby granted, // provided that the above copyright notice appears in all copies and // that both that copyright notice and the limited warranty and // restricted rights notice below appear in all supporting // documentation. // // AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS. // AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF // MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC. // DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE // UNINTERRUPTED OR ERROR FREE. // // Use, duplication, or disclosure by the U.S. Government is subject to // restrictions set forth in FAR 52.227-19 (Commercial Computer // Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii) // (Rights in Technical Data and Computer Software), as applicable. // #endregion // Header using System; using System.Diagnostics; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Xml; namespace RevitLookup.Xml.Forms { /// <summary> /// UI Test for navigating the XML Dom /// </summary> public class Dom : System.Windows.Forms.Form { private System.Windows.Forms.TreeView m_tvDom; private System.Windows.Forms.ListView m_lvData; private System.Windows.Forms.RadioButton m_rbNodeNameOnly; private System.Windows.Forms.RadioButton m_rbNodeAndText; private System.Windows.Forms.GroupBox m_grpLabelDisplay; private System.Windows.Forms.GroupBox m_grpNodeDisplay; private System.Windows.Forms.CheckBox m_cbHideCommentNodes; private System.Windows.Forms.CheckBox m_cbHideTextNodes; private System.Windows.Forms.Button m_bnParent; private System.Windows.Forms.Button m_bnOwnerDoc; private System.Windows.Forms.Button m_bnPrevSibling; private System.Windows.Forms.Button m_bnNextSibling; private System.Windows.Forms.Button m_bnFirstChild; private System.Windows.Forms.Button m_bnLastChild; private System.Windows.Forms.Button m_bnDocElem; private System.Windows.Forms.TextBox m_ebXpathPattern; private System.Windows.Forms.Button m_bnSelectSingleNode; private System.Windows.Forms.Button m_bnXpathClear; private System.Windows.Forms.Button m_bnSelectNodes; private System.Windows.Forms.Button m_bnOk; private System.Windows.Forms.ColumnHeader m_lvColLabel; private System.Windows.Forms.ColumnHeader m_lvColValue; private System.Windows.Forms.ImageList m_imgListTree; private System.Windows.Forms.Label m_txtXpathPattern; private System.Windows.Forms.GroupBox m_grpXpath; private System.Xml.XmlDocument m_xmlDoc = null; private Snoop.Collectors.CollectorXmlNode m_snoopCollector = new Snoop.Collectors.CollectorXmlNode(); private System.ComponentModel.IContainer components; public Dom(System.Xml.XmlDocument xmlDoc) { m_xmlDoc = xmlDoc; InitializeComponent(); LoadTree(); } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose(bool disposing) { if (disposing) { if (components != null) { components.Dispose(); } } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(Dom)); this.m_tvDom = new System.Windows.Forms.TreeView(); this.m_imgListTree = new System.Windows.Forms.ImageList(this.components); this.m_lvData = new System.Windows.Forms.ListView(); this.m_lvColLabel = new System.Windows.Forms.ColumnHeader(); this.m_lvColValue = new System.Windows.Forms.ColumnHeader(); this.m_rbNodeNameOnly = new System.Windows.Forms.RadioButton(); this.m_rbNodeAndText = new System.Windows.Forms.RadioButton(); this.m_grpLabelDisplay = new System.Windows.Forms.GroupBox(); this.m_grpNodeDisplay = new System.Windows.Forms.GroupBox(); this.m_cbHideTextNodes = new System.Windows.Forms.CheckBox(); this.m_cbHideCommentNodes = new System.Windows.Forms.CheckBox(); this.m_bnParent = new System.Windows.Forms.Button(); this.m_bnOwnerDoc = new System.Windows.Forms.Button(); this.m_bnPrevSibling = new System.Windows.Forms.Button(); this.m_bnNextSibling = new System.Windows.Forms.Button(); this.m_bnFirstChild = new System.Windows.Forms.Button(); this.m_bnLastChild = new System.Windows.Forms.Button(); this.m_txtXpathPattern = new System.Windows.Forms.Label(); this.m_ebXpathPattern = new System.Windows.Forms.TextBox(); this.m_bnSelectSingleNode = new System.Windows.Forms.Button(); this.m_bnSelectNodes = new System.Windows.Forms.Button(); this.m_bnOk = new System.Windows.Forms.Button(); this.m_bnXpathClear = new System.Windows.Forms.Button(); this.m_grpXpath = new System.Windows.Forms.GroupBox(); this.m_bnDocElem = new System.Windows.Forms.Button(); this.m_grpNodeDisplay.SuspendLayout(); this.m_grpXpath.SuspendLayout(); this.SuspendLayout(); // // m_tvDom // this.m_tvDom.Anchor = (((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right); this.m_tvDom.HideSelection = false; this.m_tvDom.ImageList = this.m_imgListTree; this.m_tvDom.Location = new System.Drawing.Point(16, 16); this.m_tvDom.Name = "m_tvDom"; this.m_tvDom.Size = new System.Drawing.Size(336, 416); this.m_tvDom.TabIndex = 0; this.m_tvDom.AfterSelect += new System.Windows.Forms.TreeViewEventHandler(this.TreeNodeSelected); // // m_imgListTree // this.m_imgListTree.ColorDepth = System.Windows.Forms.ColorDepth.Depth8Bit; this.m_imgListTree.ImageSize = new System.Drawing.Size(16, 16); this.m_imgListTree.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("m_imgListTree.ImageStream"))); this.m_imgListTree.TransparentColor = System.Drawing.Color.Transparent; // // m_lvData // this.m_lvData.Anchor = ((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Right); this.m_lvData.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] { this.m_lvColLabel, this.m_lvColValue}); this.m_lvData.FullRowSelect = true; this.m_lvData.GridLines = true; this.m_lvData.HeaderStyle = System.Windows.Forms.ColumnHeaderStyle.Nonclickable; this.m_lvData.Location = new System.Drawing.Point(368, 16); this.m_lvData.MultiSelect = false; this.m_lvData.Name = "m_lvData"; this.m_lvData.Size = new System.Drawing.Size(416, 328); this.m_lvData.TabIndex = 1; this.m_lvData.View = System.Windows.Forms.View.Details; this.m_lvData.Click += new System.EventHandler(this.DataItemSelected); // // m_lvColLabel // this.m_lvColLabel.Text = "Field"; this.m_lvColLabel.Width = 200; // // m_lvColValue // this.m_lvColValue.Text = "Value"; this.m_lvColValue.Width = 250; // // m_rbNodeNameOnly // this.m_rbNodeNameOnly.Anchor = (System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right); this.m_rbNodeNameOnly.Checked = true; this.m_rbNodeNameOnly.FlatStyle = System.Windows.Forms.FlatStyle.System; this.m_rbNodeNameOnly.Location = new System.Drawing.Point(384, 376); this.m_rbNodeNameOnly.Name = "m_rbNodeNameOnly"; this.m_rbNodeNameOnly.Size = new System.Drawing.Size(152, 24); this.m_rbNodeNameOnly.TabIndex = 2; this.m_rbNodeNameOnly.TabStop = true; this.m_rbNodeNameOnly.Text = "Node Name Only"; this.m_rbNodeNameOnly.CheckedChanged += new System.EventHandler(this.OnRbChanged_LabelDisplay); // // m_rbNodeAndText // this.m_rbNodeAndText.Anchor = (System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right); this.m_rbNodeAndText.FlatStyle = System.Windows.Forms.FlatStyle.System; this.m_rbNodeAndText.Location = new System.Drawing.Point(384, 400); this.m_rbNodeAndText.Name = "m_rbNodeAndText"; this.m_rbNodeAndText.Size = new System.Drawing.Size(168, 24); this.m_rbNodeAndText.TabIndex = 4; this.m_rbNodeAndText.Text = "Node Name and Value"; this.m_rbNodeAndText.CheckedChanged += new System.EventHandler(this.OnRbChanged_LabelDisplay); // // m_grpLabelDisplay // this.m_grpLabelDisplay.Anchor = (System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right); this.m_grpLabelDisplay.FlatStyle = System.Windows.Forms.FlatStyle.System; this.m_grpLabelDisplay.Location = new System.Drawing.Point(368, 360); this.m_grpLabelDisplay.Name = "m_grpLabelDisplay"; this.m_grpLabelDisplay.Size = new System.Drawing.Size(200, 72); this.m_grpLabelDisplay.TabIndex = 5; this.m_grpLabelDisplay.TabStop = false; this.m_grpLabelDisplay.Text = "Label Display"; // // m_grpNodeDisplay // this.m_grpNodeDisplay.Anchor = (System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right); this.m_grpNodeDisplay.Controls.AddRange(new System.Windows.Forms.Control[] { this.m_cbHideTextNodes, this.m_cbHideCommentNodes}); this.m_grpNodeDisplay.FlatStyle = System.Windows.Forms.FlatStyle.System; this.m_grpNodeDisplay.Location = new System.Drawing.Point(584, 360); this.m_grpNodeDisplay.Name = "m_grpNodeDisplay"; this.m_grpNodeDisplay.Size = new System.Drawing.Size(200, 72); this.m_grpNodeDisplay.TabIndex = 6; this.m_grpNodeDisplay.TabStop = false; this.m_grpNodeDisplay.Text = "Node Display"; // // m_cbHideTextNodes // this.m_cbHideTextNodes.Anchor = (System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right); this.m_cbHideTextNodes.FlatStyle = System.Windows.Forms.FlatStyle.System; this.m_cbHideTextNodes.Location = new System.Drawing.Point(16, 40); this.m_cbHideTextNodes.Name = "m_cbHideTextNodes"; this.m_cbHideTextNodes.Size = new System.Drawing.Size(176, 24); this.m_cbHideTextNodes.TabIndex = 1; this.m_cbHideTextNodes.Text = "Hide Text Nodes"; this.m_cbHideTextNodes.CheckedChanged += new System.EventHandler(this.OnCbChanged_NodeDisplay); // // m_cbHideCommentNodes // this.m_cbHideCommentNodes.Anchor = (System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right); this.m_cbHideCommentNodes.FlatStyle = System.Windows.Forms.FlatStyle.System; this.m_cbHideCommentNodes.Location = new System.Drawing.Point(16, 16); this.m_cbHideCommentNodes.Name = "m_cbHideCommentNodes"; this.m_cbHideCommentNodes.Size = new System.Drawing.Size(176, 24); this.m_cbHideCommentNodes.TabIndex = 0; this.m_cbHideCommentNodes.Text = "Hide Comment Nodes"; this.m_cbHideCommentNodes.CheckedChanged += new System.EventHandler(this.OnCbChanged_NodeDisplay); // // m_bnParent // this.m_bnParent.Anchor = (System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left); this.m_bnParent.FlatStyle = System.Windows.Forms.FlatStyle.System; this.m_bnParent.Location = new System.Drawing.Point(16, 448); this.m_bnParent.Name = "m_bnParent"; this.m_bnParent.TabIndex = 7; this.m_bnParent.Text = "Parent"; this.m_bnParent.Click += new System.EventHandler(this.OnBnParent); // // m_bnOwnerDoc // this.m_bnOwnerDoc.Anchor = (System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left); this.m_bnOwnerDoc.FlatStyle = System.Windows.Forms.FlatStyle.System; this.m_bnOwnerDoc.Location = new System.Drawing.Point(104, 448); this.m_bnOwnerDoc.Name = "m_bnOwnerDoc"; this.m_bnOwnerDoc.TabIndex = 8; this.m_bnOwnerDoc.Text = "Owner Doc"; this.m_bnOwnerDoc.Click += new System.EventHandler(this.OnBnOwnerDoc); // // m_bnPrevSibling // this.m_bnPrevSibling.Anchor = (System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left); this.m_bnPrevSibling.FlatStyle = System.Windows.Forms.FlatStyle.System; this.m_bnPrevSibling.Location = new System.Drawing.Point(192, 448); this.m_bnPrevSibling.Name = "m_bnPrevSibling"; this.m_bnPrevSibling.TabIndex = 9; this.m_bnPrevSibling.Text = "Prev Sibling"; this.m_bnPrevSibling.Click += new System.EventHandler(this.OnBnPrevSibling); // // m_bnNextSibling // this.m_bnNextSibling.Anchor = (System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left); this.m_bnNextSibling.FlatStyle = System.Windows.Forms.FlatStyle.System; this.m_bnNextSibling.Location = new System.Drawing.Point(280, 448); this.m_bnNextSibling.Name = "m_bnNextSibling"; this.m_bnNextSibling.TabIndex = 10; this.m_bnNextSibling.Text = "Next Sibling"; this.m_bnNextSibling.Click += new System.EventHandler(this.OnBnNextSibling); // // m_bnFirstChild // this.m_bnFirstChild.Anchor = (System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left); this.m_bnFirstChild.FlatStyle = System.Windows.Forms.FlatStyle.System; this.m_bnFirstChild.Location = new System.Drawing.Point(368, 448); this.m_bnFirstChild.Name = "m_bnFirstChild"; this.m_bnFirstChild.TabIndex = 11; this.m_bnFirstChild.Text = "First Child"; this.m_bnFirstChild.Click += new System.EventHandler(this.OnBnFirstChild); // // m_bnLastChild // this.m_bnLastChild.Anchor = (System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left); this.m_bnLastChild.FlatStyle = System.Windows.Forms.FlatStyle.System; this.m_bnLastChild.Location = new System.Drawing.Point(456, 448); this.m_bnLastChild.Name = "m_bnLastChild"; this.m_bnLastChild.TabIndex = 12; this.m_bnLastChild.Text = "Last Child"; this.m_bnLastChild.Click += new System.EventHandler(this.OnBnLastChild); // // m_txtXpathPattern // this.m_txtXpathPattern.Anchor = (System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left); this.m_txtXpathPattern.FlatStyle = System.Windows.Forms.FlatStyle.System; this.m_txtXpathPattern.Location = new System.Drawing.Point(32, 512); this.m_txtXpathPattern.Name = "m_txtXpathPattern"; this.m_txtXpathPattern.Size = new System.Drawing.Size(64, 23); this.m_txtXpathPattern.TabIndex = 14; this.m_txtXpathPattern.Text = "Expression:"; // // m_ebXpathPattern // this.m_ebXpathPattern.Anchor = (System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left); this.m_ebXpathPattern.Location = new System.Drawing.Point(88, 24); this.m_ebXpathPattern.Name = "m_ebXpathPattern"; this.m_ebXpathPattern.Size = new System.Drawing.Size(424, 20); this.m_ebXpathPattern.TabIndex = 15; this.m_ebXpathPattern.Text = ""; // // m_bnSelectSingleNode // this.m_bnSelectSingleNode.Anchor = (System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left); this.m_bnSelectSingleNode.FlatStyle = System.Windows.Forms.FlatStyle.System; this.m_bnSelectSingleNode.Location = new System.Drawing.Point(128, 56); this.m_bnSelectSingleNode.Name = "m_bnSelectSingleNode"; this.m_bnSelectSingleNode.Size = new System.Drawing.Size(120, 23); this.m_bnSelectSingleNode.TabIndex = 16; this.m_bnSelectSingleNode.Text = "Select Single Node"; this.m_bnSelectSingleNode.Click += new System.EventHandler(this.OnBnSelectSingleNode); // // m_bnSelectNodes // this.m_bnSelectNodes.Anchor = (System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left); this.m_bnSelectNodes.FlatStyle = System.Windows.Forms.FlatStyle.System; this.m_bnSelectNodes.Location = new System.Drawing.Point(256, 56); this.m_bnSelectNodes.Name = "m_bnSelectNodes"; this.m_bnSelectNodes.Size = new System.Drawing.Size(120, 23); this.m_bnSelectNodes.TabIndex = 17; this.m_bnSelectNodes.Text = "Select Nodes"; this.m_bnSelectNodes.Click += new System.EventHandler(this.OnBnSelectNodes); // // m_bnOk // this.m_bnOk.Anchor = (System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right); this.m_bnOk.DialogResult = System.Windows.Forms.DialogResult.OK; this.m_bnOk.FlatStyle = System.Windows.Forms.FlatStyle.System; this.m_bnOk.Location = new System.Drawing.Point(704, 544); this.m_bnOk.Name = "m_bnOk"; this.m_bnOk.TabIndex = 18; this.m_bnOk.Text = "OK"; // // m_bnXpathClear // this.m_bnXpathClear.Anchor = (System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left); this.m_bnXpathClear.FlatStyle = System.Windows.Forms.FlatStyle.System; this.m_bnXpathClear.Location = new System.Drawing.Point(384, 56); this.m_bnXpathClear.Name = "m_bnXpathClear"; this.m_bnXpathClear.Size = new System.Drawing.Size(120, 23); this.m_bnXpathClear.TabIndex = 19; this.m_bnXpathClear.Text = "Clear"; this.m_bnXpathClear.Click += new System.EventHandler(this.OnBnClear); // // m_grpXpath // this.m_grpXpath.Anchor = (System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left); this.m_grpXpath.Controls.AddRange(new System.Windows.Forms.Control[] { this.m_ebXpathPattern, this.m_bnXpathClear, this.m_bnSelectNodes, this.m_bnSelectSingleNode}); this.m_grpXpath.FlatStyle = System.Windows.Forms.FlatStyle.System; this.m_grpXpath.Location = new System.Drawing.Point(16, 488); this.m_grpXpath.Name = "m_grpXpath"; this.m_grpXpath.Size = new System.Drawing.Size(520, 88); this.m_grpXpath.TabIndex = 20; this.m_grpXpath.TabStop = false; this.m_grpXpath.Text = "XPath Expressions"; // // m_bnDocElem // this.m_bnDocElem.Anchor = (System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left); this.m_bnDocElem.FlatStyle = System.Windows.Forms.FlatStyle.System; this.m_bnDocElem.Location = new System.Drawing.Point(544, 448); this.m_bnDocElem.Name = "m_bnDocElem"; this.m_bnDocElem.Size = new System.Drawing.Size(80, 23); this.m_bnDocElem.TabIndex = 21; this.m_bnDocElem.Text = "Doc Element"; this.m_bnDocElem.Click += new System.EventHandler(this.OnBnDocElement); // // Dom // this.AcceptButton = this.m_bnOk; this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.CancelButton = this.m_bnOk; this.ClientSize = new System.Drawing.Size(800, 591); this.Controls.AddRange(new System.Windows.Forms.Control[] { this.m_bnDocElem, this.m_bnOk, this.m_txtXpathPattern, this.m_bnLastChild, this.m_bnFirstChild, this.m_bnNextSibling, this.m_bnPrevSibling, this.m_bnOwnerDoc, this.m_bnParent, this.m_grpNodeDisplay, this.m_rbNodeAndText, this.m_rbNodeNameOnly, this.m_lvData, this.m_tvDom, this.m_grpLabelDisplay, this.m_grpXpath}); this.MaximizeBox = false; this.MinimizeBox = false; this.MinimumSize = new System.Drawing.Size(650, 400); this.Name = "Dom"; this.Text = "XML DOM Tree"; this.m_grpNodeDisplay.ResumeLayout(false); this.m_grpXpath.ResumeLayout(false); this.ResumeLayout(false); } #endregion /// <summary> /// This will populate the UI TreeView with all the nodes from the DOM tree /// </summary> private void LoadTree() { m_tvDom.BeginUpdate(); // suppress redraw events m_tvDom.Nodes.Clear(); MakeTree(m_xmlDoc, null); m_tvDom.ExpandAll(); if (m_tvDom.Nodes.Count > 0) m_tvDom.SelectedNode = m_tvDom.Nodes[0]; // make first one selected m_tvDom.EndUpdate(); // flushes redraw events } /// <summary> /// Recursive function to walk the tree and populate all the nodes /// </summary> /// <param name="xmlNode">The "root" of this portion of the tree</param> /// <param name="parentNode">The parent node to attach to or null for the root</param> private void MakeTree(System.Xml.XmlNode xmlNode, TreeNode parentNode) { XmlNodeType nType = xmlNode.NodeType; // bail early if user doesn't want this type of node displayed if (((nType == XmlNodeType.Comment) && (m_cbHideCommentNodes.Checked)) || ((nType == XmlNodeType.Text) && (m_cbHideTextNodes.Checked))) return; // get image index and label to use in the TreeNode int imageIndex = GetImageIndex(nType); string labelStr = FormatLabel(xmlNode); TreeNode treeNode = new TreeNode(labelStr); treeNode.Tag = xmlNode; treeNode.ImageIndex = imageIndex; treeNode.SelectedImageIndex = imageIndex; if (parentNode == null) m_tvDom.Nodes.Add(treeNode); // This is the root node else parentNode.Nodes.Add(treeNode); // get attributes of this node XmlAttributeCollection atts = xmlNode.Attributes; if (atts != null) { foreach (XmlAttribute tmpAtt in atts) { MakeTree(tmpAtt, treeNode); } } // now recursively go to the children of this node if (xmlNode.HasChildNodes) { foreach (XmlNode childNode in xmlNode.ChildNodes) { MakeTree(childNode, treeNode); } } } /// <summary> /// Match a particular Image with the XML Node type. A different Icon will /// be used in the UI tree for each type of node. /// </summary> /// <param name="nType">The node type</param> /// <returns>index into the ImageList assigned to the TreeView</returns> private int GetImageIndex(XmlNodeType nType) { int imageIndex = 0; // associate the correct image with this type of node if (nType == XmlNodeType.Document) imageIndex = 0; else if (nType == XmlNodeType.Attribute) imageIndex = 1; else if (nType == XmlNodeType.CDATA) imageIndex = 2; else if (nType == XmlNodeType.Comment) imageIndex = 3; else if (nType == XmlNodeType.DocumentType) imageIndex = 4; else if (nType == XmlNodeType.Element) imageIndex = 5; else if (nType == XmlNodeType.Entity) imageIndex = 6; else if (nType == XmlNodeType.DocumentFragment) imageIndex = 7; else if (nType == XmlNodeType.ProcessingInstruction) imageIndex = 8; else if (nType == XmlNodeType.EntityReference) imageIndex = 9; else if (nType == XmlNodeType.Text) imageIndex = 10; else if (nType == XmlNodeType.XmlDeclaration) imageIndex = 11; // TBD: Not sure what when the rest of these come up yet? // I will reserve a spot in case they become significant else if (nType == XmlNodeType.EndElement) imageIndex = 12; else if (nType == XmlNodeType.EndEntity) imageIndex = 12; else if (nType == XmlNodeType.None) imageIndex = 12; else if (nType == XmlNodeType.Notation) imageIndex = 12; else if (nType == XmlNodeType.SignificantWhitespace) imageIndex = 12; else if (nType == XmlNodeType.Whitespace) imageIndex = 12; else { Debug.Assert(false); imageIndex = 12; } return imageIndex; } /// <summary> /// Allow the user prefernces to affect how we format the label for the tree node. /// </summary> /// <param name="node">The node to format</param> /// <returns>formatted string according to user preferences</returns> private string FormatLabel(XmlNode node) { string labelStr; if (m_rbNodeNameOnly.Checked) labelStr = node.Name; else if (m_rbNodeAndText.Checked) { if ((node.NodeType == XmlNodeType.Element) || (node.NodeType == XmlNodeType.Attribute)) labelStr = string.Format("{0} ({1})", node.Name, GetTextLabelValue(node)); else labelStr = string.Format("{0} ({1})", node.Name, node.Value); } else { Debug.Assert(false, "Unknown radio button!"); // Someone must have added a button we don't know about! labelStr = string.Empty; } return labelStr; } /// <summary> /// Retrieve the text value for a given node /// </summary> /// <param name="node">Node to look at</param> /// <returns>Text value of the node (the XmlText Child Node of the one passed in)</returns> private string GetTextLabelValue(XmlNode node) { XmlNode txtNode = node.FirstChild; if ((txtNode != null) && (txtNode.NodeType == XmlNodeType.Text)) { return txtNode.Value; } else { return string.Empty; } } /// <summary> /// Display the data values associated with a selected node in the tree. /// </summary> /// <param name="node">Currently selected node</param> private void Display(XmlNode node) { SetButtonModes(node); m_snoopCollector.Collect(node); Snoop.Utils.Display(m_lvData, m_snoopCollector); } /// <summary> /// Do a preview check to see which navigation buttons are going to work. Disable /// the ones that will not. /// </summary> /// <param name="node">Currently selected node</param> private void SetButtonModes(XmlNode node) { XmlNode tmpNode; tmpNode = node.ParentNode; m_bnParent.Enabled = (tmpNode != null); tmpNode = node.OwnerDocument; m_bnOwnerDoc.Enabled = (tmpNode != null); tmpNode = node.PreviousSibling; m_bnPrevSibling.Enabled = (tmpNode != null); tmpNode = node.NextSibling; m_bnNextSibling.Enabled = (tmpNode != null); tmpNode = node.FirstChild; m_bnFirstChild.Enabled = (tmpNode != null); tmpNode = node.LastChild; m_bnLastChild.Enabled = (tmpNode != null); } /// <summary> /// The user selected a UI TreeNode. Update the Display based on the new selection /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void TreeNodeSelected(object sender, System.Windows.Forms.TreeViewEventArgs e) { XmlNode curNode = (XmlNode)e.Node.Tag; Display(curNode); } // UI Callbacks when buttons in the Form are pressed private void OnBnParent(object sender, System.EventArgs e) { XmlNode curNode = (XmlNode)m_tvDom.SelectedNode.Tag; MoveToNewNodeInTree(curNode.ParentNode); } private void OnBnOwnerDoc(object sender, System.EventArgs e) { XmlNode curNode = (XmlNode)m_tvDom.SelectedNode.Tag; MoveToNewNodeInTree(curNode.OwnerDocument); } private void OnBnPrevSibling(object sender, System.EventArgs e) { XmlNode curNode = (XmlNode)m_tvDom.SelectedNode.Tag; MoveToNewNodeInTree(curNode.PreviousSibling); } private void OnBnNextSibling(object sender, System.EventArgs e) { XmlNode curNode = (XmlNode)m_tvDom.SelectedNode.Tag; MoveToNewNodeInTree(curNode.NextSibling); } private void OnBnFirstChild(object sender, System.EventArgs e) { XmlNode curNode = (XmlNode)m_tvDom.SelectedNode.Tag; MoveToNewNodeInTree(curNode.FirstChild); } private void OnBnLastChild(object sender, System.EventArgs e) { XmlNode curNode = (XmlNode)m_tvDom.SelectedNode.Tag; MoveToNewNodeInTree(curNode.LastChild); } private void OnBnDocElement(object sender, System.EventArgs e) { XmlElement elem = m_xmlDoc.DocumentElement; MoveToNewNodeInTree(elem); } /// <summary> /// Based on a user-specified XPath expression, try to find a matching /// node. If found, change the background of the label to a different /// color and make that item the current selection in the UI Tree. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void OnBnSelectSingleNode(object sender, System.EventArgs e) { XmlNode curNode = (XmlNode)m_tvDom.SelectedNode.Tag; try { XmlNode newNode = curNode.SelectSingleNode(m_ebXpathPattern.Text); if (newNode != null) { m_tvDom.BeginUpdate(); SetSelectedNode(m_tvDom.Nodes, newNode); MoveToNewNodeInTree(newNode); m_tvDom.EndUpdate(); } else { MessageBox.Show("No node matches the pattern.", "XPath Search", MessageBoxButtons.OK, MessageBoxIcon.Information); } } catch (System.Xml.XPath.XPathException ex) { MessageBox.Show(ex.Message, "XPath Exception", MessageBoxButtons.OK, MessageBoxIcon.Stop); } } /// <summary> /// Based on a user-specified XPath expression, try to find any matching /// nodes. If found, change the background of the labels to a different /// color and make the first item the current selection in the UI Tree. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void OnBnSelectNodes(object sender, System.EventArgs e) { XmlNode curNode = (XmlNode)m_tvDom.SelectedNode.Tag; try { XmlNodeList selNodes = curNode.SelectNodes(m_ebXpathPattern.Text); if ((selNodes != null) && (selNodes.Count > 0)) { m_tvDom.BeginUpdate(); SetSelectedNodes(m_tvDom.Nodes, selNodes); MoveToNewNodeInTree(selNodes[0]); m_tvDom.EndUpdate(); } else { MessageBox.Show("No nodes match the pattern.", "XPath Search", MessageBoxButtons.OK, MessageBoxIcon.Information); } } catch (System.Xml.XPath.XPathException ex) { MessageBox.Show(ex.Message, "XPath Exception", MessageBoxButtons.OK, MessageBoxIcon.Stop); } } private void OnBnClear(object sender, System.EventArgs e) { m_ebXpathPattern.Text = string.Empty; ClearSelectedNodes(m_tvDom.Nodes); } private void OnRbChanged_LabelDisplay(object sender, System.EventArgs e) { LoadTree(); // reload the tree with our new display preference set } private void OnCbChanged_NodeDisplay(object sender, System.EventArgs e) { LoadTree(); // reload the tree with our new display preference set } private void DataItemSelected(object sender, System.EventArgs e) { Snoop.Utils.DataItemSelected(m_lvData); } /// <summary> /// One of the navigation buttons ("Parent", "First Child", etc) was picked. Based on the /// XmlNode that those functions returned, find the corresponding UI TreeNode and make it /// the currently selected one. /// </summary> /// <param name="newXmlNode">The XmlNode that should now be selected</param> private void MoveToNewNodeInTree(XmlNode newXmlNode) { Debug.Assert(newXmlNode != null); // we should have checked out OK in SetButtonModes() TreeNode newTreeNode = FindTreeNodeFromXmlNodeTag(m_tvDom.Nodes, newXmlNode); if (newTreeNode != null) { m_tvDom.SelectedNode = newTreeNode; } else { MessageBox.Show("The node exist in the XML DOM, but not in the UI tree.\nPerhaps you have Text or Comment nodes turned off?", "MgdDbg", MessageBoxButtons.OK, MessageBoxIcon.Information); } } /// <summary> /// Sometimes we have the Xml DOM node and we need to find where that is in our /// UI tree. This function will brute-force search the UI tree looking for a /// TreeNode.Tag that matches the XmlNode we are searching for. Note: this function /// is recursive. /// </summary> /// <param name="treeNodes">The current collection of nodes to look through</param> /// <param name="xmlNode">The XmlNode we are searching for.</param> /// <returns>The found TreeNode or null, if not found</returns> private TreeNode FindTreeNodeFromXmlNodeTag(TreeNodeCollection treeNodes, XmlNode xmlNode) { XmlNode tmpXmlNode = null; // walk the list of tree nodes looking for a match in the attached // Tag object. foreach (TreeNode tNode in treeNodes) { tmpXmlNode = (XmlNode)tNode.Tag; if (tmpXmlNode == xmlNode) return tNode; // found it // Didn't find it, but this node may have children, so recursively // look for it here. if (tNode.Nodes.Count > 0) { // if we find it on the recursive call, pop back out, // otherwise continue searching at this level TreeNode recursiveNode = null; recursiveNode = FindTreeNodeFromXmlNodeTag(tNode.Nodes, xmlNode); if (recursiveNode != null) return recursiveNode; } } return null; } /// <summary> /// When nodes are selected by XPath expressions, we highlighted them by changing /// the background color. Go through and reset them to normal. This function handles /// one level of the tree at a time and then goes recursive. /// </summary> /// <param name="treeNodes">The "root" of this protion of the tree</param> private void ClearSelectedNodes(TreeNodeCollection treeNodes) { foreach (TreeNode tNode in treeNodes) { tNode.BackColor = System.Drawing.Color.Empty; if (tNode.Nodes.Count > 0) { ClearSelectedNodes(tNode.Nodes); } } } /// <summary> /// Change the background color of the matching node /// </summary> /// <param name="treeNodes">The "root" of this section of the tree</param> /// <param name="selNode">The XmlNode we are trying to find</param> private void SetSelectedNode(TreeNodeCollection treeNodes, XmlNode selNode) { foreach (TreeNode tNode in treeNodes) { if (selNode == (XmlNode)tNode.Tag) tNode.BackColor = System.Drawing.Color.LightSkyBlue; else tNode.BackColor = System.Drawing.Color.Empty; if (tNode.Nodes.Count > 0) { SetSelectedNode(tNode.Nodes, selNode); } } } /// <summary> /// Same as SetSelectedNode(), but with a set of matches. /// NOTE: You cannot manually add to an XmlNodeList, so I couldn't /// have the above function call this one. /// </summary> /// <param name="treeNodes"></param> /// <param name="selNodes"></param> private void SetSelectedNodes(TreeNodeCollection treeNodes, XmlNodeList selNodes) { foreach (TreeNode tNode in treeNodes) { if (NodeListContains(selNodes, (XmlNode)tNode.Tag)) tNode.BackColor = System.Drawing.Color.LightSkyBlue; else tNode.BackColor = System.Drawing.Color.Empty; if (tNode.Nodes.Count > 0) { SetSelectedNodes(tNode.Nodes, selNodes); } } } /// <summary> /// Is a given node part of the nodeSet? /// </summary> /// <param name="nodeSet">Set of nodes to search</param> /// <param name="findNode">Node we are searching for</param> /// <returns>true if found, false if not</returns> private bool NodeListContains(XmlNodeList nodeSet, XmlNode findNode) { foreach (XmlNode tmpNode in nodeSet) { if (tmpNode == findNode) return true; } return false; } } }
using System; using System.CodeDom.Compiler; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Globalization; using System.Linq; using System.Text; namespace EduHub.Data.Entities { /// <summary> /// Holding Table for Reformatting phone numbers Data Set /// </summary> [GeneratedCode("EduHub Data", "0.9")] public sealed partial class KPHDataSet : EduHubDataSet<KPH> { /// <inheritdoc /> public override string Name { get { return "KPH"; } } /// <inheritdoc /> public override bool SupportsEntityLastModified { get { return true; } } internal KPHDataSet(EduHubContext Context) : base(Context) { Index_KPHKEY = new Lazy<Dictionary<int, KPH>>(() => this.ToDictionary(i => i.KPHKEY)); } /// <summary> /// Matches CSV file headers to actions, used to deserialize <see cref="KPH" /> /// </summary> /// <param name="Headers">The CSV column headers</param> /// <returns>An array of actions which deserialize <see cref="KPH" /> fields for each CSV column header</returns> internal override Action<KPH, string>[] BuildMapper(IReadOnlyList<string> Headers) { var mapper = new Action<KPH, string>[Headers.Count]; for (var i = 0; i < Headers.Count; i++) { switch (Headers[i]) { case "KPHKEY": mapper[i] = (e, v) => e.KPHKEY = int.Parse(v); break; case "TABLE_NAME": mapper[i] = (e, v) => e.TABLE_NAME = v; break; case "FIELD_NAME": mapper[i] = (e, v) => e.FIELD_NAME = v; break; case "FIELD_TYPE": mapper[i] = (e, v) => e.FIELD_TYPE = v; break; case "KEY_FIELD": mapper[i] = (e, v) => e.KEY_FIELD = v; break; case "KEY_VALUE": mapper[i] = (e, v) => e.KEY_VALUE = v; break; case "OLD_VALUE": mapper[i] = (e, v) => e.OLD_VALUE = v; break; case "NEW_VALUE": mapper[i] = (e, v) => e.NEW_VALUE = v; break; case "LW_DATE": mapper[i] = (e, v) => e.LW_DATE = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture); break; case "LW_TIME": mapper[i] = (e, v) => e.LW_TIME = v == null ? (short?)null : short.Parse(v); break; case "LW_USER": mapper[i] = (e, v) => e.LW_USER = v; break; default: mapper[i] = MapperNoOp; break; } } return mapper; } /// <summary> /// Merges <see cref="KPH" /> delta entities /// </summary> /// <param name="Entities">Iterator for base <see cref="KPH" /> entities</param> /// <param name="DeltaEntities">List of delta <see cref="KPH" /> entities</param> /// <returns>A merged <see cref="IEnumerable{KPH}"/> of entities</returns> internal override IEnumerable<KPH> ApplyDeltaEntities(IEnumerable<KPH> Entities, List<KPH> DeltaEntities) { HashSet<int> Index_KPHKEY = new HashSet<int>(DeltaEntities.Select(i => i.KPHKEY)); using (var deltaIterator = DeltaEntities.GetEnumerator()) { using (var entityIterator = Entities.GetEnumerator()) { while (deltaIterator.MoveNext()) { var deltaClusteredKey = deltaIterator.Current.KPHKEY; bool yieldEntity = false; while (entityIterator.MoveNext()) { var entity = entityIterator.Current; bool overwritten = Index_KPHKEY.Remove(entity.KPHKEY); if (entity.KPHKEY.CompareTo(deltaClusteredKey) <= 0) { if (!overwritten) { yield return entity; } } else { yieldEntity = !overwritten; break; } } yield return deltaIterator.Current; if (yieldEntity) { yield return entityIterator.Current; } } while (entityIterator.MoveNext()) { yield return entityIterator.Current; } } } } #region Index Fields private Lazy<Dictionary<int, KPH>> Index_KPHKEY; #endregion #region Index Methods /// <summary> /// Find KPH by KPHKEY field /// </summary> /// <param name="KPHKEY">KPHKEY value used to find KPH</param> /// <returns>Related KPH entity</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public KPH FindByKPHKEY(int KPHKEY) { return Index_KPHKEY.Value[KPHKEY]; } /// <summary> /// Attempt to find KPH by KPHKEY field /// </summary> /// <param name="KPHKEY">KPHKEY value used to find KPH</param> /// <param name="Value">Related KPH entity</param> /// <returns>True if the related KPH entity is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindByKPHKEY(int KPHKEY, out KPH Value) { return Index_KPHKEY.Value.TryGetValue(KPHKEY, out Value); } /// <summary> /// Attempt to find KPH by KPHKEY field /// </summary> /// <param name="KPHKEY">KPHKEY value used to find KPH</param> /// <returns>Related KPH entity, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public KPH TryFindByKPHKEY(int KPHKEY) { KPH value; if (Index_KPHKEY.Value.TryGetValue(KPHKEY, out value)) { return value; } else { return null; } } #endregion #region SQL Integration /// <summary> /// Returns a <see cref="SqlCommand"/> which checks for the existence of a KPH table, and if not found, creates the table and associated indexes. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> public override SqlCommand GetSqlCreateTableCommand(SqlConnection SqlConnection) { return new SqlCommand( connection: SqlConnection, cmdText: @"IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[KPH]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1) BEGIN CREATE TABLE [dbo].[KPH]( [KPHKEY] int IDENTITY NOT NULL, [TABLE_NAME] varchar(15) NULL, [FIELD_NAME] varchar(50) NULL, [FIELD_TYPE] varchar(10) NULL, [KEY_FIELD] varchar(30) NULL, [KEY_VALUE] varchar(30) NULL, [OLD_VALUE] varchar(31) NULL, [NEW_VALUE] varchar(31) NULL, [LW_DATE] datetime NULL, [LW_TIME] smallint NULL, [LW_USER] varchar(128) NULL, CONSTRAINT [KPH_Index_KPHKEY] PRIMARY KEY CLUSTERED ( [KPHKEY] ASC ) ); END"); } /// <summary> /// Returns null as <see cref="KPHDataSet"/> has no non-clustered indexes. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <returns>null</returns> public override SqlCommand GetSqlDisableIndexesCommand(SqlConnection SqlConnection) { return null; } /// <summary> /// Returns null as <see cref="KPHDataSet"/> has no non-clustered indexes. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <returns>null</returns> public override SqlCommand GetSqlRebuildIndexesCommand(SqlConnection SqlConnection) { return null; } /// <summary> /// Returns a <see cref="SqlCommand"/> which deletes the <see cref="KPH"/> entities passed /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <param name="Entities">The <see cref="KPH"/> entities to be deleted</param> public override SqlCommand GetSqlDeleteCommand(SqlConnection SqlConnection, IEnumerable<KPH> Entities) { SqlCommand command = new SqlCommand(); int parameterIndex = 0; StringBuilder builder = new StringBuilder(); List<int> Index_KPHKEY = new List<int>(); foreach (var entity in Entities) { Index_KPHKEY.Add(entity.KPHKEY); } builder.AppendLine("DELETE [dbo].[KPH] WHERE"); // Index_KPHKEY builder.Append("[KPHKEY] IN ("); for (int index = 0; index < Index_KPHKEY.Count; index++) { if (index != 0) builder.Append(", "); // KPHKEY var parameterKPHKEY = $"@p{parameterIndex++}"; builder.Append(parameterKPHKEY); command.Parameters.Add(parameterKPHKEY, SqlDbType.Int).Value = Index_KPHKEY[index]; } builder.Append(");"); command.Connection = SqlConnection; command.CommandText = builder.ToString(); return command; } /// <summary> /// Provides a <see cref="IDataReader"/> for the KPH data set /// </summary> /// <returns>A <see cref="IDataReader"/> for the KPH data set</returns> public override EduHubDataSetDataReader<KPH> GetDataSetDataReader() { return new KPHDataReader(Load()); } /// <summary> /// Provides a <see cref="IDataReader"/> for the KPH data set /// </summary> /// <returns>A <see cref="IDataReader"/> for the KPH data set</returns> public override EduHubDataSetDataReader<KPH> GetDataSetDataReader(List<KPH> Entities) { return new KPHDataReader(new EduHubDataSetLoadedReader<KPH>(this, Entities)); } // Modest implementation to primarily support SqlBulkCopy private class KPHDataReader : EduHubDataSetDataReader<KPH> { public KPHDataReader(IEduHubDataSetReader<KPH> Reader) : base (Reader) { } public override int FieldCount { get { return 11; } } public override object GetValue(int i) { switch (i) { case 0: // KPHKEY return Current.KPHKEY; case 1: // TABLE_NAME return Current.TABLE_NAME; case 2: // FIELD_NAME return Current.FIELD_NAME; case 3: // FIELD_TYPE return Current.FIELD_TYPE; case 4: // KEY_FIELD return Current.KEY_FIELD; case 5: // KEY_VALUE return Current.KEY_VALUE; case 6: // OLD_VALUE return Current.OLD_VALUE; case 7: // NEW_VALUE return Current.NEW_VALUE; case 8: // LW_DATE return Current.LW_DATE; case 9: // LW_TIME return Current.LW_TIME; case 10: // LW_USER return Current.LW_USER; default: throw new ArgumentOutOfRangeException(nameof(i)); } } public override bool IsDBNull(int i) { switch (i) { case 1: // TABLE_NAME return Current.TABLE_NAME == null; case 2: // FIELD_NAME return Current.FIELD_NAME == null; case 3: // FIELD_TYPE return Current.FIELD_TYPE == null; case 4: // KEY_FIELD return Current.KEY_FIELD == null; case 5: // KEY_VALUE return Current.KEY_VALUE == null; case 6: // OLD_VALUE return Current.OLD_VALUE == null; case 7: // NEW_VALUE return Current.NEW_VALUE == null; case 8: // LW_DATE return Current.LW_DATE == null; case 9: // LW_TIME return Current.LW_TIME == null; case 10: // LW_USER return Current.LW_USER == null; default: return false; } } public override string GetName(int ordinal) { switch (ordinal) { case 0: // KPHKEY return "KPHKEY"; case 1: // TABLE_NAME return "TABLE_NAME"; case 2: // FIELD_NAME return "FIELD_NAME"; case 3: // FIELD_TYPE return "FIELD_TYPE"; case 4: // KEY_FIELD return "KEY_FIELD"; case 5: // KEY_VALUE return "KEY_VALUE"; case 6: // OLD_VALUE return "OLD_VALUE"; case 7: // NEW_VALUE return "NEW_VALUE"; case 8: // LW_DATE return "LW_DATE"; case 9: // LW_TIME return "LW_TIME"; case 10: // LW_USER return "LW_USER"; default: throw new ArgumentOutOfRangeException(nameof(ordinal)); } } public override int GetOrdinal(string name) { switch (name) { case "KPHKEY": return 0; case "TABLE_NAME": return 1; case "FIELD_NAME": return 2; case "FIELD_TYPE": return 3; case "KEY_FIELD": return 4; case "KEY_VALUE": return 5; case "OLD_VALUE": return 6; case "NEW_VALUE": return 7; case "LW_DATE": return 8; case "LW_TIME": return 9; case "LW_USER": return 10; default: throw new ArgumentOutOfRangeException(nameof(name)); } } } #endregion } }
using System.Threading.Tasks; using System; using System.IO; using System.Text; #if !SILVERLIGHT using System.Xml.XPath; #endif using System.Xml.Schema; using System.Diagnostics; using System.Collections.Generic; using System.Globalization; using System.Runtime.Versioning; namespace System.Xml { // Represents a writer that provides fast non-cached forward-only way of generating XML streams containing XML documents // that conform to the W3C Extensible Markup Language (XML) 1.0 specification and the Namespaces in XML specification. public abstract partial class XmlWriter : IDisposable { // Write methods // Writes out the XML declaration with the version "1.0". public virtual Task WriteStartDocumentAsync() { throw new NotImplementedException(); } //Writes out the XML declaration with the version "1.0" and the speficied standalone attribute. public virtual Task WriteStartDocumentAsync(bool standalone) { throw new NotImplementedException(); } //Closes any open elements or attributes and puts the writer back in the Start state. public virtual Task WriteEndDocumentAsync() { throw new NotImplementedException(); } // Writes out the DOCTYPE declaration with the specified name and optional attributes. public virtual Task WriteDocTypeAsync(string name, string pubid, string sysid, string subset) { throw new NotImplementedException(); } // Writes out the specified start tag and associates it with the given namespace and prefix. public virtual Task WriteStartElementAsync(string prefix, string localName, string ns) { throw new NotImplementedException(); } // Closes one element and pops the corresponding namespace scope. public virtual Task WriteEndElementAsync() { throw new NotImplementedException(); } // Closes one element and pops the corresponding namespace scope. Writes out a full end element tag, e.g. </element>. public virtual Task WriteFullEndElementAsync() { throw new NotImplementedException(); } // Writes out the attribute with the specified LocalName, value, and NamespaceURI. #if !SILVERLIGHT #endif // Writes out the attribute with the specified prefix, LocalName, NamespaceURI and value. public Task WriteAttributeStringAsync(string prefix, string localName, string ns, string value) { Task task = WriteStartAttributeAsync(prefix, localName, ns); if (task.IsSuccess()) { return WriteStringAsync(value).CallTaskFuncWhenFinish(WriteEndAttributeAsync); } else { return WriteAttributeStringAsyncHelper(task, value); } } private async Task WriteAttributeStringAsyncHelper(Task task, string value) { await task.ConfigureAwait(false); await WriteStringAsync(value).ConfigureAwait(false); await WriteEndAttributeAsync().ConfigureAwait(false); } // Writes the start of an attribute. protected internal virtual Task WriteStartAttributeAsync(string prefix, string localName, string ns) { throw new NotImplementedException(); } // Closes the attribute opened by WriteStartAttribute call. protected internal virtual Task WriteEndAttributeAsync() { throw new NotImplementedException(); } // Writes out a <![CDATA[...]]>; block containing the specified text. public virtual Task WriteCDataAsync(string text) { throw new NotImplementedException(); } // Writes out a comment <!--...-->; containing the specified text. public virtual Task WriteCommentAsync(string text) { throw new NotImplementedException(); } // Writes out a processing instruction with a space between the name and text as follows: <?name text?> public virtual Task WriteProcessingInstructionAsync(string name, string text) { throw new NotImplementedException(); } // Writes out an entity reference as follows: "&"+name+";". public virtual Task WriteEntityRefAsync(string name) { throw new NotImplementedException(); } // Forces the generation of a character entity for the specified Unicode character value. public virtual Task WriteCharEntityAsync(char ch) { throw new NotImplementedException(); } // Writes out the given whitespace. public virtual Task WriteWhitespaceAsync(string ws) { throw new NotImplementedException(); } // Writes out the specified text content. public virtual Task WriteStringAsync(string text) { throw new NotImplementedException(); } // Write out the given surrogate pair as an entity reference. public virtual Task WriteSurrogateCharEntityAsync(char lowChar, char highChar) { throw new NotImplementedException(); } // Writes out the specified text content. public virtual Task WriteCharsAsync(char[] buffer, int index, int count) { throw new NotImplementedException(); } // Writes raw markup from the given character buffer. public virtual Task WriteRawAsync(char[] buffer, int index, int count) { throw new NotImplementedException(); } // Writes raw markup from the given string. public virtual Task WriteRawAsync(string data) { throw new NotImplementedException(); } // Encodes the specified binary bytes as base64 and writes out the resulting text. public virtual Task WriteBase64Async(byte[] buffer, int index, int count) { throw new NotImplementedException(); } // Encodes the specified binary bytes as binhex and writes out the resulting text. public virtual Task WriteBinHexAsync(byte[] buffer, int index, int count) { return BinHexEncoder.EncodeAsync(buffer, index, count, this); } // Flushes data that is in the internal buffers into the underlying streams/TextReader and flushes the stream/TextReader. public virtual Task FlushAsync() { throw new NotImplementedException(); } // Scalar Value Methods // Writes out the specified name, ensuring it is a valid NmToken according to the XML specification // (http://www.w3.org/TR/1998/REC-xml-19980210#NT-Name). public virtual Task WriteNmTokenAsync(string name) { if (name == null || name.Length == 0) { throw new ArgumentException(Res.GetString(Res.Xml_EmptyName)); } return WriteStringAsync(XmlConvert.VerifyNMTOKEN(name, ExceptionType.ArgumentException)); } // Writes out the specified name, ensuring it is a valid Name according to the XML specification // (http://www.w3.org/TR/1998/REC-xml-19980210#NT-Name). public virtual Task WriteNameAsync(string name) { return WriteStringAsync(XmlConvert.VerifyQName(name, ExceptionType.ArgumentException)); } // Writes out the specified namespace-qualified name by looking up the prefix that is in scope for the given namespace. public virtual async Task WriteQualifiedNameAsync(string localName, string ns) { if (ns != null && ns.Length > 0) { string prefix = LookupPrefix(ns); if (prefix == null) { throw new ArgumentException(Res.GetString(Res.Xml_UndefNamespace, ns)); } await WriteStringAsync(prefix).ConfigureAwait(false); await WriteStringAsync(":").ConfigureAwait(false); } await WriteStringAsync(localName).ConfigureAwait(false); } // XmlReader Helper Methods // Writes out all the attributes found at the current position in the specified XmlReader. public virtual async Task WriteAttributesAsync(XmlReader reader, bool defattr) { if (null == reader) { throw new ArgumentNullException("reader"); } if (reader.NodeType == XmlNodeType.Element || reader.NodeType == XmlNodeType.XmlDeclaration) { if (reader.MoveToFirstAttribute()) { await WriteAttributesAsync(reader, defattr).ConfigureAwait(false); reader.MoveToElement(); } } else if (reader.NodeType != XmlNodeType.Attribute) { throw new XmlException(Res.Xml_InvalidPosition, string.Empty); } else { do { // we need to check both XmlReader.IsDefault and XmlReader.SchemaInfo.IsDefault. // If either of these is true and defattr=false, we should not write the attribute out if (defattr || !reader.IsDefaultInternal) { await WriteStartAttributeAsync(reader.Prefix, reader.LocalName, reader.NamespaceURI).ConfigureAwait(false); while (reader.ReadAttributeValue()) { if (reader.NodeType == XmlNodeType.EntityReference) { await WriteEntityRefAsync(reader.Name).ConfigureAwait(false); } else { await WriteStringAsync(reader.Value).ConfigureAwait(false); } } await WriteEndAttributeAsync().ConfigureAwait(false); } } while (reader.MoveToNextAttribute()); } } // Copies the current node from the given reader to the writer (including child nodes), and if called on an element moves the XmlReader // to the corresponding end element. public virtual Task WriteNodeAsync(XmlReader reader, bool defattr) { if (null == reader) { throw new ArgumentNullException("reader"); } if (reader.Settings != null && reader.Settings.Async) { return WriteNodeAsync_CallAsyncReader(reader, defattr); } else { return WriteNodeAsync_CallSyncReader(reader, defattr); } } // Copies the current node from the given reader to the writer (including child nodes), and if called on an element moves the XmlReader // to the corresponding end element. //use [....] methods on the reader internal async Task WriteNodeAsync_CallSyncReader(XmlReader reader, bool defattr) { bool canReadChunk = reader.CanReadValueChunk; int d = reader.NodeType == XmlNodeType.None ? -1 : reader.Depth; do { switch (reader.NodeType) { case XmlNodeType.Element: await WriteStartElementAsync(reader.Prefix, reader.LocalName, reader.NamespaceURI).ConfigureAwait(false); await WriteAttributesAsync(reader, defattr).ConfigureAwait(false); if (reader.IsEmptyElement) { await WriteEndElementAsync().ConfigureAwait(false); break; } break; case XmlNodeType.Text: if (canReadChunk) { if (writeNodeBuffer == null) { writeNodeBuffer = new char[WriteNodeBufferSize]; } int read; while ((read = reader.ReadValueChunk(writeNodeBuffer, 0, WriteNodeBufferSize)) > 0) { await this.WriteCharsAsync(writeNodeBuffer, 0, read).ConfigureAwait(false); } } else { await WriteStringAsync(reader.Value).ConfigureAwait(false); } break; case XmlNodeType.Whitespace: case XmlNodeType.SignificantWhitespace: await WriteWhitespaceAsync(reader.Value).ConfigureAwait(false); break; case XmlNodeType.CDATA: await WriteCDataAsync(reader.Value).ConfigureAwait(false); break; case XmlNodeType.EntityReference: await WriteEntityRefAsync(reader.Name).ConfigureAwait(false); break; case XmlNodeType.XmlDeclaration: case XmlNodeType.ProcessingInstruction: await WriteProcessingInstructionAsync(reader.Name, reader.Value).ConfigureAwait(false); break; case XmlNodeType.DocumentType: await WriteDocTypeAsync(reader.Name, reader.GetAttribute("PUBLIC"), reader.GetAttribute("SYSTEM"), reader.Value).ConfigureAwait(false); break; case XmlNodeType.Comment: await WriteCommentAsync(reader.Value).ConfigureAwait(false); break; case XmlNodeType.EndElement: await WriteFullEndElementAsync().ConfigureAwait(false); break; } } while (reader.Read() && (d < reader.Depth || (d == reader.Depth && reader.NodeType == XmlNodeType.EndElement))); } // Copies the current node from the given reader to the writer (including child nodes), and if called on an element moves the XmlReader // to the corresponding end element. //use async methods on the reader internal async Task WriteNodeAsync_CallAsyncReader(XmlReader reader, bool defattr) { bool canReadChunk = reader.CanReadValueChunk; int d = reader.NodeType == XmlNodeType.None ? -1 : reader.Depth; do { switch (reader.NodeType) { case XmlNodeType.Element: await WriteStartElementAsync(reader.Prefix, reader.LocalName, reader.NamespaceURI).ConfigureAwait(false); await WriteAttributesAsync(reader, defattr).ConfigureAwait(false); if (reader.IsEmptyElement) { await WriteEndElementAsync().ConfigureAwait(false); break; } break; case XmlNodeType.Text: if (canReadChunk) { if (writeNodeBuffer == null) { writeNodeBuffer = new char[WriteNodeBufferSize]; } int read; while ((read = await reader.ReadValueChunkAsync(writeNodeBuffer, 0, WriteNodeBufferSize).ConfigureAwait(false)) > 0) { await this.WriteCharsAsync(writeNodeBuffer, 0, read).ConfigureAwait(false); } } else { //reader.Value may block on Text or WhiteSpace node, use GetValueAsync await WriteStringAsync(await reader.GetValueAsync().ConfigureAwait(false)).ConfigureAwait(false); } break; case XmlNodeType.Whitespace: case XmlNodeType.SignificantWhitespace: await WriteWhitespaceAsync(await reader.GetValueAsync().ConfigureAwait(false)).ConfigureAwait(false); break; case XmlNodeType.CDATA: await WriteCDataAsync(reader.Value).ConfigureAwait(false); break; case XmlNodeType.EntityReference: await WriteEntityRefAsync(reader.Name).ConfigureAwait(false); break; case XmlNodeType.XmlDeclaration: case XmlNodeType.ProcessingInstruction: await WriteProcessingInstructionAsync(reader.Name, reader.Value).ConfigureAwait(false); break; case XmlNodeType.DocumentType: await WriteDocTypeAsync(reader.Name, reader.GetAttribute("PUBLIC"), reader.GetAttribute("SYSTEM"), reader.Value).ConfigureAwait(false); break; case XmlNodeType.Comment: await WriteCommentAsync(reader.Value).ConfigureAwait(false); break; case XmlNodeType.EndElement: await WriteFullEndElementAsync().ConfigureAwait(false); break; } } while (await reader.ReadAsync().ConfigureAwait(false) && (d < reader.Depth || (d == reader.Depth && reader.NodeType == XmlNodeType.EndElement))); } #if !SILVERLIGHT // Removing dependency on XPathNavigator // Copies the current node from the given XPathNavigator to the writer (including child nodes). public virtual async Task WriteNodeAsync(XPathNavigator navigator, bool defattr) { if (navigator == null) { throw new ArgumentNullException("navigator"); } int iLevel = 0; navigator = navigator.Clone(); while (true) { bool mayHaveChildren = false; XPathNodeType nodeType = navigator.NodeType; switch (nodeType) { case XPathNodeType.Element: await WriteStartElementAsync(navigator.Prefix, navigator.LocalName, navigator.NamespaceURI).ConfigureAwait(false); // Copy attributes if (navigator.MoveToFirstAttribute()) { do { IXmlSchemaInfo schemaInfo = navigator.SchemaInfo; if (defattr || (schemaInfo == null || !schemaInfo.IsDefault)) { await WriteStartAttributeAsync(navigator.Prefix, navigator.LocalName, navigator.NamespaceURI).ConfigureAwait(false); // copy string value to writer await WriteStringAsync(navigator.Value).ConfigureAwait(false); await WriteEndAttributeAsync().ConfigureAwait(false); } } while (navigator.MoveToNextAttribute()); navigator.MoveToParent(); } // Copy namespaces if (navigator.MoveToFirstNamespace(XPathNamespaceScope.Local)) { await WriteLocalNamespacesAsync(navigator).ConfigureAwait(false); navigator.MoveToParent(); } mayHaveChildren = true; break; case XPathNodeType.Attribute: // do nothing on root level attribute break; case XPathNodeType.Text: await WriteStringAsync(navigator.Value).ConfigureAwait(false); break; case XPathNodeType.SignificantWhitespace: case XPathNodeType.Whitespace: await WriteWhitespaceAsync(navigator.Value).ConfigureAwait(false); break; case XPathNodeType.Root: mayHaveChildren = true; break; case XPathNodeType.Comment: await WriteCommentAsync(navigator.Value).ConfigureAwait(false); break; case XPathNodeType.ProcessingInstruction: await WriteProcessingInstructionAsync(navigator.LocalName, navigator.Value).ConfigureAwait(false); break; case XPathNodeType.Namespace: // do nothing on root level namespace break; default: Debug.Assert(false); break; } if (mayHaveChildren) { // If children exist, move down to next level if (navigator.MoveToFirstChild()) { iLevel++; continue; } else { // EndElement if (navigator.NodeType == XPathNodeType.Element) { if (navigator.IsEmptyElement) { await WriteEndElementAsync().ConfigureAwait(false); } else { await WriteFullEndElementAsync().ConfigureAwait(false); } } } } // No children while (true) { if (iLevel == 0) { // The entire subtree has been copied return; } if (navigator.MoveToNext()) { // Found a sibling, so break to outer loop break; } // No siblings, so move up to previous level iLevel--; navigator.MoveToParent(); // EndElement if (navigator.NodeType == XPathNodeType.Element) await WriteFullEndElementAsync().ConfigureAwait(false); } } } #endif // Element Helper Methods // Writes out an attribute with the specified name, namespace URI, and string value. public async Task WriteElementStringAsync(string prefix, String localName, String ns, String value) { await WriteStartElementAsync(prefix, localName, ns).ConfigureAwait(false); if (null != value && 0 != value.Length) { await WriteStringAsync(value).ConfigureAwait(false); } await WriteEndElementAsync().ConfigureAwait(false); } #if !SILVERLIGHT // Removing dependency on XPathNavigator // Copy local namespaces on the navigator's current node to the raw writer. The namespaces are returned by the navigator in reversed order. // The recursive call reverses them back. private async Task WriteLocalNamespacesAsync(XPathNavigator nsNav) { string prefix = nsNav.LocalName; string ns = nsNav.Value; if (nsNav.MoveToNextNamespace(XPathNamespaceScope.Local)) { await WriteLocalNamespacesAsync(nsNav).ConfigureAwait(false); } if (prefix.Length == 0) { await WriteAttributeStringAsync(string.Empty, "xmlns", XmlReservedNs.NsXmlNs, ns).ConfigureAwait(false); } else { await WriteAttributeStringAsync("xmlns", prefix, XmlReservedNs.NsXmlNs, ns).ConfigureAwait(false); } } #endif } }
using System; using System.Text; using NUnit.Framework; using Org.BouncyCastle.Crypto; using Org.BouncyCastle.Crypto.Generators; using Org.BouncyCastle.Crypto.Parameters; using Org.BouncyCastle.Crypto.Signers; using Org.BouncyCastle.Math; using Org.BouncyCastle.Security; using Org.BouncyCastle.Utilities.Encoders; using Org.BouncyCastle.Utilities.Test; namespace Org.BouncyCastle.Crypto.Tests { [TestFixture] public class Gost3410Test : ITest { private static readonly byte[] hashmessage = Hex.Decode("3042453136414534424341374533364339313734453431443642453241453435"); private static byte[] zeroTwo(int length) { byte[] data = new byte[length]; data[data.Length - 1] = 0x02; return data; } private class Gost3410_TEST1_512 : ITest { public string Name { get { return "Gost3410-TEST1-512"; } } FixedSecureRandom init_random = FixedSecureRandom.From(Hex.Decode("00005EC900007341"), zeroTwo(64)); FixedSecureRandom random = FixedSecureRandom.From(Hex.Decode("90F3A564439242F5186EBB224C8E223811B7105C64E4F5390807E6362DF4C72A")); FixedSecureRandom keyRandom = FixedSecureRandom.From(Hex.Decode("3036314538303830343630454235324435324234314132373832433138443046")); BigInteger pValue = new BigInteger("EE8172AE8996608FB69359B89EB82A69854510E2977A4D63BC97322CE5DC3386EA0A12B343E9190F23177539845839786BB0C345D165976EF2195EC9B1C379E3", 16); BigInteger qValue = new BigInteger("98915E7EC8265EDFCDA31E88F24809DDB064BDC7285DD50D7289F0AC6F49DD2D", 16); public ITestResult Perform() { BigInteger r = new BigInteger("3e5f895e276d81d2d52c0763270a458157b784c57abdbd807bc44fd43a32ac06",16); BigInteger s = new BigInteger("3f0dd5d4400d47c08e4ce505ff7434b6dbf729592e37c74856dab85115a60955",16); Gost3410ParametersGenerator pGen = new Gost3410ParametersGenerator(); pGen.Init(512, 1, init_random); Gost3410Parameters parameters = pGen.GenerateParameters(); if (parameters.ValidationParameters == null) { return new SimpleTestResult(false, Name + "validation parameters wrong"); } if (parameters.ValidationParameters.C != 29505 || parameters.ValidationParameters.X0 != 24265) { return new SimpleTestResult(false, Name + "validation parameters values wrong"); } if (!init_random.IsExhausted) { return new SimpleTestResult(false, Name + ": unexpected number of bytes used from 'init_random'."); } if (!pValue.Equals(parameters.P) || !qValue.Equals(parameters.Q)) { return new SimpleTestResult(false, Name + ": p or q wrong"); } Gost3410KeyPairGenerator Gost3410KeyGen = new Gost3410KeyPairGenerator(); Gost3410KeyGenerationParameters genParam = new Gost3410KeyGenerationParameters(keyRandom, parameters); Gost3410KeyGen.Init(genParam); AsymmetricCipherKeyPair pair = Gost3410KeyGen.GenerateKeyPair(); if (!keyRandom.IsExhausted) { return new SimpleTestResult(false, Name + ": unexpected number of bytes used from 'keyRandom'."); } ParametersWithRandom param = new ParametersWithRandom(pair.Private, random); Gost3410Signer gost3410 = new Gost3410Signer(); gost3410.Init(true, param); BigInteger[] sig = gost3410.GenerateSignature(hashmessage); if (!random.IsExhausted) { return new SimpleTestResult(false, Name + ": unexpected number of bytes used from 'random'."); } if (!r.Equals(sig[0])) { return new SimpleTestResult(false, Name + ": r component wrong." + SimpleTest.NewLine + " expecting: " + r.ToString(16) + SimpleTest.NewLine + " got : " + sig[0].ToString(16)); } if (!s.Equals(sig[1])) { return new SimpleTestResult(false, Name + ": s component wrong." + SimpleTest.NewLine + " expecting: " + s.ToString(16) + SimpleTest.NewLine + " got : " + sig[1].ToString(16)); } gost3410.Init(false, pair.Public); if (gost3410.VerifySignature(hashmessage, sig[0], sig[1])) { return new SimpleTestResult(true, Name + ": Okay"); } else { return new SimpleTestResult(false, Name + ": verification fails"); } } } private class Gost3410_TEST2_512 : ITest { public string Name { get { return "Gost3410-TEST2-512"; } } FixedSecureRandom init_random = FixedSecureRandom.From(Hex.Decode("000000003DFC46F1000000000000000D"), zeroTwo(64)); FixedSecureRandom random = FixedSecureRandom.From(Hex.Decode("90F3A564439242F5186EBB224C8E223811B7105C64E4F5390807E6362DF4C72A")); FixedSecureRandom keyRandom = FixedSecureRandom.From(Hex.Decode("3036314538303830343630454235324435324234314132373832433138443046")); BigInteger pValue = new BigInteger("8b08eb135af966aab39df294538580c7da26765d6d38d30cf1c06aae0d1228c3316a0e29198460fad2b19dc381c15c888c6dfd0fc2c565abb0bf1faff9518f85", 16); BigInteger qValue = new BigInteger("931a58fb6f0dcdf2fe7549bc3f19f4724b56898f7f921a076601edb18c93dc75", 16); public ITestResult Perform() { BigInteger r = new BigInteger("7c07c8cf035c2a1cb2b7fae5807ac7cd623dfca7a1a68f6d858317822f1ea00d",16); BigInteger s = new BigInteger("7e9e036a6ff87dbf9b004818252b1f6fc310bdd4d17cb8c37d9c36c7884de60c",16); Gost3410ParametersGenerator pGen = new Gost3410ParametersGenerator(); pGen.Init(512, 2, init_random); Gost3410Parameters parameters = pGen.GenerateParameters(); if (!init_random.IsExhausted) { return new SimpleTestResult(false, Name + ": unexpected number of bytes used from 'init_random'."); } if (parameters.ValidationParameters == null) { return new SimpleTestResult(false, Name + ": validation parameters wrong"); } if (parameters.ValidationParameters.CL != 13 || parameters.ValidationParameters.X0L != 1039943409) { return new SimpleTestResult(false, Name + ": validation parameters values wrong"); } if (!pValue.Equals(parameters.P) || !qValue.Equals(parameters.Q)) { return new SimpleTestResult(false, Name + ": p or q wrong"); } Gost3410KeyPairGenerator Gost3410KeyGen = new Gost3410KeyPairGenerator(); Gost3410KeyGenerationParameters genParam = new Gost3410KeyGenerationParameters(keyRandom, parameters); Gost3410KeyGen.Init(genParam); AsymmetricCipherKeyPair pair = Gost3410KeyGen.GenerateKeyPair(); if (!keyRandom.IsExhausted) { return new SimpleTestResult(false, Name + ": unexpected number of bytes used from 'keyRandom'."); } ParametersWithRandom param = new ParametersWithRandom(pair.Private, random); Gost3410Signer Gost3410 = new Gost3410Signer(); Gost3410.Init(true, param); BigInteger[] sig = Gost3410.GenerateSignature(hashmessage); if (!random.IsExhausted) { return new SimpleTestResult(false, Name + ": unexpected number of bytes used from 'random'."); } if (!r.Equals(sig[0])) { return new SimpleTestResult(false, Name + ": r component wrong." + SimpleTest.NewLine + " expecting: " + r.ToString(16) + SimpleTest.NewLine + " got : " + sig[0].ToString(16)); } if (!s.Equals(sig[1])) { return new SimpleTestResult(false, Name + ": s component wrong." + SimpleTest.NewLine + " expecting: " + s.ToString(16) + SimpleTest.NewLine + " got : " + sig[1].ToString(16)); } Gost3410.Init(false, pair.Public); if (!Gost3410.VerifySignature(hashmessage, sig[0], sig[1])) { return new SimpleTestResult(false, Name + ": verification fails"); } return new SimpleTestResult(true, Name + ": Okay"); } } private class Gost3410_TEST1_1024 : ITest { public string Name { get { return "Gost3410-TEST1-1024"; } } private class SecureRandomImpl1 : SecureRandom { bool firstInt = true; public override int NextInt() { string x0 = "0xA565"; string c = "0x538B"; if (firstInt) { firstInt = false; return NumberParsing.DecodeIntFromHex(x0); } return NumberParsing.DecodeIntFromHex(c); } public override void NextBytes(byte[] bytes) { byte[] d = Hex.Decode("02"); Array.Copy(d, 0, bytes, bytes.Length-d.Length, d.Length); } }; SecureRandom init_random = new SecureRandomImpl1(); private class SecureRandomImpl2 : SecureRandom { public override void NextBytes(byte[] bytes) { byte[] k = Hex.Decode("90F3A564439242F5186EBB224C8E223811B7105C64E4F5390807E6362DF4C72A"); int i; for (i = 0; i < (bytes.Length - k.Length); i += k.Length) { Array.Copy(k, 0, bytes, i, k.Length); } if (i > bytes.Length) { Array.Copy(k, 0, bytes, i - k.Length, bytes.Length - (i - k.Length)); } else { Array.Copy(k, 0, bytes, i, bytes.Length - i); } } }; SecureRandom random = new SecureRandomImpl2(); private class SecureRandomImpl3 : SecureRandom { public override void NextBytes(byte[] bytes) { byte[] x = Hex.Decode("3036314538303830343630454235324435324234314132373832433138443046"); int i; for (i = 0; i < (bytes.Length - x.Length); i += x.Length) { Array.Copy(x, 0, bytes, i, x.Length); } if (i > bytes.Length) { Array.Copy(x, 0, bytes, i - x.Length, bytes.Length - (i - x.Length)); } else { Array.Copy(x, 0, bytes, i, bytes.Length - i); } } }; SecureRandom keyRandom = new SecureRandomImpl3(); BigInteger pValue = new BigInteger("ab8f37938356529e871514c1f48c5cbce77b2f4fc9a2673ac2c1653da8984090c0ac73775159a26bef59909d4c9846631270e16653a6234668f2a52a01a39b921490e694c0f104b58d2e14970fccb478f98d01e975a1028b9536d912de5236d2dd2fc396b77153594d4178780e5f16f718471e2111c8ce64a7d7e196fa57142d", 16); BigInteger qValue = new BigInteger("bcc02ca0ce4f0753ec16105ee5d530aa00d39f3171842ab2c334a26b5f576e0f", 16); public ITestResult Perform() { BigInteger r = new BigInteger("a8790aabbd5a998ff524bad048ac69cd1faff2dab048265c8d60d1471c44a9ee",16); BigInteger s = new BigInteger("30df5ba32ac77170b9632559bef7d37620017756dff3fea1088b4267db0944b8",16); Gost3410ParametersGenerator pGen = new Gost3410ParametersGenerator(); pGen.Init(1024, 1, init_random); Gost3410Parameters parameters = pGen.GenerateParameters(); if (!pValue.Equals(parameters.P) || !qValue.Equals(parameters.Q)) { return new SimpleTestResult(false, Name + ": p or q wrong"); } Gost3410KeyPairGenerator Gost3410KeyGen = new Gost3410KeyPairGenerator(); Gost3410KeyGenerationParameters genParam = new Gost3410KeyGenerationParameters(keyRandom, parameters); Gost3410KeyGen.Init(genParam); AsymmetricCipherKeyPair pair = Gost3410KeyGen.GenerateKeyPair(); ParametersWithRandom param = new ParametersWithRandom(pair.Private, random); Gost3410Signer Gost3410 = new Gost3410Signer(); Gost3410.Init(true, param); BigInteger[] sig = Gost3410.GenerateSignature(hashmessage); if (!r.Equals(sig[0])) { return new SimpleTestResult(false, Name + ": r component wrong." + SimpleTest.NewLine + " expecting: " + r.ToString(16) + SimpleTest.NewLine + " got : " + sig[0].ToString(16)); } if (!s.Equals(sig[1])) { return new SimpleTestResult(false, Name + ": s component wrong." + SimpleTest.NewLine + " expecting: " + s.ToString(16) + SimpleTest.NewLine + " got : " + sig[1].ToString(16)); } Gost3410.Init(false, pair.Public); if (Gost3410.VerifySignature(hashmessage, sig[0], sig[1])) { return new SimpleTestResult(true, Name + ": Okay"); } else { return new SimpleTestResult(false, Name + ": verification fails"); } } } private class Gost3410_TEST2_1024 : ITest { public string Name { get { return "Gost3410-TEST2-1024"; } } private class SecureRandomImpl4 : SecureRandom { bool firstLong = true; public override long NextLong() { string x0 = "0x3DFC46F1"; string c = "0xD"; if (firstLong) { firstLong = false; return NumberParsing.DecodeLongFromHex(x0); } return NumberParsing.DecodeLongFromHex(c); } public override void NextBytes(byte[] bytes) { byte[] d = Hex.Decode("02"); Array.Copy(d, 0, bytes, bytes.Length-d.Length, d.Length); } }; SecureRandom init_random = new SecureRandomImpl4(); private class SecureRandomImpl5 : SecureRandom { public override void NextBytes(byte[] bytes) { byte[] k = Hex.Decode("90F3A564439242F5186EBB224C8E223811B7105C64E4F5390807E6362DF4C72A"); int i; for (i = 0; i < (bytes.Length - k.Length); i += k.Length) { Array.Copy(k, 0, bytes, i, k.Length); } if (i > bytes.Length) { Array.Copy(k, 0, bytes, i - k.Length, bytes.Length - (i - k.Length)); } else { Array.Copy(k, 0, bytes, i, bytes.Length - i); } } }; SecureRandom random = new SecureRandomImpl5(); private class SecureRandomImpl6 : SecureRandom { public override void NextBytes(byte[] bytes) { byte[] x = Hex.Decode("3036314538303830343630454235324435324234314132373832433138443046"); int i; for (i = 0; i < (bytes.Length - x.Length); i += x.Length) { Array.Copy(x, 0, bytes, i, x.Length); } if (i > bytes.Length) { Array.Copy(x, 0, bytes, i - x.Length, bytes.Length - (i - x.Length)); } else { Array.Copy(x, 0, bytes, i, bytes.Length - i); } } }; SecureRandom keyRandom = new SecureRandomImpl6(); BigInteger pValue = new BigInteger("e2c4191c4b5f222f9ac2732562f6d9b4f18e7fb67a290ea1e03d750f0b9806755fc730d975bf3faa606d05c218b35a6c3706919aab92e0c58b1de4531c8fa8e7af43c2bff016251e21b2870897f6a27ac4450bca235a5b748ad386e4a0e4dfcb09152435abcfe48bd0b126a8122c7382f285a9864615c66decddf6afd355dfb7", 16); BigInteger qValue = new BigInteger("931a58fb6f0dcdf2fe7549bc3f19f4724b56898f7f921a076601edb18c93dc75", 16); public ITestResult Perform() { BigInteger r = new BigInteger("81d69a192e9c7ac21fc07da41bd07e230ba6a94eb9f3c1fd104c7bd976733ca5",16); BigInteger s = new BigInteger("315c879c8414f35feb4deb15e7cc0278c48e6ca1596325d6959338d860b0c47a",16); Gost3410ParametersGenerator pGen = new Gost3410ParametersGenerator(); pGen.Init(1024, 2, init_random); Gost3410Parameters parameters = pGen.GenerateParameters(); if (!pValue.Equals(parameters.P) || !qValue.Equals(parameters.Q)) { return new SimpleTestResult(false, Name + ": p or q wrong"); } Gost3410KeyPairGenerator Gost3410KeyGen = new Gost3410KeyPairGenerator(); Gost3410KeyGenerationParameters genParam = new Gost3410KeyGenerationParameters(keyRandom, parameters); Gost3410KeyGen.Init(genParam); AsymmetricCipherKeyPair pair = Gost3410KeyGen.GenerateKeyPair(); ParametersWithRandom param = new ParametersWithRandom(pair.Private, random); Gost3410Signer Gost3410 = new Gost3410Signer(); Gost3410.Init(true, param); BigInteger[] sig = Gost3410.GenerateSignature(hashmessage); if (!r.Equals(sig[0])) { return new SimpleTestResult(false, Name + ": r component wrong." + SimpleTest.NewLine + " expecting: " + r.ToString(16) + SimpleTest.NewLine + " got : " + sig[0].ToString(16)); } if (!s.Equals(sig[1])) { return new SimpleTestResult(false, Name + ": s component wrong." + SimpleTest.NewLine + " expecting: " + s.ToString(16) + SimpleTest.NewLine + " got : " + sig[1].ToString(16)); } Gost3410.Init(false, pair.Public); if (Gost3410.VerifySignature(hashmessage, sig[0], sig[1])) { return new SimpleTestResult(true, Name + ": Okay"); } else { return new SimpleTestResult(false, Name + ": verification fails"); } } } private class Gost3410_AParam : ITest { public string Name { get { return "Gost3410-AParam"; } } private class SecureRandomImpl7 : SecureRandom { bool firstLong = true; public override long NextLong() { string x0 = "0x520874F5"; string c = "0xEE39ADB3"; if (firstLong) { firstLong = false; return NumberParsing.DecodeLongFromHex(x0); } return NumberParsing.DecodeLongFromHex(c); } public override void NextBytes(byte[] bytes) { byte[] d = Hex.Decode("02"); Array.Copy(d, 0, bytes, bytes.Length-d.Length, d.Length); } }; SecureRandom init_random = new SecureRandomImpl7(); private class SecureRandomImpl8 : SecureRandom { public override void NextBytes(byte[] bytes) { byte[] k = Hex.Decode("90F3A564439242F5186EBB224C8E223811B7105C64E4F5390807E6362DF4C72A"); int i; for (i = 0; i < (bytes.Length - k.Length); i += k.Length) { Array.Copy(k, 0, bytes, i, k.Length); } if (i > bytes.Length) { Array.Copy(k, 0, bytes, i - k.Length, bytes.Length - (i - k.Length)); } else { Array.Copy(k, 0, bytes, i, bytes.Length - i); } } }; SecureRandom random = new SecureRandomImpl8(); private class SecureRandomImpl9 : SecureRandom { public override void NextBytes(byte[] bytes) { byte[] x = Hex.Decode("3036314538303830343630454235324435324234314132373832433138443046"); int i; for (i = 0; i < (bytes.Length - x.Length); i += x.Length) { Array.Copy(x, 0, bytes, i, x.Length); } if (i > bytes.Length) { Array.Copy(x, 0, bytes, i - x.Length, bytes.Length - (i - x.Length)); } else { Array.Copy(x, 0, bytes, i, bytes.Length - i); } } }; SecureRandom keyRandom = new SecureRandomImpl9(); BigInteger pValue = new BigInteger("b4e25efb018e3c8b87505e2a67553c5edc56c2914b7e4f89d23f03f03377e70a2903489dd60e78418d3d851edb5317c4871e40b04228c3b7902963c4b7d85d52b9aa88f2afdbeb28da8869d6df846a1d98924e925561bd69300b9ddd05d247b5922d967cbb02671881c57d10e5ef72d3e6dad4223dc82aa1f7d0294651a480df", 16); BigInteger qValue = new BigInteger("972432a437178b30bd96195b773789ab2fff15594b176dd175b63256ee5af2cf", 16); public ITestResult Perform() { BigInteger r = new BigInteger("64a8856628e5669d85f62cd763dd4a99bc56d33dc0e1859122855d141e9e4774",16); BigInteger s = new BigInteger("319ebac97092b288d469a4b988248794f60c865bc97858d9a3135c6d1a1bf2dd",16); Gost3410ParametersGenerator pGen = new Gost3410ParametersGenerator(); pGen.Init(1024, 2, init_random); Gost3410Parameters parameters = pGen.GenerateParameters(); if (!pValue.Equals(parameters.P) || !qValue.Equals(parameters.Q)) { return new SimpleTestResult(false, Name + ": p or q wrong"); } Gost3410KeyPairGenerator Gost3410KeyGen = new Gost3410KeyPairGenerator(); Gost3410KeyGenerationParameters genParam = new Gost3410KeyGenerationParameters(keyRandom, parameters); Gost3410KeyGen.Init(genParam); AsymmetricCipherKeyPair pair = Gost3410KeyGen.GenerateKeyPair(); ParametersWithRandom param = new ParametersWithRandom(pair.Private, random); Gost3410Signer Gost3410 = new Gost3410Signer(); Gost3410.Init(true, param); BigInteger[] sig = Gost3410.GenerateSignature(hashmessage); if (!r.Equals(sig[0])) { return new SimpleTestResult(false, Name + ": r component wrong." + SimpleTest.NewLine + " expecting: " + r.ToString(16) + SimpleTest.NewLine + " got : " + sig[0].ToString(16)); } if (!s.Equals(sig[1])) { return new SimpleTestResult(false, Name + ": s component wrong." + SimpleTest.NewLine + " expecting: " + s.ToString(16) + SimpleTest.NewLine + " got : " + sig[1].ToString(16)); } Gost3410.Init(false, pair.Public); if (Gost3410.VerifySignature(hashmessage, sig[0], sig[1])) { return new SimpleTestResult(true, Name + ": Okay"); } else { return new SimpleTestResult(false, Name + ": verification fails"); } } } private class Gost3410_BParam : ITest { public string Name { get { return "Gost3410-BParam"; } } private class SecureRandomImpl10 : SecureRandom { bool firstLong = true; public override long NextLong() { string x0 = "0x5B977CDB"; string c = "0x6E9692DD"; if (firstLong) { firstLong = false; return NumberParsing.DecodeLongFromHex(x0); } return NumberParsing.DecodeLongFromHex(c); } public override void NextBytes(byte[] bytes) { byte[] d = Hex.Decode("bc3cbbdb7e6f848286e19ad9a27a8e297e5b71c53dd974cdf60f937356df69cbc97a300ccc71685c553046147f11568c4fddf363d9d886438345a62c3b75963d6546adfabf31b31290d12cae65ecb8309ef66782"); Array.Copy(d, 0, bytes, bytes.Length-d.Length, d.Length); } }; SecureRandom init_random = new SecureRandomImpl10(); private class SecureRandomImpl11 : SecureRandom { public override void NextBytes(byte[] bytes) { byte[] k = Hex.Decode("90F3A564439242F5186EBB224C8E223811B7105C64E4F5390807E6362DF4C72A"); int i; for (i = 0; i < (bytes.Length - k.Length); i += k.Length) { Array.Copy(k, 0, bytes, i, k.Length); } if (i > bytes.Length) { Array.Copy(k, 0, bytes, i - k.Length, bytes.Length - (i - k.Length)); } else { Array.Copy(k, 0, bytes, i, bytes.Length - i); } } }; SecureRandom random = new SecureRandomImpl11(); private class SecureRandomImpl12 : SecureRandom { public override void NextBytes(byte[] bytes) { byte[] x = Hex.Decode("3036314538303830343630454235324435324234314132373832433138443046"); int i; for (i = 0; i < (bytes.Length - x.Length); i += x.Length) { Array.Copy(x, 0, bytes, i, x.Length); } if (i > bytes.Length) { Array.Copy(x, 0, bytes, i - x.Length, bytes.Length - (i - x.Length)); } else { Array.Copy(x, 0, bytes, i, bytes.Length - i); } } }; SecureRandom keyRandom = new SecureRandomImpl12(); BigInteger pValue = new BigInteger("c6971fc57524b30c9018c5e621de15499736854f56a6f8aee65a7a404632b3540f09020f67f04dc2e6783b141dceffd21a703035b7d0187c6e12cb4229922bafdb2225b73e6b23a0de36e20047065aea000c1a374283d0ad8dc1981e3995f0bb8c72526041fcb98ae6163e1e71a669d8364e9c4c3188f673c5f8ee6fadb41abf", 16); BigInteger qValue = new BigInteger("b09d634c10899cd7d4c3a7657403e05810b07c61a688bab2c37f475e308b0607", 16); public ITestResult Perform() { BigInteger r = new BigInteger("860d82c60e9502cd00c0e9e1f6563feafec304801974d745c5e02079946f729e",16); BigInteger s = new BigInteger("7ef49264ef022801aaa03033cd97915235fbab4c823ed936b0f360c22114688a",16); Gost3410ParametersGenerator pGen = new Gost3410ParametersGenerator(); pGen.Init(1024, 2, init_random); Gost3410Parameters parameters = pGen.GenerateParameters(); if (!pValue.Equals(parameters.P) || !qValue.Equals(parameters.Q)) { return new SimpleTestResult(false, Name + ": p or q wrong"); } Gost3410KeyPairGenerator Gost3410KeyGen = new Gost3410KeyPairGenerator(); Gost3410KeyGenerationParameters genParam = new Gost3410KeyGenerationParameters(keyRandom, parameters); Gost3410KeyGen.Init(genParam); AsymmetricCipherKeyPair pair = Gost3410KeyGen.GenerateKeyPair(); ParametersWithRandom param = new ParametersWithRandom(pair.Private, random); Gost3410Signer Gost3410 = new Gost3410Signer(); Gost3410.Init(true, param); BigInteger[] sig = Gost3410.GenerateSignature(hashmessage); if (!r.Equals(sig[0])) { return new SimpleTestResult(false, Name + ": r component wrong." + SimpleTest.NewLine + " expecting: " + r.ToString(16) + SimpleTest.NewLine + " got : " + sig[0].ToString(16)); } if (!s.Equals(sig[1])) { return new SimpleTestResult(false, Name + ": s component wrong." + SimpleTest.NewLine + " expecting: " + s.ToString(16) + SimpleTest.NewLine + " got : " + sig[1].ToString(16)); } Gost3410.Init(false, pair.Public); if (Gost3410.VerifySignature(hashmessage, sig[0], sig[1])) { return new SimpleTestResult(true, Name + ": Okay"); } else { return new SimpleTestResult(false, Name + ": verification fails"); } } } private class Gost3410_CParam : ITest { public string Name { get { return "Gost3410-CParam"; } } private class SecureRandomImpl13 : SecureRandom { bool firstLong = true; public override long NextLong() { string x0 = "0x43848744"; string c = "0xB50A826D"; if (firstLong) { firstLong = false; return NumberParsing.DecodeLongFromHex(x0); } return NumberParsing.DecodeLongFromHex(c); } public override void NextBytes(byte[] bytes) { byte[] d = Hex.Decode("7F575E8194BC5BDF"); Array.Copy(d, 0, bytes, bytes.Length-d.Length, d.Length); } }; SecureRandom init_random = new SecureRandomImpl13(); private class SecureRandomImpl14 : SecureRandom { public override void NextBytes(byte[] bytes) { byte[] k = Hex.Decode("90F3A564439242F5186EBB224C8E223811B7105C64E4F5390807E6362DF4C72A"); int i; for (i = 0; i < (bytes.Length - k.Length); i += k.Length) { Array.Copy(k, 0, bytes, i, k.Length); } if (i > bytes.Length) { Array.Copy(k, 0, bytes, i - k.Length, bytes.Length - (i - k.Length)); } else { Array.Copy(k, 0, bytes, i, bytes.Length - i); } } }; SecureRandom random = new SecureRandomImpl14(); private class SecureRandomImpl15 : SecureRandom { public override void NextBytes(byte[] bytes) { byte[] x = Hex.Decode("3036314538303830343630454235324435324234314132373832433138443046"); int i; for (i = 0; i < (bytes.Length - x.Length); i += x.Length) { Array.Copy(x, 0, bytes, i, x.Length); } if (i > bytes.Length) { Array.Copy(x, 0, bytes, i - x.Length, bytes.Length - (i - x.Length)); } else { Array.Copy(x, 0, bytes, i, bytes.Length - i); } } }; SecureRandom keyRandom = new SecureRandomImpl15(); BigInteger pValue = new BigInteger("9d88e6d7fe3313bd2e745c7cdd2ab9ee4af3c8899e847de74a33783ea68bc30588ba1f738c6aaf8ab350531f1854c3837cc3c860ffd7e2e106c3f63b3d8a4c034ce73942a6c3d585b599cf695ed7a3c4a93b2b947b7157bb1a1c043ab41ec8566c6145e938a611906de0d32e562494569d7e999a0dda5c879bdd91fe124df1e9", 16); BigInteger qValue = new BigInteger("fadd197abd19a1b4653eecf7eca4d6a22b1f7f893b641f901641fbb555354faf", 16); public ITestResult Perform() { BigInteger r = new BigInteger("4deb95a0b35e7ed7edebe9bef5a0f93739e16b7ff27fe794d989d0c13159cfbc",16); BigInteger s = new BigInteger("e1d0d30345c24cfeb33efde3deee5fbbda78ddc822b719d860cd0ba1fb6bd43b",16); Gost3410ParametersGenerator pGen = new Gost3410ParametersGenerator(); pGen.Init(1024, 2, init_random); Gost3410Parameters parameters = pGen.GenerateParameters(); if (!pValue.Equals(parameters.P) || !qValue.Equals(parameters.Q)) { return new SimpleTestResult(false, Name + ": p or q wrong"); } Gost3410KeyPairGenerator Gost3410KeyGen = new Gost3410KeyPairGenerator(); Gost3410KeyGenerationParameters genParam = new Gost3410KeyGenerationParameters(keyRandom, parameters); Gost3410KeyGen.Init(genParam); AsymmetricCipherKeyPair pair = Gost3410KeyGen.GenerateKeyPair(); ParametersWithRandom param = new ParametersWithRandom(pair.Private, random); Gost3410Signer Gost3410 = new Gost3410Signer(); Gost3410.Init(true, param); BigInteger[] sig = Gost3410.GenerateSignature(hashmessage); if (!r.Equals(sig[0])) { return new SimpleTestResult(false, Name + ": r component wrong." + SimpleTest.NewLine + " expecting: " + r.ToString(16) + SimpleTest.NewLine + " got : " + sig[0].ToString(16)); } if (!s.Equals(sig[1])) { return new SimpleTestResult(false, Name + ": s component wrong." + SimpleTest.NewLine + " expecting: " + s.ToString(16) + SimpleTest.NewLine + " got : " + sig[1].ToString(16)); } Gost3410.Init(false, pair.Public); if (Gost3410.VerifySignature(hashmessage, sig[0], sig[1])) { return new SimpleTestResult(true, Name + ": Okay"); } else { return new SimpleTestResult(false, Name + ": verification fails"); } } } private class Gost3410_DParam : ITest { public string Name { get { return "Gost3410-DParam"; } } private class SecureRandomImpl16 : SecureRandom { bool firstLong = true; public override long NextLong() { string x0 = "0x13DA8B9D"; string c = "0xA0E9DE4B"; if (firstLong) { firstLong = false; return NumberParsing.DecodeLongFromHex(x0); } return NumberParsing.DecodeLongFromHex(c); } public override void NextBytes(byte[] bytes) { byte[] d = Hex.Decode("41ab97857f42614355d32db0b1069f109a4da283676c7c53a68185b4"); Array.Copy(d, 0, bytes, bytes.Length-d.Length, d.Length); } }; SecureRandom init_random = new SecureRandomImpl16(); private class SecureRandomImpl17 : SecureRandom { public override void NextBytes(byte[] bytes) { byte[] k = Hex.Decode("90F3A564439242F5186EBB224C8E223811B7105C64E4F5390807E6362DF4C72A"); int i; for (i = 0; i < (bytes.Length - k.Length); i += k.Length) { Array.Copy(k, 0, bytes, i, k.Length); } if (i > bytes.Length) { Array.Copy(k, 0, bytes, i - k.Length, bytes.Length - (i - k.Length)); } else { Array.Copy(k, 0, bytes, i, bytes.Length - i); } } }; SecureRandom random = new SecureRandomImpl17(); private class SecureRandomImpl18 : SecureRandom { public override void NextBytes(byte[] bytes) { byte[] x = Hex.Decode("3036314538303830343630454235324435324234314132373832433138443046"); int i; for (i = 0; i < (bytes.Length - x.Length); i += x.Length) { Array.Copy(x, 0, bytes, i, x.Length); } if (i > bytes.Length) { Array.Copy(x, 0, bytes, i - x.Length, bytes.Length - (i - x.Length)); } else { Array.Copy(x, 0, bytes, i, bytes.Length - i); } } }; SecureRandom keyRandom = new SecureRandomImpl18(); BigInteger pValue = new BigInteger("80f102d32b0fd167d069c27a307adad2c466091904dbaa55d5b8cc7026f2f7a1919b890cb652c40e054e1e9306735b43d7b279eddf9102001cd9e1a831fe8a163eed89ab07cf2abe8242ac9dedddbf98d62cddd1ea4f5f15d3a42a6677bdd293b24260c0f27c0f1d15948614d567b66fa902baa11a69ae3bceadbb83e399c9b5", 16); BigInteger qValue = new BigInteger("f0f544c418aac234f683f033511b65c21651a6078bda2d69bb9f732867502149", 16); public ITestResult Perform() { BigInteger r = new BigInteger("712592d285b792e33b8a9a11e8e6c4f512ddf0042972bbfd1abb0a93e8fc6f54",16); BigInteger s = new BigInteger("2cf26758321258b130d5612111339f09ceb8668241f3482e38baa56529963f07",16); Gost3410ParametersGenerator pGen = new Gost3410ParametersGenerator(); pGen.Init(1024, 2, init_random); Gost3410Parameters parameters = pGen.GenerateParameters(); if (!pValue.Equals(parameters.P) || !qValue.Equals(parameters.Q)) { return new SimpleTestResult(false, Name + ": p or q wrong"); } Gost3410KeyPairGenerator Gost3410KeyGen = new Gost3410KeyPairGenerator(); Gost3410KeyGenerationParameters genParam = new Gost3410KeyGenerationParameters(keyRandom, parameters); Gost3410KeyGen.Init(genParam); AsymmetricCipherKeyPair pair = Gost3410KeyGen.GenerateKeyPair(); ParametersWithRandom param = new ParametersWithRandom(pair.Private, random); Gost3410Signer Gost3410 = new Gost3410Signer(); Gost3410.Init(true, param); BigInteger[] sig = Gost3410.GenerateSignature(hashmessage); if (!r.Equals(sig[0])) { return new SimpleTestResult(false, Name + ": r component wrong." + SimpleTest.NewLine + " expecting: " + r.ToString(16) + SimpleTest.NewLine + " got : " + sig[0].ToString(16)); } if (!s.Equals(sig[1])) { return new SimpleTestResult(false, Name + ": s component wrong." + SimpleTest.NewLine + " expecting: " + s.ToString(16) + SimpleTest.NewLine + " got : " + sig[1].ToString(16)); } Gost3410.Init(false, pair.Public); if (Gost3410.VerifySignature(hashmessage, sig[0], sig[1])) { return new SimpleTestResult(true, Name + ": Okay"); } else { return new SimpleTestResult(false, Name + ": verification fails"); } } } private class Gost3410_AExParam : ITest { public string Name { get { return "Gost3410-AExParam"; } } private class SecureRandomImpl19 : SecureRandom { bool firstLong = true; public override long NextLong() { string x0 = "0xD05E9F14"; string c = "0x46304C5F"; if (firstLong) { firstLong = false; return NumberParsing.DecodeLongFromHex(x0); } return NumberParsing.DecodeLongFromHex(c); } public override void NextBytes(byte[] bytes) { byte[] d = Hex.Decode("35ab875399cda33c146ca629660e5a5e5c07714ca326db032dd6751995cdb90a612b9228932d8302704ec24a5def7739c5813d83"); Array.Copy(d, 0, bytes, bytes.Length-d.Length, d.Length); } }; SecureRandom init_random = new SecureRandomImpl19(); private class SecureRandomImpl20 : SecureRandom { public override void NextBytes(byte[] bytes) { byte[] k = Hex.Decode("90F3A564439242F5186EBB224C8E223811B7105C64E4F5390807E6362DF4C72A"); int i; for (i = 0; i < (bytes.Length - k.Length); i += k.Length) { Array.Copy(k, 0, bytes, i, k.Length); } if (i > bytes.Length) { Array.Copy(k, 0, bytes, i - k.Length, bytes.Length - (i - k.Length)); } else { Array.Copy(k, 0, bytes, i, bytes.Length - i); } } }; SecureRandom random = new SecureRandomImpl20(); private class SecureRandomImpl21 : SecureRandom { public override void NextBytes(byte[] bytes) { byte[] x = Hex.Decode("3036314538303830343630454235324435324234314132373832433138443046"); int i; for (i = 0; i < (bytes.Length - x.Length); i += x.Length) { Array.Copy(x, 0, bytes, i, x.Length); } if (i > bytes.Length) { Array.Copy(x, 0, bytes, i - x.Length, bytes.Length - (i - x.Length)); } else { Array.Copy(x, 0, bytes, i, bytes.Length - i); } } }; SecureRandom keyRandom = new SecureRandomImpl21(); BigInteger pValue = new BigInteger("ca3b3f2eee9fd46317d49595a9e7518e6c63d8f4eb4d22d10d28af0b8839f079f8289e603b03530784b9bb5a1e76859e4850c670c7b71c0df84ca3e0d6c177fe9f78a9d8433230a883cd82a2b2b5c7a3306980278570cdb79bf01074a69c9623348824b0c53791d53c6a78cab69e1cfb28368611a397f50f541e16db348dbe5f", 16); BigInteger qValue = new BigInteger("cae4d85f80c147704b0ca48e85fb00a9057aa4acc44668e17f1996d7152690d9", 16); public ITestResult Perform() { BigInteger r = new BigInteger("90892707282f433398488f19d31ac48523a8e2ded68944e0da91c6895ee7045e",16); BigInteger s = new BigInteger("3be4620ee88f1ee8f9dd63c7d145b7e554839feeca125049118262ea4651e9de",16); Gost3410ParametersGenerator pGen = new Gost3410ParametersGenerator(); pGen.Init(1024, 2, init_random); Gost3410Parameters parameters = pGen.GenerateParameters(); if (!pValue.Equals(parameters.P) || !qValue.Equals(parameters.Q)) { return new SimpleTestResult(false, Name + ": p or q wrong"); } Gost3410KeyPairGenerator Gost3410KeyGen = new Gost3410KeyPairGenerator(); Gost3410KeyGenerationParameters genParam = new Gost3410KeyGenerationParameters(keyRandom, parameters); Gost3410KeyGen.Init(genParam); AsymmetricCipherKeyPair pair = Gost3410KeyGen.GenerateKeyPair(); ParametersWithRandom param = new ParametersWithRandom(pair.Private, random); Gost3410Signer Gost3410 = new Gost3410Signer(); Gost3410.Init(true, param); BigInteger[] sig = Gost3410.GenerateSignature(hashmessage); if (!r.Equals(sig[0])) { return new SimpleTestResult(false, Name + ": r component wrong." + SimpleTest.NewLine + " expecting: " + r.ToString(16) + SimpleTest.NewLine + " got : " + sig[0].ToString(16)); } if (!s.Equals(sig[1])) { return new SimpleTestResult(false, Name + ": s component wrong." + SimpleTest.NewLine + " expecting: " + s.ToString(16) + SimpleTest.NewLine + " got : " + sig[1].ToString(16)); } Gost3410.Init(false, pair.Public); if (Gost3410.VerifySignature(hashmessage, sig[0], sig[1])) { return new SimpleTestResult(true, Name + ": Okay"); } else { return new SimpleTestResult(false, Name + ": verification fails"); } } } private class Gost3410_BExParam : ITest { public string Name { get { return "Gost3410-BExParam"; } } private class SecureRandomImpl22 : SecureRandom { bool firstLong = true; public override long NextLong() { string x0 = "0x7A007804"; string c = "0xD31A4FF7"; if (firstLong) { firstLong = false; return NumberParsing.DecodeLongFromHex(x0); } return NumberParsing.DecodeLongFromHex(c); } public override void NextBytes(byte[] bytes) { byte[] d = Hex.Decode("7ec123d161477762838c2bea9dbdf33074af6d41d108a066a1e7a07ab3048de2"); Array.Copy(d, 0, bytes, bytes.Length-d.Length, d.Length); } }; SecureRandom init_random = new SecureRandomImpl22(); private class SecureRandomImpl23 : SecureRandom { public override void NextBytes(byte[] bytes) { byte[] k = Hex.Decode("90F3A564439242F5186EBB224C8E223811B7105C64E4F5390807E6362DF4C72A"); int i; for (i = 0; i < (bytes.Length - k.Length); i += k.Length) { Array.Copy(k, 0, bytes, i, k.Length); } if (i > bytes.Length) { Array.Copy(k, 0, bytes, i - k.Length, bytes.Length - (i - k.Length)); } else { Array.Copy(k, 0, bytes, i, bytes.Length - i); } } }; SecureRandom random = new SecureRandomImpl23(); private class SecureRandomImpl24 : SecureRandom { public override void NextBytes(byte[] bytes) { byte[] x = Hex.Decode("3036314538303830343630454235324435324234314132373832433138443046"); int i; for (i = 0; i < (bytes.Length - x.Length); i += x.Length) { Array.Copy(x, 0, bytes, i, x.Length); } if (i > bytes.Length) { Array.Copy(x, 0, bytes, i - x.Length, bytes.Length - (i - x.Length)); } else { Array.Copy(x, 0, bytes, i, bytes.Length - i); } } }; SecureRandom keyRandom = new SecureRandomImpl24(); BigInteger pValue = new BigInteger("9286dbda91eccfc3060aa5598318e2a639f5ba90a4ca656157b2673fb191cd0589ee05f4cef1bd13508408271458c30851ce7a4ef534742bfb11f4743c8f787b11193ba304c0e6bca25701bf88af1cb9b8fd4711d89f88e32b37d95316541bf1e5dbb4989b3df13659b88c0f97a3c1087b9f2d5317d557dcd4afc6d0a754e279", 16); BigInteger qValue = new BigInteger("c966e9b3b8b7cdd82ff0f83af87036c38f42238ec50a876cd390e43d67b6013f", 16); public ITestResult Perform() { BigInteger r = new BigInteger("8f79a582513df84dc247bcb624340cc0e5a34c4324a20ce7fe3ab8ff38a9db71",16); BigInteger s = new BigInteger("7508d22fd6cbb45efd438cb875e43f137247088d0f54b29a7c91f68a65b5fa85",16); Gost3410ParametersGenerator pGen = new Gost3410ParametersGenerator(); pGen.Init(1024, 2, init_random); Gost3410Parameters parameters = pGen.GenerateParameters(); if (!pValue.Equals(parameters.P) || !qValue.Equals(parameters.Q)) { return new SimpleTestResult(false, Name + ": p or q wrong"); } Gost3410KeyPairGenerator Gost3410KeyGen = new Gost3410KeyPairGenerator(); Gost3410KeyGenerationParameters genParam = new Gost3410KeyGenerationParameters(keyRandom, parameters); Gost3410KeyGen.Init(genParam); AsymmetricCipherKeyPair pair = Gost3410KeyGen.GenerateKeyPair(); ParametersWithRandom param = new ParametersWithRandom(pair.Private, random); Gost3410Signer Gost3410 = new Gost3410Signer(); Gost3410.Init(true, param); BigInteger[] sig = Gost3410.GenerateSignature(hashmessage); if (!r.Equals(sig[0])) { return new SimpleTestResult(false, Name + ": r component wrong." + SimpleTest.NewLine + " expecting: " + r.ToString(16) + SimpleTest.NewLine + " got : " + sig[0].ToString(16)); } if (!s.Equals(sig[1])) { return new SimpleTestResult(false, Name + ": s component wrong." + SimpleTest.NewLine + " expecting: " + s.ToString(16) + SimpleTest.NewLine + " got : " + sig[1].ToString(16)); } Gost3410.Init(false, pair.Public); if (Gost3410.VerifySignature(hashmessage, sig[0], sig[1])) { return new SimpleTestResult(true, Name + ": Okay"); } else { return new SimpleTestResult(false, Name + ": verification fails"); } } } private class Gost3410_CExParam : ITest { public string Name { get { return "Gost3410-CExParam"; } } private class SecureRandomImpl25 : SecureRandom { bool firstLong = true; public override long NextLong() { string x0 = "0x162AB910"; string c = "0x93F828D3"; if (firstLong) { firstLong = false; return NumberParsing.DecodeLongFromHex(x0); } return NumberParsing.DecodeLongFromHex(c); } public override void NextBytes(byte[] bytes) { byte[] d = Hex.Decode("ca82cce78a738bc46f103d53b9bf809745ec845e4f6da462606c51f60ecf302e31204b81"); Array.Copy(d, 0, bytes, bytes.Length-d.Length, d.Length); } }; SecureRandom init_random = new SecureRandomImpl25(); private class SecureRandomImpl26 : SecureRandom { public override void NextBytes(byte[] bytes) { byte[] k = Hex.Decode("90F3A564439242F5186EBB224C8E223811B7105C64E4F5390807E6362DF4C72A"); int i; for (i = 0; i < (bytes.Length - k.Length); i += k.Length) { Array.Copy(k, 0, bytes, i, k.Length); } if (i > bytes.Length) { Array.Copy(k, 0, bytes, i - k.Length, bytes.Length - (i - k.Length)); } else { Array.Copy(k, 0, bytes, i, bytes.Length - i); } } }; SecureRandom random = new SecureRandomImpl26(); private class SecureRandomImpl27 : SecureRandom { public override void NextBytes(byte[] bytes) { byte[] x = Hex.Decode("3036314538303830343630454235324435324234314132373832433138443046"); int i; for (i = 0; i < (bytes.Length - x.Length); i += x.Length) { Array.Copy(x, 0, bytes, i, x.Length); } if (i > bytes.Length) { Array.Copy(x, 0, bytes, i - x.Length, bytes.Length - (i - x.Length)); } else { Array.Copy(x, 0, bytes, i, bytes.Length - i); } } }; SecureRandom keyRandom = new SecureRandomImpl27(); BigInteger pValue = new BigInteger("b194036ace14139d36d64295ae6c50fc4b7d65d8b340711366ca93f383653908ee637be428051d86612670ad7b402c09b820fa77d9da29c8111a8496da6c261a53ed252e4d8a69a20376e6addb3bdcd331749a491a184b8fda6d84c31cf05f9119b5ed35246ea4562d85928ba1136a8d0e5a7e5c764ba8902029a1336c631a1d", 16); BigInteger qValue = new BigInteger("96120477df0f3896628e6f4a88d83c93204c210ff262bccb7dae450355125259", 16); public ITestResult Perform() { BigInteger r = new BigInteger("169fdb2dc09f690b71332432bfec806042e258fa9a21dafe73c6abfbc71407d9",16); BigInteger s = new BigInteger("9002551808ae40d19f6f31fb67e4563101243cf07cffd5f2f8ff4c537b0c9866",16); Gost3410ParametersGenerator pGen = new Gost3410ParametersGenerator(); pGen.Init(1024, 2, init_random); Gost3410Parameters parameters = pGen.GenerateParameters(); if (!pValue.Equals(parameters.P) || !qValue.Equals(parameters.Q)) { return new SimpleTestResult(false, Name + ": p or q wrong"); } Gost3410KeyPairGenerator Gost3410KeyGen = new Gost3410KeyPairGenerator(); Gost3410KeyGenerationParameters genParam = new Gost3410KeyGenerationParameters(keyRandom, parameters); Gost3410KeyGen.Init(genParam); AsymmetricCipherKeyPair pair = Gost3410KeyGen.GenerateKeyPair(); ParametersWithRandom param = new ParametersWithRandom(pair.Private, random); Gost3410Signer Gost3410 = new Gost3410Signer(); Gost3410.Init(true, param); BigInteger[] sig = Gost3410.GenerateSignature(hashmessage); if (!r.Equals(sig[0])) { return new SimpleTestResult(false, Name + ": r component wrong." + SimpleTest.NewLine + " expecting: " + r.ToString(16) + SimpleTest.NewLine + " got : " + sig[0].ToString(16)); } if (!s.Equals(sig[1])) { return new SimpleTestResult(false, Name + ": s component wrong." + SimpleTest.NewLine + " expecting: " + s.ToString(16) + SimpleTest.NewLine + " got : " + sig[1].ToString(16)); } Gost3410.Init(false, pair.Public); if (Gost3410.VerifySignature(hashmessage, sig[0], sig[1])) { return new SimpleTestResult(true, Name + ": Okay"); } else { return new SimpleTestResult(false, Name + ": verification fails"); } } } ITest[] tests = { new Gost3410_TEST1_512(), new Gost3410_TEST2_512(), // new Gost3410_TEST1_1024(), // new Gost3410_TEST2_1024(), // new Gost3410_AParam(), // new Gost3410_BParam(), // new Gost3410_CParam(), // new Gost3410_DParam(), // new Gost3410_AExParam(), // new Gost3410_BExParam(), // new Gost3410_CExParam() }; public string Name { get { return "Gost3410"; } } public ITestResult Perform() { for (int i = 0; i != tests.Length; i++) { ITestResult result = tests[i].Perform(); if (!result.IsSuccessful()) { return result; } } return new SimpleTestResult(true, "Gost3410: Okay"); } public static void Main( string[] args) { ITest test = new Gost3410Test(); ITestResult result = test.Perform(); Console.WriteLine(result); } [Test] public void TestFunction() { string resultText = Perform().ToString(); Assert.AreEqual(Name + ": Okay", resultText); } } }
using System; using System.Collections.Generic; using System.Linq; using MonoTouch.Dialog; using System.Web; #if __UNIFIED__ using Foundation; using UIKit; using CoreLocation; using CoreGraphics; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreLocation; using System.Drawing; using CGRect = global::System.Drawing.RectangleF; using CGSize = global::System.Drawing.SizeF; using CGPoint = global::System.Drawing.PointF; using nfloat = global::System.Single; using nint = global::System.Int32; using nuint = global::System.UInt32; #endif using MonoTouch.FacebookConnect; namespace FacebookiOSSample { public partial class DVCActions : DialogViewController { IFBGraphUser user; FBProfilePictureView pictureView; bool IsHiPosted = false; string HelloId = null; public DVCActions (IFBGraphUser facebookUser) : base (UITableViewStyle.Grouped, null, true) { this.user = facebookUser; pictureView = new FBProfilePictureView () { ProfileID = user.GetId() }; if (UIDevice.CurrentDevice.CheckSystemVersion (7,0)) { pictureView.Frame = new CGRect (120, 0, 80, 80); } else { pictureView.Frame = new CGRect (110, 0, 80, 80); } Root = new RootElement ("Menu") { new Section (){ new UIViewElement ("", pictureView, true) { Flags = UIViewElement.CellFlags.DisableSelection | UIViewElement.CellFlags.Transparent, } }, new Section () { new StringElement (user.GetName()) { Alignment = UITextAlignment.Center } }, new Section ("Actions") { new StringElement ("Share Xamarin.com", ShareUrl) { Alignment = UITextAlignment.Center }, new StringElement ("Graph API Sample - Post \"Hello\"", GraphApiPost) { Alignment = UITextAlignment.Center }, new StringElement ("Graph API Sample - Delete \"Hello\"", GraphApiDeletePost) { Alignment = UITextAlignment.Center }, new StringElement ("Select Some Friends", FriendPicker) { Alignment = UITextAlignment.Center }, new StringElement ("Select a Place", PlacePicker) { Alignment = UITextAlignment.Center } } }; } void ShareUrl () { // Here we must take into account several things like is Native Share Dialog // available, if not then is iOS6 integrated share dialog available. // So if we can't use native dialogs we can support either our own dialog or // Feed Dialog see (https://developers.facebook.com/docs/howtos/feed-dialog-using-ios-sdk/) var url = new NSUrl ("http://xamarin.com"); bool nativeShareDialog = FBDialogs.CanPresentShareDialog (new FBShareDialogParams () { Link = url }); bool ios6ShareDialog = FBDialogs.CanPresentOSIntegratedShareDialog (FBSession.ActiveSession); if (nativeShareDialog) { FBDialogs.PresentShareDialog (url, "Create iOS, Android, Mac\nand Windows apps in C#", (call, results, error) => { if (error != null) InvokeOnMainThread (() => new UIAlertView ("Error", error.Description, null, "Ok", null).Show ()); else if (results["completionGesture"] as NSString == "post") InvokeOnMainThread (() => new UIAlertView ("Success", "Posted on Facebook.\nPostId = " + (NSString)results["postId"], null, "Ok", null).Show ()); else if (results["completionGesture"] as NSString == "cancel") InvokeOnMainThread (() => new UIAlertView ("Cancelled", "User Cancelled Sharing", null, "Ok", null).Show ()); }); } else if (ios6ShareDialog) { FBDialogs.PresentOSIntegratedShareDialogModally (this, "Create iOS, Android, Mac and Windows apps in C#", null, new [] { url }, (result, error) => { if (error != null) InvokeOnMainThread (() => new UIAlertView ("Error", error.Description, null, "Ok", null).Show ()); else if (result == FBOSIntegratedShareDialogResult.Cancelled) InvokeOnMainThread (() => new UIAlertView ("Cancelled", "User cancelled", null, "Ok", null).Show ()); else if (result == FBOSIntegratedShareDialogResult.Succeeded) InvokeOnMainThread (() => new UIAlertView ("Success", "Successfully posted to Facebook", null, "Ok", null).Show ()); }); } else { // If we can't use native dialogs we use Feed Dialog see (https://developers.facebook.com/docs/howtos/feed-dialog-using-ios-sdk/) var data = new NSMutableDictionary (); data.Add (new NSString ("name"), new NSString ("Xamarin")); data.Add (new NSString ("caption"), new NSString ("Xamarin - cross platform that works")); data.Add (new NSString ("description"), new NSString ("Create iOS, Android, Mac and Windows apps in C#")); data.Add (new NSString ("link"), new NSString (url.AbsoluteString)); data.Add (new NSString ("picture"), new NSString ("http://xamarin.com/images/index/feature-cross-platform.png")); FBWebDialogs.PresentFeedDialogModally (null, data, (result, resultUrl, error) => { if (error != null) InvokeOnMainThread (() => new UIAlertView ("Error", error.Description, null, "Ok", null).Show ()); else if (result == FBWebDialogResult.NotCompleted) InvokeOnMainThread (() => new UIAlertView ("Error", "User canceled story publishing.", null, "Ok", null).Show ()); //User clicked the "x" icon else { // Handle the publish feed callback if (resultUrl.Query == null) InvokeOnMainThread (() => new UIAlertView ("Error", "User canceled story publishing.", null, "Ok", null).Show ()); else { var qstrings = HttpUtility.ParseQueryString (resultUrl.Query); var postId = qstrings["post_id"]; InvokeOnMainThread (() => new UIAlertView ("Success", "Posted story, Id:" + postId, null, "Ok", null).Show ()); } } }); } } void GraphApiPost () { if (IsHiPosted) { InvokeOnMainThread (() => new UIAlertView ("Error", "Hello already posted on your wall", null, "Ok", null).Show ()); return; } var data = new NSMutableDictionary (); data.Add (new NSString ("message"), new NSString ("Hello!")); // Ask for publish_actions permissions in context if (!FBSession.ActiveSession.Permissions.Contains ("publish_actions")) { // No permissions found in session, ask for it FBSession.ActiveSession.RequestNewPublishPermissions (new [] { "publish_actions" }, FBSessionDefaultAudience.Friends, (session, error) => { if (error != null) InvokeOnMainThread (() => new UIAlertView ("Error", error.Description, null, "Ok", null).Show ()); else { // If permissions granted, publish the story FBRequestConnection.StartWithGraphPath ("me/feed", data, "POST", (connection, result, err) => { if (err != null){ // Temporal validation until enums can inherit from new unified types (nint, nuint). FBErrorCode errorCode; if (IntPtr.Size == 8) errorCode = (FBErrorCode)(ulong)err.Code; else errorCode = (FBErrorCode)(uint)err.Code; InvokeOnMainThread (() => new UIAlertView ("Error", string.Format ("Error:\nDomain: {0}\nCode: {1}\nDescription: {3}", err.Domain, errorCode, err.Description), null, "Ok", null).Show ()); } else { HelloId = (result as FBGraphObject)["id"] as NSString; InvokeOnMainThread (() => new UIAlertView ("Success", "Posted Hello, MsgId: " + HelloId, null, "Ok", null).Show ()); IsHiPosted = true; } }); } }); } else { // If permissions is found, publish the story FBRequestConnection.StartWithGraphPath ("me/feed", data, "POST", (connection, result, err) => { if (err != null) { // Temporal validation until enums can inherit from new unified types (nint, nuint). FBErrorCode errorCode; if (IntPtr.Size == 8) errorCode = (FBErrorCode)(ulong)err.Code; else errorCode = (FBErrorCode)(uint)err.Code; InvokeOnMainThread (() => new UIAlertView ("Error", string.Format ("Error:\nDomain: {0}\nCode: {1}\nDescription: {3}", err.Domain, errorCode, err.Description), null, "Ok", null).Show ()); } else { HelloId = (result as FBGraphObject)["id"] as NSString; InvokeOnMainThread (() => new UIAlertView ("Success", "Posted Hello in your wall, MsgId: " + HelloId, null, "Ok", null).Show ()); IsHiPosted = true; } }); } } void GraphApiDeletePost () { if (!IsHiPosted) { new UIAlertView ("Error", "Please Post \"Hello\" to your wall first", null, "Ok", null).Show(); return; } FBRequestConnection.StartWithGraphPath (HelloId, null, "DELETE", (connection, result, err) => { if (err != null) { // Temporal validation until enums can inherit from new unified types (nint, nuint). FBErrorCode errorCode; if (IntPtr.Size == 8) errorCode = (FBErrorCode)(ulong)err.Code; else errorCode = (FBErrorCode)(uint)err.Code; InvokeOnMainThread (() => new UIAlertView ("Error", string.Format ("Error:\nDomain: {0}\nCode: {1}\nDescription: {2}", err.Domain, errorCode, err.Description), null, "Ok", null).Show ()); } else { HelloId = null; InvokeOnMainThread (() => new UIAlertView ("Success", "Deleted Hello from your wall", null, "Ok", null).Show ()); IsHiPosted = false; } }); } // Using Native Friend Picker Controller void FriendPicker () { var friendController = new FBFriendPickerViewController () { Title = "Pick some friends" }; friendController.LoadData (); friendController.PresentModallyFromViewController (this, true, (sender, donePressed) => { if (!donePressed) InvokeOnMainThread (() => new UIAlertView ("Error", "User canceled.", null, "Ok", null).Show ()); else { var ctrl = sender as FBFriendPickerViewController; foreach (var friend in ctrl.Selection) Console.WriteLine (friend.GetName ()); InvokeOnMainThread (() => new UIAlertView ("Success", "You Picked " + ctrl.Selection.Count () + " friend(s)", null, "Ok", null).Show ()); } }); } // Using native PlacePicker Controller void PlacePicker () { var placeController = new FBPlacePickerViewController () { Title = "Pick a place", LocationCoordinate = new CLLocationCoordinate2D (37.453827, -122.182187), // Hard code current location to Menlo Park, CA RadiusInMeters = 1000, // Configure the additional search parameters ResultsLimit = 50, SearchText = "Coffee" }; placeController.LoadData (); placeController.PresentModallyFromViewController (this, true, (sender, donePressed) => { if (!donePressed) InvokeOnMainThread (() => new UIAlertView ("Error", "User canceled.", null, "Ok", null).Show ()); else { var ctrl = sender as FBPlacePickerViewController; if (ctrl.Selection == null) { InvokeOnMainThread (() => new UIAlertView ("Hey!", "You haven't selected any place...", null, "Ok", null).Show ()); } else { InvokeOnMainThread (() => new UIAlertView ("Success", "You Picked " + ctrl.Selection.GetName(), null, "Ok", null).Show ()); } } }); } } }
#region S# License /****************************************************************************************** NOTICE!!! This program and source code is owned and licensed by StockSharp, LLC, www.stocksharp.com Viewing or use of this code requires your acceptance of the license agreement found at https://github.com/StockSharp/StockSharp/blob/master/LICENSE Removal of this comment is a violation of the license agreement. Project: StockSharp.Oanda.Oanda File: OandaMessageAdapter.cs Created: 2015, 11, 11, 2:32 PM Copyright 2010 by StockSharp, LLC *******************************************************************************************/ #endregion S# License namespace StockSharp.Oanda { using System; using Ecng.Common; using StockSharp.Localization; using StockSharp.Messages; using StockSharp.Oanda.Native; /// <summary> /// The messages adapter for OANDA (REST protocol). /// </summary> public partial class OandaMessageAdapter : MessageAdapter { private OandaRestClient _restClient; private OandaStreamingClient _streamigClient; /// <summary> /// Initializes a new instance of the <see cref="OandaMessageAdapter"/>. /// </summary> /// <param name="transactionIdGenerator">Transaction id generator.</param> public OandaMessageAdapter(IdGenerator transactionIdGenerator) : base(transactionIdGenerator) { HeartbeatInterval = TimeSpan.FromSeconds(60); this.AddMarketDataSupport(); this.AddTransactionalSupport(); } /// <summary> /// Create condition for order type <see cref="OrderTypes.Conditional"/>, that supports the adapter. /// </summary> /// <returns>Order condition. If the connection does not support the order type <see cref="OrderTypes.Conditional"/>, it will be returned <see langword="null" />.</returns> public override OrderCondition CreateOrderCondition() { return new OandaOrderCondition(); } /// <summary> /// Gets a value indicating whether the connector supports security lookup. /// </summary> protected override bool IsSupportNativeSecurityLookup => true; /// <summary> /// Gets a value indicating whether the connector supports position lookup. /// </summary> protected override bool IsSupportNativePortfolioLookup => true; private void StreamingClientDispose() { _streamigClient.NewError -= SendOutError; _streamigClient.NewTransaction -= SessionOnNewTransaction; _streamigClient.NewPrice -= SessionOnNewPrice; _streamigClient.Dispose(); } /// <summary> /// Send message. /// </summary> /// <param name="message">Message.</param> protected override void OnSendInMessage(Message message) { switch (message.Type) { case MessageTypes.Reset: { _accountIds.Clear(); if (_streamigClient != null) { try { StreamingClientDispose(); } catch (Exception ex) { SendOutError(ex); } _streamigClient = null; } _restClient = null; SendOutMessage(new ResetMessage()); break; } case MessageTypes.Connect: { if (_restClient != null) throw new InvalidOperationException(LocalizedStrings.Str1619); if (_streamigClient != null) throw new InvalidOperationException(LocalizedStrings.Str1619); _restClient = new OandaRestClient(Server, Token); _streamigClient = new OandaStreamingClient(Server, Token, GetAccountId); _streamigClient.NewError += SendOutError; _streamigClient.NewTransaction += SessionOnNewTransaction; _streamigClient.NewPrice += SessionOnNewPrice; SendOutMessage(new ConnectMessage()); break; } case MessageTypes.Disconnect: { if (_restClient == null) throw new InvalidOperationException(LocalizedStrings.Str1856); if (_streamigClient == null) throw new InvalidOperationException(LocalizedStrings.Str1856); StreamingClientDispose(); _streamigClient = null; _restClient = null; SendOutMessage(new DisconnectMessage()); break; } case MessageTypes.PortfolioLookup: { ProcessPortfolioLookupMessage((PortfolioLookupMessage)message); break; } case MessageTypes.Portfolio: { ProcessPortfolioMessage((PortfolioMessage)message); break; } case MessageTypes.OrderStatus: { ProcessOrderStatusMessage(); break; } case MessageTypes.Time: { //var timeMsg = (TimeMessage)message; //Session.RequestHeartbeat(new HeartbeatRequest(timeMsg.TransactionId), () => { }, CreateErrorHandler("RequestHeartbeat")); break; } case MessageTypes.OrderRegister: { ProcessOrderRegisterMessage((OrderRegisterMessage)message); break; } case MessageTypes.OrderCancel: { ProcessCancelMessage((OrderCancelMessage)message); break; } case MessageTypes.OrderReplace: { ProcessOrderReplaceMessage((OrderReplaceMessage)message); break; } case MessageTypes.SecurityLookup: { ProcessSecurityLookupMessage((SecurityLookupMessage)message); break; } case MessageTypes.MarketData: { ProcessMarketDataMessage((MarketDataMessage)message); break; } } } } }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // 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. // File System.Web.UI.WebControls.WebParts.PageCatalogPart.cs // Automatically generated contract file. using System.Collections.Generic; using System.IO; using System.Text; using System.Diagnostics.Contracts; using System; // Disable the "this variable is not used" warning as every field would imply it. #pragma warning disable 0414 // Disable the "this variable is never assigned to". #pragma warning disable 0067 // Disable the "this event is never assigned to". #pragma warning disable 0649 // Disable the "this variable is never used". #pragma warning disable 0169 // Disable the "new keyword not required" warning. #pragma warning disable 0109 // Disable the "extern without DllImport" warning. #pragma warning disable 0626 // Disable the "could hide other member" warning, can happen on certain properties. #pragma warning disable 0108 namespace System.Web.UI.WebControls.WebParts { sealed public partial class PageCatalogPart : CatalogPart { #region Methods and constructors public override WebPartDescriptionCollection GetAvailableWebPartDescriptions() { return default(WebPartDescriptionCollection); } public override WebPart GetWebPart(WebPartDescription description) { return default(WebPart); } protected internal override void OnInit(EventArgs e) { } protected internal override void OnPreRender(EventArgs e) { } public PageCatalogPart() { } protected internal override void Render(System.Web.UI.HtmlTextWriter writer) { } #endregion #region Properties and indexers public override string AccessKey { get { return default(string); } set { } } public override System.Drawing.Color BackColor { get { return default(System.Drawing.Color); } set { } } public override string BackImageUrl { get { return default(string); } set { } } public override System.Drawing.Color BorderColor { get { return default(System.Drawing.Color); } set { } } public override System.Web.UI.WebControls.BorderStyle BorderStyle { get { return default(System.Web.UI.WebControls.BorderStyle); } set { } } public override System.Web.UI.WebControls.Unit BorderWidth { get { return default(System.Web.UI.WebControls.Unit); } set { } } public override string CssClass { get { return default(string); } set { } } public override string DefaultButton { get { return default(string); } set { } } public override System.Web.UI.WebControls.ContentDirection Direction { get { return default(System.Web.UI.WebControls.ContentDirection); } set { } } public override bool Enabled { get { return default(bool); } set { } } public override bool EnableTheming { get { return default(bool); } set { } } public override System.Web.UI.WebControls.FontInfo Font { get { return default(System.Web.UI.WebControls.FontInfo); } } public override System.Drawing.Color ForeColor { get { return default(System.Drawing.Color); } set { } } public override string GroupingText { get { return default(string); } set { } } public override System.Web.UI.WebControls.Unit Height { get { return default(System.Web.UI.WebControls.Unit); } set { } } public override System.Web.UI.WebControls.HorizontalAlign HorizontalAlign { get { return default(System.Web.UI.WebControls.HorizontalAlign); } set { } } public override System.Web.UI.WebControls.ScrollBars ScrollBars { get { return default(System.Web.UI.WebControls.ScrollBars); } set { } } public override string SkinID { get { return default(string); } set { } } public override short TabIndex { get { return default(short); } set { } } public override string Title { get { return default(string); } set { } } public override string ToolTip { get { return default(string); } set { } } public override bool Visible { get { return default(bool); } set { } } public override System.Web.UI.WebControls.Unit Width { get { return default(System.Web.UI.WebControls.Unit); } set { } } public override bool Wrap { get { return default(bool); } set { } } #endregion } }
using System.Collections.Concurrent; using System.Collections.Generic; using Lucene.Net.Analysis; using Lucene.Net.Analysis.TokenAttributes; using Lucene.Net.Documents; using Lucene.Net.Index; using Lucene.Net.Spatial.Prefix.Tree; using Lucene.Net.Queries.Function; using Lucene.Net.Spatial.Queries; using Lucene.Net.Spatial.Util; using Spatial4n.Core.Shapes; namespace Lucene.Net.Spatial.Prefix { /* * 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> /// An abstract SpatialStrategy based on <see cref="Lucene.Net.Spatial.Prefix.Tree.SpatialPrefixTree"/>. The two /// subclasses are <see cref="RecursivePrefixTreeStrategy">RecursivePrefixTreeStrategy</see> and /// <see cref="TermQueryPrefixTreeStrategy">TermQueryPrefixTreeStrategy</see>. This strategy is most effective as a fast /// approximate spatial search filter. /// /// <h4>Characteristics:</h4> /// <list type="bullet"> /// <item><description>Can index any shape; however only /// <see cref="RecursivePrefixTreeStrategy">RecursivePrefixTreeStrategy</see> /// can effectively search non-point shapes.</description></item> /// <item><description>Can index a variable number of shapes per field value. This strategy /// can do it via multiple calls to <see cref="CreateIndexableFields(IShape)"/> /// for a document or by giving it some sort of Shape aggregate (e.g. NTS /// WKT MultiPoint). The shape's boundary is approximated to a grid precision. /// </description></item> /// <item><description>Can query with any shape. The shape's boundary is approximated to a grid /// precision.</description></item> /// <item><description>Only <see cref="SpatialOperation.Intersects"/> /// is supported. If only points are indexed then this is effectively equivalent /// to IsWithin.</description></item> /// <item><description>The strategy supports <see cref="MakeDistanceValueSource(IPoint, double)"/> /// even for multi-valued data, so long as the indexed data is all points; the /// behavior is undefined otherwise. However, <c>it will likely be removed in /// the future</c> in lieu of using another strategy with a more scalable /// implementation. Use of this call is the only /// circumstance in which a cache is used. The cache is simple but as such /// it doesn't scale to large numbers of points nor is it real-time-search /// friendly.</description></item> /// </list> /// /// <h4>Implementation:</h4> /// The <see cref="Lucene.Net.Spatial.Prefix.Tree.SpatialPrefixTree"/> /// does most of the work, for example returning /// a list of terms representing grids of various sizes for a supplied shape. /// An important /// configuration item is <see cref="DistErrPct"/> which balances /// shape precision against scalability. See those docs. /// /// @lucene.internal /// </summary> public abstract class PrefixTreeStrategy : SpatialStrategy { protected readonly SpatialPrefixTree m_grid; private readonly ConcurrentDictionary<string, PointPrefixTreeFieldCacheProvider> provider = new ConcurrentDictionary<string, PointPrefixTreeFieldCacheProvider>(); protected readonly bool m_simplifyIndexedCells; protected int m_defaultFieldValuesArrayLen = 2; protected double m_distErrPct = SpatialArgs.DEFAULT_DISTERRPCT;// [ 0 TO 0.5 ] public PrefixTreeStrategy(SpatialPrefixTree grid, string fieldName, bool simplifyIndexedCells) : base(grid.SpatialContext, fieldName) { this.m_grid = grid; this.m_simplifyIndexedCells = simplifyIndexedCells; } /// <summary> /// A memory hint used by <see cref="SpatialStrategy.MakeDistanceValueSource(IPoint)"/> /// for how big the initial size of each Document's array should be. The /// default is 2. Set this to slightly more than the default expected number /// of points per document. /// </summary> public virtual int DefaultFieldValuesArrayLen { get => m_defaultFieldValuesArrayLen; // LUCENENET NOTE: Added getter per MSDN guidelines set => m_defaultFieldValuesArrayLen = value; } /// <summary> /// The default measure of shape precision affecting shapes at index and query /// times. /// </summary> /// <remarks> /// The default measure of shape precision affecting shapes at index and query /// times. Points don't use this as they are always indexed at the configured /// maximum precision (<see cref="Lucene.Net.Spatial.Prefix.Tree.SpatialPrefixTree.MaxLevels"/>); /// this applies to all other shapes. Specific shapes at index and query time /// can use something different than this default value. If you don't set a /// default then the default is <see cref="SpatialArgs.DEFAULT_DISTERRPCT"/> -- /// 2.5%. /// </remarks> /// <seealso cref="Lucene.Net.Spatial.Queries.SpatialArgs.DistErrPct"/> public virtual double DistErrPct { get => m_distErrPct; set => m_distErrPct = value; } public override Field[] CreateIndexableFields(IShape shape) { double distErr = SpatialArgs.CalcDistanceFromErrPct(shape, m_distErrPct, m_ctx); return CreateIndexableFields(shape, distErr); } public virtual Field[] CreateIndexableFields(IShape shape, double distErr) { int detailLevel = m_grid.GetLevelForDistance(distErr); IList<Cell> cells = m_grid.GetCells(shape, detailLevel, true, m_simplifyIndexedCells);//intermediates cells //TODO is CellTokenStream supposed to be re-used somehow? see Uwe's comments: // http://code.google.com/p/lucene-spatial-playground/issues/detail?id=4 Field field = new Field(FieldName, new CellTokenStream(cells.GetEnumerator()), FIELD_TYPE); return new Field[] { field }; } /// <summary> /// Indexed, tokenized, not stored. /// </summary> public static readonly FieldType FIELD_TYPE = LoadFieldType(); private static FieldType LoadFieldType() // LUCENENET: Avoid static constructors (see https://github.com/apache/lucenenet/pull/224#issuecomment-469284006) { var fieldType = new FieldType { IsIndexed = true, IsTokenized = true, OmitNorms = true, IndexOptions = IndexOptions.DOCS_ONLY }; fieldType.Freeze(); return fieldType; } /// <summary>Outputs the tokenString of a cell, and if its a leaf, outputs it again with the leaf byte.</summary> internal sealed class CellTokenStream : TokenStream { private readonly ICharTermAttribute termAtt; private IEnumerator<Cell> iter = null; public CellTokenStream(IEnumerator<Cell> tokens) { this.iter = tokens; termAtt = AddAttribute<ICharTermAttribute>(); } internal string nextTokenStringNeedingLeaf = null; public override bool IncrementToken() { ClearAttributes(); if (nextTokenStringNeedingLeaf != null) { termAtt.Append(nextTokenStringNeedingLeaf); termAtt.Append((char)Cell.LEAF_BYTE); nextTokenStringNeedingLeaf = null; return true; } if (iter.MoveNext()) { Cell cell = iter.Current; string token = cell.TokenString; termAtt.Append(token); if (cell.IsLeaf) { nextTokenStringNeedingLeaf = token; } return true; } return false; } } public override ValueSource MakeDistanceValueSource(IPoint queryPoint, double multiplier) { var p = provider.GetOrAdd(FieldName, f => new PointPrefixTreeFieldCacheProvider(m_grid, FieldName, m_defaultFieldValuesArrayLen)); return new ShapeFieldCacheDistanceValueSource(m_ctx, p, queryPoint, multiplier); } public virtual SpatialPrefixTree Grid => m_grid; } }
//--------------------------------------------------------------------------- // // <copyright file="ModelVisual3D.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // // Description: // // History: // 6/9/2005 : [....] - Created // //--------------------------------------------------------------------------- using MS.Internal; using MS.Internal.Media; using MS.Internal.Media3D; using System; using System.Diagnostics; using System.Collections.Specialized; using System.ComponentModel; using System.Security; using System.Windows.Media.Composition; using System.Windows.Markup; using SR=MS.Internal.PresentationCore.SR; using SRID=MS.Internal.PresentationCore.SRID; namespace System.Windows.Media.Media3D { /// <summary> /// ModelVisual3D is a Visual3D which draws the given Model3D. /// ModelVisual3D is usable from Xaml. /// </summary> [ContentProperty("Children")] public class ModelVisual3D : Visual3D, IAddChild { //------------------------------------------------------ // // Constructors // //------------------------------------------------------ #region Constructors /// <summary> /// Default ctor /// </summary> public ModelVisual3D() { _children = new Visual3DCollection(this); } #endregion Constructors //------------------------------------------------------ // // Public Methods // //------------------------------------------------------ #region Public Methods /// <summary> /// Derived class must implement to support Visual children. The method must return /// the child at the specified index. Index must be between 0 and GetVisualChildrenCount-1. /// /// By default a Visual does not have any children. /// /// Remark: /// During this virtual call it is not valid to modify the Visual tree. /// </summary> protected sealed override Visual3D GetVisual3DChild(int index) { //VisualCollection does the range check for index return _children[index]; } /// <summary> /// Derived classes override this property to enable the Visual code to enumerate /// the Visual children. Derived classes need to return the number of children /// from this method. /// /// By default a Visual does not have any children. /// /// Remark: During this virtual method the Visual tree must not be modified. /// </summary> protected sealed override int Visual3DChildrenCount { get { return _children.Count; } } void IAddChild.AddChild(Object value) { if( value == null ) { throw new System.ArgumentNullException("value"); } Visual3D visual3D = value as Visual3D; if (visual3D == null) { throw new System.ArgumentException(SR.Get(SRID.Collection_BadType, this.GetType().Name, value.GetType().Name, typeof(Visual3D).Name)); } Children.Add(visual3D); } void IAddChild.AddText(string text) { // The only text we accept is whitespace, which we ignore. foreach (char c in text) { if (!Char.IsWhiteSpace(c)) { throw new System.InvalidOperationException(SR.Get(SRID.AddText_Invalid, this.GetType().Name)); } } } /// <summary> /// Children of this Visual3D /// </summary> [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] public Visual3DCollection Children { get { VerifyAPIReadOnly(); return _children; } } /// <summary> /// DependencyProperty which backs the ModelVisual3D.Content property. /// </summary> public static readonly DependencyProperty ContentProperty = DependencyProperty.Register( "Content", /* propertyType = */ typeof(Model3D), /* ownerType = */ typeof(ModelVisual3D), new PropertyMetadata(ContentPropertyChanged), (ValidateValueCallback) delegate { return MediaContext.CurrentMediaContext.WriteAccessEnabled; }); private static void ContentPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { ModelVisual3D owner = ((ModelVisual3D) d); // if it's not a subproperty change, then we need to change the protected Model property of Visual3D if (!e.IsASubPropertyChange) { owner.Visual3DModel = (Model3D)e.NewValue; } } /// <summary> /// The Model3D to render /// </summary> public Model3D Content { get { return (Model3D) GetValue(ContentProperty); } set { SetValue(ContentProperty, value); } } /// For binary compatability we need to keep the Transform DP and proprety here public static new readonly DependencyProperty TransformProperty = Visual3D.TransformProperty; /// <summary> /// Transform for this Visual3D. /// </summary> public new Transform3D Transform { get { return (Transform3D) GetValue(TransformProperty); } set { SetValue(TransformProperty, value); } } #endregion Public Methods //------------------------------------------------------ // // Public Properties // //------------------------------------------------------ //------------------------------------------------------ // // Public Events // //------------------------------------------------------ //------------------------------------------------------ // // Internal Methods // //------------------------------------------------------ //------------------------------------------------------ // // Private Fields // //------------------------------------------------------ #region Private Fields private readonly Visual3DCollection _children; #endregion Private Fields //------------------------------------------------------ // // Internal Fields // //------------------------------------------------------ #region Internal Fields #endregion Internal Fields } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq.Expressions; using NDatabase.Exceptions; namespace NDatabase.Core.Query.Linq { internal abstract class ExpressionTransformer { protected virtual Expression Visit(Expression exp) { if (exp == null) return null; switch (exp.NodeType) { case ExpressionType.Negate: case ExpressionType.NegateChecked: case ExpressionType.Not: case ExpressionType.Convert: case ExpressionType.ConvertChecked: case ExpressionType.ArrayLength: case ExpressionType.Quote: case ExpressionType.TypeAs: case ExpressionType.UnaryPlus: return VisitUnary((UnaryExpression) exp); case ExpressionType.Add: case ExpressionType.AddChecked: case ExpressionType.Subtract: case ExpressionType.SubtractChecked: case ExpressionType.Multiply: case ExpressionType.MultiplyChecked: case ExpressionType.Divide: case ExpressionType.Power: case ExpressionType.Modulo: case ExpressionType.And: case ExpressionType.AndAlso: case ExpressionType.Or: case ExpressionType.OrElse: case ExpressionType.LessThan: case ExpressionType.LessThanOrEqual: case ExpressionType.GreaterThan: case ExpressionType.GreaterThanOrEqual: case ExpressionType.Equal: case ExpressionType.NotEqual: case ExpressionType.Coalesce: case ExpressionType.ArrayIndex: case ExpressionType.RightShift: case ExpressionType.LeftShift: case ExpressionType.ExclusiveOr: return VisitBinary((BinaryExpression) exp); case ExpressionType.TypeIs: return VisitTypeIs((TypeBinaryExpression) exp); case ExpressionType.Conditional: return VisitConditional((ConditionalExpression) exp); case ExpressionType.Constant: return VisitConstant((ConstantExpression) exp); case ExpressionType.Parameter: return VisitParameter(exp); case ExpressionType.MemberAccess: return VisitMemberAccess((MemberExpression) exp); case ExpressionType.Call: return VisitMethodCall((MethodCallExpression) exp); case ExpressionType.Lambda: return VisitLambda((LambdaExpression) exp); case ExpressionType.New: return VisitNew((NewExpression) exp); case ExpressionType.NewArrayInit: case ExpressionType.NewArrayBounds: return VisitNewArray((NewArrayExpression) exp); case ExpressionType.Invoke: return VisitInvocation((InvocationExpression) exp); case ExpressionType.MemberInit: return VisitMemberInit((MemberInitExpression) exp); case ExpressionType.ListInit: return VisitListInit((ListInitExpression) exp); default: throw new LinqQueryException(string.Format("Unhandled expression type: '{0}'", exp.NodeType)); } } private MemberBinding VisitBinding(MemberBinding binding) { switch (binding.BindingType) { case MemberBindingType.Assignment: return VisitMemberAssignment((MemberAssignment) binding); case MemberBindingType.MemberBinding: return VisitMemberMemberBinding((MemberMemberBinding) binding); case MemberBindingType.ListBinding: return VisitMemberListBinding((MemberListBinding) binding); default: throw new LinqQueryException(string.Format("Unhandled binding type '{0}'", binding.BindingType)); } } private ElementInit VisitElementInitializer(ElementInit initializer) { var arguments = VisitExpressionList(initializer.Arguments); return arguments != initializer.Arguments ? Expression.ElementInit(initializer.AddMethod, arguments) : initializer; } protected virtual Expression VisitUnary(UnaryExpression u) { var operand = Visit(u.Operand); return operand != u.Operand ? Expression.MakeUnary(u.NodeType, operand, u.Type, u.Method) : u; } protected virtual Expression VisitBinary(BinaryExpression b) { var left = Visit(b.Left); var right = Visit(b.Right); var conversion = Visit(b.Conversion); if (left != b.Left || right != b.Right || conversion != b.Conversion) { return b.NodeType == ExpressionType.Coalesce ? Expression.Coalesce(left, right, conversion as LambdaExpression) : Expression.MakeBinary(b.NodeType, left, right, b.IsLiftedToNull, b.Method); } return b; } private Expression VisitTypeIs(TypeBinaryExpression b) { var expr = Visit(b.Expression); return expr != b.Expression ? Expression.TypeIs(expr, b.TypeOperand) : b; } protected virtual Expression VisitConstant(ConstantExpression c) { return c; } private Expression VisitConditional(ConditionalExpression c) { var test = Visit(c.Test); var ifTrue = Visit(c.IfTrue); var ifFalse = Visit(c.IfFalse); if (test != c.Test || ifTrue != c.IfTrue || ifFalse != c.IfFalse) return Expression.Condition(test, ifTrue, ifFalse); return c; } private static Expression VisitParameter(Expression p) { return p; } private Expression VisitMemberAccess(MemberExpression m) { var exp = Visit(m.Expression); return exp != m.Expression ? Expression.MakeMemberAccess(exp, m.Member) : m; } protected virtual Expression VisitMethodCall(MethodCallExpression m) { var obj = Visit(m.Object); IEnumerable<Expression> args = VisitExpressionList(m.Arguments); if (obj != m.Object || !Equals(args, m.Arguments)) return Expression.Call(obj, m.Method, args); return m; } protected ReadOnlyCollection<Expression> VisitExpressionList(ReadOnlyCollection<Expression> original) { var list = VisitList(original, Visit); return list == null ? original : new ReadOnlyCollection<Expression>(list); } private MemberAssignment VisitMemberAssignment(MemberAssignment assignment) { var e = Visit(assignment.Expression); return e != assignment.Expression ? Expression.Bind(assignment.Member, e) : assignment; } private MemberMemberBinding VisitMemberMemberBinding(MemberMemberBinding binding) { var bindings = VisitBindingList(binding.Bindings); return !Equals(bindings, binding.Bindings) ? Expression.MemberBind(binding.Member, bindings) : binding; } private MemberListBinding VisitMemberListBinding(MemberListBinding binding) { var initializers = VisitElementInitializerList(binding.Initializers); return !Equals(initializers, binding.Initializers) ? Expression.ListBind(binding.Member, initializers) : binding; } private IEnumerable<MemberBinding> VisitBindingList(ReadOnlyCollection<MemberBinding> original) { return VisitList(original, VisitBinding); } private IEnumerable<ElementInit> VisitElementInitializerList(ReadOnlyCollection<ElementInit> original) { return VisitList(original, VisitElementInitializer); } private static IList<TElement> VisitList<TElement>(ReadOnlyCollection<TElement> original, Func<TElement, TElement> visit) { List<TElement> list = null; for (int i = 0, n = original.Count; i < n; i++) { var element = visit(original[i]); if (list != null) { list.Add(element); } else if (!EqualityComparer<TElement>.Default.Equals(element, original[i])) { list = new List<TElement>(n); for (var j = 0; j < i; j++) { list.Add(original[j]); } list.Add(element); } } if (list != null) return list; return original; } protected virtual Expression VisitLambda(LambdaExpression lambda) { var body = Visit(lambda.Body); return body != lambda.Body ? Expression.Lambda(lambda.Type, body, lambda.Parameters) : lambda; } private NewExpression VisitNew(NewExpression nex) { IEnumerable<Expression> args = VisitExpressionList(nex.Arguments); return !Equals(args, nex.Arguments) ? Expression.New(nex.Constructor, args, nex.Members) : nex; } private Expression VisitMemberInit(MemberInitExpression init) { var n = VisitNew(init.NewExpression); var bindings = VisitBindingList(init.Bindings); if (n != init.NewExpression || !Equals(bindings, init.Bindings)) return Expression.MemberInit(n, bindings); return init; } private Expression VisitListInit(ListInitExpression init) { var n = VisitNew(init.NewExpression); var initializers = VisitElementInitializerList(init.Initializers); if (n != init.NewExpression || !Equals(initializers, init.Initializers)) return Expression.ListInit(n, initializers); return init; } private Expression VisitNewArray(NewArrayExpression na) { IEnumerable<Expression> exprs = VisitExpressionList(na.Expressions); if (!Equals(exprs, na.Expressions)) { return na.NodeType == ExpressionType.NewArrayInit ? Expression.NewArrayInit(na.Type.GetElementType(), exprs) : Expression.NewArrayBounds(na.Type.GetElementType(), exprs); } return na; } private Expression VisitInvocation(InvocationExpression iv) { IEnumerable<Expression> args = VisitExpressionList(iv.Arguments); var expr = Visit(iv.Expression); if (!Equals(args, iv.Arguments) || expr != iv.Expression) return Expression.Invoke(expr, args); return iv; } } }
using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using Moq; using NUnit.Framework; using SqlCE4Umbraco; using umbraco; using umbraco.businesslogic; using umbraco.cms.businesslogic; using Umbraco.Core; using Umbraco.Core.Cache; using Umbraco.Core.IO; using Umbraco.Core.Logging; using Umbraco.Core.Profiling; using Umbraco.Core.PropertyEditors; using umbraco.DataLayer; using umbraco.editorControls; using umbraco.interfaces; using umbraco.MacroEngines; using umbraco.uicontrols; using Umbraco.Web; using Umbraco.Web.PropertyEditors; namespace Umbraco.Tests.Plugins { [TestFixture] public class PluginManagerTests { private PluginManager _manager; [SetUp] public void Initialize() { //this ensures its reset _manager = new PluginManager(new ActivatorServiceProvider(), new NullCacheProvider(), new ProfilingLogger(Mock.Of<ILogger>(), Mock.Of<IProfiler>())); //for testing, we'll specify which assemblies are scanned for the PluginTypeResolver //TODO: Should probably update this so it only searches this assembly and add custom types to be found _manager.AssembliesToScan = new[] { this.GetType().Assembly, typeof(ApplicationStartupHandler).Assembly, typeof(SqlCEHelper).Assembly, typeof(CMSNode).Assembly, typeof(System.Guid).Assembly, typeof(NUnit.Framework.Assert).Assembly, typeof(Microsoft.CSharp.CSharpCodeProvider).Assembly, typeof(System.Xml.NameTable).Assembly, typeof(System.Configuration.GenericEnumConverter).Assembly, typeof(System.Web.SiteMap).Assembly, typeof(TabPage).Assembly, typeof(System.Web.Mvc.ActionResult).Assembly, typeof(TypeFinder).Assembly, typeof(ISqlHelper).Assembly, typeof(ICultureDictionary).Assembly, typeof(UmbracoContext).Assembly, typeof(BaseDataType).Assembly }; } [TearDown] public void TearDown() { _manager = null; } private DirectoryInfo PrepareFolder() { var assDir = new FileInfo(Assembly.GetExecutingAssembly().Location).Directory; var dir = Directory.CreateDirectory(Path.Combine(assDir.FullName, "PluginManager", Guid.NewGuid().ToString("N"))); foreach (var f in dir.GetFiles()) { f.Delete(); } return dir; } //[Test] //public void Scan_Vs_Load_Benchmark() //{ // var pluginManager = new PluginManager(false); // var watch = new Stopwatch(); // watch.Start(); // for (var i = 0; i < 1000; i++) // { // var type2 = Type.GetType("umbraco.macroCacheRefresh, umbraco, Version=1.0.4698.259, Culture=neutral, PublicKeyToken=null"); // var type3 = Type.GetType("umbraco.templateCacheRefresh, umbraco, Version=1.0.4698.259, Culture=neutral, PublicKeyToken=null"); // var type4 = Type.GetType("umbraco.presentation.cache.MediaLibraryRefreshers, umbraco, Version=1.0.4698.259, Culture=neutral, PublicKeyToken=null"); // var type5 = Type.GetType("umbraco.presentation.cache.pageRefresher, umbraco, Version=1.0.4698.259, Culture=neutral, PublicKeyToken=null"); // } // watch.Stop(); // Debug.WriteLine("TOTAL TIME (1st round): " + watch.ElapsedMilliseconds); // watch.Start(); // for (var i = 0; i < 1000; i++) // { // var type2 = BuildManager.GetType("umbraco.macroCacheRefresh, umbraco, Version=1.0.4698.259, Culture=neutral, PublicKeyToken=null", true); // var type3 = BuildManager.GetType("umbraco.templateCacheRefresh, umbraco, Version=1.0.4698.259, Culture=neutral, PublicKeyToken=null", true); // var type4 = BuildManager.GetType("umbraco.presentation.cache.MediaLibraryRefreshers, umbraco, Version=1.0.4698.259, Culture=neutral, PublicKeyToken=null", true); // var type5 = BuildManager.GetType("umbraco.presentation.cache.pageRefresher, umbraco, Version=1.0.4698.259, Culture=neutral, PublicKeyToken=null", true); // } // watch.Stop(); // Debug.WriteLine("TOTAL TIME (1st round): " + watch.ElapsedMilliseconds); // watch.Reset(); // watch.Start(); // for (var i = 0; i < 1000; i++) // { // var refreshers = pluginManager.ResolveTypes<ICacheRefresher>(false); // } // watch.Stop(); // Debug.WriteLine("TOTAL TIME (2nd round): " + watch.ElapsedMilliseconds); //} ////NOTE: This test shows that Type.GetType is 100% faster than Assembly.Load(..).GetType(...) so we'll use that :) //[Test] //public void Load_Type_Benchmark() //{ // var watch = new Stopwatch(); // watch.Start(); // for (var i = 0; i < 1000; i++) // { // var type2 = Type.GetType("umbraco.macroCacheRefresh, umbraco, Version=1.0.4698.259, Culture=neutral, PublicKeyToken=null"); // var type3 = Type.GetType("umbraco.templateCacheRefresh, umbraco, Version=1.0.4698.259, Culture=neutral, PublicKeyToken=null"); // var type4 = Type.GetType("umbraco.presentation.cache.MediaLibraryRefreshers, umbraco, Version=1.0.4698.259, Culture=neutral, PublicKeyToken=null"); // var type5 = Type.GetType("umbraco.presentation.cache.pageRefresher, umbraco, Version=1.0.4698.259, Culture=neutral, PublicKeyToken=null"); // } // watch.Stop(); // Debug.WriteLine("TOTAL TIME (1st round): " + watch.ElapsedMilliseconds); // watch.Reset(); // watch.Start(); // for (var i = 0; i < 1000; i++) // { // var type2 = Assembly.Load("umbraco, Version=1.0.4698.259, Culture=neutral, PublicKeyToken=null") // .GetType("umbraco.macroCacheRefresh"); // var type3 = Assembly.Load("umbraco, Version=1.0.4698.259, Culture=neutral, PublicKeyToken=null") // .GetType("umbraco.templateCacheRefresh"); // var type4 = Assembly.Load("umbraco, Version=1.0.4698.259, Culture=neutral, PublicKeyToken=null") // .GetType("umbraco.presentation.cache.MediaLibraryRefreshers"); // var type5 = Assembly.Load("umbraco, Version=1.0.4698.259, Culture=neutral, PublicKeyToken=null") // .GetType("umbraco.presentation.cache.pageRefresher"); // } // watch.Stop(); // Debug.WriteLine("TOTAL TIME (2nd round): " + watch.ElapsedMilliseconds); // watch.Reset(); // watch.Start(); // for (var i = 0; i < 1000; i++) // { // var type2 = BuildManager.GetType("umbraco.macroCacheRefresh, umbraco, Version=1.0.4698.259, Culture=neutral, PublicKeyToken=null", true); // var type3 = BuildManager.GetType("umbraco.templateCacheRefresh, umbraco, Version=1.0.4698.259, Culture=neutral, PublicKeyToken=null", true); // var type4 = BuildManager.GetType("umbraco.presentation.cache.MediaLibraryRefreshers, umbraco, Version=1.0.4698.259, Culture=neutral, PublicKeyToken=null", true); // var type5 = BuildManager.GetType("umbraco.presentation.cache.pageRefresher, umbraco, Version=1.0.4698.259, Culture=neutral, PublicKeyToken=null", true); // } // watch.Stop(); // Debug.WriteLine("TOTAL TIME (1st round): " + watch.ElapsedMilliseconds); //} [Test] public void Detect_Legacy_Plugin_File_List() { var tempFolder = IOHelper.MapPath("~/App_Data/TEMP/PluginCache"); var filePath= Path.Combine(tempFolder, string.Format("umbraco-plugins.{0}.list", NetworkHelper.FileSafeMachineName)); File.WriteAllText(filePath, @"<?xml version=""1.0"" encoding=""utf-8""?> <plugins> <baseType type=""umbraco.interfaces.ICacheRefresher""> <add type=""umbraco.macroCacheRefresh, umbraco, Version=6.0.0.0, Culture=neutral, PublicKeyToken=null"" /> </baseType> </plugins>"); Assert.IsEmpty(_manager.ReadCache()); // uber-legacy cannot be read File.Delete(filePath); File.WriteAllText(filePath, @"<?xml version=""1.0"" encoding=""utf-8""?> <plugins> <baseType type=""umbraco.interfaces.ICacheRefresher"" resolutionType=""FindAllTypes""> <add type=""umbraco.macroCacheRefresh, umbraco, Version=6.0.0.0, Culture=neutral, PublicKeyToken=null"" /> </baseType> </plugins>"); Assert.IsEmpty(_manager.ReadCache()); // legacy cannot be read File.Delete(filePath); File.WriteAllText(filePath, @"IContentFinder MyContentFinder AnotherContentFinder "); Assert.IsNotNull(_manager.ReadCache()); // works } [Test] public void Create_Cached_Plugin_File() { var types = new[] { typeof (PluginManager), typeof (PluginManagerTests), typeof (UmbracoContext) }; var typeList1 = new PluginManager.TypeList(typeof (object), null); foreach (var type in types) typeList1.Add(type); _manager.AddTypeList(typeList1); _manager.WriteCache(); var plugins = _manager.TryGetCached(typeof (object), null); var diffType = _manager.TryGetCached(typeof (object), typeof (ObsoleteAttribute)); Assert.IsTrue(plugins.Success); //this will be false since there is no cache of that type resolution kind Assert.IsFalse(diffType.Success); Assert.AreEqual(3, plugins.Result.Count()); var shouldContain = types.Select(x => x.AssemblyQualifiedName); //ensure they are all found Assert.IsTrue(plugins.Result.ContainsAll(shouldContain)); } [Test] public void Get_Plugins_Hash() { //Arrange var dir = PrepareFolder(); var d1 = dir.CreateSubdirectory("1"); var d2 = dir.CreateSubdirectory("2"); var d3 = dir.CreateSubdirectory("3"); var d4 = dir.CreateSubdirectory("4"); var f1 = new FileInfo(Path.Combine(d1.FullName, "test1.dll")); var f2 = new FileInfo(Path.Combine(d1.FullName, "test2.dll")); var f3 = new FileInfo(Path.Combine(d2.FullName, "test1.dll")); var f4 = new FileInfo(Path.Combine(d2.FullName, "test2.dll")); var f5 = new FileInfo(Path.Combine(d3.FullName, "test1.dll")); var f6 = new FileInfo(Path.Combine(d3.FullName, "test2.dll")); var f7 = new FileInfo(Path.Combine(d4.FullName, "test1.dll")); f1.CreateText().Close(); f2.CreateText().Close(); f3.CreateText().Close(); f4.CreateText().Close(); f5.CreateText().Close(); f6.CreateText().Close(); f7.CreateText().Close(); var list1 = new[] { f1, f2, f3, f4, f5, f6 }; var list2 = new[] { f1, f3, f5 }; var list3 = new[] { f1, f3, f5, f7 }; //Act var hash1 = PluginManager.GetFileHash(list1, new ProfilingLogger(Mock.Of<ILogger>(), Mock.Of<IProfiler>())); var hash2 = PluginManager.GetFileHash(list2, new ProfilingLogger(Mock.Of<ILogger>(), Mock.Of<IProfiler>())); var hash3 = PluginManager.GetFileHash(list3, new ProfilingLogger(Mock.Of<ILogger>(), Mock.Of<IProfiler>())); //Assert Assert.AreNotEqual(hash1, hash2); Assert.AreNotEqual(hash1, hash3); Assert.AreNotEqual(hash2, hash3); Assert.AreEqual(hash1, PluginManager.GetFileHash(list1, new ProfilingLogger(Mock.Of<ILogger>(), Mock.Of<IProfiler>()))); } [Test] public void Ensure_Only_One_Type_List_Created() { var foundTypes1 = _manager.ResolveFindMeTypes(); var foundTypes2 = _manager.ResolveFindMeTypes(); Assert.AreEqual(1, _manager.TypeLists.Count(x => x.BaseType == typeof(IFindMe) && x.AttributeType == null)); } [Test] public void Resolves_Assigned_Mappers() { var foundTypes1 = _manager.ResolveAssignedMapperTypes(); Assert.AreEqual(28, foundTypes1.Count()); } [Test] public void Resolves_Types() { var foundTypes1 = _manager.ResolveFindMeTypes(); Assert.AreEqual(2, foundTypes1.Count()); } [Test] public void Resolves_Attributed_Trees() { var trees = _manager.ResolveAttributedTrees(); // commit 6c5e35ec2cbfa31be6790d1228e0c2faf5f55bc8 brings the count down to 14 Assert.AreEqual(8, trees.Count()); } [Test] public void Resolves_Actions() { var actions = _manager.ResolveActions(); Assert.AreEqual(38, actions.Count()); } [Test] public void Resolves_Trees() { var trees = _manager.ResolveTrees(); Assert.AreEqual(35, trees.Count()); } [Test] public void Resolves_Applications() { var apps = _manager.ResolveApplications(); Assert.AreEqual(7, apps.Count()); } [Test] public void Resolves_DataTypes() { var types = _manager.ResolveDataTypes(); Assert.AreEqual(35, types.Count()); } [Test] public void Resolves_RazorDataTypeModels() { var types = _manager.ResolveRazorDataTypeModels(); Assert.AreEqual(2, types.Count()); } [Test] public void Resolves_RestExtensions() { var types = _manager.ResolveRestExtensions(); Assert.AreEqual(3, types.Count()); } [Test] public void Resolves_XsltExtensions() { var types = _manager.ResolveXsltExtensions(); Assert.AreEqual(3, types.Count()); } /// <summary> /// This demonstrates this issue: http://issues.umbraco.org/issue/U4-3505 - the TypeList was returning a list of assignable types /// not explicit types which is sort of ideal but is confusing so we'll do it the less confusing way. /// </summary> [Test] public void TypeList_Resolves_Explicit_Types() { var types = new HashSet<PluginManager.TypeList>(); var propEditors = new PluginManager.TypeList(typeof (PropertyEditor), null); propEditors.Add(typeof(LabelPropertyEditor)); types.Add(propEditors); var found = types.SingleOrDefault(x => x.BaseType == typeof (PropertyEditor) && x.AttributeType == null); Assert.IsNotNull(found); //This should not find a type list of this type var shouldNotFind = types.SingleOrDefault(x => x.BaseType == typeof (IParameterEditor) && x.AttributeType == null); Assert.IsNull(shouldNotFind); } [XsltExtension("Blah.Blah")] public class MyXsltExtension { } [Umbraco.Web.BaseRest.RestExtension("Blah")] public class MyRestExtesion { } public interface IFindMe : IDiscoverable { } public class FindMe1 : IFindMe { } public class FindMe2 : IFindMe { } } }
#region Apache Notice /***************************************************************************** * $Header: $ * $Revision: $ * $Date: $ * * iBATIS.NET Data Mapper * Copyright (C) 2004 - Gilles Bayon * * * 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.Text; using System.Collections.Specialized; using IBatisNet.DataMapper.Configuration.ParameterMapping; namespace IBatisNet.DataMapper.Configuration.Statements { /// <summary> /// Summary description for SqlGenerator. /// </summary> public class SqlGenerator { /// <summary> /// Creates SQL command text for a specified statement /// </summary> /// <param name="statement">The statement to build the SQL command text.</param> /// <returns>The SQL command text for the statement.</returns> public static string BuildQuery(IStatement statement) { string sqlText = string.Empty; if (statement is Select) { sqlText = BuildSelectQuery(statement); } else if (statement is Insert) { sqlText = BuildInsertQuery(statement); } else if (statement is Update) { sqlText = BuildUpdateQuery(statement); } else if (statement is Delete) { sqlText = BuildDeleteQuery(statement); } return sqlText; } /// <summary> /// Creates an select SQL command text for a specified statement /// </summary> /// <param name="statement">The statement to build the SQL command text.</param> /// <returns>The SQL command text for the statement.</returns> private static string BuildSelectQuery(IStatement statement) { StringBuilder output = new StringBuilder(); Select select = (Select) statement; int columnCount = statement.ParameterMap.PropertiesList.Count; output.Append("SELECT "); // Create the list of columns for (int i = 0; i < columnCount; i++) { ParameterProperty property = (ParameterProperty) statement.ParameterMap.PropertiesList[i]; if (i < (columnCount - 1)) { output.Append("\t" + property.ColumnName + " as "+property.PropertyName+","); } else { output.Append("\t" + property.ColumnName + " as "+property.PropertyName); } } output.Append(" FROM "); output.Append("\t" + select.Generate.Table + ""); // Create the where clause string [] compositeKeyList = select.Generate.By.Split(new Char [] {','}); if (compositeKeyList.Length > 0 && select.Generate.By.Length>0) { output.Append(" WHERE "); for (int i = 0; i < compositeKeyList.Length; i++) { string columnName = compositeKeyList[i]; if (i > 0) { output.Append("\tAND " + columnName + " = ?" ); } else { output.Append("\t" + columnName + " = ?" ); } } } // 'Select All' case if (statement.ParameterClass == null) { // The ParameterMap is just used to build the query // to avoid problems later, we set it to null statement.ParameterMap = null; } return output.ToString(); } /// <summary> /// Creates an insert SQL command text for a specified statement /// </summary> /// <param name="statement">The statement to build the SQL command text.</param> /// <returns>The SQL command text for the statement.</returns> private static string BuildInsertQuery(IStatement statement) { StringBuilder output = new StringBuilder(); Insert insert = (Insert) statement; int columnCount = statement.ParameterMap.PropertiesList.Count; output.Append("INSERT INTO " + insert.Generate.Table + " ("); // Create the parameter list for (int i = 0; i < columnCount; i++) { ParameterProperty property = (ParameterProperty) statement.ParameterMap.PropertiesList[i]; // Append the column name as a parameter of the insert statement if (i < (columnCount - 1)) { output.Append("\t" + property.ColumnName + ","); } else { output.Append("\t" + property.ColumnName + ""); } } output.Append(") VALUES ("); // Create the values list for (int i = 0; i < columnCount; i++) { ParameterProperty property = (ParameterProperty) statement.ParameterMap.PropertiesList[i]; // Append the necessary line breaks and commas if (i < (columnCount - 1)) { output.Append("\t?,"); } else { output.Append("\t?"); } } output.Append(")"); return output.ToString(); } /// <summary> /// Creates an update SQL command text for a specified statement /// </summary> /// <param name="statement">The statement to build the SQL command text.</param> /// <returns>The SQL command text for the statement.</returns> private static string BuildUpdateQuery(IStatement statement) { StringBuilder output = new StringBuilder(); Update update = (Update) statement; int columnCount = statement.ParameterMap.PropertiesList.Count; string[] keysList = update.Generate.By.Split(','); output.Append("UPDATE "); output.Append("\t" + update.Generate.Table + " "); output.Append("SET "); // Create the set statement for (int i = 0; i < columnCount; i++) { ParameterProperty property = (ParameterProperty) statement.ParameterMap.PropertiesList[i]; // Ignore key columns if (update.Generate.By.IndexOf(property.ColumnName) < 0) { if (i < (columnCount-keysList.Length - 1)) { output.Append("\t" + property.ColumnName + " = ?,"); } else { output.Append("\t" + property.ColumnName + " = ? "); } } } output.Append(" WHERE "); // Create the where clause for (int i = 0; i < keysList.Length; i++) { string columnName = keysList[i]; if (i > 0) { output.Append("\tAND " + columnName + " = ?"); } else { output.Append("\t " + columnName + " = ?"); } } return output.ToString(); } /// <summary> /// Creates an delete SQL command text for a specified statement /// </summary> /// <param name="statement">The statement to build the SQL command text.</param> /// <returns>The SQL command text for the statement.</returns> private static string BuildDeleteQuery(IStatement statement) { StringBuilder output = new StringBuilder(); Delete delete = (Delete) statement; string[] keysList = delete.Generate.By.Split(','); output.Append("DELETE FROM"); output.Append("\t" + delete.Generate.Table + ""); output.Append(" WHERE "); // Create the where clause for (int i = 0; i < keysList.Length; i++) { string columnName = keysList[i].Trim(); if (i > 0) { output.Append("\tAND " + columnName + " = ?"); } else { output.Append("\t " + columnName + " = ?"); } } return output.ToString(); } } }
// Copyright (C) 2014 dot42 // // Original filename: Org.Apache.Http.Client.Methods.cs // // 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. #pragma warning disable 1717 namespace Org.Apache.Http.Client.Methods { /// <summary> /// <para>HTTP GET method. </para><para>The HTTP GET method is defined in section 9.3 of : <blockquote><para>The GET method means retrieve whatever information (in the form of an entity) is identified by the Request-URI. If the Request-URI refers to a data-producing process, it is the produced data which shall be returned as the entity in the response and not the source text of the process, unless that text happens to be the output of the process. </para></blockquote></para><para>GetMethods will follow redirect requests from the http server by default. This behavour can be disabled by calling setFollowRedirects(false).</para><para><para></para><title>Revision:</title><para>664505 </para></para><para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/client/methods/HttpGet /// </java-name> [Dot42.DexImport("org/apache/http/client/methods/HttpGet", AccessFlags = 33)] public partial class HttpGet : global::Org.Apache.Http.Client.Methods.HttpRequestBase /* scope: __dot42__ */ { /// <java-name> /// METHOD_NAME /// </java-name> [Dot42.DexImport("METHOD_NAME", "Ljava/lang/String;", AccessFlags = 25)] public const string METHOD_NAME = "GET"; [Dot42.DexImport("<init>", "()V", AccessFlags = 1)] public HttpGet() /* MethodBuilder.Create */ { } [Dot42.DexImport("<init>", "(Ljava/net/URI;)V", AccessFlags = 1)] public HttpGet(global::System.Uri uri) /* MethodBuilder.Create */ { } [Dot42.DexImport("<init>", "(Ljava/lang/String;)V", AccessFlags = 1)] public HttpGet(string uri) /* MethodBuilder.Create */ { } /// <summary> /// <para>Returns the HTTP method this request uses, such as <code>GET</code>, <code>PUT</code>, <code>POST</code>, or other. </para> /// </summary> /// <java-name> /// getMethod /// </java-name> [Dot42.DexImport("getMethod", "()Ljava/lang/String;", AccessFlags = 1)] public override string GetMethod() /* MethodBuilder.Create */ { return default(string); } /// <summary> /// <para>Returns the HTTP method this request uses, such as <code>GET</code>, <code>PUT</code>, <code>POST</code>, or other. </para> /// </summary> /// <java-name> /// getMethod /// </java-name> public string Method { [Dot42.DexImport("getMethod", "()Ljava/lang/String;", AccessFlags = 1)] get{ return GetMethod(); } } } /// <summary> /// <para>Basic implementation of an HTTP request that can be modified.</para><para><para></para><para></para><title>Revision:</title><para>674186 </para></para><para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/client/methods/HttpEntityEnclosingRequestBase /// </java-name> [Dot42.DexImport("org/apache/http/client/methods/HttpEntityEnclosingRequestBase", AccessFlags = 1057)] public abstract partial class HttpEntityEnclosingRequestBase : global::Org.Apache.Http.Client.Methods.HttpRequestBase, global::Org.Apache.Http.IHttpEntityEnclosingRequest /* scope: __dot42__ */ { [Dot42.DexImport("<init>", "()V", AccessFlags = 1)] public HttpEntityEnclosingRequestBase() /* MethodBuilder.Create */ { } /// <java-name> /// getEntity /// </java-name> [Dot42.DexImport("getEntity", "()Lorg/apache/http/HttpEntity;", AccessFlags = 1)] public virtual global::Org.Apache.Http.IHttpEntity GetEntity() /* MethodBuilder.Create */ { return default(global::Org.Apache.Http.IHttpEntity); } /// <java-name> /// setEntity /// </java-name> [Dot42.DexImport("setEntity", "(Lorg/apache/http/HttpEntity;)V", AccessFlags = 1)] public virtual void SetEntity(global::Org.Apache.Http.IHttpEntity entity) /* MethodBuilder.Create */ { } /// <summary> /// <para>Tells if this request should use the expect-continue handshake. The expect continue handshake gives the server a chance to decide whether to accept the entity enclosing request before the possibly lengthy entity is sent across the wire. </para> /// </summary> /// <returns> /// <para>true if the expect continue handshake should be used, false if not. </para> /// </returns> /// <java-name> /// expectContinue /// </java-name> [Dot42.DexImport("expectContinue", "()Z", AccessFlags = 1)] public virtual bool ExpectContinue() /* MethodBuilder.Create */ { return default(bool); } /// <java-name> /// clone /// </java-name> [Dot42.DexImport("clone", "()Ljava/lang/Object;", AccessFlags = 1)] public override object Clone() /* MethodBuilder.Create */ { return default(object); } [Dot42.DexImport("org/apache/http/HttpRequest", "getRequestLine", "()Lorg/apache/http/RequestLine;", AccessFlags = 1025)] public override global::Org.Apache.Http.IRequestLine GetRequestLine() /* TypeBuilder.AddAbstractInterfaceMethods */ { return default(global::Org.Apache.Http.IRequestLine); } [Dot42.DexImport("org/apache/http/HttpMessage", "getProtocolVersion", "()Lorg/apache/http/ProtocolVersion;", AccessFlags = 1025)] public override global::Org.Apache.Http.ProtocolVersion GetProtocolVersion() /* TypeBuilder.AddAbstractInterfaceMethods */ { return default(global::Org.Apache.Http.ProtocolVersion); } [Dot42.DexImport("org/apache/http/HttpMessage", "containsHeader", "(Ljava/lang/String;)Z", AccessFlags = 1025)] public override bool ContainsHeader(string name) /* TypeBuilder.AddAbstractInterfaceMethods */ { return default(bool); } [Dot42.DexImport("org/apache/http/HttpMessage", "getHeaders", "(Ljava/lang/String;)[Lorg/apache/http/Header;", AccessFlags = 1025)] public override global::Org.Apache.Http.IHeader[] GetHeaders(string name) /* TypeBuilder.AddAbstractInterfaceMethods */ { return default(global::Org.Apache.Http.IHeader[]); } [Dot42.DexImport("org/apache/http/HttpMessage", "getFirstHeader", "(Ljava/lang/String;)Lorg/apache/http/Header;", AccessFlags = 1025)] public override global::Org.Apache.Http.IHeader GetFirstHeader(string name) /* TypeBuilder.AddAbstractInterfaceMethods */ { return default(global::Org.Apache.Http.IHeader); } [Dot42.DexImport("org/apache/http/HttpMessage", "getLastHeader", "(Ljava/lang/String;)Lorg/apache/http/Header;", AccessFlags = 1025)] public override global::Org.Apache.Http.IHeader GetLastHeader(string name) /* TypeBuilder.AddAbstractInterfaceMethods */ { return default(global::Org.Apache.Http.IHeader); } [Dot42.DexImport("org/apache/http/HttpMessage", "getAllHeaders", "()[Lorg/apache/http/Header;", AccessFlags = 1025)] public override global::Org.Apache.Http.IHeader[] GetAllHeaders() /* TypeBuilder.AddAbstractInterfaceMethods */ { return default(global::Org.Apache.Http.IHeader[]); } [Dot42.DexImport("org/apache/http/HttpMessage", "addHeader", "(Lorg/apache/http/Header;)V", AccessFlags = 1025)] public override void AddHeader(global::Org.Apache.Http.IHeader header) /* TypeBuilder.AddAbstractInterfaceMethods */ { } [Dot42.DexImport("org/apache/http/HttpMessage", "addHeader", "(Ljava/lang/String;Ljava/lang/String;)V", AccessFlags = 1025)] public override void AddHeader(string name, string value) /* TypeBuilder.AddAbstractInterfaceMethods */ { } [Dot42.DexImport("org/apache/http/HttpMessage", "setHeader", "(Lorg/apache/http/Header;)V", AccessFlags = 1025)] public override void SetHeader(global::Org.Apache.Http.IHeader header) /* TypeBuilder.AddAbstractInterfaceMethods */ { } [Dot42.DexImport("org/apache/http/HttpMessage", "setHeader", "(Ljava/lang/String;Ljava/lang/String;)V", AccessFlags = 1025)] public override void SetHeader(string name, string value) /* TypeBuilder.AddAbstractInterfaceMethods */ { } [Dot42.DexImport("org/apache/http/HttpMessage", "setHeaders", "([Lorg/apache/http/Header;)V", AccessFlags = 1025)] public override void SetHeaders(global::Org.Apache.Http.IHeader[] headers) /* TypeBuilder.AddAbstractInterfaceMethods */ { } [Dot42.DexImport("org/apache/http/HttpMessage", "removeHeader", "(Lorg/apache/http/Header;)V", AccessFlags = 1025)] public override void RemoveHeader(global::Org.Apache.Http.IHeader header) /* TypeBuilder.AddAbstractInterfaceMethods */ { } [Dot42.DexImport("org/apache/http/HttpMessage", "removeHeaders", "(Ljava/lang/String;)V", AccessFlags = 1025)] public override void RemoveHeaders(string name) /* TypeBuilder.AddAbstractInterfaceMethods */ { } [Dot42.DexImport("org/apache/http/HttpMessage", "headerIterator", "()Lorg/apache/http/HeaderIterator;", AccessFlags = 1025)] public override global::Org.Apache.Http.IHeaderIterator HeaderIterator() /* TypeBuilder.AddAbstractInterfaceMethods */ { return default(global::Org.Apache.Http.IHeaderIterator); } [Dot42.DexImport("org/apache/http/HttpMessage", "headerIterator", "(Ljava/lang/String;)Lorg/apache/http/HeaderIterator;", AccessFlags = 1025)] public override global::Org.Apache.Http.IHeaderIterator HeaderIterator(string name) /* TypeBuilder.AddAbstractInterfaceMethods */ { return default(global::Org.Apache.Http.IHeaderIterator); } [Dot42.DexImport("org/apache/http/HttpMessage", "getParams", "()Lorg/apache/http/params/HttpParams;", AccessFlags = 1025)] public override global::Org.Apache.Http.Params.IHttpParams GetParams() /* TypeBuilder.AddAbstractInterfaceMethods */ { return default(global::Org.Apache.Http.Params.IHttpParams); } [Dot42.DexImport("org/apache/http/HttpMessage", "setParams", "(Lorg/apache/http/params/HttpParams;)V", AccessFlags = 1025)] public override void SetParams(global::Org.Apache.Http.Params.IHttpParams @params) /* TypeBuilder.AddAbstractInterfaceMethods */ { } /// <java-name> /// getEntity /// </java-name> public global::Org.Apache.Http.IHttpEntity Entity { [Dot42.DexImport("getEntity", "()Lorg/apache/http/HttpEntity;", AccessFlags = 1)] get{ return GetEntity(); } [Dot42.DexImport("setEntity", "(Lorg/apache/http/HttpEntity;)V", AccessFlags = 1)] set{ SetEntity(value); } } public global::Org.Apache.Http.IRequestLine RequestLine { [Dot42.DexImport("org/apache/http/HttpRequest", "getRequestLine", "()Lorg/apache/http/RequestLine;", AccessFlags = 1025)] get{ return GetRequestLine(); } } public global::Org.Apache.Http.ProtocolVersion ProtocolVersion { [Dot42.DexImport("org/apache/http/HttpMessage", "getProtocolVersion", "()Lorg/apache/http/ProtocolVersion;", AccessFlags = 1025)] get{ return GetProtocolVersion(); } } public global::Org.Apache.Http.IHeader[] AllHeaders { [Dot42.DexImport("org/apache/http/HttpMessage", "getAllHeaders", "()[Lorg/apache/http/Header;", AccessFlags = 1025)] get{ return GetAllHeaders(); } } public global::Org.Apache.Http.Params.IHttpParams Params { [Dot42.DexImport("org/apache/http/HttpMessage", "getParams", "()Lorg/apache/http/params/HttpParams;", AccessFlags = 1025)] get{ return GetParams(); } [Dot42.DexImport("org/apache/http/HttpMessage", "setParams", "(Lorg/apache/http/params/HttpParams;)V", AccessFlags = 1025)] set{ SetParams(value); } } } /// <summary> /// <para>HTTP TRACE method. </para><para>The HTTP TRACE method is defined in section 9.6 of : <blockquote><para>The TRACE method is used to invoke a remote, application-layer loop- back of the request message. The final recipient of the request SHOULD reflect the message received back to the client as the entity-body of a 200 (OK) response. The final recipient is either the origin server or the first proxy or gateway to receive a Max-Forwards value of zero (0) in the request (see section 14.31). A TRACE request MUST NOT include an entity. </para></blockquote></para><para><para></para><title>Revision:</title><para>664505 </para></para><para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/client/methods/HttpTrace /// </java-name> [Dot42.DexImport("org/apache/http/client/methods/HttpTrace", AccessFlags = 33)] public partial class HttpTrace : global::Org.Apache.Http.Client.Methods.HttpRequestBase /* scope: __dot42__ */ { /// <java-name> /// METHOD_NAME /// </java-name> [Dot42.DexImport("METHOD_NAME", "Ljava/lang/String;", AccessFlags = 25)] public const string METHOD_NAME = "TRACE"; [Dot42.DexImport("<init>", "()V", AccessFlags = 1)] public HttpTrace() /* MethodBuilder.Create */ { } [Dot42.DexImport("<init>", "(Ljava/net/URI;)V", AccessFlags = 1)] public HttpTrace(global::System.Uri uri) /* MethodBuilder.Create */ { } [Dot42.DexImport("<init>", "(Ljava/lang/String;)V", AccessFlags = 1)] public HttpTrace(string uri) /* MethodBuilder.Create */ { } /// <summary> /// <para>Returns the HTTP method this request uses, such as <code>GET</code>, <code>PUT</code>, <code>POST</code>, or other. </para> /// </summary> /// <java-name> /// getMethod /// </java-name> [Dot42.DexImport("getMethod", "()Ljava/lang/String;", AccessFlags = 1)] public override string GetMethod() /* MethodBuilder.Create */ { return default(string); } /// <summary> /// <para>Returns the HTTP method this request uses, such as <code>GET</code>, <code>PUT</code>, <code>POST</code>, or other. </para> /// </summary> /// <java-name> /// getMethod /// </java-name> public string Method { [Dot42.DexImport("getMethod", "()Ljava/lang/String;", AccessFlags = 1)] get{ return GetMethod(); } } } /// <summary> /// <para>Extended version of the HttpRequest interface that provides convenience methods to access request properties such as request URI and method type.</para><para><para></para><para></para><title>Revision:</title><para>659191 </para></para><para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/client/methods/HttpUriRequest /// </java-name> [Dot42.DexImport("org/apache/http/client/methods/HttpUriRequest", AccessFlags = 1537)] public partial interface IHttpUriRequest : global::Org.Apache.Http.IHttpRequest /* scope: __dot42__ */ { /// <summary> /// <para>Returns the HTTP method this request uses, such as <code>GET</code>, <code>PUT</code>, <code>POST</code>, or other. </para> /// </summary> /// <java-name> /// getMethod /// </java-name> [Dot42.DexImport("getMethod", "()Ljava/lang/String;", AccessFlags = 1025)] string GetMethod() /* MethodBuilder.Create */ ; /// <summary> /// <para>Returns the URI this request uses, such as <code></code>. </para> /// </summary> /// <java-name> /// getURI /// </java-name> [Dot42.DexImport("getURI", "()Ljava/net/URI;", AccessFlags = 1025)] global::System.Uri GetURI() /* MethodBuilder.Create */ ; /// <summary> /// <para>Aborts execution of the request.</para><para></para> /// </summary> /// <java-name> /// abort /// </java-name> [Dot42.DexImport("abort", "()V", AccessFlags = 1025)] void Abort() /* MethodBuilder.Create */ ; /// <summary> /// <para>Tests if the request execution has been aborted.</para><para></para> /// </summary> /// <returns> /// <para><code>true</code> if the request execution has been aborted, <code>false</code> otherwise. </para> /// </returns> /// <java-name> /// isAborted /// </java-name> [Dot42.DexImport("isAborted", "()Z", AccessFlags = 1025)] bool IsAborted() /* MethodBuilder.Create */ ; } /// <summary> /// <para>HTTP DELETE method </para><para>The HTTP DELETE method is defined in section 9.7 of : <blockquote><para>The DELETE method requests that the origin server delete the resource identified by the Request-URI. [...] The client cannot be guaranteed that the operation has been carried out, even if the status code returned from the origin server indicates that the action has been completed successfully. </para></blockquote></para> /// </summary> /// <java-name> /// org/apache/http/client/methods/HttpDelete /// </java-name> [Dot42.DexImport("org/apache/http/client/methods/HttpDelete", AccessFlags = 33)] public partial class HttpDelete : global::Org.Apache.Http.Client.Methods.HttpRequestBase /* scope: __dot42__ */ { /// <java-name> /// METHOD_NAME /// </java-name> [Dot42.DexImport("METHOD_NAME", "Ljava/lang/String;", AccessFlags = 25)] public const string METHOD_NAME = "DELETE"; [Dot42.DexImport("<init>", "()V", AccessFlags = 1)] public HttpDelete() /* MethodBuilder.Create */ { } [Dot42.DexImport("<init>", "(Ljava/net/URI;)V", AccessFlags = 1)] public HttpDelete(global::System.Uri uri) /* MethodBuilder.Create */ { } [Dot42.DexImport("<init>", "(Ljava/lang/String;)V", AccessFlags = 1)] public HttpDelete(string uri) /* MethodBuilder.Create */ { } /// <summary> /// <para>Returns the HTTP method this request uses, such as <code>GET</code>, <code>PUT</code>, <code>POST</code>, or other. </para> /// </summary> /// <java-name> /// getMethod /// </java-name> [Dot42.DexImport("getMethod", "()Ljava/lang/String;", AccessFlags = 1)] public override string GetMethod() /* MethodBuilder.Create */ { return default(string); } /// <summary> /// <para>Returns the HTTP method this request uses, such as <code>GET</code>, <code>PUT</code>, <code>POST</code>, or other. </para> /// </summary> /// <java-name> /// getMethod /// </java-name> public string Method { [Dot42.DexImport("getMethod", "()Ljava/lang/String;", AccessFlags = 1)] get{ return GetMethod(); } } } /// <summary> /// <para>HTTP OPTIONS method. </para><para>The HTTP OPTIONS method is defined in section 9.2 of : <blockquote><para>The OPTIONS method represents a request for information about the communication options available on the request/response chain identified by the Request-URI. This method allows the client to determine the options and/or requirements associated with a resource, or the capabilities of a server, without implying a resource action or initiating a resource retrieval. </para></blockquote></para><para><para></para><title>Revision:</title><para>664505 </para></para><para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/client/methods/HttpOptions /// </java-name> [Dot42.DexImport("org/apache/http/client/methods/HttpOptions", AccessFlags = 33)] public partial class HttpOptions : global::Org.Apache.Http.Client.Methods.HttpRequestBase /* scope: __dot42__ */ { /// <java-name> /// METHOD_NAME /// </java-name> [Dot42.DexImport("METHOD_NAME", "Ljava/lang/String;", AccessFlags = 25)] public const string METHOD_NAME = "OPTIONS"; [Dot42.DexImport("<init>", "()V", AccessFlags = 1)] public HttpOptions() /* MethodBuilder.Create */ { } [Dot42.DexImport("<init>", "(Ljava/net/URI;)V", AccessFlags = 1)] public HttpOptions(global::System.Uri uri) /* MethodBuilder.Create */ { } [Dot42.DexImport("<init>", "(Ljava/lang/String;)V", AccessFlags = 1)] public HttpOptions(string uri) /* MethodBuilder.Create */ { } /// <summary> /// <para>Returns the HTTP method this request uses, such as <code>GET</code>, <code>PUT</code>, <code>POST</code>, or other. </para> /// </summary> /// <java-name> /// getMethod /// </java-name> [Dot42.DexImport("getMethod", "()Ljava/lang/String;", AccessFlags = 1)] public override string GetMethod() /* MethodBuilder.Create */ { return default(string); } /// <java-name> /// getAllowedMethods /// </java-name> [Dot42.DexImport("getAllowedMethods", "(Lorg/apache/http/HttpResponse;)Ljava/util/Set;", AccessFlags = 1, Signature = "(Lorg/apache/http/HttpResponse;)Ljava/util/Set<Ljava/lang/String;>;")] public virtual global::Java.Util.ISet<string> GetAllowedMethods(global::Org.Apache.Http.IHttpResponse response) /* MethodBuilder.Create */ { return default(global::Java.Util.ISet<string>); } /// <summary> /// <para>Returns the HTTP method this request uses, such as <code>GET</code>, <code>PUT</code>, <code>POST</code>, or other. </para> /// </summary> /// <java-name> /// getMethod /// </java-name> public string Method { [Dot42.DexImport("getMethod", "()Ljava/lang/String;", AccessFlags = 1)] get{ return GetMethod(); } } } /// <summary> /// <para>HTTP POST method. </para><para>The HTTP POST method is defined in section 9.5 of : <blockquote><para>The POST method is used to request that the origin server accept the entity enclosed in the request as a new subordinate of the resource identified by the Request-URI in the Request-Line. POST is designed to allow a uniform method to cover the following functions: <ul><li><para>Annotation of existing resources </para></li><li><para>Posting a message to a bulletin board, newsgroup, mailing list, or similar group of articles </para></li><li><para>Providing a block of data, such as the result of submitting a form, to a data-handling process </para></li><li><para>Extending a database through an append operation </para></li></ul></para></blockquote></para><para><para></para><title>Revision:</title><para>664505 </para></para><para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/client/methods/HttpPost /// </java-name> [Dot42.DexImport("org/apache/http/client/methods/HttpPost", AccessFlags = 33)] public partial class HttpPost : global::Org.Apache.Http.Client.Methods.HttpEntityEnclosingRequestBase /* scope: __dot42__ */ { /// <java-name> /// METHOD_NAME /// </java-name> [Dot42.DexImport("METHOD_NAME", "Ljava/lang/String;", AccessFlags = 25)] public const string METHOD_NAME = "POST"; [Dot42.DexImport("<init>", "()V", AccessFlags = 1)] public HttpPost() /* MethodBuilder.Create */ { } [Dot42.DexImport("<init>", "(Ljava/net/URI;)V", AccessFlags = 1)] public HttpPost(global::System.Uri uri) /* MethodBuilder.Create */ { } [Dot42.DexImport("<init>", "(Ljava/lang/String;)V", AccessFlags = 1)] public HttpPost(string uri) /* MethodBuilder.Create */ { } /// <summary> /// <para>Returns the HTTP method this request uses, such as <code>GET</code>, <code>PUT</code>, <code>POST</code>, or other. </para> /// </summary> /// <java-name> /// getMethod /// </java-name> [Dot42.DexImport("getMethod", "()Ljava/lang/String;", AccessFlags = 1)] public override string GetMethod() /* MethodBuilder.Create */ { return default(string); } /// <summary> /// <para>Returns the HTTP method this request uses, such as <code>GET</code>, <code>PUT</code>, <code>POST</code>, or other. </para> /// </summary> /// <java-name> /// getMethod /// </java-name> public string Method { [Dot42.DexImport("getMethod", "()Ljava/lang/String;", AccessFlags = 1)] get{ return GetMethod(); } } } /// <summary> /// <para>Interface representing an HTTP request that can be aborted by shutting down the underlying HTTP connection.</para><para><para></para><para></para><title>Revision:</title><para>639600 </para></para><para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/client/methods/AbortableHttpRequest /// </java-name> [Dot42.DexImport("org/apache/http/client/methods/AbortableHttpRequest", AccessFlags = 1537)] public partial interface IAbortableHttpRequest /* scope: __dot42__ */ { /// <summary> /// <para>Sets the ClientConnectionRequest callback that can be used to abort a long-lived request for a connection. If the request is already aborted, throws an IOException.</para><para><para>ClientConnectionManager </para><simplesectsep></simplesectsep><para>ThreadSafeClientConnManager </para></para> /// </summary> /// <java-name> /// setConnectionRequest /// </java-name> [Dot42.DexImport("setConnectionRequest", "(Lorg/apache/http/conn/ClientConnectionRequest;)V", AccessFlags = 1025)] void SetConnectionRequest(global::Org.Apache.Http.Conn.IClientConnectionRequest connRequest) /* MethodBuilder.Create */ ; /// <summary> /// <para>Sets the ConnectionReleaseTrigger callback that can be used to abort an active connection. Typically, this will be the ManagedClientConnection itself. If the request is already aborted, throws an IOException. </para> /// </summary> /// <java-name> /// setReleaseTrigger /// </java-name> [Dot42.DexImport("setReleaseTrigger", "(Lorg/apache/http/conn/ConnectionReleaseTrigger;)V", AccessFlags = 1025)] void SetReleaseTrigger(global::Org.Apache.Http.Conn.IConnectionReleaseTrigger releaseTrigger) /* MethodBuilder.Create */ ; /// <summary> /// <para>Aborts this http request. Any active execution of this method should return immediately. If the request has not started, it will abort after the next execution. Aborting this request will cause all subsequent executions with this request to fail.</para><para><para>HttpClient::execute(HttpUriRequest) </para><simplesectsep></simplesectsep><para>HttpClient::execute(org.apache.http.HttpHost, org.apache.http.HttpRequest) </para><simplesectsep></simplesectsep><para>HttpClient::execute(HttpUriRequest, org.apache.http.protocol.HttpContext) </para><simplesectsep></simplesectsep><para>HttpClient::execute(org.apache.http.HttpHost, org.apache.http.HttpRequest, org.apache.http.protocol.HttpContext) </para></para> /// </summary> /// <java-name> /// abort /// </java-name> [Dot42.DexImport("abort", "()V", AccessFlags = 1025)] void Abort() /* MethodBuilder.Create */ ; } /// <summary> /// <para>Basic implementation of an HTTP request that can be modified.</para><para><para></para><para></para><title>Revision:</title><para>674186 </para></para><para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/client/methods/HttpRequestBase /// </java-name> [Dot42.DexImport("org/apache/http/client/methods/HttpRequestBase", AccessFlags = 1057)] public abstract partial class HttpRequestBase : global::Org.Apache.Http.Message.AbstractHttpMessage, global::Org.Apache.Http.Client.Methods.IHttpUriRequest, global::Org.Apache.Http.Client.Methods.IAbortableHttpRequest, global::Java.Lang.ICloneable /* scope: __dot42__ */ { [Dot42.DexImport("<init>", "()V", AccessFlags = 1)] public HttpRequestBase() /* MethodBuilder.Create */ { } /// <summary> /// <para>Returns the HTTP method this request uses, such as <code>GET</code>, <code>PUT</code>, <code>POST</code>, or other. </para> /// </summary> /// <java-name> /// getMethod /// </java-name> [Dot42.DexImport("getMethod", "()Ljava/lang/String;", AccessFlags = 1025)] public virtual string GetMethod() /* MethodBuilder.Create */ { return default(string); } /// <summary> /// <para>Returns the protocol version this message is compatible with. </para> /// </summary> /// <java-name> /// getProtocolVersion /// </java-name> [Dot42.DexImport("getProtocolVersion", "()Lorg/apache/http/ProtocolVersion;", AccessFlags = 1)] public override global::Org.Apache.Http.ProtocolVersion GetProtocolVersion() /* MethodBuilder.Create */ { return default(global::Org.Apache.Http.ProtocolVersion); } /// <summary> /// <para>Returns the URI this request uses, such as <code></code>. </para> /// </summary> /// <java-name> /// getURI /// </java-name> [Dot42.DexImport("getURI", "()Ljava/net/URI;", AccessFlags = 1)] public virtual global::System.Uri GetURI() /* MethodBuilder.Create */ { return default(global::System.Uri); } /// <summary> /// <para>Returns the request line of this request. </para> /// </summary> /// <returns> /// <para>the request line. </para> /// </returns> /// <java-name> /// getRequestLine /// </java-name> [Dot42.DexImport("getRequestLine", "()Lorg/apache/http/RequestLine;", AccessFlags = 1)] public virtual global::Org.Apache.Http.IRequestLine GetRequestLine() /* MethodBuilder.Create */ { return default(global::Org.Apache.Http.IRequestLine); } /// <java-name> /// setURI /// </java-name> [Dot42.DexImport("setURI", "(Ljava/net/URI;)V", AccessFlags = 1)] public virtual void SetURI(global::System.Uri uri) /* MethodBuilder.Create */ { } /// <java-name> /// setConnectionRequest /// </java-name> [Dot42.DexImport("setConnectionRequest", "(Lorg/apache/http/conn/ClientConnectionRequest;)V", AccessFlags = 1)] public virtual void SetConnectionRequest(global::Org.Apache.Http.Conn.IClientConnectionRequest connRequest) /* MethodBuilder.Create */ { } /// <java-name> /// setReleaseTrigger /// </java-name> [Dot42.DexImport("setReleaseTrigger", "(Lorg/apache/http/conn/ConnectionReleaseTrigger;)V", AccessFlags = 1)] public virtual void SetReleaseTrigger(global::Org.Apache.Http.Conn.IConnectionReleaseTrigger releaseTrigger) /* MethodBuilder.Create */ { } /// <summary> /// <para>Aborts this http request. Any active execution of this method should return immediately. If the request has not started, it will abort after the next execution. Aborting this request will cause all subsequent executions with this request to fail.</para><para><para>HttpClient::execute(HttpUriRequest) </para><simplesectsep></simplesectsep><para>HttpClient::execute(org.apache.http.HttpHost, org.apache.http.HttpRequest) </para><simplesectsep></simplesectsep><para>HttpClient::execute(HttpUriRequest, org.apache.http.protocol.HttpContext) </para><simplesectsep></simplesectsep><para>HttpClient::execute(org.apache.http.HttpHost, org.apache.http.HttpRequest, org.apache.http.protocol.HttpContext) </para></para> /// </summary> /// <java-name> /// abort /// </java-name> [Dot42.DexImport("abort", "()V", AccessFlags = 1)] public virtual void Abort() /* MethodBuilder.Create */ { } /// <summary> /// <para>Tests if the request execution has been aborted.</para><para></para> /// </summary> /// <returns> /// <para><code>true</code> if the request execution has been aborted, <code>false</code> otherwise. </para> /// </returns> /// <java-name> /// isAborted /// </java-name> [Dot42.DexImport("isAborted", "()Z", AccessFlags = 1)] public virtual bool IsAborted() /* MethodBuilder.Create */ { return default(bool); } /// <java-name> /// clone /// </java-name> [Dot42.DexImport("clone", "()Ljava/lang/Object;", AccessFlags = 1)] public virtual object Clone() /* MethodBuilder.Create */ { return default(object); } [Dot42.DexImport("org/apache/http/HttpMessage", "containsHeader", "(Ljava/lang/String;)Z", AccessFlags = 1025)] public override bool ContainsHeader(string name) /* TypeBuilder.AddAbstractInterfaceMethods */ { return default(bool); } [Dot42.DexImport("org/apache/http/HttpMessage", "getHeaders", "(Ljava/lang/String;)[Lorg/apache/http/Header;", AccessFlags = 1025)] public override global::Org.Apache.Http.IHeader[] GetHeaders(string name) /* TypeBuilder.AddAbstractInterfaceMethods */ { return default(global::Org.Apache.Http.IHeader[]); } [Dot42.DexImport("org/apache/http/HttpMessage", "getFirstHeader", "(Ljava/lang/String;)Lorg/apache/http/Header;", AccessFlags = 1025)] public override global::Org.Apache.Http.IHeader GetFirstHeader(string name) /* TypeBuilder.AddAbstractInterfaceMethods */ { return default(global::Org.Apache.Http.IHeader); } [Dot42.DexImport("org/apache/http/HttpMessage", "getLastHeader", "(Ljava/lang/String;)Lorg/apache/http/Header;", AccessFlags = 1025)] public override global::Org.Apache.Http.IHeader GetLastHeader(string name) /* TypeBuilder.AddAbstractInterfaceMethods */ { return default(global::Org.Apache.Http.IHeader); } [Dot42.DexImport("org/apache/http/HttpMessage", "getAllHeaders", "()[Lorg/apache/http/Header;", AccessFlags = 1025)] public override global::Org.Apache.Http.IHeader[] GetAllHeaders() /* TypeBuilder.AddAbstractInterfaceMethods */ { return default(global::Org.Apache.Http.IHeader[]); } [Dot42.DexImport("org/apache/http/HttpMessage", "addHeader", "(Lorg/apache/http/Header;)V", AccessFlags = 1025)] public override void AddHeader(global::Org.Apache.Http.IHeader header) /* TypeBuilder.AddAbstractInterfaceMethods */ { } [Dot42.DexImport("org/apache/http/HttpMessage", "addHeader", "(Ljava/lang/String;Ljava/lang/String;)V", AccessFlags = 1025)] public override void AddHeader(string name, string value) /* TypeBuilder.AddAbstractInterfaceMethods */ { } [Dot42.DexImport("org/apache/http/HttpMessage", "setHeader", "(Lorg/apache/http/Header;)V", AccessFlags = 1025)] public override void SetHeader(global::Org.Apache.Http.IHeader header) /* TypeBuilder.AddAbstractInterfaceMethods */ { } [Dot42.DexImport("org/apache/http/HttpMessage", "setHeader", "(Ljava/lang/String;Ljava/lang/String;)V", AccessFlags = 1025)] public override void SetHeader(string name, string value) /* TypeBuilder.AddAbstractInterfaceMethods */ { } [Dot42.DexImport("org/apache/http/HttpMessage", "setHeaders", "([Lorg/apache/http/Header;)V", AccessFlags = 1025)] public override void SetHeaders(global::Org.Apache.Http.IHeader[] headers) /* TypeBuilder.AddAbstractInterfaceMethods */ { } [Dot42.DexImport("org/apache/http/HttpMessage", "removeHeader", "(Lorg/apache/http/Header;)V", AccessFlags = 1025)] public override void RemoveHeader(global::Org.Apache.Http.IHeader header) /* TypeBuilder.AddAbstractInterfaceMethods */ { } [Dot42.DexImport("org/apache/http/HttpMessage", "removeHeaders", "(Ljava/lang/String;)V", AccessFlags = 1025)] public override void RemoveHeaders(string name) /* TypeBuilder.AddAbstractInterfaceMethods */ { } [Dot42.DexImport("org/apache/http/HttpMessage", "headerIterator", "()Lorg/apache/http/HeaderIterator;", AccessFlags = 1025)] public override global::Org.Apache.Http.IHeaderIterator HeaderIterator() /* TypeBuilder.AddAbstractInterfaceMethods */ { return default(global::Org.Apache.Http.IHeaderIterator); } [Dot42.DexImport("org/apache/http/HttpMessage", "headerIterator", "(Ljava/lang/String;)Lorg/apache/http/HeaderIterator;", AccessFlags = 1025)] public override global::Org.Apache.Http.IHeaderIterator HeaderIterator(string name) /* TypeBuilder.AddAbstractInterfaceMethods */ { return default(global::Org.Apache.Http.IHeaderIterator); } [Dot42.DexImport("org/apache/http/HttpMessage", "getParams", "()Lorg/apache/http/params/HttpParams;", AccessFlags = 1025)] public override global::Org.Apache.Http.Params.IHttpParams GetParams() /* TypeBuilder.AddAbstractInterfaceMethods */ { return default(global::Org.Apache.Http.Params.IHttpParams); } [Dot42.DexImport("org/apache/http/HttpMessage", "setParams", "(Lorg/apache/http/params/HttpParams;)V", AccessFlags = 1025)] public override void SetParams(global::Org.Apache.Http.Params.IHttpParams @params) /* TypeBuilder.AddAbstractInterfaceMethods */ { } /// <summary> /// <para>Returns the HTTP method this request uses, such as <code>GET</code>, <code>PUT</code>, <code>POST</code>, or other. </para> /// </summary> /// <java-name> /// getMethod /// </java-name> public string Method { [Dot42.DexImport("getMethod", "()Ljava/lang/String;", AccessFlags = 1025)] get{ return GetMethod(); } } /// <summary> /// <para>Returns the protocol version this message is compatible with. </para> /// </summary> /// <java-name> /// getProtocolVersion /// </java-name> public global::Org.Apache.Http.ProtocolVersion ProtocolVersion { [Dot42.DexImport("getProtocolVersion", "()Lorg/apache/http/ProtocolVersion;", AccessFlags = 1)] get{ return GetProtocolVersion(); } } /// <summary> /// <para>Returns the URI this request uses, such as <code></code>. </para> /// </summary> /// <java-name> /// getURI /// </java-name> public global::System.Uri URI { [Dot42.DexImport("getURI", "()Ljava/net/URI;", AccessFlags = 1)] get{ return GetURI(); } [Dot42.DexImport("setURI", "(Ljava/net/URI;)V", AccessFlags = 1)] set{ SetURI(value); } } /// <summary> /// <para>Returns the request line of this request. </para> /// </summary> /// <returns> /// <para>the request line. </para> /// </returns> /// <java-name> /// getRequestLine /// </java-name> public global::Org.Apache.Http.IRequestLine RequestLine { [Dot42.DexImport("getRequestLine", "()Lorg/apache/http/RequestLine;", AccessFlags = 1)] get{ return GetRequestLine(); } } public global::Org.Apache.Http.IHeader[] AllHeaders { [Dot42.DexImport("org/apache/http/HttpMessage", "getAllHeaders", "()[Lorg/apache/http/Header;", AccessFlags = 1025)] get{ return GetAllHeaders(); } } } /// <summary> /// <para>HTTP PUT method. </para><para>The HTTP PUT method is defined in section 9.6 of : <blockquote><para>The PUT method requests that the enclosed entity be stored under the supplied Request-URI. If the Request-URI refers to an already existing resource, the enclosed entity SHOULD be considered as a modified version of the one residing on the origin server. </para></blockquote></para><para><para></para><title>Revision:</title><para>664505 </para></para><para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/client/methods/HttpPut /// </java-name> [Dot42.DexImport("org/apache/http/client/methods/HttpPut", AccessFlags = 33)] public partial class HttpPut : global::Org.Apache.Http.Client.Methods.HttpEntityEnclosingRequestBase /* scope: __dot42__ */ { /// <java-name> /// METHOD_NAME /// </java-name> [Dot42.DexImport("METHOD_NAME", "Ljava/lang/String;", AccessFlags = 25)] public const string METHOD_NAME = "PUT"; [Dot42.DexImport("<init>", "()V", AccessFlags = 1)] public HttpPut() /* MethodBuilder.Create */ { } [Dot42.DexImport("<init>", "(Ljava/net/URI;)V", AccessFlags = 1)] public HttpPut(global::System.Uri uri) /* MethodBuilder.Create */ { } [Dot42.DexImport("<init>", "(Ljava/lang/String;)V", AccessFlags = 1)] public HttpPut(string uri) /* MethodBuilder.Create */ { } /// <summary> /// <para>Returns the HTTP method this request uses, such as <code>GET</code>, <code>PUT</code>, <code>POST</code>, or other. </para> /// </summary> /// <java-name> /// getMethod /// </java-name> [Dot42.DexImport("getMethod", "()Ljava/lang/String;", AccessFlags = 1)] public override string GetMethod() /* MethodBuilder.Create */ { return default(string); } /// <summary> /// <para>Returns the HTTP method this request uses, such as <code>GET</code>, <code>PUT</code>, <code>POST</code>, or other. </para> /// </summary> /// <java-name> /// getMethod /// </java-name> public string Method { [Dot42.DexImport("getMethod", "()Ljava/lang/String;", AccessFlags = 1)] get{ return GetMethod(); } } } /// <summary> /// <para>HTTP HEAD method. </para><para>The HTTP HEAD method is defined in section 9.4 of : <blockquote><para>The HEAD method is identical to GET except that the server MUST NOT return a message-body in the response. The metainformation contained in the HTTP headers in response to a HEAD request SHOULD be identical to the information sent in response to a GET request. This method can be used for obtaining metainformation about the entity implied by the request without transferring the entity-body itself. This method is often used for testing hypertext links for validity, accessibility, and recent modification. </para></blockquote></para><para><para></para><title>Revision:</title><para>664505 </para></para><para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/client/methods/HttpHead /// </java-name> [Dot42.DexImport("org/apache/http/client/methods/HttpHead", AccessFlags = 33)] public partial class HttpHead : global::Org.Apache.Http.Client.Methods.HttpRequestBase /* scope: __dot42__ */ { /// <java-name> /// METHOD_NAME /// </java-name> [Dot42.DexImport("METHOD_NAME", "Ljava/lang/String;", AccessFlags = 25)] public const string METHOD_NAME = "HEAD"; [Dot42.DexImport("<init>", "()V", AccessFlags = 1)] public HttpHead() /* MethodBuilder.Create */ { } [Dot42.DexImport("<init>", "(Ljava/net/URI;)V", AccessFlags = 1)] public HttpHead(global::System.Uri uri) /* MethodBuilder.Create */ { } [Dot42.DexImport("<init>", "(Ljava/lang/String;)V", AccessFlags = 1)] public HttpHead(string uri) /* MethodBuilder.Create */ { } /// <summary> /// <para>Returns the HTTP method this request uses, such as <code>GET</code>, <code>PUT</code>, <code>POST</code>, or other. </para> /// </summary> /// <java-name> /// getMethod /// </java-name> [Dot42.DexImport("getMethod", "()Ljava/lang/String;", AccessFlags = 1)] public override string GetMethod() /* MethodBuilder.Create */ { return default(string); } /// <summary> /// <para>Returns the HTTP method this request uses, such as <code>GET</code>, <code>PUT</code>, <code>POST</code>, or other. </para> /// </summary> /// <java-name> /// getMethod /// </java-name> public string Method { [Dot42.DexImport("getMethod", "()Ljava/lang/String;", AccessFlags = 1)] get{ return GetMethod(); } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Linq; namespace PSycheTest.Runners.Framework.Utilities.Collections { /// <summary> /// Contains extension methods pertaining to enumerables. /// </summary> public static class EnumerableExtensions { /// <summary> /// Determines whether an enumerable contains all items of another enumerable. /// This does not test for proper subsets, so if the compared enumerables /// contain exactly the same items, true is returned. /// </summary> /// <param name="subset">The supposed subset of items</param> /// <param name="superset">The supposed superset of items</param> /// <returns>Whether superset contains all elements of the enumerable</returns> public static bool IsSubsetOf<T>(this IEnumerable<T> subset, IEnumerable<T> superset) { // Optimize for ISet which already contains a method to perform // this operation. var subsetSet = subset as ISet<T>; if (subsetSet != null) return subsetSet.IsSubsetOf(superset); // If subtracting the superset from the subset does not remove all items, then // the superset does not actually contain everything. IEnumerable<T> subtractedItems = subset.Except(superset); if (subtractedItems.Any()) return false; return true; } /// <summary> /// Groups an enumerable of items into a sequence of <paramref name="sliceSize"/>-sized collections. /// However, if the number of items remaining is fewer than the <paramref name="sliceSize"/>, the last /// slice will contain just the remaining items. /// </summary> /// <param name="sourceItems">The items to slice</param> /// <param name="sliceSize">The number of items per slice</param> /// <returns>An enumerable of items grouped into <paramref name="sliceSize"/> number of items</returns> public static IEnumerable<IReadOnlyCollection<T>> Slices<T>(this IEnumerable<T> sourceItems, int sliceSize) { if (sourceItems == null) throw new ArgumentNullException("sourceItems"); if (sliceSize < 1) return Enumerable.Empty<IReadOnlyCollection<T>>(); return new SliceEnumerable<T>(sourceItems, sliceSize); } /// <summary> /// Generates an IEnumerable from an IEnumerator. /// </summary> /// <param name="enumerator">The enumerator to convert</param> /// <returns>An enumerable for the enumerator</returns> /// <remarks>Borrowed from Igor Ostrovsky: /// http://igoro.com/archive/extended-linq-additional-operators-for-linq-to-objects/ /// </remarks> [DebuggerStepThrough] public static IEnumerable<T> ToEnumerable<T>(this IEnumerator<T> enumerator) { if (enumerator == null) throw new ArgumentNullException("enumerator"); return enumerator.ToEnumerableImpl(); } /// <summary> /// Implementation method that allows for eager argument validation. /// </summary> private static IEnumerable<T> ToEnumerableImpl<T>(this IEnumerator<T> enumerator) { while (enumerator.MoveNext()) yield return enumerator.Current; } /// <summary> /// Generates an IEnumerable from a single value. /// </summary> /// <param name="value">The value to create an enumerable for</param> /// <returns>An enumerable for the single value</returns> [DebuggerStepThrough] public static IEnumerable<T> ToEnumerable<T>(this T value) { yield return value; } /// <summary> /// Returns the item from an enumerable that has the maximum value according /// to a key. The default comparer is used. /// </summary> /// <typeparam name="TSource">The type of items in the source enumerable</typeparam> /// <typeparam name="TKey">The type of value being compared</typeparam> /// <param name="source">The source enumerable</param> /// <param name="selector">Determines the value from each item to use for comparison</param> /// <returns>The item from the source that has the maximum value according to its key</returns> /// <exception cref="ArgumentNullException">If source or selector are null</exception> /// <exception cref="InvalidOperationException">If the source sequence contains no elements</exception> public static TSource MaxBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> selector) { return source.MaxBy(selector, Comparer<TKey>.Default); } /// <summary> /// Returns the item from an enumerable that has the maximum value according /// to a key. /// </summary> /// <typeparam name="TSource">The type of items in the source enumerable</typeparam> /// <typeparam name="TKey">The type of value being compared</typeparam> /// <param name="source">The source enumerable</param> /// <param name="selector">Determines the value from each item to use for comparison</param> /// <param name="comparer">The comparer to use on keys</param> /// <returns>The item from the source that has the maximum value according to its key</returns> /// <exception cref="ArgumentNullException">If source or selector are null</exception> /// <exception cref="InvalidOperationException">If the source sequence contains no elements</exception> public static TSource MaxBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> selector, IComparer<TKey> comparer) { IComparer<TKey> actualComparer = comparer ?? Comparer<TKey>.Default; return source.ExtremumBy(selector, actualComparer); } /// <summary> /// Returns the item from an enumerable that has the minimum value according /// to a key. The default comparer is used. /// </summary> /// <typeparam name="TSource">The type of items in the source enumerable</typeparam> /// <typeparam name="TKey">The type of value being compared</typeparam> /// <param name="source">The source enumerable</param> /// <param name="selector">Determines the value from each item to use for comparison</param> /// <returns>The item from the source that has the minimum value according to its key</returns> /// <exception cref="ArgumentNullException">If source or selector are null</exception> /// <exception cref="InvalidOperationException">If the source sequence contains no elements</exception> public static TSource MinBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> selector) { return source.MinBy(selector, Comparer<TKey>.Default); } /// <summary> /// Returns the item from an enumerable that has the minimum value according /// to a key. /// </summary> /// <typeparam name="TSource">The type of items in the source enumerable</typeparam> /// <typeparam name="TKey">The type of value being compared</typeparam> /// <param name="source">The source enumerable</param> /// <param name="selector">Determines the value from each item to use for comparison</param> /// <param name="comparer">The comparer to use on keys</param> /// <returns>The item from the source that has the minimum value according to its key</returns> /// <exception cref="ArgumentNullException">If source or selector are null</exception> /// <exception cref="InvalidOperationException">If the source sequence contains no elements</exception> public static TSource MinBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> selector, IComparer<TKey> comparer) { IComparer<TKey> actualComparer = comparer ?? Comparer<TKey>.Default; return source.ExtremumBy(selector, new ReverseComparer<TKey>(actualComparer)); } private static TSource ExtremumBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> selector, IComparer<TKey> comparer) { if (source == null) throw new ArgumentNullException("source"); if (selector == null) throw new ArgumentNullException("selector"); TSource extremum = source.Aggregate((currentExtremum, element) => { TKey extremumKey = selector(currentExtremum); TKey elementKey = selector(element); int result = comparer.Compare(elementKey, extremumKey); return result > 0 ? element : currentExtremum; }); return extremum; } /// <summary> /// Lazily pipes the output of an enumerable to an action. /// </summary> /// <typeparam name="T">The type of items</typeparam> /// <param name="items">The items to pipe</param> /// <param name="action">The action to apply</param> /// <returns>The source enumerable</returns> public static IEnumerable<T> Tee<T>(this IEnumerable<T> items, Action<T> action) { foreach (var item in items) { action(item); yield return item; } } /// <summary> /// Iterates over an enumerable and adds each item to an existing collection. /// </summary> /// <remarks> /// This method may serve as an alternative to <see cref="Enumerable.ToList{TSource}"/> when /// an existing collection must be used instead of creating a new list. /// </remarks> /// <typeparam name="T">The type of items</typeparam> /// <param name="source">The items to iterate over</param> /// <param name="destination">An existing collection to add items to</param> public static void AddTo<T>(this IEnumerable<T> source, ICollection<T> destination) { foreach (var item in source) destination.Add(item); } /// <summary> /// Returns the first element of a sequence or <see cref="Option&lt;T>.None"/> if the sequence is empty. /// </summary> /// <typeparam name="T">The type of items in the sequence</typeparam> /// <param name="source">The source items to query</param> /// <returns>An <see cref="Option&lt;T>.Some"/> containing the first element of the sequence or <see cref="Option&lt;T>.None"/></returns> public static Option<T> FirstOrNone<T>(this IEnumerable<T> source) { return source.FirstOrNone(x => true); } /// <summary> /// Returns the first element of a sequence that satisfies a condition or <see cref="Option&lt;T>.None"/> if no such /// element is found. /// </summary> /// <typeparam name="T">The type of items in the sequence</typeparam> /// <param name="source">The source items to query</param> /// <param name="predicate">The condition an item must satisfy</param> /// <returns>An <see cref="Option&lt;T>.Some"/> containing the first element of the sequence meeting the condition or <see cref="Option&lt;T>.None"/></returns> public static Option<T> FirstOrNone<T>(this IEnumerable<T> source, Func<T, bool> predicate) { if (source == null) throw new ArgumentNullException("source"); if (predicate == null) throw new ArgumentNullException("predicate"); foreach (var item in source) { if (predicate(item)) return Option<T>.Some(item); } return Option<T>.None(); } /// <summary> /// Private class that provides the Slices enumerator. /// </summary> private class SliceEnumerable<T> : IEnumerable<IReadOnlyCollection<T>> { /// <summary> /// Creates a new Slice enumerable. /// </summary> public SliceEnumerable(IEnumerable<T> sourceItems, int sliceSize) { _sourceItems = sourceItems; _sliceSize = sliceSize; } #region IEnumerable Members /// <see cref="System.Collections.IEnumerable.GetEnumerator"/> IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } #endregion #region IEnumerable<IEnumerable<T>> Members /// <see cref="System.Collections.Generic.IEnumerable{T}.GetEnumerator"/> public IEnumerator<IReadOnlyCollection<T>> GetEnumerator() { IList<T> buffer = new List<T>(_sliceSize); int itemCounter = 1; foreach (T item in _sourceItems) { buffer.Add(item); if (itemCounter % _sliceSize == 0) { yield return new List<T>(buffer); buffer.Clear(); } itemCounter++; } if (buffer.Count > 0) yield return new List<T>(buffer); } #endregion private readonly IEnumerable<T> _sourceItems; private readonly int _sliceSize; } } }
using System; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Localization; using OrchardCore.Admin; using OrchardCore.DisplayManagement.Extensions; using OrchardCore.DisplayManagement.Notify; using OrchardCore.Environment.Extensions; using OrchardCore.Environment.Shell; using OrchardCore.Environment.Shell.Descriptor; using OrchardCore.Modules.Manifest; using OrchardCore.Security; using OrchardCore.Themes.Models; using OrchardCore.Themes.Services; namespace OrchardCore.Themes.Controllers { public class AdminController : Controller { private readonly ISiteThemeService _siteThemeService; private readonly IAdminThemeService _adminThemeService; private readonly IExtensionManager _extensionManager; private readonly IShellFeaturesManager _shellFeaturesManager; private readonly IAuthorizationService _authorizationService; private readonly INotifier _notifier; private readonly IHtmlLocalizer H; public AdminController( ISiteThemeService siteThemeService, IAdminThemeService adminThemeService, IThemeService themeService, ShellSettings shellSettings, IExtensionManager extensionManager, IHtmlLocalizer<AdminController> localizer, IShellDescriptorManager shellDescriptorManager, IShellFeaturesManager shellFeaturesManager, IAuthorizationService authorizationService, INotifier notifier) { _siteThemeService = siteThemeService; _adminThemeService = adminThemeService; _extensionManager = extensionManager; _shellFeaturesManager = shellFeaturesManager; _authorizationService = authorizationService; _notifier = notifier; H = localizer; } public async Task<ActionResult> Index() { var installThemes = await _authorizationService.AuthorizeAsync(User, StandardPermissions.SiteOwner); // only site owners //&& _shellSettings.Name == ShellSettings.; // of the default tenant //&& _featureManager.GetEnabledFeatures().FirstOrDefault(f => f.Id == "PackagingServices") != null //var featuresThatNeedUpdate = _dataMigrationManager.GetFeaturesThatNeedUpdate(); var currentSiteThemeExtensionInfo = await _siteThemeService.GetSiteThemeAsync(); var currentAdminThemeExtensionInfo = await _adminThemeService.GetAdminThemeAsync(); var currentAdminTheme = currentAdminThemeExtensionInfo != null ? new ThemeEntry(currentAdminThemeExtensionInfo) : default(ThemeEntry); var currentSiteTheme = currentSiteThemeExtensionInfo != null ? new ThemeEntry(currentSiteThemeExtensionInfo) : default(ThemeEntry); var enabledFeatures = await _shellFeaturesManager.GetEnabledFeaturesAsync(); var themes = _extensionManager.GetExtensions().OfType<IThemeExtensionInfo>().Where(extensionDescriptor => { var tags = extensionDescriptor.Manifest.Tags.ToArray(); var isHidden = tags.Any(x => string.Equals(x, "hidden", StringComparison.OrdinalIgnoreCase)); /// is the theme allowed for this tenant ? // allowed = _shellSettings.Themes.Length == 0 || _shellSettings.Themes.Contains(extensionDescriptor.Id); return !isHidden; }) .Select(extensionDescriptor => { var isAdmin = IsAdminTheme(extensionDescriptor.Manifest); var themeId = isAdmin ? currentAdminTheme?.Extension.Id : currentSiteTheme?.Extension.Id; var isCurrent = extensionDescriptor.Id == themeId; var isEnabled = enabledFeatures.Any(x => x.Extension.Id == extensionDescriptor.Id); var themeEntry = new ThemeEntry(extensionDescriptor) { //NeedsUpdate = featuresThatNeedUpdate.Contains(extensionDescriptor.Id), //IsRecentlyInstalled = _themeService.IsRecentlyInstalled(extensionDescriptor), Enabled = isEnabled, CanUninstall = installThemes, IsAdmin = isAdmin, IsCurrent = isCurrent }; //if (_extensionDisplayEventHandler != null) //{ // foreach (string notification in _extensionDisplayEventHandler.Displaying(themeEntry.Descriptor, ControllerContext.RequestContext)) // { // themeEntry.Notifications.Add(notification); // } //} return themeEntry; }) .OrderByDescending(x => x.IsCurrent); var model = new SelectThemesViewModel { CurrentSiteTheme = currentSiteTheme, CurrentAdminTheme = currentAdminTheme, Themes = themes }; return View(model); } [HttpPost] public async Task<ActionResult> SetCurrentTheme(string id) { if (!await _authorizationService.AuthorizeAsync(User, Permissions.ApplyTheme)) { return Forbid(); } if (String.IsNullOrEmpty(id)) { // Don't use any theme on the front-end } else { var feature = _extensionManager.GetFeatures().FirstOrDefault(f => f.Extension.IsTheme() && f.Id == id); if (feature == null) { return NotFound(); } else { var isAdmin = IsAdminTheme(feature.Extension.Manifest); if (isAdmin) { await _adminThemeService.SetAdminThemeAsync(id); } else { await _siteThemeService.SetSiteThemeAsync(id); } // Enable the feature lastly to avoid accessing a disposed IMemoryCache (due to the current shell being disposed after updating). var enabledFeatures = await _shellFeaturesManager.GetEnabledFeaturesAsync(); var isEnabled = enabledFeatures.Any(x => x.Extension.Id == feature.Id); if (!isEnabled) { await _shellFeaturesManager.EnableFeaturesAsync(new[] { feature }, force: true); _notifier.Success(H["{0} was enabled", feature.Name ?? feature.Id]); } _notifier.Success(H["{0} was set as the default {1} theme", feature.Name ?? feature.Id, isAdmin ? "Admin" : "Site"]); } } return RedirectToAction("Index"); } [HttpPost] public async Task<ActionResult> ResetSiteTheme() { if (!await _authorizationService.AuthorizeAsync(User, Permissions.ApplyTheme)) { return Forbid(); } await _siteThemeService.SetSiteThemeAsync(""); _notifier.Success(H["The Site theme was reset."]); return RedirectToAction("Index"); } [HttpPost] public async Task<ActionResult> ResetAdminTheme() { if (!await _authorizationService.AuthorizeAsync(User, Permissions.ApplyTheme)) { return Forbid(); } await _adminThemeService.SetAdminThemeAsync(""); _notifier.Success(H["The Admin theme was reset."]); return RedirectToAction("Index"); } [HttpPost] public async Task<IActionResult> Disable(string id) { if (!await _authorizationService.AuthorizeAsync(User, Permissions.ApplyTheme)) { return Forbid(); } var feature = _extensionManager.GetFeatures().FirstOrDefault(f => f.Extension.IsTheme() && f.Id == id); if (feature == null) { return NotFound(); } await _shellFeaturesManager.DisableFeaturesAsync(new[] { feature }, force: true); _notifier.Success(H["{0} was disabled", feature.Name ?? feature.Id]); return RedirectToAction("Index"); } [HttpPost] public async Task<IActionResult> Enable(string id) { if (!await _authorizationService.AuthorizeAsync(User, Permissions.ApplyTheme)) // , H["Not allowed to apply theme."] { return Forbid(); } var feature = _extensionManager.GetFeatures().FirstOrDefault(f => f.Extension.IsTheme() && f.Id == id); if (feature == null) { return NotFound(); } await _shellFeaturesManager.EnableFeaturesAsync(new[] { feature }, force: true); _notifier.Success(H["{0} was enabled", feature.Name ?? feature.Id]); return RedirectToAction("Index"); } private bool IsAdminTheme(IManifestInfo manifest) { return manifest.Tags.Any(x => string.Equals(x, ManifestConstants.AdminTag, StringComparison.OrdinalIgnoreCase)); } } }
// // Obstacle.cs // MSAGL Obstacle class for Rectilinear Edge Routing. // // Copyright Microsoft Corporation. using System; using System.Diagnostics; using System.Linq; using Microsoft.Msagl.Core.DataStructures; using Microsoft.Msagl.Core.Geometry; using Microsoft.Msagl.Core.Geometry.Curves; using Microsoft.Msagl.Core.Layout; using Microsoft.Msagl.Routing.Visibility; namespace Microsoft.Msagl.Routing.Rectilinear { // Defines routing information for each obstacle in the graph. internal class Obstacle { internal const int FirstSentinelOrdinal = 1; internal const int FirstNonSentinelOrdinal = 10; /// <summary> /// Only public to make the compiler happy about the "where TPoly : new" constraint. /// Will be populated by caller. /// </summary> public Obstacle(Shape shape, bool makeRect, double padding) { if (makeRect) { var paddedBox = shape.BoundingBox; paddedBox.Pad(padding); this.PaddedPolyline = Curve.PolyFromBox(paddedBox); } else { this.PaddedPolyline = InteractiveObstacleCalculator.PaddedPolylineBoundaryOfNode(shape.BoundaryCurve, padding); #if TEST_MSAGL || VERIFY_MSAGL // This throws if the polyline is nonconvex. VisibilityGraph.CheckThatPolylineIsConvex(this.PaddedPolyline); #endif // TEST || VERIFY } RoundVertices(this.PaddedPolyline); this.IsRectangle = this.IsPolylineRectangle(); if (!this.IsRectangle) { this.ConvertToRectangleIfClose(); } InputShape = shape; Ports = new Set<Port>(InputShape.Ports); } // From CreateSentinel only Obstacle(Point a, Point b, int scanlineOrdinal) { PaddedPolyline = new Polyline(ApproximateComparer.Round(a), ApproximateComparer.Round(b)) {Closed = true}; this.Ordinal = scanlineOrdinal; } internal LowObstacleSide ActiveLowSide { get; set; } internal HighObstacleSide ActiveHighSide { get; set; } internal Shape InputShape { get; set; } internal bool IsRectangle { get; private set; } /// <summary> /// The padded polyline that is tight to the input shape. /// </summary> internal Polyline PaddedPolyline { get; private set; } /// <summary> /// The polyline that is either the PaddedPolyline or a convex hull for multiple overlapping obstacles. /// </summary> internal Polyline VisibilityPolyline { get { return (this.ConvexHull != null) ? this.ConvexHull.Polyline : this.PaddedPolyline; } } /// <summary> /// The visibility polyline that is used for intersection comparisons and group obstacle avoidance. /// </summary> internal Polyline LooseVisibilityPolyline { get { if (this.looseVisibilityPolyline == null) { this.looseVisibilityPolyline = CreateLoosePolyline(this.VisibilityPolyline); } return this.looseVisibilityPolyline; } } internal static Polyline CreateLoosePolyline(Polyline polyline) { var loosePolyline = InteractiveObstacleCalculator.CreatePaddedPolyline(polyline, ApproximateComparer.IntersectionEpsilon * 10); RoundVertices(loosePolyline); return loosePolyline; } private Polyline looseVisibilityPolyline; internal Rectangle PaddedBoundingBox { get { return PaddedPolyline.BoundingBox; } } internal Rectangle VisibilityBoundingBox { get { return VisibilityPolyline.BoundingBox; } } internal bool IsGroup { get { return (null != InputShape) && InputShape.IsGroup; } } internal bool IsTransparentAncestor { get { return InputShape == null ? false : InputShape.IsTransparent; } set { if (InputShape == null) throw new InvalidOperationException(); InputShape.IsTransparent = value; } } // The ScanLine uses this as a final tiebreaker. It is set on InitializeEventQueue rather than in // AddObstacle to avoid a possible wraparound issue if a lot of obstacles are added/removed. // For sentinels, 1/2 are left/right, 3/4 are top/bottom. 0 is invalid during scanline processing. internal int Ordinal { get; set; } /// <summary> /// For overlapping obstacle management; this is just some arbitrary obstacle in the clump. /// </summary> internal Clump Clump { get; set; } internal bool IsOverlapped { get { Debug.Assert((this.Clump == null) || !this.IsGroup, "Groups should not be considered overlapped"); Debug.Assert((this.Clump == null) || (this.ConvexHull == null), "Clumped obstacles should not have overlapped convex hulls"); return (this.Clump != null); } } public bool IsInSameClump(Obstacle other) { return this.IsOverlapped && (this.Clump == other.Clump); } /// <summary> /// For sparseVg, the obstacle has a group corner inside it. /// </summary> internal bool OverlapsGroupCorner { get; set; } // A single convex hull is shared by all obstacles contained by it and we only want one occurrence of that // convex hull's polyline in the visibility graph generation. internal bool IsPrimaryObstacle { get { return (this.ConvexHull == null) || (this == this.ConvexHull.PrimaryObstacle); } } internal OverlapConvexHull ConvexHull { get; private set; } internal bool IsInConvexHull { get { return this.ConvexHull != null; } } // Note there is no !IsGroup check internal void SetConvexHull(OverlapConvexHull hull) { // This obstacle may have been in a rectangular obstacle or clump that was now found to overlap with a non-rectangular obstacle. this.Clump = null; this.IsRectangle = false; this.ConvexHull = hull; this.looseVisibilityPolyline = null; } // Cloned from InputShape and held to test for Port-membership changes. internal Set<Port> Ports { get; private set; } internal bool IsSentinel { get { return null == InputShape; } } // Set the initial ActiveLowSide and ActiveHighSide of the obstacle starting at this point. internal void CreateInitialSides(PolylinePoint startPoint, ScanDirection scanDir) { Debug.Assert((null == ActiveLowSide) && (null == ActiveHighSide) , "Cannot call SetInitialSides when sides are already set"); ActiveLowSide = new LowObstacleSide(this, startPoint, scanDir); ActiveHighSide = new HighObstacleSide(this, startPoint, scanDir); if (scanDir.IsFlat(ActiveHighSide)) { // No flat sides in the scanline; we'll do lookahead processing in the scanline to handle overlaps // with existing segments, and normal neighbor handling will take care of collinear OpenVertexEvents. ActiveHighSide = new HighObstacleSide(this, ActiveHighSide.EndVertex, scanDir); } } // Called when we've processed the HighestVertexEvent and closed the object. internal void Close() { ActiveLowSide = null; ActiveHighSide = null; } internal static Obstacle CreateSentinel(Point a, Point b, ScanDirection scanDir, int scanlineOrdinal) { var sentinel = new Obstacle(a, b, scanlineOrdinal); sentinel.CreateInitialSides(sentinel.PaddedPolyline.StartPoint, scanDir); return sentinel; } internal static void RoundVertices(Polyline polyline) { // Following creation of the padded border, round off the vertices for consistency // in later operations (intersections and event ordering). PolylinePoint ppt = polyline.StartPoint; do { ppt.Point = ApproximateComparer.Round(ppt.Point); ppt = ppt.NextOnPolyline; } while (ppt != polyline.StartPoint); RemoveCloseAndCollinearVerticesInPlace(polyline); // We've modified the points so the BoundingBox may have changed; force it to be recalculated. polyline.RequireInit(); // Verify that the polyline is still clockwise. Debug.Assert(polyline.IsClockwise(), "Polyline is not clockwise after RoundVertices"); } internal static Polyline RemoveCloseAndCollinearVerticesInPlace(Polyline polyline) { var epsilon = ApproximateComparer.IntersectionEpsilon * 10; for (PolylinePoint pp = polyline.StartPoint.Next; pp != null; pp = pp.Next) { if (ApproximateComparer.Close(pp.Prev.Point, pp.Point, epsilon)) { if (pp.Next == null) { polyline.RemoveEndPoint(); } else { pp.Prev.Next = pp.Next; pp.Next.Prev = pp.Prev; } } } if (ApproximateComparer.Close(polyline.Start, polyline.End, epsilon)) { polyline.RemoveStartPoint(); } InteractiveEdgeRouter.RemoveCollinearVertices(polyline); if ((polyline.EndPoint.Prev != null) && (Point.GetTriangleOrientation(polyline.EndPoint.Prev.Point, polyline.End, polyline.Start) == TriangleOrientation.Collinear)) { polyline.RemoveEndPoint(); } if ((polyline.StartPoint.Next != null) && (Point.GetTriangleOrientation(polyline.End, polyline.Start, polyline.StartPoint.Next.Point) == TriangleOrientation.Collinear)) { polyline.RemoveStartPoint(); } return polyline; } private bool IsPolylineRectangle () { if (this.PaddedPolyline.PolylinePoints.Count() != 4) { return false; } var ppt = this.PaddedPolyline.StartPoint; var nextPpt = ppt.NextOnPolyline; var dir = CompassVector.DirectionsFromPointToPoint(ppt.Point, nextPpt.Point); if (!CompassVector.IsPureDirection(dir)) { return false; } do { ppt = nextPpt; nextPpt = ppt.NextOnPolyline; var nextDir = CompassVector.DirectionsFromPointToPoint(ppt.Point, nextPpt.Point); // We know the polyline is clockwise. if (nextDir != CompassVector.RotateRight(dir)) { return false; } dir = nextDir; } while (ppt != this.PaddedPolyline.StartPoint); return true; } // Internal for testing internal void ConvertToRectangleIfClose() { if (this.PaddedPolyline.PolylinePoints.Count() != 4) { return; } // We're not a rectangle now but that may be due to rounding error, so we may be close to one. // First check that it's close to an axis. var ppt = this.PaddedPolyline.StartPoint; var nextPpt = ppt.NextOnPolyline; var testPoint = ppt.Point - nextPpt.Point; var slope = ((testPoint.X == 0) || (testPoint.Y == 0)) ? 0 : Math.Abs(testPoint.Y / testPoint.X); const double factor = 1000.0; if ((slope < factor) && (slope > (1.0/factor))) { return; } const double radian90 = 90.0 * (Math.PI/180.0); const double maxAngleDiff = radian90/factor; // Now check angles. do { var nextNextPpt = nextPpt.NextOnPolyline; var angle = Point.Angle(ppt.Point, nextPpt.Point, nextNextPpt.Point); if (Math.Abs(radian90 - angle) > maxAngleDiff) { return; } ppt = nextPpt; nextPpt = nextNextPpt; } while (ppt != this.PaddedPolyline.StartPoint); this.PaddedPolyline = Curve.PolyFromBox(this.PaddedPolyline.BoundingBox); this.IsRectangle = true; Debug.Assert(this.IsPolylineRectangle(), "PaddedPolyline is not rectangular"); return; } // Return whether there were any port changes, and if so which were added and removed. internal bool GetPortChanges(out Set<Port> addedPorts, out Set<Port> removedPorts) { addedPorts = InputShape.Ports - Ports; removedPorts = Ports - InputShape.Ports; if ((0 == addedPorts.Count) && (0 == removedPorts.Count)) { return false; } Ports = new Set<Port>(InputShape.Ports); return true; } /// <summary> /// </summary> /// <returns></returns> public override string ToString() { string typeString = GetType().ToString(); int lastDotLoc = typeString.LastIndexOf('.'); if (lastDotLoc >= 0) { typeString = typeString.Substring(lastDotLoc + 1); } return typeString + " [" + InputShape + "]"; } } }
// 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 ILCompiler.DependencyAnalysisFramework; using Internal.TypeSystem; using Internal.Runtime; using Internal.IL; namespace ILCompiler.DependencyAnalysis { public class NodeFactory { private TargetDetails _target; private CompilerTypeSystemContext _context; private bool _cppCodeGen; private CompilationModuleGroup _compilationModuleGroup; public NodeFactory(CompilerTypeSystemContext context, TypeInitialization typeInitManager, CompilationModuleGroup compilationModuleGroup, bool cppCodeGen) { _target = context.Target; _context = context; _cppCodeGen = cppCodeGen; _compilationModuleGroup = compilationModuleGroup; TypeInitializationManager = typeInitManager; CreateNodeCaches(); MetadataManager = new MetadataGeneration(); } public TargetDetails Target { get { return _target; } } public CompilationModuleGroup CompilationModuleGroup { get { return _compilationModuleGroup; } } public TypeInitialization TypeInitializationManager { get; private set; } public MetadataGeneration MetadataManager { get; private set; } private struct NodeCache<TKey, TValue> { private Func<TKey, TValue> _creator; private Dictionary<TKey, TValue> _cache; public NodeCache(Func<TKey, TValue> creator, IEqualityComparer<TKey> comparer) { _creator = creator; _cache = new Dictionary<TKey, TValue>(comparer); } public NodeCache(Func<TKey, TValue> creator) { _creator = creator; _cache = new Dictionary<TKey, TValue>(); } public TValue GetOrAdd(TKey key) { TValue result; if (!_cache.TryGetValue(key, out result)) { result = _creator(key); _cache.Add(key, result); } return result; } } private void CreateNodeCaches() { _typeSymbols = new NodeCache<TypeDesc, IEETypeNode>((TypeDesc type) => { if (_compilationModuleGroup.ContainsType(type)) { return new EETypeNode(type, false); } else { return new ExternEETypeSymbolNode(type); } }); _constructedTypeSymbols = new NodeCache<TypeDesc, IEETypeNode>((TypeDesc type) => { if (_compilationModuleGroup.ContainsType(type)) { return new EETypeNode(type, true); } else { return new ExternEETypeSymbolNode(type); } }); _nonGCStatics = new NodeCache<MetadataType, NonGCStaticsNode>((MetadataType type) => { return new NonGCStaticsNode(type, this); }); _GCStatics = new NodeCache<MetadataType, GCStaticsNode>((MetadataType type) => { return new GCStaticsNode(type); }); _GCStaticIndirectionNodes = new NodeCache<MetadataType, EmbeddedObjectNode>((MetadataType type) => { ISymbolNode gcStaticsNode = TypeGCStaticsSymbol(type); Debug.Assert(gcStaticsNode is GCStaticsNode); return GCStaticsRegion.NewNode((GCStaticsNode)gcStaticsNode); }); _threadStatics = new NodeCache<MetadataType, ThreadStaticsNode>((MetadataType type) => { return new ThreadStaticsNode(type, this); }); _GCStaticEETypes = new NodeCache<GCPointerMap, GCStaticEETypeNode>((GCPointerMap gcMap) => { return new GCStaticEETypeNode(Target, gcMap); }); _readOnlyDataBlobs = new NodeCache<Tuple<string, byte[], int>, BlobNode>((Tuple<string, byte[], int> key) => { return new BlobNode(key.Item1, ObjectNodeSection.ReadOnlyDataSection, key.Item2, key.Item3); }, new BlobTupleEqualityComparer()); _externSymbols = new NodeCache<string, ExternSymbolNode>((string name) => { return new ExternSymbolNode(name); }); _pInvokeModuleFixups = new NodeCache<string, PInvokeModuleFixupNode>((string name) => { return new PInvokeModuleFixupNode(name); }); _pInvokeMethodFixups = new NodeCache<Tuple<string, string>, PInvokeMethodFixupNode>((Tuple<string, string> key) => { return new PInvokeMethodFixupNode(key.Item1, key.Item2); }); _internalSymbols = new NodeCache<Tuple<ObjectNode, int, string>, ObjectAndOffsetSymbolNode>( (Tuple<ObjectNode, int, string> key) => { return new ObjectAndOffsetSymbolNode(key.Item1, key.Item2, key.Item3); }); _methodEntrypoints = new NodeCache<MethodDesc, IMethodNode>((MethodDesc method) => { if (!_cppCodeGen) { if (method.HasCustomAttribute("System.Runtime", "RuntimeImportAttribute")) { return new RuntimeImportMethodNode(method); } } if (_compilationModuleGroup.ContainsMethod(method)) { if (_cppCodeGen) return new CppMethodCodeNode(method); else return new MethodCodeNode(method); } else { return new ExternMethodSymbolNode(method); } }); _unboxingStubs = new NodeCache<MethodDesc, IMethodNode>((MethodDesc method) => { return new UnboxingStubNode(method); }); _virtMethods = new NodeCache<MethodDesc, VirtualMethodUseNode>((MethodDesc method) => { return new VirtualMethodUseNode(method); }); _readyToRunHelpers = new NodeCache<Tuple<ReadyToRunHelperId, Object>, ReadyToRunHelperNode>((Tuple < ReadyToRunHelperId, Object > helper) => { return new ReadyToRunHelperNode(helper.Item1, helper.Item2); }); _stringDataNodes = new NodeCache<string, StringDataNode>((string data) => { return new StringDataNode(data); }); _stringIndirectionNodes = new NodeCache<string, StringIndirectionNode>((string data) => { return new StringIndirectionNode(data); }); _typeOptionalFields = new NodeCache<EETypeOptionalFieldsBuilder, EETypeOptionalFieldsNode>((EETypeOptionalFieldsBuilder fieldBuilder) => { return new EETypeOptionalFieldsNode(fieldBuilder, this.Target); }); _interfaceDispatchCells = new NodeCache<MethodDesc, InterfaceDispatchCellNode>((MethodDesc method) => { return new InterfaceDispatchCellNode(method); }); _interfaceDispatchMaps = new NodeCache<TypeDesc, InterfaceDispatchMapNode>((TypeDesc type) => { return new InterfaceDispatchMapNode(type); }); _interfaceDispatchMapIndirectionNodes = new NodeCache<TypeDesc, EmbeddedObjectNode>((TypeDesc type) => { var dispatchMap = InterfaceDispatchMap(type); return DispatchMapTable.NewNodeWithSymbol(dispatchMap, (indirectionNode) => { dispatchMap.SetDispatchMapIndex(this, DispatchMapTable.IndexOfEmbeddedObject(indirectionNode)); }); }); _genericCompositions = new NodeCache<GenericCompositionDetails, GenericCompositionNode>((GenericCompositionDetails details) => { return new GenericCompositionNode(details); }); _eagerCctorIndirectionNodes = new NodeCache<MethodDesc, EmbeddedObjectNode>((MethodDesc method) => { Debug.Assert(method.IsStaticConstructor); Debug.Assert(TypeInitializationManager.HasEagerStaticConstructor((MetadataType)method.OwningType)); return EagerCctorTable.NewNode(MethodEntrypoint(method)); }); _vTableNodes = new NodeCache<TypeDesc, VTableSliceNode>((TypeDesc type ) => { if (CompilationModuleGroup.ShouldProduceFullType(type)) return new EagerlyBuiltVTableSliceNode(type); else return new LazilyBuiltVTableSliceNode(type); }); _jumpThunks = new NodeCache<Tuple<ExternSymbolNode, ISymbolNode>, SingleArgumentJumpThunk>((Tuple<ExternSymbolNode, ISymbolNode> data) => { return new SingleArgumentJumpThunk(data.Item1, data.Item2); }); } private NodeCache<TypeDesc, IEETypeNode> _typeSymbols; public IEETypeNode NecessaryTypeSymbol(TypeDesc type) { return _typeSymbols.GetOrAdd(type); } private NodeCache<TypeDesc, IEETypeNode> _constructedTypeSymbols; public IEETypeNode ConstructedTypeSymbol(TypeDesc type) { return _constructedTypeSymbols.GetOrAdd(type); } private NodeCache<MetadataType, NonGCStaticsNode> _nonGCStatics; public ISymbolNode TypeNonGCStaticsSymbol(MetadataType type) { if (_compilationModuleGroup.ContainsType(type)) { return _nonGCStatics.GetOrAdd(type); } else { return ExternSymbol("__NonGCStaticBase_" + NodeFactory.NameMangler.GetMangledTypeName(type)); } } private NodeCache<MetadataType, GCStaticsNode> _GCStatics; public ISymbolNode TypeGCStaticsSymbol(MetadataType type) { if (_compilationModuleGroup.ContainsType(type)) { return _GCStatics.GetOrAdd(type); } else { return ExternSymbol("__GCStaticBase_" + NodeFactory.NameMangler.GetMangledTypeName(type)); } } private NodeCache<MetadataType, EmbeddedObjectNode> _GCStaticIndirectionNodes; public EmbeddedObjectNode GCStaticIndirection(MetadataType type) { return _GCStaticIndirectionNodes.GetOrAdd(type); } private NodeCache<MetadataType, ThreadStaticsNode> _threadStatics; public ISymbolNode TypeThreadStaticsSymbol(MetadataType type) { if (_compilationModuleGroup.ContainsType(type)) { return _threadStatics.GetOrAdd(type); } else { return ExternSymbol("__ThreadStaticBase_" + NodeFactory.NameMangler.GetMangledTypeName(type)); } } private NodeCache<MethodDesc, InterfaceDispatchCellNode> _interfaceDispatchCells; internal InterfaceDispatchCellNode InterfaceDispatchCell(MethodDesc method) { return _interfaceDispatchCells.GetOrAdd(method); } private class BlobTupleEqualityComparer : IEqualityComparer<Tuple<string, byte[], int>> { bool IEqualityComparer<Tuple<string, byte[], int>>.Equals(Tuple<string, byte[], int> x, Tuple<string, byte[], int> y) { return x.Item1.Equals(y.Item1); } int IEqualityComparer<Tuple<string, byte[], int>>.GetHashCode(Tuple<string, byte[], int> obj) { return obj.Item1.GetHashCode(); } } private NodeCache<GCPointerMap, GCStaticEETypeNode> _GCStaticEETypes; public ISymbolNode GCStaticEEType(GCPointerMap gcMap) { return _GCStaticEETypes.GetOrAdd(gcMap); } private NodeCache<Tuple<string, byte[], int>, BlobNode> _readOnlyDataBlobs; public BlobNode ReadOnlyDataBlob(string name, byte[] blobData, int alignment) { return _readOnlyDataBlobs.GetOrAdd(new Tuple<string, byte[], int>(name, blobData, alignment)); } private NodeCache<EETypeOptionalFieldsBuilder, EETypeOptionalFieldsNode> _typeOptionalFields; internal EETypeOptionalFieldsNode EETypeOptionalFields(EETypeOptionalFieldsBuilder fieldBuilder) { return _typeOptionalFields.GetOrAdd(fieldBuilder); } private NodeCache<TypeDesc, InterfaceDispatchMapNode> _interfaceDispatchMaps; internal InterfaceDispatchMapNode InterfaceDispatchMap(TypeDesc type) { return _interfaceDispatchMaps.GetOrAdd(type); } private NodeCache<TypeDesc, EmbeddedObjectNode> _interfaceDispatchMapIndirectionNodes; public EmbeddedObjectNode InterfaceDispatchMapIndirection(TypeDesc type) { return _interfaceDispatchMapIndirectionNodes.GetOrAdd(type); } private NodeCache<GenericCompositionDetails, GenericCompositionNode> _genericCompositions; public ISymbolNode GenericComposition(GenericCompositionDetails details) { return _genericCompositions.GetOrAdd(details); } private NodeCache<string, ExternSymbolNode> _externSymbols; public ISymbolNode ExternSymbol(string name) { return _externSymbols.GetOrAdd(name); } private NodeCache<string, PInvokeModuleFixupNode> _pInvokeModuleFixups; public ISymbolNode PInvokeModuleFixup(string moduleName) { return _pInvokeModuleFixups.GetOrAdd(moduleName); } private NodeCache<Tuple<string, string>, PInvokeMethodFixupNode> _pInvokeMethodFixups; public PInvokeMethodFixupNode PInvokeMethodFixup(string moduleName, string entryPointName) { return _pInvokeMethodFixups.GetOrAdd(new Tuple<string, string>(moduleName, entryPointName)); } private NodeCache<Tuple<ObjectNode, int, string>, ObjectAndOffsetSymbolNode> _internalSymbols; public ISymbolNode ObjectAndOffset(ObjectNode obj, int offset, string name) { return _internalSymbols.GetOrAdd(new Tuple<ObjectNode, int, string>(obj, offset, name)); } private NodeCache<TypeDesc, VTableSliceNode> _vTableNodes; internal VTableSliceNode VTable(TypeDesc type) { return _vTableNodes.GetOrAdd(type); } private NodeCache<Tuple<ExternSymbolNode, ISymbolNode>, SingleArgumentJumpThunk> _jumpThunks; /// <summary> /// Create a thunk that calls an externally defined (e.g., native) function, passing /// a dependency node to the function it calls. /// </summary> internal SingleArgumentJumpThunk JumpThunk(ExternSymbolNode target, ISymbolNode argument) { return _jumpThunks.GetOrAdd(new Tuple<ExternSymbolNode, ISymbolNode>(target, argument)); } private NodeCache<MethodDesc, IMethodNode> _methodEntrypoints; private NodeCache<MethodDesc, IMethodNode> _unboxingStubs; public IMethodNode MethodEntrypoint(MethodDesc method, bool unboxingStub = false) { if (unboxingStub) { return _unboxingStubs.GetOrAdd(method); } return _methodEntrypoints.GetOrAdd(method); } private static readonly string[][] s_helperEntrypointNames = new string[][] { new string[] { "System.Runtime.CompilerServices", "ClassConstructorRunner", "CheckStaticClassConstructionReturnGCStaticBase" }, new string[] { "System.Runtime.CompilerServices", "ClassConstructorRunner", "CheckStaticClassConstructionReturnNonGCStaticBase" } }; private ISymbolNode[] _helperEntrypointSymbols; public ISymbolNode HelperEntrypoint(HelperEntrypoint entrypoint) { if (_helperEntrypointSymbols == null) _helperEntrypointSymbols = new ISymbolNode[s_helperEntrypointNames.Length]; int index = (int)entrypoint; ISymbolNode symbol = _helperEntrypointSymbols[index]; if (symbol == null) { var entry = s_helperEntrypointNames[index]; var type = _context.SystemModule.GetKnownType(entry[0], entry[1]); var method = type.GetKnownMethod(entry[2], null); symbol = MethodEntrypoint(method); _helperEntrypointSymbols[index] = symbol; } return symbol; } private MetadataType _systemArrayOfTClass; public MetadataType ArrayOfTClass { get { if (_systemArrayOfTClass == null) { _systemArrayOfTClass = _context.SystemModule.GetKnownType("System", "Array`1"); } return _systemArrayOfTClass; } } private TypeDesc _systemArrayOfTEnumeratorType; public TypeDesc ArrayOfTEnumeratorType { get { if (_systemArrayOfTEnumeratorType == null) { _systemArrayOfTEnumeratorType = ArrayOfTClass.GetNestedType("ArrayEnumerator"); } return _systemArrayOfTEnumeratorType; } } private TypeDesc _systemICastableType; public TypeDesc ICastableInterface { get { if (_systemICastableType == null) { _systemICastableType = _context.SystemModule.GetKnownType("System.Runtime.CompilerServices", "ICastable"); } return _systemICastableType; } } private NodeCache<MethodDesc, VirtualMethodUseNode> _virtMethods; public DependencyNode VirtualMethodUse(MethodDesc decl) { return _virtMethods.GetOrAdd(decl); } private NodeCache<Tuple<ReadyToRunHelperId, Object>, ReadyToRunHelperNode> _readyToRunHelpers; public ISymbolNode ReadyToRunHelper(ReadyToRunHelperId id, Object target) { return _readyToRunHelpers.GetOrAdd(new Tuple<ReadyToRunHelperId, object>(id, target)); } private NodeCache<string, StringDataNode> _stringDataNodes; public StringDataNode StringData(string data) { return _stringDataNodes.GetOrAdd(data); } private NodeCache<string, StringIndirectionNode> _stringIndirectionNodes; public StringIndirectionNode StringIndirection(string data) { return _stringIndirectionNodes.GetOrAdd(data); } private NodeCache<MethodDesc, EmbeddedObjectNode> _eagerCctorIndirectionNodes; public EmbeddedObjectNode EagerCctorIndirection(MethodDesc cctorMethod) { return _eagerCctorIndirectionNodes.GetOrAdd(cctorMethod); } /// <summary> /// Returns alternative symbol name that object writer should produce for given symbols /// in addition to the regular one. /// </summary> public string GetSymbolAlternateName(ISymbolNode node) { string value; if (!NodeAliases.TryGetValue(node, out value)) return null; return value; } public ArrayOfEmbeddedPointersNode<GCStaticsNode> GCStaticsRegion = new ArrayOfEmbeddedPointersNode<GCStaticsNode>( NameMangler.CompilationUnitPrefix + "__GCStaticRegionStart", NameMangler.CompilationUnitPrefix + "__GCStaticRegionEnd", null); public ArrayOfEmbeddedDataNode ThreadStaticsRegion = new ArrayOfEmbeddedDataNode( NameMangler.CompilationUnitPrefix + "__ThreadStaticRegionStart", NameMangler.CompilationUnitPrefix + "__ThreadStaticRegionEnd", null); public ArrayOfEmbeddedDataNode StringTable = new ArrayOfEmbeddedDataNode( NameMangler.CompilationUnitPrefix + "__StringTableStart", NameMangler.CompilationUnitPrefix + "__StringTableEnd", null); public ArrayOfEmbeddedPointersNode<IMethodNode> EagerCctorTable = new ArrayOfEmbeddedPointersNode<IMethodNode>( NameMangler.CompilationUnitPrefix + "__EagerCctorStart", NameMangler.CompilationUnitPrefix + "__EagerCctorEnd", new EagerConstructorComparer()); public ArrayOfEmbeddedPointersNode<InterfaceDispatchMapNode> DispatchMapTable = new ArrayOfEmbeddedPointersNode<InterfaceDispatchMapNode>( NameMangler.CompilationUnitPrefix + "__DispatchMapTableStart", NameMangler.CompilationUnitPrefix + "__DispatchMapTableEnd", null); public ReadyToRunHeaderNode ReadyToRunHeader; public Dictionary<ISymbolNode, string> NodeAliases = new Dictionary<ISymbolNode, string>(); internal ModuleManagerIndirectionNode ModuleManagerIndirection = new ModuleManagerIndirectionNode(); public static NameMangler NameMangler; public void AttachToDependencyGraph(DependencyAnalysisFramework.DependencyAnalyzerBase<NodeFactory> graph) { ReadyToRunHeader = new ReadyToRunHeaderNode(Target); graph.AddRoot(ReadyToRunHeader, "ReadyToRunHeader is always generated"); graph.AddRoot(new ModulesSectionNode(), "ModulesSection is always generated"); graph.AddRoot(GCStaticsRegion, "GC StaticsRegion is always generated"); graph.AddRoot(ThreadStaticsRegion, "ThreadStaticsRegion is always generated"); graph.AddRoot(StringTable, "StringTable is always generated"); graph.AddRoot(EagerCctorTable, "EagerCctorTable is always generated"); graph.AddRoot(ModuleManagerIndirection, "ModuleManagerIndirection is always generated"); graph.AddRoot(DispatchMapTable, "DispatchMapTable is always generated"); ReadyToRunHeader.Add(ReadyToRunSectionType.GCStaticRegion, GCStaticsRegion, GCStaticsRegion.StartSymbol, GCStaticsRegion.EndSymbol); ReadyToRunHeader.Add(ReadyToRunSectionType.ThreadStaticRegion, ThreadStaticsRegion, ThreadStaticsRegion.StartSymbol, ThreadStaticsRegion.EndSymbol); ReadyToRunHeader.Add(ReadyToRunSectionType.StringTable, StringTable, StringTable.StartSymbol, StringTable.EndSymbol); ReadyToRunHeader.Add(ReadyToRunSectionType.EagerCctor, EagerCctorTable, EagerCctorTable.StartSymbol, EagerCctorTable.EndSymbol); ReadyToRunHeader.Add(ReadyToRunSectionType.ModuleManagerIndirection, ModuleManagerIndirection, ModuleManagerIndirection); ReadyToRunHeader.Add(ReadyToRunSectionType.InterfaceDispatchTable, DispatchMapTable, DispatchMapTable.StartSymbol); MetadataManager.AddToReadyToRunHeader(ReadyToRunHeader); MetadataManager.AttachToDependencyGraph(graph); } } public enum HelperEntrypoint { EnsureClassConstructorRunAndReturnGCStaticBase, EnsureClassConstructorRunAndReturnNonGCStaticBase, } }
using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Reflection; using System.Text; namespace Hydra.Framework.Conversions { // // ********************************************************************** /// <summary> /// Utliity methods to work with file path. /// </summary> // ********************************************************************** // public class ConvertPath { #region Static Methods // // ********************************************************************** /// <summary> /// Convert absolute path into relative path /// </summary> /// <param name="absolutePath">absolute path need to convert into relative path</param> /// <param name="basePath">current absolute path</param> /// <returns>relative path</returns> // ********************************************************************** // static public string ConvertToRelative(string absolutePath, string basePath) { string dirSeparator = Path.DirectorySeparatorChar.ToString(); string relativeSeparator = ".." + dirSeparator; string relativePath = absolutePath.ToLower(); string currentPath = Path.GetDirectoryName(basePath).ToLower(); int pos = relativePath.IndexOf(currentPath); int pos_cut; int levelUp = 0; if (pos == -1) { // // Replace all slash with correct directory separator // string tmpPath = currentPath.Replace("/", dirSeparator); // // Remove last slash // if (tmpPath.Substring(tmpPath.Length - 1, 1) == dirSeparator) tmpPath = tmpPath.Substring(0, tmpPath.Length - 2); do { pos = tmpPath.LastIndexOf(dirSeparator); if (pos != -1) { tmpPath = tmpPath.Substring(0, pos); pos_cut = relativePath.IndexOf(tmpPath); if (pos_cut == -1) { levelUp++; } else { relativePath = relativePath.Substring(pos_cut + tmpPath.Length + 1); tmpPath = ""; for (int i = 0; i <= levelUp; i++) tmpPath += relativeSeparator; relativePath = tmpPath + relativePath; tmpPath = ""; } } else { tmpPath = ""; } } while (tmpPath.Length > 0); } else if (ConvertText.NotEmpty(currentPath)) { relativePath = absolutePath.Substring(pos + currentPath.Length + 1); } return relativePath; } // // ********************************************************************** /// <summary> /// Convert relative path into absolute path /// </summary> /// <param name="relativePath">relative path need to convert into absolute path</param> /// <param name="pathToCompare">absolute path to use as base</param> /// <returns>absolute path</returns> // ********************************************************************** // static public string ConvertToAbsolute(string relativePath, string pathToCompare) { if (ConvertText.IsEmpty(relativePath)) { return pathToCompare + @"\."; } else { string currentPath = Directory.GetCurrentDirectory(); try { if (ConvertText.NotEmpty(pathToCompare)) Directory.SetCurrentDirectory(pathToCompare); return Path.GetFullPath(relativePath); } finally { Directory.SetCurrentDirectory(currentPath); } } } // // ********************************************************************** /// <summary> /// Returns system temporary path. Creates temporary directory if does not exist. /// </summary> /// <returns>system temporary path</returns> // ********************************************************************** // static public string GetTempPath() { string path = Path.GetTempPath(); if (!Directory.Exists(path)) Directory.CreateDirectory(path); return path; } // // ********************************************************************** /// <summary> /// Creates temporary directory in temporary folder. /// </summary> /// <returns>created directory name</returns> // ********************************************************************** // static public string CreateTempFolder() { string fileName = ConvertFile.CreateTempFile(); File.Delete(fileName); Directory.CreateDirectory(fileName); return fileName; } // // ********************************************************************** /// <summary> /// Returns application assemblies folder (folder where the entry assembly is located). /// Does not contain the trailing backslash. /// </summary> /// <returns> /// assemblies folder (entry assembly folder) /// </returns> // ********************************************************************** // static public string GetApplicationBinaryFolder() { string path = ""; Assembly entry = Assembly.GetEntryAssembly(); AppDomain appDomain = AppDomain.CurrentDomain; return (entry != null) ? Path.GetDirectoryName(entry.Location) : (appDomain != null) ? Path.Combine(appDomain.BaseDirectory, ConvertUtils.Nvl(appDomain.RelativeSearchPath)) : string.Empty; } // // ********************************************************************** /// <summary> /// Deletes a directory and its content without raising an exception. /// </summary> /// <param name="dirName">folder to delete</param> /// <returns>true if folder was deleted indeed</returns> // ********************************************************************** // static public bool SilentDelete(string dirName) { if (ConvertUtils.NotEmpty(dirName)) { try { ConvertFile.SetAttrRecurrent(dirName, "*.*", FileAttributes.Normal); Directory.Delete(dirName, true); return true; } catch { return false; } } return false; } // // ********************************************************************** /// <summary> /// Returns path to current user's folder in Documents and Settings folder. /// </summary> /// <returns> /// path to current user's folder in Documents and Settings folder /// </returns> // ********************************************************************** // static public string GetUserSettingsFolder() { string s = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); if (ConvertUtils.NotEmpty(ConvertAppInfo.CompanyName)) s += "\\" + ConvertAppInfo.CompanyName; if (ConvertUtils.NotEmpty(ConvertAppInfo.ApplicationCode)) s += "\\" + ConvertAppInfo.ApplicationCode; return Directory.CreateDirectory(s).FullName; } // // ********************************************************************** /// <summary> /// Returns path to current user's folder in Documents and Settings folder. /// </summary> /// <returns> /// path to current user's folder in Documents and Settings folder /// </returns> // ********************************************************************** // static public string GetDocumentsFolder() { string s = Environment.GetFolderPath(Environment.SpecialFolder.Personal); return Directory.CreateDirectory(s).FullName; } #endregion } }
// // https://github.com/NServiceKit/NServiceKit.Text // NServiceKit.Text: .NET C# POCO JSON, JSV and CSV Text Serializers. // // Authors: // Demis Bellot (demis.bellot@gmail.com) // // Copyright 2012 ServiceStack Ltd. // // Licensed under the same terms of ServiceStack: new BSD license. // using System; using System.Collections; using System.Collections.Generic; using System.Reflection; using System.Threading; using System.Linq; using NServiceKit.Text.Common; namespace NServiceKit.Text { /// <summary>A translate list with elements.</summary> public static class TranslateListWithElements { /// <summary>The translate i collection cache.</summary> private static Dictionary<Type, ConvertInstanceDelegate> TranslateICollectionCache = new Dictionary<Type, ConvertInstanceDelegate>(); /// <summary>Translate to generic i collection cache.</summary> /// <param name="from"> Source for the.</param> /// <param name="toInstanceOfType">Type of to instance of.</param> /// <param name="elementType"> Type of the element.</param> /// <returns>An object.</returns> public static object TranslateToGenericICollectionCache(object from, Type toInstanceOfType, Type elementType) { ConvertInstanceDelegate translateToFn; if (TranslateICollectionCache.TryGetValue(toInstanceOfType, out translateToFn)) return translateToFn(from, toInstanceOfType); var genericType = typeof(TranslateListWithElements<>).MakeGenericType(elementType); var mi = genericType.GetPublicStaticMethod("LateBoundTranslateToGenericICollection"); translateToFn = (ConvertInstanceDelegate)mi.MakeDelegate(typeof(ConvertInstanceDelegate)); Dictionary<Type, ConvertInstanceDelegate> snapshot, newCache; do { snapshot = TranslateICollectionCache; newCache = new Dictionary<Type, ConvertInstanceDelegate>(TranslateICollectionCache); newCache[elementType] = translateToFn; } while (!ReferenceEquals( Interlocked.CompareExchange(ref TranslateICollectionCache, newCache, snapshot), snapshot)); return translateToFn(from, toInstanceOfType); } /// <summary>The translate convertible i collection cache.</summary> private static Dictionary<ConvertibleTypeKey, ConvertInstanceDelegate> TranslateConvertibleICollectionCache = new Dictionary<ConvertibleTypeKey, ConvertInstanceDelegate>(); /// <summary>Translate to convertible generic i collection cache.</summary> /// <param name="from"> Source for the.</param> /// <param name="toInstanceOfType">Type of to instance of.</param> /// <param name="fromElementType"> Type of from element.</param> /// <returns>An object.</returns> public static object TranslateToConvertibleGenericICollectionCache( object from, Type toInstanceOfType, Type fromElementType) { var typeKey = new ConvertibleTypeKey(toInstanceOfType, fromElementType); ConvertInstanceDelegate translateToFn; if (TranslateConvertibleICollectionCache.TryGetValue(typeKey, out translateToFn)) return translateToFn(from, toInstanceOfType); var toElementType = toInstanceOfType.GetGenericType().GenericTypeArguments()[0]; var genericType = typeof(TranslateListWithConvertibleElements<,>).MakeGenericType(fromElementType, toElementType); var mi = genericType.GetPublicStaticMethod("LateBoundTranslateToGenericICollection"); translateToFn = (ConvertInstanceDelegate)mi.MakeDelegate(typeof(ConvertInstanceDelegate)); Dictionary<ConvertibleTypeKey, ConvertInstanceDelegate> snapshot, newCache; do { snapshot = TranslateConvertibleICollectionCache; newCache = new Dictionary<ConvertibleTypeKey, ConvertInstanceDelegate>(TranslateConvertibleICollectionCache); newCache[typeKey] = translateToFn; } while (!ReferenceEquals( Interlocked.CompareExchange(ref TranslateConvertibleICollectionCache, newCache, snapshot), snapshot)); return translateToFn(from, toInstanceOfType); } /// <summary>Try translate to generic i collection.</summary> /// <param name="fromPropertyType">Type of from property.</param> /// <param name="toPropertyType"> Type of to property.</param> /// <param name="fromValue"> from value.</param> /// <returns>An object.</returns> public static object TryTranslateToGenericICollection(Type fromPropertyType, Type toPropertyType, object fromValue) { var args = typeof(ICollection<>).GetGenericArgumentsIfBothHaveSameGenericDefinitionTypeAndArguments( fromPropertyType, toPropertyType); if (args != null) { return TranslateToGenericICollectionCache( fromValue, toPropertyType, args[0]); } var varArgs = typeof(ICollection<>).GetGenericArgumentsIfBothHaveConvertibleGenericDefinitionTypeAndArguments( fromPropertyType, toPropertyType); if (varArgs != null) { return TranslateToConvertibleGenericICollectionCache( fromValue, toPropertyType, varArgs.Args1[0]); } return null; } } /// <summary>A convertible type key.</summary> public class ConvertibleTypeKey { /// <summary>Gets or sets the type of to instance.</summary> /// <value>The type of to instance.</value> public Type ToInstanceType { get; set; } /// <summary>Gets or sets the type of from elemenet.</summary> /// <value>The type of from elemenet.</value> public Type FromElemenetType { get; set; } /// <summary> /// Initializes a new instance of the NServiceKit.Text.ConvertibleTypeKey class. /// </summary> public ConvertibleTypeKey() { } /// <summary> /// Initializes a new instance of the NServiceKit.Text.ConvertibleTypeKey class. /// </summary> /// <param name="toInstanceType"> Type of to instance.</param> /// <param name="fromElemenetType">Type of from elemenet.</param> public ConvertibleTypeKey(Type toInstanceType, Type fromElemenetType) { ToInstanceType = toInstanceType; FromElemenetType = fromElemenetType; } /// <summary> /// Determines whether the specified <see cref="T:System.Object" /> is equal to the current /// <see cref="T:System.Object" />. /// </summary> /// <param name="other">The convertible type key to compare to this object.</param> /// <returns> /// true if the specified <see cref="T:System.Object" /> is equal to the current /// <see cref="T:System.Object" />; otherwise, false. /// </returns> public bool Equals(ConvertibleTypeKey other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; return Equals(other.ToInstanceType, ToInstanceType) && Equals(other.FromElemenetType, FromElemenetType); } /// <summary> /// Determines whether the specified <see cref="T:System.Object" /> is equal to the current /// <see cref="T:System.Object" />. /// </summary> /// <param name="obj">The <see cref="T:System.Object" /> to compare with the current /// <see cref="T:System.Object" />.</param> /// <returns> /// true if the specified <see cref="T:System.Object" /> is equal to the current /// <see cref="T:System.Object" />; otherwise, false. /// </returns> public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; if (obj.GetType() != typeof(ConvertibleTypeKey)) return false; return Equals((ConvertibleTypeKey)obj); } /// <summary>Serves as a hash function for a particular type.</summary> /// <returns>A hash code for the current <see cref="T:System.Object" />.</returns> public override int GetHashCode() { unchecked { return ((ToInstanceType != null ? ToInstanceType.GetHashCode() : 0) * 397) ^ (FromElemenetType != null ? FromElemenetType.GetHashCode() : 0); } } } /// <summary>A translate list with elements.</summary> /// <typeparam name="T">Generic type parameter.</typeparam> public class TranslateListWithElements<T> { /// <summary>Creates an instance.</summary> /// <param name="toInstanceOfType">Type of to instance of.</param> /// <returns>The new instance.</returns> public static object CreateInstance(Type toInstanceOfType) { if (toInstanceOfType.IsGeneric()) { if (toInstanceOfType.HasAnyTypeDefinitionsOf( typeof(ICollection<>), typeof(IList<>))) { return ReflectionExtensions.CreateInstance(typeof(List<T>)); } } return ReflectionExtensions.CreateInstance(toInstanceOfType); } /// <summary>Translate to i list.</summary> /// <param name="fromList"> List of froms.</param> /// <param name="toInstanceOfType">Type of to instance of.</param> /// <returns>An IList.</returns> public static IList TranslateToIList(IList fromList, Type toInstanceOfType) { var to = (IList)ReflectionExtensions.CreateInstance(toInstanceOfType); foreach (var item in fromList) { to.Add(item); } return to; } /// <summary>Late bound translate to generic i collection.</summary> /// <param name="fromList"> List of froms.</param> /// <param name="toInstanceOfType">Type of to instance of.</param> /// <returns>An object.</returns> public static object LateBoundTranslateToGenericICollection( object fromList, Type toInstanceOfType) { if (fromList == null) return null; //AOT return TranslateToGenericICollection( (ICollection<T>)fromList, toInstanceOfType); } /// <summary>Translate to generic i collection.</summary> /// <param name="fromList"> List of froms.</param> /// <param name="toInstanceOfType">Type of to instance of.</param> /// <returns>A list of.</returns> public static ICollection<T> TranslateToGenericICollection( ICollection<T> fromList, Type toInstanceOfType) { var to = (ICollection<T>)CreateInstance(toInstanceOfType); foreach (var item in fromList) { to.Add(item); } return to; } } /// <summary>A translate list with convertible elements.</summary> /// <typeparam name="TFrom">Type of from.</typeparam> /// <typeparam name="TTo"> Type of to.</typeparam> public class TranslateListWithConvertibleElements<TFrom, TTo> { /// <summary>The convert function.</summary> private static readonly Func<TFrom, TTo> ConvertFn; /// <summary> /// Initializes static members of the NServiceKit.Text.TranslateListWithConvertibleElements&lt; /// TFrom, TTo&gt; class. /// </summary> static TranslateListWithConvertibleElements() { ConvertFn = GetConvertFn(); } /// <summary>Late bound translate to generic i collection.</summary> /// <param name="fromList"> List of froms.</param> /// <param name="toInstanceOfType">Type of to instance of.</param> /// <returns>An object.</returns> public static object LateBoundTranslateToGenericICollection( object fromList, Type toInstanceOfType) { return TranslateToGenericICollection( (ICollection<TFrom>)fromList, toInstanceOfType); } /// <summary>Translate to generic i collection.</summary> /// <param name="fromList"> List of froms.</param> /// <param name="toInstanceOfType">Type of to instance of.</param> /// <returns>A list of.</returns> public static ICollection<TTo> TranslateToGenericICollection( ICollection<TFrom> fromList, Type toInstanceOfType) { if (fromList == null) return null; //AOT var to = (ICollection<TTo>)TranslateListWithElements<TTo>.CreateInstance(toInstanceOfType); foreach (var item in fromList) { var toItem = ConvertFn(item); to.Add(toItem); } return to; } /// <summary>Gets convert function.</summary> /// <returns>The convert function.</returns> private static Func<TFrom, TTo> GetConvertFn() { if (typeof(TTo) == typeof(string)) { return x => (TTo)(object)TypeSerializer.SerializeToString(x); } if (typeof(TFrom) == typeof(string)) { return x => TypeSerializer.DeserializeFromString<TTo>((string)(object)x); } return x => TypeSerializer.DeserializeFromString<TTo>(TypeSerializer.SerializeToString(x)); } } }
/* *************************************************************************** * This file is part of SharpNEAT - Evolution of Neural Networks. * * Copyright 2004-2016 Colin Green (sharpneat@gmail.com) * * SharpNEAT is free software; you can redistribute it and/or modify * it under the terms of The MIT License (MIT). * * You should have received a copy of the MIT License * along with SharpNEAT; if not, see https://opensource.org/licenses/MIT. */ using System; using SharpNeat.Core; using SharpNeat.Phenomes; using SharpNeat.DomainsExtra.SinglePoleBalancingBox2d; namespace SharpNeat.DomainsExtra.SinglePoleBalancingSwingUp { /// <summary> /// Evaluator for the single pole balancing task. /// </summary> public class SinglePoleBalancingSwingUpEvaluator : IPhenomeEvaluator<IBlackBox> { #region Constants const float __TrackLength = 4.8f; const float __TrackLengthHalf = __TrackLength * 0.5f; const float __MaxForceNewtons = 100f; const float __MaxForceNewtonsX2 = __MaxForceNewtons * 2f; // Some precalced angle constants. const float __SixDegrees = (float)(Math.PI / 30.0); //= 0.1047192; const float __TwelveDegrees = (float)(Math.PI / 15.0); //= 0.2094384; const float __180Degrees = (float)(Math.PI / 2.0); #endregion #region Instance Fields int _maxTimestepsPhase1; int _maxTimestepsPhase2; float _poleAngleInitial; // Evaluator state. ulong _evalCount; #endregion #region Constructors /// <summary> /// Construct evaluator with default task arguments/variables. /// </summary> public SinglePoleBalancingSwingUpEvaluator() : this(450, 10800, (float)Math.PI) {} /// <summary> /// Construct evaluator with the provided task arguments/variables. /// </summary> public SinglePoleBalancingSwingUpEvaluator(int maxTimestepsPhase1, int maxTimestepsPhase2, float poleAngleInitial) { _maxTimestepsPhase1 = maxTimestepsPhase1; _maxTimestepsPhase2 = maxTimestepsPhase2; _poleAngleInitial = poleAngleInitial; } #endregion #region IPhenomeEvaluator<IBlackBox> Members /// <summary> /// Gets the total number of evaluations that have been performed. /// </summary> public ulong EvaluationCount { get { return _evalCount; } } /// <summary> /// Gets a value indicating whether some goal fitness has been achieved and that /// the evolutionary algorithm/search should stop. This property's value can remain false /// to allow the algorithm to run indefinitely. /// </summary> public bool StopConditionSatisfied { get { return false; } } /// <summary> /// Evaluate the provided IBlackBox. /// </summary> public FitnessInfo Evaluate(IBlackBox box) { _evalCount++; double fitness1 = Evaluate_Phase1_SwingUp(box); //double fitness2 = Evaluate_Phase2_Balancing(box); //double fitness = fitness1 * fitness2; return new FitnessInfo(fitness1, fitness1); } /// <summary> /// Reset the internal state of the evaluation scheme if any exists. /// </summary> public void Reset() { } #endregion #region Private Methods private double Evaluate_Phase1_SwingUp(IBlackBox box) { // Init sim world. We add extra length to the track to allow cart to overshoot, we then detect overshooting by monitoring the cart's X position // (this is just simpler and more robust than detecting if the cart has hit the ends of the track exactly). SinglePoleBalancingWorld simWorld = new SinglePoleBalancingWorld(__TrackLength + 0.5f, __180Degrees); simWorld.InitSimulationWorld(); // Record closest approach to target state and the timestep that it occurred on. double lowestError = double.MaxValue; int timestepLowest = 0; // Run the pole-balancing simulation. int timestep = 0; for(; timestep < _maxTimestepsPhase1; timestep++) { SimulateOneStep(simWorld, box); // Calc state distance from target state. double cartPosError = Math.Abs(simWorld.CartPosX); double cartVelocityError = Math.Abs(simWorld.CartVelocityX); double poleAngleError = Math.Abs(simWorld.PoleAngle); double poleAnglularVelocityError = Math.Abs(simWorld.PoleAngularVelocity); double error = (poleAngleError) + (poleAnglularVelocityError) + (cartPosError); // Check for failure state. Has the cart run off the ends of the track. if((simWorld.CartPosX < -__TrackLengthHalf) || (simWorld.CartPosX > __TrackLengthHalf)) { return 0.0; } // Track best state achieved. if(error < lowestError) { lowestError = error; timestepLowest = timestep; } } if(0.0 == lowestError) { return 10e9; } // Alternative form of 1/x that avoids rapid rise to infinity as lowestError tends towards zero. return Math.Log10(1.0 + (1/(lowestError + 0.1))); } private double Evaluate_Phase2_Balancing(IBlackBox box) { // Init sim world. We add extra length to the track to allow cart to overshoot, we then detect overshooting by monitoring the cart's X position // (this is just simpler and more robust than detecting if the cart has hit the ends of the track exactly). SinglePoleBalancingWorld simWorld = new SinglePoleBalancingWorld(__TrackLength + 0.5f, __SixDegrees); simWorld.InitSimulationWorld(); // Run the pole-balancing simulation. int timestep = 0; for(; timestep < _maxTimestepsPhase2; timestep++) { SimulateOneStep(simWorld, box); // Check for failure state. Has the cart run off the ends of the track or has the pole // angle gone beyond the threshold. if( (simWorld.CartPosX < -__TrackLengthHalf) || (simWorld.CartPosX > __TrackLengthHalf) || (simWorld.PoleAngle > __TwelveDegrees) || (simWorld.PoleAngle < -__TwelveDegrees)) { break; } } return timestep; } private void SimulateOneStep(SinglePoleBalancingWorld simWorld, IBlackBox box) { // Provide state info to the black box inputs. box.InputSignalArray[0] = simWorld.CartPosX / __TrackLengthHalf; // CartPosX range is +-trackLengthHalf. Here we normalize it to [-1,1]. box.InputSignalArray[1] = simWorld.CartVelocityX; // Cart track velocity x is typically +-0.75. box.InputSignalArray[2] = simWorld.PoleAngle / __TwelveDegrees; // Rescale angle to match range of values during balancing. box.InputSignalArray[3] = simWorld.PoleAngularVelocity; // Pole angular velocity is typically +-1.0 radians. No scaling required. // Activate the network. box.Activate(); // Read the network's force signal output. float force = (float)(box.OutputSignalArray[0] - 0.5f) * __MaxForceNewtonsX2; // Simulate one timestep. simWorld.SetCartForce(force); simWorld.Step(); } #endregion } }
// UInt64Test.cs - NUnit Test Cases for the System.UInt64 struct // // Mario Martinez (mariom925@home.om) // // (C) Ximian, Inc. http://www.ximian.com // using NUnit.Framework; using System; using System.Globalization; using System.Threading; namespace MonoTests.System { [TestFixture] public class UInt64Test : Assertion { private const UInt64 MyUInt64_1 = 42; private const UInt64 MyUInt64_2 = 0; private const UInt64 MyUInt64_3 = 18446744073709551615; private const string MyString1 = "42"; private const string MyString2 = "0"; private const string MyString3 = "18446744073709551615"; private string[] Formats1 = {"c", "d", "e", "f", "g", "n", "p", "x" }; private string[] Formats2 = {"c5", "d5", "e5", "f5", "g5", "n5", "p5", "x5" }; private string[] Results1 = {"", "0", "0.000000e+000", "0.00", "0", "0.00", "0.00 %", "0"}; private string[] ResultsNfi1 = {NumberFormatInfo.InvariantInfo.CurrencySymbol+"0.00", "0", "0.000000e+000", "0.00", "0", "0.00", "0.00 %", "0"}; private string[] Results2 = {"", "18446744073709551615", "1.84467e+019", "18446744073709551615.00000", "1.8447e+19", "18,446,744,073,709,551,615.00000", "1,844,674,407,370,955,161,500.00000 %", "ffffffffffffffff"}; private string[] ResultsNfi2 = {NumberFormatInfo.InvariantInfo.CurrencySymbol+"18,446,744,073,709,551,615.00000", "18446744073709551615", "1.84467e+019", "18446744073709551615.00000", "1.8447e+19", "18,446,744,073,709,551,615.00000", "1,844,674,407,370,955,161,500.00000 %", "ffffffffffffffff"}; private NumberFormatInfo Nfi = NumberFormatInfo.InvariantInfo; private CultureInfo old_culture; [TestFixtureSetUp] public void SetUp() { old_culture = Thread.CurrentThread.CurrentCulture; // Set culture to en-US and don't let the user override. Thread.CurrentThread.CurrentCulture = new CultureInfo ("en-US", false); // We can't initialize this until we set the culture. string decimals = new String ('0', NumberFormatInfo.CurrentInfo.NumberDecimalDigits); string perPattern = new string[] {"n %","n%","%n"} [NumberFormatInfo.CurrentInfo.PercentPositivePattern]; Results1 [0] = NumberFormatInfo.CurrentInfo.CurrencySymbol + "0.00"; Results1 [3] = "0." + decimals; Results1 [5] = "0." + decimals; Results1 [6] = perPattern.Replace ("n","0.00"); Results2 [0] = NumberFormatInfo.CurrentInfo.CurrencySymbol + "18,446,744,073,709,551,615.00000"; Results2 [6] = perPattern.Replace ("n","1,844,674,407,370,955,161,500.00000"); } [TestFixtureTearDown] public void TearDown () { Thread.CurrentThread.CurrentCulture = old_culture; } public void TestMinMax() { AssertEquals(UInt64.MinValue, MyUInt64_2); AssertEquals(UInt64.MaxValue, MyUInt64_3); } public void TestCompareTo() { Assert(MyUInt64_3.CompareTo(MyUInt64_2) > 0); Assert(MyUInt64_2.CompareTo(MyUInt64_2) == 0); Assert(MyUInt64_1.CompareTo((UInt64)(42)) == 0); Assert(MyUInt64_2.CompareTo(MyUInt64_3) < 0); try { MyUInt64_2.CompareTo((object)(Int16)100); Fail("Should raise a System.ArgumentException"); } catch (Exception e) { Assert(typeof(ArgumentException) == e.GetType()); } } public void TestEquals() { Assert(MyUInt64_1.Equals(MyUInt64_1)); Assert(MyUInt64_1.Equals((object)(UInt64)(42))); Assert(MyUInt64_1.Equals((object)(SByte)(42)) == false); Assert(MyUInt64_1.Equals(MyUInt64_2) == false); } public void TestGetHashCode() { try { MyUInt64_1.GetHashCode(); MyUInt64_2.GetHashCode(); MyUInt64_3.GetHashCode(); } catch { Fail("GetHashCode should not raise an exception here"); } } public void TestParse() { //test Parse(string s) Assert(MyUInt64_1 == UInt64.Parse(MyString1)); Assert(MyUInt64_2 == UInt64.Parse(MyString2)); Assert(MyUInt64_3 == UInt64.Parse(MyString3)); try { UInt64.Parse(null); Fail("Should raise a ArgumentNullException"); } catch (Exception e) { Assert(typeof(ArgumentNullException) == e.GetType()); } try { UInt64.Parse("not-a-number"); Fail("Should raise a System.FormatException"); } catch (Exception e) { Assert(typeof(FormatException) == e.GetType()); } //test Parse(string s, NumberStyles style) try { double OverInt = (double)UInt64.MaxValue + 1; UInt64.Parse(OverInt.ToString(), NumberStyles.Float); Fail("Should raise a OverflowException"); } catch (Exception e) { Assert(typeof(OverflowException) == e.GetType()); } try { double OverInt = (double)UInt64.MaxValue + 1; UInt64.Parse(OverInt.ToString(), NumberStyles.Integer); Fail("Should raise a System.FormatException"); } catch (Exception e) { Assert(typeof(FormatException) == e.GetType()); } Assert(42 == UInt64.Parse(" "+NumberFormatInfo.CurrentInfo.CurrencySymbol+"42 ", NumberStyles.Currency)); try { UInt64.Parse("$42", NumberStyles.Integer); Fail("Should raise a FormatException"); } catch (Exception e) { Assert(typeof(FormatException) == e.GetType()); } //test Parse(string s, IFormatProvider provider) Assert(42 == UInt64.Parse(" 42 ", Nfi)); try { UInt64.Parse("%42", Nfi); Fail("Should raise a System.FormatException"); } catch (Exception e) { Assert(typeof(FormatException) == e.GetType()); } //test Parse(string s, NumberStyles style, IFormatProvider provider) Assert(16 == UInt64.Parse(" 10 ", NumberStyles.HexNumber, Nfi)); try { UInt64.Parse("$42", NumberStyles.Integer, Nfi); Fail("Should raise a System.FormatException"); } catch (Exception e) { Assert(typeof(FormatException) == e.GetType()); } } public void TestToString() { //test ToString() AssertEquals("A", MyString1, MyUInt64_1.ToString()); AssertEquals("B", MyString2, MyUInt64_2.ToString()); AssertEquals("C", MyString3, MyUInt64_3.ToString()); //test ToString(string format) for (int i=0; i < Formats1.Length; i++) { AssertEquals("D", Results1[i], MyUInt64_2.ToString(Formats1[i])); AssertEquals("E: format #" + i, Results2[i], MyUInt64_3.ToString(Formats2[i])); } //test ToString(string format, IFormatProvider provider); for (int i=0; i < Formats1.Length; i++) { AssertEquals("F", ResultsNfi1[i], MyUInt64_2.ToString(Formats1[i], Nfi)); AssertEquals("G", ResultsNfi2[i], MyUInt64_3.ToString(Formats2[i], Nfi)); } try { MyUInt64_1.ToString("z"); Fail("Should raise a System.FormatException"); } catch (Exception e) { Assert("H", typeof(FormatException) == e.GetType()); } } [Test] public void ToString_Defaults () { UInt64 i = 254; // everything defaults to "G" string def = i.ToString ("G"); AssertEquals ("ToString()", def, i.ToString ()); AssertEquals ("ToString((IFormatProvider)null)", def, i.ToString ((IFormatProvider)null)); AssertEquals ("ToString((string)null)", def, i.ToString ((string)null)); AssertEquals ("ToString(empty)", def, i.ToString (String.Empty)); AssertEquals ("ToString(null,null)", def, i.ToString (null, null)); AssertEquals ("ToString(empty,null)", def, i.ToString (String.Empty, null)); AssertEquals ("ToString(G)", "254", def); } } }
// // PropertyDefinition.cs // // Author: // Jb Evain (jbevain@gmail.com) // // Copyright (c) 2008 - 2010 Jb Evain // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System.Text; using Mono.Collections.Generic; namespace Mono.Cecil { public sealed class PropertyDefinition : PropertyReference, IMemberDefinition, IConstantProvider { bool? has_this; ushort attributes; Collection<CustomAttribute> custom_attributes; internal MethodDefinition get_method; internal MethodDefinition set_method; internal Collection<MethodDefinition> other_methods; object constant = Mixin.NotResolved; public PropertyAttributes Attributes { get { return (PropertyAttributes) attributes; } set { attributes = (ushort) value; } } public bool HasThis { get { if (has_this.HasValue) return has_this.Value; if (GetMethod != null) return get_method.HasThis; if (SetMethod != null) return set_method.HasThis; return false; } set { has_this = value; } } public bool HasCustomAttributes { get { if (custom_attributes != null) return custom_attributes.Count > 0; return this.GetHasCustomAttributes (Module); } } public Collection<CustomAttribute> CustomAttributes { get { return custom_attributes ?? (custom_attributes = this.GetCustomAttributes (Module)); } } public MethodDefinition GetMethod { get { if (get_method != null) return get_method; InitializeMethods (); return get_method; } set { get_method = value; } } public MethodDefinition SetMethod { get { if (set_method != null) return set_method; InitializeMethods (); return set_method; } set { set_method = value; } } public bool HasOtherMethods { get { if (other_methods != null) return other_methods.Count > 0; InitializeMethods (); return !other_methods.IsNullOrEmpty (); } } public Collection<MethodDefinition> OtherMethods { get { if (other_methods != null) return other_methods; InitializeMethods (); if (other_methods != null) return other_methods; return other_methods = new Collection<MethodDefinition> (); } } public bool HasParameters { get { if (get_method != null) return get_method.HasParameters; if (set_method != null) return set_method.HasParameters && set_method.Parameters.Count > 1; return false; } } public override Collection<ParameterDefinition> Parameters { get { InitializeMethods (); if (get_method != null) return MirrorParameters (get_method, 0); if (set_method != null) return MirrorParameters (set_method, 1); return new Collection<ParameterDefinition> (); } } static Collection<ParameterDefinition> MirrorParameters (MethodDefinition method, int bound) { var parameters = new Collection<ParameterDefinition> (); if (!method.HasParameters) return parameters; var original_parameters = method.Parameters; var end = original_parameters.Count - bound; for (int i = 0; i < end; i++) parameters.Add (original_parameters [i]); return parameters; } public bool HasConstant { get { ResolveConstant (); return constant != Mixin.NoValue; } set { if (!value) constant = Mixin.NoValue; } } public object Constant { get { return HasConstant ? constant : null; } set { constant = value; } } void ResolveConstant () { if (constant != Mixin.NotResolved) return; this.ResolveConstant (ref constant, Module); } #region PropertyAttributes public bool IsSpecialName { get { return attributes.GetAttributes ((ushort) PropertyAttributes.SpecialName); } set { attributes = attributes.SetAttributes ((ushort) PropertyAttributes.SpecialName, value); } } public bool IsRuntimeSpecialName { get { return attributes.GetAttributes ((ushort) PropertyAttributes.RTSpecialName); } set { attributes = attributes.SetAttributes ((ushort) PropertyAttributes.RTSpecialName, value); } } public bool HasDefault { get { return attributes.GetAttributes ((ushort) PropertyAttributes.HasDefault); } set { attributes = attributes.SetAttributes ((ushort) PropertyAttributes.HasDefault, value); } } #endregion public new TypeDefinition DeclaringType { get { return (TypeDefinition) base.DeclaringType; } set { base.DeclaringType = value; } } public override bool IsDefinition { get { return true; } } public override string FullName { get { var builder = new StringBuilder (); builder.Append (PropertyType.ToString ()); builder.Append (' '); builder.Append (MemberFullName ()); builder.Append ('('); if (HasParameters) { var parameters = Parameters; for (int i = 0; i < parameters.Count; i++) { if (i > 0) builder.Append (','); builder.Append (parameters [i].ParameterType.FullName); } } builder.Append (')'); return builder.ToString (); } } public PropertyDefinition (string name, PropertyAttributes attributes, TypeReference propertyType) : base (name, propertyType) { this.attributes = (ushort) attributes; this.token = new MetadataToken (TokenType.Property); } void InitializeMethods () { if (get_method != null || set_method != null) return; var module = this.Module; if (!module.HasImage ()) return; module.Read (this, (property, reader) => reader.ReadMethods (property)); } } }
using System; using System.Diagnostics; namespace FlashTools { public class Tag { private ushort id; private ulong length; #region Properties public ushort ID { get { return id; } } public ulong Length { get { return length; } } #endregion #region Constructors public Tag(SWFReader swf) { ushort tagInfo = swf.ReadUI16(); this.id = (ushort)(tagInfo >> 6); this.length = (ulong)(tagInfo & 0x3f); // Is this a long data block? if (this.length == 0x3f) { this.length = swf.ReadUI32(); } Trace.WriteLine(String.Format("Tag : {0}", GetType(this.ID))); // For now, just skip the remainder of the tag // ** This is normally where you'd process each tag in the file ** for (ulong index = 0; index < length; index++) { swf.Stream.ReadByte(); } } #endregion // Return the tag type // Special thanks to Alexis: http://sswf.sourceforge.net/SWFalexref.html#table_of_swf_tags public static string GetType(ushort id) { string result = "(unknown)"; switch (id) { // SWF Version 1.0 case 0: result = "End (V1.0)"; break; case 1: result = "ShowFrame (V1.0)"; break; case 2: result = "DefineShape (V1.0)"; break; case 3: result = "FreeCharacter (V1.0)"; break; case 4: result = "PlaceObject (V1.0)"; break; case 5: result = "RemoveObject (V1.0)"; break; case 6: result = "DefineBits (V1.0)"; break; case 7: result = "DefineButton (V1.0)"; break; case 8: result = "JPEGTables (V1.0)"; break; case 9: result = "SetBackgroundColor (V1.0)"; break; case 10: result = "DefineFont (V1.0)"; break; case 11: result = "DefineText (V1.0)"; break; case 12: result = "DoAction (V1.0)"; break; case 13: result = "DefineFontInfo (V1.0)"; break; // SWF Version 2.0 case 14: result = "DefineSound (V2.0)"; break; case 15: result = "StartSound (V2.0)"; break; case 16: result = "StopSound (V2.0)"; break; case 17: result = "DefineButtonSound (V2.0)"; break; case 18: result = "SoundStreamHead (V2.0)"; break; case 19: result = "SoundStreamBlock (V2.0)"; break; case 20: result = "DefineBitsLossless (V2.0)"; break; case 21: result = "DefineBitsJPEG2 (V2.0)"; break; case 22: result = "DefineShape2 (V2.0)"; break; case 23: result = "DefineButtonCxform (V2.0)"; break; case 24: result = "Protect (V2.0)"; break; // SWF Version 3.0 case 25: result = "PathsArePostscript (V3.0)"; break; case 26: result = "PlaceObject2 (V3.0)"; break; case 28: result = "RemoveObject2 (V3.0)"; break; case 29: result = "SyncFrame (V3.0)"; break; case 31: result = "FreeAll (V3.0)"; break; case 32: result = "DefineShape3 (V3.0)"; break; case 33: result = "DefineText2 (V3.0)"; break; case 34: result = "DefineButton2 (V3.0)"; break; case 35: result = "DefineBitsJPEG3 (V3.0)"; break; case 36: result = "DefineBitsLossless2 (V3.0)"; break; case 39: result = "DefineSprite (V3.0)"; break; case 40: result = "NameCharacter (V3.0)"; break; case 41: result = "SerialNumber (V3.0)"; break; case 42: result = "DefineTextFormat (V3.0)"; break; case 43: result = "FrameLabel (V3.0)"; break; case 45: result = "SoundStreamHead2 (V3.0)"; break; case 46: result = "DefineMorphShape (V3.0)"; break; case 47: result = "GenerateFrame (V3.0)"; break; case 48: result = "DefineFont2 (V3.0)"; break; case 49: result = "GeneratorCommand (V3.0)"; break; // SWF Version 4.0 case 37: result = "DefineEditText (V4.0)"; break; case 38: result = "DefineVideo (V4.0)"; break; // SWF Version 5.0 case 50: result = "DefineCommandObject (V5.0)"; break; case 51: result = "CharacterSet (V5.0)"; break; case 52: result = "ExternalFont (V5.0)"; break; case 56: result = "Export (V5.0)"; break; case 57: result = "Import (V5.0)"; break; case 58: result = "ProtectDebug (V5.0)"; break; // SWF Version 6.0 case 59: result = "DoInitAction (V6.0)"; break; case 60: result = "DefineVideoStream (V6.0)"; break; case 61: result = "VideoFrame (V6.0)"; break; case 62: result = "DefineFontInfo2 (V6.0)"; break; case 64: result = "ProtectDebug2 (V6.0)"; break; // SWF Version 7.0 case 65: result = "ScriptLimits (V7.0)"; break; case 66: result = "SetTabIndex (V7.0)"; break; // SWF Version 8.0 case 69: result = "FileAttributes (V8.0)"; break; case 70: result = "PlaceObject3 (V8.0)"; break; case 71: result = "Import2 (V8.0)"; break; case 73: result = "DefineFontAlignZones (V8.0)"; break; case 74: result = "CSMTextSettings (V8.0)"; break; case 75: result = "DefineFont3 (V8.0)"; break; case 77: result = "Metadata (V8.0)"; break; case 78: result = "DefineScalingGrid (V8.0)"; break; case 83: result = "DefineShape4 (V8.0)"; break; case 84: result = "DefineMorphShape2 (V8.0)"; break; } return result; } } }
namespace liquicode.AppTools { partial class MessageWindow { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose( bool disposing ) { if( disposing && (components != null) ) { components.Dispose(); } base.Dispose( disposing ); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager( typeof( MessageWindow ) ); this.CommandPanel = new System.Windows.Forms.Panel(); this.lblMessage = new System.Windows.Forms.Label(); this.cmdMoreInfo = new System.Windows.Forms.Button(); this.cmdCancel = new System.Windows.Forms.Button(); this.cmdRetry = new System.Windows.Forms.Button(); this.cmdYes = new System.Windows.Forms.Button(); this.cmdAbort = new System.Windows.Forms.Button(); this.cmdIgnore = new System.Windows.Forms.Button(); this.cmdNo = new System.Windows.Forms.Button(); this.cmdOK = new System.Windows.Forms.Button(); this.lblIconQuestion = new System.Windows.Forms.Label(); this.lblIconWarning = new System.Windows.Forms.Label(); this.lblIconInformation = new System.Windows.Forms.Label(); this.lblIconError = new System.Windows.Forms.Label(); this.picIcon = new System.Windows.Forms.PictureBox(); this.txtMessage = new System.Windows.Forms.TextBox(); this.txtUserInput = new System.Windows.Forms.TextBox(); this.pnlUserInput = new System.Windows.Forms.Label(); this.cboUserInput = new System.Windows.Forms.ComboBox(); this.lblUserInput = new System.Windows.Forms.Label(); this.CommandPanel.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.picIcon)).BeginInit(); this.pnlUserInput.SuspendLayout(); this.SuspendLayout(); // // CommandPanel // this.CommandPanel.Controls.Add( this.lblMessage ); this.CommandPanel.Controls.Add( this.cmdMoreInfo ); this.CommandPanel.Controls.Add( this.cmdCancel ); this.CommandPanel.Controls.Add( this.cmdRetry ); this.CommandPanel.Controls.Add( this.cmdYes ); this.CommandPanel.Controls.Add( this.cmdAbort ); this.CommandPanel.Controls.Add( this.cmdIgnore ); this.CommandPanel.Controls.Add( this.cmdNo ); this.CommandPanel.Controls.Add( this.cmdOK ); this.CommandPanel.Controls.Add( this.lblIconQuestion ); this.CommandPanel.Controls.Add( this.lblIconWarning ); this.CommandPanel.Controls.Add( this.lblIconInformation ); this.CommandPanel.Controls.Add( this.lblIconError ); this.CommandPanel.Controls.Add( this.picIcon ); this.CommandPanel.Dock = System.Windows.Forms.DockStyle.Bottom; this.CommandPanel.Location = new System.Drawing.Point( 0, 80 ); this.CommandPanel.Name = "CommandPanel"; this.CommandPanel.Size = new System.Drawing.Size( 451, 54 ); this.CommandPanel.TabIndex = 0; // // lblMessage // this.lblMessage.AutoSize = true; this.lblMessage.Location = new System.Drawing.Point( 103, 9 ); this.lblMessage.Name = "lblMessage"; this.lblMessage.Size = new System.Drawing.Size( 36, 39 ); this.lblMessage.TabIndex = 2; this.lblMessage.Text = "Line 1\r\nLine 2\r\nLine 3"; this.lblMessage.Visible = false; // // cmdMoreInfo // this.cmdMoreInfo.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.cmdMoreInfo.Location = new System.Drawing.Point( 130, 28 ); this.cmdMoreInfo.Name = "cmdMoreInfo"; this.cmdMoreInfo.Size = new System.Drawing.Size( 75, 23 ); this.cmdMoreInfo.TabIndex = 10; this.cmdMoreInfo.Text = "&More Info"; this.cmdMoreInfo.Visible = false; this.cmdMoreInfo.Click += new System.EventHandler( this.cmdMoreInfo_Click ); // // cmdCancel // this.cmdCancel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.cmdCancel.Location = new System.Drawing.Point( 373, 29 ); this.cmdCancel.Name = "cmdCancel"; this.cmdCancel.Size = new System.Drawing.Size( 75, 23 ); this.cmdCancel.TabIndex = 6; this.cmdCancel.Text = "&Cancel"; this.cmdCancel.Visible = false; this.cmdCancel.Click += new System.EventHandler( this.cmdCancel_Click ); // // cmdRetry // this.cmdRetry.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.cmdRetry.Location = new System.Drawing.Point( 292, 28 ); this.cmdRetry.Name = "cmdRetry"; this.cmdRetry.Size = new System.Drawing.Size( 75, 23 ); this.cmdRetry.TabIndex = 4; this.cmdRetry.Text = "&Retry"; this.cmdRetry.Visible = false; this.cmdRetry.Click += new System.EventHandler( this.cmdRetry_Click ); // // cmdYes // this.cmdYes.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.cmdYes.Location = new System.Drawing.Point( 211, 28 ); this.cmdYes.Name = "cmdYes"; this.cmdYes.Size = new System.Drawing.Size( 75, 23 ); this.cmdYes.TabIndex = 2; this.cmdYes.Text = "&Yes"; this.cmdYes.Visible = false; this.cmdYes.Click += new System.EventHandler( this.cmdYes_Click ); // // cmdAbort // this.cmdAbort.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.cmdAbort.Location = new System.Drawing.Point( 373, 3 ); this.cmdAbort.Name = "cmdAbort"; this.cmdAbort.Size = new System.Drawing.Size( 75, 23 ); this.cmdAbort.TabIndex = 5; this.cmdAbort.Text = "&Abort"; this.cmdAbort.Visible = false; this.cmdAbort.Click += new System.EventHandler( this.cmdAbort_Click ); // // cmdIgnore // this.cmdIgnore.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.cmdIgnore.Location = new System.Drawing.Point( 292, 3 ); this.cmdIgnore.Name = "cmdIgnore"; this.cmdIgnore.Size = new System.Drawing.Size( 75, 23 ); this.cmdIgnore.TabIndex = 3; this.cmdIgnore.Text = "&Ignore"; this.cmdIgnore.Visible = false; this.cmdIgnore.Click += new System.EventHandler( this.cmdIgnore_Click ); // // cmdNo // this.cmdNo.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.cmdNo.Location = new System.Drawing.Point( 211, 3 ); this.cmdNo.Name = "cmdNo"; this.cmdNo.Size = new System.Drawing.Size( 75, 23 ); this.cmdNo.TabIndex = 1; this.cmdNo.Text = "&No"; this.cmdNo.Visible = false; this.cmdNo.Click += new System.EventHandler( this.cmdNo_Click ); // // cmdOK // this.cmdOK.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.cmdOK.Location = new System.Drawing.Point( 130, 3 ); this.cmdOK.Name = "cmdOK"; this.cmdOK.Size = new System.Drawing.Size( 75, 23 ); this.cmdOK.TabIndex = 0; this.cmdOK.Text = "&OK"; this.cmdOK.Visible = false; this.cmdOK.Click += new System.EventHandler( this.cmdOK_Click ); // // lblIconQuestion // this.lblIconQuestion.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.lblIconQuestion.Location = new System.Drawing.Point( 57, 48 ); this.lblIconQuestion.Name = "lblIconQuestion"; this.lblIconQuestion.Size = new System.Drawing.Size( 40, 15 ); this.lblIconQuestion.TabIndex = 14; this.lblIconQuestion.Text = resources.GetString( "lblIconQuestion.Text" ); this.lblIconQuestion.Visible = false; // // lblIconWarning // this.lblIconWarning.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.lblIconWarning.Location = new System.Drawing.Point( 57, 33 ); this.lblIconWarning.Name = "lblIconWarning"; this.lblIconWarning.Size = new System.Drawing.Size( 40, 15 ); this.lblIconWarning.TabIndex = 13; this.lblIconWarning.Text = resources.GetString( "lblIconWarning.Text" ); this.lblIconWarning.Visible = false; // // lblIconInformation // this.lblIconInformation.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.lblIconInformation.Location = new System.Drawing.Point( 57, 18 ); this.lblIconInformation.Name = "lblIconInformation"; this.lblIconInformation.Size = new System.Drawing.Size( 40, 15 ); this.lblIconInformation.TabIndex = 12; this.lblIconInformation.Text = resources.GetString( "lblIconInformation.Text" ); this.lblIconInformation.Visible = false; // // lblIconError // this.lblIconError.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.lblIconError.Location = new System.Drawing.Point( 57, 3 ); this.lblIconError.Name = "lblIconError"; this.lblIconError.Size = new System.Drawing.Size( 40, 15 ); this.lblIconError.TabIndex = 11; this.lblIconError.Text = resources.GetString( "lblIconError.Text" ); this.lblIconError.Visible = false; // // picIcon // this.picIcon.BackColor = System.Drawing.Color.Transparent; this.picIcon.Location = new System.Drawing.Point( 3, 3 ); this.picIcon.Name = "picIcon"; this.picIcon.Size = new System.Drawing.Size( 48, 48 ); this.picIcon.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom; this.picIcon.TabIndex = 10; this.picIcon.TabStop = false; // // txtMessage // this.txtMessage.BorderStyle = System.Windows.Forms.BorderStyle.None; this.txtMessage.Dock = System.Windows.Forms.DockStyle.Fill; this.txtMessage.HideSelection = false; this.txtMessage.Location = new System.Drawing.Point( 0, 0 ); this.txtMessage.Multiline = true; this.txtMessage.Name = "txtMessage"; this.txtMessage.ReadOnly = true; this.txtMessage.Size = new System.Drawing.Size( 451, 58 ); this.txtMessage.TabIndex = 1; this.txtMessage.Text = "Line 1\r\nLine 2\r\nLine 3"; this.txtMessage.WordWrap = false; // // txtUserInput // this.txtUserInput.Location = new System.Drawing.Point( 188, 1 ); this.txtUserInput.Name = "txtUserInput"; this.txtUserInput.Size = new System.Drawing.Size( 131, 20 ); this.txtUserInput.TabIndex = 0; // // pnlUserInput // this.pnlUserInput.Controls.Add( this.cboUserInput ); this.pnlUserInput.Controls.Add( this.txtUserInput ); this.pnlUserInput.Controls.Add( this.lblUserInput ); this.pnlUserInput.Dock = System.Windows.Forms.DockStyle.Bottom; this.pnlUserInput.Location = new System.Drawing.Point( 0, 58 ); this.pnlUserInput.Name = "pnlUserInput"; this.pnlUserInput.Size = new System.Drawing.Size( 451, 22 ); this.pnlUserInput.TabIndex = 2; this.pnlUserInput.Visible = false; // // cboUserInput // this.cboUserInput.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cboUserInput.FormattingEnabled = true; this.cboUserInput.Location = new System.Drawing.Point( 325, 1 ); this.cboUserInput.Name = "cboUserInput"; this.cboUserInput.Size = new System.Drawing.Size( 114, 21 ); this.cboUserInput.TabIndex = 2; // // lblUserInput // this.lblUserInput.Dock = System.Windows.Forms.DockStyle.Left; this.lblUserInput.Font = new System.Drawing.Font( "Tahoma", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)) ); this.lblUserInput.Location = new System.Drawing.Point( 0, 0 ); this.lblUserInput.Name = "lblUserInput"; this.lblUserInput.Size = new System.Drawing.Size( 181, 22 ); this.lblUserInput.TabIndex = 1; this.lblUserInput.Text = "Please supply your answer :"; // // MessageWindow // this.AutoScaleDimensions = new System.Drawing.SizeF( 6F, 13F ); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size( 451, 134 ); this.Controls.Add( this.txtMessage ); this.Controls.Add( this.pnlUserInput ); this.Controls.Add( this.CommandPanel ); this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "MessageWindow"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; this.Text = "Message"; this.CommandPanel.ResumeLayout( false ); this.CommandPanel.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.picIcon)).EndInit(); this.pnlUserInput.ResumeLayout( false ); this.pnlUserInput.PerformLayout(); this.ResumeLayout( false ); this.PerformLayout(); } #endregion private System.Windows.Forms.Panel CommandPanel; private System.Windows.Forms.Button cmdOK; internal System.Windows.Forms.Label lblIconQuestion; internal System.Windows.Forms.Label lblIconWarning; internal System.Windows.Forms.Label lblIconInformation; internal System.Windows.Forms.Label lblIconError; internal System.Windows.Forms.PictureBox picIcon; private System.Windows.Forms.Button cmdCancel; private System.Windows.Forms.Button cmdRetry; private System.Windows.Forms.Button cmdYes; private System.Windows.Forms.Button cmdAbort; private System.Windows.Forms.Button cmdIgnore; private System.Windows.Forms.Button cmdNo; private System.Windows.Forms.TextBox txtMessage; private System.Windows.Forms.Label lblMessage; private System.Windows.Forms.Button cmdMoreInfo; private System.Windows.Forms.TextBox txtUserInput; private System.Windows.Forms.Label pnlUserInput; private System.Windows.Forms.Label lblUserInput; private System.Windows.Forms.ComboBox cboUserInput; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void AddInt32() { var test = new SimpleBinaryOpTest__AddInt32(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local works test.RunLclFldScenario(); // Validates passing an instance member works test.RunFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__AddInt32 { private const int VectorSize = 16; private const int Op1ElementCount = VectorSize / sizeof(Int32); private const int Op2ElementCount = VectorSize / sizeof(Int32); private const int RetElementCount = VectorSize / sizeof(Int32); private static Int32[] _data1 = new Int32[Op1ElementCount]; private static Int32[] _data2 = new Int32[Op2ElementCount]; private static Vector128<Int32> _clsVar1; private static Vector128<Int32> _clsVar2; private Vector128<Int32> _fld1; private Vector128<Int32> _fld2; private SimpleBinaryOpTest__DataTable<Int32, Int32, Int32> _dataTable; static SimpleBinaryOpTest__AddInt32() { var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (int)(random.Next(int.MinValue, int.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _clsVar1), ref Unsafe.As<Int32, byte>(ref _data1[0]), VectorSize); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (int)(random.Next(int.MinValue, int.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _clsVar2), ref Unsafe.As<Int32, byte>(ref _data2[0]), VectorSize); } public SimpleBinaryOpTest__AddInt32() { Succeeded = true; var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (int)(random.Next(int.MinValue, int.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), VectorSize); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (int)(random.Next(int.MinValue, int.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), VectorSize); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (int)(random.Next(int.MinValue, int.MaxValue)); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (int)(random.Next(int.MinValue, int.MaxValue)); } _dataTable = new SimpleBinaryOpTest__DataTable<Int32, Int32, Int32>(_data1, _data2, new Int32[RetElementCount], VectorSize); } public bool IsSupported => Sse2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { var result = Sse2.Add( Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { var result = Sse2.Add( Sse2.LoadVector128((Int32*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Int32*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { var result = Sse2.Add( Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { var result = typeof(Sse2).GetMethod(nameof(Sse2.Add), new Type[] { typeof(Vector128<Int32>), typeof(Vector128<Int32>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { var result = typeof(Sse2).GetMethod(nameof(Sse2.Add), new Type[] { typeof(Vector128<Int32>), typeof(Vector128<Int32>) }) .Invoke(null, new object[] { Sse2.LoadVector128((Int32*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Int32*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { var result = typeof(Sse2).GetMethod(nameof(Sse2.Add), new Type[] { typeof(Vector128<Int32>), typeof(Vector128<Int32>) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { var result = Sse2.Add( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { var left = Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr); var right = Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr); var result = Sse2.Add(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { var left = Sse2.LoadVector128((Int32*)(_dataTable.inArray1Ptr)); var right = Sse2.LoadVector128((Int32*)(_dataTable.inArray2Ptr)); var result = Sse2.Add(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { var left = Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray1Ptr)); var right = Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray2Ptr)); var result = Sse2.Add(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclFldScenario() { var test = new SimpleBinaryOpTest__AddInt32(); var result = Sse2.Add(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunFldScenario() { var result = Sse2.Add(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunUnsupportedScenario() { Succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { Succeeded = true; } } private void ValidateResult(Vector128<Int32> left, Vector128<Int32> right, void* result, [CallerMemberName] string method = "") { Int32[] inArray1 = new Int32[Op1ElementCount]; Int32[] inArray2 = new Int32[Op2ElementCount]; Int32[] outArray = new Int32[RetElementCount]; Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left); Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "") { Int32[] inArray1 = new Int32[Op1ElementCount]; Int32[] inArray2 = new Int32[Op2ElementCount]; Int32[] outArray = new Int32[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Int32[] left, Int32[] right, Int32[] result, [CallerMemberName] string method = "") { if ((int)(left[0] + right[0]) != result[0]) { Succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if ((int)(left[i] + right[i]) != result[i]) { Succeeded = false; break; } } } if (!Succeeded) { Console.WriteLine($"{nameof(Sse2)}.{nameof(Sse2.Add)}<Int32>(Vector128<Int32>, Vector128<Int32>): {method} failed:"); Console.WriteLine($" left: ({string.Join(", ", left)})"); Console.WriteLine($" right: ({string.Join(", ", right)})"); Console.WriteLine($" result: ({string.Join(", ", result)})"); Console.WriteLine(); } } } }
/* XML-RPC.NET library Copyright (c) 2001-2009, Charles Cook <charlescook@cookcomputing.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 System.ComponentModel; using System.Collections; using System.Diagnostics; using System.IO; using System.Net; using System.Reflection; using System.Security.Cryptography.X509Certificates; using System.Text; namespace CookComputing.XmlRpc { #if (!SILVERLIGHT) public class XmlRpcClientProtocol : Component, IXmlRpcProxy #else public class XmlRpcClientProtocol : IXmlRpcProxy #endif { #if (!COMPACT_FRAMEWORK) private string _connectionGroupName = null; #endif #if (!COMPACT_FRAMEWORK) private bool _expect100Continue = false; private bool _enableCompression = false; #endif #if (!SILVERLIGHT) private ICredentials _credentials = null; #endif private WebHeaderCollection _headers = new WebHeaderCollection(); private int _indentation = 2; private bool _keepAlive = true; private XmlRpcNonStandard _nonStandard = XmlRpcNonStandard.None; private bool _preAuthenticate = false; #if (!SILVERLIGHT) private Version _protocolVersion = HttpVersion.Version11; #endif #if (!SILVERLIGHT) private IWebProxy _proxy = null; #endif #if (!COMPACT_FRAMEWORK && !SILVERLIGHT) private CookieCollection _responseCookies; #endif #if (!COMPACT_FRAMEWORK) private WebHeaderCollection _responseHeaders; #endif private int _timeout = 100000; private string _url = null; private string _userAgent = "XML-RPC.NET"; private bool _useEmptyParamsTag = true; private bool _useIndentation = true; private bool _useIntTag = false; private bool _useStringTag = true; private Encoding _xmlEncoding = null; private string _xmlRpcMethod = null; #if (!COMPACT_FRAMEWORK && !SILVERLIGHT) private X509CertificateCollection _clientCertificates = new X509CertificateCollection(); #endif #if (!COMPACT_FRAMEWORK && !SILVERLIGHT) private CookieContainer _cookies = new CookieContainer(); #endif private Guid _id = Guid.NewGuid(); #if (!COMPACT_FRAMEWORK && !SILVERLIGHT) public XmlRpcClientProtocol(System.ComponentModel.IContainer container) { container.Add(this); InitializeComponent(); } #endif public XmlRpcClientProtocol() { InitializeComponent(); } #if (!SILVERLIGHT) public object Invoke( MethodBase mb, params object[] Parameters) { return Invoke(this, mb as MethodInfo, Parameters); } #endif #if (!SILVERLIGHT) public object Invoke( MethodInfo mi, params object[] Parameters) { return Invoke(this, mi, Parameters); } #endif #if (!SILVERLIGHT) public object Invoke( string MethodName, params object[] Parameters) { return Invoke(this, MethodName, Parameters); } #endif #if (!SILVERLIGHT) public object Invoke( Object clientObj, string methodName, params object[] parameters) { MethodInfo mi = GetMethodInfoFromName(clientObj, methodName, parameters); return Invoke(this, mi, parameters); } #endif #if (!SILVERLIGHT) public object Invoke( Object clientObj, MethodInfo mi, params object[] parameters) { #if (!COMPACT_FRAMEWORK && !SILVERLIGHT) _responseHeaders = null; _responseCookies = null; #endif WebRequest webReq = null; object reto = null; try { string useUrl = GetEffectiveUrl(clientObj); webReq = GetWebRequest(new Uri(useUrl)); XmlRpcRequest req = MakeXmlRpcRequest(webReq, mi, parameters, clientObj, _xmlRpcMethod, _id); SetProperties(webReq); #if (!SILVERLIGHT) SetRequestHeaders(_headers, webReq); #endif #if (!COMPACT_FRAMEWORK && !SILVERLIGHT) SetClientCertificates(_clientCertificates, webReq); #endif Stream serStream = null; Stream reqStream = null; bool logging = (RequestEvent != null); if (!logging) serStream = reqStream = webReq.GetRequestStream(); else serStream = new MemoryStream(2000); try { XmlRpcSerializer serializer = new XmlRpcSerializer(); if (_xmlEncoding != null) serializer.XmlEncoding = _xmlEncoding; serializer.UseIndentation = _useIndentation; serializer.Indentation = _indentation; serializer.NonStandard = _nonStandard; serializer.UseStringTag = _useStringTag; serializer.UseIntTag = _useIntTag; serializer.UseEmptyParamsTag = _useEmptyParamsTag; serializer.SerializeRequest(serStream, req); if (logging) { reqStream = webReq.GetRequestStream(); serStream.Position = 0; Util.CopyStream(serStream, reqStream); reqStream.Flush(); serStream.Position = 0; OnRequest(new XmlRpcRequestEventArgs(req.proxyId, req.number, serStream)); } } finally { if (reqStream != null) reqStream.Close(); } HttpWebResponse webResp = GetWebResponse(webReq) as HttpWebResponse; #if (!COMPACT_FRAMEWORK && !SILVERLIGHT) _responseCookies = webResp.Cookies; #endif #if (!COMPACT_FRAMEWORK && !SILVERLIGHT) _responseHeaders = webResp.Headers; #endif Stream respStm = null; Stream deserStream; logging = (ResponseEvent != null); try { respStm = webResp.GetResponseStream(); if (!logging) { deserStream = respStm; } else { deserStream = new MemoryStream(2000); Util.CopyStream(respStm, deserStream); deserStream.Flush(); deserStream.Position = 0; } #if (!COMPACT_FRAMEWORK && !SILVERLIGHT) deserStream = MaybeDecompressStream((HttpWebResponse)webResp, deserStream); #endif try { XmlRpcResponse resp = ReadResponse(req, webResp, deserStream, null); reto = resp.retVal; } finally { if (logging) { deserStream.Position = 0; OnResponse(new XmlRpcResponseEventArgs(req.proxyId, req.number, deserStream)); } } } finally { if (respStm != null) respStm.Close(); } } finally { if (webReq != null) webReq = null; } return reto; } #endif #if (!COMPACT_FRAMEWORK && !SILVERLIGHT) [Browsable(false)] public X509CertificateCollection ClientCertificates { get { return _clientCertificates; } } #endif #if (!COMPACT_FRAMEWORK) public string ConnectionGroupName { get { return _connectionGroupName; } set { _connectionGroupName = value; } } #endif #if (!SILVERLIGHT) [Browsable(false)] public ICredentials Credentials { get { return _credentials; } set { _credentials = value; } } #endif #if (!COMPACT_FRAMEWORK) public bool EnableCompression { get { return _enableCompression; } set { _enableCompression = value; } } #endif [Browsable(false)] public WebHeaderCollection Headers { get { return _headers; } } #if (!COMPACT_FRAMEWORK) public bool Expect100Continue { get { return _expect100Continue; } set { _expect100Continue = value; } } #endif #if (!COMPACT_FRAMEWORK && !SILVERLIGHT) public CookieContainer CookieContainer { get { return _cookies; } } #endif public Guid Id { get { return _id; } } public int Indentation { get { return _indentation; } set { _indentation = value; } } public bool KeepAlive { get { return _keepAlive; } set { _keepAlive = value; } } public XmlRpcNonStandard NonStandard { get { return _nonStandard; } set { _nonStandard = value; } } public bool PreAuthenticate { get { return _preAuthenticate; } set { _preAuthenticate = value; } } #if (!SILVERLIGHT) [Browsable(false)] public System.Version ProtocolVersion { get { return _protocolVersion; } set { _protocolVersion = value; } } #endif #if (!SILVERLIGHT) [Browsable(false)] public IWebProxy Proxy { get { return _proxy; } set { _proxy = value; } } #endif #if (!COMPACT_FRAMEWORK && !SILVERLIGHT) public CookieCollection ResponseCookies { get { return _responseCookies; } } #endif #if (!COMPACT_FRAMEWORK) public WebHeaderCollection ResponseHeaders { get { return _responseHeaders; } } #endif public int Timeout { get { return _timeout; } set { _timeout = value; } } public string Url { get { return _url; } set { _url = value; } } public bool UseEmptyParamsTag { get { return _useEmptyParamsTag; } set { _useEmptyParamsTag = value; } } public bool UseIndentation { get { return _useIndentation; } set { _useIndentation = value; } } public bool UseIntTag { get { return _useIntTag; } set { _useIntTag = value; } } public string UserAgent { get { return _userAgent; } set { _userAgent = value; } } public bool UseStringTag { get { return _useStringTag; } set { _useStringTag = value; } } [Browsable(false)] public Encoding XmlEncoding { get { return _xmlEncoding; } set { _xmlEncoding = value; } } public string XmlRpcMethod { get { return _xmlRpcMethod; } set { _xmlRpcMethod = value; } } public void SetProperties(WebRequest webReq) { #if (!SILVERLIGHT) if (_proxy != null) webReq.Proxy = _proxy; #endif HttpWebRequest httpReq = (HttpWebRequest)webReq; #if (!SILVERLIGHT) httpReq.UserAgent = _userAgent; #endif #if (!SILVERLIGHT) httpReq.ProtocolVersion = _protocolVersion; #endif #if (!SILVERLIGHT) httpReq.KeepAlive = _keepAlive; #endif #if (!COMPACT_FRAMEWORK && !SILVERLIGHT) httpReq.CookieContainer = _cookies; #endif #if (!COMPACT_FRAMEWORK && !SILVERLIGHT) httpReq.ServicePoint.Expect100Continue = _expect100Continue; #endif #if (!SILVERLIGHT) webReq.Timeout = Timeout; #endif #if (!COMPACT_FRAMEWORK && !SILVERLIGHT) webReq.ConnectionGroupName = this._connectionGroupName; #endif #if (!SILVERLIGHT) webReq.Credentials = Credentials; #endif #if (!SILVERLIGHT) webReq.PreAuthenticate = PreAuthenticate; #endif #if (!SILVERLIGHT) // Compact Framework sets this to false by default (webReq as HttpWebRequest).AllowWriteStreamBuffering = true; #endif #if (!COMPACT_FRAMEWORK && !SILVERLIGHT) if (_enableCompression) webReq.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip,deflate"); #endif } #if (!SILVERLIGHT) private void SetRequestHeaders( WebHeaderCollection headers, WebRequest webReq) { foreach (string key in headers) { webReq.Headers.Add(key, headers[key]); } } #endif #if (!COMPACT_FRAMEWORK && !SILVERLIGHT) private void SetClientCertificates( X509CertificateCollection certificates, WebRequest webReq) { foreach (X509Certificate certificate in certificates) { HttpWebRequest httpReq = (HttpWebRequest)webReq; httpReq.ClientCertificates.Add(certificate); } } #endif XmlRpcRequest MakeXmlRpcRequest(WebRequest webReq, MethodInfo mi, object[] parameters, object clientObj, string xmlRpcMethod, Guid proxyId) { webReq.Method = "POST"; webReq.ContentType = "text/xml"; string rpcMethodName = GetRpcMethodName(clientObj, mi); XmlRpcRequest req = new XmlRpcRequest(rpcMethodName, parameters, mi, xmlRpcMethod, proxyId); return req; } XmlRpcResponse ReadResponse( XmlRpcRequest req, WebResponse webResp, Stream respStm, Type returnType) { HttpWebResponse httpResp = (HttpWebResponse)webResp; if (httpResp.StatusCode != HttpStatusCode.OK) { // status 400 is used for errors caused by the client // status 500 is used for server errors (not server application // errors which are returned as fault responses) #if (!SILVERLIGHT) if (httpResp.StatusCode == HttpStatusCode.BadRequest) throw new XmlRpcException(httpResp.StatusDescription); else throw new XmlRpcServerException(httpResp.StatusDescription); #else throw new XmlRpcServerException(httpResp.StatusDescription); #endif } XmlRpcSerializer serializer = new XmlRpcSerializer(); serializer.NonStandard = _nonStandard; Type retType = returnType; if (retType == null) retType = req.mi.ReturnType; XmlRpcResponse xmlRpcResp = serializer.DeserializeResponse(respStm, retType); return xmlRpcResp; } MethodInfo GetMethodInfoFromName(object clientObj, string methodName, object[] parameters) { Type[] paramTypes = new Type[0]; if (parameters != null) { paramTypes = new Type[parameters.Length]; for (int i = 0; i < paramTypes.Length; i++) { if (parameters[i] == null) throw new XmlRpcNullParameterException("Null parameters are invalid"); paramTypes[i] = parameters[i].GetType(); } } Type type = clientObj.GetType(); MethodInfo mi = type.GetMethod(methodName, paramTypes); if (mi == null) { try { mi = type.GetMethod(methodName); } catch (System.Reflection.AmbiguousMatchException) { throw new XmlRpcInvalidParametersException("Method parameters match " + "the signature of more than one method"); } if (mi == null) throw new Exception( "Invoke on non-existent or non-public proxy method"); else throw new XmlRpcInvalidParametersException("Method parameters do " + "not match signature of any method called " + methodName); } return mi; } string GetRpcMethodName(object clientObj, MethodInfo mi) { string rpcMethod; string MethodName = mi.Name; Attribute attr = Attribute.GetCustomAttribute(mi, typeof(XmlRpcBeginAttribute)); if (attr != null) { rpcMethod = ((XmlRpcBeginAttribute)attr).Method; if (rpcMethod == "") { if (!MethodName.StartsWith("Begin") || MethodName.Length <= 5) throw new Exception(String.Format( "method {0} has invalid signature for begin method", MethodName)); rpcMethod = MethodName.Substring(5); } return rpcMethod; } // if no XmlRpcBegin attribute, must have XmlRpcMethod attribute attr = Attribute.GetCustomAttribute(mi, typeof(XmlRpcMethodAttribute)); if (attr == null) { throw new Exception("missing method attribute"); } XmlRpcMethodAttribute xrmAttr = attr as XmlRpcMethodAttribute; rpcMethod = xrmAttr.Method; if (rpcMethod == "") { rpcMethod = mi.Name; } return rpcMethod; } public IAsyncResult BeginInvoke( MethodBase mb, object[] parameters, AsyncCallback callback, object outerAsyncState) { return BeginInvoke(mb as MethodInfo, parameters, this, callback, outerAsyncState); } public IAsyncResult BeginInvoke( MethodInfo mi, object[] parameters, AsyncCallback callback, object outerAsyncState) { return BeginInvoke(mi, parameters, this, callback, outerAsyncState); } public IAsyncResult BeginInvoke( string methodName, object[] parameters, object clientObj, AsyncCallback callback, object outerAsyncState) { MethodInfo mi = GetMethodInfoFromName(clientObj, methodName, parameters); return BeginInvoke(mi, parameters, this, callback, outerAsyncState); } public IAsyncResult BeginInvoke( MethodInfo mi, object[] parameters, object clientObj, AsyncCallback callback, object outerAsyncState) { string useUrl = GetEffectiveUrl(clientObj); WebRequest webReq = GetWebRequest(new Uri(useUrl)); XmlRpcRequest xmlRpcReq = MakeXmlRpcRequest(webReq, mi, parameters, clientObj, _xmlRpcMethod, _id); SetProperties(webReq); #if (!SILVERLIGHT) SetRequestHeaders(_headers, webReq); #endif #if (!COMPACT_FRAMEWORK &&!SILVERLIGHT) SetClientCertificates(_clientCertificates, webReq); #endif Encoding useEncoding = null; if (_xmlEncoding != null) useEncoding = _xmlEncoding; XmlRpcAsyncResult asr = new XmlRpcAsyncResult(this, xmlRpcReq, useEncoding, _useEmptyParamsTag, _useIndentation, _indentation, _useIntTag, _useStringTag, webReq, callback, outerAsyncState, 0); webReq.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), asr); if (!asr.IsCompleted) asr.CompletedSynchronously = false; return asr; } static void GetRequestStreamCallback(IAsyncResult asyncResult) { XmlRpcAsyncResult clientResult = (XmlRpcAsyncResult)asyncResult.AsyncState; clientResult.CompletedSynchronously = asyncResult.CompletedSynchronously; try { Stream serStream = null; Stream reqStream = null; bool logging = (clientResult.ClientProtocol.RequestEvent != null); if (!logging) { serStream = reqStream = clientResult.Request.EndGetRequestStream(asyncResult); } else serStream = new MemoryStream(2000); try { XmlRpcRequest req = clientResult.XmlRpcRequest; XmlRpcSerializer serializer = new XmlRpcSerializer(); if (clientResult.XmlEncoding != null) serializer.XmlEncoding = clientResult.XmlEncoding; serializer.UseEmptyParamsTag = clientResult.UseEmptyParamsTag; serializer.UseIndentation = clientResult.UseIndentation; serializer.Indentation = clientResult.Indentation; serializer.UseIntTag = clientResult.UseIntTag; serializer.UseStringTag = clientResult.UseStringTag; serializer.SerializeRequest(serStream, req); if (logging) { reqStream = clientResult.Request.EndGetRequestStream(asyncResult); serStream.Position = 0; Util.CopyStream(serStream, reqStream); reqStream.Flush(); serStream.Position = 0; clientResult.ClientProtocol.OnRequest( new XmlRpcRequestEventArgs(req.proxyId, req.number, serStream)); } } finally { if (reqStream != null) reqStream.Close(); } clientResult.Request.BeginGetResponse( new AsyncCallback(GetResponseCallback), clientResult); } catch (Exception ex) { ProcessAsyncException(clientResult, ex); } } static void GetResponseCallback(IAsyncResult asyncResult) { XmlRpcAsyncResult result = (XmlRpcAsyncResult)asyncResult.AsyncState; result.CompletedSynchronously = asyncResult.CompletedSynchronously; try { result.Response = result.ClientProtocol.GetWebResponse(result.Request, asyncResult); } catch (Exception ex) { ProcessAsyncException(result, ex); if (result.Response == null) return; } ReadAsyncResponse(result); } static void ReadAsyncResponse(XmlRpcAsyncResult result) { if (result.Response.ContentLength == 0) { result.Complete(); return; } try { result.ResponseStream = result.Response.GetResponseStream(); ReadAsyncResponseStream(result); } catch (Exception ex) { ProcessAsyncException(result, ex); } } static void ReadAsyncResponseStream(XmlRpcAsyncResult result) { IAsyncResult asyncResult; do { byte[] buff = result.Buffer; long contLen = result.Response.ContentLength; if (buff == null) { if (contLen == -1) result.Buffer = new Byte[1024]; else result.Buffer = new Byte[contLen]; } else { if (contLen != -1 && contLen > result.Buffer.Length) result.Buffer = new Byte[contLen]; } buff = result.Buffer; asyncResult = result.ResponseStream.BeginRead(buff, 0, buff.Length, new AsyncCallback(ReadResponseCallback), result); if (!asyncResult.CompletedSynchronously) return; } while (!(ProcessAsyncResponseStreamResult(result, asyncResult))); } static bool ProcessAsyncResponseStreamResult(XmlRpcAsyncResult result, IAsyncResult asyncResult) { int endReadLen = result.ResponseStream.EndRead(asyncResult); long contLen = result.Response.ContentLength; bool completed; if (endReadLen == 0) completed = true; else if (contLen > 0 && endReadLen == contLen) { result.ResponseBufferedStream = new MemoryStream(result.Buffer); completed = true; } else { if (result.ResponseBufferedStream == null) { result.ResponseBufferedStream = new MemoryStream(result.Buffer.Length); } result.ResponseBufferedStream.Write(result.Buffer, 0, endReadLen); completed = false; } if (completed) result.Complete(); return completed; } static void ReadResponseCallback(IAsyncResult asyncResult) { XmlRpcAsyncResult result = (XmlRpcAsyncResult)asyncResult.AsyncState; result.CompletedSynchronously = asyncResult.CompletedSynchronously; if (asyncResult.CompletedSynchronously) return; try { bool completed = ProcessAsyncResponseStreamResult(result, asyncResult); if (!completed) ReadAsyncResponseStream(result); } catch (Exception ex) { ProcessAsyncException(result, ex); } } static void ProcessAsyncException(XmlRpcAsyncResult clientResult, Exception ex) { WebException webex = ex as WebException; if (webex != null && webex.Response != null) { clientResult.Response = webex.Response; return; } if (clientResult.IsCompleted) throw new Exception("error during async processing"); clientResult.Complete(ex); } public object EndInvoke( IAsyncResult asr) { return EndInvoke(asr, null); } public object EndInvoke( IAsyncResult asr, Type returnType) { object reto = null; Stream responseStream = null; try { XmlRpcAsyncResult clientResult = (XmlRpcAsyncResult)asr; if (clientResult.Exception != null) throw clientResult.Exception; if (clientResult.EndSendCalled) throw new Exception("dup call to EndSend"); clientResult.EndSendCalled = true; HttpWebResponse webResp = (HttpWebResponse)clientResult.WaitForResponse(); #if (!COMPACT_FRAMEWORK && !SILVERLIGHT) clientResult._responseCookies = webResp.Cookies; clientResult._responseHeaders = webResp.Headers; #endif responseStream = clientResult.ResponseBufferedStream; if (ResponseEvent != null) { OnResponse(new XmlRpcResponseEventArgs( clientResult.XmlRpcRequest.proxyId, clientResult.XmlRpcRequest.number, responseStream)); responseStream.Position = 0; } #if (!COMPACT_FRAMEWORK && !SILVERLIGHT) responseStream = MaybeDecompressStream((HttpWebResponse)webResp, responseStream); #endif XmlRpcResponse resp = ReadResponse(clientResult.XmlRpcRequest, webResp, responseStream, returnType); reto = resp.retVal; } finally { if (responseStream != null) responseStream.Close(); } return reto; } string GetEffectiveUrl(object clientObj) { Type type = clientObj.GetType(); // client can either have define URI in attribute or have set it // via proxy's ServiceURI property - but must exist by now string useUrl = ""; if (Url == "" || Url == null) { Attribute urlAttr = Attribute.GetCustomAttribute(type, typeof(XmlRpcUrlAttribute)); if (urlAttr != null) { XmlRpcUrlAttribute xrsAttr = urlAttr as XmlRpcUrlAttribute; useUrl = xrsAttr.Uri; } } else { useUrl = Url; } if (useUrl == "") { throw new XmlRpcMissingUrl("Proxy XmlRpcUrl attribute or Url " + "property not set."); } return useUrl; } #if (!SILVERLIGHT) [XmlRpcMethod("system.listMethods")] public string[] SystemListMethods() { return (string[])Invoke("SystemListMethods", new Object[0]); } [XmlRpcMethod("system.methodSignature")] public object[] SystemMethodSignature(string MethodName) { return (object[])Invoke("SystemMethodSignature", new Object[] { MethodName }); } [XmlRpcMethod("system.methodHelp")] public string SystemMethodHelp(string MethodName) { return (string)Invoke("SystemMethodHelp", new Object[] { MethodName }); } #endif [XmlRpcMethod("system.listMethods")] public IAsyncResult BeginSystemListMethods( AsyncCallback Callback, object State) { return BeginInvoke("SystemListMethods", new object[0], this, Callback, State); } public string[] EndSystemListMethods(IAsyncResult AsyncResult) { return (string[])EndInvoke(AsyncResult); } [XmlRpcMethod("system.methodSignature")] public IAsyncResult BeginSystemMethodSignature( string MethodName, AsyncCallback Callback, object State) { return BeginInvoke("SystemMethodSignature", new Object[] { MethodName }, this, Callback, State); } public Array EndSystemMethodSignature(IAsyncResult AsyncResult) { return (Array)EndInvoke(AsyncResult); } [XmlRpcMethod("system.methodHelp")] public IAsyncResult BeginSystemMethodHelp( string MethodName, AsyncCallback Callback, object State) { return BeginInvoke("SystemMethodHelp", new Object[] { MethodName }, this, Callback, State); } public string EndSystemMethodHelp(IAsyncResult AsyncResult) { return (string)EndInvoke(AsyncResult); } /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { } protected virtual WebRequest GetWebRequest(Uri uri) { WebRequest req = WebRequest.Create(uri); return req; } #if (!SILVERLIGHT) protected virtual WebResponse GetWebResponse(WebRequest request) { WebResponse ret = null; try { ret = request.GetResponse(); } catch (WebException ex) { if (ex.Response == null) throw; ret = ex.Response; } return ret; } #endif #if (!COMPACT_FRAMEWORK && !SILVERLIGHT) // support for gzip and deflate protected Stream MaybeDecompressStream(HttpWebResponse httpWebResp, Stream respStream) { Stream decodedStream; string contentEncoding = httpWebResp.ContentEncoding.ToLower(); string coen = httpWebResp.Headers["Content-Encoding"]; if (contentEncoding.Contains("gzip")) { decodedStream = new System.IO.Compression.GZipStream(respStream, System.IO.Compression.CompressionMode.Decompress); } else if (contentEncoding.Contains("deflate")) { decodedStream = new System.IO.Compression.DeflateStream(respStream, System.IO.Compression.CompressionMode.Decompress); } else decodedStream = respStream; return decodedStream; } #endif protected virtual WebResponse GetWebResponse(WebRequest request, IAsyncResult result) { return request.EndGetResponse(result); } public event XmlRpcRequestEventHandler RequestEvent; public event XmlRpcResponseEventHandler ResponseEvent; protected virtual void OnRequest(XmlRpcRequestEventArgs e) { if (RequestEvent != null) { RequestEvent(this, e); } } internal bool LogResponse { get { return ResponseEvent != null; } } protected virtual void OnResponse(XmlRpcResponseEventArgs e) { if (ResponseEvent != null) { ResponseEvent(this, e); } } internal void InternalOnResponse(XmlRpcResponseEventArgs e) { OnResponse(e); } } #if (COMPACT_FRAMEWORK || SILVERLIGHT) // dummy attribute because System.ComponentModel.Browsable is not // support in the compact framework [AttributeUsage(AttributeTargets.Property)] public class BrowsableAttribute : Attribute { public BrowsableAttribute(bool dummy) { } } #endif public delegate void XmlRpcRequestEventHandler(object sender, XmlRpcRequestEventArgs args); public delegate void XmlRpcResponseEventHandler(object sender, XmlRpcResponseEventArgs args); }
#if !SILVERLIGHT using NUnit.Framework; #else using Microsoft.Silverlight.Testing; using Microsoft.VisualStudio.TestTools.UnitTesting; #endif using DevExpress.Mvvm.UI.Interactivity; using System.Windows.Controls; using System.Windows.Data; using System.Windows; using System; namespace DevExpress.Mvvm.UI.Tests { [TestFixture] public class DependencyPropertyBehaviorTests : BaseWpfFixture { protected void ShowWindow(UIElement element) { RealWindow.Content = element; EnqueueShowRealWindow(); EnqueueWindowUpdateLayout(); } [Test, Asynchronous] public void MainCasePasswordBoxTest() { var propertyChangedViewModel = new PropertyChangedViewModel(); var passwordBox = new PasswordBox() { DataContext = propertyChangedViewModel }; ShowWindow(passwordBox); var behavior = new DependencyPropertyBehavior(); behavior.EventName = "PasswordChanged"; behavior.PropertyName = "Password"; Interaction.GetBehaviors(passwordBox).Add(behavior); BindingOperations.SetBinding(behavior, DependencyPropertyBehavior.BindingProperty, new Binding("Text") { Mode = BindingMode.TwoWay }); Assert.AreEqual(0, propertyChangedViewModel.TextChangedCounter); EnqueueShowWindow(); EnqueueCallback(() => { passwordBox.Password = "123456"; }); EnqueueWindowUpdateLayout(); EnqueueCallback(() => { Assert.AreEqual(1, propertyChangedViewModel.TextChangedCounter); Assert.AreEqual("123456", propertyChangedViewModel.Text); passwordBox.Password = ""; }); EnqueueWindowUpdateLayout(); EnqueueCallback(() => { Assert.AreEqual(2, propertyChangedViewModel.TextChangedCounter); propertyChangedViewModel.Text = "654321"; }); EnqueueWindowUpdateLayout(); EnqueueCallback(() => { Assert.AreEqual("654321", passwordBox.Password); }); EnqueueTestComplete(); } [Test, Asynchronous] public void MainCaseTextBoxTest() { var propertyChangedViewModel = new PropertyChangedViewModel(); var textBox = new TextBox() { DataContext = propertyChangedViewModel }; ShowWindow(textBox); var behaviorSelectedText = new DependencyPropertyBehavior() { EventName = "SelectionChanged", PropertyName = "SelectedText" }; var behaviorSelectionStart = new DependencyPropertyBehavior() { EventName = "SelectionChanged", PropertyName = "SelectionStart" }; var behaviorSelectionLength = new DependencyPropertyBehavior() { EventName = "SelectionChanged", PropertyName = "SelectionLength" }; Interaction.GetBehaviors(textBox).Add(behaviorSelectedText); Interaction.GetBehaviors(textBox).Add(behaviorSelectionStart); Interaction.GetBehaviors(textBox).Add(behaviorSelectionLength); BindingOperations.SetBinding(textBox, TextBox.TextProperty, new Binding("Text") { Mode = BindingMode.TwoWay }); BindingOperations.SetBinding(behaviorSelectedText, DependencyPropertyBehavior.BindingProperty, new Binding("SelectedText") { Mode = BindingMode.TwoWay }); BindingOperations.SetBinding(behaviorSelectionStart, DependencyPropertyBehavior.BindingProperty, new Binding("SelectionStart") { Mode = BindingMode.TwoWay }); BindingOperations.SetBinding(behaviorSelectionLength, DependencyPropertyBehavior.BindingProperty, new Binding("SelectionLength") { Mode = BindingMode.TwoWay }); EnqueueShowWindow(); EnqueueCallback(() => { propertyChangedViewModel.Text = "12345678901234567890"; propertyChangedViewModel.SelectionStart = 5; propertyChangedViewModel.SelectionLength = 10; }); EnqueueWindowUpdateLayout(); EnqueueCallback(() => { Assert.AreEqual("6789012345", propertyChangedViewModel.SelectedText); }); EnqueueTestComplete(); } [Test, Asynchronous] public void MainCaseNestedPropertiesTextBoxTest() { var propertyChangedViewModel = new PropertyChangedViewModel(); var button = new Button() { DataContext = propertyChangedViewModel }; var textBox = new TextBox(); button.Content = textBox; ShowWindow(button); var behaviorSelectedText = new DependencyPropertyBehavior() { EventName = "Content.SelectionChanged", PropertyName = "Content.SelectedText" }; var behaviorSelectionStart = new DependencyPropertyBehavior() { EventName = "Content.SelectionChanged", PropertyName = "Content.SelectionStart" }; var behaviorSelectionLength = new DependencyPropertyBehavior() { EventName = "Content.SelectionChanged", PropertyName = "Content.SelectionLength" }; Interaction.GetBehaviors(button).Add(behaviorSelectedText); Interaction.GetBehaviors(button).Add(behaviorSelectionStart); Interaction.GetBehaviors(button).Add(behaviorSelectionLength); BindingOperations.SetBinding(textBox, TextBox.TextProperty, new Binding("Text") { Mode = BindingMode.TwoWay }); BindingOperations.SetBinding(behaviorSelectedText, DependencyPropertyBehavior.BindingProperty, new Binding("SelectedText") { Mode = BindingMode.TwoWay }); BindingOperations.SetBinding(behaviorSelectionStart, DependencyPropertyBehavior.BindingProperty, new Binding("SelectionStart") { Mode = BindingMode.TwoWay }); BindingOperations.SetBinding(behaviorSelectionLength, DependencyPropertyBehavior.BindingProperty, new Binding("SelectionLength") { Mode = BindingMode.TwoWay }); EnqueueShowWindow(); EnqueueCallback(() => { propertyChangedViewModel.Text = "12345678901234567890"; propertyChangedViewModel.SelectionStart = 5; propertyChangedViewModel.SelectionLength = 10; }); EnqueueWindowUpdateLayout(); EnqueueCallback(() => { Assert.AreEqual("6789012345", propertyChangedViewModel.SelectedText); }); EnqueueTestComplete(); } [Test, Asynchronous, Ignore] public void ConvertableTypesTest() { var propertyChangedViewModel = new PropertyChangedViewModel() { FloatProperty = 100 }; var button = new Button() { DataContext = propertyChangedViewModel }; ShowWindow(button); var behaviorSelectedText = new DependencyPropertyBehavior() { EventName = "", PropertyName = "Width" }; Interaction.GetBehaviors(button).Add(behaviorSelectedText); BindingOperations.SetBinding(behaviorSelectedText, DependencyPropertyBehavior.BindingProperty, new Binding("FloatProperty") { Mode = BindingMode.TwoWay }); Assert.AreEqual(100, button.Width); EnqueueShowWindow(); EnqueueCallback(() => { propertyChangedViewModel.FloatProperty = 101; }); EnqueueWindowUpdateLayout(); EnqueueCallback(() => { Assert.AreEqual(101, button.Width); button.Width = 102; }); EnqueueWindowUpdateLayout(); EnqueueCallback(() => { Assert.AreEqual(102, button.Width); }); EnqueueTestComplete(); } #if !SILVERLIGHT [Test, Asynchronous] public void OneWayBinding() { var vm = new PropertyChangedViewModel(); var control = new DependencyPropertyBehaviorTestControl() { DataContext = vm }; vm.SetReadOnlyProperty("1"); var behavior = new DependencyPropertyBehavior() { PropertyName = "Property" }; BindingOperations.SetBinding(behavior, DependencyPropertyBehavior.BindingProperty, new Binding("ReadOnlyProperty") { Mode = BindingMode.OneWay }); Interaction.GetBehaviors(control).Add(behavior); Assert.AreEqual(1, control.propertyChangedCounter); Assert.AreEqual("1", control.Property); vm.SetReadOnlyProperty("2"); Assert.AreEqual(2, control.propertyChangedCounter); Assert.AreEqual("2", control.Property); } #endif } public class PropertyChangedViewModel : BindableBase { public PropertyChangedViewModel NestedPropertyChangedViewModel { get; set; } public int TextChangedCounter = 0; string text; public string Text { get { return text; } set { SetProperty(ref text, value, () => Text); TextChangedCounter++; } } public int SelectedTextChangedCounter = 0; string selectedText; public string SelectedText { get { return selectedText; } set { SetProperty(ref selectedText, value, () => SelectedText); SelectedTextChangedCounter++; } } public int SelectionStartChangedCounter = 0; int selectionStart; public int SelectionStart { get { return selectionStart; } set { SetProperty(ref selectionStart, value, () => SelectionStart); SelectionStartChangedCounter++; } } public int SelectionLengthChangedCounter = 0; int selectionLength; public int SelectionLength { get { return selectionLength; } set { SetProperty(ref selectionLength, value, () => SelectionLength); SelectionLengthChangedCounter++; } } public int FloatPropertyChangedCounter = 0; int floatProperty; public int FloatProperty { get { return floatProperty; } set { SetProperty(ref floatProperty, value, () => FloatProperty); FloatPropertyChangedCounter++; } } public string ReadOnlyProperty { get { return GetProperty(() => ReadOnlyProperty); } protected set { SetProperty(() => ReadOnlyProperty, value); } } public void SetReadOnlyProperty(string value) { ReadOnlyProperty = value; } } public class DependencyPropertyBehaviorTestControl : Control { public int propertyChangedCounter = 0; string property; public string Property { get { return property; } set { property = value; propertyChangedCounter++; } } } }
using System; using System.Collections.Generic; using Umbraco.Core.Models; using Umbraco.Core.Persistence.DatabaseModelDefinitions; namespace Umbraco.Core.Services { /// <summary> /// Defines the Media Service, which is an easy access to operations involving <see cref="IMedia"/> /// </summary> public interface IMediaService : IService { /// <summary> /// Rebuilds all xml content in the cmsContentXml table for all media /// </summary> /// <param name="contentTypeIds"> /// Only rebuild the xml structures for the content type ids passed in, if none then rebuilds the structures /// for all media /// </param> void RebuildXmlStructures(params int[] contentTypeIds); int Count(string contentTypeAlias = null); int CountChildren(int parentId, string contentTypeAlias = null); int CountDescendants(int parentId, string contentTypeAlias = null); IEnumerable<IMedia> GetByIds(IEnumerable<int> ids); /// <summary> /// Creates an <see cref="IMedia"/> object using the alias of the <see cref="IMediaType"/> /// that this Media should based on. /// </summary> /// <remarks> /// Note that using this method will simply return a new IMedia without any identity /// as it has not yet been persisted. It is intended as a shortcut to creating new media objects /// that does not invoke a save operation against the database. /// </remarks> /// <param name="name">Name of the Media object</param> /// <param name="parentId">Id of Parent for the new Media item</param> /// <param name="mediaTypeAlias">Alias of the <see cref="IMediaType"/></param> /// <param name="userId">Optional id of the user creating the media item</param> /// <returns><see cref="IMedia"/></returns> IMedia CreateMedia(string name, int parentId, string mediaTypeAlias, int userId = 0); /// <summary> /// Creates an <see cref="IMedia"/> object using the alias of the <see cref="IMediaType"/> /// that this Media should based on. /// </summary> /// <remarks> /// Note that using this method will simply return a new IMedia without any identity /// as it has not yet been persisted. It is intended as a shortcut to creating new media objects /// that does not invoke a save operation against the database. /// </remarks> /// <param name="name">Name of the Media object</param> /// <param name="parent">Parent <see cref="IMedia"/> for the new Media item</param> /// <param name="mediaTypeAlias">Alias of the <see cref="IMediaType"/></param> /// <param name="userId">Optional id of the user creating the media item</param> /// <returns><see cref="IMedia"/></returns> IMedia CreateMedia(string name, IMedia parent, string mediaTypeAlias, int userId = 0); /// <summary> /// Gets an <see cref="IMedia"/> object by Id /// </summary> /// <param name="id">Id of the Content to retrieve</param> /// <returns><see cref="IMedia"/></returns> IMedia GetById(int id); /// <summary> /// Gets a collection of <see cref="IMedia"/> objects by Parent Id /// </summary> /// <param name="id">Id of the Parent to retrieve Children from</param> /// <returns>An Enumerable list of <see cref="IMedia"/> objects</returns> IEnumerable<IMedia> GetChildren(int id); /// <summary> /// Gets a collection of <see cref="IMedia"/> objects by Parent Id /// </summary> /// <param name="id">Id of the Parent to retrieve Children from</param> /// <param name="pageIndex">Page number</param> /// <param name="pageSize">Page size</param> /// <param name="totalRecords">Total records query would return without paging</param> /// <param name="orderBy">Field to order by</param> /// <param name="orderDirection">Direction to order by</param> /// <param name="filter">Search text filter</param> /// <returns>An Enumerable list of <see cref="IContent"/> objects</returns> IEnumerable<IMedia> GetPagedChildren(int id, int pageIndex, int pageSize, out int totalRecords, string orderBy = "SortOrder", Direction orderDirection = Direction.Ascending, string filter = ""); /// <summary> /// Gets a collection of <see cref="IMedia"/> objects by Parent Id /// </summary> /// <param name="id">Id of the Parent to retrieve Descendants from</param> /// <param name="pageIndex">Page number</param> /// <param name="pageSize">Page size</param> /// <param name="totalRecords">Total records query would return without paging</param> /// <param name="orderBy">Field to order by</param> /// <param name="orderDirection">Direction to order by</param> /// <param name="filter">Search text filter</param> /// <returns>An Enumerable list of <see cref="IContent"/> objects</returns> IEnumerable<IMedia> GetPagedDescendants(int id, int pageIndex, int pageSize, out int totalRecords, string orderBy = "Path", Direction orderDirection = Direction.Ascending, string filter = ""); /// <summary> /// Gets descendants of a <see cref="IMedia"/> object by its Id /// </summary> /// <param name="id">Id of the Parent to retrieve descendants from</param> /// <returns>An Enumerable flat list of <see cref="IMedia"/> objects</returns> IEnumerable<IMedia> GetDescendants(int id); /// <summary> /// Gets a collection of <see cref="IMedia"/> objects by the Id of the <see cref="IContentType"/> /// </summary> /// <param name="id">Id of the <see cref="IMediaType"/></param> /// <returns>An Enumerable list of <see cref="IMedia"/> objects</returns> IEnumerable<IMedia> GetMediaOfMediaType(int id); /// <summary> /// Gets a collection of <see cref="IMedia"/> objects, which reside at the first level / root /// </summary> /// <returns>An Enumerable list of <see cref="IMedia"/> objects</returns> IEnumerable<IMedia> GetRootMedia(); /// <summary> /// Gets a collection of an <see cref="IMedia"/> objects, which resides in the Recycle Bin /// </summary> /// <returns>An Enumerable list of <see cref="IMedia"/> objects</returns> IEnumerable<IMedia> GetMediaInRecycleBin(); /// <summary> /// Moves an <see cref="IMedia"/> object to a new location /// </summary> /// <param name="media">The <see cref="IMedia"/> to move</param> /// <param name="parentId">Id of the Media's new Parent</param> /// <param name="userId">Id of the User moving the Media</param> void Move(IMedia media, int parentId, int userId = 0); /// <summary> /// Deletes an <see cref="IMedia"/> object by moving it to the Recycle Bin /// </summary> /// <param name="media">The <see cref="IMedia"/> to delete</param> /// <param name="userId">Id of the User deleting the Media</param> void MoveToRecycleBin(IMedia media, int userId = 0); /// <summary> /// Empties the Recycle Bin by deleting all <see cref="IMedia"/> that resides in the bin /// </summary> void EmptyRecycleBin(); /// <summary> /// Deletes all media of specified type. All children of deleted media is moved to Recycle Bin. /// </summary> /// <remarks>This needs extra care and attention as its potentially a dangerous and extensive operation</remarks> /// <param name="mediaTypeId">Id of the <see cref="IMediaType"/></param> /// <param name="userId">Optional Id of the user deleting Media</param> void DeleteMediaOfType(int mediaTypeId, int userId = 0); /// <summary> /// Permanently deletes an <see cref="IMedia"/> object /// </summary> /// <remarks> /// Please note that this method will completely remove the Media from the database, /// but current not from the file system. /// </remarks> /// <param name="media">The <see cref="IMedia"/> to delete</param> /// <param name="userId">Id of the User deleting the Media</param> void Delete(IMedia media, int userId = 0); /// <summary> /// Saves a single <see cref="IMedia"/> object /// </summary> /// <param name="media">The <see cref="IMedia"/> to save</param> /// <param name="userId">Id of the User saving the Media</param> /// <param name="raiseEvents">Optional boolean indicating whether or not to raise events.</param> void Save(IMedia media, int userId = 0, bool raiseEvents = true); /// <summary> /// Saves a collection of <see cref="IMedia"/> objects /// </summary> /// <param name="medias">Collection of <see cref="IMedia"/> to save</param> /// <param name="userId">Id of the User saving the Media</param> /// <param name="raiseEvents">Optional boolean indicating whether or not to raise events.</param> void Save(IEnumerable<IMedia> medias, int userId = 0, bool raiseEvents = true); /// <summary> /// Gets an <see cref="IMedia"/> object by its 'UniqueId' /// </summary> /// <param name="key">Guid key of the Media to retrieve</param> /// <returns><see cref="IMedia"/></returns> IMedia GetById(Guid key); /// <summary> /// Gets a collection of <see cref="IMedia"/> objects by Level /// </summary> /// <param name="level">The level to retrieve Media from</param> /// <returns>An Enumerable list of <see cref="IMedia"/> objects</returns> IEnumerable<IMedia> GetByLevel(int level); /// <summary> /// Gets a specific version of an <see cref="IMedia"/> item. /// </summary> /// <param name="versionId">Id of the version to retrieve</param> /// <returns>An <see cref="IMedia"/> item</returns> IMedia GetByVersion(Guid versionId); /// <summary> /// Gets a collection of an <see cref="IMedia"/> objects versions by Id /// </summary> /// <param name="id"></param> /// <returns>An Enumerable list of <see cref="IMedia"/> objects</returns> IEnumerable<IMedia> GetVersions(int id); /// <summary> /// Checks whether an <see cref="IMedia"/> item has any children /// </summary> /// <param name="id">Id of the <see cref="IMedia"/></param> /// <returns>True if the media has any children otherwise False</returns> bool HasChildren(int id); /// <summary> /// Permanently deletes versions from an <see cref="IMedia"/> object prior to a specific date. /// </summary> /// <param name="id">Id of the <see cref="IMedia"/> object to delete versions from</param> /// <param name="versionDate">Latest version date</param> /// <param name="userId">Optional Id of the User deleting versions of a Content object</param> void DeleteVersions(int id, DateTime versionDate, int userId = 0); /// <summary> /// Permanently deletes specific version(s) from an <see cref="IMedia"/> object. /// </summary> /// <param name="id">Id of the <see cref="IMedia"/> object to delete a version from</param> /// <param name="versionId">Id of the version to delete</param> /// <param name="deletePriorVersions">Boolean indicating whether to delete versions prior to the versionId</param> /// <param name="userId">Optional Id of the User deleting versions of a Content object</param> void DeleteVersion(int id, Guid versionId, bool deletePriorVersions, int userId = 0); /// <summary> /// Gets an <see cref="IMedia"/> object from the path stored in the 'umbracoFile' property. /// </summary> /// <param name="mediaPath">Path of the media item to retrieve (for example: /media/1024/koala_403x328.jpg)</param> /// <returns><see cref="IMedia"/></returns> IMedia GetMediaByPath(string mediaPath); /// <summary> /// Gets a collection of <see cref="IMedia"/> objects, which are ancestors of the current media. /// </summary> /// <param name="id">Id of the <see cref="IMedia"/> to retrieve ancestors for</param> /// <returns>An Enumerable list of <see cref="IMedia"/> objects</returns> IEnumerable<IMedia> GetAncestors(int id); /// <summary> /// Gets a collection of <see cref="IMedia"/> objects, which are ancestors of the current media. /// </summary> /// <param name="media"><see cref="IMedia"/> to retrieve ancestors for</param> /// <returns>An Enumerable list of <see cref="IMedia"/> objects</returns> IEnumerable<IMedia> GetAncestors(IMedia media); /// <summary> /// Gets descendants of a <see cref="IMedia"/> object by its Id /// </summary> /// <param name="media">The Parent <see cref="IMedia"/> object to retrieve descendants from</param> /// <returns>An Enumerable flat list of <see cref="IMedia"/> objects</returns> IEnumerable<IMedia> GetDescendants(IMedia media); /// <summary> /// Gets the parent of the current media as an <see cref="IMedia"/> item. /// </summary> /// <param name="id">Id of the <see cref="IMedia"/> to retrieve the parent from</param> /// <returns>Parent <see cref="IMedia"/> object</returns> IMedia GetParent(int id); /// <summary> /// Gets the parent of the current media as an <see cref="IMedia"/> item. /// </summary> /// <param name="media"><see cref="IMedia"/> to retrieve the parent from</param> /// <returns>Parent <see cref="IMedia"/> object</returns> IMedia GetParent(IMedia media); /// <summary> /// Sorts a collection of <see cref="IMedia"/> objects by updating the SortOrder according /// to the ordering of items in the passed in <see cref="IEnumerable{T}"/>. /// </summary> /// <param name="items"></param> /// <param name="userId"></param> /// <param name="raiseEvents"></param> /// <returns>True if sorting succeeded, otherwise False</returns> bool Sort(IEnumerable<IMedia> items, int userId = 0, bool raiseEvents = true); /// <summary> /// Creates an <see cref="IMedia"/> object using the alias of the <see cref="IMediaType"/> /// that this Media should based on. /// </summary> /// <remarks> /// This method returns an <see cref="IMedia"/> object that has been persisted to the database /// and therefor has an identity. /// </remarks> /// <param name="name">Name of the Media object</param> /// <param name="parent">Parent <see cref="IMedia"/> for the new Media item</param> /// <param name="mediaTypeAlias">Alias of the <see cref="IMediaType"/></param> /// <param name="userId">Optional id of the user creating the media item</param> /// <returns><see cref="IMedia"/></returns> IMedia CreateMediaWithIdentity(string name, IMedia parent, string mediaTypeAlias, int userId = 0); /// <summary> /// Creates an <see cref="IMedia"/> object using the alias of the <see cref="IMediaType"/> /// that this Media should based on. /// </summary> /// <remarks> /// This method returns an <see cref="IMedia"/> object that has been persisted to the database /// and therefor has an identity. /// </remarks> /// <param name="name">Name of the Media object</param> /// <param name="parentId">Id of Parent for the new Media item</param> /// <param name="mediaTypeAlias">Alias of the <see cref="IMediaType"/></param> /// <param name="userId">Optional id of the user creating the media item</param> /// <returns><see cref="IMedia"/></returns> IMedia CreateMediaWithIdentity(string name, int parentId, string mediaTypeAlias, int userId = 0); } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.Azure.AcceptanceTestsPaging { using Fixtures.Azure; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; /// <summary> /// PagingOperations operations. /// </summary> public partial interface IPagingOperations { /// <summary> /// A paging operation that finishes on the first call without a /// nextlink /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> Task<AzureOperationResponse<IPage<Product>>> GetSinglePagesWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// A paging operation that includes a nextLink that has 10 pages /// </summary> /// <param name='clientRequestId'> /// </param> /// <param name='pagingGetMultiplePagesOptions'> /// Additional parameters for the operation /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> Task<AzureOperationResponse<IPage<Product>>> GetMultiplePagesWithHttpMessagesAsync(string clientRequestId = default(string), PagingGetMultiplePagesOptions pagingGetMultiplePagesOptions = default(PagingGetMultiplePagesOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// A paging operation that includes a nextLink in odata format that /// has 10 pages /// </summary> /// <param name='clientRequestId'> /// </param> /// <param name='pagingGetOdataMultiplePagesOptions'> /// Additional parameters for the operation /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> Task<AzureOperationResponse<IPage<Product>>> GetOdataMultiplePagesWithHttpMessagesAsync(string clientRequestId = default(string), PagingGetOdataMultiplePagesOptions pagingGetOdataMultiplePagesOptions = default(PagingGetOdataMultiplePagesOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// A paging operation that includes a nextLink that has 10 pages /// </summary> /// <param name='pagingGetMultiplePagesWithOffsetOptions'> /// Additional parameters for the operation /// </param> /// <param name='clientRequestId'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<Product>>> GetMultiplePagesWithOffsetWithHttpMessagesAsync(PagingGetMultiplePagesWithOffsetOptions pagingGetMultiplePagesWithOffsetOptions, string clientRequestId = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// A paging operation that fails on the first call with 500 and then /// retries and then get a response including a nextLink that has 10 /// pages /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> Task<AzureOperationResponse<IPage<Product>>> GetMultiplePagesRetryFirstWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// A paging operation that includes a nextLink that has 10 pages, of /// which the 2nd call fails first with 500. The client should retry /// and finish all 10 pages eventually. /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> Task<AzureOperationResponse<IPage<Product>>> GetMultiplePagesRetrySecondWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// A paging operation that receives a 400 on the first call /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> Task<AzureOperationResponse<IPage<Product>>> GetSinglePagesFailureWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// A paging operation that receives a 400 on the second call /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> Task<AzureOperationResponse<IPage<Product>>> GetMultiplePagesFailureWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// A paging operation that receives an invalid nextLink /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> Task<AzureOperationResponse<IPage<Product>>> GetMultiplePagesFailureUriWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// A paging operation that doesn't return a full URL, just a fragment /// </summary> /// <param name='apiVersion'> /// Sets the api version to use. /// </param> /// <param name='tenant'> /// Sets the tenant to use. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<Product>>> GetMultiplePagesFragmentNextLinkWithHttpMessagesAsync(string apiVersion, string tenant, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// A paging operation that doesn't return a full URL, just a fragment /// with parameters grouped /// </summary> /// <param name='customParameterGroup'> /// Additional parameters for the operation /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<Product>>> GetMultiplePagesFragmentWithGroupingNextLinkWithHttpMessagesAsync(CustomParameterGroup customParameterGroup, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// A paging operation that doesn't return a full URL, just a fragment /// </summary> /// <param name='apiVersion'> /// Sets the api version to use. /// </param> /// <param name='tenant'> /// Sets the tenant to use. /// </param> /// <param name='nextLink'> /// Next link for list operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<Product>>> NextFragmentWithHttpMessagesAsync(string apiVersion, string tenant, string nextLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// A paging operation that doesn't return a full URL, just a fragment /// </summary> /// <param name='nextLink'> /// Next link for list operation. /// </param> /// <param name='customParameterGroup'> /// Additional parameters for the operation /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<Product>>> NextFragmentWithGroupingWithHttpMessagesAsync(string nextLink, CustomParameterGroup customParameterGroup, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// A paging operation that finishes on the first call without a /// nextlink /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<Product>>> GetSinglePagesNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// A paging operation that includes a nextLink that has 10 pages /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='clientRequestId'> /// </param> /// <param name='pagingGetMultiplePagesOptions'> /// Additional parameters for the operation /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<Product>>> GetMultiplePagesNextWithHttpMessagesAsync(string nextPageLink, string clientRequestId = default(string), PagingGetMultiplePagesOptions pagingGetMultiplePagesOptions = default(PagingGetMultiplePagesOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// A paging operation that includes a nextLink in odata format that /// has 10 pages /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='clientRequestId'> /// </param> /// <param name='pagingGetOdataMultiplePagesOptions'> /// Additional parameters for the operation /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<Product>>> GetOdataMultiplePagesNextWithHttpMessagesAsync(string nextPageLink, string clientRequestId = default(string), PagingGetOdataMultiplePagesOptions pagingGetOdataMultiplePagesOptions = default(PagingGetOdataMultiplePagesOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// A paging operation that includes a nextLink that has 10 pages /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='clientRequestId'> /// </param> /// <param name='pagingGetMultiplePagesWithOffsetNextOptions'> /// Additional parameters for the operation /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<Product>>> GetMultiplePagesWithOffsetNextWithHttpMessagesAsync(string nextPageLink, string clientRequestId = default(string), PagingGetMultiplePagesWithOffsetNextOptions pagingGetMultiplePagesWithOffsetNextOptions = default(PagingGetMultiplePagesWithOffsetNextOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// A paging operation that fails on the first call with 500 and then /// retries and then get a response including a nextLink that has 10 /// pages /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<Product>>> GetMultiplePagesRetryFirstNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// A paging operation that includes a nextLink that has 10 pages, of /// which the 2nd call fails first with 500. The client should retry /// and finish all 10 pages eventually. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<Product>>> GetMultiplePagesRetrySecondNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// A paging operation that receives a 400 on the first call /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<Product>>> GetSinglePagesFailureNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// A paging operation that receives a 400 on the second call /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<Product>>> GetMultiplePagesFailureNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// A paging operation that receives an invalid nextLink /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<Product>>> GetMultiplePagesFailureUriNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. //------------------------------------------------------------------------------ using System.Data.Common; using System.Diagnostics; using System.Globalization; namespace System.Data.SqlTypes { public struct SqlBinary : INullable, IComparable { private byte[] _value; // null if m_value is null // constructor // construct a Null private SqlBinary(bool fNull) { _value = null; } /// <devdoc> /// <para> /// Initializes a new instance of the <see cref='System.Data.SqlTypes.SqlBinary'/> class with a binary object to be stored. /// </para> /// </devdoc> public SqlBinary(byte[] value) { // if value is null, this generates a SqlBinary.Null if (value == null) _value = null; else { _value = new byte[value.Length]; value.CopyTo(_value, 0); } } /// <devdoc> /// <para> /// Initializes a new instance of the <see cref='System.Data.SqlTypes.SqlBinary'/> class with a binary object to be stored. This constructor will not copy the value. /// </para> /// </devdoc> internal SqlBinary(byte[] value, bool ignored) { // if value is null, this generates a SqlBinary.Null if (value == null) _value = null; else { _value = value; } } // INullable /// <devdoc> /// <para> /// Gets whether or not <see cref='System.Data.SqlTypes.SqlBinary.Value'/> is null. /// </para> /// </devdoc> public bool IsNull { get { return (_value == null); } } // property: Value /// <devdoc> /// <para> /// Gets /// or sets the /// value of the SQL binary object retrieved. /// </para> /// </devdoc> public byte[] Value { get { if (IsNull) throw new SqlNullValueException(); else { byte[] value = new byte[_value.Length]; _value.CopyTo(value, 0); return value; } } } // class indexer public byte this[int index] { get { if (IsNull) throw new SqlNullValueException(); else return _value[index]; } } // property: Length /// <devdoc> /// <para> /// Gets the length in bytes of <see cref='System.Data.SqlTypes.SqlBinary.Value'/>. /// </para> /// </devdoc> public int Length { get { if (!IsNull) return _value.Length; else throw new SqlNullValueException(); } } // Implicit conversion from byte[] to SqlBinary // Alternative: constructor SqlBinary(bytep[]) /// <devdoc> /// <para> /// Converts a binary object to a <see cref='System.Data.SqlTypes.SqlBinary'/>. /// </para> /// </devdoc> public static implicit operator SqlBinary(byte[] x) { return new SqlBinary(x); } // Explicit conversion from SqlBinary to byte[]. Throw exception if x is Null. // Alternative: Value property /// <devdoc> /// <para> /// Converts a <see cref='System.Data.SqlTypes.SqlBinary'/> to a binary object. /// </para> /// </devdoc> public static explicit operator byte[] (SqlBinary x) { return x.Value; } /// <devdoc> /// <para> /// Returns a string describing a <see cref='System.Data.SqlTypes.SqlBinary'/> object. /// </para> /// </devdoc> public override String ToString() { return IsNull ? SQLResource.NullString : "SqlBinary(" + _value.Length.ToString(CultureInfo.InvariantCulture) + ")"; } // Unary operators // Binary operators // Arithmetic operators /// <devdoc> /// <para> /// Adds two instances of <see cref='System.Data.SqlTypes.SqlBinary'/> together. /// </para> /// </devdoc> // Alternative method: SqlBinary.Concat public static SqlBinary operator +(SqlBinary x, SqlBinary y) { if (x.IsNull || y.IsNull) return Null; byte[] rgbResult = new byte[x.Value.Length + y.Value.Length]; x.Value.CopyTo(rgbResult, 0); y.Value.CopyTo(rgbResult, x.Value.Length); return new SqlBinary(rgbResult); } // Comparisons private static EComparison PerformCompareByte(byte[] x, byte[] y) { // the smaller length of two arrays int len = (x.Length < y.Length) ? x.Length : y.Length; int i; for (i = 0; i < len; ++i) { if (x[i] != y[i]) { if (x[i] < y[i]) return EComparison.LT; else return EComparison.GT; } } if (x.Length == y.Length) return EComparison.EQ; else { // if the remaining bytes are all zeroes, they are still equal. byte bZero = (byte)0; if (x.Length < y.Length) { // array X is shorter for (i = len; i < y.Length; ++i) { if (y[i] != bZero) return EComparison.LT; } } else { // array Y is shorter for (i = len; i < x.Length; ++i) { if (x[i] != bZero) return EComparison.GT; } } return EComparison.EQ; } } // Implicit conversions // Explicit conversions // Explicit conversion from SqlGuid to SqlBinary /// <devdoc> /// <para> /// Converts a <see cref='System.Data.SqlTypes.SqlGuid'/> to a <see cref='System.Data.SqlTypes.SqlBinary'/> /// . /// </para> /// </devdoc> // Alternative method: SqlGuid.ToSqlBinary public static explicit operator SqlBinary(SqlGuid x) { return x.IsNull ? SqlBinary.Null : new SqlBinary(x.ToByteArray()); } // Builtin functions // Overloading comparison operators /// <devdoc> /// <para> /// Compares two instances of <see cref='System.Data.SqlTypes.SqlBinary'/> for /// equality. /// </para> /// </devdoc> public static SqlBoolean operator ==(SqlBinary x, SqlBinary y) { if (x.IsNull || y.IsNull) return SqlBoolean.Null; return new SqlBoolean(PerformCompareByte(x.Value, y.Value) == EComparison.EQ); } /// <devdoc> /// <para> /// Compares two instances of <see cref='System.Data.SqlTypes.SqlBinary'/> /// for equality. /// </para> /// </devdoc> public static SqlBoolean operator !=(SqlBinary x, SqlBinary y) { return !(x == y); } /// <devdoc> /// <para> /// Compares the first <see cref='System.Data.SqlTypes.SqlBinary'/> for being less than the /// second <see cref='System.Data.SqlTypes.SqlBinary'/>. /// </para> /// </devdoc> public static SqlBoolean operator <(SqlBinary x, SqlBinary y) { if (x.IsNull || y.IsNull) return SqlBoolean.Null; return new SqlBoolean(PerformCompareByte(x.Value, y.Value) == EComparison.LT); } /// <devdoc> /// <para> /// Compares the first <see cref='System.Data.SqlTypes.SqlBinary'/> for being greater than the second <see cref='System.Data.SqlTypes.SqlBinary'/>. /// </para> /// </devdoc> public static SqlBoolean operator >(SqlBinary x, SqlBinary y) { if (x.IsNull || y.IsNull) return SqlBoolean.Null; return new SqlBoolean(PerformCompareByte(x.Value, y.Value) == EComparison.GT); } /// <devdoc> /// <para> /// Compares the first <see cref='System.Data.SqlTypes.SqlBinary'/> for being less than or equal to the second <see cref='System.Data.SqlTypes.SqlBinary'/>. /// </para> /// </devdoc> public static SqlBoolean operator <=(SqlBinary x, SqlBinary y) { if (x.IsNull || y.IsNull) return SqlBoolean.Null; EComparison cmpResult = PerformCompareByte(x.Value, y.Value); return new SqlBoolean(cmpResult == EComparison.LT || cmpResult == EComparison.EQ); } /// <devdoc> /// <para> /// Compares the first <see cref='System.Data.SqlTypes.SqlBinary'/> for being greater than or equal the second <see cref='System.Data.SqlTypes.SqlBinary'/>. /// </para> /// </devdoc> public static SqlBoolean operator >=(SqlBinary x, SqlBinary y) { if (x.IsNull || y.IsNull) return SqlBoolean.Null; EComparison cmpResult = PerformCompareByte(x.Value, y.Value); return new SqlBoolean(cmpResult == EComparison.GT || cmpResult == EComparison.EQ); } //-------------------------------------------------- // Alternative methods for overloaded operators //-------------------------------------------------- // Alternative method for operator + public static SqlBinary Add(SqlBinary x, SqlBinary y) { return x + y; } public static SqlBinary Concat(SqlBinary x, SqlBinary y) { return x + y; } // Alternative method for operator == public static SqlBoolean Equals(SqlBinary x, SqlBinary y) { return (x == y); } // Alternative method for operator != public static SqlBoolean NotEquals(SqlBinary x, SqlBinary y) { return (x != y); } // Alternative method for operator < public static SqlBoolean LessThan(SqlBinary x, SqlBinary y) { return (x < y); } // Alternative method for operator > public static SqlBoolean GreaterThan(SqlBinary x, SqlBinary y) { return (x > y); } // Alternative method for operator <= public static SqlBoolean LessThanOrEqual(SqlBinary x, SqlBinary y) { return (x <= y); } // Alternative method for operator >= public static SqlBoolean GreaterThanOrEqual(SqlBinary x, SqlBinary y) { return (x >= y); } // Alternative method for conversions. public SqlGuid ToSqlGuid() { return (SqlGuid)this; } // IComparable // Compares this object to another object, returning an integer that // indicates the relationship. // Returns a value less than zero if this < object, zero if this = object, // or a value greater than zero if this > object. // null is considered to be less than any instance. // If object is not of same type, this method throws an ArgumentException. /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public int CompareTo(Object value) { if (value is SqlBinary) { SqlBinary i = (SqlBinary)value; return CompareTo(i); } throw ADP.WrongType(value.GetType(), typeof(SqlBinary)); } public int CompareTo(SqlBinary value) { // If both Null, consider them equal. // Otherwise, Null is less than anything. if (IsNull) return value.IsNull ? 0 : -1; else if (value.IsNull) return 1; if (this < value) return -1; if (this > value) return 1; return 0; } // Compares this instance with a specified object /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public override bool Equals(Object value) { if (!(value is SqlBinary)) { return false; } SqlBinary i = (SqlBinary)value; if (i.IsNull || IsNull) return (i.IsNull && IsNull); else return (this == i).Value; } // Hash a byte array. // Trailing zeroes/spaces would affect the hash value, so caller needs to // perform trimming as necessary. internal static int HashByteArray(byte[] rgbValue, int length) { Debug.Assert(length >= 0); if (length <= 0) return 0; Debug.Assert(rgbValue.Length >= length); int ulValue = 0; int ulHi; // Size of CRC window (hashing bytes, ssstr, sswstr, numeric) const int x_cbCrcWindow = 4; // const int iShiftVal = (sizeof ulValue) * (8*sizeof(char)) - x_cbCrcWindow; const int iShiftVal = 4 * 8 - x_cbCrcWindow; for (int i = 0; i < length; i++) { ulHi = (ulValue >> iShiftVal) & 0xff; ulValue <<= x_cbCrcWindow; ulValue = ulValue ^ rgbValue[i] ^ ulHi; } return ulValue; } // For hashing purpose /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public override int GetHashCode() { if (IsNull) return 0; //First trim off extra '\0's int cbLen = _value.Length; while (cbLen > 0 && _value[cbLen - 1] == 0) --cbLen; return HashByteArray(_value, cbLen); } /// <devdoc> /// <para> /// Represents a null value that can be assigned to /// the <see cref='System.Data.SqlTypes.SqlBinary.Value'/> property of an /// instance of the <see cref='System.Data.SqlTypes.SqlBinary'/> class. /// </para> /// </devdoc> public static readonly SqlBinary Null = new SqlBinary(true); } // SqlBinary } // namespace System.Data.SqlTypes
// Copyright (c) 1995-2009 held by the author(s). 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 names of the Naval Postgraduate School (NPS) // Modeling Virtual Environments and Simulation (MOVES) Institute // (http://www.nps.edu and http://www.MovesInstitute.org) // 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. // // Copyright (c) 2008, MOVES Institute, Naval Postgraduate School. All // rights reserved. This work is licensed under the BSD open source license, // available at https://www.movesinstitute.org/licenses/bsd.html // // Author: DMcG // Modified for use with C#: // - Peter Smith (Naval Air Warfare Center - Training Systems Division) // - Zvonko Bostjancic (Blubit d.o.o. - zvonko.bostjancic@blubit.si) using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Text; using System.Xml.Serialization; using OpenDis.Core; namespace OpenDis.Dis1995 { /// <summary> /// Section 5.3.7. Electronic Emmisions /// </summary> [Serializable] [XmlRoot] public partial class DistributedEmissionsPdu : Pdu, IEquatable<DistributedEmissionsPdu> { /// <summary> /// Initializes a new instance of the <see cref="DistributedEmissionsPdu"/> class. /// </summary> public DistributedEmissionsPdu() { ProtocolFamily = (byte)6; } /// <summary> /// Implements the operator !=. /// </summary> /// <param name="left">The left operand.</param> /// <param name="right">The right operand.</param> /// <returns> /// <c>true</c> if operands are not equal; otherwise, <c>false</c>. /// </returns> public static bool operator !=(DistributedEmissionsPdu left, DistributedEmissionsPdu right) { return !(left == right); } /// <summary> /// Implements the operator ==. /// </summary> /// <param name="left">The left operand.</param> /// <param name="right">The right operand.</param> /// <returns> /// <c>true</c> if both operands are equal; otherwise, <c>false</c>. /// </returns> public static bool operator ==(DistributedEmissionsPdu left, DistributedEmissionsPdu right) { if (object.ReferenceEquals(left, right)) { return true; } if (((object)left == null) || ((object)right == null)) { return false; } return left.Equals(right); } public override int GetMarshalledSize() { int marshalSize = 0; marshalSize = base.GetMarshalledSize(); return marshalSize; } /// <summary> /// Automatically sets the length of the marshalled data, then calls the marshal method. /// </summary> /// <param name="dos">The DataOutputStream instance to which the PDU is marshaled.</param> public virtual void MarshalAutoLengthSet(DataOutputStream dos) { // Set the length prior to marshalling data this.Length = (ushort)this.GetMarshalledSize(); this.Marshal(dos); } /// <summary> /// Marshal the data to the DataOutputStream. Note: Length needs to be set before calling this method /// </summary> /// <param name="dos">The DataOutputStream instance to which the PDU is marshaled.</param> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")] public override void Marshal(DataOutputStream dos) { base.Marshal(dos); if (dos != null) { try { } catch (Exception e) { if (PduBase.TraceExceptions) { Trace.WriteLine(e); Trace.Flush(); } this.RaiseExceptionOccured(e); if (PduBase.ThrowExceptions) { throw e; } } } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")] public override void Unmarshal(DataInputStream dis) { base.Unmarshal(dis); if (dis != null) { try { } catch (Exception e) { if (PduBase.TraceExceptions) { Trace.WriteLine(e); Trace.Flush(); } this.RaiseExceptionOccured(e); if (PduBase.ThrowExceptions) { throw e; } } } } /// <summary> /// This allows for a quick display of PDU data. The current format is unacceptable and only used for debugging. /// This will be modified in the future to provide a better display. Usage: /// pdu.GetType().InvokeMember("Reflection", System.Reflection.BindingFlags.InvokeMethod, null, pdu, new object[] { sb }); /// where pdu is an object representing a single pdu and sb is a StringBuilder. /// Note: The supplied Utilities folder contains a method called 'DecodePDU' in the PDUProcessor Class that provides this functionality /// </summary> /// <param name="sb">The StringBuilder instance to which the PDU is written to.</param> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")] public override void Reflection(StringBuilder sb) { sb.AppendLine("<DistributedEmissionsPdu>"); base.Reflection(sb); try { sb.AppendLine("</DistributedEmissionsPdu>"); } catch (Exception e) { if (PduBase.TraceExceptions) { Trace.WriteLine(e); Trace.Flush(); } this.RaiseExceptionOccured(e); if (PduBase.ThrowExceptions) { throw e; } } } /// <summary> /// Determines whether the specified <see cref="System.Object"/> is equal to this instance. /// </summary> /// <param name="obj">The <see cref="System.Object"/> to compare with this instance.</param> /// <returns> /// <c>true</c> if the specified <see cref="System.Object"/> is equal to this instance; otherwise, <c>false</c>. /// </returns> public override bool Equals(object obj) { return this == obj as DistributedEmissionsPdu; } /// <summary> /// Compares for reference AND value equality. /// </summary> /// <param name="obj">The object to compare with this instance.</param> /// <returns> /// <c>true</c> if both operands are equal; otherwise, <c>false</c>. /// </returns> public bool Equals(DistributedEmissionsPdu obj) { bool ivarsEqual = true; if (obj.GetType() != this.GetType()) { return false; } ivarsEqual = base.Equals(obj); return ivarsEqual; } /// <summary> /// HashCode Helper /// </summary> /// <param name="hash">The hash value.</param> /// <returns>The new hash value.</returns> private static int GenerateHash(int hash) { hash = hash << (5 + hash); return hash; } /// <summary> /// Gets the hash code. /// </summary> /// <returns>The hash code.</returns> public override int GetHashCode() { int result = 0; result = GenerateHash(result) ^ base.GetHashCode(); return result; } } }
/* * Copyright 2010 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; namespace ZXing.Common.Detector { /// <summary> /// Detects a candidate barcode-like rectangular region within an image. It /// starts around the center of the image, increases the size of the candidate /// region until it finds a white rectangular region. By keeping track of the /// last black points it encountered, it determines the corners of the barcode. /// </summary> /// <author>David Olivier</author> public sealed class WhiteRectangleDetector { private const int INIT_SIZE = 30; private const int CORR = 1; private readonly BitMatrix image; private readonly int height; private readonly int width; private readonly int leftInit; private readonly int rightInit; private readonly int downInit; private readonly int upInit; /// <summary> /// Creates a WhiteRectangleDetector instance /// </summary> /// <param name="image">The image.</param> /// <returns>null, if image is too small, otherwise a WhiteRectangleDetector instance</returns> public static WhiteRectangleDetector Create(BitMatrix image) { var instance = new WhiteRectangleDetector(image); if (instance.upInit < 0 || instance.leftInit < 0 || instance.downInit >= instance.height || instance.rightInit >= instance.width) { return null; } return instance; } /// <summary> /// Creates a WhiteRectangleDetector instance /// </summary> /// <param name="image">The image.</param> /// <param name="initSize">Size of the init.</param> /// <param name="x">The x.</param> /// <param name="y">The y.</param> /// <returns> /// null, if image is too small, otherwise a WhiteRectangleDetector instance /// </returns> public static WhiteRectangleDetector Create(BitMatrix image, int initSize, int x, int y) { var instance = new WhiteRectangleDetector(image, initSize, x, y); if (instance.upInit < 0 || instance.leftInit < 0 || instance.downInit >= instance.height || instance.rightInit >= instance.width) { return null; } return instance; } /// <summary> /// Initializes a new instance of the <see cref="WhiteRectangleDetector"/> class. /// </summary> /// <param name="image">The image.</param> /// <exception cref="ArgumentException">if image is too small</exception> internal WhiteRectangleDetector(BitMatrix image) { this.image = image; height = image.Height; width = image.Width; leftInit = (width - INIT_SIZE) >> 1; rightInit = (width + INIT_SIZE) >> 1; upInit = (height - INIT_SIZE) >> 1; downInit = (height + INIT_SIZE) >> 1; } /// <summary> /// Initializes a new instance of the <see cref="WhiteRectangleDetector"/> class. /// </summary> /// <param name="image">The image.</param> /// <param name="initSize">Size of the init.</param> /// <param name="x">The x.</param> /// <param name="y">The y.</param> internal WhiteRectangleDetector(BitMatrix image, int initSize, int x, int y) { this.image = image; height = image.Height; width = image.Width; int halfsize = initSize >> 1; leftInit = x - halfsize; rightInit = x + halfsize; upInit = y - halfsize; downInit = y + halfsize; } /// <summary> /// Detects a candidate barcode-like rectangular region within an image. It /// starts around the center of the image, increases the size of the candidate /// region until it finds a white rectangular region. /// </summary> /// <returns><see cref="ResultPoint" />[] describing the corners of the rectangular /// region. The first and last points are opposed on the diagonal, as /// are the second and third. The first point will be the topmost /// point and the last, the bottommost. The second point will be /// leftmost and the third, the rightmost</returns> public ResultPoint[] detect() { int left = leftInit; int right = rightInit; int up = upInit; int down = downInit; bool sizeExceeded = false; bool aBlackPointFoundOnBorder = true; bool atLeastOneBlackPointFoundOnBorder = false; while (aBlackPointFoundOnBorder) { aBlackPointFoundOnBorder = false; // ..... // . | // ..... bool rightBorderNotWhite = true; while (rightBorderNotWhite && right < width) { rightBorderNotWhite = containsBlackPoint(up, down, right, false); if (rightBorderNotWhite) { right++; aBlackPointFoundOnBorder = true; } } if (right >= width) { sizeExceeded = true; break; } // ..... // . . // .___. bool bottomBorderNotWhite = true; while (bottomBorderNotWhite && down < height) { bottomBorderNotWhite = containsBlackPoint(left, right, down, true); if (bottomBorderNotWhite) { down++; aBlackPointFoundOnBorder = true; } } if (down >= height) { sizeExceeded = true; break; } // ..... // | . // ..... bool leftBorderNotWhite = true; while (leftBorderNotWhite && left >= 0) { leftBorderNotWhite = containsBlackPoint(up, down, left, false); if (leftBorderNotWhite) { left--; aBlackPointFoundOnBorder = true; } } if (left < 0) { sizeExceeded = true; break; } // .___. // . . // ..... bool topBorderNotWhite = true; while (topBorderNotWhite && up >= 0) { topBorderNotWhite = containsBlackPoint(left, right, up, true); if (topBorderNotWhite) { up--; aBlackPointFoundOnBorder = true; } } if (up < 0) { sizeExceeded = true; break; } if (aBlackPointFoundOnBorder) { atLeastOneBlackPointFoundOnBorder = true; } } if (!sizeExceeded && atLeastOneBlackPointFoundOnBorder) { int maxSize = right - left; ResultPoint z = null; for (int i = 1; i < maxSize; i++) { z = getBlackPointOnSegment(left, down - i, left + i, down); if (z != null) { break; } } if (z == null) { return null; } ResultPoint t = null; //go down right for (int i = 1; i < maxSize; i++) { t = getBlackPointOnSegment(left, up + i, left + i, up); if (t != null) { break; } } if (t == null) { return null; } ResultPoint x = null; //go down left for (int i = 1; i < maxSize; i++) { x = getBlackPointOnSegment(right, up + i, right - i, up); if (x != null) { break; } } if (x == null) { return null; } ResultPoint y = null; //go up left for (int i = 1; i < maxSize; i++) { y = getBlackPointOnSegment(right, down - i, right - i, down); if (y != null) { break; } } if (y == null) { return null; } return centerEdges(y, z, x, t); } else { return null; } } private ResultPoint getBlackPointOnSegment(float aX, float aY, float bX, float bY) { int dist = MathUtils.round(MathUtils.distance(aX, aY, bX, bY)); float xStep = (bX - aX) / dist; float yStep = (bY - aY) / dist; for (int i = 0; i < dist; i++) { int x = MathUtils.round(aX + i * xStep); int y = MathUtils.round(aY + i * yStep); if (image[x, y]) { return new ResultPoint(x, y); } } return null; } /// <summary> /// recenters the points of a constant distance towards the center /// </summary> /// <param name="y">bottom most point</param> /// <param name="z">left most point</param> /// <param name="x">right most point</param> /// <param name="t">top most point</param> /// <returns><see cref="ResultPoint"/>[] describing the corners of the rectangular /// region. The first and last points are opposed on the diagonal, as /// are the second and third. The first point will be the topmost /// point and the last, the bottommost. The second point will be /// leftmost and the third, the rightmost</returns> private ResultPoint[] centerEdges(ResultPoint y, ResultPoint z, ResultPoint x, ResultPoint t) { // // t t // z x // x OR z // y y // float yi = y.X; float yj = y.Y; float zi = z.X; float zj = z.Y; float xi = x.X; float xj = x.Y; float ti = t.X; float tj = t.Y; if (yi < width / 2.0f) { return new[] { new ResultPoint(ti - CORR, tj + CORR), new ResultPoint(zi + CORR, zj + CORR), new ResultPoint(xi - CORR, xj - CORR), new ResultPoint(yi + CORR, yj - CORR) }; } else { return new[] { new ResultPoint(ti + CORR, tj + CORR), new ResultPoint(zi + CORR, zj - CORR), new ResultPoint(xi - CORR, xj + CORR), new ResultPoint(yi - CORR, yj - CORR) }; } } /// <summary> /// Determines whether a segment contains a black point /// </summary> /// <param name="a">min value of the scanned coordinate</param> /// <param name="b">max value of the scanned coordinate</param> /// <param name="fixed">value of fixed coordinate</param> /// <param name="horizontal">set to true if scan must be horizontal, false if vertical</param> /// <returns> /// true if a black point has been found, else false. /// </returns> private bool containsBlackPoint(int a, int b, int @fixed, bool horizontal) { if (horizontal) { for (int x = a; x <= b; x++) { if (image[x, @fixed]) { return true; } } } else { for (int y = a; y <= b; y++) { if (image[@fixed, y]) { return true; } } } return false; } } }
// 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.Collections.Generic; using System.Linq; using NUnit.Framework; using osu.Framework.Extensions.ObjectExtensions; using osu.Framework.Graphics; using osu.Framework.Graphics.Sprites; using osu.Framework.Testing; using osu.Framework.Utils; using osu.Game.Graphics.UserInterface; using osu.Game.Online; using osu.Game.Online.API.Requests.Responses; using osu.Game.Online.Multiplayer; using osu.Game.Online.Rooms; using osu.Game.Rulesets.Mods; using osu.Game.Rulesets.Osu.Mods; using osu.Game.Screens.OnlinePlay.Multiplayer.Participants; using osu.Game.Users; using osuTK; namespace osu.Game.Tests.Visual.Multiplayer { public class TestSceneMultiplayerParticipantsList : MultiplayerTestScene { [SetUpSteps] public void SetupSteps() { createNewParticipantsList(); } [Test] public void TestAddUser() { AddAssert("one unique panel", () => this.ChildrenOfType<ParticipantPanel>().Select(p => p.User).Distinct().Count() == 1); AddStep("add user", () => MultiplayerClient.AddUser(new APIUser { Id = 3, Username = "Second", CoverUrl = @"https://osu.ppy.sh/images/headers/profile-covers/c3.jpg", })); AddAssert("two unique panels", () => this.ChildrenOfType<ParticipantPanel>().Select(p => p.User).Distinct().Count() == 2); } [Test] public void TestAddUnresolvedUser() { AddAssert("one unique panel", () => this.ChildrenOfType<ParticipantPanel>().Select(p => p.User).Distinct().Count() == 1); AddStep("add non-resolvable user", () => MultiplayerClient.TestAddUnresolvedUser()); AddAssert("null user added", () => MultiplayerClient.Room.AsNonNull().Users.Count(u => u.User == null) == 1); AddUntilStep("two unique panels", () => this.ChildrenOfType<ParticipantPanel>().Select(p => p.User).Distinct().Count() == 2); AddStep("kick null user", () => this.ChildrenOfType<ParticipantPanel>().Single(p => p.User.User == null) .ChildrenOfType<ParticipantPanel.KickButton>().Single().TriggerClick()); AddAssert("null user kicked", () => MultiplayerClient.Room.AsNonNull().Users.Count == 1); } [Test] public void TestRemoveUser() { APIUser secondUser = null; AddStep("add a user", () => { MultiplayerClient.AddUser(secondUser = new APIUser { Id = 3, Username = "Second", CoverUrl = @"https://osu.ppy.sh/images/headers/profile-covers/c3.jpg", }); }); AddStep("remove host", () => MultiplayerClient.RemoveUser(API.LocalUser.Value)); AddAssert("single panel is for second user", () => this.ChildrenOfType<ParticipantPanel>().Single().User.User == secondUser); } [Test] public void TestGameStateHasPriorityOverDownloadState() { AddStep("set to downloading map", () => MultiplayerClient.ChangeBeatmapAvailability(BeatmapAvailability.Downloading(0))); checkProgressBarVisibility(true); AddStep("make user ready", () => MultiplayerClient.ChangeState(MultiplayerUserState.Results)); checkProgressBarVisibility(false); AddUntilStep("ready mark visible", () => this.ChildrenOfType<StateDisplay>().Single().IsPresent); AddStep("make user ready", () => MultiplayerClient.ChangeState(MultiplayerUserState.Idle)); checkProgressBarVisibility(true); } [Test] public void TestCorrectInitialState() { AddStep("set to downloading map", () => MultiplayerClient.ChangeBeatmapAvailability(BeatmapAvailability.Downloading(0))); createNewParticipantsList(); checkProgressBarVisibility(true); } [Test] public void TestBeatmapDownloadingStates() { AddStep("set to no map", () => MultiplayerClient.ChangeBeatmapAvailability(BeatmapAvailability.NotDownloaded())); AddStep("set to downloading map", () => MultiplayerClient.ChangeBeatmapAvailability(BeatmapAvailability.Downloading(0))); checkProgressBarVisibility(true); AddRepeatStep("increment progress", () => { float progress = this.ChildrenOfType<ParticipantPanel>().Single().User.BeatmapAvailability.DownloadProgress ?? 0; MultiplayerClient.ChangeBeatmapAvailability(BeatmapAvailability.Downloading(progress + RNG.NextSingle(0.1f))); }, 25); AddAssert("progress bar increased", () => this.ChildrenOfType<ProgressBar>().Single().Current.Value > 0); AddStep("set to importing map", () => MultiplayerClient.ChangeBeatmapAvailability(BeatmapAvailability.Importing())); checkProgressBarVisibility(false); AddStep("set to available", () => MultiplayerClient.ChangeBeatmapAvailability(BeatmapAvailability.LocallyAvailable())); } [Test] public void TestToggleReadyState() { AddAssert("ready mark invisible", () => !this.ChildrenOfType<StateDisplay>().Single().IsPresent); AddStep("make user ready", () => MultiplayerClient.ChangeState(MultiplayerUserState.Ready)); AddUntilStep("ready mark visible", () => this.ChildrenOfType<StateDisplay>().Single().IsPresent); AddStep("make user idle", () => MultiplayerClient.ChangeState(MultiplayerUserState.Idle)); AddUntilStep("ready mark invisible", () => !this.ChildrenOfType<StateDisplay>().Single().IsPresent); } [Test] public void TestToggleSpectateState() { AddStep("make user spectating", () => MultiplayerClient.ChangeState(MultiplayerUserState.Spectating)); AddStep("make user idle", () => MultiplayerClient.ChangeState(MultiplayerUserState.Idle)); } [Test] public void TestCrownChangesStateWhenHostTransferred() { AddStep("add user", () => MultiplayerClient.AddUser(new APIUser { Id = 3, Username = "Second", CoverUrl = @"https://osu.ppy.sh/images/headers/profile-covers/c3.jpg", })); AddUntilStep("first user crown visible", () => this.ChildrenOfType<ParticipantPanel>().ElementAt(0).ChildrenOfType<SpriteIcon>().First().Alpha == 1); AddUntilStep("second user crown hidden", () => this.ChildrenOfType<ParticipantPanel>().ElementAt(1).ChildrenOfType<SpriteIcon>().First().Alpha == 0); AddStep("make second user host", () => MultiplayerClient.TransferHost(3)); AddUntilStep("first user crown hidden", () => this.ChildrenOfType<ParticipantPanel>().ElementAt(0).ChildrenOfType<SpriteIcon>().First().Alpha == 0); AddUntilStep("second user crown visible", () => this.ChildrenOfType<ParticipantPanel>().ElementAt(1).ChildrenOfType<SpriteIcon>().First().Alpha == 1); } [Test] public void TestKickButtonOnlyPresentWhenHost() { AddStep("add user", () => MultiplayerClient.AddUser(new APIUser { Id = 3, Username = "Second", CoverUrl = @"https://osu.ppy.sh/images/headers/profile-covers/c3.jpg", })); AddUntilStep("kick buttons visible", () => this.ChildrenOfType<ParticipantPanel.KickButton>().Count(d => d.IsPresent) == 1); AddStep("make second user host", () => MultiplayerClient.TransferHost(3)); AddUntilStep("kick buttons not visible", () => this.ChildrenOfType<ParticipantPanel.KickButton>().Count(d => d.IsPresent) == 0); AddStep("make local user host again", () => MultiplayerClient.TransferHost(API.LocalUser.Value.Id)); AddUntilStep("kick buttons visible", () => this.ChildrenOfType<ParticipantPanel.KickButton>().Count(d => d.IsPresent) == 1); } [Test] public void TestKickButtonKicks() { AddStep("add user", () => MultiplayerClient.AddUser(new APIUser { Id = 3, Username = "Second", CoverUrl = @"https://osu.ppy.sh/images/headers/profile-covers/c3.jpg", })); AddStep("kick second user", () => this.ChildrenOfType<ParticipantPanel.KickButton>().Single(d => d.IsPresent).TriggerClick()); AddAssert("second user kicked", () => MultiplayerClient.Room?.Users.Single().UserID == API.LocalUser.Value.Id); } [Test] public void TestManyUsers() { AddStep("add many users", () => { for (int i = 0; i < 20; i++) { MultiplayerClient.AddUser(new APIUser { Id = i, Username = $"User {i}", RulesetsStatistics = new Dictionary<string, UserStatistics> { { Ruleset.Value.ShortName, new UserStatistics { GlobalRank = RNG.Next(1, 100000), } } }, CoverUrl = @"https://osu.ppy.sh/images/headers/profile-covers/c3.jpg", }); MultiplayerClient.ChangeUserState(i, (MultiplayerUserState)RNG.Next(0, (int)MultiplayerUserState.Results + 1)); if (RNG.NextBool()) { var beatmapState = (DownloadState)RNG.Next(0, (int)DownloadState.LocallyAvailable + 1); switch (beatmapState) { case DownloadState.NotDownloaded: MultiplayerClient.ChangeUserBeatmapAvailability(i, BeatmapAvailability.NotDownloaded()); break; case DownloadState.Downloading: MultiplayerClient.ChangeUserBeatmapAvailability(i, BeatmapAvailability.Downloading(RNG.NextSingle())); break; case DownloadState.Importing: MultiplayerClient.ChangeUserBeatmapAvailability(i, BeatmapAvailability.Importing()); break; } } } }); } [Test] public void TestUserWithMods() { AddStep("add user", () => { MultiplayerClient.AddUser(new APIUser { Id = 0, Username = "User 0", RulesetsStatistics = new Dictionary<string, UserStatistics> { { Ruleset.Value.ShortName, new UserStatistics { GlobalRank = RNG.Next(1, 100000), } } }, CoverUrl = @"https://osu.ppy.sh/images/headers/profile-covers/c3.jpg", }); MultiplayerClient.ChangeUserMods(0, new Mod[] { new OsuModHardRock(), new OsuModDifficultyAdjust { ApproachRate = { Value = 1 } } }); }); for (var i = MultiplayerUserState.Idle; i < MultiplayerUserState.Results; i++) { var state = i; AddStep($"set state: {state}", () => MultiplayerClient.ChangeUserState(0, state)); } AddStep("set state: downloading", () => MultiplayerClient.ChangeUserBeatmapAvailability(0, BeatmapAvailability.Downloading(0))); AddStep("set state: locally available", () => MultiplayerClient.ChangeUserBeatmapAvailability(0, BeatmapAvailability.LocallyAvailable())); } [Test] public void TestModOverlap() { AddStep("add dummy mods", () => { MultiplayerClient.ChangeUserMods(new Mod[] { new OsuModNoFail(), new OsuModDoubleTime() }); }); AddStep("add user with mods", () => { MultiplayerClient.AddUser(new APIUser { Id = 0, Username = "Baka", RulesetsStatistics = new Dictionary<string, UserStatistics> { { Ruleset.Value.ShortName, new UserStatistics { GlobalRank = RNG.Next(1, 100000), } } }, CoverUrl = @"https://osu.ppy.sh/images/headers/profile-covers/c3.jpg", }); MultiplayerClient.ChangeUserMods(0, new Mod[] { new OsuModHardRock(), new OsuModDoubleTime() }); }); AddStep("set 0 ready", () => MultiplayerClient.ChangeState(MultiplayerUserState.Ready)); AddStep("set 1 spectate", () => MultiplayerClient.ChangeUserState(0, MultiplayerUserState.Spectating)); // Have to set back to idle due to status priority. AddStep("set 0 no map, 1 ready", () => { MultiplayerClient.ChangeState(MultiplayerUserState.Idle); MultiplayerClient.ChangeBeatmapAvailability(BeatmapAvailability.NotDownloaded()); MultiplayerClient.ChangeUserState(0, MultiplayerUserState.Ready); }); AddStep("set 0 downloading", () => MultiplayerClient.ChangeBeatmapAvailability(BeatmapAvailability.Downloading(0))); AddStep("set 0 spectate", () => MultiplayerClient.ChangeUserState(0, MultiplayerUserState.Spectating)); AddStep("make both default", () => { MultiplayerClient.ChangeBeatmapAvailability(BeatmapAvailability.LocallyAvailable()); MultiplayerClient.ChangeUserState(0, MultiplayerUserState.Idle); MultiplayerClient.ChangeState(MultiplayerUserState.Idle); }); } private void createNewParticipantsList() { ParticipantsList participantsList = null; AddStep("create new list", () => Child = participantsList = new ParticipantsList { Anchor = Anchor.Centre, Origin = Anchor.Centre, RelativeSizeAxes = Axes.Y, Size = new Vector2(380, 0.7f) }); AddUntilStep("wait for list to load", () => participantsList.IsLoaded); } private void checkProgressBarVisibility(bool visible) => AddUntilStep($"progress bar {(visible ? "is" : "is not")}visible", () => this.ChildrenOfType<ProgressBar>().Single().IsPresent == visible); } }
/******************************************************************************* * Copyright 2008-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"). You may not use * this file except in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************** * __ _ _ ___ * ( )( \/\/ )/ __) * /__\ \ / \__ \ * (_)(_) \/\/ (___/ * * AWS SDK for .NET */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; namespace Amazon.EC2.Model { /// <summary> /// Route description /// </summary> [XmlRootAttribute(IsNullable = false)] public class Route { private string destinationCidrBlockField; private string gatewayIdField; private string instanceIdField; private string stateField; private string instanceOwnerIdField; private string networkInterfaceIdField; /// <summary> /// The CIDR address block used for the destination match. /// For example: 0.0.0.0/0. /// </summary> [XmlElementAttribute(ElementName = "DestinationCidrBlock")] public string DestinationCidrBlock { get { return this.destinationCidrBlockField; } set { this.destinationCidrBlockField = value; } } /// <summary> /// Sets the CIDR address block used for the destination match. /// </summary> /// <param name="destinationCidrBlock">The CIDR address block used for the destination match. /// For example: 0.0.0.0/0.</param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public Route WithDestinationCidrBlock(string destinationCidrBlock) { this.destinationCidrBlockField = destinationCidrBlock; return this; } /// <summary> /// Checks if DestinationCidrBlock property is set /// </summary> /// <returns>true if DestinationCidrBlock property is set</returns> public bool IsSetDestinationCidrBlock() { return this.destinationCidrBlockField != null; } /// <summary> /// The ID of a gateway attached to your VPC. /// </summary> [XmlElementAttribute(ElementName = "GatewayId")] public string GatewayId { get { return this.gatewayIdField; } set { this.gatewayIdField = value; } } /// <summary> /// Sets the ID of a gateway attached to your VPC. /// </summary> /// <param name="gatewayId">The ID of a gateway attached to your VPC.</param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public Route WithGatewayId(string gatewayId) { this.gatewayIdField = gatewayId; return this; } /// <summary> /// Checks if GatewayId property is set /// </summary> /// <returns>true if GatewayId property is set</returns> public bool IsSetGatewayId() { return this.gatewayIdField != null; } /// <summary> /// The ID of a NAT instance in your VPC. /// </summary> [XmlElementAttribute(ElementName = "InstanceId")] public string InstanceId { get { return this.instanceIdField; } set { this.instanceIdField = value; } } /// <summary> /// Sets the ID of a NAT instance in your VPC. /// </summary> /// <param name="instanceId">The ID of a NAT instance in your VPC.</param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public Route WithInstanceId(string instanceId) { this.instanceIdField = instanceId; return this; } /// <summary> /// Checks if InstanceId property is set /// </summary> /// <returns>true if InstanceId property is set</returns> public bool IsSetInstanceId() { return this.instanceIdField != null; } /// <summary> /// The state of the route. /// The blackhole state indicates that the route's /// target isn't available (e.g., the specified gateway isn't attached to the /// VPC, the specified NAT instance has been terminated, etc.). /// </summary> [XmlElementAttribute(ElementName = "State")] public string State { get { return this.stateField; } set { this.stateField = value; } } /// <summary> /// Sets the state of the route. /// </summary> /// <param name="state">The state of the route.The blackhole state indicates that the route's /// target isn't available (e.g., the specified gateway isn't attached to the /// VPC, the specified NAT instance has been terminated, etc.).</param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public Route WithState(string state) { this.stateField = state; return this; } /// <summary> /// Checks if State property is set /// </summary> /// <returns>true if State property is set</returns> public bool IsSetState() { return this.stateField != null; } /// <summary> /// The owner of the instance. /// </summary> [XmlElementAttribute(ElementName = "InstanceOwnerId")] public string InstanceOwnerId { get { return this.instanceOwnerIdField; } set { this.instanceOwnerIdField = value; } } /// <summary> /// Sets the owner of the instance. /// </summary> /// <param name="instanceOwnerId">The owner of the instance.</param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public Route WithInstanceOwnerId(string instanceOwnerId) { this.instanceOwnerIdField = instanceOwnerId; return this; } /// <summary> /// Checks if the InstanceOwnerId property is set /// </summary> /// <returns>true if the InstanceOwnerId property is set</returns> public bool IsSetInstanceOwnerId() { return !string.IsNullOrEmpty(this.instanceOwnerIdField); } /// <summary> /// The network interface ID. /// </summary> [XmlElementAttribute(ElementName = "NetworkInterfaceId")] public string NetworkInterfaceId { get { return this.networkInterfaceIdField; } set { this.networkInterfaceIdField = value; } } /// <summary> /// Sets the network interface ID. /// </summary> /// <param name="networkInterfaceId">Network interface ID</param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public Route WithNetworkInterfaceId(string networkInterfaceId) { this.networkInterfaceIdField = networkInterfaceId; return this; } /// <summary> /// Checks if the NetworkInterfaceId property is set /// </summary> /// <returns>true if the NetworkInterfaceId property is set</returns> public bool IsSetNetworkInterfaceId() { return !string.IsNullOrEmpty(this.networkInterfaceIdField); } } }
// 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.Globalization; using System.Linq; using Cake.Core; using Cake.Core.IO; using Cake.Core.Tooling; namespace Cake.Common.Tools.WiX.Heat { /// <summary> /// The WiX Heat runner. /// </summary> public sealed class HeatRunner : Tool<HeatSettings> { private readonly ICakeEnvironment _environment; /// <summary> /// Initializes a new instance of the <see cref="HeatRunner" /> class. /// </summary> /// <param name="fileSystem">The file system.</param> /// <param name="environment">The environment.</param> /// <param name="processRunner">The process runner.</param> /// <param name="toolService">The tool service.</param> public HeatRunner(IFileSystem fileSystem, ICakeEnvironment environment, IProcessRunner processRunner, IToolLocator toolService) : base(fileSystem, environment, processRunner, toolService) { if (environment == null) { throw new ArgumentNullException(nameof(environment)); } _environment = environment; } /// <summary> /// Runs the Wix Heat runner for the specified directory path. /// </summary> /// <param name="directoryPath">The directory path.</param> /// <param name="outputFile">The output file.</param> /// <param name="harvestType">The WiX harvest type.</param> /// <param name="settings">The settings.</param> public void Run(DirectoryPath directoryPath, FilePath outputFile, WiXHarvestType harvestType, HeatSettings settings) { if (directoryPath == null) { throw new ArgumentNullException(nameof(directoryPath)); } if (outputFile == null) { throw new ArgumentNullException(nameof(outputFile)); } if (settings == null) { throw new ArgumentNullException(nameof(settings)); } Run(settings, GetArguments(directoryPath, outputFile, harvestType, settings)); } /// <summary> /// Runs the Wix Heat runner for the specified directory path. /// </summary> /// <param name="objectFiles">The object files.</param> /// <param name="outputFile">The output file.</param> /// <param name="harvestType">The WiX harvest type.</param> /// <param name="settings">The settings.</param> public void Run(IEnumerable<FilePath> objectFiles, FilePath outputFile, WiXHarvestType harvestType, HeatSettings settings) { if (objectFiles == null) { throw new ArgumentNullException(nameof(objectFiles)); } if (outputFile == null) { throw new ArgumentNullException(nameof(outputFile)); } if (settings == null) { throw new ArgumentNullException(nameof(settings)); } var objectFilesArray = objectFiles as FilePath[] ?? objectFiles.ToArray(); if (!objectFilesArray.Any()) { throw new ArgumentException("No object files provided.", nameof(objectFiles)); } Run(settings, GetArguments(objectFilesArray, outputFile, harvestType, settings)); } /// <summary> /// Runs the Wix Heat runner for the specified directory path. /// </summary> /// <param name="harvestTarget">The harvest target.</param> /// <param name="outputFile">The output file.</param> /// <param name="harvestType">The WiX harvest type.</param> /// <param name="settings">The settings.</param> public void Run(string harvestTarget, FilePath outputFile, WiXHarvestType harvestType, HeatSettings settings) { if (harvestTarget == null) { throw new ArgumentNullException(nameof(harvestTarget)); } if (outputFile == null) { throw new ArgumentNullException(nameof(outputFile)); } if (settings == null) { throw new ArgumentNullException(nameof(settings)); } Run(settings, GetArguments(harvestTarget, outputFile, harvestType, settings)); } private ProcessArgumentBuilder GetArguments(IEnumerable<FilePath> objectFiles, FilePath outputFile, WiXHarvestType harvestType, HeatSettings settings) { var builder = new ProcessArgumentBuilder(); builder.Append(GetHarvestType(harvestType)); // Object files foreach (var objectFile in objectFiles.Select(file => file.MakeAbsolute(_environment).FullPath)) { builder.AppendQuoted(objectFile); } var args = GetArguments(outputFile, settings); args.CopyTo(builder); return builder; } private ProcessArgumentBuilder GetArguments(DirectoryPath directoryPath, FilePath outputFile, WiXHarvestType harvestType, HeatSettings settings) { var builder = new ProcessArgumentBuilder(); builder.Append(GetHarvestType(harvestType)); builder.AppendQuoted(directoryPath.MakeAbsolute(_environment).FullPath); var args = GetArguments(outputFile, settings); args.CopyTo(builder); return builder; } private ProcessArgumentBuilder GetArguments(string harvestTarget, FilePath outputFile, WiXHarvestType harvestType, HeatSettings settings) { var builder = new ProcessArgumentBuilder(); builder.Append(GetHarvestType(harvestType)); builder.AppendQuoted(harvestTarget); var args = GetArguments(outputFile, settings); args.CopyTo(builder); return builder; } private ProcessArgumentBuilder GetArguments(FilePath outputFile, HeatSettings settings) { var builder = new ProcessArgumentBuilder(); // Add extensions if (settings.Extensions != null && settings.Extensions.Any()) { var extensions = settings.Extensions.Select(extension => string.Format(CultureInfo.InvariantCulture, "-ext {0}", extension)); foreach (var extension in extensions) { builder.Append(extension); } } // No logo if (settings.NoLogo) { builder.Append("-nologo"); } // Suppress specific warnings if (settings.SuppressSpecificWarnings != null && settings.SuppressSpecificWarnings.Any()) { var warnings = settings.SuppressSpecificWarnings.Select(warning => string.Format(CultureInfo.InvariantCulture, "-sw{0}", warning)); foreach (var warning in warnings) { builder.Append(warning); } } // Treat specific warnings as errors if (settings.TreatSpecificWarningsAsErrors != null && settings.TreatSpecificWarningsAsErrors.Any()) { var errors = settings.TreatSpecificWarningsAsErrors.Select(error => string.Format(CultureInfo.InvariantCulture, "-wx{0}", error)); foreach (var error in errors) { builder.Append(error); } } // Auto generate guids if (settings.AutogeneratedGuid) { builder.Append("-ag"); } // Component group name if (settings.ComponentGroupName != null) { builder.Append("-cg"); builder.Append(settings.ComponentGroupName); } if (!string.IsNullOrEmpty(settings.Configuration)) { builder.Append("-configuration"); builder.Append(settings.Configuration); } // Directory reference id if (!string.IsNullOrEmpty(settings.DirectoryId)) { builder.Append("-directoryid"); builder.Append(settings.DirectoryId); } if (!string.IsNullOrWhiteSpace(settings.DirectoryReferenceId)) { builder.Append("-dr"); builder.Append(settings.DirectoryReferenceId); } // Default is components if (settings.Generate != WiXGenerateType.Components) { builder.Append("-generate"); builder.Append(settings.Generate.ToString().ToLower()); } if (settings.GenerateGuid) { builder.Append("-gg"); } if (settings.GenerateGuidWithoutBraces) { builder.Append("-g1"); } if (settings.KeepEmptyDirectories) { builder.Append("-ke"); } if (!string.IsNullOrEmpty(settings.Platform)) { builder.Append("-platform"); builder.Append(settings.Platform); } if (settings.OutputGroup != null) { builder.Append("-pog:"); switch (settings.OutputGroup) { case WiXOutputGroupType.Binaries: builder.Append("binaries"); break; case WiXOutputGroupType.Symbols: builder.Append("symbols"); break; case WiXOutputGroupType.Documents: builder.Append("documents"); break; case WiXOutputGroupType.Satallites: builder.Append("satallites"); break; case WiXOutputGroupType.Sources: builder.Append("sources"); break; case WiXOutputGroupType.Content: builder.Append("content"); break; } } if (!string.IsNullOrEmpty(settings.ProjectName)) { builder.Append("-projectname"); builder.Append(settings.ProjectName); } // Suppress Com if (settings.SuppressCom) { builder.Append("-scom"); } // Suppress fragments if (settings.SuppressFragments) { builder.Append("-sfrag"); } // Suppress unique identifiers if (settings.SuppressUniqueIds) { builder.Append("-suid"); } // Suppress root directory if (settings.SuppressRootDirectory) { builder.Append("-srd"); } // Suppress root directory if (settings.SuppressRegistry) { builder.Append("-sreg"); } if (settings.SuppressVb6Com) { builder.Append("-svb6"); } if (settings.Template != null) { builder.Append("-template"); switch (settings.Template) { case WiXTemplateType.Fragment: builder.Append("fragment"); break; case WiXTemplateType.Module: builder.Append("module"); break; case WiXTemplateType.Product: builder.Append("product"); break; } } if (settings.Transform != null) { builder.Append("-t"); builder.AppendQuoted(settings.Transform); } if (settings.Indent != null) { builder.Append("-indent"); builder.Append(settings.Indent.ToString()); } // Verbose if (settings.Verbose) { builder.Append("-v"); } // Preprocessor variable if (!string.IsNullOrEmpty(settings.PreprocessorVariable)) { builder.Append("-var"); builder.Append(settings.PreprocessorVariable); } // Generate binder variables if (settings.GenerateBinderVariables) { builder.Append("-wixvar"); } // Output file builder.Append("-out"); builder.AppendQuoted(outputFile.MakeAbsolute(_environment).FullPath); return builder; } private string GetHarvestType(WiXHarvestType harvestType) { switch (harvestType) { case WiXHarvestType.Dir: return "dir"; case WiXHarvestType.File: return "file"; case WiXHarvestType.Project: return "project"; case WiXHarvestType.Reg: return "reg"; case WiXHarvestType.Perf: return "perf"; case WiXHarvestType.Website: return "website"; default: return "dir"; } } /// <summary> /// Gets the name of the tool. /// </summary> /// <returns> The name of the tool. </returns> protected override string GetToolName() { return "Heat"; } /// <summary> /// Gets the possible names of the tool executable. /// </summary> /// <returns> The tool executable name. </returns> protected override IEnumerable<string> GetToolExecutableNames() { return new[] { "heat.exe" }; } } }
// // MonoSymbolFile.cs // // Authors: // Martin Baulig (martin@ximian.com) // Marek Safar (marek.safar@gmail.com) // // (C) 2003 Ximian, Inc. http://www.ximian.com // Copyright (C) 2012 Xamarin Inc (http://www.xamarin.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 System.Reflection; using System.Collections.Generic; using System.IO; namespace Mono.CompilerServices.SymbolWriter { public class MonoSymbolFileException : Exception { public MonoSymbolFileException () : base () { } public MonoSymbolFileException (string message, params object[] args) : base (String.Format (message, args)) { } public MonoSymbolFileException (string message, Exception innerException) : base (message, innerException) { } } sealed class MyBinaryWriter : System.IO.BinaryWriter { public MyBinaryWriter (Stream stream) : base (stream) { } public void WriteLeb128 (int value) { base.Write7BitEncodedInt (value); } } internal class MyBinaryReader : BinaryReader { public MyBinaryReader (Stream stream) : base (stream) { } public int ReadLeb128 () { return base.Read7BitEncodedInt (); } public string ReadString (int offset) { long old_pos = BaseStream.Position; BaseStream.Position = offset; string text = ReadString (); BaseStream.Position = old_pos; return text; } } public interface ISourceFile { SourceFileEntry Entry { get; } } public interface ICompileUnit { CompileUnitEntry Entry { get; } } public interface IMethodDef { string Name { get; } int Token { get; } } public class MonoSymbolFile : IDisposable { List<MethodEntry> methods = new List<MethodEntry> (); List<SourceFileEntry> sources = new List<SourceFileEntry> (); List<CompileUnitEntry> comp_units = new List<CompileUnitEntry> (); Dictionary<int, AnonymousScopeEntry> anonymous_scopes; OffsetTable ot; int last_type_index; int last_method_index; int last_namespace_index; public readonly int MajorVersion = OffsetTable.MajorVersion; public readonly int MinorVersion = OffsetTable.MinorVersion; public int NumLineNumbers; public MonoSymbolFile () { ot = new OffsetTable (); } public int AddSource (SourceFileEntry source) { sources.Add (source); return sources.Count; } public int AddCompileUnit (CompileUnitEntry entry) { comp_units.Add (entry); return comp_units.Count; } public void AddMethod (MethodEntry entry) { methods.Add (entry); } public MethodEntry DefineMethod (CompileUnitEntry comp_unit, int token, ScopeVariable[] scope_vars, LocalVariableEntry[] locals, LineNumberEntry[] lines, CodeBlockEntry[] code_blocks, string real_name, MethodEntry.Flags flags, int namespace_id) { if (reader != null) throw new InvalidOperationException (); MethodEntry method = new MethodEntry ( this, comp_unit, token, scope_vars, locals, lines, code_blocks, real_name, flags, namespace_id); AddMethod (method); return method; } internal void DefineAnonymousScope (int id) { if (reader != null) throw new InvalidOperationException (); if (anonymous_scopes == null) anonymous_scopes = new Dictionary<int, AnonymousScopeEntry> (); anonymous_scopes.Add (id, new AnonymousScopeEntry (id)); } internal void DefineCapturedVariable (int scope_id, string name, string captured_name, CapturedVariable.CapturedKind kind) { if (reader != null) throw new InvalidOperationException (); AnonymousScopeEntry scope = anonymous_scopes [scope_id]; scope.AddCapturedVariable (name, captured_name, kind); } internal void DefineCapturedScope (int scope_id, int id, string captured_name) { if (reader != null) throw new InvalidOperationException (); AnonymousScopeEntry scope = anonymous_scopes [scope_id]; scope.AddCapturedScope (id, captured_name); } internal int GetNextTypeIndex () { return ++last_type_index; } internal int GetNextMethodIndex () { return ++last_method_index; } internal int GetNextNamespaceIndex () { return ++last_namespace_index; } void Write (MyBinaryWriter bw, Guid guid) { // Magic number and file version. bw.Write (OffsetTable.Magic); bw.Write (MajorVersion); bw.Write (MinorVersion); bw.Write (guid.ToByteArray ()); // // Offsets of file sections; we must write this after we're done // writing the whole file, so we just reserve the space for it here. // long offset_table_offset = bw.BaseStream.Position; ot.Write (bw, MajorVersion, MinorVersion); // // Sort the methods according to their tokens and update their index. // methods.Sort (); for (int i = 0; i < methods.Count; i++) methods [i].Index = i + 1; // // Write data sections. // ot.DataSectionOffset = (int) bw.BaseStream.Position; foreach (SourceFileEntry source in sources) source.WriteData (bw); foreach (CompileUnitEntry comp_unit in comp_units) comp_unit.WriteData (bw); foreach (MethodEntry method in methods) method.WriteData (this, bw); ot.DataSectionSize = (int) bw.BaseStream.Position - ot.DataSectionOffset; // // Write the method index table. // ot.MethodTableOffset = (int) bw.BaseStream.Position; for (int i = 0; i < methods.Count; i++) { MethodEntry entry = methods [i]; entry.Write (bw); } ot.MethodTableSize = (int) bw.BaseStream.Position - ot.MethodTableOffset; // // Write source table. // ot.SourceTableOffset = (int) bw.BaseStream.Position; for (int i = 0; i < sources.Count; i++) { SourceFileEntry source = sources [i]; source.Write (bw); } ot.SourceTableSize = (int) bw.BaseStream.Position - ot.SourceTableOffset; // // Write compilation unit table. // ot.CompileUnitTableOffset = (int) bw.BaseStream.Position; for (int i = 0; i < comp_units.Count; i++) { CompileUnitEntry unit = comp_units [i]; unit.Write (bw); } ot.CompileUnitTableSize = (int) bw.BaseStream.Position - ot.CompileUnitTableOffset; // // Write anonymous scope table. // ot.AnonymousScopeCount = anonymous_scopes != null ? anonymous_scopes.Count : 0; ot.AnonymousScopeTableOffset = (int) bw.BaseStream.Position; if (anonymous_scopes != null) { foreach (AnonymousScopeEntry scope in anonymous_scopes.Values) scope.Write (bw); } ot.AnonymousScopeTableSize = (int) bw.BaseStream.Position - ot.AnonymousScopeTableOffset; // // Fixup offset table. // ot.TypeCount = last_type_index; ot.MethodCount = methods.Count; ot.SourceCount = sources.Count; ot.CompileUnitCount = comp_units.Count; // // Write offset table. // ot.TotalFileSize = (int) bw.BaseStream.Position; bw.Seek ((int) offset_table_offset, SeekOrigin.Begin); ot.Write (bw, MajorVersion, MinorVersion); bw.Seek (0, SeekOrigin.End); #if false Console.WriteLine ("TOTAL: {0} line numbes, {1} bytes, extended {2} bytes, " + "{3} methods.", NumLineNumbers, LineNumberSize, ExtendedLineNumberSize, methods.Count); #endif } public void CreateSymbolFile (Guid guid, Stream fs) { if (reader != null) throw new InvalidOperationException (); Write (new MyBinaryWriter (fs), guid); } MyBinaryReader reader; Dictionary<int, SourceFileEntry> source_file_hash; Dictionary<int, CompileUnitEntry> compile_unit_hash; List<MethodEntry> method_list; Dictionary<int, MethodEntry> method_token_hash; Dictionary<string, int> source_name_hash; Guid guid; MonoSymbolFile (Stream stream) { reader = new MyBinaryReader (stream); try { long magic = reader.ReadInt64 (); int major_version = reader.ReadInt32 (); int minor_version = reader.ReadInt32 (); if (magic != OffsetTable.Magic) throw new MonoSymbolFileException ("Symbol file is not a valid"); if (major_version != OffsetTable.MajorVersion) throw new MonoSymbolFileException ( "Symbol file has version {0} but expected {1}", major_version, OffsetTable.MajorVersion); if (minor_version != OffsetTable.MinorVersion) throw new MonoSymbolFileException ("Symbol file has version {0}.{1} but expected {2}.{3}", major_version, minor_version, OffsetTable.MajorVersion, OffsetTable.MinorVersion); MajorVersion = major_version; MinorVersion = minor_version; guid = new Guid (reader.ReadBytes (16)); ot = new OffsetTable (reader, major_version, minor_version); } catch (Exception e) { throw new MonoSymbolFileException ("Cannot read symbol file", e); } source_file_hash = new Dictionary<int, SourceFileEntry> (); compile_unit_hash = new Dictionary<int, CompileUnitEntry> (); } public static MonoSymbolFile ReadSymbolFile (string mdbFilename) { return ReadSymbolFile (PclFileAccess.OpenFileStream (mdbFilename)); } public static MonoSymbolFile ReadSymbolFile (string mdbFilename, Guid assemblyGuid) { var sf = ReadSymbolFile (mdbFilename); if (assemblyGuid != sf.guid) throw new MonoSymbolFileException ("Symbol file `{0}' does not match assembly", mdbFilename); return sf; } public static MonoSymbolFile ReadSymbolFile (Stream stream) { return new MonoSymbolFile (stream); } public int CompileUnitCount { get { return ot.CompileUnitCount; } } public int SourceCount { get { return ot.SourceCount; } } public int MethodCount { get { return ot.MethodCount; } } public int TypeCount { get { return ot.TypeCount; } } public int AnonymousScopeCount { get { return ot.AnonymousScopeCount; } } public int NamespaceCount { get { return last_namespace_index; } } public Guid Guid { get { return guid; } } public OffsetTable OffsetTable { get { return ot; } } internal int LineNumberCount = 0; internal int LocalCount = 0; internal int StringSize = 0; internal int LineNumberSize = 0; internal int ExtendedLineNumberSize = 0; public SourceFileEntry GetSourceFile (int index) { if ((index < 1) || (index > ot.SourceCount)) throw new ArgumentException (); if (reader == null) throw new InvalidOperationException (); lock (this) { SourceFileEntry source; if (source_file_hash.TryGetValue (index, out source)) return source; long old_pos = reader.BaseStream.Position; reader.BaseStream.Position = ot.SourceTableOffset + SourceFileEntry.Size * (index - 1); source = new SourceFileEntry (this, reader); source_file_hash.Add (index, source); reader.BaseStream.Position = old_pos; return source; } } public SourceFileEntry[] Sources { get { if (reader == null) throw new InvalidOperationException (); SourceFileEntry[] retval = new SourceFileEntry [SourceCount]; for (int i = 0; i < SourceCount; i++) retval [i] = GetSourceFile (i + 1); return retval; } } public CompileUnitEntry GetCompileUnit (int index) { if ((index < 1) || (index > ot.CompileUnitCount)) throw new ArgumentException (); if (reader == null) throw new InvalidOperationException (); lock (this) { CompileUnitEntry unit; if (compile_unit_hash.TryGetValue (index, out unit)) return unit; long old_pos = reader.BaseStream.Position; reader.BaseStream.Position = ot.CompileUnitTableOffset + CompileUnitEntry.Size * (index - 1); unit = new CompileUnitEntry (this, reader); compile_unit_hash.Add (index, unit); reader.BaseStream.Position = old_pos; return unit; } } public CompileUnitEntry[] CompileUnits { get { if (reader == null) throw new InvalidOperationException (); CompileUnitEntry[] retval = new CompileUnitEntry [CompileUnitCount]; for (int i = 0; i < CompileUnitCount; i++) retval [i] = GetCompileUnit (i + 1); return retval; } } void read_methods () { lock (this) { if (method_token_hash != null) return; method_token_hash = new Dictionary<int, MethodEntry> (); method_list = new List<MethodEntry> (); long old_pos = reader.BaseStream.Position; reader.BaseStream.Position = ot.MethodTableOffset; for (int i = 0; i < MethodCount; i++) { MethodEntry entry = new MethodEntry (this, reader, i + 1); method_token_hash.Add (entry.Token, entry); method_list.Add (entry); } reader.BaseStream.Position = old_pos; } } public MethodEntry GetMethodByToken (int token) { if (reader == null) throw new InvalidOperationException (); lock (this) { read_methods (); MethodEntry me; method_token_hash.TryGetValue (token, out me); return me; } } public MethodEntry GetMethod (int index) { if ((index < 1) || (index > ot.MethodCount)) throw new ArgumentException (); if (reader == null) throw new InvalidOperationException (); lock (this) { read_methods (); return method_list [index - 1]; } } public MethodEntry[] Methods { get { if (reader == null) throw new InvalidOperationException (); lock (this) { read_methods (); MethodEntry[] retval = new MethodEntry [MethodCount]; method_list.CopyTo (retval, 0); return retval; } } } public int FindSource (string file_name) { if (reader == null) throw new InvalidOperationException (); lock (this) { if (source_name_hash == null) { source_name_hash = new Dictionary<string, int> (); for (int i = 0; i < ot.SourceCount; i++) { SourceFileEntry source = GetSourceFile (i + 1); source_name_hash.Add (source.FileName, i); } } int value; if (!source_name_hash.TryGetValue (file_name, out value)) return -1; return value; } } public AnonymousScopeEntry GetAnonymousScope (int id) { if (reader == null) throw new InvalidOperationException (); AnonymousScopeEntry scope; lock (this) { if (anonymous_scopes != null) { anonymous_scopes.TryGetValue (id, out scope); return scope; } anonymous_scopes = new Dictionary<int, AnonymousScopeEntry> (); reader.BaseStream.Position = ot.AnonymousScopeTableOffset; for (int i = 0; i < ot.AnonymousScopeCount; i++) { scope = new AnonymousScopeEntry (reader); anonymous_scopes.Add (scope.ID, scope); } return anonymous_scopes [id]; } } internal MyBinaryReader BinaryReader { get { if (reader == null) throw new InvalidOperationException (); return reader; } } public void Dispose () { Dispose (true); } protected virtual void Dispose (bool disposing) { if (disposing) { if (reader != null) { reader.Dispose (); reader = null; } } } } }
// Copyright (c) .NET Core Community. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Data; using System.Threading; using System.Threading.Tasks; using DotNetCore.CAP.Internal; using DotNetCore.CAP.Messages; using DotNetCore.CAP.Monitoring; using DotNetCore.CAP.Persistence; using DotNetCore.CAP.Serialization; using Microsoft.EntityFrameworkCore.Storage; using Microsoft.Extensions.Options; using Npgsql; namespace DotNetCore.CAP.PostgreSql { public class PostgreSqlDataStorage : IDataStorage { private readonly IOptions<CapOptions> _capOptions; private readonly IStorageInitializer _initializer; private readonly IOptions<PostgreSqlOptions> _options; private readonly ISerializer _serializer; private readonly string _pubName; private readonly string _recName; public PostgreSqlDataStorage( IOptions<PostgreSqlOptions> options, IOptions<CapOptions> capOptions, IStorageInitializer initializer, ISerializer serializer) { _capOptions = capOptions; _initializer = initializer; _options = options; _serializer = serializer; _pubName = initializer.GetPublishedTableName(); _recName = initializer.GetReceivedTableName(); } public async Task ChangePublishStateAsync(MediumMessage message, StatusName state) => await ChangeMessageStateAsync(_pubName, message, state); public async Task ChangeReceiveStateAsync(MediumMessage message, StatusName state) => await ChangeMessageStateAsync(_recName, message, state); public MediumMessage StoreMessage(string name, Message content, object? dbTransaction = null) { var sql = $"INSERT INTO {_pubName} (\"Id\",\"Version\",\"Name\",\"Content\",\"Retries\",\"Added\",\"ExpiresAt\",\"StatusName\")" + $"VALUES(@Id,'{_options.Value.Version}',@Name,@Content,@Retries,@Added,@ExpiresAt,@StatusName);"; var message = new MediumMessage { DbId = content.GetId(), Origin = content, Content = _serializer.Serialize(content), Added = DateTime.Now, ExpiresAt = null, Retries = 0 }; object[] sqlParams = { new NpgsqlParameter("@Id", long.Parse(message.DbId)), new NpgsqlParameter("@Name", name), new NpgsqlParameter("@Content", message.Content), new NpgsqlParameter("@Retries", message.Retries), new NpgsqlParameter("@Added", message.Added), new NpgsqlParameter("@ExpiresAt", message.ExpiresAt.HasValue ? message.ExpiresAt.Value : DBNull.Value), new NpgsqlParameter("@StatusName", nameof(StatusName.Scheduled)) }; if (dbTransaction == null) { using var connection = new NpgsqlConnection(_options.Value.ConnectionString); connection.ExecuteNonQuery(sql, sqlParams: sqlParams); } else { var dbTrans = dbTransaction as IDbTransaction; if (dbTrans == null && dbTransaction is IDbContextTransaction dbContextTrans) dbTrans = dbContextTrans.GetDbTransaction(); var conn = dbTrans?.Connection!; conn.ExecuteNonQuery(sql, dbTrans, sqlParams); } return message; } public void StoreReceivedExceptionMessage(string name, string group, string content) { object[] sqlParams = { new NpgsqlParameter("@Id", SnowflakeId.Default().NextId()), new NpgsqlParameter("@Name", name), new NpgsqlParameter("@Group", group), new NpgsqlParameter("@Content", content), new NpgsqlParameter("@Retries", _capOptions.Value.FailedRetryCount), new NpgsqlParameter("@Added", DateTime.Now), new NpgsqlParameter("@ExpiresAt", DateTime.Now.AddDays(15)), new NpgsqlParameter("@StatusName", nameof(StatusName.Failed)) }; StoreReceivedMessage(sqlParams); } public MediumMessage StoreReceivedMessage(string name, string group, Message message) { var mdMessage = new MediumMessage { DbId = SnowflakeId.Default().NextId().ToString(), Origin = message, Added = DateTime.Now, ExpiresAt = null, Retries = 0 }; object[] sqlParams = { new NpgsqlParameter("@Id", long.Parse(mdMessage.DbId)), new NpgsqlParameter("@Name", name), new NpgsqlParameter("@Group", group), new NpgsqlParameter("@Content", _serializer.Serialize(mdMessage.Origin)), new NpgsqlParameter("@Retries", mdMessage.Retries), new NpgsqlParameter("@Added", mdMessage.Added), new NpgsqlParameter("@ExpiresAt", mdMessage.ExpiresAt.HasValue ? mdMessage.ExpiresAt.Value : DBNull.Value), new NpgsqlParameter("@StatusName", nameof(StatusName.Scheduled)) }; StoreReceivedMessage(sqlParams); return mdMessage; } public async Task<int> DeleteExpiresAsync(string table, DateTime timeout, int batchCount = 1000, CancellationToken token = default) { await using var connection = new NpgsqlConnection(_options.Value.ConnectionString); return connection.ExecuteNonQuery( $"DELETE FROM {table} WHERE \"Id\" IN (SELECT \"Id\" FROM {table} WHERE \"ExpiresAt\" < @timeout LIMIT @batchCount);", null, new NpgsqlParameter("@timeout", timeout), new NpgsqlParameter("@batchCount", batchCount)); } public async Task<IEnumerable<MediumMessage>> GetPublishedMessagesOfNeedRetry() => await GetMessagesOfNeedRetryAsync(_pubName); public async Task<IEnumerable<MediumMessage>> GetReceivedMessagesOfNeedRetry() => await GetMessagesOfNeedRetryAsync(_recName); public IMonitoringApi GetMonitoringApi() { return new PostgreSqlMonitoringApi(_options, _initializer); } private async Task ChangeMessageStateAsync(string tableName, MediumMessage message, StatusName state) { var sql = $"UPDATE {tableName} SET \"Content\"=@Content,\"Retries\"=@Retries,\"ExpiresAt\"=@ExpiresAt,\"StatusName\"=@StatusName WHERE \"Id\"=@Id"; object[] sqlParams = { new NpgsqlParameter("@Id", long.Parse(message.DbId)), new NpgsqlParameter("@Content", _serializer.Serialize(message.Origin)), new NpgsqlParameter("@Retries", message.Retries), new NpgsqlParameter("@ExpiresAt", message.ExpiresAt), new NpgsqlParameter("@StatusName", state.ToString("G")) }; await using var connection = new NpgsqlConnection(_options.Value.ConnectionString); connection.ExecuteNonQuery(sql, sqlParams: sqlParams); } private void StoreReceivedMessage(object[] sqlParams) { var sql = $"INSERT INTO {_recName}(\"Id\",\"Version\",\"Name\",\"Group\",\"Content\",\"Retries\",\"Added\",\"ExpiresAt\",\"StatusName\")" + $"VALUES(@Id,'{_capOptions.Value.Version}',@Name,@Group,@Content,@Retries,@Added,@ExpiresAt,@StatusName) RETURNING \"Id\";"; using var connection = new NpgsqlConnection(_options.Value.ConnectionString); connection.ExecuteNonQuery(sql, sqlParams: sqlParams); } private async Task<IEnumerable<MediumMessage>> GetMessagesOfNeedRetryAsync(string tableName) { var fourMinAgo = DateTime.Now.AddMinutes(-4).ToString("O"); var sql = $"SELECT \"Id\",\"Content\",\"Retries\",\"Added\" FROM {tableName} WHERE \"Retries\"<{_capOptions.Value.FailedRetryCount} " + $"AND \"Version\"='{_capOptions.Value.Version}' AND \"Added\"<'{fourMinAgo}' AND (\"StatusName\"='{StatusName.Failed}' OR \"StatusName\"='{StatusName.Scheduled}') LIMIT 200;"; await using var connection = new NpgsqlConnection(_options.Value.ConnectionString); var result = connection.ExecuteReader(sql, reader => { var messages = new List<MediumMessage>(); while (reader.Read()) { messages.Add(new MediumMessage { DbId = reader.GetInt64(0).ToString(), Origin = _serializer.Deserialize(reader.GetString(1))!, Retries = reader.GetInt32(2), Added = reader.GetDateTime(3) }); } return messages; }); return result; } } }
// Copyright (C) 2014 Stephan Bouchard - All Rights Reserved // This code can only be used under the standard Unity Asset Store End User License Agreement // A Copy of the EULA APPENDIX 1 is available at http://unity3d.com/company/legal/as_terms using UnityEngine; using UnityEditor; using System.Collections; namespace TMPro.EditorUtilities { [CustomEditor(typeof(TextMeshProFont))] public class TMPro_FontEditor : Editor { private struct UI_PanelState { public static bool fontInfoPanel = true; public static bool glyphInfoPanel = false; public static bool kerningInfoPanel = true; } private const string k_UndoRedo = "UndoRedoPerformed"; private GUISkin mySkin; private GUIStyle SquareAreaBox85G; private GUIStyle GroupLabel; private GUIStyle SectionLabel; private SerializedProperty font_atlas_prop; private SerializedProperty font_material_prop; private SerializedProperty font_normalStyle_prop; private SerializedProperty font_boldStyle_prop; private SerializedProperty font_italicStyle_prop; private SerializedProperty m_fontInfo_prop; private SerializedProperty m_glyphInfoList_prop; private SerializedProperty m_kerningInfo_prop; private KerningTable m_kerningTable; private SerializedProperty m_kerningPair_prop; private TextMeshProFont m_fontAsset; private bool isAssetDirty = false; private int errorCode; private System.DateTime timeStamp; private string[] uiStateLabel = new string[] { "<i>(Click to expand)</i>", "<i>(Click to collapse)</i>" }; public void OnEnable() { font_atlas_prop = serializedObject.FindProperty("atlas"); font_material_prop = serializedObject.FindProperty("material"); font_normalStyle_prop = serializedObject.FindProperty("NormalStyle"); font_boldStyle_prop = serializedObject.FindProperty("BoldStyle"); font_italicStyle_prop = serializedObject.FindProperty("ItalicStyle"); m_fontInfo_prop = serializedObject.FindProperty("m_fontInfo"); m_glyphInfoList_prop = serializedObject.FindProperty("m_glyphInfoList"); m_kerningInfo_prop = serializedObject.FindProperty("m_kerningInfo"); m_kerningPair_prop = serializedObject.FindProperty("m_kerningPair"); //m_isGlyphInfoListExpanded_prop = serializedObject.FindProperty("isGlyphInfoListExpanded"); //m_isKerningTableExpanded_prop = serializedObject.FindProperty("isKerningTableExpanded"); m_fontAsset = target as TextMeshProFont; m_kerningTable = m_fontAsset.kerningInfo; // Find to location of the TextMesh Pro Asset Folder (as users may have moved it) string tmproAssetFolderPath = TMPro_EditorUtility.GetAssetLocation(); // GUI Skin if (EditorGUIUtility.isProSkin) mySkin = AssetDatabase.LoadAssetAtPath(tmproAssetFolderPath + "/GUISkins/TMPro_DarkSkin.guiskin", typeof(GUISkin)) as GUISkin; else mySkin = AssetDatabase.LoadAssetAtPath(tmproAssetFolderPath + "/GUISkins/TMPro_LightSkin.guiskin", typeof(GUISkin)) as GUISkin; if (mySkin != null) { SectionLabel = mySkin.FindStyle("Section Label"); GroupLabel = mySkin.FindStyle("Group Label"); SquareAreaBox85G = mySkin.FindStyle("Square Area Box (85 Grey)"); } } public override void OnInspectorGUI() { //Debug.Log("OnInspectorGUI Called."); serializedObject.Update(); GUILayout.Label("<b>TextMesh Pro! Font Asset</b>", SectionLabel); // TextMeshPro Font Info Panel GUILayout.Label("Face Info", SectionLabel); EditorGUI.indentLevel = 1; GUI.enabled = false; // Lock UI EditorGUIUtility.labelWidth = 135; //EditorGUIUtility.fieldWidth = 80; EditorGUILayout.PropertyField(m_fontInfo_prop.FindPropertyRelative("Name"), new GUIContent("Font Source")); EditorGUILayout.PropertyField(m_fontInfo_prop.FindPropertyRelative("PointSize")); GUI.enabled = true; EditorGUILayout.PropertyField(m_fontInfo_prop.FindPropertyRelative("LineHeight")); GUI.enabled = false; EditorGUILayout.PropertyField(m_fontInfo_prop.FindPropertyRelative("Baseline")); EditorGUILayout.PropertyField(m_fontInfo_prop.FindPropertyRelative("Ascender")); EditorGUILayout.PropertyField(m_fontInfo_prop.FindPropertyRelative("Descender")); GUI.enabled = true; EditorGUILayout.PropertyField(m_fontInfo_prop.FindPropertyRelative("Underline")); //EditorGUILayout.PropertyField(m_fontInfo_prop.FindPropertyRelative("UnderlineThickness")); GUI.enabled = false; //EditorGUILayout.PropertyField(m_fontInfo_prop.FindPropertyRelative("Padding")); //GUILayout.Label("Atlas Size"); EditorGUI.indentLevel = 1; GUILayout.Space(18); EditorGUILayout.PropertyField(m_fontInfo_prop.FindPropertyRelative("AtlasWidth"), new GUIContent("Width")); EditorGUILayout.PropertyField(m_fontInfo_prop.FindPropertyRelative("AtlasHeight"), new GUIContent("Height")); GUI.enabled = true; EditorGUI.indentLevel = 0; GUILayout.Space(20); GUILayout.Label("Font Sub-Assets", SectionLabel); GUI.enabled = false; EditorGUI.indentLevel = 1; EditorGUILayout.PropertyField(font_atlas_prop, new GUIContent("Font Atlas:")); EditorGUILayout.PropertyField(font_material_prop, new GUIContent("Font Material:")); GUI.enabled = true; // Font SETTINGS GUILayout.Space(10); GUILayout.Label("Face Style", SectionLabel); string evt_cmd = Event.current.commandName; // Get Current Event CommandName to check for Undo Events EditorGUILayout.BeginHorizontal(); EditorGUILayout.PropertyField(font_normalStyle_prop, new GUIContent("Normal weight")); font_normalStyle_prop.floatValue = Mathf.Clamp(font_normalStyle_prop.floatValue, -3.0f, 3.0f); if (GUI.changed || evt_cmd == k_UndoRedo) { GUI.changed = false; Material mat = font_material_prop.objectReferenceValue as Material; mat.SetFloat("_WeightNormal", font_normalStyle_prop.floatValue); } //Rect rect = EditorGUILayout.GetControlRect(); EditorGUILayout.PropertyField(font_boldStyle_prop, new GUIContent("Bold weight")); font_boldStyle_prop.floatValue = Mathf.Clamp(font_boldStyle_prop.floatValue, -3.0f, 3.0f); if (GUI.changed || evt_cmd == k_UndoRedo) { GUI.changed = false; Material mat = font_material_prop.objectReferenceValue as Material; mat.SetFloat("_WeightBold", font_boldStyle_prop.floatValue); } EditorGUILayout.EndHorizontal(); EditorGUILayout.PropertyField(font_italicStyle_prop, new GUIContent("Italic Style: ")); font_italicStyle_prop.intValue = Mathf.Clamp(font_italicStyle_prop.intValue, 15, 60); GUILayout.Space(10); EditorGUI.indentLevel = 0; if (GUILayout.Button("Glyph Info \t\t\t" + (UI_PanelState.glyphInfoPanel ? uiStateLabel[1] : uiStateLabel[0]), SectionLabel)) UI_PanelState.glyphInfoPanel = !UI_PanelState.glyphInfoPanel; if (UI_PanelState.glyphInfoPanel) { if (m_glyphInfoList_prop.arraySize > 0) { // Display each GlyphInfo entry using the GlyphInfo property drawer. for (int i = 0; i < m_glyphInfoList_prop.arraySize; i++) { SerializedProperty glyphInfo = m_glyphInfoList_prop.GetArrayElementAtIndex(i); EditorGUILayout.BeginVertical(GroupLabel); EditorGUILayout.PropertyField(glyphInfo); EditorGUILayout.EndVertical(); } } } // KERNING TABLE PANEL if (GUILayout.Button("Kerning Table Info\t\t\t" + (UI_PanelState.kerningInfoPanel ? uiStateLabel[1] : uiStateLabel[0]), SectionLabel)) UI_PanelState.kerningInfoPanel = !UI_PanelState.kerningInfoPanel; if (UI_PanelState.kerningInfoPanel) { Rect pos; SerializedProperty kerningPairs_prop = m_kerningInfo_prop.FindPropertyRelative("kerningPairs"); int pairCount = kerningPairs_prop.arraySize; EditorGUILayout.BeginHorizontal(); GUILayout.Label("Left Char", mySkin.label); GUILayout.Label("Right Char", mySkin.label); GUILayout.Label("Offset Value", mySkin.label); GUILayout.Label(GUIContent.none, GUILayout.Width(20)); EditorGUILayout.EndHorizontal(); GUILayout.BeginVertical(mySkin.label); for (int i = 0; i < pairCount; i++) { SerializedProperty kerningPair_prop = kerningPairs_prop.GetArrayElementAtIndex(i); pos = EditorGUILayout.BeginHorizontal(); EditorGUI.PropertyField(new Rect(pos.x, pos.y, pos.width - 20f, pos.height), kerningPair_prop, GUIContent.none); // Button to Delete Kerning Pair if (GUILayout.Button("-", GUILayout.ExpandWidth(false))) { m_kerningTable.RemoveKerningPair(i); m_fontAsset.ReadFontDefinition(); // Reload Font Definition. serializedObject.Update(); // Get an updated version of the SerializedObject. isAssetDirty = true; break; } EditorGUILayout.EndHorizontal(); } GUILayout.EndVertical(); GUILayout.Space(10); // Add New Kerning Pair Section GUILayout.BeginVertical(SquareAreaBox85G); pos = EditorGUILayout.BeginHorizontal(); // Draw Empty Kerning Pair EditorGUI.PropertyField(new Rect(pos.x, pos.y, pos.width - 20f, pos.height), m_kerningPair_prop); GUILayout.Label(GUIContent.none, GUILayout.Height(19)); EditorGUILayout.EndHorizontal(); GUILayout.Space(5); if (GUILayout.Button("Add New Kerning Pair")) { int asci_left = m_kerningPair_prop.FindPropertyRelative("AscII_Left").intValue; int asci_right = m_kerningPair_prop.FindPropertyRelative("AscII_Right").intValue; float xOffset = m_kerningPair_prop.FindPropertyRelative("XadvanceOffset").floatValue; errorCode = m_kerningTable.AddKerningPair(asci_left, asci_right, xOffset); // Sort Kerning Pairs & Reload Font Asset if new kerpair was added. if (errorCode != -1) { m_kerningTable.SortKerningPairs(); m_fontAsset.ReadFontDefinition(); // Reload Font Definition. serializedObject.Update(); // Get an updated version of the SerializedObject. isAssetDirty = true; } else { timeStamp = System.DateTime.Now.AddSeconds(5); } } if (errorCode == -1) { GUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); GUILayout.Label("Kerning Pair already <color=#ffff00>exists!</color>", mySkin.label); GUILayout.FlexibleSpace(); GUILayout.EndHorizontal(); if (System.DateTime.Now > timeStamp) errorCode = 0; } GUILayout.EndVertical(); } if (serializedObject.ApplyModifiedProperties() || evt_cmd == k_UndoRedo || isAssetDirty) { //Debug.Log("Serialized properties have changed."); TMPro_EventManager.ON_FONT_PROPERTY_CHANGED(true, m_fontAsset); isAssetDirty = false; TMPro_EditorUtility.RepaintAll(); // Consider SetDirty } } } }
// // ListViewBackend.cs // // Author: // Lluis Sanchez <lluis@xamarin.com> // Jan Strnadek <jan.strnadek@gmail.com> // - GetAtRowPosition // - NSTableView for mouse events // // Copyright (c) 2011 Xamarin 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 MonoMac.AppKit; using Xwt.Backends; using MonoMac.Foundation; namespace Xwt.Mac { public class ListViewBackend: TableViewBackend<NSTableView, IListViewEventSink>, IListViewBackend { IListDataSource source; ListSource tsource; protected override NSTableView CreateView () { return new NSTableViewBackend (EventSink, ApplicationContext); } protected override string SelectionChangeEventName { get { return "NSTableViewSelectionDidChangeNotification"; } } public override void EnableEvent (object eventId) { base.EnableEvent (eventId); if (eventId is ListViewEvent) { switch ((ListViewEvent)eventId) { case ListViewEvent.RowActivated: Table.DoubleClick += HandleDoubleClick; break; } } } public override void DisableEvent (object eventId) { base.DisableEvent (eventId); if (eventId is ListViewEvent) { switch ((ListViewEvent)eventId) { case ListViewEvent.RowActivated: Table.DoubleClick -= HandleDoubleClick; Table.DoubleAction = null; break; } } } void HandleDoubleClick (object sender, EventArgs e) { var cr = Table.ClickedRow; if (cr >= 0) { ApplicationContext.InvokeUserCode (delegate { ((IListViewEventSink)EventSink).OnRowActivated (cr); }); } } public virtual void SetSource (IListDataSource source, IBackend sourceBackend) { this.source = source; tsource = new ListSource (source); Table.DataSource = tsource; //TODO: Reloading single rows would be slightly more efficient. // According to NSTableView.ReloadData() documentation, // only the visible rows are reloaded. source.RowInserted += (sender, e) => Table.ReloadData(); source.RowDeleted += (sender, e) => Table.ReloadData(); source.RowChanged += (sender, e) => Table.ReloadData(); source.RowsReordered += (sender, e) => Table.ReloadData(); } public int[] SelectedRows { get { int[] sel = new int [Table.SelectedRowCount]; if (sel.Length > 0) { int i = 0; foreach (int r in Table.SelectedRows) sel [i++] = r; } return sel; } } public void SelectRow (int pos) { Table.SelectRow (pos, false); } public void UnselectRow (int pos) { Table.DeselectRow (pos); } public override object GetValue (object pos, int nField) { return source.GetValue ((int)pos, nField); } public override void SetValue (object pos, int nField, object value) { source.SetValue ((int)pos, nField, value); } public int CurrentEventRow { get; internal set; } public override void SetCurrentEventRow (object pos) { CurrentEventRow = (int)pos; } // TODO public bool BorderVisible { get; set; } public int GetRowAtPosition (Point p) { return Table.GetRow (new System.Drawing.PointF ((float)p.X, (float)p.Y)); } public Rectangle GetCellBounds (int row, CellView cell, bool includeMargin) { return Rectangle.Zero; } } class TableRow: NSObject, ITablePosition { public int Row; public object Position { get { return Row; } } } class ListSource: NSTableViewDataSource { IListDataSource source; public ListSource (IListDataSource source) { this.source = source; } public override bool AcceptDrop (NSTableView tableView, NSDraggingInfo info, int row, NSTableViewDropOperation dropOperation) { return false; } public override string[] FilesDropped (NSTableView tableView, MonoMac.Foundation.NSUrl dropDestination, MonoMac.Foundation.NSIndexSet indexSet) { return new string [0]; } public override MonoMac.Foundation.NSObject GetObjectValue (NSTableView tableView, NSTableColumn tableColumn, int row) { return NSObject.FromObject (row); } public override int GetRowCount (NSTableView tableView) { return source.RowCount; } public override void SetObjectValue (NSTableView tableView, MonoMac.Foundation.NSObject theObject, NSTableColumn tableColumn, int row) { } public override void SortDescriptorsChanged (NSTableView tableView, MonoMac.Foundation.NSSortDescriptor[] oldDescriptors) { } public override NSDragOperation ValidateDrop (NSTableView tableView, NSDraggingInfo info, int row, NSTableViewDropOperation dropOperation) { return NSDragOperation.None; } public override bool WriteRows (NSTableView tableView, MonoMac.Foundation.NSIndexSet rowIndexes, NSPasteboard pboard) { return false; } } }
using System; using System.Runtime.InteropServices; using System.Globalization; using System.Diagnostics.Contracts; using System.Runtime.CompilerServices; using System.Threading; using System.IO; namespace Microsoft.Build.Logging.StructuredLogger { public class BufferedReadStream : Stream { private const Int32 _DefaultBufferSize = 4096; private Stream _stream; // Underlying stream. Close sets _stream to null. private Byte[] _buffer; // Shared read/write buffer. Alloc on first use. private readonly Int32 _bufferSize; // Length of internal buffer (not counting the shadow buffer). private Int32 _readPos; // Read pointer within shared buffer. private Int32 _readLen; // Number of bytes read in buffer from _stream. private Int32 _writePos; // Write pointer within shared buffer. public BufferedReadStream(Stream stream) : this(stream, _DefaultBufferSize) { } private class __Error { internal static void StreamIsClosed() { throw new NotImplementedException(); } internal static void SeekNotSupported() { throw new NotImplementedException(); } internal static void ReadNotSupported() { throw new NotImplementedException(); } internal static void WriteNotSupported() { throw new NotImplementedException(); } } private class Environment { public static string GetResourceString(string text, params string[] args) => text; } public BufferedReadStream(Stream stream, Int32 bufferSize) { if (stream == null) throw new ArgumentNullException("stream"); if (bufferSize <= 0) throw new ArgumentOutOfRangeException("bufferSize", Environment.GetResourceString("ArgumentOutOfRange_MustBePositive", "bufferSize")); Contract.EndContractBlock(); _stream = stream; _bufferSize = bufferSize; // Allocate _buffer on its first use - it will not be used if all reads // & writes are greater than or equal to buffer size. if (!_stream.CanRead && !_stream.CanWrite) __Error.StreamIsClosed(); } private void EnsureNotClosed() { if (_stream == null) __Error.StreamIsClosed(); } private void EnsureCanSeek() { Contract.Requires(_stream != null); if (!_stream.CanSeek) __Error.SeekNotSupported(); } private void EnsureCanRead() { Contract.Requires(_stream != null); if (!_stream.CanRead) __Error.ReadNotSupported(); } private void EnsureCanWrite() { Contract.Requires(_stream != null); if (!_stream.CanWrite) __Error.WriteNotSupported(); } /// <summary><code>MaxShadowBufferSize</code> is chosed such that shadow buffers are not allocated on the Large Object Heap. /// Currently, an object is allocated on the LOH if it is larger than 85000 bytes. See LARGE_OBJECT_SIZE in ndp\clr\src\vm\gc.h /// We will go with exactly 80 KBytes, although this is somewhat arbitrary.</summary> private const Int32 MaxShadowBufferSize = 81920; // Make sure not to get to the Large Object Heap. private void EnsureShadowBufferAllocated() { Contract.Assert(_buffer != null); Contract.Assert(_bufferSize > 0); // Already have shadow buffer? if (_buffer.Length != _bufferSize || _bufferSize >= MaxShadowBufferSize) return; Byte[] shadowBuffer = new Byte[Math.Min(_bufferSize + _bufferSize, MaxShadowBufferSize)]; Buffer.BlockCopy(_buffer, 0, shadowBuffer, 0, _writePos); _buffer = shadowBuffer; } private void EnsureBufferAllocated() { Contract.Assert(_bufferSize > 0); // BufferedStream is not intended for multi-threaded use, so no worries about the get/set ---- on _buffer. if (_buffer == null) _buffer = new Byte[_bufferSize]; } internal Stream UnderlyingStream { get { return _stream; } } internal Int32 BufferSize { get { return _bufferSize; } } public override bool CanRead { [Pure] get { return _stream != null && _stream.CanRead; } } public override bool CanWrite { [Pure] get { return _stream != null && _stream.CanWrite; } } public override bool CanSeek { [Pure] get { return _stream != null && _stream.CanSeek; } } public override Int64 Length { get { EnsureNotClosed(); if (_writePos > 0) FlushWrite(); return _stream.Length; } } public override Int64 Position { get { EnsureNotClosed(); EnsureCanSeek(); Contract.Assert(!(_writePos > 0 && _readPos != _readLen), "Read and Write buffers cannot both have data in them at the same time."); return _stream.Position + (_readPos - _readLen + _writePos); } set { if (value < 0) throw new ArgumentOutOfRangeException("value", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); Contract.EndContractBlock(); EnsureNotClosed(); EnsureCanSeek(); if (_writePos > 0) FlushWrite(); _readPos = 0; _readLen = 0; _stream.Seek(value, SeekOrigin.Begin); } } protected override void Dispose(bool disposing) { try { if (disposing && _stream != null) { try { Flush(); } finally { _stream.Close(); } } } finally { _stream = null; _buffer = null; #if !FEATURE_PAL && FEATURE_ASYNC_IO _lastSyncCompletedReadTask = null; #endif // !FEATURE_PAL && FEATURE_ASYNC_IO // Call base.Dispose(bool) to cleanup async IO resources base.Dispose(disposing); } } public override void Flush() { EnsureNotClosed(); // Has WRITE data in the buffer: if (_writePos > 0) { FlushWrite(); Contract.Assert(_writePos == 0 && _readPos == 0 && _readLen == 0); return; } // Has READ data in the buffer: if (_readPos < _readLen) { // If the underlying stream is not seekable AND we have something in the read buffer, then FlushRead would throw. // We can either throw away the buffer resulting in data loss (!) or ignore the Flush. // (We cannot throw becasue it would be a breaking change.) We opt into ignoring the Flush in that situation. if (!_stream.CanSeek) return; FlushRead(); // User streams may have opted to throw from Flush if CanWrite is false (although the abstract Stream does not do so). // However, if we do not forward the Flush to the underlying stream, we may have problems when chaining several streams. // Let us make a best effort attempt: if (_stream.CanWrite || _stream is BufferedStream) _stream.Flush(); Contract.Assert(_writePos == 0 && _readPos == 0 && _readLen == 0); return; } // We had no data in the buffer, but we still need to tell the underlying stream to flush. if (_stream.CanWrite || _stream is BufferedStream) _stream.Flush(); _writePos = _readPos = _readLen = 0; } // Reading is done in blocks, but someone could read 1 byte from the buffer then write. // At that point, the underlying stream's pointer is out of sync with this stream's position. // All write functions should call this function to ensure that the buffered data is not lost. private void FlushRead() { Contract.Assert(_writePos == 0, "BufferedStream: Write buffer must be empty in FlushRead!"); if (_readPos - _readLen != 0) _stream.Seek(_readPos - _readLen, SeekOrigin.Current); _readPos = 0; _readLen = 0; } private void ClearReadBufferBeforeWrite() { // This is called by write methods to clear the read buffer. Contract.Assert(_readPos <= _readLen, "_readPos <= _readLen [" + _readPos + " <= " + _readLen + "]"); // No READ data in the buffer: if (_readPos == _readLen) { _readPos = _readLen = 0; return; } // Must have READ data. Contract.Assert(_readPos < _readLen); // If the underlying stream cannot seek, FlushRead would end up throwing NotSupported. // However, since the user did not call a method that is intuitively expected to seek, a better message is in order. // Ideally, we would throw an InvalidOperation here, but for backward compat we have to stick with NotSupported. if (!_stream.CanSeek) throw new NotSupportedException(Environment.GetResourceString("NotSupported_CannotWriteToBufferedStreamIfReadBufferCannotBeFlushed")); FlushRead(); } private void FlushWrite() { Contract.Assert(_readPos == 0 && _readLen == 0, "BufferedStream: Read buffer must be empty in FlushWrite!"); Contract.Assert(_buffer != null && _bufferSize >= _writePos, "BufferedStream: Write buffer must be allocated and write position must be in the bounds of the buffer in FlushWrite!"); _stream.Write(_buffer, 0, _writePos); _writePos = 0; _stream.Flush(); } private Int32 ReadFromBuffer(Byte[] array, Int32 offset, Int32 count) { Int32 readBytes = _readLen - _readPos; Contract.Assert(readBytes >= 0); if (readBytes == 0) return 0; Contract.Assert(readBytes > 0); if (readBytes > count) readBytes = count; Buffer.BlockCopy(_buffer, _readPos, array, offset, readBytes); _readPos += readBytes; return readBytes; } private Int32 ReadFromBuffer(Byte[] array, Int32 offset, Int32 count, out Exception error) { try { error = null; return ReadFromBuffer(array, offset, count); } catch (Exception ex) { error = ex; return 0; } } public override int Read([In, Out] Byte[] array, Int32 offset, Int32 count) { if (array == null) throw new ArgumentNullException("array", Environment.GetResourceString("ArgumentNull_Buffer")); if (offset < 0) throw new ArgumentOutOfRangeException("offset", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (count < 0) throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (array.Length - offset < count) throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen")); Contract.EndContractBlock(); EnsureNotClosed(); EnsureCanRead(); Int32 bytesFromBuffer = ReadFromBuffer(array, offset, count); // We may have read less than the number of bytes the user asked for, but that is part of the Stream contract. // Reading again for more data may cause us to block if we're using a device with no clear end of file, // such as a serial port or pipe. If we blocked here and this code was used with redirected pipes for a // process's standard output, this can lead to deadlocks involving two processes. // BUT - this is a breaking change. // So: If we could not read all bytes the user asked for from the buffer, we will try once from the underlying // stream thus ensuring the same blocking behaviour as if the underlying stream was not wrapped in this BufferedStream. if (bytesFromBuffer == count) return bytesFromBuffer; Int32 alreadySatisfied = bytesFromBuffer; if (bytesFromBuffer > 0) { count -= bytesFromBuffer; offset += bytesFromBuffer; } // So the READ buffer is empty. Contract.Assert(_readLen == _readPos); _readPos = _readLen = 0; // If there was anything in the WRITE buffer, clear it. if (_writePos > 0) FlushWrite(); // If the requested read is larger than buffer size, avoid the buffer and still use a single read: if (count >= _bufferSize) { return _stream.Read(array, offset, count) + alreadySatisfied; } // Ok. We can fill the buffer: EnsureBufferAllocated(); _readLen = _stream.Read(_buffer, 0, _bufferSize); bytesFromBuffer = ReadFromBuffer(array, offset, count); // We may have read less than the number of bytes the user asked for, but that is part of the Stream contract. // Reading again for more data may cause us to block if we're using a device with no clear end of stream, // such as a serial port or pipe. If we blocked here & this code was used with redirected pipes for a process's // standard output, this can lead to deadlocks involving two processes. Additionally, translating one read on the // BufferedStream to more than one read on the underlying Stream may defeat the whole purpose of buffering of the // underlying reads are significantly more expensive. return bytesFromBuffer + alreadySatisfied; } public override Int32 ReadByte() { //EnsureNotClosed(); //EnsureCanRead(); if (_readPos == _readLen) { if (_writePos > 0) FlushWrite(); EnsureBufferAllocated(); _readLen = _stream.Read(_buffer, 0, _bufferSize); _readPos = 0; } if (_readPos == _readLen) return -1; Int32 b = _buffer[_readPos++]; return b; } private void WriteToBuffer(Byte[] array, ref Int32 offset, ref Int32 count) { Int32 bytesToWrite = Math.Min(_bufferSize - _writePos, count); if (bytesToWrite <= 0) return; EnsureBufferAllocated(); Buffer.BlockCopy(array, offset, _buffer, _writePos, bytesToWrite); _writePos += bytesToWrite; count -= bytesToWrite; offset += bytesToWrite; } private void WriteToBuffer(Byte[] array, ref Int32 offset, ref Int32 count, out Exception error) { try { error = null; WriteToBuffer(array, ref offset, ref count); } catch (Exception ex) { error = ex; } } public override void Write(Byte[] array, Int32 offset, Int32 count) { if (array == null) throw new ArgumentNullException("array", Environment.GetResourceString("ArgumentNull_Buffer")); if (offset < 0) throw new ArgumentOutOfRangeException("offset", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (count < 0) throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (array.Length - offset < count) throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen")); Contract.EndContractBlock(); EnsureNotClosed(); EnsureCanWrite(); if (_writePos == 0) ClearReadBufferBeforeWrite(); #region Write algorithm comment // We need to use the buffer, while avoiding unnecessary buffer usage / memory copies. // We ASSUME that memory copies are much cheaper than writes to the underlying stream, so if an extra copy is // guaranteed to reduce the number of writes, we prefer it. // We pick a simple strategy that makes degenerate cases rare if our assumptions are right. // // For ever write, we use a simple heuristic (below) to decide whether to use the buffer. // The heuristic has the desirable property (*) that if the specified user data can fit into the currently available // buffer space without filling it up completely, the heuristic will always tell us to use the buffer. It will also // tell us to use the buffer in cases where the current write would fill the buffer, but the remaining data is small // enough such that subsequent operations can use the buffer again. // // Algorithm: // Determine whether or not to buffer according to the heuristic (below). // If we decided to use the buffer: // Copy as much user data as we can into the buffer. // If we consumed all data: We are finished. // Otherwise, write the buffer out. // Copy the rest of user data into the now cleared buffer (no need to write out the buffer again as the heuristic // will prevent it from being filled twice). // If we decided not to use the buffer: // Can the data already in the buffer and current user data be combines to a single write // by allocating a "shadow" buffer of up to twice the size of _bufferSize (up to a limit to avoid LOH)? // Yes, it can: // Allocate a larger "shadow" buffer and ensure the buffered data is moved there. // Copy user data to the shadow buffer. // Write shadow buffer to the underlying stream in a single operation. // No, it cannot (amount of data is still too large): // Write out any data possibly in the buffer. // Write out user data directly. // // Heuristic: // If the subsequent write operation that follows the current write operation will result in a write to the // underlying stream in case that we use the buffer in the current write, while it would not have if we avoided // using the buffer in the current write (by writing current user data to the underlying stream directly), then we // prefer to avoid using the buffer since the corresponding memory copy is wasted (it will not reduce the number // of writes to the underlying stream, which is what we are optimising for). // ASSUME that the next write will be for the same amount of bytes as the current write (most common case) and // determine if it will cause a write to the underlying stream. If the next write is actually larger, our heuristic // still yields the right behaviour, if the next write is actually smaller, we may making an unnecessary write to // the underlying stream. However, this can only occur if the current write is larger than half the buffer size and // we will recover after one iteration. // We have: // useBuffer = (_writePos + count + count < _bufferSize + _bufferSize) // // Example with _bufferSize = 20, _writePos = 6, count = 10: // // +---------------------------------------+---------------------------------------+ // | current buffer | next iteration's "future" buffer | // +---------------------------------------+---------------------------------------+ // |0| | | | | | | | | |1| | | | | | | | | |2| | | | | | | | | |3| | | | | | | | | | // |0|1|2|3|4|5|6|7|8|9|0|1|2|3|4|5|6|7|8|9|0|1|2|3|4|5|6|7|8|9|0|1|2|3|4|5|6|7|8|9| // +-----------+-------------------+-------------------+---------------------------+ // | _writePos | current count | assumed next count|avail buff after next write| // +-----------+-------------------+-------------------+---------------------------+ // // A nice property (*) of this heuristic is that it will always succeed if the user data completely fits into the // available buffer, i.e. if count < (_bufferSize - _writePos). #endregion Write algorithm comment Contract.Assert(_writePos < _bufferSize); Int32 totalUserBytes; bool useBuffer; checked { // We do not expect buffer sizes big enough for an overflow, but if it happens, lets fail early: totalUserBytes = _writePos + count; useBuffer = (totalUserBytes + count < (_bufferSize + _bufferSize)); } if (useBuffer) { WriteToBuffer(array, ref offset, ref count); if (_writePos < _bufferSize) { Contract.Assert(count == 0); return; } Contract.Assert(count >= 0); Contract.Assert(_writePos == _bufferSize); Contract.Assert(_buffer != null); _stream.Write(_buffer, 0, _writePos); _writePos = 0; WriteToBuffer(array, ref offset, ref count); Contract.Assert(count == 0); Contract.Assert(_writePos < _bufferSize); } else { // if (!useBuffer) // Write out the buffer if necessary. if (_writePos > 0) { Contract.Assert(_buffer != null); Contract.Assert(totalUserBytes >= _bufferSize); // Try avoiding extra write to underlying stream by combining previously buffered data with current user data: if (totalUserBytes <= (_bufferSize + _bufferSize) && totalUserBytes <= MaxShadowBufferSize) { EnsureShadowBufferAllocated(); Buffer.BlockCopy(array, offset, _buffer, _writePos, count); _stream.Write(_buffer, 0, totalUserBytes); _writePos = 0; return; } _stream.Write(_buffer, 0, _writePos); _writePos = 0; } // Write out user data. _stream.Write(array, offset, count); } } public override void WriteByte(Byte value) { EnsureNotClosed(); if (_writePos == 0) { EnsureCanWrite(); ClearReadBufferBeforeWrite(); EnsureBufferAllocated(); } // We should not be flushing here, but only writing to the underlying stream, but previous version flushed, so we keep this. if (_writePos >= _bufferSize - 1) FlushWrite(); _buffer[_writePos++] = value; Contract.Assert(_writePos < _bufferSize); } public override Int64 Seek(Int64 offset, SeekOrigin origin) { EnsureNotClosed(); EnsureCanSeek(); // If we have bytes in the WRITE buffer, flush them out, seek and be done. if (_writePos > 0) { // We should be only writing the buffer and not flushing, // but the previous version did flush and we stick to it for back-compat reasons. FlushWrite(); return _stream.Seek(offset, origin); } // The buffer is either empty or we have a buffered READ. if (_readLen - _readPos > 0 && origin == SeekOrigin.Current) { // If we have bytes in the READ buffer, adjust the seek offset to account for the resulting difference // between this stream's position and the underlying stream's position. offset -= (_readLen - _readPos); } Int64 oldPos = Position; Contract.Assert(oldPos == _stream.Position + (_readPos - _readLen)); Int64 newPos = _stream.Seek(offset, origin); // If the seek destination is still within the data currently in the buffer, we want to keep the buffer data and continue using it. // Otherwise we will throw away the buffer. This can only happen on READ, as we flushed WRITE data above. // The offset of the new/updated seek pointer within _buffer: _readPos = (Int32)(newPos - (oldPos - _readPos)); // If the offset of the updated seek pointer in the buffer is still legal, then we can keep using the buffer: if (0 <= _readPos && _readPos < _readLen) { // Adjust the seek pointer of the underlying stream to reflect the amount of useful bytes in the read buffer: _stream.Seek(_readLen - _readPos, SeekOrigin.Current); } else { // The offset of the updated seek pointer is not a legal offset. Loose the buffer. _readPos = _readLen = 0; } Contract.Assert(newPos == Position, "newPos (=" + newPos + ") == Position (=" + Position + ")"); return newPos; } public override void SetLength(Int64 value) { if (value < 0) throw new ArgumentOutOfRangeException("value", Environment.GetResourceString("ArgumentOutOfRange_NegFileSize")); Contract.EndContractBlock(); EnsureNotClosed(); EnsureCanSeek(); EnsureCanWrite(); Flush(); _stream.SetLength(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. // ---------------------------------------------------------------------------------- // Interop library code // // Marshalling helpers used by MCG // // NOTE: // These source code are being published to InternalAPIs and consumed by RH builds // Use PublishInteropAPI.bat to keep the InternalAPI copies in sync // ---------------------------------------------------------------------------------- using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Reflection; using System.Runtime.InteropServices.WindowsRuntime; using System.Runtime.InteropServices; using System.Threading; using System.Text; using System.Runtime; using System.Diagnostics.Contracts; using System.Runtime.CompilerServices; using Internal.NativeFormat; #if !CORECLR using Internal.Runtime.Augments; #endif #if RHTESTCL using OutputClass = System.Console; #else using OutputClass = System.Diagnostics.Debug; #endif namespace System.Runtime.InteropServices { /// <summary> /// Expose functionality from System.Private.CoreLib and forwards calls to InteropExtensions in System.Private.CoreLib /// </summary> [CLSCompliant(false)] public static partial class McgMarshal { public static void SaveLastWin32Error() { PInvokeMarshal.SaveLastWin32Error(); } public static bool GuidEquals(ref Guid left, ref Guid right) { return InteropExtensions.GuidEquals(ref left, ref right); } public static bool ComparerEquals<T>(T left, T right) { return InteropExtensions.ComparerEquals<T>(left, right); } public static T CreateClass<T>() where T : class { return InteropExtensions.UncheckedCast<T>(InteropExtensions.RuntimeNewObject(typeof(T).TypeHandle)); } public static bool IsEnum(object obj) { #if RHTESTCL return false; #else return InteropExtensions.IsEnum(obj.GetTypeHandle()); #endif } public static bool IsCOMObject(Type type) { #if RHTESTCL return false; #else return type.GetTypeInfo().IsSubclassOf(typeof(__ComObject)); #endif } public static T FastCast<T>(object value) where T : class { // We have an assert here, to verify that a "real" cast would have succeeded. // However, casting on weakly-typed RCWs modifies their state, by doing a QI and caching // the result. This often makes things work which otherwise wouldn't work (especially variance). Debug.Assert(value == null || value is T); return InteropExtensions.UncheckedCast<T>(value); } /// <summary> /// Converts a managed DateTime to native OLE datetime /// Used by MCG marshalling code /// </summary> public static double ToNativeOleDate(DateTime dateTime) { return InteropExtensions.ToNativeOleDate(dateTime); } /// <summary> /// Converts native OLE datetime to managed DateTime /// Used by MCG marshalling code /// </summary> public static DateTime FromNativeOleDate(double nativeOleDate) { return InteropExtensions.FromNativeOleDate(nativeOleDate); } /// <summary> /// Used in Marshalling code /// Call safeHandle.InitializeHandle to set the internal _handle field /// </summary> public static void InitializeHandle(SafeHandle safeHandle, IntPtr win32Handle) { InteropExtensions.InitializeHandle(safeHandle, win32Handle); } /// <summary> /// Check if obj's type is the same as represented by normalized handle /// </summary> [MethodImpl(MethodImplOptions.NoInlining)] public static bool IsOfType(object obj, RuntimeTypeHandle handle) { return obj.IsOfType(handle); } #if ENABLE_MIN_WINRT public static unsafe void SetExceptionErrorCode(Exception exception, int errorCode) { InteropExtensions.SetExceptionErrorCode(exception, errorCode); } /// <summary> /// Used in Marshalling code /// Gets the handle of the CriticalHandle /// </summary> public static IntPtr GetHandle(CriticalHandle criticalHandle) { return InteropExtensions.GetCriticalHandle(criticalHandle); } /// <summary> /// Used in Marshalling code /// Sets the handle of the CriticalHandle /// </summary> public static void SetHandle(CriticalHandle criticalHandle, IntPtr handle) { InteropExtensions.SetCriticalHandle(criticalHandle, handle); } #endif } /// <summary> /// McgMarshal helpers exposed to be used by MCG /// </summary> public static partial class McgMarshal { #region Type marshalling public static Type TypeNameToType(HSTRING nativeTypeName, int nativeTypeKind) { #if ENABLE_WINRT return McgTypeHelpers.TypeNameToType(nativeTypeName, nativeTypeKind); #else throw new NotSupportedException("TypeNameToType"); #endif } public static unsafe void TypeToTypeName( Type type, out HSTRING nativeTypeName, out int nativeTypeKind) { #if ENABLE_WINRT McgTypeHelpers.TypeToTypeName(type, out nativeTypeName, out nativeTypeKind); #else throw new NotSupportedException("TypeToTypeName"); #endif } #endregion #region String marshalling [CLSCompliant(false)] public static unsafe void StringBuilderToUnicodeString(System.Text.StringBuilder stringBuilder, ushort* destination) { PInvokeMarshal.StringBuilderToUnicodeString(stringBuilder, destination); } [CLSCompliant(false)] public static unsafe void UnicodeStringToStringBuilder(ushort* newBuffer, System.Text.StringBuilder stringBuilder) { PInvokeMarshal.UnicodeStringToStringBuilder(newBuffer, stringBuilder); } #if !RHTESTCL [CLSCompliant(false)] public static unsafe void StringBuilderToAnsiString(System.Text.StringBuilder stringBuilder, byte* pNative, bool bestFit, bool throwOnUnmappableChar) { PInvokeMarshal.StringBuilderToAnsiString(stringBuilder, pNative, bestFit, throwOnUnmappableChar); } [CLSCompliant(false)] public static unsafe void AnsiStringToStringBuilder(byte* newBuffer, System.Text.StringBuilder stringBuilder) { PInvokeMarshal.AnsiStringToStringBuilder(newBuffer, stringBuilder); } /// <summary> /// Convert ANSI string to unicode string, with option to free native memory. Calls generated by MCG /// </summary> /// <remarks>Input assumed to be zero terminated. Generates String.Empty for zero length string. /// This version is more efficient than ConvertToUnicode in src\Interop\System\Runtime\InteropServices\Marshal.cs in that it can skip calling /// MultiByteToWideChar for ASCII string, and it does not need another char[] buffer</remarks> [CLSCompliant(false)] public static unsafe string AnsiStringToString(byte* pchBuffer) { return PInvokeMarshal.AnsiStringToString(pchBuffer); } /// <summary> /// Convert UNICODE string to ANSI string. /// </summary> /// <remarks>This version is more efficient than StringToHGlobalAnsi in Interop\System\Runtime\InteropServices\Marshal.cs in that /// it could allocate single byte per character, instead of SystemMaxDBCSCharSize per char, and it can skip calling WideCharToMultiByte for ASCII string</remarks> [CLSCompliant(false)] public static unsafe byte* StringToAnsiString(string str, bool bestFit, bool throwOnUnmappableChar) { return PInvokeMarshal.StringToAnsiString(str, bestFit, throwOnUnmappableChar); } /// <summary> /// Convert UNICODE wide char array to ANSI ByVal byte array. /// </summary> /// <remarks> /// * This version works with array instead string, it means that there will be NO NULL to terminate the array. /// * The buffer to store the byte array must be allocated by the caller and must fit managedArray.Length. /// </remarks> /// <param name="managedArray">UNICODE wide char array</param> /// <param name="pNative">Allocated buffer where the ansi characters must be placed. Could NOT be null. Buffer size must fit char[].Length.</param> [CLSCompliant(false)] public static unsafe void ByValWideCharArrayToAnsiCharArray(char[] managedArray, byte* pNative, int expectedCharCount, bool bestFit, bool throwOnUnmappableChar) { PInvokeMarshal.ByValWideCharArrayToAnsiCharArray(managedArray, pNative, expectedCharCount, bestFit, throwOnUnmappableChar); } [CLSCompliant(false)] public static unsafe void ByValAnsiCharArrayToWideCharArray(byte* pNative, char[] managedArray) { PInvokeMarshal.ByValAnsiCharArrayToWideCharArray(pNative, managedArray); } [CLSCompliant(false)] public static unsafe void WideCharArrayToAnsiCharArray(char[] managedArray, byte* pNative, bool bestFit, bool throwOnUnmappableChar) { PInvokeMarshal.WideCharArrayToAnsiCharArray(managedArray, pNative, bestFit, throwOnUnmappableChar); } /// <summary> /// Convert ANSI ByVal byte array to UNICODE wide char array, best fit /// </summary> /// <remarks> /// * This version works with array instead to string, it means that the len must be provided and there will be NO NULL to /// terminate the array. /// * The buffer to the UNICODE wide char array must be allocated by the caller. /// </remarks> /// <param name="pNative">Pointer to the ANSI byte array. Could NOT be null.</param> /// <param name="lenInBytes">Maximum buffer size.</param> /// <param name="managedArray">Wide char array that has already been allocated.</param> [CLSCompliant(false)] public static unsafe void AnsiCharArrayToWideCharArray(byte* pNative, char[] managedArray) { PInvokeMarshal.AnsiCharArrayToWideCharArray(pNative, managedArray); } /// <summary> /// Convert a single UNICODE wide char to a single ANSI byte. /// </summary> /// <param name="managedArray">single UNICODE wide char value</param> public static unsafe byte WideCharToAnsiChar(char managedValue, bool bestFit, bool throwOnUnmappableChar) { return PInvokeMarshal.WideCharToAnsiChar(managedValue, bestFit, throwOnUnmappableChar); } /// <summary> /// Convert a single ANSI byte value to a single UNICODE wide char value, best fit. /// </summary> /// <param name="nativeValue">Single ANSI byte value.</param> public static unsafe char AnsiCharToWideChar(byte nativeValue) { return PInvokeMarshal.AnsiCharToWideChar(nativeValue); } /// <summary> /// Convert UNICODE string to ANSI ByVal string. /// </summary> /// <remarks>This version is more efficient than StringToHGlobalAnsi in Interop\System\Runtime\InteropServices\Marshal.cs in that /// it could allocate single byte per character, instead of SystemMaxDBCSCharSize per char, and it can skip calling WideCharToMultiByte for ASCII string</remarks> /// <param name="str">Unicode string.</param> /// <param name="pNative"> Allocated buffer where the ansi string must be placed. Could NOT be null. Buffer size must fit str.Length.</param> [CLSCompliant(false)] public static unsafe void StringToByValAnsiString(string str, byte* pNative, int charCount, bool bestFit, bool throwOnUnmappableChar) { PInvokeMarshal.StringToByValAnsiString(str, pNative, charCount, bestFit, throwOnUnmappableChar); } /// <summary> /// Convert ANSI string to unicode string, with option to free native memory. Calls generated by MCG /// </summary> /// <remarks>Input assumed to be zero terminated. Generates String.Empty for zero length string. /// This version is more efficient than ConvertToUnicode in src\Interop\System\Runtime\InteropServices\Marshal.cs in that it can skip calling /// MultiByteToWideChar for ASCII string, and it does not need another char[] buffer</remarks> [CLSCompliant(false)] public static unsafe string ByValAnsiStringToString(byte* pchBuffer, int charCount) { return PInvokeMarshal.ByValAnsiStringToString(pchBuffer, charCount); } #endif #if ENABLE_WINRT [MethodImplAttribute(MethodImplOptions.NoInlining)] public static unsafe HSTRING StringToHString(string sourceString) { if (sourceString == null) throw new ArgumentNullException(nameof(sourceString), SR.Null_HString); return StringToHStringInternal(sourceString); } [MethodImplAttribute(MethodImplOptions.NoInlining)] public static unsafe HSTRING StringToHStringForField(string sourceString) { #if !RHTESTCL if (sourceString == null) throw new MarshalDirectiveException(SR.BadMarshalField_Null_HString); #endif return StringToHStringInternal(sourceString); } private static unsafe HSTRING StringToHStringInternal(string sourceString) { HSTRING ret; int hr = StringToHStringNoNullCheck(sourceString, &ret); if (hr < 0) throw Marshal.GetExceptionForHR(hr); return ret; } [MethodImplAttribute(MethodImplOptions.NoInlining)] internal static unsafe int StringToHStringNoNullCheck(string sourceString, HSTRING* hstring) { fixed (char* pChars = sourceString) { int hr = ExternalInterop.WindowsCreateString(pChars, (uint)sourceString.Length, (void*)hstring); return hr; } } #endif //ENABLE_WINRT #endregion #region COM marshalling /// <summary> /// Explicit AddRef for RCWs /// You can't call IFoo.AddRef anymore as IFoo no longer derive from IUnknown /// You need to call McgMarshal.AddRef(); /// </summary> /// <remarks> /// Used by prefast MCG plugin (mcgimportpft) only /// </remarks> [CLSCompliant(false)] public static int AddRef(__ComObject obj) { return obj.AddRef(); } /// <summary> /// Explicit Release for RCWs /// You can't call IFoo.Release anymore as IFoo no longer derive from IUnknown /// You need to call McgMarshal.Release(); /// </summary> /// <remarks> /// Used by prefast MCG plugin (mcgimportpft) only /// </remarks> [CLSCompliant(false)] public static int Release(__ComObject obj) { return obj.Release(); } [MethodImpl(MethodImplOptions.NoInlining)] public static unsafe int ComAddRef(IntPtr pComItf) { return CalliIntrinsics.StdCall__AddRef(((__com_IUnknown*)(void*)pComItf)->pVtable-> pfnAddRef, pComItf); } [MethodImpl(MethodImplOptions.NoInlining)] internal static unsafe int ComRelease_StdCall(IntPtr pComItf) { return CalliIntrinsics.StdCall__Release(((__com_IUnknown*)(void*)pComItf)->pVtable-> pfnRelease, pComItf); } /// <summary> /// Inline version of ComRelease /// </summary> [MethodImpl(MethodImplOptions.NoInlining)] //reduces MCG-generated code size public static unsafe int ComRelease(IntPtr pComItf) { IntPtr pRelease = ((__com_IUnknown*)(void*)pComItf)->pVtable->pfnRelease; // Check if the COM object is implemented by PN Interop code, for which we can call directly if (pRelease == AddrOfIntrinsics.AddrOf<AddrOfRelease>(__vtable_IUnknown.Release)) { return __interface_ccw.DirectRelease(pComItf); } // Normal slow path, do not inline return ComRelease_StdCall(pComItf); } [MethodImpl(MethodImplOptions.NoInlining)] public static unsafe int ComSafeRelease(IntPtr pComItf) { if (pComItf != default(IntPtr)) { return ComRelease(pComItf); } return 0; } public static int FinalReleaseComObject(object o) { if (o == null) throw new ArgumentNullException(nameof(o)); __ComObject co = null; // Make sure the obj is an __ComObject. try { co = (__ComObject)o; } catch (InvalidCastException) { throw new ArgumentException(SR.Argument_ObjNotComObject, nameof(o)); } co.FinalReleaseSelf(); return 0; } /// <summary> /// Returns the cached WinRT factory RCW under the current context /// </summary> [CLSCompliant(false)] public static unsafe __ComObject GetActivationFactory(string className, RuntimeTypeHandle factoryIntf) { #if ENABLE_MIN_WINRT return FactoryCache.Get().GetActivationFactory(className, factoryIntf); #else throw new PlatformNotSupportedException("GetActivationFactory"); #endif } /// <summary> /// Used by CCW infrastructure code to return the target object from this pointer /// </summary> /// <returns>The target object pointed by this pointer</returns> public static object ThisPointerToTargetObject(IntPtr pUnk) { return ComCallableObject.GetTarget(pUnk); } [CLSCompliant(false)] public static object ComInterfaceToObject_NoUnboxing( IntPtr pComItf, RuntimeTypeHandle interfaceType) { return McgComHelpers.ComInterfaceToObjectInternal( pComItf, interfaceType, default(RuntimeTypeHandle), McgComHelpers.CreateComObjectFlags.SkipTypeResolutionAndUnboxing ); } /// <summary> /// Shared CCW Interface To Object /// </summary> /// <param name="pComItf"></param> /// <param name="interfaceType"></param> /// <param name="classTypeInSignature"></param> /// <returns></returns> [CLSCompliant(false)] public static object ComInterfaceToObject( System.IntPtr pComItf, RuntimeTypeHandle interfaceType, RuntimeTypeHandle classTypeInSignature) { #if ENABLE_MIN_WINRT if (interfaceType.Equals(typeof(object).TypeHandle)) { return McgMarshal.IInspectableToObject(pComItf); } if (interfaceType.Equals(typeof(System.String).TypeHandle)) { return McgMarshal.HStringToString(pComItf); } if (interfaceType.IsComClass()) { RuntimeTypeHandle defaultInterface = interfaceType.GetDefaultInterface(); Debug.Assert(!defaultInterface.IsNull()); return ComInterfaceToObjectInternal(pComItf, defaultInterface, interfaceType); } #endif return ComInterfaceToObjectInternal( pComItf, interfaceType, classTypeInSignature ); } [CLSCompliant(false)] public static object ComInterfaceToObject( IntPtr pComItf, RuntimeTypeHandle interfaceType) { return ComInterfaceToObject(pComItf, interfaceType, default(RuntimeTypeHandle)); } private static object ComInterfaceToObjectInternal( IntPtr pComItf, RuntimeTypeHandle interfaceType, RuntimeTypeHandle classTypeInSignature) { object result = McgComHelpers.ComInterfaceToObjectInternal(pComItf, interfaceType, classTypeInSignature, McgComHelpers.CreateComObjectFlags.None); // // Make sure the type we returned is actually of the right type // NOTE: Don't pass null to IsInstanceOfClass as it'll return false // if (!classTypeInSignature.IsNull() && result != null) { if (!InteropExtensions.IsInstanceOfClass(result, classTypeInSignature)) throw new InvalidCastException(); } return result; } public static unsafe IntPtr ComQueryInterfaceNoThrow(IntPtr pComItf, ref Guid iid) { int hr = 0; return ComQueryInterfaceNoThrow(pComItf, ref iid, out hr); } public static unsafe IntPtr ComQueryInterfaceNoThrow(IntPtr pComItf, ref Guid iid, out int hr) { IntPtr pComIUnk; hr = ComQueryInterfaceWithHR(pComItf, ref iid, out pComIUnk); return pComIUnk; } internal static unsafe int ComQueryInterfaceWithHR(IntPtr pComItf, ref Guid iid, out IntPtr ppv) { IntPtr pComIUnk; int hr; fixed (Guid* unsafe_iid = &iid) { hr = CalliIntrinsics.StdCall__QueryInterface(((__com_IUnknown*)(void*)pComItf)->pVtable-> pfnQueryInterface, pComItf, new IntPtr(unsafe_iid), new IntPtr(&pComIUnk)); } if (hr != 0) { ppv = default(IntPtr); } else { ppv = pComIUnk; } return hr; } /// <summary> /// Helper function to copy vTable to native heap on CoreCLR. /// </summary> /// <typeparam name="T">Vtbl type</typeparam> /// <param name="pVtbl">static v-table field , always a valid pointer</param> /// <param name="pNativeVtbl">Pointer to Vtable on native heap on CoreCLR , on N it's an alias for pVtbl</param> public static unsafe IntPtr GetCCWVTableCopy(void* pVtbl, ref IntPtr pNativeVtbl, int size) { if (pNativeVtbl == default(IntPtr)) { #if CORECLR // On CoreCLR copy vTable to native heap , on N VTable is frozen. IntPtr pv = Marshal.AllocHGlobal(size); int* pSrc = (int*)pVtbl; int* pDest = (int*)pv.ToPointer(); int pSize = sizeof(int); // this should never happen , if a CCW is discarded we never get here. Debug.Assert(size >= pSize); for (int i = 0; i < size; i += pSize) { *pDest++ = *pSrc++; } if (Interlocked.CompareExchange(ref pNativeVtbl, pv, default(IntPtr)) != default(IntPtr)) { // Another thread sneaked-in and updated pNativeVtbl , just use the update from other thread Marshal.FreeHGlobal(pv); } #else // .NET NATIVE // Wrap it in an IntPtr pNativeVtbl = (IntPtr)pVtbl; #endif // CORECLR } return pNativeVtbl; } [CLSCompliant(false)] public static IntPtr ObjectToComInterface( object obj, RuntimeTypeHandle typeHnd) { #if ENABLE_MIN_WINRT if (typeHnd.Equals(typeof(object).TypeHandle)) { return McgMarshal.ObjectToIInspectable(obj); } if (typeHnd.Equals(typeof(System.String).TypeHandle)) { return McgMarshal.StringToHString((string)obj).handle; } if (typeHnd.IsComClass()) { Debug.Assert(obj == null || obj is __ComObject); /// /// This code path should be executed only for WinRT classes /// typeHnd = typeHnd.GetDefaultInterface(); Debug.Assert(!typeHnd.IsNull()); } #endif return McgComHelpers.ObjectToComInterfaceInternal( obj, typeHnd ); } public static IntPtr ObjectToIInspectable(Object obj) { #if ENABLE_MIN_WINRT return ObjectToComInterface(obj, InternalTypes.IInspectable); #else throw new PlatformNotSupportedException("ObjectToIInspectable"); #endif } // This is not a safe function to use for any funtion pointers that do not point // at a static function. This is due to the behavior of shared generics, // where instance function entry points may share the exact same address // but static functions are always represented in delegates with customized // stubs. private static bool DelegateTargetMethodEquals(Delegate del, IntPtr pfn) { RuntimeTypeHandle thDummy; return del.GetFunctionPointer(out thDummy) == pfn; } [MethodImpl(MethodImplOptions.NoInlining)] public static IntPtr DelegateToComInterface(Delegate del, RuntimeTypeHandle typeHnd) { if (del == null) return default(IntPtr); IntPtr stubFunctionAddr = typeHnd.GetDelegateInvokeStub(); object targetObj; // // If the delegate points to the forward stub for the native delegate, // then we want the RCW associated with the native interface. Otherwise, // this is a managed delegate, and we want the CCW associated with it. // if (DelegateTargetMethodEquals(del, stubFunctionAddr)) targetObj = del.Target; else targetObj = del; return McgMarshal.ObjectToComInterface(targetObj, typeHnd); } [MethodImpl(MethodImplOptions.NoInlining)] public static Delegate ComInterfaceToDelegate(IntPtr pComItf, RuntimeTypeHandle typeHnd) { if (pComItf == default(IntPtr)) return null; object obj = ComInterfaceToObject(pComItf, typeHnd, /* classIndexInSignature */ default(RuntimeTypeHandle)); // // If the object we got back was a managed delegate, then we're good. Otherwise, // the object is an RCW for a native delegate, so we need to wrap it with a managed // delegate that invokes the correct stub. // Delegate del = obj as Delegate; if (del == null) { Debug.Assert(obj is __ComObject); IntPtr stubFunctionAddr = typeHnd.GetDelegateInvokeStub(); del = InteropExtensions.CreateDelegate( typeHnd, stubFunctionAddr, obj, /*isStatic:*/ true, /*isVirtual:*/ false, /*isOpen:*/ false); } return del; } /// <summary> /// Marshal array of objects /// </summary> [MethodImplAttribute(MethodImplOptions.NoInlining)] unsafe public static void ObjectArrayToComInterfaceArray(uint len, System.IntPtr* dst, object[] src, RuntimeTypeHandle typeHnd) { for (uint i = 0; i < len; i++) { dst[i] = McgMarshal.ObjectToComInterface(src[i], typeHnd); } } /// <summary> /// Allocate native memory, and then marshal array of objects /// </summary> [MethodImplAttribute(MethodImplOptions.NoInlining)] unsafe public static System.IntPtr* ObjectArrayToComInterfaceArrayAlloc(object[] src, RuntimeTypeHandle typeHnd, out uint len) { System.IntPtr* dst = null; len = 0; if (src != null) { len = (uint)src.Length; dst = (System.IntPtr*)PInvokeMarshal.CoTaskMemAlloc((System.UIntPtr)(len * (sizeof(System.IntPtr)))); for (uint i = 0; i < len; i++) { dst[i] = McgMarshal.ObjectToComInterface(src[i], typeHnd); } } return dst; } /// <summary> /// Get outer IInspectable for managed object deriving from native scenario /// At this point the inner is not created yet - you need the outer first and pass it to the factory /// to create the inner /// </summary> [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static IntPtr GetOuterIInspectableForManagedObject(__ComObject managedObject) { ComCallableObject ccw = null; try { // // Create the CCW over the RCW // Note that they are actually both the same object // Base class = inner // Derived class = outer // ccw = new ComCallableObject( managedObject, // The target object = managedObject managedObject // The inner RCW (as __ComObject) = managedObject ); // // Retrieve the outer IInspectable // Pass skipInterfaceCheck = true to avoid redundant checks // return ccw.GetComInterfaceForType_NoCheck(InternalTypes.IInspectable, ref Interop.COM.IID_IInspectable); } finally { // // Free the extra ref count initialized by __native_ccw.Init (to protect the CCW from being collected) // if (ccw != null) ccw.Release(); } } [CLSCompliant(false)] public static unsafe IntPtr ManagedObjectToComInterface(Object obj, RuntimeTypeHandle interfaceType) { return McgComHelpers.ManagedObjectToComInterface(obj, interfaceType); } public static unsafe object IInspectableToObject(IntPtr pComItf) { #if ENABLE_WINRT return ComInterfaceToObject(pComItf, InternalTypes.IInspectable); #else throw new PlatformNotSupportedException("IInspectableToObject"); #endif } public static unsafe IntPtr CreateInstanceFromApp(Guid clsid) { #if ENABLE_WINRT Interop.COM.MULTI_QI results; IntPtr pResults = new IntPtr(&results); fixed (Guid* pIID = &Interop.COM.IID_IUnknown) { Guid* pClsid = &clsid; results.pIID = new IntPtr(pIID); results.pItf = IntPtr.Zero; results.hr = 0; int hr = ExternalInterop.CoCreateInstanceFromApp(pClsid, IntPtr.Zero, 0x15 /* (CLSCTX_SERVER) */, IntPtr.Zero, 1, pResults); if (hr < 0) { throw McgMarshal.GetExceptionForHR(hr, /*isWinRTScenario = */ false); } if (results.hr < 0) { throw McgMarshal.GetExceptionForHR(results.hr, /* isWinRTScenario = */ false); } return results.pItf; } #else throw new PlatformNotSupportedException("CreateInstanceFromApp"); #endif } #endregion #region Testing /// <summary> /// Internal-only method to allow testing of apartment teardown code /// </summary> public static void ReleaseRCWsInCurrentApartment() { ContextEntry.RemoveCurrentContext(); } /// <summary> /// Used by detecting leaks /// Used in prefast MCG only /// </summary> public static int GetTotalComObjectCount() { return ComObjectCache.s_comObjectMap.Count; } /// <summary> /// Used by detecting and dumping leaks /// Used in prefast MCG only /// </summary> public static IEnumerable<__ComObject> GetAllComObjects() { List<__ComObject> list = new List<__ComObject>(); for (int i = 0; i < ComObjectCache.s_comObjectMap.GetMaxCount(); ++i) { IntPtr pHandle = default(IntPtr); if (ComObjectCache.s_comObjectMap.GetValue(i, ref pHandle) && (pHandle != default(IntPtr))) { GCHandle handle = GCHandle.FromIntPtr(pHandle); list.Add(InteropExtensions.UncheckedCast<__ComObject>(handle.Target)); } } return list; } #endregion /// <summary> /// This method returns HR for the exception being thrown. /// 1. On Windows8+, WinRT scenarios we do the following. /// a. Check whether the exception has any IRestrictedErrorInfo associated with it. /// If so, it means that this exception was actually caused by a native exception in which case we do simply use the same /// message and stacktrace. /// b. If not, this is actually a managed exception and in this case we RoOriginateLanguageException with the msg, hresult and the IErrorInfo /// aasociated with the managed exception. This helps us to retrieve the same exception in case it comes back to native. /// 2. On win8 and for classic COM scenarios. /// a. We create IErrorInfo for the given Exception object and SetErrorInfo with the given IErrorInfo. /// </summary> /// <param name="ex"></param> [MethodImpl(MethodImplOptions.NoInlining)] public static int GetHRForExceptionWinRT(Exception ex) { #if ENABLE_WINRT return ExceptionHelpers.GetHRForExceptionWithErrorPropogationNoThrow(ex, true); #else // TODO : ExceptionHelpers should be platform specific , move it to // seperate source files return 0; //return Marshal.GetHRForException(ex); #endif } [MethodImpl(MethodImplOptions.NoInlining)] public static int GetHRForException(Exception ex) { #if ENABLE_WINRT return ExceptionHelpers.GetHRForExceptionWithErrorPropogationNoThrow(ex, false); #else return ex.HResult; #endif } [MethodImpl(MethodImplOptions.NoInlining)] public static void ThrowOnExternalCallFailed(int hr, System.RuntimeTypeHandle typeHnd) { bool isWinRTScenario #if ENABLE_WINRT = typeHnd.IsSupportIInspectable(); #else = false; #endif throw McgMarshal.GetExceptionForHR(hr, isWinRTScenario); } /// <summary> /// This method returns a new Exception object given the HR value. /// </summary> /// <param name="hr"></param> /// <param name="isWinRTScenario"></param> public static Exception GetExceptionForHR(int hr, bool isWinRTScenario) { #if ENABLE_WINRT return ExceptionHelpers.GetExceptionForHRInternalNoThrow(hr, isWinRTScenario, !isWinRTScenario); #elif CORECLR return Marshal.GetExceptionForHR(hr); #else return new COMException(hr.ToString(), hr); #endif } #region Shared templates #if ENABLE_MIN_WINRT public static void CleanupNative<T>(IntPtr pObject) { if (typeof(T) == typeof(string)) { global::System.Runtime.InteropServices.McgMarshal.FreeHString(pObject); } else { global::System.Runtime.InteropServices.McgMarshal.ComSafeRelease(pObject); } } #endif #endregion #if ENABLE_MIN_WINRT [MethodImpl(MethodImplOptions.NoInlining)] public static unsafe IntPtr ActivateInstance(string typeName) { __ComObject target = McgMarshal.GetActivationFactory( typeName, InternalTypes.IActivationFactoryInternal ); IntPtr pIActivationFactoryInternalItf = target.QueryInterface_NoAddRef_Internal( InternalTypes.IActivationFactoryInternal, /* cacheOnly= */ false, /* throwOnQueryInterfaceFailure= */ true ); __com_IActivationFactoryInternal* pIActivationFactoryInternal = (__com_IActivationFactoryInternal*)pIActivationFactoryInternalItf; IntPtr pResult = default(IntPtr); int hr = CalliIntrinsics.StdCall<int>( pIActivationFactoryInternal->pVtable->pfnActivateInstance, pIActivationFactoryInternal, &pResult ); GC.KeepAlive(target); if (hr < 0) { throw McgMarshal.GetExceptionForHR(hr, /* isWinRTScenario = */ true); } return pResult; } #endif [MethodImpl(MethodImplOptions.NoInlining)] public static IntPtr GetInterface( __ComObject obj, RuntimeTypeHandle typeHnd) { return obj.QueryInterface_NoAddRef_Internal( typeHnd); } [MethodImplAttribute(MethodImplOptions.NoInlining)] public static object GetDynamicAdapter(__ComObject obj, RuntimeTypeHandle requestedType, RuntimeTypeHandle existingType) { return obj.GetDynamicAdapter(requestedType, existingType); } [MethodImplAttribute(MethodImplOptions.NoInlining)] public static object GetDynamicAdapter(__ComObject obj, RuntimeTypeHandle requestedType) { return obj.GetDynamicAdapter(requestedType, default(RuntimeTypeHandle)); } #region "PInvoke Delegate" public static IntPtr GetStubForPInvokeDelegate(RuntimeTypeHandle delegateType, Delegate dele) { #if CORECLR throw new NotSupportedException(); #else return PInvokeMarshal.GetStubForPInvokeDelegate(dele); #endif } /// <summary> /// Retrieve the corresponding P/invoke instance from the stub /// </summary> public static Delegate GetPInvokeDelegateForStub(IntPtr pStub, RuntimeTypeHandle delegateType) { #if CORECLR if (pStub == IntPtr.Zero) return null; McgPInvokeDelegateData pInvokeDelegateData; if (!McgModuleManager.GetPInvokeDelegateData(delegateType, out pInvokeDelegateData)) { return null; } return CalliIntrinsics.Call__Delegate( pInvokeDelegateData.ForwardDelegateCreationStub, pStub ); #else return PInvokeMarshal.GetPInvokeDelegateForStub(pStub, delegateType); #endif } /// <summary> /// Retrieves the function pointer for the current open static delegate that is being called /// </summary> public static IntPtr GetCurrentCalleeOpenStaticDelegateFunctionPointer() { #if RHTESTCL || CORECLR || CORERT throw new NotSupportedException(); #else return PInvokeMarshal.GetCurrentCalleeOpenStaticDelegateFunctionPointer(); #endif } /// <summary> /// Retrieves the current delegate that is being called /// </summary> public static T GetCurrentCalleeDelegate<T>() where T : class // constraint can't be System.Delegate { #if RHTESTCL || CORECLR || CORERT throw new NotSupportedException(); #else return PInvokeMarshal.GetCurrentCalleeDelegate<T>(); #endif } #endregion } /// <summary> /// McgMarshal helpers exposed to be used by MCG /// </summary> public static partial class McgMarshal { public static object UnboxIfBoxed(object target) { return UnboxIfBoxed(target, null); } public static object UnboxIfBoxed(object target, string className) { // // If it is a managed wrapper, unbox it // object unboxedObj = McgComHelpers.UnboxManagedWrapperIfBoxed(target); if (unboxedObj != target) return unboxedObj; if (className == null) className = System.Runtime.InteropServices.McgComHelpers.GetRuntimeClassName(target); if (!String.IsNullOrEmpty(className)) { IntPtr unboxingStub; if (McgModuleManager.TryGetUnboxingStub(className, out unboxingStub)) { object ret = CalliIntrinsics.Call<object>(unboxingStub, target); if (ret != null) return ret; } #if ENABLE_WINRT else if(McgModuleManager.UseDynamicInterop) { BoxingInterfaceKind boxingInterfaceKind; RuntimeTypeHandle genericTypeArgument; if (DynamicInteropBoxingHelpers.TryGetBoxingArgumentTypeHandleFromString(className, out boxingInterfaceKind, out genericTypeArgument)) { Debug.Assert(target is __ComObject); return DynamicInteropBoxingHelpers.Unboxing(boxingInterfaceKind, genericTypeArgument, target); } } #endif } return null; } internal static object BoxIfBoxable(object target) { return BoxIfBoxable(target, default(RuntimeTypeHandle)); } /// <summary> /// Given a boxed value type, return a wrapper supports the IReference interface /// </summary> /// <param name="typeHandleOverride"> /// You might want to specify how to box this. For example, any object[] derived array could /// potentially boxed as object[] if everything else fails /// </param> internal static object BoxIfBoxable(object target, RuntimeTypeHandle typeHandleOverride) { RuntimeTypeHandle expectedTypeHandle = typeHandleOverride; if (expectedTypeHandle.Equals(default(RuntimeTypeHandle))) expectedTypeHandle = target.GetTypeHandle(); RuntimeTypeHandle boxingWrapperType; IntPtr boxingStub; int boxingPropertyType; if (McgModuleManager.TryGetBoxingWrapperType(expectedTypeHandle, target, out boxingWrapperType, out boxingPropertyType, out boxingStub)) { if (!boxingWrapperType.IsInvalid()) { // // IReference<T> / IReferenceArray<T> / IKeyValuePair<K, V> // All these scenarios require a managed wrapper // // Allocate the object object refImplType = InteropExtensions.RuntimeNewObject(boxingWrapperType); if (boxingPropertyType >= 0) { Debug.Assert(refImplType is BoxedValue); BoxedValue boxed = InteropExtensions.UncheckedCast<BoxedValue>(refImplType); // Call ReferenceImpl<T>.Initialize(obj, type); boxed.Initialize(target, boxingPropertyType); } else { Debug.Assert(refImplType is BoxedKeyValuePair); BoxedKeyValuePair boxed = InteropExtensions.UncheckedCast<BoxedKeyValuePair>(refImplType); // IKeyValuePair<,>, call CLRIKeyValuePairImpl<K,V>.Initialize(object obj); // IKeyValuePair<,>[], call CLRIKeyValuePairArrayImpl<K,V>.Initialize(object obj); refImplType = boxed.Initialize(target); } return refImplType; } else { // // General boxing for projected types, such as System.Uri // return CalliIntrinsics.Call<object>(boxingStub, target); } } return null; } } }
// Copyright (c) The Avalonia Project. All rights reserved. // Licensed under the MIT license. See licence.md file in the project root for full license information. using System; using System.Globalization; using System.Linq; namespace Avalonia { /// <summary> /// Defines a size. /// </summary> public struct Size { /// <summary> /// A size representing infinity. /// </summary> public static readonly Size Infinity = new Size(double.PositiveInfinity, double.PositiveInfinity); /// <summary> /// A size representing zero /// </summary> public static readonly Size Empty = new Size(0, 0); /// <summary> /// The width. /// </summary> private readonly double _width; /// <summary> /// The height. /// </summary> private readonly double _height; /// <summary> /// Initializes a new instance of the <see cref="Size"/> structure. /// </summary> /// <param name="width">The width.</param> /// <param name="height">The height.</param> public Size(double width, double height) { _width = width; _height = height; } /// <summary> /// Gets the aspect ratio of the size. /// </summary> public double AspectRatio => _width / _height; /// <summary> /// Gets the width. /// </summary> public double Width => _width; /// <summary> /// Gets the height. /// </summary> public double Height => _height; /// <summary> /// Checks for equality between two <see cref="Size"/>s. /// </summary> /// <param name="left">The first size.</param> /// <param name="right">The second size.</param> /// <returns>True if the sizes are equal; otherwise false.</returns> public static bool operator ==(Size left, Size right) { return left._width == right._width && left._height == right._height; } /// <summary> /// Checks for unequality between two <see cref="Size"/>s. /// </summary> /// <param name="left">The first size.</param> /// <param name="right">The second size.</param> /// <returns>True if the sizes are unequal; otherwise false.</returns> public static bool operator !=(Size left, Size right) { return !(left == right); } /// <summary> /// Scales a size. /// </summary> /// <param name="size">The size</param> /// <param name="scale">The scaling factor.</param> /// <returns>The scaled size.</returns> public static Size operator *(Size size, Vector scale) { return new Size(size._width * scale.X, size._height * scale.Y); } /// <summary> /// Scales a size. /// </summary> /// <param name="size">The size</param> /// <param name="scale">The scaling factor.</param> /// <returns>The scaled size.</returns> public static Size operator /(Size size, Vector scale) { return new Size(size._width / scale.X, size._height / scale.Y); } /// <summary> /// Divides a size by another size to produce a scaling factor. /// </summary> /// <param name="left">The first size</param> /// <param name="right">The second size.</param> /// <returns>The scaled size.</returns> public static Vector operator /(Size left, Size right) { return new Vector(left._width / right._width, left._height / right._height); } /// <summary> /// Scales a size. /// </summary> /// <param name="size">The size</param> /// <param name="scale">The scaling factor.</param> /// <returns>The scaled size.</returns> public static Size operator *(Size size, double scale) { return new Size(size._width * scale, size._height * scale); } /// <summary> /// Scales a size. /// </summary> /// <param name="size">The size</param> /// <param name="scale">The scaling factor.</param> /// <returns>The scaled size.</returns> public static Size operator /(Size size, double scale) { return new Size(size._width / scale, size._height / scale); } public static Size operator +(Size size, Size toAdd) { return new Size(size._width + toAdd._width, size._height + toAdd._height); } public static Size operator -(Size size, Size toSubstract) { return new Size(size._width - toSubstract._width, size._height - toSubstract._height); } /// <summary> /// Parses a <see cref="Size"/> string. /// </summary> /// <param name="s">The string.</param> /// <param name="culture">The current culture.</param> /// <returns>The <see cref="Size"/>.</returns> public static Size Parse(string s, CultureInfo culture) { var parts = s.Split(new[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries) .Select(x => x.Trim()) .ToList(); if (parts.Count == 2) { return new Size(double.Parse(parts[0], culture), double.Parse(parts[1], culture)); } else { throw new FormatException("Invalid Size."); } } /// <summary> /// Constrains the size. /// </summary> /// <param name="constraint">The size to constrain to.</param> /// <returns>The constrained size.</returns> public Size Constrain(Size constraint) { return new Size( Math.Min(_width, constraint._width), Math.Min(_height, constraint._height)); } /// <summary> /// Deflates the size by a <see cref="Thickness"/>. /// </summary> /// <param name="thickness">The thickness.</param> /// <returns>The deflated size.</returns> /// <remarks>The deflated size cannot be less than 0.</remarks> public Size Deflate(Thickness thickness) { return new Size( Math.Max(0, _width - thickness.Left - thickness.Right), Math.Max(0, _height - thickness.Top - thickness.Bottom)); } /// <summary> /// Checks for equality between a size and an object. /// </summary> /// <param name="obj">The object.</param> /// <returns> /// True if <paramref name="obj"/> is a size that equals the current size. /// </returns> public override bool Equals(object obj) { if (obj is Size) { var other = (Size)obj; return Width == other.Width && Height == other.Height; } return false; } /// <summary> /// Returns a hash code for a <see cref="Size"/>. /// </summary> /// <returns>The hash code.</returns> public override int GetHashCode() { unchecked { int hash = 17; hash = (hash * 23) + Width.GetHashCode(); hash = (hash * 23) + Height.GetHashCode(); return hash; } } /// <summary> /// Inflates the size by a <see cref="Thickness"/>. /// </summary> /// <param name="thickness">The thickness.</param> /// <returns>The inflated size.</returns> public Size Inflate(Thickness thickness) { return new Size( _width + thickness.Left + thickness.Right, _height + thickness.Top + thickness.Bottom); } /// <summary> /// Returns a new <see cref="Size"/> with the same height and the specified width. /// </summary> /// <param name="width">The width.</param> /// <returns>The new <see cref="Size"/>.</returns> public Size WithWidth(double width) { return new Size(width, _height); } /// <summary> /// Returns a new <see cref="Size"/> with the same width and the specified height. /// </summary> /// <param name="height">The height.</param> /// <returns>The new <see cref="Size"/>.</returns> public Size WithHeight(double height) { return new Size(_width, height); } /// <summary> /// Returns the string representation of the size. /// </summary> /// <returns>The string representation of the size.</returns> public override string ToString() { return string.Format(CultureInfo.InvariantCulture, "{0}, {1}", _width, _height); } } }
using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using umbraco.presentation.nodeFactory; using System.Collections.Generic; namespace TABS_UserControls.usercontrols { public partial class navigation : System.Web.UI.UserControl { protected void Page_Load(object sender, EventArgs e) { Node currentpage = Node.GetCurrent(); string currentPageShort = currentpage.Name.ToLower().Replace(" ", "").Replace("&", "").Replace(".", "").Replace("'", "").Replace("-", ""); string[] for_home = { "", "Home", "RSS Feed", "Sitemap", "Legal" }; string[] for_students = { "", "For Students", "Student Lounge", "The Basics", "5 Good Reasons", "Old School", "Famous Grads", "History - For Students", "Myths 101" }; string[] for_parents = { "", "For Parents", "The Fundamentals", "The Advantages", "The Tradition", "Distinguished Alumni", "History - For Parents", "Common Misconceptions" }; string[] find_school = { "", "Find a School", "School Browser", "Guided Search", "Guided Search Result", "A-Z School List", "School Profile", "Explore Your Options", "Campus Visits", "Asia Fairs", "School Fairs", "Summer Programs", "Contact Schools", "Request a Free Directory", "Find an Expert" }; string[] how_apply = { "", "How to Apply", "Application", "Testing", "Expenses & Aid", "After You Apply", "International Applicants", "U.S Visas", "International Visas", "Administration Application Form" }; string[] for_schools = { "", "For Schools", "Professional Development", "Forum", "Marketing", "Become a Member", "TABS Library", "Job Board", "Sponsors", "Educational Consultants", "Join TABS", "Conferences", "Workshops", "Asia Fairs", "Whats New", "Research and Stats", "News", "Articles and Op-Eds", "Bookstore", "Helpful Links", "Directors Cut", "Job Board", "Sponsors", "Educational Consultants", "TABS Calendar For Schools", "TABS Calendar Detail", "Workshop", "eNewsletter", "Student Parent Form", "Student Parent Confirm", "Add Job", "Job Listing", "Account Info", "Users", "Users Add", "My Profile", "Post Edit Jobs", "Edit School Profile", "Find a Colleague", "TAB Library", "Proposal Conference", "Proposal Thankyou", "Asia Fair" }; string[] about_tabs = { "", "About Tabs", "About Us", "Corporate Sponsors", "About Sponsorship", "Friends In Education", "Articles", "Contact Us", "Our Mission", "Board of Trustees", "TABS Staff", "TABS Calendar", "TABS Calendar Event", "eNewsletter TABS", "Press Room", "Reports & Finances", "Careers with TABS", "Sponsorships", "Send A Idea" }; if (Array.IndexOf(for_home, currentpage.Name) > 0) liHome.Attributes.Add("class", "current"); if (Array.IndexOf(for_students, currentpage.Name) > 0) { liStudents.Attributes.Add("class", "current"); string[] for_students_sub = { "", "Famous Grads", "History - For Students" }; if (Array.IndexOf(for_students_sub, currentpage.Name) > 0) { AddClassToElement("oldschool", "highlight"); } } if (Array.IndexOf(for_parents, currentpage.Name) > 0) { liParents.Attributes.Add("class", "current"); string[] for_parents_sub = { "", "Distinguished Alumni", "History - For Parents" }; if (Array.IndexOf(for_parents_sub, currentpage.Name) > 0) { AddClassToElement("thetradition", "highlight"); } } if (Array.IndexOf(find_school, currentpage.Name) > 0) { liFindSchool.Attributes.Add("class", "current"); string[] find_school_sub = { "", "School Browser", "Guided Search", "A-Z School List" }; if (Array.IndexOf(find_school_sub, currentpage.Name) > 0) { AddClassToElement("findaschool", "highlight"); } string [] find_school_sub2 = { "", "Campus Visits", "School Fairs", "Contact Schools", "Request a Free Directory" }; if (Array.IndexOf(find_school_sub2, currentpage.Name) > 0) { AddClassToElement("exploreyouroptions", "highlight"); } } if (Array.IndexOf(how_apply, currentpage.Name) > 0) { liApply.Attributes.Add("class", "current"); string[] how_apply_sub = { "", "U.S Visas", "International Visas" }; if (Array.IndexOf(how_apply_sub, currentpage.Name) > 0) { AddClassToElement("internationalapplicants", "highlight"); } } if (Array.IndexOf(for_schools, currentpage.Name) > 0) { liSchools.Attributes.Add("class", "current"); string[] for_schools_sub = { "", "Join TABS" }; if (Array.IndexOf(for_schools_sub, currentpage.Name) > 0) { AddClassToElement("overview", "highlight"); } string[] for_schools_sub2 = { "", "TABS Calendar For Schools", "Conferences", "Workshops" }; if (Array.IndexOf(for_schools_sub2, currentpage.Name) > 0) { AddClassToElement("professionaldevelopment", "highlight"); } string[] for_schools_sub3 = { "", "Asia Fairs", "Whats New" }; if (Array.IndexOf(for_schools_sub3, currentpage.Name) > 0) { AddClassToElement("marketing", "highlight"); } string[] for_schools_sub4 = { "", "News", "Research and Stats", "Articles and Op-Eds", "eNewsletter", "Bookstore", "Helpful Links", "Directors Cut" }; if (Array.IndexOf(for_schools_sub4, currentpage.Name) > 0) { AddClassToElement("tabslibrary", "highlight"); } } if (Array.IndexOf(about_tabs, currentpage.Name) > 0) { liTABS.Attributes.Add("class", "current"); string[] about_tabs_sub = { "", "Our Mission", "Board of Trustees", "TABS Staff", "TABS Calendar", "eNewsletter TABS", "Reports & Finances", "Careers with TABS" }; if (Array.IndexOf(about_tabs_sub, currentpage.Name) > 0) { AddClassToElement("abouttabs", "highlight"); } string[] about_tabs_sub2 = { "", "Corporate Sponsors", "About Sponsorship"}; if (Array.IndexOf(about_tabs_sub2, currentpage.Name) > 0) { AddClassToElement("corporatesponsors", "highlight"); } string[] about_tabs_sub3 = { "", "Friends In Eduction" }; if (Array.IndexOf(about_tabs_sub3, currentpage.Name) > 0) { AddClassToElement("friendsineducation", "highlight"); } string[] about_tabs_sub4 = { "", "Become a Member" }; if (Array.IndexOf(about_tabs_sub4, currentpage.Name) > 0) { AddClassToElement("contactus", "highlight"); } } if (Request.Url.AbsoluteUri.Contains("marketing/asia-fairs.aspx")) { liSchools.Attributes.Add("class", "current"); AddClassToElement("marketing", "highlight"); liFindSchool.Attributes.Remove("class"); liexploreyouroptions.Attributes.Remove("class"); } if (Request.Url.AbsoluteUri.Contains("explore-your-options/asia-fairs")) { liFindSchool.Attributes.Add("class", "current"); AddClassToElement("exploreyouroptions", "highlight"); liSchools.Attributes.Remove("class"); limarketing.Attributes.Remove("class"); } // Add the sub nav's highlight color AddClassToElement(currentPageShort, "highlight"); if (Session["userid"] == null) { sendidea.Visible = false; liMEMBER.Visible = false; } } private void AddClassToElement(string elementName, string className) { HtmlContainerControl li = (HtmlContainerControl)FindControlRecursive(Page, "li" + elementName.ToLower()); if (li != null) { li.Attributes.Add("class", "highlight"); } } private Control FindControlRecursive(Control root, string id) { try { if (root.ID.Equals(id)) { return root; } } catch (Exception) { } foreach (Control c in root.Controls) { Control t = FindControlRecursive(c, id); if (t != null) { return t; } } return null; } } }
//--------------------------------------------------------------------------- // // File: GestureRecognizer.cs // // Description: // The implementation of GestureRecognizer class // // Features: // // History: // 01/14/2005 waynezen: Created // // Copyright (C) 2001 by Microsoft Corporation. All rights reserved. // //--------------------------------------------------------------------------- using MS.Utility; using MS.Internal.Ink.GestureRecognition; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.InteropServices; using System; using System.Security; using System.Security.Permissions; using SecurityHelper=MS.Internal.SecurityHelper; using SR=MS.Internal.PresentationCore.SR; using SRID=MS.Internal.PresentationCore.SRID; namespace System.Windows.Ink { /// <summary> /// Performs gesture recognition on a StrokeCollection /// </summary> /// <remarks> /// No finalizer is defined because all unmanaged resources are wrapped in SafeHandle's /// NOTE: this class provides the public APIs that call into unmanaged code to perform /// recognition. There are two inputs that are accepted: /// ApplicationGesture[] and StrokeCollection. /// This class verifies the ApplicationGesture[] and StrokeCollection / Stroke are validated. /// </remarks> public sealed class GestureRecognizer : DependencyObject, IDisposable { //------------------------------------------------------------------------------- // // Constructors // //------------------------------------------------------------------------------- #region Constructors /// <summary> /// The default constructor which enables all the application gestures. /// </summary> public GestureRecognizer() : this ( new ApplicationGesture[] { ApplicationGesture.AllGestures } ) { } /// <summary> /// The constructor which take an array of the enabled application gestures. /// </summary> /// <param name="enabledApplicationGestures"></param> public GestureRecognizer(IEnumerable<ApplicationGesture> enabledApplicationGestures) { _nativeRecognizer = NativeRecognizer.CreateInstance(); if (_nativeRecognizer == null) { //just verify the gestures NativeRecognizer.GetApplicationGestureArrayAndVerify(enabledApplicationGestures); } else { // // we only set this if _nativeRecognizer is non null // (available) because there is no way to use this state // otherwise. // SetEnabledGestures(enabledApplicationGestures); } } #endregion Constructors //------------------------------------------------------------------------------- // // Public Methods // //------------------------------------------------------------------------------- #region Public Methods /// <summary> /// Set the enabled gestures /// </summary> /// <param name="applicationGestures"></param> /// <remarks> /// We wrap the System.Runtime.InteropServices.COMException with a more specific one /// /// Do wrap specific exceptions in a more descriptive exception when appropriate. /// public Int32 GetInt(Int32[] array, Int32 index){ /// try{ /// return array[index]; /// }catch(IndexOutOfRangeException e){ /// throw new ArgumentOutOfRangeException( /// Parameter index is out of range.); /// } /// } /// /// </remarks> public void SetEnabledGestures(IEnumerable<ApplicationGesture> applicationGestures) { VerifyAccess(); VerifyDisposed(); VerifyRecognizerAvailable(); //don't verfify the gestures, NativeRecognizer.SetEnabledGestures does it // since it is the TAS boundary // // we don't wrap the COM exceptions generated from the Recognizer // with our own exception // ApplicationGesture[] enabledGestures = _nativeRecognizer.SetEnabledGestures(applicationGestures); //only update the state when SetEnabledGestures succeeds (since it verifies the array) _enabledGestures = enabledGestures; } /// <summary> /// Get the enabled gestures /// </summary> /// <returns></returns> public ReadOnlyCollection<ApplicationGesture> GetEnabledGestures() { VerifyAccess(); VerifyDisposed(); VerifyRecognizerAvailable(); //can be null if the call to SetEnabledGestures failed if (_enabledGestures == null) { _enabledGestures = new ApplicationGesture[] { }; } return new ReadOnlyCollection<ApplicationGesture>(_enabledGestures); } /// <summary> /// Performs gesture recognition on the StrokeCollection if a gesture recognizer /// is present and installed on the system. If not, this method throws an InvalidOperationException. /// To determine if this method will throw an exception, only call this method if /// the RecognizerAvailable property returns true. /// /// </summary> /// <param name="strokes">The StrokeCollection to perform gesture recognition on</param> /// <returns></returns> /// <remarks>Callers must have UnmanagedCode permission to call this API.</remarks> /// <SecurityNote> /// Critical: Calls SecurityCritical method RecognizeImpl /// /// PublicOK: We demand UnmanagedCode before proceeding and /// UnmanagedCode is the only permission we assert. /// </SecurityNote> [SecurityCritical] public ReadOnlyCollection<GestureRecognitionResult> Recognize(StrokeCollection strokes) { // // due to possible exploits in the Tablet PC Gesture recognizer's Recognize method, // we demand unmanaged code. // SecurityHelper.DemandUnmanagedCode(); return RecognizeImpl(strokes); } /// <summary> /// Performs gesture recognition on the StrokeCollection if a gesture recognizer /// is present and installed on the system. If not, this method throws an InvalidOperationException. /// To determine if this method will throw an exception, only call this method if /// the RecognizerAvailable property returns true. /// </summary> /// <param name="strokes">The StrokeCollection to perform gesture recognition on</param> /// <returns></returns> /// <SecurityNote> /// Critical: Calls a SecurityCritical method RecognizeImpl. /// /// FriendAccess is allowed so the critical method InkCanvas.RaiseGestureOrStrokeCollected /// can use this method /// </SecurityNote> // Built into Core, also used by Framework. [SecurityCritical] internal ReadOnlyCollection<GestureRecognitionResult> CriticalRecognize(StrokeCollection strokes) { return RecognizeImpl(strokes); } /// <summary> /// Performs gesture recognition on the StrokeCollection if a gesture recognizer /// is present and installed on the system. /// </summary> /// <param name="strokes">The StrokeCollection to perform gesture recognition on</param> /// <returns></returns> /// <SecurityNote> /// Critical: Calls SecurityCritical method NativeRecognizer.Recognize /// </SecurityNote> [SecurityCritical] private ReadOnlyCollection<GestureRecognitionResult> RecognizeImpl(StrokeCollection strokes) { if (strokes == null) { throw new ArgumentNullException("strokes"); // Null is not allowed as the argument value } if (strokes.Count > 2) { throw new ArgumentException(SR.Get(SRID.StrokeCollectionCountTooBig), "strokes"); } VerifyAccess(); VerifyDisposed(); VerifyRecognizerAvailable(); return new ReadOnlyCollection<GestureRecognitionResult>(_nativeRecognizer.Recognize(strokes)); } #endregion Public Methods //------------------------------------------------------------------------------- // // Public Properties // //------------------------------------------------------------------------------- #region Public Properties /// <summary> /// Indicates if a GestureRecognizer is present and installed on the system. /// </summary> public bool IsRecognizerAvailable { get { VerifyAccess(); VerifyDisposed(); if (_nativeRecognizer == null) { return false; } return true; } } #endregion Public Properties //------------------------------------------------------------------------------- // // IDisposable // //------------------------------------------------------------------------------- #region IDisposable /// <summary> /// Dispose this GestureRecognizer /// </summary> public void Dispose() { VerifyAccess(); // A simple pattern of the dispose implementation. // There is no finalizer since the SafeHandle in the NativeRecognizer will release the context properly. if ( _disposed ) { return; } // NTRAID-WINDOWSBUG#1102945-WAYNEZEN, // Since the constructor might create a null _nativeRecognizer, // here we have to make sure we do have some thing to dispose. // Otherwise just no-op. if ( _nativeRecognizer != null ) { _nativeRecognizer.Dispose(); _nativeRecognizer = null; } _disposed = true; } #endregion IDisposable //------------------------------------------------------------------------------- // // Private Methods // //------------------------------------------------------------------------------- #region Private Methods //verify that there is a recognizer available, throw if not private void VerifyRecognizerAvailable() { if (_nativeRecognizer == null) { throw new InvalidOperationException(SR.Get(SRID.GestureRecognizerNotAvailable)); } } // Verify whether this object has been disposed. private void VerifyDisposed() { if ( _disposed ) { throw new ObjectDisposedException("GestureRecognizer"); } } #endregion Private Methods //------------------------------------------------------------------------------- // // Private Fields // //------------------------------------------------------------------------------- #region Private Fields private ApplicationGesture[] _enabledGestures; private NativeRecognizer _nativeRecognizer; private bool _disposed; #endregion Private Fields } }