context
stringlengths
2.52k
185k
gt
stringclasses
1 value
/* * Copyright (c) Contributors, http://aurora-sim.org/, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Aurora-Sim Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Threading; using System.Timers; using Nini.Config; using log4net.Core; using Timer = System.Timers.Timer; namespace Aurora.Framework { /// <summary> /// This is a special class designed to take over control of the command console prompt of /// the server instance to allow for the input and output to the server to be redirected /// by an external application, in this case a GUI based application on Windows. /// </summary> public class GUIConsole : BaseConsole, ICommandConsole { public bool m_isPrompting; public int m_lastSetPromptOption; public List<string> m_promptOptions = new List<string>(); public bool HasProcessedCurrentCommand { get; set; } public virtual void Initialize(IConfigSource source, ISimulationBase baseOpenSim) { if (source.Configs["Console"] == null || source.Configs["Console"].GetString("Console", String.Empty) != Name) { return; } baseOpenSim.ApplicationRegistry.RegisterModuleInterface<ICommandConsole>(this); MainConsole.Instance = this; m_Commands.AddCommand("help", "help", "Get a general command list", Help); MainConsole.Instance.Info("[GUIConsole] initialised."); } public void Help(string[] cmd) { List<string> help = m_Commands.GetHelp(cmd); foreach (string s in help) Output(s, "Severe"); } /// <summary> /// Display a command prompt on the console and wait for user input /// </summary> public void Prompt() { // Set this culture for the thread // to en-US to avoid number parsing issues Culture.SetCurrentCulture(); /*string line = */ReadLine(m_defaultPrompt + "# ", true, true); // result.AsyncWaitHandle.WaitOne(-1); // if (line != String.Empty && line.Replace(" ", "") != String.Empty) //If there is a space, its fine // { // MainConsole.Instance.Info("[GUICONSOLE] Invalid command"); // } } public void RunCommand(string cmd) { string[] parts = Parser.Parse(cmd); m_Commands.Resolve(parts); Output(""); } /// <summary> /// Method that reads a line of text from the user. /// </summary> /// <param name = "p"></param> /// <param name = "isCommand"></param> /// <param name = "e"></param> /// <returns></returns> public virtual string ReadLine(string p, bool isCommand, bool e) { string oldDefaultPrompt = m_defaultPrompt; m_defaultPrompt = p; // System.Console.Write("{0}", p); string cmdinput = Console.ReadLine(); // while (cmdinput.Equals(null)) // { // ; // } if (isCommand) { string[] cmd = m_Commands.Resolve(Parser.Parse(cmdinput)); if (cmd.Length != 0) { int i; for (i = 0; i < cmd.Length; i++) { if (cmd[i].Contains(" ")) cmd[i] = "\"" + cmd[i] + "\""; } return String.Empty; } } m_defaultPrompt = oldDefaultPrompt; return cmdinput; } public string Prompt(string p) { m_isPrompting = true; string line = ReadLine(String.Format("{0}: ", p), false, true); m_isPrompting = false; return line; } public string Prompt(string p, string def) { m_isPrompting = true; string ret = ReadLine(String.Format("{0} [{1}]: ", p, def), false, true); if (ret == String.Empty) ret = def; m_isPrompting = false; return ret; } public string Prompt(string p, string def, List<char> excludedCharacters) { m_isPrompting = true; bool itisdone = false; string ret = String.Empty; while (!itisdone) { itisdone = true; ret = Prompt(p, def); if (ret == String.Empty) { ret = def; } else { string ret1 = ret; #if (!ISWIN) foreach (char c in excludedCharacters) { if (ret1.Contains(c.ToString())) { Console.WriteLine("The character \"" + c.ToString() + "\" is not permitted."); itisdone = false; } } #else foreach (char c in excludedCharacters.Where(c => ret1.Contains(c.ToString()))) { Console.WriteLine("The character \"" + c.ToString() + "\" is not permitted."); itisdone = false; } #endif } } m_isPrompting = false; return ret; } // Displays a command prompt and returns a default value, user may only enter 1 of 2 options public string Prompt(string prompt, string defaultresponse, List<string> options) { m_isPrompting = true; m_promptOptions = new List<string>(options); bool itisdone = false; #if (!ISWIN) string optstr = String.Empty; foreach (string option in options) optstr = optstr + (" " + option); #else string optstr = options.Aggregate(String.Empty, (current, s) => current + (" " + s)); #endif string temp = Prompt(prompt, defaultresponse); while (itisdone == false) { if (options.Contains(temp)) { itisdone = true; } else { Console.WriteLine("Valid options are" + optstr); temp = Prompt(prompt, defaultresponse); } } m_isPrompting = false; m_promptOptions.Clear(); return temp; } // Displays a prompt and waits for the user to enter a string, then returns that string // (Done with no echo and suitable for passwords) public string PasswordPrompt(string p) { m_isPrompting = true; string line = ReadLine(p + ": ", false, false); m_isPrompting = false; return line; } public virtual void Output(string text, string level) { Output(text); } public virtual void Output(string text) { Log(text); Console.WriteLine(text); } public virtual void Log(string text) { } public virtual void LockOutput() { } public virtual void UnlockOutput() { } public virtual bool CompareLogLevels(string a, string b) { Level aa = GetLevel(a); Level bb = GetLevel(b); return aa <= bb; } public Level GetLevel(string lvl) { switch (lvl.ToLower()) { case "alert": return Level.Alert; case "all": return Level.All; case "critical": return Level.Critical; case "debug": return Level.Debug; case "emergency": return Level.Emergency; case "error": return Level.Error; case "fatal": return Level.Fatal; case "fine": return Level.Fine; case "finer": return Level.Finer; case "finest": return Level.Finest; case "info": return Level.Info; case "notice": return Level.Notice; case "off": return Level.Off; case "severe": return Level.Severe; case "trace": return Level.Trace; case "verbose": return Level.Verbose; case "warn": return Level.Warn; } return null; } /// <summary> /// The default prompt text. /// </summary> public virtual string DefaultPrompt { set { m_defaultPrompt = value; } get { return m_defaultPrompt; } } protected string m_defaultPrompt; public virtual string Name { get { return "GUIConsole"; } } public Commands m_Commands = new Commands(); public Commands Commands { get { return m_Commands; } set { m_Commands = value; } } public IScene ConsoleScene { get { return m_ConsoleScene; } set { m_ConsoleScene = value; } } public IScene m_ConsoleScene; public void Dispose() { } public void EndConsoleProcessing() { Processing = false; } public bool Processing = true; private delegate void PromptEvent(); private IAsyncResult result; private PromptEvent action; private readonly Object m_consoleLock = new Object(); private bool m_calledEndInvoke; /// <summary> /// Starts the prompt for the console. This will never stop until the region is closed. /// </summary> public void ReadConsole() { WaitHandle[] wHandles = new WaitHandle[1]; if (result != null) { wHandles[0] = result.AsyncWaitHandle; } Timer t = new Timer {Interval = 0.5}; t.Elapsed += t_Elapsed; t.Start(); while (true) { if (!Processing) { throw new Exception("Restart"); } lock (m_consoleLock) { if (action == null) { action = Prompt; result = action.BeginInvoke(null, null); m_calledEndInvoke = false; } try { if ((!result.IsCompleted) && (!result.AsyncWaitHandle.WaitOne(5000, false) || !result.IsCompleted)) { } else if (action != null && !result.CompletedSynchronously && !m_calledEndInvoke) { m_calledEndInvoke = true; action.EndInvoke(result); action = null; result = null; } } catch (Exception ex) { //Eat the exception and go on Output("[Console]: Failed to execute command: " + ex); action = null; result = null; } } } } private void t_Elapsed(object sender, ElapsedEventArgs e) { //Tell the GUI that we are still here and it needs to keep checking Console.Write((char) 0); } } }
using System; using UnityEngine; using System.Collections.Generic; using System.Linq; namespace Projeny.Internal { public enum PmViewStates { ReleasesAndPackages, PackagesAndProject, Project, ProjectAndVisualStudio, } [Serializable] public class PmModel { public event Action PluginItemsChanged = delegate { }; public event Action AssetItemsChanged = delegate { }; public event Action PackageFoldersChanged = delegate { }; public event Action ReleasesChanged = delegate { }; public event Action VsProjectsChanged = delegate { }; public event Action PackageFolderIndexChanged = delegate { }; [SerializeField] List<PackageFolderInfo> _folderInfos = new List<PackageFolderInfo>(); [SerializeField] List<ReleaseInfo> _releases = new List<ReleaseInfo>(); [SerializeField] List<string> _assetItems = new List<string>(); [SerializeField] List<string> _pluginItems = new List<string>(); [SerializeField] List<string> _vsProjects = new List<string>(); [SerializeField] List<string> _savedPackageFolders = new List<string>(); [SerializeField] List<string> _prebuilt = new List<string>(); [SerializeField] Dictionary<string, string> _solutionFolders = new Dictionary<string, string>(); [SerializeField] string _projectSettingsPath; [SerializeField] string _unityPackagesPath; [SerializeField] int _packageFolderIndex; //Is not used in Unity-plugin, but must be propagated so it is kept in config [SerializeField] public List<string> ProjectPlatforms = new List<string>(); public PmModel() { } public int PackageFolderIndex { get { return _packageFolderIndex; } set { if (_packageFolderIndex != value) { _packageFolderIndex = value; PackageFolderIndexChanged(); } } } public string ProjectSettingsPath { get { return _projectSettingsPath; } set { _projectSettingsPath = value; } } public string UnityPackagesPath { get { return _unityPackagesPath; } set { _unityPackagesPath = value; } } public IEnumerable<ReleaseInfo> Releases { get { return _releases; } } public IEnumerable<string> AssetItems { get { return _assetItems; } } public IEnumerable<PackageInfo> AllPackages { get { return _folderInfos.SelectMany(x => x.Packages); } } public IEnumerable<string> PluginItems { get { return _pluginItems; } } public IEnumerable<PackageFolderInfo> PackageFolders { get { return _folderInfos; } } public IEnumerable<string> PrebuiltProjects { get { return _prebuilt; } } public IEnumerable<string> VsProjects { get { return _vsProjects; } } public IEnumerable<KeyValuePair<string, string>> VsSolutionFolders { get { return _solutionFolders; } } public IEnumerable<string> SavedPackageFolders { get { return _savedPackageFolders; } } public string GetCurrentPackageFolderPath() { var folderPath = TryGetCurrentPackageFolderPath(); Assert.IsNotNull(folderPath, "Could not find current package root folder path"); return folderPath; } public string TryGetCurrentPackageFolderPath() { if (_packageFolderIndex >= 0 && _packageFolderIndex < _folderInfos.Count) { return _folderInfos[_packageFolderIndex].Path; } return null; } public IEnumerable<PackageInfo> GetCurrentFolderPackages() { if (_packageFolderIndex >= 0 && _packageFolderIndex < _folderInfos.Count) { return _folderInfos[_packageFolderIndex].Packages; } return Enumerable.Empty<PackageInfo>(); } public void ClearSavedPackageFolders() { _savedPackageFolders.Clear(); } public void ClearSolutionFolders() { _solutionFolders.Clear(); } public void ClearPrebuiltProjects() { _prebuilt.Clear(); } public void ClearSolutionProjects() { _vsProjects.Clear(); VsProjectsChanged(); } public void ClearAssetItems() { _assetItems.Clear(); AssetItemsChanged(); } public void RemoveVsProject(string name) { _vsProjects.RemoveWithConfirm(name); VsProjectsChanged(); } public void RemoveAssetItem(string name) { _assetItems.RemoveWithConfirm(name); AssetItemsChanged(); } public bool HasAssetItem(string name) { return _assetItems.Contains(name); } public bool HasVsProject(string name) { return _vsProjects.Contains(name); } public bool HasPluginItem(string name) { return _pluginItems.Contains(name); } public void RemovePluginItem(string name) { _pluginItems.RemoveWithConfirm(name); PluginItemsChanged(); } public void AddVsProject(string name) { _vsProjects.Add(name); VsProjectsChanged(); } public void AddPrebuilt(string value) { _prebuilt.Add(value); } public void AddSavedPackageFolder(string value) { _savedPackageFolders.Add(value); } public void AddSolutionFolder(string key, string value) { _solutionFolders.Add(key, value); } public void AddAssetItem(string name) { _assetItems.Add(name); AssetItemsChanged(); } public void AddPluginItem(string name) { _pluginItems.Add(name); PluginItemsChanged(); } public void ClearPluginItems() { _pluginItems.Clear(); PluginItemsChanged(); } public void SetPackageFolders(List<PackageFolderInfo> folderInfos) { _folderInfos.Clear(); _folderInfos.AddRange(folderInfos); PackageFoldersChanged(); } public void SetReleases(List<ReleaseInfo> releases) { Assert.That(releases.All(x => !string.IsNullOrEmpty(x.Name))); _releases.Clear(); _releases.AddRange(releases); ReleasesChanged(); } public bool IsPackageAddedToProject(string name) { return _assetItems.Concat(_pluginItems).Contains(name); } public bool IsReleaseInstalled(ReleaseInfo info) { return AllPackages .Any(x => x.InstallInfo != null && x.InstallInfo.ReleaseInfo != null && x.InstallInfo.ReleaseInfo.Id == info.Id && x.InstallInfo.ReleaseInfo.VersionCode == info.VersionCode); } } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================================= ** ** Class: ITypeInfo ** ** ** Purpose: ITypeInfo interface definition. ** ** =============================================================================*/ namespace System.Runtime.InteropServices.ComTypes { using System; [Serializable] public enum TYPEKIND { TKIND_ENUM = 0, TKIND_RECORD = TKIND_ENUM + 1, TKIND_MODULE = TKIND_RECORD + 1, TKIND_INTERFACE = TKIND_MODULE + 1, TKIND_DISPATCH = TKIND_INTERFACE + 1, TKIND_COCLASS = TKIND_DISPATCH + 1, TKIND_ALIAS = TKIND_COCLASS + 1, TKIND_UNION = TKIND_ALIAS + 1, TKIND_MAX = TKIND_UNION + 1 } [Serializable] [Flags()] public enum TYPEFLAGS : short { TYPEFLAG_FAPPOBJECT = 0x1, TYPEFLAG_FCANCREATE = 0x2, TYPEFLAG_FLICENSED = 0x4, TYPEFLAG_FPREDECLID = 0x8, TYPEFLAG_FHIDDEN = 0x10, TYPEFLAG_FCONTROL = 0x20, TYPEFLAG_FDUAL = 0x40, TYPEFLAG_FNONEXTENSIBLE = 0x80, TYPEFLAG_FOLEAUTOMATION = 0x100, TYPEFLAG_FRESTRICTED = 0x200, TYPEFLAG_FAGGREGATABLE = 0x400, TYPEFLAG_FREPLACEABLE = 0x800, TYPEFLAG_FDISPATCHABLE = 0x1000, TYPEFLAG_FREVERSEBIND = 0x2000, TYPEFLAG_FPROXY = 0x4000 } [Serializable] [Flags()] public enum IMPLTYPEFLAGS { IMPLTYPEFLAG_FDEFAULT = 0x1, IMPLTYPEFLAG_FSOURCE = 0x2, IMPLTYPEFLAG_FRESTRICTED = 0x4, IMPLTYPEFLAG_FDEFAULTVTABLE = 0x8, } [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)] public struct TYPEATTR { // Constant used with the memid fields. public const int MEMBER_ID_NIL = unchecked((int)0xFFFFFFFF); // Actual fields of the TypeAttr struct. public Guid guid; public Int32 lcid; public Int32 dwReserved; public Int32 memidConstructor; public Int32 memidDestructor; public IntPtr lpstrSchema; public Int32 cbSizeInstance; public TYPEKIND typekind; public Int16 cFuncs; public Int16 cVars; public Int16 cImplTypes; public Int16 cbSizeVft; public Int16 cbAlignment; public TYPEFLAGS wTypeFlags; public Int16 wMajorVerNum; public Int16 wMinorVerNum; public TYPEDESC tdescAlias; public IDLDESC idldescType; } [StructLayout(LayoutKind.Sequential)] public struct FUNCDESC { public int memid; //MEMBERID memid; public IntPtr lprgscode; // /* [size_is(cScodes)] */ SCODE RPC_FAR *lprgscode; public IntPtr lprgelemdescParam; // /* [size_is(cParams)] */ ELEMDESC __RPC_FAR *lprgelemdescParam; public FUNCKIND funckind; //FUNCKIND funckind; public INVOKEKIND invkind; //INVOKEKIND invkind; public CALLCONV callconv; //CALLCONV callconv; public Int16 cParams; //short cParams; public Int16 cParamsOpt; //short cParamsOpt; public Int16 oVft; //short oVft; public Int16 cScodes; //short cScodes; public ELEMDESC elemdescFunc; //ELEMDESC elemdescFunc; public Int16 wFuncFlags; //WORD wFuncFlags; } [Serializable] [Flags()] public enum IDLFLAG : short { IDLFLAG_NONE = PARAMFLAG.PARAMFLAG_NONE, IDLFLAG_FIN = PARAMFLAG.PARAMFLAG_FIN, IDLFLAG_FOUT = PARAMFLAG.PARAMFLAG_FOUT, IDLFLAG_FLCID = PARAMFLAG.PARAMFLAG_FLCID, IDLFLAG_FRETVAL = PARAMFLAG.PARAMFLAG_FRETVAL } [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)] public struct IDLDESC { public IntPtr dwReserved; public IDLFLAG wIDLFlags; } [Serializable] [Flags()] public enum PARAMFLAG :short { PARAMFLAG_NONE = 0, PARAMFLAG_FIN = 0x1, PARAMFLAG_FOUT = 0x2, PARAMFLAG_FLCID = 0x4, PARAMFLAG_FRETVAL = 0x8, PARAMFLAG_FOPT = 0x10, PARAMFLAG_FHASDEFAULT = 0x20, PARAMFLAG_FHASCUSTDATA = 0x40 } [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)] public struct PARAMDESC { public IntPtr lpVarValue; public PARAMFLAG wParamFlags; } [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)] public struct TYPEDESC { public IntPtr lpValue; public Int16 vt; } [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)] public struct ELEMDESC { public TYPEDESC tdesc; [System.Runtime.InteropServices.StructLayout(LayoutKind.Explicit, CharSet=CharSet.Unicode)] public struct DESCUNION { [FieldOffset(0)] public IDLDESC idldesc; [FieldOffset(0)] public PARAMDESC paramdesc; }; public DESCUNION desc; } [Serializable] public enum VARKIND : int { VAR_PERINSTANCE = 0x0, VAR_STATIC = 0x1, VAR_CONST = 0x2, VAR_DISPATCH = 0x3 } [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)] public struct VARDESC { public int memid; public String lpstrSchema; [System.Runtime.InteropServices.StructLayout(LayoutKind.Explicit, CharSet=CharSet.Unicode)] public struct DESCUNION { [FieldOffset(0)] public int oInst; [FieldOffset(0)] public IntPtr lpvarValue; }; public DESCUNION desc; public ELEMDESC elemdescVar; public short wVarFlags; public VARKIND varkind; } [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)] public struct DISPPARAMS { public IntPtr rgvarg; public IntPtr rgdispidNamedArgs; public int cArgs; public int cNamedArgs; } [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)] public struct EXCEPINFO { public Int16 wCode; public Int16 wReserved; [MarshalAs(UnmanagedType.BStr)] public String bstrSource; [MarshalAs(UnmanagedType.BStr)] public String bstrDescription; [MarshalAs(UnmanagedType.BStr)] public String bstrHelpFile; public int dwHelpContext; public IntPtr pvReserved; public IntPtr pfnDeferredFillIn; public Int32 scode; } [Serializable] public enum FUNCKIND : int { FUNC_VIRTUAL = 0, FUNC_PUREVIRTUAL = 1, FUNC_NONVIRTUAL = 2, FUNC_STATIC = 3, FUNC_DISPATCH = 4 } [Serializable] [Flags] public enum INVOKEKIND : int { INVOKE_FUNC = 0x1, INVOKE_PROPERTYGET = 0x2, INVOKE_PROPERTYPUT = 0x4, INVOKE_PROPERTYPUTREF = 0x8 } [Serializable] public enum CALLCONV : int { CC_CDECL =1, CC_MSCPASCAL=2, CC_PASCAL =CC_MSCPASCAL, CC_MACPASCAL=3, CC_STDCALL =4, CC_RESERVED =5, CC_SYSCALL =6, CC_MPWCDECL =7, CC_MPWPASCAL=8, CC_MAX =9 } [Serializable] [Flags()] public enum FUNCFLAGS : short { FUNCFLAG_FRESTRICTED= 0x1, FUNCFLAG_FSOURCE = 0x2, FUNCFLAG_FBINDABLE = 0x4, FUNCFLAG_FREQUESTEDIT = 0x8, FUNCFLAG_FDISPLAYBIND = 0x10, FUNCFLAG_FDEFAULTBIND = 0x20, FUNCFLAG_FHIDDEN = 0x40, FUNCFLAG_FUSESGETLASTERROR= 0x80, FUNCFLAG_FDEFAULTCOLLELEM= 0x100, FUNCFLAG_FUIDEFAULT = 0x200, FUNCFLAG_FNONBROWSABLE = 0x400, FUNCFLAG_FREPLACEABLE = 0x800, FUNCFLAG_FIMMEDIATEBIND = 0x1000 } [Serializable] [Flags()] public enum VARFLAGS : short { VARFLAG_FREADONLY =0x1, VARFLAG_FSOURCE =0x2, VARFLAG_FBINDABLE =0x4, VARFLAG_FREQUESTEDIT =0x8, VARFLAG_FDISPLAYBIND =0x10, VARFLAG_FDEFAULTBIND =0x20, VARFLAG_FHIDDEN =0x40, VARFLAG_FRESTRICTED =0x80, VARFLAG_FDEFAULTCOLLELEM =0x100, VARFLAG_FUIDEFAULT =0x200, VARFLAG_FNONBROWSABLE =0x400, VARFLAG_FREPLACEABLE =0x800, VARFLAG_FIMMEDIATEBIND =0x1000 } [Guid("00020401-0000-0000-C000-000000000046")] [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] [ComImport] public interface ITypeInfo { void GetTypeAttr(out IntPtr ppTypeAttr); void GetTypeComp(out ITypeComp ppTComp); void GetFuncDesc(int index, out IntPtr ppFuncDesc); void GetVarDesc(int index, out IntPtr ppVarDesc); void GetNames(int memid, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2), Out] String[] rgBstrNames, int cMaxNames, out int pcNames); void GetRefTypeOfImplType(int index, out int href); void GetImplTypeFlags(int index, out IMPLTYPEFLAGS pImplTypeFlags); void GetIDsOfNames([MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.LPWStr, SizeParamIndex = 1), In] String[] rgszNames, int cNames, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1), Out] int[] pMemId); void Invoke([MarshalAs(UnmanagedType.IUnknown)] Object pvInstance, int memid, Int16 wFlags, ref DISPPARAMS pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, out int puArgErr); void GetDocumentation(int index, out String strName, out String strDocString, out int dwHelpContext, out String strHelpFile); void GetDllEntry(int memid, INVOKEKIND invKind, IntPtr pBstrDllName, IntPtr pBstrName, IntPtr pwOrdinal); void GetRefTypeInfo(int hRef, out ITypeInfo ppTI); void AddressOfMember(int memid, INVOKEKIND invKind, out IntPtr ppv); void CreateInstance([MarshalAs(UnmanagedType.IUnknown)] Object pUnkOuter, [In] ref Guid riid, [MarshalAs(UnmanagedType.IUnknown), Out] out Object ppvObj); void GetMops(int memid, out String pBstrMops); void GetContainingTypeLib(out ITypeLib ppTLB, out int pIndex); [PreserveSig] void ReleaseTypeAttr(IntPtr pTypeAttr); [PreserveSig] void ReleaseFuncDesc(IntPtr pFuncDesc); [PreserveSig] void ReleaseVarDesc(IntPtr pVarDesc); } }
// 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.Threading.Tasks; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations { public class ReturnKeywordRecommenderTests : KeywordRecommenderTests { [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAtRoot_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterClass_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"class C { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterGlobalStatement_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"System.Console.WriteLine(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterGlobalVariableDeclaration_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"int i = 0; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInUsingAlias() { await VerifyAbsenceAsync( @"using Foo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestEmptyStatement() { await VerifyKeywordAsync(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestBeforeStatement() { await VerifyKeywordAsync(AddInsideMethod( @"$$ return true;")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterStatement() { await VerifyKeywordAsync(AddInsideMethod( @"return true; $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterBlock() { await VerifyKeywordAsync(AddInsideMethod( @"if (true) { } $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterReturn() { await VerifyAbsenceAsync(AddInsideMethod( @"return $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterYield() { await VerifyKeywordAsync(AddInsideMethod( @"yield $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInClass() { await VerifyAbsenceAsync(@"class C { $$ }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInAttributeInsideClass() { await VerifyKeywordAsync( @"class C { [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInAttributeAfterAttributeInsideClass() { await VerifyKeywordAsync( @"class C { [Foo] [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInAttributeAfterMethod() { await VerifyKeywordAsync( @"class C { void Foo() { } [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInAttributeAfterProperty() { await VerifyKeywordAsync( @"class C { int Foo { get; } [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInAttributeAfterField() { await VerifyKeywordAsync( @"class C { int Foo; [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInAttributeAfterEvent() { await VerifyKeywordAsync( @"class C { event Action<int> Foo; [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInOuterAttribute() { await VerifyAbsenceAsync(SourceCodeKind.Regular, @"[$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInOuterAttributeScripting() { await VerifyKeywordAsync(SourceCodeKind.Script, @"[$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInParameterAttribute() { await VerifyAbsenceAsync( @"class C { void Foo([$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInPropertyAttribute() { await VerifyAbsenceAsync( @"class C { int Foo { [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInEventAttribute() { await VerifyAbsenceAsync( @"class C { event Action<int> Foo { [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInClassReturnParameters() { await VerifyAbsenceAsync( @"class C<[$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInDelegateReturnParameters() { await VerifyAbsenceAsync( @"delegate void D<[$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInMethodReturnParameters() { await VerifyAbsenceAsync( @"class C { void M<[$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInInterface() { await VerifyKeywordAsync( @"interface I { [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInStruct() { await VerifyKeywordAsync( @"struct S { [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInEnum() { await VerifyAbsenceAsync( @"enum E { [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterElse() { await VerifyKeywordAsync(AddInsideMethod( @"if (foo) { } else $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterElseClause() { await VerifyKeywordAsync(AddInsideMethod( @"if (foo) { } else { } $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterFixed() { await VerifyKeywordAsync(AddInsideMethod( @"fixed (byte* pResult = result) { } $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterSwitch() { await VerifyKeywordAsync(AddInsideMethod( @"switch (foo) { } $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterCatch() { await VerifyKeywordAsync(AddInsideMethod( @"try { } catch { } $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterFinally() { await VerifyKeywordAsync(AddInsideMethod( @"try { } finally { } $$")); } } }
// Licensed to Elasticsearch B.V under one or more agreements. // Elasticsearch B.V licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; using System.Globalization; using System.Linq; using System.Text.Json; using System.Text.Json.Serialization; using Elastic.Transport; namespace Elastic.Clients.Elasticsearch { [JsonConverter(typeof(RoutingConverter))] [DebuggerDisplay("{" + nameof(DebugDisplay) + ",nq}")] public class Routing : IEquatable<Routing>, IUrlParameter { private static readonly char[] Separator = {','}; internal Routing(Func<object> documentGetter) { Tag = 0; DocumentGetter = documentGetter; } public Routing(string routing) { Tag = 1; StringValue = routing; } public Routing(long routing) { Tag = 2; LongValue = routing; } public Routing(object document) { Tag = 4; Document = document; } internal object Document { get; } internal Func<object> DocumentGetter { get; } internal long? LongValue { get; } internal string StringOrLongValue => StringValue ?? LongValue?.ToString(CultureInfo.InvariantCulture); internal string StringValue { get; } internal int Tag { get; } private string DebugDisplay => StringOrLongValue ?? "Routing from instance typeof: " + Document?.GetType().Name; private static int TypeHashCode { get; } = typeof(Routing).GetHashCode(); public bool Equals(Routing other) { if (other == null) return false; if (Tag == other.Tag) { switch (Tag) { case 0: var t = DocumentGetter(); var o = other.DocumentGetter(); return t?.Equals(o) ?? false; case 4: return Document?.Equals(other.Document) ?? false; default: return StringEquals(StringOrLongValue, other.StringOrLongValue); } } else if (Tag + other.Tag == 3) return StringEquals(StringOrLongValue, other.StringOrLongValue); else return false; } string IUrlParameter.GetString(ITransportConfiguration settings) { var ElasticsearchClientSettings = settings as IElasticsearchClientSettings; return GetString(ElasticsearchClientSettings); } public override string ToString() => DebugDisplay; public static implicit operator Routing(string routing) => routing.IsNullOrEmptyCommaSeparatedList(out _) ? null : new Routing(routing); public static implicit operator Routing(string[] routing) => routing.IsEmpty() ? null : new Routing(string.Join(",", routing)); public static implicit operator Routing(long routing) => new(routing); public static implicit operator Routing(Guid routing) => new(routing.ToString("D")); /// <summary> Use the inferred routing from <paramref name="document" /> </summary> public static Routing From<T>(T document) where T : class => new(document); internal string GetString(IElasticsearchClientSettings settings) { string value = null; if (DocumentGetter != null) { var doc = DocumentGetter(); value = settings.Inferrer.Routing(doc); } else if (Document != null) value = settings.Inferrer.Routing(Document); return value ?? StringOrLongValue; } public static bool operator ==(Routing left, Routing right) => Equals(left, right); public static bool operator !=(Routing left, Routing right) => !Equals(left, right); private static bool StringEquals(string left, string right) { if (left == null && right == null) return true; else if (left == null || right == null) return false; if (!left.Contains(",") || !right.Contains(",")) return left == right; var l1 = left.Split(Separator, StringSplitOptions.RemoveEmptyEntries).Select(v => v.Trim()).ToList(); var l2 = right.Split(Separator, StringSplitOptions.RemoveEmptyEntries).Select(v => v.Trim()).ToList(); if (l1.Count != l2.Count) return false; return l1.Count == l2.Count && !l1.Except(l2).Any(); } public override bool Equals(object obj) { switch (obj) { case Routing r: return Equals(r); case string s: return Equals(s); case int l: return Equals(l); case long l: return Equals(l); case Guid g: return Equals(g); } return Equals(new Routing(obj)); } public override int GetHashCode() { unchecked { var result = TypeHashCode; result = (result * 397) ^ (StringValue?.GetHashCode() ?? 0); result = (result * 397) ^ (LongValue?.GetHashCode() ?? 0); result = (result * 397) ^ (DocumentGetter?.GetHashCode() ?? 0); result = (result * 397) ^ (Document?.GetHashCode() ?? 0); return result; } } //internal bool ShouldSerialize(IJsonFormatterResolver formatterResolver) //{ // var inferrer = formatterResolver.GetConnectionSettings().Inferrer; // var resolved = inferrer.Resolve(this); // return !resolved.IsNullOrEmpty(); //} } internal sealed class RoutingConverter : JsonConverter<Routing> { private readonly IElasticsearchClientSettings _settings; public RoutingConverter(IElasticsearchClientSettings settings) => _settings = settings; public override Routing? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) => reader.TokenType == JsonTokenType.Number ? new Routing(reader.GetInt64()) : new Routing(reader.GetString()); public override void Write(Utf8JsonWriter writer, Routing value, JsonSerializerOptions options) { if (value is null) { writer.WriteNullValue(); return; } if (value.Document is not null) { var documentId = _settings.Inferrer.Routing(value.Document.GetType(), value.Document); if (documentId is null) { writer.WriteNullValue(); return; } writer.WriteStringValue(documentId); } else if (value.DocumentGetter is not null) { var doc = value.DocumentGetter(); var documentId = _settings.Inferrer.Routing(doc.GetType(), doc); writer.WriteStringValue(documentId); } else if (value.LongValue.HasValue) { writer.WriteNumberValue(value.LongValue.Value); } else { writer.WriteStringValue(value.StringValue); } } } }
// Copyright (c) DotSpatial Team. All rights reserved. // Licensed under the MIT license. See License.txt file in the project root for full license information. using System.Collections.Generic; using System.IO; using System.Linq; using GeoAPI.Geometries; using NetTopologySuite.Algorithm; namespace DotSpatial.Data { /// <summary> /// A shapefile class that handles the special case where the data is made up of polygons /// </summary> public class PolygonShapefile : Shapefile { /// <summary> /// Initializes a new instance of the <see cref="PolygonShapefile"/> class for in-ram handling only. /// </summary> public PolygonShapefile() : base(FeatureType.Polygon, ShapeType.Polygon) { } /// <summary> /// Initializes a new instance of the <see cref="PolygonShapefile"/> class that is loaded from the supplied fileName. /// </summary> /// <param name="fileName">The string fileName of the polygon shapefile to load</param> public PolygonShapefile(string fileName) : this() { Open(fileName, null); } /// <summary> /// Opens a shapefile. /// </summary> /// <param name="fileName">The string fileName of the polygon shapefile to load.</param> /// <param name="progressHandler">Any valid implementation of the DotSpatial.Data.IProgressHandler</param> public void Open(string fileName, IProgressHandler progressHandler) { if (!File.Exists(fileName)) return; Filename = fileName; IndexMode = true; Header = new ShapefileHeader(Filename); switch (Header.ShapeType) { case ShapeType.PolygonM: CoordinateType = CoordinateType.M; break; case ShapeType.PolygonZ: CoordinateType = CoordinateType.Z; break; default: CoordinateType = CoordinateType.Regular; break; } Extent = Header.ToExtent(); Name = Path.GetFileNameWithoutExtension(fileName); Attributes.Open(Filename); LineShapefile.FillLines(Filename, progressHandler, this, FeatureType.Polygon); ReadProjection(); } // X Y Poly Lines: Total Length = 28 Bytes // --------------------------------------------------------- // Position Value Type Number Byte Order // --------------------------------------------------------- // Byte 0 Record Number Integer 1 Big // Byte 4 Content Length Integer 1 Big // Byte 8 Shape Type 3 Integer 1 Little // Byte 12 Xmin Double 1 Little // Byte 20 Ymin Double 1 Little // Byte 28 Xmax Double 1 Little // Byte 36 Ymax Double 1 Little // Byte 44 NumParts Integer 1 Little // Byte 48 NumPoints Integer 1 Little // Byte 52 Parts Integer NumParts Little // Byte X Points Point NumPoints Little // X = 52 + 4 * NumParts // X Y M Poly Lines: Total Length = 34 Bytes // --------------------------------------------------------- // Position Value Type Number Byte Order // --------------------------------------------------------- // Byte 0 Record Number Integer 1 Big // Byte 4 Content Length Integer 1 Big // Byte 8 Shape Type 23 Integer 1 Little // Byte 12 Box Double 4 Little // Byte 44 NumParts Integer 1 Little // Byte 48 NumPoints Integer 1 Little // Byte 52 Parts Integer NumParts Little // Byte X Points Point NumPoints Little // Byte Y* Mmin Double 1 Little // Byte Y + 8* Mmax Double 1 Little // Byte Y + 16* Marray Double NumPoints Little // X = 52 + (4 * NumParts) // Y = X + (16 * NumPoints) // * = optional // X Y Z M Poly Lines: Total Length = 44 Bytes // --------------------------------------------------------- // Position Value Type Number Byte Order // --------------------------------------------------------- // Byte 0 Record Number Integer 1 Big // Byte 4 Content Length Integer 1 Big // Byte 8 Shape Type 13 Integer 1 Little // Byte 12 Box Double 4 Little // Byte 44 NumParts Integer 1 Little // Byte 48 NumPoints Integer 1 Little // Byte 52 Parts Integer NumParts Little // Byte X Points Point NumPoints Little // Byte Y Zmin Double 1 Little // Byte Y + 8 Zmax Double 1 Little // Byte Y + 16 Zarray Double NumPoints Little // Byte Z* Mmin Double 1 Little // Byte Z+8* Mmax Double 1 Little // Byte Z+16* Marray Double NumPoints Little // X = 52 + (4 * NumParts) // Y = X + (16 * NumPoints) // Z = Y + 16 + (8 * NumPoints) // * = optional /// <summary> /// Gets the specified feature by constructing it from the vertices, rather /// than requiring that all the features be created. (which takes up a lot of memory). /// </summary> /// <param name="index">The integer index</param> /// <returns>The polygon feature belonging to the given index.</returns> public override IFeature GetFeature(int index) { IFeature f; if (!IndexMode) { f = Features[index]; } else { f = GetPolygon(index); f.DataRow = AttributesPopulated ? DataTable.Rows[index] : Attributes.SupplyPageOfData(index, 1).Rows[0]; } return f; } /// <inheritdoc /> protected override void SetHeaderShapeType() { if (CoordinateType == CoordinateType.Regular) Header.ShapeType = ShapeType.Polygon; else if (CoordinateType == CoordinateType.M) Header.ShapeType = ShapeType.PolygonM; else if (CoordinateType == CoordinateType.Z) Header.ShapeType = ShapeType.PolygonZ; } /// <inheritdoc /> protected override StreamLengthPair PopulateShpAndShxStreams(Stream shpStream, Stream shxStream, bool indexed) { if (indexed) return LineShapefile.PopulateStreamsIndexed(shpStream, shxStream, this, ShapeType.PolygonZ, ShapeType.PolygonM, true); return LineShapefile.PopulateStreamsNotIndexed(shpStream, shxStream, this, AddPoints, ShapeType.PolygonZ, ShapeType.PolygonM, true); } /// <summary> /// Adds the parts and points of the given feature to the given parts and points lists. /// </summary> /// <param name="parts">List of parts, where the features parts get added.</param> /// <param name="points">List of points, where the features points get added.</param> /// <param name="f">Feature, whose parts and points get added to the lists.</param> private static void AddPoints(List<int> parts, List<Coordinate> points, IFeature f) { for (int iPart = 0; iPart < f.Geometry.NumGeometries; iPart++) { parts.Add(points.Count); IPolygon pg = f.Geometry.GetGeometryN(iPart) as IPolygon; if (pg == null) continue; ILineString bl = pg.Shell; // Exterior rings need to be clockwise IEnumerable<Coordinate> coords = CGAlgorithms.IsCCW(bl.Coordinates) ? bl.Coordinates.Reverse() : bl.Coordinates; points.AddRange(coords); foreach (var hole in pg.Holes) { parts.Add(points.Count); // Interior rings need to be counter-clockwise IEnumerable<Coordinate> holeCoords = CGAlgorithms.IsCCW(hole.Coordinates) ? hole.Coordinates : hole.Coordinates.Reverse(); points.AddRange(holeCoords); } } } } }
using System; using System.Configuration; using System.Data; using System.Data.OracleClient; using System.Collections; namespace PetShop.DBUtility { /// <summary> /// A helper class used to execute queries against an Oracle database /// </summary> public abstract class OracleHelper { // Read the connection strings from the configuration file public static readonly string ConnectionStringLocalTransaction = ConfigurationManager.ConnectionStrings["OraConnString1"].ConnectionString; public static readonly string ConnectionStringInventoryDistributedTransaction = ConfigurationManager.ConnectionStrings["OraConnString2"].ConnectionString; public static readonly string ConnectionStringOrderDistributedTransaction = ConfigurationManager.ConnectionStrings["OraConnString3"].ConnectionString; public static readonly string ConnectionStringProfile = ConfigurationManager.ConnectionStrings["OraProfileConnString"].ConnectionString; public static readonly string ConnectionStringMembership = ConfigurationManager.ConnectionStrings["OraMembershipConnString"].ConnectionString; //Create a hashtable for the parameter cached private static Hashtable parmCache = Hashtable.Synchronized(new Hashtable()); /// <summary> /// Execute a database query which does not include a select /// </summary> /// <param name="connString">Connection string to database</param> /// <param name="cmdType">Command type either stored procedure or SQL</param> /// <param name="cmdText">Acutall SQL Command</param> /// <param name="commandParameters">Parameters to bind to the command</param> /// <returns></returns> public static int ExecuteNonQuery(string connectionString, CommandType cmdType, string cmdText, params OracleParameter[] commandParameters) { // Create a new Oracle command OracleCommand cmd = new OracleCommand(); //Create a connection using (OracleConnection connection = new OracleConnection(connectionString)) { //Prepare the command PrepareCommand(cmd, connection, null, cmdType, cmdText, commandParameters); //Execute the command int val = cmd.ExecuteNonQuery(); cmd.Parameters.Clear(); return val; } } /// <summary> /// Execute an OracleCommand (that returns no resultset) against an existing database transaction /// using the provided parameters. /// </summary> /// <remarks> /// e.g.: /// int result = ExecuteNonQuery(trans, CommandType.StoredProcedure, "PublishOrders", new OracleParameter(":prodid", 24)); /// </remarks> /// <param name="trans">an existing database transaction</param> /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param> /// <param name="commandText">the stored procedure name or PL/SQL command</param> /// <param name="commandParameters">an array of OracleParamters used to execute the command</param> /// <returns>an int representing the number of rows affected by the command</returns> public static int ExecuteNonQuery(OracleTransaction trans, CommandType cmdType, string cmdText, params OracleParameter[] commandParameters) { OracleCommand cmd = new OracleCommand(); PrepareCommand(cmd, trans.Connection, trans, cmdType, cmdText, commandParameters); int val = cmd.ExecuteNonQuery(); cmd.Parameters.Clear(); return val; } /// <summary> /// Execute an OracleCommand (that returns no resultset) against an existing database connection /// using the provided parameters. /// </summary> /// <remarks> /// e.g.: /// int result = ExecuteNonQuery(connString, CommandType.StoredProcedure, "PublishOrders", new OracleParameter(":prodid", 24)); /// </remarks> /// <param name="conn">an existing database connection</param> /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param> /// <param name="commandText">the stored procedure name or PL/SQL command</param> /// <param name="commandParameters">an array of OracleParamters used to execute the command</param> /// <returns>an int representing the number of rows affected by the command</returns> public static int ExecuteNonQuery(OracleConnection connection, CommandType cmdType, string cmdText, params OracleParameter[] commandParameters) { OracleCommand cmd = new OracleCommand(); PrepareCommand(cmd, connection, null, cmdType, cmdText, commandParameters); int val = cmd.ExecuteNonQuery(); cmd.Parameters.Clear(); return val; } /// <summary> /// Execute a select query that will return a result set /// </summary> /// <param name="connString">Connection string</param> //// <param name="commandType">the CommandType (stored procedure, text, etc.)</param> /// <param name="commandText">the stored procedure name or PL/SQL command</param> /// <param name="commandParameters">an array of OracleParamters used to execute the command</param> /// <returns></returns> public static OracleDataReader ExecuteReader(string connectionString, CommandType cmdType, string cmdText, params OracleParameter[] commandParameters) { //Create the command and connection OracleCommand cmd = new OracleCommand(); OracleConnection conn = new OracleConnection(connectionString); try { //Prepare the command to execute PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParameters); //Execute the query, stating that the connection should close when the resulting datareader has been read OracleDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection); cmd.Parameters.Clear(); return rdr; } catch { //If an error occurs close the connection as the reader will not be used and we expect it to close the connection conn.Close(); throw; } } /// <summary> /// Execute an OracleCommand that returns the first column of the first record against the database specified in the connection string /// using the provided parameters. /// </summary> /// <remarks> /// e.g.: /// Object obj = ExecuteScalar(connString, CommandType.StoredProcedure, "PublishOrders", new OracleParameter(":prodid", 24)); /// </remarks> /// <param name="connectionString">a valid connection string for a SqlConnection</param> /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param> /// <param name="commandText">the stored procedure name or PL/SQL command</param> /// <param name="commandParameters">an array of OracleParamters used to execute the command</param> /// <returns>An object that should be converted to the expected type using Convert.To{Type}</returns> public static object ExecuteScalar(string connectionString, CommandType cmdType, string cmdText, params OracleParameter[] commandParameters) { OracleCommand cmd = new OracleCommand(); using (OracleConnection conn = new OracleConnection(connectionString)) { PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParameters); object val = cmd.ExecuteScalar(); cmd.Parameters.Clear(); return val; } } /// <summary> /// Execute a OracleCommand (that returns a 1x1 resultset) against the specified SqlTransaction /// using the provided parameters. /// </summary> /// <param name="transaction">A valid SqlTransaction</param> /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param> /// <param name="commandText">The stored procedure name or PL/SQL command</param> /// <param name="commandParameters">An array of OracleParamters used to execute the command</param> /// <returns>An object containing the value in the 1x1 resultset generated by the command</returns> public static object ExecuteScalar(OracleTransaction transaction, CommandType commandType, string commandText, params OracleParameter[] commandParameters) { if(transaction == null) throw new ArgumentNullException("transaction"); if(transaction != null && transaction.Connection == null) throw new ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction"); // Create a command and prepare it for execution OracleCommand cmd = new OracleCommand(); PrepareCommand(cmd, transaction.Connection, transaction, commandType, commandText, commandParameters); // Execute the command & return the results object retval = cmd.ExecuteScalar(); // Detach the SqlParameters from the command object, so they can be used again cmd.Parameters.Clear(); return retval; } /// <summary> /// Execute an OracleCommand that returns the first column of the first record against an existing database connection /// using the provided parameters. /// </summary> /// <remarks> /// e.g.: /// Object obj = ExecuteScalar(conn, CommandType.StoredProcedure, "PublishOrders", new OracleParameter(":prodid", 24)); /// </remarks> /// <param name="conn">an existing database connection</param> /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param> /// <param name="commandText">the stored procedure name or PL/SQL command</param> /// <param name="commandParameters">an array of OracleParamters used to execute the command</param> /// <returns>An object that should be converted to the expected type using Convert.To{Type}</returns> public static object ExecuteScalar(OracleConnection connectionString, CommandType cmdType, string cmdText, params OracleParameter[] commandParameters) { OracleCommand cmd = new OracleCommand(); PrepareCommand(cmd, connectionString, null, cmdType, cmdText, commandParameters); object val = cmd.ExecuteScalar(); cmd.Parameters.Clear(); return val; } /// <summary> /// Add a set of parameters to the cached /// </summary> /// <param name="cacheKey">Key value to look up the parameters</param> /// <param name="commandParameters">Actual parameters to cached</param> public static void CacheParameters(string cacheKey, params OracleParameter[] commandParameters) { parmCache[cacheKey] = commandParameters; } /// <summary> /// Fetch parameters from the cache /// </summary> /// <param name="cacheKey">Key to look up the parameters</param> /// <returns></returns> public static OracleParameter[] GetCachedParameters(string cacheKey) { OracleParameter[] cachedParms = (OracleParameter[])parmCache[cacheKey]; if (cachedParms == null) return null; // If the parameters are in the cache OracleParameter[] clonedParms = new OracleParameter[cachedParms.Length]; // return a copy of the parameters for (int i = 0, j = cachedParms.Length; i < j; i++) clonedParms[i] = (OracleParameter)((ICloneable)cachedParms[i]).Clone(); return clonedParms; } /// <summary> /// Internal function to prepare a command for execution by the database /// </summary> /// <param name="cmd">Existing command object</param> /// <param name="conn">Database connection object</param> /// <param name="trans">Optional transaction object</param> /// <param name="cmdType">Command type, e.g. stored procedure</param> /// <param name="cmdText">Command test</param> /// <param name="commandParameters">Parameters for the command</param> private static void PrepareCommand(OracleCommand cmd, OracleConnection conn, OracleTransaction trans, CommandType cmdType, string cmdText, OracleParameter[] commandParameters) { //Open the connection if required if (conn.State != ConnectionState.Open) conn.Open(); //Set up the command cmd.Connection = conn; cmd.CommandText = cmdText; cmd.CommandType = cmdType; //Bind it to the transaction if it exists if (trans != null) cmd.Transaction = trans; // Bind the parameters passed in if (commandParameters != null) { foreach (OracleParameter parm in commandParameters) cmd.Parameters.Add(parm); } } /// <summary> /// Converter to use boolean data type with Oracle /// </summary> /// <param name="value">Value to convert</param> /// <returns></returns> public static string OraBit(bool value) { if(value) return "Y"; else return "N"; } /// <summary> /// Converter to use boolean data type with Oracle /// </summary> /// <param name="value">Value to convert</param> /// <returns></returns> public static bool OraBool(string value) { if(value.Equals("Y")) return true; else return false; } } }
// 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.Diagnostics; using System.Runtime.InteropServices.ComTypes; using Microsoft.DiaSymReader; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests { internal sealed class MockSymUnmanagedReader : ISymUnmanagedReader, ISymUnmanagedReader2, ISymUnmanagedReader3 { private readonly ImmutableDictionary<int, MethodDebugInfoBytes> _methodDebugInfoMap; public MockSymUnmanagedReader(ImmutableDictionary<int, MethodDebugInfoBytes> methodDebugInfoMap) { _methodDebugInfoMap = methodDebugInfoMap; } public int GetMethodByVersion(int methodToken, int version, out ISymUnmanagedMethod retVal) { Assert.Equal(1, version); MethodDebugInfoBytes info; if (!_methodDebugInfoMap.TryGetValue(methodToken, out info)) { retVal = null; return SymUnmanagedReaderExtensions.E_FAIL; } Assert.NotNull(info); retVal = info.Method; return SymUnmanagedReaderExtensions.S_OK; } public int GetSymAttribute(int methodToken, string name, int bufferLength, out int count, byte[] customDebugInformation) { // The EE should never be calling ISymUnmanagedReader.GetSymAttribute. // In order to account for EnC updates, it should always be calling // ISymUnmanagedReader3.GetSymAttributeByVersion instead. throw ExceptionUtilities.Unreachable; } public int GetSymAttributeByVersion(int methodToken, int version, string name, int bufferLength, out int count, byte[] customDebugInformation) { Assert.Equal(1, version); Assert.Equal("MD2", name); MethodDebugInfoBytes info; if (!_methodDebugInfoMap.TryGetValue(methodToken, out info)) { count = 0; return SymUnmanagedReaderExtensions.S_FALSE; // This is a guess. We're not consuming it, so it doesn't really matter. } Assert.NotNull(info); info.Bytes.TwoPhaseCopy(bufferLength, out count, customDebugInformation); return SymUnmanagedReaderExtensions.S_OK; } public int GetDocument(string url, Guid language, Guid languageVendor, Guid documentType, out ISymUnmanagedDocument document) { throw new NotImplementedException(); } public int GetDocuments(int bufferLength, out int count, ISymUnmanagedDocument[] documents) { throw new NotImplementedException(); } public int GetUserEntryPoint(out int methodToken) { throw new NotImplementedException(); } public int GetMethod(int methodToken, out ISymUnmanagedMethod method) { throw new NotImplementedException(); } public int GetVariables(int methodToken, int bufferLength, out int count, ISymUnmanagedVariable[] variables) { throw new NotImplementedException(); } public int GetGlobalVariables(int bufferLength, out int count, ISymUnmanagedVariable[] variables) { throw new NotImplementedException(); } public int GetMethodFromDocumentPosition(ISymUnmanagedDocument document, int line, int column, out ISymUnmanagedMethod method) { throw new NotImplementedException(); } public int GetNamespaces(int bufferLength, out int count, ISymUnmanagedNamespace[] namespaces) { throw new NotImplementedException(); } public int Initialize(object metadataImporter, string fileName, string searchPath, IStream stream) { throw new NotImplementedException(); } public int UpdateSymbolStore(string fileName, IStream stream) { throw new NotImplementedException(); } public int ReplaceSymbolStore(string fileName, IStream stream) { throw new NotImplementedException(); } public int GetSymbolStoreFileName(int bufferLength, out int count, char[] name) { throw new NotImplementedException(); } public int GetMethodsFromDocumentPosition(ISymUnmanagedDocument document, int line, int column, int bufferLength, out int count, ISymUnmanagedMethod[] methods) { throw new NotImplementedException(); } public int GetDocumentVersion(ISymUnmanagedDocument document, out int version, out bool isCurrent) { throw new NotImplementedException(); } public int GetMethodVersion(ISymUnmanagedMethod method, out int version) { throw new NotImplementedException(); } public int GetMethodByVersionPreRemap(int methodToken, int version, out ISymUnmanagedMethod method) { throw new NotImplementedException(); } public int GetSymAttributePreRemap(int methodToken, string name, int bufferLength, out int count, byte[] customDebugInformation) { throw new NotImplementedException(); } public int GetMethodsInDocument(ISymUnmanagedDocument document, int bufferLength, out int count, ISymUnmanagedMethod[] methods) { throw new NotImplementedException(); } public int GetSymAttributeByVersionPreRemap(int methodToken, int version, string name, int bufferLength, out int count, byte[] customDebugInformation) { throw new NotImplementedException(); } } internal sealed class MockSymUnmanagedMethod : ISymUnmanagedMethod { private readonly ISymUnmanagedScope _rootScope; public MockSymUnmanagedMethod(ISymUnmanagedScope rootScope) { _rootScope = rootScope; } int ISymUnmanagedMethod.GetRootScope(out ISymUnmanagedScope retVal) { retVal = _rootScope; return SymUnmanagedReaderExtensions.S_OK; } int ISymUnmanagedMethod.GetSequencePointCount(out int retVal) { retVal = 1; return SymUnmanagedReaderExtensions.S_OK; } int ISymUnmanagedMethod.GetSequencePoints(int cPoints, out int pcPoints, int[] offsets, ISymUnmanagedDocument[] documents, int[] lines, int[] columns, int[] endLines, int[] endColumns) { pcPoints = 1; offsets[0] = 0; documents[0] = null; lines[0] = 0; columns[0] = 0; endLines[0] = 0; endColumns[0] = 0; return SymUnmanagedReaderExtensions.S_OK; } int ISymUnmanagedMethod.GetNamespace(out ISymUnmanagedNamespace retVal) { throw new NotImplementedException(); } int ISymUnmanagedMethod.GetOffset(ISymUnmanagedDocument document, int line, int column, out int retVal) { throw new NotImplementedException(); } int ISymUnmanagedMethod.GetParameters(int cParams, out int pcParams, ISymUnmanagedVariable[] parms) { throw new NotImplementedException(); } int ISymUnmanagedMethod.GetRanges(ISymUnmanagedDocument document, int line, int column, int cRanges, out int pcRanges, int[] ranges) { throw new NotImplementedException(); } int ISymUnmanagedMethod.GetScopeFromOffset(int offset, out ISymUnmanagedScope retVal) { throw new NotImplementedException(); } int ISymUnmanagedMethod.GetSourceStartEnd(ISymUnmanagedDocument[] docs, int[] lines, int[] columns, out bool retVal) { throw new NotImplementedException(); } int ISymUnmanagedMethod.GetToken(out int pToken) { throw new NotImplementedException(); } } internal sealed class MockSymUnmanagedScope : ISymUnmanagedScope, ISymUnmanagedScope2 { private readonly ImmutableArray<ISymUnmanagedScope> _children; private readonly ImmutableArray<ISymUnmanagedNamespace> _namespaces; private readonly ISymUnmanagedConstant[] _constants; private readonly int _startOffset; private readonly int _endOffset; public MockSymUnmanagedScope(ImmutableArray<ISymUnmanagedScope> children, ImmutableArray<ISymUnmanagedNamespace> namespaces, ISymUnmanagedConstant[] constants = null, int startOffset = 0, int endOffset = 1) { _children = children; _namespaces = namespaces; _constants = constants ?? new ISymUnmanagedConstant[0]; _startOffset = startOffset; _endOffset = endOffset; } public int GetChildren(int numDesired, out int numRead, ISymUnmanagedScope[] buffer) { _children.TwoPhaseCopy(numDesired, out numRead, buffer); return SymUnmanagedReaderExtensions.S_OK; } public int GetNamespaces(int numDesired, out int numRead, ISymUnmanagedNamespace[] buffer) { _namespaces.TwoPhaseCopy(numDesired, out numRead, buffer); return SymUnmanagedReaderExtensions.S_OK; } public int GetStartOffset(out int pRetVal) { pRetVal = _startOffset; return SymUnmanagedReaderExtensions.S_OK; } public int GetEndOffset(out int pRetVal) { pRetVal = _endOffset; return SymUnmanagedReaderExtensions.S_OK; } public int GetLocalCount(out int pRetVal) { pRetVal = 0; return SymUnmanagedReaderExtensions.S_OK; } public int GetLocals(int cLocals, out int pcLocals, ISymUnmanagedVariable[] locals) { pcLocals = 0; return SymUnmanagedReaderExtensions.S_OK; } public int GetMethod(out ISymUnmanagedMethod pRetVal) { throw new NotImplementedException(); } public int GetParent(out ISymUnmanagedScope pRetVal) { throw new NotImplementedException(); } public int GetConstantCount(out int pRetVal) { pRetVal = _constants.Length; return SymUnmanagedReaderExtensions.S_OK; } public int GetConstants(int cConstants, out int pcConstants, ISymUnmanagedConstant[] constants) { pcConstants = _constants.Length; if (constants != null) { Array.Copy(_constants, constants, constants.Length); } return SymUnmanagedReaderExtensions.S_OK; } } internal sealed class MockSymUnmanagedNamespace : ISymUnmanagedNamespace { private readonly ImmutableArray<char> _nameChars; public MockSymUnmanagedNamespace(string name) { if (name != null) { var builder = ArrayBuilder<char>.GetInstance(); builder.AddRange(name); builder.AddRange('\0'); _nameChars = builder.ToImmutableAndFree(); } } int ISymUnmanagedNamespace.GetName(int numDesired, out int numRead, char[] buffer) { _nameChars.TwoPhaseCopy(numDesired, out numRead, buffer); return 0; } int ISymUnmanagedNamespace.GetNamespaces(int cNameSpaces, out int pcNameSpaces, ISymUnmanagedNamespace[] namespaces) { throw new NotImplementedException(); } int ISymUnmanagedNamespace.GetVariables(int cVars, out int pcVars, ISymUnmanagedVariable[] pVars) { throw new NotImplementedException(); } } internal delegate int GetSignatureDelegate(int bufferLength, out int count, byte[] signature); internal sealed class MockSymUnmanagedConstant : ISymUnmanagedConstant { private readonly string _name; private readonly object _value; private readonly GetSignatureDelegate _getSignature; public MockSymUnmanagedConstant(string name, object value, GetSignatureDelegate getSignature) { _name = name; _value = value; _getSignature = getSignature; } int ISymUnmanagedConstant.GetName(int bufferLength, out int count, char[] name) { count = _name.Length + 1; // + 1 for null terminator Debug.Assert((bufferLength == 0) || (bufferLength == count)); for (int i = 0; i < bufferLength - 1; i++) { name[i] = _name[i]; } return SymUnmanagedReaderExtensions.S_OK; } int ISymUnmanagedConstant.GetSignature(int bufferLength, out int count, byte[] signature) { return _getSignature(bufferLength, out count, signature); } int ISymUnmanagedConstant.GetValue(out object value) { value = _value; return SymUnmanagedReaderExtensions.S_OK; } } internal static class MockSymUnmanagedHelpers { public static void TwoPhaseCopy<T>(this ImmutableArray<T> source, int numDesired, out int numRead, T[] destination) { if (destination == null) { Assert.Equal(0, numDesired); numRead = source.IsDefault ? 0 : source.Length; } else { Assert.False(source.IsDefault); Assert.Equal(source.Length, numDesired); source.CopyTo(0, destination, 0, numDesired); numRead = numDesired; } } public static void Add2(this ArrayBuilder<byte> bytes, short s) { var shortBytes = BitConverter.GetBytes(s); Assert.Equal(2, shortBytes.Length); bytes.AddRange(shortBytes); } public static void Add4(this ArrayBuilder<byte> bytes, int i) { var intBytes = BitConverter.GetBytes(i); Assert.Equal(4, intBytes.Length); bytes.AddRange(intBytes); } } }
// <copyright file="ChiSquareTests.cs" company="Math.NET"> // Math.NET Numerics, part of the Math.NET Project // http://numerics.mathdotnet.com // http://github.com/mathnet/mathnet-numerics // http://mathnetnumerics.codeplex.com // // Copyright (c) 2009-2014 Math.NET // // 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. // </copyright> using System; using System.Linq; using MathNet.Numerics.Distributions; using NUnit.Framework; namespace MathNet.Numerics.UnitTests.DistributionTests.Continuous { using Random = System.Random; /// <summary> /// Chi square distribution test /// </summary> [TestFixture, Category("Distributions")] public class ChiSquareTests { /// <summary> /// Can create chi square. /// </summary> /// <param name="dof">Degrees of freedom.</param> [TestCase(1.0)] [TestCase(3.0)] [TestCase(Double.PositiveInfinity)] public void CanCreateChiSquare(double dof) { var n = new ChiSquared(dof); Assert.AreEqual(dof, n.DegreesOfFreedom); } /// <summary> /// Chi square create fails with bad parameters. /// </summary> /// <param name="dof">Degrees of freedom.</param> [TestCase(0.0)] [TestCase(-1.0)] [TestCase(-100.0)] [TestCase(Double.NegativeInfinity)] [TestCase(Double.NaN)] public void ChiSquareCreateFailsWithBadParameters(double dof) { Assert.That(() => new ChiSquared(dof), Throws.ArgumentException); } /// <summary> /// Validate ToString. /// </summary> [Test] public void ValidateToString() { var n = new ChiSquared(1.0); Assert.AreEqual("ChiSquared(k = 1)", n.ToString()); } /// <summary> /// Validate mean. /// </summary> /// <param name="dof">Degrees of freedom.</param> [TestCase(1.0)] [TestCase(2.0)] [TestCase(2.5)] [TestCase(5.0)] [TestCase(Double.PositiveInfinity)] public void ValidateMean(double dof) { var n = new ChiSquared(dof); Assert.AreEqual(dof, n.Mean); } /// <summary> /// Validate variance. /// </summary> /// <param name="dof">Degrees of freedom</param> [TestCase(1.0)] [TestCase(2.0)] [TestCase(2.5)] [TestCase(3.0)] [TestCase(Double.PositiveInfinity)] public void ValidateVariance(double dof) { var n = new ChiSquared(dof); Assert.AreEqual(2 * dof, n.Variance); } /// <summary> /// Validate standard deviation /// </summary> /// <param name="dof">Degrees of freedom</param> [TestCase(1.0)] [TestCase(2.0)] [TestCase(2.5)] [TestCase(3.0)] [TestCase(Double.PositiveInfinity)] public void ValidateStdDev(double dof) { var n = new ChiSquared(dof); Assert.AreEqual(Math.Sqrt(n.Variance), n.StdDev); } /// <summary> /// Validate mode. /// </summary> /// <param name="dof">Degrees of freedom</param> [TestCase(1.0)] [TestCase(2.0)] [TestCase(2.5)] [TestCase(3.0)] [TestCase(Double.PositiveInfinity)] public void ValidateMode(double dof) { var n = new ChiSquared(dof); Assert.AreEqual(dof - 2, n.Mode); } /// <summary> /// Validate median. /// </summary> /// <param name="dof">Degrees of freedom</param> [TestCase(1.0)] [TestCase(2.0)] [TestCase(2.5)] [TestCase(3.0)] [TestCase(Double.PositiveInfinity)] public void ValidateMedian(double dof) { var n = new ChiSquared(dof); Assert.AreEqual(dof - (2.0 / 3.0), n.Median); } /// <summary> /// Validate minimum. /// </summary> [Test] public void ValidateMinimum() { var n = new ChiSquared(1.0); Assert.AreEqual(0.0, n.Minimum); } /// <summary> /// Validate maximum. /// </summary> [Test] public void ValidateMaximum() { var n = new ChiSquared(1.0); Assert.AreEqual(Double.PositiveInfinity, n.Maximum); } /// <summary> /// Validate density. /// </summary> /// <param name="dof">Degrees of freedom.</param> /// <param name="x">Input X value.</param> [TestCase(1.0, 0.0)] [TestCase(1.0, 0.1)] [TestCase(1.0, 1.0)] [TestCase(1.0, 5.5)] [TestCase(1.0, 110.1)] [TestCase(1.0, Double.PositiveInfinity)] [TestCase(2.0, 0.0)] [TestCase(2.0, 0.1)] [TestCase(2.0, 1.0)] [TestCase(2.0, 5.5)] [TestCase(2.0, 110.1)] [TestCase(2.0, Double.PositiveInfinity)] [TestCase(2.5, 0.0)] [TestCase(2.5, 0.1)] [TestCase(2.5, 1.0)] [TestCase(2.5, 5.5)] [TestCase(2.5, 110.1)] [TestCase(2.5, Double.PositiveInfinity)] [TestCase(Double.PositiveInfinity, 0.0)] [TestCase(Double.PositiveInfinity, 0.1)] [TestCase(Double.PositiveInfinity, 1.0)] [TestCase(Double.PositiveInfinity, 5.5)] [TestCase(Double.PositiveInfinity, 110.1)] [TestCase(Double.PositiveInfinity, Double.PositiveInfinity)] public void ValidateDensity(double dof, double x) { var n = new ChiSquared(dof); double expected = (Math.Pow(x, (dof / 2.0) - 1.0) * Math.Exp(-x / 2.0)) / (Math.Pow(2.0, dof / 2.0) * SpecialFunctions.Gamma(dof / 2.0)); Assert.AreEqual(expected, n.Density(x)); Assert.AreEqual(expected, ChiSquared.PDF(dof, x)); } /// <summary> /// Validate density log. /// </summary> /// <param name="dof">Degrees of freedom.</param> /// <param name="x">Input X value.</param> [TestCase(1.0, 0.0)] [TestCase(1.0, 0.1)] [TestCase(1.0, 1.0)] [TestCase(1.0, 5.5)] [TestCase(1.0, 110.1)] [TestCase(1.0, Double.PositiveInfinity)] [TestCase(2.0, 0.0)] [TestCase(2.0, 0.1)] [TestCase(2.0, 1.0)] [TestCase(2.0, 5.5)] [TestCase(2.0, 110.1)] [TestCase(2.0, Double.PositiveInfinity)] [TestCase(2.5, 0.0)] [TestCase(2.5, 0.1)] [TestCase(2.5, 1.0)] [TestCase(2.5, 5.5)] [TestCase(2.5, 110.1)] [TestCase(2.5, Double.PositiveInfinity)] [TestCase(Double.PositiveInfinity, 0.0)] [TestCase(Double.PositiveInfinity, 0.1)] [TestCase(Double.PositiveInfinity, 1.0)] [TestCase(Double.PositiveInfinity, 5.5)] [TestCase(Double.PositiveInfinity, 110.1)] [TestCase(Double.PositiveInfinity, Double.PositiveInfinity)] public void ValidateDensityLn(double dof, double x) { var n = new ChiSquared(dof); double expected = (-x / 2.0) + (((dof / 2.0) - 1.0) * Math.Log(x)) - ((dof / 2.0) * Math.Log(2)) - SpecialFunctions.GammaLn(dof / 2.0); Assert.AreEqual(expected, n.DensityLn(x)); Assert.AreEqual(expected, ChiSquared.PDFLn(dof, x)); } /// <summary> /// Can sample static. /// </summary> [Test] public void CanSampleStatic() { ChiSquared.Sample(new Random(0), 2.0); } /// <summary> /// Fail sample static with bad parameters. /// </summary> [Test] public void FailSampleStatic() { Assert.That(() => ChiSquared.Sample(new Random(0), -1.0), Throws.ArgumentException); } /// <summary> /// Can sample. /// </summary> [Test] public void CanSample() { var n = new ChiSquared(1.0); n.Sample(); } /// <summary> /// Can sample sequence. /// </summary> [Test] public void CanSampleSequence() { var n = new ChiSquared(1.0); var ied = n.Samples(); GC.KeepAlive(ied.Take(5).ToArray()); } /// <summary> /// Validate cumulative distribution. /// </summary> /// <param name="dof">Degrees of freedom.</param> /// <param name="x">Input X value.</param> [TestCase(1.0, 0.0)] [TestCase(1.0, 0.1)] [TestCase(1.0, 1.0)] [TestCase(1.0, 5.5)] [TestCase(1.0, 110.1)] [TestCase(1.0, Double.PositiveInfinity)] [TestCase(2.0, 0.0)] [TestCase(2.0, 0.1)] [TestCase(2.0, 1.0)] [TestCase(2.0, 5.5)] [TestCase(2.0, 110.1)] [TestCase(2.0, Double.PositiveInfinity)] [TestCase(2.5, 0.0)] [TestCase(2.5, 0.1)] [TestCase(2.5, 1.0)] [TestCase(2.5, 5.5)] [TestCase(2.5, 110.1)] [TestCase(2.5, Double.PositiveInfinity)] [TestCase(Double.PositiveInfinity, 0.0)] [TestCase(Double.PositiveInfinity, 0.1)] [TestCase(Double.PositiveInfinity, 1.0)] [TestCase(Double.PositiveInfinity, 5.5)] [TestCase(Double.PositiveInfinity, 110.1)] [TestCase(Double.PositiveInfinity, Double.PositiveInfinity)] public void ValidateCumulativeDistribution(double dof, double x) { var n = new ChiSquared(dof); double expected = SpecialFunctions.GammaLowerIncomplete(dof / 2.0, x / 2.0) / SpecialFunctions.Gamma(dof / 2.0); Assert.AreEqual(expected, n.CumulativeDistribution(x)); Assert.AreEqual(expected, ChiSquared.CDF(dof, x)); } } }
#region License // // The Open Toolkit Library License // // Copyright (c) 2006 - 2009 the Open Toolkit library. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights to // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of // the Software, and to permit persons to whom the Software is furnished to do // so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. // #endregion using System; using System.Diagnostics; using System.Runtime.InteropServices; using System.Text; using OpenTK.Graphics; using OpenTK.Input; using System.Collections.Generic; using System.IO; using System.Drawing; namespace OpenTK.Platform.Windows { /// \internal /// <summary> /// Drives GameWindow on Windows. /// This class supports OpenTK, and is not intended for use by OpenTK programs. /// </summary> internal sealed class WinGLNative : INativeWindow, IInputDriver { #region Fields const ExtendedWindowStyle ParentStyleEx = ExtendedWindowStyle.WindowEdge | ExtendedWindowStyle.ApplicationWindow; const ExtendedWindowStyle ChildStyleEx = 0; static readonly WinKeyMap KeyMap = new WinKeyMap(); readonly IntPtr Instance = Marshal.GetHINSTANCE(typeof(WinGLNative).Module); readonly IntPtr ClassName = Marshal.StringToHGlobalAuto(Guid.NewGuid().ToString()); readonly WindowProcedure WindowProcedureDelegate; readonly uint ModalLoopTimerPeriod = 1; UIntPtr timer_handle; readonly Functions.TimerProc ModalLoopCallback; bool class_registered; bool disposed; bool exists; WinWindowInfo window, child_window; WindowBorder windowBorder = WindowBorder.Resizable; Nullable<WindowBorder> previous_window_border; // Set when changing to fullscreen state. Nullable<WindowBorder> deferred_window_border; // Set to avoid changing borders during fullscreen state. WindowState windowState = WindowState.Normal; bool borderless_maximized_window_state = false; // Hack to get maximized mode with hidden border (not normally possible). bool focused; bool mouse_outside_window = true; bool invisible_since_creation; // Set by WindowsMessage.CREATE and consumed by Visible = true (calls BringWindowToFront). int suppress_resize; // Used in WindowBorder and WindowState in order to avoid rapid, consecutive resize events. Rectangle bounds = new Rectangle(), client_rectangle = new Rectangle(), previous_bounds = new Rectangle(); // Used to restore previous size when leaving fullscreen mode. Icon icon; const ClassStyle DefaultClassStyle = ClassStyle.OwnDC; // Used for IInputDriver implementation WinMMJoystick joystick_driver = new WinMMJoystick(); KeyboardDevice keyboard = new KeyboardDevice(); MouseDevice mouse = new MouseDevice(); IList<KeyboardDevice> keyboards = new List<KeyboardDevice>(1); IList<MouseDevice> mice = new List<MouseDevice>(1); const long ExtendedBit = 1 << 24; // Used to distinguish left and right control, alt and enter keys. static readonly uint ShiftRightScanCode = Functions.MapVirtualKey(VirtualKeys.RSHIFT, 0); // Used to distinguish left and right shift keys. KeyPressEventArgs key_press = new KeyPressEventArgs((char)0); int cursor_visible_count = 0; static readonly object SyncRoot = new object(); #endregion #region Contructors public WinGLNative(int x, int y, int width, int height, string title, GameWindowFlags options, DisplayDevice device) { lock (SyncRoot) { // This is the main window procedure callback. We need the callback in order to create the window, so // don't move it below the CreateWindow calls. WindowProcedureDelegate = WindowProcedure; //// This timer callback is called periodically when the window enters a sizing / moving modal loop. //ModalLoopCallback = delegate(IntPtr handle, WindowMessage msg, UIntPtr eventId, int time) //{ // // Todo: find a way to notify the frontend that it should process queued up UpdateFrame/RenderFrame events. // if (Move != null) // Move(this, EventArgs.Empty); //}; // To avoid issues with Ati drivers on Windows 6+ with compositing enabled, the context will not be // bound to the top-level window, but rather to a child window docked in the parent. window = new WinWindowInfo( CreateWindow(x, y, width, height, title, options, device, IntPtr.Zero), null); child_window = new WinWindowInfo( CreateWindow(0, 0, ClientSize.Width, ClientSize.Height, title, options, device, window.WindowHandle), window); exists = true; keyboard.Description = "Standard Windows keyboard"; keyboard.NumberOfFunctionKeys = 12; keyboard.NumberOfKeys = 101; keyboard.NumberOfLeds = 3; mouse.Description = "Standard Windows mouse"; mouse.NumberOfButtons = 3; mouse.NumberOfWheels = 1; keyboards.Add(keyboard); mice.Add(mouse); } } #endregion #region Private Members #region WindowProcedure IntPtr WindowProcedure(IntPtr handle, WindowMessage message, IntPtr wParam, IntPtr lParam) { switch (message) { #region Size / Move / Style events case WindowMessage.ACTIVATE: // See http://msdn.microsoft.com/en-us/library/ms646274(VS.85).aspx (WM_ACTIVATE notification): // wParam: The low-order word specifies whether the window is being activated or deactivated. bool new_focused_state = Focused; if (IntPtr.Size == 4) focused = (wParam.ToInt32() & 0xFFFF) != 0; else focused = (wParam.ToInt64() & 0xFFFF) != 0; if (new_focused_state != Focused) FocusedChanged(this, EventArgs.Empty); break; case WindowMessage.ENTERMENULOOP: case WindowMessage.ENTERSIZEMOVE: // Entering the modal size/move loop: we don't want rendering to // stop during this time, so we register a timer callback to continue // processing from time to time. StartTimer(handle); break; case WindowMessage.EXITMENULOOP: case WindowMessage.EXITSIZEMOVE: // ExitingmModal size/move loop: the timer callback is no longer // necessary. StopTimer(handle); break; case WindowMessage.ERASEBKGND: return new IntPtr(1); case WindowMessage.WINDOWPOSCHANGED: unsafe { WindowPosition* pos = (WindowPosition*)lParam; if (window != null && pos->hwnd == window.WindowHandle) { Point new_location = new Point(pos->x, pos->y); if (Location != new_location) { bounds.Location = new_location; Move(this, EventArgs.Empty); } Size new_size = new Size(pos->cx, pos->cy); if (Size != new_size) { bounds.Width = pos->cx; bounds.Height = pos->cy; Win32Rectangle rect; Functions.GetClientRect(handle, out rect); client_rectangle = rect.ToRectangle(); Functions.SetWindowPos(child_window.WindowHandle, IntPtr.Zero, 0, 0, ClientRectangle.Width, ClientRectangle.Height, SetWindowPosFlags.NOZORDER | SetWindowPosFlags.NOOWNERZORDER | SetWindowPosFlags.NOACTIVATE | SetWindowPosFlags.NOSENDCHANGING); if (suppress_resize <= 0) Resize(this, EventArgs.Empty); } // Ensure cursor remains grabbed if (!CursorVisible) GrabCursor(); } } break; case WindowMessage.STYLECHANGED: unsafe { if (wParam.ToInt64() == (long)GWL.STYLE) { WindowStyle style = ((StyleStruct*)lParam)->New; if ((style & WindowStyle.Popup) != 0) windowBorder = WindowBorder.Hidden; else if ((style & WindowStyle.ThickFrame) != 0) windowBorder = WindowBorder.Resizable; else if ((style & ~(WindowStyle.ThickFrame | WindowStyle.MaximizeBox)) != 0) windowBorder = WindowBorder.Fixed; } } // Ensure cursor remains grabbed if (!CursorVisible) GrabCursor(); break; case WindowMessage.SIZE: SizeMessage state = (SizeMessage)wParam.ToInt64(); WindowState new_state = windowState; switch (state) { case SizeMessage.RESTORED: new_state = borderless_maximized_window_state ? WindowState.Maximized : WindowState.Normal; break; case SizeMessage.MINIMIZED: new_state = WindowState.Minimized; break; case SizeMessage.MAXIMIZED: new_state = WindowBorder == WindowBorder.Hidden ? WindowState.Fullscreen : WindowState.Maximized; break; } if (new_state != windowState) { windowState = new_state; WindowStateChanged(this, EventArgs.Empty); } // Ensure cursor remains grabbed if (!CursorVisible) GrabCursor(); break; #endregion #region Input events case WindowMessage.CHAR: if (IntPtr.Size == 4) key_press.KeyChar = (char)wParam.ToInt32(); else key_press.KeyChar = (char)wParam.ToInt64(); KeyPress(this, key_press); break; case WindowMessage.MOUSEMOVE: Point point = new Point( (short)((uint)lParam.ToInt32() & 0x0000FFFF), (short)(((uint)lParam.ToInt32() & 0xFFFF0000) >> 16)); mouse.Position = point; if (mouse_outside_window) { // Once we receive a mouse move event, it means that the mouse has // re-entered the window. mouse_outside_window = false; EnableMouseTracking(); MouseEnter(this, EventArgs.Empty); } break; case WindowMessage.MOUSELEAVE: mouse_outside_window = true; // Mouse tracking is disabled automatically by the OS MouseLeave(this, EventArgs.Empty); break; case WindowMessage.MOUSEWHEEL: // This is due to inconsistent behavior of the WParam value on 64bit arch, whese // wparam = 0xffffffffff880000 or wparam = 0x00000000ff100000 mouse.WheelPrecise += ((long)wParam << 32 >> 48) / 120.0f; break; case WindowMessage.LBUTTONDOWN: Functions.SetCapture(window.WindowHandle); mouse[MouseButton.Left] = true; break; case WindowMessage.MBUTTONDOWN: Functions.SetCapture(window.WindowHandle); mouse[MouseButton.Middle] = true; break; case WindowMessage.RBUTTONDOWN: Functions.SetCapture(window.WindowHandle); mouse[MouseButton.Right] = true; break; case WindowMessage.XBUTTONDOWN: Functions.SetCapture(window.WindowHandle); mouse[((wParam.ToInt32() & 0xFFFF0000) >> 16) != (int)MouseKeys.XButton1 ? MouseButton.Button1 : MouseButton.Button2] = true; break; case WindowMessage.LBUTTONUP: Functions.ReleaseCapture(); mouse[MouseButton.Left] = false; break; case WindowMessage.MBUTTONUP: Functions.ReleaseCapture(); mouse[MouseButton.Middle] = false; break; case WindowMessage.RBUTTONUP: Functions.ReleaseCapture(); mouse[MouseButton.Right] = false; break; case WindowMessage.XBUTTONUP: Functions.ReleaseCapture(); mouse[((wParam.ToInt32() & 0xFFFF0000) >> 16) != (int)MouseKeys.XButton1 ? MouseButton.Button1 : MouseButton.Button2] = false; break; // Keyboard events: case WindowMessage.KEYDOWN: case WindowMessage.KEYUP: case WindowMessage.SYSKEYDOWN: case WindowMessage.SYSKEYUP: bool pressed = message == WindowMessage.KEYDOWN || message == WindowMessage.SYSKEYDOWN; // Shift/Control/Alt behave strangely when e.g. ShiftRight is held down and ShiftLeft is pressed // and released. It looks like neither key is released in this case, or that the wrong key is // released in the case of Control and Alt. // To combat this, we are going to release both keys when either is released. Hacky, but should work. // Win95 does not distinguish left/right key constants (GetAsyncKeyState returns 0). // In this case, both keys will be reported as pressed. bool extended = (lParam.ToInt64() & ExtendedBit) != 0; switch ((VirtualKeys)wParam) { case VirtualKeys.SHIFT: // The behavior of this key is very strange. Unlike Control and Alt, there is no extended bit // to distinguish between left and right keys. Moreover, pressing both keys and releasing one // may result in both keys being held down (but not always). // The only reliable way to solve this was reported by BlueMonkMN at the forums: we should // check the scancodes. It looks like GLFW does the same thing, so it should be reliable. // Note: we release both keys when either shift is released. // Otherwise, the state of one key might be stuck to pressed. if (ShiftRightScanCode != 0 && pressed) { unchecked { if (((lParam.ToInt64() >> 16) & 0xFF) == ShiftRightScanCode) keyboard[Input.Key.ShiftRight] = pressed; else keyboard[Input.Key.ShiftLeft] = pressed; } } else { // Windows 9x and NT4.0 or key release event. keyboard[Input.Key.ShiftLeft] = keyboard[Input.Key.ShiftRight] = pressed; } return IntPtr.Zero; case VirtualKeys.CONTROL: if (extended) keyboard[Input.Key.ControlRight] = pressed; else keyboard[Input.Key.ControlLeft] = pressed; return IntPtr.Zero; case VirtualKeys.MENU: if (extended) keyboard[Input.Key.AltRight] = pressed; else keyboard[Input.Key.AltLeft] = pressed; return IntPtr.Zero; case VirtualKeys.RETURN: if (extended) keyboard[Key.KeypadEnter] = pressed; else keyboard[Key.Enter] = pressed; return IntPtr.Zero; default: if (!KeyMap.ContainsKey((VirtualKeys)wParam)) { Debug.Print("Virtual key {0} ({1}) not mapped.", (VirtualKeys)wParam, (long)lParam); break; } else { keyboard[KeyMap[(VirtualKeys)wParam]] = pressed; } return IntPtr.Zero; } break; case WindowMessage.SYSCHAR: return IntPtr.Zero; case WindowMessage.KILLFOCUS: keyboard.ClearKeys(); break; #endregion #region Creation / Destruction events case WindowMessage.CREATE: CreateStruct cs = (CreateStruct)Marshal.PtrToStructure(lParam, typeof(CreateStruct)); if (cs.hwndParent == IntPtr.Zero) { bounds.X = cs.x; bounds.Y = cs.y; bounds.Width = cs.cx; bounds.Height = cs.cy; Win32Rectangle rect; Functions.GetClientRect(handle, out rect); client_rectangle = rect.ToRectangle(); invisible_since_creation = true; } break; case WindowMessage.CLOSE: System.ComponentModel.CancelEventArgs e = new System.ComponentModel.CancelEventArgs(); Closing(this, e); if (!e.Cancel) { DestroyWindow(); break; } return IntPtr.Zero; case WindowMessage.DESTROY: exists = false; Functions.UnregisterClass(ClassName, Instance); window.Dispose(); child_window.Dispose(); Closed(this, EventArgs.Empty); break; #endregion } return Functions.DefWindowProc(handle, message, wParam, lParam); } private void EnableMouseTracking() { TrackMouseEventStructure me = new TrackMouseEventStructure(); me.Size = TrackMouseEventStructure.SizeInBytes; me.TrackWindowHandle = child_window.WindowHandle; me.Flags = TrackMouseEventFlags.LEAVE; if (!Functions.TrackMouseEvent(ref me)) Debug.Print("[Warning] Failed to enable mouse tracking, error: {0}.", Marshal.GetLastWin32Error()); } private void StartTimer(IntPtr handle) { if (timer_handle == UIntPtr.Zero) { timer_handle = Functions.SetTimer(handle, new UIntPtr(1), ModalLoopTimerPeriod, ModalLoopCallback); if (timer_handle == UIntPtr.Zero) Debug.Print("[Warning] Failed to set modal loop timer callback ({0}:{1}->{2}).", GetType().Name, handle, Marshal.GetLastWin32Error()); } } private void StopTimer(IntPtr handle) { if (timer_handle != UIntPtr.Zero) { if (!Functions.KillTimer(handle, timer_handle)) Debug.Print("[Warning] Failed to kill modal loop timer callback ({0}:{1}->{2}).", GetType().Name, handle, Marshal.GetLastWin32Error()); timer_handle = UIntPtr.Zero; } } #endregion #region IsIdle bool IsIdle { get { MSG message = new MSG(); return !Functions.PeekMessage(ref message, window.WindowHandle, 0, 0, 0); } } #endregion #region CreateWindow IntPtr CreateWindow(int x, int y, int width, int height, string title, GameWindowFlags options, DisplayDevice device, IntPtr parentHandle) { // Use win32 to create the native window. // Keep in mind that some construction code runs in the WM_CREATE message handler. // The style of a parent window is different than that of a child window. // Note: the child window should always be visible, even if the parent isn't. WindowStyle style = 0; ExtendedWindowStyle ex_style = 0; if (parentHandle == IntPtr.Zero) { style |= WindowStyle.OverlappedWindow | WindowStyle.ClipChildren; ex_style = ParentStyleEx; } else { style |= WindowStyle.Visible | WindowStyle.Child | WindowStyle.ClipSiblings; ex_style = ChildStyleEx; } // Find out the final window rectangle, after the WM has added its chrome (titlebar, sidebars etc). Win32Rectangle rect = new Win32Rectangle(); rect.left = x; rect.top = y; rect.right = x + width; rect.bottom = y + height; Functions.AdjustWindowRectEx(ref rect, style, false, ex_style); // Create the window class that we will use for this window. // The current approach is to register a new class for each top-level WinGLWindow we create. if (!class_registered) { ExtendedWindowClass wc = new ExtendedWindowClass(); wc.Size = ExtendedWindowClass.SizeInBytes; wc.Style = DefaultClassStyle; wc.Instance = Instance; wc.WndProc = WindowProcedureDelegate; wc.ClassName = ClassName; wc.Icon = Icon != null ? Icon.Handle : IntPtr.Zero; #warning "This seems to resize one of the 'large' icons, rather than using a small icon directly (multi-icon files). Investigate!" wc.IconSm = Icon != null ? new Icon(Icon, 16, 16).Handle : IntPtr.Zero; wc.Cursor = Functions.LoadCursor(CursorName.Arrow); ushort atom = Functions.RegisterClassEx(ref wc); if (atom == 0) throw new PlatformException(String.Format("Failed to register window class. Error: {0}", Marshal.GetLastWin32Error())); class_registered = true; } IntPtr window_name = Marshal.StringToHGlobalAuto(title); IntPtr handle = Functions.CreateWindowEx( ex_style, ClassName, window_name, style, rect.left, rect.top, rect.Width, rect.Height, parentHandle, IntPtr.Zero, Instance, IntPtr.Zero); if (handle == IntPtr.Zero) throw new PlatformException(String.Format("Failed to create window. Error: {0}", Marshal.GetLastWin32Error())); return handle; } #endregion #region DestroyWindow /// <summary> /// Starts the teardown sequence for the current window. /// </summary> void DestroyWindow() { if (Exists) { Debug.Print("Destroying window: {0}", window.ToString()); Functions.DestroyWindow(window.WindowHandle); exists = false; } } #endregion void HideBorder() { suppress_resize++; WindowBorder = WindowBorder.Hidden; ProcessEvents(); suppress_resize--; } void RestoreBorder() { suppress_resize++; WindowBorder = deferred_window_border.HasValue ? deferred_window_border.Value : previous_window_border.HasValue ? previous_window_border.Value : WindowBorder; ProcessEvents(); suppress_resize--; deferred_window_border = previous_window_border = null; } void ResetWindowState() { suppress_resize++; WindowState = WindowState.Normal; ProcessEvents(); suppress_resize--; } void GrabCursor() { Point pos = PointToScreen(new Point(ClientRectangle.X, ClientRectangle.Y)); Win32Rectangle rect = new Win32Rectangle(); rect.left = pos.X; rect.right = pos.X + ClientRectangle.Width; rect.top = pos.Y; rect.bottom = pos.Y + ClientRectangle.Height; if (!Functions.ClipCursor(ref rect)) Debug.WriteLine(String.Format("Failed to grab cursor. Error: {0}", Marshal.GetLastWin32Error())); } void UngrabCursor() { if (!Functions.ClipCursor(IntPtr.Zero)) Debug.WriteLine(String.Format("Failed to ungrab cursor. Error: {0}", Marshal.GetLastWin32Error())); } #endregion #region INativeWindow Members #region Bounds public Rectangle Bounds { get { return bounds; } set { // Note: the bounds variable is updated when the resize/move message arrives. Functions.SetWindowPos(window.WindowHandle, IntPtr.Zero, value.X, value.Y, value.Width, value.Height, 0); } } #endregion #region Location public Point Location { get { return Bounds.Location; } set { // Note: the bounds variable is updated when the resize/move message arrives. Functions.SetWindowPos(window.WindowHandle, IntPtr.Zero, value.X, value.Y, 0, 0, SetWindowPosFlags.NOSIZE); } } #endregion #region Size public Size Size { get { return Bounds.Size; } set { // Note: the bounds variable is updated when the resize/move message arrives. Functions.SetWindowPos(window.WindowHandle, IntPtr.Zero, 0, 0, value.Width, value.Height, SetWindowPosFlags.NOMOVE); } } #endregion #region ClientRectangle public Rectangle ClientRectangle { get { if (client_rectangle.Width == 0) client_rectangle.Width = 1; if (client_rectangle.Height == 0) client_rectangle.Height = 1; return client_rectangle; } set { ClientSize = value.Size; } } #endregion #region ClientSize public Size ClientSize { get { return ClientRectangle.Size; } set { WindowStyle style = (WindowStyle)Functions.GetWindowLong(window.WindowHandle, GetWindowLongOffsets.STYLE); Win32Rectangle rect = Win32Rectangle.From(value); Functions.AdjustWindowRect(ref rect, style, false); Size = new Size(rect.Width, rect.Height); } } #endregion #region Width public int Width { get { return ClientRectangle.Width; } set { ClientRectangle = new Rectangle(0, 0, value, Height); } } #endregion #region Height public int Height { get { return ClientRectangle.Height; } set { ClientRectangle = new Rectangle(0, 0, Width, value); } } #endregion #region X public int X { get { return Location.X; } set { Location = new Point(value, Y); } } #endregion #region Y public int Y { get { return Location.Y; } set { Location = new Point(X, value); } } #endregion #region Icon public Icon Icon { get { return icon; } set { if (value != icon) { icon = value; if (window.WindowHandle != IntPtr.Zero) { Functions.SendMessage(window.WindowHandle, WindowMessage.SETICON, (IntPtr)0, icon == null ? IntPtr.Zero : value.Handle); Functions.SendMessage(window.WindowHandle, WindowMessage.SETICON, (IntPtr)1, icon == null ? IntPtr.Zero : value.Handle); } IconChanged(this, EventArgs.Empty); } } } #endregion #region Focused public bool Focused { get { return focused; } } #endregion #region Title StringBuilder sb_title = new StringBuilder(256); public string Title { get { sb_title.Remove(0, sb_title.Length); if (Functions.GetWindowText(window.WindowHandle, sb_title, sb_title.Capacity) == 0) Debug.Print("Failed to retrieve window title (window:{0}, reason:{1}).", window.WindowHandle, Marshal.GetLastWin32Error()); return sb_title.ToString(); } set { if (Title != value) { if (!Functions.SetWindowText(window.WindowHandle, value)) Debug.Print("Failed to change window title (window:{0}, new title:{1}, reason:{2}).", window.WindowHandle, value, Marshal.GetLastWin32Error()); TitleChanged(this, EventArgs.Empty); } } } #endregion #region Visible public bool Visible { get { return Functions.IsWindowVisible(window.WindowHandle); } set { if (value != Visible) { if (value) { Functions.ShowWindow(window.WindowHandle, ShowWindowCommand.SHOW); if (invisible_since_creation) { Functions.BringWindowToTop(window.WindowHandle); Functions.SetForegroundWindow(window.WindowHandle); } } else if (!value) { Functions.ShowWindow(window.WindowHandle, ShowWindowCommand.HIDE); } VisibleChanged(this, EventArgs.Empty); } } } #endregion #region Exists public bool Exists { get { return exists; } } #endregion #region CursorVisible public bool CursorVisible { get { return cursor_visible_count >= 0; } // Not used set { if (value && cursor_visible_count < 0) { do { cursor_visible_count = Functions.ShowCursor(true); } while (cursor_visible_count < 0); UngrabCursor(); } else if (!value && cursor_visible_count >= 0) { do { cursor_visible_count = Functions.ShowCursor(false); } while (cursor_visible_count >= 0); GrabCursor(); } } } #endregion #region Close public void Close() { Functions.PostMessage(window.WindowHandle, WindowMessage.CLOSE, IntPtr.Zero, IntPtr.Zero); } #endregion #region public WindowState WindowState public WindowState WindowState { get { return windowState; } set { if (WindowState == value) return; ShowWindowCommand command = 0; bool exiting_fullscreen = false; borderless_maximized_window_state = false; switch (value) { case WindowState.Normal: command = ShowWindowCommand.RESTORE; // If we are leaving fullscreen mode we need to restore the border. if (WindowState == WindowState.Fullscreen) exiting_fullscreen = true; break; case WindowState.Maximized: // Note: if we use the MAXIMIZE command and the window border is Hidden (i.e. WS_POPUP), // we will enter fullscreen mode - we don't want that! As a workaround, we'll resize the window // manually to cover the whole working area of the current monitor. // Reset state to avoid strange interactions with fullscreen/minimized windows. ResetWindowState(); if (WindowBorder == WindowBorder.Hidden) { IntPtr current_monitor = Functions.MonitorFromWindow(window.WindowHandle, MonitorFrom.Nearest); MonitorInfo info = new MonitorInfo(); info.Size = MonitorInfo.SizeInBytes; Functions.GetMonitorInfo(current_monitor, ref info); previous_bounds = Bounds; borderless_maximized_window_state = true; Bounds = info.Work.ToRectangle(); } else { command = ShowWindowCommand.MAXIMIZE; } break; case WindowState.Minimized: command = ShowWindowCommand.MINIMIZE; break; case WindowState.Fullscreen: // We achieve fullscreen by hiding the window border and sending the MAXIMIZE command. // We cannot use the WindowState.Maximized directly, as that will not send the MAXIMIZE // command for windows with hidden borders. // Reset state to avoid strange side-effects from maximized/minimized windows. ResetWindowState(); previous_bounds = Bounds; previous_window_border = WindowBorder; HideBorder(); command = ShowWindowCommand.MAXIMIZE; Functions.SetForegroundWindow(window.WindowHandle); break; } if (command != 0) Functions.ShowWindow(window.WindowHandle, command); // Restore previous window border or apply pending border change when leaving fullscreen mode. if (exiting_fullscreen) { RestoreBorder(); } // Restore previous window size/location if necessary if (command == ShowWindowCommand.RESTORE && previous_bounds != Rectangle.Empty) { Bounds = previous_bounds; previous_bounds = Rectangle.Empty; } } } #endregion #region public WindowBorder WindowBorder public WindowBorder WindowBorder { get { return windowBorder; } set { // Do not allow border changes during fullscreen mode. // Defer them for when we leave fullscreen. if (WindowState == WindowState.Fullscreen) { deferred_window_border = value; return; } if (windowBorder == value) return; // We wish to avoid making an invisible window visible just to change the border. // However, it's a good idea to make a visible window invisible temporarily, to // avoid garbage caused by the border change. bool was_visible = Visible; // To ensure maximized/minimized windows work correctly, reset state to normal, // change the border, then go back to maximized/minimized. WindowState state = WindowState; ResetWindowState(); WindowStyle style = WindowStyle.ClipChildren | WindowStyle.ClipSiblings; switch (value) { case WindowBorder.Resizable: style |= WindowStyle.OverlappedWindow; break; case WindowBorder.Fixed: style |= WindowStyle.OverlappedWindow & ~(WindowStyle.ThickFrame | WindowStyle.MaximizeBox | WindowStyle.SizeBox); break; case WindowBorder.Hidden: style |= WindowStyle.Popup; break; } // Make sure client size doesn't change when changing the border style. Size client_size = ClientSize; Win32Rectangle rect = Win32Rectangle.From(client_size); Functions.AdjustWindowRectEx(ref rect, style, false, ParentStyleEx); // This avoids leaving garbage on the background window. if (was_visible) Visible = false; Functions.SetWindowLong(window.WindowHandle, GetWindowLongOffsets.STYLE, (IntPtr)(int)style); Functions.SetWindowPos(window.WindowHandle, IntPtr.Zero, 0, 0, rect.Width, rect.Height, SetWindowPosFlags.NOMOVE | SetWindowPosFlags.NOZORDER | SetWindowPosFlags.FRAMECHANGED); // Force window to redraw update its borders, but only if it's // already visible (invisible windows will change borders when // they become visible, so no need to make them visiable prematurely). if (was_visible) Visible = true; WindowState = state; WindowBorderChanged(this, EventArgs.Empty); } } #endregion #region PointToClient public Point PointToClient(Point point) { if (!Functions.ScreenToClient(window.WindowHandle, ref point)) throw new InvalidOperationException(String.Format( "Could not convert point {0} from screen to client coordinates. Windows error: {1}", point.ToString(), Marshal.GetLastWin32Error())); return point; } #endregion #region PointToScreen public Point PointToScreen(Point point) { if (!Functions.ClientToScreen(window.WindowHandle, ref point)) throw new InvalidOperationException(String.Format( "Could not convert point {0} from screen to client coordinates. Windows error: {1}", point.ToString(), Marshal.GetLastWin32Error())); return point; } #endregion #region Events public event EventHandler<EventArgs> Move = delegate { }; public event EventHandler<EventArgs> Resize = delegate { }; public event EventHandler<System.ComponentModel.CancelEventArgs> Closing = delegate { }; public event EventHandler<EventArgs> Closed = delegate { }; public event EventHandler<EventArgs> Disposed = delegate { }; public event EventHandler<EventArgs> IconChanged = delegate { }; public event EventHandler<EventArgs> TitleChanged = delegate { }; public event EventHandler<EventArgs> VisibleChanged = delegate { }; public event EventHandler<EventArgs> FocusedChanged = delegate { }; public event EventHandler<EventArgs> WindowBorderChanged = delegate { }; public event EventHandler<EventArgs> WindowStateChanged = delegate { }; public event EventHandler<OpenTK.Input.KeyboardKeyEventArgs> KeyDown = delegate { }; public event EventHandler<KeyPressEventArgs> KeyPress = delegate { }; public event EventHandler<OpenTK.Input.KeyboardKeyEventArgs> KeyUp = delegate { }; public event EventHandler<EventArgs> MouseEnter = delegate { }; public event EventHandler<EventArgs> MouseLeave = delegate { }; #endregion #endregion #region INativeGLWindow Members #region public void ProcessEvents() private int ret; MSG msg; public void ProcessEvents() { while (!IsIdle) { ret = Functions.GetMessage(ref msg, window.WindowHandle, 0, 0); if (ret == -1) { throw new PlatformException(String.Format( "An error happened while processing the message queue. Windows error: {0}", Marshal.GetLastWin32Error())); } Functions.TranslateMessage(ref msg); Functions.DispatchMessage(ref msg); } } #endregion #region public IInputDriver InputDriver public IInputDriver InputDriver { get { return this; } } #endregion #region public IWindowInfo WindowInfo public IWindowInfo WindowInfo { get { return child_window; } } #endregion #endregion #region IInputDriver Members public void Poll() { joystick_driver.Poll(); } #endregion #region IKeyboardDriver Members public IList<KeyboardDevice> Keyboard { get { return keyboards; } } public KeyboardState GetState() { throw new NotImplementedException(); } public KeyboardState GetState(int index) { throw new NotImplementedException(); } #endregion #region IMouseDriver Members public IList<MouseDevice> Mouse { get { return mice; } } #endregion #region IJoystickDriver Members public IList<JoystickDevice> Joysticks { get { return joystick_driver.Joysticks; } } #endregion #region IDisposable Members public void Dispose() { this.Dispose(true); GC.SuppressFinalize(this); } void Dispose(bool calledManually) { if (!disposed) { if (calledManually) { // Safe to clean managed resources DestroyWindow(); if (Icon != null) Icon.Dispose(); } else { Debug.Print("[Warning] INativeWindow leaked ({0}). Did you forget to call INativeWindow.Dispose()?", this); } Disposed(this, EventArgs.Empty); disposed = true; } } ~WinGLNative() { Dispose(false); } #endregion } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Linq; namespace LibGit2Sharp.Core { internal class HistoryRewriter { private readonly IRepository repo; private readonly HashSet<Commit> targetedCommits; private readonly Dictionary<GitObject, GitObject> objectMap = new Dictionary<GitObject, GitObject>(); private readonly Dictionary<Reference, Reference> refMap = new Dictionary<Reference, Reference>(); private readonly Queue<Action> rollbackActions = new Queue<Action>(); private readonly string backupRefsNamespace; private readonly RewriteHistoryOptions options; public HistoryRewriter( IRepository repo, IEnumerable<Commit> commitsToRewrite, RewriteHistoryOptions options) { this.repo = repo; this.options = options; targetedCommits = new HashSet<Commit>(commitsToRewrite); backupRefsNamespace = this.options.BackupRefsNamespace; if (!backupRefsNamespace.EndsWith("/", StringComparison.Ordinal)) { backupRefsNamespace += "/"; } } public void Execute() { var success = false; try { // Find out which refs lead to at least one the commits var refsToRewrite = repo.Refs.ReachableFrom(targetedCommits).ToList(); var filter = new CommitFilter { Since = refsToRewrite, SortBy = CommitSortStrategies.Reverse | CommitSortStrategies.Topological }; var commits = repo.Commits.QueryBy(filter); foreach (var commit in commits) { RewriteCommit(commit); } // Ordering matters. In the case of `A -> B -> commit`, we need to make sure B is rewritten // before A. foreach (var reference in refsToRewrite.OrderBy(ReferenceDepth)) { // TODO: Check how rewriting of notes actually behaves RewriteReference(reference); } success = true; if (options.OnSucceeding != null) { options.OnSucceeding(); } } catch (Exception ex) { try { if (!success && options.OnError != null) { options.OnError(ex); } } finally { foreach (var action in rollbackActions) { action(); } } throw; } finally { rollbackActions.Clear(); } } private Reference RewriteReference(Reference reference) { // Has this target already been rewritten? if (refMap.ContainsKey(reference)) { return refMap[reference]; } var sref = reference as SymbolicReference; if (sref != null) { return RewriteReference( sref, old => old.Target, RewriteReference, (refs, old, target, sig, logMessage) => refs.UpdateTarget(old, target, sig, logMessage)); } var dref = reference as DirectReference; if (dref != null) { return RewriteReference( dref, old => old.Target, RewriteTarget, (refs, old, target, sig, logMessage) => refs.UpdateTarget(old, target.Id, sig, logMessage)); } return reference; } private delegate Reference ReferenceUpdater<in TRef, in TTarget>( ReferenceCollection refs, TRef origRef, TTarget origTarget, Signature signature, string logMessage) where TRef : Reference where TTarget : class; private Reference RewriteReference<TRef, TTarget>( TRef oldRef, Func<TRef, TTarget> selectTarget, Func<TTarget, TTarget> rewriteTarget, ReferenceUpdater<TRef, TTarget> updateTarget) where TRef : Reference where TTarget : class { var oldRefTarget = selectTarget(oldRef); var signature = repo.Config.BuildSignature(DateTimeOffset.Now); string newRefName = oldRef.CanonicalName; if (oldRef.IsTag() && options.TagNameRewriter != null) { newRefName = Reference.TagPrefix + options.TagNameRewriter(oldRef.CanonicalName.Substring(Reference.TagPrefix.Length), false, oldRef.TargetIdentifier); } var newTarget = rewriteTarget(oldRefTarget); if (oldRefTarget.Equals(newTarget) && oldRef.CanonicalName == newRefName) { // The reference isn't rewritten return oldRef; } string backupName = backupRefsNamespace + oldRef.CanonicalName.Substring("refs/".Length); if (repo.Refs.Resolve<Reference>(backupName) != null) { throw new InvalidOperationException( String.Format( CultureInfo.InvariantCulture, "Can't back up reference '{0}' - '{1}' already exists", oldRef.CanonicalName, backupName)); } repo.Refs.Add(backupName, oldRef.TargetIdentifier, signature, "filter-branch: backup"); rollbackActions.Enqueue(() => repo.Refs.Remove(backupName)); if (newTarget == null) { repo.Refs.Remove(oldRef); rollbackActions.Enqueue(() => repo.Refs.Add(oldRef.CanonicalName, oldRef, signature, "filter-branch: abort", true)); return refMap[oldRef] = null; } Reference newRef = updateTarget(repo.Refs, oldRef, newTarget, signature, "filter-branch: rewrite"); rollbackActions.Enqueue(() => updateTarget(repo.Refs, oldRef, oldRefTarget, signature, "filter-branch: abort")); if (newRef.CanonicalName == newRefName) { return refMap[oldRef] = newRef; } var movedRef = repo.Refs.Move(newRef, newRefName); rollbackActions.Enqueue(() => repo.Refs.Move(newRef, oldRef.CanonicalName)); return refMap[oldRef] = movedRef; } private void RewriteCommit(Commit commit) { var newHeader = CommitRewriteInfo.From(commit); var newTree = commit.Tree; // Find the new parents var newParents = commit.Parents; if (targetedCommits.Contains(commit)) { // Get the new commit header if (options.CommitHeaderRewriter != null) { newHeader = options.CommitHeaderRewriter(commit) ?? newHeader; } if (options.CommitTreeRewriter != null) { // Get the new commit tree var newTreeDefinition = options.CommitTreeRewriter(commit); newTree = repo.ObjectDatabase.CreateTree(newTreeDefinition); } // Retrieve new parents if (options.CommitParentsRewriter != null) { newParents = options.CommitParentsRewriter(commit); } } // Create the new commit var mappedNewParents = newParents .Select(oldParent => objectMap.ContainsKey(oldParent) ? objectMap[oldParent] as Commit : oldParent) .Where(newParent => newParent != null) .ToList(); if (options.PruneEmptyCommits && TryPruneEmptyCommit(commit, mappedNewParents, newTree)) { return; } var newCommit = repo.ObjectDatabase.CreateCommit(newHeader.Author, newHeader.Committer, newHeader.Message, true, newTree, mappedNewParents); // Record the rewrite objectMap[commit] = newCommit; } private bool TryPruneEmptyCommit(Commit commit, IList<Commit> mappedNewParents, Tree newTree) { var parent = mappedNewParents.Count > 0 ? mappedNewParents[0] : null; if (parent == null) { if (newTree.Count == 0) { objectMap[commit] = null; return true; } } else if (parent.Tree == newTree) { objectMap[commit] = parent; return true; } return false; } private GitObject RewriteTarget(GitObject oldTarget) { // Has this target already been rewritten? if (objectMap.ContainsKey(oldTarget)) { return objectMap[oldTarget]; } Debug.Assert((oldTarget as Commit) == null); var annotation = oldTarget as TagAnnotation; if (annotation == null) { //TODO: Probably a Tree or a Blob. This is not covered by any test return oldTarget; } // Recursively rewrite annotations if necessary var newTarget = RewriteTarget(annotation.Target); string newName = annotation.Name; if (options.TagNameRewriter != null) { newName = options.TagNameRewriter(annotation.Name, true, annotation.Target.Sha); } var newAnnotation = repo.ObjectDatabase.CreateTagAnnotation(newName, newTarget, annotation.Tagger, annotation.Message); objectMap[annotation] = newAnnotation; return newAnnotation; } private int ReferenceDepth(Reference reference) { var dref = reference as DirectReference; return dref == null ? 1 + ReferenceDepth(((SymbolicReference)reference).Target) : 1; } } }
using UnityEngine; using UnityEngine.UI; using System.Collections; public class PlayerController : MonoBehaviour { // Our forward speed. Acceleration I guess. public float speed; // Our rotate speed. public float rotationSpeed; // Weapons public string ourWeaponTag; public GameObject shot; public Transform shotSpawn; public float fireRate; private float nextFire; // Engines public GameObject engines; private int roll; public GameObject smokeTrail; // The ships smoke trail particle emitter private ParticleSystem pe; // Ship life parameters public GameObject explosion; public GameObject spark; public float hitsToDestroy; // Cargo Pickups public int maxCargoLoadCount; private int cargoLoadCount = 0; public GameObject cargoObject; public Transform cargoDumpSpawn; private Rigidbody rigidBody; private float speedModifier; // Sound clips private AudioSource audioWeapon; private AudioSource audioCrystalPickup; // Main game controller private GameController gGameController; private int eController = 0; private Transform targetPlayer; private Transform targetCrystal; public float maxDetectRange = 20; public float maxWeaponRange = 15; private Transform myTransform; private bool bAIFire = false; private bool bAIFire2 = false; private bool bAIDump = false; private float AI_yaw = 0; private float AI_thrust = 0; private Light []lights; private bool bLightsOn; //------------------------------------------------------------------------- void Awake() { myTransform = transform; } //------------------------------------------------------------------------- // Use this for initialization void Start () { GameObject gameControllerObject = GameObject.FindGameObjectWithTag("GameController"); if (gameControllerObject != null) { gGameController = gameControllerObject.GetComponent<GameController>(); } if (gGameController == null) { Debug.Log("Cannot find 'GameController' script"); } rigidBody = GetComponent<Rigidbody>(); if (smokeTrail) pe = smokeTrail.GetComponent<ParticleSystem> (); else pe = null; roll = 0; gGameController.UI_SetSheildLevelMax(hitsToDestroy); gGameController.UI_SetSheildLevel(hitsToDestroy); gGameController.UI_SetCargoLevelMax(maxCargoLoadCount); gGameController.UI_SetCargoLevel(0); // Assign audio sources AudioSource[] audioClips = GetComponents<AudioSource>(); // Load clips. These are in order that they appear in the inspector audioWeapon = audioClips[0]; audioCrystalPickup = audioClips[1]; // Set controller entity for this player if (CompareTag ("Enemy")) eController = 1; else eController = 0; targetPlayer = null; targetCrystal = null; lights = gameObject.GetComponentsInChildren<Light>(); SetLights (true); } //------------------------------------------------------------------------- void Update() { bool bFire = false; bool bFire2 = false; bool bCargoDump = false; bool bLights = false; switch (eController) { case 0: bFire = Input.GetButton ("Fire1"); bFire2 = Input.GetButton ("Fire2"); bCargoDump = Input.GetKeyDown (KeyCode.C); bLights = Input.GetKeyDown (KeyCode.L); break; case 1: bFire = bAIFire; bFire2 = bAIFire2; bCargoDump = bAIDump; bAIFire = bAIFire2 = bAIDump = bLights = false; break; } // Shoot a bolt if (bFire && Time.time > nextFire) { nextFire = Time.time + fireRate; GameObject shotObject = (GameObject)Instantiate(shot, shotSpawn.position, shotSpawn.rotation); // as GameObject; shotObject.GetComponent<Mover> ().SetParentSpeed (transform.GetComponent<Rigidbody> ().velocity); audioWeapon.Play(); } // Shoot out the mining laser if (bFire2) { Debug.Log("Fire2"); } // Defined ship key controls // C - Cargo, dump crystals that are in the cargo hold if (bCargoDump) { DumpCrystal(cargoDumpSpawn); } if (bLights) { SetLights (!bLightsOn); } } //------------------------------------------------------------------------- void FixedUpdate () { float yaw = 0; float thrust = 0; float thrustVector; float thrustScale; switch (eController) { case 0: //Player1 yaw = Input.GetAxisRaw ("Horizontal"); thrust = Input.GetAxisRaw ("Vertical"); break; case 1: // AI AI_Controller(out yaw, out thrust); break; } // max roll angle is a function of yaw and speed int roll_max = (int)(-yaw * rigidBody.velocity.magnitude * 8); // Show engine thrust only when thrusting forward or turning //Debug.Log("thrust: " + thrust); if (engines) engines.SetActive((thrust > 0) || (yaw != 0)); if (thrust > 0) { // thrusting... // Turn on smoke if (pe) pe.maxParticles = 50; // Turn off drag speedModifier = 1.0f; // Calculate flame angle and size thrustVector = yaw * -45.0f; thrustScale = thrust * 4.0f; } else { // no thrust (or reverse thrust)... // Reduce smoke until gone if (pe) { if (pe.maxParticles > 0) pe.maxParticles--; } // Apply drag speedModifier = 0.25f; // Flame (if any) will be pointed 90 deg left or right thrustVector = (yaw > 0) ? -90 : 90; // Calculate flame size based on yaw thrustScale = 0.5f + ((yaw > 0) ? yaw : -yaw); } if (engines) { // point and scale engine flames engines.transform.localEulerAngles = new Vector3 (90, 90 + thrustVector, 0); engines.transform.localScale = new Vector3 (thrustScale, thrustScale, 1); } // remove previous roll component transform.Rotate(0, 0, (float)-roll); // Apply turning as a rotation. transform.Rotate(0, yaw * Time.deltaTime * rotationSpeed, 0); // Add in new roll component roll += (roll < roll_max) ? 1 : (roll > roll_max) ? -1 : 0; transform.Rotate(0, 0, (float)roll); // Apply thrust as a force. rigidBody.AddForce(transform.TransformDirection(0, 0, thrust * speed * speedModifier)); } //------------------------------------------------------------------------- // This function does the same as the "DestroyByContact" but is less generic. It is needed here // so the health bar can be updated and player objects can be respawned void OnTriggerEnter(Collider other) { //if (other.tag == "Bolt") // Debug.Log("OnTriggerEnter: Bolt"); //if (other.tag == "BoltEnemy") // Debug.Log("OnTriggerEnter: BoltEnemy"); if ((other.tag == "Bolt" || other.tag == "BoltEnemy") && other.tag != ourWeaponTag) { hitsToDestroy--; gGameController.UI_SetSheildLevel(hitsToDestroy); if (hitsToDestroy == 0) { if (explosion != null) { Instantiate (explosion, transform.position, transform.rotation); } Destroy (gameObject); if (CompareTag("Player")) gGameController.PlayerDead (); } else if (spark != null) { Instantiate (spark, other.gameObject.transform.position, other.gameObject.transform.rotation); } Destroy(other.gameObject); } } //------------------------------------------------------------------------- void OnCollisionEnter(Collision collision) { Debug.Log("Player: OnCollisionEnter called on tag: " + collision.gameObject.tag); if (collision.gameObject.tag == "Crystal") { if (cargoLoadCount < maxCargoLoadCount) { cargoLoadCount++; gGameController.UI_SetCargoLevel(cargoLoadCount); Destroy(collision.gameObject); audioCrystalPickup.Play(); } } } //------------------------------------------------------------------------- void DumpCrystal(Transform spawnTransform) { if (cargoLoadCount > 0 && cargoObject != null) { cargoLoadCount--; gGameController.UI_SetCargoLevel(cargoLoadCount); GameObject xtal = (GameObject)Instantiate(cargoObject, spawnTransform.position, spawnTransform.rotation); xtal.GetComponent<Rigidbody>().velocity = transform.forward * -2.0f; } } void AI_Controller(out float yaw, out float thrust) { Transform target = null; float distanceToTarget = 0; bool bArmed = false; yaw = 0; thrust = 0; if (targetPlayer != null) { distanceToTarget = Vector3.Distance (targetPlayer.position, myTransform.position); if (distanceToTarget < (maxDetectRange * 1.2f)) { target = targetPlayer.transform; bArmed = true; } } if ((target == null) && (targetCrystal != null) && (cargoLoadCount < maxCargoLoadCount)) { target = targetCrystal.transform; distanceToTarget = Vector3.Distance (targetCrystal.position, myTransform.position); } if (null != target) { Debug.DrawLine(target.position, myTransform.position, Color.red); SetLights (true); // Detect and Follow logic Vector3 targetVector = target.position - myTransform.position; Quaternion q = Quaternion.LookRotation (targetVector); yaw = (int)(q.eulerAngles.y - transform.localRotation.eulerAngles.y); // normalize from +/-360 to +/-180; if (yaw > 180) yaw -= 360; if (yaw < -180) yaw += 360; if ((yaw < 5) && (yaw > -5)) bAIFire = bArmed; yaw = yaw / 30; if (yaw > 1) yaw = 1; else if (yaw < -1) yaw = -1; AI_yaw = yaw; thrust = distanceToTarget / 10; if (bArmed && (thrust < 0.5f)) thrust = 0; if (thrust > 1) thrust = 1; } else { AI_yaw += Random.Range (-.01f, .01f); if (AI_yaw < 0) AI_yaw = 0; if (AI_yaw > 1) AI_yaw = 1; AI_thrust += Random.Range (-.02f, .02f); if (AI_thrust < 0) AI_thrust = 0; if (AI_thrust > 0.5f) AI_thrust = 0.5f; //wander here yaw = AI_yaw; thrust = AI_thrust; SetLights (false); } } public void SetTarget(GameObject newTarget) { if (newTarget.CompareTag ("Player")) { targetPlayer = newTarget.transform; } else if (newTarget.CompareTag ("Crystal")){ targetCrystal = newTarget.transform; } } private void SetLights(bool bEnable) { bLightsOn = bEnable; foreach (Light lite in lights) lite.enabled = bEnable; } }
using System; using System.Collections.Concurrent; using System.IO.Ports; using System.Security.Cryptography; namespace CaptiveAire.BACnet.Samples.Slave { public class BacnetMstpLink { private MstpRxBuffer _rxBuffer; private MstpTxBuffer _txBuffer; private BacnetMstpEnvironment _bacnetMstpEnvironment; private BacnetMstpMaster _bacnetMstpMaster; private LowLevelCommInterface _lowLevelCommInterface; private bool _rxEnabled; private bool _thisDeviceAddressed; private bool _receivedInvalidFrame = false; private bool _receivedValidFrame = false; private bool _rxTimeoutCondition = false; /*Received frame information private fields.*/ private FrameType _type; private byte _dest; private byte _source; private int _dataLength; private byte _headerCrc; private UInt16 _dataCrc; private bool _dataExpectingReply; public BacnetMstpLink (BacnetMstpEnvironment bacnetMstpEnvironment, BacnetMstpMaster bacnetMstpMaster, LowLevelCommInterface lowLevelCommInterface, MstpRxBuffer rxBuffer, MstpTxBuffer txBuffer) { _bacnetMstpEnvironment = bacnetMstpEnvironment; _bacnetMstpMaster = bacnetMstpMaster; _lowLevelCommInterface = lowLevelCommInterface; _rxBuffer = rxBuffer; _txBuffer = txBuffer; _rxEnabled = false; _rxBuffer.WriteIndex = 0; _rxBuffer.ReadIndex = 0; } private Action StateAction; /*Received frame information public properties.*/ public FrameType ReceivedFrameType { get { return _type; } set { _type = value; } } public byte ReceivedFrameDest { get { return _dest; } set { _dest = value; } } public byte ReceivedFrameSource { get { return _source; } set { _source = value; } } public int ReceivedFrameDataLength { get { return _dataLength; } set { _dataLength = value; } } public byte ReceivedFrameHeaderCrc { get { return _headerCrc; } set { _headerCrc = value; } } public UInt16 ReceivedFrameDataCrc { get { return _dataCrc; } set { _dataCrc = value; } } public bool ReceivedFrameDataExpectingReply { get { return _dataExpectingReply; } set { _dataExpectingReply = value; } } public bool ReceivedInvalidFrame { get { return _receivedInvalidFrame; } set { _receivedInvalidFrame = value; } } public bool ReceivedValidFrame { get { return _receivedValidFrame; } set { _receivedValidFrame = value; } } public bool RxTimeoutCondition { get { return _rxTimeoutCondition; } } //public int RxTimeoutSetting { get { return _serialPort.ReadTimeout; } set { _serialPort.ReadTimeout = value; } } public int RxTimeoutSetting { get { return _lowLevelCommInterface.ReadTimeout; } set { _lowLevelCommInterface.ReadTimeout = value; } } public void EnableRx() { _rxEnabled = true; } public void Open() { _lowLevelCommInterface.EnableActiveEntity(); } public void DisableRx() { _rxEnabled = false; } public void Transmit() { Console.WriteLine("Calling llci.WriteOctetFrame"); _lowLevelCommInterface.WriteOctetFrame(_txBuffer.Data, _txBuffer.NumberOfBytesToSend); } public void RunRxAnalyzer() { Console.WriteLine("Initializing Actor..."); StateAction = Search; while (_rxEnabled) { StateAction(); } } public void Search() { /*States*/ const byte WaitingForPreamble0 = 0; const byte WaitingForPreamble1 = 1; byte state = WaitingForPreamble0; byte value = 0; Console.WriteLine("Search mode started."); while (true) { if (state == WaitingForPreamble0) { try { value = _lowLevelCommInterface.WaitOnOctetToRead(); if (value == 0x55) { state = WaitingForPreamble1; BufferData(0x55); } } catch { Console.WriteLine("Timeout"); _rxTimeoutCondition = true; _rxEnabled = false; break; } } else if (state == WaitingForPreamble1) { if (_lowLevelCommInterface.WaitOnOctetToRead() == 0xff/*_serialPort.ReadByte() == 0xff*/) { StateAction = TrackIncomingFrame; BufferData(0xff); break; } Console.WriteLine("Reset back to preamble 0"); state = WaitingForPreamble0; } } } public void TrackIncomingFrame() { /*States*/ const byte WaitingForFrameType = 0; const byte WaitingForDestination = 1; const byte WaitingForSource = 2; const byte WaitingForDataLength = 3; const byte WaitingForHeaderCrc = 4; const byte Error = 5; byte state = WaitingForFrameType; byte value = 0; Console.WriteLine("Track mode started."); if (state == WaitingForFrameType) { Console.WriteLine("Waiting for frame type."); //value = (byte)_serialPort.ReadByte(); value = _lowLevelCommInterface.WaitOnOctetToRead(); if (IsFrameTypeValid(value)) { _type = (FrameType)value; state = WaitingForDestination; BufferData(value); } else { state = Error; Console.WriteLine("Malformed frame. Expected valid MSTP preamble. Going back to search."); } } if (state == WaitingForDestination) { Console.WriteLine("Waiting for destination address."); //value = (byte)_serialPort.ReadByte(); value = _lowLevelCommInterface.WaitOnOctetToRead(); //if (value == _bacnetMstpPort.PortAddress || value == 0xff) if(value == _bacnetMstpMaster.StationId) { _thisDeviceAddressed = true; } else { _thisDeviceAddressed = false; } _dest = value; BufferData(value); state = WaitingForSource; } if (state == WaitingForSource) { Console.WriteLine("Waiting for source address."); //value = (byte)_serialPort.ReadByte(); value = _lowLevelCommInterface.WaitOnOctetToRead(); if (IsSourceAddressValid(value)) { _source = value; BufferData(value); state = WaitingForDataLength; } else { state = Error; Console.WriteLine("Malformed frame. Expected valid MSTP source address. Going back to search.-------------------------------------------------"); Console.WriteLine("---------------------------------------------------------------------------------------------------------------------------"); Console.WriteLine("---------------------------------------------------------------------------------------------------------------------------"); byte[] stallSignal = new byte[] {0xcc, 0xcc, 0xcc, 0xcd}; while (true) { //_serialPort.Write(stallSignal, 0, 4); _lowLevelCommInterface.WriteOctetFrame(stallSignal, 4); } } } if (state == WaitingForDataLength) { Console.WriteLine("Waiting for data length."); //value = (byte)_serialPort.ReadByte(); value = _lowLevelCommInterface.WaitOnOctetToRead(); BufferData(value); _dataLength = (value << 8); //value = (byte)_serialPort.ReadByte(); value = _lowLevelCommInterface.WaitOnOctetToRead(); BufferData(value); _dataLength |= value; if (IsFrameTypeNonData(_type)) { if (_dataLength != 0) { Console.WriteLine("Malformed frame. Expected valid data length. Going back to search."); state = Error; } else { state = WaitingForHeaderCrc; } } else if (IsDataLengthValid(_dataLength)) { state = WaitingForHeaderCrc; } else { Console.WriteLine("Malformed frame. Expected valid data length. Going back to search."); state = Error; } } if (state == WaitingForHeaderCrc) { Console.WriteLine("Waiting for header CRC."); //value = (byte)_serialPort.ReadByte(); value = _lowLevelCommInterface.WaitOnOctetToRead(); BufferData(value); _headerCrc = value; if (IsHeaderCrcValid(_rxBuffer, 2, 6)) { StateAction = PresentFrame; Console.WriteLine("Valid CRC"); } else { Console.WriteLine("Invalid Header CRC. Going back to search."); state = Error; } } if (state == Error) { StateAction = Search; ResetBuffer(); } } public void PresentFrame() { Console.WriteLine("\nFrame Data:"); WriteFrameInfoToConsole(); ResetBuffer(); _receivedValidFrame = true; StateAction = Search; _rxEnabled = false; } public void Finish() { Console.WriteLine("\nFrame Data:"); WriteFrameInfoToConsole(); //_serialPort.Write(_rxBuffer.Data, 0, 7); _lowLevelCommInterface.WriteOctetFrame(_rxBuffer.Data, 7); ResetBuffer(); StateAction = Search; DisableRx(); Console.WriteLine("\n\nRestarting...\n\n"); } private void HandleError() { StateAction = TrackIncomingFrame; _rxBuffer.WriteIndex = 0; } /*Utility*/ private void BufferData(byte data) { _rxBuffer.Data[_rxBuffer.WriteIndex] = data; _rxBuffer.WriteIndex++; } private bool IsFrameTypeValid(byte type) { if ((type >= 0) && (type <= 7)) { return true; } return false; } private bool IsDestinationAddressValid(byte value) { if ((value <= 255)) { return true; } return false; } private bool IsAddressThisStation(byte value) { if (value == 0x10) return true; return false; } private bool IsSourceAddressValid(byte value) { if ((value >= 0) && (value <= 127) && (!IsAddressThisStation(value))) return true; return false; } private bool IsFrameTypeNonData(FrameType type) { if ((type == FrameType.BACnetDataNotExpectingReply) || (type == FrameType.BACnetDataExpectingReply)) return false; return true; } private bool IsDataLengthValid(int length) { if (length > 400) return false; return true; } private bool IsHeaderCrcValid(MstpBuffer buffer, int startIndex, int numberOfElements) { if(CrcHelpers.GetMstpHeaderCrc(_rxBuffer, 2, 6) == 0x55) return true; return false; } private void ResetBuffer() { _rxBuffer.WriteIndex = 0; } public void WriteFrameInfoToConsole() { Console.WriteLine("Frame Type = {0}", _type); Console.WriteLine("Destination = {0:X}", _dest); Console.WriteLine("Source = {0:X}", _source); Console.WriteLine("Data Length = {0}", _dataLength); Console.WriteLine("Header CRC = {0:X}", _headerCrc); Console.WriteLine("Data CRC = {0:X}", _dataCrc); Console.WriteLine("Data Expecting Replry = {0}", _dataExpectingReply); } } }
/* Copyright 2006 - 2010 Intel Corporation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.Text; using System.Collections; namespace OpenSource.UPnP { /// <summary> /// Summary description for DText. /// </summary> public class DText { /* public string ATTRMARK = "^"; public string MULTMARK = "]"; public string SUBVMARK = "/"; */ public string ATTRMARK = "\x80"; public string MULTMARK = "\x81"; public string SUBVMARK = "\x82"; private ArrayList ATTRLIST = new ArrayList(); public DText() { } public DText(string STR) { ParseString(STR); } public int DCOUNT() { return(ATTRLIST.Count); } public int DCOUNT(int A) { if (A==0) return(DCOUNT()); if (ATTRLIST.Count<A) return(0); return(((ArrayList)ATTRLIST[A-1]).Count); } public int DCOUNT(int A, int M) { if (M==0) return(DCOUNT(A)); if (ATTRLIST.Count<A) return(0); if (((ArrayList)ATTRLIST[A-1]).Count<M) return(0); return(((ArrayList)((ArrayList)ATTRLIST[A-1])[M-1]).Count); } public string this[int A] { get { StringBuilder sb = new StringBuilder(); if (A>0) { int i = DCOUNT(A); for(int x=1;x<=i;++x) { if (x!=1) sb.Append(MULTMARK); sb.Append(this[A,x]); } return(sb.ToString()); } else { int i = DCOUNT(); for(int x=1;x<=i;++x) { if (x!=1) sb.Append(ATTRMARK); sb.Append(this[x]); } return(sb.ToString()); } } set { if (A==0) { ATTRLIST = this.ParseString(value); } else { while(ATTRLIST.Count<A) ATTRLIST.Add(new ArrayList()); ArrayList t = ParseString(value); if (t.Count>1) { // ATTRMARKS in this ATTRLIST.Insert(A-1,t); } else { // No ATTRMARKS if (ATTRLIST.Count<A-1) { ATTRLIST.Insert(A-1,t[0]); } else { ATTRLIST[A-1] = t[0]; } } } } } public string this[int A, int M] { get { if (M==0) return(this[A]); StringBuilder sb = new StringBuilder(); int i = DCOUNT(A,M); for(int x=1;x<=i;++x) { if (x!=1) sb.Append(SUBVMARK); sb.Append(this[A,M,x]); } return(sb.ToString()); } set { if (M==0) { this[A] = value; return; } while(ATTRLIST.Count<A) ATTRLIST.Add(new ArrayList()); while(((ArrayList)ATTRLIST[A-1]).Count<M) ((ArrayList)ATTRLIST[A-1]).Add(new ArrayList()); ArrayList t = ParseString(value); if (t.Count>1) { // There are ATTRMARKs in this ATTRLIST.Insert(A-1,t); } else { if (((ArrayList)t[0]).Count>1) { // There are MULTMARKS in this ((ArrayList)ATTRLIST[A-1]).Insert(M-1,t[0]); } else { // Only SUBVMARK stuff ((ArrayList)ATTRLIST[A-1])[M-1] = ((ArrayList)((ArrayList)t[0])[0]); } } } } public string this[int A, int M, int V] { get { if (V==0) return(this[A,M]); try { return((string)((ArrayList)((ArrayList)ATTRLIST[A-1])[M-1])[V-1]); } catch(Exception ex) { OpenSource.Utilities.EventLogger.Log(ex); return (""); } } set { if (V==0) { this[A,M] = value; return; } while(ATTRLIST.Count<A) ATTRLIST.Add(new ArrayList()); while(((ArrayList)ATTRLIST[A-1]).Count<M) ((ArrayList)ATTRLIST[A-1]).Add(new ArrayList()); while(((ArrayList)((ArrayList)ATTRLIST[A-1])[M-1]).Count<V) ((ArrayList)((ArrayList)ATTRLIST[A-1])[M-1]).Add(new ArrayList()); ((ArrayList)((ArrayList)ATTRLIST[A-1])[M-1])[V-1] = value; } } private ArrayList ParseString(string STR) { if (null == STR || 0 == STR.Length) { ArrayList Temp = new ArrayList(); Temp.Add(new ArrayList()); ((ArrayList)Temp[0]).Add(new ArrayList()); return(Temp); } int ATTRCTR = 1; int MULTCTR = 1; int SUBVCTR = 1; StringBuilder sb = new StringBuilder(); ArrayList _ATTRLIST = new ArrayList(); int i=0; while(i<STR.Length) { while(_ATTRLIST.Count<ATTRCTR) _ATTRLIST.Add(new ArrayList()); while(((ArrayList)_ATTRLIST[ATTRCTR-1]).Count<MULTCTR) ((ArrayList)_ATTRLIST[ATTRCTR-1]).Add(new ArrayList()); while(((ArrayList)((ArrayList)_ATTRLIST[ATTRCTR-1])[MULTCTR-1]).Count<SUBVCTR) ((ArrayList)((ArrayList)_ATTRLIST[ATTRCTR-1])[MULTCTR-1]).Add(new ArrayList()); string t = STR.Substring(i,1); if (t==ATTRMARK.Substring(0,1) || t==MULTMARK.Substring(0,1) || t==SUBVMARK.Substring(0,1)) { bool isATTRMARK = false; bool isMULTMARK = false; bool isSUBVMARK = false; if (i+ATTRMARK.Length<=STR.Length) { if (STR.Substring(i,ATTRMARK.Length)==ATTRMARK) { isATTRMARK = true; i+=(ATTRMARK.Length-1); } } if (i+MULTMARK.Length<=STR.Length) { if (STR.Substring(i,MULTMARK.Length)==MULTMARK) { isMULTMARK = true; i+=(MULTMARK.Length-1); } } if (i+SUBVMARK.Length<=STR.Length) { if (STR.Substring(i,SUBVMARK.Length)==SUBVMARK) { isSUBVMARK = true; i+=(SUBVMARK.Length-1); } } if (isATTRMARK||isMULTMARK||isSUBVMARK) { ((ArrayList)((ArrayList)_ATTRLIST[ATTRCTR-1])[MULTCTR-1])[SUBVCTR-1] = sb.ToString(); sb = new StringBuilder(); if (isATTRMARK) { ++ATTRCTR; MULTCTR = 1; SUBVCTR = 1; } if (isMULTMARK) { ++MULTCTR; SUBVCTR = 1; } if (isSUBVMARK) ++SUBVCTR; } else { sb.Append(t); } } else { sb.Append(t); } ++i; } if (sb.Length>0) { ((ArrayList)((ArrayList)_ATTRLIST[ATTRCTR-1])[MULTCTR-1])[SUBVCTR-1] = sb.ToString(); } else { while(_ATTRLIST.Count<ATTRCTR) _ATTRLIST.Add(new ArrayList()); while(((ArrayList)_ATTRLIST[ATTRCTR-1]).Count<MULTCTR) ((ArrayList)_ATTRLIST[ATTRCTR-1]).Add(new ArrayList()); while(((ArrayList)((ArrayList)_ATTRLIST[ATTRCTR-1])[MULTCTR-1]).Count<SUBVCTR) ((ArrayList)((ArrayList)_ATTRLIST[ATTRCTR-1])[MULTCTR-1]).Add(new ArrayList()); ((ArrayList)((ArrayList)_ATTRLIST[ATTRCTR-1])[MULTCTR-1])[SUBVCTR-1] = ""; } return(_ATTRLIST); } } }
using System; using System.ComponentModel; using System.Linq; using Eto.Drawing; using Eto.Forms; using Eto.GtkSharp.Drawing; using Eto.GtkSharp.Forms; using Eto.GtkSharp.Forms.Menu; namespace Eto.GtkSharp.Forms { public interface IGtkWindow { bool CloseWindow(Action<CancelEventArgs> closing = null); Gtk.Window Control { get; } } public class GtkShrinkableVBox : Gtk.VBox { public GtkShrinkableVBox() { } public GtkShrinkableVBox(Gtk.Widget child) { if (child != null) PackStart(child, true, true, 0); } #if GTK3 protected override void OnGetPreferredWidth(out int minimum_width, out int natural_width) { base.OnGetPreferredWidth(out minimum_width, out natural_width); minimum_width = 0; } protected override void OnGetPreferredHeight(out int minimum_height, out int natural_height) { base.OnGetPreferredHeight(out minimum_height, out natural_height); minimum_height = 0; } #endif } public abstract class GtkWindow<TControl, TWidget, TCallback> : GtkPanel<TControl, TWidget, TCallback>, Window.IHandler, IGtkWindow where TControl: Gtk.Window where TWidget: Window where TCallback: Window.ICallback { Gtk.VBox vbox; readonly Gtk.VBox actionvbox; readonly Gtk.Box topToolbarBox; Gtk.Box menuBox; Gtk.Box containerBox; readonly Gtk.Box bottomToolbarBox; MenuBar menuBar; Icon icon; Eto.Forms.ToolBar toolBar; Gtk.AccelGroup accelGroup; Rectangle? restoreBounds; Point? currentLocation; Size? initialSize; WindowState state; WindowStyle style; bool topmost; protected GtkWindow() { vbox = new Gtk.VBox(); actionvbox = new Gtk.VBox(); menuBox = new Gtk.HBox(); topToolbarBox = new Gtk.VBox(); containerBox = new GtkShrinkableVBox(); containerBox.Visible = true; bottomToolbarBox = new Gtk.VBox(); actionvbox.PackStart(menuBox, false, false, 0); actionvbox.PackStart(topToolbarBox, false, false, 0); vbox.PackStart(containerBox, true, true, 0); vbox.PackStart(bottomToolbarBox, false, false, 0); } protected override Color DefaultBackgroundColor { get { return Control.GetBackground(); } } protected override bool UseMinimumSizeRequested { get { return false; } } public override Size MinimumSize { get { return base.MinimumSize; } set { base.MinimumSize = value; } } public Gtk.Widget WindowContentControl { get { return vbox; } } public Gtk.Widget WindowActionControl { get { return actionvbox; } } public override Gtk.Widget ContainerContentControl { get { return containerBox; } } public bool Resizable { get { return Control.Resizable; } set { Control.Resizable = value; #if GTK2 Control.AllowGrow = value; #else Control.HasResizeGrip = value; #endif } } public bool Minimizable { get; set; } public bool Maximizable { get; set; } public bool ShowInTaskbar { get { return !Control.SkipTaskbarHint; } set { Control.SkipTaskbarHint = !value; } } public bool Topmost { get { return topmost; } set { if (topmost != value) { topmost = value; Control.KeepAbove = topmost; } } } public WindowStyle WindowStyle { get { return style; } set { if (style != value) { style = value; switch (style) { case WindowStyle.Default: Control.Decorated = true; break; case WindowStyle.None: Control.Decorated = false; break; default: throw new NotSupportedException(); } } } } public override Size Size { get { var window = Control.GetWindow(); return window != null ? window.FrameExtents.Size.ToEto() : initialSize ?? Control.DefaultSize.ToEto(); } set { var window = Control.GetWindow(); if (window != null) { var diff = window.FrameExtents.Size.ToEto() - Control.Allocation.Size.ToEto(); Control.Resize(value.Width - diff.Width, value.Height - diff.Height); } else { Control.Resize(value.Width, value.Height); initialSize = value; } } } void HandleControlRealized(object sender, EventArgs e) { var allocation = Control.Allocation.Size; var minSize = MinimumSize; if (initialSize != null) { var gdkWindow = Control.GetWindow(); var frameExtents = gdkWindow.FrameExtents.Size.ToEto(); // HACK: get twice to get 'real' size? Ubuntu 14.04 returns inflated size the first call. frameExtents = gdkWindow.FrameExtents.Size.ToEto(); var diff = frameExtents - Control.Allocation.Size.ToEto(); allocation.Width = initialSize.Value.Width - diff.Width; allocation.Height = initialSize.Value.Height - diff.Height; initialSize = null; } if (Resizable) { Control.Resize(allocation.Width, allocation.Height); } else { // when not resizable, Control.Resize doesn't work minSize.Width = Math.Max(minSize.Width, allocation.Width); minSize.Height = Math.Max(minSize.Height, allocation.Height); } // set initial minimum size Control.SetSizeRequest(minSize.Width, minSize.Height); containerBox.SetSizeRequest(-1, -1); // only do this the first time Control.Realized -= HandleControlRealized; } public override Size ClientSize { get { return containerBox.IsRealized ? containerBox.Allocation.Size.ToEto() : containerBox.GetPreferredSize().ToEto(); } set { if (Control.IsRealized) { var diff = vbox.Allocation.Size.ToEto() - containerBox.Allocation.Size.ToEto(); Control.Resize(value.Width + diff.Width, value.Height + diff.Height); } else { containerBox.SetSizeRequest(value.Width, value.Height); } } } protected override void Initialize() { base.Initialize(); HandleEvent(Window.WindowStateChangedEvent); // to set restore bounds properly HandleEvent(Window.ClosingEvent); // to chain application termination events HandleEvent(Eto.Forms.Control.SizeChangedEvent); // for RestoreBounds HandleEvent(Window.LocationChangedEvent); // for RestoreBounds Control.SetSizeRequest(-1, -1); Control.Realized += HandleControlRealized; #if GTK2 Control.AllowShrink = false; #endif } public override void AttachEvent(string id) { switch (id) { case Eto.Forms.Control.KeyDownEvent: EventControl.AddEvents((int)Gdk.EventMask.KeyPressMask); EventControl.KeyPressEvent += Connector.HandleWindowKeyPressEvent; break; case Window.ClosedEvent: HandleEvent(Window.ClosingEvent); break; case Window.ClosingEvent: Control.DeleteEvent += Connector.HandleDeleteEvent; break; case Eto.Forms.Control.ShownEvent: Control.Shown += Connector.HandleShownEvent; break; case Window.WindowStateChangedEvent: Connector.OldState = WindowState; Control.WindowStateEvent += Connector.HandleWindowStateEvent; break; case Eto.Forms.Control.SizeChangedEvent: Control.SizeAllocated += Connector.HandleWindowSizeAllocated; break; case Window.LocationChangedEvent: Control.ConfigureEvent += Connector.HandleConfigureEvent; break; default: base.AttachEvent(id); break; } } protected new GtkWindowConnector Connector { get { return (GtkWindowConnector)base.Connector; } } protected override WeakConnector CreateConnector() { return new GtkWindowConnector(); } protected class GtkWindowConnector : GtkPanelEventConnector { Size? oldSize; public WindowState OldState { get; set; } public new GtkWindow<TControl, TWidget, TCallback> Handler { get { return (GtkWindow<TControl, TWidget, TCallback>)base.Handler; } } public void HandleDeleteEvent(object o, Gtk.DeleteEventArgs args) { args.RetVal = !Handler.CloseWindow(); } public void HandleShownEvent(object sender, EventArgs e) { Handler.Callback.OnShown(Handler.Widget, EventArgs.Empty); } public void HandleWindowStateEvent(object o, Gtk.WindowStateEventArgs args) { var handler = Handler; if (handler == null) return; var windowState = handler.WindowState; if (windowState == WindowState.Normal) { if (args.Event.ChangedMask.HasFlag(Gdk.WindowState.Maximized) && !args.Event.NewWindowState.HasFlag(Gdk.WindowState.Maximized)) { handler.restoreBounds = handler.Widget.Bounds; } else if (args.Event.ChangedMask.HasFlag(Gdk.WindowState.Iconified) && !args.Event.NewWindowState.HasFlag(Gdk.WindowState.Iconified)) { handler.restoreBounds = handler.Widget.Bounds; } else if (args.Event.ChangedMask.HasFlag(Gdk.WindowState.Fullscreen) && !args.Event.NewWindowState.HasFlag(Gdk.WindowState.Fullscreen)) { handler.restoreBounds = handler.Widget.Bounds; } } if (windowState != OldState) { OldState = windowState; Handler.Callback.OnWindowStateChanged(Handler.Widget, EventArgs.Empty); } } // do not connect before, otherwise it is sent before sending to child public void HandleWindowKeyPressEvent(object o, Gtk.KeyPressEventArgs args) { var e = args.Event.ToEto(); if (e != null) { Handler.Callback.OnKeyDown(Handler.Widget, e); args.RetVal = e.Handled; } } public void HandleWindowSizeAllocated(object o, Gtk.SizeAllocatedArgs args) { var handler = Handler; var newSize = handler.Size; if (handler.Control.IsRealized && oldSize != newSize) { handler.Callback.OnSizeChanged(Handler.Widget, EventArgs.Empty); if (handler.WindowState == WindowState.Normal) handler.restoreBounds = handler.Widget.Bounds; oldSize = newSize; } } Point? oldLocation; [GLib.ConnectBefore] public void HandleConfigureEvent(object o, Gtk.ConfigureEventArgs args) { var handler = Handler; if (handler == null) return; handler.currentLocation = new Point(args.Event.X, args.Event.Y); if (handler.Control.IsRealized && handler.Widget.Loaded && oldLocation != handler.currentLocation) { handler.Callback.OnLocationChanged(handler.Widget, EventArgs.Empty); if (handler.WindowState == WindowState.Normal) handler.restoreBounds = handler.Widget.Bounds; oldLocation = handler.currentLocation; } handler.currentLocation = null; } } public MenuBar Menu { get { return menuBar; } set { if (menuBar != null) menuBox.Remove((Gtk.Widget)menuBar.ControlObject); if (accelGroup != null) Control.RemoveAccelGroup(accelGroup); accelGroup = new Gtk.AccelGroup(); Control.AddAccelGroup(accelGroup); // set accelerators menuBar = value; var handler = menuBar != null ? menuBar.Handler as IMenuHandler : null; if (handler != null) handler.SetAccelGroup(accelGroup); if (value != null) { menuBox.PackStart((Gtk.Widget)value.ControlObject, true, true, 0); ((Gtk.Widget)value.ControlObject).ShowAll(); } } } protected override void SetContainerContent(Gtk.Widget content) { containerBox.PackStart(content, true, true, 0); } public string Title { get { return Control.Title; } set { Control.Title = value; } } public bool CloseWindow(Action<CancelEventArgs> closing = null) { var args = new CancelEventArgs(); Callback.OnClosing(Widget, args); var shouldQuit = false; if (!args.Cancel) { if (closing != null) closing(args); else { var windows = Gdk.Screen.Default.ToplevelWindows; if (windows.Count(r => r.IsViewable) == 1 && ReferenceEquals(windows.First(r => r.IsViewable), Control.GetWindow())) { var app = ((ApplicationHandler)Application.Instance.Handler); app.Callback.OnTerminating(app.Widget, args); shouldQuit = !args.Cancel; } } } if (!args.Cancel) { Callback.OnClosed(Widget, EventArgs.Empty); if (shouldQuit) Gtk.Application.Quit(); } return !args.Cancel; } public virtual void Close() { if (CloseWindow()) { Control.Hide(); } } protected override void Dispose(bool disposing) { if (disposing) { Control.Destroy(); if (menuBox != null) { menuBox.Dispose(); menuBox = null; } if (vbox != null) { vbox.Dispose(); vbox = null; } if (containerBox != null) { containerBox.Dispose(); containerBox = null; } } base.Dispose(disposing); } public Eto.Forms.ToolBar ToolBar { get { return toolBar; } set { if (toolBar != null) topToolbarBox.Remove((Gtk.Widget)toolBar.ControlObject); toolBar = value; if (toolBar != null) topToolbarBox.Add((Gtk.Widget)toolBar.ControlObject); topToolbarBox.ShowAll(); } } public Icon Icon { get { return icon; } set { icon = value; Control.Icon = ((IconHandler)icon.Handler).Pixbuf; } } public new Point Location { get { if (currentLocation != null) return currentLocation.Value; int x, y; Control.GetPosition(out x, out y); return new Point(x, y); } set { Control.Move(value.X, value.Y); } } public WindowState WindowState { get { var gdkWindow = Control.GetWindow(); if (gdkWindow == null) return state; if (gdkWindow.State.HasFlag(Gdk.WindowState.Iconified)) return WindowState.Minimized; if (gdkWindow.State.HasFlag(Gdk.WindowState.Maximized)) return WindowState.Maximized; if (gdkWindow.State.HasFlag(Gdk.WindowState.Fullscreen)) return WindowState.Maximized; return WindowState.Normal; } set { if (state != value) { state = value; var gdkWindow = Control.GetWindow(); switch (value) { case WindowState.Maximized: if (gdkWindow != null) { if (gdkWindow.State.HasFlag(Gdk.WindowState.Fullscreen)) Control.Unfullscreen(); if (gdkWindow.State.HasFlag(Gdk.WindowState.Iconified)) Control.Deiconify(); } Control.Maximize(); break; case WindowState.Minimized: Control.Iconify(); break; case WindowState.Normal: if (gdkWindow != null) { if (gdkWindow.State.HasFlag(Gdk.WindowState.Fullscreen)) Control.Unfullscreen(); if (gdkWindow.State.HasFlag(Gdk.WindowState.Maximized)) Control.Unmaximize(); if (gdkWindow.State.HasFlag(Gdk.WindowState.Iconified)) Control.Deiconify(); } break; } } } } public Rectangle RestoreBounds { get { return WindowState == WindowState.Normal ? Widget.Bounds : restoreBounds ?? Widget.Bounds; } } public double Opacity { get { return Control.Opacity; } set { Control.Opacity = value; } } Gtk.Window IGtkWindow.Control { get { return Control; } } public Screen Screen { get { var screen = Control.Screen; var gdkWindow = Control.GetWindow(); if (screen != null && gdkWindow != null) { var monitor = screen.GetMonitorAtWindow(gdkWindow); return new Screen(new ScreenHandler(screen, monitor)); } return null; } } public void BringToFront() { Control.Present(); } public void SendToBack() { var gdkWindow = Control.GetWindow(); if (gdkWindow != null) gdkWindow.Lower(); } public virtual void SetOwner(Window owner) { Control.TransientFor = owner.ToGtk(); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Runtime.InteropServices; using System.Runtime.Serialization; using GlmSharp.Swizzle; // ReSharper disable InconsistentNaming namespace GlmSharp { /// <summary> /// Static class that contains static glm functions /// </summary> public static partial class glm { /// <summary> /// Returns an object that can be used for arbitrary swizzling (e.g. swizzle.zy) /// </summary> public static swizzle_dvec2 swizzle(dvec2 v) => v.swizzle; /// <summary> /// Returns an array with all values /// </summary> public static double[] Values(dvec2 v) => v.Values; /// <summary> /// Returns an enumerator that iterates through all components. /// </summary> public static IEnumerator<double> GetEnumerator(dvec2 v) => v.GetEnumerator(); /// <summary> /// Returns a string representation of this vector using ', ' as a seperator. /// </summary> public static string ToString(dvec2 v) => v.ToString(); /// <summary> /// Returns a string representation of this vector using a provided seperator. /// </summary> public static string ToString(dvec2 v, string sep) => v.ToString(sep); /// <summary> /// Returns a string representation of this vector using a provided seperator and a format provider for each component. /// </summary> public static string ToString(dvec2 v, string sep, IFormatProvider provider) => v.ToString(sep, provider); /// <summary> /// Returns a string representation of this vector using a provided seperator and a format for each component. /// </summary> public static string ToString(dvec2 v, string sep, string format) => v.ToString(sep, format); /// <summary> /// Returns a string representation of this vector using a provided seperator and a format and format provider for each component. /// </summary> public static string ToString(dvec2 v, string sep, string format, IFormatProvider provider) => v.ToString(sep, format, provider); /// <summary> /// Returns the number of components (2). /// </summary> public static int Count(dvec2 v) => v.Count; /// <summary> /// Returns true iff this equals rhs component-wise. /// </summary> public static bool Equals(dvec2 v, dvec2 rhs) => v.Equals(rhs); /// <summary> /// Returns true iff this equals rhs type- and component-wise. /// </summary> public static bool Equals(dvec2 v, object obj) => v.Equals(obj); /// <summary> /// Returns a hash code for this instance. /// </summary> public static int GetHashCode(dvec2 v) => v.GetHashCode(); /// <summary> /// Returns true iff distance between lhs and rhs is less than or equal to epsilon /// </summary> public static bool ApproxEqual(dvec2 lhs, dvec2 rhs, double eps = 0.1d) => dvec2.ApproxEqual(lhs, rhs, eps); /// <summary> /// Returns a bvec2 from component-wise application of Equal (lhs == rhs). /// </summary> public static bvec2 Equal(dvec2 lhs, dvec2 rhs) => dvec2.Equal(lhs, rhs); /// <summary> /// Returns a bvec2 from component-wise application of NotEqual (lhs != rhs). /// </summary> public static bvec2 NotEqual(dvec2 lhs, dvec2 rhs) => dvec2.NotEqual(lhs, rhs); /// <summary> /// Returns a bvec2 from component-wise application of GreaterThan (lhs &gt; rhs). /// </summary> public static bvec2 GreaterThan(dvec2 lhs, dvec2 rhs) => dvec2.GreaterThan(lhs, rhs); /// <summary> /// Returns a bvec2 from component-wise application of GreaterThanEqual (lhs &gt;= rhs). /// </summary> public static bvec2 GreaterThanEqual(dvec2 lhs, dvec2 rhs) => dvec2.GreaterThanEqual(lhs, rhs); /// <summary> /// Returns a bvec2 from component-wise application of LesserThan (lhs &lt; rhs). /// </summary> public static bvec2 LesserThan(dvec2 lhs, dvec2 rhs) => dvec2.LesserThan(lhs, rhs); /// <summary> /// Returns a bvec2 from component-wise application of LesserThanEqual (lhs &lt;= rhs). /// </summary> public static bvec2 LesserThanEqual(dvec2 lhs, dvec2 rhs) => dvec2.LesserThanEqual(lhs, rhs); /// <summary> /// Returns a bvec2 from component-wise application of IsInfinity (double.IsInfinity(v)). /// </summary> public static bvec2 IsInfinity(dvec2 v) => dvec2.IsInfinity(v); /// <summary> /// Returns a bvec2 from component-wise application of IsFinite (!double.IsNaN(v) &amp;&amp; !double.IsInfinity(v)). /// </summary> public static bvec2 IsFinite(dvec2 v) => dvec2.IsFinite(v); /// <summary> /// Returns a bvec2 from component-wise application of IsNaN (double.IsNaN(v)). /// </summary> public static bvec2 IsNaN(dvec2 v) => dvec2.IsNaN(v); /// <summary> /// Returns a bvec2 from component-wise application of IsNegativeInfinity (double.IsNegativeInfinity(v)). /// </summary> public static bvec2 IsNegativeInfinity(dvec2 v) => dvec2.IsNegativeInfinity(v); /// <summary> /// Returns a bvec2 from component-wise application of IsPositiveInfinity (double.IsPositiveInfinity(v)). /// </summary> public static bvec2 IsPositiveInfinity(dvec2 v) => dvec2.IsPositiveInfinity(v); /// <summary> /// Returns a dvec2 from component-wise application of Abs (Math.Abs(v)). /// </summary> public static dvec2 Abs(dvec2 v) => dvec2.Abs(v); /// <summary> /// Returns a dvec2 from component-wise application of HermiteInterpolationOrder3 ((3 - 2 * v) * v * v). /// </summary> public static dvec2 HermiteInterpolationOrder3(dvec2 v) => dvec2.HermiteInterpolationOrder3(v); /// <summary> /// Returns a dvec2 from component-wise application of HermiteInterpolationOrder5 (((6 * v - 15) * v + 10) * v * v * v). /// </summary> public static dvec2 HermiteInterpolationOrder5(dvec2 v) => dvec2.HermiteInterpolationOrder5(v); /// <summary> /// Returns a dvec2 from component-wise application of Sqr (v * v). /// </summary> public static dvec2 Sqr(dvec2 v) => dvec2.Sqr(v); /// <summary> /// Returns a dvec2 from component-wise application of Pow2 (v * v). /// </summary> public static dvec2 Pow2(dvec2 v) => dvec2.Pow2(v); /// <summary> /// Returns a dvec2 from component-wise application of Pow3 (v * v * v). /// </summary> public static dvec2 Pow3(dvec2 v) => dvec2.Pow3(v); /// <summary> /// Returns a dvec2 from component-wise application of Step (v &gt;= 0.0 ? 1.0 : 0.0). /// </summary> public static dvec2 Step(dvec2 v) => dvec2.Step(v); /// <summary> /// Returns a dvec2 from component-wise application of Sqrt ((double)Math.Sqrt((double)v)). /// </summary> public static dvec2 Sqrt(dvec2 v) => dvec2.Sqrt(v); /// <summary> /// Returns a dvec2 from component-wise application of InverseSqrt ((double)(1.0 / Math.Sqrt((double)v))). /// </summary> public static dvec2 InverseSqrt(dvec2 v) => dvec2.InverseSqrt(v); /// <summary> /// Returns a ivec2 from component-wise application of Sign (Math.Sign(v)). /// </summary> public static ivec2 Sign(dvec2 v) => dvec2.Sign(v); /// <summary> /// Returns a dvec2 from component-wise application of Max (Math.Max(lhs, rhs)). /// </summary> public static dvec2 Max(dvec2 lhs, dvec2 rhs) => dvec2.Max(lhs, rhs); /// <summary> /// Returns a dvec2 from component-wise application of Min (Math.Min(lhs, rhs)). /// </summary> public static dvec2 Min(dvec2 lhs, dvec2 rhs) => dvec2.Min(lhs, rhs); /// <summary> /// Returns a dvec2 from component-wise application of Pow ((double)Math.Pow((double)lhs, (double)rhs)). /// </summary> public static dvec2 Pow(dvec2 lhs, dvec2 rhs) => dvec2.Pow(lhs, rhs); /// <summary> /// Returns a dvec2 from component-wise application of Log ((double)Math.Log((double)lhs, (double)rhs)). /// </summary> public static dvec2 Log(dvec2 lhs, dvec2 rhs) => dvec2.Log(lhs, rhs); /// <summary> /// Returns a dvec2 from component-wise application of Clamp (Math.Min(Math.Max(v, min), max)). /// </summary> public static dvec2 Clamp(dvec2 v, dvec2 min, dvec2 max) => dvec2.Clamp(v, min, max); /// <summary> /// Returns a dvec2 from component-wise application of Mix (min * (1-a) + max * a). /// </summary> public static dvec2 Mix(dvec2 min, dvec2 max, dvec2 a) => dvec2.Mix(min, max, a); /// <summary> /// Returns a dvec2 from component-wise application of Lerp (min * (1-a) + max * a). /// </summary> public static dvec2 Lerp(dvec2 min, dvec2 max, dvec2 a) => dvec2.Lerp(min, max, a); /// <summary> /// Returns a dvec2 from component-wise application of Smoothstep (((v - edge0) / (edge1 - edge0)).Clamp().HermiteInterpolationOrder3()). /// </summary> public static dvec2 Smoothstep(dvec2 edge0, dvec2 edge1, dvec2 v) => dvec2.Smoothstep(edge0, edge1, v); /// <summary> /// Returns a dvec2 from component-wise application of Smootherstep (((v - edge0) / (edge1 - edge0)).Clamp().HermiteInterpolationOrder5()). /// </summary> public static dvec2 Smootherstep(dvec2 edge0, dvec2 edge1, dvec2 v) => dvec2.Smootherstep(edge0, edge1, v); /// <summary> /// Returns a dvec2 from component-wise application of Fma (a * b + c). /// </summary> public static dvec2 Fma(dvec2 a, dvec2 b, dvec2 c) => dvec2.Fma(a, b, c); /// <summary> /// OuterProduct treats the first parameter c as a column vector (matrix with one column) and the second parameter r as a row vector (matrix with one row) and does a linear algebraic matrix multiply c * r, yielding a matrix whose number of rows is the number of components in c and whose number of columns is the number of components in r. /// </summary> public static dmat2 OuterProduct(dvec2 c, dvec2 r) => dvec2.OuterProduct(c, r); /// <summary> /// OuterProduct treats the first parameter c as a column vector (matrix with one column) and the second parameter r as a row vector (matrix with one row) and does a linear algebraic matrix multiply c * r, yielding a matrix whose number of rows is the number of components in c and whose number of columns is the number of components in r. /// </summary> public static dmat3x2 OuterProduct(dvec2 c, dvec3 r) => dvec2.OuterProduct(c, r); /// <summary> /// OuterProduct treats the first parameter c as a column vector (matrix with one column) and the second parameter r as a row vector (matrix with one row) and does a linear algebraic matrix multiply c * r, yielding a matrix whose number of rows is the number of components in c and whose number of columns is the number of components in r. /// </summary> public static dmat4x2 OuterProduct(dvec2 c, dvec4 r) => dvec2.OuterProduct(c, r); /// <summary> /// Returns a dvec2 from component-wise application of Add (lhs + rhs). /// </summary> public static dvec2 Add(dvec2 lhs, dvec2 rhs) => dvec2.Add(lhs, rhs); /// <summary> /// Returns a dvec2 from component-wise application of Sub (lhs - rhs). /// </summary> public static dvec2 Sub(dvec2 lhs, dvec2 rhs) => dvec2.Sub(lhs, rhs); /// <summary> /// Returns a dvec2 from component-wise application of Mul (lhs * rhs). /// </summary> public static dvec2 Mul(dvec2 lhs, dvec2 rhs) => dvec2.Mul(lhs, rhs); /// <summary> /// Returns a dvec2 from component-wise application of Div (lhs / rhs). /// </summary> public static dvec2 Div(dvec2 lhs, dvec2 rhs) => dvec2.Div(lhs, rhs); /// <summary> /// Returns a dvec2 from component-wise application of Modulo (lhs % rhs). /// </summary> public static dvec2 Modulo(dvec2 lhs, dvec2 rhs) => dvec2.Modulo(lhs, rhs); /// <summary> /// Returns a dvec2 from component-wise application of Degrees (Radians-To-Degrees Conversion). /// </summary> public static dvec2 Degrees(dvec2 v) => dvec2.Degrees(v); /// <summary> /// Returns a dvec2 from component-wise application of Radians (Degrees-To-Radians Conversion). /// </summary> public static dvec2 Radians(dvec2 v) => dvec2.Radians(v); /// <summary> /// Returns a dvec2 from component-wise application of Acos ((double)Math.Acos((double)v)). /// </summary> public static dvec2 Acos(dvec2 v) => dvec2.Acos(v); /// <summary> /// Returns a dvec2 from component-wise application of Asin ((double)Math.Asin((double)v)). /// </summary> public static dvec2 Asin(dvec2 v) => dvec2.Asin(v); /// <summary> /// Returns a dvec2 from component-wise application of Atan ((double)Math.Atan((double)v)). /// </summary> public static dvec2 Atan(dvec2 v) => dvec2.Atan(v); /// <summary> /// Returns a dvec2 from component-wise application of Cos ((double)Math.Cos((double)v)). /// </summary> public static dvec2 Cos(dvec2 v) => dvec2.Cos(v); /// <summary> /// Returns a dvec2 from component-wise application of Cosh ((double)Math.Cosh((double)v)). /// </summary> public static dvec2 Cosh(dvec2 v) => dvec2.Cosh(v); /// <summary> /// Returns a dvec2 from component-wise application of Exp ((double)Math.Exp((double)v)). /// </summary> public static dvec2 Exp(dvec2 v) => dvec2.Exp(v); /// <summary> /// Returns a dvec2 from component-wise application of Log ((double)Math.Log((double)v)). /// </summary> public static dvec2 Log(dvec2 v) => dvec2.Log(v); /// <summary> /// Returns a dvec2 from component-wise application of Log2 ((double)Math.Log((double)v, 2)). /// </summary> public static dvec2 Log2(dvec2 v) => dvec2.Log2(v); /// <summary> /// Returns a dvec2 from component-wise application of Log10 ((double)Math.Log10((double)v)). /// </summary> public static dvec2 Log10(dvec2 v) => dvec2.Log10(v); /// <summary> /// Returns a dvec2 from component-wise application of Floor ((double)Math.Floor(v)). /// </summary> public static dvec2 Floor(dvec2 v) => dvec2.Floor(v); /// <summary> /// Returns a dvec2 from component-wise application of Ceiling ((double)Math.Ceiling(v)). /// </summary> public static dvec2 Ceiling(dvec2 v) => dvec2.Ceiling(v); /// <summary> /// Returns a dvec2 from component-wise application of Round ((double)Math.Round(v)). /// </summary> public static dvec2 Round(dvec2 v) => dvec2.Round(v); /// <summary> /// Returns a dvec2 from component-wise application of Sin ((double)Math.Sin((double)v)). /// </summary> public static dvec2 Sin(dvec2 v) => dvec2.Sin(v); /// <summary> /// Returns a dvec2 from component-wise application of Sinh ((double)Math.Sinh((double)v)). /// </summary> public static dvec2 Sinh(dvec2 v) => dvec2.Sinh(v); /// <summary> /// Returns a dvec2 from component-wise application of Tan ((double)Math.Tan((double)v)). /// </summary> public static dvec2 Tan(dvec2 v) => dvec2.Tan(v); /// <summary> /// Returns a dvec2 from component-wise application of Tanh ((double)Math.Tanh((double)v)). /// </summary> public static dvec2 Tanh(dvec2 v) => dvec2.Tanh(v); /// <summary> /// Returns a dvec2 from component-wise application of Truncate ((double)Math.Truncate((double)v)). /// </summary> public static dvec2 Truncate(dvec2 v) => dvec2.Truncate(v); /// <summary> /// Returns a dvec2 from component-wise application of Fract ((double)(v - Math.Floor(v))). /// </summary> public static dvec2 Fract(dvec2 v) => dvec2.Fract(v); /// <summary> /// Returns a dvec2 from component-wise application of Trunc ((long)(v)). /// </summary> public static dvec2 Trunc(dvec2 v) => dvec2.Trunc(v); /// <summary> /// Returns the minimal component of this vector. /// </summary> public static double MinElement(dvec2 v) => v.MinElement; /// <summary> /// Returns the maximal component of this vector. /// </summary> public static double MaxElement(dvec2 v) => v.MaxElement; /// <summary> /// Returns the euclidean length of this vector. /// </summary> public static double Length(dvec2 v) => v.Length; /// <summary> /// Returns the squared euclidean length of this vector. /// </summary> public static double LengthSqr(dvec2 v) => v.LengthSqr; /// <summary> /// Returns the sum of all components. /// </summary> public static double Sum(dvec2 v) => v.Sum; /// <summary> /// Returns the euclidean norm of this vector. /// </summary> public static double Norm(dvec2 v) => v.Norm; /// <summary> /// Returns the one-norm of this vector. /// </summary> public static double Norm1(dvec2 v) => v.Norm1; /// <summary> /// Returns the two-norm (euclidean length) of this vector. /// </summary> public static double Norm2(dvec2 v) => v.Norm2; /// <summary> /// Returns the max-norm of this vector. /// </summary> public static double NormMax(dvec2 v) => v.NormMax; /// <summary> /// Returns the p-norm of this vector. /// </summary> public static double NormP(dvec2 v, double p) => v.NormP(p); /// <summary> /// Returns a copy of this vector with length one (undefined if this has zero length). /// </summary> public static dvec2 Normalized(dvec2 v) => v.Normalized; /// <summary> /// Returns a copy of this vector with length one (returns zero if length is zero). /// </summary> public static dvec2 NormalizedSafe(dvec2 v) => v.NormalizedSafe; /// <summary> /// Returns the vector angle (atan2(y, x)) in radians. /// </summary> public static double Angle(dvec2 v) => v.Angle; /// <summary> /// Returns a 2D vector that was rotated by a given angle in radians (CAUTION: result is casted and may be truncated). /// </summary> public static dvec2 Rotated(dvec2 v, double angleInRad) => v.Rotated(angleInRad); /// <summary> /// Returns the inner product (dot product, scalar product) of the two vectors. /// </summary> public static double Dot(dvec2 lhs, dvec2 rhs) => dvec2.Dot(lhs, rhs); /// <summary> /// Returns the euclidean distance between the two vectors. /// </summary> public static double Distance(dvec2 lhs, dvec2 rhs) => dvec2.Distance(lhs, rhs); /// <summary> /// Returns the squared euclidean distance between the two vectors. /// </summary> public static double DistanceSqr(dvec2 lhs, dvec2 rhs) => dvec2.DistanceSqr(lhs, rhs); /// <summary> /// Calculate the reflection direction for an incident vector (N should be normalized in order to achieve the desired result). /// </summary> public static dvec2 Reflect(dvec2 I, dvec2 N) => dvec2.Reflect(I, N); /// <summary> /// Calculate the refraction direction for an incident vector (The input parameters I and N should be normalized in order to achieve the desired result). /// </summary> public static dvec2 Refract(dvec2 I, dvec2 N, double eta) => dvec2.Refract(I, N, eta); /// <summary> /// Returns a vector pointing in the same direction as another (faceforward orients a vector to point away from a surface as defined by its normal. If dot(Nref, I) is negative faceforward returns N, otherwise it returns -N). /// </summary> public static dvec2 FaceForward(dvec2 N, dvec2 I, dvec2 Nref) => dvec2.FaceForward(N, I, Nref); /// <summary> /// Returns the length of the outer product (cross product, vector product) of the two vectors. /// </summary> public static double Cross(dvec2 l, dvec2 r) => dvec2.Cross(l, r); /// <summary> /// Returns a dvec2 with independent and identically distributed uniform values between 'minValue' and 'maxValue'. /// </summary> public static dvec2 Random(Random random, dvec2 minValue, dvec2 maxValue) => dvec2.Random(random, minValue, maxValue); /// <summary> /// Returns a dvec2 with independent and identically distributed uniform values between 'minValue' and 'maxValue'. /// </summary> public static dvec2 RandomUniform(Random random, dvec2 minValue, dvec2 maxValue) => dvec2.RandomUniform(random, minValue, maxValue); /// <summary> /// Returns a dvec2 with independent and identically distributed values according to a normal/Gaussian distribution with specified mean and variance. /// </summary> public static dvec2 RandomNormal(Random random, dvec2 mean, dvec2 variance) => dvec2.RandomNormal(random, mean, variance); /// <summary> /// Returns a dvec2 with independent and identically distributed values according to a normal/Gaussian distribution with specified mean and variance. /// </summary> public static dvec2 RandomGaussian(Random random, dvec2 mean, dvec2 variance) => dvec2.RandomGaussian(random, mean, variance); } }
#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) using System; using System.Collections; using Org.BouncyCastle.Utilities; using Org.BouncyCastle.Utilities.Collections; namespace Org.BouncyCastle.Asn1.X509 { public class X509Extensions : Asn1Encodable { /** * Subject Directory Attributes */ public static readonly DerObjectIdentifier SubjectDirectoryAttributes = new DerObjectIdentifier("2.5.29.9"); /** * Subject Key Identifier */ public static readonly DerObjectIdentifier SubjectKeyIdentifier = new DerObjectIdentifier("2.5.29.14"); /** * Key Usage */ public static readonly DerObjectIdentifier KeyUsage = new DerObjectIdentifier("2.5.29.15"); /** * Private Key Usage Period */ public static readonly DerObjectIdentifier PrivateKeyUsagePeriod = new DerObjectIdentifier("2.5.29.16"); /** * Subject Alternative Name */ public static readonly DerObjectIdentifier SubjectAlternativeName = new DerObjectIdentifier("2.5.29.17"); /** * Issuer Alternative Name */ public static readonly DerObjectIdentifier IssuerAlternativeName = new DerObjectIdentifier("2.5.29.18"); /** * Basic Constraints */ public static readonly DerObjectIdentifier BasicConstraints = new DerObjectIdentifier("2.5.29.19"); /** * CRL Number */ public static readonly DerObjectIdentifier CrlNumber = new DerObjectIdentifier("2.5.29.20"); /** * Reason code */ public static readonly DerObjectIdentifier ReasonCode = new DerObjectIdentifier("2.5.29.21"); /** * Hold Instruction Code */ public static readonly DerObjectIdentifier InstructionCode = new DerObjectIdentifier("2.5.29.23"); /** * Invalidity Date */ public static readonly DerObjectIdentifier InvalidityDate = new DerObjectIdentifier("2.5.29.24"); /** * Delta CRL indicator */ public static readonly DerObjectIdentifier DeltaCrlIndicator = new DerObjectIdentifier("2.5.29.27"); /** * Issuing Distribution Point */ public static readonly DerObjectIdentifier IssuingDistributionPoint = new DerObjectIdentifier("2.5.29.28"); /** * Certificate Issuer */ public static readonly DerObjectIdentifier CertificateIssuer = new DerObjectIdentifier("2.5.29.29"); /** * Name Constraints */ public static readonly DerObjectIdentifier NameConstraints = new DerObjectIdentifier("2.5.29.30"); /** * CRL Distribution Points */ public static readonly DerObjectIdentifier CrlDistributionPoints = new DerObjectIdentifier("2.5.29.31"); /** * Certificate Policies */ public static readonly DerObjectIdentifier CertificatePolicies = new DerObjectIdentifier("2.5.29.32"); /** * Policy Mappings */ public static readonly DerObjectIdentifier PolicyMappings = new DerObjectIdentifier("2.5.29.33"); /** * Authority Key Identifier */ public static readonly DerObjectIdentifier AuthorityKeyIdentifier = new DerObjectIdentifier("2.5.29.35"); /** * Policy Constraints */ public static readonly DerObjectIdentifier PolicyConstraints = new DerObjectIdentifier("2.5.29.36"); /** * Extended Key Usage */ public static readonly DerObjectIdentifier ExtendedKeyUsage = new DerObjectIdentifier("2.5.29.37"); /** * Freshest CRL */ public static readonly DerObjectIdentifier FreshestCrl = new DerObjectIdentifier("2.5.29.46"); /** * Inhibit Any Policy */ public static readonly DerObjectIdentifier InhibitAnyPolicy = new DerObjectIdentifier("2.5.29.54"); /** * Authority Info Access */ public static readonly DerObjectIdentifier AuthorityInfoAccess = new DerObjectIdentifier("1.3.6.1.5.5.7.1.1"); /** * Subject Info Access */ public static readonly DerObjectIdentifier SubjectInfoAccess = new DerObjectIdentifier("1.3.6.1.5.5.7.1.11"); /** * Logo Type */ public static readonly DerObjectIdentifier LogoType = new DerObjectIdentifier("1.3.6.1.5.5.7.1.12"); /** * BiometricInfo */ public static readonly DerObjectIdentifier BiometricInfo = new DerObjectIdentifier("1.3.6.1.5.5.7.1.2"); /** * QCStatements */ public static readonly DerObjectIdentifier QCStatements = new DerObjectIdentifier("1.3.6.1.5.5.7.1.3"); /** * Audit identity extension in attribute certificates. */ public static readonly DerObjectIdentifier AuditIdentity = new DerObjectIdentifier("1.3.6.1.5.5.7.1.4"); /** * NoRevAvail extension in attribute certificates. */ public static readonly DerObjectIdentifier NoRevAvail = new DerObjectIdentifier("2.5.29.56"); /** * TargetInformation extension in attribute certificates. */ public static readonly DerObjectIdentifier TargetInformation = new DerObjectIdentifier("2.5.29.55"); private readonly IDictionary extensions = Platform.CreateHashtable(); private readonly IList ordering; public static X509Extensions GetInstance( Asn1TaggedObject obj, bool explicitly) { return GetInstance(Asn1Sequence.GetInstance(obj, explicitly)); } public static X509Extensions GetInstance( object obj) { if (obj == null || obj is X509Extensions) { return (X509Extensions) obj; } if (obj is Asn1Sequence) { return new X509Extensions((Asn1Sequence) obj); } if (obj is Asn1TaggedObject) { return GetInstance(((Asn1TaggedObject) obj).GetObject()); } throw new ArgumentException("unknown object in factory: " + obj.GetType().Name, "obj"); } /** * Constructor from Asn1Sequence. * * the extensions are a list of constructed sequences, either with (Oid, OctetString) or (Oid, Boolean, OctetString) */ private X509Extensions( Asn1Sequence seq) { this.ordering = Platform.CreateArrayList(); foreach (Asn1Encodable ae in seq) { Asn1Sequence s = Asn1Sequence.GetInstance(ae.ToAsn1Object()); if (s.Count < 2 || s.Count > 3) throw new ArgumentException("Bad sequence size: " + s.Count); DerObjectIdentifier oid = DerObjectIdentifier.GetInstance(s[0].ToAsn1Object()); bool isCritical = s.Count == 3 && DerBoolean.GetInstance(s[1].ToAsn1Object()).IsTrue; Asn1OctetString octets = Asn1OctetString.GetInstance(s[s.Count - 1].ToAsn1Object()); extensions.Add(oid, new X509Extension(isCritical, octets)); ordering.Add(oid); } } /** * constructor from a table of extensions. * <p> * it's is assumed the table contains Oid/string pairs.</p> */ public X509Extensions( IDictionary extensions) : this(null, extensions) { } /** * Constructor from a table of extensions with ordering. * <p> * It's is assumed the table contains Oid/string pairs.</p> */ public X509Extensions( IList ordering, IDictionary extensions) { if (ordering == null) { this.ordering = Platform.CreateArrayList(extensions.Keys); } else { this.ordering = Platform.CreateArrayList(ordering); } foreach (DerObjectIdentifier oid in this.ordering) { this.extensions.Add(oid, (X509Extension)extensions[oid]); } } /** * Constructor from two vectors * * @param objectIDs an ArrayList of the object identifiers. * @param values an ArrayList of the extension values. */ public X509Extensions( IList oids, IList values) { this.ordering = Platform.CreateArrayList(oids); int count = 0; foreach (DerObjectIdentifier oid in this.ordering) { this.extensions.Add(oid, (X509Extension)values[count++]); } } #if !SILVERLIGHT && !NETFX_CORE && !UNITY_WP8 /** * constructor from a table of extensions. * <p> * it's is assumed the table contains Oid/string pairs.</p> */ [Obsolete] public X509Extensions( Hashtable extensions) : this(null, extensions) { } /** * Constructor from a table of extensions with ordering. * <p> * It's is assumed the table contains Oid/string pairs.</p> */ [Obsolete] public X509Extensions( ArrayList ordering, Hashtable extensions) { if (ordering == null) { this.ordering = Platform.CreateArrayList(extensions.Keys); } else { this.ordering = Platform.CreateArrayList(ordering); } foreach (DerObjectIdentifier oid in this.ordering) { this.extensions.Add(oid, (X509Extension) extensions[oid]); } } /** * Constructor from two vectors * * @param objectIDs an ArrayList of the object identifiers. * @param values an ArrayList of the extension values. */ [Obsolete] public X509Extensions( ArrayList oids, ArrayList values) { this.ordering = Platform.CreateArrayList(oids); int count = 0; foreach (DerObjectIdentifier oid in this.ordering) { this.extensions.Add(oid, (X509Extension) values[count++]); } } #endif [Obsolete("Use ExtensionOids IEnumerable property")] public IEnumerator Oids() { return ExtensionOids.GetEnumerator(); } /** * return an Enumeration of the extension field's object ids. */ public IEnumerable ExtensionOids { get { return new EnumerableProxy(ordering); } } /** * return the extension represented by the object identifier * passed in. * * @return the extension if it's present, null otherwise. */ public X509Extension GetExtension( DerObjectIdentifier oid) { return (X509Extension) extensions[oid]; } /** * <pre> * Extensions ::= SEQUENCE SIZE (1..MAX) OF Extension * * Extension ::= SEQUENCE { * extnId EXTENSION.&amp;id ({ExtensionSet}), * critical BOOLEAN DEFAULT FALSE, * extnValue OCTET STRING } * </pre> */ public override Asn1Object ToAsn1Object() { Asn1EncodableVector vec = new Asn1EncodableVector(); foreach (DerObjectIdentifier oid in ordering) { X509Extension ext = (X509Extension) extensions[oid]; Asn1EncodableVector v = new Asn1EncodableVector(oid); if (ext.IsCritical) { v.Add(DerBoolean.True); } v.Add(ext.Value); vec.Add(new DerSequence(v)); } return new DerSequence(vec); } public bool Equivalent( X509Extensions other) { if (extensions.Count != other.extensions.Count) return false; foreach (DerObjectIdentifier oid in extensions.Keys) { if (!extensions[oid].Equals(other.extensions[oid])) return false; } return true; } public DerObjectIdentifier[] GetExtensionOids() { return ToOidArray(ordering); } public DerObjectIdentifier[] GetNonCriticalExtensionOids() { return GetExtensionOids(false); } public DerObjectIdentifier[] GetCriticalExtensionOids() { return GetExtensionOids(true); } private DerObjectIdentifier[] GetExtensionOids(bool isCritical) { IList oids = Platform.CreateArrayList(); foreach (DerObjectIdentifier oid in this.ordering) { X509Extension ext = (X509Extension)extensions[oid]; if (ext.IsCritical == isCritical) { oids.Add(oid); } } return ToOidArray(oids); } private static DerObjectIdentifier[] ToOidArray(IList oids) { DerObjectIdentifier[] oidArray = new DerObjectIdentifier[oids.Count]; oids.CopyTo(oidArray, 0); return oidArray; } } } #endif
// =========================================================== // Copyright (c) 2014-2015, Enrico Da Ros/kendar.org // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // =========================================================== using System.Collections.Generic; using System.Configuration; using System.Data.SqlClient; using System.Diagnostics; using System.Timers; using Dapper; using ECQRS.Commons.Bus; using ECQRS.Commons.Commands; using ECQRS.Commons.Events; using ECQRS.Commons.Exceptions; using System; using System.Collections.Concurrent; using System.Linq; using System.Threading; using ECQRS.Commons.Interfaces; using ECQRS.SqlServer.Repositories; using Newtonsoft.Json; using Timer = System.Timers.Timer; using ECQRS.SqlServer.Bus.Entities; namespace ECQRS.SqlServer.Bus { public class DapperBus : IBus, IDisposable, IEventPublisher, ICommandSender, IECQRSService { internal const string QUEUES_TABLE = "Queue"; internal const string MESSAGES_TABLE = "Message"; internal const string SUBSCRIPTIONS_TABLE = "Subscription"; private readonly ConcurrentDictionary<string, QueueInstance> _queues; private readonly Timer _timer; private long _running = 0; public DapperBus() { _queues = new ConcurrentDictionary<string, QueueInstance>(StringComparer.InvariantCultureIgnoreCase); _timer = new Timer(500); _timer.Elapsed += OnTimer; _timer.Enabled = StartupInitializer.IsServer; } void OnTimer(object sender, ElapsedEventArgs e) { if (!StartupInitializer.IsServer) return; if (Interlocked.CompareExchange(ref _running, 1, 0) == 1) return; try { var somethingToDo = false; using (var db = new SqlConnection(StartupInitializer.ConnectionString)) { db.Open(); var res = db.Query<MessageEntity>( string.Format( "SELECT * FROM [{0}] WHERE Reserved=@resId AND Elaborated=@elab", DapperBus.MESSAGES_TABLE), new { resId = Guid.Empty, elab = false }).FirstOrDefault(); somethingToDo = res != null; if (somethingToDo) { var keys = _queues.Keys.ToList(); foreach (var key in keys) { _queues[key].Run(db); } } } } catch (ThreadAbortException ta) { Debug.WriteLine(ta); Thread.ResetAbort(); } catch (Exception ex) { Debug.WriteLine(ex); } Interlocked.Exchange(ref _running, 0); } public void Subscribe<T>(IBusHandler target, string queueId = null) where T : Message { Subscribe(typeof(T), target, queueId); } public void Unsubscribe<T>(IBusHandler target, string queueId = null) where T : Message { Unsubscribe(typeof(T), target, queueId); } public void Subscribe(Type t, IBusHandler handlerInstance, string queueId = null) { if (string.IsNullOrWhiteSpace(queueId)) queueId = string.Empty; var subscriberId = SubscriberId(); using (var db = new SqlConnection(StartupInitializer.ConnectionString)) { var result = db.Query<QueueEntity>( string.Format("SELECT * FROM [{0}] WHERE QueueId=@id ", QUEUES_TABLE), new { id = queueId }).FirstOrDefault(); if (result == null) { throw new MissingQueueException(queueId); } var subscriptions = db.Query<SubscriptionEntity>( string.Format("SELECT * FROM [{0}] WHERE QueueId=@qid AND SubscriberId=@sid AND TypeName=@tn", SUBSCRIPTIONS_TABLE), new { qid = queueId, sid = subscriberId, tn = t.Name }).FirstOrDefault(); if (subscriptions == null) { DapperRepository.InsertGeneric(db, SUBSCRIPTIONS_TABLE, new SubscriptionEntity { LastMessage = DateTime.UtcNow, QueueId = queueId, SubscriberId = subscriberId, TypeName = t.Name }); } } _queues[queueId].Subscribe(t, handlerInstance, queueId); } public static string SubscriberId() { #if DEBUG return "localhost"; #else var subscriberId = ConfigurationManager.AppSettings["CQRS.Subscriber"]; if (string.IsNullOrWhiteSpace(subscriberId)) { subscriberId = Environment.MachineName; return subscriberId; } #endif } public void Unsubscribe(Type t, IBusHandler handlerInstance, string queueId = null) { if (string.IsNullOrWhiteSpace(queueId)) queueId = string.Empty; var subscriberId = SubscriberId(); using (var db = new SqlConnection(StartupInitializer.ConnectionString)) { var result = db.Query<QueueEntity>(string.Format("SELECT * FROM [{0}] WHERE QueueId=@id", QUEUES_TABLE), new { id = queueId }).FirstOrDefault(); if (result == null) { throw new MissingQueueException(queueId); } db.ExecuteScalar( string.Format("DELETE FROM [{0}] WHERE QueueId=@id AND SubscriberId=@sid AND TypeName=@tn", SUBSCRIPTIONS_TABLE), new { qid = queueId, sid = subscriberId, tn = t.Name }); } _queues[queueId].Unsubscribe(t, handlerInstance, queueId); } public void SendMessage(Message message, string queueId = null) { SendMessageInternal(queueId, new[] { message }); } public void SendMessage(IEnumerable<Message> messages, string queueId = null) { SendMessageInternal(queueId, messages); } public void SendMessageSync(Message message, string queueId = null) { SendMessageInternalSync(queueId, new[] { message }); } public void SendMessageSync(IEnumerable<Message> messages, string queueId = null) { SendMessageInternalSync(queueId, messages); } public void SendMessageInternal(string queueId, IEnumerable<Message> messages) { if (string.IsNullOrWhiteSpace(queueId)) queueId = string.Empty; var subscriberId = SubscriberId(); if (_queues[queueId].IsMultiple) { using (var db = new SqlConnection(StartupInitializer.ConnectionString)) { db.Open(); using (var tr = db.BeginTransaction()) { foreach (var message in messages) { db.ExecuteScalar( string.Format("INSERT INTO [{0}] SELECT (" + "@Elaborated AS Elaborated," + "@Message AS Message," + "@QueueId= AS QueueId," + "@SubscriptionId AS SubscriptionId," + "SubscriberId," + "@Timestamp AS Timestamp," + "@Reserved AS Reserved FROM [{1}] " + "WHERE " + "QueueId = @QueueId AND " + "TypeName = @SubscriptionId", MESSAGES_TABLE, SUBSCRIPTIONS_TABLE), new { Elaborated = false, Message = JsonConvert.SerializeObject(message), QueueId = queueId, SubscriptionId = message.GetType().Name, SubscriberId = subscriberId, Timestamp = DateTime.UtcNow, Reserved = Guid.Empty }, tr); } tr.Commit(); } } } else { using (var db = new SqlConnection(StartupInitializer.ConnectionString)) { db.Open(); using (var tr = db.BeginTransaction()) { foreach (var message in messages) { DapperRepository.InsertGeneric(db, MESSAGES_TABLE, new MessageEntity { Elaborated = false, Id = Guid.NewGuid(), Message = JsonConvert.SerializeObject(message), QueueId = queueId, SubscriptionId = message.GetType().Name, SubscriberId = "global", Timestamp = DateTime.UtcNow, Reserved = Guid.Empty }, tr); } tr.Commit(); } } } } public void Dispose() { _running = 0; _timer.Enabled = false; _timer.Stop(); _timer.Elapsed -= OnTimer; } public void CreateQueue(string queueId, bool multiple = false) { using (var db = new SqlConnection(StartupInitializer.ConnectionString)) { var result = db.Query<QueueEntity>(string.Format("SELECT * FROM [{0}] WHERE QueueId=@id", QUEUES_TABLE), new { id = queueId }).FirstOrDefault(); if (result == null) { DapperRepository.InsertGeneric(db, QUEUES_TABLE, new QueueEntity { Id = Guid.NewGuid(), QueueId = queueId, IsMultiple = multiple }); } } if (_queues.ContainsKey(queueId)) { return; } _queues[queueId] = new QueueInstance(multiple, queueId); } public void Publish(params Event[] events) { SendMessage(events, "ecqrs.events"); } public void Send(params Command[] commands) { SendMessage(commands, "ecqrs.commands"); } public void SendSync(params Command[] commands) { SendMessageSync(commands, "ecqrs.commands"); } public void Start() { if (StartupInitializer.IsServer) { _timer.Start(); } } public void SendMessageInternalSync(string queueId, IEnumerable<Message> messages) { if (string.IsNullOrWhiteSpace(queueId)) queueId = string.Empty; var subscriberId = SubscriberId(); if (_queues.ContainsKey(queueId)) { _queues[queueId].RunSync(messages); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Diagnostics.Contracts; using System.Runtime.CompilerServices; namespace System { [System.Runtime.InteropServices.ComVisible(true)] public abstract class StringComparer : IComparer, IEqualityComparer, IComparer<string>, IEqualityComparer<string> { private static readonly StringComparer s_ordinal = new OrdinalComparer(false); private static readonly StringComparer s_ordinalIgnoreCase = new OrdinalComparer(true); public static StringComparer CurrentCulture { get { Contract.Ensures(Contract.Result<StringComparer>() != null); return FormatProvider.GetCultureAwareStringComparer(false); } } public static StringComparer CurrentCultureIgnoreCase { get { Contract.Ensures(Contract.Result<StringComparer>() != null); return FormatProvider.GetCultureAwareStringComparer(true); } } public static StringComparer Ordinal { get { Contract.Ensures(Contract.Result<StringComparer>() != null); return s_ordinal; } } public static StringComparer OrdinalIgnoreCase { get { Contract.Ensures(Contract.Result<StringComparer>() != null); return s_ordinalIgnoreCase; } } int IComparer.Compare(object x, object y) { if (x == y) return 0; if (x == null) return -1; if (y == null) return 1; String sa = x as String; if (sa != null) { String sb = y as String; if (sb != null) { return Compare(sa, sb); } } IComparable ia = x as IComparable; if (ia != null) { return ia.CompareTo(y); } throw new ArgumentException(SR.Argument_ImplementIComparable); } bool IEqualityComparer.Equals(Object x, Object y) { if (x == y) return true; if (x == null || y == null) return false; String sa = x as String; if (sa != null) { String sb = y as String; if (sb != null) { return Equals(sa, sb); } } return x.Equals(y); } int IEqualityComparer.GetHashCode(object obj) { if (obj == null) { throw new ArgumentNullException("obj"); } Contract.EndContractBlock(); string s = obj as string; if (s != null) { return GetHashCode(s); } return obj.GetHashCode(); } public abstract int Compare(String x, String y); public abstract bool Equals(String x, String y); public abstract int GetHashCode(string obj); } #if FEATURE_RANDOMIZED_STRING_HASHING internal sealed class CultureAwareRandomizedComparer : StringComparer, IWellKnownStringEqualityComparer { private CompareInfo _compareInfo; private bool _ignoreCase; private long _entropy; internal CultureAwareRandomizedComparer(CompareInfo compareInfo, bool ignoreCase) { _compareInfo = compareInfo; _ignoreCase = ignoreCase; _entropy = HashHelpers.GetEntropy(); } public override int Compare(string x, string y) { if (Object.ReferenceEquals(x, y)) return 0; if (x == null) return -1; if (y == null) return 1; return _compareInfo.Compare(x, y, _ignoreCase ? CompareOptions.IgnoreCase : CompareOptions.None); } public override bool Equals(string x, string y) { if (Object.ReferenceEquals(x, y)) return true; if (x == null || y == null) return false; return (_compareInfo.Compare(x, y, _ignoreCase ? CompareOptions.IgnoreCase : CompareOptions.None) == 0); } public override int GetHashCode(string obj) { if (obj == null) { throw new ArgumentNullException("obj"); } Contract.EndContractBlock(); CompareOptions options = CompareOptions.None; if (_ignoreCase) { options |= CompareOptions.IgnoreCase; } return _compareInfo.GetHashCodeOfString(obj, options, true, _entropy); } // Equals method for the comparer itself. public override bool Equals(Object obj) { CultureAwareRandomizedComparer comparer = obj as CultureAwareRandomizedComparer; if (comparer == null) { return false; } return (this._ignoreCase == comparer._ignoreCase) && (this._compareInfo.Equals(comparer._compareInfo)) && (this._entropy == comparer._entropy); } public override int GetHashCode() { int hashCode = _compareInfo.GetHashCode(); return ((_ignoreCase ? (~hashCode) : hashCode) ^ ((int)(_entropy & 0x7FFFFFFF))); } IEqualityComparer IWellKnownStringEqualityComparer.GetRandomizedEqualityComparer() { return new CultureAwareRandomizedComparer(_compareInfo, _ignoreCase); } // We want to serialize the old comparer. IEqualityComparer IWellKnownStringEqualityComparer.GetEqualityComparerForSerialization() { return new CultureAwareComparer(_compareInfo, _ignoreCase); } } #endif // Provide x more optimal implementation of ordinal comparison. internal sealed class OrdinalComparer : StringComparer #if FEATURE_RANDOMIZED_STRING_HASHING , IWellKnownStringEqualityComparer #endif { private bool _ignoreCase; internal OrdinalComparer(bool ignoreCase) { _ignoreCase = ignoreCase; } public override int Compare(string x, string y) { if (Object.ReferenceEquals(x, y)) return 0; if (x == null) return -1; if (y == null) return 1; if (_ignoreCase) { return String.Compare(x, y, StringComparison.OrdinalIgnoreCase); } return String.CompareOrdinal(x, y); } public override bool Equals(string x, string y) { if (Object.ReferenceEquals(x, y)) return true; if (x == null || y == null) return false; if (_ignoreCase) { if (x.Length != y.Length) { return false; } return (String.Compare(x, y, StringComparison.OrdinalIgnoreCase) == 0); } return x.Equals(y); } public override int GetHashCode(string obj) { if (obj == null) { throw new ArgumentNullException("obj"); } Contract.EndContractBlock(); if (_ignoreCase) { return FormatProvider.GetHashCodeOrdinalIgnoreCase(obj); } return obj.GetHashCode(); } // Equals method for the comparer itself. public override bool Equals(Object obj) { OrdinalComparer comparer = obj as OrdinalComparer; if (comparer == null) { return false; } return (_ignoreCase == comparer._ignoreCase); } public override int GetHashCode() { string name = "OrdinalComparer"; int hashCode = name.GetHashCode(); return _ignoreCase ? (~hashCode) : hashCode; } #if FEATURE_RANDOMIZED_STRING_HASHING IEqualityComparer IWellKnownStringEqualityComparer.GetRandomizedEqualityComparer() { return new OrdinalRandomizedComparer(_ignoreCase); } IEqualityComparer IWellKnownStringEqualityComparer.GetEqualityComparerForSerialization() { return this; } #endif } #if FEATURE_RANDOMIZED_STRING_HASHING internal sealed class OrdinalRandomizedComparer : StringComparer, IWellKnownStringEqualityComparer { private bool _ignoreCase; private long _entropy; internal OrdinalRandomizedComparer(bool ignoreCase) { _ignoreCase = ignoreCase; _entropy = HashHelpers.GetEntropy(); } public override int Compare(string x, string y) { if (Object.ReferenceEquals(x, y)) return 0; if (x == null) return -1; if (y == null) return 1; if (_ignoreCase) { return String.Compare(x, y, StringComparison.OrdinalIgnoreCase); } return String.CompareOrdinal(x, y); } public override bool Equals(string x, string y) { if (Object.ReferenceEquals(x, y)) return true; if (x == null || y == null) return false; if (_ignoreCase) { if (x.Length != y.Length) { return false; } return (String.Compare(x, y, StringComparison.OrdinalIgnoreCase) == 0); } return x.Equals(y); } [System.Security.SecuritySafeCritical] public override int GetHashCode(string obj) { if (obj == null) { throw new ArgumentNullException("obj"); } Contract.EndContractBlock(); if (_ignoreCase) { return TextInfo.GetHashCodeOrdinalIgnoreCase(obj, true, _entropy); } return String.InternalMarvin32HashString(obj, obj.Length, _entropy); } // Equals method for the comparer itself. public override bool Equals(Object obj) { OrdinalRandomizedComparer comparer = obj as OrdinalRandomizedComparer; if (comparer == null) { return false; } return (this._ignoreCase == comparer._ignoreCase) && (this._entropy == comparer._entropy); } public override int GetHashCode() { string name = "OrdinalRandomizedComparer"; int hashCode = name.GetHashCode(); return ((_ignoreCase ? (~hashCode) : hashCode) ^ ((int)(_entropy & 0x7FFFFFFF))); } IEqualityComparer IWellKnownStringEqualityComparer.GetRandomizedEqualityComparer() { return new OrdinalRandomizedComparer(_ignoreCase); } // We want to serialize the old comparer. IEqualityComparer IWellKnownStringEqualityComparer.GetEqualityComparerForSerialization() { return new OrdinalComparer(_ignoreCase); } } // This interface is implemented by string comparers in the framework that can opt into // randomized hashing behaviors. internal interface IWellKnownStringEqualityComparer { // Get an IEqualityComparer that has the same equality comparision rules as "this" but uses Randomized Hashing. IEqualityComparer GetRandomizedEqualityComparer(); // Get an IEqaulityComparer that can be serailzied (e.g., it exists in older versions). IEqualityComparer GetEqualityComparerForSerialization(); } #endif }
using System; using Gdk; using Mono.TextEditor; using Mono.TextEditor.Highlighting; namespace Moscrif.IDE.Components { public class DebugTextMarker : StyleTextMarker, IIconBarMarker { protected Mono.TextEditor.TextEditor editor; public DebugTextMarker(Mono.TextEditor.TextEditor editor) { this.editor = editor; } public void DrawIcon(Mono.TextEditor.TextEditor editor, Gdk.Drawable win, LineSegment line, int lineNumber, int x, int y, int width, int height) { int size; if (width > height) { x += (width - height) / 2; size = height; } else { y += (height - width) / 2; size = width; } using (Cairo.Context cr = Gdk.CairoHelper.Create(win)) DrawIcon(cr, x, y, size); } protected virtual void DrawIcon(Cairo.Context cr, int x, int y, int size) { } protected void DrawCircle(Cairo.Context cr, double x, double y, int size) { x += 0.5; y += 0.5; cr.NewPath(); cr.Arc(x + size / 2, y + size / 2, (size - 4) / 2, 0, 2 * Math.PI); cr.ClosePath(); } protected void DrawDiamond(Cairo.Context cr, double x, double y, double size) { x += 0.5; y += 0.5; size -= 2; cr.NewPath(); cr.MoveTo(x + size / 2, y); cr.LineTo(x + size, y + size / 2); cr.LineTo(x + size / 2, y + size); cr.LineTo(x, y + size / 2); cr.LineTo(x + size / 2, y); cr.ClosePath(); } protected void DrawArrow(Cairo.Context cr, double x, double y, double size) { y += 2.5; x += 2.5; size -= 4; double awidth = 0.5; double aheight = 0.4; double pich = (size - (size * aheight)) / 2; cr.NewPath(); cr.MoveTo(x + size * awidth, y); cr.LineTo(x + size, y + size / 2); cr.LineTo(x + size * awidth, y + size); cr.RelLineTo(0, -pich); cr.RelLineTo(-size * awidth, 0); cr.RelLineTo(0, -size * aheight); cr.RelLineTo(size * awidth, 0); cr.RelLineTo(0, -pich); cr.ClosePath(); } protected void FillGradient(Cairo.Context cr, Cairo.Color color1, Cairo.Color color2, int x, int y, int size) { Cairo.Gradient pat = new Cairo.LinearGradient(x + size / 4, y, x + size / 2, y + size - 4); pat.AddColorStop(0, color1); pat.AddColorStop(1, color2); cr.Pattern = pat; cr.FillPreserve(); } protected void DrawBorder(Cairo.Context cr, Cairo.Color color, int x, int y, int size) { Cairo.Gradient pat = new Cairo.LinearGradient(x, y + size, x + size, y); pat.AddColorStop(0, color); cr.Pattern = pat; cr.LineWidth = 1; cr.Stroke(); } public void MousePress(MarginMouseEventArgs args) { } public void MouseRelease(MarginMouseEventArgs args) { } } public class BreakpointTextMarker : DebugTextMarker { public override Color BackgroundColor { get { return editor.ColorStyle.BreakpointBg; } set { } } public override Color Color { get { return editor.ColorStyle.BreakpointFg; } set { } } public bool IsTracepoint { get; set; } public BreakpointTextMarker(Mono.TextEditor.TextEditor editor, bool isTracePoint) : base(editor) { IncludedStyles |= StyleFlag.BackgroundColor | StyleFlag.Color; IsTracepoint = isTracePoint; } protected override void DrawIcon(Cairo.Context cr, int x, int y, int size) { Cairo.Color color1 = Style.ToCairoColor(editor.ColorStyle.BreakpointMarkerColor1); Cairo.Color color2 = Style.ToCairoColor(editor.ColorStyle.BreakpointMarkerColor2); if (IsTracepoint) DrawDiamond(cr, x, y, size); else DrawCircle(cr, x, y, size); FillGradient(cr, color1, color2, x, y, size); DrawBorder(cr, color2, x, y, size); } } public class DisabledBreakpointTextMarker : DebugTextMarker { public override Color BackgroundColor { get { return editor.ColorStyle.DisabledBreakpointBg; } set { } } public DisabledBreakpointTextMarker(Mono.TextEditor.TextEditor editor, bool isTracePoint) : base(editor) { IncludedStyles |= StyleFlag.BackgroundColor; IsTracepoint = isTracePoint; } public bool IsTracepoint { get; set; } protected override void DrawIcon(Cairo.Context cr, int x, int y, int size) { Cairo.Color border = Style.ToCairoColor(editor.ColorStyle.InvalidBreakpointMarkerBorder); if (IsTracepoint) DrawDiamond(cr, x, y, size); else DrawCircle(cr, x, y, size); //FillGradient (cr, new Cairo.Color (1,1,1), new Cairo.Color (1,0.8,0.8), x, y, size); DrawBorder(cr, border, x, y, size); } } public class CurrentDebugLineTextMarker : DebugTextMarker { public override Color BackgroundColor { get { return editor.ColorStyle.CurrentDebugLineBg; } set { } } public override Color Color { get { return editor.ColorStyle.CurrentDebugLineFg; } set { } } public CurrentDebugLineTextMarker(Mono.TextEditor.TextEditor editor) : base(editor) { IncludedStyles |= StyleFlag.BackgroundColor | StyleFlag.Color; } protected override void DrawIcon(Cairo.Context cr, int x, int y, int size) { Cairo.Color color1 = Style.ToCairoColor(editor.ColorStyle.CurrentDebugLineMarkerColor1); Cairo.Color color2 = Style.ToCairoColor(editor.ColorStyle.CurrentDebugLineMarkerColor2); Cairo.Color border = Style.ToCairoColor(editor.ColorStyle.CurrentDebugLineMarkerBorder); DrawArrow(cr, x, y, size); FillGradient(cr, color1, color2, x, y, size); DrawBorder(cr, border, x, y, size); } } public class DebugStackLineTextMarker : DebugTextMarker { public override Color BackgroundColor { get { return editor.ColorStyle.DebugStackLineBg; } set { } } public override Color Color { get { return editor.ColorStyle.DebugStackLineFg; } set { } } public DebugStackLineTextMarker(Mono.TextEditor.TextEditor editor) : base(editor) { IncludedStyles |= StyleFlag.BackgroundColor | StyleFlag.Color; } protected override void DrawIcon(Cairo.Context cr, int x, int y, int size) { Cairo.Color color1 = Style.ToCairoColor(editor.ColorStyle.DebugStackLineMarkerColor1); Cairo.Color color2 = Style.ToCairoColor(editor.ColorStyle.DebugStackLineMarkerColor2); Cairo.Color border = Style.ToCairoColor(editor.ColorStyle.DebugStackLineMarkerBorder); DrawArrow(cr, x, y, size); FillGradient(cr, color1, color2, x, y, size); DrawBorder(cr, border, x, y, size); } } public class InvalidBreakpointTextMarker : DebugTextMarker { public override Color BackgroundColor { get { return editor.ColorStyle.InvalidBreakpointBg; } set { } } public InvalidBreakpointTextMarker(Mono.TextEditor.TextEditor editor) : base(editor) { IncludedStyles |= StyleFlag.BackgroundColor; } protected override void DrawIcon(Cairo.Context cr, int x, int y, int size) { Cairo.Color color1 = Style.ToCairoColor(editor.ColorStyle.InvalidBreakpointMarkerColor1); Cairo.Color color2 = color1; Cairo.Color border = Style.ToCairoColor(editor.ColorStyle.InvalidBreakpointMarkerBorder); DrawCircle(cr, x, y, size); FillGradient(cr, color1, color2, x, y, size); DrawBorder(cr, border, x, y, size); } } }
// // Copyright (c) 2014 .NET Foundation // // 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. // // // Copyright (c) 2014 Couchbase, Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file // except in compliance with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed under the // License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, // either express or implied. See the License for the specific language governing permissions // and limitations under the License. //using System; using System.Collections.Generic; using System.Text; using Couchbase.Lite.Util; using Sharpen; namespace Couchbase.Lite.Storage { public sealed class ContentValues { public const string Tag = "ContentValues"; /// <summary>Holds the actual values</summary> private Dictionary<string, object> mValues; /// <summary>Creates an empty set of values using the default initial size</summary> public ContentValues() { // COPY: Copied from android.content.ContentValues // Choosing a default size of 8 based on analysis of typical // consumption by applications. mValues = new Dictionary<string, object>(8); } /// <summary>Creates an empty set of values using the given initial size</summary> /// <param name="size">the initial size of the set of values</param> public ContentValues(int size) { mValues = new Dictionary<string, object>(size, 1.0f); } /// <summary>Creates a set of values copied from the given set</summary> /// <param name="from">the values to copy</param> public ContentValues(Couchbase.Lite.Storage.ContentValues from) { mValues = new Dictionary<string, object>(from.mValues); } public override bool Equals(object @object) { if (!(@object is Couchbase.Lite.Storage.ContentValues)) { return false; } return mValues.Equals(((Couchbase.Lite.Storage.ContentValues)@object).mValues); } public override int GetHashCode() { return mValues.GetHashCode(); } /// <summary>Adds a value to the set.</summary> /// <remarks>Adds a value to the set.</remarks> /// <param name="key">the name of the value to put</param> /// <param name="value">the data for the value to put</param> public void Put(string key, string value) { mValues.Put(key, value); } /// <summary>Adds all values from the passed in ContentValues.</summary> /// <remarks>Adds all values from the passed in ContentValues.</remarks> /// <param name="other">the ContentValues from which to copy</param> public void PutAll(Couchbase.Lite.Storage.ContentValues other) { mValues.PutAll(other.mValues); } /// <summary>Adds a value to the set.</summary> /// <remarks>Adds a value to the set.</remarks> /// <param name="key">the name of the value to put</param> /// <param name="value">the data for the value to put</param> public void Put(string key, byte value) { mValues.Put(key, value); } /// <summary>Adds a value to the set.</summary> /// <remarks>Adds a value to the set.</remarks> /// <param name="key">the name of the value to put</param> /// <param name="value">the data for the value to put</param> public void Put(string key, short value) { mValues.Put(key, value); } /// <summary>Adds a value to the set.</summary> /// <remarks>Adds a value to the set.</remarks> /// <param name="key">the name of the value to put</param> /// <param name="value">the data for the value to put</param> public void Put(string key, int value) { mValues.Put(key, value); } /// <summary>Adds a value to the set.</summary> /// <remarks>Adds a value to the set.</remarks> /// <param name="key">the name of the value to put</param> /// <param name="value">the data for the value to put</param> public void Put(string key, long value) { mValues.Put(key, value); } /// <summary>Adds a value to the set.</summary> /// <remarks>Adds a value to the set.</remarks> /// <param name="key">the name of the value to put</param> /// <param name="value">the data for the value to put</param> public void Put(string key, float value) { mValues.Put(key, value); } /// <summary>Adds a value to the set.</summary> /// <remarks>Adds a value to the set.</remarks> /// <param name="key">the name of the value to put</param> /// <param name="value">the data for the value to put</param> public void Put(string key, double value) { mValues.Put(key, value); } /// <summary>Adds a value to the set.</summary> /// <remarks>Adds a value to the set.</remarks> /// <param name="key">the name of the value to put</param> /// <param name="value">the data for the value to put</param> public void Put(string key, bool value) { mValues.Put(key, value); } /// <summary>Adds a value to the set.</summary> /// <remarks>Adds a value to the set.</remarks> /// <param name="key">the name of the value to put</param> /// <param name="value">the data for the value to put</param> public void Put(string key, byte[] value) { mValues.Put(key, value); } /// <summary>Adds a null value to the set.</summary> /// <remarks>Adds a null value to the set.</remarks> /// <param name="key">the name of the value to make null</param> public void PutNull(string key) { mValues.Put(key, null); } /// <summary>Returns the number of values.</summary> /// <remarks>Returns the number of values.</remarks> /// <returns>the number of values</returns> public int Size() { return mValues.Count; } /// <summary>Remove a single value.</summary> /// <remarks>Remove a single value.</remarks> /// <param name="key">the name of the value to remove</param> public void Remove(string key) { Sharpen.Collections.Remove(mValues, key); } /// <summary>Removes all values.</summary> /// <remarks>Removes all values.</remarks> public void Clear() { mValues.Clear(); } /// <summary>Returns true if this object has the named value.</summary> /// <remarks>Returns true if this object has the named value.</remarks> /// <param name="key">the value to check for</param> /// <returns> /// /// <code>true</code> /// if the value is present, /// <code>false</code> /// otherwise /// </returns> public bool ContainsKey(string key) { return mValues.ContainsKey(key); } /// <summary>Gets a value.</summary> /// <remarks> /// Gets a value. Valid value types are /// <see cref="string">string</see> /// , /// <see cref="bool">bool</see> /// , and /// <see cref="Sharpen.Number">Sharpen.Number</see> /// implementations. /// </remarks> /// <param name="key">the value to get</param> /// <returns>the data for the value</returns> public object Get(string key) { return mValues.Get(key); } /// <summary>Gets a value and converts it to a String.</summary> /// <remarks>Gets a value and converts it to a String.</remarks> /// <param name="key">the value to get</param> /// <returns>the String for the value</returns> public string GetAsString(string key) { object value = mValues.Get(key); return value != null ? value.ToString() : null; } /// <summary>Gets a value and converts it to a Long.</summary> /// <remarks>Gets a value and converts it to a Long.</remarks> /// <param name="key">the value to get</param> /// <returns>the Long value, or null if the value is missing or cannot be converted</returns> public long GetAsLong(string key) { object value = mValues.Get(key); try { return value != null ? ((Number)value) : null; } catch (InvalidCastException e) { if (value is CharSequence) { try { return Sharpen.Extensions.ValueOf(value.ToString()); } catch (FormatException) { Log.E(Tag, "Cannot parse Long value for %s at key %s", value, key); return null; } } else { Log.E(Tag, "Cannot cast value for %s to a Long: %s", e, key, value); return null; } } } /// <summary>Gets a value and converts it to an Integer.</summary> /// <remarks>Gets a value and converts it to an Integer.</remarks> /// <param name="key">the value to get</param> /// <returns>the Integer value, or null if the value is missing or cannot be converted /// </returns> public int GetAsInteger(string key) { object value = mValues.Get(key); try { return value != null ? ((Number)value) : null; } catch (InvalidCastException e) { if (value is CharSequence) { try { return Sharpen.Extensions.ValueOf(value.ToString()); } catch (FormatException) { Log.E(Tag, "Cannot parse Integer value for %s at key %s", value, key); return null; } } else { Log.E(Tag, "Cannot cast value for %s to a Integer: %s", e, key, value); return null; } } } /// <summary>Gets a value and converts it to a Short.</summary> /// <remarks>Gets a value and converts it to a Short.</remarks> /// <param name="key">the value to get</param> /// <returns>the Short value, or null if the value is missing or cannot be converted</returns> public short GetAsShort(string key) { object value = mValues.Get(key); try { return value != null ? ((Number)value) : null; } catch (InvalidCastException e) { if (value is CharSequence) { try { return short.ValueOf(value.ToString()); } catch (FormatException) { Log.E(Tag, "Cannot parse Short value for %s at key %s", value, key); return null; } } else { Log.E(Tag, "Cannot cast value for %s to a Short: %s", e, key, value); return null; } } } /// <summary>Gets a value and converts it to a Byte.</summary> /// <remarks>Gets a value and converts it to a Byte.</remarks> /// <param name="key">the value to get</param> /// <returns>the Byte value, or null if the value is missing or cannot be converted</returns> public byte GetAsByte(string key) { object value = mValues.Get(key); try { return value != null ? ((Number)value) : null; } catch (InvalidCastException e) { if (value is CharSequence) { try { return byte.ValueOf(value.ToString()); } catch (FormatException) { Log.E(Tag, "Cannot parse Byte value for %s at key %s", value, key); return null; } } else { Log.E(Tag, "Cannot cast value for %s to a Byte: %s", e, key, value); return null; } } } /// <summary>Gets a value and converts it to a Double.</summary> /// <remarks>Gets a value and converts it to a Double.</remarks> /// <param name="key">the value to get</param> /// <returns>the Double value, or null if the value is missing or cannot be converted /// </returns> public double GetAsDouble(string key) { object value = mValues.Get(key); try { return value != null ? ((Number)value) : null; } catch (InvalidCastException e) { if (value is CharSequence) { try { return double.ValueOf(value.ToString()); } catch (FormatException) { Log.E(Tag, "Cannot parse Double value for %s at key %s", value, key); return null; } } else { Log.E(Tag, "Cannot cast value for %s to a Double: %s", e, key, value); return null; } } } /// <summary>Gets a value and converts it to a Float.</summary> /// <remarks>Gets a value and converts it to a Float.</remarks> /// <param name="key">the value to get</param> /// <returns>the Float value, or null if the value is missing or cannot be converted</returns> public float GetAsFloat(string key) { object value = mValues.Get(key); try { return value != null ? ((Number)value) : null; } catch (InvalidCastException e) { if (value is CharSequence) { try { return float.ValueOf(value.ToString()); } catch (FormatException) { Log.E(Tag, "Cannot parse Float value for %s at key %s", value, key); return null; } } else { Log.E(Tag, "Cannot cast value for %s to a Float: %s", e, key, value); return null; } } } /// <summary>Gets a value and converts it to a Boolean.</summary> /// <remarks>Gets a value and converts it to a Boolean.</remarks> /// <param name="key">the value to get</param> /// <returns>the Boolean value, or null if the value is missing or cannot be converted /// </returns> public bool GetAsBoolean(string key) { object value = mValues.Get(key); try { return (bool)value; } catch (InvalidCastException e) { if (value is CharSequence) { return Sharpen.Extensions.ValueOf(value.ToString()); } else { if (value is Number) { return ((Number)value) != 0; } else { Log.E(Tag, "Cannot cast value for " + key + " to a Boolean: " + value, e); return null; } } } } /// <summary>Gets a value that is a byte array.</summary> /// <remarks> /// Gets a value that is a byte array. Note that this method will not convert /// any other types to byte arrays. /// </remarks> /// <param name="key">the value to get</param> /// <returns>the byte[] value, or null is the value is missing or not a byte[]</returns> public byte[] GetAsByteArray(string key) { object value = mValues.Get(key); if (value is byte[]) { return (byte[])value; } else { return null; } } /// <summary>Returns a set of all of the keys and values</summary> /// <returns>a set of all of the keys and values</returns> public ICollection<KeyValuePair<string, object>> ValueSet() { return mValues.EntrySet(); } /// <summary>Returns a set of all of the keys</summary> /// <returns>a set of all of the keys</returns> public ICollection<string> KeySet() { return mValues.Keys; } /// <summary>Returns a string containing a concise, human-readable description of this object. /// </summary> /// <remarks>Returns a string containing a concise, human-readable description of this object. /// </remarks> /// <returns>a printable representation of this object.</returns> public override string ToString() { StringBuilder sb = new StringBuilder(); foreach (string name in mValues.Keys) { string value = GetAsString(name); if (sb.Length > 0) { sb.Append(" "); } sb.Append(name + "=" + value); } return sb.ToString(); } } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: EmergencyExplorerService.proto #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; /// <summary>Holder for reflection information generated from EmergencyExplorerService.proto</summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public static partial class EmergencyExplorerServiceReflection { #region Descriptor /// <summary>File descriptor for EmergencyExplorerService.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static EmergencyExplorerServiceReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "Ch5FbWVyZ2VuY3lFeHBsb3JlclNlcnZpY2UucHJvdG8iRwoMTG9naW5SZXF1", "ZXN0EhAKCHVzZXJuYW1lGAEgASgJEhAKCHBhc3N3b3JkGAIgASgJEhMKC3Jl", "bWVtYmVyX21lGAMgASgIIjcKFUxvZ2luV2l0aFRva2VuUmVxdWVzdBIPCgd1", "c2VyX2lkGAEgASgNEg0KBXRva2VuGAIgASgJIkAKDUxvZ2luUmVzcG9uc2US", "DwoHc3VjY2VzcxgBIAEoCBIPCgd1c2VyX2lkGAIgASgNEg0KBXRva2VuGAMg", "ASgJMnwKGEVtZXJnZW5jeUV4cGxvcmVyU2VydmljZRImCgVMb2dpbhINLkxv", "Z2luUmVxdWVzdBoOLkxvZ2luUmVzcG9uc2USOAoOTG9naW5XaXRoVG9rZW4S", "Fi5Mb2dpbldpdGhUb2tlblJlcXVlc3QaDi5Mb2dpblJlc3BvbnNlYgZwcm90", "bzM=")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { }, new pbr::GeneratedCodeInfo(null, new pbr::GeneratedCodeInfo[] { new pbr::GeneratedCodeInfo(typeof(global::LoginRequest), global::LoginRequest.Parser, new[]{ "Username", "Password", "RememberMe" }, null, null, null), new pbr::GeneratedCodeInfo(typeof(global::LoginWithTokenRequest), global::LoginWithTokenRequest.Parser, new[]{ "UserId", "Token" }, null, null, null), new pbr::GeneratedCodeInfo(typeof(global::LoginResponse), global::LoginResponse.Parser, new[]{ "Success", "UserId", "Token" }, null, null, null) })); } #endregion } #region Messages [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public sealed partial class LoginRequest : pb::IMessage<LoginRequest> { private static readonly pb::MessageParser<LoginRequest> _parser = new pb::MessageParser<LoginRequest>(() => new LoginRequest()); public static pb::MessageParser<LoginRequest> Parser { get { return _parser; } } public static pbr::MessageDescriptor Descriptor { get { return global::EmergencyExplorerServiceReflection.Descriptor.MessageTypes[0]; } } pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } public LoginRequest() { OnConstruction(); } partial void OnConstruction(); public LoginRequest(LoginRequest other) : this() { username_ = other.username_; password_ = other.password_; rememberMe_ = other.rememberMe_; } public LoginRequest Clone() { return new LoginRequest(this); } /// <summary>Field number for the "username" field.</summary> public const int UsernameFieldNumber = 1; private string username_ = ""; public string Username { get { return username_; } set { username_ = pb::Preconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "password" field.</summary> public const int PasswordFieldNumber = 2; private string password_ = ""; public string Password { get { return password_; } set { password_ = pb::Preconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "remember_me" field.</summary> public const int RememberMeFieldNumber = 3; private bool rememberMe_; public bool RememberMe { get { return rememberMe_; } set { rememberMe_ = value; } } public override bool Equals(object other) { return Equals(other as LoginRequest); } public bool Equals(LoginRequest other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Username != other.Username) return false; if (Password != other.Password) return false; if (RememberMe != other.RememberMe) return false; return true; } public override int GetHashCode() { int hash = 1; if (Username.Length != 0) hash ^= Username.GetHashCode(); if (Password.Length != 0) hash ^= Password.GetHashCode(); if (RememberMe != false) hash ^= RememberMe.GetHashCode(); return hash; } public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } public void WriteTo(pb::CodedOutputStream output) { if (Username.Length != 0) { output.WriteRawTag(10); output.WriteString(Username); } if (Password.Length != 0) { output.WriteRawTag(18); output.WriteString(Password); } if (RememberMe != false) { output.WriteRawTag(24); output.WriteBool(RememberMe); } } public int CalculateSize() { int size = 0; if (Username.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Username); } if (Password.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Password); } if (RememberMe != false) { size += 1 + 1; } return size; } public void MergeFrom(LoginRequest other) { if (other == null) { return; } if (other.Username.Length != 0) { Username = other.Username; } if (other.Password.Length != 0) { Password = other.Password; } if (other.RememberMe != false) { RememberMe = other.RememberMe; } } public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { Username = input.ReadString(); break; } case 18: { Password = input.ReadString(); break; } case 24: { RememberMe = input.ReadBool(); break; } } } } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public sealed partial class LoginWithTokenRequest : pb::IMessage<LoginWithTokenRequest> { private static readonly pb::MessageParser<LoginWithTokenRequest> _parser = new pb::MessageParser<LoginWithTokenRequest>(() => new LoginWithTokenRequest()); public static pb::MessageParser<LoginWithTokenRequest> Parser { get { return _parser; } } public static pbr::MessageDescriptor Descriptor { get { return global::EmergencyExplorerServiceReflection.Descriptor.MessageTypes[1]; } } pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } public LoginWithTokenRequest() { OnConstruction(); } partial void OnConstruction(); public LoginWithTokenRequest(LoginWithTokenRequest other) : this() { userId_ = other.userId_; token_ = other.token_; } public LoginWithTokenRequest Clone() { return new LoginWithTokenRequest(this); } /// <summary>Field number for the "user_id" field.</summary> public const int UserIdFieldNumber = 1; private uint userId_; public uint UserId { get { return userId_; } set { userId_ = value; } } /// <summary>Field number for the "token" field.</summary> public const int TokenFieldNumber = 2; private string token_ = ""; public string Token { get { return token_; } set { token_ = pb::Preconditions.CheckNotNull(value, "value"); } } public override bool Equals(object other) { return Equals(other as LoginWithTokenRequest); } public bool Equals(LoginWithTokenRequest other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (UserId != other.UserId) return false; if (Token != other.Token) return false; return true; } public override int GetHashCode() { int hash = 1; if (UserId != 0) hash ^= UserId.GetHashCode(); if (Token.Length != 0) hash ^= Token.GetHashCode(); return hash; } public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } public void WriteTo(pb::CodedOutputStream output) { if (UserId != 0) { output.WriteRawTag(8); output.WriteUInt32(UserId); } if (Token.Length != 0) { output.WriteRawTag(18); output.WriteString(Token); } } public int CalculateSize() { int size = 0; if (UserId != 0) { size += 1 + pb::CodedOutputStream.ComputeUInt32Size(UserId); } if (Token.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Token); } return size; } public void MergeFrom(LoginWithTokenRequest other) { if (other == null) { return; } if (other.UserId != 0) { UserId = other.UserId; } if (other.Token.Length != 0) { Token = other.Token; } } public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 8: { UserId = input.ReadUInt32(); break; } case 18: { Token = input.ReadString(); break; } } } } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public sealed partial class LoginResponse : pb::IMessage<LoginResponse> { private static readonly pb::MessageParser<LoginResponse> _parser = new pb::MessageParser<LoginResponse>(() => new LoginResponse()); public static pb::MessageParser<LoginResponse> Parser { get { return _parser; } } public static pbr::MessageDescriptor Descriptor { get { return global::EmergencyExplorerServiceReflection.Descriptor.MessageTypes[2]; } } pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } public LoginResponse() { OnConstruction(); } partial void OnConstruction(); public LoginResponse(LoginResponse other) : this() { success_ = other.success_; userId_ = other.userId_; token_ = other.token_; } public LoginResponse Clone() { return new LoginResponse(this); } /// <summary>Field number for the "success" field.</summary> public const int SuccessFieldNumber = 1; private bool success_; public bool Success { get { return success_; } set { success_ = value; } } /// <summary>Field number for the "user_id" field.</summary> public const int UserIdFieldNumber = 2; private uint userId_; public uint UserId { get { return userId_; } set { userId_ = value; } } /// <summary>Field number for the "token" field.</summary> public const int TokenFieldNumber = 3; private string token_ = ""; public string Token { get { return token_; } set { token_ = pb::Preconditions.CheckNotNull(value, "value"); } } public override bool Equals(object other) { return Equals(other as LoginResponse); } public bool Equals(LoginResponse other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Success != other.Success) return false; if (UserId != other.UserId) return false; if (Token != other.Token) return false; return true; } public override int GetHashCode() { int hash = 1; if (Success != false) hash ^= Success.GetHashCode(); if (UserId != 0) hash ^= UserId.GetHashCode(); if (Token.Length != 0) hash ^= Token.GetHashCode(); return hash; } public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } public void WriteTo(pb::CodedOutputStream output) { if (Success != false) { output.WriteRawTag(8); output.WriteBool(Success); } if (UserId != 0) { output.WriteRawTag(16); output.WriteUInt32(UserId); } if (Token.Length != 0) { output.WriteRawTag(26); output.WriteString(Token); } } public int CalculateSize() { int size = 0; if (Success != false) { size += 1 + 1; } if (UserId != 0) { size += 1 + pb::CodedOutputStream.ComputeUInt32Size(UserId); } if (Token.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Token); } return size; } public void MergeFrom(LoginResponse other) { if (other == null) { return; } if (other.Success != false) { Success = other.Success; } if (other.UserId != 0) { UserId = other.UserId; } if (other.Token.Length != 0) { Token = other.Token; } } public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 8: { Success = input.ReadBool(); break; } case 16: { UserId = input.ReadUInt32(); break; } case 26: { Token = input.ReadString(); break; } } } } } #endregion #endregion Designer generated code
using System.Collections.Specialized; using System.ComponentModel; using System.Drawing; using System.Runtime.CompilerServices; using Newtonsoft.Json; namespace Cyotek.SkylineGenerator { [JsonObject] internal class SimpleSkylineGeneratorSettings : INotifyPropertyChanged { #region Fields private BackgroundStyle _background; private BuildingStyleCollection _buildings; private int _density; private int _horizon; private double _lightingDensity; private Size _maximumBuildingSize; private Size _minimumBuildingSize; private int _seed; private Size _size; private StarStyle _stars; private bool _updatesLocked; private bool _wrap; #endregion #region Constructors public SimpleSkylineGeneratorSettings() { this.Background = new BackgroundStyle(); this.Buildings = new BuildingStyleCollection { new BuildingStyle { Color = Color.FromArgb(37, 36, 90), LightColor = Color.FromArgb(255, 254, 203), GrowWindows = true }, new BuildingStyle { Color = Color.FromArgb(1, 0, 58), LightColor = Color.FromArgb(74, 131, 171), GrowWindows = true } }; this.Size = new Size(1280, 720); this.MaximumBuildingSize = new Size(50, 210); this.MinimumBuildingSize = new Size(10, 20); this.Density = 500; this.LightingDensity = 0.5; this.Stars = new StarStyle(); this.Horizon = 360; this.Wrap = true; } #endregion #region Properties [NotifyParentProperty(true)] public BackgroundStyle Background { get { return _background; } set { if (_background != null) { _background.PropertyChanged -= this.BackgroundPropertyChangedHandler; } _background = value; if (_background != null) { _background.PropertyChanged += this.BackgroundPropertyChangedHandler; } this.OnPropertyChanged(); } } [NotifyParentProperty(true)] public BuildingStyleCollection Buildings { get { return _buildings; } set { if (_buildings != null) { _buildings.CollectionChanged -= this.BuildingsCollectionChangedHandler; _buildings.PropertyChanged -= this.BuildingsPropertyChangedHandler; } _buildings = value; if (_buildings != null) { _buildings.CollectionChanged += this.BuildingsCollectionChangedHandler; _buildings.PropertyChanged += this.BuildingsPropertyChangedHandler; } } } [DefaultValue(500)] public int Density { get { return _density; } set { if (_density != value) { _density = value; this.OnPropertyChanged(); } } } [Category("")] [DefaultValue(360)] public virtual int Horizon { get { return _horizon; } set { if (this.Horizon != value) { _horizon = value; this.OnPropertyChanged(); } } } [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public Bitmap Image { get; protected set; } [Category("")] [DefaultValue(0.5)] public double LightingDensity { get { return _lightingDensity; } set { _lightingDensity = value; this.OnPropertyChanged(); } } [DefaultValue(typeof(Size), "50, 210")] public Size MaximumBuildingSize { get { return _maximumBuildingSize; } set { if (_maximumBuildingSize != value) { _maximumBuildingSize = value; this.OnPropertyChanged(); } } } [DefaultValue(typeof(Size), "10, 20")] public Size MinimumBuildingSize { get { return _minimumBuildingSize; } set { if (_minimumBuildingSize != value) { _minimumBuildingSize = value; this.OnPropertyChanged(); } } } [DefaultValue(0)] public int Seed { get { return _seed; } set { if (_seed != value) { _seed = value; this.OnPropertyChanged(); } } } [DefaultValue(typeof(Size), "1280, 720")] public Size Size { get { return _size; } set { if (_size != value) { _size = value; this.OnPropertyChanged(); } } } [NotifyParentProperty(true)] public StarStyle Stars { get { return _stars; } set { if (_stars != null) { _stars.PropertyChanged -= this.StarsPropertyChangedHandler; } _stars = value; if (_stars != null) { _stars.PropertyChanged += this.StarsPropertyChangedHandler; } this.OnPropertyChanged(); } } [Category("")] [DefaultValue(true)] public virtual bool Wrap { get { return _wrap; } set { if (this.Wrap != value) { _wrap = value; this.OnPropertyChanged(); } } } #endregion #region Methods public void CopyFrom(SimpleSkylineGeneratorSettings source) { try { _updatesLocked = true; this.Background = source.Background.Clone(); this.Buildings = new BuildingStyleCollection(); foreach (BuildingStyle building in source.Buildings) { this.Buildings.Add(building.Clone()); } this.Size = source.Size; this.MaximumBuildingSize = source.MaximumBuildingSize; this.MinimumBuildingSize = source.MinimumBuildingSize; this.Density = source.Density; this.LightingDensity = source.LightingDensity; this.Horizon = source.Horizon; this.Stars = source.Stars.Clone(); this.Seed = source.Seed; } finally { _updatesLocked = false; } this.OnPropertyChanged("Seed"); } protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) { if (!_updatesLocked) { this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } private void BackgroundPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { this.OnPropertyChanged("Background"); } private void BuildingsCollectionChangedHandler(object sender, NotifyCollectionChangedEventArgs notifyCollectionChangedEventArgs) { this.OnPropertyChanged("Buildings"); } private void BuildingsPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { this.OnPropertyChanged("Buildings"); } private void StarsPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { this.OnPropertyChanged("Stars"); } #endregion #region INotifyPropertyChanged Interface public event PropertyChangedEventHandler PropertyChanged; #endregion } }
#pragma warning disable 1591 using AjaxControlToolkit.Design; using AjaxControlToolkit.HtmlEditor.ToolbarButtons; using System; using System.Collections.ObjectModel; using System.ComponentModel; using System.Drawing; using System.Web.UI; using System.Web.UI.WebControls; namespace AjaxControlToolkit.HtmlEditor { [Obsolete("HtmlEditor is obsolete. Use HtmlEditorExtender instead.")] [Designer("AjaxControlToolkit.Design.EditorDesigner, AjaxControlToolkit")] [ToolboxItem(false)] [ValidationPropertyAttribute("Content")] [ClientCssResource(Constants.HtmlEditorEditorName)] [RequiredScript(typeof(CommonToolkitScripts))] [RequiredScript(typeof(AjaxControlToolkit.HtmlEditor.Enums))] [RequiredScript(typeof(AjaxControlToolkit.HtmlEditor.ToolbarButtons.BackColorClear))] [RequiredScript(typeof(AjaxControlToolkit.HtmlEditor.ToolbarButtons.BackColorSelector))] [RequiredScript(typeof(AjaxControlToolkit.HtmlEditor.ToolbarButtons.Bold))] [RequiredScript(typeof(AjaxControlToolkit.HtmlEditor.ToolbarButtons.BoxButton))] [RequiredScript(typeof(AjaxControlToolkit.HtmlEditor.ToolbarButtons.BulletedList))] [RequiredScript(typeof(AjaxControlToolkit.HtmlEditor.ToolbarButtons.ColorButton))] [RequiredScript(typeof(AjaxControlToolkit.HtmlEditor.ToolbarButtons.ColorSelector))] [RequiredScript(typeof(AjaxControlToolkit.HtmlEditor.ToolbarButtons.CommonButton))] [RequiredScript(typeof(AjaxControlToolkit.HtmlEditor.ToolbarButtons.Copy))] [RequiredScript(typeof(AjaxControlToolkit.HtmlEditor.ToolbarButtons.Cut))] [RequiredScript(typeof(AjaxControlToolkit.HtmlEditor.ToolbarButtons.DecreaseIndent))] [RequiredScript(typeof(AjaxControlToolkit.HtmlEditor.ToolbarButtons.DesignMode))] [RequiredScript(typeof(AjaxControlToolkit.HtmlEditor.ToolbarButtons.DesignModeBoxButton))] [RequiredScript(typeof(AjaxControlToolkit.HtmlEditor.ToolbarButtons.DesignModeImageButton))] [RequiredScript(typeof(AjaxControlToolkit.HtmlEditor.ToolbarButtons.DesignModePopupImageButton))] [RequiredScript(typeof(AjaxControlToolkit.HtmlEditor.ToolbarButtons.DesignModeSelectButton))] [RequiredScript(typeof(AjaxControlToolkit.HtmlEditor.ToolbarButtons.EditorToggleButton))] [RequiredScript(typeof(AjaxControlToolkit.HtmlEditor.ToolbarButtons.FixedBackColor))] [RequiredScript(typeof(AjaxControlToolkit.HtmlEditor.ToolbarButtons.FixedColorButton))] [RequiredScript(typeof(AjaxControlToolkit.HtmlEditor.ToolbarButtons.FixedForeColor))] [RequiredScript(typeof(AjaxControlToolkit.HtmlEditor.ToolbarButtons.FontName))] [RequiredScript(typeof(AjaxControlToolkit.HtmlEditor.ToolbarButtons.FontSize))] [RequiredScript(typeof(AjaxControlToolkit.HtmlEditor.ToolbarButtons.ForeColor))] [RequiredScript(typeof(AjaxControlToolkit.HtmlEditor.ToolbarButtons.ForeColorClear))] [RequiredScript(typeof(AjaxControlToolkit.HtmlEditor.ToolbarButtons.ForeColorSelector))] [RequiredScript(typeof(AjaxControlToolkit.HtmlEditor.ToolbarButtons.HorizontalSeparator))] [RequiredScript(typeof(AjaxControlToolkit.HtmlEditor.ToolbarButtons.HtmlMode))] [RequiredScript(typeof(AjaxControlToolkit.HtmlEditor.ToolbarButtons.ImageButton))] [RequiredScript(typeof(AjaxControlToolkit.HtmlEditor.ToolbarButtons.IncreaseIndent))] [RequiredScript(typeof(AjaxControlToolkit.HtmlEditor.ToolbarButtons.InsertHR))] [RequiredScript(typeof(AjaxControlToolkit.HtmlEditor.ToolbarButtons.InsertLink))] [RequiredScript(typeof(AjaxControlToolkit.HtmlEditor.ToolbarButtons.Italic))] [RequiredScript(typeof(AjaxControlToolkit.HtmlEditor.ToolbarButtons.JustifyCenter))] [RequiredScript(typeof(AjaxControlToolkit.HtmlEditor.ToolbarButtons.JustifyFull))] [RequiredScript(typeof(AjaxControlToolkit.HtmlEditor.ToolbarButtons.JustifyLeft))] [RequiredScript(typeof(AjaxControlToolkit.HtmlEditor.ToolbarButtons.JustifyRight))] [RequiredScript(typeof(AjaxControlToolkit.HtmlEditor.ToolbarButtons.Ltr))] [RequiredScript(typeof(AjaxControlToolkit.HtmlEditor.ToolbarButtons.MethodButton))] [RequiredScript(typeof(AjaxControlToolkit.HtmlEditor.ToolbarButtons.ModeButton))] [RequiredScript(typeof(AjaxControlToolkit.HtmlEditor.ToolbarButtons.OkCancelPopupButton))] [RequiredScript(typeof(AjaxControlToolkit.HtmlEditor.ToolbarButtons.OrderedList))] [RequiredScript(typeof(AjaxControlToolkit.HtmlEditor.ToolbarButtons.Paragraph))] [RequiredScript(typeof(AjaxControlToolkit.HtmlEditor.ToolbarButtons.Paste))] [RequiredScript(typeof(AjaxControlToolkit.HtmlEditor.ToolbarButtons.PasteText))] [RequiredScript(typeof(AjaxControlToolkit.HtmlEditor.ToolbarButtons.PasteWord))] [RequiredScript(typeof(AjaxControlToolkit.HtmlEditor.ToolbarButtons.PreviewMode))] [RequiredScript(typeof(AjaxControlToolkit.HtmlEditor.ToolbarButtons.Redo))] [RequiredScript(typeof(AjaxControlToolkit.HtmlEditor.ToolbarButtons.RemoveAlignment))] [RequiredScript(typeof(AjaxControlToolkit.HtmlEditor.ToolbarButtons.RemoveLink))] [RequiredScript(typeof(AjaxControlToolkit.HtmlEditor.ToolbarButtons.RemoveStyles))] [RequiredScript(typeof(AjaxControlToolkit.HtmlEditor.ToolbarButtons.Rtl))] [RequiredScript(typeof(AjaxControlToolkit.HtmlEditor.ToolbarButtons.SelectButton))] [RequiredScript(typeof(AjaxControlToolkit.HtmlEditor.ToolbarButtons.SelectOption))] [RequiredScript(typeof(AjaxControlToolkit.HtmlEditor.ToolbarButtons.Selector))] [RequiredScript(typeof(AjaxControlToolkit.HtmlEditor.ToolbarButtons.StrikeThrough))] [RequiredScript(typeof(AjaxControlToolkit.HtmlEditor.ToolbarButtons.SubScript))] [RequiredScript(typeof(AjaxControlToolkit.HtmlEditor.ToolbarButtons.SuperScript))] [RequiredScript(typeof(AjaxControlToolkit.HtmlEditor.ToolbarButtons.Underline))] [RequiredScript(typeof(AjaxControlToolkit.HtmlEditor.ToolbarButtons.Undo))] [RequiredScript(typeof(AjaxControlToolkit.HtmlEditor.Popups.AttachedPopup))] [RequiredScript(typeof(AjaxControlToolkit.HtmlEditor.Popups.AttachedTemplatePopup))] [RequiredScript(typeof(AjaxControlToolkit.HtmlEditor.Popups.BaseColorsPopup))] [RequiredScript(typeof(AjaxControlToolkit.HtmlEditor.Popups.LinkProperties))] [RequiredScript(typeof(AjaxControlToolkit.HtmlEditor.Popups.OkCancelAttachedTemplatePopup))] [RequiredScript(typeof(AjaxControlToolkit.HtmlEditor.Popups.Popup))] [RequiredScript(typeof(AjaxControlToolkit.HtmlEditor.Popups.PopupBGIButton))] [RequiredScript(typeof(AjaxControlToolkit.HtmlEditor.Popups.PopupBoxButton))] [RequiredScript(typeof(AjaxControlToolkit.HtmlEditor.Popups.PopupCommonButton))] [RequiredScript(typeof(AjaxControlToolkit.HtmlEditor.Popups.RegisteredField))] [ClientScriptResource("Sys.Extended.UI.HtmlEditor.Editor", Constants.HtmlEditorEditorName)] [ToolboxBitmap(typeof(ToolboxIcons.Accessor), Constants.HtmlEditorName + Constants.IconPostfix)] public class Editor : ScriptControlBase { internal Toolbar _bottomToolbar; internal Toolbar _topToolbar; EditPanel _editPanel; Toolbar _changingToolbar; TableCell _editPanelCell; TableRow _topToolbarRow; TableRow _bottomToolbarRow; bool _wasPreRender; public Editor() : base(false, HtmlTextWriterTag.Div) { } [Category("Behavior")] public event ContentChangedEventHandler ContentChanged { add { EditPanel.Events.AddHandler(EditPanel.EventContentChanged, value); } remove { EditPanel.Events.RemoveHandler(EditPanel.EventContentChanged, value); } } protected bool IsDesign { get { try { var isd = false; if(Context == null) isd = true; else if(Site != null) isd = Site.DesignMode; else isd = false; return isd; } catch { return true; } } } [DefaultValue(false)] [Category("Behavior")] public virtual bool SuppressTabInDesignMode { get { return EditPanel.SuppressTabInDesignMode; } set { EditPanel.SuppressTabInDesignMode = value; } } [DefaultValue(false)] public virtual bool TopToolbarPreservePlace { get { return (bool)(ViewState["TopToolbarPreservePlace"] ?? false); } set { ViewState["TopToolbarPreservePlace"] = value; } } [DefaultValue(false)] [Category("Behavior")] public virtual bool IgnoreTab { get { return (bool)(ViewState["IgnoreTab"] ?? false); } set { ViewState["IgnoreTab"] = value; } } [DefaultValue("")] [Category("Appearance")] [Description("Folder used for toolbar's buttons' images")] public virtual string ButtonImagesFolder { get { return (String)(ViewState["ButtonImagesFolder"] ?? String.Empty); } set { ViewState["ButtonImagesFolder"] = value; } } [DefaultValue(false)] [Category("Behavior")] public virtual bool NoUnicode { get { return EditPanel.NoUnicode; } set { EditPanel.NoUnicode = value; } } [DefaultValue(false)] [Category("Behavior")] public virtual bool NoScript { get { return EditPanel.NoScript; } set { EditPanel.NoScript = value; } } [DefaultValue(false)] [Category("Behavior")] public virtual bool InitialCleanUp { get { return EditPanel.InitialCleanUp; } set { EditPanel.InitialCleanUp = value; } } [DefaultValue("ajax__htmleditor_htmlpanel_default")] [Category("Appearance")] public virtual string HtmlPanelCssClass { get { return EditPanel.HtmlPanelCssClass; } set { EditPanel.HtmlPanelCssClass = value; } } [DefaultValue("")] [Category("Appearance")] public virtual string DocumentCssPath { get { return EditPanel.DocumentCssPath; } set { EditPanel.DocumentCssPath = value; } } [DefaultValue("")] [Category("Appearance")] public virtual string DesignPanelCssPath { get { return EditPanel.DesignPanelCssPath; } set { EditPanel.DesignPanelCssPath = value; } } [DefaultValue(true)] [Category("Behavior")] public virtual bool AutoFocus { get { return EditPanel.AutoFocus; } set { EditPanel.AutoFocus = value; } } [DefaultValue("")] [Category("Appearance")] public virtual string Content { get { return EditPanel.Content; } set { EditPanel.Content = value; } } [DefaultValue(ActiveModeType.Design)] [Category("Behavior")] public virtual ActiveModeType ActiveMode { get { return EditPanel.ActiveMode; } set { EditPanel.ActiveMode = value; } } [DefaultValue("")] [Category("Behavior")] public virtual string OnClientActiveModeChanged { get { return EditPanel.OnClientActiveModeChanged; } set { EditPanel.OnClientActiveModeChanged = value; } } [DefaultValue("")] [Category("Behavior")] public virtual string OnClientBeforeActiveModeChanged { get { return EditPanel.OnClientBeforeActiveModeChanged; } set { EditPanel.OnClientBeforeActiveModeChanged = value; } } [DefaultValue(typeof(Unit), "")] [Category("Appearance")] public override Unit Height { get { return base.Height; } set { base.Height = value; } } [DefaultValue(typeof(Unit), "")] [Category("Appearance")] public override Unit Width { get { return base.Width; } set { base.Width = value; } } [DefaultValue("ajax__htmleditor_editor_default")] [Category("Appearance")] public override string CssClass { get { return base.CssClass; } set { base.CssClass = value; } } internal EditPanel EditPanel { get { if(_editPanel == null) _editPanel = new EditPanelInstance(); return _editPanel; } } protected Toolbar BottomToolbar { get { if(_bottomToolbar == null) _bottomToolbar = new ToolbarInstance(); return _bottomToolbar; } } protected Toolbar TopToolbar { get { if(_topToolbar == null) _topToolbar = new ToolbarInstance(); return _topToolbar; } } protected override Style CreateControlStyle() { var style = new EditorStyle(ViewState); style.CssClass = "ajax__htmleditor_editor_default"; return style; } protected override void AddAttributesToRender(HtmlTextWriter writer) { if(!ControlStyleCreated || IsDesign) { writer.AddAttribute(HtmlTextWriterAttribute.Class, (IsDesign ? "ajax__htmleditor_editor_base " : "") + "ajax__htmleditor_editor_default"); } base.AddAttributesToRender(writer); } protected override void DescribeComponent(ScriptComponentDescriptor descriptor) { base.DescribeComponent(descriptor); descriptor.AddComponentProperty("editPanel", EditPanel.ClientID); if(_changingToolbar != null) descriptor.AddComponentProperty("changingToolbar", _changingToolbar.ClientID); } protected override void OnInit(EventArgs e) { base.OnInit(e); EditPanel.Toolbars.Add(BottomToolbar); _changingToolbar = TopToolbar; EditPanel.Toolbars.Add(TopToolbar); var table = new Table(); TableRow row; TableCell cell; table.CellPadding = 0; table.CellSpacing = 0; table.CssClass = "ajax__htmleditor_editor_container"; table.Style[HtmlTextWriterStyle.BorderCollapse] = "separate"; _topToolbarRow = row = new TableRow(); cell = new TableCell(); cell.Controls.Add(TopToolbar); cell.CssClass = "ajax__htmleditor_editor_toptoolbar"; row.Cells.Add(cell); table.Rows.Add(row); row = new TableRow(); _editPanelCell = cell = new TableCell(); cell.CssClass = "ajax__htmleditor_editor_editpanel"; cell.Controls.Add(EditPanel); row.Cells.Add(cell); table.Rows.Add(row); _bottomToolbarRow = row = new TableRow(); cell = new TableCell(); cell.Controls.Add(BottomToolbar); cell.CssClass = "ajax__htmleditor_editor_bottomtoolbar"; row.Cells.Add(cell); table.Rows.Add(row); Controls.Add(table); } protected virtual void FillBottomToolbar() { BottomToolbar.Buttons.Add(new DesignMode()); BottomToolbar.Buttons.Add(new HtmlMode()); BottomToolbar.Buttons.Add(new PreviewMode()); } protected virtual void FillTopToolbar() { Collection<SelectOption> options; SelectOption option; TopToolbar.Buttons.Add(new ToolbarButtons.Undo()); TopToolbar.Buttons.Add(new ToolbarButtons.Redo()); TopToolbar.Buttons.Add(new ToolbarButtons.HorizontalSeparator()); TopToolbar.Buttons.Add(new ToolbarButtons.Bold()); TopToolbar.Buttons.Add(new ToolbarButtons.Italic()); TopToolbar.Buttons.Add(new ToolbarButtons.Underline()); TopToolbar.Buttons.Add(new ToolbarButtons.StrikeThrough()); TopToolbar.Buttons.Add(new ToolbarButtons.SubScript()); TopToolbar.Buttons.Add(new ToolbarButtons.SuperScript()); TopToolbar.Buttons.Add(new ToolbarButtons.HorizontalSeparator()); TopToolbar.Buttons.Add(new ToolbarButtons.Ltr()); TopToolbar.Buttons.Add(new ToolbarButtons.Rtl()); TopToolbar.Buttons.Add(new ToolbarButtons.HorizontalSeparator()); var FixedForeColor = new ToolbarButtons.FixedForeColor(); TopToolbar.Buttons.Add(FixedForeColor); var ForeColorSelector = new ToolbarButtons.ForeColorSelector(); ForeColorSelector.FixedColorButtonId = FixedForeColor.ID = "FixedForeColor"; TopToolbar.Buttons.Add(ForeColorSelector); TopToolbar.Buttons.Add(new ToolbarButtons.ForeColorClear()); TopToolbar.Buttons.Add(new ToolbarButtons.HorizontalSeparator()); var FixedBackColor = new ToolbarButtons.FixedBackColor(); TopToolbar.Buttons.Add(FixedBackColor); var BackColorSelector = new ToolbarButtons.BackColorSelector(); BackColorSelector.FixedColorButtonId = FixedBackColor.ID = "FixedBackColor"; TopToolbar.Buttons.Add(BackColorSelector); TopToolbar.Buttons.Add(new ToolbarButtons.BackColorClear()); TopToolbar.Buttons.Add(new ToolbarButtons.HorizontalSeparator()); TopToolbar.Buttons.Add(new ToolbarButtons.RemoveStyles()); TopToolbar.Buttons.Add(new ToolbarButtons.HorizontalSeparator()); var fontName = new FontName(); TopToolbar.Buttons.Add(fontName); options = fontName.Options; option = new SelectOption { Text = "Arial", Value = "arial,helvetica,sans-serif" }; options.Add(option); option = new SelectOption { Text = "Courier New", Value = "courier new,courier,monospace" }; options.Add(option); option = new SelectOption { Text = "Georgia", Value = "georgia,times new roman,times,serif" }; options.Add(option); option = new SelectOption { Text = "Tahoma", Value = "tahoma,arial,helvetica,sans-serif" }; options.Add(option); option = new SelectOption { Text = "Times New Roman", Value = "times new roman,times,serif" }; options.Add(option); option = new SelectOption { Text = "Verdana", Value = "verdana,arial,helvetica,sans-serif" }; options.Add(option); option = new SelectOption { Text = "Impact", Value = "impact" }; options.Add(option); option = new SelectOption { Text = "WingDings", Value = "wingdings" }; options.Add(option); TopToolbar.Buttons.Add(new ToolbarButtons.HorizontalSeparator()); var fontSize = new ToolbarButtons.FontSize(); TopToolbar.Buttons.Add(fontSize); options = fontSize.Options; option = new SelectOption { Text = "1 ( 8 pt)", Value = "8pt" }; options.Add(option); option = new SelectOption { Text = "2 (10 pt)", Value = "10pt" }; options.Add(option); option = new SelectOption { Text = "3 (12 pt)", Value = "12pt" }; options.Add(option); option = new SelectOption { Text = "4 (14 pt)", Value = "14pt" }; options.Add(option); option = new SelectOption { Text = "5 (18 pt)", Value = "18pt" }; options.Add(option); option = new SelectOption { Text = "6 (24 pt)", Value = "24pt" }; options.Add(option); option = new SelectOption { Text = "7 (36 pt)", Value = "36pt" }; options.Add(option); TopToolbar.Buttons.Add(new ToolbarButtons.HorizontalSeparator()); TopToolbar.Buttons.Add(new ToolbarButtons.Cut()); TopToolbar.Buttons.Add(new ToolbarButtons.Copy()); TopToolbar.Buttons.Add(new ToolbarButtons.Paste()); TopToolbar.Buttons.Add(new ToolbarButtons.PasteText()); TopToolbar.Buttons.Add(new ToolbarButtons.PasteWord()); TopToolbar.Buttons.Add(new ToolbarButtons.HorizontalSeparator()); TopToolbar.Buttons.Add(new ToolbarButtons.DecreaseIndent()); TopToolbar.Buttons.Add(new ToolbarButtons.IncreaseIndent()); TopToolbar.Buttons.Add(new ToolbarButtons.HorizontalSeparator()); TopToolbar.Buttons.Add(new ToolbarButtons.Paragraph()); TopToolbar.Buttons.Add(new ToolbarButtons.JustifyLeft()); TopToolbar.Buttons.Add(new ToolbarButtons.JustifyCenter()); TopToolbar.Buttons.Add(new ToolbarButtons.JustifyRight()); TopToolbar.Buttons.Add(new ToolbarButtons.JustifyFull()); TopToolbar.Buttons.Add(new ToolbarButtons.RemoveAlignment()); TopToolbar.Buttons.Add(new ToolbarButtons.HorizontalSeparator()); TopToolbar.Buttons.Add(new ToolbarButtons.OrderedList()); TopToolbar.Buttons.Add(new ToolbarButtons.BulletedList()); TopToolbar.Buttons.Add(new ToolbarButtons.HorizontalSeparator()); TopToolbar.Buttons.Add(new ToolbarButtons.InsertHR()); TopToolbar.Buttons.Add(new ToolbarButtons.InsertLink()); TopToolbar.Buttons.Add(new ToolbarButtons.RemoveLink()); } protected override void CreateChildControls() { BottomToolbar.Buttons.Clear(); FillBottomToolbar(); if(BottomToolbar.Buttons.Count == 0) { if(EditPanel.Toolbars.Contains(BottomToolbar)) EditPanel.Toolbars.Remove(BottomToolbar); _bottomToolbarRow.Visible = false; (EditPanel.Parent as TableCell).Style["border-bottom-width"] = "0"; } else { BottomToolbar.AlwaysVisible = true; BottomToolbar.ButtonImagesFolder = ButtonImagesFolder; for(var i = 0; i < BottomToolbar.Buttons.Count; i++) BottomToolbar.Buttons[i].IgnoreTab = IgnoreTab; } TopToolbar.Buttons.Clear(); FillTopToolbar(); if(TopToolbar.Buttons.Count == 0) { if(EditPanel.Toolbars.Contains(TopToolbar)) EditPanel.Toolbars.Remove(TopToolbar); _topToolbarRow.Visible = false; (EditPanel.Parent as TableCell).Style["border-top-width"] = "0"; _changingToolbar = null; } else { TopToolbar.ButtonImagesFolder = ButtonImagesFolder; for(var i = 0; i < TopToolbar.Buttons.Count; i++) { TopToolbar.Buttons[i].IgnoreTab = IgnoreTab; TopToolbar.Buttons[i].PreservePlace = TopToolbarPreservePlace; } } if(!Height.IsEmpty) (Controls[0] as Table).Style.Add(HtmlTextWriterStyle.Height, Height.ToString()); if(!Width.IsEmpty) (Controls[0] as Table).Style.Add(HtmlTextWriterStyle.Width, Width.ToString()); if(EditPanel.IE(Page) && !IsDesign) { _editPanelCell.Style[HtmlTextWriterStyle.Height] = "expression(Sys.Extended.UI.HtmlEditor.Editor.MidleCellHeightForIE(this.parentNode.parentNode.parentNode,this.parentNode))"; } EditPanel.IgnoreTab = IgnoreTab; } protected override void OnPreRender(EventArgs e) { try { base.OnPreRender(e); } catch { } _wasPreRender = true; } protected override void Render(HtmlTextWriter writer) { if(!_wasPreRender) OnPreRender(new EventArgs()); base.Render(writer); } internal void CreateChilds(DesignerWithMapPath designer) { CreateChildControls(); TopToolbar.CreateChilds(designer); BottomToolbar.CreateChilds(designer); EditPanel.SetDesigner(designer); } private sealed class EditorStyle : Style { public EditorStyle(StateBag state) : base(state) { } protected override void FillStyleAttributes(CssStyleCollection attributes, IUrlResolutionService urlResolver) { base.FillStyleAttributes(attributes, urlResolver); attributes.Remove(HtmlTextWriterStyle.Height); attributes.Remove(HtmlTextWriterStyle.Width); } } } } #pragma warning restore 1591
using System.Collections.Generic; using System.IO; using Wasm.Binary; namespace Wasm { /// <summary> /// A type of section that imports values. /// </summary> public sealed class ImportSection : Section { /// <summary> /// Creates an empty import section. /// </summary> public ImportSection() { this.Imports = new List<ImportedValue>(); this.ExtraPayload = new byte[0]; } /// <summary> /// Creates an import section from a sequence of imports. /// </summary> /// <param name="imports">A sequence of imports to put in the import section.</param> public ImportSection(IEnumerable<ImportedValue> imports) : this(imports, new byte[0]) { } /// <summary> /// Creates an import section from a sequence of imports and a trailing payload. /// </summary> /// <param name="imports">A sequence of imports to put in the import section.</param> /// <param name="extraPayload"> /// A sequence of bytes that have no intrinsic meaning; they are part /// of the import section but are placed after the import section's actual contents. /// </param> public ImportSection(IEnumerable<ImportedValue> imports, byte[] extraPayload) { this.Imports = new List<ImportedValue>(imports); this.ExtraPayload = extraPayload; } /// <inheritdoc/> public override SectionName Name => new SectionName(SectionCode.Import); /// <summary> /// Gets the list of all values that are exported by this section. /// </summary> /// <returns>A list of all values exported by this section.</returns> public List<ImportedValue> Imports { get; private set; } /// <summary> /// Gets this function section's additional payload. /// </summary> /// <returns>The additional payload, as an array of bytes.</returns> public byte[] ExtraPayload { get; set; } /// <inheritdoc/> public override void WritePayloadTo(BinaryWasmWriter writer) { writer.WriteVarUInt32((uint)Imports.Count); foreach (var import in Imports) { import.WriteTo(writer); } writer.Writer.Write(ExtraPayload); } /// <summary> /// Reads the import section with the given header. /// </summary> /// <param name="header">The section header.</param> /// <param name="reader">A reader for a binary WebAssembly file.</param> /// <returns>The parsed section.</returns> public static ImportSection ReadSectionPayload( SectionHeader header, BinaryWasmReader reader) { long startPos = reader.Position; // Read the imported values. uint count = reader.ReadVarUInt32(); var importedVals = new List<ImportedValue>(); for (uint i = 0; i < count; i++) { importedVals.Add(ImportedValue.ReadFrom(reader)); } // Skip any remaining bytes. var extraPayload = reader.ReadRemainingPayload(startPos, header); return new ImportSection(importedVals, extraPayload); } /// <inheritdoc/> public override void Dump(TextWriter writer) { writer.Write(Name.ToString()); writer.Write("; number of entries: "); writer.Write(Imports.Count); writer.WriteLine(); for (int i = 0; i < Imports.Count; i++) { writer.Write("#"); writer.Write(i); writer.Write(" -> "); Imports[i].Dump(writer); writer.WriteLine(); } if (ExtraPayload.Length > 0) { writer.Write("Extra payload size: "); writer.Write(ExtraPayload.Length); writer.WriteLine(); DumpHelpers.DumpBytes(ExtraPayload, writer); writer.WriteLine(); } } } /// <summary> /// An entry in an import section. /// </summary> public abstract class ImportedValue { /// <summary> /// Creates an import value from the given pair of names. /// </summary> /// <param name="moduleName">The name of the module from which a value is imported.</param> /// <param name="fieldName">The name of the value that is imported.</param> public ImportedValue(string moduleName, string fieldName) { this.ModuleName = moduleName; this.FieldName = fieldName; } /// <summary> /// Gets or sets the name of the module from which a value is imported. /// </summary> /// <returns>The name of the module from which a value is imported.</returns> public string ModuleName { get; set; } /// <summary> /// Gets or sets the name of the value that is imported. /// </summary> /// <returns>The name of the value that is imported.</returns> public string FieldName { get; set; } /// <summary> /// Gets the kind of value that is exported. /// </summary> /// <returns>The kind of value that is exported.</returns> public abstract ExternalKind Kind { get; } /// <summary> /// Writes the contents of this imported value to the given binary WebAssembly writer. /// </summary> /// <param name="writer">A WebAssembly writer.</param> protected abstract void WriteContentsTo(BinaryWasmWriter writer); /// <summary> /// Dumps the contents of this imported value to the given text writer. /// </summary> /// <param name="writer">A text writer.</param> protected abstract void DumpContents(TextWriter writer); /// <summary> /// Writes this exported value to the given WebAssembly file writer. /// </summary> /// <param name="writer">The WebAssembly file writer.</param> public void WriteTo(BinaryWasmWriter writer) { writer.WriteString(ModuleName); writer.WriteString(FieldName); writer.Writer.Write((byte)Kind); WriteContentsTo(writer); } /// <summary> /// Writes a textual representation of this exported value to the given writer. /// </summary> /// <param name="writer">The writer to which text is written.</param> public void Dump(TextWriter writer) { writer.Write( "from \"{0}\" import {1} \"{2}\": ", ModuleName, ((object)Kind).ToString().ToLower(), FieldName); DumpContents(writer); } /// <summary> /// Reads an imported value from the given binary WebAssembly reader. /// </summary> /// <param name="reader">The WebAssembly reader.</param> /// <returns>The imported value that was read.</returns> public static ImportedValue ReadFrom(BinaryWasmReader reader) { string moduleName = reader.ReadString(); string fieldName = reader.ReadString(); var kind = (ExternalKind)reader.ReadByte(); switch (kind) { case ExternalKind.Function: return new ImportedFunction(moduleName, fieldName, reader.ReadVarUInt32()); case ExternalKind.Global: return new ImportedGlobal(moduleName, fieldName, GlobalType.ReadFrom(reader)); case ExternalKind.Memory: return new ImportedMemory(moduleName, fieldName, MemoryType.ReadFrom(reader)); case ExternalKind.Table: return new ImportedTable(moduleName, fieldName, TableType.ReadFrom(reader)); default: throw new WasmException("Unknown imported value kind: " + kind); } } } /// <summary> /// Describes an entry in the import section that imports a function. /// </summary> public sealed class ImportedFunction : ImportedValue { /// <summary> /// Creates a function import from the given module name, field and function index. /// </summary> /// <param name="moduleName">The name of the module from which a value is imported.</param> /// <param name="fieldName">The name of the value that is imported.</param> /// <param name="typeIndex">The type index of the function signature.</param> public ImportedFunction(string moduleName, string fieldName, uint typeIndex) : base(moduleName, fieldName) { this.TypeIndex = typeIndex; } /// <summary> /// Gets or sets the type index of the function signature. /// </summary> /// <returns>The type index of the function signature.</returns> public uint TypeIndex { get; set; } /// <inheritdoc/> public override ExternalKind Kind => ExternalKind.Function; /// <inheritdoc/> protected override void DumpContents(TextWriter writer) { writer.Write("type #{0}", TypeIndex); } /// <inheritdoc/> protected override void WriteContentsTo(BinaryWasmWriter writer) { writer.WriteVarUInt32(TypeIndex); } } /// <summary> /// Describes an entry in the import section that imports a table. /// </summary> public sealed class ImportedTable : ImportedValue { /// <summary> /// Creates a table import from the given module name, field and table type. /// </summary> /// <param name="moduleName">The name of the module from which a value is imported.</param> /// <param name="fieldName">The name of the value that is imported.</param> /// <param name="table">A description of the imported table.</param> public ImportedTable(string moduleName, string fieldName, TableType table) : base(moduleName, fieldName) { this.Table = table; } /// <summary> /// Gets or sets a description of the table that is imported. /// </summary> /// <returns>A description of the table that is imported.</returns> public TableType Table { get; set; } /// <inheritdoc/> public override ExternalKind Kind => ExternalKind.Table; /// <inheritdoc/> protected override void DumpContents(TextWriter writer) { Table.Dump(writer); } /// <inheritdoc/> protected override void WriteContentsTo(BinaryWasmWriter writer) { Table.WriteTo(writer); } } /// <summary> /// Describes an entry in the import section that imports a linear memory. /// </summary> public sealed class ImportedMemory : ImportedValue { /// <summary> /// Creates a memory import from the given module name, field and memory type. /// </summary> /// <param name="moduleName">The name of the module from which a value is imported.</param> /// <param name="fieldName">The name of the value that is imported.</param> /// <param name="memory">A description of the imported memory.</param> public ImportedMemory(string moduleName, string fieldName, MemoryType memory) : base(moduleName, fieldName) { this.Memory = memory; } /// <summary> /// Gets or sets a description of the table that is imported. /// </summary> /// <returns>A description of the table that is imported.</returns> public MemoryType Memory { get; set; } /// <inheritdoc/> public override ExternalKind Kind => ExternalKind.Memory; /// <inheritdoc/> protected override void DumpContents(TextWriter writer) { Memory.Dump(writer); } /// <inheritdoc/> protected override void WriteContentsTo(BinaryWasmWriter writer) { Memory.WriteTo(writer); } } /// <summary> /// Describes an entry in the import section that imports a global variable. /// </summary> public sealed class ImportedGlobal : ImportedValue { /// <summary> /// Creates a global import from the given module name, field and global type. /// </summary> /// <param name="moduleName">The name of the module from which a value is imported.</param> /// <param name="fieldName">The name of the value that is imported.</param> /// <param name="global">A description of the imported global.</param> public ImportedGlobal(string moduleName, string fieldName, GlobalType global) : base(moduleName, fieldName) { this.Global = global; } /// <summary> /// Gets or sets a description of the global variable that is imported. /// </summary> /// <returns>A description of the global variable that is imported.</returns> public GlobalType Global { get; set; } /// <inheritdoc/> public override ExternalKind Kind => ExternalKind.Global; /// <inheritdoc/> protected override void DumpContents(TextWriter writer) { Global.Dump(writer); } /// <inheritdoc/> protected override void WriteContentsTo(BinaryWasmWriter writer) { Global.WriteTo(writer); } } }
using System; using System.Text; using System.Data; using System.Data.SqlClient; using System.Data.Common; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Xml; using System.Xml.Serialization; using SubSonic; using SubSonic.Utilities; namespace DalSic { /// <summary> /// Strongly-typed collection for the SysCIE10 class. /// </summary> [Serializable] public partial class SysCIE10Collection : ActiveList<SysCIE10, SysCIE10Collection> { public SysCIE10Collection() {} /// <summary> /// Filters an existing collection based on the set criteria. This is an in-memory filter /// Thanks to developingchris for this! /// </summary> /// <returns>SysCIE10Collection</returns> public SysCIE10Collection Filter() { for (int i = this.Count - 1; i > -1; i--) { SysCIE10 o = this[i]; foreach (SubSonic.Where w in this.wheres) { bool remove = false; System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName); if (pi.CanRead) { object val = pi.GetValue(o, null); switch (w.Comparison) { case SubSonic.Comparison.Equals: if (!val.Equals(w.ParameterValue)) { remove = true; } break; } } if (remove) { this.Remove(o); break; } } } return this; } } /// <summary> /// This is an ActiveRecord class which wraps the Sys_CIE10 table. /// </summary> [Serializable] public partial class SysCIE10 : ActiveRecord<SysCIE10>, IActiveRecord { #region .ctors and Default Settings public SysCIE10() { SetSQLProps(); InitSetDefaults(); MarkNew(); } private void InitSetDefaults() { SetDefaults(); } public SysCIE10(bool useDatabaseDefaults) { SetSQLProps(); if(useDatabaseDefaults) ForceDefaults(); MarkNew(); } public SysCIE10(object keyID) { SetSQLProps(); InitSetDefaults(); LoadByKey(keyID); } public SysCIE10(string columnName, object columnValue) { SetSQLProps(); InitSetDefaults(); LoadByParam(columnName,columnValue); } protected static void SetSQLProps() { GetTableSchema(); } #endregion #region Schema and Query Accessor public static Query CreateQuery() { return new Query(Schema); } public static TableSchema.Table Schema { get { if (BaseSchema == null) SetSQLProps(); return BaseSchema; } } private static void GetTableSchema() { if(!IsSchemaInitialized) { //Schema declaration TableSchema.Table schema = new TableSchema.Table("Sys_CIE10", TableType.Table, DataService.GetInstance("sicProvider")); schema.Columns = new TableSchema.TableColumnCollection(); schema.SchemaName = @"dbo"; //columns TableSchema.TableColumn colvarId = new TableSchema.TableColumn(schema); colvarId.ColumnName = "ID"; colvarId.DataType = DbType.Int32; colvarId.MaxLength = 0; colvarId.AutoIncrement = true; colvarId.IsNullable = false; colvarId.IsPrimaryKey = true; colvarId.IsForeignKey = false; colvarId.IsReadOnly = false; colvarId.DefaultSetting = @""; colvarId.ForeignKeyTableName = ""; schema.Columns.Add(colvarId); TableSchema.TableColumn colvarCapitulo = new TableSchema.TableColumn(schema); colvarCapitulo.ColumnName = "CAPITULO"; colvarCapitulo.DataType = DbType.String; colvarCapitulo.MaxLength = 255; colvarCapitulo.AutoIncrement = false; colvarCapitulo.IsNullable = true; colvarCapitulo.IsPrimaryKey = false; colvarCapitulo.IsForeignKey = false; colvarCapitulo.IsReadOnly = false; colvarCapitulo.DefaultSetting = @""; colvarCapitulo.ForeignKeyTableName = ""; schema.Columns.Add(colvarCapitulo); TableSchema.TableColumn colvarGRUPOCIE10 = new TableSchema.TableColumn(schema); colvarGRUPOCIE10.ColumnName = "GRUPOCIE10"; colvarGRUPOCIE10.DataType = DbType.String; colvarGRUPOCIE10.MaxLength = 255; colvarGRUPOCIE10.AutoIncrement = false; colvarGRUPOCIE10.IsNullable = true; colvarGRUPOCIE10.IsPrimaryKey = false; colvarGRUPOCIE10.IsForeignKey = false; colvarGRUPOCIE10.IsReadOnly = false; colvarGRUPOCIE10.DefaultSetting = @""; colvarGRUPOCIE10.ForeignKeyTableName = ""; schema.Columns.Add(colvarGRUPOCIE10); TableSchema.TableColumn colvarCausa = new TableSchema.TableColumn(schema); colvarCausa.ColumnName = "CAUSA"; colvarCausa.DataType = DbType.String; colvarCausa.MaxLength = 255; colvarCausa.AutoIncrement = false; colvarCausa.IsNullable = true; colvarCausa.IsPrimaryKey = false; colvarCausa.IsForeignKey = false; colvarCausa.IsReadOnly = false; colvarCausa.DefaultSetting = @""; colvarCausa.ForeignKeyTableName = ""; schema.Columns.Add(colvarCausa); TableSchema.TableColumn colvarSubcausa = new TableSchema.TableColumn(schema); colvarSubcausa.ColumnName = "SUBCAUSA"; colvarSubcausa.DataType = DbType.String; colvarSubcausa.MaxLength = 255; colvarSubcausa.AutoIncrement = false; colvarSubcausa.IsNullable = true; colvarSubcausa.IsPrimaryKey = false; colvarSubcausa.IsForeignKey = false; colvarSubcausa.IsReadOnly = false; colvarSubcausa.DefaultSetting = @""; colvarSubcausa.ForeignKeyTableName = ""; schema.Columns.Add(colvarSubcausa); TableSchema.TableColumn colvarCodigo = new TableSchema.TableColumn(schema); colvarCodigo.ColumnName = "CODIGO"; colvarCodigo.DataType = DbType.String; colvarCodigo.MaxLength = 255; colvarCodigo.AutoIncrement = false; colvarCodigo.IsNullable = true; colvarCodigo.IsPrimaryKey = false; colvarCodigo.IsForeignKey = false; colvarCodigo.IsReadOnly = false; colvarCodigo.DefaultSetting = @""; colvarCodigo.ForeignKeyTableName = ""; schema.Columns.Add(colvarCodigo); TableSchema.TableColumn colvarNombre = new TableSchema.TableColumn(schema); colvarNombre.ColumnName = "Nombre"; colvarNombre.DataType = DbType.String; colvarNombre.MaxLength = 255; colvarNombre.AutoIncrement = false; colvarNombre.IsNullable = true; colvarNombre.IsPrimaryKey = false; colvarNombre.IsForeignKey = false; colvarNombre.IsReadOnly = false; colvarNombre.DefaultSetting = @""; colvarNombre.ForeignKeyTableName = ""; schema.Columns.Add(colvarNombre); TableSchema.TableColumn colvarSinonimo = new TableSchema.TableColumn(schema); colvarSinonimo.ColumnName = "Sinonimo"; colvarSinonimo.DataType = DbType.String; colvarSinonimo.MaxLength = 255; colvarSinonimo.AutoIncrement = false; colvarSinonimo.IsNullable = true; colvarSinonimo.IsPrimaryKey = false; colvarSinonimo.IsForeignKey = false; colvarSinonimo.IsReadOnly = false; colvarSinonimo.DefaultSetting = @"('')"; colvarSinonimo.ForeignKeyTableName = ""; schema.Columns.Add(colvarSinonimo); TableSchema.TableColumn colvarDescripCap = new TableSchema.TableColumn(schema); colvarDescripCap.ColumnName = "DescripCap"; colvarDescripCap.DataType = DbType.String; colvarDescripCap.MaxLength = 255; colvarDescripCap.AutoIncrement = false; colvarDescripCap.IsNullable = true; colvarDescripCap.IsPrimaryKey = false; colvarDescripCap.IsForeignKey = false; colvarDescripCap.IsReadOnly = false; colvarDescripCap.DefaultSetting = @""; colvarDescripCap.ForeignKeyTableName = ""; schema.Columns.Add(colvarDescripCap); TableSchema.TableColumn colvarModif = new TableSchema.TableColumn(schema); colvarModif.ColumnName = "Modif"; colvarModif.DataType = DbType.Double; colvarModif.MaxLength = 0; colvarModif.AutoIncrement = false; colvarModif.IsNullable = true; colvarModif.IsPrimaryKey = false; colvarModif.IsForeignKey = false; colvarModif.IsReadOnly = false; colvarModif.DefaultSetting = @""; colvarModif.ForeignKeyTableName = ""; schema.Columns.Add(colvarModif); TableSchema.TableColumn colvarCepsap = new TableSchema.TableColumn(schema); colvarCepsap.ColumnName = "CEPSAP"; colvarCepsap.DataType = DbType.String; colvarCepsap.MaxLength = 50; colvarCepsap.AutoIncrement = false; colvarCepsap.IsNullable = true; colvarCepsap.IsPrimaryKey = false; colvarCepsap.IsForeignKey = false; colvarCepsap.IsReadOnly = false; colvarCepsap.DefaultSetting = @""; colvarCepsap.ForeignKeyTableName = ""; schema.Columns.Add(colvarCepsap); TableSchema.TableColumn colvarC2 = new TableSchema.TableColumn(schema); colvarC2.ColumnName = "C2"; colvarC2.DataType = DbType.Boolean; colvarC2.MaxLength = 0; colvarC2.AutoIncrement = false; colvarC2.IsNullable = false; colvarC2.IsPrimaryKey = false; colvarC2.IsForeignKey = false; colvarC2.IsReadOnly = false; colvarC2.DefaultSetting = @"((0))"; colvarC2.ForeignKeyTableName = ""; schema.Columns.Add(colvarC2); BaseSchema = schema; //add this schema to the provider //so we can query it later DataService.Providers["sicProvider"].AddSchema("Sys_CIE10",schema); } } #endregion #region Props [XmlAttribute("Id")] [Bindable(true)] public int Id { get { return GetColumnValue<int>(Columns.Id); } set { SetColumnValue(Columns.Id, value); } } [XmlAttribute("Capitulo")] [Bindable(true)] public string Capitulo { get { return GetColumnValue<string>(Columns.Capitulo); } set { SetColumnValue(Columns.Capitulo, value); } } [XmlAttribute("GRUPOCIE10")] [Bindable(true)] public string GRUPOCIE10 { get { return GetColumnValue<string>(Columns.GRUPOCIE10); } set { SetColumnValue(Columns.GRUPOCIE10, value); } } [XmlAttribute("Causa")] [Bindable(true)] public string Causa { get { return GetColumnValue<string>(Columns.Causa); } set { SetColumnValue(Columns.Causa, value); } } [XmlAttribute("Subcausa")] [Bindable(true)] public string Subcausa { get { return GetColumnValue<string>(Columns.Subcausa); } set { SetColumnValue(Columns.Subcausa, value); } } [XmlAttribute("Codigo")] [Bindable(true)] public string Codigo { get { return GetColumnValue<string>(Columns.Codigo); } set { SetColumnValue(Columns.Codigo, value); } } [XmlAttribute("Nombre")] [Bindable(true)] public string Nombre { get { return GetColumnValue<string>(Columns.Nombre); } set { SetColumnValue(Columns.Nombre, value); } } [XmlAttribute("Sinonimo")] [Bindable(true)] public string Sinonimo { get { return GetColumnValue<string>(Columns.Sinonimo); } set { SetColumnValue(Columns.Sinonimo, value); } } [XmlAttribute("DescripCap")] [Bindable(true)] public string DescripCap { get { return GetColumnValue<string>(Columns.DescripCap); } set { SetColumnValue(Columns.DescripCap, value); } } [XmlAttribute("Modif")] [Bindable(true)] public double? Modif { get { return GetColumnValue<double?>(Columns.Modif); } set { SetColumnValue(Columns.Modif, value); } } [XmlAttribute("Cepsap")] [Bindable(true)] public string Cepsap { get { return GetColumnValue<string>(Columns.Cepsap); } set { SetColumnValue(Columns.Cepsap, value); } } [XmlAttribute("C2")] [Bindable(true)] public bool C2 { get { return GetColumnValue<bool>(Columns.C2); } set { SetColumnValue(Columns.C2, value); } } #endregion #region PrimaryKey Methods protected override void SetPrimaryKey(object oValue) { base.SetPrimaryKey(oValue); SetPKValues(); } private DalSic.SysAntecedenteEnfermedadCollection colSysAntecedenteEnfermedadRecords; public DalSic.SysAntecedenteEnfermedadCollection SysAntecedenteEnfermedadRecords { get { if(colSysAntecedenteEnfermedadRecords == null) { colSysAntecedenteEnfermedadRecords = new DalSic.SysAntecedenteEnfermedadCollection().Where(SysAntecedenteEnfermedad.Columns.CODCIE10, Id).Load(); colSysAntecedenteEnfermedadRecords.ListChanged += new ListChangedEventHandler(colSysAntecedenteEnfermedadRecords_ListChanged); } return colSysAntecedenteEnfermedadRecords; } set { colSysAntecedenteEnfermedadRecords = value; colSysAntecedenteEnfermedadRecords.ListChanged += new ListChangedEventHandler(colSysAntecedenteEnfermedadRecords_ListChanged); } } void colSysAntecedenteEnfermedadRecords_ListChanged(object sender, ListChangedEventArgs e) { if (e.ListChangedType == ListChangedType.ItemAdded) { // Set foreign key value colSysAntecedenteEnfermedadRecords[e.NewIndex].CODCIE10 = Id; } } private DalSic.AprRelRecienNacidoEnfermedadCollection colAprRelRecienNacidoEnfermedadRecords; public DalSic.AprRelRecienNacidoEnfermedadCollection AprRelRecienNacidoEnfermedadRecords { get { if(colAprRelRecienNacidoEnfermedadRecords == null) { colAprRelRecienNacidoEnfermedadRecords = new DalSic.AprRelRecienNacidoEnfermedadCollection().Where(AprRelRecienNacidoEnfermedad.Columns.CODCIE10, Id).Load(); colAprRelRecienNacidoEnfermedadRecords.ListChanged += new ListChangedEventHandler(colAprRelRecienNacidoEnfermedadRecords_ListChanged); } return colAprRelRecienNacidoEnfermedadRecords; } set { colAprRelRecienNacidoEnfermedadRecords = value; colAprRelRecienNacidoEnfermedadRecords.ListChanged += new ListChangedEventHandler(colAprRelRecienNacidoEnfermedadRecords_ListChanged); } } void colAprRelRecienNacidoEnfermedadRecords_ListChanged(object sender, ListChangedEventArgs e) { if (e.ListChangedType == ListChangedType.ItemAdded) { // Set foreign key value colAprRelRecienNacidoEnfermedadRecords[e.NewIndex].CODCIE10 = Id; } } private DalSic.AprAntecedentePatologiaEmbarazoCollection colAprAntecedentePatologiaEmbarazoRecords; public DalSic.AprAntecedentePatologiaEmbarazoCollection AprAntecedentePatologiaEmbarazoRecords { get { if(colAprAntecedentePatologiaEmbarazoRecords == null) { colAprAntecedentePatologiaEmbarazoRecords = new DalSic.AprAntecedentePatologiaEmbarazoCollection().Where(AprAntecedentePatologiaEmbarazo.Columns.IdPatologiaEmbarazo, Id).Load(); colAprAntecedentePatologiaEmbarazoRecords.ListChanged += new ListChangedEventHandler(colAprAntecedentePatologiaEmbarazoRecords_ListChanged); } return colAprAntecedentePatologiaEmbarazoRecords; } set { colAprAntecedentePatologiaEmbarazoRecords = value; colAprAntecedentePatologiaEmbarazoRecords.ListChanged += new ListChangedEventHandler(colAprAntecedentePatologiaEmbarazoRecords_ListChanged); } } void colAprAntecedentePatologiaEmbarazoRecords_ListChanged(object sender, ListChangedEventArgs e) { if (e.ListChangedType == ListChangedType.ItemAdded) { // Set foreign key value colAprAntecedentePatologiaEmbarazoRecords[e.NewIndex].IdPatologiaEmbarazo = Id; } } private DalSic.AprActualPatologiaEmbarazoCollection colAprActualPatologiaEmbarazoRecords; public DalSic.AprActualPatologiaEmbarazoCollection AprActualPatologiaEmbarazoRecords { get { if(colAprActualPatologiaEmbarazoRecords == null) { colAprActualPatologiaEmbarazoRecords = new DalSic.AprActualPatologiaEmbarazoCollection().Where(AprActualPatologiaEmbarazo.Columns.IdPatologiaEmbarazo, Id).Load(); colAprActualPatologiaEmbarazoRecords.ListChanged += new ListChangedEventHandler(colAprActualPatologiaEmbarazoRecords_ListChanged); } return colAprActualPatologiaEmbarazoRecords; } set { colAprActualPatologiaEmbarazoRecords = value; colAprActualPatologiaEmbarazoRecords.ListChanged += new ListChangedEventHandler(colAprActualPatologiaEmbarazoRecords_ListChanged); } } void colAprActualPatologiaEmbarazoRecords_ListChanged(object sender, ListChangedEventArgs e) { if (e.ListChangedType == ListChangedType.ItemAdded) { // Set foreign key value colAprActualPatologiaEmbarazoRecords[e.NewIndex].IdPatologiaEmbarazo = Id; } } private DalSic.AprAbortoCollection colAprAbortoRecords; public DalSic.AprAbortoCollection AprAbortoRecords { get { if(colAprAbortoRecords == null) { colAprAbortoRecords = new DalSic.AprAbortoCollection().Where(AprAborto.Columns.DIAGCIE10, Id).Load(); colAprAbortoRecords.ListChanged += new ListChangedEventHandler(colAprAbortoRecords_ListChanged); } return colAprAbortoRecords; } set { colAprAbortoRecords = value; colAprAbortoRecords.ListChanged += new ListChangedEventHandler(colAprAbortoRecords_ListChanged); } } void colAprAbortoRecords_ListChanged(object sender, ListChangedEventArgs e) { if (e.ListChangedType == ListChangedType.ItemAdded) { // Set foreign key value colAprAbortoRecords[e.NewIndex].DIAGCIE10 = Id; } } private DalSic.AprProblemasMenorCollection colAprProblemasMenorRecords; public DalSic.AprProblemasMenorCollection AprProblemasMenorRecords { get { if(colAprProblemasMenorRecords == null) { colAprProblemasMenorRecords = new DalSic.AprProblemasMenorCollection().Where(AprProblemasMenor.Columns.CODCIE10, Id).Load(); colAprProblemasMenorRecords.ListChanged += new ListChangedEventHandler(colAprProblemasMenorRecords_ListChanged); } return colAprProblemasMenorRecords; } set { colAprProblemasMenorRecords = value; colAprProblemasMenorRecords.ListChanged += new ListChangedEventHandler(colAprProblemasMenorRecords_ListChanged); } } void colAprProblemasMenorRecords_ListChanged(object sender, ListChangedEventArgs e) { if (e.ListChangedType == ListChangedType.ItemAdded) { // Set foreign key value colAprProblemasMenorRecords[e.NewIndex].CODCIE10 = Id; } } private DalSic.AprEgresoPorAbortoCollection colAprEgresoPorAbortoRecords; public DalSic.AprEgresoPorAbortoCollection AprEgresoPorAbortoRecords { get { if(colAprEgresoPorAbortoRecords == null) { colAprEgresoPorAbortoRecords = new DalSic.AprEgresoPorAbortoCollection().Where(AprEgresoPorAborto.Columns.DIAGCIE10, Id).Load(); colAprEgresoPorAbortoRecords.ListChanged += new ListChangedEventHandler(colAprEgresoPorAbortoRecords_ListChanged); } return colAprEgresoPorAbortoRecords; } set { colAprEgresoPorAbortoRecords = value; colAprEgresoPorAbortoRecords.ListChanged += new ListChangedEventHandler(colAprEgresoPorAbortoRecords_ListChanged); } } void colAprEgresoPorAbortoRecords_ListChanged(object sender, ListChangedEventArgs e) { if (e.ListChangedType == ListChangedType.ItemAdded) { // Set foreign key value colAprEgresoPorAbortoRecords[e.NewIndex].DIAGCIE10 = Id; } } private DalSic.GuardiaRegistrosDiagnosticosCie10Collection colGuardiaRegistrosDiagnosticosCie10Records; public DalSic.GuardiaRegistrosDiagnosticosCie10Collection GuardiaRegistrosDiagnosticosCie10Records { get { if(colGuardiaRegistrosDiagnosticosCie10Records == null) { colGuardiaRegistrosDiagnosticosCie10Records = new DalSic.GuardiaRegistrosDiagnosticosCie10Collection().Where(GuardiaRegistrosDiagnosticosCie10.Columns.IdCie10, Id).Load(); colGuardiaRegistrosDiagnosticosCie10Records.ListChanged += new ListChangedEventHandler(colGuardiaRegistrosDiagnosticosCie10Records_ListChanged); } return colGuardiaRegistrosDiagnosticosCie10Records; } set { colGuardiaRegistrosDiagnosticosCie10Records = value; colGuardiaRegistrosDiagnosticosCie10Records.ListChanged += new ListChangedEventHandler(colGuardiaRegistrosDiagnosticosCie10Records_ListChanged); } } void colGuardiaRegistrosDiagnosticosCie10Records_ListChanged(object sender, ListChangedEventArgs e) { if (e.ListChangedType == ListChangedType.ItemAdded) { // Set foreign key value colGuardiaRegistrosDiagnosticosCie10Records[e.NewIndex].IdCie10 = Id; } } private DalSic.ConConsultaDiagnosticoCollection colConConsultaDiagnosticoRecords; public DalSic.ConConsultaDiagnosticoCollection ConConsultaDiagnosticoRecords { get { if(colConConsultaDiagnosticoRecords == null) { colConConsultaDiagnosticoRecords = new DalSic.ConConsultaDiagnosticoCollection().Where(ConConsultaDiagnostico.Columns.CODCIE10, Id).Load(); colConConsultaDiagnosticoRecords.ListChanged += new ListChangedEventHandler(colConConsultaDiagnosticoRecords_ListChanged); } return colConConsultaDiagnosticoRecords; } set { colConConsultaDiagnosticoRecords = value; colConConsultaDiagnosticoRecords.ListChanged += new ListChangedEventHandler(colConConsultaDiagnosticoRecords_ListChanged); } } void colConConsultaDiagnosticoRecords_ListChanged(object sender, ListChangedEventArgs e) { if (e.ListChangedType == ListChangedType.ItemAdded) { // Set foreign key value colConConsultaDiagnosticoRecords[e.NewIndex].CODCIE10 = Id; } } #endregion //no foreign key tables defined (0) //no ManyToMany tables defined (0) #region ObjectDataSource support /// <summary> /// Inserts a record, can be used with the Object Data Source /// </summary> public static void Insert(string varCapitulo,string varGRUPOCIE10,string varCausa,string varSubcausa,string varCodigo,string varNombre,string varSinonimo,string varDescripCap,double? varModif,string varCepsap,bool varC2) { SysCIE10 item = new SysCIE10(); item.Capitulo = varCapitulo; item.GRUPOCIE10 = varGRUPOCIE10; item.Causa = varCausa; item.Subcausa = varSubcausa; item.Codigo = varCodigo; item.Nombre = varNombre; item.Sinonimo = varSinonimo; item.DescripCap = varDescripCap; item.Modif = varModif; item.Cepsap = varCepsap; item.C2 = varC2; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } /// <summary> /// Updates a record, can be used with the Object Data Source /// </summary> public static void Update(int varId,string varCapitulo,string varGRUPOCIE10,string varCausa,string varSubcausa,string varCodigo,string varNombre,string varSinonimo,string varDescripCap,double? varModif,string varCepsap,bool varC2) { SysCIE10 item = new SysCIE10(); item.Id = varId; item.Capitulo = varCapitulo; item.GRUPOCIE10 = varGRUPOCIE10; item.Causa = varCausa; item.Subcausa = varSubcausa; item.Codigo = varCodigo; item.Nombre = varNombre; item.Sinonimo = varSinonimo; item.DescripCap = varDescripCap; item.Modif = varModif; item.Cepsap = varCepsap; item.C2 = varC2; item.IsNew = false; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } #endregion #region Typed Columns public static TableSchema.TableColumn IdColumn { get { return Schema.Columns[0]; } } public static TableSchema.TableColumn CapituloColumn { get { return Schema.Columns[1]; } } public static TableSchema.TableColumn GRUPOCIE10Column { get { return Schema.Columns[2]; } } public static TableSchema.TableColumn CausaColumn { get { return Schema.Columns[3]; } } public static TableSchema.TableColumn SubcausaColumn { get { return Schema.Columns[4]; } } public static TableSchema.TableColumn CodigoColumn { get { return Schema.Columns[5]; } } public static TableSchema.TableColumn NombreColumn { get { return Schema.Columns[6]; } } public static TableSchema.TableColumn SinonimoColumn { get { return Schema.Columns[7]; } } public static TableSchema.TableColumn DescripCapColumn { get { return Schema.Columns[8]; } } public static TableSchema.TableColumn ModifColumn { get { return Schema.Columns[9]; } } public static TableSchema.TableColumn CepsapColumn { get { return Schema.Columns[10]; } } public static TableSchema.TableColumn C2Column { get { return Schema.Columns[11]; } } #endregion #region Columns Struct public struct Columns { public static string Id = @"ID"; public static string Capitulo = @"CAPITULO"; public static string GRUPOCIE10 = @"GRUPOCIE10"; public static string Causa = @"CAUSA"; public static string Subcausa = @"SUBCAUSA"; public static string Codigo = @"CODIGO"; public static string Nombre = @"Nombre"; public static string Sinonimo = @"Sinonimo"; public static string DescripCap = @"DescripCap"; public static string Modif = @"Modif"; public static string Cepsap = @"CEPSAP"; public static string C2 = @"C2"; } #endregion #region Update PK Collections public void SetPKValues() { if (colSysAntecedenteEnfermedadRecords != null) { foreach (DalSic.SysAntecedenteEnfermedad item in colSysAntecedenteEnfermedadRecords) { if (item.CODCIE10 != Id) { item.CODCIE10 = Id; } } } if (colAprRelRecienNacidoEnfermedadRecords != null) { foreach (DalSic.AprRelRecienNacidoEnfermedad item in colAprRelRecienNacidoEnfermedadRecords) { if (item.CODCIE10 != Id) { item.CODCIE10 = Id; } } } if (colAprAntecedentePatologiaEmbarazoRecords != null) { foreach (DalSic.AprAntecedentePatologiaEmbarazo item in colAprAntecedentePatologiaEmbarazoRecords) { if (item.IdPatologiaEmbarazo != Id) { item.IdPatologiaEmbarazo = Id; } } } if (colAprActualPatologiaEmbarazoRecords != null) { foreach (DalSic.AprActualPatologiaEmbarazo item in colAprActualPatologiaEmbarazoRecords) { if (item.IdPatologiaEmbarazo != Id) { item.IdPatologiaEmbarazo = Id; } } } if (colAprAbortoRecords != null) { foreach (DalSic.AprAborto item in colAprAbortoRecords) { if (item.DIAGCIE10 != Id) { item.DIAGCIE10 = Id; } } } if (colAprProblemasMenorRecords != null) { foreach (DalSic.AprProblemasMenor item in colAprProblemasMenorRecords) { if (item.CODCIE10 != Id) { item.CODCIE10 = Id; } } } if (colAprEgresoPorAbortoRecords != null) { foreach (DalSic.AprEgresoPorAborto item in colAprEgresoPorAbortoRecords) { if (item.DIAGCIE10 != Id) { item.DIAGCIE10 = Id; } } } if (colGuardiaRegistrosDiagnosticosCie10Records != null) { foreach (DalSic.GuardiaRegistrosDiagnosticosCie10 item in colGuardiaRegistrosDiagnosticosCie10Records) { if (item.IdCie10 != Id) { item.IdCie10 = Id; } } } if (colConConsultaDiagnosticoRecords != null) { foreach (DalSic.ConConsultaDiagnostico item in colConConsultaDiagnosticoRecords) { if (item.CODCIE10 != Id) { item.CODCIE10 = Id; } } } } #endregion #region Deep Save public void DeepSave() { Save(); if (colSysAntecedenteEnfermedadRecords != null) { colSysAntecedenteEnfermedadRecords.SaveAll(); } if (colAprRelRecienNacidoEnfermedadRecords != null) { colAprRelRecienNacidoEnfermedadRecords.SaveAll(); } if (colAprAntecedentePatologiaEmbarazoRecords != null) { colAprAntecedentePatologiaEmbarazoRecords.SaveAll(); } if (colAprActualPatologiaEmbarazoRecords != null) { colAprActualPatologiaEmbarazoRecords.SaveAll(); } if (colAprAbortoRecords != null) { colAprAbortoRecords.SaveAll(); } if (colAprProblemasMenorRecords != null) { colAprProblemasMenorRecords.SaveAll(); } if (colAprEgresoPorAbortoRecords != null) { colAprEgresoPorAbortoRecords.SaveAll(); } if (colGuardiaRegistrosDiagnosticosCie10Records != null) { colGuardiaRegistrosDiagnosticosCie10Records.SaveAll(); } if (colConConsultaDiagnosticoRecords != null) { colConConsultaDiagnosticoRecords.SaveAll(); } } #endregion } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace Crossroads.Gateway.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { private const int DefaultCollectionSize = 3; 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); } } } }
// 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 Xunit; namespace ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Operators.Twoclass2operates.unary.overload001.overload001 { // <Title> Tests overload resolution for 2 class and 2 methods</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Base { public static short operator +(Base x) { return short.MinValue; } } public class Derived : Base { public static int operator +(Derived x) { return short.MaxValue; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = new Derived(); int s = +d; if (s == short.MaxValue) return 0; System.Console.WriteLine("Failed!"); return 1; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Operators.Twoclass2operates.unary.overload002.overload002 { // <Title> Tests overload resolution for 2 class and 2 methods</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Base { public static short operator +(Base x) { return short.MinValue; } } public class Derived : Base { public static short operator +(Derived x) { return short.MaxValue; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = new Derived(); short s = +d; if (s == short.MaxValue) return 0; return 1; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Operators.Twoclass2operates.unary.overload003.overload003 { // <Title> Tests overload resolution for 2 class and 2 methods</Title> // <Description> // Select the best method to call. // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Base { public int Field; public static Base operator ++(Base x) { x.Field = 3; return x; } } public class Derived : Base { public static Derived operator ++(Derived x) { x.Field = 4; return x; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = new Derived(); dynamic x = 3; dynamic dd = ++d; if (dd.Field == 4) return 0; return 1; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Operators.Twoclass2operates.unary.overload004.overload004 { // <Title> Tests overload resolution for 2 class and 2 methods</Title> // <Description> // Select the best method to call. // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Base { public int Field; public static Base operator --(Base x) { x.Field = 3; return x; } } public class Derived : Base { public static Derived operator --(Derived x) { x.Field = 4; return x; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = new Derived(); dynamic x = 3; dynamic dd = --d; if (dd.Field == 4) return 0; return 1; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Operators.Twoclass2operates.unary.overload005.overload005 { // <Title> Tests overload resolution for 2 class and 2 methods</Title> // <Description> // Select the best method to call. // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Base { public static int Status; public static bool operator true(Base x) { Base.Status = 1; return true; } public static bool operator false(Base x) { Base.Status = 2; return false; } } public class Derived : Base { public static bool operator true(Derived x) { return false; } public static bool operator false(Derived x) { return true; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = new Derived(); // Derived op 'true' invoked -> false if (d) return 1; return 0; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Operators.Twoclass2operates.unary.overload008.overload008 { // <Title> Tests overload resolution for 2 class and 2 methods</Title> // <Description> // Select the best method to call. // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Base { public static dynamic operator -(Base x) { return 1; } } public class Derived : Base { public static short operator -(Derived x) { return 2; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = new Derived(); dynamic x = 3; dynamic dd = -d; if (dd == 2) return 0; else return 1; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Operators.Twoclass2operates.unary.overload009.overload009 { // <Title> Tests overload resolution for 2 class and 2 methods</Title> // <Description> // Select the best method to call. // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Base { public static dynamic operator -(Base x) { return 1; } } public class Derived : Base { public static short operator -(Derived x) { return 2; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = new Base(); dynamic x = 3; dynamic dd = -d; if (dd == 1) return 0; else return 1; } } // </Code> }
using System; using System.Collections; using System.Globalization; using System.Reflection; using System.Drawing; using System.Configuration; using System.ComponentModel; using System.Text; using System.Web; using System.Web.UI.Design; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.HtmlControls; namespace DUEMETRI.UI.WebControls.HWMenu { /// <summary> /// HWMenu WebControl. /// </summary> /// [History("mario@hartmann.net", "2003/06/14", "use of named CSS styles added")] [ Designer("DUEMETRI.UI.WebControls.HWMenu.Design.MenuDesigner"), ParseChildren(true) ] public class Menu : WebControl { #region Private implementation MenuTreeNodes _childs; Style _controlItemStyle; Style _controlSubStyle; Style _controlHiStyle; Style _controlHiSubStyle; void Initialize() { _childs = new MenuTreeNodes(); _controlItemStyle = new Style(); _controlSubStyle = new Style(); _controlHiStyle = new Style(); _controlHiSubStyle = new Style(); CssClass =""; _controlItemStyle.CssClass=""; _controlSubStyle.CssClass =""; _controlHiStyle.CssClass =""; _controlHiSubStyle.CssClass =""; BackColor = Color.White; _controlItemStyle.BackColor = Color.White; _controlSubStyle.BackColor = Color.White; _controlHiStyle.BackColor = Color.Black; _controlHiSubStyle.BackColor = Color.Black; ForeColor = Color.Black; _controlItemStyle.ForeColor = Color.Black; _controlSubStyle.ForeColor = Color.Black; _controlHiStyle.ForeColor = Color.White; _controlHiSubStyle.ForeColor = Color.White; BorderColor = Color.Black; _controlItemStyle.BorderColor = Color.Black; _controlSubStyle.BorderColor = Color.Black; BorderWidth = new Unit(1); ControlStyle.Width = new Unit(100); ControlStyle.Height = new Unit(20); Font.Names = new string[2] {"Arial", "sans-serif"}; Font.Size = new FontUnit(9); Font.Bold = true; Font.Italic = false; _arrws = new System.Web.UI.WebControls.Image[3]; _arrws[0] = new System.Web.UI.WebControls.Image(); _arrws[0].ImageUrl = "tri.gif"; _arrws[0].Width = 5; _arrws[0].Height = 10; _arrws[1] = new System.Web.UI.WebControls.Image(); _arrws[1].ImageUrl = "tridown.gif"; _arrws[1].Width = 10; _arrws[1].Height = 5; _arrws[2] = new System.Web.UI.WebControls.Image(); _arrws[2].ImageUrl = "trileft.gif"; _arrws[2].Width = 5; _arrws[2].Height = 10; } #endregion /// <summary> /// Style of this element when the mouse is not over the element. /// </summary> [ Category("Style"), Description("Style of this element when the mouse is over the element."), DesignerSerializationVisibility(DesignerSerializationVisibility.Content), NotifyParentProperty(true), PersistenceMode(PersistenceMode.InnerProperty), ] public Style ControlItemStyle { get { if (_controlItemStyle == null) { _controlItemStyle = new Style(); if (IsTrackingViewState) ((IStateManager)_controlItemStyle).TrackViewState(); } return _controlItemStyle; } set { _controlItemStyle = value; } } /// <summary> /// Style of this element when the mouse is over the element. /// </summary> [ Category("Style"), Description("Style of this element when the mouse is over the element."), DesignerSerializationVisibility(DesignerSerializationVisibility.Content), NotifyParentProperty(true), PersistenceMode(PersistenceMode.InnerProperty) ] public Style ControlHiStyle { get { if (_controlHiStyle == null) { _controlHiStyle = new Style(); if (IsTrackingViewState) ((IStateManager)_controlHiStyle).TrackViewState(); } return _controlHiStyle; } set { _controlHiStyle = value; } } /// <summary> /// Style of tSubs element when the mouse is not over the element. /// </summary> [ Category("Style"), Description("Style of tSubs element when the mouse is over the element."), DesignerSerializationVisibility(DesignerSerializationVisibility.Content), NotifyParentProperty(true), PersistenceMode(PersistenceMode.InnerProperty), ] public Style ControlSubStyle { get { if (_controlSubStyle == null) { _controlSubStyle = new Style(); if (IsTrackingViewState) ((IStateManager)_controlSubStyle).TrackViewState(); } return _controlSubStyle; } set { _controlSubStyle = value; } } /// <summary> /// Style of the Subs element when the mouse is over the element. /// </summary> [ Category("Style"), Description("Style of the Subs element when the mouse is over the element."), DesignerSerializationVisibility(DesignerSerializationVisibility.Content), NotifyParentProperty(true), PersistenceMode(PersistenceMode.InnerProperty), ] public Style ControlHiSubStyle { get { if (_controlHiSubStyle == null) { _controlHiSubStyle = new Style(); if (IsTrackingViewState) ((IStateManager)_controlHiSubStyle).TrackViewState(); } return _controlHiSubStyle; } set { _controlHiSubStyle = value; } } /// <summary> /// Border between elements /// </summary> public bool BorderBtwnElmnts = true; /// <summary> /// Item text position 'left', 'center' or 'right' /// </summary> public HorizontalAlign MenuTextCentered = HorizontalAlign.Left; /// <summary> /// Menu horizontal position 'left', 'center' or 'right' /// </summary> public HorizontalAlign MenuCentered = HorizontalAlign.Left; /// <summary> /// Menu vertical position 'top', 'middle','bottom' or 'static' /// </summary> public VerticalAlign MenuVerticalCentered = VerticalAlign.Top; /// <summary> /// horizontal overlap child/ parent /// </summary> public double ChildOverlap = .1; /// <summary> /// vertical overlap child/ parent /// </summary> public double ChildVerticalOverlap = .1; /// <summary> /// Menu offset x coordinate /// </summary> public int StartTop = 0; /// <summary> /// Menu offset y coordinate /// </summary> public int StartLeft = 0; /// <summary> /// Multiple frames y correction /// </summary> public int VerCorrect = 0; /// <summary> /// Multiple frames x correction /// </summary> public int HorCorrect = 0; /// <summary> /// Left padding /// </summary> public int LeftPaddng = 2; /// <summary> /// Top padding /// </summary> public int TopPaddng = 2; private bool _horizontal = true; /// <summary> /// Horizontal or vertical menu /// </summary> /// [ Category("Appearance"), Description("Horizontal or vertical menu.") ] public bool Horizontal { get { return _horizontal; } set { _horizontal = value; } } /// <summary> /// Frames in cols or rows 1 or 0 /// </summary> public bool MenuFramesVertical = true; /// <summary> /// delay before menu folds in (milliseconds) /// </summary> public int DissapearDelay = 1000; /// <summary> /// Menu frame takes over background color subitem frame /// </summary> public bool TakeOverBgColor = true; /// <summary> /// Frame where first level appears /// </summary> public string FirstLineFrame = ""; /// <summary> /// Frame where sub levels appear /// </summary> public string SecLineFrame = ""; /// <summary> /// Frame where target documents appear /// </summary> public string DocTargetFrame = "_self"; /// <summary> /// span id for relative positioning /// </summary> public string TargetLoc = "MenuContainer"; /// <summary> /// Hide first level when loading new document 1 or 0 /// </summary> public bool HideTop = false; /// <summary> /// enables/ disables menu wrap 1 or 0 /// </summary> public bool MenuWrap = true; /// <summary> /// enables/ disables right to left unfold 1 or 0 /// </summary> public bool RightToLeft = false; /// <summary> /// Level 1 unfolds onclick/ onmouseover /// </summary> public bool UnfoldsOnClick = false; /// <summary> /// menu tree checking on or off 1 or 0 /// </summary> public bool WebMasterCheck = false; /// <summary> /// Uses arrow gifs when 1 /// </summary> public bool ShowArrow = true; /// <summary> /// Keep selected path highligthed /// </summary> public bool KeepHilite = true; private System.Web.UI.WebControls.Image[] _arrws; /// <summary> /// Arrow image /// </summary> [ Category("Appearance"), Description("Arrow image"), PersistenceMode(PersistenceMode.InnerProperty), DesignerSerializationVisibility(DesignerSerializationVisibility.Content) ] public System.Web.UI.WebControls.Image ArrowImage { get{return _arrws[0];} set{_arrws[0] = value;} } /// <summary> /// Arrow image down /// </summary> [ Category("Appearance"), Description("Arrow image down"), PersistenceMode(PersistenceMode.InnerProperty), DesignerSerializationVisibility(DesignerSerializationVisibility.Content) ] public System.Web.UI.WebControls.Image ArrowImageDown { get{return _arrws[1];} set{_arrws[1] = value;} } /// <summary> /// Arrow image left /// </summary> [ Category("Appearance"), Description("Arrow image left"), PersistenceMode(PersistenceMode.InnerProperty), DesignerSerializationVisibility(DesignerSerializationVisibility.Content) ] public System.Web.UI.WebControls.Image ArrowImageLeft { get{return _arrws[2];} set{_arrws[2] = value;} } /// <summary> /// Menu items collection. /// </summary> [ Category("Data"), Description("Menu items."), PersistenceMode(PersistenceMode.InnerProperty) ] public MenuTreeNodes Childs { get { return(_childs); } } /// <summary> /// Client script path. /// </summary> [ Category("Data"), Description("Client script path."), PersistenceMode(PersistenceMode.Attribute) ] public string ClientScriptPath { get { object _clientScriptPath = this.ViewState["ClientScriptPath"]; if (_clientScriptPath != null) return (String) _clientScriptPath; return GetClientScriptPath(); } set { string _clientScriptPath = value; if (_clientScriptPath.Length > 0 && !_clientScriptPath.EndsWith("/")) _clientScriptPath = _clientScriptPath + "/"; this.ViewState["ClientScriptPath"] = _clientScriptPath; } } /// <summary> /// Client images path. /// </summary> [ Category("Data"), Description("Client images path."), PersistenceMode(PersistenceMode.Attribute) ] public string ImagesPath { get { object _imagesPath = this.ViewState["ImagesPath"]; if (_imagesPath != null) return (String) _imagesPath; return GetClientScriptPath(); } set { string _imagesPath = value; if (_imagesPath.Length > 0 && !_imagesPath.EndsWith("/")) _imagesPath = _imagesPath + "/"; this.ViewState["ImagesPath"] = _imagesPath; } } /// <summary> /// Public constructor /// </summary> public Menu() { Initialize(); } /// <summary> /// Retrieves a string representing the current menu array /// </summary> /// <param name="prefix"></param> /// <returns>The current menu array</returns> protected string ToMenuArray(string prefix) { WebColorConverter wc = new WebColorConverter(); StringBuilder sb = new StringBuilder(); sb.Append("<script type = 'text/javascript'>\n"); sb.Append(" function Go(){return}\n"); sb.Append("</script>\n"); sb.Append("<script type = 'text/javascript'>\n"); sb.Append("var NoOffFirstLineMenus = "); sb.Append(Childs.Count); sb.Append(";\n"); //MH: sb.Append("var CssItemClassName = "); sb.Append("\""); sb.Append(ControlItemStyle.CssClass ); sb.Append("\""); sb.Append(";\n"); sb.Append("var CssHiClassName = "); sb.Append("\""); sb.Append(ControlHiStyle.CssClass ); sb.Append("\""); sb.Append(";\n"); sb.Append("var CssSubClassName = "); sb.Append("\""); sb.Append(ControlSubStyle.CssClass ); sb.Append("\""); sb.Append(";\n"); sb.Append("var CssHiSubClassName = "); sb.Append("\""); sb.Append(ControlHiSubStyle.CssClass ); sb.Append("\""); sb.Append(";\n"); //MH: sb.Append("var LowBgColor = "); sb.Append("\""); sb.Append(wc.ConvertToString(BackColor)); sb.Append("\""); sb.Append(";\n"); sb.Append("var LowSubBgColor = "); sb.Append("\""); sb.Append(wc.ConvertToString(ControlSubStyle.BackColor)); sb.Append("\""); sb.Append(";\n"); sb.Append("var HighBgColor = "); sb.Append("\""); sb.Append(wc.ConvertToString(ControlHiStyle.BackColor)); sb.Append("\""); sb.Append(";\n"); sb.Append("var HighSubBgColor = "); sb.Append("\""); sb.Append(wc.ConvertToString(ControlHiSubStyle.BackColor)); sb.Append("\""); sb.Append(";\n"); sb.Append("var FontLowColor = "); sb.Append("\""); sb.Append(wc.ConvertToString(ForeColor)); sb.Append("\""); sb.Append(";\n"); sb.Append("var FontSubLowColor = "); sb.Append("\""); sb.Append(wc.ConvertToString(ControlSubStyle.ForeColor)); sb.Append("\""); sb.Append(";\n"); sb.Append("var FontHighColor = "); sb.Append("\""); sb.Append(wc.ConvertToString(ControlHiStyle.ForeColor)); sb.Append("\""); sb.Append(";\n"); sb.Append("var FontSubHighColor = "); sb.Append("\""); sb.Append(wc.ConvertToString(ControlHiSubStyle.ForeColor)); sb.Append("\""); sb.Append(";\n"); sb.Append("var BorderColor = "); sb.Append("\""); sb.Append(wc.ConvertToString(BorderColor)); sb.Append("\""); sb.Append(";\n"); sb.Append("var BorderSubColor = "); sb.Append("\""); sb.Append(wc.ConvertToString(ControlSubStyle.BorderColor)); sb.Append("\""); sb.Append(";\n"); sb.Append("var BorderWidth = "); sb.Append(BorderWidth.Value); sb.Append(";\n"); sb.Append("var BorderBtwnElmnts = "); sb.Append(BorderBtwnElmnts ? 1 : 0); sb.Append(";\n"); sb.Append("var FontFamily = "); sb.Append("\""); sb.Append(Font.Name); sb.Append("\""); sb.Append(";\n"); sb.Append("var FontSize = "); sb.Append(Font.Size.Unit.Value); sb.Append(";\n"); sb.Append("var FontBold = "); sb.Append(Font.Bold ? 1 : 0); sb.Append(";\n"); sb.Append("var FontItalic = "); sb.Append(Font.Italic ? 1 : 0); sb.Append(";\n"); sb.Append("var MenuTextCentered = "); sb.Append("\""); sb.Append(MenuTextCentered.ToString().ToLower()); sb.Append("\""); sb.Append(";\n"); sb.Append("var MenuCentered = "); sb.Append("\""); sb.Append(MenuCentered.ToString().ToLower()); sb.Append("\""); sb.Append(";\n"); sb.Append("var MenuVerticalCentered = "); sb.Append("\""); sb.Append(MenuVerticalCentered.ToString().ToLower()); sb.Append("\""); sb.Append(";\n"); sb.Append("var ChildOverlap = "); sb.Append(ChildOverlap.ToString(new CultureInfo("en-US").NumberFormat)); sb.Append(";\n"); sb.Append("var ChildVerticalOverlap = "); sb.Append(ChildVerticalOverlap.ToString(new CultureInfo("en-US").NumberFormat)); sb.Append(";\n"); sb.Append("var LeftPaddng = "); sb.Append(LeftPaddng); sb.Append(";\n"); sb.Append("var TopPaddng = "); sb.Append(TopPaddng); sb.Append(";\n"); sb.Append("var StartTop = "); sb.Append(StartTop); sb.Append(";\n"); sb.Append("var StartLeft = "); sb.Append(StartLeft); sb.Append(";\n"); sb.Append("var VerCorrect = "); sb.Append(VerCorrect); sb.Append(";\n"); sb.Append("var HorCorrect = "); sb.Append(HorCorrect); sb.Append(";\n"); sb.Append("var FirstLineHorizontal = "); sb.Append(Horizontal ? 1 : 0); sb.Append(";\n"); sb.Append("var MenuFramesVertical = "); sb.Append(MenuFramesVertical ? 1 : 0); sb.Append(";\n"); sb.Append("var DissapearDelay = "); sb.Append(DissapearDelay); sb.Append(";\n"); sb.Append("var TakeOverBgColor = "); sb.Append(TakeOverBgColor ? 1 : 0); sb.Append(";\n"); sb.Append("var FirstLineFrame = "); sb.Append("\""); sb.Append(FirstLineFrame); sb.Append("\""); sb.Append(";\n"); sb.Append("var SecLineFrame = "); sb.Append("\""); sb.Append(SecLineFrame); sb.Append("\""); sb.Append(";\n"); sb.Append("var DocTargetFrame = "); sb.Append("\""); sb.Append(DocTargetFrame); sb.Append("\""); sb.Append(";\n"); sb.Append("var HideTop = "); sb.Append(HideTop ? 1 : 0); sb.Append(";\n"); sb.Append("var TargetLoc = "); sb.Append("\""); //sb.Append(TargetLoc); //sb.Append(this.Controls[0].ClientID); sb.Append("MenuPos"); //NS4 bug fix sb.Append("\""); sb.Append(";\n"); sb.Append("var MenuWrap = "); sb.Append(MenuWrap ? 1 : 0); sb.Append(";\n"); sb.Append("var RightToLeft = "); sb.Append(RightToLeft ? 1 : 0); sb.Append(";\n"); sb.Append("var UnfoldsOnClick = "); sb.Append(UnfoldsOnClick ? 1 : 0); sb.Append(";\n"); sb.Append("var WebMasterCheck = "); sb.Append(WebMasterCheck ? 1 : 0); sb.Append(";\n"); sb.Append("var ShowArrow = "); sb.Append(ShowArrow ? 1 : 0); sb.Append(";\n"); sb.Append("var KeepHilite = "); sb.Append(KeepHilite ? 1 : 0); sb.Append(";\n"); sb.Append("var Arrws = "); sb.Append("["); for(int i = 0; i <= _arrws.GetUpperBound(0); i++) { sb.Append("\""); sb.Append(ImagesPath + _arrws[i].ImageUrl); sb.Append("\", "); sb.Append(_arrws[i].Width.Value); sb.Append(", "); sb.Append(_arrws[i].Height.Value); if(i != _arrws.GetUpperBound(0)) sb.Append(", "); } sb.Append("]"); sb.Append(";\n"); sb.Append("function BeforeStart(){;}\n"); sb.Append("function AfterBuild(){;}\n"); sb.Append("function BeforeFirstOpen(){;}\n"); sb.Append("function AfterCloseAll(){;}\n"); sb.Append(Childs.ToMenuArray(prefix)); sb.Append("</script>\n"); sb.Append("<script type = 'text/javascript' src = '" + ClientScriptPath + "menu_com.js'></script>\n"); sb.Append("<noscript>Your browser does not support script</noscript>\n"); return sb.ToString(); } /// <summary> /// Render the control /// </summary> /// <param name="output"></param> override protected void Render(HtmlTextWriter output) { if (!HasControls()) //HACK CreateChildControls(); //If on pane CreateChildControls is not fired if(Childs.Count > 0 && HasControls()) { //Added by groskrg@versifit.com: 10/13/2004 to resolve issue with the Menu consuming more width than it should in Netscape browser. this.Page.ClientScript.RegisterStartupScript(this.GetType(), "HWMenuScript", ToMenuArray("Menu")); //line made obsolete by the change above //output.Write(ToMenuArray("Menu")); this.Controls[0].RenderControl(output); } } /// <summary> /// CreateChildControl /// </summary> protected override void CreateChildControls() { LiteralControl MenuContainer; Unit myWidth = new Unit(); Unit myHeight = new Unit(); if(Childs.Count > 0) { if(this.Horizontal) { myHeight = Height; myWidth = Childs.Width; } else { myHeight = Childs.Height; myWidth = Width; } } myHeight = new Unit(myHeight.Value + StartTop); //correction myWidth = new Unit(myWidth.Value + StartLeft); //correction //MenuContainer.MergeStyle(this.ControlStyle); MenuContainer = new LiteralControl(@"<div id='MenuPos' style='padding:0;margin:0;border-width:0;position:relative;width:" + myWidth.Value + "; height:" + myHeight.Value + ";'><img style='padding:0;margin:0;border-width:0' src='" + ClientScriptPath + "1x1.gif' border='0' width='" + myWidth.Value + "' height='" + myHeight.Value + "'></div>"); //ns4 bug fix MenuContainer.ID = TargetLoc; this.Controls.Add(MenuContainer); } /// <summary> /// GetClientScriptPath() method -- works out the /// location of the shared scripts and images. /// </summary> /// <returns></returns> protected virtual string GetClientScriptPath() { string location = null; IDictionary configData = null; if(Context != null) configData = (IDictionary)Context.GetConfig("system.web/webControls"); if (configData != null) location = (string)configData["clientScriptsLocation"]; if (location == null) return String.Empty; else if (location.IndexOf("{0}") >= 0) { AssemblyName assemblyName = GetType().Assembly.GetName(); string assembly = assemblyName.Name.Replace('.', '_'); string version = assemblyName.Version.ToString().Replace('.', '_'); location = String.Format(location, assembly, version); } if (location == null) return String.Empty; else return location; } /// <summary> /// Restores the view-state information from a previous /// user control request that was saved by the /// <seealso cref="M:SaveViewState"/> method. /// </summary> /// <param name="savedState"></param> protected override void LoadViewState(object savedState) { // Customize state management to handle saving state of contained objects. if (savedState != null) { object[] myState = (object[])savedState; if (myState[0] != null) base.LoadViewState(myState[0]); if (myState[1] != null) ((IStateManager)_controlItemStyle).LoadViewState(myState[1]); if (myState[2] != null) ((IStateManager)_controlHiStyle).LoadViewState(myState[2]); if (myState[3] != null) ((IStateManager)_controlSubStyle).LoadViewState(myState[3]); if (myState[4] != null) ((IStateManager)_controlHiSubStyle).LoadViewState(myState[4]); } } /// <summary> /// Saves any user control view-state changes that have /// occurred since the last page postback. /// </summary> /// <returns></returns> protected override object SaveViewState() { // Customized state management to handle saving state of contained objects such as styles. object baseState = base.SaveViewState(); object controlStyle = (ControlStyle != null) ? ((IStateManager)_controlItemStyle).SaveViewState() : null; object controlHiStyle = (ControlHiStyle != null) ? ((IStateManager)_controlHiStyle).SaveViewState() : null; object controlSubStyle = (ControlSubStyle != null) ? ((IStateManager)_controlSubStyle).SaveViewState() : null; object controlHiSubStyle = (ControlHiSubStyle != null) ? ((IStateManager)_controlHiSubStyle).SaveViewState() : null; object[] myState = new object[5]; myState[0] = baseState; myState[1] = controlStyle; myState[2] = controlHiStyle; myState[3] = controlSubStyle; myState[4] = controlHiSubStyle; return myState; } /// <summary> /// Causes tracking of view-state changes to the server control /// so they can be stored in the server control's StateBag object. /// This object is accessible through the <seealso cref="P:Control.ViewState"/> property. /// </summary> protected override void TrackViewState() { // Customized state management to handle saving state of contained objects such as styles. base.TrackViewState(); if (_controlItemStyle != null) ((IStateManager)_controlItemStyle).TrackViewState(); if (_controlHiStyle != null) ((IStateManager)_controlHiStyle).TrackViewState(); if (_controlSubStyle != null) ((IStateManager)_controlSubStyle).TrackViewState(); if (_controlHiSubStyle != null) ((IStateManager)_controlHiSubStyle).TrackViewState(); } } }
// // (C) Copyright 2003-2011 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. // using System; using System.IO; using System.Xml; using System.Xml.Linq; using Autodesk.Revit.DB; using Autodesk.Revit.DB.PointClouds; using Autodesk.Revit.UI; namespace Revit.SDK.Samples.CS.PointCloudEngine { /// <summary> /// ExternalApplication used to register the point cloud engines managed by this sample. /// </summary> [Autodesk.Revit.Attributes.Regeneration(Autodesk.Revit.Attributes.RegenerationOption.Manual)] public class PointCloudTestApplication: IExternalApplication { #region IExternalApplication Members /// <summary> /// The implementation of IExternalApplication.OnStartup() /// </summary> /// <param name="application">The Revit application.</param> /// <returns>Result.Succeeded</returns> public Result OnStartup(UIControlledApplication application) { try { // Register point cloud engines for the sample. // Predefined engine (non-randomized) IPointCloudEngine engine = new BasicPointCloudEngine(PointCloudEngineType.Predefined); PointCloudEngineRegistry.RegisterPointCloudEngine("apipc", engine, false); // Predefined engine with randomized points at the cell borders engine = new BasicPointCloudEngine(PointCloudEngineType.RandomizedPoints); PointCloudEngineRegistry.RegisterPointCloudEngine("apipcr", engine, false); // XML-based point cloud definition engine = new BasicPointCloudEngine(PointCloudEngineType.FileBased); PointCloudEngineRegistry.RegisterPointCloudEngine("xml", engine, true); // Create user interface for accessing predefined point clouds RibbonPanel panel = application.CreateRibbonPanel("Point cloud testing"); System.Reflection.Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly(); panel.AddItem(new PushButtonData("AddPredefinedInstance", "Add predefined instance", assembly.Location, "Revit.SDK.Samples.CS.PointCloudEngine.AddPredefinedInstanceCommand")); panel.AddSeparator(); panel.AddItem(new PushButtonData("AddRandomizedInstance", "Add randomized instance", assembly.Location, "Revit.SDK.Samples.CS.PointCloudEngine.AddRandomizedInstanceCommand")); panel.AddSeparator(); panel.AddItem(new PushButtonData("AddTransformedInstance", "Add randomized instance\nat transform", assembly.Location, "Revit.SDK.Samples.CS.PointCloudEngine.AddTransformedInstanceCommand")); panel.AddSeparator(); panel.AddItem(new PushButtonData("SerializePointCloud", "Serialize point cloud (utility)", assembly.Location, "Revit.SDK.Samples.CS.PointCloudEngine.SerializePredefinedPointCloud")); } catch (Exception e) { TaskDialog.Show("Exception from OnStartup", e.ToString()); } return Result.Succeeded; } /// <summary> /// The implementation of IExternalApplication.OnShutdown() /// </summary> /// <param name="application">The Revit application.</param> /// <returns>Result.Succeeded.</returns> public Result OnShutdown(UIControlledApplication application) { return Result.Succeeded; } #endregion } /// <summary> /// ExternalCommand to add a predefined point cloud. /// </summary> [Autodesk.Revit.Attributes.Transaction(Autodesk.Revit.Attributes.TransactionMode.Manual)] public class AddPredefinedInstanceCommand : AddInstanceCommandBase, IExternalCommand { #region IExternalCommand Members /// <summary> /// The implementation for IExternalCommand.Execute() /// </summary> /// <param name="commandData">The Revit command data.</param> /// <param name="message">The error message (ignored).</param> /// <param name="elements">The elements to display in the failure dialog (ignored).</param> /// <returns>Result.Succeeded</returns> public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { Document doc = commandData.View.Document; AddInstance(doc, "apipc", "", Transform.Identity); return Result.Succeeded; } #endregion } /// <summary> /// ExternalCommand to a predefined point cloud with randomized points. /// </summary> [Autodesk.Revit.Attributes.Transaction(Autodesk.Revit.Attributes.TransactionMode.Manual)] public class AddRandomizedInstanceCommand : AddInstanceCommandBase, IExternalCommand { #region IExternalCommand Members /// <summary> /// The implementation for IExternalCommand.Execute() /// </summary> /// <param name="commandData">The Revit command data.</param> /// <param name="message">The error message (ignored).</param> /// <param name="elements">The elements to display in the failure dialog (ignored).</param> /// <returns>Result.Succeeded</returns> public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { Document doc = commandData.View.Document; AddInstance(doc, "apipcr", "", Transform.Identity); return Result.Succeeded; } #endregion } /// <summary> /// ExternalCommand to add a predefined point cloud at a non-default transform. /// </summary> [Autodesk.Revit.Attributes.Transaction(Autodesk.Revit.Attributes.TransactionMode.Manual)] public class AddTransformedInstanceCommand : AddInstanceCommandBase, IExternalCommand { #region IExternalCommand Members /// <summary> /// The implementation for IExternalCommand.Execute() /// </summary> /// <param name="commandData">The Revit command data.</param> /// <param name="message">The error message (ignored).</param> /// <param name="elements">The elements to display in the failure dialog (ignored).</param> /// <returns>Result.Succeeded</returns> public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { Document doc = commandData.View.Document; Transform trf = Transform.get_Rotation(new XYZ(10, 5, 0), XYZ.BasisZ, Math.PI / 6.0); AddInstance(doc, "apipcr", "", trf); return Result.Succeeded; } #endregion } /// <summary> /// Base class for ExternalCommands used to add point cloud instances programmatically. /// </summary> public class AddInstanceCommandBase { /// <summary> /// Adds a point cloud instance programmatically. /// </summary> /// <param name="doc">The document.</param> /// <param name="engineType">The engine identifier string.</param> /// <param name="identifier">The identifier for the particular point cloud.</param> /// <param name="trf">The transform to apply to the new point cloud instance.</param> public void AddInstance(Document doc, String engineType, String identifier, Transform trf) { Transaction t = new Transaction(doc, "Create PC instance"); t.Start(); PointCloudType type = PointCloudType.Create(doc, engineType, identifier); PointCloudInstance.Create(doc, type.Id, trf); t.Commit(); } } /// <summary> /// Utility ExternalCommand to take a predefined point cloud and write the corresponding XML for it to disk. /// </summary> [Autodesk.Revit.Attributes.Transaction(Autodesk.Revit.Attributes.TransactionMode.ReadOnly)] public class SerializePredefinedPointCloud : AddInstanceCommandBase, IExternalCommand { #region IExternalCommand Members /// <summary> /// The implementation for IExternalCommand.Execute() /// </summary> /// <param name="commandData">The Revit command data.</param> /// <param name="message">The error message (ignored).</param> /// <param name="elements">The elements to display in the failure dialog (ignored).</param> /// <returns>Result.Succeeded</returns> public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { PredefinedPointCloud cloud = new PredefinedPointCloud("dummy"); XDocument doc = new XDocument(); XElement root = new XElement("PointCloud"); cloud.SerializeObjectData(root); doc.Add(root); TextWriter writer = new StreamWriter(@"c:\serializedPC.xml"); doc.WriteTo(new XmlTextWriter(writer)); writer.Close(); return Result.Succeeded; } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Security.Cryptography; using Microsoft.Win32.SafeHandles; namespace Internal.Cryptography.Pal { internal static class PkcsFormatReader { internal static bool IsPkcs7(byte[] rawData) { using (SafePkcs7Handle pkcs7 = Interop.Crypto.DecodePkcs7(rawData, rawData.Length)) { if (pkcs7.IsInvalid) { Interop.Crypto.ErrClearError(); } else { return true; } } using (SafeBioHandle bio = Interop.Crypto.CreateMemoryBio()) { Interop.Crypto.CheckValidOpenSslHandle(bio); if (Interop.Crypto.BioWrite(bio, rawData, rawData.Length) != rawData.Length) { Interop.Crypto.ErrClearError(); } using (SafePkcs7Handle pkcs7 = Interop.Crypto.PemReadBioPkcs7(bio)) { if (pkcs7.IsInvalid) { Interop.Crypto.ErrClearError(); return false; } return true; } } } internal static bool IsPkcs7Der(SafeBioHandle fileBio) { using (SafePkcs7Handle pkcs7 = Interop.Crypto.D2IPkcs7Bio(fileBio)) { if (pkcs7.IsInvalid) { Interop.Crypto.ErrClearError(); return false; } return true; } } internal static bool IsPkcs7Pem(SafeBioHandle fileBio) { using (SafePkcs7Handle pkcs7 = Interop.Crypto.PemReadBioPkcs7(fileBio)) { if (pkcs7.IsInvalid) { Interop.Crypto.ErrClearError(); return false; } return true; } } internal static bool TryReadPkcs7Der(byte[] rawData, out ICertificatePal certPal) { List<ICertificatePal> ignored; return TryReadPkcs7Der(rawData, true, out certPal, out ignored); } internal static bool TryReadPkcs7Der(SafeBioHandle bio, out ICertificatePal certPal) { List<ICertificatePal> ignored; return TryReadPkcs7Der(bio, true, out certPal, out ignored); } internal static bool TryReadPkcs7Der(byte[] rawData, out List<ICertificatePal> certPals) { ICertificatePal ignored; return TryReadPkcs7Der(rawData, false, out ignored, out certPals); } internal static bool TryReadPkcs7Der(SafeBioHandle bio, out List<ICertificatePal> certPals) { ICertificatePal ignored; return TryReadPkcs7Der(bio, false, out ignored, out certPals); } private static bool TryReadPkcs7Der( byte[] rawData, bool single, out ICertificatePal certPal, out List<ICertificatePal> certPals) { using (SafePkcs7Handle pkcs7 = Interop.Crypto.DecodePkcs7(rawData, rawData.Length)) { if (pkcs7.IsInvalid) { certPal = null; certPals = null; Interop.Crypto.ErrClearError(); return false; } return TryReadPkcs7(pkcs7, single, out certPal, out certPals); } } private static bool TryReadPkcs7Der( SafeBioHandle bio, bool single, out ICertificatePal certPal, out List<ICertificatePal> certPals) { using (SafePkcs7Handle pkcs7 = Interop.Crypto.D2IPkcs7Bio(bio)) { if (pkcs7.IsInvalid) { certPal = null; certPals = null; Interop.Crypto.ErrClearError(); return false; } return TryReadPkcs7(pkcs7, single, out certPal, out certPals); } } internal static bool TryReadPkcs7Pem(byte[] rawData, out ICertificatePal certPal) { List<ICertificatePal> ignored; return TryReadPkcs7Pem(rawData, true, out certPal, out ignored); } internal static bool TryReadPkcs7Pem(SafeBioHandle bio, out ICertificatePal certPal) { List<ICertificatePal> ignored; return TryReadPkcs7Pem(bio, true, out certPal, out ignored); } internal static bool TryReadPkcs7Pem(byte[] rawData, out List<ICertificatePal> certPals) { ICertificatePal ignored; return TryReadPkcs7Pem(rawData, false, out ignored, out certPals); } internal static bool TryReadPkcs7Pem(SafeBioHandle bio, out List<ICertificatePal> certPals) { ICertificatePal ignored; return TryReadPkcs7Pem(bio, false, out ignored, out certPals); } private static bool TryReadPkcs7Pem( byte[] rawData, bool single, out ICertificatePal certPal, out List<ICertificatePal> certPals) { using (SafeBioHandle bio = Interop.Crypto.CreateMemoryBio()) { Interop.Crypto.CheckValidOpenSslHandle(bio); if (Interop.Crypto.BioWrite(bio, rawData, rawData.Length) != rawData.Length) { Interop.Crypto.ErrClearError(); } return TryReadPkcs7Pem(bio, single, out certPal, out certPals); } } private static bool TryReadPkcs7Pem( SafeBioHandle bio, bool single, out ICertificatePal certPal, out List<ICertificatePal> certPals) { using (SafePkcs7Handle pkcs7 = Interop.Crypto.PemReadBioPkcs7(bio)) { if (pkcs7.IsInvalid) { certPal = null; certPals = null; Interop.Crypto.ErrClearError(); return false; } return TryReadPkcs7(pkcs7, single, out certPal, out certPals); } } private static bool TryReadPkcs7( SafePkcs7Handle pkcs7, bool single, out ICertificatePal certPal, out List<ICertificatePal> certPals) { List<ICertificatePal> readPals = single ? null : new List<ICertificatePal>(); using (SafeSharedX509StackHandle certs = Interop.Crypto.GetPkcs7Certificates(pkcs7)) { int count = Interop.Crypto.GetX509StackFieldCount(certs); if (single) { // In single mode for a PKCS#7 signed or signed-and-enveloped file we're supposed to return // the certificate which signed the PKCS#7 file. // // X509Certificate2Collection::Export(X509ContentType.Pkcs7) claims to be a signed PKCS#7, // but doesn't emit a signature block. So this is hard to test. // // TODO(2910): Figure out how to extract the signing certificate, when it's present. throw new CryptographicException(SR.Cryptography_X509_PKCS7_NoSigner); } for (int i = 0; i < count; i++) { // Use FromHandle to duplicate the handle since it would otherwise be freed when the PKCS7 // is Disposed. IntPtr certHandle = Interop.Crypto.GetX509StackField(certs, i); ICertificatePal pal = CertificatePal.FromHandle(certHandle); readPals.Add(pal); } } certPal = null; certPals = readPals; return true; } internal static bool TryReadPkcs12(byte[] rawData, SafePasswordHandle password, out ICertificatePal certPal, out Exception openSslException) { List<ICertificatePal> ignored; return TryReadPkcs12(rawData, password, true, out certPal, out ignored, out openSslException); } internal static bool TryReadPkcs12(SafeBioHandle bio, SafePasswordHandle password, out ICertificatePal certPal, out Exception openSslException) { List<ICertificatePal> ignored; return TryReadPkcs12(bio, password, true, out certPal, out ignored, out openSslException); } internal static bool TryReadPkcs12(byte[] rawData, SafePasswordHandle password, out List<ICertificatePal> certPals, out Exception openSslException) { ICertificatePal ignored; return TryReadPkcs12(rawData, password, false, out ignored, out certPals, out openSslException); } internal static bool TryReadPkcs12(SafeBioHandle bio, SafePasswordHandle password, out List<ICertificatePal> certPals, out Exception openSslException) { ICertificatePal ignored; return TryReadPkcs12(bio, password, false, out ignored, out certPals, out openSslException); } private static bool TryReadPkcs12( byte[] rawData, SafePasswordHandle password, bool single, out ICertificatePal readPal, out List<ICertificatePal> readCerts, out Exception openSslException) { // DER-PKCS12 OpenSslPkcs12Reader pfx; if (!OpenSslPkcs12Reader.TryRead(rawData, out pfx, out openSslException)) { readPal = null; readCerts = null; return false; } using (pfx) { return TryReadPkcs12(pfx, password, single, out readPal, out readCerts); } } private static bool TryReadPkcs12( SafeBioHandle bio, SafePasswordHandle password, bool single, out ICertificatePal readPal, out List<ICertificatePal> readCerts, out Exception openSslException) { // DER-PKCS12 OpenSslPkcs12Reader pfx; if (!OpenSslPkcs12Reader.TryRead(bio, out pfx, out openSslException)) { readPal = null; readCerts = null; return false; } using (pfx) { return TryReadPkcs12(pfx, password, single, out readPal, out readCerts); } } private static bool TryReadPkcs12( OpenSslPkcs12Reader pfx, SafePasswordHandle password, bool single, out ICertificatePal readPal, out List<ICertificatePal> readCerts) { pfx.Decrypt(password); ICertificatePal first = null; List<ICertificatePal> certs = null; if (!single) { certs = new List<ICertificatePal>(); } foreach (OpenSslX509CertificateReader certPal in pfx.ReadCertificates()) { if (single) { // When requesting an X509Certificate2 from a PFX only the first entry is // returned. Other entries should be disposed. if (first == null) { first = certPal; } else if (certPal.HasPrivateKey && !first.HasPrivateKey) { first.Dispose(); first = certPal; } else { certPal.Dispose(); } } else { certs.Add(certPal); } } readPal = first; readCerts = certs; return true; } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Simplification; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.IntroduceVariable { internal partial class CSharpIntroduceVariableService { protected override Task<Document> IntroduceLocalAsync( SemanticDocument document, ExpressionSyntax expression, bool allOccurrences, bool isConstant, CancellationToken cancellationToken) { var options = document.Project.Solution.Workspace.Options; var newLocalNameToken = (SyntaxToken)GenerateUniqueLocalName(document, expression, isConstant, cancellationToken); var newLocalName = SyntaxFactory.IdentifierName(newLocalNameToken); var modifiers = isConstant ? SyntaxFactory.TokenList(SyntaxFactory.Token(SyntaxKind.ConstKeyword)) : default(SyntaxTokenList); var declarationStatement = SyntaxFactory.LocalDeclarationStatement( modifiers, SyntaxFactory.VariableDeclaration( this.GetTypeSyntax(document, expression, isConstant, options, cancellationToken), SyntaxFactory.SingletonSeparatedList(SyntaxFactory.VariableDeclarator( newLocalNameToken.WithAdditionalAnnotations(RenameAnnotation.Create()), null, SyntaxFactory.EqualsValueClause(expression.WithoutTrailingTrivia().WithoutLeadingTrivia()))))); var anonymousMethodParameters = GetAnonymousMethodParameters(document, expression, cancellationToken); var lambdas = anonymousMethodParameters.SelectMany(p => p.ContainingSymbol.DeclaringSyntaxReferences.Select(r => r.GetSyntax(cancellationToken)).AsEnumerable()) .Where(n => n is ParenthesizedLambdaExpressionSyntax || n is SimpleLambdaExpressionSyntax) .ToSet(); var parentLambda = GetParentLambda(expression, lambdas); if (parentLambda != null) { return Task.FromResult(IntroduceLocalDeclarationIntoLambda( document, expression, newLocalName, declarationStatement, parentLambda, allOccurrences, cancellationToken)); } else if (IsInExpressionBodiedMember(expression)) { return Task.FromResult(RewriteExpressionBodiedMemberAndIntroduceLocalDeclaration( document, expression, newLocalName, declarationStatement, allOccurrences, cancellationToken)); } else { return IntroduceLocalDeclarationIntoBlockAsync( document, expression, newLocalName, declarationStatement, allOccurrences, cancellationToken); } } private Document IntroduceLocalDeclarationIntoLambda( SemanticDocument document, ExpressionSyntax expression, IdentifierNameSyntax newLocalName, LocalDeclarationStatementSyntax declarationStatement, SyntaxNode oldLambda, bool allOccurrences, CancellationToken cancellationToken) { var oldBody = oldLambda is ParenthesizedLambdaExpressionSyntax ? (ExpressionSyntax)((ParenthesizedLambdaExpressionSyntax)oldLambda).Body : (ExpressionSyntax)((SimpleLambdaExpressionSyntax)oldLambda).Body; var rewrittenBody = Rewrite( document, expression, newLocalName, document, oldBody, allOccurrences, cancellationToken); var delegateType = document.SemanticModel.GetTypeInfo(oldLambda, cancellationToken).ConvertedType as INamedTypeSymbol; var newBody = delegateType != null && delegateType.DelegateInvokeMethod != null && delegateType.DelegateInvokeMethod.ReturnsVoid ? SyntaxFactory.Block(declarationStatement) : SyntaxFactory.Block(declarationStatement, SyntaxFactory.ReturnStatement(rewrittenBody)); newBody = newBody.WithAdditionalAnnotations(Formatter.Annotation); var newLambda = oldLambda is ParenthesizedLambdaExpressionSyntax ? ((ParenthesizedLambdaExpressionSyntax)oldLambda).WithBody(newBody) : (SyntaxNode)((SimpleLambdaExpressionSyntax)oldLambda).WithBody(newBody); var newRoot = document.Root.ReplaceNode(oldLambda, newLambda); return document.Document.WithSyntaxRoot(newRoot); } private SyntaxNode GetParentLambda(ExpressionSyntax expression, ISet<SyntaxNode> lambdas) { var current = expression; while (current != null) { if (lambdas.Contains(current.Parent)) { return current.Parent; } current = current.Parent as ExpressionSyntax; } return null; } private TypeSyntax GetTypeSyntax(SemanticDocument document, ExpressionSyntax expression, bool isConstant, OptionSet options, CancellationToken cancellationToken) { var typeSymbol = GetTypeSymbol(document, expression, cancellationToken); if (typeSymbol.ContainsAnonymousType()) { return SyntaxFactory.IdentifierName("var"); } if (!isConstant && options.GetOption(CSharpCodeStyleOptions.UseVarWhenDeclaringLocals) && CanUseVar(typeSymbol)) { return SyntaxFactory.IdentifierName("var"); } return typeSymbol.GenerateTypeSyntax(); } private bool CanUseVar(ITypeSymbol typeSymbol) { return typeSymbol.TypeKind != TypeKind.Delegate && !typeSymbol.IsErrorType(); } private static async Task<Tuple<SemanticDocument, ISet<ExpressionSyntax>>> ComplexifyParentingStatements( SemanticDocument semanticDocument, ISet<ExpressionSyntax> matches, CancellationToken cancellationToken) { // First, track the matches so that we can get back to them later. var newRoot = semanticDocument.Root.TrackNodes(matches); var newDocument = semanticDocument.Document.WithSyntaxRoot(newRoot); var newSemanticDocument = await SemanticDocument.CreateAsync(newDocument, cancellationToken).ConfigureAwait(false); var newMatches = newSemanticDocument.Root.GetCurrentNodes(matches.AsEnumerable()).ToSet(); // Next, expand the topmost parenting expression of each match, being careful // not to expand the matches themselves. var topMostExpressions = newMatches .Select(m => m.AncestorsAndSelf().OfType<ExpressionSyntax>().Last()) .Distinct(); newRoot = await newSemanticDocument.Root .ReplaceNodesAsync( topMostExpressions, computeReplacementAsync: async (oldNode, newNode, ct) => { return await Simplifier .ExpandAsync( oldNode, newSemanticDocument.Document, expandInsideNode: node => { var expression = node as ExpressionSyntax; return expression == null || !newMatches.Contains(expression); }, cancellationToken: ct) .ConfigureAwait(false); }, cancellationToken: cancellationToken) .ConfigureAwait(false); newDocument = newSemanticDocument.Document.WithSyntaxRoot(newRoot); newSemanticDocument = await SemanticDocument.CreateAsync(newDocument, cancellationToken).ConfigureAwait(false); newMatches = newSemanticDocument.Root.GetCurrentNodes(matches.AsEnumerable()).ToSet(); return Tuple.Create(newSemanticDocument, newMatches); } private Document RewriteExpressionBodiedMemberAndIntroduceLocalDeclaration( SemanticDocument document, ExpressionSyntax expression, NameSyntax newLocalName, LocalDeclarationStatementSyntax declarationStatement, bool allOccurrences, CancellationToken cancellationToken) { var oldBody = expression.GetAncestorOrThis<ArrowExpressionClauseSyntax>(); var oldParentingNode = oldBody.Parent; var leadingTrivia = oldBody.GetLeadingTrivia() .AddRange(oldBody.ArrowToken.TrailingTrivia); var newStatement = Rewrite(document, expression, newLocalName, document, oldBody.Expression, allOccurrences, cancellationToken); var newBody = SyntaxFactory.Block(declarationStatement, SyntaxFactory.ReturnStatement(newStatement)) .WithLeadingTrivia(leadingTrivia) .WithTrailingTrivia(oldBody.GetTrailingTrivia()) .WithAdditionalAnnotations(Formatter.Annotation); SyntaxNode newParentingNode = null; if (oldParentingNode is BasePropertyDeclarationSyntax) { var getAccessor = SyntaxFactory.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration, newBody); var accessorList = SyntaxFactory.AccessorList(SyntaxFactory.List(new[] { getAccessor })); newParentingNode = ((BasePropertyDeclarationSyntax)oldParentingNode).RemoveNode(oldBody, SyntaxRemoveOptions.KeepNoTrivia); if (newParentingNode.IsKind(SyntaxKind.PropertyDeclaration)) { var propertyDeclaration = ((PropertyDeclarationSyntax)newParentingNode); newParentingNode = propertyDeclaration .WithAccessorList(accessorList) .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.None)) .WithTrailingTrivia(propertyDeclaration.SemicolonToken.TrailingTrivia); } else if (newParentingNode.IsKind(SyntaxKind.IndexerDeclaration)) { var indexerDeclaration = ((IndexerDeclarationSyntax)newParentingNode); newParentingNode = indexerDeclaration .WithAccessorList(accessorList) .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.None)) .WithTrailingTrivia(indexerDeclaration.SemicolonToken.TrailingTrivia); } } else if (oldParentingNode is BaseMethodDeclarationSyntax) { newParentingNode = ((BaseMethodDeclarationSyntax)oldParentingNode) .RemoveNode(oldBody, SyntaxRemoveOptions.KeepNoTrivia) .WithBody(newBody); if (newParentingNode.IsKind(SyntaxKind.MethodDeclaration)) { var methodDeclaration = ((MethodDeclarationSyntax)newParentingNode); newParentingNode = methodDeclaration .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.None)) .WithTrailingTrivia(methodDeclaration.SemicolonToken.TrailingTrivia); } else if (newParentingNode.IsKind(SyntaxKind.OperatorDeclaration)) { var operatorDeclaration = ((OperatorDeclarationSyntax)newParentingNode); newParentingNode = operatorDeclaration .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.None)) .WithTrailingTrivia(operatorDeclaration.SemicolonToken.TrailingTrivia); } else if (newParentingNode.IsKind(SyntaxKind.ConversionOperatorDeclaration)) { var conversionOperatorDeclaration = ((ConversionOperatorDeclarationSyntax)newParentingNode); newParentingNode = conversionOperatorDeclaration .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.None)) .WithTrailingTrivia(conversionOperatorDeclaration.SemicolonToken.TrailingTrivia); } } var newRoot = document.Root.ReplaceNode(oldParentingNode, newParentingNode); return document.Document.WithSyntaxRoot(newRoot); } private async Task<Document> IntroduceLocalDeclarationIntoBlockAsync( SemanticDocument document, ExpressionSyntax expression, NameSyntax newLocalName, LocalDeclarationStatementSyntax declarationStatement, bool allOccurrences, CancellationToken cancellationToken) { declarationStatement = declarationStatement.WithAdditionalAnnotations(Formatter.Annotation); var oldOutermostBlock = expression.GetAncestorsOrThis<BlockSyntax>().LastOrDefault(); var matches = FindMatches(document, expression, document, oldOutermostBlock, allOccurrences, cancellationToken); Debug.Assert(matches.Contains(expression)); var complexified = await ComplexifyParentingStatements(document, matches, cancellationToken).ConfigureAwait(false); document = complexified.Item1; matches = complexified.Item2; // Our original expression should have been one of the matches, which were tracked as part // of complexification, so we can retrieve the latest version of the expression here. expression = document.Root.GetCurrentNodes(expression).First(); var innermostStatements = new HashSet<StatementSyntax>( matches.Select(expr => expr.GetAncestorOrThis<StatementSyntax>())); if (innermostStatements.Count == 1) { // If there was only one match, or all the matches came from the same // statement, then we want to place the declaration right above that // statement. Note: we special case this because the statement we are going // to go above might not be in a block and we may have to generate it return IntroduceLocalForSingleOccurrenceIntoBlock( document, expression, newLocalName, declarationStatement, allOccurrences, cancellationToken); } var oldInnerMostCommonBlock = matches.FindInnermostCommonBlock(); var allAffectedStatements = new HashSet<StatementSyntax>(matches.SelectMany(expr => expr.GetAncestorsOrThis<StatementSyntax>())); var firstStatementAffectedInBlock = oldInnerMostCommonBlock.Statements.First(allAffectedStatements.Contains); var firstStatementAffectedIndex = oldInnerMostCommonBlock.Statements.IndexOf(firstStatementAffectedInBlock); var newInnerMostBlock = Rewrite( document, expression, newLocalName, document, oldInnerMostCommonBlock, allOccurrences, cancellationToken); var statements = new List<StatementSyntax>(); statements.AddRange(newInnerMostBlock.Statements.Take(firstStatementAffectedIndex)); statements.Add(declarationStatement); statements.AddRange(newInnerMostBlock.Statements.Skip(firstStatementAffectedIndex)); var finalInnerMostBlock = newInnerMostBlock.WithStatements( SyntaxFactory.List<StatementSyntax>(statements)); var newRoot = document.Root.ReplaceNode(oldInnerMostCommonBlock, finalInnerMostBlock); return document.Document.WithSyntaxRoot(newRoot); } private Document IntroduceLocalForSingleOccurrenceIntoBlock( SemanticDocument document, ExpressionSyntax expression, NameSyntax localName, LocalDeclarationStatementSyntax localDeclaration, bool allOccurrences, CancellationToken cancellationToken) { var oldStatement = expression.GetAncestorOrThis<StatementSyntax>(); var newStatement = Rewrite( document, expression, localName, document, oldStatement, allOccurrences, cancellationToken); if (oldStatement.IsParentKind(SyntaxKind.Block)) { var oldBlock = oldStatement.Parent as BlockSyntax; var statementIndex = oldBlock.Statements.IndexOf(oldStatement); var newBlock = oldBlock.WithStatements(CreateNewStatementList( oldBlock.Statements, localDeclaration, newStatement, statementIndex)); var newRoot = document.Root.ReplaceNode(oldBlock, newBlock); return document.Document.WithSyntaxRoot(newRoot); } else if (oldStatement.IsParentKind(SyntaxKind.SwitchSection)) { var oldSwitchSection = oldStatement.Parent as SwitchSectionSyntax; var statementIndex = oldSwitchSection.Statements.IndexOf(oldStatement); var newSwitchSection = oldSwitchSection.WithStatements(CreateNewStatementList( oldSwitchSection.Statements, localDeclaration, newStatement, statementIndex)); var newRoot = document.Root.ReplaceNode(oldSwitchSection, newSwitchSection); return document.Document.WithSyntaxRoot(newRoot); } else { // we need to introduce a block to put the original statement, along with // the statement we're generating var newBlock = SyntaxFactory.Block(localDeclaration, newStatement).WithAdditionalAnnotations(Formatter.Annotation); var newRoot = document.Root.ReplaceNode(oldStatement, newBlock); return document.Document.WithSyntaxRoot(newRoot); } } private static SyntaxList<StatementSyntax> CreateNewStatementList( SyntaxList<StatementSyntax> oldStatements, LocalDeclarationStatementSyntax localDeclaration, StatementSyntax newStatement, int statementIndex) { return oldStatements.Take(statementIndex) .Concat(localDeclaration.WithLeadingTrivia(oldStatements.Skip(statementIndex).First().GetLeadingTrivia())) .Concat(newStatement.WithoutLeadingTrivia()) .Concat(oldStatements.Skip(statementIndex + 1)) .ToSyntaxList(); } } }
//JSON RPC based on Jayrock - JSON and JSON-RPC for Microsoft .NET Framework and Mono //http://jayrock.berlios.de/ using System; using System.Collections; using System.Diagnostics; using System.Globalization; using System.Reflection; using FluorineFx.Util; using FluorineFx.Messaging; using FluorineFx.Messaging.Messages; namespace FluorineFx.Json.Services { /// <summary> /// This type supports the Fluorine infrastructure and is not intended to be used directly from your code. /// </summary> public sealed class Method { private string _name; private Type _resultType; private Parameter[] _parameters; private string[] _parameterNames; private Parameter[] _sortedParameters; private string _description; public static Method FromMethodInfo(MethodInfo methodInfo) { Method method = new Method(); method._name = methodInfo.Name; method._resultType = methodInfo.ReturnType; method._description = null; method._parameters = new Parameter[methodInfo.GetParameters().Length]; method._parameterNames = new string[methodInfo.GetParameters().Length]; foreach (ParameterInfo parameterInfo in methodInfo.GetParameters()) { Parameter parameter = Parameter.FromParameterInfo(parameterInfo); int position = parameter.Position; method._parameters[position] = parameter; method._parameterNames[position] = parameter.Name; } // Keep a sorted list of parameters and their names so we can do fast look ups using binary search. method._sortedParameters = (Parameter[])method._parameters.Clone(); InvariantStringArray.Sort(method._parameterNames, method._sortedParameters); return method; } internal Method() { } public string Name { get { return _name; } } public Parameter[] GetParameters() { return _parameters; } public Type ResultType { get { return _resultType; } } public string Description { get { return _description; } } /* public object Invoke(object service, string[] names, object[] args) { if (names != null) args = MapArguments(names, args); args = TransposeVariableArguments(args); return _handler.Invoke(service, args); } */ /// <summary> /// Determines if the method accepts variable number of arguments or /// not. A method is designated as accepting variable arguments by /// annotating the last parameter of the method with the JsonRpcParams /// attribute. /// </summary> public bool HasParamArray { get { return _parameters.Length > 0 && _parameters[_parameters.Length - 1].IsParamArray; } } private object[] MapArguments(string[] names, object[] args) { Debug.Assert(names != null); Debug.Assert(args != null); Debug.Assert(names.Length == args.Length); object[] mapped = new object[_parameters.Length]; for (int i = 0; i < names.Length; i++) { string name = names[i]; if (name == null || name.Length == 0) continue; object arg = args[i]; if (arg == null) continue; int position = -1; if (name.Length <= 2) { char ch1; char ch2; if (name.Length == 2) { ch1 = name[0]; ch2 = name[1]; } else { ch1 = '0'; ch2 = name[0]; } if (ch1 >= '0' && ch1 <= '9' && ch2 >= '0' && ch2 <= '9') { position = int.Parse(name, NumberStyles.Number, CultureInfo.InvariantCulture); if (position < _parameters.Length) mapped[position] = arg; } } if (position < 0) { int order = InvariantStringArray.BinarySearch(_parameterNames, name); if (order >= 0) position = _sortedParameters[order].Position; } if (position >= 0) mapped[position] = arg; } return mapped; } /// <summary> /// Takes an array of arguments that are designated for a method and /// transposes them if the target method supports variable arguments (in /// other words, the last parameter is annotated with the JsonRpcParams /// attribute). If the method does not support variable arguments then /// the input array is returned verbatim. /// </summary> // TODO: Allow args to be null to represent empty arguments. // TODO: Allow parameter conversions public object[] TransposeVariableArguments(object[] args) { // // If the method does not have take variable arguments then just // return the arguments array verbatim. // if (!HasParamArray) return args; int parameterCount = _parameters.Length; object[] varArgs = null; // // The variable argument may already be setup correctly as an // array. If so then the formal and actual parameter count will // match here. // if (args.Length == parameterCount) { object lastArg = args[args.Length - 1]; if (lastArg != null) { // // Is the last argument already set up as an object // array ready to be received as the variable arguments? // varArgs = lastArg as object[]; if (varArgs == null) { // // Is the last argument an array of some sort? If so // then we convert it into an array of objects since // that is what we support right now for variable // arguments. // // TODO: Allow variable arguments to be more specific type, such as array of integers. // TODO: Don't make a copy if one doesn't have to be made. // For example if the types are compatible on the receiving end. // Array lastArrayArg = lastArg as Array; if (lastArrayArg != null && lastArrayArg.GetType().GetArrayRank() == 1) { varArgs = new object[lastArrayArg.Length]; Array.Copy(lastArrayArg, varArgs, varArgs.Length); } } } } // // Copy out the extra arguments into a new array that represents // the variable parts. // if (varArgs == null) { varArgs = new object[(args.Length - parameterCount) + 1]; Array.Copy(args, parameterCount - 1, varArgs, 0, varArgs.Length); } // // Setup a new array of arguments that has a copy of the fixed // arguments followed by the variable arguments array setup above. // object[] transposedArgs = new object[parameterCount]; Array.Copy(args, transposedArgs, parameterCount - 1); transposedArgs[transposedArgs.Length - 1] = varArgs; return transposedArgs; } private static bool TypesMatch(Type expected, Type actual) { Debug.Assert(expected != null); Debug.Assert(actual != null); // // If the expected type is sealed then use a quick check by // comparing types for equality. Otherwise, use the slow // approach to determine type compatibility be their // relationship. // return expected.IsSealed ? expected.Equals(actual) : expected.IsAssignableFrom(actual); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using Internal.Runtime.CompilerServices; namespace System.Buffers { public readonly partial struct ReadOnlySequence<T> { [MethodImpl(MethodImplOptions.AggressiveInlining)] internal bool TryGetBuffer(in SequencePosition position, out ReadOnlyMemory<T> memory, out SequencePosition next) { object? positionObject = position.GetObject(); next = default; if (positionObject == null) { memory = default; return false; } SequenceType type = GetSequenceType(); object? endObject = _endObject; int startIndex = GetIndex(position); int endIndex = GetIndex(_endInteger); if (type == SequenceType.MultiSegment) { Debug.Assert(positionObject is ReadOnlySequenceSegment<T>); ReadOnlySequenceSegment<T> startSegment = (ReadOnlySequenceSegment<T>)positionObject; if (startSegment != endObject) { ReadOnlySequenceSegment<T>? nextSegment = startSegment.Next; if (nextSegment == null) ThrowHelper.ThrowInvalidOperationException_EndPositionNotReached(); next = new SequencePosition(nextSegment, 0); memory = startSegment.Memory.Slice(startIndex); } else { memory = startSegment.Memory.Slice(startIndex, endIndex - startIndex); } } else { if (positionObject != endObject) ThrowHelper.ThrowInvalidOperationException_EndPositionNotReached(); if (type == SequenceType.Array) { Debug.Assert(positionObject is T[]); memory = new ReadOnlyMemory<T>((T[])positionObject, startIndex, endIndex - startIndex); } else if (typeof(T) == typeof(char) && type == SequenceType.String) { Debug.Assert(positionObject is string); memory = (ReadOnlyMemory<T>)(object)((string)positionObject).AsMemory(startIndex, endIndex - startIndex); } else // type == SequenceType.MemoryManager { Debug.Assert(type == SequenceType.MemoryManager); Debug.Assert(positionObject is MemoryManager<T>); memory = ((MemoryManager<T>)positionObject).Memory.Slice(startIndex, endIndex - startIndex); } } return true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private ReadOnlyMemory<T> GetFirstBuffer() { object? startObject = _startObject; if (startObject == null) return default; int startIndex = _startInteger; int endIndex = _endInteger; bool isMultiSegment = startObject != _endObject; // The highest bit of startIndex and endIndex are used to infer the sequence type // The code below is structured this way for performance reasons and is equivalent to the following: // SequenceType type = GetSequenceType(); // if (type == SequenceType.MultiSegment) { ... } // else if (type == SequenceType.Array) { ... } // else if (type == SequenceType.String){ ... } // else if (type == SequenceType.MemoryManager) { ... } // Highest bit of startIndex: A = startIndex >> 31 // Highest bit of endIndex: B = endIndex >> 31 // A == 0 && B == 0 means SequenceType.MultiSegment // Equivalent to startIndex >= 0 && endIndex >= 0 if ((startIndex | endIndex) >= 0) { ReadOnlyMemory<T> memory = ((ReadOnlySequenceSegment<T>)startObject).Memory; if (isMultiSegment) { return memory.Slice(startIndex); } return memory.Slice(startIndex, endIndex - startIndex); } else { return GetFirstBufferSlow(startObject, isMultiSegment); } } [MethodImpl(MethodImplOptions.NoInlining)] private ReadOnlyMemory<T> GetFirstBufferSlow(object startObject, bool isMultiSegment) { if (isMultiSegment) ThrowHelper.ThrowInvalidOperationException_EndPositionNotReached(); int startIndex = _startInteger; int endIndex = _endInteger; Debug.Assert(startIndex < 0 || endIndex < 0); // A == 0 && B == 1 means SequenceType.Array if (startIndex >= 0) { Debug.Assert(endIndex < 0); return new ReadOnlyMemory<T>((T[])startObject, startIndex, (endIndex & ReadOnlySequence.IndexBitMask) - startIndex); } else { // The type == char check here is redundant. However, we still have it to allow // the JIT to see when that the code is unreachable and eliminate it. // A == 1 && B == 1 means SequenceType.String if (typeof(T) == typeof(char) && endIndex < 0) { // No need to remove the FlagBitMask since (endIndex - startIndex) == (endIndex & ReadOnlySequence.IndexBitMask) - (startIndex & ReadOnlySequence.IndexBitMask) return (ReadOnlyMemory<T>)(object)((string)startObject).AsMemory(startIndex & ReadOnlySequence.IndexBitMask, endIndex - startIndex); } else // endIndex >= 0, A == 1 && B == 0 means SequenceType.MemoryManager { startIndex &= ReadOnlySequence.IndexBitMask; return ((MemoryManager<T>)startObject).Memory.Slice(startIndex, endIndex - startIndex); } } } [MethodImpl(MethodImplOptions.AggressiveInlining)] private ReadOnlySpan<T> GetFirstSpan() { object? startObject = _startObject; if (startObject == null) return default; int startIndex = _startInteger; int endIndex = _endInteger; bool isMultiSegment = startObject != _endObject; // The highest bit of startIndex and endIndex are used to infer the sequence type // The code below is structured this way for performance reasons and is equivalent to the following: // SequenceType type = GetSequenceType(); // if (type == SequenceType.MultiSegment) { ... } // else if (type == SequenceType.Array) { ... } // else if (type == SequenceType.String){ ... } // else if (type == SequenceType.MemoryManager) { ... } // Highest bit of startIndex: A = startIndex >> 31 // Highest bit of endIndex: B = endIndex >> 31 // A == 0 && B == 0 means SequenceType.MultiSegment // Equivalent to startIndex >= 0 && endIndex >= 0 if ((startIndex | endIndex) >= 0) { ReadOnlySpan<T> span = ((ReadOnlySequenceSegment<T>)startObject).Memory.Span; if (isMultiSegment) { return span.Slice(startIndex); } return span.Slice(startIndex, endIndex - startIndex); } else { return GetFirstSpanSlow(startObject, isMultiSegment); } } [MethodImpl(MethodImplOptions.NoInlining)] private ReadOnlySpan<T> GetFirstSpanSlow(object startObject, bool isMultiSegment) { if (isMultiSegment) ThrowHelper.ThrowInvalidOperationException_EndPositionNotReached(); int startIndex = _startInteger; int endIndex = _endInteger; Debug.Assert(startIndex < 0 || endIndex < 0); // A == 0 && B == 1 means SequenceType.Array if (startIndex >= 0) { Debug.Assert(endIndex < 0); ReadOnlySpan<T> span = (T[])startObject; return span.Slice(startIndex, (endIndex & ReadOnlySequence.IndexBitMask) - startIndex); } else { // The type == char check here is redundant. However, we still have it to allow // the JIT to see when that the code is unreachable and eliminate it. // A == 1 && B == 1 means SequenceType.String if (typeof(T) == typeof(char) && endIndex < 0) { var memory = (ReadOnlyMemory<T>)(object)((string)startObject).AsMemory(); // No need to remove the FlagBitMask since (endIndex - startIndex) == (endIndex & ReadOnlySequence.IndexBitMask) - (startIndex & ReadOnlySequence.IndexBitMask) return memory.Span.Slice(startIndex & ReadOnlySequence.IndexBitMask, endIndex - startIndex); } else // endIndex >= 0, A == 1 && B == 0 means SequenceType.MemoryManager { startIndex &= ReadOnlySequence.IndexBitMask; return ((MemoryManager<T>)startObject).Memory.Span.Slice(startIndex, endIndex - startIndex); } } } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal SequencePosition Seek(long offset, ExceptionArgument exceptionArgument = ExceptionArgument.offset) { object? startObject = _startObject; object? endObject = _endObject; int startIndex = GetIndex(_startInteger); int endIndex = GetIndex(_endInteger); if (startObject != endObject) { Debug.Assert(startObject != null); var startSegment = (ReadOnlySequenceSegment<T>)startObject; int currentLength = startSegment.Memory.Length - startIndex; // Position in start segment, defer to single segment seek if (currentLength > offset) goto IsSingleSegment; if (currentLength < 0) ThrowHelper.ThrowArgumentOutOfRangeException_PositionOutOfRange(); // End of segment. Move to start of next. return SeekMultiSegment(startSegment.Next!, endObject!, endIndex, offset - currentLength, exceptionArgument); } Debug.Assert(startObject == endObject); if (endIndex - startIndex < offset) ThrowHelper.ThrowArgumentOutOfRangeException(exceptionArgument); // Single segment Seek IsSingleSegment: return new SequencePosition(startObject, startIndex + (int)offset); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private SequencePosition Seek(in SequencePosition start, long offset) { object? startObject = start.GetObject(); object? endObject = _endObject; int startIndex = GetIndex(start); int endIndex = GetIndex(_endInteger); if (startObject != endObject) { Debug.Assert(startObject != null); var startSegment = (ReadOnlySequenceSegment<T>)startObject; int currentLength = startSegment.Memory.Length - startIndex; // Position in start segment, defer to single segment seek if (currentLength > offset) goto IsSingleSegment; if (currentLength < 0) ThrowHelper.ThrowArgumentOutOfRangeException_PositionOutOfRange(); // End of segment. Move to start of next. return SeekMultiSegment(startSegment.Next!, endObject!, endIndex, offset - currentLength, ExceptionArgument.offset); } Debug.Assert(startObject == endObject); if (endIndex - startIndex < offset) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.offset); // Single segment Seek IsSingleSegment: return new SequencePosition(startObject, startIndex + (int)offset); } [MethodImpl(MethodImplOptions.NoInlining)] private static SequencePosition SeekMultiSegment(ReadOnlySequenceSegment<T>? currentSegment, object endObject, int endIndex, long offset, ExceptionArgument argument) { Debug.Assert(currentSegment != null); // currentSegment parameter is marked as nullable as the parameter is reused/reassigned in the body Debug.Assert(offset >= 0); while (currentSegment != null && currentSegment != endObject) { int memoryLength = currentSegment.Memory.Length; // Fully contained in this segment if (memoryLength > offset) goto FoundSegment; // Move to next offset -= memoryLength; currentSegment = currentSegment.Next; } // Hit the end of the segments but didn't reach the count if (currentSegment == null || endIndex < offset) ThrowHelper.ThrowArgumentOutOfRangeException(argument); FoundSegment: return new SequencePosition(currentSegment, (int)offset); } private void BoundsCheck(in SequencePosition position, bool positionIsNotNull) { uint sliceStartIndex = (uint)GetIndex(position); object? startObject = _startObject; object? endObject = _endObject; uint startIndex = (uint)GetIndex(_startInteger); uint endIndex = (uint)GetIndex(_endInteger); // Single-Segment Sequence if (startObject == endObject) { if (!InRange(sliceStartIndex, startIndex, endIndex)) { ThrowHelper.ThrowArgumentOutOfRangeException_PositionOutOfRange(); } } else { // Multi-Segment Sequence // Storing this in a local since it is used twice within InRange() ulong startRange = (ulong)(((ReadOnlySequenceSegment<T>)startObject!).RunningIndex + startIndex); long runningIndex = 0; if (positionIsNotNull) { Debug.Assert(position.GetObject() != null); runningIndex = ((ReadOnlySequenceSegment<T>)position.GetObject()!).RunningIndex; } if (!InRange( (ulong)(runningIndex + sliceStartIndex), startRange, (ulong)(((ReadOnlySequenceSegment<T>)endObject!).RunningIndex + endIndex))) { ThrowHelper.ThrowArgumentOutOfRangeException_PositionOutOfRange(); } } } private void BoundsCheck(uint sliceStartIndex, object? sliceStartObject, uint sliceEndIndex, object? sliceEndObject) { object? startObject = _startObject; object? endObject = _endObject; uint startIndex = (uint)GetIndex(_startInteger); uint endIndex = (uint)GetIndex(_endInteger); // Single-Segment Sequence if (startObject == endObject) { if (sliceStartObject != sliceEndObject || sliceStartObject != startObject || sliceStartIndex > sliceEndIndex || sliceStartIndex < startIndex || sliceEndIndex > endIndex) { ThrowHelper.ThrowArgumentOutOfRangeException_PositionOutOfRange(); } } else { // Multi-Segment Sequence // This optimization works because we know sliceStartIndex, sliceEndIndex, startIndex, and endIndex are all >= 0 Debug.Assert(sliceStartIndex >= 0 && startIndex >= 0 && endIndex >= 0); ulong sliceStartRange = sliceStartIndex; ulong sliceEndRange = sliceEndIndex; if (sliceStartObject != null) { sliceStartRange += (ulong)((ReadOnlySequenceSegment<T>)sliceStartObject).RunningIndex; } if (sliceEndObject != null) { sliceEndRange += (ulong)((ReadOnlySequenceSegment<T>)sliceEndObject).RunningIndex; } if (sliceStartRange > sliceEndRange) ThrowHelper.ThrowArgumentOutOfRangeException_PositionOutOfRange(); if (sliceStartRange < (ulong)(((ReadOnlySequenceSegment<T>)startObject!).RunningIndex + startIndex) || sliceEndRange > (ulong)(((ReadOnlySequenceSegment<T>)endObject!).RunningIndex + endIndex)) { ThrowHelper.ThrowArgumentOutOfRangeException_PositionOutOfRange(); } } } private static SequencePosition GetEndPosition(ReadOnlySequenceSegment<T> startSegment, object startObject, int startIndex, object endObject, int endIndex, long length) { int currentLength = startSegment.Memory.Length - startIndex; if (currentLength > length) { return new SequencePosition(startObject, startIndex + (int)length); } if (currentLength < 0) ThrowHelper.ThrowArgumentOutOfRangeException_PositionOutOfRange(); return SeekMultiSegment(startSegment.Next, endObject, endIndex, length - currentLength, ExceptionArgument.length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private SequenceType GetSequenceType() { // We take high order bits of two indexes and move them // to a first and second position to convert to SequenceType // if (start < 0 and end < 0) // start >> 31 = -1, end >> 31 = -1 // 2 * (-1) + (-1) = -3, result = (SequenceType)3 // if (start < 0 and end >= 0) // start >> 31 = -1, end >> 31 = 0 // 2 * (-1) + 0 = -2, result = (SequenceType)2 // if (start >= 0 and end >= 0) // start >> 31 = 0, end >> 31 = 0 // 2 * 0 + 0 = 0, result = (SequenceType)0 // if (start >= 0 and end < 0) // start >> 31 = 0, end >> 31 = -1 // 2 * 0 + (-1) = -1, result = (SequenceType)1 return (SequenceType)(-(2 * (_startInteger >> 31) + (_endInteger >> 31))); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static int GetIndex(in SequencePosition position) => position.GetInteger() & ReadOnlySequence.IndexBitMask; [MethodImpl(MethodImplOptions.AggressiveInlining)] private static int GetIndex(int Integer) => Integer & ReadOnlySequence.IndexBitMask; [MethodImpl(MethodImplOptions.AggressiveInlining)] private ReadOnlySequence<T> SliceImpl(in SequencePosition start, in SequencePosition end) { // In this method we reset high order bits from indices // of positions that were passed in // and apply type bits specific for current ReadOnlySequence type return new ReadOnlySequence<T>( start.GetObject(), GetIndex(start) | (_startInteger & ReadOnlySequence.FlagBitMask), end.GetObject(), GetIndex(end) | (_endInteger & ReadOnlySequence.FlagBitMask) ); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private ReadOnlySequence<T> SliceImpl(in SequencePosition start) { // In this method we reset high order bits from indices // of positions that were passed in // and apply type bits specific for current ReadOnlySequence type return new ReadOnlySequence<T>( start.GetObject(), GetIndex(start) | (_startInteger & ReadOnlySequence.FlagBitMask), _endObject, _endInteger ); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private long GetLength() { object? startObject = _startObject; object? endObject = _endObject; int startIndex = GetIndex(_startInteger); int endIndex = GetIndex(_endInteger); if (startObject != endObject) { var startSegment = (ReadOnlySequenceSegment<T>)startObject!; var endSegment = (ReadOnlySequenceSegment<T>)endObject!; // (End offset) - (start offset) return (endSegment.RunningIndex + endIndex) - (startSegment.RunningIndex + startIndex); } // Single segment length return endIndex - startIndex; } internal bool TryGetReadOnlySequenceSegment(out ReadOnlySequenceSegment<T>? startSegment, out int startIndex, out ReadOnlySequenceSegment<T>? endSegment, out int endIndex) { object? startObject = _startObject; // Default or not MultiSegment if (startObject == null || GetSequenceType() != SequenceType.MultiSegment) { startSegment = null; startIndex = 0; endSegment = null; endIndex = 0; return false; } Debug.Assert(_endObject != null); startSegment = (ReadOnlySequenceSegment<T>)startObject; startIndex = GetIndex(_startInteger); endSegment = (ReadOnlySequenceSegment<T>)_endObject; endIndex = GetIndex(_endInteger); return true; } internal bool TryGetArray(out ArraySegment<T> segment) { if (GetSequenceType() != SequenceType.Array) { segment = default; return false; } Debug.Assert(_startObject != null); int startIndex = GetIndex(_startInteger); segment = new ArraySegment<T>((T[])_startObject, startIndex, GetIndex(_endInteger) - startIndex); return true; } internal bool TryGetString(out string? text, out int start, out int length) { if (typeof(T) != typeof(char) || GetSequenceType() != SequenceType.String) { start = 0; length = 0; text = null; return false; } Debug.Assert(_startObject != null); start = GetIndex(_startInteger); length = GetIndex(_endInteger) - start; text = (string)_startObject; return true; } private static bool InRange(uint value, uint start, uint end) { // _sequenceStart and _sequenceEnd must be well-formed Debug.Assert(start <= int.MaxValue); Debug.Assert(end <= int.MaxValue); Debug.Assert(start <= end); // The case, value > int.MaxValue, is invalid, and hence it shouldn't be in the range. // If value > int.MaxValue, it is invariably greater than both 'start' and 'end'. // In that case, the experession simplifies to value <= end, which will return false. // The case, value < start, is invalid. // In that case, (value - start) would underflow becoming larger than int.MaxValue. // (end - start) can never underflow and hence must be within 0 and int.MaxValue. // So, we will correctly return false. // The case, value > end, is invalid. // In that case, the expression simplifies to value <= end, which will return false. // This is because end > start & value > end implies value > start as well. // In all other cases, value is valid, and we return true. // Equivalent to: return (start <= value && value <= end) return (value - start) <= (end - start); } private static bool InRange(ulong value, ulong start, ulong end) { // _sequenceStart and _sequenceEnd must be well-formed Debug.Assert(start <= long.MaxValue); Debug.Assert(end <= long.MaxValue); Debug.Assert(start <= end); // The case, value > long.MaxValue, is invalid, and hence it shouldn't be in the range. // If value > long.MaxValue, it is invariably greater than both 'start' and 'end'. // In that case, the experession simplifies to value <= end, which will return false. // The case, value < start, is invalid. // In that case, (value - start) would underflow becoming larger than long.MaxValue. // (end - start) can never underflow and hence must be within 0 and long.MaxValue. // So, we will correctly return false. // The case, value > end, is invalid. // In that case, the expression simplifies to value <= end, which will return false. // This is because end > start & value > end implies value > start as well. // In all other cases, value is valid, and we return true. // Equivalent to: return (start <= value && value <= start) return (value - start) <= (end - start); } /// <summary> /// Helper to efficiently prepare the <see cref="SequenceReader{T}"/> /// </summary> /// <param name="first">The first span in the sequence.</param> /// <param name="next">The next position.</param> [MethodImpl(MethodImplOptions.AggressiveInlining)] internal void GetFirstSpan(out ReadOnlySpan<T> first, out SequencePosition next) { first = default; next = default; object? startObject = _startObject; int startIndex = _startInteger; if (startObject != null) { bool hasMultipleSegments = startObject != _endObject; int endIndex = _endInteger; if (startIndex >= 0) { if (endIndex >= 0) { // Positive start and end index == ReadOnlySequenceSegment<T> ReadOnlySequenceSegment<T> segment = (ReadOnlySequenceSegment<T>)startObject; next = new SequencePosition(segment.Next, 0); first = segment.Memory.Span; if (hasMultipleSegments) { first = first.Slice(startIndex); } else { first = first.Slice(startIndex, endIndex - startIndex); } } else { // Positive start and negative end index == T[] if (hasMultipleSegments) ThrowHelper.ThrowInvalidOperationException_EndPositionNotReached(); first = new ReadOnlySpan<T>((T[])startObject, startIndex, (endIndex & ReadOnlySequence.IndexBitMask) - startIndex); } } else { first = GetFirstSpanSlow(startObject, startIndex, endIndex, hasMultipleSegments); } } } [MethodImpl(MethodImplOptions.NoInlining)] private static ReadOnlySpan<T> GetFirstSpanSlow(object startObject, int startIndex, int endIndex, bool hasMultipleSegments) { Debug.Assert(startIndex < 0); if (hasMultipleSegments) ThrowHelper.ThrowInvalidOperationException_EndPositionNotReached(); // The type == char check here is redundant. However, we still have it to allow // the JIT to see when that the code is unreachable and eliminate it. if (typeof(T) == typeof(char) && endIndex < 0) { // Negative start and negative end index == string ReadOnlySpan<char> spanOfChar = ((string)startObject).AsSpan(startIndex & ReadOnlySequence.IndexBitMask, endIndex - startIndex); return MemoryMarshal.CreateReadOnlySpan(ref Unsafe.As<char, T>(ref MemoryMarshal.GetReference(spanOfChar)), spanOfChar.Length); } else { // Negative start and positive end index == MemoryManager<T> startIndex &= ReadOnlySequence.IndexBitMask; return ((MemoryManager<T>)startObject).Memory.Span.Slice(startIndex, endIndex - startIndex); } } } }
/* * Copyright (c) 2015, InWorldz Halcyon Developers * 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 halcyon nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using OpenSim.Region.Physics.Manager; using System.Threading; namespace InWorldz.PhysxPhysics.Commands { /// <summary> /// Creates a parent and all child shapes from the given data /// </summary> internal class BulkCreateObjectCmd : ICommand, IDisposable { private PhysxScene.AddPrimShapeFlags _flags; private ICollection<BulkShapeData> _shapes; private PhysicsShape _newPrimaryShape; private BulkShapeData _primaryShapeData; private Dictionary<BulkShapeData, PhysicsShape> _meshedShapes = new Dictionary<BulkShapeData,PhysicsShape>(); private int _totalNumShapes; private int _meshedSoFar; private bool _rootHasVdSet = false; public readonly ManualResetEventSlim FinishedEvent = new ManualResetEventSlim(false); public BulkCreateObjectCmd(PhysxScene.AddPrimShapeFlags flags, ICollection<BulkShapeData> shapes) { _flags = flags; _shapes = shapes; _totalNumShapes = shapes.Count; _meshedSoFar = 0; } public bool AffectsMultiplePrims() { return false; } public PhysxPrim GetTargetPrim() { return null; } public bool RemoveWaitAndCheckReady() { return true; } public void Execute(PhysxScene scene) { bool isPhysical = (_flags & PhysicsScene.AddPrimShapeFlags.Physical) != 0; if (_rootHasVdSet) { isPhysical = false; } if (_newPrimaryShape == null) { bool first = true; foreach (BulkShapeData shape in _shapes) { BulkShapeData thisShape = shape; if (first) { _primaryShapeData = thisShape; PhysicsProperties properties = PhysicsProperties.DeserializeOrCreateNew(scene, shape.Material, shape.PhysicsProperties); _rootHasVdSet = properties.VolumeDetectActive; if (_rootHasVdSet) { isPhysical = false; } scene.MeshingStageImpl.QueueForMeshing(String.Empty, shape.Pbs, shape.Size, Meshing.MeshingStage.SCULPT_MESH_LOD, isPhysical || _rootHasVdSet, shape.SerializedShapes, (_flags & PhysxScene.AddPrimShapeFlags.FromCrossing) == PhysicsScene.AddPrimShapeFlags.FromCrossing, delegate(PhysicsShape meshedShape) { _newPrimaryShape = meshedShape; _meshedShapes.Add(thisShape, meshedShape); if (++_meshedSoFar == _totalNumShapes) { scene.QueueCommand(this); } } ); first = false; } else { scene.MeshingStageImpl.QueueForMeshing(String.Empty, shape.Pbs, shape.Size, Meshing.MeshingStage.SCULPT_MESH_LOD, isPhysical || _rootHasVdSet, shape.SerializedShapes, (_flags & PhysxScene.AddPrimShapeFlags.FromCrossing) == PhysicsScene.AddPrimShapeFlags.FromCrossing, delegate(PhysicsShape meshedShape) { _meshedShapes.Add(thisShape, meshedShape); if (++_meshedSoFar == _totalNumShapes) { scene.QueueCommand(this); } } ); } } } else { OpenMetaverse.Vector3 rootVelocity = OpenMetaverse.Vector3.Zero; OpenMetaverse.Vector3 rootAngularVelocity = OpenMetaverse.Vector3.Zero; //we have all the shapes for the parent and all children, time to construct the group bool first = true; PhysxPrim rootPrim = null; CollisionGroupFlag collisionGroup = (_flags & PhysicsScene.AddPrimShapeFlags.Phantom) == 0 ? CollisionGroupFlag.Normal : CollisionGroupFlag.PhysicalPhantom; foreach (BulkShapeData shape in _shapes) { if (first) { bool kinematicStatic; PhysicsProperties properties = PhysicsProperties.DeserializeOrCreateNew(scene, shape.Material, shape.PhysicsProperties); PhysX.RigidActor actor = PhysxActorFactory.CreateProperInitialActor(_newPrimaryShape, scene, shape.Position, shape.Rotation, _flags, out kinematicStatic, properties.PhysxMaterial); rootPrim = new PhysxPrim(scene, shape.Pbs, shape.Position, shape.Rotation, _newPrimaryShape, actor, isPhysical, properties, collisionGroup); scene.AddPrimSync(rootPrim, isPhysical, kinematicStatic); shape.OutActor = rootPrim; rootVelocity = shape.Velocity; rootAngularVelocity = shape.AngularVelocity; first = false; } else { PhysicsShape phyShape = _meshedShapes[shape]; PhysicsProperties properties = PhysicsProperties.DeserializeOrCreateNew(scene, shape.Material, shape.PhysicsProperties); PhysxPrim childPrim = new PhysxPrim(rootPrim, scene, shape.Pbs, shape.Position, shape.Rotation, phyShape, null, isPhysical, properties, collisionGroup); rootPrim.LinkPrimAsChildSync(phyShape, childPrim, shape.Position, shape.Rotation, true); shape.OutActor = childPrim; } } rootPrim.UpdateMassAndInertia(); if (_rootHasVdSet) { rootPrim.SetVolumeDetectSync(_rootHasVdSet); } if ((_flags & PhysicsScene.AddPrimShapeFlags.StartSuspended) != 0) { rootPrim.SuspendPhysicsSync(_primaryShapeData.ObjectReceivedOn); } rootPrim.DynamicsPostcheck(); rootPrim.SetInitialVelocities(rootVelocity, rootAngularVelocity); if ((_flags & PhysicsScene.AddPrimShapeFlags.Interpolate) != 0) { rootPrim.SuspendPhysicsSync(_primaryShapeData.ObjectReceivedOn); rootPrim.ResumePhysicsSync(true); } FinishedEvent.Set(); } } public void Dispose() { FinishedEvent.Dispose(); } public bool IsCullable { get { return false; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.IO.PortsTests; using System.Linq; using System.Threading; using Legacy.Support; using Xunit; namespace System.IO.Ports.Tests { public class ReadBufferSize_Property : PortsTest { private const int MAX_RANDOM_BUFFER_SIZE = 1024 * 16; private const int LARGE_BUFFER_SIZE = 1024 * 128; #region Test Cases [ConditionalFact(nameof(HasOneSerialPort))] public void ReadBufferSize_Default() { using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { SerialPortProperties serPortProp = new SerialPortProperties(); Debug.WriteLine("Verifying default ReadBufferSize before Open"); serPortProp.SetAllPropertiesToDefaults(); serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); serPortProp.VerifyPropertiesAndPrint(com1); Debug.WriteLine("Verifying default ReadBufferSize after Open"); com1.Open(); serPortProp = new SerialPortProperties(); serPortProp.SetAllPropertiesToOpenDefaults(); serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); serPortProp.VerifyPropertiesAndPrint(com1); Debug.WriteLine("Verifying default ReadBufferSize after Close"); com1.Close(); serPortProp = new SerialPortProperties(); serPortProp.SetAllPropertiesToDefaults(); serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); serPortProp.VerifyPropertiesAndPrint(com1); } } [ConditionalFact(nameof(HasNullModem))] public void ReadBufferSize_AfterOpen() { VerifyException(1024, null, typeof(InvalidOperationException)); } [ConditionalFact(nameof(HasNullModem))] public void ReadBufferSize_NEG1() { VerifyException(-1, typeof(ArgumentOutOfRangeException), typeof(ArgumentOutOfRangeException)); } [ConditionalFact(nameof(HasNullModem))] public void ReadBufferSize_Int32MinValue() { VerifyException(int.MinValue, typeof(ArgumentOutOfRangeException), typeof(ArgumentOutOfRangeException)); } [ConditionalFact(nameof(HasNullModem))] public void ReadBufferSize_0() { VerifyException(0, typeof(ArgumentOutOfRangeException), typeof(ArgumentOutOfRangeException)); } [ConditionalFact(nameof(HasNullModem))] public void ReadBufferSize_1() { Debug.WriteLine("Verifying setting ReadBufferSize=1"); VerifyException(1, typeof(IOException), typeof(InvalidOperationException), true); } [ConditionalFact(nameof(HasNullModem))] public void ReadBufferSize_2() { Debug.WriteLine("Verifying setting ReadBufferSize="); VerifyReadBufferSize(2); } [ConditionalFact(nameof(HasNullModem))] public void ReadBufferSize_Smaller() { using (var com = new SerialPort()) { uint newReadBufferSize = (uint)com.ReadBufferSize; newReadBufferSize /= 2; //Make the new buffer size half the original size newReadBufferSize &= 0xFFFFFFFE; //Make sure the new buffer size is even by clearing the lowest order bit VerifyReadBufferSize((int)newReadBufferSize); } } [ConditionalFact(nameof(HasNullModem))] public void ReadBufferSize_Larger() { VerifyReadBufferSize(((new SerialPort()).ReadBufferSize) * 2); } [ConditionalFact(nameof(HasNullModem))] public void ReadBufferSize_Odd() { Debug.WriteLine("Verifying setting ReadBufferSize=Odd"); VerifyException(((new SerialPort()).ReadBufferSize) * 2 + 1, typeof(IOException), typeof(InvalidOperationException), true); } [ConditionalFact(nameof(HasNullModem))] public void ReadBufferSize_Even() { Debug.WriteLine("Verifying setting ReadBufferSize=Even"); VerifyReadBufferSize(((new SerialPort()).ReadBufferSize) * 2); } [ConditionalFact(nameof(HasNullModem))] public void ReadBufferSize_Rnd() { Random rndGen = new Random(-55); uint newReadBufferSize = (uint)rndGen.Next(MAX_RANDOM_BUFFER_SIZE); newReadBufferSize &= 0xFFFFFFFE; //Make sure the new buffer size is even by clearing the lowest order bit // if(!VerifyReadBufferSize((int)newReadBufferSize)){ VerifyReadBufferSize(11620); } [ConditionalFact(nameof(HasNullModem))] public void ReadBufferSize_Large() { VerifyReadBufferSize(LARGE_BUFFER_SIZE); } #endregion #region Verification for Test Cases private void VerifyException(int newReadBufferSize, Type expectedExceptionBeforeOpen, Type expectedExceptionAfterOpen) { VerifyException(newReadBufferSize, expectedExceptionBeforeOpen, expectedExceptionAfterOpen, false); } private void VerifyException(int newReadBufferSize, Type expectedExceptionBeforeOpen, Type expectedExceptionAfterOpen, bool throwAtOpen) { VerifyExceptionBeforeOpen(newReadBufferSize, expectedExceptionBeforeOpen, throwAtOpen); VerifyExceptionAfterOpen(newReadBufferSize, expectedExceptionAfterOpen); } private void VerifyExceptionBeforeOpen(int newReadBufferSize, Type expectedException, bool throwAtOpen) { using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { try { com.ReadBufferSize = newReadBufferSize; if (throwAtOpen) com.Open(); if (null != expectedException) { Fail("Err_707278ahpa!!! expected exception {0} and nothing was thrown", expectedException); } } catch (Exception e) { if (null == expectedException) { Fail("Err_201890ioyun Expected no exception to be thrown and following was thrown \n{0}", e); } else if (e.GetType() != expectedException) { Fail("Err_545498ahpba!!! expected exception {0} and {1} was thrown", expectedException, e.GetType()); } } } } private void VerifyExceptionAfterOpen(int newReadBufferSize, Type expectedException) { using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { int originalReadBufferSize = com.ReadBufferSize; com.Open(); try { com.ReadBufferSize = newReadBufferSize; Fail("Err_561567anhbp!!! expected exception {0} and nothing was thrown", expectedException); } catch (Exception e) { if (e.GetType() != expectedException) { Fail("Err_21288ajpbam!!! expected exception {0} and {1} was thrown", expectedException, e.GetType()); } else if (originalReadBufferSize != com.ReadBufferSize) { Fail("Err_454987ahbopa!!! expected ReadBufferSize={0} and actual={1}", originalReadBufferSize, com.ReadBufferSize); } VerifyReadBufferSize(com); } } } private void VerifyReadBufferSize(int newReadBufferSize) { Debug.WriteLine("Verifying setting ReadBufferSize={0} BEFORE a call to Open() has been made", newReadBufferSize); VerifyReadBufferSizeBeforeOpen(newReadBufferSize); } private void VerifyReadBufferSizeBeforeOpen(int newReadBufferSize) { using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { byte[] xmitBytes = new byte[newReadBufferSize]; byte[] rcvBytes; SerialPortProperties serPortProp = new SerialPortProperties(); Random rndGen = new Random(-55); int newBytesToRead; for (int i = 0; i < xmitBytes.Length; i++) { xmitBytes[i] = (byte)rndGen.Next(0, 256); } if (newReadBufferSize < 4096) newBytesToRead = Math.Min(4096, xmitBytes.Length + (xmitBytes.Length / 2)); else newBytesToRead = Math.Min(newReadBufferSize, xmitBytes.Length); rcvBytes = new byte[newBytesToRead]; serPortProp.SetAllPropertiesToOpenDefaults(); serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); com1.ReadBufferSize = newReadBufferSize; serPortProp.SetProperty("ReadBufferSize", newReadBufferSize); com1.Open(); com2.Open(); int origBaudRate = com1.BaudRate; com2.BaudRate = 115200; com1.BaudRate = 115200; for (int j = 0; j < 1; j++) { com2.Write(xmitBytes, 0, xmitBytes.Length); com2.Write(xmitBytes, xmitBytes.Length / 2, xmitBytes.Length / 2); TCSupport.WaitForReadBufferToLoad(com1, newBytesToRead); Thread.Sleep(250); //This is to wait for the bytes to be received after the buffer is full serPortProp.SetProperty("BytesToRead", newBytesToRead); serPortProp.SetProperty("BaudRate", 115200); Debug.WriteLine("Verifying properties after bytes have been written"); serPortProp.VerifyPropertiesAndPrint(com1); com1.Read(rcvBytes, 0, newBytesToRead); Assert.Equal(xmitBytes.Take(newReadBufferSize), rcvBytes.Take(newReadBufferSize)); Debug.WriteLine("Verifying properties after bytes have been read"); serPortProp.SetProperty("BytesToRead", 0); serPortProp.VerifyPropertiesAndPrint(com1); } com2.Write(xmitBytes, 0, xmitBytes.Length); com2.Write(xmitBytes, xmitBytes.Length / 2, xmitBytes.Length / 2); TCSupport.WaitForReadBufferToLoad(com1, newBytesToRead); serPortProp.SetProperty("BytesToRead", newBytesToRead); Debug.WriteLine("Verifying properties after writing bytes"); serPortProp.VerifyPropertiesAndPrint(com1); com2.BaudRate = origBaudRate; com1.BaudRate = origBaudRate; } } private void VerifyReadBufferSize(SerialPort com1) { using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { int readBufferSize = com1.ReadBufferSize; byte[] xmitBytes = new byte[1024]; SerialPortProperties serPortProp = new SerialPortProperties(); Random rndGen = new Random(-55); int bytesToRead = readBufferSize < 4096 ? 4096 : readBufferSize; int origBaudRate = com1.BaudRate; int origReadTimeout = com1.ReadTimeout; int bytesRead; for (int i = 0; i < xmitBytes.Length; i++) { xmitBytes[i] = (byte)rndGen.Next(0, 256); } //bytesToRead = Math.Min(4096, xmitBytes.Length + (xmitBytes.Length / 2)); serPortProp.SetAllPropertiesToOpenDefaults(); serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); serPortProp.SetProperty("ReadBufferSize", readBufferSize); serPortProp.SetProperty("BaudRate", 115200); com2.Open(); com2.BaudRate = 115200; com1.BaudRate = 115200; for (int i = 0; i < bytesToRead / xmitBytes.Length; i++) { com2.Write(xmitBytes, 0, xmitBytes.Length); } com2.Write(xmitBytes, 0, xmitBytes.Length / 2); TCSupport.WaitForReadBufferToLoad(com1, bytesToRead); Thread.Sleep(250); //This is to wait for the bytes to be received after the buffer is full var rcvBytes = new byte[(int)(bytesToRead * 1.5)]; if (bytesToRead != (bytesRead = com1.Read(rcvBytes, 0, rcvBytes.Length))) { Fail("Err_2971ahius Did not read all expected bytes({0}) bytesRead={1} ReadBufferSize={2}", bytesToRead, bytesRead, com1.ReadBufferSize); } for (int i = 0; i < bytesToRead; i++) { if (rcvBytes[i] != xmitBytes[i % xmitBytes.Length]) { Fail("Err_70929apba!!!: Expected to read byte {0} actual={1} at {2}", xmitBytes[i % xmitBytes.Length], rcvBytes[i], i); } } serPortProp.SetProperty("BytesToRead", 0); serPortProp.VerifyPropertiesAndPrint(com1); com1.ReadTimeout = 250; // "Err_1707ahspb!!!: After reading all bytes from buffer ReadByte() did not timeout"); Assert.Throws<TimeoutException>(() => com1.ReadByte()); com1.ReadTimeout = origReadTimeout; } } #endregion } }
/****************************************************************************** * Spine Runtimes Software License * Version 2.1 * * Copyright (c) 2013, Esoteric Software * All rights reserved. * * You are granted a perpetual, non-exclusive, non-sublicensable and * non-transferable license to install, execute and perform the Spine Runtimes * Software (the "Software") solely for internal use. Without the written * permission of Esoteric Software (typically granted by licensing Spine), you * may not (a) modify, translate, adapt or otherwise create derivative works, * improvements of the Software or develop new applications using the Software * or (b) remove, delete, alter or obscure any trademarks or any copyright, * trademark, patent or other intellectual property or proprietary rights * notices on or in the Software, including any copy thereof. Redistributions * in binary or source form must include this license and terms. * * THIS SOFTWARE IS PROVIDED BY ESOTERIC SOFTWARE "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 ESOTERIC SOFTARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *****************************************************************************/ using System; using System.IO; using System.Collections.Generic; using UnityEngine; using Spine; /// <summary>Renders a skeleton.</summary> [ExecuteInEditMode, RequireComponent(typeof(MeshFilter), typeof(MeshRenderer))] public class SkeletonRenderer : MonoBehaviour { public bool valid; public Skeleton skeleton; public SkeletonDataAsset skeletonDataAsset; public String initialSkinName; public bool calculateNormals; public bool calculateTangents; public float zSpacing; private MeshFilter meshFilter; private Mesh mesh, mesh1, mesh2; private bool useMesh1; private float[] tempVertices = new float[8]; private int lastVertexCount; private Vector3[] vertices; private Color32[] colors; private Vector2[] uvs; private Material[] sharedMaterials = new Material[0]; private readonly List<Material> submeshMaterials = new List<Material>(); private readonly List<Submesh> submeshes = new List<Submesh>(); private readonly int[] quadTriangles = {0, 2, 1, 2, 3, 1}; public virtual void Reset () { if (meshFilter != null) meshFilter.sharedMesh = null; if (mesh != null) DestroyImmediate(mesh); if (renderer != null) renderer.sharedMaterial = null; mesh = null; mesh1 = null; mesh2 = null; lastVertexCount = 0; vertices = null; colors = null; uvs = null; sharedMaterials = new Material[0]; submeshMaterials.Clear(); submeshes.Clear(); skeleton = null; if (!skeletonDataAsset) { Debug.LogError("Missing SkeletonData asset.", this); valid = false; return; } valid = true; meshFilter = GetComponent<MeshFilter>(); mesh1 = newMesh(); mesh2 = newMesh(); vertices = new Vector3[0]; skeleton = new Skeleton(skeletonDataAsset.GetSkeletonData(false)); if (initialSkinName != null && initialSkinName.Length > 0 && initialSkinName != "default") skeleton.SetSkin(initialSkinName); } public void Awake () { Reset(); } private Mesh newMesh () { Mesh mesh = new Mesh(); mesh.name = "Skeleton Mesh"; mesh.hideFlags = HideFlags.HideAndDontSave; mesh.MarkDynamic(); return mesh; } public virtual void OnWillRenderObject () { if (!valid) return; // Count vertices and submesh triangles. int vertexCount = 0; int submeshTriangleCount = 0, submeshFirstVertex = 0, submeshStartSlotIndex = 0; Material lastMaterial = null; submeshMaterials.Clear(); List<Slot> drawOrder = skeleton.DrawOrder; int drawOrderCount = drawOrder.Count; for (int i = 0; i < drawOrderCount; i++) { Attachment attachment = drawOrder[i].attachment; object rendererObject; int attachmentVertexCount, attachmentTriangleCount; if (attachment is RegionAttachment) { rendererObject = ((RegionAttachment)attachment).RendererObject; attachmentVertexCount = 4; attachmentTriangleCount = 6; } else if (attachment is MeshAttachment) { MeshAttachment meshAttachment = (MeshAttachment)attachment; rendererObject = meshAttachment.RendererObject; attachmentVertexCount = meshAttachment.vertices.Length / 2; attachmentTriangleCount = meshAttachment.triangles.Length; } else if (attachment is SkinnedMeshAttachment) { SkinnedMeshAttachment meshAttachment = (SkinnedMeshAttachment)attachment; rendererObject = meshAttachment.RendererObject; attachmentVertexCount = meshAttachment.uvs.Length / 2; attachmentTriangleCount = meshAttachment.triangles.Length; } else continue; // Populate submesh when material changes. Material material = (Material)((AtlasRegion)rendererObject).page.rendererObject; if (lastMaterial != material && lastMaterial != null) { addSubmesh(lastMaterial, submeshStartSlotIndex, i, submeshTriangleCount, submeshFirstVertex, false); submeshTriangleCount = 0; submeshFirstVertex = vertexCount; submeshStartSlotIndex = i; } lastMaterial = material; submeshTriangleCount += attachmentTriangleCount; vertexCount += attachmentVertexCount; } addSubmesh(lastMaterial, submeshStartSlotIndex, drawOrderCount, submeshTriangleCount, submeshFirstVertex, true); // Set materials. if (submeshMaterials.Count == sharedMaterials.Length) submeshMaterials.CopyTo(sharedMaterials); else sharedMaterials = submeshMaterials.ToArray(); renderer.sharedMaterials = sharedMaterials; // Ensure mesh data is the right size. Vector3[] vertices = this.vertices; bool newTriangles = vertexCount > vertices.Length; if (newTriangles) { // Not enough vertices, increase size. this.vertices = vertices = new Vector3[vertexCount]; this.colors = new Color32[vertexCount]; this.uvs = new Vector2[vertexCount]; mesh1.Clear(); mesh2.Clear(); } else { // Too many vertices, zero the extra. Vector3 zero = Vector3.zero; for (int i = vertexCount, n = lastVertexCount; i < n; i++) vertices[i] = zero; } lastVertexCount = vertexCount; // Setup mesh. float[] tempVertices = this.tempVertices; Vector2[] uvs = this.uvs; Color32[] colors = this.colors; int vertexIndex = 0; Color32 color = new Color32(); float x = skeleton.x, y = skeleton.y, zSpacing = this.zSpacing; float a = skeleton.a * 255, r = skeleton.r, g = skeleton.g, b = skeleton.b; for (int i = 0; i < drawOrderCount; i++) { Slot slot = drawOrder[i]; Attachment attachment = slot.attachment; if (attachment is RegionAttachment) { RegionAttachment regionAttachment = (RegionAttachment)attachment; regionAttachment.ComputeWorldVertices(x, y, slot.bone, tempVertices); float z = i * zSpacing; vertices[vertexIndex] = new Vector3(tempVertices[RegionAttachment.X1], tempVertices[RegionAttachment.Y1], z); vertices[vertexIndex + 1] = new Vector3(tempVertices[RegionAttachment.X4], tempVertices[RegionAttachment.Y4], z); vertices[vertexIndex + 2] = new Vector3(tempVertices[RegionAttachment.X2], tempVertices[RegionAttachment.Y2], z); vertices[vertexIndex + 3] = new Vector3(tempVertices[RegionAttachment.X3], tempVertices[RegionAttachment.Y3], z); color.a = (byte)(a * slot.a * regionAttachment.a); color.r = (byte)(r * slot.r * regionAttachment.r * color.a); color.g = (byte)(g * slot.g * regionAttachment.g * color.a); color.b = (byte)(b * slot.b * regionAttachment.b * color.a); if (slot.data.additiveBlending) color.a = 0; colors[vertexIndex] = color; colors[vertexIndex + 1] = color; colors[vertexIndex + 2] = color; colors[vertexIndex + 3] = color; float[] regionUVs = regionAttachment.uvs; uvs[vertexIndex] = new Vector2(regionUVs[RegionAttachment.X1], regionUVs[RegionAttachment.Y1]); uvs[vertexIndex + 1] = new Vector2(regionUVs[RegionAttachment.X4], regionUVs[RegionAttachment.Y4]); uvs[vertexIndex + 2] = new Vector2(regionUVs[RegionAttachment.X2], regionUVs[RegionAttachment.Y2]); uvs[vertexIndex + 3] = new Vector2(regionUVs[RegionAttachment.X3], regionUVs[RegionAttachment.Y3]); vertexIndex += 4; } else if (attachment is MeshAttachment) { MeshAttachment meshAttachment = (MeshAttachment)attachment; int meshVertexCount = meshAttachment.vertices.Length; if (tempVertices.Length < meshVertexCount) tempVertices = new float[meshVertexCount]; meshAttachment.ComputeWorldVertices(x, y, slot, tempVertices); color.a = (byte)(a * slot.a * meshAttachment.a); color.r = (byte)(r * slot.r * meshAttachment.r * color.a); color.g = (byte)(g * slot.g * meshAttachment.g * color.a); color.b = (byte)(b * slot.b * meshAttachment.b * color.a); if (slot.data.additiveBlending) color.a = 0; float[] meshUVs = meshAttachment.uvs; float z = i * zSpacing; for (int ii = 0; ii < meshVertexCount; ii += 2, vertexIndex++) { vertices[vertexIndex] = new Vector3(tempVertices[ii], tempVertices[ii + 1], z); colors[vertexIndex] = color; uvs[vertexIndex] = new Vector2(meshUVs[ii], meshUVs[ii + 1]); } } else if (attachment is SkinnedMeshAttachment) { SkinnedMeshAttachment meshAttachment = (SkinnedMeshAttachment)attachment; int meshVertexCount = meshAttachment.uvs.Length; if (tempVertices.Length < meshVertexCount) tempVertices = new float[meshVertexCount]; meshAttachment.ComputeWorldVertices(x, y, slot, tempVertices); color.a = (byte)(a * slot.a * meshAttachment.a); color.r = (byte)(r * slot.r * meshAttachment.r * color.a); color.g = (byte)(g * slot.g * meshAttachment.g * color.a); color.b = (byte)(b * slot.b * meshAttachment.b * color.a); if (slot.data.additiveBlending) color.a = 0; float[] meshUVs = meshAttachment.uvs; float z = i * zSpacing; for (int ii = 0; ii < meshVertexCount; ii += 2, vertexIndex++) { vertices[vertexIndex] = new Vector3(tempVertices[ii], tempVertices[ii + 1], z); colors[vertexIndex] = color; uvs[vertexIndex] = new Vector2(meshUVs[ii], meshUVs[ii + 1]); } } } // Double buffer mesh. Mesh mesh = useMesh1 ? mesh1 : mesh2; meshFilter.sharedMesh = mesh; mesh.vertices = vertices; mesh.colors32 = colors; mesh.uv = uvs; int submeshCount = submeshMaterials.Count; mesh.subMeshCount = submeshCount; for (int i = 0; i < submeshCount; ++i) mesh.SetTriangles(submeshes[i].triangles, i); mesh.RecalculateBounds(); if (newTriangles && calculateNormals) { Vector3[] normals = new Vector3[vertexCount]; Vector3 normal = new Vector3(0, 0, -1); for (int i = 0; i < vertexCount; i++) normals[i] = normal; (useMesh1 ? mesh2 : mesh1).vertices = vertices; // Set other mesh vertices. mesh1.normals = normals; mesh2.normals = normals; if (calculateTangents) { Vector4[] tangents = new Vector4[vertexCount]; Vector3 tangent = new Vector3(0, 0, 1); for (int i = 0; i < vertexCount; i++) tangents[i] = tangent; mesh1.tangents = tangents; mesh2.tangents = tangents; } } useMesh1 = !useMesh1; } /** Stores vertices and triangles for a single material. */ private void addSubmesh (Material material, int startSlot, int endSlot, int triangleCount, int firstVertex, bool lastSubmesh) { int submeshIndex = submeshMaterials.Count; submeshMaterials.Add(material); if (submeshes.Count <= submeshIndex) submeshes.Add(new Submesh()); Submesh submesh = submeshes[submeshIndex]; int[] triangles = submesh.triangles; int trianglesCapacity = triangles.Length; if (lastSubmesh && trianglesCapacity > triangleCount) { // Last submesh may have more triangles than required, so zero triangles to the end. for (int i = triangleCount; i < trianglesCapacity; i++) triangles[i] = 0; submesh.triangleCount = triangleCount; } else if (trianglesCapacity != triangleCount) { // Reallocate triangles when not the exact size needed. submesh.triangles = triangles = new int[triangleCount]; submesh.triangleCount = 0; } List<Slot> drawOrder = skeleton.DrawOrder; for (int i = startSlot, triangleIndex = 0; i < endSlot; i++) { Attachment attachment = drawOrder[i].attachment; int[] attachmentTriangles; int attachmentVertexCount; if (attachment is RegionAttachment) { attachmentVertexCount = 4; attachmentTriangles = quadTriangles; } else if (attachment is MeshAttachment) { MeshAttachment meshAttachment = (MeshAttachment)attachment; attachmentVertexCount = meshAttachment.vertices.Length / 2; attachmentTriangles = meshAttachment.triangles; } else if (attachment is SkinnedMeshAttachment) { SkinnedMeshAttachment meshAttachment = (SkinnedMeshAttachment)attachment; attachmentVertexCount = meshAttachment.uvs.Length / 2; attachmentTriangles = meshAttachment.triangles; } else continue; for (int ii = 0, nn = attachmentTriangles.Length; ii < nn; ii++, triangleIndex++) triangles[triangleIndex] = firstVertex + attachmentTriangles[ii]; firstVertex += attachmentVertexCount; } } #if UNITY_EDITOR void OnDrawGizmos() { // Make selection easier by drawing a clear gizmo over the skeleton. if (vertices == null) return; Vector3 gizmosCenter = new Vector3(); Vector3 gizmosSize = new Vector3(); Vector3 min = new Vector3(float.MaxValue, float.MaxValue, 0f); Vector3 max = new Vector3(float.MinValue, float.MinValue, 0f); foreach (Vector3 vert in vertices) { min = Vector3.Min (min, vert); max = Vector3.Max (max, vert); } float width = max.x - min.x; float height = max.y - min.y; gizmosCenter = new Vector3(min.x + (width / 2f), min.y + (height / 2f), 0f); gizmosSize = new Vector3(width, height, 1f); Gizmos.color = Color.clear; Gizmos.matrix = transform.localToWorldMatrix; Gizmos.DrawCube(gizmosCenter, gizmosSize); } #endif } class Submesh { public int[] triangles = new int[0]; public int triangleCount; }
// 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.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Diagnostics.Contracts; using System.Collections.Generic; namespace System.Globalization { // // List of calendar data // Note the we cache overrides. // Note that localized names (resource names) aren't available from here. // // NOTE: Calendars depend on the locale name that creates it. Only a few // properties are available without locales using CalendarData.GetCalendar(CalendarData) internal partial class CalendarData { // Max calendars internal const int MAX_CALENDARS = 23; // Identity internal String sNativeName; // Calendar Name for the locale // Formats internal String[] saShortDates; // Short Data format, default first internal String[] saYearMonths; // Year/Month Data format, default first internal String[] saLongDates; // Long Data format, default first internal String sMonthDay; // Month/Day format // Calendar Parts Names internal String[] saEraNames; // Names of Eras internal String[] saAbbrevEraNames; // Abbreviated Era Names internal String[] saAbbrevEnglishEraNames; // Abbreviated Era Names in English internal String[] saDayNames; // Day Names, null to use locale data, starts on Sunday internal String[] saAbbrevDayNames; // Abbrev Day Names, null to use locale data, starts on Sunday internal String[] saSuperShortDayNames; // Super short Day of week names internal String[] saMonthNames; // Month Names (13) internal String[] saAbbrevMonthNames; // Abbrev Month Names (13) internal String[] saMonthGenitiveNames; // Genitive Month Names (13) internal String[] saAbbrevMonthGenitiveNames; // Genitive Abbrev Month Names (13) internal String[] saLeapYearMonthNames; // Multiple strings for the month names in a leap year. // Integers at end to make marshaller happier internal int iTwoDigitYearMax = 2029; // Max 2 digit year (for Y2K bug data entry) internal int iCurrentEra = 0; // current era # (usually 1) // Use overrides? internal bool bUseUserOverrides; // True if we want user overrides. // Static invariant for the invariant locale internal static CalendarData Invariant; // Private constructor private CalendarData() { } // Invariant constructor static CalendarData() { // Set our default/gregorian US calendar data // Calendar IDs are 1-based, arrays are 0 based. CalendarData invariant = new CalendarData(); // Set default data for calendar // Note that we don't load resources since this IS NOT supposed to change (by definition) invariant.sNativeName = "Gregorian Calendar"; // Calendar Name // Year invariant.iTwoDigitYearMax = 2029; // Max 2 digit year (for Y2K bug data entry) invariant.iCurrentEra = 1; // Current era # // Formats invariant.saShortDates = new String[] { "MM/dd/yyyy", "yyyy-MM-dd" }; // short date format invariant.saLongDates = new String[] { "dddd, dd MMMM yyyy" }; // long date format invariant.saYearMonths = new String[] { "yyyy MMMM" }; // year month format invariant.sMonthDay = "MMMM dd"; // Month day pattern // Calendar Parts Names invariant.saEraNames = new String[] { "A.D." }; // Era names invariant.saAbbrevEraNames = new String[] { "AD" }; // Abbreviated Era names invariant.saAbbrevEnglishEraNames = new String[] { "AD" }; // Abbreviated era names in English invariant.saDayNames = new String[] { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };// day names invariant.saAbbrevDayNames = new String[] { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" }; // abbreviated day names invariant.saSuperShortDayNames = new String[] { "Su", "Mo", "Tu", "We", "Th", "Fr", "Sa" }; // The super short day names invariant.saMonthNames = new String[] { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December", String.Empty}; // month names invariant.saAbbrevMonthNames = new String[] { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", String.Empty}; // abbreviated month names invariant.saMonthGenitiveNames = invariant.saMonthNames; // Genitive month names (same as month names for invariant) invariant.saAbbrevMonthGenitiveNames = invariant.saAbbrevMonthNames; // Abbreviated genitive month names (same as abbrev month names for invariant) invariant.saLeapYearMonthNames = invariant.saMonthNames; // leap year month names are unused in Gregorian English (invariant) invariant.bUseUserOverrides = false; // Calendar was built, go ahead and assign it... Invariant = invariant; } // // Get a bunch of data for a calendar // internal CalendarData(String localeName, CalendarId calendarId, bool bUseUserOverrides) { this.bUseUserOverrides = bUseUserOverrides; if (!LoadCalendarDataFromSystem(localeName, calendarId)) { Contract.Assert(false, "[CalendarData] LoadCalendarDataFromSystem call isn't expected to fail for calendar " + calendarId + " locale " + localeName); // Something failed, try invariant for missing parts // This is really not good, but we don't want the callers to crash. if (this.sNativeName == null) this.sNativeName = String.Empty; // Calendar Name for the locale. // Formats if (this.saShortDates == null) this.saShortDates = Invariant.saShortDates; // Short Data format, default first if (this.saYearMonths == null) this.saYearMonths = Invariant.saYearMonths; // Year/Month Data format, default first if (this.saLongDates == null) this.saLongDates = Invariant.saLongDates; // Long Data format, default first if (this.sMonthDay == null) this.sMonthDay = Invariant.sMonthDay; // Month/Day format // Calendar Parts Names if (this.saEraNames == null) this.saEraNames = Invariant.saEraNames; // Names of Eras if (this.saAbbrevEraNames == null) this.saAbbrevEraNames = Invariant.saAbbrevEraNames; // Abbreviated Era Names if (this.saAbbrevEnglishEraNames == null) this.saAbbrevEnglishEraNames = Invariant.saAbbrevEnglishEraNames; // Abbreviated Era Names in English if (this.saDayNames == null) this.saDayNames = Invariant.saDayNames; // Day Names, null to use locale data, starts on Sunday if (this.saAbbrevDayNames == null) this.saAbbrevDayNames = Invariant.saAbbrevDayNames; // Abbrev Day Names, null to use locale data, starts on Sunday if (this.saSuperShortDayNames == null) this.saSuperShortDayNames = Invariant.saSuperShortDayNames; // Super short Day of week names if (this.saMonthNames == null) this.saMonthNames = Invariant.saMonthNames; // Month Names (13) if (this.saAbbrevMonthNames == null) this.saAbbrevMonthNames = Invariant.saAbbrevMonthNames; // Abbrev Month Names (13) // Genitive and Leap names can follow the fallback below } if (calendarId == CalendarId.TAIWAN) { if (SystemSupportsTaiwaneseCalendar()) { // We got the month/day names from the OS (same as gregorian), but the native name is wrong this.sNativeName = "\x4e2d\x83ef\x6c11\x570b\x66c6"; } else { this.sNativeName = String.Empty; } } // Check for null genitive names (in case unmanaged side skips it for non-gregorian calendars, etc) if (this.saMonthGenitiveNames == null || this.saMonthGenitiveNames.Length == 0 || String.IsNullOrEmpty(this.saMonthGenitiveNames[0])) this.saMonthGenitiveNames = this.saMonthNames; // Genitive month names (same as month names for invariant) if (this.saAbbrevMonthGenitiveNames == null || this.saAbbrevMonthGenitiveNames.Length == 0 || String.IsNullOrEmpty(this.saAbbrevMonthGenitiveNames[0])) this.saAbbrevMonthGenitiveNames = this.saAbbrevMonthNames; // Abbreviated genitive month names (same as abbrev month names for invariant) if (this.saLeapYearMonthNames == null || this.saLeapYearMonthNames.Length == 0 || String.IsNullOrEmpty(this.saLeapYearMonthNames[0])) this.saLeapYearMonthNames = this.saMonthNames; InitializeEraNames(localeName, calendarId); InitializeAbbreviatedEraNames(localeName, calendarId); // Abbreviated English Era Names are only used for the Japanese calendar. if (calendarId == CalendarId.JAPAN) { this.saAbbrevEnglishEraNames = JapaneseCalendar.EnglishEraNames(); } else { // For all others just use the an empty string (doesn't matter we'll never ask for it for other calendars) this.saAbbrevEnglishEraNames = new String[] { "" }; } // Japanese is the only thing with > 1 era. Its current era # is how many ever // eras are in the array. (And the others all have 1 string in the array) this.iCurrentEra = this.saEraNames.Length; } private void InitializeEraNames(string localeName, CalendarId calendarId) { // Note that the saEraNames only include "A.D." We don't have localized names for other calendars available from windows switch (calendarId) { // For Localized Gregorian we really expect the data from the OS. case CalendarId.GREGORIAN: // Fallback for CoreCLR < Win7 or culture.dll missing if (this.saEraNames == null || this.saEraNames.Length == 0 || String.IsNullOrEmpty(this.saEraNames[0])) { this.saEraNames = new String[] { "A.D." }; } break; // The rest of the calendars have constant data, so we'll just use that case CalendarId.GREGORIAN_US: case CalendarId.JULIAN: this.saEraNames = new String[] { "A.D." }; break; case CalendarId.HEBREW: this.saEraNames = new String[] { "C.E." }; break; case CalendarId.HIJRI: case CalendarId.UMALQURA: if (localeName == "dv-MV") { // Special case for Divehi this.saEraNames = new String[] { "\x0780\x07a8\x0796\x07b0\x0783\x07a9" }; } else { this.saEraNames = new String[] { "\x0628\x0639\x062F \x0627\x0644\x0647\x062C\x0631\x0629" }; } break; case CalendarId.GREGORIAN_ARABIC: case CalendarId.GREGORIAN_XLIT_ENGLISH: case CalendarId.GREGORIAN_XLIT_FRENCH: // These are all the same: this.saEraNames = new String[] { "\x0645" }; break; case CalendarId.GREGORIAN_ME_FRENCH: this.saEraNames = new String[] { "ap. J.-C." }; break; case CalendarId.TAIWAN: if (SystemSupportsTaiwaneseCalendar()) { this.saEraNames = new String[] { "\x4e2d\x83ef\x6c11\x570b" }; } else { this.saEraNames = new String[] { String.Empty }; } break; case CalendarId.KOREA: this.saEraNames = new String[] { "\xb2e8\xae30" }; break; case CalendarId.THAI: this.saEraNames = new String[] { "\x0e1e\x002e\x0e28\x002e" }; break; case CalendarId.JAPAN: case CalendarId.JAPANESELUNISOLAR: this.saEraNames = JapaneseCalendar.EraNames(); break; default: // Most calendars are just "A.D." this.saEraNames = Invariant.saEraNames; break; } } private void InitializeAbbreviatedEraNames(string localeName, CalendarId calendarId) { // Note that the saAbbrevEraNames only include "AD" We don't have localized names for other calendars available from windows switch (calendarId) { // For Localized Gregorian we really expect the data from the OS. case CalendarId.GREGORIAN: // Fallback for CoreCLR < Win7 or culture.dll missing if (this.saAbbrevEraNames == null || this.saAbbrevEraNames.Length == 0 || String.IsNullOrEmpty(this.saAbbrevEraNames[0])) { this.saAbbrevEraNames = new String[] { "AD" }; } break; // The rest of the calendars have constant data, so we'll just use that case CalendarId.GREGORIAN_US: case CalendarId.JULIAN: this.saAbbrevEraNames = new String[] { "AD" }; break; case CalendarId.JAPAN: case CalendarId.JAPANESELUNISOLAR: this.saAbbrevEraNames = JapaneseCalendar.AbbrevEraNames(); break; case CalendarId.HIJRI: case CalendarId.UMALQURA: if (localeName == "dv-MV") { // Special case for Divehi this.saAbbrevEraNames = new String[] { "\x0780\x002e" }; } else { this.saAbbrevEraNames = new String[] { "\x0647\x0640" }; } break; case CalendarId.TAIWAN: // Get era name and abbreviate it this.saAbbrevEraNames = new String[1]; if (this.saEraNames[0].Length == 4) { this.saAbbrevEraNames[0] = this.saEraNames[0].Substring(2, 2); } else { this.saAbbrevEraNames[0] = this.saEraNames[0]; } break; default: // Most calendars just use the full name this.saAbbrevEraNames = this.saEraNames; break; } } internal static CalendarData GetCalendarData(CalendarId calendarId) { // // Get a calendar. // Unfortunately we depend on the locale in the OS, so we need a locale // no matter what. So just get the appropriate calendar from the // appropriate locale here // // Get a culture name // TODO: NLS Arrowhead Arrowhead - note that this doesn't handle the new calendars (lunisolar, etc) String culture = CalendarIdToCultureName(calendarId); // Return our calendar return CultureInfo.GetCultureInfo(culture).m_cultureData.GetCalendar(calendarId); } private static String CalendarIdToCultureName(CalendarId calendarId) { switch (calendarId) { case CalendarId.GREGORIAN_US: return "fa-IR"; // "fa-IR" Iran case CalendarId.JAPAN: return "ja-JP"; // "ja-JP" Japan case CalendarId.TAIWAN: return "zh-TW"; // zh-TW Taiwan case CalendarId.KOREA: return "ko-KR"; // "ko-KR" Korea case CalendarId.HIJRI: case CalendarId.GREGORIAN_ARABIC: case CalendarId.UMALQURA: return "ar-SA"; // "ar-SA" Saudi Arabia case CalendarId.THAI: return "th-TH"; // "th-TH" Thailand case CalendarId.HEBREW: return "he-IL"; // "he-IL" Israel case CalendarId.GREGORIAN_ME_FRENCH: return "ar-DZ"; // "ar-DZ" Algeria case CalendarId.GREGORIAN_XLIT_ENGLISH: case CalendarId.GREGORIAN_XLIT_FRENCH: return "ar-IQ"; // "ar-IQ"; Iraq default: // Default to gregorian en-US break; } return "en-US"; } } }
/************************************************************************* Copyright (c) Sergey Bochkanov (ALGLIB project). >>> SOURCE LICENSE >>> 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 (www.fsf.org); 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. A copy of the GNU General Public License is available at http://www.fsf.org/licensing/licenses >>> END OF LICENSE >>> *************************************************************************/ #pragma warning disable 162 #pragma warning disable 219 using System; public partial class alglib { /************************************************************************* *************************************************************************/ public class odesolverstate : alglibobject { // // Public declarations // public bool needdy { get { return _innerobj.needdy; } set { _innerobj.needdy = value; } } public double[] y { get { return _innerobj.y; } } public double[] dy { get { return _innerobj.dy; } } public double x { get { return _innerobj.x; } set { _innerobj.x = value; } } public odesolverstate() { _innerobj = new odesolver.odesolverstate(); } // // Although some of declarations below are public, you should not use them // They are intended for internal use only // private odesolver.odesolverstate _innerobj; public odesolver.odesolverstate innerobj { get { return _innerobj; } } public odesolverstate(odesolver.odesolverstate obj) { _innerobj = obj; } } /************************************************************************* *************************************************************************/ public class odesolverreport : alglibobject { // // Public declarations // public int nfev { get { return _innerobj.nfev; } set { _innerobj.nfev = value; } } public int terminationtype { get { return _innerobj.terminationtype; } set { _innerobj.terminationtype = value; } } public odesolverreport() { _innerobj = new odesolver.odesolverreport(); } // // Although some of declarations below are public, you should not use them // They are intended for internal use only // private odesolver.odesolverreport _innerobj; public odesolver.odesolverreport innerobj { get { return _innerobj; } } public odesolverreport(odesolver.odesolverreport obj) { _innerobj = obj; } } /************************************************************************* Cash-Karp adaptive ODE solver. This subroutine solves ODE Y'=f(Y,x) with initial conditions Y(xs)=Ys (here Y may be single variable or vector of N variables). INPUT PARAMETERS: Y - initial conditions, array[0..N-1]. contains values of Y[] at X[0] N - system size X - points at which Y should be tabulated, array[0..M-1] integrations starts at X[0], ends at X[M-1], intermediate values at X[i] are returned too. SHOULD BE ORDERED BY ASCENDING OR BY DESCENDING!!!! M - number of intermediate points + first point + last point: * M>2 means that you need both Y(X[M-1]) and M-2 values at intermediate points * M=2 means that you want just to integrate from X[0] to X[1] and don't interested in intermediate values. * M=1 means that you don't want to integrate :) it is degenerate case, but it will be handled correctly. * M<1 means error Eps - tolerance (absolute/relative error on each step will be less than Eps). When passing: * Eps>0, it means desired ABSOLUTE error * Eps<0, it means desired RELATIVE error. Relative errors are calculated with respect to maximum values of Y seen so far. Be careful to use this criterion when starting from Y[] that are close to zero. H - initial step lenth, it will be adjusted automatically after the first step. If H=0, step will be selected automatically (usualy it will be equal to 0.001 of min(x[i]-x[j])). OUTPUT PARAMETERS State - structure which stores algorithm state between subsequent calls of OdeSolverIteration. Used for reverse communication. This structure should be passed to the OdeSolverIteration subroutine. SEE ALSO AutoGKSmoothW, AutoGKSingular, AutoGKIteration, AutoGKResults. -- ALGLIB -- Copyright 01.09.2009 by Bochkanov Sergey *************************************************************************/ public static void odesolverrkck(double[] y, int n, double[] x, int m, double eps, double h, out odesolverstate state) { state = new odesolverstate(); odesolver.odesolverrkck(y, n, x, m, eps, h, state.innerobj); return; } public static void odesolverrkck(double[] y, double[] x, double eps, double h, out odesolverstate state) { int n; int m; state = new odesolverstate(); n = ap.len(y); m = ap.len(x); odesolver.odesolverrkck(y, n, x, m, eps, h, state.innerobj); return; } /************************************************************************* This function provides reverse communication interface Reverse communication interface is not documented or recommended to use. See below for functions which provide better documented API *************************************************************************/ public static bool odesolveriteration(odesolverstate state) { bool result = odesolver.odesolveriteration(state.innerobj); return result; } /************************************************************************* This function is used to launcn iterations of ODE solver It accepts following parameters: diff - callback which calculates dy/dx for given y and x obj - optional object which is passed to diff; can be NULL -- ALGLIB -- Copyright 01.09.2009 by Bochkanov Sergey *************************************************************************/ public static void odesolversolve(odesolverstate state, ndimensional_ode_rp diff, object obj) { if( diff==null ) throw new alglibexception("ALGLIB: error in 'odesolversolve()' (diff is null)"); while( alglib.odesolveriteration(state) ) { if( state.needdy ) { diff(state.innerobj.y, state.innerobj.x, state.innerobj.dy, obj); continue; } throw new alglibexception("ALGLIB: unexpected error in 'odesolversolve'"); } } /************************************************************************* ODE solver results Called after OdeSolverIteration returned False. INPUT PARAMETERS: State - algorithm state (used by OdeSolverIteration). OUTPUT PARAMETERS: M - number of tabulated values, M>=1 XTbl - array[0..M-1], values of X YTbl - array[0..M-1,0..N-1], values of Y in X[i] Rep - solver report: * Rep.TerminationType completetion code: * -2 X is not ordered by ascending/descending or there are non-distinct X[], i.e. X[i]=X[i+1] * -1 incorrect parameters were specified * 1 task has been solved * Rep.NFEV contains number of function calculations -- ALGLIB -- Copyright 01.09.2009 by Bochkanov Sergey *************************************************************************/ public static void odesolverresults(odesolverstate state, out int m, out double[] xtbl, out double[,] ytbl, out odesolverreport rep) { m = 0; xtbl = new double[0]; ytbl = new double[0,0]; rep = new odesolverreport(); odesolver.odesolverresults(state.innerobj, ref m, ref xtbl, ref ytbl, rep.innerobj); return; } } public partial class alglib { public class odesolver { public class odesolverstate : apobject { public int n; public int m; public double xscale; public double h; public double eps; public bool fraceps; public double[] yc; public double[] escale; public double[] xg; public int solvertype; public bool needdy; public double x; public double[] y; public double[] dy; public double[,] ytbl; public int repterminationtype; public int repnfev; public double[] yn; public double[] yns; public double[] rka; public double[] rkc; public double[] rkcs; public double[,] rkb; public double[,] rkk; public rcommstate rstate; public odesolverstate() { init(); } public override void init() { yc = new double[0]; escale = new double[0]; xg = new double[0]; y = new double[0]; dy = new double[0]; ytbl = new double[0,0]; yn = new double[0]; yns = new double[0]; rka = new double[0]; rkc = new double[0]; rkcs = new double[0]; rkb = new double[0,0]; rkk = new double[0,0]; rstate = new rcommstate(); } public override alglib.apobject make_copy() { odesolverstate _result = new odesolverstate(); _result.n = n; _result.m = m; _result.xscale = xscale; _result.h = h; _result.eps = eps; _result.fraceps = fraceps; _result.yc = (double[])yc.Clone(); _result.escale = (double[])escale.Clone(); _result.xg = (double[])xg.Clone(); _result.solvertype = solvertype; _result.needdy = needdy; _result.x = x; _result.y = (double[])y.Clone(); _result.dy = (double[])dy.Clone(); _result.ytbl = (double[,])ytbl.Clone(); _result.repterminationtype = repterminationtype; _result.repnfev = repnfev; _result.yn = (double[])yn.Clone(); _result.yns = (double[])yns.Clone(); _result.rka = (double[])rka.Clone(); _result.rkc = (double[])rkc.Clone(); _result.rkcs = (double[])rkcs.Clone(); _result.rkb = (double[,])rkb.Clone(); _result.rkk = (double[,])rkk.Clone(); _result.rstate = (rcommstate)rstate.make_copy(); return _result; } }; public class odesolverreport : apobject { public int nfev; public int terminationtype; public odesolverreport() { init(); } public override void init() { } public override alglib.apobject make_copy() { odesolverreport _result = new odesolverreport(); _result.nfev = nfev; _result.terminationtype = terminationtype; return _result; } }; public const double odesolvermaxgrow = 3.0; public const double odesolvermaxshrink = 10.0; /************************************************************************* Cash-Karp adaptive ODE solver. This subroutine solves ODE Y'=f(Y,x) with initial conditions Y(xs)=Ys (here Y may be single variable or vector of N variables). INPUT PARAMETERS: Y - initial conditions, array[0..N-1]. contains values of Y[] at X[0] N - system size X - points at which Y should be tabulated, array[0..M-1] integrations starts at X[0], ends at X[M-1], intermediate values at X[i] are returned too. SHOULD BE ORDERED BY ASCENDING OR BY DESCENDING!!!! M - number of intermediate points + first point + last point: * M>2 means that you need both Y(X[M-1]) and M-2 values at intermediate points * M=2 means that you want just to integrate from X[0] to X[1] and don't interested in intermediate values. * M=1 means that you don't want to integrate :) it is degenerate case, but it will be handled correctly. * M<1 means error Eps - tolerance (absolute/relative error on each step will be less than Eps). When passing: * Eps>0, it means desired ABSOLUTE error * Eps<0, it means desired RELATIVE error. Relative errors are calculated with respect to maximum values of Y seen so far. Be careful to use this criterion when starting from Y[] that are close to zero. H - initial step lenth, it will be adjusted automatically after the first step. If H=0, step will be selected automatically (usualy it will be equal to 0.001 of min(x[i]-x[j])). OUTPUT PARAMETERS State - structure which stores algorithm state between subsequent calls of OdeSolverIteration. Used for reverse communication. This structure should be passed to the OdeSolverIteration subroutine. SEE ALSO AutoGKSmoothW, AutoGKSingular, AutoGKIteration, AutoGKResults. -- ALGLIB -- Copyright 01.09.2009 by Bochkanov Sergey *************************************************************************/ public static void odesolverrkck(double[] y, int n, double[] x, int m, double eps, double h, odesolverstate state) { alglib.ap.assert(n>=1, "ODESolverRKCK: N<1!"); alglib.ap.assert(m>=1, "ODESolverRKCK: M<1!"); alglib.ap.assert(alglib.ap.len(y)>=n, "ODESolverRKCK: Length(Y)<N!"); alglib.ap.assert(alglib.ap.len(x)>=m, "ODESolverRKCK: Length(X)<M!"); alglib.ap.assert(apserv.isfinitevector(y, n), "ODESolverRKCK: Y contains infinite or NaN values!"); alglib.ap.assert(apserv.isfinitevector(x, m), "ODESolverRKCK: Y contains infinite or NaN values!"); alglib.ap.assert(math.isfinite(eps), "ODESolverRKCK: Eps is not finite!"); alglib.ap.assert((double)(eps)!=(double)(0), "ODESolverRKCK: Eps is zero!"); alglib.ap.assert(math.isfinite(h), "ODESolverRKCK: H is not finite!"); odesolverinit(0, y, n, x, m, eps, h, state); } /************************************************************************* -- ALGLIB -- Copyright 01.09.2009 by Bochkanov Sergey *************************************************************************/ public static bool odesolveriteration(odesolverstate state) { bool result = new bool(); int n = 0; int m = 0; int i = 0; int j = 0; int k = 0; double xc = 0; double v = 0; double h = 0; double h2 = 0; bool gridpoint = new bool(); double err = 0; double maxgrowpow = 0; int klimit = 0; int i_ = 0; // // Reverse communication preparations // I know it looks ugly, but it works the same way // anywhere from C++ to Python. // // This code initializes locals by: // * random values determined during code // generation - on first subroutine call // * values from previous call - on subsequent calls // if( state.rstate.stage>=0 ) { n = state.rstate.ia[0]; m = state.rstate.ia[1]; i = state.rstate.ia[2]; j = state.rstate.ia[3]; k = state.rstate.ia[4]; klimit = state.rstate.ia[5]; gridpoint = state.rstate.ba[0]; xc = state.rstate.ra[0]; v = state.rstate.ra[1]; h = state.rstate.ra[2]; h2 = state.rstate.ra[3]; err = state.rstate.ra[4]; maxgrowpow = state.rstate.ra[5]; } else { n = -983; m = -989; i = -834; j = 900; k = -287; klimit = 364; gridpoint = false; xc = -338; v = -686; h = 912; h2 = 585; err = 497; maxgrowpow = -271; } if( state.rstate.stage==0 ) { goto lbl_0; } // // Routine body // // // prepare // if( state.repterminationtype!=0 ) { result = false; return result; } n = state.n; m = state.m; h = state.h; maxgrowpow = Math.Pow(odesolvermaxgrow, 5); state.repnfev = 0; // // some preliminary checks for internal errors // after this we assume that H>0 and M>1 // alglib.ap.assert((double)(state.h)>(double)(0), "ODESolver: internal error"); alglib.ap.assert(m>1, "ODESolverIteration: internal error"); // // choose solver // if( state.solvertype!=0 ) { goto lbl_1; } // // Cask-Karp solver // Prepare coefficients table. // Check it for errors // state.rka = new double[6]; state.rka[0] = 0; state.rka[1] = (double)1/(double)5; state.rka[2] = (double)3/(double)10; state.rka[3] = (double)3/(double)5; state.rka[4] = 1; state.rka[5] = (double)7/(double)8; state.rkb = new double[6, 5]; state.rkb[1,0] = (double)1/(double)5; state.rkb[2,0] = (double)3/(double)40; state.rkb[2,1] = (double)9/(double)40; state.rkb[3,0] = (double)3/(double)10; state.rkb[3,1] = -((double)9/(double)10); state.rkb[3,2] = (double)6/(double)5; state.rkb[4,0] = -((double)11/(double)54); state.rkb[4,1] = (double)5/(double)2; state.rkb[4,2] = -((double)70/(double)27); state.rkb[4,3] = (double)35/(double)27; state.rkb[5,0] = (double)1631/(double)55296; state.rkb[5,1] = (double)175/(double)512; state.rkb[5,2] = (double)575/(double)13824; state.rkb[5,3] = (double)44275/(double)110592; state.rkb[5,4] = (double)253/(double)4096; state.rkc = new double[6]; state.rkc[0] = (double)37/(double)378; state.rkc[1] = 0; state.rkc[2] = (double)250/(double)621; state.rkc[3] = (double)125/(double)594; state.rkc[4] = 0; state.rkc[5] = (double)512/(double)1771; state.rkcs = new double[6]; state.rkcs[0] = (double)2825/(double)27648; state.rkcs[1] = 0; state.rkcs[2] = (double)18575/(double)48384; state.rkcs[3] = (double)13525/(double)55296; state.rkcs[4] = (double)277/(double)14336; state.rkcs[5] = (double)1/(double)4; state.rkk = new double[6, n]; // // Main cycle consists of two iterations: // * outer where we travel from X[i-1] to X[i] // * inner where we travel inside [X[i-1],X[i]] // state.ytbl = new double[m, n]; state.escale = new double[n]; state.yn = new double[n]; state.yns = new double[n]; xc = state.xg[0]; for(i_=0; i_<=n-1;i_++) { state.ytbl[0,i_] = state.yc[i_]; } for(j=0; j<=n-1; j++) { state.escale[j] = 0; } i = 1; lbl_3: if( i>m-1 ) { goto lbl_5; } // // begin inner iteration // lbl_6: if( false ) { goto lbl_7; } // // truncate step if needed (beyond right boundary). // determine should we store X or not // if( (double)(xc+h)>=(double)(state.xg[i]) ) { h = state.xg[i]-xc; gridpoint = true; } else { gridpoint = false; } // // Update error scale maximums // // These maximums are initialized by zeros, // then updated every iterations. // for(j=0; j<=n-1; j++) { state.escale[j] = Math.Max(state.escale[j], Math.Abs(state.yc[j])); } // // make one step: // 1. calculate all info needed to do step // 2. update errors scale maximums using values/derivatives // obtained during (1) // // Take into account that we use scaling of X to reduce task // to the form where x[0] < x[1] < ... < x[n-1]. So X is // replaced by x=xscale*t, and dy/dx=f(y,x) is replaced // by dy/dt=xscale*f(y,xscale*t). // for(i_=0; i_<=n-1;i_++) { state.yn[i_] = state.yc[i_]; } for(i_=0; i_<=n-1;i_++) { state.yns[i_] = state.yc[i_]; } k = 0; lbl_8: if( k>5 ) { goto lbl_10; } // // prepare data for the next update of YN/YNS // state.x = state.xscale*(xc+state.rka[k]*h); for(i_=0; i_<=n-1;i_++) { state.y[i_] = state.yc[i_]; } for(j=0; j<=k-1; j++) { v = state.rkb[k,j]; for(i_=0; i_<=n-1;i_++) { state.y[i_] = state.y[i_] + v*state.rkk[j,i_]; } } state.needdy = true; state.rstate.stage = 0; goto lbl_rcomm; lbl_0: state.needdy = false; state.repnfev = state.repnfev+1; v = h*state.xscale; for(i_=0; i_<=n-1;i_++) { state.rkk[k,i_] = v*state.dy[i_]; } // // update YN/YNS // v = state.rkc[k]; for(i_=0; i_<=n-1;i_++) { state.yn[i_] = state.yn[i_] + v*state.rkk[k,i_]; } v = state.rkcs[k]; for(i_=0; i_<=n-1;i_++) { state.yns[i_] = state.yns[i_] + v*state.rkk[k,i_]; } k = k+1; goto lbl_8; lbl_10: // // estimate error // err = 0; for(j=0; j<=n-1; j++) { if( !state.fraceps ) { // // absolute error is estimated // err = Math.Max(err, Math.Abs(state.yn[j]-state.yns[j])); } else { // // Relative error is estimated // v = state.escale[j]; if( (double)(v)==(double)(0) ) { v = 1; } err = Math.Max(err, Math.Abs(state.yn[j]-state.yns[j])/v); } } // // calculate new step, restart if necessary // if( (double)(maxgrowpow*err)<=(double)(state.eps) ) { h2 = odesolvermaxgrow*h; } else { h2 = h*Math.Pow(state.eps/err, 0.2); } if( (double)(h2)<(double)(h/odesolvermaxshrink) ) { h2 = h/odesolvermaxshrink; } if( (double)(err)>(double)(state.eps) ) { h = h2; goto lbl_6; } // // advance position // xc = xc+h; for(i_=0; i_<=n-1;i_++) { state.yc[i_] = state.yn[i_]; } // // update H // h = h2; // // break on grid point // if( gridpoint ) { goto lbl_7; } goto lbl_6; lbl_7: // // save result // for(i_=0; i_<=n-1;i_++) { state.ytbl[i,i_] = state.yc[i_]; } i = i+1; goto lbl_3; lbl_5: state.repterminationtype = 1; result = false; return result; lbl_1: result = false; return result; // // Saving state // lbl_rcomm: result = true; state.rstate.ia[0] = n; state.rstate.ia[1] = m; state.rstate.ia[2] = i; state.rstate.ia[3] = j; state.rstate.ia[4] = k; state.rstate.ia[5] = klimit; state.rstate.ba[0] = gridpoint; state.rstate.ra[0] = xc; state.rstate.ra[1] = v; state.rstate.ra[2] = h; state.rstate.ra[3] = h2; state.rstate.ra[4] = err; state.rstate.ra[5] = maxgrowpow; return result; } /************************************************************************* ODE solver results Called after OdeSolverIteration returned False. INPUT PARAMETERS: State - algorithm state (used by OdeSolverIteration). OUTPUT PARAMETERS: M - number of tabulated values, M>=1 XTbl - array[0..M-1], values of X YTbl - array[0..M-1,0..N-1], values of Y in X[i] Rep - solver report: * Rep.TerminationType completetion code: * -2 X is not ordered by ascending/descending or there are non-distinct X[], i.e. X[i]=X[i+1] * -1 incorrect parameters were specified * 1 task has been solved * Rep.NFEV contains number of function calculations -- ALGLIB -- Copyright 01.09.2009 by Bochkanov Sergey *************************************************************************/ public static void odesolverresults(odesolverstate state, ref int m, ref double[] xtbl, ref double[,] ytbl, odesolverreport rep) { double v = 0; int i = 0; int i_ = 0; m = 0; xtbl = new double[0]; ytbl = new double[0,0]; rep.terminationtype = state.repterminationtype; if( rep.terminationtype>0 ) { m = state.m; rep.nfev = state.repnfev; xtbl = new double[state.m]; v = state.xscale; for(i_=0; i_<=state.m-1;i_++) { xtbl[i_] = v*state.xg[i_]; } ytbl = new double[state.m, state.n]; for(i=0; i<=state.m-1; i++) { for(i_=0; i_<=state.n-1;i_++) { ytbl[i,i_] = state.ytbl[i,i_]; } } } else { rep.nfev = 0; } } /************************************************************************* Internal initialization subroutine *************************************************************************/ private static void odesolverinit(int solvertype, double[] y, int n, double[] x, int m, double eps, double h, odesolverstate state) { int i = 0; double v = 0; int i_ = 0; // // Prepare RComm // state.rstate.ia = new int[5+1]; state.rstate.ba = new bool[0+1]; state.rstate.ra = new double[5+1]; state.rstate.stage = -1; state.needdy = false; // // check parameters. // if( (n<=0 || m<1) || (double)(eps)==(double)(0) ) { state.repterminationtype = -1; return; } if( (double)(h)<(double)(0) ) { h = -h; } // // quick exit if necessary. // after this block we assume that M>1 // if( m==1 ) { state.repnfev = 0; state.repterminationtype = 1; state.ytbl = new double[1, n]; for(i_=0; i_<=n-1;i_++) { state.ytbl[0,i_] = y[i_]; } state.xg = new double[m]; for(i_=0; i_<=m-1;i_++) { state.xg[i_] = x[i_]; } return; } // // check again: correct order of X[] // if( (double)(x[1])==(double)(x[0]) ) { state.repterminationtype = -2; return; } for(i=1; i<=m-1; i++) { if( ((double)(x[1])>(double)(x[0]) && (double)(x[i])<=(double)(x[i-1])) || ((double)(x[1])<(double)(x[0]) && (double)(x[i])>=(double)(x[i-1])) ) { state.repterminationtype = -2; return; } } // // auto-select H if necessary // if( (double)(h)==(double)(0) ) { v = Math.Abs(x[1]-x[0]); for(i=2; i<=m-1; i++) { v = Math.Min(v, Math.Abs(x[i]-x[i-1])); } h = 0.001*v; } // // store parameters // state.n = n; state.m = m; state.h = h; state.eps = Math.Abs(eps); state.fraceps = (double)(eps)<(double)(0); state.xg = new double[m]; for(i_=0; i_<=m-1;i_++) { state.xg[i_] = x[i_]; } if( (double)(x[1])>(double)(x[0]) ) { state.xscale = 1; } else { state.xscale = -1; for(i_=0; i_<=m-1;i_++) { state.xg[i_] = -1*state.xg[i_]; } } state.yc = new double[n]; for(i_=0; i_<=n-1;i_++) { state.yc[i_] = y[i_]; } state.solvertype = solvertype; state.repterminationtype = 0; // // Allocate arrays // state.y = new double[n]; state.dy = new double[n]; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Diagnostics; using System.Runtime.CompilerServices; using System.Security; namespace System.Net.Http { internal static class WinHttpTraceHelper { private const string WinHtpTraceEnvironmentVariable = "WINHTTPHANDLER_TRACE"; private static bool s_TraceEnabled; static WinHttpTraceHelper() { string env; try { env = Environment.GetEnvironmentVariable(WinHtpTraceEnvironmentVariable); } catch (SecurityException) { env = null; } s_TraceEnabled = !string.IsNullOrEmpty(env); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsTraceEnabled() { return s_TraceEnabled; } public static void Trace(string message) { if (!IsTraceEnabled()) { return; } Debug.WriteLine(message); } public static void Trace(string format, object arg0) { if (!IsTraceEnabled()) { return; } Debug.WriteLine(format, arg0); } public static void Trace(string format, object arg0, object arg1, object arg2) { if (!IsTraceEnabled()) { return; } Debug.WriteLine(format, arg0, arg1, arg2); } public static void TraceCallbackStatus(string message, IntPtr handle, IntPtr context, uint status) { if (!IsTraceEnabled()) { return; } Debug.WriteLine( "{0}: handle=0x{1:X}, context=0x{2:X}, {3}", message, handle, context, GetStringFromInternetStatus(status)); } public static void TraceAsyncError(string message, Interop.WinHttp.WINHTTP_ASYNC_RESULT asyncResult) { if (!IsTraceEnabled()) { return; } uint apiIndex = (uint)asyncResult.dwResult.ToInt32(); uint error = asyncResult.dwError; Debug.WriteLine( "{0}: api={1}, error={2}({3}) \"{4}\"", message, GetNameFromApiIndex(apiIndex), GetNameFromError(error), error, WinHttpException.GetErrorMessage((int)error)); } private static string GetNameFromApiIndex(uint index) { switch (index) { case Interop.WinHttp.API_RECEIVE_RESPONSE: return "API_RECEIVE_RESPONSE"; case Interop.WinHttp.API_QUERY_DATA_AVAILABLE: return "API_QUERY_DATA_AVAILABLE"; case Interop.WinHttp.API_READ_DATA: return "API_READ_DATA"; case Interop.WinHttp.API_WRITE_DATA: return "API_WRITE_DATA"; case Interop.WinHttp.API_SEND_REQUEST: return "API_SEND_REQUEST"; default: return index.ToString(); } } private static string GetNameFromError(uint error) { switch (error) { case Interop.WinHttp.ERROR_FILE_NOT_FOUND: return "ERROR_FILE_NOT_FOUND"; case Interop.WinHttp.ERROR_INVALID_HANDLE: return "ERROR_INVALID_HANDLE"; case Interop.WinHttp.ERROR_INVALID_PARAMETER: return "ERROR_INVALID_PARAMETER"; case Interop.WinHttp.ERROR_INSUFFICIENT_BUFFER: return "ERROR_INSUFFICIENT_BUFFER"; case Interop.WinHttp.ERROR_NOT_FOUND: return "ERROR_NOT_FOUND"; case Interop.WinHttp.ERROR_WINHTTP_INVALID_OPTION: return "WINHTTP_INVALID_OPTION"; case Interop.WinHttp.ERROR_WINHTTP_LOGIN_FAILURE: return "WINHTTP_LOGIN_FAILURE"; case Interop.WinHttp.ERROR_WINHTTP_OPERATION_CANCELLED: return "WINHTTP_OPERATION_CANCELLED"; case Interop.WinHttp.ERROR_WINHTTP_INCORRECT_HANDLE_STATE: return "WINHTTP_INCORRECT_HANDLE_STATE"; case Interop.WinHttp.ERROR_WINHTTP_CONNECTION_ERROR: return "WINHTTP_CONNECTION_ERROR"; case Interop.WinHttp.ERROR_WINHTTP_RESEND_REQUEST: return "WINHTTP_RESEND_REQUEST"; case Interop.WinHttp.ERROR_WINHTTP_CLIENT_AUTH_CERT_NEEDED: return "WINHTTP_CLIENT_AUTH_CERT_NEEDED"; case Interop.WinHttp.ERROR_WINHTTP_HEADER_NOT_FOUND: return "WINHTTP_HEADER_NOT_FOUND"; case Interop.WinHttp.ERROR_WINHTTP_SECURE_FAILURE: return "WINHTTP_SECURE_FAILURE"; case Interop.WinHttp.ERROR_WINHTTP_AUTODETECTION_FAILED: return "WINHTTP_AUTODETECTION_FAILED"; default: return error.ToString(); } } private static string GetStringFromInternetStatus(uint status) { switch (status) { case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_RESOLVING_NAME: return "STATUS_RESOLVING_NAME"; case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_NAME_RESOLVED: return "STATUS_NAME_RESOLVED"; case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_CONNECTING_TO_SERVER: return "STATUS_CONNECTING_TO_SERVER"; case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_CONNECTED_TO_SERVER: return "STATUS_CONNECTED_TO_SERVER"; case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_SENDING_REQUEST: return "STATUS_SENDING_REQUEST"; case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_REQUEST_SENT: return "STATUS_REQUEST_SENT"; case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_RECEIVING_RESPONSE: return "STATUS_RECEIVING_RESPONSE"; case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_RESPONSE_RECEIVED: return "STATUS_RESPONSE_RECEIVED"; case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_CLOSING_CONNECTION: return "STATUS_CLOSING_CONNECTION"; case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_CONNECTION_CLOSED: return "STATUS_CONNECTION_CLOSED"; case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_HANDLE_CREATED: return "STATUS_HANDLE_CREATED"; case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_HANDLE_CLOSING: return "STATUS_HANDLE_CLOSING"; case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_DETECTING_PROXY: return "STATUS_DETECTING_PROXY"; case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_REDIRECT: return "STATUS_REDIRECT"; case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_INTERMEDIATE_RESPONSE: return "STATUS_INTERMEDIATE_RESPONSE"; case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_SECURE_FAILURE: return "STATUS_SECURE_FAILURE"; case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_HEADERS_AVAILABLE: return "STATUS_HEADERS_AVAILABLE"; case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_DATA_AVAILABLE: return "STATUS_DATA_AVAILABLE"; case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_READ_COMPLETE: return "STATUS_READ_COMPLETE"; case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_WRITE_COMPLETE: return "STATUS_WRITE_COMPLETE"; case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_REQUEST_ERROR: return "STATUS_REQUEST_ERROR"; case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_SENDREQUEST_COMPLETE: return "STATUS_SENDREQUEST_COMPLETE"; case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_GETPROXYFORURL_COMPLETE: return "STATUS_GETPROXYFORURL_COMPLETE"; case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_CLOSE_COMPLETE: return "STATUS_CLOSE_COMPLETE"; case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_SHUTDOWN_COMPLETE: return "STATUS_SHUTDOWN_COMPLETE"; default: return string.Format("0x{0:X}", status); } } } }
// 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 0.17.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Graph.RBAC { using System; using System.Linq; using System.Collections.Generic; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Microsoft.Rest.Serialization; using Newtonsoft.Json; using Microsoft.Rest.Azure.OData; using Microsoft.Rest.Azure; using Models; /// <summary> /// UsersOperations operations. /// </summary> internal partial class UsersOperations : IServiceOperations<GraphRbacManagementClient>, IUsersOperations { /// <summary> /// Initializes a new instance of the UsersOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal UsersOperations(GraphRbacManagementClient client) { if (client == null) { throw new ArgumentNullException("client"); } this.Client = client; } /// <summary> /// Gets a reference to the GraphRbacManagementClient /// </summary> public GraphRbacManagementClient Client { get; private set; } /// <summary> /// Create a new user. Reference: /// https://msdn.microsoft.com/library/azure/ad/graph/api/users-operations#CreateUser /// </summary> /// <param name='parameters'> /// Parameters to create a user. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="GraphErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<User>> CreateWithHttpMessagesAsync(UserCreateParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (parameters == null) { throw new ValidationException(ValidationRules.CannotBeNull, "parameters"); } if (parameters != null) { parameters.Validate(); } if (this.Client.TenantID == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.TenantID"); } string apiVersion = "1.6"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("parameters", parameters); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Create", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "{tenantID}/users").ToString(); _url = _url.Replace("{tenantID}", Uri.EscapeDataString(this.Client.TenantID)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("POST"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(parameters != null) { _requestContent = SafeJsonConvert.SerializeObject(parameters, this.Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 201) { var ex = new GraphErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); GraphError _errorBody = SafeJsonConvert.DeserializeObject<GraphError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<User>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 201) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<User>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Gets list of users for the current tenant. Reference /// https://msdn.microsoft.com/en-us/library/azure/ad/graph/api/users-operations#GetUsers /// </summary> /// <param name='odataQuery'> /// OData parameters to apply to the operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="GraphErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<User>>> ListWithHttpMessagesAsync(ODataQuery<User> odataQuery = default(ODataQuery<User>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (this.Client.TenantID == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.TenantID"); } string apiVersion = "1.6"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("odataQuery", odataQuery); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "{tenantID}/users").ToString(); _url = _url.Replace("{tenantID}", Uri.EscapeDataString(this.Client.TenantID)); List<string> _queryParameters = new List<string>(); if (odataQuery != null) { var _odataFilter = odataQuery.ToString(); if (!string.IsNullOrEmpty(_odataFilter)) { _queryParameters.Add(_odataFilter); } } if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new GraphErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); GraphError _errorBody = SafeJsonConvert.DeserializeObject<GraphError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<User>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<Page1<User>>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Gets user information from the directory. Reference: /// https://msdn.microsoft.com/en-us/library/azure/ad/graph/api/users-operations#GetAUser /// </summary> /// <param name='upnOrObjectId'> /// User object Id or user principal name to get user information. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="GraphErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<User>> GetWithHttpMessagesAsync(string upnOrObjectId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (upnOrObjectId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "upnOrObjectId"); } if (this.Client.TenantID == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.TenantID"); } string apiVersion = "1.6"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("upnOrObjectId", upnOrObjectId); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "{tenantID}/users/{upnOrObjectId}").ToString(); _url = _url.Replace("{upnOrObjectId}", upnOrObjectId); _url = _url.Replace("{tenantID}", Uri.EscapeDataString(this.Client.TenantID)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new GraphErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); GraphError _errorBody = SafeJsonConvert.DeserializeObject<GraphError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<User>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<User>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Updates an exisitng user. Reference: /// https://msdn.microsoft.com/en-us/library/azure/ad/graph/api/users-operations#UpdateUser /// </summary> /// <param name='upnOrObjectId'> /// User object Id or user principal name to get user information. /// </param> /// <param name='parameters'> /// Parameters to update an exisitng user. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="GraphErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse> UpdateWithHttpMessagesAsync(string upnOrObjectId, UserUpdateParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (upnOrObjectId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "upnOrObjectId"); } if (parameters == null) { throw new ValidationException(ValidationRules.CannotBeNull, "parameters"); } if (this.Client.TenantID == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.TenantID"); } string apiVersion = "1.6"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("upnOrObjectId", upnOrObjectId); tracingParameters.Add("parameters", parameters); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Update", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "{tenantID}/users/{upnOrObjectId}").ToString(); _url = _url.Replace("{upnOrObjectId}", upnOrObjectId); _url = _url.Replace("{tenantID}", Uri.EscapeDataString(this.Client.TenantID)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PATCH"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(parameters != null) { _requestContent = SafeJsonConvert.SerializeObject(parameters, this.Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 204) { var ex = new GraphErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); GraphError _errorBody = SafeJsonConvert.DeserializeObject<GraphError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Delete a user. Reference: /// https://msdn.microsoft.com/en-us/library/azure/ad/graph/api/users-operations#DeleteUser /// </summary> /// <param name='upnOrObjectId'> /// user object id or user principal name (upn) /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="GraphErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string upnOrObjectId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (upnOrObjectId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "upnOrObjectId"); } if (this.Client.TenantID == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.TenantID"); } string apiVersion = "1.6"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("upnOrObjectId", upnOrObjectId); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Delete", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "{tenantID}/users/{upnOrObjectId}").ToString(); _url = _url.Replace("{upnOrObjectId}", upnOrObjectId); _url = _url.Replace("{tenantID}", Uri.EscapeDataString(this.Client.TenantID)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("DELETE"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 204) { var ex = new GraphErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); GraphError _errorBody = SafeJsonConvert.DeserializeObject<GraphError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Gets a collection that contains the Object IDs of the groups of which the /// user is a member. /// </summary> /// <param name='objectId'> /// User filtering parameters. /// </param> /// <param name='parameters'> /// User filtering parameters. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="GraphErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IEnumerable<string>>> GetMemberGroupsWithHttpMessagesAsync(string objectId, UserGetMemberGroupsParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (objectId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "objectId"); } if (parameters == null) { throw new ValidationException(ValidationRules.CannotBeNull, "parameters"); } if (parameters != null) { parameters.Validate(); } if (this.Client.TenantID == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.TenantID"); } string apiVersion = "1.6"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("objectId", objectId); tracingParameters.Add("parameters", parameters); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetMemberGroups", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "{tenantID}/users/{objectId}/getMemberGroups").ToString(); _url = _url.Replace("{objectId}", objectId); _url = _url.Replace("{tenantID}", Uri.EscapeDataString(this.Client.TenantID)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("POST"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(parameters != null) { _requestContent = SafeJsonConvert.SerializeObject(parameters, this.Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new GraphErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); GraphError _errorBody = SafeJsonConvert.DeserializeObject<GraphError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IEnumerable<string>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<Page<string>>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Gets list of users for the current tenant. /// </summary> /// <param name='nextLink'> /// Next link for list operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="GraphErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<User>>> ListNextWithHttpMessagesAsync(string nextLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextLink"); } if (this.Client.TenantID == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.TenantID"); } string apiVersion = "1.6"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextLink", nextLink); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "{tenantID}/{nextLink}").ToString(); _url = _url.Replace("{nextLink}", nextLink); _url = _url.Replace("{tenantID}", Uri.EscapeDataString(this.Client.TenantID)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { // Temporary hack for nextLink issue since nextLink already contains query param, a '?' is part of that. Remove this once the issue is fixed in AutoRest. _url += "&" + string.Join("&", _queryParameters); // _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new GraphErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); GraphError _errorBody = SafeJsonConvert.DeserializeObject<GraphError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<User>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<Page1<User>>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! namespace Google.Cloud.Dialogflow.Cx.V3.Snippets { using Google.Api.Gax; using System; using System.Linq; using System.Threading.Tasks; /// <summary>Generated snippets.</summary> public sealed class AllGeneratedDeploymentsClientSnippets { /// <summary>Snippet for ListDeployments</summary> public void ListDeploymentsRequestObject() { // Snippet: ListDeployments(ListDeploymentsRequest, CallSettings) // Create client DeploymentsClient deploymentsClient = DeploymentsClient.Create(); // Initialize request argument(s) ListDeploymentsRequest request = new ListDeploymentsRequest { ParentAsEnvironmentName = EnvironmentName.FromProjectLocationAgentEnvironment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]"), }; // Make the request PagedEnumerable<ListDeploymentsResponse, Deployment> response = deploymentsClient.ListDeployments(request); // Iterate over all response items, lazily performing RPCs as required foreach (Deployment item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListDeploymentsResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Deployment item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Deployment> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Deployment item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListDeploymentsAsync</summary> public async Task ListDeploymentsRequestObjectAsync() { // Snippet: ListDeploymentsAsync(ListDeploymentsRequest, CallSettings) // Create client DeploymentsClient deploymentsClient = await DeploymentsClient.CreateAsync(); // Initialize request argument(s) ListDeploymentsRequest request = new ListDeploymentsRequest { ParentAsEnvironmentName = EnvironmentName.FromProjectLocationAgentEnvironment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]"), }; // Make the request PagedAsyncEnumerable<ListDeploymentsResponse, Deployment> response = deploymentsClient.ListDeploymentsAsync(request); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((Deployment item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListDeploymentsResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Deployment item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Deployment> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Deployment item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListDeployments</summary> public void ListDeployments() { // Snippet: ListDeployments(string, string, int?, CallSettings) // Create client DeploymentsClient deploymentsClient = DeploymentsClient.Create(); // Initialize request argument(s) string parent = "projects/[PROJECT]/locations/[LOCATION]/agents/[AGENT]/environments/[ENVIRONMENT]"; // Make the request PagedEnumerable<ListDeploymentsResponse, Deployment> response = deploymentsClient.ListDeployments(parent); // Iterate over all response items, lazily performing RPCs as required foreach (Deployment item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListDeploymentsResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Deployment item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Deployment> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Deployment item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListDeploymentsAsync</summary> public async Task ListDeploymentsAsync() { // Snippet: ListDeploymentsAsync(string, string, int?, CallSettings) // Create client DeploymentsClient deploymentsClient = await DeploymentsClient.CreateAsync(); // Initialize request argument(s) string parent = "projects/[PROJECT]/locations/[LOCATION]/agents/[AGENT]/environments/[ENVIRONMENT]"; // Make the request PagedAsyncEnumerable<ListDeploymentsResponse, Deployment> response = deploymentsClient.ListDeploymentsAsync(parent); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((Deployment item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListDeploymentsResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Deployment item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Deployment> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Deployment item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListDeployments</summary> public void ListDeploymentsResourceNames() { // Snippet: ListDeployments(EnvironmentName, string, int?, CallSettings) // Create client DeploymentsClient deploymentsClient = DeploymentsClient.Create(); // Initialize request argument(s) EnvironmentName parent = EnvironmentName.FromProjectLocationAgentEnvironment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]"); // Make the request PagedEnumerable<ListDeploymentsResponse, Deployment> response = deploymentsClient.ListDeployments(parent); // Iterate over all response items, lazily performing RPCs as required foreach (Deployment item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListDeploymentsResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Deployment item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Deployment> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Deployment item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListDeploymentsAsync</summary> public async Task ListDeploymentsResourceNamesAsync() { // Snippet: ListDeploymentsAsync(EnvironmentName, string, int?, CallSettings) // Create client DeploymentsClient deploymentsClient = await DeploymentsClient.CreateAsync(); // Initialize request argument(s) EnvironmentName parent = EnvironmentName.FromProjectLocationAgentEnvironment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]"); // Make the request PagedAsyncEnumerable<ListDeploymentsResponse, Deployment> response = deploymentsClient.ListDeploymentsAsync(parent); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((Deployment item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListDeploymentsResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Deployment item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Deployment> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Deployment item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for GetDeployment</summary> public void GetDeploymentRequestObject() { // Snippet: GetDeployment(GetDeploymentRequest, CallSettings) // Create client DeploymentsClient deploymentsClient = DeploymentsClient.Create(); // Initialize request argument(s) GetDeploymentRequest request = new GetDeploymentRequest { DeploymentName = DeploymentName.FromProjectLocationAgentEnvironmentDeployment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]", "[DEPLOYMENT]"), }; // Make the request Deployment response = deploymentsClient.GetDeployment(request); // End snippet } /// <summary>Snippet for GetDeploymentAsync</summary> public async Task GetDeploymentRequestObjectAsync() { // Snippet: GetDeploymentAsync(GetDeploymentRequest, CallSettings) // Additional: GetDeploymentAsync(GetDeploymentRequest, CancellationToken) // Create client DeploymentsClient deploymentsClient = await DeploymentsClient.CreateAsync(); // Initialize request argument(s) GetDeploymentRequest request = new GetDeploymentRequest { DeploymentName = DeploymentName.FromProjectLocationAgentEnvironmentDeployment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]", "[DEPLOYMENT]"), }; // Make the request Deployment response = await deploymentsClient.GetDeploymentAsync(request); // End snippet } /// <summary>Snippet for GetDeployment</summary> public void GetDeployment() { // Snippet: GetDeployment(string, CallSettings) // Create client DeploymentsClient deploymentsClient = DeploymentsClient.Create(); // Initialize request argument(s) string name = "projects/[PROJECT]/locations/[LOCATION]/agents/[AGENT]/environments/[ENVIRONMENT]/deployments/[DEPLOYMENT]"; // Make the request Deployment response = deploymentsClient.GetDeployment(name); // End snippet } /// <summary>Snippet for GetDeploymentAsync</summary> public async Task GetDeploymentAsync() { // Snippet: GetDeploymentAsync(string, CallSettings) // Additional: GetDeploymentAsync(string, CancellationToken) // Create client DeploymentsClient deploymentsClient = await DeploymentsClient.CreateAsync(); // Initialize request argument(s) string name = "projects/[PROJECT]/locations/[LOCATION]/agents/[AGENT]/environments/[ENVIRONMENT]/deployments/[DEPLOYMENT]"; // Make the request Deployment response = await deploymentsClient.GetDeploymentAsync(name); // End snippet } /// <summary>Snippet for GetDeployment</summary> public void GetDeploymentResourceNames() { // Snippet: GetDeployment(DeploymentName, CallSettings) // Create client DeploymentsClient deploymentsClient = DeploymentsClient.Create(); // Initialize request argument(s) DeploymentName name = DeploymentName.FromProjectLocationAgentEnvironmentDeployment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]", "[DEPLOYMENT]"); // Make the request Deployment response = deploymentsClient.GetDeployment(name); // End snippet } /// <summary>Snippet for GetDeploymentAsync</summary> public async Task GetDeploymentResourceNamesAsync() { // Snippet: GetDeploymentAsync(DeploymentName, CallSettings) // Additional: GetDeploymentAsync(DeploymentName, CancellationToken) // Create client DeploymentsClient deploymentsClient = await DeploymentsClient.CreateAsync(); // Initialize request argument(s) DeploymentName name = DeploymentName.FromProjectLocationAgentEnvironmentDeployment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]", "[DEPLOYMENT]"); // Make the request Deployment response = await deploymentsClient.GetDeploymentAsync(name); // End snippet } } }
// 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; #if !ES_BUILD_AGAINST_DOTNET_V35 using Contract = System.Diagnostics.Contracts.Contract; #else using Contract = Microsoft.Diagnostics.Contracts.Internal.Contract; #endif #if ES_BUILD_STANDALONE namespace Microsoft.Diagnostics.Tracing #else namespace System.Diagnostics.Tracing #endif { /// <summary> /// Provides support for EventSource activities by marking the start and /// end of a particular operation. /// </summary> internal sealed class EventSourceActivity : IDisposable { /// <summary> /// Initializes a new instance of the EventSourceActivity class that /// is attached to the specified event source. The new activity will /// not be attached to any related (parent) activity. /// The activity is created in the Initialized state. /// </summary> /// <param name="eventSource"> /// The event source to which the activity information is written. /// </param> public EventSourceActivity(EventSource eventSource) { if (eventSource == null) throw new ArgumentNullException(nameof(eventSource)); Contract.EndContractBlock(); this.eventSource = eventSource; } /// <summary> /// You can make an activity out of just an EventSource. /// </summary> public static implicit operator EventSourceActivity(EventSource eventSource) { return new EventSourceActivity(eventSource); } /* Properties */ /// <summary> /// Gets the event source to which this activity writes events. /// </summary> public EventSource EventSource { get { return this.eventSource; } } /// <summary> /// Gets this activity's unique identifier, or the default Guid if the /// event source was disabled when the activity was initialized. /// </summary> public Guid Id { get { return this.activityId; } } #if false // don't expose RelatedActivityId unless there is a need. /// <summary> /// Gets the unique identifier of this activity's related (parent) /// activity. /// </summary> public Guid RelatedId { get { return this.relatedActivityId; } } #endif /// <summary> /// Writes a Start event with the specified name and data. If the start event is not active (because the provider /// is not on or keyword-level indicates the event is off, then the returned activity is simply the 'this' pointer /// and it is effectively like start did not get called. /// /// A new activityID GUID is generated and the returned /// EventSourceActivity remembers this activity and will mark every event (including the start stop and any writes) /// with this activityID. In addition the Start activity will log a 'relatedActivityID' that was the activity /// ID before the start event. This way event processors can form a linked list of all the activities that /// caused this one (directly or indirectly). /// </summary> /// <param name="eventName"> /// The name to use for the event. It is strongly suggested that this name end in 'Start' (e.g. DownloadStart). /// If you do this, then the Stop() method will automatically replace the 'Start' suffix with a 'Stop' suffix. /// </param> /// <param name="options">Allow options (keywords, level) to be set for the write associated with this start /// These will also be used for the stop event.</param> /// <param name="data">The data to include in the event.</param> public EventSourceActivity Start<T>(string eventName, EventSourceOptions options, T data) { return this.Start(eventName, ref options, ref data); } /// <summary> /// Shortcut version see Start(string eventName, EventSourceOptions options, T data) Options is empty (no keywords /// and level==Info) Data payload is empty. /// </summary> public EventSourceActivity Start(string eventName) { var options = new EventSourceOptions(); var data = new EmptyStruct(); return this.Start(eventName, ref options, ref data); } /// <summary> /// Shortcut version see Start(string eventName, EventSourceOptions options, T data). Data payload is empty. /// </summary> public EventSourceActivity Start(string eventName, EventSourceOptions options) { var data = new EmptyStruct(); return this.Start(eventName, ref options, ref data); } /// <summary> /// Shortcut version see Start(string eventName, EventSourceOptions options, T data) Options is empty (no keywords /// and level==Info) /// </summary> public EventSourceActivity Start<T>(string eventName, T data) { var options = new EventSourceOptions(); return this.Start(eventName, ref options, ref data); } /// <summary> /// Writes a Stop event with the specified data, and sets the activity /// to the Stopped state. The name is determined by the eventName used in Start. /// If that Start event name is suffixed with 'Start' that is removed, and regardless /// 'Stop' is appended to the result to form the Stop event name. /// May only be called when the activity is in the Started state. /// </summary> /// <param name="data">The data to include in the event.</param> public void Stop<T>(T data) { this.Stop(null, ref data); } /// <summary> /// Used if you wish to use the non-default stop name (which is the start name with Start replace with 'Stop') /// This can be useful to indicate unusual ways of stopping (but it is still STRONGLY recommended that /// you start with the same prefix used for the start event and you end with the 'Stop' suffix. /// </summary> public void Stop<T>(string eventName) { var data = new EmptyStruct(); this.Stop(eventName, ref data); } /// <summary> /// Used if you wish to use the non-default stop name (which is the start name with Start replace with 'Stop') /// This can be useful to indicate unusual ways of stopping (but it is still STRONGLY recommended that /// you start with the same prefix used for the start event and you end with the 'Stop' suffix. /// </summary> public void Stop<T>(string eventName, T data) { this.Stop(eventName, ref data); } /// <summary> /// Writes an event associated with this activity to the eventSource associated with this activity. /// May only be called when the activity is in the Started state. /// </summary> /// <param name="eventName"> /// The name to use for the event. If null, the name is determined from /// data's type. /// </param> /// <param name="options"> /// The options to use for the event. /// </param> /// <param name="data">The data to include in the event.</param> public void Write<T>(string eventName, EventSourceOptions options, T data) { this.Write(this.eventSource, eventName, ref options, ref data); } /// <summary> /// Writes an event associated with this activity. /// May only be called when the activity is in the Started state. /// </summary> /// <param name="eventName"> /// The name to use for the event. If null, the name is determined from /// data's type. /// </param> /// <param name="data">The data to include in the event.</param> public void Write<T>(string eventName, T data) { var options = new EventSourceOptions(); this.Write(this.eventSource, eventName, ref options, ref data); } /// <summary> /// Writes a trivial event associated with this activity. /// May only be called when the activity is in the Started state. /// </summary> /// <param name="eventName"> /// The name to use for the event. Must not be null. /// </param> /// <param name="options"> /// The options to use for the event. /// </param> public void Write(string eventName, EventSourceOptions options) { var data = new EmptyStruct(); this.Write(this.eventSource, eventName, ref options, ref data); } /// <summary> /// Writes a trivial event associated with this activity. /// May only be called when the activity is in the Started state. /// </summary> /// <param name="eventName"> /// The name to use for the event. Must not be null. /// </param> public void Write(string eventName) { var options = new EventSourceOptions(); var data = new EmptyStruct(); this.Write(this.eventSource, eventName, ref options, ref data); } /// <summary> /// Writes an event to a arbitrary eventSource stamped with the activity ID of this activity. /// </summary> public void Write<T>(EventSource source, string eventName, EventSourceOptions options, T data) { this.Write(source, eventName, ref options, ref data); } /// <summary> /// Releases any unmanaged resources associated with this object. /// If the activity is in the Started state, calls Stop(). /// </summary> public void Dispose() { if (this.state == State.Started) { var data = new EmptyStruct(); this.Stop(null, ref data); } } #region private private EventSourceActivity Start<T>(string eventName, ref EventSourceOptions options, ref T data) { if (this.state != State.Started) throw new InvalidOperationException(); // If the source is not on at all, then we don't need to do anything and we can simply return ourselves. if (!this.eventSource.IsEnabled()) return this; var newActivity = new EventSourceActivity(eventSource); if (!this.eventSource.IsEnabled(options.Level, options.Keywords)) { // newActivity.relatedActivityId = this.Id; Guid relatedActivityId = this.Id; newActivity.activityId = Guid.NewGuid(); newActivity.startStopOptions = options; newActivity.eventName = eventName; newActivity.startStopOptions.Opcode = EventOpcode.Start; this.eventSource.Write(eventName, ref newActivity.startStopOptions, ref newActivity.activityId, ref relatedActivityId, ref data); } else { // If we are not active, we don't set the eventName, which basically also turns off the Stop event as well. newActivity.activityId = this.Id; } return newActivity; } private void Write<T>(EventSource eventSource, string eventName, ref EventSourceOptions options, ref T data) { if (this.state != State.Started) throw new InvalidOperationException(); // Write after stop. if (eventName == null) throw new ArgumentNullException(); eventSource.Write(eventName, ref options, ref this.activityId, ref s_empty, ref data); } private void Stop<T>(string eventName, ref T data) { if (this.state != State.Started) throw new InvalidOperationException(); // If start was not fired, then stop isn't as well. if (!StartEventWasFired) return; this.state = State.Stopped; if (eventName == null) { eventName = this.eventName; if (eventName.EndsWith("Start")) eventName = eventName.Substring(0, eventName.Length - 5); eventName = eventName + "Stop"; } this.startStopOptions.Opcode = EventOpcode.Stop; this.eventSource.Write(eventName, ref this.startStopOptions, ref this.activityId, ref s_empty, ref data); } private enum State { Started, Stopped } /// <summary> /// If eventName is non-null then we logged a start event /// </summary> private bool StartEventWasFired { get { return eventName != null; } } private readonly EventSource eventSource; private EventSourceOptions startStopOptions; internal Guid activityId; // internal Guid relatedActivityId; private State state; private string eventName; static internal Guid s_empty; #endregion } }
#region Apache License // // 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. // #endregion using System; using System.Collections; #if NETCF_1_0 using Stack = log4net.Util.ThreadContextStack.Stack; #endif namespace log4net { /// <summary> /// Implementation of Nested Diagnostic Contexts. /// </summary> /// <remarks> /// <note> /// <para> /// The NDC is deprecated and has been replaced by the <see cref="ThreadContext.Stacks"/>. /// The current NDC implementation forwards to the <c>ThreadContext.Stacks["NDC"]</c>. /// </para> /// </note> /// <para> /// A Nested Diagnostic Context, or NDC in short, is an instrument /// to distinguish interleaved log output from different sources. Log /// output is typically interleaved when a server handles multiple /// clients near-simultaneously. /// </para> /// <para> /// Interleaved log output can still be meaningful if each log entry /// from different contexts had a distinctive stamp. This is where NDCs /// come into play. /// </para> /// <para> /// Note that NDCs are managed on a per thread basis. The NDC class /// is made up of static methods that operate on the context of the /// calling thread. /// </para> /// </remarks> /// <example>How to push a message into the context /// <code lang="C#"> /// using(NDC.Push("my context message")) /// { /// ... all log calls will have 'my context message' included ... /// /// } // at the end of the using block the message is automatically removed /// </code> /// </example> /// <threadsafety static="true" instance="true" /> /// <author>Nicko Cadell</author> /// <author>Gert Driesen</author> /*[Obsolete("NDC has been replaced by ThreadContext.Stacks")]*/ public sealed class NDC { #region Private Instance Constructors /// <summary> /// Initializes a new instance of the <see cref="NDC" /> class. /// </summary> /// <remarks> /// Uses a private access modifier to prevent instantiation of this class. /// </remarks> private NDC() { } #endregion Private Instance Constructors #region Public Static Properties /// <summary> /// Gets the current context depth. /// </summary> /// <value>The current context depth.</value> /// <remarks> /// <note> /// <para> /// The NDC is deprecated and has been replaced by the <see cref="ThreadContext.Stacks"/>. /// The current NDC implementation forwards to the <c>ThreadContext.Stacks["NDC"]</c>. /// </para> /// </note> /// <para> /// The number of context values pushed onto the context stack. /// </para> /// <para> /// Used to record the current depth of the context. This can then /// be restored using the <see cref="SetMaxDepth"/> method. /// </para> /// </remarks> /// <seealso cref="SetMaxDepth"/> /*[Obsolete("NDC has been replaced by ThreadContext.Stacks")]*/ public static int Depth { get { return ThreadContext.Stacks["NDC"].Count; } } #endregion Public Static Properties #region Public Static Methods /// <summary> /// Clears all the contextual information held on the current thread. /// </summary> /// <remarks> /// <note> /// <para> /// The NDC is deprecated and has been replaced by the <see cref="ThreadContext.Stacks"/>. /// The current NDC implementation forwards to the <c>ThreadContext.Stacks["NDC"]</c>. /// </para> /// </note> /// <para> /// Clears the stack of NDC data held on the current thread. /// </para> /// </remarks> /*[Obsolete("NDC has been replaced by ThreadContext.Stacks")]*/ public static void Clear() { ThreadContext.Stacks["NDC"].Clear(); } /// <summary> /// Creates a clone of the stack of context information. /// </summary> /// <returns>A clone of the context info for this thread.</returns> /// <remarks> /// <note> /// <para> /// The NDC is deprecated and has been replaced by the <see cref="ThreadContext.Stacks"/>. /// The current NDC implementation forwards to the <c>ThreadContext.Stacks["NDC"]</c>. /// </para> /// </note> /// <para> /// The results of this method can be passed to the <see cref="Inherit"/> /// method to allow child threads to inherit the context of their /// parent thread. /// </para> /// </remarks> /*[Obsolete("NDC has been replaced by ThreadContext.Stacks")]*/ public static Stack CloneStack() { return ThreadContext.Stacks["NDC"].InternalStack; } /// <summary> /// Inherits the contextual information from another thread. /// </summary> /// <param name="stack">The context stack to inherit.</param> /// <remarks> /// <note> /// <para> /// The NDC is deprecated and has been replaced by the <see cref="ThreadContext.Stacks"/>. /// The current NDC implementation forwards to the <c>ThreadContext.Stacks["NDC"]</c>. /// </para> /// </note> /// <para> /// This thread will use the context information from the stack /// supplied. This can be used to initialize child threads with /// the same contextual information as their parent threads. These /// contexts will <b>NOT</b> be shared. Any further contexts that /// are pushed onto the stack will not be visible to the other. /// Call <see cref="CloneStack"/> to obtain a stack to pass to /// this method. /// </para> /// </remarks> /*[Obsolete("NDC has been replaced by ThreadContext.Stacks", true)]*/ public static void Inherit(Stack stack) { ThreadContext.Stacks["NDC"].InternalStack = stack; } /// <summary> /// Removes the top context from the stack. /// </summary> /// <returns> /// The message in the context that was removed from the top /// of the stack. /// </returns> /// <remarks> /// <note> /// <para> /// The NDC is deprecated and has been replaced by the <see cref="ThreadContext.Stacks"/>. /// The current NDC implementation forwards to the <c>ThreadContext.Stacks["NDC"]</c>. /// </para> /// </note> /// <para> /// Remove the top context from the stack, and return /// it to the caller. If the stack is empty then an /// empty string (not <c>null</c>) is returned. /// </para> /// </remarks> /*[Obsolete("NDC has been replaced by ThreadContext.Stacks")]*/ public static string Pop() { return ThreadContext.Stacks["NDC"].Pop(); } /// <summary> /// Pushes a new context message. /// </summary> /// <param name="message">The new context message.</param> /// <returns> /// An <see cref="IDisposable"/> that can be used to clean up /// the context stack. /// </returns> /// <remarks> /// <note> /// <para> /// The NDC is deprecated and has been replaced by the <see cref="ThreadContext.Stacks"/>. /// The current NDC implementation forwards to the <c>ThreadContext.Stacks["NDC"]</c>. /// </para> /// </note> /// <para> /// Pushes a new context onto the context stack. An <see cref="IDisposable"/> /// is returned that can be used to clean up the context stack. This /// can be easily combined with the <c>using</c> keyword to scope the /// context. /// </para> /// </remarks> /// <example>Simple example of using the <c>Push</c> method with the <c>using</c> keyword. /// <code lang="C#"> /// using(log4net.NDC.Push("NDC_Message")) /// { /// log.Warn("This should have an NDC message"); /// } /// </code> /// </example> /*[Obsolete("NDC has been replaced by ThreadContext.Stacks")]*/ public static IDisposable Push(string message) { return ThreadContext.Stacks["NDC"].Push(message); } /// <summary> /// Pushes a new context message. /// </summary> /// <param name="messageFormat">The new context message string format.</param> /// <param name="args">Arguments to be passed into messageFormat.</param> /// <returns> /// An <see cref="IDisposable"/> that can be used to clean up /// the context stack. /// </returns> /// <remarks> /// <note> /// <para> /// The NDC is deprecated and has been replaced by the <see cref="ThreadContext.Stacks"/>. /// The current NDC implementation forwards to the <c>ThreadContext.Stacks["NDC"]</c>. /// </para> /// </note> /// <para> /// Pushes a new context onto the context stack. An <see cref="IDisposable"/> /// is returned that can be used to clean up the context stack. This /// can be easily combined with the <c>using</c> keyword to scope the /// context. /// </para> /// </remarks> /// <example>Simple example of using the <c>Push</c> method with the <c>using</c> keyword. /// <code lang="C#"> /// var someValue = "ExampleContext" /// using(log4net.NDC.PushFormat("NDC_Message {0}", someValue)) /// { /// log.Warn("This should have an NDC message"); /// } /// </code> /// </example> /*[Obsolete("NDC has been replaced by ThreadContext.Stacks")]*/ public static IDisposable PushFormat(string messageFormat, params object[] args) { return Push(string.Format(messageFormat, args)); } /// <summary> /// Removes the context information for this thread. It is /// not required to call this method. /// </summary> /// <remarks> /// <note> /// <para> /// The NDC is deprecated and has been replaced by the <see cref="ThreadContext.Stacks"/>. /// The current NDC implementation forwards to the <c>ThreadContext.Stacks["NDC"]</c>. /// </para> /// </note> /// <para> /// This method is not implemented. /// </para> /// </remarks> /*[Obsolete("NDC has been replaced by ThreadContext.Stacks")]*/ public static void Remove() { } /// <summary> /// Forces the stack depth to be at most <paramref name="maxDepth"/>. /// </summary> /// <param name="maxDepth">The maximum depth of the stack</param> /// <remarks> /// <note> /// <para> /// The NDC is deprecated and has been replaced by the <see cref="ThreadContext.Stacks"/>. /// The current NDC implementation forwards to the <c>ThreadContext.Stacks["NDC"]</c>. /// </para> /// </note> /// <para> /// Forces the stack depth to be at most <paramref name="maxDepth"/>. /// This may truncate the head of the stack. This only affects the /// stack in the current thread. Also it does not prevent it from /// growing, it only sets the maximum depth at the time of the /// call. This can be used to return to a known context depth. /// </para> /// </remarks> /*[Obsolete("NDC has been replaced by ThreadContext.Stacks")]*/ public static void SetMaxDepth(int maxDepth) { if (maxDepth >= 0) { log4net.Util.ThreadContextStack stack = ThreadContext.Stacks["NDC"]; if (maxDepth == 0) { stack.Clear(); } else { while(stack.Count > maxDepth) { stack.Pop(); } } } } #endregion Public Static Methods } }
// // Copyright (C) DataStax 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.Linq; using System.Net; using System.Threading.Tasks; using Cassandra.IntegrationTests.TestBase; using Cassandra.SessionManagement; using Cassandra.IntegrationTests.TestClusterManagement; using Cassandra.IntegrationTests.TestClusterManagement.Simulacron; using Cassandra.Tests; using NUnit.Framework; namespace Cassandra.IntegrationTests.Core { [TestFixture, Category(TestCategory.Short)] public class ClusterTests : TestGlobals { private SimulacronCluster _testCluster; private ITestCluster _realCluster; [TearDown] public void TestTearDown() { _testCluster?.Dispose(); _testCluster = null; TestClusterManager.TryRemove(); _realCluster = null; } [Test] [TestCase(true)] [TestCase(false)] public Task Cluster_Connect_Should_Initialize_Loadbalancing_With_ControlConnection_Address_Set(bool asyncConnect) { _testCluster = SimulacronCluster.CreateNew(2); var lbp = new TestLoadBalancingPolicy(); var cluster = ClusterBuilder() .AddContactPoint(_testCluster.InitialContactPoint) .WithLoadBalancingPolicy(lbp) .Build(); return TestGlobals.ConnectAndDispose(cluster, asyncConnect, session => { Assert.NotNull(lbp.ControlConnectionHost); Assert.AreEqual(_testCluster.InitialContactPoint, lbp.ControlConnectionHost.Address); }); } [Test] [TestCase(true)] [TestCase(false)] public Task Cluster_Connect_Should_Use_Node2_Address(bool asyncConnect) { _testCluster = SimulacronCluster.CreateNew(2); var nodes = _testCluster.GetNodes().ToArray(); var contactPoints = nodes.Select(n => n.ContactPoint).ToArray(); nodes[0].DisableConnectionListener().GetAwaiter().GetResult(); var lbp = new TestLoadBalancingPolicy(); var cluster = ClusterBuilder() .AddContactPoints(contactPoints.Select(s => s.Split(':').First())) .WithLoadBalancingPolicy(lbp) .Build(); return TestGlobals.ConnectAndDispose(cluster, asyncConnect, session => { Assert.NotNull(lbp.ControlConnectionHost); Assert.AreEqual(contactPoints[1], lbp.ControlConnectionHost.Address.ToString()); }); } /// Tests that MaxProtocolVersion is honored when set /// /// Cluster_Should_Honor_MaxProtocolVersion_Set tests that the MaxProtocolVersion set when building a cluster is /// honored properly by the driver. It first verifies that the default MaxProtocolVersion is the maximum available by /// the driver (ProtocolVersion 4 as of driver 3.0.1). It then verifies that a set MaxProtocolVersion is honored when /// connecting to a Cassandra cluster. It also verifies that setting an arbitary MaxProtocolVersion is allowed, as the /// ProtocolVersion will be negotiated down upon first connection. Finally, it verifies that a MaxProtocolVersion is /// not valid. /// /// @expected_errors ArgumentException When MaxProtocolVersion is set to 0. /// /// @since 3.0.1 /// @jira_ticket CSHARP-388 /// @expected_result MaxProtocolVersion is set and honored upon connection. /// /// @test_category connection [Test] [TestCase(true)] [TestCase(false)] public async Task Cluster_Should_Honor_MaxProtocolVersion_Set(bool asyncConnect) { _testCluster = SimulacronCluster.CreateNew(2); // Default MaxProtocolVersion var clusterDefault = ClusterBuilder() .AddContactPoint(_testCluster.InitialContactPoint) .Build(); Assert.AreEqual(Cluster.MaxProtocolVersion, clusterDefault.Configuration.ProtocolOptions.MaxProtocolVersion); // MaxProtocolVersion set var clusterMax = ClusterBuilder() .AddContactPoint(_testCluster.InitialContactPoint) .WithMaxProtocolVersion(3) .Build(); Assert.AreEqual(3, clusterMax.Configuration.ProtocolOptions.MaxProtocolVersion); await TestGlobals.ConnectAndDispose(clusterMax, asyncConnect, session => { if (TestClusterManager.CheckCassandraVersion(false, Version.Parse("2.1"), Comparison.LessThan)) Assert.AreEqual(2, session.BinaryProtocolVersion); else Assert.AreEqual(3, session.BinaryProtocolVersion); }).ConfigureAwait(false); // Arbitrary MaxProtocolVersion set, will negotiate down upon connect var clusterNegotiate = ClusterBuilder() .AddContactPoint(_testCluster.InitialContactPoint) .WithMaxProtocolVersion(10) .Build(); Assert.AreEqual(10, clusterNegotiate.Configuration.ProtocolOptions.MaxProtocolVersion); await TestGlobals.ConnectAndDispose(clusterNegotiate, asyncConnect, session => { Assert.LessOrEqual(4, clusterNegotiate.Configuration.ProtocolOptions.MaxProtocolVersion); }).ConfigureAwait(false); // ProtocolVersion 0 does not exist Assert.Throws<ArgumentException>( () => ClusterBuilder().AddContactPoint("127.0.0.1").WithMaxProtocolVersion((byte)0)); } /// <summary> /// Validates that the client adds the newly bootstrapped node and eventually queries from it /// </summary> [Test] [Category(TestCategory.RealClusterLong)] public async Task Should_Add_And_Query_Newly_Bootstrapped_Node() { _realCluster = TestClusterManager.CreateNew(); var cluster = ClusterBuilder() .WithSocketOptions(new SocketOptions().SetReadTimeoutMillis(22000).SetConnectTimeoutMillis(60000)) .AddContactPoint(_realCluster.InitialContactPoint) .Build(); await TestGlobals.ConnectAndDispose(cluster, false, session => { Assert.AreEqual(1, cluster.AllHosts().Count); _realCluster.BootstrapNode(2); Trace.TraceInformation("Node bootstrapped"); var newNodeAddress = _realCluster.ClusterIpPrefix + 2; var newNodeIpAddress = IPAddress.Parse(newNodeAddress); TestHelper.RetryAssert(() => { Assert.True(TestUtils.IsNodeReachable(newNodeIpAddress)); //New node should be part of the metadata Assert.AreEqual(2, cluster.AllHosts().Count); var host = cluster.AllHosts().FirstOrDefault(h => h.Address.Address.Equals(newNodeIpAddress)); Assert.IsNotNull(host); }, 2000, 90); TestHelper.RetryAssert(() => { var rs = session.Execute("SELECT key FROM system.local"); Assert.True(rs.Info.QueriedHost.Address.ToString() == newNodeAddress, "Newly bootstrapped node should be queried"); }, 1, 100); }).ConfigureAwait(false); } [Test] [Category(TestCategory.RealClusterLong)] public async Task Should_Remove_Decommissioned_Node() { const int numberOfNodes = 2; _realCluster = TestClusterManager.CreateNew(numberOfNodes); var cluster = ClusterBuilder().AddContactPoint(_realCluster.InitialContactPoint).Build(); await TestGlobals.ConnectAndDispose(cluster, false, session => { Assert.AreEqual(numberOfNodes, cluster.AllHosts().Count); if (TestClusterManager.SupportsDecommissionForcefully()) { _realCluster.DecommissionNodeForcefully(numberOfNodes); } else { _realCluster.DecommissionNode(numberOfNodes); } _realCluster.Stop(numberOfNodes); Trace.TraceInformation("Node decommissioned"); string decommisionedNode = null; TestHelper.RetryAssert(() => { decommisionedNode = _realCluster.ClusterIpPrefix + 2; Assert.False(TestUtils.IsNodeReachable(IPAddress.Parse(decommisionedNode))); //New node should be part of the metadata Assert.AreEqual(1, cluster.AllHosts().Count); }, 100, 100); var queried = false; for (var i = 0; i < 10; i++) { var rs = session.Execute("SELECT key FROM system.local"); if (rs.Info.QueriedHost.Address.ToString() == decommisionedNode) { queried = true; break; } } Assert.False(queried, "Removed node should be queried"); }).ConfigureAwait(false); } private class TestLoadBalancingPolicy : ILoadBalancingPolicy { private ICluster _cluster; public Host ControlConnectionHost { get; private set; } public void Initialize(ICluster cluster) { _cluster = cluster; ControlConnectionHost = ((IInternalCluster)cluster).GetControlConnection().Host; } public HostDistance Distance(Host host) { return HostDistance.Local; } public IEnumerable<Host> NewQueryPlan(string keyspace, IStatement query) { return _cluster.AllHosts(); } } } }
/* ==================================================================== 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 NPOI.XWPF.UserModel { using System; using System.Collections.Generic; using NPOI.OpenXmlFormats.Wordprocessing; using System.Xml; public class XWPFFootnote : IEnumerator<XWPFParagraph>, IBody { private List<XWPFParagraph> paragraphs = new List<XWPFParagraph>(); private List<XWPFTable> tables = new List<XWPFTable>(); private List<XWPFPictureData> pictures = new List<XWPFPictureData>(); private List<IBodyElement> bodyElements = new List<IBodyElement>(); private CT_FtnEdn ctFtnEdn; private XWPFFootnotes footnotes; private XWPFDocument document; public XWPFFootnote(CT_FtnEdn note, XWPFFootnotes xFootnotes) { footnotes = xFootnotes; ctFtnEdn = note; document = xFootnotes.GetXWPFDocument(); Init(); } public XWPFFootnote(XWPFDocument document, CT_FtnEdn body) { ctFtnEdn = body; this.document = document; Init(); } private void Init() { //copied from XWPFDocument...should centralize this code //to avoid duplication foreach (object o in ctFtnEdn.Items) { if (o is CT_P) { XWPFParagraph p = new XWPFParagraph((CT_P)o, this); bodyElements.Add(p); paragraphs.Add(p); } else if (o is CT_Tbl) { XWPFTable t = new XWPFTable((CT_Tbl)o, this); bodyElements.Add(t); tables.Add(t); } else if (o is CT_SdtBlock) { XWPFSDT c = new XWPFSDT((CT_SdtBlock)o, this); bodyElements.Add(c); } } } public IList<XWPFParagraph> Paragraphs { get { return paragraphs; } } public IEnumerator<XWPFParagraph> GetEnumerator() { return paragraphs.GetEnumerator(); } public IList<XWPFTable> Tables { get { return tables; } } public IList<XWPFPictureData> Pictures { get { return pictures; } } public IList<IBodyElement> BodyElements { get { return bodyElements; } } public CT_FtnEdn GetCTFtnEdn() { return ctFtnEdn; } public void SetCTFtnEdn(CT_FtnEdn footnote) { ctFtnEdn = footnote; } /// <summary> /// /// </summary> /// <param name="pos">position in table array</param> /// <returns>The table at position pos</returns> public XWPFTable GetTableArray(int pos) { if (pos >= 0 && pos < tables.Count) { return tables[(pos)]; } return null; } /// <summary> /// inserts an existing XWPFTable to the arrays bodyElements and tables /// </summary> /// <param name="pos"></param> /// <param name="table"></param> public void InsertTable(int pos, XWPFTable table) { bodyElements.Insert(pos, table); int i; for (i = 0; i < ctFtnEdn.GetTblList().Count; i++) { CT_Tbl tbl = ctFtnEdn.GetTblArray(i); if(tbl == table.GetCTTbl()){ break; } } tables.Insert(i, table); } /** * if there is a corresponding {@link XWPFTable} of the parameter ctTable in the tableList of this header * the method will return this table * if there is no corresponding {@link XWPFTable} the method will return null * @param ctTable * @see NPOI.XWPF.UserModel.IBody#getTable(CTTbl ctTable) */ public XWPFTable GetTable(CT_Tbl ctTable) { foreach (XWPFTable table in tables) { if(table==null) return null; if(table.GetCTTbl().Equals(ctTable)) return table; } return null; } /** * if there is a corresponding {@link XWPFParagraph} of the parameter ctTable in the paragraphList of this header or footer * the method will return this paragraph * if there is no corresponding {@link XWPFParagraph} the method will return null * @param p is instance of CTP and is searching for an XWPFParagraph * @return null if there is no XWPFParagraph with an corresponding CTPparagraph in the paragraphList of this header or footer * XWPFParagraph with the correspondig CTP p * @see NPOI.XWPF.UserModel.IBody#getParagraph(CTP p) */ public XWPFParagraph GetParagraph(CT_P p) { foreach (XWPFParagraph paragraph in paragraphs) { if(paragraph.GetCTP().Equals(p)) return paragraph; } return null; } /// <summary> /// Returns the paragraph that holds the text of the header or footer. /// </summary> /// <param name="pos"></param> /// <returns></returns> public XWPFParagraph GetParagraphArray(int pos) { if (pos >= 0 && pos < paragraphs.Count) { return paragraphs[pos]; } return null; } /// <summary> /// Get the TableCell which belongs to the TableCell /// </summary> /// <param name="cell"></param> /// <returns></returns> public XWPFTableCell GetTableCell(CT_Tc cell) { object obj = cell.Parent; if (!(obj is CT_Row)) return null; CT_Row row = (CT_Row)obj; if (!(row.Parent is CT_Tbl)) return null; CT_Tbl tbl = (CT_Tbl)row.Parent; XWPFTable table = GetTable(tbl); if(table == null){ return null; } XWPFTableRow tableRow = table.GetRow(row); if (tableRow == null) { return null; } return tableRow.GetTableCell(cell); } /** * verifies that cursor is on the right position * @param cursor */ private bool IsCursorInFtn(/*XmlCursor*/XmlDocument cursor) { /*XmlCursor verify = cursor.NewCursor(); verify.ToParent(); if(verify.Object == this.ctFtnEdn){ return true; } return false;*/ throw new NotImplementedException(); } public POIXMLDocumentPart Owner { get { return footnotes; } } /** * * @param cursor * @return the inserted table * @see NPOI.XWPF.UserModel.IBody#insertNewTbl(XmlCursor cursor) */ public XWPFTable InsertNewTbl(/*XmlCursor*/XmlDocument cursor) { /*if(isCursorInFtn(cursor)){ String uri = CTTbl.type.Name.NamespaceURI; String localPart = "tbl"; cursor.BeginElement(localPart,uri); cursor.ToParent(); CTTbl t = (CTTbl)cursor.Object; XWPFTable newT = new XWPFTable(t, this); cursor.RemoveXmlContents(); XmlObject o = null; while(!(o is CTTbl)&&(cursor.ToPrevSibling())){ o = cursor.Object; } if(!(o is CTTbl)){ tables.Add(0, newT); } else{ int pos = tables.IndexOf(getTable((CTTbl)o))+1; tables.Add(pos,newT); } int i=0; cursor = t.NewCursor(); while(cursor.ToPrevSibling()){ o =cursor.Object; if(o is CTP || o is CTTbl) i++; } bodyElements.Add(i, newT); cursor = t.NewCursor(); cursor.ToEndToken(); return newT; } return null;*/ throw new NotImplementedException(); } /** * add a new paragraph at position of the cursor * @param cursor * @return the inserted paragraph * @see NPOI.XWPF.UserModel.IBody#insertNewParagraph(XmlCursor cursor) */ public XWPFParagraph InsertNewParagraph(/*XmlCursor*/XmlDocument cursor) { /*if(isCursorInFtn(cursor)){ String uri = CTP.type.Name.NamespaceURI; String localPart = "p"; cursor.BeginElement(localPart,uri); cursor.ToParent(); CTP p = (CTP)cursor.Object; XWPFParagraph newP = new XWPFParagraph(p, this); XmlObject o = null; while(!(o is CTP)&&(cursor.ToPrevSibling())){ o = cursor.Object; } if((!(o is CTP)) || (CTP)o == p){ paragraphs.Add(0, newP); } else{ int pos = paragraphs.IndexOf(getParagraph((CTP)o))+1; paragraphs.Add(pos,newP); } int i=0; cursor.ToCursor(p.NewCursor()); while(cursor.ToPrevSibling()){ o =cursor.Object; if(o is CTP || o is CTTbl) i++; } bodyElements.Add(i, newP); cursor.ToCursor(p.NewCursor()); cursor.ToEndToken(); return newP; } return null;*/ throw new NotImplementedException(); } /** * add a new table to the end of the footnote * @param table * @return the Added XWPFTable */ public XWPFTable AddNewTbl(CT_Tbl table) { CT_Tbl newTable = ctFtnEdn.AddNewTbl(); newTable.Set(table); XWPFTable xTable = new XWPFTable(newTable, this); tables.Add(xTable); return xTable; } /** * add a new paragraph to the end of the footnote * @param paragraph * @return the Added XWPFParagraph */ public XWPFParagraph AddNewParagraph(CT_P paragraph) { CT_P newPara = ctFtnEdn.AddNewP(paragraph); //newPara.Set(paragraph); XWPFParagraph xPara = new XWPFParagraph(newPara, this); paragraphs.Add(xPara); return xPara; } /** * @see NPOI.XWPF.UserModel.IBody#getXWPFDocument() */ public XWPFDocument GetXWPFDocument() { return document; } /** * returns the Part, to which the body belongs, which you need for Adding relationship to other parts * @see NPOI.XWPF.UserModel.IBody#getPart() */ public POIXMLDocumentPart Part { get { return footnotes; } } /** * Get the PartType of the body * @see NPOI.XWPF.UserModel.IBody#getPartType() */ public BodyType PartType { get { return BodyType.FOOTNOTE; } } public XWPFParagraph Current { get { throw new NotImplementedException(); } } public void Dispose() { throw new NotImplementedException(); } object System.Collections.IEnumerator.Current { get { throw new NotImplementedException(); } } public bool MoveNext() { throw new NotImplementedException(); } public void Reset() { throw new NotImplementedException(); } } }
/* * AjaxSettings.cs * * Copyright ?2007 Michael Schwarz (http://www.ajaxpro.info). * All Rights Reserved. * * 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. */ /* * MS 06-04-04 added DebugEnabled web.config property <debug enabled="true"/> * MS 06-04-05 added OldStyle string collection (see web.config) * MS 06-04-12 added UseAssemblyQualifiedName (see web.config) * MS 06-05-30 changed to new converter dictionary * MS 06-06-07 added OnlyAllowTypesInList property (see web.config) * MS 06-10-06 using new JavaScriptConverterList for .NET 1.1 * MS 07-04-24 added IncludeTypeProperty * added UseSimpleObjectNaming * using new AjaxSecurityProvider * fixed Ajax token * */ using System; using System.Collections; #if(NET20) using System.Collections.Generic; #endif namespace AjaxPro { #if(JSONLIB) internal class AjaxSettings { private System.Collections.Specialized.StringCollection m_OldStyle = new System.Collections.Specialized.StringCollection(); private bool m_IncludeTypeProperty = false; #if(NET20) internal Dictionary<Type, IJavaScriptConverter> SerializableConverters; internal Dictionary<Type, IJavaScriptConverter> DeserializableConverters; #else internal Hashtable SerializableConverters; internal Hashtable DeserializableConverters; #endif /// <summary> /// Initializes a new instance of the <see cref="AjaxSettings"/> class. /// </summary> internal AjaxSettings() { #if(NET20) SerializableConverters = new Dictionary<Type, IJavaScriptConverter>(); DeserializableConverters = new Dictionary<Type, IJavaScriptConverter>(); #else SerializableConverters = new Hashtable(); DeserializableConverters = new Hashtable(); #endif } /// <summary> /// Gets or sets several settings that will be used for old styled web applications. /// </summary> internal System.Collections.Specialized.StringCollection OldStyle { get { return m_OldStyle; } set { m_OldStyle = value; } } internal bool IncludeTypeProperty { get { return m_IncludeTypeProperty; } set { m_IncludeTypeProperty = value; } } } #else internal class AjaxSettings { private System.Collections.Hashtable m_UrlNamespaceMappings = new System.Collections.Hashtable(); private bool m_DebugEnabled = false; private bool m_UseAssemblyQualifiedName = false; private bool m_IncludeTypeProperty = false; private bool m_UseSimpleObjectNaming = false; private System.Collections.Specialized.StringCollection m_OldStyle = new System.Collections.Specialized.StringCollection(); private AjaxSecurity m_AjaxSecurity = null; private string m_TokenSitePassword = "ajaxpro"; #if(NET20) internal Dictionary<Type, IJavaScriptConverter> SerializableConverters; internal Dictionary<Type, IJavaScriptConverter> DeserializableConverters; #else internal JavaScriptConverterList SerializableConverters; internal JavaScriptConverterList DeserializableConverters; #endif private string m_TypeJavaScriptProvider = null; private bool m_OnlyAllowTypesInList = false; private string m_CoreScript = null; private System.Collections.Specialized.StringDictionary m_ScriptReplacements = new System.Collections.Specialized.StringDictionary(); /// <summary> /// Initializes a new instance of the <see cref="AjaxSettings"/> class. /// </summary> internal AjaxSettings() { #if(NET20) SerializableConverters = new Dictionary<Type, IJavaScriptConverter>(); DeserializableConverters = new Dictionary<Type, IJavaScriptConverter>(); #else SerializableConverters = new JavaScriptConverterList(); DeserializableConverters = new JavaScriptConverterList(); #endif } #region Public Properties internal string TypeJavaScriptProvider { get { return m_TypeJavaScriptProvider; } set { m_TypeJavaScriptProvider = value; } } /// <summary> /// Gets or sets the URL namespace mappings. /// </summary> /// <value>The URL namespace mappings.</value> internal System.Collections.Hashtable UrlNamespaceMappings { get{ return m_UrlNamespaceMappings; } set{ m_UrlNamespaceMappings = value; } } /// <summary> /// Gets or sets a value indicating whether [only allow types in list]. /// </summary> /// <value> /// <c>true</c> if [only allow types in list]; otherwise, <c>false</c>. /// </value> internal bool OnlyAllowTypesInList { get { return m_OnlyAllowTypesInList; } set { m_OnlyAllowTypesInList = value; } } /// <summary> /// Gets or sets if debug information should be enabled. /// </summary> /// <value><c>true</c> if [debug enabled]; otherwise, <c>false</c>.</value> internal bool DebugEnabled { get { return m_DebugEnabled; } set { m_DebugEnabled = value; } } /// <summary> /// Gets or sets the use of the AssemblyQualifiedName. /// </summary> /// <value> /// <c>true</c> if [use assembly qualified name]; otherwise, <c>false</c>. /// </value> internal bool UseAssemblyQualifiedName { get { return m_UseAssemblyQualifiedName; } set { m_UseAssemblyQualifiedName = value; } } internal bool IncludeTypeProperty { get { return m_IncludeTypeProperty; } set { m_IncludeTypeProperty = value; } } internal bool UseSimpleObjectNaming { get { return m_UseSimpleObjectNaming; } set { m_UseSimpleObjectNaming = value; } } /// <summary> /// Gets or sets several settings that will be used for old styled web applications. /// </summary> /// <value>The old style.</value> internal System.Collections.Specialized.StringCollection OldStyle { get { return m_OldStyle; } set { m_OldStyle = value; } } /// <summary> /// Gets or sets the encryption. /// </summary> /// <value>The encryption.</value> internal AjaxSecurity Security { get { return m_AjaxSecurity; } set { m_AjaxSecurity = value; } } /// <summary> /// Gets or sets the token site password. /// </summary> /// <value>The token site password.</value> internal string TokenSitePassword { get{ return m_TokenSitePassword; } set{ m_TokenSitePassword = value; } } /// <summary> /// Gets or sets the core script. /// </summary> /// <value>The core script.</value> [Obsolete("The recommended alternative is to configure a scriptReplacement/file in web.config.", true)] internal string CoreScript { get{ return m_CoreScript; } set{ m_CoreScript = value; } } /// <summary> /// Gets or sets the script replacements. /// </summary> /// <value>The script replacements.</value> internal System.Collections.Specialized.StringDictionary ScriptReplacements { get{ return m_ScriptReplacements; } set{ m_ScriptReplacements = value; } } #endregion } #endif }
namespace android.content.pm { [global::MonoJavaBridge.JavaClass()] public partial class ResolveInfo : java.lang.Object, android.os.Parcelable { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; protected ResolveInfo(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } [global::MonoJavaBridge.JavaClass()] public partial class DisplayNameComparator : java.lang.Object, java.util.Comparator { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; protected DisplayNameComparator(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } private static global::MonoJavaBridge.MethodId _m0; public virtual int compare(android.content.pm.ResolveInfo arg0, android.content.pm.ResolveInfo arg1) { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.content.pm.ResolveInfo.DisplayNameComparator.staticClass, "compare", "(Landroid/content/pm/ResolveInfo;Landroid/content/pm/ResolveInfo;)I", ref global::android.content.pm.ResolveInfo.DisplayNameComparator._m0, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m1; public virtual int compare(java.lang.Object arg0, java.lang.Object arg1) { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.content.pm.ResolveInfo.DisplayNameComparator.staticClass, "compare", "(Ljava/lang/Object;Ljava/lang/Object;)I", ref global::android.content.pm.ResolveInfo.DisplayNameComparator._m1, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m2; public DisplayNameComparator(android.content.pm.PackageManager arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::android.content.pm.ResolveInfo.DisplayNameComparator._m2.native == global::System.IntPtr.Zero) global::android.content.pm.ResolveInfo.DisplayNameComparator._m2 = @__env.GetMethodIDNoThrow(global::android.content.pm.ResolveInfo.DisplayNameComparator.staticClass, "<init>", "(Landroid/content/pm/PackageManager;)V"); global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.content.pm.ResolveInfo.DisplayNameComparator.staticClass, global::android.content.pm.ResolveInfo.DisplayNameComparator._m2, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); Init(@__env, handle); } static DisplayNameComparator() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.content.pm.ResolveInfo.DisplayNameComparator.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/content/pm/ResolveInfo$DisplayNameComparator")); } } private static global::MonoJavaBridge.MethodId _m0; public override global::java.lang.String toString() { return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.String>(this, global::android.content.pm.ResolveInfo.staticClass, "toString", "()Ljava/lang/String;", ref global::android.content.pm.ResolveInfo._m0) as java.lang.String; } private static global::MonoJavaBridge.MethodId _m1; public virtual void dump(android.util.Printer arg0, java.lang.String arg1) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.content.pm.ResolveInfo.staticClass, "dump", "(Landroid/util/Printer;Ljava/lang/String;)V", ref global::android.content.pm.ResolveInfo._m1, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } public void dump(global::android.util.PrinterDelegate arg0, java.lang.String arg1) { dump((global::android.util.PrinterDelegateWrapper)arg0, arg1); } private static global::MonoJavaBridge.MethodId _m2; public virtual void writeToParcel(android.os.Parcel arg0, int arg1) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.content.pm.ResolveInfo.staticClass, "writeToParcel", "(Landroid/os/Parcel;I)V", ref global::android.content.pm.ResolveInfo._m2, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m3; public virtual int describeContents() { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.content.pm.ResolveInfo.staticClass, "describeContents", "()I", ref global::android.content.pm.ResolveInfo._m3); } private static global::MonoJavaBridge.MethodId _m4; public virtual global::java.lang.CharSequence loadLabel(android.content.pm.PackageManager arg0) { return global::MonoJavaBridge.JavaBridge.CallIJavaObjectMethod<java.lang.CharSequence>(this, global::android.content.pm.ResolveInfo.staticClass, "loadLabel", "(Landroid/content/pm/PackageManager;)Ljava/lang/CharSequence;", ref global::android.content.pm.ResolveInfo._m4, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as java.lang.CharSequence; } private static global::MonoJavaBridge.MethodId _m5; public virtual global::android.graphics.drawable.Drawable loadIcon(android.content.pm.PackageManager arg0) { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.content.pm.ResolveInfo.staticClass, "loadIcon", "(Landroid/content/pm/PackageManager;)Landroid/graphics/drawable/Drawable;", ref global::android.content.pm.ResolveInfo._m5, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as android.graphics.drawable.Drawable; } public new int IconResource { get { return getIconResource(); } } private static global::MonoJavaBridge.MethodId _m6; public virtual int getIconResource() { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.content.pm.ResolveInfo.staticClass, "getIconResource", "()I", ref global::android.content.pm.ResolveInfo._m6); } private static global::MonoJavaBridge.MethodId _m7; public ResolveInfo() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::android.content.pm.ResolveInfo._m7.native == global::System.IntPtr.Zero) global::android.content.pm.ResolveInfo._m7 = @__env.GetMethodIDNoThrow(global::android.content.pm.ResolveInfo.staticClass, "<init>", "()V"); global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.content.pm.ResolveInfo.staticClass, global::android.content.pm.ResolveInfo._m7); Init(@__env, handle); } internal static global::MonoJavaBridge.FieldId _activityInfo2113; public global::android.content.pm.ActivityInfo activityInfo { get { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.GetObjectField(this.JvmHandle, _activityInfo2113)) as android.content.pm.ActivityInfo; } set { } } internal static global::MonoJavaBridge.FieldId _serviceInfo2114; public global::android.content.pm.ServiceInfo serviceInfo { get { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.GetObjectField(this.JvmHandle, _serviceInfo2114)) as android.content.pm.ServiceInfo; } set { } } internal static global::MonoJavaBridge.FieldId _filter2115; public global::android.content.IntentFilter filter { get { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.GetObjectField(this.JvmHandle, _filter2115)) as android.content.IntentFilter; } set { } } internal static global::MonoJavaBridge.FieldId _priority2116; public int priority { get { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return @__env.GetIntField(this.JvmHandle, _priority2116); } set { } } internal static global::MonoJavaBridge.FieldId _preferredOrder2117; public int preferredOrder { get { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return @__env.GetIntField(this.JvmHandle, _preferredOrder2117); } set { } } internal static global::MonoJavaBridge.FieldId _match2118; public int match { get { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return @__env.GetIntField(this.JvmHandle, _match2118); } set { } } internal static global::MonoJavaBridge.FieldId _specificIndex2119; public int specificIndex { get { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return @__env.GetIntField(this.JvmHandle, _specificIndex2119); } set { } } internal static global::MonoJavaBridge.FieldId _isDefault2120; public bool isDefault { get { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return @__env.GetBooleanField(this.JvmHandle, _isDefault2120); } set { } } internal static global::MonoJavaBridge.FieldId _labelRes2121; public int labelRes { get { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return @__env.GetIntField(this.JvmHandle, _labelRes2121); } set { } } internal static global::MonoJavaBridge.FieldId _nonLocalizedLabel2122; public global::java.lang.CharSequence nonLocalizedLabel { get { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.lang.CharSequence>(@__env.GetObjectField(this.JvmHandle, _nonLocalizedLabel2122)) as java.lang.CharSequence; } set { } } internal static global::MonoJavaBridge.FieldId _icon2123; public int icon { get { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return @__env.GetIntField(this.JvmHandle, _icon2123); } set { } } internal static global::MonoJavaBridge.FieldId _resolvePackageName2124; public global::java.lang.String resolvePackageName { get { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<java.lang.String>(@__env.GetObjectField(this.JvmHandle, _resolvePackageName2124)) as java.lang.String; } set { } } internal static global::MonoJavaBridge.FieldId _CREATOR2125; public static global::android.os.Parcelable_Creator CREATOR { get { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.os.Parcelable_Creator>(@__env.GetStaticObjectField(global::android.content.pm.ResolveInfo.staticClass, _CREATOR2125)) as android.os.Parcelable_Creator; } } static ResolveInfo() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.content.pm.ResolveInfo.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/content/pm/ResolveInfo")); global::android.content.pm.ResolveInfo._activityInfo2113 = @__env.GetFieldIDNoThrow(global::android.content.pm.ResolveInfo.staticClass, "activityInfo", "Landroid/content/pm/ActivityInfo;"); global::android.content.pm.ResolveInfo._serviceInfo2114 = @__env.GetFieldIDNoThrow(global::android.content.pm.ResolveInfo.staticClass, "serviceInfo", "Landroid/content/pm/ServiceInfo;"); global::android.content.pm.ResolveInfo._filter2115 = @__env.GetFieldIDNoThrow(global::android.content.pm.ResolveInfo.staticClass, "filter", "Landroid/content/IntentFilter;"); global::android.content.pm.ResolveInfo._priority2116 = @__env.GetFieldIDNoThrow(global::android.content.pm.ResolveInfo.staticClass, "priority", "I"); global::android.content.pm.ResolveInfo._preferredOrder2117 = @__env.GetFieldIDNoThrow(global::android.content.pm.ResolveInfo.staticClass, "preferredOrder", "I"); global::android.content.pm.ResolveInfo._match2118 = @__env.GetFieldIDNoThrow(global::android.content.pm.ResolveInfo.staticClass, "match", "I"); global::android.content.pm.ResolveInfo._specificIndex2119 = @__env.GetFieldIDNoThrow(global::android.content.pm.ResolveInfo.staticClass, "specificIndex", "I"); global::android.content.pm.ResolveInfo._isDefault2120 = @__env.GetFieldIDNoThrow(global::android.content.pm.ResolveInfo.staticClass, "isDefault", "Z"); global::android.content.pm.ResolveInfo._labelRes2121 = @__env.GetFieldIDNoThrow(global::android.content.pm.ResolveInfo.staticClass, "labelRes", "I"); global::android.content.pm.ResolveInfo._nonLocalizedLabel2122 = @__env.GetFieldIDNoThrow(global::android.content.pm.ResolveInfo.staticClass, "nonLocalizedLabel", "Ljava/lang/CharSequence;"); global::android.content.pm.ResolveInfo._icon2123 = @__env.GetFieldIDNoThrow(global::android.content.pm.ResolveInfo.staticClass, "icon", "I"); global::android.content.pm.ResolveInfo._resolvePackageName2124 = @__env.GetFieldIDNoThrow(global::android.content.pm.ResolveInfo.staticClass, "resolvePackageName", "Ljava/lang/String;"); global::android.content.pm.ResolveInfo._CREATOR2125 = @__env.GetStaticFieldIDNoThrow(global::android.content.pm.ResolveInfo.staticClass, "CREATOR", "Landroid/os/Parcelable$Creator;"); } } }
using System; using Gtk; using System.Reflection; using Moscrif.IDE.Components; using Moscrif.IDE.Controls; using Mono.TextEditor; using Mono.TextEditor.Highlighting; using System.IO; using System.Xml; using System.Collections; using System.Collections.Generic; using System.Text; using MessageDialogs = Moscrif.IDE.Controls.MessageDialog; using System.Linq; using Mono.Data.Sqlite; using Moscrif.IDE.Tool; using Moscrif.IDE.Completion; //using Newtonsoft.Json; //using Newtonsoft.Json.Linq; namespace Moscrif.IDE.Actions { public class GenerateAutoCompleteWords : Gtk.Action { public GenerateAutoCompleteWords():base("generateAutoComplete",MainClass.Languages.Translate("menu_generate_autoComplete"),MainClass.Languages.Translate("menu_title_generate_autoComplete"),null) { } private SqlLiteDal sqlLiteDal; protected override void OnActivated () { MessageDialogs md = new MessageDialogs(MessageDialogs.DialogButtonType.OkCancel, "Are you sure?", "", Gtk.MessageType.Question); int result = md.ShowDialog(); if(result != (int)Gtk.ResponseType.Ok){ return; } ProgressDialog progressDialog; string filename = System.IO.Path.Combine(MainClass.Paths.ConfingDir, "completedcache"); sqlLiteDal = new SqlLiteDal(filename); string sql = ""; if(sqlLiteDal.CheckExistTable("completed") ){ sql = "DROP TABLE completed ;"; sqlLiteDal.RunSqlScalar(sql); } sql = "CREATE TABLE completed (id INTEGER PRIMARY KEY, name TEXT, signature TEXT, type NUMERIC, parent TEXT,summary TEXT ,returnType TEXT ) ;"; sqlLiteDal.RunSqlScalar(sql); SyntaxMode mode = new SyntaxMode(); mode = SyntaxModeService.GetSyntaxMode("text/moscrif"); progressDialog = new ProgressDialog("Generated...",ProgressDialog.CancelButtonType.None, mode.Keywords.Count() ,MainClass.MainWindow); foreach (Keywords kw in mode.Keywords){ progressDialog.Update(kw.ToString()); foreach (string wrd in kw.Words){ insertNewRow(wrd,wrd,(int)CompletionDataTyp.keywords,"","",""); } } Gtk.FileChooserDialog fc = new Gtk.FileChooserDialog("data.json", null, FileChooserAction.Open, "Cancel", ResponseType.Cancel, "Open", ResponseType.Accept); fc.TransientFor = MainClass.MainWindow; fc.SetCurrentFolder(@"d:\Work\docs-api\output\"); if (fc.Run() != (int)ResponseType.Accept) { return; } string json ; string fileName = fc.Filename; progressDialog.Destroy(); fc.Destroy(); progressDialog = new ProgressDialog("Generated...",ProgressDialog.CancelButtonType.None,100 ,MainClass.MainWindow); using (StreamReader file = new StreamReader(fileName)) { json = file.ReadToEnd(); file.Close(); file.Dispose(); } //XmlDocument doc = (XmlDocument)JsonConvert.DeserializeXmlNode(json); //doc.Save(fileName+"xml"); /*JObject jDoc= JObject.Parse(json); //classes Console.WriteLine("o.Count->"+jDoc.Count); foreach (JProperty jp in jDoc.Properties()){ Console.WriteLine(jp.Name); } Console.WriteLine("------------"); JObject classes = (JObject)jDoc["classes"]; foreach (JProperty jp in classes.Properties()){ Console.WriteLine(jp.Name); JObject classDefin = (JObject)classes[jp.Name]; string name = (string)classDefin["name"]; string shortname = (string)classDefin["shortname"]; string description = (string)classDefin["description"]; //string type = (string)classDefin["type"]; insertNewRow(name,name,(int)CompletionDataTyp.types,"",description,name); } Console.WriteLine("------------"); JArray classitems = (JArray)jDoc["classitems"]; foreach (JObject classitem in classitems){ string name = (string)classitem["name"]; Console.WriteLine(name); string description = (string)classitem["description"]; string itemtype = (string)classitem["itemtype"]; string classParent = (string)classitem["class"]; string signature = (string)classitem["name"]; CompletionDataTyp type = CompletionDataTyp.noting; string returnType= classParent; switch (itemtype){ case "method":{ JArray paramsArray = (JArray)classitem["params"]; signature = signature+ GetParams(paramsArray); type = CompletionDataTyp.members; JObject returnJO =(JObject)classitem["return"] ; if(returnJO!=null){ returnType = (string)returnJO["type"]; } break; } case "property":{ string tmpType = (string)classitem["type"]; if(!String.IsNullOrEmpty(tmpType)){ returnType=tmpType.Replace("{","").Replace("}",""); } type = CompletionDataTyp.properties; break; } case "event":{ JArray paramsArray = (JArray)classitem["params"]; signature = signature+ GetParams(paramsArray); type = CompletionDataTyp.events; break; } case "attribute":{ continue; break; } default:{ type = CompletionDataTyp.noting; break; } } insertNewRow(name,signature,(int)type,classParent,description,returnType); }*/ //classitems // string name = (string)o["project"]["name"]; // Console.WriteLine(name); progressDialog.Destroy(); md = new MessageDialogs(MessageDialogs.DialogButtonType.Ok, "Done", "", Gtk.MessageType.Info); md.ShowDialog(); return; /* Gtk.FileChooserDialog fc = new Gtk.FileChooserDialog("Select DOC Directory (with xml)", null, FileChooserAction.SelectFolder, "Cancel", ResponseType.Cancel, "Open", ResponseType.Accept); FileInfo[] xmls = new FileInfo[]{}; if (fc.Run() == (int)ResponseType.Accept) { DirectoryInfo di = new DirectoryInfo(fc.Filename); xmls = di.GetFiles("*.xml"); //List<string> output = new List<string>(); //MainClass.CompletedCache.ListTypes= listSignature.Distinct().ToList(); //MainClass.CompletedCache.ListMembers= listMemberSignature.Distinct().ToList(); } progressDialog.Destroy(); fc.Destroy(); progressDialog = new ProgressDialog("Generated...",ProgressDialog.CancelButtonType.None,xmls.Length ,MainClass.MainWindow); foreach (FileInfo xml in xmls) { try { progressDialog.Update(xml.Name); if(!xml.Name.StartsWith("_")) getObject(xml.FullName); } catch(Exception ex) { Console.WriteLine(ex.Message); Console.WriteLine(ex.StackTrace); return; } } progressDialog.Destroy(); md = new MessageDialogs(MessageDialogs.DialogButtonType.Ok, "Done", "", Gtk.MessageType.Info); md.ShowDialog();*/ } private void getObject(string file ){ XmlDocument rssDoc; XmlNode nodeRss = new XmlDocument(); //XmlNode nodeChannel = new XmlDocument(); XmlNode nodeItem; try{ XmlTextReader reader = new XmlTextReader(file); rssDoc = new XmlDocument(); rssDoc.Load(reader); for (int i = 0; i < rssDoc.ChildNodes.Count; i++) { if (rssDoc.ChildNodes[i].Name == "doc"){ nodeRss = rssDoc.ChildNodes[i]; } } /*for (int i = 0; i < nodeRss.ChildNodes.Count; i++){ if (nodeRss.ChildNodes[i].Name == "members"){ nodeChannel = nodeRss.ChildNodes[i]; } }*/ string parent = ""; for (int i = 0; i < nodeRss.ChildNodes.Count; i++) { if (nodeRss.ChildNodes[i].Name == "member") { nodeItem = nodeRss.ChildNodes[i]; string name=""; string signature=""; string summary = GetSummary(nodeItem); bool visibility = false; foreach (XmlAttribute atrb in nodeItem.Attributes){ if (atrb.Name == "name"){ name =atrb.InnerText; } if (atrb.Name == "signature"){ signature =atrb.InnerText; } if (atrb.Name == "visibility"){ if (atrb.InnerText.Trim() == "private"){ visibility = true; } } } if(visibility) continue; if(!string.IsNullOrEmpty(name) && !string.IsNullOrEmpty(signature)){ if(signature.Trim().StartsWith("(") || signature.Trim().StartsWith("{") || signature.Trim().StartsWith("[") || signature.Trim().StartsWith("!")){ continue; } if(name.StartsWith("T:")){ parent =signature; insertNewRow(signature,signature,(int)CompletionDataTyp.types,"",summary,""); } if(name.Contains("this")) continue; if (name.StartsWith("P:")){ int indx = signature.Trim().IndexOf("."); if(indx>0){ string tmp = signature.Substring(0,indx); if(tmp.Length<2) continue; insertNewRow(tmp,signature,(int)CompletionDataTyp.properties,parent,summary,""); //listMemberSignature.Add(tmp); continue; } if(signature.Length<2) continue; insertNewRow(signature,signature,(int)CompletionDataTyp.properties,parent,summary,""); } else if(name.StartsWith("M:")){ int indx = signature.IndexOf("("); if(indx>0){ string tmp = signature.Substring(0,indx); if(tmp.Length<2) continue; insertNewRow(tmp,signature,(int)CompletionDataTyp.members,parent,summary,""); continue; } if(signature.Length<2) continue; insertNewRow(signature,signature,(int)CompletionDataTyp.members,parent,summary,""); } else if(name.StartsWith("E:")){ int indx = signature.IndexOf("("); if(indx>0){ string tmp = signature.Substring(0,indx); insertNewRow(tmp,signature,(int)CompletionDataTyp.events,parent,summary,""); continue; } insertNewRow(signature,signature,(int)CompletionDataTyp.events,parent,summary,""); } } } } } catch(Exception ex){ MessageDialogs md = new MessageDialogs(MessageDialogs.DialogButtonType.Ok, "ERROR", ex.Message, Gtk.MessageType.Error); md.ShowDialog(); Console.WriteLine(file); Console.WriteLine(ex.Message); } } private string GetSummary (XmlNode nodeItem){ for (int j = 0; j < nodeItem.ChildNodes.Count; j++) { if (nodeItem.ChildNodes[j].Name == "summary") { string summary =nodeItem.ChildNodes[j].InnerText; summary = summary.Trim(); summary = summary.Replace("\t"," "); return summary; } } return ""; } /* private string GetParams(JArray paramsArray){ if(paramsArray == null) return "()"; string paramsString = "("; foreach (JObject jo in paramsArray){ StringBuilder param = new StringBuilder(); string name = (string)jo["name"]; string description = (string)jo["description"]; string type = (string)jo["type"]; JValue optionalStr = (JValue)jo["optional"]; bool optional = false; if(optionalStr!=null){ if (!bool.TryParse(optionalStr.ToString(),out optional)){ optional = false; } } string optdefault = (string)jo["optdefault"]; JValue multipleStr = (JValue)jo["multiple"]; bool multiple = false; if(multipleStr!=null){ if (!bool.TryParse(multipleStr.ToString(),out multiple)){ multiple = false; } } param.Append(name); if(!String.IsNullOrEmpty(optdefault)) param.Append("="+optdefault); if((optional) && (String.IsNullOrEmpty(optdefault))) param.Append("=undefined"); if(multiple) param.Append(",.."); paramsString = paramsString + param.ToString()+","; } paramsString = paramsString.TrimEnd(','); paramsString = paramsString+ ")"; return paramsString; } */ private void insertNewRow(string name,string signature,int type,string parent,string summary,string returnType){ string sql; signature = signature.Replace("'", "" ); if(!String.IsNullOrEmpty(summary)) summary = summary.Replace("'", "" ); if(String.IsNullOrEmpty(parent)) sql = String.Format("INSERT INTO completed (name,signature,type,summary,returnType) values ( '{0}' , '{1}' , '{2}', '{3}','{4}' ) ;",name,signature,type,summary,returnType); else sql = String.Format("INSERT INTO completed (name,signature,type, parent,summary,returnType) values ( '{0}' , '{3}.{1}' , '{2}', '{3}', '{4}','{5}' ) ;",name,signature,type,parent,summary,returnType); sqlLiteDal.RunSqlScalar(sql); } /* protected override void OnActivated () { MainClass.CompletedCache.ListKeywords = new System.Collections.Generic.List<string>(); MainClass.CompletedCache.ListTypes = new System.Collections.Generic.List<string>(); SyntaxMode mode = new SyntaxMode(); mode = SyntaxModeService.GetSyntaxMode("text/moscrif"); foreach (Keywords kw in mode.Keywords){ foreach (string wrd in kw.Words){ MainClass.CompletedCache.ListKeywords.Add(wrd); } } MainClass.CompletedCache.SaveCompletedCache(); List<string> listSignature = new List<string>(); List<string> listMemberSignature = new List<string>(); Gtk.FileChooserDialog fc = new Gtk.FileChooserDialog("Select DOC Directory (with xml)", null, FileChooserAction.SelectFolder, "Cancel", ResponseType.Cancel, "Open", ResponseType.Accept); if (fc.Run() == (int)ResponseType.Accept) { DirectoryInfo di = new DirectoryInfo(fc.Filename); FileInfo[] xmls = di.GetFiles("*.xml"); List<string> output = new List<string>(); foreach (FileInfo xml in xmls) { try { getObject(xml.FullName, ref listSignature, ref listMemberSignature); } catch(Exception ex) { Console.WriteLine(ex.Message); Console.WriteLine(ex.StackTrace); return; } } MainClass.CompletedCache.ListTypes= listSignature.Distinct().ToList(); MainClass.CompletedCache.ListMembers= listMemberSignature.Distinct().ToList(); } fc.Destroy(); MainClass.CompletedCache.SaveCompletedCache(); MessageDialogs md = new MessageDialogs(MessageDialogs.DialogButtonType.Ok, "Done", "", Gtk.MessageType.Info); md.ShowDialog(); } private void getObject(string file , ref List<string> listSignature,ref List<string> listMemberSignature){ XmlDocument rssDoc; XmlNode nodeRss = new XmlDocument(); XmlNode nodeChannel = new XmlDocument(); XmlNode nodeItem; try{ XmlTextReader reader = new XmlTextReader(file); rssDoc = new XmlDocument(); rssDoc.Load(reader); for (int i = 0; i < rssDoc.ChildNodes.Count; i++) { if (rssDoc.ChildNodes[i].Name == "doc"){ nodeRss = rssDoc.ChildNodes[i]; } } for (int i = 0; i < nodeRss.ChildNodes.Count; i++){ if (nodeRss.ChildNodes[i].Name == "members") { nodeChannel = nodeRss.ChildNodes[i]; } } for (int i = 0; i < nodeChannel.ChildNodes.Count; i++) { if (nodeChannel.ChildNodes[i].Name == "member") { nodeItem = nodeChannel.ChildNodes[i]; string name=""; string signature=""; foreach (XmlAttribute atrb in nodeItem.Attributes){ if (atrb.Name == "name"){ name =atrb.InnerText; } if (atrb.Name == "signature"){ signature =atrb.InnerText; } } if(!string.IsNullOrEmpty(name) && !string.IsNullOrEmpty(signature)){ if(signature.Trim().StartsWith("(") || signature.Trim().StartsWith("{") || signature.Trim().StartsWith("[") || signature.Trim().StartsWith("!")){ continue; } if(name.StartsWith("T:")){ listSignature.Add(signature); } else if (name.StartsWith("P:")){ int indx = signature.Trim().IndexOf("."); if(indx>0){ string tmp = signature.Substring(0,indx); if(tmp.Length<2) continue; listMemberSignature.Add(tmp); continue; } if(signature.Length<2) continue; listMemberSignature.Add(signature); } else if(name.StartsWith("M:")){ int indx = signature.IndexOf("("); if(indx>0){ string tmp = signature.Substring(0,indx); if(tmp.Length<2) continue; listMemberSignature.Add(tmp); continue; } if(signature.Length<2) continue; listMemberSignature.Add(signature); } else if(name.StartsWith("E:")){ int indx = signature.IndexOf("("); if(indx>0){ string tmp = signature.Substring(0,indx); listMemberSignature.Add(tmp); continue; } listMemberSignature.Add(signature); } } } } } catch(Exception ex){ MessageDialogs md = new MessageDialogs(MessageDialogs.DialogButtonType.Ok, "ERROR", ex.Message, Gtk.MessageType.Error); md.ShowDialog(); Console.WriteLine(file); Console.WriteLine(ex.Message); } }*/ } }
using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Http2.Hpack; using Http2.Internal; namespace Http2 { /// <summary> /// Implementation of a HTTP/2 stream /// </summary> internal class StreamImpl : IStream { /// <summary>The ID of the stream</summary> public uint Id { get; } /// <summary>Returns the current state of the stream</summary> public StreamState State { get { lock (stateMutex) { return this.state; } } } private readonly Connection connection; private StreamState state; private readonly object stateMutex = new object(); /// Allows only a single write at a time private SemaphoreSlim writeMutex = new SemaphoreSlim(1); private bool headersSent = false; private bool dataSent = false; private enum HeaderReceptionState : byte { ReceivedNoHeaders, ReceivedInformationalHeaders, ReceivedAllHeaders, } private HeaderReceptionState headersReceived = HeaderReceptionState.ReceivedNoHeaders; private bool dataReceived = false; // A trailersReceived field is not necessary, since receiving trailers // moves the state to HalfClosedRemote private List<HeaderField> inHeaders; private List<HeaderField> inTrailers; // Semaphores for unblocking async access operations private readonly AsyncManualResetEvent readDataPossible = new AsyncManualResetEvent(false); private readonly AsyncManualResetEvent readHeadersPossible = new AsyncManualResetEvent(false); private readonly AsyncManualResetEvent readTrailersPossible = new AsyncManualResetEvent(false); private long declaredInContentLength = -1; private long totalInData = 0; private int totalReceiveWindow; private int receiveWindow; /// Intrusive linked list item for receive buffer queue private class ReceiveQueueItem { public byte[] Buffer; public int Offset; public int Count; public ReceiveQueueItem Next; public ReceiveQueueItem(ArraySegment<byte> segment) { this.Buffer = segment.Array; this.Offset = segment.Offset; this.Count = segment.Count; } } private ReceiveQueueItem receiveQueueHead = null; private int ReceiveQueueLength { get { int len = 0; var item = receiveQueueHead; while (item != null) { len += item.Count; item = item.Next; } return len; } } /// Reusable empty list of headers private static readonly HeaderField[] EmptyHeaders = new HeaderField[0]; public StreamImpl( Connection connection, uint streamId, StreamState state, int receiveWindow) { this.connection = connection; this.Id = streamId; // In case we are on the server side and the client opens a stream // the expected state is Open and we get headers. // TODO: Or are we only Idle and get headers soon after that? // In case we are on the client side we are idle and need // to send headers before doing anything. this.state = state; this.receiveWindow = receiveWindow; this.totalReceiveWindow = receiveWindow; } private async Task SendHeaders( IEnumerable<HeaderField> headers, bool endOfStream) { var fhh = new FrameHeader { StreamId = this.Id, Type = FrameType.Headers, // EndOfHeaders will be auto-set Flags = endOfStream ? (byte)HeadersFrameFlags.EndOfStream : (byte)0, }; var res = await connection.writer.WriteHeaders(fhh, headers); if (res != ConnectionWriter.WriteResult.Success) { // TODO: Improve the exception throw new Exception("Can not write to stream"); } } public Task WriteHeadersAsync( IEnumerable<HeaderField> headers, bool endOfStream) { HeaderValidationResult hvr; // TODO: For push promises other validates might need to be used if (connection.IsServer) hvr = HeaderValidator.ValidateResponseHeaders(headers); else hvr = HeaderValidator.ValidateRequestHeaders(headers); if (hvr != HeaderValidationResult.Ok) { throw new Exception(hvr.ToString()); } return WriteValidatedHeadersAsync(headers, endOfStream); } internal async Task WriteValidatedHeadersAsync( IEnumerable<HeaderField> headers, bool endOfStream) { var removeStream = false; await writeMutex.WaitAsync(); try { // Check what already has been sent lock (stateMutex) { // Check if data has already been sent. // Headers may be only sent in front of all data. if (dataSent) { throw new Exception("Attempted to write headers after data"); } if (headersSent) { // TODO: Allow for multiple header packets or not? // It seems it is required for informational headers to work // However we might check later on if a status code different // from 100 was already sent and if yes don't allow further // headers to be sent. } headersSent = true; switch (state) { case StreamState.Idle: state = StreamState.Open; break; case StreamState.ReservedLocal: state = StreamState.HalfClosedRemote; break; case StreamState.Reset: throw new StreamResetException(); // TODO: Check if the other stream states are covered // by the dataSent/headersSent logic. // At least in order for a stream to be closed headers // need to be sent. With push promises it might be different } if (state == StreamState.Open && endOfStream) { state = StreamState.HalfClosedLocal; } else if (state == StreamState.HalfClosedRemote && endOfStream) { state = StreamState.Closed; removeStream = true; } } await SendHeaders(headers, endOfStream); // TODO: Use result } finally { writeMutex.Release(); if (removeStream) { connection.UnregisterStream(this); } } } public async Task WriteTrailersAsync(IEnumerable<HeaderField> headers) { HeaderValidationResult hvr = HeaderValidator.ValidateTrailingHeaders(headers); // TODO: For push promises other validates might need to be used if (hvr != HeaderValidationResult.Ok) { throw new Exception(hvr.ToString()); } var removeStream = false; await writeMutex.WaitAsync(); try { // Check what already has been sent lock (stateMutex) { if (!dataSent) { throw new Exception("Attempted to write trailers without data"); } switch (state) { case StreamState.Open: state = StreamState.HalfClosedLocal; break; case StreamState.HalfClosedRemote: state = StreamState.HalfClosedRemote; state = StreamState.Closed; removeStream = true; break; case StreamState.Idle: case StreamState.ReservedRemote: case StreamState.HalfClosedLocal: case StreamState.Closed: throw new Exception("Invalid state for sending trailers"); case StreamState.Reset: throw new StreamResetException(); case StreamState.ReservedLocal: // We can't be in here if we already have data sent throw new Exception("Unexpected state: ReservedLocal after data sent"); } } await SendHeaders(headers, true); // TODO: Use result } finally { writeMutex.Release(); if (removeStream) { connection.UnregisterStream(this); } } } public void Cancel() { var writeResetTask = Reset(ErrorCode.Cancel, false); // We don't really need to care about this task. // Even if it fails the stream will be reset anyway internally. // And failing most likely occured because of a dead connection. // The only helpful thing could be attaching a continuation for // logging } public void Dispose() { // Disposing a stream is equivalent to resetting it Cancel(); } internal ValueTask<ConnectionWriter.WriteResult> Reset( ErrorCode errorCode, bool fromRemote) { ValueTask<ConnectionWriter.WriteResult> writeResetTask = new ValueTask<ConnectionWriter.WriteResult>( ConnectionWriter.WriteResult.Success); lock (stateMutex) { if (state == StreamState.Reset || state == StreamState.Closed) { // Already reset or fully closed return writeResetTask; } state = StreamState.Reset; // Free the receive queue var head = receiveQueueHead; receiveQueueHead = null; FreeReceiveQueue(head); } if (connection.logger != null) { connection.logger.LogTrace( "Resetted stream {0} with error code {1}", Id, errorCode); } // Remark: Even if we are here in IDLE state we need to send the // RESET frame. The reason for this is that if we receive a header // for a new stream which is invalid a StreamImpl instance will be // created and put into IDLE state. The header processing will fail // and Reset will get called. As the remote thinks we are in Open // state we must send a RST_STREAM. if (!fromRemote) { // Send a reset frame with the given error code var fh = new FrameHeader { StreamId = this.Id, Type = FrameType.ResetStream, Flags = 0, }; var resetData = new ResetFrameData { ErrorCode = errorCode }; writeResetTask = connection.writer.WriteResetStream(fh, resetData); } else { // If we don't send a notification we still have to unregister // from the writer in order to cancel pending writes connection.writer.RemoveStream(this.Id); } // Unregister from the connection // If this has happened from the remote side the connection will // already have performed this if (!fromRemote) { this.connection.UnregisterStream(this); } // Unblock all waiters readDataPossible.Set(); readTrailersPossible.Set(); readHeadersPossible.Set(); return writeResetTask; } public async ValueTask<StreamReadResult> ReadAsync(ArraySegment<byte> buffer) { while (true) { await readDataPossible; int windowUpdateAmount = 0; StreamReadResult result = new StreamReadResult(); bool hasResult = false; lock (stateMutex) { if (state == StreamState.Reset) { throw new StreamResetException(); } var streamClosedFromRemote = state == StreamState.Closed || state == StreamState.HalfClosedRemote; if (receiveQueueHead != null) { // Copy as much data as possible from internal queue into // user buffer var offset = buffer.Offset; var count = buffer.Count; while (receiveQueueHead != null && count > 0) { // Copy data from receive buffer to target var toCopy = Math.Min(receiveQueueHead.Count, count); Array.Copy( receiveQueueHead.Buffer, receiveQueueHead.Offset, buffer.Array, offset, toCopy); offset += toCopy; count -= toCopy; if (toCopy == receiveQueueHead.Count) { connection.config.BufferPool.Return( receiveQueueHead.Buffer); receiveQueueHead = receiveQueueHead.Next; } else { receiveQueueHead.Offset += toCopy; receiveQueueHead.Count -= toCopy; break; } } // Calculate whether we should send a window update frame // after the read is complete. // Only need to do this if the stream has not yet ended if (!streamClosedFromRemote) { var isFree = totalReceiveWindow - ReceiveQueueLength; var possibleWindowUpdate = isFree - receiveWindow; if (possibleWindowUpdate >= (totalReceiveWindow/2)) { windowUpdateAmount = possibleWindowUpdate; receiveWindow += windowUpdateAmount; if (connection.logger != null && connection.logger.IsEnabled(LogLevel.Trace)) { connection.logger.LogTrace( "Incoming flow control window update:\n" + " Stream {0} window: {1} -> {2}", Id, receiveWindow - windowUpdateAmount, receiveWindow); } } } result = new StreamReadResult{ BytesRead = offset - buffer.Offset, EndOfStream = false, }; hasResult = true; if (receiveQueueHead == null && !streamClosedFromRemote) { // If all data was consumed the next read must be blocked // until more data comes in or the stream gets closed or reset readDataPossible.Reset(); } } else if (streamClosedFromRemote) { // Deliver a notification that the stream was closed result = new StreamReadResult{ BytesRead = 0, EndOfStream = true, }; hasResult = true; } } if (hasResult) { if (windowUpdateAmount > 0) { // We need to send a window update frame before delivering // the result await SendWindowUpdate(windowUpdateAmount); } return result; } } } /// <summary> /// Sends a window update frame for this stream /// </summary> private async ValueTask<object> SendWindowUpdate(int amount) { // Send the header var fh = new FrameHeader { StreamId = this.Id, Type = FrameType.WindowUpdate, Flags = 0, }; var updateData = new WindowUpdateData { WindowSizeIncrement = amount, }; try { await this.connection.writer.WriteWindowUpdate(fh, updateData); } catch (Exception) { // We ignore errors on sending window updates since they are // not important to the reading task, which is the request // handling task. // An error means the writer is dead, which again means // window updates are no longer necessary } return null; } public Task WriteAsync(ArraySegment<byte> buffer) { return WriteAsync(buffer, false); } public async Task WriteAsync(ArraySegment<byte> buffer, bool endOfStream = false) { var removeStream = false; await writeMutex.WaitAsync(); try { lock (stateMutex) { // Check the current stream state if (state == StreamState.Reset) { throw new StreamResetException(); } else if (state != StreamState.Open && state != StreamState.HalfClosedRemote) { throw new Exception("Attempt to write data in invalid stream state"); } else if (state == StreamState.Open && endOfStream) { state = StreamState.HalfClosedLocal; } else if (state == StreamState.HalfClosedRemote && endOfStream) { state = StreamState.Closed; removeStream = true; } // Besides state check also check if headers have already been sent // StreamState.Open could mean we only have received them if (!this.headersSent) { throw new Exception("Attempted to write data before headers"); } // Remark: There's no need to check whether trailers have already // been sent as writing trailers will (half)close the stream, // which is checked for dataSent = true; // Set a flag do disallow following headers } // Remark: // As we hold the writeMutex nobody can close the stream or send trailers // in between. // The only thing that may happen is that the stream get's reset in between, // which would be reported through the ConnectionWriter to us var fh = new FrameHeader { StreamId = this.Id, Type = FrameType.Data, Flags = endOfStream ? ((byte)DataFrameFlags.EndOfStream) : (byte)0, }; var res = await connection.writer.WriteData(fh, buffer); if (res == ConnectionWriter.WriteResult.StreamResetError) { throw new StreamResetException(); } else if (res != ConnectionWriter.WriteResult.Success) { throw new Exception("Can not write to stream"); // TODO: Improve me } } finally { writeMutex.Release(); if (removeStream) { connection.UnregisterStream(this); } } } public Task CloseAsync() { return this.WriteAsync(Constants.EmptyByteArray, true); } public async Task<IEnumerable<HeaderField>> ReadHeadersAsync() { await readHeadersPossible; IEnumerable<HeaderField> result = null; lock (stateMutex) { if (state == StreamState.Reset) { throw new StreamResetException(); } if (inHeaders != null) { result = inHeaders; // If the headers which are read are the informatianal headers // we reset the received headers, so that they can be // replaced by the real headers later on. if (result.IsInformationalHeaders()) { inHeaders = null; readHeadersPossible.Reset(); } } else result = EmptyHeaders; } return result; } public async Task<IEnumerable<HeaderField>> ReadTrailersAsync() { await readTrailersPossible; IEnumerable<HeaderField> result = null; lock (stateMutex) { if (state == StreamState.Reset) { throw new StreamResetException(); } if (inTrailers != null) result = inTrailers; else result = EmptyHeaders; } return result; } /// <summary> /// Processes the reception of incoming headers /// </summary> public Http2Error? ProcessHeaders( CompleteHeadersFrameData headers) { var wakeupDataWaiter = false; var wakeupHeaderWaiter = false; var wakeupTrailerWaiter = false; var removeStream = false; lock (stateMutex) { // Header frames are not valid in all states switch (state) { case StreamState.ReservedLocal: case StreamState.ReservedRemote: // Push promises are currently not implemented // So this needs to be reviewed later on // Currently we should never encounter this state return new Http2Error { StreamId = Id, Code = ErrorCode.InternalError, Message = "Received header frame in uncovered push promise state", }; case StreamState.Idle: case StreamState.Open: case StreamState.HalfClosedLocal: // Open can mean we have already received headers // (in case we are a server) or not (in case we are // a client and only have sent headers) // If headers were already received before there must be // a data frame in between and these are trailers. // An exception is if we are client, where we can // receive informational headers and normal headers. // This requires no data in between. These header must // contain a 1xy status code. // Trailers must have the EndOfStream flag set and must // always follow after a data frame. if (headersReceived != HeaderReceptionState.ReceivedAllHeaders) { // We are receiving headers HeaderValidationResult hvr; if (connection.IsServer) { hvr = HeaderValidator.ValidateRequestHeaders(headers.Headers); } else { hvr = HeaderValidator.ValidateResponseHeaders(headers.Headers); } if (hvr != HeaderValidationResult.Ok) { return new Http2Error { StreamId = Id, Code = ErrorCode.ProtocolError, Message = "Received invalid headers", }; } if (!connection.config.IsServer && headers.Headers.IsInformationalHeaders()) { // Clients support the reception of informational headers. // If this is only an informational header we might // receive additional headers later on. headersReceived = HeaderReceptionState.ReceivedInformationalHeaders; } else { // Servers don't support informational headers at all. // And if we are client and directly receive response // headers it's also fine. headersReceived = HeaderReceptionState.ReceivedAllHeaders; } wakeupHeaderWaiter = true; // TODO: Uncompress cookie headers here? declaredInContentLength = headers.Headers.GetContentLength(); inHeaders = headers.Headers; } else if (!dataReceived) { // We already have received headers, so this should // be trailers. However there was no DATA frame in // between, so this is simply invalid. return new Http2Error { StreamId = Id, Code = ErrorCode.ProtocolError, Message = "Received trailers without headers", }; } else { // These are trailers // trailers must have end of stream set. It is not // valid to receive multiple trailers if (!headers.EndOfStream) { return new Http2Error { StreamId = Id, Code = ErrorCode.ProtocolError, Message = "Received trailers without EndOfStream flag", }; } var hvr = HeaderValidator.ValidateTrailingHeaders(headers.Headers); if (hvr != HeaderValidationResult.Ok) { return new Http2Error { StreamId = Id, Code = ErrorCode.ProtocolError, Message = "Received invalid trailers", }; } // If content-length was set we must also validate // it against the received dataamount here if (declaredInContentLength >= 0 && declaredInContentLength != totalInData) { return new Http2Error { StreamId = Id, Code = ErrorCode.ProtocolError, Message = "Length of DATA frames does not match content-length", }; } wakeupTrailerWaiter = true; inTrailers = headers.Headers; } // Handle state changes that are caused by HEADERS frame if (state == StreamState.Idle) { state = StreamState.Open; } if (headers.EndOfStream) { if (state == StreamState.HalfClosedLocal) { state = StreamState.Closed; removeStream = true; } else // Must be Open, since Idle moves to Open { state = StreamState.HalfClosedRemote; } wakeupTrailerWaiter = true; wakeupDataWaiter = true; } break; case StreamState.HalfClosedRemote: case StreamState.Closed: // Received a header frame for a stream that was // already closed from remote side. // That's not valid return new Http2Error { Code = ErrorCode.StreamClosed, StreamId = Id, Message = "Received headers for closed stream", }; case StreamState.Reset: // The stream was already reset // What we really should do here depends on the previous state, // which is not stored for efficiency. If we reset the // stream late headers are ok. If the remote resetted it // this is a protocol error for the stream. // As it does not really matter just ignore the frame. break; default: throw new Exception("Unhandled stream state"); } } // Wakeup any blocked calls that are waiting on headers or end of stream if (wakeupHeaderWaiter) { readHeadersPossible.Set(); } if (wakeupDataWaiter) { readDataPossible.Set(); } if (wakeupTrailerWaiter) { readTrailersPossible.Set(); } if (removeStream) { connection.UnregisterStream(this); } return null; } /// <summary> /// Processes the reception of a DATA frame. /// The connection is responsible for checking the maximum frame length /// before calling this function. /// </summary> public Http2Error? PushBuffer( ArraySegment<byte> buffer, bool endOfStream, out bool tookBufferOwnership) { tookBufferOwnership = false; var wakeupDataWaiter = false; var wakeupTrailerWaiter = false; var removeStream = false; lock (stateMutex) { // Data frames are not valid in all states switch (state) { case StreamState.ReservedLocal: case StreamState.ReservedRemote: // Push promises are currently not implemented // At the moment these should already been // rejected in the Connection. // This needs to be reviewed later on throw new NotImplementedException(); case StreamState.Open: case StreamState.HalfClosedLocal: if (headersReceived != HeaderReceptionState.ReceivedAllHeaders) { // Received DATA without HEADERS before. // State Open can also mean we only have sent // headers but not received them. // Therefore checking the state alone isn't sufficient. return new Http2Error { StreamId = Id, Code = ErrorCode.ProtocolError, Message = "Received data before all headers", }; } // Only enqueue DATA frames with a real content length // of at least 1 byte, otherwise the reader is needlessly // woken up. // Empty DATA frames are also not checked against the // flow control window, which means they are valid even // in case of a negative flow control window (which is // not possible in the current state of the implementation). // However we still treat empty DATA frames as a valid // separator between HEADERS and trailing HEADERS. if (buffer.Count > 0) { // Check if the flow control window is exceeded if (buffer.Count > receiveWindow) { return new Http2Error { StreamId = Id, Code = ErrorCode.FlowControlError, Message = "Received window exceeded", }; } if (connection.logger != null && connection.logger.IsEnabled(LogLevel.Trace)) { connection.logger.LogTrace( "Incoming flow control window update:\n" + " Stream {0} window: {1} -> {2}", Id, receiveWindow, receiveWindow - buffer.Count); } receiveWindow -= buffer.Count; // Enqueue the data at the end of the receive queue // TODO: Instead of appending buffers with only small // content on the end of each other we might to concat // the buffers together, which avoids the worst-case // scenario: The remote side sending us lots of 1byte // DATA frames, where we need a queue item for each // one. var newItem = new ReceiveQueueItem(buffer); EnqueueReceiveQueueItem(newItem); wakeupDataWaiter = true; tookBufferOwnership = true; } // Allow trailing headers afterwards dataReceived = true; // Check if data matches declared content-length // TODO: What should be done if the declared // content-length was invalid (-2)? totalInData += buffer.Count; if (endOfStream && declaredInContentLength >= 0 && declaredInContentLength != totalInData) { return new Http2Error { StreamId = Id, Code = ErrorCode.ProtocolError, Message = "Length of DATA frames does not match content-length", }; } // All checks OK so far, wakeup waiter and handle state changes // Handle state changes that are caused by DATA frames if (endOfStream) { if (state == StreamState.HalfClosedLocal) { state = StreamState.Closed; removeStream = true; } else // Open { state = StreamState.HalfClosedRemote; } wakeupTrailerWaiter = true; wakeupDataWaiter = true; } break; case StreamState.Idle: case StreamState.HalfClosedRemote: case StreamState.Closed: // Received a DATA frame for a stream that was // already closed or not properly opened from remote side. // That's not valid return new Http2Error { StreamId = Id, Code = ErrorCode.StreamClosed, Message = "Received data for closed stream", }; case StreamState.Reset: // The stream was already reset // What we really should do here depends on the previous state, // which is not stored for efficiency. If we reset the // stream late headers are ok. If the remote resetted it // this is a protocol error for the stream. // As it does not really matter just ignore the frame. break; default: throw new Exception("Unhandled stream state"); } } // Wakeup any blocked calls that are waiting on data or end of stream if (wakeupDataWaiter) { // Wakeup any blocked call that waits for headers to get available readDataPossible.Set(); } if (wakeupTrailerWaiter) { readTrailersPossible.Set(); } if (removeStream) { connection.UnregisterStream(this); } return null; } /// <summary> /// Enqueues a new item at the end of the receive queue /// </summary> private void EnqueueReceiveQueueItem(ReceiveQueueItem newItem) { if (receiveQueueHead == null) { receiveQueueHead = newItem; } else { var current = receiveQueueHead; var next = receiveQueueHead.Next; while (next != null) { current = next; next = current.Next; } current.Next = newItem; } } /// <summary> /// Frees a linked list of receive queue buffers. /// </summary> private void FreeReceiveQueue(ReceiveQueueItem item) { while (item != null && item.Buffer != null) { connection.config.BufferPool.Return(item.Buffer); item.Buffer = null; var current = item; item = item.Next; current.Next = null; } } } }
using System; using System.Collections.Generic; using System.Text; using System.Data; using NCsvLib; using NUnit.Framework; using System.IO; namespace NCsvLibTestSuite { [TestFixture] public class DataSourceRecordReaderDbTest { IDbConnection[] Conn; [SetUp] public void SetUp() { Helpers.CreateEnvironment(); Conn = new IDbConnection[6]; for (int i=0; i<Conn.Length; i++) Conn[i] = Helpers.GetDbConnectionFromFile(Helpers.ConnStrFileName); } [TearDown] public void TearDown() { for (int i = 0; i < Conn.Length; i++) { if (Conn[i].State == System.Data.ConnectionState.Open) Conn[i].Close(); } } [Test] public void OpenCloseSingle() { DataSourceReaderBase rdr = new DataSourceReaderBase(); DataSourceRecordReaderDb rec = new DataSourceRecordReaderDb(Helpers.R1, Conn[0], Helpers.Qry1); rdr.Add(Helpers.R1, rec); rec.Open(); Assert.That(rdr[Helpers.R1].Eof(), Is.False); rec.Close(); } [Test] public void OpenCloseMulti() { DataSourceReaderBase rdr = new DataSourceReaderBase(); rdr.Add(Helpers.R1, new DataSourceRecordReaderDb(Helpers.R1, Conn[0], Helpers.Qry1)); rdr.Add(Helpers.R2, new DataSourceRecordReaderDb(Helpers.R2, Conn[1], Helpers.Qry2)); rdr.Add(Helpers.R3, new DataSourceRecordReaderDb(Helpers.R3, Conn[2], Helpers.Qry3)); rdr.Add(Helpers.R4, new DataSourceRecordReaderDb(Helpers.R4, Conn[3], Helpers.Qry4)); rdr.Add(Helpers.R5, new DataSourceRecordReaderDb(Helpers.R5, Conn[4], Helpers.Qry5)); rdr.Add(Helpers.R6, new DataSourceRecordReaderDb(Helpers.R6, Conn[5], Helpers.Qry6)); rdr[Helpers.R1].Open(); Assert.That(rdr[Helpers.R1].Eof(), Is.False); rdr[Helpers.R1].Close(); rdr[Helpers.R2].Open(); Assert.That(rdr[Helpers.R2].Eof(), Is.False); rdr[Helpers.R2].Close(); rdr[Helpers.R3].Open(); Assert.That(rdr[Helpers.R3].Eof(), Is.False); rdr[Helpers.R3].Close(); rdr[Helpers.R4].Open(); Assert.That(rdr[Helpers.R4].Eof(), Is.False); rdr[Helpers.R4].Close(); rdr[Helpers.R5].Open(); Assert.That(rdr[Helpers.R5].Eof(), Is.False); rdr[Helpers.R5].Close(); rdr[Helpers.R6].Open(); Assert.That(rdr[Helpers.R6].Eof(), Is.False); rdr[Helpers.R6].Close(); } [Test] public void OpenCloseAll() { DataSourceReaderBase rdr = new DataSourceReaderBase(); rdr.Add(Helpers.R1, new DataSourceRecordReaderDb(Helpers.R1, Conn[0], Helpers.Qry1)); rdr.Add(Helpers.R2, new DataSourceRecordReaderDb(Helpers.R2, Conn[1], Helpers.Qry2)); rdr.Add(Helpers.R3, new DataSourceRecordReaderDb(Helpers.R3, Conn[2], Helpers.Qry3)); rdr.Add(Helpers.R4, new DataSourceRecordReaderDb(Helpers.R4, Conn[3], Helpers.Qry4)); rdr.Add(Helpers.R5, new DataSourceRecordReaderDb(Helpers.R5, Conn[4], Helpers.Qry5)); rdr.Add(Helpers.R6, new DataSourceRecordReaderDb(Helpers.R6, Conn[5], Helpers.Qry6)); rdr.OpenAll(); rdr.CloseAll(); } [Test] public void ReadSingle() { DataSourceReaderBase rdr = new DataSourceReaderBase(); DataSourceRecordReaderDb rec = new DataSourceRecordReaderDb(Helpers.R1, Conn[0], Helpers.Qry1); rdr.Add(Helpers.R1, rec); rec.Open(); for (int i = 0; i < 4; i++) Assert.That(rec.Read(), Is.True); Assert.That(rec.Read(), Is.False); rec.Close(); } [Test] public void ReadMulti() { DataSourceReaderBase rdr = new DataSourceReaderBase(); rdr.Add(Helpers.R1, new DataSourceRecordReaderDb(Helpers.R1, Conn[0], Helpers.Qry1)); rdr.Add(Helpers.R2, new DataSourceRecordReaderDb(Helpers.R2, Conn[1], Helpers.Qry2)); rdr.Add(Helpers.R3, new DataSourceRecordReaderDb(Helpers.R3, Conn[2], Helpers.Qry3)); rdr.Add(Helpers.R4, new DataSourceRecordReaderDb(Helpers.R4, Conn[3], Helpers.Qry4)); rdr.Add(Helpers.R5, new DataSourceRecordReaderDb(Helpers.R5, Conn[4], Helpers.Qry5)); rdr.Add(Helpers.R6, new DataSourceRecordReaderDb(Helpers.R6, Conn[5], Helpers.Qry6)); rdr[Helpers.R1].Open(); rdr[Helpers.R2].Open(); rdr[Helpers.R3].Open(); rdr[Helpers.R4].Open(); rdr[Helpers.R5].Open(); rdr[Helpers.R6].Open(); for (int i = 0; i < 4; i++) { Assert.That(rdr[Helpers.R1].Read(), Is.True); Assert.That(rdr[Helpers.R2].Read(), Is.True); Assert.That(rdr[Helpers.R3].Read(), Is.True); Assert.That(rdr[Helpers.R4].Read(), Is.True); Assert.That(rdr[Helpers.R5].Read(), Is.True); Assert.That(rdr[Helpers.R6].Read(), Is.True); } Assert.That(rdr[Helpers.R1].Read(), Is.False); //Records 2 and 3 have 8 records in db Assert.That(rdr[Helpers.R2].Read(), Is.True); Assert.That(rdr[Helpers.R3].Read(), Is.True); //Record 4 has 9 records in db for (int i = 0; i < 5; i++) Assert.That(rdr[Helpers.R4].Read(), Is.True); Assert.That(rdr[Helpers.R4].Read(), Is.False); //Record 5 has 8 records in db for (int i = 0; i < 4; i++) Assert.That(rdr[Helpers.R5].Read(), Is.True); Assert.That(rdr[Helpers.R5].Read(), Is.False); //Record 6 has 8 records in db for (int i = 0; i < 4; i++) Assert.That(rdr[Helpers.R6].Read(), Is.True); Assert.That(rdr[Helpers.R6].Read(), Is.False); rdr[Helpers.R1].Close(); rdr[Helpers.R2].Close(); rdr[Helpers.R3].Close(); rdr[Helpers.R4].Close(); rdr[Helpers.R5].Close(); rdr[Helpers.R6].Close(); } [Test] public void GetFieldSingle() { DataSourceField fld; DataSourceReaderBase rdr = new DataSourceReaderBase(); rdr.Add(Helpers.R1, new DataSourceRecordReaderDb(Helpers.R1, Conn[0], Helpers.Qry1)); rdr[Helpers.R1].Open(); rdr[Helpers.R1].Read(); fld = rdr[Helpers.R1].GetField("intfld"); Assert.That(fld.Name, Is.EqualTo("intfld")); Assert.That((int)fld.Value, Is.EqualTo(1)); fld = rdr[Helpers.R1].GetField("strfld"); Assert.That((string)fld.Value, Is.EqualTo("aaa")); fld = rdr[Helpers.R1].GetField("doublefld"); Assert.That((double)fld.Value, Is.EqualTo(100.1)); fld = rdr[Helpers.R1].GetField("decimalfld"); Assert.That((decimal)fld.Value, Is.EqualTo((decimal)1000.11)); fld = rdr[Helpers.R1].GetField("dtfld"); Assert.That((DateTime)fld.Value, Is.EqualTo(new DateTime(2001, 1, 11, 10, 11, 12))); fld = rdr[Helpers.R1].GetField("strfld2"); Assert.That((string)fld.Value, Is.EqualTo("TEST1")); fld = rdr[Helpers.R1].GetField("boolfld"); Assert.That((int)fld.Value, Is.EqualTo((int)1)); rdr[Helpers.R1].Read(); rdr[Helpers.R1].Read(); fld = rdr[Helpers.R1].GetField("intfld"); Assert.That((int)fld.Value, Is.EqualTo(3)); fld = rdr[Helpers.R1].GetField("strfld"); Assert.That((string)fld.Value, Is.EqualTo("ccc")); fld = rdr[Helpers.R1].GetField("doublefld"); Assert.That((double)fld.Value, Is.EqualTo(300.3)); fld = rdr[Helpers.R1].GetField("decimalfld"); Assert.That((decimal)fld.Value, Is.EqualTo((decimal)3000.33)); fld = rdr[Helpers.R1].GetField("dtfld"); Assert.That((DateTime)fld.Value, Is.EqualTo(new DateTime(2003, 3, 13, 13, 14, 15))); fld = rdr[Helpers.R1].GetField("strfld2"); Assert.That((string)fld.Value, Is.EqualTo("TEST3")); fld = rdr[Helpers.R1].GetField("boolfld"); Assert.That((int)fld.Value, Is.EqualTo((int)1)); rdr[Helpers.R1].Close(); } [Test] public void GetFieldMulti() { DataSourceField fld; DataSourceReaderBase rdr = new DataSourceReaderBase(); rdr.Add(Helpers.R1, new DataSourceRecordReaderDb(Helpers.R1, Conn[0], Helpers.Qry1)); rdr.Add(Helpers.R2, new DataSourceRecordReaderDb(Helpers.R2, Conn[1], Helpers.Qry2)); rdr.Add(Helpers.R3, new DataSourceRecordReaderDb(Helpers.R3, Conn[2], Helpers.Qry3)); rdr.Add(Helpers.R4, new DataSourceRecordReaderDb(Helpers.R4, Conn[3], Helpers.Qry4)); rdr.Add(Helpers.R5, new DataSourceRecordReaderDb(Helpers.R4, Conn[4], Helpers.Qry5)); rdr.Add(Helpers.R6, new DataSourceRecordReaderDb(Helpers.R4, Conn[5], Helpers.Qry6)); rdr[Helpers.R1].Open(); rdr[Helpers.R2].Open(); rdr[Helpers.R3].Open(); rdr[Helpers.R4].Open(); rdr[Helpers.R5].Open(); rdr[Helpers.R6].Open(); rdr[Helpers.R2].Read(); fld = rdr[Helpers.R2].GetField("intr2"); Assert.That(fld.Name, Is.EqualTo("intr2")); Assert.That((int)fld.Value, Is.EqualTo(1)); fld = rdr[Helpers.R2].GetField("strr2"); Assert.That((string)fld.Value, Is.EqualTo("r2_1")); fld = rdr[Helpers.R2].GetField("bool2"); Assert.That((string)fld.Value, Is.EqualTo("T")); rdr[Helpers.R2].Read(); rdr[Helpers.R2].Read(); fld = rdr[Helpers.R2].GetField("intr2"); Assert.That(fld.Name, Is.EqualTo("intr2")); Assert.That((int)fld.Value, Is.EqualTo(3)); fld = rdr[Helpers.R2].GetField("intr2left"); Assert.That(fld.Name, Is.EqualTo("intr2left")); Assert.That((int)fld.Value, Is.EqualTo(33)); fld = rdr[Helpers.R2].GetField("strr2"); Assert.That((string)fld.Value, Is.EqualTo("r2_3")); fld = rdr[Helpers.R2].GetField("bool2"); Assert.That((string)fld.Value, Is.EqualTo("T")); rdr[Helpers.R3].Read(); fld = rdr[Helpers.R3].GetField("intr3"); Assert.That(fld.Name, Is.EqualTo("intr3")); Assert.That((int)fld.Value, Is.EqualTo(1)); fld = rdr[Helpers.R3].GetField("strr3"); Assert.That((string)fld.Value, Is.EqualTo("r3_1")); rdr[Helpers.R3].Read(); rdr[Helpers.R3].Read(); fld = rdr[Helpers.R3].GetField("intr3"); Assert.That(fld.Name, Is.EqualTo("intr3")); Assert.That((int)fld.Value, Is.EqualTo(3)); fld = rdr[Helpers.R3].GetField("strr3"); Assert.That((string)fld.Value, Is.EqualTo("r3_3")); rdr[Helpers.R4].Read(); fld = rdr[Helpers.R4].GetField("intr4"); Assert.That(fld.Name, Is.EqualTo("intr4")); Assert.That((int)fld.Value, Is.EqualTo(1)); fld = rdr[Helpers.R4].GetField("doubler4"); Assert.That((double)fld.Value, Is.EqualTo(11.1)); fld = rdr[Helpers.R4].GetField("decimalr4"); Assert.That((decimal)fld.Value, Is.EqualTo((decimal)111.11)); rdr[Helpers.R4].Read(); rdr[Helpers.R4].Read(); fld = rdr[Helpers.R4].GetField("intr4"); Assert.That(fld.Name, Is.EqualTo("intr4")); Assert.That((int)fld.Value, Is.EqualTo(3)); fld = rdr[Helpers.R4].GetField("doubler4"); Assert.That((double)fld.Value, Is.EqualTo(33.3)); fld = rdr[Helpers.R4].GetField("decimalr4"); Assert.That((decimal)fld.Value, Is.EqualTo((decimal)333.33)); rdr[Helpers.R5].Read(); fld = rdr[Helpers.R5].GetField("intr5"); Assert.That(fld.Name, Is.EqualTo("intr5")); Assert.That((int)fld.Value, Is.EqualTo(1)); fld = rdr[Helpers.R5].GetField("strr5"); Assert.That(fld.Name, Is.EqualTo("strr5")); Assert.That(fld.Value, Is.EqualTo("AA")); rdr[Helpers.R5].Read(); rdr[Helpers.R5].Read(); rdr[Helpers.R5].Read(); fld = rdr[Helpers.R5].GetField("intr5"); Assert.That(fld.Name, Is.EqualTo("intr5")); Assert.That((int)fld.Value, Is.EqualTo(4)); fld = rdr[Helpers.R5].GetField("strr5"); Assert.That(fld.Name, Is.EqualTo("strr5")); Assert.That(fld.Value, Is.EqualTo("DD")); rdr[Helpers.R6].Read(); fld = rdr[Helpers.R6].GetField("intr6"); Assert.That(fld.Name, Is.EqualTo("intr6")); Assert.That((int)fld.Value, Is.EqualTo(11)); fld = rdr[Helpers.R6].GetField("strr6"); Assert.That(fld.Name, Is.EqualTo("strr6")); Assert.That(fld.Value, Is.EqualTo("AAA")); rdr[Helpers.R6].Read(); rdr[Helpers.R6].Read(); fld = rdr[Helpers.R6].GetField("intr6"); Assert.That(fld.Name, Is.EqualTo("intr6")); Assert.That((int)fld.Value, Is.EqualTo(33)); fld = rdr[Helpers.R6].GetField("strr6"); Assert.That(fld.Name, Is.EqualTo("strr6")); Assert.That(fld.Value, Is.EqualTo("CCC")); } } }
// Copyright 2004-2009 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. namespace Castle.DynamicProxy.Test { using System; using System.Collections; using System.IO; using System.Runtime.Serialization.Formatters.Binary; using Castle.DynamicProxy.Serialization; using NUnit.Framework; using Castle.DynamicProxy.Test.Classes; using Castle.DynamicProxy.Test.Mixins; using Castle.DynamicProxy.Test.ClassInterfaces; using Castle.DynamicProxy.Builder.CodeGenerators; /// <summary> /// Summary description for SerializableClassTestCase. /// </summary> [TestFixture] public class SerializableClassTestCase { ProxyGenerator generator; [SetUp] public void Init() { generator = new ProxyGenerator(); } [Test] public void CreateSerializable() { ProxyObjectReference.ResetScope(); MySerializableClass proxy = (MySerializableClass) generator.CreateClassProxy( typeof(MySerializableClass), new StandardInterceptor() ); Assert.IsTrue( proxy.GetType().IsSerializable ); } [Test] public void SimpleProxySerialization() { ProxyObjectReference.ResetScope(); MySerializableClass proxy = (MySerializableClass) generator.CreateClassProxy( typeof(MySerializableClass), new StandardInterceptor() ); DateTime current = proxy.Current; MySerializableClass otherProxy = (MySerializableClass) SerializeAndDeserialize(proxy); Assert.AreEqual( current, otherProxy.Current ); } [Test] public void SerializationDelegate() { ProxyObjectReference.ResetScope(); MySerializableClass2 proxy = (MySerializableClass2) generator.CreateClassProxy( typeof(MySerializableClass2), new StandardInterceptor() ); DateTime current = proxy.Current; MySerializableClass2 otherProxy = (MySerializableClass2) SerializeAndDeserialize(proxy); Assert.AreEqual( current, otherProxy.Current ); } [Test] public void SimpleInterfaceProxy() { ProxyObjectReference.ResetScope(); object proxy = generator.CreateProxy( typeof(IMyInterface), new StandardInterceptor( ), new MyInterfaceImpl() ); Assert.IsTrue( proxy.GetType().IsSerializable ); IMyInterface inter = (IMyInterface) proxy; inter.Name = "opa"; Assert.AreEqual( "opa", inter.Name ); inter.Started = true; Assert.AreEqual( true, inter.Started ); IMyInterface otherProxy = (IMyInterface) SerializeAndDeserialize(proxy); Assert.AreEqual( inter.Name, otherProxy.Name ); Assert.AreEqual( inter.Started, otherProxy.Started ); } [Test] public void CustomMarkerInterface() { ProxyObjectReference.ResetScope(); ClassProxyGenerator classGenerator = new ClassProxyGenerator( new ModuleScope(), new GeneratorContext() ); Type proxyType = classGenerator.GenerateCode( typeof(ClassWithMarkerInterface), new Type[] { typeof(IMarkerInterface) } ); object proxy = Activator.CreateInstance( proxyType, new object[] { new StandardInterceptor() } ); Assert.IsNotNull( proxy ); Assert.IsTrue( proxy is IMarkerInterface ); object otherProxy = SerializeAndDeserialize(proxy); Assert.IsTrue( otherProxy is IMarkerInterface ); } #if !MONO [Test] #endif [Category("DotNetOnly")] public void MixinSerialization() { ProxyObjectReference.ResetScope(); GeneratorContext context = new GeneratorContext(); SimpleMixin mixin1 = new SimpleMixin(); OtherMixin mixin2 = new OtherMixin(); context.AddMixinInstance( mixin1 ); context.AddMixinInstance( mixin2 ); object proxy = generator.CreateCustomClassProxy( typeof(SimpleClass), new StandardInterceptor(), context ); Assert.IsTrue( typeof(SimpleClass).IsAssignableFrom( proxy.GetType() ) ); (proxy as SimpleClass).DoSome(); ISimpleMixin mixin = proxy as ISimpleMixin; Assert.AreEqual(1, mixin.DoSomething()); IOtherMixin other = proxy as IOtherMixin; Assert.AreEqual(3, other.Sum(1,2)); SimpleClass otherProxy = (SimpleClass) SerializeAndDeserialize(proxy); otherProxy.DoSome(); mixin = otherProxy as ISimpleMixin; Assert.AreEqual(1, mixin.DoSomething()); other = otherProxy as IOtherMixin; Assert.AreEqual(3, other.Sum(1,2)); } [Test] [Ignore("XmlSerializer does not respect the ObjectReference protocol so it wont work")] public void XmlSerialization() { ProxyObjectReference.ResetScope(); GeneratorContext context = new GeneratorContext(); SimpleMixin mixin1 = new SimpleMixin(); OtherMixin mixin2 = new OtherMixin(); context.AddMixinInstance( mixin1 ); context.AddMixinInstance( mixin2 ); object proxy = generator.CreateCustomClassProxy( typeof(SimpleClass), new StandardInterceptor(), context ); System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(SimpleClass)); MemoryStream stream = new MemoryStream(); serializer.Serialize(stream, proxy); stream.Position = 0; SimpleClass otherProxy = (SimpleClass) serializer.Deserialize( stream ); ISimpleMixin mixin = otherProxy as ISimpleMixin; Assert.AreEqual(1, mixin.DoSomething()); IOtherMixin other = otherProxy as IOtherMixin; Assert.AreEqual(3, other.Sum(1,2)); } [Test] public void HashtableSerialization() { ProxyObjectReference.ResetScope(); object proxy = generator.CreateClassProxy( typeof(Hashtable), new StandardInterceptor() ); Assert.IsTrue( typeof(Hashtable).IsAssignableFrom( proxy.GetType() ) ); (proxy as Hashtable).Add("key", "helloooo!"); Hashtable otherProxy = (Hashtable) SerializeAndDeserialize(proxy); Assert.IsTrue(otherProxy.ContainsKey("key")); Assert.AreEqual("helloooo!", otherProxy["key"]); } public static object SerializeAndDeserialize( object proxy ) { MemoryStream stream = new MemoryStream(); BinaryFormatter formatter = new BinaryFormatter(); formatter.Serialize( stream, proxy ); stream.Position = 0; return formatter.Deserialize( stream ); } } }
// 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 Test.Cryptography; using Xunit; namespace System.Security.Cryptography.Algorithms.Tests { public partial class IncrementalHashTests { // Some arbitrarily chosen OID segments private static readonly byte[] s_hmacKey = { 2, 5, 29, 54, 1, 2, 84, 113, 54, 91, 1, 1, 2, 5, 29, 10, }; private static readonly byte[] s_inputBytes = ByteUtils.RepeatByte(0xA5, 512); public static IEnumerable<object[]> GetHashAlgorithms() { return new[] { new object[] { MD5.Create(), HashAlgorithmName.MD5 }, new object[] { SHA1.Create(), HashAlgorithmName.SHA1 }, new object[] { SHA256.Create(), HashAlgorithmName.SHA256 }, new object[] { SHA384.Create(), HashAlgorithmName.SHA384 }, new object[] { SHA512.Create(), HashAlgorithmName.SHA512 }, }; } public static IEnumerable<object[]> GetHMACs() { return new[] { new object[] { new HMACMD5(), HashAlgorithmName.MD5 }, new object[] { new HMACSHA1(), HashAlgorithmName.SHA1 }, new object[] { new HMACSHA256(), HashAlgorithmName.SHA256 }, new object[] { new HMACSHA384(), HashAlgorithmName.SHA384 }, new object[] { new HMACSHA512(), HashAlgorithmName.SHA512 }, }; } [Fact] public static void InvalidArguments_Throw() { AssertExtensions.Throws<ArgumentException>("hashAlgorithm", () => IncrementalHash.CreateHash(new HashAlgorithmName(null))); AssertExtensions.Throws<ArgumentException>("hashAlgorithm", () => IncrementalHash.CreateHash(new HashAlgorithmName(""))); AssertExtensions.Throws<ArgumentException>("hashAlgorithm", () => IncrementalHash.CreateHMAC(new HashAlgorithmName(null), new byte[1])); AssertExtensions.Throws<ArgumentException>("hashAlgorithm", () => IncrementalHash.CreateHMAC(new HashAlgorithmName(""), new byte[1])); AssertExtensions.Throws<ArgumentNullException>("key", () => IncrementalHash.CreateHMAC(HashAlgorithmName.SHA512, null)); using (IncrementalHash incrementalHash = IncrementalHash.CreateHash(HashAlgorithmName.SHA512)) { AssertExtensions.Throws<ArgumentNullException>("data", () => incrementalHash.AppendData(null)); AssertExtensions.Throws<ArgumentNullException>("data", () => incrementalHash.AppendData(null, 0, 0)); AssertExtensions.Throws<ArgumentOutOfRangeException>("offset", () => incrementalHash.AppendData(new byte[1], -1, 1)); AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => incrementalHash.AppendData(new byte[1], 0, -1)); AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => incrementalHash.AppendData(new byte[1], 0, 2)); Assert.Throws<ArgumentException>(() => incrementalHash.AppendData(new byte[2], 1, 2)); } } [Theory] [MemberData(nameof(GetHashAlgorithms))] public static void VerifyIncrementalHash(HashAlgorithm referenceAlgorithm, HashAlgorithmName hashAlgorithm) { using (referenceAlgorithm) using (IncrementalHash incrementalHash = IncrementalHash.CreateHash(hashAlgorithm)) { Assert.Equal(hashAlgorithm, incrementalHash.AlgorithmName); VerifyIncrementalResult(referenceAlgorithm, incrementalHash); } } [Theory] [MemberData(nameof(GetHMACs))] public static void VerifyIncrementalHMAC(HMAC referenceAlgorithm, HashAlgorithmName hashAlgorithm) { using (referenceAlgorithm) using (IncrementalHash incrementalHash = IncrementalHash.CreateHMAC(hashAlgorithm, s_hmacKey)) { referenceAlgorithm.Key = s_hmacKey; VerifyIncrementalResult(referenceAlgorithm, incrementalHash); } } private static void VerifyIncrementalResult(HashAlgorithm referenceAlgorithm, IncrementalHash incrementalHash) { byte[] referenceHash = referenceAlgorithm.ComputeHash(s_inputBytes); const int StepA = 13; const int StepB = 7; int position = 0; while (position < s_inputBytes.Length - StepA) { incrementalHash.AppendData(s_inputBytes, position, StepA); position += StepA; } incrementalHash.AppendData(s_inputBytes, position, s_inputBytes.Length - position); byte[] incrementalA = incrementalHash.GetHashAndReset(); Assert.Equal(referenceHash, incrementalA); // Now try again, verifying both immune to step size behaviors, and that GetHashAndReset resets. position = 0; while (position < s_inputBytes.Length - StepB) { incrementalHash.AppendData(s_inputBytes, position, StepB); position += StepB; } incrementalHash.AppendData(s_inputBytes, position, s_inputBytes.Length - position); byte[] incrementalB = incrementalHash.GetHashAndReset(); Assert.Equal(referenceHash, incrementalB); } [Theory] [MemberData(nameof(GetHashAlgorithms))] public static void VerifyEmptyHash(HashAlgorithm referenceAlgorithm, HashAlgorithmName hashAlgorithm) { using (referenceAlgorithm) using (IncrementalHash incrementalHash = IncrementalHash.CreateHash(hashAlgorithm)) { for (int i = 0; i < 10; i++) { incrementalHash.AppendData(Array.Empty<byte>()); } byte[] referenceHash = referenceAlgorithm.ComputeHash(Array.Empty<byte>()); byte[] incrementalResult = incrementalHash.GetHashAndReset(); Assert.Equal(referenceHash, incrementalResult); } } [Theory] [MemberData(nameof(GetHMACs))] public static void VerifyEmptyHMAC(HMAC referenceAlgorithm, HashAlgorithmName hashAlgorithm) { using (referenceAlgorithm) using (IncrementalHash incrementalHash = IncrementalHash.CreateHMAC(hashAlgorithm, s_hmacKey)) { referenceAlgorithm.Key = s_hmacKey; for (int i = 0; i < 10; i++) { incrementalHash.AppendData(Array.Empty<byte>()); } byte[] referenceHash = referenceAlgorithm.ComputeHash(Array.Empty<byte>()); byte[] incrementalResult = incrementalHash.GetHashAndReset(); Assert.Equal(referenceHash, incrementalResult); } } [Theory] [MemberData(nameof(GetHashAlgorithms))] public static void VerifyTrivialHash(HashAlgorithm referenceAlgorithm, HashAlgorithmName hashAlgorithm) { using (referenceAlgorithm) using (IncrementalHash incrementalHash = IncrementalHash.CreateHash(hashAlgorithm)) { byte[] referenceHash = referenceAlgorithm.ComputeHash(Array.Empty<byte>()); byte[] incrementalResult = incrementalHash.GetHashAndReset(); Assert.Equal(referenceHash, incrementalResult); } } [Theory] [MemberData(nameof(GetHMACs))] public static void VerifyTrivialHMAC(HMAC referenceAlgorithm, HashAlgorithmName hashAlgorithm) { using (referenceAlgorithm) using (IncrementalHash incrementalHash = IncrementalHash.CreateHMAC(hashAlgorithm, s_hmacKey)) { referenceAlgorithm.Key = s_hmacKey; byte[] referenceHash = referenceAlgorithm.ComputeHash(Array.Empty<byte>()); byte[] incrementalResult = incrementalHash.GetHashAndReset(); Assert.Equal(referenceHash, incrementalResult); } } [Fact] public static void AppendDataAfterHashClose() { using (IncrementalHash hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256)) { byte[] firstHash = hash.GetHashAndReset(); hash.AppendData(Array.Empty<byte>()); byte[] secondHash = hash.GetHashAndReset(); Assert.Equal(firstHash, secondHash); } } [Fact] public static void AppendDataAfterHMACClose() { using (IncrementalHash hash = IncrementalHash.CreateHMAC(HashAlgorithmName.SHA256, s_hmacKey)) { byte[] firstHash = hash.GetHashAndReset(); hash.AppendData(Array.Empty<byte>()); byte[] secondHash = hash.GetHashAndReset(); Assert.Equal(firstHash, secondHash); } } [Fact] public static void GetHashTwice() { using (IncrementalHash hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256)) { byte[] firstHash = hash.GetHashAndReset(); byte[] secondHash = hash.GetHashAndReset(); Assert.Equal(firstHash, secondHash); } } [Fact] public static void GetHMACTwice() { using (IncrementalHash hash = IncrementalHash.CreateHMAC(HashAlgorithmName.SHA256, s_hmacKey)) { byte[] firstHash = hash.GetHashAndReset(); byte[] secondHash = hash.GetHashAndReset(); Assert.Equal(firstHash, secondHash); } } [Fact] public static void ModifyAfterHashDispose() { using (IncrementalHash hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256)) { hash.Dispose(); Assert.Throws<ObjectDisposedException>(() => hash.AppendData(Array.Empty<byte>())); Assert.Throws<ObjectDisposedException>(() => hash.GetHashAndReset()); } } [Fact] public static void ModifyAfterHMACDispose() { using (IncrementalHash hash = IncrementalHash.CreateHMAC(HashAlgorithmName.SHA256, s_hmacKey)) { hash.Dispose(); Assert.Throws<ObjectDisposedException>(() => hash.AppendData(Array.Empty<byte>())); Assert.Throws<ObjectDisposedException>(() => hash.GetHashAndReset()); } } } }
using UnityEditor; using UnityEngine; using System.Collections.Generic; [CanEditMultipleObjects] [CustomEditor(typeof(tk2dTextMesh))] class tk2dTextMeshEditor : Editor { tk2dGenericIndexItem[] allFonts = null; // all generators string[] allFontNames = null; Vector2 gradientScroll; // Word wrap on text area - almost impossible to use otherwise GUIStyle _textAreaStyle = null; GUIStyle textAreaStyle { get { if (_textAreaStyle == null) { _textAreaStyle = new GUIStyle(EditorStyles.textField); _textAreaStyle.wordWrap = true; } return _textAreaStyle; } } tk2dTextMesh[] targetTextMeshes = new tk2dTextMesh[0]; #if !(UNITY_3_5 || UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2) Renderer[] renderers = new Renderer[0]; #endif void OnEnable() { targetTextMeshes = new tk2dTextMesh[targets.Length]; for (int i = 0; i < targets.Length; ++i) { targetTextMeshes[i] = targets[i] as tk2dTextMesh; } #if !(UNITY_3_5 || UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2) List<Renderer> rs = new List<Renderer>(); foreach (var v in targetTextMeshes) { if (v != null && v.GetComponent<Renderer>() != null) { rs.Add(v.GetComponent<Renderer>()); } } renderers = rs.ToArray(); #endif } void OnDestroy() { tk2dEditorSkin.Done(); } // Draws the word wrap GUI void DrawWordWrapSceneGUI(tk2dTextMesh textMesh) { tk2dFontData font = textMesh.font; Transform transform = textMesh.transform; int px = textMesh.wordWrapWidth; Vector3 p0 = transform.position; float width = font.texelSize.x * px * transform.localScale.x; bool drawRightHandle = true; bool drawLeftHandle = false; switch (textMesh.anchor) { case TextAnchor.LowerCenter: case TextAnchor.MiddleCenter: case TextAnchor.UpperCenter: drawLeftHandle = true; p0 -= width * 0.5f * transform.right; break; case TextAnchor.LowerRight: case TextAnchor.MiddleRight: case TextAnchor.UpperRight: drawLeftHandle = true; drawRightHandle = false; p0 -= width * transform.right; break; } Vector3 p1 = p0 + width * transform.right; Handles.color = new Color32(255, 255, 255, 24); float subPin = font.texelSize.y * 2048; Handles.DrawLine(p0, p1); Handles.DrawLine(p0 - subPin * transform.up, p0 + subPin * transform.up); Handles.DrawLine(p1 - subPin * transform.up, p1 + subPin * transform.up); Handles.color = Color.white; Vector3 pin = transform.up * font.texelSize.y * 10.0f; Handles.DrawLine(p0 - pin, p0 + pin); Handles.DrawLine(p1 - pin, p1 + pin); if (drawRightHandle) { Vector3 newp1 = Handles.Slider(p1, transform.right, HandleUtility.GetHandleSize(p1), Handles.ArrowCap, 0.0f); if (newp1 != p1) { tk2dUndo.RecordObject(textMesh, "TextMesh Wrap Length"); int newPx = (int)Mathf.Round((newp1 - p0).magnitude / (font.texelSize.x * transform.localScale.x)); newPx = Mathf.Max(newPx, 0); textMesh.wordWrapWidth = newPx; textMesh.Commit(); } } if (drawLeftHandle) { Vector3 newp0 = Handles.Slider(p0, -transform.right, HandleUtility.GetHandleSize(p0), Handles.ArrowCap, 0.0f); if (newp0 != p0) { tk2dUndo.RecordObject(textMesh, "TextMesh Wrap Length"); int newPx = (int)Mathf.Round((p1 - newp0).magnitude / (font.texelSize.x * transform.localScale.x)); newPx = Mathf.Max(newPx, 0); textMesh.wordWrapWidth = newPx; textMesh.Commit(); } } } public void OnSceneGUI() { tk2dTextMesh textMesh = (tk2dTextMesh)target; if (textMesh.formatting && textMesh.wordWrapWidth > 0) { DrawWordWrapSceneGUI(textMesh); } if (tk2dPreferences.inst.enableSpriteHandles == true) { MeshFilter meshFilter = textMesh.GetComponent<MeshFilter>(); if (!meshFilter || meshFilter.sharedMesh == null) { return; } Transform t = textMesh.transform; Bounds b = meshFilter.sharedMesh.bounds; Rect localRect = new Rect(b.min.x, b.min.y, b.size.x, b.size.y); // Draw rect outline Handles.color = new Color(1,1,1,0.5f); tk2dSceneHelper.DrawRect (localRect, t); Handles.BeginGUI (); // Resize handles if (tk2dSceneHelper.RectControlsToggle ()) { EditorGUI.BeginChangeCheck (); Rect resizeRect = tk2dSceneHelper.RectControl (132546, localRect, t); if (EditorGUI.EndChangeCheck ()) { int newWrapWidth = (int)((float)textMesh.wordWrapWidth * resizeRect.width / localRect.width); newWrapWidth = Mathf.Max(1, newWrapWidth); Vector3 newScale = new Vector3 (textMesh.scale.x * (resizeRect.width / localRect.width), textMesh.scale.y * (resizeRect.height / localRect.height)); if (textMesh.formatting && textMesh.wordWrapWidth > 0) { float fx = (float)newWrapWidth / (float)textMesh.wordWrapWidth; newScale.x = textMesh.scale.x * fx; if (Mathf.Abs(localRect.xMin - resizeRect.xMin) < Mathf.Abs(localRect.xMax - resizeRect.xMax)) { resizeRect.xMax = localRect.xMin + fx * localRect.width; } else { resizeRect.xMin = localRect.xMax - fx * localRect.width; } } float scaleMin = 0.001f; if (Mathf.Abs(newScale.x) < scaleMin) { newScale.x = scaleMin * Mathf.Sign(textMesh.scale.x); } if (Mathf.Abs(newScale.y) < scaleMin) { newScale.y = scaleMin * Mathf.Sign(textMesh.scale.y); } if (newScale != textMesh.scale) { tk2dUndo.RecordObjects (new Object[] {t, textMesh}, "Resize"); float factorX = newScale.x / (Mathf.Approximately(textMesh.scale.x, 0.0f) ? 1.0f : textMesh.scale.x); float factorY = newScale.y / (Mathf.Approximately(textMesh.scale.y, 0.0f) ? 1.0f : textMesh.scale.y); Vector3 offset = new Vector3(resizeRect.xMin - localRect.xMin * factorX, resizeRect.yMin - localRect.yMin * factorY, 0.0f); Vector3 newPosition = t.TransformPoint (offset); if (newPosition != t.position) { t.position = newPosition; } textMesh.scale = newScale; if (textMesh.formatting && textMesh.wordWrapWidth > 0) { textMesh.wordWrapWidth = newWrapWidth; } textMesh.Commit (); tk2dUtil.SetDirty(textMesh); } } } // Rotate handles if (!tk2dSceneHelper.RectControlsToggle ()) { EditorGUI.BeginChangeCheck(); float theta = tk2dSceneHelper.RectRotateControl (645231, localRect, t, new List<int>()); if (EditorGUI.EndChangeCheck()) { if (Mathf.Abs(theta) > Mathf.Epsilon) { tk2dUndo.RecordObject (t, "Rotate"); t.Rotate(t.forward, theta, Space.World); } } } Handles.EndGUI (); // Sprite selecting tk2dSceneHelper.HandleSelectSprites(); // Move targeted sprites tk2dSceneHelper.HandleMoveSprites(t, localRect); } if (GUI.changed) { tk2dUtil.SetDirty(target); } } void UndoableAction( System.Action<tk2dTextMesh> action ) { tk2dUndo.RecordObjects (targetTextMeshes, "Inspector"); foreach (tk2dTextMesh tm in targetTextMeshes) { action(tm); } } static bool showInlineStylingHelp = false; public override void OnInspectorGUI() { tk2dTextMesh textMesh = (tk2dTextMesh)target; tk2dGuiUtility.LookLikeControls(80, 50); // maybe cache this if its too slow later if (allFonts == null || allFontNames == null) { tk2dGenericIndexItem[] indexFonts = tk2dEditorUtility.GetOrCreateIndex().GetFonts(); List<tk2dGenericIndexItem> filteredFonts = new List<tk2dGenericIndexItem>(); foreach (var f in indexFonts) if (!f.managed) filteredFonts.Add(f); allFonts = filteredFonts.ToArray(); allFontNames = new string[allFonts.Length]; for (int i = 0; i < allFonts.Length; ++i) allFontNames[i] = allFonts[i].AssetName; } if (allFonts != null && allFonts.Length > 0) { if (textMesh.font == null) { textMesh.font = allFonts[0].GetAsset<tk2dFont>().data; } int currId = -1; string guid = AssetDatabase.AssetPathToGUID(AssetDatabase.GetAssetPath(textMesh.font)); for (int i = 0; i < allFonts.Length; ++i) { if (allFonts[i].dataGUID == guid) { currId = i; } } int newId = EditorGUILayout.Popup("Font", currId, allFontNames); if (newId != currId) { UndoableAction( tm => tm.font = allFonts[newId].GetAsset<tk2dFont>().data ); GUI.changed = true; } EditorGUILayout.BeginHorizontal(); int newMaxChars = Mathf.Clamp( EditorGUILayout.IntField("Max Chars", textMesh.maxChars), 1, 16000 ); if (newMaxChars != textMesh.maxChars) { UndoableAction( tm => tm.maxChars = newMaxChars ); } if (GUILayout.Button("Fit", GUILayout.MaxWidth(32.0f))) { UndoableAction( tm => tm.maxChars = tm.NumTotalCharacters() ); GUI.changed = true; } EditorGUILayout.EndHorizontal(); bool newFormatting = EditorGUILayout.BeginToggleGroup("Formatting", textMesh.formatting); if (newFormatting != textMesh.formatting) { UndoableAction( tm => tm.formatting = newFormatting ); GUI.changed = true; } GUILayout.BeginHorizontal(); ++EditorGUI.indentLevel; if (textMesh.wordWrapWidth == 0) { EditorGUILayout.PrefixLabel("Word Wrap"); if (GUILayout.Button("Enable", EditorStyles.miniButton, GUILayout.ExpandWidth(false))) { UndoableAction( tm => tm.wordWrapWidth = (tm.wordWrapWidth == 0) ? 500 : tm.wordWrapWidth ); GUI.changed = true; } } else { int newWordWrapWidth = EditorGUILayout.IntField("Word Wrap", textMesh.wordWrapWidth); if (newWordWrapWidth != textMesh.wordWrapWidth) { UndoableAction( tm => tm.wordWrapWidth = newWordWrapWidth ); } if (GUILayout.Button("Disable", EditorStyles.miniButton, GUILayout.ExpandWidth(false))) { UndoableAction( tm => tm.wordWrapWidth = 0 ); GUI.changed = true; } } --EditorGUI.indentLevel; GUILayout.EndHorizontal(); EditorGUILayout.EndToggleGroup(); GUILayout.BeginHorizontal (); bool newInlineStyling = EditorGUILayout.Toggle("Inline Styling", textMesh.inlineStyling); if (newInlineStyling != textMesh.inlineStyling) { UndoableAction( tm => tm.inlineStyling = newInlineStyling ); } if (textMesh.inlineStyling) { showInlineStylingHelp = GUILayout.Toggle(showInlineStylingHelp, "?", EditorStyles.miniButton, GUILayout.ExpandWidth(false)); } GUILayout.EndHorizontal (); if (textMesh.inlineStyling && showInlineStylingHelp) { Color bg = GUI.backgroundColor; GUI.backgroundColor = new Color32(154, 176, 203, 255); string message = "Inline style commands\n\n" + "^cRGBA - set color\n" + "^gRGBARGBA - set top and bottom colors\n" + " RGBA = single digit hex values (0 - f)\n\n" + "^CRRGGBBAA - set color\n" + "^GRRGGBBAARRGGBBAA - set top and bottom colors\n" + " RRGGBBAA = 2 digit hex values (00 - ff)\n\n" + ((textMesh.font.textureGradients && textMesh.font.gradientCount > 0) ? "^0-9 - select gradient\n" : "") + "^^ - print ^"; tk2dGuiUtility.InfoBox( message, tk2dGuiUtility.WarningLevel.Info ); GUI.backgroundColor = bg; } GUILayout.BeginHorizontal(); EditorGUILayout.PrefixLabel("Text"); string newText = EditorGUILayout.TextArea(textMesh.text, textAreaStyle, GUILayout.Height(64)); if (newText != textMesh.text) { UndoableAction( tm => tm.text = newText ); GUI.changed = true; } GUILayout.EndHorizontal(); if (textMesh.NumTotalCharacters() > textMesh.maxChars) { tk2dGuiUtility.InfoBox( "Number of printable characters in text mesh exceeds MaxChars on this text mesh. "+ "The text will be clipped at " + textMesh.maxChars.ToString() + " characters.", tk2dGuiUtility.WarningLevel.Error ); } TextAnchor newTextAnchor = (TextAnchor)EditorGUILayout.EnumPopup("Anchor", textMesh.anchor); if (newTextAnchor != textMesh.anchor) UndoableAction( tm => tm.anchor = newTextAnchor ); bool newKerning = EditorGUILayout.Toggle("Kerning", textMesh.kerning); if (newKerning != textMesh.kerning) UndoableAction( tm => tm.kerning = newKerning ); float newSpacing = EditorGUILayout.FloatField("Spacing", textMesh.Spacing); if (newSpacing != textMesh.Spacing) UndoableAction( tm => tm.Spacing = newSpacing ); float newLineSpacing = EditorGUILayout.FloatField("Line Spacing", textMesh.LineSpacing); if (newLineSpacing != textMesh.LineSpacing) UndoableAction( tm => tm.LineSpacing = newLineSpacing ); #if UNITY_3_5 || UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2 int sortingOrder = EditorGUILayout.IntField("Sorting Order In Layer", targetTextMeshes[0].SortingOrder); if (sortingOrder != targetTextMeshes[0].SortingOrder) { tk2dUndo.RecordObjects(targetTextMeshes, "Sorting Order In Layer"); foreach (tk2dTextMesh s in targetTextMeshes) { s.SortingOrder = sortingOrder; } } #else if (renderers.Length > 0) { string sortingLayerName = tk2dEditorUtility.SortingLayerNamePopup("Sorting Layer", renderers[0].sortingLayerName); if (sortingLayerName != renderers[0].sortingLayerName) { tk2dUndo.RecordObjects(renderers, "Sorting Layer"); foreach (Renderer r in renderers) { r.sortingLayerName = sortingLayerName; tk2dUtil.SetDirty(r); } } int sortingOrder = EditorGUILayout.IntField("Order In Layer", targetTextMeshes[0].SortingOrder); if (sortingOrder != targetTextMeshes[0].SortingOrder) { tk2dUndo.RecordObjects(targetTextMeshes, "Order In Layer"); tk2dUndo.RecordObjects(renderers, "Order In Layer"); foreach (tk2dTextMesh s in targetTextMeshes) { s.SortingOrder = sortingOrder; } } } #endif Vector3 newScale = EditorGUILayout.Vector3Field("Scale", textMesh.scale); if (newScale != textMesh.scale) UndoableAction( tm => tm.scale = newScale ); if (textMesh.font.textureGradients && textMesh.font.gradientCount > 0) { GUILayout.BeginHorizontal(); EditorGUILayout.PrefixLabel("TextureGradient"); // Draw gradient scroller bool drawGradientScroller = true; if (drawGradientScroller) { textMesh.textureGradient = textMesh.textureGradient % textMesh.font.gradientCount; gradientScroll = EditorGUILayout.BeginScrollView(gradientScroll, GUILayout.ExpandHeight(false)); Rect r = GUILayoutUtility.GetRect(textMesh.font.gradientTexture.width, textMesh.font.gradientTexture.height, GUILayout.ExpandWidth(false), GUILayout.ExpandHeight(false)); GUI.DrawTexture(r, textMesh.font.gradientTexture); Rect hr = r; hr.width /= textMesh.font.gradientCount; hr.x += hr.width * textMesh.textureGradient; float ox = hr.width / 8; float oy = hr.height / 8; Vector3[] rectVerts = { new Vector3(hr.x + 0.5f + ox, hr.y + oy, 0), new Vector3(hr.x + hr.width - ox, hr.y + oy, 0), new Vector3(hr.x + hr.width - ox, hr.y + hr.height - 0.5f - oy, 0), new Vector3(hr.x + ox, hr.y + hr.height - 0.5f - oy, 0) }; Handles.DrawSolidRectangleWithOutline(rectVerts, new Color(0,0,0,0.2f), new Color(0,0,0,1)); if (GUIUtility.hotControl == 0 && Event.current.type == EventType.MouseDown && r.Contains(Event.current.mousePosition)) { int newTextureGradient = (int)(Event.current.mousePosition.x / (textMesh.font.gradientTexture.width / textMesh.font.gradientCount)); if (newTextureGradient != textMesh.textureGradient) { UndoableAction( delegate(tk2dTextMesh tm) { if (tm.useGUILayout && tm.font != null && newTextureGradient < tm.font.gradientCount) { tm.textureGradient = newTextureGradient; } } ); } GUI.changed = true; } EditorGUILayout.EndScrollView(); } GUILayout.EndHorizontal(); } EditorGUILayout.BeginHorizontal(); if (GUILayout.Button("HFlip")) { UndoableAction( delegate(tk2dTextMesh tm) { Vector3 s = tm.scale; s.x *= -1.0f; tm.scale = s; } ); GUI.changed = true; } if (GUILayout.Button("VFlip")) { UndoableAction( delegate(tk2dTextMesh tm) { Vector3 s = tm.scale; s.y *= -1.0f; tm.scale = s; } ); GUI.changed = true; } EditorGUILayout.EndHorizontal(); EditorGUILayout.BeginHorizontal(); if (GUILayout.Button("Bake Scale")) { tk2dScaleUtility.Bake(textMesh.transform); GUI.changed = true; } GUIContent pixelPerfectButton = new GUIContent("1:1", "Make Pixel Perfect"); if ( GUILayout.Button(pixelPerfectButton )) { if (tk2dPixelPerfectHelper.inst) tk2dPixelPerfectHelper.inst.Setup(); UndoableAction( tm => tm.MakePixelPerfect() ); GUI.changed = true; } EditorGUILayout.EndHorizontal(); if (textMesh.font && !textMesh.font.inst.isPacked) { bool newUseGradient = EditorGUILayout.Toggle("Use Gradient", textMesh.useGradient); if (newUseGradient != textMesh.useGradient) { UndoableAction( tm => tm.useGradient = newUseGradient ); } if (textMesh.useGradient) { Color newColor = EditorGUILayout.ColorField("Top Color", textMesh.color); if (newColor != textMesh.color) UndoableAction( tm => tm.color = newColor ); Color newColor2 = EditorGUILayout.ColorField("Bottom Color", textMesh.color2); if (newColor2 != textMesh.color2) UndoableAction( tm => tm.color2 = newColor2 ); } else { Color newColor = EditorGUILayout.ColorField("Color", textMesh.color); if (newColor != textMesh.color) UndoableAction( tm => tm.color = newColor ); } } if (GUI.changed) { foreach (tk2dTextMesh tm in targetTextMeshes) { tm.ForceBuild(); tk2dUtil.SetDirty(tm); } } } } [MenuItem(tk2dMenu.createBase + "TextMesh", false, 13905)] static void DoCreateTextMesh() { tk2dFontData fontData = null; // Find reference in scene tk2dTextMesh dupeMesh = GameObject.FindObjectOfType(typeof(tk2dTextMesh)) as tk2dTextMesh; if (dupeMesh) fontData = dupeMesh.font; // Find in library if (fontData == null) { tk2dGenericIndexItem[] allFontEntries = tk2dEditorUtility.GetOrCreateIndex().GetFonts(); foreach (var v in allFontEntries) { if (v.managed) continue; tk2dFontData data = v.GetData<tk2dFontData>(); if (data != null) { fontData = data; break; } } } if (fontData == null) { EditorUtility.DisplayDialog("Create TextMesh", "Unable to create text mesh as no Fonts have been found.", "Ok"); return; } GameObject go = tk2dEditorUtility.CreateGameObjectInScene("TextMesh"); tk2dTextMesh textMesh = go.AddComponent<tk2dTextMesh>(); textMesh.font = fontData; textMesh.text = "New TextMesh"; textMesh.Commit(); Selection.activeGameObject = go; Undo.RegisterCreatedObjectUndo(go, "Create TextMesh"); } }
using System; using System.Collections.Generic; using System.Diagnostics; using BTDB.Buffer; namespace BTDB.KVDBLayer.BTree { class BTreeBranch : IBTreeNode { internal readonly long TransactionId; byte[][] _keys; IBTreeNode[] _children; long[] _pairCounts; internal const int MaxChildren = 30; internal BTreeBranch(long transactionId, IBTreeNode node1, IBTreeNode node2) { TransactionId = transactionId; _children = new[] { node1, node2 }; _keys = new[] { node2.GetLeftMostKey() }; var leftCount = node1.CalcKeyCount(); var rightCount = node2.CalcKeyCount(); _pairCounts = new[] { leftCount, leftCount + rightCount }; } BTreeBranch(long transactionId, byte[][] newKeys, IBTreeNode[] newChildren, long[] newPairCounts) { TransactionId = transactionId; _keys = newKeys; _children = newChildren; _pairCounts = newPairCounts; } public BTreeBranch(long transactionId, int count, Func<IBTreeNode> generator) { Debug.Assert(count > 0 && count <= MaxChildren); TransactionId = transactionId; _keys = new byte[count - 1][]; _pairCounts = new long[count]; _children = new IBTreeNode[count]; long pairs = 0; for (var i = 0; i < _children.Length; i++) { var child = generator(); _children[i] = child; pairs += child.CalcKeyCount(); _pairCounts[i] = pairs; if (i > 0) { _keys[i - 1] = child.GetLeftMostKey(); } } } int Find(byte[] prefix, ByteBuffer key) { var left = 0; var right = _keys.Length; while (left < right) { var middle = (left + right) / 2; var currentKey = _keys[middle]; var result = BitArrayManipulation.CompareByteArray(prefix, prefix.Length, currentKey, Math.Min(currentKey.Length, prefix.Length)); if (result == 0) { result = BitArrayManipulation.CompareByteArray(key.Buffer, key.Offset, key.Length, currentKey, prefix.Length, currentKey.Length - prefix.Length); } if (result < 0) { right = middle; } else { left = middle + 1; } } return left; } public void CreateOrUpdate(CreateOrUpdateCtx ctx) { var index = Find(ctx.KeyPrefix, ctx.Key); ctx.Stack.Add(new NodeIdxPair { Node = this, Idx = index }); ctx.Depth++; _children[index].CreateOrUpdate(ctx); ctx.Depth--; var newBranch = this; if (ctx.Split) { ctx.Split = false; var newKeys = new byte[_children.Length][]; var newChildren = new IBTreeNode[_children.Length + 1]; var newPairCounts = new long[_children.Length + 1]; Array.Copy(_keys, 0, newKeys, 0, index); newKeys[index] = ctx.Node2.GetLeftMostKey(); Array.Copy(_keys, index, newKeys, index + 1, _keys.Length - index); Array.Copy(_children, 0, newChildren, 0, index); newChildren[index] = ctx.Node1; newChildren[index + 1] = ctx.Node2; Array.Copy(_children, index + 1, newChildren, index + 2, _children.Length - index - 1); Array.Copy(_pairCounts, newPairCounts, index); var previousPairCount = index > 0 ? newPairCounts[index - 1] : 0; for (var i = index; i < newPairCounts.Length; i++) { previousPairCount += newChildren[i].CalcKeyCount(); newPairCounts[i] = previousPairCount; } ctx.Node1 = null; ctx.Node2 = null; if (_children.Length < MaxChildren) { if (TransactionId != ctx.TransactionId) { newBranch = new BTreeBranch(ctx.TransactionId, newKeys, newChildren, newPairCounts); ctx.Node1 = newBranch; ctx.Update = true; } else { _keys = newKeys; _children = newChildren; _pairCounts = newPairCounts; } if (ctx.SplitInRight) index++; ctx.Stack[ctx.Depth] = new NodeIdxPair { Node = newBranch, Idx = index }; return; } if (ctx.SplitInRight) index++; ctx.Split = true; var keyCountLeft = (newChildren.Length + 1) / 2; var keyCountRight = newChildren.Length - keyCountLeft; var splitKeys = new byte[keyCountLeft - 1][]; var splitChildren = new IBTreeNode[keyCountLeft]; var splitPairCounts = new long[keyCountLeft]; Array.Copy(newKeys, splitKeys, splitKeys.Length); Array.Copy(newChildren, splitChildren, splitChildren.Length); Array.Copy(newPairCounts, splitPairCounts, splitPairCounts.Length); ctx.Node1 = new BTreeBranch(ctx.TransactionId, splitKeys, splitChildren, splitPairCounts); splitKeys = new byte[keyCountRight - 1][]; splitChildren = new IBTreeNode[keyCountRight]; splitPairCounts = new long[keyCountRight]; Array.Copy(newKeys, keyCountLeft, splitKeys, 0, splitKeys.Length); Array.Copy(newChildren, keyCountLeft, splitChildren, 0, splitChildren.Length); for (int i = 0; i < splitPairCounts.Length; i++) { splitPairCounts[i] = newPairCounts[keyCountLeft + i] - newPairCounts[keyCountLeft - 1]; } ctx.Node2 = new BTreeBranch(ctx.TransactionId, splitKeys, splitChildren, splitPairCounts); if (index < keyCountLeft) { ctx.Stack[ctx.Depth] = new NodeIdxPair { Node = ctx.Node1, Idx = index }; ctx.SplitInRight = false; } else { ctx.Stack[ctx.Depth] = new NodeIdxPair { Node = ctx.Node2, Idx = index - keyCountLeft }; ctx.SplitInRight = true; } return; } if (ctx.Update) { if (TransactionId != ctx.TransactionId) { var newKeys = new byte[_keys.Length][]; var newChildren = new IBTreeNode[_children.Length]; var newPairCounts = new long[_children.Length]; Array.Copy(_keys, newKeys, _keys.Length); Array.Copy(_children, newChildren, _children.Length); newChildren[index] = ctx.Node1; Array.Copy(_pairCounts, newPairCounts, _pairCounts.Length); newBranch = new BTreeBranch(ctx.TransactionId, newKeys, newChildren, newPairCounts); ctx.Node1 = newBranch; } else { _children[index] = ctx.Node1; ctx.Update = false; ctx.Node1 = null; } ctx.Stack[ctx.Depth] = new NodeIdxPair { Node = newBranch, Idx = index }; } Debug.Assert(newBranch.TransactionId == ctx.TransactionId); if (!ctx.Created) return; var pairCounts = newBranch._pairCounts; for (var i = index; i < pairCounts.Length; i++) { pairCounts[i]++; } } public FindResult FindKey(List<NodeIdxPair> stack, out long keyIndex, byte[] prefix, ByteBuffer key) { var idx = Find(prefix, key); stack.Add(new NodeIdxPair { Node = this, Idx = idx }); var result = _children[idx].FindKey(stack, out keyIndex, prefix, key); if (idx > 0) keyIndex += _pairCounts[idx - 1]; return result; } public long CalcKeyCount() { return _pairCounts[_pairCounts.Length - 1]; } public byte[] GetLeftMostKey() { return _children[0].GetLeftMostKey(); } public void FillStackByIndex(List<NodeIdxPair> stack, long keyIndex) { var left = 0; var right = _pairCounts.Length - 1; while (left < right) { var middle = (left + right) / 2; var currentIndex = _pairCounts[middle]; if (keyIndex < currentIndex) { right = middle; } else { left = middle + 1; } } stack.Add(new NodeIdxPair { Node = this, Idx = left }); _children[left].FillStackByIndex(stack, keyIndex - (left > 0 ? _pairCounts[left - 1] : 0)); } public long FindLastWithPrefix(byte[] prefix) { var left = 0; var right = _keys.Length; while (left < right) { var middle = (left + right) / 2; var currentKey = _keys[middle]; var result = BitArrayManipulation.CompareByteArray(prefix, prefix.Length, currentKey, Math.Min(currentKey.Length, prefix.Length)); if (result < 0) { right = middle; } else { left = middle + 1; } } return _children[left].FindLastWithPrefix(prefix) + (left > 0 ? _pairCounts[left - 1] : 0); } public bool NextIdxValid(int idx) { return idx + 1 < _children.Length; } public void FillStackByLeftMost(List<NodeIdxPair> stack, int idx) { var leftMost = _children[idx]; stack.Add(new NodeIdxPair { Node = leftMost, Idx = 0 }); leftMost.FillStackByLeftMost(stack, 0); } public void FillStackByRightMost(List<NodeIdxPair> stack, int idx) { var rightMost = _children[idx]; var lastIdx = rightMost.GetLastChildrenIdx(); stack.Add(new NodeIdxPair { Node = rightMost, Idx = lastIdx }); rightMost.FillStackByRightMost(stack, lastIdx); } public int GetLastChildrenIdx() { return _children.Length - 1; } public IBTreeNode EraseRange(long transactionId, long firstKeyIndex, long lastKeyIndex) { int firstRemoved = -1; int lastRemoved = -1; IBTreeNode firstPartialNode = null; IBTreeNode lastPartialNode = null; for (int i = 0; i < _pairCounts.Length; i++) { var prevPairCount = i > 0 ? _pairCounts[i - 1] : 0; if (lastKeyIndex < prevPairCount) break; var nextPairCount = _pairCounts[i]; if (nextPairCount <= firstKeyIndex) continue; if (firstKeyIndex <= prevPairCount && nextPairCount - 1 <= lastKeyIndex) { if (firstRemoved == -1) firstRemoved = i; lastRemoved = i; continue; } if (prevPairCount <= firstKeyIndex && lastKeyIndex < nextPairCount) { firstRemoved = i; lastRemoved = i; firstPartialNode = _children[i].EraseRange(transactionId, firstKeyIndex - prevPairCount, lastKeyIndex - prevPairCount); lastPartialNode = firstPartialNode; break; } if (firstRemoved == -1 && firstKeyIndex < nextPairCount) { if (prevPairCount > firstKeyIndex) throw new InvalidOperationException(); if (nextPairCount > lastKeyIndex) throw new InvalidOperationException(); firstRemoved = i; firstPartialNode = _children[i].EraseRange(transactionId, firstKeyIndex - prevPairCount, nextPairCount - 1 - prevPairCount); continue; } if (lastKeyIndex >= nextPairCount - 1) throw new InvalidOperationException(); lastRemoved = i; lastPartialNode = _children[i].EraseRange(transactionId, 0, lastKeyIndex - prevPairCount); break; } var finalChildrenCount = firstRemoved - (firstPartialNode == null ? 1 : 0) + _children.Length + 1 - lastRemoved - (lastPartialNode == null ? 1 : 0) - (firstPartialNode == lastPartialNode && firstPartialNode != null ? 1 : 0); var newKeys = new byte[finalChildrenCount - 1][]; var newChildren = new IBTreeNode[finalChildrenCount]; var newPairCounts = new long[finalChildrenCount]; Array.Copy(_children, 0, newChildren, 0, firstRemoved); var idx = firstRemoved; if (firstPartialNode != null && firstPartialNode != lastPartialNode) { newChildren[idx] = firstPartialNode; idx++; } if (lastPartialNode != null) { newChildren[idx] = lastPartialNode; idx++; } Array.Copy(_children, lastRemoved + 1, newChildren, idx, finalChildrenCount - idx); var previousPairCount = 0L; for (var i = 0; i < finalChildrenCount; i++) { previousPairCount += newChildren[i].CalcKeyCount(); newPairCounts[i] = previousPairCount; } for (var i = 0; i < finalChildrenCount - 1; i++) { newKeys[i] = newChildren[i + 1].GetLeftMostKey(); } if (transactionId == TransactionId) { _keys = newKeys; _children = newChildren; _pairCounts = newPairCounts; return this; } return new BTreeBranch(transactionId, newKeys, newChildren, newPairCounts); } public void Iterate(ValuesIterateAction action) { foreach (var child in _children) { child.Iterate(action); } } public IBTreeNode ReplaceValues(ReplaceValuesCtx ctx) { var result = this; var children = _children; var i = 0; if (ctx._restartKey != null) { for (; i < _keys.Length; i++) { var compRes = BitArrayManipulation.CompareByteArray(_keys[i], 0, _keys[i].Length, ctx._restartKey, 0, ctx._restartKey.Length); if (compRes > 0) break; } } for (; i < children.Length; i++) { var child = children[i]; var newChild = child.ReplaceValues(ctx); if (newChild != child) { if (result.TransactionId != ctx._transactionId) { var newKeys = new byte[_keys.Length][]; Array.Copy(_keys, newKeys, newKeys.Length); var newChildren = new IBTreeNode[_children.Length]; Array.Copy(_children, newChildren, newChildren.Length); var newPairCounts = new long[_pairCounts.Length]; Array.Copy(_pairCounts, newPairCounts, newPairCounts.Length); result = new BTreeBranch(ctx._transactionId, newKeys, newChildren, newPairCounts); children = newChildren; } children[i] = newChild; } if (ctx._interrupt) break; ctx._restartKey = null; var now = DateTime.UtcNow; if (i < _keys.Length && (now > ctx._iterationTimeOut || ctx._cancellation.IsCancellationRequested)) { ctx._interrupt = true; ctx._restartKey = _keys[i]; break; } } return result; } } }
//----------------------------------------------------------------------------- // Verve // Copyright (C) - Violent Tulip //----------------------------------------------------------------------------- $VerveEditor::FilePath = "sequences"; $VerveEditor::FileSpec = "Verve Sequence Files (*.vsf)|*.vsf|All Files (*.*)|*.*|"; //----------------------------------------------------------------------------- function VerveEditor::GetFileTarget( %type ) { %filePath = $VerveEditor::FilePath; if ( strlen( $Pref::VerveEditor::FilePath ) > 0 ) { %filePath = $Pref::VerveEditor::FilePath; } %fileDialog = new ( %type @ "FileDialog" )() { Filters = $VerveEditor::FileSpec; DefaultPath = %filePath; ChangePath = false; MustExist = true; }; // Record the file name %filename = ""; if ( %fileDialog.Execute() ) { %filename = %fileDialog.FileName; // Store the preference $Pref::VerveEditor::FilePath = makeRelativePath( filePath( %filename ), getMainDotCsDir() ); } // Delete the dialog %fileDialog.delete(); // Return the filename return %filename; } function VerveEditor::NewFile() { if ( !isObject( $VerveEditor::Controller ) ) { return; } // Save? if ( !VerveEditor::SavePrompt() ) { return; } // Clear Sequence Lists. $VerveEditor::Controller.clear(); // Clear File. $VerveEditor::Controller.FileName = ""; // Reset Properties. $VerveEditor::Controller.Time = 0; $VerveEditor::Controller.Duration = 5000; $VerveEditor::Controller.TimeScale = 1.0; // Clear Editor History. VerveEditor::ClearHistory(); // Refresh Editor. VerveEditor::Refresh(); } function VerveEditor::LoadFile( %fileName ) { if ( !isObject( $VerveEditor::Controller ) ) { return; } // Save? if ( !VerveEditor::SavePrompt() ) { return; } if ( %fileName $= "" ) { %fileName = VerveEditor::GetFileTarget( "Open" ); } // Clear File. $VerveEditor::Controller.FileName = ""; if ( $VerveEditor::Controller.readFile( %fileName ) ) { // Pause. VerveEditor::Pause(); // Store the File. $VerveEditor::Controller.FileName = %fileName; // Update File History. VerveEditor::UpdateFileHistory( %fileName ); // Clear Editor History. VerveEditor::ClearHistory(); // Refresh Editor. VerveEditor::Refresh(); return true; } // Argh! // Attempting to load a file which results in failure means the existing // sequence is messed up, ouch! Do something better than creating a new // sequence... VerveEditor::NewFile(); return false; } function VerveEditor::SaveFile( %forceSaveAs ) { if ( !isObject( $VerveEditor::Controller ) ) { return false; } %fileName = $VerveEditor::Controller.FileName; if ( %forceSaveAs || %fileName $= "" ) { %fileName = VerveEditor::GetFileTarget( "Save" ); if ( %fileName $= "" ) { // No Save. return false; } } if ( fileExt( fileName( %fileName ) ) $= "" ) { // Add Extension. %fileName = %fileName @ ".vsf"; } // Write. $VerveEditor::Controller.writeFile( %fileName ); // Store the File. $VerveEditor::Controller.FileName = %fileName; // Update File History. VerveEditor::UpdateFileHistory( %fileName ); // Clear Dirty. VerveEditor::ClearDirty(); // Update Window Title. VerveEditorWindow.UpdateWindowTitle(); // Valid Save. return true; } function VerveEditor::SavePrompt() { if ( !VerveEditor::IsDirty() ) { return true; } %result = messageBox( "Verve Editor", "Save Changes to your sequence?", "SaveDontSave", "Warning" ); if ( %result $= $MROk ) { // Save. return VerveEditor::SaveFile(); } return true; } function VerveEditor::SavePromptCancel() { if ( !VerveEditor::IsDirty() ) { return true; } %result = messageBox( "Verve Editor", "Save Changes to your sequence?", "SaveDontSaveCancel", "Warning" ); if ( %result $= $MRCancel ) { return false; } if ( %result $= $MROk ) { // Save. return VerveEditor::SaveFile(); } return true; } function VerveEditor::UpdateFileHistory( %filePath ) { // Make Relative. %fileLabel = makeRelativePath( %filePath, getMainDotCsDir() ); // Select an Index. %initIndex = $Pref::VerveEditor::RecentFileSize; for ( %i = 0; %i < %initIndex; %i++ ) { %prefFile = $Pref::VerveEditor::RecentFile[%i]; if ( %prefFile $= %fileLabel ) { %initIndex = %i; break; } } // Push Others Down. for ( %i = %initIndex; %i > 0; %i-- ) { $Pref::VerveEditor::RecentFile[%i] = $Pref::VerveEditor::RecentFile[%i - 1]; } // Push to the Front. $Pref::VerveEditor::RecentFile[0] = %fileLabel; }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using ga = Google.Api; using gaxgrpc = Google.Api.Gax.Grpc; using lro = Google.LongRunning; using proto = Google.Protobuf; using wkt = Google.Protobuf.WellKnownTypes; using grpccore = Grpc.Core; using moq = Moq; using st = System.Threading; using stt = System.Threading.Tasks; using xunit = Xunit; namespace Google.Cloud.RecommendationEngine.V1Beta1.Tests { /// <summary>Generated unit tests.</summary> public sealed class GeneratedUserEventServiceClientTest { [xunit::FactAttribute] public void WriteUserEventRequestObject() { moq::Mock<UserEventService.UserEventServiceClient> mockGrpcClient = new moq::Mock<UserEventService.UserEventServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); WriteUserEventRequest request = new WriteUserEventRequest { ParentAsEventStoreName = EventStoreName.FromProjectLocationCatalogEventStore("[PROJECT]", "[LOCATION]", "[CATALOG]", "[EVENT_STORE]"), UserEvent = new UserEvent(), }; UserEvent expectedResponse = new UserEvent { EventType = "event_type1436d01c", UserInfo = new UserInfo(), EventDetail = new EventDetail(), ProductEventDetail = new ProductEventDetail(), EventTime = new wkt::Timestamp(), EventSource = UserEvent.Types.EventSource.Automl, }; mockGrpcClient.Setup(x => x.WriteUserEvent(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); UserEventServiceClient client = new UserEventServiceClientImpl(mockGrpcClient.Object, null); UserEvent response = client.WriteUserEvent(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task WriteUserEventRequestObjectAsync() { moq::Mock<UserEventService.UserEventServiceClient> mockGrpcClient = new moq::Mock<UserEventService.UserEventServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); WriteUserEventRequest request = new WriteUserEventRequest { ParentAsEventStoreName = EventStoreName.FromProjectLocationCatalogEventStore("[PROJECT]", "[LOCATION]", "[CATALOG]", "[EVENT_STORE]"), UserEvent = new UserEvent(), }; UserEvent expectedResponse = new UserEvent { EventType = "event_type1436d01c", UserInfo = new UserInfo(), EventDetail = new EventDetail(), ProductEventDetail = new ProductEventDetail(), EventTime = new wkt::Timestamp(), EventSource = UserEvent.Types.EventSource.Automl, }; mockGrpcClient.Setup(x => x.WriteUserEventAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<UserEvent>(stt::Task.FromResult(expectedResponse), null, null, null, null)); UserEventServiceClient client = new UserEventServiceClientImpl(mockGrpcClient.Object, null); UserEvent responseCallSettings = await client.WriteUserEventAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); UserEvent responseCancellationToken = await client.WriteUserEventAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void WriteUserEvent() { moq::Mock<UserEventService.UserEventServiceClient> mockGrpcClient = new moq::Mock<UserEventService.UserEventServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); WriteUserEventRequest request = new WriteUserEventRequest { ParentAsEventStoreName = EventStoreName.FromProjectLocationCatalogEventStore("[PROJECT]", "[LOCATION]", "[CATALOG]", "[EVENT_STORE]"), UserEvent = new UserEvent(), }; UserEvent expectedResponse = new UserEvent { EventType = "event_type1436d01c", UserInfo = new UserInfo(), EventDetail = new EventDetail(), ProductEventDetail = new ProductEventDetail(), EventTime = new wkt::Timestamp(), EventSource = UserEvent.Types.EventSource.Automl, }; mockGrpcClient.Setup(x => x.WriteUserEvent(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); UserEventServiceClient client = new UserEventServiceClientImpl(mockGrpcClient.Object, null); UserEvent response = client.WriteUserEvent(request.Parent, request.UserEvent); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task WriteUserEventAsync() { moq::Mock<UserEventService.UserEventServiceClient> mockGrpcClient = new moq::Mock<UserEventService.UserEventServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); WriteUserEventRequest request = new WriteUserEventRequest { ParentAsEventStoreName = EventStoreName.FromProjectLocationCatalogEventStore("[PROJECT]", "[LOCATION]", "[CATALOG]", "[EVENT_STORE]"), UserEvent = new UserEvent(), }; UserEvent expectedResponse = new UserEvent { EventType = "event_type1436d01c", UserInfo = new UserInfo(), EventDetail = new EventDetail(), ProductEventDetail = new ProductEventDetail(), EventTime = new wkt::Timestamp(), EventSource = UserEvent.Types.EventSource.Automl, }; mockGrpcClient.Setup(x => x.WriteUserEventAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<UserEvent>(stt::Task.FromResult(expectedResponse), null, null, null, null)); UserEventServiceClient client = new UserEventServiceClientImpl(mockGrpcClient.Object, null); UserEvent responseCallSettings = await client.WriteUserEventAsync(request.Parent, request.UserEvent, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); UserEvent responseCancellationToken = await client.WriteUserEventAsync(request.Parent, request.UserEvent, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void WriteUserEventResourceNames() { moq::Mock<UserEventService.UserEventServiceClient> mockGrpcClient = new moq::Mock<UserEventService.UserEventServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); WriteUserEventRequest request = new WriteUserEventRequest { ParentAsEventStoreName = EventStoreName.FromProjectLocationCatalogEventStore("[PROJECT]", "[LOCATION]", "[CATALOG]", "[EVENT_STORE]"), UserEvent = new UserEvent(), }; UserEvent expectedResponse = new UserEvent { EventType = "event_type1436d01c", UserInfo = new UserInfo(), EventDetail = new EventDetail(), ProductEventDetail = new ProductEventDetail(), EventTime = new wkt::Timestamp(), EventSource = UserEvent.Types.EventSource.Automl, }; mockGrpcClient.Setup(x => x.WriteUserEvent(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); UserEventServiceClient client = new UserEventServiceClientImpl(mockGrpcClient.Object, null); UserEvent response = client.WriteUserEvent(request.ParentAsEventStoreName, request.UserEvent); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task WriteUserEventResourceNamesAsync() { moq::Mock<UserEventService.UserEventServiceClient> mockGrpcClient = new moq::Mock<UserEventService.UserEventServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); WriteUserEventRequest request = new WriteUserEventRequest { ParentAsEventStoreName = EventStoreName.FromProjectLocationCatalogEventStore("[PROJECT]", "[LOCATION]", "[CATALOG]", "[EVENT_STORE]"), UserEvent = new UserEvent(), }; UserEvent expectedResponse = new UserEvent { EventType = "event_type1436d01c", UserInfo = new UserInfo(), EventDetail = new EventDetail(), ProductEventDetail = new ProductEventDetail(), EventTime = new wkt::Timestamp(), EventSource = UserEvent.Types.EventSource.Automl, }; mockGrpcClient.Setup(x => x.WriteUserEventAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<UserEvent>(stt::Task.FromResult(expectedResponse), null, null, null, null)); UserEventServiceClient client = new UserEventServiceClientImpl(mockGrpcClient.Object, null); UserEvent responseCallSettings = await client.WriteUserEventAsync(request.ParentAsEventStoreName, request.UserEvent, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); UserEvent responseCancellationToken = await client.WriteUserEventAsync(request.ParentAsEventStoreName, request.UserEvent, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void CollectUserEventRequestObject() { moq::Mock<UserEventService.UserEventServiceClient> mockGrpcClient = new moq::Mock<UserEventService.UserEventServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); CollectUserEventRequest request = new CollectUserEventRequest { ParentAsEventStoreName = EventStoreName.FromProjectLocationCatalogEventStore("[PROJECT]", "[LOCATION]", "[CATALOG]", "[EVENT_STORE]"), UserEvent = "user_eventc8146d99", Uri = "uri3db70593", Ets = -4649673071663131288L, }; ga::HttpBody expectedResponse = new ga::HttpBody { ContentType = "content_type085be0ea", Data = proto::ByteString.CopyFromUtf8("data387f778d"), Extensions = { new wkt::Any(), }, }; mockGrpcClient.Setup(x => x.CollectUserEvent(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); UserEventServiceClient client = new UserEventServiceClientImpl(mockGrpcClient.Object, null); ga::HttpBody response = client.CollectUserEvent(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task CollectUserEventRequestObjectAsync() { moq::Mock<UserEventService.UserEventServiceClient> mockGrpcClient = new moq::Mock<UserEventService.UserEventServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); CollectUserEventRequest request = new CollectUserEventRequest { ParentAsEventStoreName = EventStoreName.FromProjectLocationCatalogEventStore("[PROJECT]", "[LOCATION]", "[CATALOG]", "[EVENT_STORE]"), UserEvent = "user_eventc8146d99", Uri = "uri3db70593", Ets = -4649673071663131288L, }; ga::HttpBody expectedResponse = new ga::HttpBody { ContentType = "content_type085be0ea", Data = proto::ByteString.CopyFromUtf8("data387f778d"), Extensions = { new wkt::Any(), }, }; mockGrpcClient.Setup(x => x.CollectUserEventAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ga::HttpBody>(stt::Task.FromResult(expectedResponse), null, null, null, null)); UserEventServiceClient client = new UserEventServiceClientImpl(mockGrpcClient.Object, null); ga::HttpBody responseCallSettings = await client.CollectUserEventAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); ga::HttpBody responseCancellationToken = await client.CollectUserEventAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void CollectUserEvent() { moq::Mock<UserEventService.UserEventServiceClient> mockGrpcClient = new moq::Mock<UserEventService.UserEventServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); CollectUserEventRequest request = new CollectUserEventRequest { ParentAsEventStoreName = EventStoreName.FromProjectLocationCatalogEventStore("[PROJECT]", "[LOCATION]", "[CATALOG]", "[EVENT_STORE]"), UserEvent = "user_eventc8146d99", Uri = "uri3db70593", Ets = -4649673071663131288L, }; ga::HttpBody expectedResponse = new ga::HttpBody { ContentType = "content_type085be0ea", Data = proto::ByteString.CopyFromUtf8("data387f778d"), Extensions = { new wkt::Any(), }, }; mockGrpcClient.Setup(x => x.CollectUserEvent(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); UserEventServiceClient client = new UserEventServiceClientImpl(mockGrpcClient.Object, null); ga::HttpBody response = client.CollectUserEvent(request.Parent, request.UserEvent, request.Uri, request.Ets); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task CollectUserEventAsync() { moq::Mock<UserEventService.UserEventServiceClient> mockGrpcClient = new moq::Mock<UserEventService.UserEventServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); CollectUserEventRequest request = new CollectUserEventRequest { ParentAsEventStoreName = EventStoreName.FromProjectLocationCatalogEventStore("[PROJECT]", "[LOCATION]", "[CATALOG]", "[EVENT_STORE]"), UserEvent = "user_eventc8146d99", Uri = "uri3db70593", Ets = -4649673071663131288L, }; ga::HttpBody expectedResponse = new ga::HttpBody { ContentType = "content_type085be0ea", Data = proto::ByteString.CopyFromUtf8("data387f778d"), Extensions = { new wkt::Any(), }, }; mockGrpcClient.Setup(x => x.CollectUserEventAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ga::HttpBody>(stt::Task.FromResult(expectedResponse), null, null, null, null)); UserEventServiceClient client = new UserEventServiceClientImpl(mockGrpcClient.Object, null); ga::HttpBody responseCallSettings = await client.CollectUserEventAsync(request.Parent, request.UserEvent, request.Uri, request.Ets, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); ga::HttpBody responseCancellationToken = await client.CollectUserEventAsync(request.Parent, request.UserEvent, request.Uri, request.Ets, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void CollectUserEventResourceNames() { moq::Mock<UserEventService.UserEventServiceClient> mockGrpcClient = new moq::Mock<UserEventService.UserEventServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); CollectUserEventRequest request = new CollectUserEventRequest { ParentAsEventStoreName = EventStoreName.FromProjectLocationCatalogEventStore("[PROJECT]", "[LOCATION]", "[CATALOG]", "[EVENT_STORE]"), UserEvent = "user_eventc8146d99", Uri = "uri3db70593", Ets = -4649673071663131288L, }; ga::HttpBody expectedResponse = new ga::HttpBody { ContentType = "content_type085be0ea", Data = proto::ByteString.CopyFromUtf8("data387f778d"), Extensions = { new wkt::Any(), }, }; mockGrpcClient.Setup(x => x.CollectUserEvent(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); UserEventServiceClient client = new UserEventServiceClientImpl(mockGrpcClient.Object, null); ga::HttpBody response = client.CollectUserEvent(request.ParentAsEventStoreName, request.UserEvent, request.Uri, request.Ets); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task CollectUserEventResourceNamesAsync() { moq::Mock<UserEventService.UserEventServiceClient> mockGrpcClient = new moq::Mock<UserEventService.UserEventServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); CollectUserEventRequest request = new CollectUserEventRequest { ParentAsEventStoreName = EventStoreName.FromProjectLocationCatalogEventStore("[PROJECT]", "[LOCATION]", "[CATALOG]", "[EVENT_STORE]"), UserEvent = "user_eventc8146d99", Uri = "uri3db70593", Ets = -4649673071663131288L, }; ga::HttpBody expectedResponse = new ga::HttpBody { ContentType = "content_type085be0ea", Data = proto::ByteString.CopyFromUtf8("data387f778d"), Extensions = { new wkt::Any(), }, }; mockGrpcClient.Setup(x => x.CollectUserEventAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ga::HttpBody>(stt::Task.FromResult(expectedResponse), null, null, null, null)); UserEventServiceClient client = new UserEventServiceClientImpl(mockGrpcClient.Object, null); ga::HttpBody responseCallSettings = await client.CollectUserEventAsync(request.ParentAsEventStoreName, request.UserEvent, request.Uri, request.Ets, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); ga::HttpBody responseCancellationToken = await client.CollectUserEventAsync(request.ParentAsEventStoreName, request.UserEvent, request.Uri, request.Ets, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections; using System.Collections.Generic; using System.ComponentModel.Design.Serialization; using System.Diagnostics; using System.Globalization; using System.Reflection; namespace System.ComponentModel { /// <summary> /// Provides a type converter to convert <see cref='System.Globalization.CultureInfo'/> /// objects to and from various other representations. /// </summary> public class CultureInfoConverter : TypeConverter { private StandardValuesCollection _values; /// <summary> /// Retrieves the "default" name for our culture. /// </summary> private string DefaultCultureString => SR.CultureInfoConverterDefaultCultureString; const string DefaultInvariantCultureString = "(Default)"; /// <summary> /// Retrieves the Name for a input CultureInfo. /// </summary> protected virtual string GetCultureName(CultureInfo culture) => culture.Name; /// <summary> /// Gets a value indicating whether this converter can convert an object in the given /// source type to a System.Globalization.CultureInfo object using the specified context. /// </summary> public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) { if (sourceType == typeof(string)) { return true; } return sourceType == typeof(string) || base.CanConvertFrom(context, sourceType); } /// <summary> /// Gets a value indicating whether this converter can convert an object to /// the given destination type using the context. /// </summary> public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) { return destinationType == typeof(InstanceDescriptor) || base.CanConvertTo(context, destinationType); } /// <summary> /// Converts the specified value object to a <see cref='System.Globalization.CultureInfo'/> /// object. /// </summary> public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { // Hack, Only when GetCultureName returns culture.Name, we use CultureInfoMapper // (Since CultureInfoMapper will transfer Culture.DisplayName to Culture.Name). // Otherwise, we just keep the value unchange. if (value is string text) { if (GetCultureName(CultureInfo.InvariantCulture).Equals("")) { text = CultureInfoMapper.GetCultureInfoName((string)value); } CultureInfo retVal = null; string defaultCultureString = DefaultCultureString; if (culture != null && culture.Equals(CultureInfo.InvariantCulture)) { defaultCultureString = DefaultInvariantCultureString; } // Look for the default culture info. if (string.IsNullOrEmpty(text) || string.Equals(text, defaultCultureString, StringComparison.Ordinal)) { retVal = CultureInfo.InvariantCulture; } // Now look in our set of installed cultures. if (retVal == null) { foreach (CultureInfo info in GetStandardValues(context)) { if (info != null && string.Equals(GetCultureName(info), text, StringComparison.Ordinal)) { retVal = info; break; } } } // Now try to create a new culture info from this value. if (retVal == null) { try { retVal = new CultureInfo(text); } catch { } } // Finally, try to find a partial match. if (retVal == null) { text = text.ToLower(CultureInfo.CurrentCulture); foreach (CultureInfo info in _values) { if (info != null && GetCultureName(info).ToLower(CultureInfo.CurrentCulture).StartsWith(text)) { retVal = info; break; } } } // No good. We can't support it. if (retVal == null) { throw new ArgumentException(SR.Format(SR.CultureInfoConverterInvalidCulture, (string)value)); } return retVal; } return base.ConvertFrom(context, culture, value); } /// <summary> /// Converts the given value object to the specified destination type. /// </summary> public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { if (destinationType == null) { throw new ArgumentNullException(nameof(destinationType)); } if (destinationType == typeof(string)) { string retVal; string defaultCultureString = DefaultCultureString; if (culture != null && culture.Equals(CultureInfo.InvariantCulture)) { defaultCultureString = DefaultInvariantCultureString; } if (value == null || value == CultureInfo.InvariantCulture) { retVal = defaultCultureString; } else { retVal = GetCultureName(((CultureInfo)value)); } return retVal; } if (destinationType == typeof(InstanceDescriptor) && value is CultureInfo) { CultureInfo c = (CultureInfo)value; ConstructorInfo ctor = typeof(CultureInfo).GetConstructor(new Type[] { typeof(string) }); if (ctor != null) { return new InstanceDescriptor(ctor, new object[] { c.Name }); } } return base.ConvertTo(context, culture, value, destinationType); } /// <summary> /// Gets a collection of standard values collection for a System.Globalization.CultureInfo /// object using the specified context. /// </summary> public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) { if (_values == null) { CultureInfo[] installedCultures = CultureInfo.GetCultures(CultureTypes.SpecificCultures | CultureTypes.NeutralCultures); int invariantIndex = Array.IndexOf(installedCultures, CultureInfo.InvariantCulture); CultureInfo[] array; if (invariantIndex != -1) { Debug.Assert(invariantIndex >= 0 && invariantIndex < installedCultures.Length); installedCultures[invariantIndex] = null; array = new CultureInfo[installedCultures.Length]; } else { array = new CultureInfo[installedCultures.Length + 1]; } Array.Copy(installedCultures, array, installedCultures.Length); Array.Sort(array, new CultureComparer(this)); Debug.Assert(array[0] == null); if (array[0] == null) { //we replace null with the real default culture because there are code paths // where the propgrid will send values from this returned array directly -- instead // of converting it to a string and then back to a value (which this relied on). array[0] = CultureInfo.InvariantCulture; //null isn't the value here -- invariantculture is. } _values = new StandardValuesCollection(array); } return _values; } /// <summary> /// Gets a value indicating whether the list of standard values returned from /// System.ComponentModel.CultureInfoConverter.GetStandardValues is an exclusive list. /// </summary> public override bool GetStandardValuesExclusive(ITypeDescriptorContext context) => false; /// <summary> /// Gets a value indicating whether this object supports a standard set /// of values that can be picked from a list using the specified context. /// </summary> public override bool GetStandardValuesSupported(ITypeDescriptorContext context) => true; /// <summary> /// IComparer object used for sorting CultureInfos /// WARNING: If you change where null is positioned, then you must fix CultureConverter.GetStandardValues! /// </summary> private class CultureComparer : IComparer { private CultureInfoConverter _converter; public CultureComparer(CultureInfoConverter cultureConverter) { Debug.Assert(cultureConverter != null); _converter = cultureConverter; } public int Compare(object item1, object item2) { if (item1 == null) { // If both are null, then they are equal. if (item2 == null) { return 0; } // Otherwise, item1 is null, but item2 is valid (greater). return -1; } if (item2 == null) { // item2 is null, so item 1 is greater. return 1; } string itemName1 = _converter.GetCultureName(((CultureInfo)item1)); string itemName2 = _converter.GetCultureName(((CultureInfo)item2)); CompareInfo compInfo = (CultureInfo.CurrentCulture).CompareInfo; return compInfo.Compare(itemName1, itemName2, CompareOptions.StringSort); } } private static class CultureInfoMapper { /// Dictionary of CultureInfo.DisplayName, CultureInfo.Name for cultures that have changed DisplayName over releases. /// This is to workaround an issue with CultureInfoConverter that serializes DisplayName (fixing it would introduce breaking changes). private static readonly Dictionary<string, string> s_cultureInfoNameMap = CreateMap(); private static Dictionary<string,string> CreateMap() { const int Count = 274; var result = new Dictionary<string, string>(Count) { {"Afrikaans", "af"}, {"Afrikaans (South Africa)", "af-ZA"}, {"Albanian", "sq"}, {"Albanian (Albania)", "sq-AL"}, {"Alsatian (France)", "gsw-FR"}, {"Amharic (Ethiopia)", "am-ET"}, {"Arabic", "ar"}, {"Arabic (Algeria)", "ar-DZ"}, {"Arabic (Bahrain)", "ar-BH"}, {"Arabic (Egypt)", "ar-EG"}, {"Arabic (Iraq)", "ar-IQ"}, {"Arabic (Jordan)", "ar-JO"}, {"Arabic (Kuwait)", "ar-KW"}, {"Arabic (Lebanon)", "ar-LB"}, {"Arabic (Libya)", "ar-LY"}, {"Arabic (Morocco)", "ar-MA"}, {"Arabic (Oman)", "ar-OM"}, {"Arabic (Qatar)", "ar-QA"}, {"Arabic (Saudi Arabia)", "ar-SA"}, {"Arabic (Syria)", "ar-SY"}, {"Arabic (Tunisia)", "ar-TN"}, {"Arabic (U.A.E.)", "ar-AE"}, {"Arabic (Yemen)", "ar-YE"}, {"Armenian", "hy"}, {"Armenian (Armenia)", "hy-AM"}, {"Assamese (India)", "as-IN"}, {"Azeri", "az"}, {"Azeri (Cyrillic, Azerbaijan)", "az-Cyrl-AZ"}, {"Azeri (Latin, Azerbaijan)", "az-Latn-AZ"}, {"Bashkir (Russia)", "ba-RU"}, {"Basque", "eu"}, {"Basque (Basque)", "eu-ES"}, {"Belarusian", "be"}, {"Belarusian (Belarus)", "be-BY"}, {"Bengali (Bangladesh)", "bn-BD"}, {"Bengali (India)", "bn-IN"}, {"Bosnian (Cyrillic, Bosnia and Herzegovina)", "bs-Cyrl-BA"}, {"Bosnian (Latin, Bosnia and Herzegovina)", "bs-Latn-BA"}, {"Breton (France)", "br-FR"}, {"Bulgarian", "bg"}, {"Bulgarian (Bulgaria)", "bg-BG"}, {"Catalan", "ca"}, {"Catalan (Catalan)", "ca-ES"}, {"Chinese (Hong Kong S.A.R.)", "zh-HK"}, {"Chinese (Macao S.A.R.)", "zh-MO"}, {"Chinese (People's Republic of China)", "zh-CN"}, {"Chinese (Simplified)", "zh-CHS"}, {"Chinese (Singapore)", "zh-SG"}, {"Chinese (Taiwan)", "zh-TW"}, {"Chinese (Traditional)", "zh-CHT"}, {"Corsican (France)", "co-FR"}, {"Croatian", "hr"}, {"Croatian (Croatia)", "hr-HR"}, {"Croatian (Latin, Bosnia and Herzegovina)", "hr-BA"}, {"Czech", "cs"}, {"Czech (Czech Republic)", "cs-CZ"}, {"Danish", "da"}, {"Danish (Denmark)", "da-DK"}, {"Dari (Afghanistan)", "prs-AF"}, {"Divehi", "dv"}, {"Divehi (Maldives)", "dv-MV"}, {"Dutch", "nl"}, {"Dutch (Belgium)", "nl-BE"}, {"Dutch (Netherlands)", "nl-NL"}, {"English", "en"}, {"English (Australia)", "en-AU"}, {"English (Belize)", "en-BZ"}, {"English (Canada)", "en-CA"}, {"English (Caribbean)", "en-029"}, {"English (India)", "en-IN"}, {"English (Ireland)", "en-IE"}, {"English (Jamaica)", "en-JM"}, {"English (Malaysia)", "en-MY"}, {"English (New Zealand)", "en-NZ"}, {"English (Republic of the Philippines)", "en-PH"}, {"English (Singapore)", "en-SG"}, {"English (South Africa)", "en-ZA"}, {"English (Trinidad and Tobago)", "en-TT"}, {"English (United Kingdom)", "en-GB"}, {"English (United States)", "en-US"}, {"English (Zimbabwe)", "en-ZW"}, {"Estonian", "et"}, {"Estonian (Estonia)", "et-EE"}, {"Faroese", "fo"}, {"Faroese (Faroe Islands)", "fo-FO"}, {"Filipino (Philippines)", "fil-PH"}, {"Finnish", "fi"}, {"Finnish (Finland)", "fi-FI"}, {"French", "fr"}, {"French (Belgium)", "fr-BE"}, {"French (Canada)", "fr-CA"}, {"French (France)", "fr-FR"}, {"French (Luxembourg)", "fr-LU"}, {"French (Principality of Monaco)", "fr-MC"}, {"French (Switzerland)", "fr-CH"}, {"Frisian (Netherlands)", "fy-NL"}, {"Galician", "gl"}, {"Galician (Galician)", "gl-ES"}, {"Georgian", "ka"}, {"Georgian (Georgia)", "ka-GE"}, {"German", "de"}, {"German (Austria)", "de-AT"}, {"German (Germany)", "de-DE"}, {"German (Liechtenstein)", "de-LI"}, {"German (Luxembourg)", "de-LU"}, {"German (Switzerland)", "de-CH"}, {"Greek", "el"}, {"Greek (Greece)", "el-GR"}, {"Greenlandic (Greenland)", "kl-GL"}, {"Gujarati", "gu"}, {"Gujarati (India)", "gu-IN"}, {"Hausa (Latin, Nigeria)", "ha-Latn-NG"}, {"Hebrew", "he"}, {"Hebrew (Israel)", "he-IL"}, {"Hindi", "hi"}, {"Hindi (India)", "hi-IN"}, {"Hungarian", "hu"}, {"Hungarian (Hungary)", "hu-HU"}, {"Icelandic", "is"}, {"Icelandic (Iceland)", "is-IS"}, {"Igbo (Nigeria)", "ig-NG"}, {"Indonesian", "id"}, {"Indonesian (Indonesia)", "id-ID"}, {"Inuktitut (Latin, Canada)", "iu-Latn-CA"}, {"Inuktitut (Syllabics, Canada)", "iu-Cans-CA"}, {"Invariant Language (Invariant Country)", ""}, {"Irish (Ireland)", "ga-IE"}, {"isiXhosa (South Africa)", "xh-ZA"}, {"isiZulu (South Africa)", "zu-ZA"}, {"Italian", "it"}, {"Italian (Italy)", "it-IT"}, {"Italian (Switzerland)", "it-CH"}, {"Japanese", "ja"}, {"Japanese (Japan)", "ja-JP"}, {"K'iche (Guatemala)", "qut-GT"}, {"Kannada", "kn"}, {"Kannada (India)", "kn-IN"}, {"Kazakh", "kk"}, {"Kazakh (Kazakhstan)", "kk-KZ"}, {"Khmer (Cambodia)", "km-KH"}, {"Kinyarwanda (Rwanda)", "rw-RW"}, {"Kiswahili", "sw"}, {"Kiswahili (Kenya)", "sw-KE"}, {"Konkani", "kok"}, {"Konkani (India)", "kok-IN"}, {"Korean", "ko"}, {"Korean (Korea)", "ko-KR"}, {"Kyrgyz", "ky"}, {"Kyrgyz (Kyrgyzstan)", "ky-KG"}, {"Lao (Lao P.D.R.)", "lo-LA"}, {"Latvian", "lv"}, {"Latvian (Latvia)", "lv-LV"}, {"Lithuanian", "lt"}, {"Lithuanian (Lithuania)", "lt-LT"}, {"Lower Sorbian (Germany)", "dsb-DE"}, {"Luxembourgish (Luxembourg)", "lb-LU"}, {"Macedonian", "mk"}, {"Macedonian (Former Yugoslav Republic of Macedonia)", "mk-MK"}, {"Malay", "ms"}, {"Malay (Brunei Darussalam)", "ms-BN"}, {"Malay (Malaysia)", "ms-MY"}, {"Malayalam (India)", "ml-IN"}, {"Maltese (Malta)", "mt-MT"}, {"Maori (New Zealand)", "mi-NZ"}, {"Mapudungun (Chile)", "arn-CL"}, {"Marathi", "mr"}, {"Marathi (India)", "mr-IN"}, {"Mohawk (Mohawk)", "moh-CA"}, {"Mongolian", "mn"}, {"Mongolian (Cyrillic, Mongolia)", "mn-MN"}, {"Mongolian (Traditional Mongolian, PRC)", "mn-Mong-CN"}, {"Nepali (Nepal)", "ne-NP"}, {"Norwegian", "no"}, {"Norwegian, Bokm\u00E5l (Norway)", "nb-NO"}, {"Norwegian, Nynorsk (Norway)", "nn-NO"}, {"Occitan (France)", "oc-FR"}, {"Oriya (India)", "or-IN"}, {"Pashto (Afghanistan)", "ps-AF"}, {"Persian", "fa"}, {"Persian (Iran)", "fa-IR"}, {"Polish", "pl"}, {"Polish (Poland)", "pl-PL"}, {"Portuguese", "pt"}, {"Portuguese (Brazil)", "pt-BR"}, {"Portuguese (Portugal)", "pt-PT"}, {"Punjabi", "pa"}, {"Punjabi (India)", "pa-IN"}, {"Quechua (Bolivia)", "quz-BO"}, {"Quechua (Ecuador)", "quz-EC"}, {"Quechua (Peru)", "quz-PE"}, {"Romanian", "ro"}, {"Romanian (Romania)", "ro-RO"}, {"Romansh (Switzerland)", "rm-CH"}, {"Russian", "ru"}, {"Russian (Russia)", "ru-RU"}, {"Sami, Inari (Finland)", "smn-FI"}, {"Sami, Lule (Norway)", "smj-NO"}, {"Sami, Lule (Sweden)", "smj-SE"}, {"Sami, Northern (Finland)", "se-FI"}, {"Sami, Northern (Norway)", "se-NO"}, {"Sami, Northern (Sweden)", "se-SE"}, {"Sami, Skolt (Finland)", "sms-FI"}, {"Sami, Southern (Norway)", "sma-NO"}, {"Sami, Southern (Sweden)", "sma-SE"}, {"Sanskrit", "sa"}, {"Sanskrit (India)", "sa-IN"}, {"Serbian", "sr"}, {"Serbian (Cyrillic, Bosnia and Herzegovina)", "sr-Cyrl-BA"}, {"Serbian (Cyrillic, Serbia)", "sr-Cyrl-CS"}, {"Serbian (Latin, Bosnia and Herzegovina)", "sr-Latn-BA"}, {"Serbian (Latin, Serbia)", "sr-Latn-CS"}, {"Sesotho sa Leboa (South Africa)", "nso-ZA"}, {"Setswana (South Africa)", "tn-ZA"}, {"Sinhala (Sri Lanka)", "si-LK"}, {"Slovak", "sk"}, {"Slovak (Slovakia)", "sk-SK"}, {"Slovenian", "sl"}, {"Slovenian (Slovenia)", "sl-SI"}, {"Spanish", "es"}, {"Spanish (Argentina)", "es-AR"}, {"Spanish (Bolivia)", "es-BO"}, {"Spanish (Chile)", "es-CL"}, {"Spanish (Colombia)", "es-CO"}, {"Spanish (Costa Rica)", "es-CR"}, {"Spanish (Dominican Republic)", "es-DO"}, {"Spanish (Ecuador)", "es-EC"}, {"Spanish (El Salvador)", "es-SV"}, {"Spanish (Guatemala)", "es-GT"}, {"Spanish (Honduras)", "es-HN"}, {"Spanish (Mexico)", "es-MX"}, {"Spanish (Nicaragua)", "es-NI"}, {"Spanish (Panama)", "es-PA"}, {"Spanish (Paraguay)", "es-PY"}, {"Spanish (Peru)", "es-PE"}, {"Spanish (Puerto Rico)", "es-PR"}, {"Spanish (Spain)", "es-ES"}, {"Spanish (United States)", "es-US"}, {"Spanish (Uruguay)", "es-UY"}, {"Spanish (Venezuela)", "es-VE"}, {"Swedish", "sv"}, {"Swedish (Finland)", "sv-FI"}, {"Swedish (Sweden)", "sv-SE"}, {"Syriac", "syr"}, {"Syriac (Syria)", "syr-SY"}, {"Tajik (Cyrillic, Tajikistan)", "tg-Cyrl-TJ"}, {"Tamazight (Latin, Algeria)", "tzm-Latn-DZ"}, {"Tamil", "ta"}, {"Tamil (India)", "ta-IN"}, {"Tatar", "tt"}, {"Tatar (Russia)", "tt-RU"}, {"Telugu", "te"}, {"Telugu (India)", "te-IN"}, {"Thai", "th"}, {"Thai (Thailand)", "th-TH"}, {"Tibetan (PRC)", "bo-CN"}, {"Turkish", "tr"}, {"Turkish (Turkey)", "tr-TR"}, {"Turkmen (Turkmenistan)", "tk-TM"}, {"Uighur (PRC)", "ug-CN"}, {"Ukrainian", "uk"}, {"Ukrainian (Ukraine)", "uk-UA"}, {"Upper Sorbian (Germany)", "hsb-DE"}, {"Urdu", "ur"}, {"Urdu (Islamic Republic of Pakistan)", "ur-PK"}, {"Uzbek", "uz"}, {"Uzbek (Cyrillic, Uzbekistan)", "uz-Cyrl-UZ"}, {"Uzbek (Latin, Uzbekistan)", "uz-Latn-UZ"}, {"Vietnamese", "vi"}, {"Vietnamese (Vietnam)", "vi-VN"}, {"Welsh (United Kingdom)", "cy-GB"}, {"Wolof (Senegal)", "wo-SN"}, {"Yakut (Russia)", "sah-RU"}, {"Yi (PRC)", "ii-CN"}, {"Yoruba (Nigeria)", "yo-NG"} }; Debug.Assert(result.Count == Count); return result; } public static string GetCultureInfoName(string cultureInfoDisplayName) { return s_cultureInfoNameMap.TryGetValue(cultureInfoDisplayName, out string name) ? name : cultureInfoDisplayName; } } } }
// 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 Xunit; namespace System.Net.NetworkInformation.Tests { public class StatisticsParsingTests : FileCleanupTestBase { [Fact] public void Icmpv4Parsing() { string fileName = GetTestFilePath(); FileUtil.NormalizeLineEndings("NetworkFiles/snmp", fileName); Icmpv4StatisticsTable table = StringParsingHelpers.ParseIcmpv4FromSnmpFile(fileName); Assert.Equal(1L, table.InMsgs); Assert.Equal(2L, table.InErrors); Assert.Equal(3L, table.InCsumErrors); Assert.Equal(4L, table.InDestUnreachs); Assert.Equal(5L, table.InTimeExcds); Assert.Equal(6L, table.InParmProbs); Assert.Equal(7L, table.InSrcQuenchs); Assert.Equal(8L, table.InRedirects); Assert.Equal(9L, table.InEchos); Assert.Equal(10L, table.InEchoReps); Assert.Equal(20L, table.InTimestamps); Assert.Equal(30L, table.InTimeStampReps); Assert.Equal(40L, table.InAddrMasks); Assert.Equal(50L, table.InAddrMaskReps); Assert.Equal(60L, table.OutMsgs); Assert.Equal(70L, table.OutErrors); Assert.Equal(80L, table.OutDestUnreachs); Assert.Equal(90L, table.OutTimeExcds); Assert.Equal(100L, table.OutParmProbs); Assert.Equal(255L, table.OutSrcQuenchs); Assert.Equal(1024L, table.OutRedirects); Assert.Equal(256L, table.OutEchos); Assert.Equal(9001L, table.OutEchoReps); Assert.Equal(42L, table.OutTimestamps); Assert.Equal(4100414L, table.OutTimestampReps); Assert.Equal(2147483647L, table.OutAddrMasks); Assert.Equal(0L, table.OutAddrMaskReps); } [Fact] public void Icmpv6Parsing() { string fileName = GetTestFilePath(); FileUtil.NormalizeLineEndings("NetworkFiles/snmp6", fileName); Icmpv6StatisticsTable table = StringParsingHelpers.ParseIcmpv6FromSnmp6File(fileName); Assert.Equal(1L, table.InMsgs); Assert.Equal(2L, table.InErrors); Assert.Equal(3L, table.OutMsgs); Assert.Equal(4L, table.OutErrors); Assert.Equal(6L, table.InDestUnreachs); Assert.Equal(7L, table.InPktTooBigs); Assert.Equal(8L, table.InTimeExcds); Assert.Equal(9L, table.InParmProblems); Assert.Equal(10L, table.InEchos); Assert.Equal(11L, table.InEchoReplies); Assert.Equal(12L, table.InGroupMembQueries); Assert.Equal(13L, table.InGroupMembResponses); Assert.Equal(14L, table.InGroupMembReductions); Assert.Equal(15L, table.InRouterSolicits); Assert.Equal(16L, table.InRouterAdvertisements); Assert.Equal(17L, table.InNeighborSolicits); Assert.Equal(18L, table.InNeighborAdvertisements); Assert.Equal(19L, table.InRedirects); Assert.Equal(21L, table.OutDestUnreachs); Assert.Equal(22L, table.OutPktTooBigs); Assert.Equal(23L, table.OutTimeExcds); Assert.Equal(24L, table.OutParmProblems); Assert.Equal(25L, table.OutEchos); Assert.Equal(26L, table.OutEchoReplies); Assert.Equal(27L, table.OutInGroupMembQueries); Assert.Equal(28L, table.OutGroupMembResponses); Assert.Equal(29L, table.OutGroupMembReductions); Assert.Equal(30L, table.OutRouterSolicits); Assert.Equal(31L, table.OutRouterAdvertisements); Assert.Equal(32L, table.OutNeighborSolicits); Assert.Equal(33L, table.OutNeighborAdvertisements); Assert.Equal(34L, table.OutRedirects); } [Fact] public void TcpGlobalStatisticsParsing() { string fileName = GetTestFilePath(); FileUtil.NormalizeLineEndings("NetworkFiles/snmp", fileName); TcpGlobalStatisticsTable table = StringParsingHelpers.ParseTcpGlobalStatisticsFromSnmpFile(fileName); Assert.Equal(1L, table.RtoAlgorithm); Assert.Equal(200L, table.RtoMin); Assert.Equal(120000L, table.RtoMax); Assert.Equal(-1L, table.MaxConn); Assert.Equal(359L, table.ActiveOpens); Assert.Equal(28L, table.PassiveOpens); Assert.Equal(2L, table.AttemptFails); Assert.Equal(53L, table.EstabResets); Assert.Equal(4L, table.CurrEstab); Assert.Equal(2592159585L, table.InSegs); Assert.Equal(2576867425L, table.OutSegs); Assert.Equal(19L, table.RetransSegs); Assert.Equal(0L, table.InErrs); Assert.Equal(111L, table.OutRsts); Assert.Equal(0L, table.InCsumErrors); } [Fact] public void Udpv4GlobalStatisticsParsing() { string fileName = GetTestFilePath(); FileUtil.NormalizeLineEndings("NetworkFiles/snmp", fileName); UdpGlobalStatisticsTable table = StringParsingHelpers.ParseUdpv4GlobalStatisticsFromSnmpFile(fileName); Assert.Equal(7181L, table.InDatagrams); Assert.Equal(150L, table.NoPorts); Assert.Equal(0L, table.InErrors); Assert.Equal(4386L, table.OutDatagrams); Assert.Equal(0L, table.RcvbufErrors); Assert.Equal(0L, table.SndbufErrors); Assert.Equal(1L, table.InCsumErrors); } [Fact] public void Udpv6GlobalStatisticsParsing() { string fileName = GetTestFilePath(); FileUtil.NormalizeLineEndings("NetworkFiles/snmp6", fileName); UdpGlobalStatisticsTable table = StringParsingHelpers.ParseUdpv6GlobalStatisticsFromSnmp6File(fileName); Assert.Equal(19L, table.InDatagrams); Assert.Equal(0L, table.NoPorts); Assert.Equal(0L, table.InErrors); Assert.Equal(21L, table.OutDatagrams); Assert.Equal(99999L, table.RcvbufErrors); Assert.Equal(11011011L, table.SndbufErrors); Assert.Equal(0L, table.InCsumErrors); } [Fact] public void Ipv4GlobalStatisticsParsing() { string fileName = GetTestFilePath(); FileUtil.NormalizeLineEndings("NetworkFiles/snmp", fileName); IPGlobalStatisticsTable table = StringParsingHelpers.ParseIPv4GlobalStatisticsFromSnmpFile(fileName); Assert.Equal(false, table.Forwarding); Assert.Equal(64L, table.DefaultTtl); Assert.Equal(28121L, table.InReceives); Assert.Equal(0L, table.InHeaderErrors); Assert.Equal(2L, table.InAddressErrors); Assert.Equal(0L, table.ForwardedDatagrams); Assert.Equal(0L, table.InUnknownProtocols); Assert.Equal(0L, table.InDiscards); Assert.Equal(28117L, table.InDelivers); Assert.Equal(24616L, table.OutRequests); Assert.Equal(48L, table.OutDiscards); Assert.Equal(0L, table.OutNoRoutes); Assert.Equal(0L, table.ReassemblyTimeout); Assert.Equal(0L, table.ReassemblyRequireds); Assert.Equal(1L, table.ReassemblyOKs); Assert.Equal(2L, table.ReassemblyFails); Assert.Equal(14L, table.FragmentOKs); Assert.Equal(0L, table.FragmentFails); Assert.Equal(92L, table.FragmentCreates); } [Fact] public void Ipv6GlobalStatisticsParsing() { string fileName = GetTestFilePath(); FileUtil.NormalizeLineEndings("NetworkFiles/snmp6", fileName); IPGlobalStatisticsTable table = StringParsingHelpers.ParseIPv6GlobalStatisticsFromSnmp6File(fileName); Assert.Equal(189L, table.InReceives); Assert.Equal(0L, table.InHeaderErrors); Assert.Equal(2000L, table.InAddressErrors); Assert.Equal(42L, table.InUnknownProtocols); Assert.Equal(0L, table.InDiscards); Assert.Equal(189L, table.InDelivers); Assert.Equal(55L, table.ForwardedDatagrams); Assert.Equal(199L, table.OutRequests); Assert.Equal(0L, table.OutDiscards); Assert.Equal(53L, table.OutNoRoutes); Assert.Equal(2121L, table.ReassemblyTimeout); Assert.Equal(1L, table.ReassemblyRequireds); Assert.Equal(2L, table.ReassemblyOKs); Assert.Equal(4L, table.ReassemblyFails); Assert.Equal(8L, table.FragmentOKs); Assert.Equal(16L, table.FragmentFails); Assert.Equal(32L, table.FragmentCreates); } [Fact] public void IpInterfaceStatisticsParsingFirst() { string fileName = GetTestFilePath(); FileUtil.NormalizeLineEndings("NetworkFiles/dev", fileName); IPInterfaceStatisticsTable table = StringParsingHelpers.ParseInterfaceStatisticsTableFromFile(fileName, "wlan0"); Assert.Equal(26622L, table.BytesReceived); Assert.Equal(394L, table.PacketsReceived); Assert.Equal(2L, table.ErrorsReceived); Assert.Equal(4L, table.IncomingPacketsDropped); Assert.Equal(6L, table.FifoBufferErrorsReceived); Assert.Equal(8L, table.PacketFramingErrorsReceived); Assert.Equal(10L, table.CompressedPacketsReceived); Assert.Equal(12L, table.MulticastFramesReceived); Assert.Equal(429496730000L, table.BytesTransmitted); Assert.Equal(208L, table.PacketsTransmitted); Assert.Equal(1L, table.ErrorsTransmitted); Assert.Equal(2L, table.OutgoingPacketsDropped); Assert.Equal(3L, table.FifoBufferErrorsTransmitted); Assert.Equal(4L, table.CollisionsDetected); Assert.Equal(5L, table.CarrierLosses); Assert.Equal(6L, table.CompressedPacketsTransmitted); } [Fact] public void IpInterfaceStatisticsParsingLast() { string fileName = GetTestFilePath(); FileUtil.NormalizeLineEndings("NetworkFiles/dev", fileName); IPInterfaceStatisticsTable table = StringParsingHelpers.ParseInterfaceStatisticsTableFromFile(fileName, "lo"); Assert.Equal(long.MaxValue, table.BytesReceived); Assert.Equal(302L, table.PacketsReceived); Assert.Equal(0L, table.ErrorsReceived); Assert.Equal(0L, table.IncomingPacketsDropped); Assert.Equal(0L, table.FifoBufferErrorsReceived); Assert.Equal(0L, table.PacketFramingErrorsReceived); Assert.Equal(0L, table.CompressedPacketsReceived); Assert.Equal(0L, table.MulticastFramesReceived); Assert.Equal(30008L, table.BytesTransmitted); Assert.Equal(302L, table.PacketsTransmitted); Assert.Equal(0L, table.ErrorsTransmitted); Assert.Equal(0L, table.OutgoingPacketsDropped); Assert.Equal(0L, table.FifoBufferErrorsTransmitted); Assert.Equal(0L, table.CollisionsDetected); Assert.Equal(0L, table.CarrierLosses); Assert.Equal(0L, table.CompressedPacketsTransmitted); } } }
using System; using System.IO; namespace SharpRemote.CodeGeneration.Serialization.Binary { internal sealed class BinaryMethodCallReader : IMethodCallReader { private readonly Stream _stream; private readonly BinarySerializer2 _serializer; private readonly BinaryReader _reader; private readonly ulong _grainId; private readonly string _methodName; private readonly ulong _rpcId; public BinaryMethodCallReader(BinarySerializer2 serializer, BinaryReader reader) { if (reader == null) throw new ArgumentNullException(nameof(reader)); _serializer = serializer; _reader = reader; _stream = reader.BaseStream; _grainId = _reader.ReadUInt64(); _methodName = _reader.ReadString(); _rpcId = _reader.ReadUInt64(); } private bool EndOfStream => _stream.Position >= _stream.Length; public void Dispose() { _reader.Dispose(); } public ulong GrainId => _grainId; public string MethodName => _methodName; public ulong RpcId => _rpcId; public bool ReadNextArgument(out object value) { if (EndOfStream) { value = null; return false; } value = _serializer.ReadObject(_reader); return true; } public bool ReadNextArgumentAsStruct<T>(out T value) where T : struct { throw new NotImplementedException(); } public bool ReadNextArgumentAsSByte(out sbyte value) { if (EndOfStream) { value = sbyte.MinValue; return false; } value = BinarySerializer2.ReadValueAsSByte(_reader); return true; } public bool ReadNextArgumentAsByte(out byte value) { if (EndOfStream) { value = byte.MinValue; return false; } value = BinarySerializer2.ReadValueAsByte(_reader); return true; } public bool ReadNextArgumentAsUInt16(out ushort value) { if (EndOfStream) { value = ushort.MinValue; return false; } value = BinarySerializer2.ReadValueAsUInt16(_reader); return true; } public bool ReadNextArgumentAsInt16(out short value) { if (EndOfStream) { value = short.MinValue; return false; } value = BinarySerializer2.ReadValueAsInt16(_reader); return true; } public bool ReadNextArgumentAsUInt32(out uint value) { if (EndOfStream) { value = uint.MinValue; return false; } value = BinarySerializer2.ReadValueAsUInt32(_reader); return true; } public bool ReadNextArgumentAsInt32(out int value) { if (EndOfStream) { value = int.MinValue; return false; } value = BinarySerializer2.ReadValueAsInt32(_reader); return true; } public bool ReadNextArgumentAsUInt64(out ulong value) { if (EndOfStream) { value = ulong.MinValue; return false; } value = BinarySerializer2.ReadValueAsUInt64(_reader); return true; } public bool ReadNextArgumentAsInt64(out long value) { if (EndOfStream) { value = long.MinValue; return false; } value = BinarySerializer2.ReadValueAsInt64(_reader); return true; } public bool ReadNextArgumentAsSingle(out float value) { if (EndOfStream) { value = float.MinValue; return false; } value = BinarySerializer2.ReadValueAsSingle(_reader); return true; } public bool ReadNextArgumentAsDouble(out double value) { if (EndOfStream) { value = double.MinValue; return false; } value = BinarySerializer2.ReadValueAsDouble(_reader); return true; } public bool ReadNextArgumentAsDecimal(out decimal value) { if (EndOfStream) { value = decimal.MinValue; return false; } value = BinarySerializer2.ReadValueAsDecimal(_reader); return true; } public bool ReadNextArgumentAsDateTime(out DateTime value) { if (EndOfStream) { value = DateTime.MinValue; return false; } value = DateTime.FromBinary(_reader.ReadInt64()); return true; } public bool ReadNextArgumentAsString(out string value) { if (EndOfStream) { value = null; return false; } value = BinarySerializer2.ReadValueAsString(_reader); return true; } public bool ReadNextArgumentAsBytes(out byte[] value) { if (EndOfStream) { value = null; return false; } if (_reader.ReadBoolean()) { int length = _reader.ReadInt32(); value = _reader.ReadBytes(length); } else { value = null; } return true; } } }
using AutoBogus.Util; using FluentAssertions; using FluentAssertions.Execution; using FluentAssertions.Primitives; using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Reflection; namespace AutoBogus.Tests.Models { public sealed class GenerateAssertions : ReferenceTypeAssertions<object, GenerateAssertions> { private MethodInfo DefaultValueFactory; private IDictionary<Func<Type, bool>, Func<string, Type, object, string>> Assertions = new Dictionary<Func<Type, bool>, Func<string, Type, object, string>>(); internal GenerateAssertions(object subject) { var type = GetType(); Subject = subject; DefaultValueFactory = type.GetMethod("GetDefaultValue", BindingFlags.Instance | BindingFlags.NonPublic); // Add the assertions to type mappings Assertions.Add(IsBool, AssertBool); Assertions.Add(IsByte, AssertByte); Assertions.Add(IsChar, AssertChar); Assertions.Add(IsDateTime, AssertDateTime); Assertions.Add(IsDateTimeOffset, AssertDateTimeOffset); Assertions.Add(IsDecimal, AssertDecimal); Assertions.Add(IsDouble, AssertDouble); Assertions.Add(IsFloat, AssertFloat); Assertions.Add(IsGuid, AssertGuid); Assertions.Add(IsInt, AssertInt); Assertions.Add(IsIPAddress, AssertIPAddress); Assertions.Add(IsLong, AssertLong); Assertions.Add(IsSByte, AssertSByte); Assertions.Add(IsShort, AssertShort); Assertions.Add(IsString, AssertString); Assertions.Add(IsUInt, AssertUInt); Assertions.Add(IsULong, AssertULong); Assertions.Add(IsUri, AssertUri); Assertions.Add(IsUShort, AssertUShort); Assertions.Add(IsArray, AssertArray); Assertions.Add(IsEnum, AssertEnum); Assertions.Add(IsDictionary, AssertDictionary); Assertions.Add(IsEnumerable, AssertEnumerable); Assertions.Add(IsNullable, AssertNullable); } private IAssertionScope Scope { get; set; } protected override string Identifier => "Generate"; public AndConstraint<object> BeGenerated() { var type = Subject.GetType(); var assertion = GetAssertion(type); Scope = Execute.Assertion; // Assert the value and output any fail messages var message = assertion.Invoke(null, type, Subject); Scope = Scope .ForCondition(message == null) .FailWith(message) .Then; return new AndConstraint<object>(Subject); } public AndConstraint<object> BeGeneratedWithMocks() { // Ensure the mocked objects are asserted as not null Assertions.Add(IsInterface, AssertMock); Assertions.Add(IsAbstract, AssertMock); return AssertSubject(); } public AndConstraint<object> BeGeneratedWithoutMocks() { // Ensure the mocked objects are asserted as null Assertions.Add(IsInterface, AssertNull); Assertions.Add(IsAbstract, AssertNull); return AssertSubject(); } public AndConstraint<object> NotBeGenerated() { var type = Subject.GetType(); var memberInfos = GetMemberInfos(type); Scope = Execute.Assertion; foreach (var memberInfo in memberInfos) { AssertDefaultValue(memberInfo); } return new AndConstraint<object>(Subject); } private AndConstraint<object> AssertSubject() { var type = Subject.GetType(); var assertion = GetAssertion(type); Scope = Execute.Assertion; assertion.Invoke(type.Name, type, Subject); return new AndConstraint<object>(Subject); } private string AssertType(string path, Type type, object instance) { // Iterate the members for the instance and assert their values var members = GetMemberInfos(type); foreach (var member in members) { AssertMember(path, member, instance); } return null; } private void AssertDefaultValue(MemberInfo memberInfo) { ExtractMemberInfo(memberInfo, out Type memberType, out Func<object, object> memberGetter); // Resolve the default value for the current member type and check it matches var factory = DefaultValueFactory.MakeGenericMethod(memberType); var defaultValue = factory.Invoke(this, new object[0]); var value = memberGetter.Invoke(Subject); var equal = value == null && defaultValue == null; if (!equal) { // Ensure Equals() is called on a non-null instance if (value != null) { equal = value.Equals(defaultValue); } else { equal = defaultValue.Equals(value); } } Scope = Scope .ForCondition(equal) .FailWith($"Expected a default '{memberType.FullName}' value for '{memberInfo.Name}'.") .Then; } private static bool IsBool(Type type) => type == typeof(bool); private static bool IsByte(Type type) => type == typeof(byte); private static bool IsChar(Type type) => type == typeof(char); private static bool IsDateTime(Type type) => type == typeof(DateTime); private static bool IsDateTimeOffset(Type type) => type == typeof(DateTimeOffset); private static bool IsDecimal(Type type) => type == typeof(decimal); private static bool IsDouble(Type type) => type == typeof(double); private static bool IsFloat(Type type) => type == typeof(float); private static bool IsGuid(Type type) => type == typeof(Guid); private static bool IsInt(Type type) => type == typeof(int); private static bool IsIPAddress(Type type) => type == typeof(IPAddress); private static bool IsLong(Type type) => type == typeof(long); private static bool IsSByte(Type type) => type == typeof(sbyte); private static bool IsShort(Type type) => type == typeof(short); private static bool IsString(Type type) => type == typeof(string); private static bool IsUInt(Type type) => type == typeof(uint); private static bool IsULong(Type type) => type == typeof(ulong); private static bool IsUri(Type type) => type == typeof(Uri); private static bool IsUShort(Type type) => type == typeof(ushort); private static bool IsArray(Type type) => type.IsArray; private static bool IsEnum(Type type) => ReflectionHelper.IsEnum(type); private static bool IsDictionary(Type type) => IsType(type, typeof(IDictionary<,>)); private static bool IsEnumerable(Type type) => IsType(type, typeof(IEnumerable<>)); private static bool IsNullable(Type type) => ReflectionHelper.IsGenericType(type) && type.GetGenericTypeDefinition() == typeof(Nullable<>); private static bool IsAbstract(Type type) => ReflectionHelper.IsAbstract(type); private static bool IsInterface(Type type) => ReflectionHelper.IsInterface(type); private static string AssertBool(string path, Type type, object value) => value != null && bool.TryParse(value.ToString(), out bool result) ? null : GetAssertionMessage(path, type, value); private static string AssertByte(string path, Type type, object value) => value != null && byte.TryParse(value.ToString(), out byte result) ? null : GetAssertionMessage(path, type, value); private static string AssertChar(string path, Type type, object value) => value != null && char.TryParse(value.ToString(), out char result) && result != default(char) ? null : GetAssertionMessage(path, type, value); private static string AssertDateTime(string path, Type type, object value) => value != null && DateTime.TryParse(value.ToString(), out DateTime result) && result != default ? null : GetAssertionMessage(path, type, value); private static string AssertDateTimeOffset(string path, Type type, object value) => value != null && DateTimeOffset.TryParse(value.ToString(), out DateTimeOffset result) && result != default ? null : GetAssertionMessage(path, type, value); private static string AssertDecimal(string path, Type type, object value) => value != null && decimal.TryParse(value.ToString(), out decimal result) && result != default ? null : GetAssertionMessage(path, type, value); private static string AssertDouble(string path, Type type, object value) => value != null && double.TryParse(value.ToString(), out double result) && result != default ? null : GetAssertionMessage(path, type, value); private static string AssertFloat(string path, Type type, object value) => value != null && float.TryParse(value.ToString(), out float result) && result != default ? null : GetAssertionMessage(path, type, value); private static string AssertGuid(string path, Type type, object value) => value != null && Guid.TryParse(value.ToString(), out Guid result) && result != default ? null : GetAssertionMessage(path, type, value); private static string AssertInt(string path, Type type, object value) => value != null && int.TryParse(value.ToString(), out int result) && result != default ? null : GetAssertionMessage(path, type, value); private static string AssertIPAddress(string path, Type type, object value) => value != null && IPAddress.TryParse(value.ToString(), out IPAddress result) && result != default(IPAddress) ? null : GetAssertionMessage(path, type, value); private static string AssertLong(string path, Type type, object value) => value != null && long.TryParse(value.ToString(), out long result) && result != default ? null : GetAssertionMessage(path, type, value); private static string AssertSByte(string path, Type type, object value) => value != null && sbyte.TryParse(value.ToString(), out sbyte result) ? null : GetAssertionMessage(path, type, value); private static string AssertShort(string path, Type type, object value) => value != null && short.TryParse(value.ToString(), out short result) && result != default(short) ? null : GetAssertionMessage(path, type, value); private static string AssertUInt(string path, Type type, object value) => value != null && uint.TryParse(value.ToString(), out uint result) && result != default ? null : GetAssertionMessage(path, type, value); private static string AssertULong(string path, Type type, object value) => value != null && ulong.TryParse(value.ToString(), out ulong result) && result != default ? null : GetAssertionMessage(path, type, value); private static string AssertUri(string path, Type type, object value) => value != null && Uri.IsWellFormedUriString(value.ToString(), UriKind.RelativeOrAbsolute) ? null : GetAssertionMessage(path, type, value); private static string AssertUShort(string path, Type type, object value) => value != null && ushort.TryParse(value.ToString(), out ushort result) && result != default(ushort) ? null : GetAssertionMessage(path, type, value); private static string AssertEnum(string path, Type type, object value) => value != null && Enum.IsDefined(type, value) ? null : GetAssertionMessage(path, type, value); private static string AssertNull(string path, Type type, object value) => value == null ? null : $"Expected value to be null for '{path}'."; private static string AssertString(string path, Type type, object value) { var str = value?.ToString(); return string.IsNullOrWhiteSpace(str) ? GetAssertionMessage(path, type, value) : null ; } private string AssertNullable(string path, Type type, object value) { var genericType = type.GenericTypeArguments.Single(); var assertion = GetAssertion(genericType); return assertion.Invoke(path, genericType, value); } private string AssertMock(string path, Type type, object value) { if (value == null) { return $"Excepted value to not be null for '{path}'."; } // Assert via assignment rather than explicit checks (the actual instance could be a sub class) var valueType = value.GetType(); return type.IsAssignableFrom(valueType) ? null : GetAssertionMessage(path, type, value); } private string AssertArray(string path, Type type, object value) { var itemType = type.GetElementType(); return AssertItems(path, itemType, value as Array); } private string AssertDictionary(string path, Type type, object value) { var genericTypes = type.GetGenericArguments(); var keyType = genericTypes.ElementAt(0); var valueType = genericTypes.ElementAt(1); var dictionary = value as IDictionary; if (dictionary == null) { return $"Excepted value to not be null for '{path}'."; } // Check the keys and values individually var keysMessage = AssertItems(path, keyType, dictionary.Keys, "keys", ".Key"); if (keysMessage == null) { return AssertItems(path, valueType, dictionary.Values, "values", ".Value"); } return keysMessage; } private string AssertEnumerable(string path, Type type, object value) { var genericTypes = type.GetGenericArguments(); var itemType = genericTypes.Single(); return AssertItems(path, itemType, value as IEnumerable); } private string AssertItems(string path, Type type, IEnumerable items, string elementType = null, string suffix = null) { // Check the list of items is not null if (items == null) { return $"Excepted value to not be null for '{path}'."; } // Check the count state of the items var count = 0; var enumerator = items.GetEnumerator(); while (enumerator.MoveNext()) { count++; } if (count > 0) { // If we have any items, check each of them var index = 0; var assertion = GetAssertion(type); foreach (var item in items) { var element = string.Format("{0}[{1}]{2}", path, index++, suffix); var message = assertion.Invoke(element, type, item); if (message != null) { return message; } } } else { // Otherwise ensure we are not dealing with interface or abstract class // These types will result in an empty list by default because they cannot be generated if (!ReflectionHelper.IsInterface(type) && !ReflectionHelper.IsAbstract(type)) { elementType = elementType ?? "value"; return $"Excepted {elementType} to not be empty for '{path}'."; } } return null; } private void AssertMember(string path, MemberInfo memberInfo, object instance) { ExtractMemberInfo(memberInfo, out Type memberType, out Func<object, object> memberGetter); // Create a trace path for the current member path = string.Concat(path, ".", memberInfo.Name); // Resolve the assertion and value for the member type var value = memberGetter.Invoke(instance); var assertion = GetAssertion(memberType); var message = assertion.Invoke(path, memberType, value); // Register an assertion for each member Scope = Scope .ForCondition(message == null) .FailWith(message) .Then; } private object GetDefaultValue<TType>() { // This method is used via reflection above return default(TType); } private static string GetAssertionMessage(string path, Type type, object value) { return string.IsNullOrWhiteSpace(path) ? $"Excepted a value of type '{type.FullName}' -> {value ?? "?"}." : $"Excepted a value of type '{type.FullName}' for '{path}' -> {value ?? "?"}."; } private Func<string, Type, object, string> GetAssertion(Type type) { var assertion = (from k in Assertions.Keys where k.Invoke(type) select Assertions[k]).FirstOrDefault(); return assertion ?? AssertType; } private IEnumerable<MemberInfo> GetMemberInfos(Type type) { return (from m in type.GetMembers(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public) where ReflectionHelper.IsField(m) || ReflectionHelper.IsProperty(m) select m); } private static bool IsType(Type type, Type baseType) { // We may need to do some generics magic to compare the types if (ReflectionHelper.IsGenericType(type) && ReflectionHelper.IsGenericType(baseType)) { var types = type.GetGenericArguments(); var baseTypes = baseType.GetGenericArguments(); if (types.Length == baseTypes.Length) { baseType = baseType.MakeGenericType(types); } } return baseType.IsAssignableFrom(type); } private static void ExtractMemberInfo(MemberInfo member, out Type memberType, out Func<object, object> memberGetter) { memberType = null; memberGetter = null; // Extract the member type and getter action if (ReflectionHelper.IsField(member)) { var fieldInfo = member as FieldInfo; memberType = fieldInfo.FieldType; memberGetter = fieldInfo.GetValue; } else if (ReflectionHelper.IsProperty(member)) { var propertyInfo = member as PropertyInfo; memberType = propertyInfo.PropertyType; memberGetter = propertyInfo.GetValue; } } } }
// 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. // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // // OrderPreservingPipeliningMergeHelper.cs // // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; namespace System.Linq.Parallel { /// <summary> /// A merge helper that yields results in a streaming fashion, while still ensuring correct output /// ordering. This merge only works if each producer task generates outputs in the correct order, /// i.e. with an Increasing (or Correct) order index. /// /// The merge creates DOP producer tasks, each of which will be writing results into a separate /// buffer. /// /// The consumer always waits until each producer buffer contains at least one element. If we don't /// have one element from each producer, we cannot yield the next element. (If the order index is /// Correct, or in some special cases with the Increasing order, we could yield sooner. The /// current algorithm does not take advantage of this.) /// /// The consumer maintains a producer heap, and uses it to decide which producer should yield the next output /// result. After yielding an element from a particular producer, the consumer will take another element /// from the same producer. However, if the producer buffer exceeded a particular threshold, the consumer /// will take the entire buffer, and give the producer an empty buffer to fill. /// /// Finally, if the producer notices that its buffer has exceeded an even greater threshold, it will /// go to sleep and wait until the consumer takes the entire buffer. /// </summary> internal class OrderPreservingPipeliningMergeHelper<TOutput, TKey> : IMergeHelper<TOutput> { private readonly QueryTaskGroupState _taskGroupState; // State shared among tasks. private readonly PartitionedStream<TOutput, TKey> _partitions; // Source partitions. private readonly TaskScheduler _taskScheduler; // The task manager to execute the query. /// <summary> /// Whether the producer is allowed to buffer up elements before handing a chunk to the consumer. /// If false, the producer will make each result available to the consumer immediately after it is /// produced. /// </summary> private readonly bool _autoBuffered; /// <summary> /// Buffers for the results. Each buffer has elements added by one producer, and removed /// by the consumer. /// </summary> private readonly Queue<Pair<TKey, TOutput>>[] _buffers; /// <summary> /// Whether each producer is done producing. Set to true by individual producers, read by consumer. /// </summary> private readonly bool[] _producerDone; /// <summary> /// Whether a particular producer is waiting on the consumer. Read by the consumer, set to true /// by producers, set to false by the consumer. /// </summary> private readonly bool[] _producerWaiting; /// <summary> /// Whether the consumer is waiting on a particular producer. Read by producers, set to true /// by consumer, set to false by producer. /// </summary> private readonly bool[] _consumerWaiting; /// <summary> /// Each object is a lock protecting the corresponding elements in _buffers, _producerDone, /// _producerWaiting and _consumerWaiting. /// </summary> private readonly object[] _bufferLocks; /// <summary> /// A comparer used by the producer heap. /// </summary> private IComparer<Producer<TKey>> _producerComparer; /// <summary> /// The initial capacity of the buffer queue. The value was chosen experimentally. /// </summary> internal const int INITIAL_BUFFER_SIZE = 128; /// <summary> /// If the consumer notices that the queue reached this limit, it will take the entire buffer from /// the producer, instead of just popping off one result. The value was chosen experimentally. /// </summary> internal const int STEAL_BUFFER_SIZE = 1024; /// <summary> /// If the producer notices that the queue reached this limit, it will go to sleep until woken up /// by the consumer. Chosen experimentally. /// </summary> internal const int MAX_BUFFER_SIZE = 8192; //----------------------------------------------------------------------------------- // Instantiates a new merge helper. // // Arguments: // partitions - the source partitions from which to consume data. // ignoreOutput - whether we're enumerating "for effect" or for output. // internal OrderPreservingPipeliningMergeHelper( PartitionedStream<TOutput, TKey> partitions, TaskScheduler taskScheduler, CancellationState cancellationState, bool autoBuffered, int queryId, IComparer<TKey> keyComparer) { Debug.Assert(partitions != null); TraceHelpers.TraceInfo("KeyOrderPreservingMergeHelper::.ctor(..): creating an order preserving merge helper"); _taskGroupState = new QueryTaskGroupState(cancellationState, queryId); _partitions = partitions; _taskScheduler = taskScheduler; _autoBuffered = autoBuffered; int partitionCount = _partitions.PartitionCount; _buffers = new Queue<Pair<TKey, TOutput>>[partitionCount]; _producerDone = new bool[partitionCount]; _consumerWaiting = new bool[partitionCount]; _producerWaiting = new bool[partitionCount]; _bufferLocks = new object[partitionCount]; if (keyComparer == Util.GetDefaultComparer<int>()) { Debug.Assert(typeof(TKey) == typeof(int)); _producerComparer = (IComparer<Producer<TKey>>)new ProducerComparerInt(); } else { _producerComparer = new ProducerComparer(keyComparer); } } //----------------------------------------------------------------------------------- // Schedules execution of the merge itself. // void IMergeHelper<TOutput>.Execute() { OrderPreservingPipeliningSpoolingTask<TOutput, TKey>.Spool( _taskGroupState, _partitions, _consumerWaiting, _producerWaiting, _producerDone, _buffers, _bufferLocks, _taskScheduler, _autoBuffered); } //----------------------------------------------------------------------------------- // Gets the enumerator from which to enumerate output results. // IEnumerator<TOutput> IMergeHelper<TOutput>.GetEnumerator() { return new OrderedPipeliningMergeEnumerator(this, _producerComparer); } //----------------------------------------------------------------------------------- // Returns the results as an array. // [ExcludeFromCodeCoverage] public TOutput[] GetResultsAsArray() { Debug.Fail("An ordered pipelining merge is not intended to be used this way."); throw new InvalidOperationException(); } /// <summary> /// A comparer used by FixedMaxHeap(Of Producer) /// /// This comparer will be used by max-heap. We want the producer with the smallest MaxKey to /// end up in the root of the heap. /// /// x.MaxKey GREATER_THAN y.MaxKey => x LESS_THAN y => return - /// x.MaxKey EQUALS y.MaxKey => x EQUALS y => return 0 /// x.MaxKey LESS_THAN y.MaxKey => x GREATER_THAN y => return + /// </summary> private class ProducerComparer : IComparer<Producer<TKey>> { private IComparer<TKey> _keyComparer; internal ProducerComparer(IComparer<TKey> keyComparer) { _keyComparer = keyComparer; } public int Compare(Producer<TKey> x, Producer<TKey> y) { return _keyComparer.Compare(y.MaxKey, x.MaxKey); } } /// <summary> /// Enumerator over the results of an order-preserving pipelining merge. /// </summary> private class OrderedPipeliningMergeEnumerator : MergeEnumerator<TOutput> { /// <summary> /// Merge helper associated with this enumerator /// </summary> private OrderPreservingPipeliningMergeHelper<TOutput, TKey> _mergeHelper; /// <summary> /// Heap used to efficiently locate the producer whose result should be consumed next. /// For each producer, stores the order index for the next element to be yielded. /// /// Read and written by the consumer only. /// </summary> private readonly FixedMaxHeap<Producer<TKey>> _producerHeap; /// <summary> /// Stores the next element to be yielded from each producer. We use a separate array /// rather than storing this information in the producer heap to keep the Producer struct /// small. /// /// Read and written by the consumer only. /// </summary> private readonly TOutput[] _producerNextElement; /// <summary> /// A private buffer for the consumer. When the size of a producer buffer exceeds a threshold /// (STEAL_BUFFER_SIZE), the consumer will take ownership of the entire buffer, and give the /// producer a new empty buffer to place results into. /// /// Read and written by the consumer only. /// </summary> private readonly Queue<Pair<TKey, TOutput>>[] _privateBuffer; /// <summary> /// Tracks whether MoveNext() has already been called previously. /// </summary> private bool _initialized = false; /// <summary> /// Constructor /// </summary> internal OrderedPipeliningMergeEnumerator(OrderPreservingPipeliningMergeHelper<TOutput, TKey> mergeHelper, IComparer<Producer<TKey>> producerComparer) : base(mergeHelper._taskGroupState) { int partitionCount = mergeHelper._partitions.PartitionCount; _mergeHelper = mergeHelper; _producerHeap = new FixedMaxHeap<Producer<TKey>>(partitionCount, producerComparer); _privateBuffer = new Queue<Pair<TKey, TOutput>>[partitionCount]; _producerNextElement = new TOutput[partitionCount]; } /// <summary> /// Returns the current result /// </summary> public override TOutput Current { get { int producerToYield = _producerHeap.MaxValue.ProducerIndex; return _producerNextElement[producerToYield]; } } /// <summary> /// Moves the enumerator to the next result, or returns false if there are no more results to yield. /// </summary> public override bool MoveNext() { if (!_initialized) { // // Initialization: wait until each producer has produced at least one element. Since the order indices // are increasing, we cannot start yielding until we have at least one element from each producer. // _initialized = true; for (int producer = 0; producer < _mergeHelper._partitions.PartitionCount; producer++) { Pair<TKey, TOutput> element = default(Pair<TKey, TOutput>); // Get the first element from this producer if (TryWaitForElement(producer, ref element)) { // Update the producer heap and its helper array with the received element _producerHeap.Insert(new Producer<TKey>(element.First, producer)); _producerNextElement[producer] = element.Second; } else { // If this producer didn't produce any results because it encountered an exception, // cancellation would have been initiated by now. If cancellation has started, we will // propagate the exception now. ThrowIfInTearDown(); } } } else { // If the producer heap is empty, we are done. In fact, we know that a previous MoveNext() call // already returned false. if (_producerHeap.Count == 0) { return false; } // // Get the next element from the producer that yielded a value last. Update the producer heap. // The next producer to yield will be in the front of the producer heap. // // The last producer whose result the merge yielded int lastProducer = _producerHeap.MaxValue.ProducerIndex; // Get the next element from the same producer Pair<TKey, TOutput> element = default(Pair<TKey, TOutput>); if (TryGetPrivateElement(lastProducer, ref element) || TryWaitForElement(lastProducer, ref element)) { // Update the producer heap and its helper array with the received element _producerHeap.ReplaceMax(new Producer<TKey>(element.First, lastProducer)); _producerNextElement[lastProducer] = element.Second; } else { // If this producer is done because it encountered an exception, cancellation // would have been initiated by now. If cancellation has started, we will propagate // the exception now. ThrowIfInTearDown(); // This producer is done. Remove it from the producer heap. _producerHeap.RemoveMax(); } } return _producerHeap.Count > 0; } /// <summary> /// If the cancellation of the query has been initiated (because one or more producers /// encountered exceptions, or because external cancellation token has been set), the method /// will tear down the query and rethrow the exception. /// </summary> private void ThrowIfInTearDown() { if (_mergeHelper._taskGroupState.CancellationState.MergedCancellationToken.IsCancellationRequested) { try { // Wake up all producers. Since the cancellation token has already been // set, the producers will eventually stop after waking up. object[] locks = _mergeHelper._bufferLocks; for (int i = 0; i < locks.Length; i++) { lock (locks[i]) { Monitor.Pulse(locks[i]); } } // Now, we wait for all producers to wake up, notice the cancellation and stop executing. // QueryEnd will wait on all tasks to complete and then propagate all exceptions. _taskGroupState.QueryEnd(false); Debug.Fail("QueryEnd() should have thrown an exception."); } finally { // Clear the producer heap so that future calls to MoveNext simply return false. _producerHeap.Clear(); } } } /// <summary> /// Wait until a producer's buffer is non-empty, or until that producer is done. /// </summary> /// <returns>false if there is no element to yield because the producer is done, true otherwise</returns> private bool TryWaitForElement(int producer, ref Pair<TKey, TOutput> element) { Queue<Pair<TKey, TOutput>> buffer = _mergeHelper._buffers[producer]; object bufferLock = _mergeHelper._bufferLocks[producer]; lock (bufferLock) { // If the buffer is empty, we need to wait on the producer if (buffer.Count == 0) { // If the producer is already done, return false if (_mergeHelper._producerDone[producer]) { element = default(Pair<TKey, TOutput>); return false; } _mergeHelper._consumerWaiting[producer] = true; Monitor.Wait(bufferLock); // If the buffer is still empty, the producer is done if (buffer.Count == 0) { Debug.Assert(_mergeHelper._producerDone[producer]); element = default(Pair<TKey, TOutput>); return false; } } Debug.Assert(buffer.Count > 0, "Producer's buffer should not be empty here."); // If the producer is waiting, wake it up if (_mergeHelper._producerWaiting[producer]) { Monitor.Pulse(bufferLock); _mergeHelper._producerWaiting[producer] = false; } if (buffer.Count < STEAL_BUFFER_SIZE) { element = buffer.Dequeue(); return true; } else { // Privatize the entire buffer _privateBuffer[producer] = _mergeHelper._buffers[producer]; // Give an empty buffer to the producer _mergeHelper._buffers[producer] = new Queue<Pair<TKey, TOutput>>(INITIAL_BUFFER_SIZE); // No return statement. // This is the only branch that continues below of the lock region. } } // Get an element out of the private buffer. bool gotElement = TryGetPrivateElement(producer, ref element); Debug.Assert(gotElement); return true; } /// <summary> /// Looks for an element from a particular producer in the consumer's private buffer. /// </summary> private bool TryGetPrivateElement(int producer, ref Pair<TKey, TOutput> element) { var privateChunk = _privateBuffer[producer]; if (privateChunk != null) { if (privateChunk.Count > 0) { element = privateChunk.Dequeue(); return true; } Debug.Assert(_privateBuffer[producer].Count == 0); _privateBuffer[producer] = null; } return false; } public override void Dispose() { // Wake up any waiting producers int partitionCount = _mergeHelper._buffers.Length; for (int producer = 0; producer < partitionCount; producer++) { object bufferLock = _mergeHelper._bufferLocks[producer]; lock (bufferLock) { if (_mergeHelper._producerWaiting[producer]) { Monitor.Pulse(bufferLock); } } } base.Dispose(); } } } /// <summary> /// A structure to represent a producer in the producer heap. /// </summary> internal struct Producer<TKey> { internal readonly TKey MaxKey; // Order index of the next element from this producer internal readonly int ProducerIndex; // Index of the producer, [0..DOP) internal Producer(TKey maxKey, int producerIndex) { MaxKey = maxKey; ProducerIndex = producerIndex; } } /// <summary> /// A comparer used by FixedMaxHeap(Of Producer) /// /// This comparer will be used by max-heap. We want the producer with the smallest MaxKey to /// end up in the root of the heap. /// /// x.MaxKey GREATER_THAN y.MaxKey => x LESS_THAN y => return - /// x.MaxKey EQUALS y.MaxKey => x EQUALS y => return 0 /// x.MaxKey LESS_THAN y.MaxKey => x GREATER_THAN y => return + /// </summary> internal class ProducerComparerInt : IComparer<Producer<int>> { public int Compare(Producer<int> x, Producer<int> y) { Debug.Assert(x.MaxKey >= 0 && y.MaxKey >= 0); // Guarantees no overflow on next line return y.MaxKey - x.MaxKey; } } }
using System; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using TestHelper; using Xunit; namespace JiiLib.Constraints.Tests { public class NonAbstractAnalyzerTests : DiagnosticVerifier { [Fact] public async Task VerifyDiagnosticsOnInterfaceAndAbstractClass() { const string source = @"using System; using JiiLib.Constraints; namespace N { public class C<[NonAbstractOnly] T> { } public abstract class X { } public interface IX { } static class P { static void M() { var err1 = new C<X>(); var err2 = new C<IX>(); } } } "; var expected = new[] { new DiagnosticResult { Id = "JLC0002", Message = "Type argument 'X' must be a non-abstract type", Severity = DiagnosticSeverity.Error, Locations = new[] { new DiagnosticResultLocation("Test0.cs", line: 15, column: 30) } }, new DiagnosticResult { Id = "JLC0002", Message = "Type argument 'IX' must be a non-abstract type", Severity = DiagnosticSeverity.Error, Locations = new[] { new DiagnosticResultLocation("Test0.cs", line: 16, column: 30) } } }; await VerifyCSharpDiagnostic(source, expected); } [Fact] public async Task VerifyNoDiagnosticOnConcreteType() { const string source = @"using System; using JiiLib.Constraints; namespace N { public class C<[NonAbstractOnly] T> { } public class X { } public struct S { } static class P { static void M() { var valid1 = new C<X>(); var valid2 = new C<S>(); } } } "; await VerifyCSharpDiagnostic(source, Array.Empty<DiagnosticResult>()); } [Fact] public async Task VerifyDiagnosticOnMethodCall() { const string source = @"using System; using JiiLib.Constraints; namespace N { public class C { public C M<[NonAbstractOnly] T>() => this; } public abstract class X { } static class P { static void M() { var err = new C().M<X>(); } } } "; var expected = new[] { new DiagnosticResult { Id = "JLC0002", Message = "Type argument 'X' must be a non-abstract type", Severity = DiagnosticSeverity.Error, Locations = new[] { new DiagnosticResultLocation("Test0.cs", line: 17, column: 33) } } }; await VerifyCSharpDiagnostic(source, expected); } [Fact] public async Task VerifyNoDiagnosticOnSameAttributeTypeParam() { const string source = @"using System; using JiiLib.Constraints; namespace N { public class C { public NoAbstract<T> M<[NonAbstractOnly] T>() where T : IFormattable { return new NoAbstract<T>(); } } public class NoAbstract<[NonAbstractOnly] T> { } } "; await VerifyCSharpDiagnostic(source, Array.Empty<DiagnosticResult>()); } [Fact] public async Task VerifyNoDiagnosticOnEIM() { const string source = @"using System; using JiiLib.Constraints; namespace N { public interface I { void M<[NonAbstractOnly] T>(); } public class C : I { void I.M<T>() { } } } "; await VerifyCSharpDiagnostic(source, Array.Empty<DiagnosticResult>()); } [Fact] public async Task VerifyDiagnosticOnIIM() { const string source = @"using System; using JiiLib.Constraints; namespace N { public interface I { void M<[NonAbstractOnly] T>(); } public class C : I { public void M<T>() { } } } "; var expected = new[] { new DiagnosticResult() { Id = "JLC0002", Message = "Type argument 'T' must be a non-abstract type", Severity = DiagnosticSeverity.Error, Locations = new[] { new DiagnosticResultLocation("Test0.cs", line: 13, column: 23) } } }; await VerifyCSharpDiagnostic(source, expected); } [Fact] public async Task VerifyDiagnosticOnOverride() { const string source = @"using System; using JiiLib.Constraints; namespace N { public abstract class Base { public abstract void M<[NonAbstractOnly] T>(); } public class C : Base { public override void M<T>() { } } } "; var expected = new[] { new DiagnosticResult() { Id = "JLC0002", Message = "Type argument 'T' must be a non-abstract type", Severity = DiagnosticSeverity.Error, Locations = new[] { new DiagnosticResultLocation("Test0.cs", line: 13, column: 32) } } }; await VerifyCSharpDiagnostic(source, expected); } protected override DiagnosticAnalyzer GetCSharpDiagnosticAnalyzer() => (Activator.CreateInstance( assemblyName: "JiiLib.Constraints", typeName: "JiiLib.Constraints.Analyzers.NonAbstractConstraintAnalyzer")?.Unwrap() as DiagnosticAnalyzer)!; } }
using System; using System.Drawing; using System.Collections; using System.Windows.Forms; using System.Data; using System.IO; using Franson.BlueTools; using Franson.Protocols.Obex; using Franson.Protocols.Obex.ObjectPush; namespace ObjectPushSampleCF { /// <summary> /// Summary description for Form1. /// </summary> public class MainForm : System.Windows.Forms.Form { private System.Windows.Forms.ProgressBar progressBar; private System.Windows.Forms.Button sendBtn; private System.Windows.Forms.Button discoverBtn; private System.Windows.Forms.Label label1; private System.Windows.Forms.ListBox deviceList; private System.Windows.Forms.OpenFileDialog openFileDialog; private System.Windows.Forms.Label informLabel; private System.Windows.Forms.StatusBar statusBar; private Manager m_manager = null; private Network m_network = null; private ObexObjectPush m_objectPush = null; private bool m_boolAborted = false; private bool m_boolDenied = false; // these objects should be class global to prevent them from being taken by the garbage collector private RemoteService m_serviceCurrent = null; private Stream m_streamCurrent = null; private bool m_boolUnrecoverableError = false; public MainForm() { // // Required for Windows Form Designer support // InitializeComponent(); // catch all BlueTools exceptions - like e.g. license expired try { // get your trial license or buy BlueTools at franson.com Franson.BlueTools.License license = new Franson.BlueTools.License(); license.LicenseKey = "HU5UZer022JOLX98oidhQkbRbvv0NRJbHXEc"; // get bluetools manager m_manager = Manager.GetManager(); // get first network dongle - bluetools 1.0 only supports one! m_network = m_manager.Networks[0]; // marshal events into this class thread. m_manager.Parent = this; statusBar.Text = GetStack(); } catch (Exception exc) { // display BlueTools errors here MessageBox.Show(exc.Message); } } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { // BlueTools manager must be disposed, otherwise you can't exit application! Manager.GetManager().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.progressBar = new System.Windows.Forms.ProgressBar(); this.sendBtn = new System.Windows.Forms.Button(); this.discoverBtn = new System.Windows.Forms.Button(); this.label1 = new System.Windows.Forms.Label(); this.deviceList = new System.Windows.Forms.ListBox(); this.openFileDialog = new System.Windows.Forms.OpenFileDialog(); this.statusBar = new System.Windows.Forms.StatusBar(); this.informLabel = new System.Windows.Forms.Label(); // // progressBar // this.progressBar.Location = new System.Drawing.Point(40, 152); this.progressBar.Size = new System.Drawing.Size(160, 8); // // sendBtn // this.sendBtn.Enabled = false; this.sendBtn.Location = new System.Drawing.Point(128, 168); this.sendBtn.Text = "Push"; this.sendBtn.Click += new System.EventHandler(this.sendBtn_Click); // // discoverBtn // this.discoverBtn.Location = new System.Drawing.Point(40, 168); this.discoverBtn.Text = "Discover"; this.discoverBtn.Click += new System.EventHandler(this.discoverBtn_Click); // // label1 // this.label1.Location = new System.Drawing.Point(40, 8); this.label1.Size = new System.Drawing.Size(100, 16); this.label1.Text = "Devices"; // // deviceList // this.deviceList.Location = new System.Drawing.Point(40, 32); this.deviceList.Size = new System.Drawing.Size(160, 119); this.deviceList.SelectedIndexChanged += new System.EventHandler(this.deviceList_SelectedIndexChanged); // // statusBar // this.statusBar.Location = new System.Drawing.Point(0, 248); this.statusBar.Size = new System.Drawing.Size(240, 22); // // informLabel // this.informLabel.Location = new System.Drawing.Point(8, 200); this.informLabel.Size = new System.Drawing.Size(224, 40); this.informLabel.Text = "Click on discover to detect Bluetooth devices."; // // MainForm // this.Controls.Add(this.informLabel); this.Controls.Add(this.statusBar); this.Controls.Add(this.progressBar); this.Controls.Add(this.sendBtn); this.Controls.Add(this.discoverBtn); this.Controls.Add(this.label1); this.Controls.Add(this.deviceList); this.MaximizeBox = false; this.MinimizeBox = false; this.Text = "Object Push Sample CF"; this.Closing += new System.ComponentModel.CancelEventHandler(this.MainForm_Closing); } #endregion /// <summary> /// The main entry point for the application. /// </summary> static void Main() { Application.Run(new MainForm()); } private void discoverBtn_Click(object sender, System.EventArgs e) { m_network.DeviceDiscovered += new BlueToolsEventHandler(m_network_DeviceDiscovered); m_network.DeviceDiscoveryStarted += new BlueToolsEventHandler(m_network_DeviceDiscoveryStarted); m_network.DeviceDiscoveryCompleted += new BlueToolsEventHandler(m_network_DeviceDiscoveryCompleted); // Start looking for devices on the network // Use Network.DiscoverDevices() if you don't want to use events. m_network.DiscoverDevicesAsync(); } private void m_network_DeviceDiscovered(object sender, BlueToolsEventArgs eventArgs) { // add every device found RemoteDevice device = (RemoteDevice)((DiscoveryEventArgs)eventArgs).Discovery; deviceList.Items.Add(device); } private void m_network_DeviceDiscoveryStarted(object sender, BlueToolsEventArgs eventArgs) { // disable the Discover button when we begin device discovery discoverBtn.Enabled = false; // inform the user what we're doing informLabel.Text = "Scanning for devices..."; // disable device list while scanning deviceList.Enabled = false; } private void m_network_DeviceDiscoveryCompleted(object sender, BlueToolsEventArgs eventArgs) { // enable Discover button again since device discovery is complete discoverBtn.Enabled = true; // inform the user what to do informLabel.Text = "Click on the device you wish to push a file to."; // enable device list again deviceList.Enabled = true; m_network.DeviceDiscovered -= new BlueToolsEventHandler(m_network_DeviceDiscovered); m_network.DeviceDiscoveryStarted -= new BlueToolsEventHandler(m_network_DeviceDiscoveryStarted); m_network.DeviceDiscoveryCompleted -= new BlueToolsEventHandler(m_network_DeviceDiscoveryCompleted); } private void deviceList_SelectedIndexChanged(object sender, System.EventArgs e) { // cancel any possible ongoing device discovery if user clicks on anything m_network.CancelDeviceDiscovery(); // get selected item (a remote device) RemoteDevice selectedDevice = (RemoteDevice)deviceList.SelectedItem; selectedDevice.ServiceDiscoveryStarted += new BlueToolsEventHandler(selectedDevice_ServiceDiscoveryStarted); selectedDevice.ServiceDiscoveryCompleted += new BlueToolsEventHandler(selectedDevice_ServiceDiscoveryCompleted); // detect Object Push service (OPP) on this device selectedDevice.DiscoverServicesAsync(ServiceType.OBEXObjectPush); } private void selectedDevice_ServiceDiscoveryStarted(object sender, BlueToolsEventArgs eventArgs) { // when beginning to search for services - disable the Discover button // we shouldn't scan for devices while attempting to scan for services. discoverBtn.Enabled = false; sendBtn.Enabled = false; } private void selectedDevice_ServiceDiscoveryCompleted(object sender, BlueToolsEventArgs eventArgs) { // when service discovery is complete - let us re-enable the discover button. // It is okay to try to update the device list discoverBtn.Enabled = true; // set error event handler for the device RemoteDevice device = (RemoteDevice)sender; device.Error += new BlueToolsEventHandler(device_Error); // get all services found Service[] services = (Service[])((DiscoveryEventArgs)eventArgs).Discovery; // if we have a service since before, close the stream if (m_streamCurrent != null) { m_streamCurrent.Close(); m_streamCurrent = null; } // and remove the service if (m_serviceCurrent != null) { m_serviceCurrent = null; } // if we found a new service... if (services.Length > 0) { // ...get OPP service object m_serviceCurrent = (RemoteService)services[0]; try { // create an ObexObjectPush object connected to the ServiceStream // wait for 20 seconds for frozen devices m_objectPush = new ObexObjectPush(-1); // marshal event to this class thread m_objectPush.Parent = this; // setup event handlers m_objectPush.Error += new ObexEventHandler(m_objectPush_Error); m_objectPush.PutFileBegin += new ObexEventHandler(m_objectPush_PutFileBegin); m_objectPush.PutFileProgress += new ObexEventHandler(m_objectPush_PutFileProgress); m_objectPush.PutFileEnd += new ObexEventHandler(m_objectPush_PutFileEnd); m_objectPush.DisconnectEnd += new ObexEventHandler(m_objectPush_DisconnectEnd); sendBtn.Enabled = true; informLabel.Text = "Click on Push to select file(s) to push to device."; } catch (Exception exc) { sendBtn.Enabled = false; MessageBox.Show(exc.Message); } } } private void sendBtn_Click(object sender, System.EventArgs e) { if (sendBtn.Text.Equals("Push")) { try { // if we have a service to send to if (m_serviceCurrent != null) { // make sure ObexObjectPush is initialized and select file to push to device if (m_objectPush != null && openFileDialog.ShowDialog() == DialogResult.OK) { sendBtn.Text = "Cancel"; m_streamCurrent = m_serviceCurrent.Stream; FileStream fileStream = new FileStream(openFileDialog.FileName, FileMode.Open, FileAccess.Read); m_objectPush.PushFileAsync(fileStream, Path.GetFileName(openFileDialog.FileName), m_streamCurrent); } } } catch (Exception exc) { MessageBox.Show(exc.Message); } } else { // if button text isn't Send it will be Cancel - // if user click it, we tell ObexObjectPush that we want to abort m_objectPush.Abort(); // only need to press cancel once - won't help you to press it more sendBtn.Enabled = false; } } private void m_objectPush_PutFileProgress(object sender, ObexEventArgs eventArgs) { ObexCopyEventArgs copyArgs = (ObexCopyEventArgs)eventArgs; // if max value on progressbar isn't set, set it if (copyArgs.Size != progressBar.Maximum) { progressBar.Maximum = (int)copyArgs.Size; } // set position of file copy progressBar.Value = (int)copyArgs.Position; // update copy panel to show progress in kb statusBar.Text = Convert.ToString(copyArgs.Position / 1024) + " kb / " + Convert.ToString(copyArgs.Size / 1024) + " kb"; } private void m_objectPush_PutFileEnd(object sender, ObexEventArgs eventArgs) { // when finished copying... // ...close file stream ObexCopyEventArgs copyArgs = (ObexCopyEventArgs)eventArgs; // Close Stream opened by ObexObjectPush copyArgs.Stream.Close(); // ...enable discover button discoverBtn.Enabled = true; // ...change text caption back to Push sendBtn.Text = "Push"; // set progressbar position back to beginning - just for show, doesn't really matter progressBar.Value = 0; // set copy panel to nothing to make it invisible again - it's auto-resizing :) statusBar.Text = GetStack(); // inform the user what is happening if (m_boolAborted) { // ...if transfer was aborted.. informLabel.Text = "Push aborted."; } else if (m_boolDenied) { // ... if transfer was impossible informLabel.Text = "Push denied by device."; } else if (m_boolUnrecoverableError) { informLabel.Text = "Stream was lost to device."; } else { // ...transfer completed informLabel.Text = "File(s) sent to device."; } // enable device list again when finished deviceList.Enabled = true; // show user what to do next informLabel.Text += "\nClick on Send to select file(s) to push to device."; // we enable the Send button again if it was disabled when it was a Cancel button sendBtn.Enabled = true; } private void m_objectPush_PutFileBegin(object sender, ObexEventArgs eventArgs) { // this transfer hasn't been aborted (yet!) m_boolAborted = false; // this transfer hasn't been denied (yet!) m_boolDenied = false; // this transfer has not had any errors (yet!) m_boolUnrecoverableError = false; // while copying, disable the discover button discoverBtn.Enabled = false; // inform the user what is happening informLabel.Text = "Sending file(s) to device..."; // disable device list while copying deviceList.Enabled = false; } private void m_objectPush_Error(object sender, ObexEventArgs eventArgs) { ObexErrorEventArgs errorArgs = (ObexErrorEventArgs)eventArgs; // if the error was not an Obex error - we can assume the Stream is not available anymore if (errorArgs.Error == Franson.Protocols.Obex.ErrorCode.StreamError) { // since the stream was lost, re-enable the UI // the Push button sendBtn.Enabled = false; // the device list deviceList.Enabled = true; // this error can't be recovered from m_boolUnrecoverableError = true; // show this error in a box - it's pretty serious MessageBox.Show(errorArgs.Message); } else { // if the error is transfer was aborted, set boolean so we can display this to user if (errorArgs.Error == Franson.Protocols.Obex.ErrorCode.Aborted || errorArgs.Error == Franson.Protocols.Obex.ErrorCode.SecurityAbort) { m_boolAborted = true; } if (errorArgs.Error == Franson.Protocols.Obex.ErrorCode.SendDenied) { m_boolDenied = true; } // show message to user MessageBox.Show(errorArgs.Message); } } private void device_Error(object sender, BlueToolsEventArgs eventArgs) { Franson.BlueTools.ErrorEventArgs errorArgs = (Franson.BlueTools.ErrorEventArgs)eventArgs; statusBar.Text = errorArgs.Message; } private string GetStack() { // update statusbar panel with name of currently used stack switch (Manager.StackID) { case StackID.STACK_MICROSOFT: { return "Microsoft Stack"; } case StackID.STACK_WIDCOMM: { return "Widcomm Stack"; } default: { return "Unknown stack"; } } } private void MainForm_Closing(object sender, System.ComponentModel.CancelEventArgs e) { // if m_serviceCurrent is available, close the stream if (m_serviceCurrent != null) { if (m_streamCurrent != null) m_streamCurrent.Close(); // set these objects to null to mark them for GC m_streamCurrent = null; m_serviceCurrent = null; } // dispose objects - also makes sure that Manager are disposed. Dispose(); } private void m_objectPush_DisconnectEnd(object sender, ObexEventArgs e) { // we close this stream to ensure that we get a fresh new one when pushing next time. // this is needed since some devices do not allow multiple pushes in one stream if (m_streamCurrent != null) { m_streamCurrent.Close(); } } } }
// 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 AndNotSByte() { var test = new SimpleBinaryOpTest__AndNotSByte(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); // 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 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(); // 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__AndNotSByte { private const int VectorSize = 32; private const int ElementCount = VectorSize / sizeof(SByte); private static SByte[] _data1 = new SByte[ElementCount]; private static SByte[] _data2 = new SByte[ElementCount]; private static Vector256<SByte> _clsVar1; private static Vector256<SByte> _clsVar2; private Vector256<SByte> _fld1; private Vector256<SByte> _fld2; private SimpleBinaryOpTest__DataTable<SByte> _dataTable; static SimpleBinaryOpTest__AndNotSByte() { var random = new Random(); for (var i = 0; i < ElementCount; i++) { _data1[i] = (sbyte)(random.Next(sbyte.MinValue, sbyte.MaxValue)); _data2[i] = (sbyte)(random.Next(sbyte.MinValue, sbyte.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<SByte>, byte>(ref _clsVar1), ref Unsafe.As<SByte, byte>(ref _data2[0]), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<SByte>, byte>(ref _clsVar2), ref Unsafe.As<SByte, byte>(ref _data1[0]), VectorSize); } public SimpleBinaryOpTest__AndNotSByte() { Succeeded = true; var random = new Random(); for (var i = 0; i < ElementCount; i++) { _data1[i] = (sbyte)(random.Next(sbyte.MinValue, sbyte.MaxValue)); _data2[i] = (sbyte)(random.Next(sbyte.MinValue, sbyte.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<SByte>, byte>(ref _fld1), ref Unsafe.As<SByte, byte>(ref _data1[0]), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<SByte>, byte>(ref _fld2), ref Unsafe.As<SByte, byte>(ref _data2[0]), VectorSize); for (var i = 0; i < ElementCount; i++) { _data1[i] = (sbyte)(random.Next(sbyte.MinValue, sbyte.MaxValue)); _data2[i] = (sbyte)(random.Next(sbyte.MinValue, sbyte.MaxValue)); } _dataTable = new SimpleBinaryOpTest__DataTable<SByte>(_data1, _data2, new SByte[ElementCount], VectorSize); } public bool IsSupported => Avx2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { var result = Avx2.AndNot( Unsafe.Read<Vector256<SByte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<SByte>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { var result = Avx2.AndNot( Avx.LoadVector256((SByte*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((SByte*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { var result = Avx2.AndNot( Avx.LoadAlignedVector256((SByte*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((SByte*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { var result = typeof(Avx2).GetMethod(nameof(Avx2.AndNot), new Type[] { typeof(Vector256<SByte>), typeof(Vector256<SByte>) }) .Invoke(null, new object[] { Unsafe.Read<Vector256<SByte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<SByte>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<SByte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { var result = typeof(Avx2).GetMethod(nameof(Avx2.AndNot), new Type[] { typeof(Vector256<SByte>), typeof(Vector256<SByte>) }) .Invoke(null, new object[] { Avx.LoadVector256((SByte*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((SByte*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<SByte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { var result = typeof(Avx2).GetMethod(nameof(Avx2.AndNot), new Type[] { typeof(Vector256<SByte>), typeof(Vector256<SByte>) }) .Invoke(null, new object[] { Avx.LoadAlignedVector256((SByte*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((SByte*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<SByte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { var result = Avx2.AndNot( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { var left = Unsafe.Read<Vector256<SByte>>(_dataTable.inArray1Ptr); var right = Unsafe.Read<Vector256<SByte>>(_dataTable.inArray2Ptr); var result = Avx2.AndNot(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { var left = Avx.LoadVector256((SByte*)(_dataTable.inArray1Ptr)); var right = Avx.LoadVector256((SByte*)(_dataTable.inArray2Ptr)); var result = Avx2.AndNot(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { var left = Avx.LoadAlignedVector256((SByte*)(_dataTable.inArray1Ptr)); var right = Avx.LoadAlignedVector256((SByte*)(_dataTable.inArray2Ptr)); var result = Avx2.AndNot(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclFldScenario() { var test = new SimpleBinaryOpTest__AndNotSByte(); var result = Avx2.AndNot(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunFldScenario() { var result = Avx2.AndNot(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunUnsupportedScenario() { Succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { Succeeded = true; } } private void ValidateResult(Vector256<SByte> left, Vector256<SByte> right, void* result, [CallerMemberName] string method = "") { SByte[] inArray1 = new SByte[ElementCount]; SByte[] inArray2 = new SByte[ElementCount]; SByte[] outArray = new SByte[ElementCount]; Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left); Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right); Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, 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 = "") { SByte[] inArray1 = new SByte[ElementCount]; SByte[] inArray2 = new SByte[ElementCount]; SByte[] outArray = new SByte[ElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(SByte[] left, SByte[] right, SByte[] result, [CallerMemberName] string method = "") { if ((sbyte)(~left[0] & right[0]) != result[0]) { Succeeded = false; } else { for (var i = 1; i < left.Length; i++) { if ((sbyte)(~left[i] & right[i]) != result[i]) { Succeeded = false; break; } } } if (!Succeeded) { Console.WriteLine($"{nameof(Avx2)}.{nameof(Avx2.AndNot)}<SByte>: {method} failed:"); Console.WriteLine($" left: ({string.Join(", ", left)})"); Console.WriteLine($" right: ({string.Join(", ", right)})"); Console.WriteLine($" result: ({string.Join(", ", result)})"); Console.WriteLine(); } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Xunit; using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace Test { // a key part of cancellation testing is 'promptness'. Those tests appear in pfxperfunittests. // the tests here are only regarding basic API correctness and sanity checking. public static class WithCancellationTests { [Fact] public static void PreCanceledToken_ForAll() { OperationCanceledException caughtException = null; var cs = new CancellationTokenSource(); cs.Cancel(); int[] srcEnumerable = Enumerable.Range(0, 1000).ToArray(); ThrowOnFirstEnumerable<int> throwOnFirstEnumerable = new ThrowOnFirstEnumerable<int>(srcEnumerable); try { throwOnFirstEnumerable .AsParallel() .WithCancellation(cs.Token) .ForAll((x) => { Console.WriteLine(x.ToString()); }); } catch (OperationCanceledException ex) { caughtException = ex; } Assert.NotNull(caughtException); Assert.Equal(cs.Token, caughtException.CancellationToken); } [Fact] public static void PreCanceledToken_SimpleEnumerator() { OperationCanceledException caughtException = null; var cs = new CancellationTokenSource(); cs.Cancel(); int[] srcEnumerable = Enumerable.Range(0, 1000).ToArray(); ThrowOnFirstEnumerable<int> throwOnFirstEnumerable = new ThrowOnFirstEnumerable<int>(srcEnumerable); try { var query = throwOnFirstEnumerable .AsParallel() .WithCancellation(cs.Token); foreach (var item in query) { } } catch (OperationCanceledException ex) { caughtException = ex; } Assert.NotNull(caughtException); Assert.Equal(cs.Token, caughtException.CancellationToken); } [Fact] public static void MultiplesWithCancellationIsIllegal() { InvalidOperationException caughtException = null; try { CancellationTokenSource cs = new CancellationTokenSource(); CancellationToken ct = cs.Token; var query = Enumerable.Range(1, 10).AsParallel().WithDegreeOfParallelism(2).WithDegreeOfParallelism(2); query.ToArray(); } catch (InvalidOperationException ex) { caughtException = ex; //Program.TestHarness.Log("IOE caught. message = " + ex.Message); } Assert.NotNull(caughtException); } // This test is failing on our CI machines, probably due to the VM's limited CPU. // To-do: Re-enable this test when we resolve the build machine issues. // [Fact(Skip="Issue #176")] public static void CTT_Sorting_ToArray() { int size = 10000; CancellationTokenSource tokenSource = new CancellationTokenSource(); Task.Run( () => { //Thread.Sleep(500); tokenSource.Cancel(); }); OperationCanceledException caughtException = null; try { // This query should run for at least a few seconds due to the sleeps in the select-delegate var query = Enumerable.Range(1, size).AsParallel() .WithCancellation(tokenSource.Token) .Select( i => { //Thread.Sleep(1); return i; }); query.ToArray(); } catch (OperationCanceledException ex) { caughtException = ex; } Assert.NotNull(caughtException); Assert.Equal(tokenSource.Token, caughtException.CancellationToken); } // This test is failing on our CI machines, probably due to the VM's limited CPU. // To-do: Re-enable this test when we resolve the build machine issues. // [Fact(Skip="Issue #176")] public static void CTT_NonSorting_AsynchronousMergerEnumeratorDispose() { int size = 10000; CancellationTokenSource tokenSource = new CancellationTokenSource(); Exception caughtException = null; var query = Enumerable.Range(1, size).AsParallel() .WithCancellation(tokenSource.Token) .Select( i => { //Thread.Sleep(1000); return i; }); IEnumerator<int> enumerator = query.GetEnumerator(); Task.Run( () => { //Thread.Sleep(500); enumerator.Dispose(); }); try { // This query should run for at least a few seconds due to the sleeps in the select-delegate for (int j = 0; j < 1000; j++) { enumerator.MoveNext(); } } catch (Exception ex) { caughtException = ex; } Assert.NotNull(caughtException); } [Fact] public static void CTT_NonSorting_SynchronousMergerEnumeratorDispose() { int size = 10000; CancellationTokenSource tokenSource = new CancellationTokenSource(); Exception caughtException = null; var query = Enumerable.Range(1, size).AsParallel() .WithCancellation(tokenSource.Token) .Select( i => { SimulateThreadSleep(100); return i; }).WithMergeOptions(ParallelMergeOptions.FullyBuffered); IEnumerator<int> enumerator = query.GetEnumerator(); Task.Run( () => { SimulateThreadSleep(200); enumerator.Dispose(); }); try { // This query should run for at least a few seconds due to the sleeps in the select-delegate for (int j = 0; j < 1000; j++) { enumerator.MoveNext(); } } catch (ObjectDisposedException ex) { caughtException = ex; } Assert.NotNull(caughtException); } // This test is failing on our CI machines, probably due to the VM's limited CPU. // To-do: Re-enable this test when we resolve the build machine issues. // [Fact(Skip="Issue #176")] public static void CTT_NonSorting_ToArray_ExternalCancel() { int size = 10000; CancellationTokenSource tokenSource = new CancellationTokenSource(); OperationCanceledException caughtException = null; Task.Run( () => { //Thread.Sleep(1000); tokenSource.Cancel(); }); try { int[] output = Enumerable.Range(1, size).AsParallel() .WithCancellation(tokenSource.Token) .Select( i => { //Thread.Sleep(100); return i; }).ToArray(); } catch (OperationCanceledException ex) { caughtException = ex; } Assert.NotNull(caughtException); Assert.Equal(tokenSource.Token, caughtException.CancellationToken); } /// <summary> /// /// [Regression Test] /// This issue occured because the QuerySettings structure was not being deep-cloned during /// query-opening. As a result, the concurrent inner-enumerators (for the RHS operators) /// that occur in SelectMany were sharing CancellationState that they should not have. /// The result was that enumerators could falsely believe they had been canceled when /// another inner-enumerator was disposed. /// /// Note: the failure was intermittent. this test would fail about 1 in 2 times on mikelid1 (4-core). /// </summary> /// <returns></returns> [Fact] public static void CloningQuerySettingsForSelectMany() { var plinq_src = ParallelEnumerable.Range(0, 1999).AsParallel(); Exception caughtException = null; try { var inner = ParallelEnumerable.Range(0, 20).AsParallel().Select(_item => _item); var output = plinq_src .SelectMany( _x => inner, (_x, _y) => _x ) .ToArray(); } catch (Exception ex) { caughtException = ex; } Assert.Null(caughtException); } // [Regression Test] // Use of the async channel can block both the consumer and producer threads.. before the cancellation work // these had no means of being awoken. // // However, only the producers need to wake up on cancellation as the consumer // will wake up once all the producers have gone away (via AsynchronousOneToOneChannel.SetDone()) // // To specifically verify this test, we want to know that the Async channels were blocked in TryEnqueChunk before Dispose() is called // -> this was verified manually, but is not simple to automate [Fact] public static void ChannelCancellation_ProducerBlocked() { Console.WriteLine("PlinqCancellationTests.ChannelCancellation_ProducerBlocked()"); Console.WriteLine(" Query running (should be few seconds max).."); var query1 = Enumerable.Range(0, 100000000) //provide 100million elements to ensure all the cores get >64K ints. Good up to 1600cores .AsParallel() .Select(x => x); var enumerator1 = query1.GetEnumerator(); enumerator1.MoveNext(); Task.Delay(1000); //Thread.Sleep(1000); // give the pipelining time to fill up some buffers. enumerator1.MoveNext(); enumerator1.Dispose(); //can potentially hang Console.WriteLine(" Done (success)."); } /// <summary> /// [Regression Test] /// This issue occurred because aggregations like Sum or Average would incorrectly /// wrap OperationCanceledException with AggregateException. /// </summary> [Fact] public static void AggregatesShouldntWrapOCE() { var cs = new CancellationTokenSource(); cs.Cancel(); // Expect OperationCanceledException rather than AggregateException or something else try { Enumerable.Range(0, 1000).AsParallel().WithCancellation(cs.Token).Sum(x => x); } catch (OperationCanceledException) { return; } catch (Exception e) { Assert.True(false, string.Format("PlinqCancellationTests.AggregatesShouldntWrapOCE: > Failed: got {0}, expected OperationCanceledException", e.GetType().ToString())); } Assert.True(false, string.Format("PlinqCancellationTests.AggregatesShouldntWrapOCE: > Failed: no exception occured, expected OperationCanceledException")); } // Plinq supresses OCE(externalCT) occuring in worker threads and then throws a single OCE(ct) // if a manual OCE(ct) is thrown but ct is not canceled, Plinq should not suppress it, else things // get confusing... // ONLY an OCE(ct) for ct.IsCancellationRequested=true is co-operative cancellation [Fact] public static void OnlySuppressOCEifCTCanceled() { AggregateException caughtException = null; CancellationTokenSource cts = new CancellationTokenSource(); CancellationToken externalToken = cts.Token; try { Enumerable.Range(1, 10).AsParallel() .WithCancellation(externalToken) .Select( x => { if (x % 2 == 0) throw new OperationCanceledException(externalToken); return x; } ) .ToArray(); } catch (AggregateException ae) { caughtException = ae; } Assert.NotNull(caughtException); } // a specific repro where inner queries would see an ODE on the merged cancellation token source // when the implementation involved disposing and recreating the token on each worker thread [Fact] public static void Cancellation_ODEIssue() { AggregateException caughtException = null; try { Enumerable.Range(0, 1999).ToArray() .AsParallel().AsUnordered() .WithExecutionMode(ParallelExecutionMode.ForceParallelism) .Zip<int, int, int>( Enumerable.Range(1000, 20).Select<int, int>(_item => (int)_item).AsParallel().AsUnordered(), (first, second) => { throw new OperationCanceledException(); }) .ForAll(x => { }); } catch (AggregateException ae) { caughtException = ae; } //the failure was an ODE coming out due to an ephemeral disposed merged cancellation token source. Assert.True(caughtException != null, "Cancellation_ODEIssue: We expect an aggregate exception with OCEs in it."); } [Fact] public static void CancellationSequentialWhere() { IEnumerable<int> src = Enumerable.Repeat(0, int.MaxValue); CancellationTokenSource tokenSrc = new CancellationTokenSource(); var q = src.AsParallel().WithCancellation(tokenSrc.Token).Where(x => false).TakeWhile(x => true); Task task = Task.Factory.StartNew( () => { try { foreach (var x in q) { } Assert.True(false, string.Format("PlinqCancellationTests.CancellationSequentialWhere: > Failed: OperationCanceledException was not caught.")); } catch (OperationCanceledException oce) { if (oce.CancellationToken != tokenSrc.Token) { Assert.True(false, string.Format("PlinqCancellationTests.CancellationSequentialWhere: > Failed: Wrong cancellation token.")); } } } ); // We wait for 100 ms. If we canceled the token source immediately, the cancellation // would occur at the query opening time. The goal of this test is to test cancellation // at query execution time. Task.Delay(100); //Thread.Sleep(100); tokenSrc.Cancel(); task.Wait(); } [Fact] public static void CancellationSequentialElementAt() { IEnumerable<int> src = Enumerable.Repeat(0, int.MaxValue); CancellationTokenSource tokenSrc = new CancellationTokenSource(); Task task = Task.Factory.StartNew( () => { try { int res = src.AsParallel() .WithCancellation(tokenSrc.Token) .Where(x => true) .TakeWhile(x => true) .ElementAt(int.MaxValue - 1); Assert.True(false, string.Format("PlinqCancellationTests.CancellationSequentialElementAt: > Failed: OperationCanceledException was not caught.")); } catch (OperationCanceledException oce) { Assert.Equal(oce.CancellationToken, tokenSrc.Token); } } ); // We wait for 100 ms. If we canceled the token source immediately, the cancellation // would occur at the query opening time. The goal of this test is to test cancellation // at query execution time. Task.WaitAll(Task.Delay(100)); //Thread.Sleep(100); tokenSrc.Cancel(); task.Wait(); } [Fact] public static void CancellationSequentialDistinct() { IEnumerable<int> src = Enumerable.Repeat(0, int.MaxValue); CancellationTokenSource tokenSrc = new CancellationTokenSource(); Task task = Task.Factory.StartNew( () => { try { var q = src.AsParallel() .WithCancellation(tokenSrc.Token) .Distinct() .TakeWhile(x => true); foreach (var x in q) { } Assert.True(false, string.Format("PlinqCancellationTests.CancellationSequentialDistinct: > Failed: OperationCanceledException was not caught.")); } catch (OperationCanceledException oce) { Assert.Equal(oce.CancellationToken, tokenSrc.Token); } } ); // We wait for 100 ms. If we canceled the token source immediately, the cancellation // would occur at the query opening time. The goal of this test is to test cancellation // at query execution time. Task.Delay(100); //Thread.Sleep(100); tokenSrc.Cancel(); task.Wait(); } // Regression test for an issue causing ODE if a queryEnumator is disposed before moveNext is called. [Fact] public static void ImmediateDispose() { var queryEnumerator = Enumerable.Range(1, 10).AsParallel().Select(x => x).GetEnumerator(); queryEnumerator.Dispose(); } // REPRO 1 -- cancellation [Fact] public static void SetOperationsThrowAggregateOnCancelOrDispose_1() { var mre = new ManualResetEvent(false); var plinq_src = Enumerable.Range(0, 5000000).Select(x => { if (x == 0) mre.Set(); return x; }); Task t = null; try { CancellationTokenSource cs = new CancellationTokenSource(); var plinq = plinq_src .AsParallel().WithCancellation(cs.Token) .WithDegreeOfParallelism(1) .Union(Enumerable.Range(0, 10).AsParallel()); var walker = plinq.GetEnumerator(); t = Task.Factory.StartNew(() => { mre.WaitOne(); cs.Cancel(); }); while (walker.MoveNext()) { //Thread.Sleep(1); var item = walker.Current; } walker.MoveNext(); Assert.True(false, string.Format("PlinqCancellationTests.SetOperationsThrowAggregateOnCancelOrDispose_1: OperationCanceledException was expected, but no exception occured.")); } catch (OperationCanceledException) { //This is expected. } catch (Exception e) { Assert.True(false, string.Format("PlinqCancellationTests.SetOperationsThrowAggregateOnCancelOrDispose_1: OperationCanceledException was expected, but a different exception occured. " + e.ToString())); } if (t != null) t.Wait(); } // throwing a fake OCE(ct) when the ct isn't canceled should produce an AggregateException. [Fact] public static void SetOperationsThrowAggregateOnCancelOrDispose_2() { try { CancellationTokenSource cs = new CancellationTokenSource(); var plinq = Enumerable.Range(0, 50) .AsParallel().WithCancellation(cs.Token) .WithDegreeOfParallelism(1) .Union(Enumerable.Range(0, 10).AsParallel().Select<int, int>(x => { throw new OperationCanceledException(cs.Token); })); var walker = plinq.GetEnumerator(); while (walker.MoveNext()) { //Thread.Sleep(1); } walker.MoveNext(); Assert.True(false, string.Format("PlinqCancellationTests.SetOperationsThrowAggregateOnCancelOrDispose_2: failed. AggregateException was expected, but no exception occured.")); } catch (OperationCanceledException) { Assert.True(false, string.Format("PlinqCancellationTests.SetOperationsThrowAggregateOnCancelOrDispose_2: FAILED. AggregateExcption was expected, but an OperationCanceledException occured.")); } catch (AggregateException) { // expected } catch (Exception e) { Assert.True(false, string.Format("PlinqCancellationTests.SetOperationsThrowAggregateOnCancelOrDispose_2. failed. AggregateExcption was expected, but some other exception occured." + e.ToString())); } } // Changes made to hash-partitioning (April'09) lost the cancellation checks during the // main repartitioning loop (matrix building). [Fact] public static void HashPartitioningCancellation() { OperationCanceledException caughtException = null; CancellationTokenSource cs = new CancellationTokenSource(); //Without ordering var queryUnordered = Enumerable.Range(0, int.MaxValue) .Select(x => { if (x == 0) cs.Cancel(); return x; }) .AsParallel() .WithCancellation(cs.Token) .Intersect(Enumerable.Range(0, 1000000).AsParallel()); try { foreach (var item in queryUnordered) { } } catch (OperationCanceledException oce) { caughtException = oce; } Assert.NotNull(caughtException); caughtException = null; //With ordering var queryOrdered = Enumerable.Range(0, int.MaxValue) .Select(x => { if (x == 0) cs.Cancel(); return x; }) .AsParallel().AsOrdered() .WithCancellation(cs.Token) .Intersect(Enumerable.Range(0, 1000000).AsParallel()); try { foreach (var item in queryOrdered) { } } catch (OperationCanceledException oce) { caughtException = oce; } Assert.NotNull(caughtException); } // If a query is cancelled and immediately disposed, the dispose should not throw an OCE. [Fact] public static void CancelThenDispose() { try { CancellationTokenSource cancel = new CancellationTokenSource(); var q = ParallelEnumerable.Range(0, 1000).WithCancellation(cancel.Token).Select(x => x); IEnumerator<int> e = q.GetEnumerator(); e.MoveNext(); cancel.Cancel(); e.Dispose(); } catch (Exception e) { Assert.True(false, string.Format("PlinqCancellationTests.CancelThenDispose: > Failed. Expected no exception, got " + e.GetType())); } } [Fact] public static void CancellationCausingNoDataMustThrow() { OperationCanceledException oce = null; CancellationTokenSource cs = new CancellationTokenSource(); var query = Enumerable.Range(0, 100000000) .Select(x => { if (x == 0) cs.Cancel(); return x; }) .AsParallel() .WithCancellation(cs.Token) .Select(x => x); try { foreach (var item in query) //We expect an OperationCancelledException during the MoveNext { } } catch (OperationCanceledException ex) { oce = ex; } Assert.NotNull(oce); } [Fact] public static void DontDoWorkIfTokenAlreadyCanceled() { OperationCanceledException oce = null; CancellationTokenSource cs = new CancellationTokenSource(); var query = Enumerable.Range(0, 100000000) .Select(x => { if (x > 0) // to avoid the "Error:unreachable code detected" throw new ArgumentException("User-delegate exception."); return x; }) .AsParallel() .WithCancellation(cs.Token) .Select(x => x); cs.Cancel(); try { foreach (var item in query) //We expect an OperationCancelledException during the MoveNext { } } catch (OperationCanceledException ex) { oce = ex; } Assert.NotNull(oce); } // To help the user, we will check if a cancellation token passed to WithCancellation() is // not backed by a disposed CTS. This will help them identify incorrect cts.Dispose calls, but // doesn't solve all their problems if they don't manage CTS lifetime correctly. // We test via a few random queries that have shown inconsistent behaviour in the past. [Fact] public static void PreDisposedCTSPassedToPlinq() { ArgumentException ae1 = null; ArgumentException ae2 = null; ArgumentException ae3 = null; CancellationTokenSource cts = new CancellationTokenSource(); CancellationToken ct = cts.Token; cts.Dispose(); // Early dispose try { Enumerable.Range(1, 10).AsParallel() .WithCancellation(ct) .OrderBy(x => x) .ToArray(); } catch (Exception ex) { ae1 = (ArgumentException)ex; } try { Enumerable.Range(1, 10).AsParallel() .WithCancellation(ct) .Last(); } catch (Exception ex) { ae2 = (ArgumentException)ex; } try { Enumerable.Range(1, 10).AsParallel() .WithCancellation(ct) .OrderBy(x => x) .Last(); } catch (Exception ex) { ae3 = (ArgumentException)ex; } Assert.NotNull(ae1); Assert.NotNull(ae2); Assert.NotNull(ae3); } public static void SimulateThreadSleep(int milliseconds) { ManualResetEvent mre = new ManualResetEvent(false); mre.WaitOne(milliseconds); } } // --------------------------- // Helper classes // --------------------------- internal class ThrowOnFirstEnumerable<T> : IEnumerable<T> { private readonly IEnumerable<T> _innerEnumerable; public ThrowOnFirstEnumerable(IEnumerable<T> innerEnumerable) { _innerEnumerable = innerEnumerable; } public IEnumerator<T> GetEnumerator() { return new ThrowOnFirstEnumerator<T>(_innerEnumerable.GetEnumerator()); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } internal class ThrowOnFirstEnumerator<T> : IEnumerator<T> { private IEnumerator<T> _innerEnumerator; public ThrowOnFirstEnumerator(IEnumerator<T> sourceEnumerator) { _innerEnumerator = sourceEnumerator; } public void Dispose() { _innerEnumerator.Dispose(); } public bool MoveNext() { throw new InvalidOperationException("ThrowOnFirstEnumerator throws on the first MoveNext"); } public T Current { get { return _innerEnumerator.Current; } } object IEnumerator.Current { get { return Current; } } public void Reset() { _innerEnumerator.Reset(); } } }
using System.Collections.Generic; using System.Diagnostics.Contracts; using System.Runtime.InteropServices; using System.Text; namespace System.Globalization { internal partial class CultureData { /// <summary> /// Check with the OS to see if this is a valid culture. /// If so we populate a limited number of fields. If its not valid we return false. /// /// The fields we populate: /// /// sWindowsName -- The name that windows thinks this culture is, ie: /// en-US if you pass in en-US /// de-DE_phoneb if you pass in de-DE_phoneb /// fj-FJ if you pass in fj (neutral, on a pre-Windows 7 machine) /// fj if you pass in fj (neutral, post-Windows 7 machine) /// /// sRealName -- The name you used to construct the culture, in pretty form /// en-US if you pass in EN-us /// en if you pass in en /// de-DE_phoneb if you pass in de-DE_phoneb /// /// sSpecificCulture -- The specific culture for this culture /// en-US for en-US /// en-US for en /// de-DE_phoneb for alt sort /// fj-FJ for fj (neutral) /// /// sName -- The IETF name of this culture (ie: no sort info, could be neutral) /// en-US if you pass in en-US /// en if you pass in en /// de-DE if you pass in de-DE_phoneb /// /// bNeutral -- TRUE if it is a neutral locale /// /// For a neutral we just populate the neutral name, but we leave the windows name pointing to the /// windows locale that's going to provide data for us. /// </summary> private unsafe bool InitCultureData() { // TODO: Implement this fully. sWindowsName = ""; sRealName = ""; sSpecificCulture = ""; sName = ""; bNeutral = false; return true; } private string GetLocaleInfo(LocaleStringData type) { // TODO: Implement this fully. return GetLocaleInfo("", type); } // For LOCALE_SPARENT we need the option of using the "real" name (forcing neutral names) instead of the // "windows" name, which can be specific for downlevel (< windows 7) os's. private string GetLocaleInfo(string localeName, LocaleStringData type) { // TODO: Implement this fully. switch(type) { case LocaleStringData.LocalizedDisplayName: return "Invariant Language (Invariant Country)"; case LocaleStringData.EnglishDisplayName: return "Invariant Language (Invariant Country)"; case LocaleStringData.NativeDisplayName: return "Invariant Language (Invariant Country)"; case LocaleStringData.LocalizedLanguageName: return "Invariant Language"; case LocaleStringData.EnglishLanguageName: return "Invariant Language"; case LocaleStringData.NativeLanguageName: return "Invariant Language"; case LocaleStringData.EnglishCountryName: return "Invariant Country"; case LocaleStringData.NativeCountryName: return "Invariant Country"; case LocaleStringData.ListSeparator: return ","; case LocaleStringData.DecimalSeparator: return "."; case LocaleStringData.ThousandSeparator: return ","; case LocaleStringData.Digits: return "3;0"; case LocaleStringData.MonetarySymbol: return "\u00A4"; case LocaleStringData.Iso4217MonetarySymbol: return "XDR"; case LocaleStringData.MonetaryDecimalSeparator: return "."; case LocaleStringData.MonetaryThousandSeparator: return ","; case LocaleStringData.AMDesignator: return "AM"; case LocaleStringData.PMDesignator: return "PM"; case LocaleStringData.PositiveSign: return "+"; case LocaleStringData.NegativeSign: return "-"; case LocaleStringData.Iso639LanguageName: return "iv"; case LocaleStringData.Iso3166CountryName: return "IV"; case LocaleStringData.NaNSymbol: return "NaN"; case LocaleStringData.PositiveInfinitySymbol: return "Infinity"; case LocaleStringData.NegativeInfinitySymbol: return "-Infinity"; case LocaleStringData.ParentName: return ""; case LocaleStringData.PercentSymbol: return "%"; case LocaleStringData.PerMilleSymbol: return "\u2030"; default: Contract.Assert(false, "Unmatched case in GetLocaleInfo(LocaleStringData)"); throw new NotImplementedException(); } } private int GetLocaleInfo(LocaleNumberData type) { // TODO: Implement this fully. switch (type) { case LocaleNumberData.LanguageId: return 127; case LocaleNumberData.MeasurementSystem: return 0; case LocaleNumberData.FractionalDigitsCount: return 2; case LocaleNumberData.NegativeNumberFormat: return 1; case LocaleNumberData.MonetaryFractionalDigitsCount: return 2; case LocaleNumberData.PositiveMonetaryNumberFormat: return 0; case LocaleNumberData.NegativeMonetaryNumberFormat: return 0; case LocaleNumberData.CalendarType: return 1; case LocaleNumberData.FirstWeekOfYear: return 0; case LocaleNumberData.ReadingLayout: return 0; case LocaleNumberData.NegativePercentFormat: return 0; case LocaleNumberData.PositivePercentFormat: return 0; default: Contract.Assert(false, "Unmatched case in GetLocaleInfo(LocaleNumberData)"); throw new NotImplementedException(); } } private int[] GetLocaleInfo(LocaleGroupingData type) { // TODO: Implement this fully. switch (type) { case LocaleGroupingData.Digit: return new int[] { 3 }; case LocaleGroupingData.Monetary: return new int[] { 3 }; default: Contract.Assert(false, "Unmatched case in GetLocaleInfo(LocaleGroupingData)"); throw new NotImplementedException(); } } private string GetTimeFormatString() { // TODO: Implement this fully. return "HH:mm:ss"; } private int GetFirstDayOfWeek() { // TODO: Implement this fully. return 0; } private String[] GetTimeFormats() { // TODO: Implement this fully. return new string[] { "HH:mm:ss" }; } private String[] GetShortTimeFormats() { // TODO: Implement this fully. return new string[] { "HH:mm", "hh:mm tt", "H:mm", "h:mm tt" }; } // Enumerate all system cultures and then try to find out which culture has // region name match the requested region name private static CultureData GetCultureDataFromRegionName(String regionName) { // TODO: Implement this fully. if (regionName == "") { return CultureInfo.InvariantCulture.m_cultureData; } throw new NotImplementedException(); } private static string GetLanguageDisplayName(string cultureName) { // TODO: Implement this fully. if (cultureName == "") { return "Invariant Language"; } throw new NotImplementedException(); } private static string GetRegionDisplayName(string isoCountryCode) { // TODO: Implement this fully. throw new NotImplementedException(); } private static CultureInfo GetUserDefaultCulture() { // TODO: Implement this fully. return CultureInfo.InvariantCulture; } private static bool IsCustomCultureId(int cultureId) { // TODO: Implement this fully. throw new NotImplementedException(); } // PAL methods end here. } }
// 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.Threading.Tasks; using System.Security.Authentication.ExtendedProtection; using System.Security.Principal; namespace System.Net.Security { /* An authenticated stream based on NEGO SSP. The class that can be used by client and server side applications - to transfer Identities across the stream - to encrypt data based on NEGO SSP package In most cases the innerStream will be of type NetworkStream. On Win9x data encryption is not available and both sides have to explicitly drop SecurityLevel and MuatualAuth requirements. This is a simple wrapper class. All real work is done by internal NegoState class and the other partial implementation files. */ public partial class NegotiateStream : AuthenticatedStream { private NegoState _negoState; private string _package; private IIdentity _remoteIdentity; public NegotiateStream(Stream innerStream) : this(innerStream, false) { } public NegotiateStream(Stream innerStream, bool leaveInnerStreamOpen) : base(innerStream, leaveInnerStreamOpen) { #if DEBUG using (DebugThreadTracking.SetThreadKind(ThreadKinds.User)) { #endif _negoState = new NegoState(innerStream, leaveInnerStreamOpen); _package = NegoState.DefaultPackage; InitializeStreamPart(); #if DEBUG } #endif } public virtual IAsyncResult BeginAuthenticateAsClient(AsyncCallback asyncCallback, object asyncState) { return BeginAuthenticateAsClient((NetworkCredential)CredentialCache.DefaultCredentials, null, string.Empty, ProtectionLevel.EncryptAndSign, TokenImpersonationLevel.Identification, asyncCallback, asyncState); } public virtual IAsyncResult BeginAuthenticateAsClient(NetworkCredential credential, string targetName, AsyncCallback asyncCallback, object asyncState) { return BeginAuthenticateAsClient(credential, null, targetName, ProtectionLevel.EncryptAndSign, TokenImpersonationLevel.Identification, asyncCallback, asyncState); } public virtual IAsyncResult BeginAuthenticateAsClient(NetworkCredential credential, ChannelBinding binding, string targetName, AsyncCallback asyncCallback, object asyncState) { return BeginAuthenticateAsClient(credential, binding, targetName, ProtectionLevel.EncryptAndSign, TokenImpersonationLevel.Identification, asyncCallback, asyncState); } public virtual IAsyncResult BeginAuthenticateAsClient( NetworkCredential credential, string targetName, ProtectionLevel requiredProtectionLevel, TokenImpersonationLevel allowedImpersonationLevel, AsyncCallback asyncCallback, object asyncState) { return BeginAuthenticateAsClient(credential, null, targetName, requiredProtectionLevel, allowedImpersonationLevel, asyncCallback, asyncState); } public virtual IAsyncResult BeginAuthenticateAsClient( NetworkCredential credential, ChannelBinding binding, string targetName, ProtectionLevel requiredProtectionLevel, TokenImpersonationLevel allowedImpersonationLevel, AsyncCallback asyncCallback, object asyncState) { #if DEBUG using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Async)) { #endif _negoState.ValidateCreateContext(_package, false, credential, targetName, binding, requiredProtectionLevel, allowedImpersonationLevel); LazyAsyncResult result = new LazyAsyncResult(_negoState, asyncState, asyncCallback); _negoState.ProcessAuthentication(result); return result; #if DEBUG } #endif } public virtual void EndAuthenticateAsClient(IAsyncResult asyncResult) { #if DEBUG using (DebugThreadTracking.SetThreadKind(ThreadKinds.User)) { #endif _negoState.EndProcessAuthentication(asyncResult); #if DEBUG } #endif } public virtual void AuthenticateAsServer() { AuthenticateAsServer((NetworkCredential)CredentialCache.DefaultCredentials, null, ProtectionLevel.EncryptAndSign, TokenImpersonationLevel.Identification); } public virtual void AuthenticateAsServer(ExtendedProtectionPolicy policy) { AuthenticateAsServer((NetworkCredential)CredentialCache.DefaultCredentials, policy, ProtectionLevel.EncryptAndSign, TokenImpersonationLevel.Identification); } public virtual void AuthenticateAsServer(NetworkCredential credential, ProtectionLevel requiredProtectionLevel, TokenImpersonationLevel requiredImpersonationLevel) { AuthenticateAsServer(credential, null, requiredProtectionLevel, requiredImpersonationLevel); } public virtual void AuthenticateAsServer(NetworkCredential credential, ExtendedProtectionPolicy policy, ProtectionLevel requiredProtectionLevel, TokenImpersonationLevel requiredImpersonationLevel) { #if DEBUG using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Sync)) { #endif _negoState.ValidateCreateContext(_package, credential, string.Empty, policy, requiredProtectionLevel, requiredImpersonationLevel); _negoState.ProcessAuthentication(null); #if DEBUG } #endif } public virtual IAsyncResult BeginAuthenticateAsServer(AsyncCallback asyncCallback, object asyncState) { return BeginAuthenticateAsServer((NetworkCredential)CredentialCache.DefaultCredentials, null, ProtectionLevel.EncryptAndSign, TokenImpersonationLevel.Identification, asyncCallback, asyncState); } public virtual IAsyncResult BeginAuthenticateAsServer(ExtendedProtectionPolicy policy, AsyncCallback asyncCallback, object asyncState) { return BeginAuthenticateAsServer((NetworkCredential)CredentialCache.DefaultCredentials, policy, ProtectionLevel.EncryptAndSign, TokenImpersonationLevel.Identification, asyncCallback, asyncState); } public virtual IAsyncResult BeginAuthenticateAsServer( NetworkCredential credential, ProtectionLevel requiredProtectionLevel, TokenImpersonationLevel requiredImpersonationLevel, AsyncCallback asyncCallback, object asyncState) { return BeginAuthenticateAsServer(credential, null, requiredProtectionLevel, requiredImpersonationLevel, asyncCallback, asyncState); } public virtual IAsyncResult BeginAuthenticateAsServer( NetworkCredential credential, ExtendedProtectionPolicy policy, ProtectionLevel requiredProtectionLevel, TokenImpersonationLevel requiredImpersonationLevel, AsyncCallback asyncCallback, object asyncState) { #if DEBUG using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Async)) { #endif _negoState.ValidateCreateContext(_package, credential, string.Empty, policy, requiredProtectionLevel, requiredImpersonationLevel); LazyAsyncResult result = new LazyAsyncResult(_negoState, asyncState, asyncCallback); _negoState.ProcessAuthentication(result); return result; #if DEBUG } #endif } // public virtual void EndAuthenticateAsServer(IAsyncResult asyncResult) { #if DEBUG using (DebugThreadTracking.SetThreadKind(ThreadKinds.User)) { #endif _negoState.EndProcessAuthentication(asyncResult); #if DEBUG } #endif } public virtual void AuthenticateAsClient() { AuthenticateAsClient((NetworkCredential)CredentialCache.DefaultCredentials, null, string.Empty, ProtectionLevel.EncryptAndSign, TokenImpersonationLevel.Identification); } public virtual void AuthenticateAsClient(NetworkCredential credential, string targetName) { AuthenticateAsClient(credential, null, targetName, ProtectionLevel.EncryptAndSign, TokenImpersonationLevel.Identification); } public virtual void AuthenticateAsClient(NetworkCredential credential, ChannelBinding binding, string targetName) { AuthenticateAsClient(credential, binding, targetName, ProtectionLevel.EncryptAndSign, TokenImpersonationLevel.Identification); } public virtual void AuthenticateAsClient( NetworkCredential credential, string targetName, ProtectionLevel requiredProtectionLevel, TokenImpersonationLevel allowedImpersonationLevel) { AuthenticateAsClient(credential, null, targetName, requiredProtectionLevel, allowedImpersonationLevel); } public virtual void AuthenticateAsClient( NetworkCredential credential, ChannelBinding binding, string targetName, ProtectionLevel requiredProtectionLevel, TokenImpersonationLevel allowedImpersonationLevel) { #if DEBUG using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Sync)) { #endif _negoState.ValidateCreateContext(_package, false, credential, targetName, binding, requiredProtectionLevel, allowedImpersonationLevel); _negoState.ProcessAuthentication(null); #if DEBUG } #endif } public virtual Task AuthenticateAsClientAsync() { return Task.Factory.FromAsync(BeginAuthenticateAsClient, EndAuthenticateAsClient, null); } public virtual Task AuthenticateAsClientAsync(NetworkCredential credential, string targetName) { return Task.Factory.FromAsync(BeginAuthenticateAsClient, EndAuthenticateAsClient, credential, targetName, null); } public virtual Task AuthenticateAsClientAsync( NetworkCredential credential, string targetName, ProtectionLevel requiredProtectionLevel, TokenImpersonationLevel allowedImpersonationLevel) { return Task.Factory.FromAsync((callback, state) => BeginAuthenticateAsClient(credential, targetName, requiredProtectionLevel, allowedImpersonationLevel, callback, state), EndAuthenticateAsClient, null); } public virtual Task AuthenticateAsClientAsync(NetworkCredential credential, ChannelBinding binding, string targetName) { return Task.Factory.FromAsync(BeginAuthenticateAsClient, EndAuthenticateAsClient, credential, binding, targetName, null); } public virtual Task AuthenticateAsClientAsync( NetworkCredential credential, ChannelBinding binding, string targetName, ProtectionLevel requiredProtectionLevel, TokenImpersonationLevel allowedImpersonationLevel) { return Task.Factory.FromAsync((callback, state) => BeginAuthenticateAsClient(credential, binding, targetName, requiredProtectionLevel, allowedImpersonationLevel, callback, state), EndAuthenticateAsClient, null); } public virtual Task AuthenticateAsServerAsync() { return Task.Factory.FromAsync(BeginAuthenticateAsServer, EndAuthenticateAsServer, null); } public virtual Task AuthenticateAsServerAsync(ExtendedProtectionPolicy policy) { return Task.Factory.FromAsync(BeginAuthenticateAsServer, EndAuthenticateAsServer, policy, null); } public virtual Task AuthenticateAsServerAsync(NetworkCredential credential, ProtectionLevel requiredProtectionLevel, TokenImpersonationLevel requiredImpersonationLevel) { return Task.Factory.FromAsync(BeginAuthenticateAsServer, EndAuthenticateAsServer, credential, requiredProtectionLevel, requiredImpersonationLevel, null); } public virtual Task AuthenticateAsServerAsync( NetworkCredential credential, ExtendedProtectionPolicy policy, ProtectionLevel requiredProtectionLevel, TokenImpersonationLevel requiredImpersonationLevel) { return Task.Factory.FromAsync((callback, state) => BeginAuthenticateAsServer(credential, policy, requiredProtectionLevel, requiredImpersonationLevel, callback, state), EndAuthenticateAsClient, null); } public override bool IsAuthenticated { get { #if DEBUG using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Async)) { #endif return _negoState.IsAuthenticated; #if DEBUG } #endif } } public override bool IsMutuallyAuthenticated { get { #if DEBUG using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Async)) { #endif return _negoState.IsMutuallyAuthenticated; #if DEBUG } #endif } } public override bool IsEncrypted { get { #if DEBUG using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Async)) { #endif return _negoState.IsEncrypted; #if DEBUG } #endif } } public override bool IsSigned { get { #if DEBUG using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Async)) { #endif return _negoState.IsSigned; #if DEBUG } #endif } } public override bool IsServer { get { #if DEBUG using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Async)) { #endif return _negoState.IsServer; #if DEBUG } #endif } } public virtual TokenImpersonationLevel ImpersonationLevel { get { #if DEBUG using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Async)) { #endif return _negoState.AllowedImpersonation; #if DEBUG } #endif } } public virtual IIdentity RemoteIdentity { get { #if DEBUG using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Async)) { #endif if (_remoteIdentity == null) { _remoteIdentity = _negoState.GetIdentity(); } return _remoteIdentity; #if DEBUG } #endif } } // // Stream contract implementation // public override bool CanSeek { get { return false; } } public override bool CanRead { get { return IsAuthenticated && InnerStream.CanRead; } } public override bool CanTimeout { get { return InnerStream.CanTimeout; } } public override bool CanWrite { get { return IsAuthenticated && InnerStream.CanWrite; } } public override int ReadTimeout { get { return InnerStream.ReadTimeout; } set { InnerStream.ReadTimeout = value; } } public override int WriteTimeout { get { return InnerStream.WriteTimeout; } set { InnerStream.WriteTimeout = value; } } public override long Length { get { return InnerStream.Length; } } public override long Position { get { return InnerStream.Position; } set { throw new NotSupportedException(SR.net_noseek); } } public override void SetLength(long value) { InnerStream.SetLength(value); } public override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException(SR.net_noseek); } public override void Flush() { #if DEBUG using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Sync)) { #endif InnerStream.Flush(); #if DEBUG } #endif } public override Task FlushAsync(CancellationToken cancellationToken) { return InnerStream.FlushAsync(cancellationToken); } protected override void Dispose(bool disposing) { #if DEBUG using (DebugThreadTracking.SetThreadKind(ThreadKinds.User)) { #endif try { _negoState.Close(); } finally { base.Dispose(disposing); } #if DEBUG } #endif } public override int Read(byte[] buffer, int offset, int count) { #if DEBUG using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Sync)) { #endif _negoState.CheckThrow(true); if (!_negoState.CanGetSecureStream) { return InnerStream.Read(buffer, offset, count); } return ProcessRead(buffer, offset, count, null); #if DEBUG } #endif } public override void Write(byte[] buffer, int offset, int count) { #if DEBUG using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Sync)) { #endif _negoState.CheckThrow(true); if (!_negoState.CanGetSecureStream) { InnerStream.Write(buffer, offset, count); return; } ProcessWrite(buffer, offset, count, null); #if DEBUG } #endif } public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback asyncCallback, object asyncState) { #if DEBUG using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Async)) { #endif _negoState.CheckThrow(true); if (!_negoState.CanGetSecureStream) { return TaskToApm.Begin(InnerStream.ReadAsync(buffer, offset, count), asyncCallback, asyncState); } BufferAsyncResult bufferResult = new BufferAsyncResult(this, buffer, offset, count, asyncState, asyncCallback); AsyncProtocolRequest asyncRequest = new AsyncProtocolRequest(bufferResult); ProcessRead(buffer, offset, count, asyncRequest); return bufferResult; #if DEBUG } #endif } public override int EndRead(IAsyncResult asyncResult) { #if DEBUG using (DebugThreadTracking.SetThreadKind(ThreadKinds.User)) { #endif _negoState.CheckThrow(true); if (!_negoState.CanGetSecureStream) { return TaskToApm.End<int>(asyncResult); } if (asyncResult == null) { throw new ArgumentNullException(nameof(asyncResult)); } BufferAsyncResult bufferResult = asyncResult as BufferAsyncResult; if (bufferResult == null) { throw new ArgumentException(SR.Format(SR.net_io_async_result, asyncResult.GetType().FullName), nameof(asyncResult)); } if (Interlocked.Exchange(ref _NestedRead, 0) == 0) { throw new InvalidOperationException(SR.Format(SR.net_io_invalidendcall, "EndRead")); } // No "artificial" timeouts implemented so far, InnerStream controls timeout. bufferResult.InternalWaitForCompletion(); if (bufferResult.Result is Exception) { if (bufferResult.Result is IOException) { throw (Exception)bufferResult.Result; } throw new IOException(SR.net_io_read, (Exception)bufferResult.Result); } return bufferResult.Int32Result; #if DEBUG } #endif } // // public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback asyncCallback, object asyncState) { #if DEBUG using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Async)) { #endif _negoState.CheckThrow(true); if (!_negoState.CanGetSecureStream) { return TaskToApm.Begin(InnerStream.WriteAsync(buffer, offset, count), asyncCallback, asyncState); } BufferAsyncResult bufferResult = new BufferAsyncResult(this, buffer, offset, count, asyncState, asyncCallback); AsyncProtocolRequest asyncRequest = new AsyncProtocolRequest(bufferResult); ProcessWrite(buffer, offset, count, asyncRequest); return bufferResult; #if DEBUG } #endif } public override void EndWrite(IAsyncResult asyncResult) { #if DEBUG using (DebugThreadTracking.SetThreadKind(ThreadKinds.User)) { #endif _negoState.CheckThrow(true); if (!_negoState.CanGetSecureStream) { TaskToApm.End(asyncResult); return; } if (asyncResult == null) { throw new ArgumentNullException(nameof(asyncResult)); } BufferAsyncResult bufferResult = asyncResult as BufferAsyncResult; if (bufferResult == null) { throw new ArgumentException(SR.Format(SR.net_io_async_result, asyncResult.GetType().FullName), nameof(asyncResult)); } if (Interlocked.Exchange(ref _NestedWrite, 0) == 0) { throw new InvalidOperationException(SR.Format(SR.net_io_invalidendcall, "EndWrite")); } // No "artificial" timeouts implemented so far, InnerStream controls timeout. bufferResult.InternalWaitForCompletion(); if (bufferResult.Result is Exception) { if (bufferResult.Result is IOException) { throw (Exception)bufferResult.Result; } throw new IOException(SR.net_io_write, (Exception)bufferResult.Result); } #if DEBUG } #endif } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using NUnit.Framework; using Outlander.Core.Client.Scripting; namespace Outlander.Core.Client.Tests { [TestFixture] public class TokenizerTests { private Tokenizer theTokenizer; [SetUp] public void SetUp() { theTokenizer = new Tokenizer(TokenDefinitionRegistry.Default().Definitions()); } [Test] public void creates_label_token() { const string line = "somewhere:"; var tokens = theTokenizer.Tokenize(line).ToList(); Assert.AreEqual(1, tokens.Count); Assert.AreEqual("label", tokens[0].Type); Assert.AreEqual("somewhere", tokens[0].Value); } [Test] public void creates_label_swim_token() { const string line = "Swim:\r"; var tokens = theTokenizer.Tokenize(line).ToList(); Assert.AreEqual(1, tokens.Count); Assert.AreEqual("label", tokens[0].Type); Assert.AreEqual("Swim", tokens[0].Value); } [Test] public void creates_action_not_label_token() { const string line = "action var circle $1;put #var circle $1 when Circle:\\s+(\\d+)$"; var tokens = theTokenizer.Tokenize(line).ToList(); Assert.AreEqual(1, tokens.Count); var token = tokens.First().As<ActionToken>(); Assert.NotNull(token); Assert.AreEqual("action", token.Type); Assert.AreEqual("var circle $1;put #var circle $1", token.Action); Assert.AreEqual("Circle:\\s+(\\d+)$", token.When); } [Test] public void creates_goto_token() { const string line = "goto somewhere"; var tokens = theTokenizer.Tokenize(line).ToList(); Assert.AreEqual(1, tokens.Count); Assert.AreEqual("goto", tokens[0].Type); Assert.AreEqual("somewhere", tokens[0].Value); } [Test] public void creates_waitfor_token() { const string line = "waitfor You finish playing"; var tokens = theTokenizer.Tokenize(line).ToList(); Assert.AreEqual(1, tokens.Count); Assert.AreEqual("waitfor", tokens[0].Type); Assert.AreEqual("You finish playing", tokens[0].Value); } [Test] public void creates_waitforre_token() { const string line = "waitforre You finish playing|Something else"; var tokens = theTokenizer.Tokenize(line).ToList(); Assert.AreEqual(1, tokens.Count); Assert.AreEqual("waitforre", tokens[0].Type); Assert.AreEqual("You finish playing|Something else", tokens[0].Value); } [Test] public void creates_pause_token() { const string line = "pause 0.5"; var tokens = theTokenizer.Tokenize(line).ToList(); Assert.AreEqual(1, tokens.Count); Assert.AreEqual("pause", tokens[0].Type); Assert.AreEqual("0.5", tokens[0].Value); } [Test] public void creates_pause_token_without_value() { const string line = "pause"; var tokens = theTokenizer.Tokenize(line).ToList(); Assert.AreEqual(1, tokens.Count); Assert.AreEqual("pause", tokens[0].Type); Assert.AreEqual("", tokens[0].Value); } [Test] public void creates_put_token() { const string line = "PUT collect rocks"; var tokens = theTokenizer.Tokenize(line).ToList(); Assert.AreEqual(1, tokens.Count); Assert.AreEqual("put", tokens[0].Type); Assert.AreEqual("collect rocks", tokens[0].Value); } [Test] public void creates_match_token() { const string line = "match Kick You manage to collect"; var token = theTokenizer.Tokenize(line).Single().As<MatchToken>(); Assert.AreEqual("match", token.Type); Assert.AreEqual("Kick", token.Goto); Assert.AreEqual("You manage to collect", token.Pattern); } [Test] public void creates_match_token_2() { const string line = "match Wait1 ...wait something"; var token = theTokenizer.Tokenize(line).Single().As<MatchToken>(); Assert.AreEqual("match", token.Type); Assert.AreEqual("Wait1", token.Goto); Assert.AreEqual("...wait something", token.Pattern); } [Test] public void creates_match_token_3() { const string line = "MATCH braid You get"; var token = theTokenizer.Tokenize(line).Single().As<MatchToken>(); Assert.AreEqual("match", token.Type); Assert.AreEqual("braid", token.Goto); Assert.AreEqual("You get", token.Pattern); } [Test] public void creates_match_token_trims_end() { const string line = "MATCH braid You get\r"; var token = theTokenizer.Tokenize(line).Single().As<MatchToken>(); Assert.AreEqual("match", token.Type); Assert.AreEqual("braid", token.Goto); Assert.AreEqual("You get", token.Pattern); } [Test] public void creates_matchre_token() { const string line = "matchre CheckEXP You take a step back|Now what did the|I could not find"; const string pattern = "You take a step back|Now what did the|I could not find"; var token = theTokenizer.Tokenize(line).Single().As<MatchToken>(); Assert.AreEqual("matchre", token.Type); Assert.AreEqual("CheckEXP", token.Goto); Assert.AreEqual(pattern, token.Pattern); } [Test] public void creates_matchre_token_trims_end() { const string line = "matchre CheckEXP You take a step back|Now what did the|I could not find\r"; const string pattern = "You take a step back|Now what did the|I could not find"; var token = theTokenizer.Tokenize(line).Single().As<MatchToken>(); Assert.AreEqual("matchre", token.Type); Assert.AreEqual("CheckEXP", token.Goto); Assert.AreEqual(pattern, token.Pattern); } [Test] public void creates_if_token() { const string line = "if ($Outdoorsmanship.LearningRate >= %maxexp) then goto END"; var token = theTokenizer.Tokenize(line).Single().As<IfToken>(); Assert.AreEqual("if", token.Type); Assert.AreEqual("($Outdoorsmanship.LearningRate >= %maxexp) then goto END", token.Value); } [Test] public void creates_if_num_token() { const string line = "if_1 goto something"; var token = theTokenizer.Tokenize(line).Single().As<IfToken>(); Assert.AreEqual("if_", token.Type); Assert.AreEqual("1", token.Blocks.IfEval); Assert.AreEqual("goto something", token.Blocks.IfBlock); } [Test] public void creates_if_num_2_token() { const string line = "if_13 goto somewhere"; var token = theTokenizer.Tokenize(line).Single().As<IfToken>(); Assert.AreEqual("if_", token.Type); Assert.AreEqual("13", token.Blocks.IfEval); Assert.AreEqual("goto somewhere", token.Blocks.IfBlock); } [Test] public void creates_var_token() { const string line = "var something another"; var token = theTokenizer.Tokenize(line).Single(); Assert.AreEqual("var", token.Type); Assert.AreEqual("something another", token.Value); } [Test] public void creates_var_token_from_setvariable() { const string line = "setvariable something another"; var token = theTokenizer.Tokenize(line).Single(); Assert.AreEqual("var", token.Type); Assert.AreEqual("something another", token.Value); } [Test] public void creates_unvar_token() { const string line = "unvar something"; var token = theTokenizer.Tokenize(line).Single(); Assert.AreEqual("unvar", token.Type); Assert.AreEqual("unvar something", token.Text); Assert.AreEqual("something", token.Value); } [Test] public void creates_hasvar_token() { const string line = "hasvar something newvar"; var token = theTokenizer.Tokenize(line).Single(); Assert.AreEqual("hasvar", token.Type); Assert.AreEqual("hasvar something newvar", token.Text); Assert.AreEqual("something newvar", token.Value); } [Test] public void creates_move_token() { const string line = "move something somewhere"; var token = theTokenizer.Tokenize(line).Single(); Assert.AreEqual("move", token.Type); Assert.AreEqual("something somewhere", token.Value); } [Test] public void creates_nextroom_token() { const string line = "nextroom something somewhere"; var token = theTokenizer.Tokenize(line).Single(); Assert.AreEqual("nextroom", token.Type); Assert.AreEqual("something somewhere", token.Value); } [Test] public void creates_action_token() { const string line = "action do something when some condition"; var token = theTokenizer.Tokenize(line).Single().As<ActionToken>(); Assert.AreEqual("do something", token.Action); Assert.AreEqual("some condition", token.When); } [Test] public void creates_send_token() { const string line = "send stuff"; var token = theTokenizer.Tokenize(line).Single(); Assert.AreEqual("send", token.Type); Assert.AreEqual("stuff", token.Value); } [Test] public void creates_echo_token() { const string line = "echo something"; var token = theTokenizer.Tokenize(line).Single(); Assert.AreEqual("echo", token.Type); Assert.AreEqual("something\n", token.Value); } [Test] public void creates_echo_empty_token() { const string line = "echo"; var token = theTokenizer.Tokenize(line).Single(); Assert.AreEqual("echo", token.Type); Assert.AreEqual("\n", token.Value); } [Test] public void creates_echo_empty_ignore_case_token() { const string line = "ECHO"; var token = theTokenizer.Tokenize(line).Single(); Assert.AreEqual("echo", token.Type); Assert.AreEqual("\n", token.Value); } [Test] public void creates_debuglevel_token() { const string line = "debuglevel 5"; var token = theTokenizer.Tokenize(line).Single(); Assert.AreEqual("debuglevel", token.Type); Assert.AreEqual("5", token.Value); } [Test] public void creates_parse_token() { const string line = "parse something"; var token = theTokenizer.Tokenize(line).Single(); Assert.AreEqual("parse", token.Type); Assert.AreEqual("something", token.Value); } [Test] public void creates_containsre_token() { const string line = "containsre something other"; var token = theTokenizer.Tokenize(line).Single(); Assert.AreEqual("containsre", token.Type); Assert.AreEqual("something other", token.Value); } [Test] public void creates_gosub_token() { const string line = "gosub label"; var token = theTokenizer.Tokenize(line).Single().As<GotoToken>(); Assert.AreEqual("gosub", token.Type); Assert.AreEqual("label", token.Value); Assert.AreEqual("label", token.Label); } [Test] public void creates_gosub_token_with_arguments() { const string line = "gosub label one two"; var token = theTokenizer.Tokenize(line).Single().As<GotoToken>(); Assert.AreEqual("gosub", token.Type); Assert.AreEqual("label one two", token.Value); Assert.AreEqual("label", token.Label); Assert.True(token.Args.SequenceEqual(new string[]{ "one", "two" })); } [Test] public void creates_gosub_token_with_quoted_arguments() { const string line = "gosub label one \"two three\" four \"five six\""; var token = theTokenizer.Tokenize(line).Single().As<GotoToken>(); Assert.AreEqual("gosub", token.Type); Assert.AreEqual("label one \"two three\" four \"five six\"", token.Value); Assert.AreEqual("label", token.Label); Assert.True(token.Args.SequenceEqual(new string[]{ "one", "two three", "four", "five six" })); } } }
/// This code was generated by /// \ / _ _ _| _ _ /// | (_)\/(_)(_|\/| |(/_ v1.0.0 /// / / /// <summary> /// PLEASE NOTE that this class contains beta products that are subject to change. Use them with caution. /// /// FaxMediaResource /// </summary> using Newtonsoft.Json; using System; using System.Collections.Generic; using Twilio.Base; using Twilio.Clients; using Twilio.Converters; using Twilio.Exceptions; using Twilio.Http; namespace Twilio.Rest.Fax.V1.Fax { public class FaxMediaResource : Resource { private static Request BuildFetchRequest(FetchFaxMediaOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Get, Rest.Domain.Fax, "/v1/Faxes/" + options.PathFaxSid + "/Media/" + options.PathSid + "", queryParams: options.GetParams(), headerParams: null ); } /// <summary> /// Fetch a specific fax media instance. /// </summary> /// <param name="options"> Fetch FaxMedia parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of FaxMedia </returns> public static FaxMediaResource Fetch(FetchFaxMediaOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildFetchRequest(options, client)); return FromJson(response.Content); } #if !NET35 /// <summary> /// Fetch a specific fax media instance. /// </summary> /// <param name="options"> Fetch FaxMedia parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of FaxMedia </returns> public static async System.Threading.Tasks.Task<FaxMediaResource> FetchAsync(FetchFaxMediaOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildFetchRequest(options, client)); return FromJson(response.Content); } #endif /// <summary> /// Fetch a specific fax media instance. /// </summary> /// <param name="pathFaxSid"> The SID of the fax with the FaxMedia resource to fetch </param> /// <param name="pathSid"> The unique string that identifies the resource to fetch </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of FaxMedia </returns> public static FaxMediaResource Fetch(string pathFaxSid, string pathSid, ITwilioRestClient client = null) { var options = new FetchFaxMediaOptions(pathFaxSid, pathSid); return Fetch(options, client); } #if !NET35 /// <summary> /// Fetch a specific fax media instance. /// </summary> /// <param name="pathFaxSid"> The SID of the fax with the FaxMedia resource to fetch </param> /// <param name="pathSid"> The unique string that identifies the resource to fetch </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of FaxMedia </returns> public static async System.Threading.Tasks.Task<FaxMediaResource> FetchAsync(string pathFaxSid, string pathSid, ITwilioRestClient client = null) { var options = new FetchFaxMediaOptions(pathFaxSid, pathSid); return await FetchAsync(options, client); } #endif private static Request BuildReadRequest(ReadFaxMediaOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Get, Rest.Domain.Fax, "/v1/Faxes/" + options.PathFaxSid + "/Media", queryParams: options.GetParams(), headerParams: null ); } /// <summary> /// Retrieve a list of all fax media instances for the specified fax. /// </summary> /// <param name="options"> Read FaxMedia parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of FaxMedia </returns> public static ResourceSet<FaxMediaResource> Read(ReadFaxMediaOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildReadRequest(options, client)); var page = Page<FaxMediaResource>.FromJson("media", response.Content); return new ResourceSet<FaxMediaResource>(page, options, client); } #if !NET35 /// <summary> /// Retrieve a list of all fax media instances for the specified fax. /// </summary> /// <param name="options"> Read FaxMedia parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of FaxMedia </returns> public static async System.Threading.Tasks.Task<ResourceSet<FaxMediaResource>> ReadAsync(ReadFaxMediaOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildReadRequest(options, client)); var page = Page<FaxMediaResource>.FromJson("media", response.Content); return new ResourceSet<FaxMediaResource>(page, options, client); } #endif /// <summary> /// Retrieve a list of all fax media instances for the specified fax. /// </summary> /// <param name="pathFaxSid"> The SID of the fax with the FaxMedia resources to read </param> /// <param name="pageSize"> Page size </param> /// <param name="limit"> Record limit </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of FaxMedia </returns> public static ResourceSet<FaxMediaResource> Read(string pathFaxSid, int? pageSize = null, long? limit = null, ITwilioRestClient client = null) { var options = new ReadFaxMediaOptions(pathFaxSid){PageSize = pageSize, Limit = limit}; return Read(options, client); } #if !NET35 /// <summary> /// Retrieve a list of all fax media instances for the specified fax. /// </summary> /// <param name="pathFaxSid"> The SID of the fax with the FaxMedia resources to read </param> /// <param name="pageSize"> Page size </param> /// <param name="limit"> Record limit </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of FaxMedia </returns> public static async System.Threading.Tasks.Task<ResourceSet<FaxMediaResource>> ReadAsync(string pathFaxSid, int? pageSize = null, long? limit = null, ITwilioRestClient client = null) { var options = new ReadFaxMediaOptions(pathFaxSid){PageSize = pageSize, Limit = limit}; return await ReadAsync(options, client); } #endif /// <summary> /// Fetch the target page of records /// </summary> /// <param name="targetUrl"> API-generated URL for the requested results page </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> The target page of records </returns> public static Page<FaxMediaResource> GetPage(string targetUrl, ITwilioRestClient client) { client = client ?? TwilioClient.GetRestClient(); var request = new Request( HttpMethod.Get, targetUrl ); var response = client.Request(request); return Page<FaxMediaResource>.FromJson("media", response.Content); } /// <summary> /// Fetch the next page of records /// </summary> /// <param name="page"> current page of records </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> The next page of records </returns> public static Page<FaxMediaResource> NextPage(Page<FaxMediaResource> page, ITwilioRestClient client) { var request = new Request( HttpMethod.Get, page.GetNextPageUrl(Rest.Domain.Fax) ); var response = client.Request(request); return Page<FaxMediaResource>.FromJson("media", response.Content); } /// <summary> /// Fetch the previous page of records /// </summary> /// <param name="page"> current page of records </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> The previous page of records </returns> public static Page<FaxMediaResource> PreviousPage(Page<FaxMediaResource> page, ITwilioRestClient client) { var request = new Request( HttpMethod.Get, page.GetPreviousPageUrl(Rest.Domain.Fax) ); var response = client.Request(request); return Page<FaxMediaResource>.FromJson("media", response.Content); } private static Request BuildDeleteRequest(DeleteFaxMediaOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Delete, Rest.Domain.Fax, "/v1/Faxes/" + options.PathFaxSid + "/Media/" + options.PathSid + "", queryParams: options.GetParams(), headerParams: null ); } /// <summary> /// Delete a specific fax media instance. /// </summary> /// <param name="options"> Delete FaxMedia parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of FaxMedia </returns> public static bool Delete(DeleteFaxMediaOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildDeleteRequest(options, client)); return response.StatusCode == System.Net.HttpStatusCode.NoContent; } #if !NET35 /// <summary> /// Delete a specific fax media instance. /// </summary> /// <param name="options"> Delete FaxMedia parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of FaxMedia </returns> public static async System.Threading.Tasks.Task<bool> DeleteAsync(DeleteFaxMediaOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildDeleteRequest(options, client)); return response.StatusCode == System.Net.HttpStatusCode.NoContent; } #endif /// <summary> /// Delete a specific fax media instance. /// </summary> /// <param name="pathFaxSid"> The SID of the fax with the FaxMedia resource to delete </param> /// <param name="pathSid"> The unique string that identifies the resource </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of FaxMedia </returns> public static bool Delete(string pathFaxSid, string pathSid, ITwilioRestClient client = null) { var options = new DeleteFaxMediaOptions(pathFaxSid, pathSid); return Delete(options, client); } #if !NET35 /// <summary> /// Delete a specific fax media instance. /// </summary> /// <param name="pathFaxSid"> The SID of the fax with the FaxMedia resource to delete </param> /// <param name="pathSid"> The unique string that identifies the resource </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of FaxMedia </returns> public static async System.Threading.Tasks.Task<bool> DeleteAsync(string pathFaxSid, string pathSid, ITwilioRestClient client = null) { var options = new DeleteFaxMediaOptions(pathFaxSid, pathSid); return await DeleteAsync(options, client); } #endif /// <summary> /// Converts a JSON string into a FaxMediaResource object /// </summary> /// <param name="json"> Raw JSON string </param> /// <returns> FaxMediaResource object represented by the provided JSON </returns> public static FaxMediaResource FromJson(string json) { // Convert all checked exceptions to Runtime try { return JsonConvert.DeserializeObject<FaxMediaResource>(json); } catch (JsonException e) { throw new ApiException(e.Message, e); } } /// <summary> /// The unique string that identifies the resource /// </summary> [JsonProperty("sid")] public string Sid { get; private set; } /// <summary> /// The SID of the Account that created the resource /// </summary> [JsonProperty("account_sid")] public string AccountSid { get; private set; } /// <summary> /// The SID of the fax the FaxMedia resource is associated with /// </summary> [JsonProperty("fax_sid")] public string FaxSid { get; private set; } /// <summary> /// The content type of the stored fax media /// </summary> [JsonProperty("content_type")] public string ContentType { get; private set; } /// <summary> /// The ISO 8601 date and time in GMT when the resource was created /// </summary> [JsonProperty("date_created")] public DateTime? DateCreated { get; private set; } /// <summary> /// The ISO 8601 date and time in GMT when the resource was last updated /// </summary> [JsonProperty("date_updated")] public DateTime? DateUpdated { get; private set; } /// <summary> /// The absolute URL of the FaxMedia resource /// </summary> [JsonProperty("url")] public Uri Url { get; private set; } private FaxMediaResource() { } } }
using System; using Lucene.Net.Documents; namespace Lucene.Net.Index { using NUnit.Framework; using Directory = Lucene.Net.Store.Directory; using Document = Documents.Document; using Field = Field; using LuceneTestCase = Lucene.Net.Util.LuceneTestCase; /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using MockAnalyzer = Lucene.Net.Analysis.MockAnalyzer; using MockDirectoryWrapper = Lucene.Net.Store.MockDirectoryWrapper; using NoLockFactory = Lucene.Net.Store.NoLockFactory; [TestFixture] public class TestCrash : LuceneTestCase { private IndexWriter InitIndex(Random random, bool initialCommit) { return InitIndex(random, NewMockDirectory(random), initialCommit); } private IndexWriter InitIndex(Random random, MockDirectoryWrapper dir, bool initialCommit) { dir.LockFactory = NoLockFactory.DoNoLockFactory; IndexWriter writer = new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random)).SetMaxBufferedDocs(10).SetMergeScheduler(new ConcurrentMergeScheduler())); ((ConcurrentMergeScheduler)writer.Config.MergeScheduler).SetSuppressExceptions(); if (initialCommit) { writer.Commit(); } Document doc = new Document(); doc.Add(NewTextField("content", "aaa", Field.Store.NO)); doc.Add(NewTextField("id", "0", Field.Store.NO)); for (int i = 0; i < 157; i++) { writer.AddDocument(doc); } return writer; } private void Crash(IndexWriter writer) { MockDirectoryWrapper dir = (MockDirectoryWrapper)writer.Directory; ConcurrentMergeScheduler cms = (ConcurrentMergeScheduler)writer.Config.MergeScheduler; cms.Sync(); dir.Crash(); cms.Sync(); dir.ClearCrash(); } [Test] public virtual void TestCrashWhileIndexing() { // this test relies on being able to open a reader before any commit // happened, so we must create an initial commit just to allow that, but // before any documents were added. IndexWriter writer = InitIndex(Random(), true); MockDirectoryWrapper dir = (MockDirectoryWrapper)writer.Directory; // We create leftover files because merging could be // running when we crash: dir.AssertNoUnrefencedFilesOnClose = false; Crash(writer); IndexReader reader = DirectoryReader.Open(dir); Assert.IsTrue(reader.NumDocs < 157); reader.Dispose(); // Make a new dir, copying from the crashed dir, and // open IW on it, to confirm IW "recovers" after a // crash: Directory dir2 = NewDirectory(dir); dir.Dispose(); (new RandomIndexWriter(Random(), dir2)).Dispose(); dir2.Dispose(); } [Test] public virtual void TestWriterAfterCrash() { // this test relies on being able to open a reader before any commit // happened, so we must create an initial commit just to allow that, but // before any documents were added. Console.WriteLine("TEST: initIndex"); IndexWriter writer = InitIndex(Random(), true); Console.WriteLine("TEST: done initIndex"); MockDirectoryWrapper dir = (MockDirectoryWrapper)writer.Directory; // We create leftover files because merging could be // running / store files could be open when we crash: dir.AssertNoUnrefencedFilesOnClose = false; dir.PreventDoubleWrite = false; Console.WriteLine("TEST: now crash"); Crash(writer); writer = InitIndex(Random(), dir, false); writer.Dispose(); IndexReader reader = DirectoryReader.Open(dir); Assert.IsTrue(reader.NumDocs < 314); reader.Dispose(); // Make a new dir, copying from the crashed dir, and // open IW on it, to confirm IW "recovers" after a // crash: Directory dir2 = NewDirectory(dir); dir.Dispose(); (new RandomIndexWriter(Random(), dir2)).Dispose(); dir2.Dispose(); } [Test] public virtual void TestCrashAfterReopen() { IndexWriter writer = InitIndex(Random(), false); MockDirectoryWrapper dir = (MockDirectoryWrapper)writer.Directory; // We create leftover files because merging could be // running when we crash: dir.AssertNoUnrefencedFilesOnClose = false; writer.Dispose(); writer = InitIndex(Random(), dir, false); Assert.AreEqual(314, writer.MaxDoc); Crash(writer); /* System.out.println("\n\nTEST: open reader"); String[] l = dir.list(); Arrays.sort(l); for(int i=0;i<l.Length;i++) System.out.println("file " + i + " = " + l[i] + " " + dir.FileLength(l[i]) + " bytes"); */ IndexReader reader = DirectoryReader.Open(dir); Assert.IsTrue(reader.NumDocs >= 157); reader.Dispose(); // Make a new dir, copying from the crashed dir, and // open IW on it, to confirm IW "recovers" after a // crash: Directory dir2 = NewDirectory(dir); dir.Dispose(); (new RandomIndexWriter(Random(), dir2)).Dispose(); dir2.Dispose(); } [Test] public virtual void TestCrashAfterClose() { IndexWriter writer = InitIndex(Random(), false); MockDirectoryWrapper dir = (MockDirectoryWrapper)writer.Directory; writer.Dispose(); dir.Crash(); /* String[] l = dir.list(); Arrays.sort(l); for(int i=0;i<l.Length;i++) System.out.println("file " + i + " = " + l[i] + " " + dir.FileLength(l[i]) + " bytes"); */ IndexReader reader = DirectoryReader.Open(dir); Assert.AreEqual(157, reader.NumDocs); reader.Dispose(); dir.Dispose(); } [Test] public virtual void TestCrashAfterCloseNoWait() { IndexWriter writer = InitIndex(Random(), false); MockDirectoryWrapper dir = (MockDirectoryWrapper)writer.Directory; writer.Dispose(false); dir.Crash(); /* String[] l = dir.list(); Arrays.sort(l); for(int i=0;i<l.Length;i++) System.out.println("file " + i + " = " + l[i] + " " + dir.FileLength(l[i]) + " bytes"); */ IndexReader reader = DirectoryReader.Open(dir); Assert.AreEqual(157, reader.NumDocs); reader.Dispose(); dir.Dispose(); } } }
//----------------------------------------------------------------------- // <copyright file="ClusterSingletonManagerLeaveSpec.cs" company="Akka.NET Project"> // Copyright (C) 2009-2016 Lightbend Inc. <http://www.lightbend.com> // Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net> // </copyright> //----------------------------------------------------------------------- using System; using System.Linq; using Akka.Actor; using Akka.Cluster.TestKit; using Akka.Cluster.Tools.Singleton; using Akka.Configuration; using Akka.Remote.TestKit; using FluentAssertions; namespace Akka.Cluster.Tools.Tests.MultiNode.Singleton { public class ClusterSingletonManagerLeaveSpecConfig : MultiNodeConfig { public RoleName First { get; } public RoleName Second { get; } public RoleName Third { get; } public ClusterSingletonManagerLeaveSpecConfig() { First = Role("first"); Second = Role("second"); Third = Role("third"); CommonConfig = ConfigurationFactory.ParseString(@" akka.loglevel = INFO akka.actor.provider = ""Akka.Cluster.ClusterActorRefProvider, Akka.Cluster"" akka.remote.log-remote-lifecycle-events = off akka.cluster.auto-down-unreachable-after = off ") .WithFallback(ClusterSingletonManager.DefaultConfig()) .WithFallback(ClusterSingletonProxy.DefaultConfig()) .WithFallback(MultiNodeClusterSpec.ClusterConfig()); } // The singleton actor public class Echo : ReceiveActor { private readonly IActorRef _testActorRef; public Echo(IActorRef testActorRef) { _testActorRef = testActorRef; Receive<string>(x => x.Equals("stop"), _ => { _testActorRef.Tell("stop"); Context.Stop(Self); }); ReceiveAny(x => Sender.Tell(Self)); } protected override void PreStart() { _testActorRef.Tell("preStart"); } protected override void PostStop() { _testActorRef.Tell("postStop"); } public static Props Props(IActorRef testActorRef) => Actor.Props.Create(() => new Echo(testActorRef)); } } public class ClusterSingletonManagerLeaveSpec : MultiNodeClusterSpec { private readonly ClusterSingletonManagerLeaveSpecConfig _config; private readonly Lazy<IActorRef> _echoProxy; protected override int InitialParticipantsValueFactory => Roles.Count; public ClusterSingletonManagerLeaveSpec() : this(new ClusterSingletonManagerLeaveSpecConfig()) { } protected ClusterSingletonManagerLeaveSpec(ClusterSingletonManagerLeaveSpecConfig config) : base(config, typeof(ClusterSingletonManagerLeaveSpec)) { _config = config; _echoProxy = new Lazy<IActorRef>(() => Watch(Sys.ActorOf(ClusterSingletonProxy.Props( singletonManagerPath: "/user/echo", settings: ClusterSingletonProxySettings.Create(Sys)), name: "echoProxy"))); } private void Join(RoleName from, RoleName to) { RunOn(() => { Cluster.Join(Node(to).Address); CreateSingleton(); }, from); } private IActorRef CreateSingleton() { return Sys.ActorOf(ClusterSingletonManager.Props( singletonProps: ClusterSingletonManagerLeaveSpecConfig.Echo.Props(TestActor), terminationMessage: "stop", settings: ClusterSingletonManagerSettings.Create(Sys)), name: "echo"); } [MultiNodeFact] public void ClusterSingletonManagerLeaveSpecs() { Leaving_ClusterSingletonManager_must_handover_to_new_instance(); } public void Leaving_ClusterSingletonManager_must_handover_to_new_instance() { Join(_config.First, _config.First); RunOn(() => { Within(5.Seconds(), () => { ExpectMsg("preStart"); _echoProxy.Value.Tell("hello"); ExpectMsg<IActorRef>(); }); }, _config.First); EnterBarrier("first-active"); Join(_config.Second, _config.First); RunOn(() => { Within(10.Seconds(), () => { AwaitAssert(() => Cluster.State.Members.Count(m => m.Status == MemberStatus.Up).Should().Be(2)); }); }, _config.First, _config.Second); EnterBarrier("second-up"); Join(_config.Third, _config.First); Within(10.Seconds(), () => { AwaitAssert(() => Cluster.State.Members.Count(m => m.Status == MemberStatus.Up).Should().Be(3)); }); EnterBarrier("all-up"); RunOn(() => { Cluster.Leave(Node(_config.First).Address); }, _config.Second); RunOn(() => { var t = TestActor; Cluster.RegisterOnMemberRemoved(() => t.Tell("MemberRemoved")); ExpectMsg("stop", 10.Seconds()); ExpectMsg("postStop"); // CoordinatedShutdown makes sure that singleton actors are // stopped before Cluster shutdown ExpectMsg("MemberRemoved"); }, _config.First); EnterBarrier("first-stopped"); RunOn(() => { ExpectMsg("preStart"); }, _config.Second); EnterBarrier("second-started"); RunOn(() => { var p = CreateTestProbe(); var firstAddress = Node(_config.First).Address; p.Within(15.Seconds(), () => { p.AwaitAssert(() => { _echoProxy.Value.Tell("hello2", p.Ref); p.ExpectMsg<IActorRef>(1.Seconds()).Path.Address.Should().NotBe(firstAddress); }); }); }, _config.Second, _config.Third); EnterBarrier("second-working"); RunOn(() => { var t = TestActor; Cluster.RegisterOnMemberRemoved(() => t.Tell("MemberRemoved")); Cluster.Leave(Node(_config.Second).Address); ExpectMsg("stop", 15.Seconds()); ExpectMsg("postStop"); ExpectMsg("MemberRemoved"); ExpectTerminated(_echoProxy.Value, TimeSpan.FromSeconds(10)); }, _config.Second); EnterBarrier("second-stopped"); RunOn(() => { ExpectMsg("preStart"); }, _config.Third); EnterBarrier("third-started"); RunOn(() => { var t = TestActor; Cluster.RegisterOnMemberRemoved(() => t.Tell("MemberRemoved")); Cluster.Leave(Node(_config.Third).Address); ExpectMsg("stop", 10.Seconds()); ExpectMsg("postStop"); ExpectMsg("MemberRemoved"); ExpectTerminated(_echoProxy.Value, TimeSpan.FromSeconds(10)); }, _config.Third); EnterBarrier("third-stopped"); } } }
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Linq; using Microsoft.AspNet.Razor.Generator; using Microsoft.AspNet.Razor.Parser.SyntaxTree; using Microsoft.AspNet.Razor.Text; using Microsoft.AspNet.Razor.Tokenizer.Symbols; namespace Microsoft.AspNet.Razor.Parser { public partial class CSharpCodeParser { private void SetUpKeywords() { MapKeywords(ConditionalBlock, CSharpKeyword.For, CSharpKeyword.Foreach, CSharpKeyword.While, CSharpKeyword.Switch, CSharpKeyword.Lock); MapKeywords(CaseStatement, false, CSharpKeyword.Case, CSharpKeyword.Default); MapKeywords(IfStatement, CSharpKeyword.If); MapKeywords(TryStatement, CSharpKeyword.Try); MapKeywords(UsingKeyword, CSharpKeyword.Using); MapKeywords(DoStatement, CSharpKeyword.Do); MapKeywords(ReservedDirective, CSharpKeyword.Namespace, CSharpKeyword.Class); } protected virtual void ReservedDirective(bool topLevel) { Context.OnError(CurrentLocation, string.Format(RazorResources.ParseError_ReservedWord, CurrentSymbol.Content)); AcceptAndMoveNext(); Span.EditHandler.AcceptedCharacters = AcceptedCharacters.None; Span.CodeGenerator = SpanCodeGenerator.Null; Context.CurrentBlock.Type = BlockType.Directive; CompleteBlock(); Output(SpanKind.MetaCode); } private void KeywordBlock(bool topLevel) { HandleKeyword(topLevel, () => { Context.CurrentBlock.Type = BlockType.Expression; Context.CurrentBlock.CodeGenerator = new ExpressionCodeGenerator(); ImplicitExpression(); }); } private void CaseStatement(bool topLevel) { Assert(CSharpSymbolType.Keyword); Debug.Assert(CurrentSymbol.Keyword != null && (CurrentSymbol.Keyword.Value == CSharpKeyword.Case || CurrentSymbol.Keyword.Value == CSharpKeyword.Default)); AcceptUntil(CSharpSymbolType.Colon); Optional(CSharpSymbolType.Colon); } private void DoStatement(bool topLevel) { Assert(CSharpKeyword.Do); UnconditionalBlock(); WhileClause(); if (topLevel) { CompleteBlock(); } } private void WhileClause() { Span.EditHandler.AcceptedCharacters = AcceptedCharacters.Any; IEnumerable<CSharpSymbol> ws = SkipToNextImportantToken(); if (At(CSharpKeyword.While)) { Accept(ws); Assert(CSharpKeyword.While); AcceptAndMoveNext(); AcceptWhile(IsSpacingToken(includeNewLines: true, includeComments: true)); if (AcceptCondition() && Optional(CSharpSymbolType.Semicolon)) { Span.EditHandler.AcceptedCharacters = AcceptedCharacters.None; } } else { PutCurrentBack(); PutBack(ws); } } private void UsingKeyword(bool topLevel) { Assert(CSharpKeyword.Using); Block block = new Block(CurrentSymbol); AcceptAndMoveNext(); AcceptWhile(IsSpacingToken(includeNewLines: false, includeComments: true)); if (At(CSharpSymbolType.LeftParenthesis)) { // using ( ==> Using Statement UsingStatement(block); } else if (At(CSharpSymbolType.Identifier)) { // using Identifier ==> Using Declaration if (!topLevel) { Context.OnError(block.Start, RazorResources.ParseError_NamespaceImportAndTypeAlias_Cannot_Exist_Within_CodeBlock); StandardStatement(); } else { UsingDeclaration(); } } if (topLevel) { CompleteBlock(); } } private void UsingDeclaration() { // Set block type to directive Context.CurrentBlock.Type = BlockType.Directive; // Parse a type name Assert(CSharpSymbolType.Identifier); NamespaceOrTypeName(); IEnumerable<CSharpSymbol> ws = ReadWhile(IsSpacingToken(includeNewLines: true, includeComments: true)); if (At(CSharpSymbolType.Assign)) { // Alias Accept(ws); Assert(CSharpSymbolType.Assign); AcceptAndMoveNext(); AcceptWhile(IsSpacingToken(includeNewLines: true, includeComments: true)); // One more namespace or type name NamespaceOrTypeName(); } else { PutCurrentBack(); PutBack(ws); } Span.EditHandler.AcceptedCharacters = AcceptedCharacters.AnyExceptNewline; Span.CodeGenerator = new AddImportCodeGenerator( Span.GetContent(syms => syms.Skip(1)), // Skip "using" SyntaxConstants.CSharp.UsingKeywordLength); // Optional ";" if (EnsureCurrent()) { Optional(CSharpSymbolType.Semicolon); } } protected bool NamespaceOrTypeName() { if (Optional(CSharpSymbolType.Identifier) || Optional(CSharpSymbolType.Keyword)) { Optional(CSharpSymbolType.QuestionMark); // Nullable if (Optional(CSharpSymbolType.DoubleColon)) { if (!Optional(CSharpSymbolType.Identifier)) { Optional(CSharpSymbolType.Keyword); } } if (At(CSharpSymbolType.LessThan)) { TypeArgumentList(); } if (Optional(CSharpSymbolType.Dot)) { NamespaceOrTypeName(); } while (At(CSharpSymbolType.LeftBracket)) { Balance(BalancingModes.None); Optional(CSharpSymbolType.RightBracket); } return true; } else { return false; } } private void TypeArgumentList() { Assert(CSharpSymbolType.LessThan); Balance(BalancingModes.None); Optional(CSharpSymbolType.GreaterThan); } private void UsingStatement(Block block) { Assert(CSharpSymbolType.LeftParenthesis); // Parse condition if (AcceptCondition()) { AcceptWhile(IsSpacingToken(includeNewLines: true, includeComments: true)); // Parse code block ExpectCodeBlock(block); } } private void TryStatement(bool topLevel) { Assert(CSharpKeyword.Try); UnconditionalBlock(); AfterTryClause(); if (topLevel) { CompleteBlock(); } } private void IfStatement(bool topLevel) { Assert(CSharpKeyword.If); ConditionalBlock(topLevel: false); AfterIfClause(); if (topLevel) { CompleteBlock(); } } private void AfterTryClause() { // Grab whitespace IEnumerable<CSharpSymbol> ws = SkipToNextImportantToken(); // Check for a catch or finally part if (At(CSharpKeyword.Catch)) { Accept(ws); Assert(CSharpKeyword.Catch); ConditionalBlock(topLevel: false); AfterTryClause(); } else if (At(CSharpKeyword.Finally)) { Accept(ws); Assert(CSharpKeyword.Finally); UnconditionalBlock(); } else { // Return whitespace and end the block PutCurrentBack(); PutBack(ws); Span.EditHandler.AcceptedCharacters = AcceptedCharacters.Any; } } private void AfterIfClause() { // Grab whitespace and razor comments IEnumerable<CSharpSymbol> ws = SkipToNextImportantToken(); // Check for an else part if (At(CSharpKeyword.Else)) { Accept(ws); Assert(CSharpKeyword.Else); ElseClause(); } else { // No else, return whitespace PutCurrentBack(); PutBack(ws); Span.EditHandler.AcceptedCharacters = AcceptedCharacters.Any; } } private void ElseClause() { if (!At(CSharpKeyword.Else)) { return; } Block block = new Block(CurrentSymbol); AcceptAndMoveNext(); AcceptWhile(IsSpacingToken(includeNewLines: true, includeComments: true)); if (At(CSharpKeyword.If)) { // ElseIf block.Name = SyntaxConstants.CSharp.ElseIfKeyword; ConditionalBlock(block); AfterIfClause(); } else if (!EndOfFile) { // Else ExpectCodeBlock(block); } } private void ExpectCodeBlock(Block block) { if (!EndOfFile) { // Check for "{" to make sure we're at a block if (!At(CSharpSymbolType.LeftBrace)) { Context.OnError(CurrentLocation, string.Format(RazorResources.ParseError_SingleLine_ControlFlowStatements_Not_Allowed, Language.GetSample(CSharpSymbolType.LeftBrace), CurrentSymbol.Content)); } // Parse the statement and then we're done Statement(block); } } private void UnconditionalBlock() { Assert(CSharpSymbolType.Keyword); Block block = new Block(CurrentSymbol); AcceptAndMoveNext(); AcceptWhile(IsSpacingToken(includeNewLines: true, includeComments: true)); ExpectCodeBlock(block); } private void ConditionalBlock(bool topLevel) { Assert(CSharpSymbolType.Keyword); Block block = new Block(CurrentSymbol); ConditionalBlock(block); if (topLevel) { CompleteBlock(); } } private void ConditionalBlock(Block block) { AcceptAndMoveNext(); AcceptWhile(IsSpacingToken(includeNewLines: true, includeComments: true)); // Parse the condition, if present (if not present, we'll let the C# compiler complain) if (AcceptCondition()) { AcceptWhile(IsSpacingToken(includeNewLines: true, includeComments: true)); ExpectCodeBlock(block); } } private bool AcceptCondition() { if (At(CSharpSymbolType.LeftParenthesis)) { bool complete = Balance(BalancingModes.BacktrackOnFailure | BalancingModes.AllowCommentsAndTemplates); if (!complete) { AcceptUntil(CSharpSymbolType.NewLine); } else { Optional(CSharpSymbolType.RightParenthesis); } return complete; } return true; } private void Statement() { Statement(null); } private void Statement(Block block) { Span.EditHandler.AcceptedCharacters = AcceptedCharacters.Any; // Accept whitespace but always keep the last whitespace node so we can put it back if necessary CSharpSymbol lastWs = AcceptWhiteSpaceInLines(); Debug.Assert(lastWs == null || (lastWs.Start.AbsoluteIndex + lastWs.Content.Length == CurrentLocation.AbsoluteIndex)); if (EndOfFile) { if (lastWs != null) { Accept(lastWs); } return; } CSharpSymbolType type = CurrentSymbol.Type; SourceLocation loc = CurrentLocation; bool isSingleLineMarkup = type == CSharpSymbolType.Transition && NextIs(CSharpSymbolType.Colon); bool isMarkup = isSingleLineMarkup || type == CSharpSymbolType.LessThan || (type == CSharpSymbolType.Transition && NextIs(CSharpSymbolType.LessThan)); if (Context.DesignTimeMode || !isMarkup) { // CODE owns whitespace, MARKUP owns it ONLY in DesignTimeMode. if (lastWs != null) { Accept(lastWs); } } else { // MARKUP owns whitespace EXCEPT in DesignTimeMode. PutCurrentBack(); PutBack(lastWs); } if (isMarkup) { if (type == CSharpSymbolType.Transition && !isSingleLineMarkup) { Context.OnError(loc, RazorResources.ParseError_AtInCode_Must_Be_Followed_By_Colon_Paren_Or_Identifier_Start); } // Markup block Output(SpanKind.Code); if (Context.DesignTimeMode && CurrentSymbol != null && (CurrentSymbol.Type == CSharpSymbolType.LessThan || CurrentSymbol.Type == CSharpSymbolType.Transition)) { PutCurrentBack(); } OtherParserBlock(); } else { // What kind of statement is this? HandleStatement(block, type); } } private void HandleStatement(Block block, CSharpSymbolType type) { switch (type) { case CSharpSymbolType.RazorCommentTransition: Output(SpanKind.Code); RazorComment(); Statement(block); break; case CSharpSymbolType.LeftBrace: // Verbatim Block block = block ?? new Block(RazorResources.BlockName_Code, CurrentLocation); AcceptAndMoveNext(); CodeBlock(block); break; case CSharpSymbolType.Keyword: // Keyword block HandleKeyword(false, StandardStatement); break; case CSharpSymbolType.Transition: // Embedded Expression block EmbeddedExpression(); break; case CSharpSymbolType.RightBrace: // Possible end of Code Block, just run the continuation break; case CSharpSymbolType.Comment: AcceptAndMoveNext(); break; default: // Other statement StandardStatement(); break; } } private void EmbeddedExpression() { // First, verify the type of the block Assert(CSharpSymbolType.Transition); CSharpSymbol transition = CurrentSymbol; NextToken(); if (At(CSharpSymbolType.Transition)) { // Escaped "@" Output(SpanKind.Code); // Output "@" as hidden span Accept(transition); Span.CodeGenerator = SpanCodeGenerator.Null; Output(SpanKind.Code); Assert(CSharpSymbolType.Transition); AcceptAndMoveNext(); StandardStatement(); } else { // Throw errors as necessary, but continue parsing if (At(CSharpSymbolType.LeftBrace)) { Context.OnError(CurrentLocation, RazorResources.ParseError_Unexpected_Nested_CodeBlock); } // @( or @foo - Nested expression, parse a child block PutCurrentBack(); PutBack(transition); // Before exiting, add a marker span if necessary AddMarkerSymbolIfNecessary(); NestedBlock(); } } private void StandardStatement() { while (!EndOfFile) { int bookmark = CurrentLocation.AbsoluteIndex; IEnumerable<CSharpSymbol> read = ReadWhile(sym => sym.Type != CSharpSymbolType.Semicolon && sym.Type != CSharpSymbolType.RazorCommentTransition && sym.Type != CSharpSymbolType.Transition && sym.Type != CSharpSymbolType.LeftBrace && sym.Type != CSharpSymbolType.LeftParenthesis && sym.Type != CSharpSymbolType.LeftBracket && sym.Type != CSharpSymbolType.RightBrace); if (At(CSharpSymbolType.LeftBrace) || At(CSharpSymbolType.LeftParenthesis) || At(CSharpSymbolType.LeftBracket)) { Accept(read); if (Balance(BalancingModes.AllowCommentsAndTemplates | BalancingModes.BacktrackOnFailure)) { Optional(CSharpSymbolType.RightBrace); } else { // Recovery AcceptUntil(CSharpSymbolType.LessThan, CSharpSymbolType.RightBrace); return; } } else if (At(CSharpSymbolType.Transition) && (NextIs(CSharpSymbolType.LessThan, CSharpSymbolType.Colon))) { Accept(read); Output(SpanKind.Code); Template(); } else if (At(CSharpSymbolType.RazorCommentTransition)) { Accept(read); RazorComment(); } else if (At(CSharpSymbolType.Semicolon)) { Accept(read); AcceptAndMoveNext(); return; } else if (At(CSharpSymbolType.RightBrace)) { Accept(read); return; } else { Context.Source.Position = bookmark; NextToken(); AcceptUntil(CSharpSymbolType.LessThan, CSharpSymbolType.RightBrace); return; } } } private void CodeBlock(Block block) { CodeBlock(true, block); } private void CodeBlock(bool acceptTerminatingBrace, Block block) { EnsureCurrent(); while (!EndOfFile && !At(CSharpSymbolType.RightBrace)) { // Parse a statement, then return here Statement(); EnsureCurrent(); } if (EndOfFile) { Context.OnError(block.Start, string.Format(RazorResources.ParseError_Expected_EndOfBlock_Before_EOF, block.Name, '}', '{')); } else if (acceptTerminatingBrace) { Assert(CSharpSymbolType.RightBrace); Span.EditHandler.AcceptedCharacters = AcceptedCharacters.None; AcceptAndMoveNext(); } } private void HandleKeyword(bool topLevel, Action fallback) { Debug.Assert(CurrentSymbol.Type == CSharpSymbolType.Keyword && CurrentSymbol.Keyword != null); Action<bool> handler; if (_keywordParsers.TryGetValue(CurrentSymbol.Keyword.Value, out handler)) { handler(topLevel); } else { fallback(); } } private IEnumerable<CSharpSymbol> SkipToNextImportantToken() { while (!EndOfFile) { IEnumerable<CSharpSymbol> ws = ReadWhile(IsSpacingToken(includeNewLines: true, includeComments: true)); if (At(CSharpSymbolType.RazorCommentTransition)) { Accept(ws); Span.EditHandler.AcceptedCharacters = AcceptedCharacters.Any; RazorComment(); } else { return ws; } } return Enumerable.Empty<CSharpSymbol>(); } // Common code for Parsers, but FxCop REALLY doesn't like it in the base class.. moving it here for now. protected override void OutputSpanBeforeRazorComment() { AddMarkerSymbolIfNecessary(); Output(SpanKind.Code); } protected class Block { public Block(string name, SourceLocation start) { Name = name; Start = start; } public Block(CSharpSymbol symbol) : this(GetName(symbol), symbol.Start) { } public string Name { get; set; } public SourceLocation Start { get; set; } private static string GetName(CSharpSymbol sym) { if (sym.Type == CSharpSymbolType.Keyword) { return CSharpLanguageCharacteristics.GetKeyword(sym.Keyword.Value); } return sym.Content; } } } }
using System.Collections.Generic; using System.Configuration; using System.IO; using System.Text; namespace Codentia.Common.Helper { /// <summary> /// Helper Methods for Sites /// </summary> public static class SiteHelper { private static string _siteEnvironment = ConfigurationManager.AppSettings["SiteEnvironment"]; /// <summary> /// Gets the site environment. /// </summary> /// <value>The site environment.</value> public static string SiteEnvironment { get { string environment; if (_siteEnvironment == null) { _siteEnvironment = string.Empty; } switch (_siteEnvironment.ToUpper()) { case "DEV": environment = "DEV"; break; case "TEST": environment = "TEST"; break; case "UAT": environment = "UAT"; break; case "LIVE": case "DEMO": environment = "LIVE"; break; default: environment = "DEV"; break; } return environment; } } /// <summary> /// Gets the payment environment. /// </summary> /// <value>The payment environment.</value> public static string PaymentEnvironment { get { string environment; if (_siteEnvironment == null) { _siteEnvironment = string.Empty; } switch (_siteEnvironment.ToUpper()) { case "DEV": environment = "DEV"; break; case "TEST": environment = "TEST"; break; case "UAT": environment = "UAT"; break; case "LIVE": environment = "LIVE"; break; case "DEMO": environment = "DEMO"; break; default: environment = "DEV"; break; } return environment; } } /// <summary> /// Sets the base environment. /// </summary> /// <value>The base environment.</value> public static string BaseEnvironment { set { _siteEnvironment = value; } } /// <summary> /// Builds the site map. /// </summary> /// <param name="baseUrl">The base URL.</param> /// <param name="basePath">The base path.</param> /// <param name="startPath">The start path.</param> /// <param name="extensions">The extensions.</param> /// <param name="fileExclusions">The file exclusions.</param> /// <param name="directoryExclusions">The directory exclusions.</param> /// <returns>string of sitemap</returns> public static string BuildSiteMap(string baseUrl, string basePath, string startPath, string[] extensions, string[] fileExclusions, string[] directoryExclusions) { StringBuilder output = new StringBuilder(); output.Append("<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">"); SiteHelper.BuildSiteMapRecursive(output, baseUrl, basePath, startPath, extensions, fileExclusions, directoryExclusions); output.Append("</urlset>"); return output.ToString(); } /// <summary> /// Builds the site map recursively. /// </summary> /// <param name="output">The output.</param> /// <param name="baseUrl">The base URL.</param> /// <param name="basePath">The base path.</param> /// <param name="startPath">The start path.</param> /// <param name="extensions">The extensions.</param> /// <param name="fileExclusions">The file exclusions.</param> /// <param name="directoryExclusions">The directory exclusions.</param> private static void BuildSiteMapRecursive(StringBuilder output, string baseUrl, string basePath, string startPath, string[] extensions, string[] fileExclusions, string[] directoryExclusions) { // output all files in base path that match the given pattern (aspx, html) List<string> fileList = new List<string>(); for (int i = 0; i < extensions.Length; i++) { string[] newFiles = System.IO.Directory.GetFiles(startPath, extensions[i]); fileList.AddRange(newFiles); } string[] files = fileList.ToArray(); string displayPath = startPath.Replace(basePath, string.Empty); if (!displayPath.EndsWith("/")) { displayPath = string.Format("{0}/", displayPath); } // handle separators displayPath = displayPath.Replace("\\", "/"); for (int i = 0; i < files.Length; i++) { string name = Path.GetFileName(files[i]); string modified = File.GetLastWriteTime(files[i]).ToString("yyyy-MM-dd"); // check exclusions bool excluded = false; for (int j = 0; j < fileExclusions.Length && !excluded; j++) { excluded = name.ToLower().Contains(fileExclusions[j].ToLower()); } if (!excluded) { string entry = string.Format("<url><loc>{0}{1}{2}</loc><lastmod>{3}</lastmod></url>", baseUrl, displayPath, name, modified); entry = entry.Replace("//", "/"); entry = entry.Replace("\\", string.Empty); entry = entry.Replace(":/", "://"); output.Append(entry); } } // then do the same in all sub folders, excluding user string[] folders = System.IO.Directory.GetDirectories(startPath); for (int i = 0; i < folders.Length; i++) { bool excluded = false; for (int j = 0; j < directoryExclusions.Length && !excluded; j++) { if (folders[i].ToLower().EndsWith(string.Format("{0}{1}", Path.DirectorySeparatorChar, directoryExclusions[j].ToLower()))) { excluded = true; } } if (!excluded) { BuildSiteMapRecursive(output, baseUrl, basePath, folders[i], extensions, fileExclusions, directoryExclusions); } } } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.ApiManagement { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Rest; using Microsoft.Rest.Azure; using Microsoft.Rest.Azure.OData; using Models; using System.Threading; using System.Threading.Tasks; /// <summary> /// Extension methods for UserOperations. /// </summary> public static partial class UserOperationsExtensions { /// <summary> /// Lists a collection of registered users in the specified service instance. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='serviceName'> /// The name of the API Management service. /// </param> /// <param name='odataQuery'> /// OData parameters to apply to the operation. /// </param> public static IPage<UserContract> ListByService(this IUserOperations operations, string resourceGroupName, string serviceName, ODataQuery<UserContract> odataQuery = default(ODataQuery<UserContract>)) { return ((IUserOperations)operations).ListByServiceAsync(resourceGroupName, serviceName, odataQuery).GetAwaiter().GetResult(); } /// <summary> /// Lists a collection of registered users in the specified service instance. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='serviceName'> /// The name of the API Management service. /// </param> /// <param name='odataQuery'> /// OData parameters to apply to the operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<UserContract>> ListByServiceAsync(this IUserOperations operations, string resourceGroupName, string serviceName, ODataQuery<UserContract> odataQuery = default(ODataQuery<UserContract>), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListByServiceWithHttpMessagesAsync(resourceGroupName, serviceName, odataQuery, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets the details of the user specified by its identifier. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='serviceName'> /// The name of the API Management service. /// </param> /// <param name='uid'> /// User identifier. Must be unique in the current API Management service /// instance. /// </param> public static UserContract Get(this IUserOperations operations, string resourceGroupName, string serviceName, string uid) { return operations.GetAsync(resourceGroupName, serviceName, uid).GetAwaiter().GetResult(); } /// <summary> /// Gets the details of the user specified by its identifier. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='serviceName'> /// The name of the API Management service. /// </param> /// <param name='uid'> /// User identifier. Must be unique in the current API Management service /// instance. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<UserContract> GetAsync(this IUserOperations operations, string resourceGroupName, string serviceName, string uid, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, serviceName, uid, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Creates or Updates a user. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='serviceName'> /// The name of the API Management service. /// </param> /// <param name='uid'> /// User identifier. Must be unique in the current API Management service /// instance. /// </param> /// <param name='parameters'> /// Create or update parameters. /// </param> public static UserContract CreateOrUpdate(this IUserOperations operations, string resourceGroupName, string serviceName, string uid, UserCreateParameters parameters) { return operations.CreateOrUpdateAsync(resourceGroupName, serviceName, uid, parameters).GetAwaiter().GetResult(); } /// <summary> /// Creates or Updates a user. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='serviceName'> /// The name of the API Management service. /// </param> /// <param name='uid'> /// User identifier. Must be unique in the current API Management service /// instance. /// </param> /// <param name='parameters'> /// Create or update parameters. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<UserContract> CreateOrUpdateAsync(this IUserOperations operations, string resourceGroupName, string serviceName, string uid, UserCreateParameters parameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, serviceName, uid, parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Updates the details of the user specified by its identifier. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='serviceName'> /// The name of the API Management service. /// </param> /// <param name='uid'> /// User identifier. Must be unique in the current API Management service /// instance. /// </param> /// <param name='parameters'> /// Update parameters. /// </param> /// <param name='ifMatch'> /// The entity state (Etag) version of the user to update. A value of "*" can /// be used for If-Match to unconditionally apply the operation. /// </param> public static ErrorResponse Update(this IUserOperations operations, string resourceGroupName, string serviceName, string uid, UserUpdateParameters parameters, string ifMatch) { return operations.UpdateAsync(resourceGroupName, serviceName, uid, parameters, ifMatch).GetAwaiter().GetResult(); } /// <summary> /// Updates the details of the user specified by its identifier. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='serviceName'> /// The name of the API Management service. /// </param> /// <param name='uid'> /// User identifier. Must be unique in the current API Management service /// instance. /// </param> /// <param name='parameters'> /// Update parameters. /// </param> /// <param name='ifMatch'> /// The entity state (Etag) version of the user to update. A value of "*" can /// be used for If-Match to unconditionally apply the operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<ErrorResponse> UpdateAsync(this IUserOperations operations, string resourceGroupName, string serviceName, string uid, UserUpdateParameters parameters, string ifMatch, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.UpdateWithHttpMessagesAsync(resourceGroupName, serviceName, uid, parameters, ifMatch, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Deletes specific user. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='serviceName'> /// The name of the API Management service. /// </param> /// <param name='uid'> /// User identifier. Must be unique in the current API Management service /// instance. /// </param> /// <param name='ifMatch'> /// The entity state (Etag) version of the user to delete. A value of "*" can /// be used for If-Match to unconditionally apply the operation. /// </param> /// <param name='deleteSubscriptions'> /// Whether to delete user's subscription or not. /// </param> public static void Delete(this IUserOperations operations, string resourceGroupName, string serviceName, string uid, string ifMatch, bool? deleteSubscriptions = default(bool?)) { operations.DeleteAsync(resourceGroupName, serviceName, uid, ifMatch, deleteSubscriptions).GetAwaiter().GetResult(); } /// <summary> /// Deletes specific user. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='serviceName'> /// The name of the API Management service. /// </param> /// <param name='uid'> /// User identifier. Must be unique in the current API Management service /// instance. /// </param> /// <param name='ifMatch'> /// The entity state (Etag) version of the user to delete. A value of "*" can /// be used for If-Match to unconditionally apply the operation. /// </param> /// <param name='deleteSubscriptions'> /// Whether to delete user's subscription or not. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task DeleteAsync(this IUserOperations operations, string resourceGroupName, string serviceName, string uid, string ifMatch, bool? deleteSubscriptions = default(bool?), CancellationToken cancellationToken = default(CancellationToken)) { (await operations.DeleteWithHttpMessagesAsync(resourceGroupName, serviceName, uid, ifMatch, deleteSubscriptions, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Retrieves a redirection URL containing an authentication token for signing /// a given user into the developer portal. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='serviceName'> /// The name of the API Management service. /// </param> /// <param name='uid'> /// User identifier. Must be unique in the current API Management service /// instance. /// </param> public static GenerateSsoUrlResult GenerateSsoUrl(this IUserOperations operations, string resourceGroupName, string serviceName, string uid) { return operations.GenerateSsoUrlAsync(resourceGroupName, serviceName, uid).GetAwaiter().GetResult(); } /// <summary> /// Retrieves a redirection URL containing an authentication token for signing /// a given user into the developer portal. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='serviceName'> /// The name of the API Management service. /// </param> /// <param name='uid'> /// User identifier. Must be unique in the current API Management service /// instance. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<GenerateSsoUrlResult> GenerateSsoUrlAsync(this IUserOperations operations, string resourceGroupName, string serviceName, string uid, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GenerateSsoUrlWithHttpMessagesAsync(resourceGroupName, serviceName, uid, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets the Shared Access Authorization Token for the User. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='serviceName'> /// The name of the API Management service. /// </param> /// <param name='uid'> /// User identifier. Must be unique in the current API Management service /// instance. /// </param> /// <param name='parameters'> /// Create Authorization Token parameters. /// </param> public static UserTokenResult GetSharedAccessToken(this IUserOperations operations, string resourceGroupName, string serviceName, string uid, UserTokenParameters parameters) { return operations.GetSharedAccessTokenAsync(resourceGroupName, serviceName, uid, parameters).GetAwaiter().GetResult(); } /// <summary> /// Gets the Shared Access Authorization Token for the User. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='serviceName'> /// The name of the API Management service. /// </param> /// <param name='uid'> /// User identifier. Must be unique in the current API Management service /// instance. /// </param> /// <param name='parameters'> /// Create Authorization Token parameters. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<UserTokenResult> GetSharedAccessTokenAsync(this IUserOperations operations, string resourceGroupName, string serviceName, string uid, UserTokenParameters parameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetSharedAccessTokenWithHttpMessagesAsync(resourceGroupName, serviceName, uid, parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Lists a collection of registered users in the specified service instance. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> public static IPage<UserContract> ListByServiceNext(this IUserOperations operations, string nextPageLink) { return operations.ListByServiceNextAsync(nextPageLink).GetAwaiter().GetResult(); } /// <summary> /// Lists a collection of registered users in the specified service instance. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<UserContract>> ListByServiceNextAsync(this IUserOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListByServiceNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Extensions.Options; using Orleans.Configuration; using Orleans.Runtime.Configuration; namespace Orleans.Runtime { /* Example of printout in logs: StageAnalysis= Stage: Runtime.IncomingMessageAgent.Application Measured average CPU per request: 0.067 ms Measured average Wall-clock per request: 0.068 ms Measured number of requests: 1777325 requests Estimated wait time: 0.000 ms Suggested thread allocation: 2 threads (rounded up from 1.136) Stage: Scheduler.WorkerPoolThread Measured average CPU per request: 0.153 ms Measured average Wall-clock per request: 0.160 ms Measured number of requests: 4404680 requests Estimated wait time: 0.000 ms Suggested thread allocation: 7 threads (rounded up from 6.386) Stage: Runtime.Messaging.GatewaySender.GatewaySiloSender Measured average CPU per request: 0.152 ms Measured average Wall-clock per request: 0.155 ms Measured number of requests: 92428 requests Estimated wait time: 0.000 ms Suggested thread allocation: 1 threads (rounded up from 0.133) Stage: Runtime.Messaging.SiloMessageSender.AppMsgsSender Measured average CPU per request: 0.034 ms Measured average Wall-clock per request: 0.125 ms Measured number of requests: 1815072 requests Estimated wait time: 0.089 ms Suggested thread allocation: 2 threads (rounded up from 1.765) CPU usage by thread type: 0.415, Untracked 0.359, Scheduler.WorkerPoolThread 0.072, Untracked.ThreadPoolThread 0.064, Runtime.IncomingMessageAgent.Application 0.049, ThreadPoolThread 0.033, Runtime.Messaging.SiloMessageSender.AppMsgsSender 0.008, Runtime.Messaging.GatewaySender.GatewaySiloSender 0.000, Scheduler.WorkerPoolThread.System 0.000, Runtime.Messaging.SiloMessageSender.SystemSender 0.000, Runtime.IncomingMessageAgent.System 0.000, Runtime.Messaging.SiloMessageSender.PingSender 0.000, Runtime.IncomingMessageAgent.Ping EndStageAnalysis */ /// <summary> /// Stage analysis, one instance should exist in each Silo /// </summary> internal class StageAnalysisStatisticsGroup { private readonly double stableReadyTimeProportion; private readonly Dictionary<string, List<ThreadTrackingStatistic>> stageGroups; public StageAnalysisStatisticsGroup(IOptions<StatisticsOptions> statisticsOptions) { // Load test experiments suggested these parameter values stableReadyTimeProportion = 0.3; stageGroups = new Dictionary<string, List<ThreadTrackingStatistic>>(); this.PerformStageAnalysis = statisticsOptions.Value.CollectionLevel.PerformStageAnalysis(); if (this.PerformStageAnalysis) { StringValueStatistic.FindOrCreate(StatisticNames.STAGE_ANALYSIS, StageAnalysisInfo); } } public bool PerformStageAnalysis { get; } public void AddTracking(ThreadTrackingStatistic tts) { lock (stageGroups) { // we trim all thread numbers from thread name, so allow to group them. char[] toTrim = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '/', '_', '.' }; string stageName = tts.Name.Trim(toTrim); List<ThreadTrackingStatistic> stageGroup; if (!stageGroups.TryGetValue(stageName, out stageGroup)) { stageGroup = new List<ThreadTrackingStatistic>(); stageGroups.Add(stageName, stageGroup); } stageGroup.Add(tts); } } // the interesting stages to print in stage analysis private static readonly List<string> stages = new List<string>() { "Runtime.IncomingMessageAgent.Application", "Scheduler.WorkerPoolThread", "Runtime.Messaging.GatewaySender.GatewaySiloSender", "Runtime.Messaging.SiloMessageSender.AppMsgsSender" }; // stages where wait time is expected to be nonzero private static readonly HashSet<string> waitingStages = new HashSet<string>() { //stages[1], // if we know there is no waiting in the WorkerPoolThreads, we can remove it from waitingStages and get more accuarte measurements stages[2], stages[3] }; private static readonly string firstStage = stages[0]; private string StageAnalysisInfo() { try { lock (stageGroups) { double cores = Environment.ProcessorCount; Dictionary<string, double> cpuPerRequest = new Dictionary<string, double>(); // CPU time per request for each stage Dictionary<string, double> wallClockPerRequest = new Dictionary<string, double>(); // Wallclock time per request for each stage Dictionary<string, double> numberOfRequests = new Dictionary<string, double>(); // Number of requests for each stage foreach (var keyVal in stageGroups) { string name = keyVal.Key; if (GetNumberOfRequests(name) > 0) { cpuPerRequest.Add(name, GetCpuPerStagePerRequest(name)); wallClockPerRequest.Add(name, GetWallClockPerStagePerRequest(name)); numberOfRequests.Add(name, GetNumberOfRequests(name)); } } cpuPerRequest.Add("Untracked.ThreadPoolThread", GetCpuPerStagePerRequest("Untracked.ThreadPoolThread")); numberOfRequests.Add("Untracked.ThreadPoolThread", GetNumberOfRequests("Untracked.ThreadPoolThread")); double elapsedWallClock = GetMaxWallClock(); double elapsedCPUClock = GetTotalCPU(); // Idle time estimation double untrackedProportionTime = 1 - elapsedCPUClock / (cores * elapsedWallClock); // Ratio of wall clock per cpu time calculation double sum = 0; double num = 0; foreach (var stage in wallClockPerRequest.Keys) { if (!waitingStages.Contains(stage)) { double ratio = wallClockPerRequest[stage] / cpuPerRequest[stage] - 1; sum += ratio * numberOfRequests[stage]; num += numberOfRequests[stage]; } } double avgRatio = sum / num; // Wait time estimation - implementation of strategy 2 from the "local-throughput.pdf" "Coping with Practical Measurements". var waitTimes = new Dictionary<string, double>(); // Wait time per request for each stage foreach (var stage in wallClockPerRequest.Keys) { waitTimes.Add(stage, waitingStages.Contains(stage) ? Math.Max(wallClockPerRequest[stage] - avgRatio*cpuPerRequest[stage] - cpuPerRequest[stage], 0) : 0); } // CPU sum for denominator of final equation double cpuSum = 0; foreach (var stage in cpuPerRequest.Keys) { cpuSum += cpuPerRequest[stage] * numberOfRequests[stage]; } // beta and lambda values var beta = new Dictionary<string, double>(); var s = new Dictionary<string, double>(); var lambda = new Dictionary<string, double>(); foreach (var stage in wallClockPerRequest.Keys) { beta.Add(stage, cpuPerRequest[stage] / (cpuPerRequest[stage] + waitTimes[stage])); s.Add(stage, 1000.0 / (cpuPerRequest[stage] + waitTimes[stage])); lambda.Add(stage, 1000.0 * numberOfRequests[stage] / elapsedWallClock); } // Final equation thread allocation - implementation of theorem 2 from the "local-throughput.pdf" "Incorporating Ready Time". var throughputThreadAllocation = new Dictionary<string, double>(); // Thread allocation suggestion for each stage foreach (var stage in wallClockPerRequest.Keys) { // cores is p // numberOfRequests is q // cpuPerRequest is x // stableReadyTimeProportion is alpha // waitTimes is w throughputThreadAllocation.Add(stage, cores * numberOfRequests[stage] * (cpuPerRequest[stage] * (1 + stableReadyTimeProportion) + waitTimes[stage]) / cpuSum); } double sum1 = 0; foreach (var stage in s.Keys) sum1 += lambda[stage]*beta[stage]/s[stage]; double sum2 = 0; foreach (var stage in s.Keys) sum2 += Math.Sqrt(lambda[stage]*beta[stage]/s[stage]); var latencyThreadAllocation = new Dictionary<string, double>(); // Latency thread allocation suggestion for each stage foreach (var stage in wallClockPerRequest.Keys) latencyThreadAllocation.Add(stage, lambda[stage]/s[stage] + Math.Sqrt(lambda[stage])*(cores - sum1)/(Math.Sqrt(s[stage]*beta[stage])*sum2)); var latencyPenalizedThreadAllocationConst = new Dictionary<string, double>(); var latencyPenalizedThreadAllocationCoef = new Dictionary<string, double>(); foreach (var stage in wallClockPerRequest.Keys) { latencyPenalizedThreadAllocationConst.Add(stage, lambda[stage] / s[stage]); latencyPenalizedThreadAllocationCoef.Add(stage, Math.Sqrt(lambda[stage] / (lambda[firstStage] * s[stage]))); } double sum3 = 0; foreach (var stage in s.Keys) sum3 += beta[stage]*Math.Sqrt(lambda[stage]/s[stage]); double zeta = Math.Pow(sum3 / (cores - sum1), 2) / lambda[firstStage]; var sb = new StringBuilder(); sb.AppendLine(); sb.AppendLine(); sb.AppendLine("zeta: " + zeta); sb.AppendLine(); foreach (var stage in stages.Intersect(wallClockPerRequest.Keys)) { sb.AppendLine("Stage: " + stage); sb.AppendLine(" Measured average CPU per request: " + cpuPerRequest[stage].ToString("F3") + " ms"); sb.AppendLine(" Measured average Wall-clock per request: " + wallClockPerRequest[stage].ToString("F3") + " ms"); sb.AppendLine(" Measured number of requests: " + numberOfRequests[stage].ToString("F0") + " requests"); sb.AppendLine(" lambda: " + lambda[stage].ToString("F3") + " arrival rate requests/sec"); sb.AppendLine(" s: " + s[stage].ToString("F3") + " per thread service rate requests/sec"); sb.AppendLine(" beta: " + beta[stage].ToString("F3") + " per thread CPU usage"); sb.AppendLine(" Estimated wait time: " + waitTimes[stage].ToString("F3") + " ms"); sb.AppendLine(" Throughput thread allocation: " + Math.Ceiling(throughputThreadAllocation[stage]) + " threads (rounded up from " + throughputThreadAllocation[stage].ToString("F3") + ")"); sb.AppendLine(" Latency thread allocation: " + Math.Ceiling(latencyThreadAllocation[stage]) + " threads (rounded up from " + latencyThreadAllocation[stage].ToString("F3") + ")"); sb.AppendLine(" Regularlized latency thread allocation: " + latencyPenalizedThreadAllocationConst[stage].ToString("F3") + " + " + latencyPenalizedThreadAllocationCoef[stage].ToString("F3") + " / sqrt(eta) threads (rounded this value up)"); } var cpuBreakdown = new Dictionary<string, double>(); foreach (var stage in cpuPerRequest.Keys) { double val = (numberOfRequests[stage] * cpuPerRequest[stage]) / (cores * elapsedWallClock); cpuBreakdown.Add(stage == "ThreadPoolThread" ? "ThreadPoolThread.AsynchronousReceive" : stage, val); } cpuBreakdown.Add("Untracked", untrackedProportionTime); sb.AppendLine(); sb.AppendLine("CPU usage by thread type:"); foreach (var v in cpuBreakdown.OrderBy(key => (-1*key.Value))) sb.AppendLine(" " + v.Value.ToString("F3") + ", " + v.Key); sb.AppendLine(); sb.Append("EndStageAnalysis"); return sb.ToString(); } } catch (Exception e) { return e + Environment.NewLine + e.StackTrace; } } /// <summary> /// get all cpu used by all types of threads /// </summary> /// <returns> milliseconds of total cpu time </returns> private double GetTotalCPU() { double total = 0; foreach (var keyVal in stageGroups) foreach (var statistics in keyVal.Value) total += statistics.ExecutingCpuCycleTime.Elapsed.TotalMilliseconds; return total; } /// <summary> /// gets total wallclock which is the wallclock of the stage with maximum wallclock time /// </summary> private double GetMaxWallClock() { double maxTime = 0; foreach (var keyVal in stageGroups) foreach (var statistics in keyVal.Value) maxTime = Math.Max(maxTime, statistics.ExecutingWallClockTime.Elapsed.TotalMilliseconds); maxTime -= 60 * 1000; // warmup time for grains needs to be subtracted return maxTime; } /// <summary> /// get number of requests for a stage /// </summary> /// <param name="stageName">name of a stage from thread tracking statistics</param> /// <returns>number of requests</returns> private double GetNumberOfRequests(string stageName) { if (stageName == "Untracked.ThreadPoolThread") return 1; double num = 0; if (!stageGroups.ContainsKey(stageName)) return 0; foreach (var tts in stageGroups[stageName]) num += tts.NumRequests; return num; } /// <summary> /// get wall clock time for a request of a stage /// </summary> /// <param name="stageName">name of a stage from thread tracking statistics</param> /// <returns>average milliseconds of wallclock time per request</returns> private double GetWallClockPerStagePerRequest(string stageName) { double sum = 0; if (!stageGroups.ContainsKey(stageName)) return 0; foreach (var statistics in stageGroups[stageName]) if (stageName == "ThreadPoolThread") { sum += statistics.ProcessingWallClockTime.Elapsed.TotalMilliseconds; } else { sum += statistics.ProcessingWallClockTime.Elapsed.TotalMilliseconds; // We need to add the pure Take time, since in the GetCpuPerStagePerRequest we includes both processingCPUCycleTime and the Take time. TimeSpan takeCPUCycles = statistics.ExecutingCpuCycleTime.Elapsed - statistics.ProcessingCpuCycleTime.Elapsed; sum += takeCPUCycles.TotalMilliseconds; } return sum / GetNumberOfRequests(stageName); } /// <summary> /// get cpu time for a request of a stage /// </summary> /// <param name="stageName">name of a stage from thread tracking statistics</param> /// <returns>average milliseconds of cpu time per request</returns> private double GetCpuPerStagePerRequest(string stageName) { double sum = 0; if (stageName == "Untracked.ThreadPoolThread") { foreach (var statistics in stageGroups["ThreadPoolThread"]) { sum += statistics.ExecutingCpuCycleTime.Elapsed.TotalMilliseconds; sum -= statistics.ProcessingCpuCycleTime.Elapsed.TotalMilliseconds; } return sum; } if (!stageGroups.ContainsKey(stageName)) return 0; foreach (var statistics in stageGroups[stageName]) { if (stageName == "ThreadPoolThread") { sum += statistics.ProcessingCpuCycleTime.Elapsed.TotalMilliseconds; } else { // this includes both processingCPUCycleTime and the Take time. sum += statistics.ExecutingCpuCycleTime.Elapsed.TotalMilliseconds; } } return sum / GetNumberOfRequests(stageName); } } }
using Lucene.Net.Support; using Lucene.Net.Util; using System; using System.IO; namespace Lucene.Net.Search { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using AtomicReaderContext = Lucene.Net.Index.AtomicReaderContext; using Entry = Lucene.Net.Search.FieldValueHitQueue.Entry; /// <summary> /// A <see cref="ICollector"/> that sorts by <see cref="SortField"/> using /// <see cref="FieldComparer"/>s. /// <para/> /// See the <see cref="Create(Lucene.Net.Search.Sort, int, bool, bool, bool, bool)"/> method /// for instantiating a <see cref="TopFieldCollector"/>. /// <para/> /// @lucene.experimental /// </summary> public abstract class TopFieldCollector : TopDocsCollector<Entry> { // TODO: one optimization we could do is to pre-fill // the queue with sentinel value that guaranteed to // always compare lower than a real hit; this would // save having to check queueFull on each insert /// <summary> /// Implements a <see cref="TopFieldCollector"/> over one <see cref="SortField"/> criteria, without /// tracking document scores and maxScore. /// </summary> private class OneComparerNonScoringCollector : TopFieldCollector { internal FieldComparer comparer; internal readonly int reverseMul; internal readonly FieldValueHitQueue<Entry> queue; public OneComparerNonScoringCollector(FieldValueHitQueue<Entry> queue, int numHits, bool fillFields) : base(queue, numHits, fillFields) { this.queue = queue; comparer = queue.Comparers[0]; reverseMul = queue.ReverseMul[0]; } internal void UpdateBottom(int doc) { // bottom.score is already set to Float.NaN in add(). bottom.Doc = docBase + doc; bottom = m_pq.UpdateTop(); } public override void Collect(int doc) { ++m_totalHits; if (queueFull) { if ((reverseMul * comparer.CompareBottom(doc)) <= 0) { // since docs are visited in doc Id order, if compare is 0, it means // this document is larger than anything else in the queue, and // therefore not competitive. return; } // this hit is competitive - replace bottom element in queue & adjustTop comparer.Copy(bottom.Slot, doc); UpdateBottom(doc); comparer.SetBottom(bottom.Slot); } else { // Startup transient: queue hasn't gathered numHits yet int slot = m_totalHits - 1; // Copy hit into queue comparer.Copy(slot, doc); Add(slot, doc, float.NaN); if (queueFull) { comparer.SetBottom(bottom.Slot); } } } public override void SetNextReader(AtomicReaderContext context) { this.docBase = context.DocBase; queue.SetComparer(0, comparer.SetNextReader(context)); comparer = queue.FirstComparer; } public override void SetScorer(Scorer scorer) { comparer.SetScorer(scorer); } } /// <summary> /// Implements a <see cref="TopFieldCollector"/> over one <see cref="SortField"/> criteria, without /// tracking document scores and maxScore, and assumes out of orderness in doc /// Ids collection. /// </summary> private class OutOfOrderOneComparerNonScoringCollector : OneComparerNonScoringCollector { public OutOfOrderOneComparerNonScoringCollector(FieldValueHitQueue<Entry> queue, int numHits, bool fillFields) : base(queue, numHits, fillFields) { } public override void Collect(int doc) { ++m_totalHits; if (queueFull) { // Fastmatch: return if this hit is not competitive int cmp = reverseMul * comparer.CompareBottom(doc); if (cmp < 0 || (cmp == 0 && doc + docBase > bottom.Doc)) { return; } // this hit is competitive - replace bottom element in queue & adjustTop comparer.Copy(bottom.Slot, doc); UpdateBottom(doc); comparer.SetBottom(bottom.Slot); } else { // Startup transient: queue hasn't gathered numHits yet int slot = m_totalHits - 1; // Copy hit into queue comparer.Copy(slot, doc); Add(slot, doc, float.NaN); if (queueFull) { comparer.SetBottom(bottom.Slot); } } } public override bool AcceptsDocsOutOfOrder => true; } /// <summary> /// Implements a <see cref="TopFieldCollector"/> over one <see cref="SortField"/> criteria, while tracking /// document scores but no maxScore. /// </summary> private class OneComparerScoringNoMaxScoreCollector : OneComparerNonScoringCollector { internal Scorer scorer; public OneComparerScoringNoMaxScoreCollector(FieldValueHitQueue<Entry> queue, int numHits, bool fillFields) : base(queue, numHits, fillFields) { } internal void UpdateBottom(int doc, float score) { bottom.Doc = docBase + doc; bottom.Score = score; bottom = m_pq.UpdateTop(); } public override void Collect(int doc) { ++m_totalHits; if (queueFull) { if ((reverseMul * comparer.CompareBottom(doc)) <= 0) { // since docs are visited in doc Id order, if compare is 0, it means // this document is largest than anything else in the queue, and // therefore not competitive. return; } // Compute the score only if the hit is competitive. float score = scorer.GetScore(); // this hit is competitive - replace bottom element in queue & adjustTop comparer.Copy(bottom.Slot, doc); UpdateBottom(doc, score); comparer.SetBottom(bottom.Slot); } else { // Compute the score only if the hit is competitive. float score = scorer.GetScore(); // Startup transient: queue hasn't gathered numHits yet int slot = m_totalHits - 1; // Copy hit into queue comparer.Copy(slot, doc); Add(slot, doc, score); if (queueFull) { comparer.SetBottom(bottom.Slot); } } } public override void SetScorer(Scorer scorer) { this.scorer = scorer; comparer.SetScorer(scorer); } } /// <summary> /// Implements a <see cref="TopFieldCollector"/> over one <see cref="SortField"/> criteria, while tracking /// document scores but no maxScore, and assumes out of orderness in doc Ids /// collection. /// </summary> private class OutOfOrderOneComparerScoringNoMaxScoreCollector : OneComparerScoringNoMaxScoreCollector { public OutOfOrderOneComparerScoringNoMaxScoreCollector(FieldValueHitQueue<Entry> queue, int numHits, bool fillFields) : base(queue, numHits, fillFields) { } public override void Collect(int doc) { ++m_totalHits; if (queueFull) { // Fastmatch: return if this hit is not competitive int cmp = reverseMul * comparer.CompareBottom(doc); if (cmp < 0 || (cmp == 0 && doc + docBase > bottom.Doc)) { return; } // Compute the score only if the hit is competitive. float score = scorer.GetScore(); // this hit is competitive - replace bottom element in queue & adjustTop comparer.Copy(bottom.Slot, doc); UpdateBottom(doc, score); comparer.SetBottom(bottom.Slot); } else { // Compute the score only if the hit is competitive. float score = scorer.GetScore(); // Startup transient: queue hasn't gathered numHits yet int slot = m_totalHits - 1; // Copy hit into queue comparer.Copy(slot, doc); Add(slot, doc, score); if (queueFull) { comparer.SetBottom(bottom.Slot); } } } public override bool AcceptsDocsOutOfOrder => true; } /// <summary> /// Implements a <see cref="TopFieldCollector"/> over one <see cref="SortField"/> criteria, with tracking /// document scores and maxScore. /// </summary> private class OneComparerScoringMaxScoreCollector : OneComparerNonScoringCollector { internal Scorer scorer; public OneComparerScoringMaxScoreCollector(FieldValueHitQueue<Entry> queue, int numHits, bool fillFields) : base(queue, numHits, fillFields) { // Must set maxScore to NEG_INF, or otherwise Math.max always returns NaN. maxScore = float.NegativeInfinity; } internal void UpdateBottom(int doc, float score) { bottom.Doc = docBase + doc; bottom.Score = score; bottom = m_pq.UpdateTop(); } public override void Collect(int doc) { float score = scorer.GetScore(); if (score > maxScore) { maxScore = score; } ++m_totalHits; if (queueFull) { if ((reverseMul * comparer.CompareBottom(doc)) <= 0) { // since docs are visited in doc Id order, if compare is 0, it means // this document is largest than anything else in the queue, and // therefore not competitive. return; } // this hit is competitive - replace bottom element in queue & adjustTop comparer.Copy(bottom.Slot, doc); UpdateBottom(doc, score); comparer.SetBottom(bottom.Slot); } else { // Startup transient: queue hasn't gathered numHits yet int slot = m_totalHits - 1; // Copy hit into queue comparer.Copy(slot, doc); Add(slot, doc, score); if (queueFull) { comparer.SetBottom(bottom.Slot); } } } public override void SetScorer(Scorer scorer) { this.scorer = scorer; base.SetScorer(scorer); } } /// <summary> /// Implements a <see cref="TopFieldCollector"/> over one <see cref="SortField"/> criteria, with tracking /// document scores and maxScore, and assumes out of orderness in doc Ids /// collection. /// </summary> private class OutOfOrderOneComparerScoringMaxScoreCollector : OneComparerScoringMaxScoreCollector { public OutOfOrderOneComparerScoringMaxScoreCollector(FieldValueHitQueue<Entry> queue, int numHits, bool fillFields) : base(queue, numHits, fillFields) { } public override void Collect(int doc) { float score = scorer.GetScore(); if (score > maxScore) { maxScore = score; } ++m_totalHits; if (queueFull) { // Fastmatch: return if this hit is not competitive int cmp = reverseMul * comparer.CompareBottom(doc); if (cmp < 0 || (cmp == 0 && doc + docBase > bottom.Doc)) { return; } // this hit is competitive - replace bottom element in queue & adjustTop comparer.Copy(bottom.Slot, doc); UpdateBottom(doc, score); comparer.SetBottom(bottom.Slot); } else { // Startup transient: queue hasn't gathered numHits yet int slot = m_totalHits - 1; // Copy hit into queue comparer.Copy(slot, doc); Add(slot, doc, score); if (queueFull) { comparer.SetBottom(bottom.Slot); } } } public override bool AcceptsDocsOutOfOrder => true; } /// <summary> /// Implements a <see cref="TopFieldCollector"/> over multiple <see cref="SortField"/> criteria, without /// tracking document scores and maxScore. /// </summary> private class MultiComparerNonScoringCollector : TopFieldCollector { internal readonly FieldComparer[] comparers; internal readonly int[] reverseMul; internal readonly FieldValueHitQueue<Entry> queue; public MultiComparerNonScoringCollector(FieldValueHitQueue<Entry> queue, int numHits, bool fillFields) : base(queue, numHits, fillFields) { this.queue = queue; comparers = queue.Comparers; reverseMul = queue.ReverseMul; } internal void UpdateBottom(int doc) { // bottom.score is already set to Float.NaN in add(). bottom.Doc = docBase + doc; bottom = m_pq.UpdateTop(); } public override void Collect(int doc) { ++m_totalHits; if (queueFull) { // Fastmatch: return if this hit is not competitive for (int i = 0; ; i++) { int c = reverseMul[i] * comparers[i].CompareBottom(doc); if (c < 0) { // Definitely not competitive. return; } else if (c > 0) { // Definitely competitive. break; } else if (i == comparers.Length - 1) { // Here c=0. If we're at the last comparer, this doc is not // competitive, since docs are visited in doc Id order, which means // this doc cannot compete with any other document in the queue. return; } } // this hit is competitive - replace bottom element in queue & adjustTop for (int i = 0; i < comparers.Length; i++) { comparers[i].Copy(bottom.Slot, doc); } UpdateBottom(doc); for (int i = 0; i < comparers.Length; i++) { comparers[i].SetBottom(bottom.Slot); } } else { // Startup transient: queue hasn't gathered numHits yet int slot = m_totalHits - 1; // Copy hit into queue for (int i = 0; i < comparers.Length; i++) { comparers[i].Copy(slot, doc); } Add(slot, doc, float.NaN); if (queueFull) { for (int i = 0; i < comparers.Length; i++) { comparers[i].SetBottom(bottom.Slot); } } } } public override void SetNextReader(AtomicReaderContext context) { docBase = context.DocBase; for (int i = 0; i < comparers.Length; i++) { queue.SetComparer(i, comparers[i].SetNextReader(context)); } } public override void SetScorer(Scorer scorer) { // set the value on all comparers for (int i = 0; i < comparers.Length; i++) { comparers[i].SetScorer(scorer); } } } /// <summary> /// Implements a <see cref="TopFieldCollector"/> over multiple <see cref="SortField"/> criteria, without /// tracking document scores and maxScore, and assumes out of orderness in doc /// Ids collection. /// </summary> private class OutOfOrderMultiComparerNonScoringCollector : MultiComparerNonScoringCollector { public OutOfOrderMultiComparerNonScoringCollector(FieldValueHitQueue<Entry> queue, int numHits, bool fillFields) : base(queue, numHits, fillFields) { } public override void Collect(int doc) { ++m_totalHits; if (queueFull) { // Fastmatch: return if this hit is not competitive for (int i = 0; ; i++) { int c = reverseMul[i] * comparers[i].CompareBottom(doc); if (c < 0) { // Definitely not competitive. return; } else if (c > 0) { // Definitely competitive. break; } else if (i == comparers.Length - 1) { // this is the equals case. if (doc + docBase > bottom.Doc) { // Definitely not competitive return; } break; } } // this hit is competitive - replace bottom element in queue & adjustTop for (int i = 0; i < comparers.Length; i++) { comparers[i].Copy(bottom.Slot, doc); } UpdateBottom(doc); for (int i = 0; i < comparers.Length; i++) { comparers[i].SetBottom(bottom.Slot); } } else { // Startup transient: queue hasn't gathered numHits yet int slot = m_totalHits - 1; // Copy hit into queue for (int i = 0; i < comparers.Length; i++) { comparers[i].Copy(slot, doc); } Add(slot, doc, float.NaN); if (queueFull) { for (int i = 0; i < comparers.Length; i++) { comparers[i].SetBottom(bottom.Slot); } } } } public override bool AcceptsDocsOutOfOrder => true; } /// <summary> /// Implements a <see cref="TopFieldCollector"/> over multiple <see cref="SortField"/> criteria, with /// tracking document scores and maxScore. /// </summary> private class MultiComparerScoringMaxScoreCollector : MultiComparerNonScoringCollector { internal Scorer scorer; public MultiComparerScoringMaxScoreCollector(FieldValueHitQueue<Entry> queue, int numHits, bool fillFields) : base(queue, numHits, fillFields) { // Must set maxScore to NEG_INF, or otherwise Math.max always returns NaN. maxScore = float.NegativeInfinity; } internal void UpdateBottom(int doc, float score) { bottom.Doc = docBase + doc; bottom.Score = score; bottom = m_pq.UpdateTop(); } public override void Collect(int doc) { float score = scorer.GetScore(); if (score > maxScore) { maxScore = score; } ++m_totalHits; if (queueFull) { // Fastmatch: return if this hit is not competitive for (int i = 0; ; i++) { int c = reverseMul[i] * comparers[i].CompareBottom(doc); if (c < 0) { // Definitely not competitive. return; } else if (c > 0) { // Definitely competitive. break; } else if (i == comparers.Length - 1) { // Here c=0. If we're at the last comparer, this doc is not // competitive, since docs are visited in doc Id order, which means // this doc cannot compete with any other document in the queue. return; } } // this hit is competitive - replace bottom element in queue & adjustTop for (int i = 0; i < comparers.Length; i++) { comparers[i].Copy(bottom.Slot, doc); } UpdateBottom(doc, score); for (int i = 0; i < comparers.Length; i++) { comparers[i].SetBottom(bottom.Slot); } } else { // Startup transient: queue hasn't gathered numHits yet int slot = m_totalHits - 1; // Copy hit into queue for (int i = 0; i < comparers.Length; i++) { comparers[i].Copy(slot, doc); } Add(slot, doc, score); if (queueFull) { for (int i = 0; i < comparers.Length; i++) { comparers[i].SetBottom(bottom.Slot); } } } } public override void SetScorer(Scorer scorer) { this.scorer = scorer; base.SetScorer(scorer); } } /// <summary> /// Implements a <see cref="TopFieldCollector"/> over multiple <see cref="SortField"/> criteria, with /// tracking document scores and maxScore, and assumes out of orderness in doc /// Ids collection. /// </summary> private sealed class OutOfOrderMultiComparerScoringMaxScoreCollector : MultiComparerScoringMaxScoreCollector { public OutOfOrderMultiComparerScoringMaxScoreCollector(FieldValueHitQueue<Entry> queue, int numHits, bool fillFields) : base(queue, numHits, fillFields) { } public override void Collect(int doc) { float score = scorer.GetScore(); if (score > maxScore) { maxScore = score; } ++m_totalHits; if (queueFull) { // Fastmatch: return if this hit is not competitive for (int i = 0; ; i++) { int c = reverseMul[i] * comparers[i].CompareBottom(doc); if (c < 0) { // Definitely not competitive. return; } else if (c > 0) { // Definitely competitive. break; } else if (i == comparers.Length - 1) { // this is the equals case. if (doc + docBase > bottom.Doc) { // Definitely not competitive return; } break; } } // this hit is competitive - replace bottom element in queue & adjustTop for (int i = 0; i < comparers.Length; i++) { comparers[i].Copy(bottom.Slot, doc); } UpdateBottom(doc, score); for (int i = 0; i < comparers.Length; i++) { comparers[i].SetBottom(bottom.Slot); } } else { // Startup transient: queue hasn't gathered numHits yet int slot = m_totalHits - 1; // Copy hit into queue for (int i = 0; i < comparers.Length; i++) { comparers[i].Copy(slot, doc); } Add(slot, doc, score); if (queueFull) { for (int i = 0; i < comparers.Length; i++) { comparers[i].SetBottom(bottom.Slot); } } } } public override bool AcceptsDocsOutOfOrder => true; } /// <summary> /// Implements a <see cref="TopFieldCollector"/> over multiple <see cref="SortField"/> criteria, with /// tracking document scores and maxScore. /// </summary> private class MultiComparerScoringNoMaxScoreCollector : MultiComparerNonScoringCollector { internal Scorer scorer; public MultiComparerScoringNoMaxScoreCollector(FieldValueHitQueue<Entry> queue, int numHits, bool fillFields) : base(queue, numHits, fillFields) { } internal void UpdateBottom(int doc, float score) { bottom.Doc = docBase + doc; bottom.Score = score; bottom = m_pq.UpdateTop(); } public override void Collect(int doc) { ++m_totalHits; if (queueFull) { // Fastmatch: return if this hit is not competitive for (int i = 0; ; i++) { int c = reverseMul[i] * comparers[i].CompareBottom(doc); if (c < 0) { // Definitely not competitive. return; } else if (c > 0) { // Definitely competitive. break; } else if (i == comparers.Length - 1) { // Here c=0. If we're at the last comparer, this doc is not // competitive, since docs are visited in doc Id order, which means // this doc cannot compete with any other document in the queue. return; } } // this hit is competitive - replace bottom element in queue & adjustTop for (int i = 0; i < comparers.Length; i++) { comparers[i].Copy(bottom.Slot, doc); } // Compute score only if it is competitive. float score = scorer.GetScore(); UpdateBottom(doc, score); for (int i = 0; i < comparers.Length; i++) { comparers[i].SetBottom(bottom.Slot); } } else { // Startup transient: queue hasn't gathered numHits yet int slot = m_totalHits - 1; // Copy hit into queue for (int i = 0; i < comparers.Length; i++) { comparers[i].Copy(slot, doc); } // Compute score only if it is competitive. float score = scorer.GetScore(); Add(slot, doc, score); if (queueFull) { for (int i = 0; i < comparers.Length; i++) { comparers[i].SetBottom(bottom.Slot); } } } } public override void SetScorer(Scorer scorer) { this.scorer = scorer; base.SetScorer(scorer); } } /// <summary> /// Implements a <see cref="TopFieldCollector"/> over multiple <see cref="SortField"/> criteria, with /// tracking document scores and maxScore, and assumes out of orderness in doc /// Ids collection. /// </summary> private sealed class OutOfOrderMultiComparerScoringNoMaxScoreCollector : MultiComparerScoringNoMaxScoreCollector { public OutOfOrderMultiComparerScoringNoMaxScoreCollector(FieldValueHitQueue<Entry> queue, int numHits, bool fillFields) : base(queue, numHits, fillFields) { } public override void Collect(int doc) { ++m_totalHits; if (queueFull) { // Fastmatch: return if this hit is not competitive for (int i = 0; ; i++) { int c = reverseMul[i] * comparers[i].CompareBottom(doc); if (c < 0) { // Definitely not competitive. return; } else if (c > 0) { // Definitely competitive. break; } else if (i == comparers.Length - 1) { // this is the equals case. if (doc + docBase > bottom.Doc) { // Definitely not competitive return; } break; } } // this hit is competitive - replace bottom element in queue & adjustTop for (int i = 0; i < comparers.Length; i++) { comparers[i].Copy(bottom.Slot, doc); } // Compute score only if it is competitive. float score = scorer.GetScore(); UpdateBottom(doc, score); for (int i = 0; i < comparers.Length; i++) { comparers[i].SetBottom(bottom.Slot); } } else { // Startup transient: queue hasn't gathered numHits yet int slot = m_totalHits - 1; // Copy hit into queue for (int i = 0; i < comparers.Length; i++) { comparers[i].Copy(slot, doc); } // Compute score only if it is competitive. float score = scorer.GetScore(); Add(slot, doc, score); if (queueFull) { for (int i = 0; i < comparers.Length; i++) { comparers[i].SetBottom(bottom.Slot); } } } } public override void SetScorer(Scorer scorer) { this.scorer = scorer; base.SetScorer(scorer); } public override bool AcceptsDocsOutOfOrder => true; } /// <summary> /// Implements a <see cref="TopFieldCollector"/> when after != null. /// </summary> private sealed class PagingFieldCollector : TopFieldCollector { internal Scorer scorer; internal int collectedHits; internal readonly FieldComparer[] comparers; internal readonly int[] reverseMul; internal readonly FieldValueHitQueue<Entry> queue; internal readonly bool trackDocScores; internal readonly bool trackMaxScore; internal readonly FieldDoc after; internal int afterDoc; public PagingFieldCollector(FieldValueHitQueue<Entry> queue, FieldDoc after, int numHits, bool fillFields, bool trackDocScores, bool trackMaxScore) : base(queue, numHits, fillFields) { this.queue = queue; this.trackDocScores = trackDocScores; this.trackMaxScore = trackMaxScore; this.after = after; comparers = queue.Comparers; reverseMul = queue.ReverseMul; // Must set maxScore to NEG_INF, or otherwise Math.max always returns NaN. maxScore = float.NegativeInfinity; // Tell all comparers their top value: for (int i = 0; i < comparers.Length; i++) { FieldComparer comparer = comparers[i]; comparer.SetTopValue(after.Fields[i]); } } internal void UpdateBottom(int doc, float score) { bottom.Doc = docBase + doc; bottom.Score = score; bottom = m_pq.UpdateTop(); } public override void Collect(int doc) { //System.out.println(" collect doc=" + doc); m_totalHits++; float score = float.NaN; if (trackMaxScore) { score = scorer.GetScore(); if (score > maxScore) { maxScore = score; } } if (queueFull) { // Fastmatch: return if this hit is no better than // the worst hit currently in the queue: for (int i = 0; ; i++) { int c = reverseMul[i] * comparers[i].CompareBottom(doc); if (c < 0) { // Definitely not competitive. return; } else if (c > 0) { // Definitely competitive. break; } else if (i == comparers.Length - 1) { // this is the equals case. if (doc + docBase > bottom.Doc) { // Definitely not competitive return; } break; } } } // Check if this hit was already collected on a // previous page: bool sameValues = true; for (int compIDX = 0; compIDX < comparers.Length; compIDX++) { FieldComparer comp = comparers[compIDX]; int cmp = reverseMul[compIDX] * comp.CompareTop(doc); if (cmp > 0) { // Already collected on a previous page //System.out.println(" skip: before"); return; } else if (cmp < 0) { // Not yet collected sameValues = false; //System.out.println(" keep: after; reverseMul=" + reverseMul[compIDX]); break; } } // Tie-break by docID: if (sameValues && doc <= afterDoc) { // Already collected on a previous page //System.out.println(" skip: tie-break"); return; } if (queueFull) { // this hit is competitive - replace bottom element in queue & adjustTop for (int i = 0; i < comparers.Length; i++) { comparers[i].Copy(bottom.Slot, doc); } // Compute score only if it is competitive. if (trackDocScores && !trackMaxScore) { score = scorer.GetScore(); } UpdateBottom(doc, score); for (int i = 0; i < comparers.Length; i++) { comparers[i].SetBottom(bottom.Slot); } } else { collectedHits++; // Startup transient: queue hasn't gathered numHits yet int slot = collectedHits - 1; //System.out.println(" slot=" + slot); // Copy hit into queue for (int i = 0; i < comparers.Length; i++) { comparers[i].Copy(slot, doc); } // Compute score only if it is competitive. if (trackDocScores && !trackMaxScore) { score = scorer.GetScore(); } bottom = m_pq.Add(new Entry(slot, docBase + doc, score)); queueFull = collectedHits == numHits; if (queueFull) { for (int i = 0; i < comparers.Length; i++) { comparers[i].SetBottom(bottom.Slot); } } } } public override void SetScorer(Scorer scorer) { this.scorer = scorer; for (int i = 0; i < comparers.Length; i++) { comparers[i].SetScorer(scorer); } } public override bool AcceptsDocsOutOfOrder => true; public override void SetNextReader(AtomicReaderContext context) { docBase = context.DocBase; afterDoc = after.Doc - docBase; for (int i = 0; i < comparers.Length; i++) { queue.SetComparer(i, comparers[i].SetNextReader(context)); } } } private static readonly ScoreDoc[] EMPTY_SCOREDOCS = Arrays.Empty<ScoreDoc>(); private readonly bool fillFields; /// <summary> /// Stores the maximum score value encountered, needed for normalizing. If /// document scores are not tracked, this value is initialized to NaN. /// </summary> internal float maxScore = float.NaN; internal readonly int numHits; internal FieldValueHitQueue.Entry bottom = null; internal bool queueFull; internal int docBase; // Declaring the constructor private prevents extending this class by anyone // else. Note that the class cannot be final since it's extended by the // internal versions. If someone will define a constructor with any other // visibility, then anyone will be able to extend the class, which is not what // we want. private TopFieldCollector(PriorityQueue<Entry> pq, int numHits, bool fillFields) : base(pq) { this.numHits = numHits; this.fillFields = fillFields; } /// <summary> /// Creates a new <see cref="TopFieldCollector"/> from the given /// arguments. /// /// <para/><b>NOTE</b>: The instances returned by this method /// pre-allocate a full array of length /// <paramref name="numHits"/>. /// </summary> /// <param name="sort"> /// The sort criteria (<see cref="SortField"/>s). </param> /// <param name="numHits"> /// The number of results to collect. </param> /// <param name="fillFields"> /// Specifies whether the actual field values should be returned on /// the results (<see cref="FieldDoc"/>). </param> /// <param name="trackDocScores"> /// Specifies whether document scores should be tracked and set on the /// results. Note that if set to <c>false</c>, then the results' scores will /// be set to <see cref="float.NaN"/>. Setting this to <c>true</c> affects performance, as /// it incurs the score computation on each competitive result. /// Therefore if document scores are not required by the application, /// it is recommended to set it to <c>false</c>. </param> /// <param name="trackMaxScore"> /// Specifies whether the query's <see cref="maxScore"/> should be tracked and set /// on the resulting <see cref="TopDocs"/>. Note that if set to <c>false</c>, /// <see cref="TopDocs.MaxScore"/> returns <see cref="float.NaN"/>. Setting this to /// <c>true</c> affects performance as it incurs the score computation on /// each result. Also, setting this <c>true</c> automatically sets /// <paramref name="trackDocScores"/> to <c>true</c> as well. </param> /// <param name="docsScoredInOrder"> /// Specifies whether documents are scored in doc Id order or not by /// the given <see cref="Scorer"/> in <see cref="ICollector.SetScorer(Scorer)"/>. </param> /// <returns> A <see cref="TopFieldCollector"/> instance which will sort the results by /// the sort criteria. </returns> /// <exception cref="IOException"> If there is a low-level I/O error </exception> public static TopFieldCollector Create(Sort sort, int numHits, bool fillFields, bool trackDocScores, bool trackMaxScore, bool docsScoredInOrder) { return Create(sort, numHits, null, fillFields, trackDocScores, trackMaxScore, docsScoredInOrder); } /// <summary> /// Creates a new <see cref="TopFieldCollector"/> from the given /// arguments. /// /// <para/><b>NOTE</b>: The instances returned by this method /// pre-allocate a full array of length /// <paramref name="numHits"/>. /// </summary> /// <param name="sort"> /// The sort criteria (<see cref="SortField"/>s). </param> /// <param name="numHits"> /// The number of results to collect. </param> /// <param name="after"> /// Only hits after this <see cref="FieldDoc"/> will be collected </param> /// <param name="fillFields"> /// Specifies whether the actual field values should be returned on /// the results (<see cref="FieldDoc"/>). </param> /// <param name="trackDocScores"> /// Specifies whether document scores should be tracked and set on the /// results. Note that if set to <c>false</c>, then the results' scores will /// be set to <see cref="float.NaN"/>. Setting this to <c>true</c> affects performance, as /// it incurs the score computation on each competitive result. /// Therefore if document scores are not required by the application, /// it is recommended to set it to <c>false</c>. </param> /// <param name="trackMaxScore"> /// Specifies whether the query's maxScore should be tracked and set /// on the resulting <see cref="TopDocs"/>. Note that if set to <c>false</c>, /// <see cref="TopDocs.MaxScore"/> returns <see cref="float.NaN"/>. Setting this to /// <c>true</c> affects performance as it incurs the score computation on /// each result. Also, setting this <c>true</c> automatically sets /// <paramref name="trackDocScores"/> to <c>true</c> as well. </param> /// <param name="docsScoredInOrder"> /// Specifies whether documents are scored in doc Id order or not by /// the given <see cref="Scorer"/> in <see cref="ICollector.SetScorer(Scorer)"/>. </param> /// <returns> A <see cref="TopFieldCollector"/> instance which will sort the results by /// the sort criteria. </returns> /// <exception cref="IOException"> If there is a low-level I/O error </exception> public static TopFieldCollector Create(Sort sort, int numHits, FieldDoc after, bool fillFields, bool trackDocScores, bool trackMaxScore, bool docsScoredInOrder) { if (sort.fields.Length == 0) { throw new ArgumentException("Sort must contain at least one field"); } if (numHits <= 0) { throw new ArgumentException("numHits must be > 0; please use TotalHitCountCollector if you just need the total hit count"); } FieldValueHitQueue<Entry> queue = FieldValueHitQueue.Create<Entry>(sort.fields, numHits); if (after == null) { if (queue.Comparers.Length == 1) { if (docsScoredInOrder) { if (trackMaxScore) { return new OneComparerScoringMaxScoreCollector(queue, numHits, fillFields); } else if (trackDocScores) { return new OneComparerScoringNoMaxScoreCollector(queue, numHits, fillFields); } else { return new OneComparerNonScoringCollector(queue, numHits, fillFields); } } else { if (trackMaxScore) { return new OutOfOrderOneComparerScoringMaxScoreCollector(queue, numHits, fillFields); } else if (trackDocScores) { return new OutOfOrderOneComparerScoringNoMaxScoreCollector(queue, numHits, fillFields); } else { return new OutOfOrderOneComparerNonScoringCollector(queue, numHits, fillFields); } } } // multiple comparers. if (docsScoredInOrder) { if (trackMaxScore) { return new MultiComparerScoringMaxScoreCollector(queue, numHits, fillFields); } else if (trackDocScores) { return new MultiComparerScoringNoMaxScoreCollector(queue, numHits, fillFields); } else { return new MultiComparerNonScoringCollector(queue, numHits, fillFields); } } else { if (trackMaxScore) { return new OutOfOrderMultiComparerScoringMaxScoreCollector(queue, numHits, fillFields); } else if (trackDocScores) { return new OutOfOrderMultiComparerScoringNoMaxScoreCollector(queue, numHits, fillFields); } else { return new OutOfOrderMultiComparerNonScoringCollector(queue, numHits, fillFields); } } } else { if (after.Fields == null) { throw new ArgumentException("after.fields wasn't set; you must pass fillFields=true for the previous search"); } if (after.Fields.Length != sort.GetSort().Length) { throw new ArgumentException("after.fields has " + after.Fields.Length + " values but sort has " + sort.GetSort().Length); } return new PagingFieldCollector(queue, after, numHits, fillFields, trackDocScores, trackMaxScore); } } internal void Add(int slot, int doc, float score) { bottom = m_pq.Add(new Entry(slot, docBase + doc, score)); queueFull = m_totalHits == numHits; } /* * Only the following callback methods need to be overridden since * topDocs(int, int) calls them to return the results. */ protected override void PopulateResults(ScoreDoc[] results, int howMany) { if (fillFields) { // avoid casting if unnecessary. FieldValueHitQueue<Entry> queue = (FieldValueHitQueue<Entry>)m_pq; for (int i = howMany - 1; i >= 0; i--) { results[i] = queue.FillFields(queue.Pop()); } } else { for (int i = howMany - 1; i >= 0; i--) { Entry entry = m_pq.Pop(); results[i] = new FieldDoc(entry.Doc, entry.Score); } } } protected override TopDocs NewTopDocs(ScoreDoc[] results, int start) { if (results == null) { results = EMPTY_SCOREDOCS; // Set maxScore to NaN, in case this is a maxScore tracking collector. maxScore = float.NaN; } // If this is a maxScoring tracking collector and there were no results, return new TopFieldDocs(m_totalHits, results, ((FieldValueHitQueue<Entry>)m_pq).Fields, maxScore); } public override bool AcceptsDocsOutOfOrder => false; } }
// Copyright (c) The Avalonia Project. All rights reserved. // Licensed under the MIT license. See licence.md file in the project root for full license information. using System; using System.Collections.Generic; using System.Reactive.Linq; using Moq; using Avalonia.Styling; using Avalonia.UnitTests; using Xunit; using Avalonia.LogicalTree; using Avalonia.Controls; namespace Avalonia.Styling.UnitTests { public class StyledElementTests { [Fact] public void Classes_Should_Initially_Be_Empty() { var target = new StyledElement(); Assert.Empty(target.Classes); } [Fact] public void Setting_Parent_Should_Also_Set_InheritanceParent() { var parent = new Decorator(); var target = new TestControl(); parent.Child = target; Assert.Equal(parent, target.Parent); Assert.Equal(parent, target.InheritanceParent); } [Fact] public void Setting_Parent_Should_Not_Set_InheritanceParent_If_Already_Set() { var parent = new Decorator(); var inheritanceParent = new Decorator(); var target = new TestControl(); ((ISetInheritanceParent)target).SetParent(inheritanceParent); parent.Child = target; Assert.Equal(parent, target.Parent); Assert.Equal(inheritanceParent, target.InheritanceParent); } [Fact] public void InheritanceParent_Should_Be_Cleared_When_Removed_From_Parent() { var parent = new Decorator(); var target = new TestControl(); parent.Child = target; parent.Child = null; Assert.Null(target.InheritanceParent); } [Fact] public void InheritanceParent_Should_Be_Cleared_When_Removed_From_Parent_When_Has_Different_InheritanceParent() { var parent = new Decorator(); var inheritanceParent = new Decorator(); var target = new TestControl(); ((ISetInheritanceParent)target).SetParent(inheritanceParent); parent.Child = target; parent.Child = null; Assert.Null(target.InheritanceParent); } [Fact] public void AttachedToLogicalParent_Should_Be_Called_When_Added_To_Tree() { var root = new TestRoot(); var parent = new Border(); var child = new Border(); var grandchild = new Border(); var parentRaised = false; var childRaised = false; var grandchildRaised = false; parent.AttachedToLogicalTree += (s, e) => parentRaised = true; child.AttachedToLogicalTree += (s, e) => childRaised = true; grandchild.AttachedToLogicalTree += (s, e) => grandchildRaised = true; parent.Child = child; child.Child = grandchild; Assert.False(parentRaised); Assert.False(childRaised); Assert.False(grandchildRaised); root.Child = parent; Assert.True(parentRaised); Assert.True(childRaised); Assert.True(grandchildRaised); } [Fact] public void AttachedToLogicalParent_Should_Be_Called_Before_Parent_Change_Signalled() { var root = new TestRoot(); var child = new Border(); var raised = new List<string>(); child.AttachedToLogicalTree += (s, e) => { Assert.Equal(root, child.Parent); raised.Add("attached"); }; child.GetObservable(StyledElement.ParentProperty).Skip(1).Subscribe(_ => raised.Add("parent")); root.Child = child; Assert.Equal(new[] { "attached", "parent" }, raised); } [Fact] public void AttachedToLogicalParent_Should_Not_Be_Called_With_GlobalStyles_As_Root() { var globalStyles = Mock.Of<IGlobalStyles>(); var root = new TestRoot { StylingParent = globalStyles }; var child = new Border(); var raised = false; child.AttachedToLogicalTree += (s, e) => { Assert.Equal(root, e.Root); raised = true; }; root.Child = child; Assert.True(raised); } [Fact] public void DetachedFromLogicalParent_Should_Be_Called_When_Removed_From_Tree() { var root = new TestRoot(); var parent = new Border(); var child = new Border(); var grandchild = new Border(); var parentRaised = false; var childRaised = false; var grandchildRaised = false; parent.Child = child; child.Child = grandchild; root.Child = parent; parent.DetachedFromLogicalTree += (s, e) => parentRaised = true; child.DetachedFromLogicalTree += (s, e) => childRaised = true; grandchild.DetachedFromLogicalTree += (s, e) => grandchildRaised = true; root.Child = null; Assert.True(parentRaised); Assert.True(childRaised); Assert.True(grandchildRaised); } [Fact] public void DetachedFromLogicalParent_Should_Not_Be_Called_With_GlobalStyles_As_Root() { var globalStyles = Mock.Of<IGlobalStyles>(); var root = new TestRoot { StylingParent = globalStyles }; var child = new Border(); var raised = false; child.DetachedFromLogicalTree += (s, e) => { Assert.Equal(root, e.Root); raised = true; }; root.Child = child; root.Child = null; Assert.True(raised); } [Fact] public void Adding_Tree_To_IStyleRoot_Should_Style_Controls() { using (AvaloniaLocator.EnterScope()) { var root = new TestRoot(); var parent = new Border(); var child = new Border(); var grandchild = new Control(); var styler = new Mock<IStyler>(); AvaloniaLocator.CurrentMutable.Bind<IStyler>().ToConstant(styler.Object); parent.Child = child; child.Child = grandchild; styler.Verify(x => x.ApplyStyles(It.IsAny<IStyleable>()), Times.Never()); root.Child = parent; styler.Verify(x => x.ApplyStyles(parent), Times.Once()); styler.Verify(x => x.ApplyStyles(child), Times.Once()); styler.Verify(x => x.ApplyStyles(grandchild), Times.Once()); } } [Fact] public void Styles_Not_Applied_Until_Initialization_Finished() { using (AvaloniaLocator.EnterScope()) { var root = new TestRoot(); var child = new Border(); var styler = new Mock<IStyler>(); AvaloniaLocator.CurrentMutable.Bind<IStyler>().ToConstant(styler.Object); ((ISupportInitialize)child).BeginInit(); root.Child = child; styler.Verify(x => x.ApplyStyles(It.IsAny<IStyleable>()), Times.Never()); ((ISupportInitialize)child).EndInit(); styler.Verify(x => x.ApplyStyles(child), Times.Once()); } } [Fact] public void Adding_To_Logical_Tree_Should_Register_With_NameScope() { using (AvaloniaLocator.EnterScope()) { var root = new TestRoot(); var child = new Border(); child.Name = "foo"; root.Child = child; Assert.Same(root.FindControl<Border>("foo"), child); } } [Fact] public void Name_Cannot_Be_Set_After_Added_To_Logical_Tree() { using (AvaloniaLocator.EnterScope()) { var root = new TestRoot(); var child = new Border(); root.Child = child; Assert.Throws<InvalidOperationException>(() => child.Name = "foo"); } } [Fact] public void Name_Can_Be_Set_While_Initializing() { using (AvaloniaLocator.EnterScope()) { var root = new TestRoot(); var child = new Border(); ((ISupportInitialize)child).BeginInit(); root.Child = child; child.Name = "foo"; Assert.Null(root.FindControl<Border>("foo")); ((ISupportInitialize)child).EndInit(); Assert.Same(root.FindControl<Border>("foo"), child); } } [Fact] public void StyleDetach_Is_Triggered_When_Control_Removed_From_Logical_Tree() { using (AvaloniaLocator.EnterScope()) { var root = new TestRoot(); var child = new Border(); root.Child = child; bool styleDetachTriggered = false; ((IStyleable)child).StyleDetach.Subscribe(_ => styleDetachTriggered = true); root.Child = null; Assert.True(styleDetachTriggered); } } [Fact] public void EndInit_Should_Raise_Initialized() { var root = new TestRoot(); var target = new Border(); var called = false; target.Initialized += (s, e) => called = true; ((ISupportInitialize)target).BeginInit(); root.Child = target; ((ISupportInitialize)target).EndInit(); Assert.True(called); Assert.True(target.IsInitialized); } [Fact] public void Attaching_To_Visual_Tree_Should_Raise_Initialized() { var root = new TestRoot(); var target = new Border(); var called = false; target.Initialized += (s, e) => called = true; root.Child = target; Assert.True(called); Assert.True(target.IsInitialized); } [Fact] public void DataContextChanged_Should_Be_Called() { var root = new TestStackPanel { Name = "root", Children = { new TestControl { Name = "a1", Child = new TestControl { Name = "b1", } }, new TestControl { Name = "a2", DataContext = "foo", }, } }; var called = new List<string>(); void Record(object sender, EventArgs e) => called.Add(((StyledElement)sender).Name); root.DataContextChanged += Record; foreach (TestControl c in root.GetLogicalDescendants()) { c.DataContextChanged += Record; } root.DataContext = "foo"; Assert.Equal(new[] { "root", "a1", "b1", }, called); } [Fact] public void DataContext_Notifications_Should_Be_Called_In_Correct_Order() { var root = new TestStackPanel { Name = "root", Children = { new TestControl { Name = "a1", Child = new TestControl { Name = "b1", } }, new TestControl { Name = "a2", DataContext = "foo", }, } }; var called = new List<string>(); foreach (IDataContextEvents c in root.GetSelfAndLogicalDescendants()) { c.DataContextBeginUpdate += (s, e) => called.Add("begin " + ((StyledElement)s).Name); c.DataContextChanged += (s, e) => called.Add("changed " + ((StyledElement)s).Name); c.DataContextEndUpdate += (s, e) => called.Add("end " + ((StyledElement)s).Name); } root.DataContext = "foo"; Assert.Equal( new[] { "begin root", "begin a1", "begin b1", "changed root", "changed a1", "changed b1", "end b1", "end a1", "end root", }, called); } private interface IDataContextEvents { event EventHandler DataContextBeginUpdate; event EventHandler DataContextChanged; event EventHandler DataContextEndUpdate; } private class TestControl : Decorator, IDataContextEvents { public event EventHandler DataContextBeginUpdate; public event EventHandler DataContextEndUpdate; public new IAvaloniaObject InheritanceParent => base.InheritanceParent; protected override void OnDataContextBeginUpdate() { DataContextBeginUpdate?.Invoke(this, EventArgs.Empty); base.OnDataContextBeginUpdate(); } protected override void OnDataContextEndUpdate() { DataContextEndUpdate?.Invoke(this, EventArgs.Empty); base.OnDataContextEndUpdate(); } } private class TestStackPanel : StackPanel, IDataContextEvents { public event EventHandler DataContextBeginUpdate; public event EventHandler DataContextEndUpdate; protected override void OnDataContextBeginUpdate() { DataContextBeginUpdate?.Invoke(this, EventArgs.Empty); base.OnDataContextBeginUpdate(); } protected override void OnDataContextEndUpdate() { DataContextEndUpdate?.Invoke(this, EventArgs.Empty); base.OnDataContextEndUpdate(); } } } }
// 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. //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by google-apis-code-generator 1.5.1 // C# generator version: 1.38.0 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ /** * \brief * PageSpeed Insights API Version v5 * * \section ApiInfo API Version Information * <table> * <tr><th>API * <td><a href='https://developers.google.com/speed/docs/insights/v5/get-started'>PageSpeed Insights API</a> * <tr><th>API Version<td>v5 * <tr><th>API Rev<td>20190129 (1489) * <tr><th>API Docs * <td><a href='https://developers.google.com/speed/docs/insights/v5/get-started'> * https://developers.google.com/speed/docs/insights/v5/get-started</a> * <tr><th>Discovery Name<td>pagespeedonline * </table> * * \section ForMoreInfo For More Information * * The complete API documentation for using PageSpeed Insights API can be found at * <a href='https://developers.google.com/speed/docs/insights/v5/get-started'>https://developers.google.com/speed/docs/insights/v5/get-started</a>. * * For more information about the Google APIs Client Library for .NET, see * <a href='https://developers.google.com/api-client-library/dotnet/get_started'> * https://developers.google.com/api-client-library/dotnet/get_started</a> */ namespace Google.Apis.Pagespeedonline.v5 { /// <summary>The Pagespeedonline Service.</summary> public class PagespeedonlineService : Google.Apis.Services.BaseClientService { /// <summary>The API version.</summary> public const string Version = "v5"; /// <summary>The discovery version used to generate this service.</summary> public static Google.Apis.Discovery.DiscoveryVersion DiscoveryVersionUsed = Google.Apis.Discovery.DiscoveryVersion.Version_1_0; /// <summary>Constructs a new service.</summary> public PagespeedonlineService() : this(new Google.Apis.Services.BaseClientService.Initializer()) {} /// <summary>Constructs a new service.</summary> /// <param name="initializer">The service initializer.</param> public PagespeedonlineService(Google.Apis.Services.BaseClientService.Initializer initializer) : base(initializer) { pagespeedapi = new PagespeedapiResource(this); } /// <summary>Gets the service supported features.</summary> public override System.Collections.Generic.IList<string> Features { get { return new string[0]; } } /// <summary>Gets the service name.</summary> public override string Name { get { return "pagespeedonline"; } } /// <summary>Gets the service base URI.</summary> public override string BaseUri { get { return "https://www.googleapis.com/pagespeedonline/v5/"; } } /// <summary>Gets the service base path.</summary> public override string BasePath { get { return "pagespeedonline/v5/"; } } #if !NET40 /// <summary>Gets the batch base URI; <c>null</c> if unspecified.</summary> public override string BatchUri { get { return "https://www.googleapis.com/batch/pagespeedonline/v5"; } } /// <summary>Gets the batch base path; <c>null</c> if unspecified.</summary> public override string BatchPath { get { return "batch/pagespeedonline/v5"; } } #endif private readonly PagespeedapiResource pagespeedapi; /// <summary>Gets the Pagespeedapi resource.</summary> public virtual PagespeedapiResource Pagespeedapi { get { return pagespeedapi; } } } ///<summary>A base abstract class for Pagespeedonline requests.</summary> public abstract class PagespeedonlineBaseServiceRequest<TResponse> : Google.Apis.Requests.ClientServiceRequest<TResponse> { ///<summary>Constructs a new PagespeedonlineBaseServiceRequest instance.</summary> protected PagespeedonlineBaseServiceRequest(Google.Apis.Services.IClientService service) : base(service) { } /// <summary>Data format for the response.</summary> /// [default: json] [Google.Apis.Util.RequestParameterAttribute("alt", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<AltEnum> Alt { get; set; } /// <summary>Data format for the response.</summary> public enum AltEnum { /// <summary>Responses with Content-Type of application/json</summary> [Google.Apis.Util.StringValueAttribute("json")] Json, } /// <summary>Selector specifying which fields to include in a partial response.</summary> [Google.Apis.Util.RequestParameterAttribute("fields", Google.Apis.Util.RequestParameterType.Query)] public virtual string Fields { get; set; } /// <summary>API key. Your API key identifies your project and provides you with API access, quota, and reports. /// Required unless you provide an OAuth 2.0 token.</summary> [Google.Apis.Util.RequestParameterAttribute("key", Google.Apis.Util.RequestParameterType.Query)] public virtual string Key { get; set; } /// <summary>OAuth 2.0 token for the current user.</summary> [Google.Apis.Util.RequestParameterAttribute("oauth_token", Google.Apis.Util.RequestParameterType.Query)] public virtual string OauthToken { get; set; } /// <summary>Returns response with indentations and line breaks.</summary> /// [default: true] [Google.Apis.Util.RequestParameterAttribute("prettyPrint", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<bool> PrettyPrint { get; set; } /// <summary>An opaque string that represents a user for quota purposes. Must not exceed 40 /// characters.</summary> [Google.Apis.Util.RequestParameterAttribute("quotaUser", Google.Apis.Util.RequestParameterType.Query)] public virtual string QuotaUser { get; set; } /// <summary>Deprecated. Please use quotaUser instead.</summary> [Google.Apis.Util.RequestParameterAttribute("userIp", Google.Apis.Util.RequestParameterType.Query)] public virtual string UserIp { get; set; } /// <summary>Initializes Pagespeedonline parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "alt", new Google.Apis.Discovery.Parameter { Name = "alt", IsRequired = false, ParameterType = "query", DefaultValue = "json", Pattern = null, }); RequestParameters.Add( "fields", new Google.Apis.Discovery.Parameter { Name = "fields", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "key", new Google.Apis.Discovery.Parameter { Name = "key", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "oauth_token", new Google.Apis.Discovery.Parameter { Name = "oauth_token", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "prettyPrint", new Google.Apis.Discovery.Parameter { Name = "prettyPrint", IsRequired = false, ParameterType = "query", DefaultValue = "true", Pattern = null, }); RequestParameters.Add( "quotaUser", new Google.Apis.Discovery.Parameter { Name = "quotaUser", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "userIp", new Google.Apis.Discovery.Parameter { Name = "userIp", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); } } /// <summary>The "pagespeedapi" collection of methods.</summary> public class PagespeedapiResource { private const string Resource = "pagespeedapi"; /// <summary>The service which this resource belongs to.</summary> private readonly Google.Apis.Services.IClientService service; /// <summary>Constructs a new resource.</summary> public PagespeedapiResource(Google.Apis.Services.IClientService service) { this.service = service; } /// <summary>Runs PageSpeed analysis on the page at the specified URL, and returns PageSpeed scores, a list of /// suggestions to make that page faster, and other information.</summary> /// <param name="url">The URL to fetch and analyze</param> public virtual RunpagespeedRequest Runpagespeed(string url) { return new RunpagespeedRequest(service, url); } /// <summary>Runs PageSpeed analysis on the page at the specified URL, and returns PageSpeed scores, a list of /// suggestions to make that page faster, and other information.</summary> public class RunpagespeedRequest : PagespeedonlineBaseServiceRequest<Google.Apis.Pagespeedonline.v5.Data.PagespeedApiPagespeedResponseV5> { /// <summary>Constructs a new Runpagespeed request.</summary> public RunpagespeedRequest(Google.Apis.Services.IClientService service, string url) : base(service) { Url = url; InitParameters(); } /// <summary>The URL to fetch and analyze</summary> [Google.Apis.Util.RequestParameterAttribute("url", Google.Apis.Util.RequestParameterType.Query)] public virtual string Url { get; private set; } /// <summary>A Lighthouse category to run; if none are given, only Performance category will be /// run</summary> [Google.Apis.Util.RequestParameterAttribute("category", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<CategoryEnum> Category { get; set; } /// <summary>A Lighthouse category to run; if none are given, only Performance category will be /// run</summary> public enum CategoryEnum { [Google.Apis.Util.StringValueAttribute("accessibility")] Accessibility, [Google.Apis.Util.StringValueAttribute("best-practices")] BestPractices, [Google.Apis.Util.StringValueAttribute("performance")] Performance, [Google.Apis.Util.StringValueAttribute("pwa")] Pwa, [Google.Apis.Util.StringValueAttribute("seo")] Seo, } /// <summary>The locale used to localize formatted results</summary> [Google.Apis.Util.RequestParameterAttribute("locale", Google.Apis.Util.RequestParameterType.Query)] public virtual string Locale { get; set; } /// <summary>The analysis strategy (desktop or mobile) to use, and desktop is the default</summary> [Google.Apis.Util.RequestParameterAttribute("strategy", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<StrategyEnum> Strategy { get; set; } /// <summary>The analysis strategy (desktop or mobile) to use, and desktop is the default</summary> public enum StrategyEnum { /// <summary>Fetch and analyze the URL for desktop browsers</summary> [Google.Apis.Util.StringValueAttribute("desktop")] Desktop, /// <summary>Fetch and analyze the URL for mobile devices</summary> [Google.Apis.Util.StringValueAttribute("mobile")] Mobile, } /// <summary>Campaign name for analytics.</summary> [Google.Apis.Util.RequestParameterAttribute("utm_campaign", Google.Apis.Util.RequestParameterType.Query)] public virtual string UtmCampaign { get; set; } /// <summary>Campaign source for analytics.</summary> [Google.Apis.Util.RequestParameterAttribute("utm_source", Google.Apis.Util.RequestParameterType.Query)] public virtual string UtmSource { get; set; } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "runpagespeed"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "GET"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "runPagespeed"; } } /// <summary>Initializes Runpagespeed parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "url", new Google.Apis.Discovery.Parameter { Name = "url", IsRequired = true, ParameterType = "query", DefaultValue = null, Pattern = @"(?i)http(s)?://.*", }); RequestParameters.Add( "category", new Google.Apis.Discovery.Parameter { Name = "category", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "locale", new Google.Apis.Discovery.Parameter { Name = "locale", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = @"[a-zA-Z]+((_|-)[a-zA-Z]+)?", }); RequestParameters.Add( "strategy", new Google.Apis.Discovery.Parameter { Name = "strategy", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "utm_campaign", new Google.Apis.Discovery.Parameter { Name = "utm_campaign", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "utm_source", new Google.Apis.Discovery.Parameter { Name = "utm_source", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); } } } } namespace Google.Apis.Pagespeedonline.v5.Data { public class LighthouseAuditResultV5 : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The description of the audit.</summary> [Newtonsoft.Json.JsonPropertyAttribute("description")] public virtual string Description { get; set; } /// <summary>Freeform details section of the audit.</summary> [Newtonsoft.Json.JsonPropertyAttribute("details")] public virtual System.Collections.Generic.IDictionary<string,object> Details { get; set; } /// <summary>The value that should be displayed on the UI for this audit.</summary> [Newtonsoft.Json.JsonPropertyAttribute("displayValue")] public virtual string DisplayValue { get; set; } /// <summary>An error message from a thrown error inside the audit.</summary> [Newtonsoft.Json.JsonPropertyAttribute("errorMessage")] public virtual string ErrorMessage { get; set; } /// <summary>An explanation of the errors in the audit.</summary> [Newtonsoft.Json.JsonPropertyAttribute("explanation")] public virtual string Explanation { get; set; } /// <summary>The audit's id.</summary> [Newtonsoft.Json.JsonPropertyAttribute("id")] public virtual string Id { get; set; } [Newtonsoft.Json.JsonPropertyAttribute("score")] public virtual object Score { get; set; } /// <summary>The enumerated score display mode.</summary> [Newtonsoft.Json.JsonPropertyAttribute("scoreDisplayMode")] public virtual string ScoreDisplayMode { get; set; } /// <summary>The human readable title.</summary> [Newtonsoft.Json.JsonPropertyAttribute("title")] public virtual string Title { get; set; } [Newtonsoft.Json.JsonPropertyAttribute("warnings")] public virtual object Warnings { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } public class LighthouseCategoryV5 : Google.Apis.Requests.IDirectResponseSchema { /// <summary>An array of references to all the audit members of this category.</summary> [Newtonsoft.Json.JsonPropertyAttribute("auditRefs")] public virtual System.Collections.Generic.IList<LighthouseCategoryV5.AuditRefsData> AuditRefs { get; set; } /// <summary>A more detailed description of the category and its importance.</summary> [Newtonsoft.Json.JsonPropertyAttribute("description")] public virtual string Description { get; set; } /// <summary>The string identifier of the category.</summary> [Newtonsoft.Json.JsonPropertyAttribute("id")] public virtual string Id { get; set; } /// <summary>A description for the manual audits in the category.</summary> [Newtonsoft.Json.JsonPropertyAttribute("manualDescription")] public virtual string ManualDescription { get; set; } [Newtonsoft.Json.JsonPropertyAttribute("score")] public virtual object Score { get; set; } /// <summary>The human-friendly name of the category.</summary> [Newtonsoft.Json.JsonPropertyAttribute("title")] public virtual string Title { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } public class AuditRefsData { /// <summary>The category group that the audit belongs to (optional).</summary> [Newtonsoft.Json.JsonPropertyAttribute("group")] public virtual string Group { get; set; } /// <summary>The audit ref id.</summary> [Newtonsoft.Json.JsonPropertyAttribute("id")] public virtual string Id { get; set; } /// <summary>The weight this audit's score has on the overall category score.</summary> [Newtonsoft.Json.JsonPropertyAttribute("weight")] public virtual System.Nullable<double> Weight { get; set; } } } public class LighthouseResultV5 : Google.Apis.Requests.IDirectResponseSchema { /// <summary>Map of audits in the LHR.</summary> [Newtonsoft.Json.JsonPropertyAttribute("audits")] public virtual System.Collections.Generic.IDictionary<string,LighthouseAuditResultV5> Audits { get; set; } /// <summary>Map of categories in the LHR.</summary> [Newtonsoft.Json.JsonPropertyAttribute("categories")] public virtual LighthouseResultV5.CategoriesData Categories { get; set; } /// <summary>Map of category groups in the LHR.</summary> [Newtonsoft.Json.JsonPropertyAttribute("categoryGroups")] public virtual System.Collections.Generic.IDictionary<string,LighthouseResultV5.CategoryGroupsDataElement> CategoryGroups { get; set; } /// <summary>The configuration settings for this LHR.</summary> [Newtonsoft.Json.JsonPropertyAttribute("configSettings")] public virtual LighthouseResultV5.ConfigSettingsData ConfigSettings { get; set; } /// <summary>Environment settings that were used when making this LHR.</summary> [Newtonsoft.Json.JsonPropertyAttribute("environment")] public virtual LighthouseResultV5.EnvironmentData Environment { get; set; } /// <summary>The time that this run was fetched.</summary> [Newtonsoft.Json.JsonPropertyAttribute("fetchTime")] public virtual string FetchTime { get; set; } /// <summary>The final resolved url that was audited.</summary> [Newtonsoft.Json.JsonPropertyAttribute("finalUrl")] public virtual string FinalUrl { get; set; } /// <summary>The internationalization strings that are required to render the LHR.</summary> [Newtonsoft.Json.JsonPropertyAttribute("i18n")] public virtual LighthouseResultV5.I18nData I18n { get; set; } /// <summary>The lighthouse version that was used to generate this LHR.</summary> [Newtonsoft.Json.JsonPropertyAttribute("lighthouseVersion")] public virtual string LighthouseVersion { get; set; } /// <summary>The original requested url.</summary> [Newtonsoft.Json.JsonPropertyAttribute("requestedUrl")] public virtual string RequestedUrl { get; set; } /// <summary>List of all run warnings in the LHR. Will always output to at least `[]`.</summary> [Newtonsoft.Json.JsonPropertyAttribute("runWarnings")] public virtual System.Collections.Generic.IList<object> RunWarnings { get; set; } /// <summary>A top-level error message that, if present, indicates a serious enough problem that this Lighthouse /// result may need to be discarded.</summary> [Newtonsoft.Json.JsonPropertyAttribute("runtimeError")] public virtual LighthouseResultV5.RuntimeErrorData RuntimeError { get; set; } /// <summary>Timing information for this LHR.</summary> [Newtonsoft.Json.JsonPropertyAttribute("timing")] public virtual LighthouseResultV5.TimingData Timing { get; set; } /// <summary>The user agent that was used to run this LHR.</summary> [Newtonsoft.Json.JsonPropertyAttribute("userAgent")] public virtual string UserAgent { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } /// <summary>Map of categories in the LHR.</summary> public class CategoriesData { /// <summary>The accessibility category, containing all accessibility related audits.</summary> [Newtonsoft.Json.JsonPropertyAttribute("accessibility")] public virtual LighthouseCategoryV5 Accessibility { get; set; } /// <summary>The best practices category, containing all web best practice related audits.</summary> [Newtonsoft.Json.JsonPropertyAttribute("best-practices")] public virtual LighthouseCategoryV5 BestPractices { get; set; } /// <summary>The performance category, containing all performance related audits.</summary> [Newtonsoft.Json.JsonPropertyAttribute("performance")] public virtual LighthouseCategoryV5 Performance { get; set; } /// <summary>The Progressive-Web-App (PWA) category, containing all pwa related audits.</summary> [Newtonsoft.Json.JsonPropertyAttribute("pwa")] public virtual LighthouseCategoryV5 Pwa { get; set; } /// <summary>The Search-Engine-Optimization (SEO) category, containing all seo related audits.</summary> [Newtonsoft.Json.JsonPropertyAttribute("seo")] public virtual LighthouseCategoryV5 Seo { get; set; } } /// <summary>A grouping contained in a category that groups similar audits together.</summary> public class CategoryGroupsDataElement { /// <summary>An optional human readable description of the category group.</summary> [Newtonsoft.Json.JsonPropertyAttribute("description")] public virtual string Description { get; set; } /// <summary>The title of the category group.</summary> [Newtonsoft.Json.JsonPropertyAttribute("title")] public virtual string Title { get; set; } } /// <summary>The configuration settings for this LHR.</summary> public class ConfigSettingsData { /// <summary>The form factor the emulation should use.</summary> [Newtonsoft.Json.JsonPropertyAttribute("emulatedFormFactor")] public virtual string EmulatedFormFactor { get; set; } /// <summary>The locale setting.</summary> [Newtonsoft.Json.JsonPropertyAttribute("locale")] public virtual string Locale { get; set; } [Newtonsoft.Json.JsonPropertyAttribute("onlyCategories")] public virtual object OnlyCategories { get; set; } } /// <summary>Environment settings that were used when making this LHR.</summary> public class EnvironmentData { /// <summary>The benchmark index number that indicates rough device class.</summary> [Newtonsoft.Json.JsonPropertyAttribute("benchmarkIndex")] public virtual System.Nullable<double> BenchmarkIndex { get; set; } /// <summary>The user agent string of the version of Chrome used.</summary> [Newtonsoft.Json.JsonPropertyAttribute("hostUserAgent")] public virtual string HostUserAgent { get; set; } /// <summary>The user agent string that was sent over the network.</summary> [Newtonsoft.Json.JsonPropertyAttribute("networkUserAgent")] public virtual string NetworkUserAgent { get; set; } } /// <summary>The internationalization strings that are required to render the LHR.</summary> public class I18nData { /// <summary>Internationalized strings that are formatted to the locale in configSettings.</summary> [Newtonsoft.Json.JsonPropertyAttribute("rendererFormattedStrings")] public virtual I18nData.RendererFormattedStringsData RendererFormattedStrings { get; set; } /// <summary>Internationalized strings that are formatted to the locale in configSettings.</summary> public class RendererFormattedStringsData { /// <summary>The tooltip text on an expandable chevron icon.</summary> [Newtonsoft.Json.JsonPropertyAttribute("auditGroupExpandTooltip")] public virtual string AuditGroupExpandTooltip { get; set; } /// <summary>The label for the initial request in a critical request chain.</summary> [Newtonsoft.Json.JsonPropertyAttribute("crcInitialNavigation")] public virtual string CrcInitialNavigation { get; set; } /// <summary>The label for values shown in the summary of critical request chains.</summary> [Newtonsoft.Json.JsonPropertyAttribute("crcLongestDurationLabel")] public virtual string CrcLongestDurationLabel { get; set; } /// <summary>The label shown next to an audit or metric that has had an error.</summary> [Newtonsoft.Json.JsonPropertyAttribute("errorLabel")] public virtual string ErrorLabel { get; set; } /// <summary>The error string shown next to an erroring audit.</summary> [Newtonsoft.Json.JsonPropertyAttribute("errorMissingAuditInfo")] public virtual string ErrorMissingAuditInfo { get; set; } /// <summary>The title of the lab data performance category.</summary> [Newtonsoft.Json.JsonPropertyAttribute("labDataTitle")] public virtual string LabDataTitle { get; set; } /// <summary>The disclaimer shown under performance explaning that the network can vary.</summary> [Newtonsoft.Json.JsonPropertyAttribute("lsPerformanceCategoryDescription")] public virtual string LsPerformanceCategoryDescription { get; set; } /// <summary>The heading shown above a list of audits that were not computerd in the run.</summary> [Newtonsoft.Json.JsonPropertyAttribute("manualAuditsGroupTitle")] public virtual string ManualAuditsGroupTitle { get; set; } /// <summary>The heading shown above a list of audits that do not apply to a page.</summary> [Newtonsoft.Json.JsonPropertyAttribute("notApplicableAuditsGroupTitle")] public virtual string NotApplicableAuditsGroupTitle { get; set; } /// <summary>The heading for the estimated page load savings opportunity of an audit.</summary> [Newtonsoft.Json.JsonPropertyAttribute("opportunityResourceColumnLabel")] public virtual string OpportunityResourceColumnLabel { get; set; } /// <summary>The heading for the estimated page load savings of opportunity audits.</summary> [Newtonsoft.Json.JsonPropertyAttribute("opportunitySavingsColumnLabel")] public virtual string OpportunitySavingsColumnLabel { get; set; } /// <summary>The heading that is shown above a list of audits that are passing.</summary> [Newtonsoft.Json.JsonPropertyAttribute("passedAuditsGroupTitle")] public virtual string PassedAuditsGroupTitle { get; set; } /// <summary>The label that explains the score gauges scale (0-49, 50-89, 90-100).</summary> [Newtonsoft.Json.JsonPropertyAttribute("scorescaleLabel")] public virtual string ScorescaleLabel { get; set; } /// <summary>The label shown preceding important warnings that may have invalidated an entire /// report.</summary> [Newtonsoft.Json.JsonPropertyAttribute("toplevelWarningsMessage")] public virtual string ToplevelWarningsMessage { get; set; } /// <summary>The disclaimer shown below a performance metric value.</summary> [Newtonsoft.Json.JsonPropertyAttribute("varianceDisclaimer")] public virtual string VarianceDisclaimer { get; set; } /// <summary>The label shown above a bulleted list of warnings.</summary> [Newtonsoft.Json.JsonPropertyAttribute("warningHeader")] public virtual string WarningHeader { get; set; } } } /// <summary>A top-level error message that, if present, indicates a serious enough problem that this Lighthouse /// result may need to be discarded.</summary> public class RuntimeErrorData { /// <summary>The enumerated Lighthouse Error code.</summary> [Newtonsoft.Json.JsonPropertyAttribute("code")] public virtual string Code { get; set; } /// <summary>A human readable message explaining the error code.</summary> [Newtonsoft.Json.JsonPropertyAttribute("message")] public virtual string Message { get; set; } } /// <summary>Timing information for this LHR.</summary> public class TimingData { /// <summary>The total duration of Lighthouse's run.</summary> [Newtonsoft.Json.JsonPropertyAttribute("total")] public virtual System.Nullable<double> Total { get; set; } } } public class PagespeedApiLoadingExperienceV5 : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The url, pattern or origin which the metrics are on.</summary> [Newtonsoft.Json.JsonPropertyAttribute("id")] public virtual string Id { get; set; } [Newtonsoft.Json.JsonPropertyAttribute("initial_url")] public virtual string InitialUrl { get; set; } [Newtonsoft.Json.JsonPropertyAttribute("metrics")] public virtual System.Collections.Generic.IDictionary<string,PagespeedApiLoadingExperienceV5.MetricsDataElement> Metrics { get; set; } [Newtonsoft.Json.JsonPropertyAttribute("overall_category")] public virtual string OverallCategory { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } /// <summary>The type of the metric.</summary> public class MetricsDataElement { [Newtonsoft.Json.JsonPropertyAttribute("category")] public virtual string Category { get; set; } [Newtonsoft.Json.JsonPropertyAttribute("distributions")] public virtual System.Collections.Generic.IList<MetricsDataElement.DistributionsData> Distributions { get; set; } [Newtonsoft.Json.JsonPropertyAttribute("percentile")] public virtual System.Nullable<int> Percentile { get; set; } public class DistributionsData { [Newtonsoft.Json.JsonPropertyAttribute("max")] public virtual System.Nullable<int> Max { get; set; } [Newtonsoft.Json.JsonPropertyAttribute("min")] public virtual System.Nullable<int> Min { get; set; } [Newtonsoft.Json.JsonPropertyAttribute("proportion")] public virtual System.Nullable<double> Proportion { get; set; } } } } public class PagespeedApiPagespeedResponseV5 : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The UTC timestamp of this analysis.</summary> [Newtonsoft.Json.JsonPropertyAttribute("analysisUTCTimestamp")] public virtual string AnalysisUTCTimestamp { get; set; } /// <summary>The captcha verify result</summary> [Newtonsoft.Json.JsonPropertyAttribute("captchaResult")] public virtual string CaptchaResult { get; set; } /// <summary>Canonicalized and final URL for the document, after following page redirects (if any).</summary> [Newtonsoft.Json.JsonPropertyAttribute("id")] public virtual string Id { get; set; } /// <summary>Kind of result.</summary> [Newtonsoft.Json.JsonPropertyAttribute("kind")] public virtual string Kind { get; set; } /// <summary>Lighthouse response for the audit url as an object.</summary> [Newtonsoft.Json.JsonPropertyAttribute("lighthouseResult")] public virtual LighthouseResultV5 LighthouseResult { get; set; } /// <summary>Metrics of end users' page loading experience.</summary> [Newtonsoft.Json.JsonPropertyAttribute("loadingExperience")] public virtual PagespeedApiLoadingExperienceV5 LoadingExperience { get; set; } /// <summary>Metrics of the aggregated page loading experience of the origin</summary> [Newtonsoft.Json.JsonPropertyAttribute("originLoadingExperience")] public virtual PagespeedApiLoadingExperienceV5 OriginLoadingExperience { get; set; } /// <summary>The version of PageSpeed used to generate these results.</summary> [Newtonsoft.Json.JsonPropertyAttribute("version")] public virtual PagespeedApiPagespeedResponseV5.VersionData Version { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } /// <summary>The version of PageSpeed used to generate these results.</summary> public class VersionData { /// <summary>The major version number of PageSpeed used to generate these results.</summary> [Newtonsoft.Json.JsonPropertyAttribute("major")] public virtual System.Nullable<int> Major { get; set; } /// <summary>The minor version number of PageSpeed used to generate these results.</summary> [Newtonsoft.Json.JsonPropertyAttribute("minor")] public virtual System.Nullable<int> Minor { get; set; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Runtime.InteropServices; using System.Threading.Tasks; using Microsoft.DotNet.RemoteExecutor; using Xunit; namespace System.Threading.Tests { public class MutexTests : FileCleanupTestBase { [Fact] public void Ctor_ConstructWaitRelease() { using (Mutex m = new Mutex()) { m.CheckedWait(); m.ReleaseMutex(); } using (Mutex m = new Mutex(false)) { m.CheckedWait(); m.ReleaseMutex(); } using (Mutex m = new Mutex(true)) { m.CheckedWait(); m.ReleaseMutex(); m.ReleaseMutex(); } } [Fact] [PlatformSpecific(TestPlatforms.AnyUnix)] public void Ctor_InvalidNames_Unix() { AssertExtensions.Throws<ArgumentException>("name", null, () => new Mutex(false, new string('a', 1000), out bool createdNew)); } [Theory] [MemberData(nameof(GetValidNames))] public void Ctor_ValidName(string name) { bool createdNew; using (Mutex m1 = new Mutex(false, name, out createdNew)) { Assert.True(createdNew); using (Mutex m2 = new Mutex(false, name, out createdNew)) { Assert.False(createdNew); } } } [PlatformSpecific(TestPlatforms.Windows)] // named semaphores aren't supported on Unix [Fact] public void Ctor_NameUsedByOtherSynchronizationPrimitive_Windows() { string name = Guid.NewGuid().ToString("N"); using (Semaphore s = new Semaphore(1, 1, name)) { Assert.Throws<WaitHandleCannotBeOpenedException>(() => new Mutex(false, name)); } } [PlatformSpecific(TestPlatforms.Windows)] [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotInAppContainer))] // Can't create global objects in appcontainer public void Ctor_ImpersonateAnonymousAndTryCreateGlobalMutexTest() { ThreadTestHelpers.RunTestInBackgroundThread(() => { if (!ImpersonateAnonymousToken(GetCurrentThread())) { // Impersonation is not allowed in the current context, this test is inappropriate in such a case return; } Assert.Throws<UnauthorizedAccessException>(() => new Mutex(false, "Global\\" + Guid.NewGuid().ToString("N"))); Assert.True(RevertToSelf()); }); } [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsInAppContainer))] // Can't create global objects in appcontainer [PlatformSpecific(TestPlatforms.Windows)] public void Ctor_TryCreateGlobalMutexTest_Uwp() { ThreadTestHelpers.RunTestInBackgroundThread(() => Assert.Throws<UnauthorizedAccessException>(() => new Mutex(false, "Global\\" + Guid.NewGuid().ToString("N")))); } [Theory] [MemberData(nameof(GetValidNames))] public void OpenExisting(string name) { Mutex resultHandle; Assert.False(Mutex.TryOpenExisting(name, out resultHandle)); using (Mutex m1 = new Mutex(false, name)) { using (Mutex m2 = Mutex.OpenExisting(name)) { m1.CheckedWait(); Assert.False(Task.Factory.StartNew(() => m2.WaitOne(0), CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default).Result); m1.ReleaseMutex(); m2.CheckedWait(); Assert.False(Task.Factory.StartNew(() => m1.WaitOne(0), CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default).Result); m2.ReleaseMutex(); } Assert.True(Mutex.TryOpenExisting(name, out resultHandle)); Assert.NotNull(resultHandle); resultHandle.Dispose(); } } [Fact] public void OpenExisting_InvalidNames() { AssertExtensions.Throws<ArgumentNullException>("name", () => Mutex.OpenExisting(null)); AssertExtensions.Throws<ArgumentException>("name", null, () => Mutex.OpenExisting(string.Empty)); } [Fact] public void OpenExisting_UnavailableName() { string name = Guid.NewGuid().ToString("N"); Assert.Throws<WaitHandleCannotBeOpenedException>(() => Mutex.OpenExisting(name)); Mutex ignored; Assert.False(Mutex.TryOpenExisting(name, out ignored)); } [PlatformSpecific(TestPlatforms.Windows)] // named semaphores aren't supported on Unix [Fact] public void OpenExisting_NameUsedByOtherSynchronizationPrimitive_Windows() { string name = Guid.NewGuid().ToString("N"); using (Semaphore sema = new Semaphore(1, 1, name)) { Assert.Throws<WaitHandleCannotBeOpenedException>(() => Mutex.OpenExisting(name)); Mutex ignored; Assert.False(Mutex.TryOpenExisting(name, out ignored)); } } public enum WaitHandleWaitType { WaitOne, WaitAny, WaitAll } private static IEnumerable<string> GetNamePrefixes() { yield return string.Empty; yield return "Local\\"; yield return "Global\\"; } public static IEnumerable<object[]> AbandonExisting_MemberData() { var nameGuidStr = Guid.NewGuid().ToString("N"); foreach (WaitHandleWaitType waitType in Enum.GetValues(typeof(WaitHandleWaitType))) { foreach (int waitCount in new int[] { 1, 3 }) { if (waitType == WaitHandleWaitType.WaitOne && waitCount != 1) { continue; } for (int notAbandonedWaitIndex = 0; notAbandonedWaitIndex < waitCount; ++notAbandonedWaitIndex) { foreach (bool abandonDuringWait in new bool[] { false, true }) { var args = new object[] { null, // name waitType, waitCount, notAbandonedWaitIndex, false, // isNotAbandonedWaitObjectSignaled abandonDuringWait }; bool includeArgsForSignaledNotAbandonedWaitObject = waitCount != 1 && (waitType == WaitHandleWaitType.WaitAll || !abandonDuringWait); yield return (object[])args.Clone(); if (includeArgsForSignaledNotAbandonedWaitObject) { var newArgs = (object[])args.Clone(); newArgs[4] = true; // isNotAbandonedWaitObjectSignaled yield return newArgs; } if (waitCount == 1 || PlatformDetection.IsWindows) { foreach (var namePrefix in GetNamePrefixes()) { var newArgs = (object[])args.Clone(); newArgs[0] = namePrefix + nameGuidStr; yield return newArgs; if (includeArgsForSignaledNotAbandonedWaitObject) { newArgs = (object[])newArgs.Clone(); newArgs[4] = true; // isNotAbandonedWaitObjectSignaled yield return newArgs; } } } } } } } } [Theory] [MemberData(nameof(AbandonExisting_MemberData))] public void AbandonExisting( string name, WaitHandleWaitType waitType, int waitCount, int notAbandonedWaitIndex, bool isNotAbandonedWaitObjectSignaled, bool abandonDuringWait) { ThreadTestHelpers.RunTestInBackgroundThread(() => { using (var m = new Mutex(false, name)) using (Mutex m2 = waitCount == 1 ? null : new Mutex(false, name == null ? null : name + "_2")) using (ManualResetEvent e = waitCount == 1 ? null : new ManualResetEvent(isNotAbandonedWaitObjectSignaled)) using (ManualResetEvent threadReadyForAbandon = abandonDuringWait ? new ManualResetEvent(false) : null) using (ManualResetEvent abandonSoon = abandonDuringWait ? new ManualResetEvent(false) : null) { WaitHandle[] waitHandles = null; if (waitType != WaitHandleWaitType.WaitOne) { waitHandles = new WaitHandle[waitCount]; if (waitCount == 1) { waitHandles[0] = m; } else { waitHandles[notAbandonedWaitIndex] = e; waitHandles[notAbandonedWaitIndex == 0 ? 1 : 0] = m; waitHandles[notAbandonedWaitIndex == 2 ? 1 : 2] = m2; } } Thread t = ThreadTestHelpers.CreateGuardedThread(out Action waitForThread, () => { Assert.True(m.WaitOne(0)); if (m2 != null) { Assert.True(m2.WaitOne(0)); } if (abandonDuringWait) { threadReadyForAbandon.Set(); abandonSoon.CheckedWait(); Thread.Sleep(ThreadTestHelpers.ExpectedTimeoutMilliseconds); } // don't release the mutexes; abandon them on this thread }); t.IsBackground = true; t.Start(); if (abandonDuringWait) { threadReadyForAbandon.CheckedWait(); abandonSoon.Set(); } else { waitForThread(); } AbandonedMutexException ame; switch (waitType) { case WaitHandleWaitType.WaitOne: ame = AssertExtensions.Throws<AbandonedMutexException, bool>( () => m.WaitOne(ThreadTestHelpers.UnexpectedTimeoutMilliseconds)); Assert.Equal(-1, ame.MutexIndex); Assert.Null(ame.Mutex); break; case WaitHandleWaitType.WaitAny: if (waitCount != 1 && isNotAbandonedWaitObjectSignaled && notAbandonedWaitIndex == 0) { Assert.Equal(0, WaitHandle.WaitAny(waitHandles, 0)); AssertExtensions.Throws<AbandonedMutexException, bool>( () => m.WaitOne(ThreadTestHelpers.UnexpectedTimeoutMilliseconds)); AssertExtensions.Throws<AbandonedMutexException, bool>( () => m2.WaitOne(ThreadTestHelpers.UnexpectedTimeoutMilliseconds)); break; } if (waitCount != 1 && isNotAbandonedWaitObjectSignaled && notAbandonedWaitIndex != 0) { ame = Assert.Throws<AbandonedMutexException>(() => { ThreadTestHelpers.WaitForCondition(() => { // Actually expecting an exception from WaitAny(), but there may be a delay before // the mutex is actually released and abandoned. If there is no exception, the // WaitAny() must have succeeded due to the event being signaled. int r = WaitHandle.WaitAny(waitHandles, ThreadTestHelpers.UnexpectedTimeoutMilliseconds); Assert.Equal(notAbandonedWaitIndex, r); return false; }); }); } else { ame = AssertExtensions.Throws<AbandonedMutexException, int>( () => WaitHandle.WaitAny(waitHandles, ThreadTestHelpers.UnexpectedTimeoutMilliseconds)); } // Due to a potential delay in abandoning mutexes, either mutex may have been seen to be // abandoned first Assert.True(ame.Mutex == m || (m2 != null && ame.Mutex == m2)); int mIndex = waitCount != 1 && notAbandonedWaitIndex == 0 ? 1 : 0; int m2Index = waitCount != 1 && notAbandonedWaitIndex == 2 ? 1 : 2; if (ame.Mutex == m) { Assert.Equal(mIndex, ame.MutexIndex); } else { Assert.True(m2Index < notAbandonedWaitIndex); Assert.Equal(m2Index, ame.MutexIndex); } // Verify that the other mutex also gets abandoned if (ame.MutexIndex == mIndex) { if (m2 != null) { AssertExtensions.Throws<AbandonedMutexException, bool>( () => m2.WaitOne(ThreadTestHelpers.UnexpectedTimeoutMilliseconds)); } } else { AssertExtensions.Throws<AbandonedMutexException, bool>( () => m.WaitOne(ThreadTestHelpers.UnexpectedTimeoutMilliseconds)); } break; case WaitHandleWaitType.WaitAll: if (waitCount != 1 && !isNotAbandonedWaitObjectSignaled) { Assert.False(WaitHandle.WaitAll(waitHandles, ThreadTestHelpers.ExpectedTimeoutMilliseconds * 2)); Assert.True(e.Set()); } ame = AssertExtensions.Throws<AbandonedMutexException, bool>( () => WaitHandle.WaitAll(waitHandles, ThreadTestHelpers.UnexpectedTimeoutMilliseconds)); Assert.Equal(-1, ame.MutexIndex); Assert.Null(ame.Mutex); break; } if (abandonDuringWait) { waitForThread(); } m.ReleaseMutex(); m2?.ReleaseMutex(); } }); } public static IEnumerable<object[]> CrossProcess_NamedMutex_ProtectedFileAccessAtomic_MemberData() { var nameGuidStr = Guid.NewGuid().ToString("N"); foreach (var namePrefix in GetNamePrefixes()) { yield return new object[] { namePrefix + nameGuidStr }; } } [ActiveIssue(34666)] [Theory] [MemberData(nameof(CrossProcess_NamedMutex_ProtectedFileAccessAtomic_MemberData))] public void CrossProcess_NamedMutex_ProtectedFileAccessAtomic(string prefix) { ThreadTestHelpers.RunTestInBackgroundThread(() => { string mutexName = prefix + Guid.NewGuid().ToString("N"); string fileName = GetTestFilePath(); Action<string, string> otherProcess = (m, f) => { using (var mutex = Mutex.OpenExisting(m)) { mutex.CheckedWait(); try { File.WriteAllText(f, "0"); } finally { mutex.ReleaseMutex(); } IncrementValueInFileNTimes(mutex, f, 10); } }; using (var mutex = new Mutex(false, mutexName)) using (var remote = RemoteExecutor.Invoke(otherProcess, mutexName, fileName)) { SpinWait.SpinUntil(() => File.Exists(fileName), ThreadTestHelpers.UnexpectedTimeoutMilliseconds); IncrementValueInFileNTimes(mutex, fileName, 10); } Assert.Equal(20, int.Parse(File.ReadAllText(fileName))); }); } private static void IncrementValueInFileNTimes(Mutex mutex, string fileName, int n) { for (int i = 0; i < n; i++) { mutex.CheckedWait(); try { int current = int.Parse(File.ReadAllText(fileName)); Thread.Sleep(10); File.WriteAllText(fileName, (current + 1).ToString()); } finally { mutex.ReleaseMutex(); } } } public static TheoryData<string> GetValidNames() { var names = new TheoryData<string>() { Guid.NewGuid().ToString("N") }; if (PlatformDetection.IsWindows) names.Add(Guid.NewGuid().ToString("N") + new string('a', 1000)); return names; } [DllImport("kernel32.dll")] private static extern IntPtr GetCurrentThread(); [DllImport("advapi32.dll")] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool ImpersonateAnonymousToken(IntPtr threadHandle); [DllImport("advapi32.dll")] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool RevertToSelf(); } }
using System; using System.Xml; using System.Data; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using WeifenLuo.WinFormsUI.Docking; using MyMeta; namespace MyGeneration { /// <summary> /// Summary description for LanguageMappings. /// </summary> public class LanguageMappings : DockContent, IMyGenContent { private IMyGenerationMDI mdi; GridLayoutHelper gridLayoutHelper; private System.ComponentModel.IContainer components; private System.Windows.Forms.ComboBox cboxLanguage; private System.Windows.Forms.DataGrid XmlEditor; private System.Windows.Forms.ImageList imageList1; private System.Windows.Forms.ToolBar toolBar1; private System.Windows.Forms.ToolBarButton toolBarButton_Save; private System.Windows.Forms.ToolBarButton toolBarButton_New; private System.Windows.Forms.ToolBarButton toolBarButton1; private System.Windows.Forms.ToolBarButton toolBarButton_Delete; private System.Windows.Forms.DataGridTextBoxColumn col_From; private System.Windows.Forms.DataGridTextBoxColumn col_To; private System.Windows.Forms.DataGridTableStyle MyXmlStyle; public LanguageMappings(IMyGenerationMDI mdi) { InitializeComponent(); this.mdi = mdi; this.ShowHint = DockState.DockRight; } protected override string GetPersistString() { return this.GetType().FullName; } /// <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.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(LanguageMappings)); this.cboxLanguage = new System.Windows.Forms.ComboBox(); this.imageList1 = new System.Windows.Forms.ImageList(this.components); this.XmlEditor = new System.Windows.Forms.DataGrid(); this.MyXmlStyle = new System.Windows.Forms.DataGridTableStyle(); this.col_From = new System.Windows.Forms.DataGridTextBoxColumn(); this.col_To = new System.Windows.Forms.DataGridTextBoxColumn(); this.toolBar1 = new System.Windows.Forms.ToolBar(); this.toolBarButton_Save = new System.Windows.Forms.ToolBarButton(); this.toolBarButton_New = new System.Windows.Forms.ToolBarButton(); this.toolBarButton1 = new System.Windows.Forms.ToolBarButton(); this.toolBarButton_Delete = new System.Windows.Forms.ToolBarButton(); ((System.ComponentModel.ISupportInitialize)(this.XmlEditor)).BeginInit(); this.SuspendLayout(); // // cboxLanguage // this.cboxLanguage.Dock = System.Windows.Forms.DockStyle.Top; this.cboxLanguage.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cboxLanguage.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.cboxLanguage.Location = new System.Drawing.Point(2, 2); this.cboxLanguage.Name = "cboxLanguage"; this.cboxLanguage.Size = new System.Drawing.Size(494, 21); this.cboxLanguage.TabIndex = 11; this.cboxLanguage.SelectionChangeCommitted += new System.EventHandler(this.cboxLanguage_SelectionChangeCommitted); // // imageList1 // this.imageList1.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imageList1.ImageStream"))); this.imageList1.TransparentColor = System.Drawing.Color.Magenta; this.imageList1.Images.SetKeyName(0, ""); this.imageList1.Images.SetKeyName(1, ""); this.imageList1.Images.SetKeyName(2, ""); // // XmlEditor // this.XmlEditor.AlternatingBackColor = System.Drawing.Color.Moccasin; this.XmlEditor.BackColor = System.Drawing.Color.LightGray; this.XmlEditor.BackgroundColor = System.Drawing.Color.LightGray; this.XmlEditor.CaptionVisible = false; this.XmlEditor.DataMember = ""; this.XmlEditor.Dock = System.Windows.Forms.DockStyle.Fill; this.XmlEditor.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold); this.XmlEditor.GridLineColor = System.Drawing.Color.BurlyWood; this.XmlEditor.HeaderForeColor = System.Drawing.SystemColors.ControlText; this.XmlEditor.Location = new System.Drawing.Point(2, 49); this.XmlEditor.Name = "XmlEditor"; this.XmlEditor.Size = new System.Drawing.Size(494, 951); this.XmlEditor.TabIndex = 7; this.XmlEditor.TableStyles.AddRange(new System.Windows.Forms.DataGridTableStyle[] { this.MyXmlStyle}); // // MyXmlStyle // this.MyXmlStyle.AlternatingBackColor = System.Drawing.Color.LightGray; this.MyXmlStyle.BackColor = System.Drawing.Color.LightSteelBlue; this.MyXmlStyle.DataGrid = this.XmlEditor; this.MyXmlStyle.GridColumnStyles.AddRange(new System.Windows.Forms.DataGridColumnStyle[] { this.col_From, this.col_To}); this.MyXmlStyle.GridLineColor = System.Drawing.Color.DarkGray; this.MyXmlStyle.HeaderForeColor = System.Drawing.SystemColors.ControlText; this.MyXmlStyle.MappingName = "Language"; // // col_From // this.col_From.Format = ""; this.col_From.FormatInfo = null; this.col_From.HeaderText = "From"; this.col_From.MappingName = "From"; this.col_From.NullText = ""; this.col_From.Width = 75; // // col_To // this.col_To.Format = ""; this.col_To.FormatInfo = null; this.col_To.HeaderText = "To"; this.col_To.MappingName = "To"; this.col_To.NullText = ""; this.col_To.Width = 75; // // toolBar1 // this.toolBar1.Appearance = System.Windows.Forms.ToolBarAppearance.Flat; this.toolBar1.Buttons.AddRange(new System.Windows.Forms.ToolBarButton[] { this.toolBarButton_Save, this.toolBarButton_New, this.toolBarButton1, this.toolBarButton_Delete}); this.toolBar1.Divider = false; this.toolBar1.DropDownArrows = true; this.toolBar1.ImageList = this.imageList1; this.toolBar1.Location = new System.Drawing.Point(2, 23); this.toolBar1.Name = "toolBar1"; this.toolBar1.ShowToolTips = true; this.toolBar1.Size = new System.Drawing.Size(494, 26); this.toolBar1.TabIndex = 13; this.toolBar1.ButtonClick += new System.Windows.Forms.ToolBarButtonClickEventHandler(this.toolBar1_ButtonClick); // // toolBarButton_Save // this.toolBarButton_Save.ImageIndex = 0; this.toolBarButton_Save.Name = "toolBarButton_Save"; this.toolBarButton_Save.Tag = "save"; this.toolBarButton_Save.ToolTipText = "Save Language Mappings"; // // toolBarButton_New // this.toolBarButton_New.ImageIndex = 2; this.toolBarButton_New.Name = "toolBarButton_New"; this.toolBarButton_New.Tag = "new"; this.toolBarButton_New.ToolTipText = "Create New Language Mapping"; // // toolBarButton1 // this.toolBarButton1.Name = "toolBarButton1"; this.toolBarButton1.Style = System.Windows.Forms.ToolBarButtonStyle.Separator; // // toolBarButton_Delete // this.toolBarButton_Delete.ImageIndex = 1; this.toolBarButton_Delete.Name = "toolBarButton_Delete"; this.toolBarButton_Delete.Tag = "delete"; this.toolBarButton_Delete.ToolTipText = "Delete Language Mappings"; // // LanguageMappings // this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.AutoScroll = true; this.ClientSize = new System.Drawing.Size(498, 1002); this.Controls.Add(this.XmlEditor); this.Controls.Add(this.toolBar1); this.Controls.Add(this.cboxLanguage); this.HideOnClose = true; this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.Name = "LanguageMappings"; this.Padding = new System.Windows.Forms.Padding(2); this.TabText = "Language Mappings"; this.Text = "Language Mappings"; this.Load += new System.EventHandler(this.LanguageMappings_Load); ((System.ComponentModel.ISupportInitialize)(this.XmlEditor)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion /*public void DefaultSettingsChanged(DefaultSettings settings) { PromptForSave(false); this.dbDriver = settings.DbDriver; PopulateComboBox(settings); PopulateGrid(this.dbDriver); MarkAsDirty(false); }*/ public bool CanClose(bool allowPrevent) { return PromptForSave(allowPrevent); } private bool PromptForSave(bool allowPrevent) { bool canClose = true; if(this.isDirty) { DialogResult result; if(allowPrevent) { result = MessageBox.Show("The Language Mappings have been Modified, Do you wish to save them?", "Language Mappings", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question); } else { result = MessageBox.Show("The Language Mappings have been Modified, Do you wish to save them?", "Language Mappings", MessageBoxButtons.YesNo, MessageBoxIcon.Question); } switch(result) { case DialogResult.Yes: { DefaultSettings settings = DefaultSettings.Instance; xml.Save(settings.LanguageMappingFile); MarkAsDirty(false); } break; case DialogResult.Cancel: canClose = false; break; } } return canClose; } private void MarkAsDirty(bool isDirty) { this.isDirty = isDirty; this.toolBarButton_Save.Visible = isDirty; } public void Show(DockPanel dockManager) { DefaultSettings settings = DefaultSettings.Instance; if (!System.IO.File.Exists(settings.LanguageMappingFile)) { MessageBox.Show(this, "Language Mapping File does not exist at: " + settings.LanguageMappingFile + "\r\nPlease fix this in DefaultSettings."); } else { base.Show(dockManager); } } private void LanguageMappings_Load(object sender, System.EventArgs e) { this.col_From.TextBox.BorderStyle = BorderStyle.None; this.col_To.TextBox.BorderStyle = BorderStyle.None; this.col_From.TextBox.Move += new System.EventHandler(this.ColorTextBox); this.col_To.TextBox.Move += new System.EventHandler(this.ColorTextBox); DefaultSettings settings = DefaultSettings.Instance; this.dbDriver = settings.DbDriver; this.xml.Load(settings.LanguageMappingFile); PopulateComboBox(settings); PopulateGrid(this.dbDriver); MarkAsDirty(false); gridLayoutHelper = new GridLayoutHelper(XmlEditor, MyXmlStyle, new decimal[] { 0.50M, 0.50M }, new int[] { 100, 100 }); } private void cboxLanguage_SelectionChangeCommitted(object sender, System.EventArgs e) { DefaultSettings settings = DefaultSettings.Instance; PopulateGrid(this.dbDriver); } private void PopulateComboBox(DefaultSettings settings) { this.cboxLanguage.Items.Clear(); // Populate the ComboBox dbRoot myMeta = new dbRoot(); myMeta.LanguageMappingFileName = settings.LanguageMappingFile; myMeta.Language = settings.Language; string[] languages = myMeta.GetLanguageMappings(settings.DbDriver); if(null != languages) { for(int i = 0; i < languages.Length; i++) { this.cboxLanguage.Items.Add(languages[i]); } this.cboxLanguage.SelectedItem = myMeta.Language; if(this.cboxLanguage.SelectedIndex == -1) { // The default doesn't exist, set it to the first in the list this.cboxLanguage.SelectedIndex = 0; } } } private void PopulateGrid(string dbDriver) { string language; if(this.cboxLanguage.SelectedItem != null) { XmlEditor.Enabled = true; language = this.cboxLanguage.SelectedItem as String; } else { XmlEditor.Enabled = false; language = ""; } this.Text = "Language Mappings for " + dbDriver; langNode = this.xml.SelectSingleNode(@"//Languages/Language[@From='" + dbDriver + "' and @To='" + language + "']"); DataSet ds = new DataSet(); DataTable dt = new DataTable("this"); dt.Columns.Add("this", Type.GetType("System.Object")); ds.Tables.Add(dt); dt.Rows.Add(new object[] { this }); dt = new DataTable("Language"); DataColumn from = dt.Columns.Add("From", Type.GetType("System.String")); from.AllowDBNull = false; DataColumn to = dt.Columns.Add("To", Type.GetType("System.String")); to.AllowDBNull = false; ds.Tables.Add(dt); UniqueConstraint pk = new UniqueConstraint(from, false); dt.Constraints.Add(pk); ds.EnforceConstraints = true; if(null != langNode) { foreach(XmlNode mappingpNode in langNode.ChildNodes) { XmlAttributeCollection attrs = mappingpNode.Attributes; string sFrom = attrs["From"].Value; string sTo = attrs["To"].Value; dt.Rows.Add( new object[] { sFrom, sTo } ); } dt.AcceptChanges(); } XmlEditor.DataSource = dt; dt.RowChanged += new DataRowChangeEventHandler(GridRowChanged); dt.RowDeleting += new DataRowChangeEventHandler(GridRowDeleting); dt.RowDeleted += new DataRowChangeEventHandler(GridRowDeleted); } private static void GridRowChanged(object sender, DataRowChangeEventArgs e) { LanguageMappings This = e.Row.Table.DataSet.Tables["this"].Rows[0]["this"] as LanguageMappings; This.MarkAsDirty(true); This.GridRowChangedEvent(sender, e); } private static void GridRowDeleting(object sender, DataRowChangeEventArgs e) { LanguageMappings This = e.Row.Table.DataSet.Tables["this"].Rows[0]["this"] as LanguageMappings; This.MarkAsDirty(true); This.GridRowDeletingEvent(sender, e); } private static void GridRowDeleted(object sender, DataRowChangeEventArgs e) { LanguageMappings This = e.Row.Table.DataSet.Tables["this"].Rows[0]["this"] as LanguageMappings; This.MarkAsDirty(true); This.GridRowDeletedEvent(sender, e); } private void GridRowChangedEvent(object sender, DataRowChangeEventArgs e) { try { string sFrom = e.Row["From"] as string; string sTo = e.Row["To"] as string; string xPath; XmlNode typeNode; switch(e.Row.RowState) { case DataRowState.Added: { typeNode = langNode.OwnerDocument.CreateNode(XmlNodeType.Element, "Type", null); langNode.AppendChild(typeNode); XmlAttribute attr; attr = langNode.OwnerDocument.CreateAttribute("From"); attr.Value = sFrom; typeNode.Attributes.Append(attr); attr = langNode.OwnerDocument.CreateAttribute("To"); attr.Value = sTo; typeNode.Attributes.Append(attr); } break; case DataRowState.Modified: { xPath = @"./Type[@From='" + sFrom + "']"; typeNode = langNode.SelectSingleNode(xPath); typeNode.Attributes["To"].Value = sTo; } break; } } catch {} } private void GridRowDeletingEvent(object sender, DataRowChangeEventArgs e) { string xPath = @"./Type[@From='" + e.Row["From"] + "' and @To='" + e.Row["To"] + "']"; XmlNode node = langNode.SelectSingleNode(xPath); if(node != null) { node.ParentNode.RemoveChild(node); } } private void GridRowDeletedEvent(object sender, DataRowChangeEventArgs e) { DataTable dt = e.Row.Table; dt.RowChanged -= new DataRowChangeEventHandler(GridRowChanged); dt.RowDeleting -= new DataRowChangeEventHandler(GridRowDeleting); dt.RowDeleted -= new DataRowChangeEventHandler(GridRowDeleted); dt.AcceptChanges(); dt.RowChanged += new DataRowChangeEventHandler(GridRowChanged); dt.RowDeleting += new DataRowChangeEventHandler(GridRowDeleting); dt.RowDeleted += new DataRowChangeEventHandler(GridRowDeleted); } private void ColorTextBox(object sender, System.EventArgs e) { TextBox txtBox = (TextBox)sender; // Bail if we're in la la land Size size = txtBox.Size; if(size.Width == 0 && size.Height == 0) { return; } int row = this.XmlEditor.CurrentCell.RowNumber; int col = this.XmlEditor.CurrentCell.ColumnNumber; if(isEven(row)) txtBox.BackColor = Color.LightSteelBlue; else txtBox.BackColor = Color.LightGray; if(col == 0) { if(txtBox.Text == string.Empty) txtBox.ReadOnly = false; else txtBox.ReadOnly = true; } } private bool isEven(int x) { return (x & 1) == 0; } private void toolBar1_ButtonClick(object sender, System.Windows.Forms.ToolBarButtonClickEventArgs e) { DefaultSettings settings = DefaultSettings.Instance; switch(e.Button.Tag as string) { case "save": xml.Save(settings.LanguageMappingFile); MarkAsDirty(false); break; case "new": { int count = this.cboxLanguage.Items.Count; string[] languages = new string[count]; for(int i = 0; i < this.cboxLanguage.Items.Count; i++) { languages[i] = this.cboxLanguage.Items[i] as string; } AddLanguageMappingDialog dialog = new AddLanguageMappingDialog(languages, this.dbDriver); if(dialog.ShowDialog() == DialogResult.OK) { if(dialog.BasedUpon != string.Empty) { string xPath = @"//Languages/Language[@From='" + this.dbDriver + "' and @To='" + dialog.BasedUpon + "']"; XmlNode node = xml.SelectSingleNode(xPath); XmlNode newNode = node.CloneNode(true); newNode.Attributes["To"].Value = dialog.NewLanguage; node.ParentNode.AppendChild(newNode); } else { XmlNode parentNode = xml.SelectSingleNode(@"//Languages"); XmlAttribute attr; // Language Node langNode = xml.CreateNode(XmlNodeType.Element, "Language", null); parentNode.AppendChild(langNode); attr = xml.CreateAttribute("From"); attr.Value = settings.DbDriver; langNode.Attributes.Append(attr); attr = xml.CreateAttribute("To"); attr.Value = dialog.NewLanguage; langNode.Attributes.Append(attr); } this.cboxLanguage.Items.Add(dialog.NewLanguage); this.cboxLanguage.SelectedItem = dialog.NewLanguage; PopulateGrid(this.dbDriver); MarkAsDirty(true); } } break; case "delete": if(this.cboxLanguage.SelectedItem != null) { string language = this.cboxLanguage.SelectedItem as String; DialogResult result = MessageBox.Show("Delete '" + language + "' Mappings. Are you sure?", "Delete Language Mappings", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Warning); if(result == DialogResult.Yes) { string xPath = @"//Languages/Language[@From='" + this.dbDriver + "' and @To='" + language + "']"; XmlNode node = xml.SelectSingleNode(xPath); node.ParentNode.RemoveChild(node); this.cboxLanguage.Items.Remove(language); if(this.cboxLanguage.Items.Count > 0) { this.cboxLanguage.SelectedItem = this.cboxLanguage.SelectedIndex = 0; } PopulateGrid(this.dbDriver); MarkAsDirty(true); } } break; } } private XmlDocument xml = new XmlDocument(); private XmlNode langNode = null; private string dbDriver = ""; private bool isDirty = false; #region IMyGenContent Members public ToolStrip ToolStrip { get { return null; } } public void ProcessAlert(IMyGenContent sender, string command, params object[] args) { if (command == "UpdateDefaultSettings") { DefaultSettings settings = DefaultSettings.Instance; PromptForSave(false); this.dbDriver = settings.DbDriver; PopulateComboBox(settings); PopulateGrid(this.dbDriver); MarkAsDirty(false); } } public DockContent DockContent { get { return this; } } #endregion } }
/*``The contents of this file are subject to the Erlang Public License, * Version 1.1, (the "License"); you may not use this file except in * compliance with the License. You should have received a copy of the * Erlang Public License along with this software. If not, it can be * retrieved via the world wide web at http://www.erlang.org/. * * Software distributed under the License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See * the License for the specific language governing rights and limitations * under the License. * * The Initial Developer of the Original Code is Ericsson Utvecklings AB. * Portions created by Ericsson are Copyright 1999, Ericsson Utvecklings * AB. All Rights Reserved.'' * * Converted from Java to C# by Vlad Dumitrescu (vlad_Dumitrescu@hotmail.com) */ namespace Otp { /*This class implements a generic FIFO queue. There is no upper * bound on the length of the queue, items are linked. */ using System; public class GenericQueue { private const int open = 0; private const int closing = 1; private const int closed = 2; private int status = closed; private Bucket head; private Bucket tail; private int count; private void init() { head = null; tail = null; count = 0; } /*Create an empty queue */ public GenericQueue() { init(); status = open; } /*Clear a queue */ public virtual void flush() { close(); init(); status = open; } public virtual void close() { status = closing; init(); try { System.Threading.Monitor.PulseAll(this); } catch { } status = closed; } /*Add an object to the tail of the queue. * @param o Object to insert in the queue */ public virtual void put(System.Object o) { lock(this) { Bucket b = new Bucket(this, o); if (tail != null) { tail.setNext(b); tail = b; } else { // queue was empty but has one element now head = (tail = b); } count++; // notify any waiting tasks //UPGRADE_TODO: threading! System.Threading.Monitor.PulseAll(this); } } private System.Object get(bool once) { lock(this) { System.Object o = null; while ((o = tryGet()) == null && !once && status == open) { try { //UPGRADE_TODO: threading! System.Threading.Monitor.Wait(this); } catch (System.Threading.ThreadInterruptedException) { } } return o; } } /*Retrieve an object from the head of the queue, or block until * one arrives. * * @return The object at the head of the queue. */ public virtual System.Object get() { return get(false); } /*Retrieve an object from the head of the queue, blocking until * one arrives or until timeout occurs. * * @param timeout Maximum time to block on queue, in ms. Use 0 to poll the queue. * * @exception InterruptedException if the operation times out. * * @return The object at the head of the queue, or null if none arrived in time. */ public virtual System.Object get(long timeout) { if (timeout == -1) return get(false); else if (timeout == 0) return get(true); lock(this) { if (status != open) return null; long currentTime = SupportClass.currentTimeMillis(); long stopTime = currentTime + timeout; System.Object o = null; while (true) { if (status != open || (o = tryGet()) != null) return o; currentTime = SupportClass.currentTimeMillis(); if (stopTime <= currentTime) throw new System.Threading.ThreadInterruptedException("Get operation timed out"); try { //UPGRADE_TODO: threading! System.Threading.Monitor.Wait(this, new TimeSpan((stopTime - currentTime)*TimeSpan.TicksPerMillisecond)); } catch (System.Threading.ThreadInterruptedException) { // ignore, but really should retry operation instead } } } } // attempt to retrieve message from queue head public virtual System.Object tryGet() { System.Object o = null; if (head != null) { o = head.getContents(); head = head.getNext(); count--; if (head == null) { tail = null; count = 0; } } return o; } public virtual int getCount() { lock(this) { return count; } } /* * The Bucket class. The queue is implemented as a linked list * of Buckets. The container holds the queued object and a * reference to the next Bucket. */ internal class Bucket { private void InitBlock(GenericQueue enclosingInstance) { this.enclosingInstance = enclosingInstance; } private GenericQueue enclosingInstance; private Bucket next; private System.Object contents; public Bucket(GenericQueue enclosingInstance, System.Object o) { InitBlock(enclosingInstance); next = null; contents = o; } public virtual void setNext(Bucket newNext) { next = newNext; } public virtual Bucket getNext() { return next; } public virtual System.Object getContents() { return contents; } } } }
#region PDFsharp - A .NET library for processing PDF // // Authors: // Stefan Lange (mailto:Stefan.Lange@pdfsharp.com) // // Copyright (c) 2005-2009 empira Software GmbH, Cologne (Germany) // // http://www.pdfsharp.com // http://sourceforge.net/projects/pdfsharp // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. #endregion using System; using System.Diagnostics; using System.Collections.Generic; using System.Reflection; using PdfSharp.Pdf.IO; namespace PdfSharp.Pdf { /// <summary> /// Hold information about the value of a key in a dictionary. This information is used to create /// and interpret this value. /// </summary> internal sealed class KeyDescriptor { /// <summary> /// Initializes a new instance of KeyDescriptor from the specified attribute during a KeysMeta /// initializes itself using reflection. /// </summary> public KeyDescriptor(KeyInfoAttribute attribute) { this.version = attribute.Version; this.keyType = attribute.KeyType; this.fixedValue = attribute.FixedValue; this.objectType = attribute.ObjectType; if (this.version == "") version = "1.0"; } /// <summary> /// Gets or sets the PDF version starting with the availability of the described key. /// </summary> public string Version { get { return this.version; } set { this.version = value; } } string version; public KeyType KeyType { get { return this.keyType; } set { this.keyType = value; } } KeyType keyType; public string KeyValue { get { return this.keyValue; } set { this.keyValue = value; } } string keyValue; public string FixedValue { get { return this.fixedValue; } } string fixedValue; public Type ObjectType { get { return this.objectType; } set { this.objectType = value; } } Type objectType; public bool CanBeIndirect { get { return (this.keyType & KeyType.MustNotBeIndirect) == 0; } } /// <summary> /// Returns the type of the object to be created as value for the described key. /// </summary> public Type GetValueType() { Type type = this.objectType; if (type == null) { // If we have no ObjectType specified, use the KeyType enumeration. switch (this.keyType & KeyType.TypeMask) { case KeyType.Name: type = typeof(PdfName); break; case KeyType.String: type = typeof(PdfString); break; case KeyType.Boolean: type = typeof(PdfBoolean); break; case KeyType.Integer: type = typeof(PdfInteger); break; case KeyType.Real: type = typeof(PdfReal); break; case KeyType.Date: type = typeof(PdfDate); break; case KeyType.Rectangle: type = typeof(PdfRectangle); break; case KeyType.Array: type = typeof(PdfArray); break; case KeyType.Dictionary: type = typeof(PdfDictionary); break; case KeyType.Stream: type = typeof(PdfDictionary); break; // The following types are not yet used case KeyType.NumberTree: throw new NotImplementedException("KeyType.NumberTree"); case KeyType.NameOrArray: throw new NotImplementedException("KeyType.NameOrArray"); case KeyType.ArrayOrDictionary: throw new NotImplementedException("KeyType.ArrayOrDictionary"); case KeyType.StreamOrArray: throw new NotImplementedException("KeyType.StreamOrArray"); case KeyType.ArrayOrNameOrString: throw new NotImplementedException("KeyType.ArrayOrNameOrString"); default: Debug.Assert(false, "Invalid KeyType: " + this.keyType); break; } } return type; } } /// <summary> /// Contains meta information about all keys of a PDF dictionary. /// </summary> internal class DictionaryMeta { public DictionaryMeta(Type type) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy); foreach (FieldInfo field in fields) { object[] attributes = field.GetCustomAttributes(typeof(KeyInfoAttribute), false); if (attributes.Length == 1) { KeyInfoAttribute attribute = (KeyInfoAttribute)attributes[0]; KeyDescriptor descriptor = new KeyDescriptor(attribute); descriptor.KeyValue = (string)field.GetValue(null); this.keyDescriptors[descriptor.KeyValue] = descriptor; } } } public KeyDescriptor this[string key] { get { return this.keyDescriptors[key]; } } readonly Dictionary<string, KeyDescriptor> keyDescriptors = new Dictionary<string, KeyDescriptor>(); } }
using System; using System.Collections.Generic; using System.Drawing; using System.Text; using System.Windows.Forms; using Krystals4ObjectLibrary; namespace Krystals4ControlLibrary { internal partial class PointGroupParameters : UserControl { public PointGroupParameters() { InitializeComponent(); this.Enabled = false; SetInitialValues(); PlanetValueUIntControl.updateContainer += new UnsignedIntControl.UintControlReturnKeyHandler(UpdatePointGroupParameters); StartMomentUIntControl.updateContainer += new UnsignedIntControl.UintControlReturnKeyHandler(UpdatePointGroupParameters); FixedPointsValuesUIntSeqControl.updateContainer += new UnsignedIntSeqControl.UnsignedIntSeqControlReturnKeyHandler(UpdatePointGroupParameters); ShiftAngleFloatControl.updateContainer = new FloatControl.FloatControlReturnKeyHandler(UpdatePointGroupParameters); ShiftRadiusFloatControl.updateContainer = new FloatControl.FloatControlReturnKeyHandler(UpdatePointGroupParameters); RotationFloatControl.updateContainer = new FloatControl.FloatControlReturnKeyHandler(UpdatePointGroupParameters); ToAngleFloatControl.updateContainer = new FloatControl.FloatControlReturnKeyHandler(UpdatePointGroupParameters); ToRadiusFloatControl.updateContainer = new FloatControl.FloatControlReturnKeyHandler(UpdatePointGroupParameters); FromRadiusFloatControl.updateContainer = new FloatControl.FloatControlReturnKeyHandler(UpdatePointGroupParameters); FromAngleFloatControl.updateContainer = new FloatControl.FloatControlReturnKeyHandler(UpdatePointGroupParameters); } #region public functions public void InitSamplePanel( float inputDotSize, float outputDotSize, Pen theLinePen, Brush theOutputFillBrush) { _editingOutputPoints = true; _editingFixedPoints = true; _sg = SamplePanel.CreateGraphics(); _sg.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias; _theLinePen = theLinePen; _theLinePen.DashStyle = System.Drawing.Drawing2D.DashStyle.Dash; _inputDotSize = inputDotSize; _outputDotSize = outputDotSize; _theOutputFillBrush = theOutputFillBrush; // used for filling dots // The following line causes this control to call DrawPanel(), // so requires the above fields to have been set. ColorComboBox.SelectedIndex = 0; // black } public void SetControl() { if (_editingOutputPoints) { if (_editingFixedPoints) { TitleText = "Fixed Ouput Points"; CountLabelText = " Count:"; } else { TitleText = "Output Planet Subpath"; CountLabelText = "Start Moment:"; } } else // editing input (=expansion) points { if (_editingFixedPoints) { TitleText = "Fixed Input Points"; CountLabelText = " Count:"; // this.ShapeComboBox.SelectedIndex = 0; // Circle is default (when editing new fixed input points) } else { TitleText = "Input Planet Subpath"; CountLabelText = "Start Moment:"; // this.ShapeComboBox.SelectedIndex = 1; // Spiral is default (when editing new input planets } } SetValueControls(); DrawSamplePanel(); } private void SetValueControls() { if (_editingFixedPoints) { CountValueLabel.Visible = true; StartMomentUIntControl.Visible = false; FixedPointsValuesUIntSeqControl.Visible = true; FixedPointsValuesLabel.Visible = true; PlanetValueUIntControl.Visible = false; PlanetValueLabel.Visible = false; } else { CountValueLabel.Visible = false; StartMomentUIntControl.Visible = true; FixedPointsValuesUIntSeqControl.Visible = false; FixedPointsValuesLabel.Visible = false; PlanetValueUIntControl.Visible = true; PlanetValueLabel.Visible = true; } } public PointGroup GetPointGroup() { PointGroup pGroup = new PointGroup(); pGroup.Shape = (K.PointGroupShape)ShapeComboBox.SelectedIndex; if (_editingFixedPoints) { pGroup.Value = K.GetUIntList(FixedPointsValuesUIntSeqControl.Sequence.ToString()); pGroup.Count = (uint) pGroup.Value.Count; // the number of values in the Value string } else { pGroup.StartMoment = uint.Parse(StartMomentUIntControl.UnsignedInteger.ToString()); // MidiMoments //if (pGroup.StartMoment == 0) // pGroup.StartMoment = 1; pGroup.Value = K.GetUIntList(PlanetValueUIntControl.UnsignedInteger.ToString()); //pGroup.Count = 1; // this value requires knowledge of the other pointGroups in the planet } pGroup.FromRadius = float.Parse(FromRadiusFloatControl.Float.ToString()); pGroup.FromAngle = float.Parse(FromAngleFloatControl.Float.ToString()); if (pGroup.Shape == K.PointGroupShape.circle) { pGroup.ToRadius = float.Parse(CircleToRadiusValueLabel.Text); pGroup.ToAngle = float.Parse(CircleToAngleValueLabel.Text); } else { pGroup.ToRadius = float.Parse(ToRadiusFloatControl.Float.ToString()); pGroup.ToAngle = float.Parse(ToAngleFloatControl.Float.ToString()); } pGroup.RotateAngle = float.Parse(RotationFloatControl.Float.ToString()); pGroup.TranslateRadius = float.Parse(ShiftRadiusFloatControl.Float.ToString()); pGroup.TranslateAngle = float.Parse(ShiftAngleFloatControl.Float.ToString()); pGroup.Visible = VisibleCheckBox.Checked; pGroup.Color = (K.DisplayColor)ColorComboBox.SelectedIndex; return pGroup; } public void SetPointGroup(PointGroup pg) { if (pg == null) // disable this control { this.Enabled = false; // some objects are rendered black even when this control is disabled, // so hide them as well this.CircleToAngleValueLabel.Visible = false; this.CircleToRadiusValueLabel.Visible = false; this.CountValueLabel.Visible = false; this.SamplePanel.Visible = false; } else { this.Enabled = true; this.CircleToAngleValueLabel.Visible = true; this.CircleToRadiusValueLabel.Visible = true; this.CountValueLabel.Visible = true; this.SamplePanel.Visible = true; this.ShapeComboBox.SelectedIndex = (int)pg.Shape; if (_editingFixedPoints) { FixedPointsValuesUIntSeqControl.Sequence = new StringBuilder( K.GetStringOfUnsignedInts(pg.Value)); CountValueLabel.Text = pg.Value.Count.ToString(); } else { StartMomentUIntControl.UnsignedInteger = new StringBuilder(pg.StartMoment.ToString()); PlanetValueUIntControl.UnsignedInteger = new StringBuilder(pg.Value[0].ToString()); } FromRadiusFloatControl.Float = new StringBuilder(pg.FromRadius.ToString()); FromAngleFloatControl.Float = new StringBuilder(pg.FromAngle.ToString()); if (ShapeComboBox.SelectedIndex == (int)K.PointGroupShape.circle) { CircleToRadiusValueLabel.Visible = true; CircleToAngleValueLabel.Visible = true; ToRadiusFloatControl.Visible = false; ToAngleFloatControl.Visible = false; CircleToRadiusValueLabel.Text = pg.FromRadius.ToString(); CircleToAngleValueLabel.Text = (pg.FromAngle + 360f).ToString(); } else { CircleToRadiusValueLabel.Visible = false; CircleToAngleValueLabel.Visible = false; ToRadiusFloatControl.Visible = true; ToAngleFloatControl.Visible = true; ToRadiusFloatControl.Float = new StringBuilder(pg.ToRadius.ToString()); ToAngleFloatControl.Float = new StringBuilder(pg.ToAngle.ToString()); } RotationFloatControl.Float = new StringBuilder(pg.RotateAngle.ToString()); ShiftRadiusFloatControl.Float = new StringBuilder(pg.TranslateRadius.ToString()); ShiftAngleFloatControl.Float = new StringBuilder(pg.TranslateAngle.ToString()); VisibleCheckBox.Checked = pg.Visible; ColorComboBox.SelectedIndex = (int)pg.Color; } } public List<uint> GetValue() { if (_editingFixedPoints) return (K.GetUIntList(FixedPointsValuesUIntSeqControl.Sequence.ToString())); else return (K.GetUIntList(PlanetValueUIntControl.UnsignedInteger.ToString())); } /// <summary> /// Set by the containing control when these properties change. /// </summary> public bool EditingOutputPoints { set { _editingOutputPoints = value; } } public bool EditingFixedPoints { set { _editingFixedPoints = value; } } public bool Display { get { return VisibleCheckBox.Checked; } } // called when displaying the point group #endregion public functions #region Event Handlers private void VisibleCheckBox_CheckedChanged(object sender, EventArgs e) { UpdatePointGroupParameters(); } private void ShapeComboBox_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e) { if (e.KeyData == Keys.Return || e.KeyData == Keys.Enter) UpdatePointGroupParameters(); } private void ColorComboBox_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e) { if (e.KeyData == Keys.Return || e.KeyData == Keys.Enter) UpdatePointGroupParameters(); } private void ColorComboBox_SelectedIndexChanged(object sender, EventArgs e) { DrawSamplePanel(); if(UpdateFieldEditor != null) UpdateFieldEditor(); } private void GraphicsControl_Paint(object sender, PaintEventArgs e) { DrawSamplePanel(); } #endregion Event Handlers #region Properties /// <summary> /// The PointGroupParameters block should only be accessed by one event-handler at a time, so this flag /// is checked by every event handler prior to accessing the block. If the block is not busy, the Busy /// flag is set to true before the event handler begins its work. The flag is cleared again when the /// event handler is finished. /// If this flag has not been set, the function GetPointGroupParameters() throws an exception. /// </summary> public bool Busy { get { return _busy; } set { _busy = value; } } #endregion Properties #region Delegates /// <summary> /// The UpdateFieldEditor function is delegated to this control's container (the FieldEditorWindow). /// It is called here when any of the following events happen: /// 1) The "Visible" checkbox is checked or unchecked /// 2) The 'return' or 'enter' key is pressed while /// a) the "Shape" or "Colour" combobox is active /// b) one of the contained UintControl, UnsignedIntSeqControl or FloatClontrols is active /// This is done via this.UpdateDisplay(), which is the delegate used diectly by the contained /// controls in 2b. /// </summary> public delegate void PointGroupParametersChangedHandler(); public PointGroupParametersChangedHandler UpdateFieldEditor; private void UpdatePointGroupParameters() // called by subordinate controls as their delegate { if (UpdateFieldEditor != null) UpdateFieldEditor(); // delegated to the FieldEditor (this control's container) } #endregion Delegates #region private functions private void GetShape(object sender, EventArgs e) { ComboBox cb = sender as ComboBox; if (cb.SelectedIndex == -1) cb.SelectedIndex = 0; } private void ShapeComboBox_SelectedIndexChanged(object sender, EventArgs e) { if (ShapeComboBox.SelectedIndex == (int)K.PointGroupShape.circle) { CircleToRadiusValueLabel.Visible = true; CircleToAngleValueLabel.Visible = true; ToRadiusFloatControl.Visible = false; ToAngleFloatControl.Visible = false; } else { CircleToRadiusValueLabel.Visible = false; CircleToAngleValueLabel.Visible = false; ToRadiusFloatControl.Visible = true; ToAngleFloatControl.Visible = true; } } private void GetStartMoment(object sender, EventArgs e) { UnsignedIntControl uic = sender as UnsignedIntControl; if (uic.UnsignedInteger.Length == 0) uic.UnsignedInteger = new StringBuilder("0"); } private void GetFloat(object sender, EventArgs e) { FloatControl fc = sender as FloatControl; if (fc.Float.Length == 0) fc.Float = new StringBuilder("0"); if (ShapeComboBox.SelectedIndex == (int)K.PointGroupShape.circle) { if (fc.Tag.ToString() == "FromRadiusControlTag") CircleToRadiusValueLabel.Text = fc.Float.ToString(); if (fc.Tag.ToString() == "FromAngleControlTag") { float fval = float.Parse(fc.Float.ToString()); fval += 360f; CircleToAngleValueLabel.Text = fval.ToString(); } } } private void UIntSeqControl_Leave(object sender, EventArgs e) { string val = FixedPointsValuesUIntSeqControl.Sequence.ToString(); string[] values = val.Split(' ', '\r', '\n'); if (values[0].Equals("")) CountValueLabel.Text = "0"; else CountValueLabel.Text = values.Length.ToString(); } private string TitleText { set { PointGroupGroupBox.Text = value; } } private string CountLabelText { set { CountLabel.Text = value; } } private void SetInitialValues() { SamplePanel.Visible = false; ShapeComboBox.SelectedIndex = 0; StartMomentUIntControl.UnsignedInteger = new StringBuilder("0"); if (_editingFixedPoints) FixedPointsValuesUIntSeqControl.Sequence = new StringBuilder("0"); else PlanetValueUIntControl.UnsignedInteger = new StringBuilder("0"); FromRadiusFloatControl.Float = new StringBuilder("0"); FromAngleFloatControl.Float = new StringBuilder("0"); ToRadiusFloatControl.Float = new StringBuilder("0"); ToAngleFloatControl.Float = new StringBuilder("0"); RotationFloatControl.Float = new StringBuilder("0"); ShiftRadiusFloatControl.Float = new StringBuilder("0"); ShiftAngleFloatControl.Float = new StringBuilder("0"); //VisibleCheckBox.Checked = false; cant do this because VisibleCheckBox.Checked is being watched! //ColorComboBox.SelectedIndex = 0; cant do this because ColorComboBox.SelectedIndex is being watched! } /// <summary> /// Called when the containing control sets either the Field or Group properties. /// </summary> private void DrawSamplePanel() { if (_sg != null) { _sg.Clear(Color.White); float _inputDotOffset = ((_inputDotSize - 1) / 2) + 0.5f; float _outputDotOffset = ((_outputDotSize - 1) / 2) + 0.5f; float lineOriginX = 11f; // 10f for d == 6 float distance = 31f; // 19f for d == 6 float lineHeight = 8f; GetTheDotPen(); GetTheLinePen(); for (float d = 0; d < 4; d++) { float lineX = lineOriginX + d * distance; if (!_editingFixedPoints && d < 3) // connecting lines are only drawn for planets _sg.DrawLine(_theLinePen, lineX, lineHeight, lineX + distance, lineHeight); if (_editingOutputPoints) // output points { _sg.FillEllipse(_theOutputFillBrush, lineOriginX + (d * distance) - _outputDotOffset, lineHeight - _outputDotOffset, _outputDotSize, _outputDotSize); _sg.DrawEllipse(_theDotPen, lineOriginX + (d * distance) - _outputDotOffset, lineHeight - _outputDotOffset, _outputDotSize, _outputDotSize); } else // input points { _sg.FillEllipse(_theDotPen.Brush, lineOriginX + (d * distance) - _inputDotOffset, lineHeight - _inputDotOffset, _inputDotSize, _inputDotSize); _sg.DrawEllipse(_theDotPen, lineOriginX + (d * distance) - _inputDotOffset, lineHeight - _inputDotOffset, _inputDotSize, _inputDotSize); } } } } /// <summary> /// This control owns these pens. /// </summary> public Pen TheDotPen { get { return _theDotPen; } } public Pen TheLinePen { get { return _theLinePen; } } private void GetTheDotPen() { switch (ColorComboBox.SelectedIndex) { case 0: _theDotPen.Brush = Brushes.Black; break; case 1: _theDotPen.Brush = Brushes.Red; break; case 2: _theDotPen.Brush = Brushes.MediumSeaGreen; break; case 3: _theDotPen.Brush = Brushes.Blue; break; case 4: _theDotPen.Brush = Brushes.DarkOrange; break; case 5: _theDotPen.Brush = Brushes.DarkViolet; break; case 6: _theDotPen.Brush = Brushes.Magenta; break; default: throw new ApplicationException("Unknown point colour."); } } private void GetTheLinePen() { switch (ColorComboBox.SelectedIndex) { case 0: _theLinePen.Brush = Brushes.Gray; break; case 1: _theLinePen.Brush = Brushes.OrangeRed; break; case 2: _theLinePen.Brush = Brushes.MediumSeaGreen; break; case 3: _theLinePen.Brush = Brushes.MediumSlateBlue; break; case 4: _theLinePen.Brush = Brushes.Orange; break; case 5: _theLinePen.Brush = Brushes.Violet; break; case 6: _theLinePen.Brush = Brushes.HotPink; break; default: throw new ApplicationException("Unknown point colour."); } } #endregion private functions #region private variables /// <summary> /// The _busy flag is set to true by an external event handler (using the corresponding Property) when it /// begins working with the PointGroupParameters. The flag must be reset to false when the event handler /// is finished. /// </summary> private bool _busy; private Graphics _sg; // the Graphics object for the Samples Panel private bool _editingOutputPoints; private bool _editingFixedPoints; private Pen _theDotPen = new Pen(Brushes.Black); private Pen _theLinePen; private float _inputDotSize; private float _outputDotSize; private Brush _theOutputFillBrush; #endregion private variables } }
using Lucene.Net.Documents; using Lucene.Net.Index.Extensions; using NUnit.Framework; using System; using Assert = Lucene.Net.TestFramework.Assert; namespace Lucene.Net.Search { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using AtomicReaderContext = Lucene.Net.Index.AtomicReaderContext; using IBits = Lucene.Net.Util.IBits; using Directory = Lucene.Net.Store.Directory; using DirectoryReader = Lucene.Net.Index.DirectoryReader; using Document = Documents.Document; using Field = Field; using FixedBitSet = Lucene.Net.Util.FixedBitSet; using IndexReader = Lucene.Net.Index.IndexReader; using IOUtils = Lucene.Net.Util.IOUtils; using LuceneTestCase = Lucene.Net.Util.LuceneTestCase; using MockAnalyzer = Lucene.Net.Analysis.MockAnalyzer; using RandomIndexWriter = Lucene.Net.Index.RandomIndexWriter; using SerialMergeScheduler = Lucene.Net.Index.SerialMergeScheduler; using SlowCompositeReaderWrapper = Lucene.Net.Index.SlowCompositeReaderWrapper; using StringField = StringField; using Term = Lucene.Net.Index.Term; [TestFixture] public class TestCachingWrapperFilter : LuceneTestCase { private Directory dir; private DirectoryReader ir; private IndexSearcher @is; private RandomIndexWriter iw; [SetUp] public override void SetUp() { base.SetUp(); dir = NewDirectory(); iw = new RandomIndexWriter( #if FEATURE_INSTANCE_TESTDATA_INITIALIZATION this, #endif Random, dir); Document doc = new Document(); Field idField = new StringField("id", "", Field.Store.NO); doc.Add(idField); // add 500 docs with id 0..499 for (int i = 0; i < 500; i++) { idField.SetStringValue(Convert.ToString(i)); iw.AddDocument(doc); } // delete 20 of them for (int i = 0; i < 20; i++) { iw.DeleteDocuments(new Term("id", Convert.ToString(Random.Next(iw.MaxDoc)))); } ir = iw.GetReader(); @is = NewSearcher(ir); } [TearDown] public override void TearDown() { IOUtils.Dispose(iw, ir, dir); base.TearDown(); } private void AssertFilterEquals(Filter f1, Filter f2) { Query query = new MatchAllDocsQuery(); TopDocs hits1 = @is.Search(query, f1, ir.MaxDoc); TopDocs hits2 = @is.Search(query, f2, ir.MaxDoc); Assert.AreEqual(hits1.TotalHits, hits2.TotalHits); CheckHits.CheckEqual(query, hits1.ScoreDocs, hits2.ScoreDocs); // now do it again to confirm caching works TopDocs hits3 = @is.Search(query, f1, ir.MaxDoc); TopDocs hits4 = @is.Search(query, f2, ir.MaxDoc); Assert.AreEqual(hits3.TotalHits, hits4.TotalHits); CheckHits.CheckEqual(query, hits3.ScoreDocs, hits4.ScoreDocs); } /// <summary> /// test null iterator </summary> [Test] public virtual void TestEmpty() { Query query = new BooleanQuery(); Filter expected = new QueryWrapperFilter(query); Filter actual = new CachingWrapperFilter(expected); AssertFilterEquals(expected, actual); } /// <summary> /// test iterator returns NO_MORE_DOCS </summary> [Test] public virtual void TestEmpty2() { BooleanQuery query = new BooleanQuery(); query.Add(new TermQuery(new Term("id", "0")), Occur.MUST); query.Add(new TermQuery(new Term("id", "0")), Occur.MUST_NOT); Filter expected = new QueryWrapperFilter(query); Filter actual = new CachingWrapperFilter(expected); AssertFilterEquals(expected, actual); } /// <summary> /// test null docidset </summary> [Test] public virtual void TestEmpty3() { Filter expected = new PrefixFilter(new Term("bogusField", "bogusVal")); Filter actual = new CachingWrapperFilter(expected); AssertFilterEquals(expected, actual); } /// <summary> /// test iterator returns single document </summary> [Test] public virtual void TestSingle() { for (int i = 0; i < 10; i++) { int id = Random.Next(ir.MaxDoc); Query query = new TermQuery(new Term("id", Convert.ToString(id))); Filter expected = new QueryWrapperFilter(query); Filter actual = new CachingWrapperFilter(expected); AssertFilterEquals(expected, actual); } } /// <summary> /// test sparse filters (match single documents) </summary> [Test] public virtual void TestSparse() { for (int i = 0; i < 10; i++) { int id_start = Random.Next(ir.MaxDoc - 1); int id_end = id_start + 1; Query query = TermRangeQuery.NewStringRange("id", Convert.ToString(id_start), Convert.ToString(id_end), true, true); Filter expected = new QueryWrapperFilter(query); Filter actual = new CachingWrapperFilter(expected); AssertFilterEquals(expected, actual); } } /// <summary> /// test dense filters (match entire index) </summary> [Test] public virtual void TestDense() { Query query = new MatchAllDocsQuery(); Filter expected = new QueryWrapperFilter(query); Filter actual = new CachingWrapperFilter(expected); AssertFilterEquals(expected, actual); } [Test] public virtual void TestCachingWorks() { Directory dir = NewDirectory(); RandomIndexWriter writer = new RandomIndexWriter( #if FEATURE_INSTANCE_TESTDATA_INITIALIZATION this, #endif Random, dir); writer.Dispose(); IndexReader reader = SlowCompositeReaderWrapper.Wrap(DirectoryReader.Open(dir)); AtomicReaderContext context = (AtomicReaderContext)reader.Context; MockFilter filter = new MockFilter(); CachingWrapperFilter cacher = new CachingWrapperFilter(filter); // first time, nested filter is called DocIdSet strongRef = cacher.GetDocIdSet(context, (context.AtomicReader).LiveDocs); Assert.IsTrue(filter.WasCalled(), "first time"); // make sure no exception if cache is holding the wrong docIdSet cacher.GetDocIdSet(context, (context.AtomicReader).LiveDocs); // second time, nested filter should not be called filter.Clear(); cacher.GetDocIdSet(context, (context.AtomicReader).LiveDocs); Assert.IsFalse(filter.WasCalled(), "second time"); reader.Dispose(); dir.Dispose(); } [Test] public virtual void TestNullDocIdSet() { Directory dir = NewDirectory(); RandomIndexWriter writer = new RandomIndexWriter( #if FEATURE_INSTANCE_TESTDATA_INITIALIZATION this, #endif Random, dir); writer.Dispose(); IndexReader reader = SlowCompositeReaderWrapper.Wrap(DirectoryReader.Open(dir)); AtomicReaderContext context = (AtomicReaderContext)reader.Context; Filter filter = new FilterAnonymousClass(this, context); CachingWrapperFilter cacher = new CachingWrapperFilter(filter); // the caching filter should return the empty set constant //Assert.IsNull(cacher.GetDocIdSet(context, "second time", (context.AtomicReader).LiveDocs)); Assert.IsNull(cacher.GetDocIdSet(context, (context.AtomicReader).LiveDocs)); reader.Dispose(); dir.Dispose(); } private class FilterAnonymousClass : Filter { private readonly TestCachingWrapperFilter outerInstance; private AtomicReaderContext context; public FilterAnonymousClass(TestCachingWrapperFilter outerInstance, AtomicReaderContext context) { this.outerInstance = outerInstance; this.context = context; } public override DocIdSet GetDocIdSet(AtomicReaderContext context, IBits acceptDocs) { return null; } } [Test] public virtual void TestNullDocIdSetIterator() { Directory dir = NewDirectory(); RandomIndexWriter writer = new RandomIndexWriter( #if FEATURE_INSTANCE_TESTDATA_INITIALIZATION this, #endif Random, dir); writer.Dispose(); IndexReader reader = SlowCompositeReaderWrapper.Wrap(DirectoryReader.Open(dir)); AtomicReaderContext context = (AtomicReaderContext)reader.Context; Filter filter = new FilterAnonymousClass2(this, context); CachingWrapperFilter cacher = new CachingWrapperFilter(filter); // the caching filter should return the empty set constant Assert.IsNull(cacher.GetDocIdSet(context, (context.AtomicReader).LiveDocs)); reader.Dispose(); dir.Dispose(); } private class FilterAnonymousClass2 : Filter { private readonly TestCachingWrapperFilter outerInstance; private AtomicReaderContext context; public FilterAnonymousClass2(TestCachingWrapperFilter outerInstance, AtomicReaderContext context) { this.outerInstance = outerInstance; this.context = context; } public override DocIdSet GetDocIdSet(AtomicReaderContext context, IBits acceptDocs) { return new DocIdSetAnonymousClass(this); } private class DocIdSetAnonymousClass : DocIdSet { private readonly FilterAnonymousClass2 outerInstance; public DocIdSetAnonymousClass(FilterAnonymousClass2 outerInstance) { this.outerInstance = outerInstance; } public override DocIdSetIterator GetIterator() { return null; } } } private static void AssertDocIdSetCacheable(IndexReader reader, Filter filter, bool shouldCacheable) { Assert.IsTrue(reader.Context is AtomicReaderContext); AtomicReaderContext context = (AtomicReaderContext)reader.Context; CachingWrapperFilter cacher = new CachingWrapperFilter(filter); DocIdSet originalSet = filter.GetDocIdSet(context, (context.AtomicReader).LiveDocs); DocIdSet cachedSet = cacher.GetDocIdSet(context, (context.AtomicReader).LiveDocs); if (originalSet == null) { Assert.IsNull(cachedSet); } if (cachedSet == null) { Assert.IsTrue(originalSet == null || originalSet.GetIterator() == null); } else { Assert.IsTrue(cachedSet.IsCacheable); Assert.AreEqual(shouldCacheable, originalSet.IsCacheable); //System.out.println("Original: "+originalSet.getClass().getName()+" -- cached: "+cachedSet.getClass().getName()); if (originalSet.IsCacheable) { Assert.AreEqual(originalSet.GetType(), cachedSet.GetType(), "Cached DocIdSet must be of same class like uncached, if cacheable"); } else { Assert.IsTrue(cachedSet is FixedBitSet || cachedSet == null, "Cached DocIdSet must be an FixedBitSet if the original one was not cacheable"); } } } [Test] public virtual void TestIsCacheAble() { Directory dir = NewDirectory(); RandomIndexWriter writer = new RandomIndexWriter( #if FEATURE_INSTANCE_TESTDATA_INITIALIZATION this, #endif Random, dir); writer.AddDocument(new Document()); writer.Dispose(); IndexReader reader = SlowCompositeReaderWrapper.Wrap(DirectoryReader.Open(dir)); // not cacheable: AssertDocIdSetCacheable(reader, new QueryWrapperFilter(new TermQuery(new Term("test", "value"))), false); // returns default empty docidset, always cacheable: AssertDocIdSetCacheable(reader, NumericRangeFilter.NewInt32Range("test", Convert.ToInt32(10000), Convert.ToInt32(-10000), true, true), true); // is cacheable: AssertDocIdSetCacheable(reader, FieldCacheRangeFilter.NewInt32Range("test", Convert.ToInt32(10), Convert.ToInt32(20), true, true), true); // a fixedbitset filter is always cacheable AssertDocIdSetCacheable(reader, new FilterAnonymousClass3(this), true); reader.Dispose(); dir.Dispose(); } private class FilterAnonymousClass3 : Filter { private readonly TestCachingWrapperFilter outerInstance; public FilterAnonymousClass3(TestCachingWrapperFilter outerInstance) { this.outerInstance = outerInstance; } public override DocIdSet GetDocIdSet(AtomicReaderContext context, IBits acceptDocs) { return new FixedBitSet(context.Reader.MaxDoc); } } [Test] public virtual void TestEnforceDeletions() { Directory dir = NewDirectory(); RandomIndexWriter writer = new RandomIndexWriter(Random, dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random)).SetMergeScheduler(new SerialMergeScheduler()).SetMergePolicy(NewLogMergePolicy(10))); // asserts below requires no unexpected merges: // NOTE: cannot use writer.getReader because RIW (on // flipping a coin) may give us a newly opened reader, // but we use .reopen on this reader below and expect to // (must) get an NRT reader: DirectoryReader reader = DirectoryReader.Open(writer.IndexWriter, true); // same reason we don't wrap? IndexSearcher searcher = NewSearcher( #if FEATURE_INSTANCE_TESTDATA_INITIALIZATION this, #endif reader, false); // add a doc, refresh the reader, and check that it's there Document doc = new Document(); doc.Add(NewStringField("id", "1", Field.Store.YES)); writer.AddDocument(doc); reader = RefreshReader(reader); searcher = NewSearcher( #if FEATURE_INSTANCE_TESTDATA_INITIALIZATION this, #endif reader, false); TopDocs docs = searcher.Search(new MatchAllDocsQuery(), 1); Assert.AreEqual(1, docs.TotalHits, "Should find a hit..."); Filter startFilter = new QueryWrapperFilter(new TermQuery(new Term("id", "1"))); CachingWrapperFilter filter = new CachingWrapperFilter(startFilter); docs = searcher.Search(new MatchAllDocsQuery(), filter, 1); Assert.IsTrue(filter.GetSizeInBytes() > 0); Assert.AreEqual(1, docs.TotalHits, "[query + filter] Should find a hit..."); Query constantScore = new ConstantScoreQuery(filter); docs = searcher.Search(constantScore, 1); Assert.AreEqual(1, docs.TotalHits, "[just filter] Should find a hit..."); // make sure we get a cache hit when we reopen reader // that had no change to deletions // fake delete (deletes nothing): writer.DeleteDocuments(new Term("foo", "bar")); IndexReader oldReader = reader; reader = RefreshReader(reader); Assert.IsTrue(reader == oldReader); int missCount = filter.missCount; docs = searcher.Search(constantScore, 1); Assert.AreEqual(1, docs.TotalHits, "[just filter] Should find a hit..."); // cache hit: Assert.AreEqual(missCount, filter.missCount); // now delete the doc, refresh the reader, and see that it's not there writer.DeleteDocuments(new Term("id", "1")); // NOTE: important to hold ref here so GC doesn't clear // the cache entry! Else the assert below may sometimes // fail: oldReader = reader; reader = RefreshReader(reader); searcher = NewSearcher(reader, false); missCount = filter.missCount; docs = searcher.Search(new MatchAllDocsQuery(), filter, 1); Assert.AreEqual(0, docs.TotalHits, "[query + filter] Should *not* find a hit..."); // cache hit Assert.AreEqual(missCount, filter.missCount); docs = searcher.Search(constantScore, 1); Assert.AreEqual(0, docs.TotalHits, "[just filter] Should *not* find a hit..."); // apply deletes dynamically: filter = new CachingWrapperFilter(startFilter); writer.AddDocument(doc); reader = RefreshReader(reader); searcher = NewSearcher(reader, false); docs = searcher.Search(new MatchAllDocsQuery(), filter, 1); Assert.AreEqual(1, docs.TotalHits, "[query + filter] Should find a hit..."); missCount = filter.missCount; Assert.IsTrue(missCount > 0); constantScore = new ConstantScoreQuery(filter); docs = searcher.Search(constantScore, 1); Assert.AreEqual(1, docs.TotalHits, "[just filter] Should find a hit..."); Assert.AreEqual(missCount, filter.missCount); writer.AddDocument(doc); // NOTE: important to hold ref here so GC doesn't clear // the cache entry! Else the assert below may sometimes // fail: oldReader = reader; reader = RefreshReader(reader); searcher = NewSearcher( #if FEATURE_INSTANCE_TESTDATA_INITIALIZATION this, #endif reader, false); docs = searcher.Search(new MatchAllDocsQuery(), filter, 1); Assert.AreEqual(2, docs.TotalHits, "[query + filter] Should find 2 hits..."); Assert.IsTrue(filter.missCount > missCount); missCount = filter.missCount; constantScore = new ConstantScoreQuery(filter); docs = searcher.Search(constantScore, 1); Assert.AreEqual(2, docs.TotalHits, "[just filter] Should find a hit..."); Assert.AreEqual(missCount, filter.missCount); // now delete the doc, refresh the reader, and see that it's not there writer.DeleteDocuments(new Term("id", "1")); reader = RefreshReader(reader); searcher = NewSearcher( #if FEATURE_INSTANCE_TESTDATA_INITIALIZATION this, #endif reader, false); docs = searcher.Search(new MatchAllDocsQuery(), filter, 1); Assert.AreEqual(0, docs.TotalHits, "[query + filter] Should *not* find a hit..."); // CWF reused the same entry (it dynamically applied the deletes): Assert.AreEqual(missCount, filter.missCount); docs = searcher.Search(constantScore, 1); Assert.AreEqual(0, docs.TotalHits, "[just filter] Should *not* find a hit..."); // CWF reused the same entry (it dynamically applied the deletes): Assert.AreEqual(missCount, filter.missCount); // NOTE: silliness to make sure JRE does not eliminate // our holding onto oldReader to prevent // CachingWrapperFilter's WeakHashMap from dropping the // entry: Assert.IsTrue(oldReader != null); reader.Dispose(); writer.Dispose(); dir.Dispose(); } private static DirectoryReader RefreshReader(DirectoryReader reader) { DirectoryReader oldReader = reader; reader = DirectoryReader.OpenIfChanged(reader); if (reader != null) { oldReader.Dispose(); return reader; } else { return oldReader; } } } }
// // SegmentedBar.cs // // Author: // Aaron Bockover <abockover@novell.com> // // Copyright (C) 2008 Novell, Inc. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Collections.Generic; using Gtk; using Cairo; using Hyena.Gui; namespace Hyena.Widgets { public class SegmentedBar : Widget { public delegate string BarValueFormatHandler (Segment segment); public class Segment { private string title; private double percent; private Cairo.Color color; private bool show_in_bar; public Segment (string title, double percent, Cairo.Color color) : this (title, percent, color, true) { } public Segment (string title, double percent, Cairo.Color color, bool showInBar) { this.title = title; this.percent = percent; this.color = color; this.show_in_bar = showInBar; } public string Title { get { return title; } set { title = value; } } public double Percent { get { return percent; } set { percent = value; } } public Cairo.Color Color { get { return color; } set { color = value; } } public bool ShowInBar { get { return show_in_bar; } set { show_in_bar = value; } } internal int LayoutWidth; internal int LayoutHeight; } // State private List<Segment> segments = new List<Segment> (); private int layout_width; private int layout_height; // Properties private int bar_height = 26; private int bar_label_spacing = 8; private int segment_label_spacing = 16; private int segment_box_size = 12; private int segment_box_spacing = 6; private int h_padding = 0; private bool show_labels = true; private bool reflect = true; private Color remainder_color = CairoExtensions.RgbToColor (0xeeeeee); private BarValueFormatHandler format_handler; public SegmentedBar () { HasWindow = false; } protected override void OnRealized () { Window = Parent.Window; base.OnRealized (); } #region Size Calculations protected override void OnGetPreferredHeight (out int minimum_height, out int natural_height) { minimum_height = natural_height = 0; } protected override void OnGetPreferredWidth (out int minimum_width, out int natural_width) { minimum_width = natural_width = 200; } protected override void OnSizeAllocated (Gdk.Rectangle allocation) { int _bar_height = reflect ? (int)Math.Ceiling (bar_height * 1.75) : bar_height; if (show_labels) { ComputeLayoutSize (); HeightRequest = Math.Max (bar_height + bar_label_spacing + layout_height, _bar_height); WidthRequest = layout_width + (2 * h_padding); } else { HeightRequest = _bar_height; WidthRequest = bar_height + (2 * h_padding); } base.OnSizeAllocated (allocation); } private void ComputeLayoutSize () { if (segments.Count == 0) { return; } Pango.Layout layout = null; layout_width = layout_height = 0; for (int i = 0, n = segments.Count; i < n; i++) { int aw, ah, bw, bh; layout = CreateAdaptLayout (layout, false, true); layout.SetText (FormatSegmentText (segments[i])); layout.GetPixelSize (out aw, out ah); layout = CreateAdaptLayout (layout, true, false); layout.SetText (FormatSegmentValue (segments[i])); layout.GetPixelSize (out bw, out bh); int w = Math.Max (aw, bw); int h = ah + bh; segments[i].LayoutWidth = w; segments[i].LayoutHeight = Math.Max (h, segment_box_size * 2); layout_width += segments[i].LayoutWidth + segment_box_size + segment_box_spacing + (i < n - 1 ? segment_label_spacing : 0); layout_height = Math.Max (layout_height, segments[i].LayoutHeight); } layout.Dispose (); } #endregion #region Public Methods public void AddSegmentRgba (string title, double percent, uint rgbaColor) { AddSegment (title, percent, CairoExtensions.RgbaToColor (rgbaColor)); } public void AddSegmentRgb (string title, double percent, uint rgbColor) { AddSegment (title, percent, CairoExtensions.RgbToColor (rgbColor)); } public void AddSegment (string title, double percent, Color color) { AddSegment (new Segment (title, percent, color, true)); } public void AddSegment (string title, double percent, Color color, bool showInBar) { AddSegment (new Segment (title, percent, color, showInBar)); } public void AddSegment (Segment segment) { lock (segments) { segments.Add (segment); QueueDraw (); } } public void UpdateSegment (int index, double percent) { segments[index].Percent = percent; QueueDraw (); } #endregion #region Public Properties public BarValueFormatHandler ValueFormatter { get { return format_handler; } set { format_handler = value; } } public Color RemainderColor { get { return remainder_color; } set { remainder_color = value; QueueDraw (); } } public int BarHeight { get { return bar_height; } set { if (bar_height != value) { bar_height = value; QueueResize (); } } } public bool ShowReflection { get { return reflect; } set { if (reflect != value) { reflect = value; QueueResize (); } } } public bool ShowLabels { get { return show_labels; } set { if (show_labels != value) { show_labels = value; QueueResize (); } } } public int SegmentLabelSpacing { get { return segment_label_spacing; } set { if (segment_label_spacing != value) { segment_label_spacing = value; QueueResize (); } } } public int SegmentBoxSize { get { return segment_box_size; } set { if (segment_box_size != value) { segment_box_size = value; QueueResize (); } } } public int SegmentBoxSpacing { get { return segment_box_spacing; } set { if (segment_box_spacing != value) { segment_box_spacing = value; QueueResize (); } } } public int BarLabelSpacing { get { return bar_label_spacing; } set { if (bar_label_spacing != value) { bar_label_spacing = value; QueueResize (); } } } public int HorizontalPadding { get { return h_padding; } set { if (h_padding != value) { h_padding = value; QueueResize (); } } } #endregion #region Rendering protected override bool OnDrawn (Cairo.Context cr) { if (!CairoHelper.ShouldDrawWindow (cr, Window)) { return base.OnDrawn (cr); } if (reflect) { cr.PushGroup (); } cr.Operator = Operator.Over; cr.Translate (h_padding, 0); cr.Rectangle (0, 0, Allocation.Width - h_padding, Math.Max (2 * bar_height, bar_height + bar_label_spacing + layout_height)); cr.Clip (); using (var bar = RenderBar (Allocation.Width - 2 * h_padding, bar_height)) { cr.Save (); cr.SetSource (bar); cr.Paint (); cr.Restore (); if (reflect) { cr.Save (); cr.Rectangle (0, bar_height, Allocation.Width - h_padding, bar_height); cr.Clip (); Matrix matrix = new Matrix (); matrix.InitScale (1, -1); matrix.Translate (0, -(2 * bar_height) + 1); cr.Transform (matrix); cr.SetSource (bar); using (var mask = new LinearGradient (0, 0, 0, bar_height)) { mask.AddColorStop (0.25, new Color (0, 0, 0, 0)); mask.AddColorStop (0.5, new Color (0, 0, 0, 0.125)); mask.AddColorStop (0.75, new Color (0, 0, 0, 0.4)); mask.AddColorStop (1.0, new Color (0, 0, 0, 0.7)); cr.Mask (mask); } cr.Restore (); cr.PopGroupToSource (); cr.Paint (); } if (show_labels) { cr.Translate ((reflect ? 0 : -h_padding) + (Allocation.Width - layout_width) / 2, bar_height + bar_label_spacing); RenderLabels (cr); } } return true; } private Pattern RenderBar (int w, int h) { Pattern pattern; using (var s = new ImageSurface (Format.Argb32, w, h)) { using (var cr = new Context (s)) { RenderBar (cr, w, h, h / 2); // TODO Implement the new ctor - see http://bugzilla.gnome.org/show_bug.cgi?id=561394 #pragma warning disable 0618 pattern = new Pattern (s); #pragma warning restore 0618 } } return pattern; } private void RenderBar (Context cr, int w, int h, int r) { RenderBarSegments (cr, w, h, r); RenderBarStrokes (cr, w, h, r); } private void RenderBarSegments (Context cr, int w, int h, int r) { using (var grad = new LinearGradient (0, 0, w, 0)) { double last = 0.0; foreach (Segment segment in segments) { if (segment.Percent > 0) { grad.AddColorStop (last, segment.Color); grad.AddColorStop (last += segment.Percent, segment.Color); } } CairoExtensions.RoundedRectangle (cr, 0, 0, w, h, r); cr.SetSource (grad); cr.FillPreserve (); } using (var grad = new LinearGradient (0, 0, 0, h)) { grad.AddColorStop (0.0, new Color (1, 1, 1, 0.125)); grad.AddColorStop (0.35, new Color (1, 1, 1, 0.255)); grad.AddColorStop (1, new Color (0, 0, 0, 0.4)); cr.SetSource (grad); cr.Fill (); } } private void RenderBarStrokes (Context cr, int w, int h, int r) { using (var stroke = MakeSegmentGradient (h, CairoExtensions.RgbaToColor (0x00000040))) { using (var seg_sep_light = MakeSegmentGradient (h, CairoExtensions.RgbaToColor (0xffffff20))) { using (var seg_sep_dark = MakeSegmentGradient (h, CairoExtensions.RgbaToColor (0x00000020))) { cr.LineWidth = 1; double seg_w = 20; double x = seg_w > r ? seg_w : r; while (x <= w - r) { cr.MoveTo (x - 0.5, 1); cr.LineTo (x - 0.5, h - 1); cr.SetSource (seg_sep_light); cr.Stroke (); cr.MoveTo (x + 0.5, 1); cr.LineTo (x + 0.5, h - 1); cr.SetSource (seg_sep_dark); cr.Stroke (); x += seg_w; } CairoExtensions.RoundedRectangle (cr, 0.5, 0.5, w - 1, h - 1, r); cr.SetSource (stroke); cr.Stroke (); } } } } private LinearGradient MakeSegmentGradient (int h, Color color) { return MakeSegmentGradient (h, color, false); } private LinearGradient MakeSegmentGradient (int h, Color color, bool diag) { LinearGradient grad = new LinearGradient (0, 0, 0, h); grad.AddColorStop (0, CairoExtensions.ColorShade (color, 1.1)); grad.AddColorStop (0.35, CairoExtensions.ColorShade (color, 1.2)); grad.AddColorStop (1, CairoExtensions.ColorShade (color, 0.8)); return grad; } private void RenderLabels (Context cr) { if (segments.Count == 0) { return; } Pango.Layout layout = null; Gdk.RGBA rgba = StyleContext.GetColor (StateFlags); Color text_color = CairoExtensions.GdkRGBAToCairoColor (rgba); Color box_stroke_color = new Color (0, 0, 0, 0.6); int x = 0; foreach (Segment segment in segments) { cr.LineWidth = 1; cr.Rectangle (x + 0.5, 2 + 0.5, segment_box_size - 1, segment_box_size - 1); using (var grad = MakeSegmentGradient (segment_box_size, segment.Color, true)) { cr.SetSource (grad); cr.FillPreserve (); cr.SetSourceColor (box_stroke_color); cr.Stroke (); } x += segment_box_size + segment_box_spacing; int lw, lh; layout = CreateAdaptLayout (layout, false, true); layout.SetText (FormatSegmentText (segment)); layout.GetPixelSize (out lw, out lh); cr.MoveTo (x, 0); text_color.A = 0.9; cr.SetSourceColor (text_color); Pango.CairoHelper.ShowLayout (cr, layout); cr.Fill (); layout = CreateAdaptLayout (layout, true, false); layout.SetText (FormatSegmentValue (segment)); cr.MoveTo (x, lh); text_color.A = 0.75; cr.SetSourceColor (text_color); Pango.CairoHelper.ShowLayout (cr, layout); cr.Fill (); x += segment.LayoutWidth + segment_label_spacing; } layout.Dispose (); } #endregion #region Utilities private int pango_size_normal; private Pango.Layout CreateAdaptLayout (Pango.Layout layout, bool small, bool bold) { if (layout == null) { Pango.Context context = CreatePangoContext (); layout = new Pango.Layout (context); layout.FontDescription = context.FontDescription; pango_size_normal = layout.FontDescription.Size; } layout.FontDescription.Size = small ? (int)(layout.FontDescription.Size * Pango.Scale.Small) : pango_size_normal; layout.FontDescription.Weight = bold ? Pango.Weight.Bold : Pango.Weight.Normal; return layout; } private string FormatSegmentText (Segment segment) { return segment.Title; } private string FormatSegmentValue (Segment segment) { return format_handler == null ? String.Format ("{0}%", segment.Percent * 100.0) : format_handler (segment); } #endregion } #region Test Module [TestModule ("Segmented Bar")] internal class SegmentedBarTestModule : Window { private SegmentedBar bar; private VBox box; public SegmentedBarTestModule () : base ("Segmented Bar") { BorderWidth = 10; AppPaintable = true; box = new VBox (); box.Spacing = 10; Add (box); int space = 55; bar = new SegmentedBar (); bar.HorizontalPadding = bar.BarHeight / 2; bar.AddSegmentRgb ("Audio", 0.00187992456702332, 0x3465a4); bar.AddSegmentRgb ("Other", 0.0788718162651326, 0xf57900); bar.AddSegmentRgb ("Video", 0.0516869922033282, 0x73d216); bar.AddSegment ("Free Space", 0.867561266964516, bar.RemainderColor, false); bar.ValueFormatter = delegate (SegmentedBar.Segment segment) { return String.Format ("{0} GB", space * segment.Percent); }; HBox controls = new HBox (); controls.Spacing = 5; Label label = new Label ("Height:"); controls.PackStart (label, false, false, 0); SpinButton height = new SpinButton (new Adjustment (bar.BarHeight, 5, 100, 1, 1, 1), 1, 0); height.Activated += delegate { bar.BarHeight = height.ValueAsInt; }; height.Changed += delegate { bar.BarHeight = height.ValueAsInt; bar.HorizontalPadding = bar.BarHeight / 2; }; controls.PackStart (height, false, false, 0); CheckButton reflect = new CheckButton ("Reflection"); reflect.Active = bar.ShowReflection; reflect.Toggled += delegate { bar.ShowReflection = reflect.Active; }; controls.PackStart (reflect, false, false, 0); CheckButton labels = new CheckButton ("Labels"); labels.Active = bar.ShowLabels; labels.Toggled += delegate { bar.ShowLabels = labels.Active; }; controls.PackStart (labels, false, false, 0); box.PackStart (controls, false, false, 0); box.PackStart (new HSeparator (), false, false, 0); box.PackStart (bar, false, false, 0); box.ShowAll (); SetSizeRequest (350, -1); Gdk.Geometry limits = new Gdk.Geometry (); int nat_width; GetPreferredWidth (out limits.MinWidth, out nat_width); limits.MaxWidth = Gdk.Screen.Default.Width; limits.MinHeight = -1; limits.MaxHeight = -1; SetGeometryHints (this, limits, Gdk.WindowHints.MaxSize | Gdk.WindowHints.MinSize); } } #endregion }
using System; using System.Collections.Generic; using LogoFX.Bootstrapping; #if (NET || NETCORE || NETFRAMEWORK) && !TEST #endif #if !TEST && (NETFX_CORE || WINDOWS_UWP) using Windows.ApplicationModel; using Windows.ApplicationModel.Activation; #endif using LogoFX.Client.Bootstrapping.Adapters.Contracts; using Solid.Extensibility; using Solid.Practices.IoC; using Solid.Practices.Middleware; namespace LogoFX.Client.Bootstrapping { /// <summary> /// Application bootstrapper with ioc container and its adapter. /// </summary> /// <typeparam name="TIocContainerAdapter">The type of the ioc container adapter.</typeparam> /// <typeparam name="TIocContainer">The type of the ioc container.</typeparam> public partial class #if TEST TestBootstrapperContainerBase #else BootstrapperContainerBase #endif <TIocContainerAdapter, TIocContainer> : #if TEST TestBootstrapperContainerBase #else BootstrapperContainerBase #endif <TIocContainerAdapter>, IBootstrapperWithContainer<TIocContainerAdapter, TIocContainer> where TIocContainerAdapter : class, IIocContainer, IIocContainerAdapter<TIocContainer>, IBootstrapperAdapter where TIocContainer : class { /// <summary> /// Application bootstrapper with ioc container, its adapter and root object. /// </summary> /// <typeparam name="TRootObject"></typeparam> public new class WithRootObject<TRootObject> : #if TEST TestBootstrapperContainerBase #else BootstrapperContainerBase #endif <TIocContainerAdapter, TIocContainer> { #if TEST /// <summary> /// Initializes a new instance of <see cref="TestBootstrapperContainerBase{TIocContainerAdapter, TIocContainer}.WithRootObject{TRootObject}"/> /// </summary> /// <param name="iocContainer">The ioc container.</param> /// <param name="adapterCreator">The adapter creation function.</param> #else /// <summary> /// Initializes a new instance of <see cref="BootstrapperContainerBase{TIocContainerAdapter, TIocContainer}.WithRootObject{TRootObject}"/> /// </summary> /// <param name="iocContainer">The ioc container.</param> /// <param name="adapterCreator">The adapter creation function.</param> #endif public WithRootObject(TIocContainer iocContainer, Func<TIocContainer, TIocContainerAdapter> adapterCreator) : this(iocContainer, adapterCreator, new BootstrapperCreationOptions { ExcludedTypes = new List<Type> { typeof(TRootObject) } }) { } #if TEST /// <summary> /// Initializes a new instance of <see cref="TestBootstrapperContainerBase{TIocContainerAdapter, TIocContainer}.WithRootObject{TRootObject}"/> /// </summary> /// <param name="iocContainer">The ioc container.</param> /// <param name="adapterCreator">The adapter creation function.</param> /// <param name="creationOptions">The bootstrapper creation options.</param> #else /// <summary> /// Initializes a new instance of <see cref="BootstrapperContainerBase{TIocContainerAdapter, TIocContainer}.WithRootObject{TRootObject}"/> /// </summary> /// <param name="iocContainer">The ioc container.</param> /// <param name="adapterCreator">The adapter creation function.</param> /// <param name="creationOptions">The bootstrapper creation options.</param> #endif public WithRootObject(TIocContainer iocContainer, Func<TIocContainer, TIocContainerAdapter> adapterCreator, BootstrapperCreationOptions creationOptions) : base(iocContainer, adapterCreator, AddRootObject(creationOptions)) { Use(new CreateRootObjectMiddleware<TIocContainerAdapter>( typeof(TRootObject), creationOptions.DisplayRootView, true)); } private static BootstrapperCreationOptions AddRootObject(BootstrapperCreationOptions creationOptions) { if (creationOptions.ExcludedTypes == null) { creationOptions.ExcludedTypes = new List<Type>(); } if (creationOptions.ExcludedTypes.Contains(typeof(TRootObject)) == false) { creationOptions.ExcludedTypes.Add(typeof(TRootObject)); } return creationOptions; } } /// <summary> /// Application bootstrapper with ioc container, its adapter and root object. /// </summary> /// <typeparam name="TRootObject"></typeparam> public new class WithRootObjectAsContract<TRootObject> : #if TEST TestBootstrapperContainerBase #else BootstrapperContainerBase #endif <TIocContainerAdapter, TIocContainer> { #if TEST /// <summary> /// Initializes a new instance of <see cref="TestBootstrapperContainerBase{TIocContainerAdapter, TIocContainer}.WithRootObject{TRootObject}"/> /// </summary> /// <param name="iocContainer">The ioc container.</param> /// <param name="adapterCreator">The adapter creation function.</param> #else /// <summary> /// Initializes a new instance of <see cref="BootstrapperContainerBase{TIocContainerAdapter, TIocContainer}.WithRootObject{TRootObject}"/> /// </summary> /// <param name="iocContainer">The ioc container.</param> /// <param name="adapterCreator">The adapter creation function.</param> #endif public WithRootObjectAsContract(TIocContainer iocContainer, Func<TIocContainer, TIocContainerAdapter> adapterCreator) : this(iocContainer, adapterCreator, new BootstrapperCreationOptions { ExcludedTypes = new List<Type> { typeof(TRootObject) }, RegisterRoot = false }) { } #if TEST /// <summary> /// Initializes a new instance of <see cref="TestBootstrapperContainerBase{TIocContainerAdapter, TIocContainer}.WithRootObject{TRootObject}"/> /// </summary> /// <param name="iocContainer">The ioc container.</param> /// <param name="adapterCreator">The adapter creation function.</param> /// <param name="creationOptions">The bootstrapper creation options.</param> #else /// <summary> /// Initializes a new instance of <see cref="BootstrapperContainerBase{TIocContainerAdapter, TIocContainer}.WithRootObject{TRootObject}"/> /// </summary> /// <param name="iocContainer">The ioc container.</param> /// <param name="adapterCreator">The adapter creation function.</param> /// <param name="creationOptions">The bootstrapper creation options.</param> #endif public WithRootObjectAsContract(TIocContainer iocContainer, Func<TIocContainer, TIocContainerAdapter> adapterCreator, BootstrapperCreationOptions creationOptions) : base(iocContainer, adapterCreator, AddRootObjectAsContract(creationOptions)) { Use(new CreateRootObjectMiddleware<TIocContainerAdapter>( typeof(TRootObject), creationOptions.DisplayRootView, creationOptions.RegisterRoot)); } private static BootstrapperCreationOptions AddRootObjectAsContract(BootstrapperCreationOptions creationOptions) { if (creationOptions.ExcludedTypes == null) { creationOptions.ExcludedTypes = new List<Type>(); } if (creationOptions.ExcludedTypes.Contains(typeof(TRootObject)) == false) { creationOptions.ExcludedTypes.Add(typeof(TRootObject)); } creationOptions.RegisterRoot = false; return creationOptions; } } #if TEST /// <summary> /// Initializes a new instance of the /// <see cref="TestBootstrapperContainerBase{TIocContainerAdapter, TIocContainer}"/> class. /// </summary> /// <param name="iocContainer">The ioc container.</param> /// <param name="adapterCreator">The adapter creator function.</param> #else /// <summary> /// Initializes a new instance of the /// <see cref="BootstrapperContainerBase{TIocContainerAdapter, TIocContainer}"/> class. /// </summary> /// <param name="iocContainer">The ioc container.</param> /// <param name="adapterCreator">The adapter creator function.</param> #endif public #if TEST TestBootstrapperContainerBase #else BootstrapperContainerBase #endif ( TIocContainer iocContainer, Func<TIocContainer, TIocContainerAdapter> adapterCreator) : this(iocContainer, adapterCreator, new BootstrapperCreationOptions()) { } #if TEST /// <summary> /// Initializes a new instance of the /// <see cref="TestBootstrapperContainerBase{TIocContainerAdapter, TIocContainer}"/> class. /// </summary> /// <param name="iocContainer">The ioc container.</param> /// <param name="adapterCreator">The adapter creator function.</param> /// <param name="creationOptions">The bootstrapper creation options.</param> #else /// <summary> /// Initializes a new instance of the /// <see cref="BootstrapperContainerBase{TIocContainerAdapter, TIocContainer}"/> class. /// </summary> /// <param name="iocContainer">The ioc container.</param> /// <param name="adapterCreator">The adapter creator function.</param> /// <param name="creationOptions">The bootstrapper creation options.</param> #endif public #if TEST TestBootstrapperContainerBase #else BootstrapperContainerBase #endif ( TIocContainer iocContainer, Func<TIocContainer, TIocContainerAdapter> adapterCreator, BootstrapperCreationOptions creationOptions) : base(adapterCreator(iocContainer), creationOptions) { Container = iocContainer; _middlewaresWrapper = new MiddlewaresWrapper<IBootstrapperWithContainer<TIocContainerAdapter, TIocContainer>>(this); if (creationOptions.UseDefaultMiddlewares) { Use(new RegisterCompositionModulesMiddleware<TIocContainerAdapter, TIocContainer>()); } } /// <summary> /// Gets the container. /// </summary> /// <value> /// The container. /// </value> public TIocContainer Container { get; } /// <summary> /// Override this method to inject custom logic during bootstrapper configuration. /// </summary> /// <param name="dependencyRegistrator">The dependency registrator.</param> protected override void OnConfigure(IDependencyRegistrator dependencyRegistrator) { base.OnConfigure(dependencyRegistrator); MiddlewareApplier.ApplyMiddlewares(this, _middlewaresWrapper.Middlewares); } } }
//----------------------------------------------------------------------------- // Copyright (c) 2012 GarageGames, LLC // // 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. //----------------------------------------------------------------------------- //---------------------------------------------------------------------------- // Player Audio Profiles //---------------------------------------------------------------------------- datablock SFXProfile(DeathCrySound) { fileName = "art/sound/orc_death"; description = AudioClose3d; preload = true; }; datablock SFXProfile(PainCrySound) { fileName = "art/sound/orc_pain"; description = AudioClose3d; preload = true; }; //---------------------------------------------------------------------------- datablock SFXProfile(FootLightSoftSound) { filename = "art/sound/lgtStep_mono_01"; description = AudioClosest3d; preload = true; }; datablock SFXProfile(FootLightHardSound) { filename = "art/sound/hvystep_ mono_01"; description = AudioClose3d; preload = true; }; datablock SFXProfile(FootLightMetalSound) { filename = "art/sound/metalstep_mono_01"; description = AudioClose3d; preload = true; }; datablock SFXProfile(FootLightSnowSound) { filename = "art/sound/snowstep_mono_01"; description = AudioClosest3d; preload = true; }; datablock SFXProfile(FootLightShallowSplashSound) { filename = "art/sound/waterstep_mono_01"; description = AudioClose3d; preload = true; }; datablock SFXProfile(FootLightWadingSound) { filename = "art/sound/waterstep_mono_01"; description = AudioClose3d; preload = true; }; datablock SFXProfile(FootLightUnderwaterSound) { filename = "art/sound/waterstep_mono_01"; description = AudioClosest3d; preload = true; }; //---------------------------------------------------------------------------- // Splash //---------------------------------------------------------------------------- datablock ParticleData(PlayerSplashMist) { dragCoefficient = 2.0; gravityCoefficient = -0.05; inheritedVelFactor = 0.0; constantAcceleration = 0.0; lifetimeMS = 400; lifetimeVarianceMS = 100; useInvAlpha = false; spinRandomMin = -90.0; spinRandomMax = 500.0; textureName = "art/shapes/actors/common/splash"; colors[0] = "0.7 0.8 1.0 1.0"; colors[1] = "0.7 0.8 1.0 0.5"; colors[2] = "0.7 0.8 1.0 0.0"; sizes[0] = 0.5; sizes[1] = 0.5; sizes[2] = 0.8; times[0] = 0.0; times[1] = 0.5; times[2] = 1.0; }; datablock ParticleEmitterData(PlayerSplashMistEmitter) { ejectionPeriodMS = 5; periodVarianceMS = 0; ejectionVelocity = 3.0; velocityVariance = 2.0; ejectionOffset = 0.0; thetaMin = 85; thetaMax = 85; phiReferenceVel = 0; phiVariance = 360; overrideAdvance = false; lifetimeMS = 250; particles = "PlayerSplashMist"; }; datablock ParticleData(PlayerBubbleParticle) { dragCoefficient = 0.0; gravityCoefficient = -0.50; inheritedVelFactor = 0.0; constantAcceleration = 0.0; lifetimeMS = 400; lifetimeVarianceMS = 100; useInvAlpha = false; textureName = "art/shapes/actors/common/splash"; colors[0] = "0.7 0.8 1.0 0.4"; colors[1] = "0.7 0.8 1.0 0.4"; colors[2] = "0.7 0.8 1.0 0.0"; sizes[0] = 0.1; sizes[1] = 0.3; sizes[2] = 0.3; times[0] = 0.0; times[1] = 0.5; times[2] = 1.0; }; datablock ParticleEmitterData(PlayerBubbleEmitter) { ejectionPeriodMS = 1; periodVarianceMS = 0; ejectionVelocity = 2.0; ejectionOffset = 0.5; velocityVariance = 0.5; thetaMin = 0; thetaMax = 80; phiReferenceVel = 0; phiVariance = 360; overrideAdvance = false; particles = "PlayerBubbleParticle"; }; datablock ParticleData(PlayerFoamParticle) { dragCoefficient = 2.0; gravityCoefficient = -0.05; inheritedVelFactor = 0.1; constantAcceleration = 0.0; lifetimeMS = 600; lifetimeVarianceMS = 100; useInvAlpha = false; spinRandomMin = -90.0; spinRandomMax = 500.0; textureName = "art/particles/millsplash01"; colors[0] = "0.7 0.8 1.0 0.20"; colors[1] = "0.7 0.8 1.0 0.20"; colors[2] = "0.7 0.8 1.0 0.00"; sizes[0] = 0.2; sizes[1] = 0.4; sizes[2] = 1.6; times[0] = 0.0; times[1] = 0.5; times[2] = 1.0; }; datablock ParticleEmitterData(PlayerFoamEmitter) { ejectionPeriodMS = 10; periodVarianceMS = 0; ejectionVelocity = 3.0; velocityVariance = 1.0; ejectionOffset = 0.0; thetaMin = 85; thetaMax = 85; phiReferenceVel = 0; phiVariance = 360; overrideAdvance = false; particles = "PlayerFoamParticle"; }; datablock ParticleData( PlayerFoamDropletsParticle ) { dragCoefficient = 1; gravityCoefficient = 0.2; inheritedVelFactor = 0.2; constantAcceleration = -0.0; lifetimeMS = 600; lifetimeVarianceMS = 0; textureName = "art/shapes/actors/common/splash"; colors[0] = "0.7 0.8 1.0 1.0"; colors[1] = "0.7 0.8 1.0 0.5"; colors[2] = "0.7 0.8 1.0 0.0"; sizes[0] = 0.8; sizes[1] = 0.3; sizes[2] = 0.0; times[0] = 0.0; times[1] = 0.5; times[2] = 1.0; }; datablock ParticleEmitterData( PlayerFoamDropletsEmitter ) { ejectionPeriodMS = 7; periodVarianceMS = 0; ejectionVelocity = 2; velocityVariance = 1.0; ejectionOffset = 0.0; thetaMin = 60; thetaMax = 80; phiReferenceVel = 0; phiVariance = 360; overrideAdvance = false; orientParticles = true; particles = "PlayerFoamDropletsParticle"; }; datablock ParticleData( PlayerWakeParticle ) { textureName = "art/particles/wake"; dragCoefficient = "0.0"; gravityCoefficient = "0.0"; inheritedVelFactor = "0.0"; lifetimeMS = "2500"; lifetimeVarianceMS = "200"; windCoefficient = "0.0"; useInvAlpha = "1"; spinRandomMin = "30.0"; spinRandomMax = "30.0"; animateTexture = true; framesPerSec = 1; animTexTiling = "2 1"; animTexFrames = "0 1"; colors[0] = "1 1 1 0.1"; colors[1] = "1 1 1 0.7"; colors[2] = "1 1 1 0.3"; colors[3] = "0.5 0.5 0.5 0"; sizes[0] = "1.0"; sizes[1] = "2.0"; sizes[2] = "3.0"; sizes[3] = "3.5"; times[0] = "0.0"; times[1] = "0.25"; times[2] = "0.5"; times[3] = "1.0"; }; datablock ParticleEmitterData( PlayerWakeEmitter ) { ejectionPeriodMS = "200"; periodVarianceMS = "10"; ejectionVelocity = "0"; velocityVariance = "0"; ejectionOffset = "0"; thetaMin = "89"; thetaMax = "90"; phiReferenceVel = "0"; phiVariance = "1"; alignParticles = "1"; alignDirection = "0 0 1"; particles = "PlayerWakeParticle"; }; datablock ParticleData( PlayerSplashParticle ) { dragCoefficient = 1; gravityCoefficient = 0.2; inheritedVelFactor = 0.2; constantAcceleration = -0.0; lifetimeMS = 600; lifetimeVarianceMS = 0; colors[0] = "0.7 0.8 1.0 1.0"; colors[1] = "0.7 0.8 1.0 0.5"; colors[2] = "0.7 0.8 1.0 0.0"; sizes[0] = 0.5; sizes[1] = 0.5; sizes[2] = 0.5; times[0] = 0.0; times[1] = 0.5; times[2] = 1.0; }; datablock ParticleEmitterData( PlayerSplashEmitter ) { ejectionPeriodMS = 1; periodVarianceMS = 0; ejectionVelocity = 3; velocityVariance = 1.0; ejectionOffset = 0.0; thetaMin = 60; thetaMax = 80; phiReferenceVel = 0; phiVariance = 360; overrideAdvance = false; orientParticles = true; lifetimeMS = 100; particles = "PlayerSplashParticle"; }; datablock SplashData(PlayerSplash) { numSegments = 15; ejectionFreq = 15; ejectionAngle = 40; ringLifetime = 0.5; lifetimeMS = 300; velocity = 4.0; startRadius = 0.0; acceleration = -3.0; texWrap = 5.0; texture = "art/particles/millsplash01"; emitter[0] = PlayerSplashEmitter; emitter[1] = PlayerSplashMistEmitter; colors[0] = "0.7 0.8 1.0 0.0"; colors[1] = "0.7 0.8 1.0 0.3"; colors[2] = "0.7 0.8 1.0 0.7"; colors[3] = "0.7 0.8 1.0 0.0"; times[0] = 0.0; times[1] = 0.4; times[2] = 0.8; times[3] = 1.0; }; //---------------------------------------------------------------------------- // Foot puffs //---------------------------------------------------------------------------- datablock ParticleData(LightPuff) { dragCoefficient = 2.0; gravityCoefficient = -0.01; inheritedVelFactor = 0.6; constantAcceleration = 0.0; lifetimeMS = 800; lifetimeVarianceMS = 100; useInvAlpha = true; spinRandomMin = -35.0; spinRandomMax = 35.0; colors[0] = "1.0 1.0 1.0 1.0"; colors[1] = "1.0 1.0 1.0 0.0"; sizes[0] = 0.1; sizes[1] = 0.8; times[0] = 0.3; times[1] = 1.0; times[2] = 1.0; textureName = "art/particles/dustParticle.png"; }; datablock ParticleEmitterData(LightPuffEmitter) { ejectionPeriodMS = 35; periodVarianceMS = 10; ejectionVelocity = 0.2; velocityVariance = 0.1; ejectionOffset = 0.0; thetaMin = 20; thetaMax = 60; phiReferenceVel = 0; phiVariance = 360; overrideAdvance = false; useEmitterColors = true; particles = "LightPuff"; }; //---------------------------------------------------------------------------- // Liftoff dust //---------------------------------------------------------------------------- datablock ParticleData(LiftoffDust) { dragCoefficient = 1.0; gravityCoefficient = -0.01; inheritedVelFactor = 0.0; constantAcceleration = 0.0; lifetimeMS = 1000; lifetimeVarianceMS = 100; useInvAlpha = true; spinRandomMin = -90.0; spinRandomMax = 500.0; colors[0] = "1.0 1.0 1.0 1.0"; sizes[0] = 1.0; times[0] = 1.0; textureName = "art/particles/dustParticle"; }; datablock ParticleEmitterData(LiftoffDustEmitter) { ejectionPeriodMS = 5; periodVarianceMS = 0; ejectionVelocity = 2.0; velocityVariance = 0.0; ejectionOffset = 0.0; thetaMin = 90; thetaMax = 90; phiReferenceVel = 0; phiVariance = 360; overrideAdvance = false; useEmitterColors = true; particles = "LiftoffDust"; }; //---------------------------------------------------------------------------- datablock DecalData(PlayerFootprint) { size = 0.4; material = CommonPlayerFootprint; }; datablock DebrisData( PlayerDebris ) { explodeOnMaxBounce = false; elasticity = 0.15; friction = 0.5; lifetime = 4.0; lifetimeVariance = 0.0; minSpinSpeed = 40; maxSpinSpeed = 600; numBounces = 5; bounceVariance = 0; staticOnMaxBounce = true; gravModifier = 1.0; useRadiusMass = true; baseRadius = 1; velocity = 20.0; velocityVariance = 12.0; }; // ---------------------------------------------------------------------------- // This is our default player datablock that all others will derive from. // ---------------------------------------------------------------------------- datablock PlayerData(DefaultPlayerData) { renderFirstPerson = false; firstPersonShadows = true; computeCRC = false; // Third person shape shapeFile = "art/shapes/actors/Soldier/soldier_rigged.DAE"; cameraMaxDist = 3; allowImageStateAnimation = true; // First person arms imageAnimPrefixFP = "soldier"; shapeNameFP[0] = "art/shapes/actors/Soldier/FP/FP_SoldierArms.DAE"; cmdCategory = "Clients"; cameraDefaultFov = 55.0; cameraMinFov = 5.0; cameraMaxFov = 65.0; debrisShapeName = "art/shapes/actors/common/debris_player.dts"; debris = playerDebris; throwForce = 30; minLookAngle = "-1.4"; maxLookAngle = "0.9"; maxFreelookAngle = 3.0; mass = 120; drag = 1.3; maxdrag = 0.4; density = 1.1; maxDamage = 100; maxEnergy = 60; repairRate = 0.33; rechargeRate = 0.256; runForce = 4320; runEnergyDrain = 0; minRunEnergy = 0; maxForwardSpeed = 8; maxBackwardSpeed = 6; maxSideSpeed = 6; sprintForce = 4320; sprintEnergyDrain = 0; minSprintEnergy = 0; maxSprintForwardSpeed = 14; maxSprintBackwardSpeed = 8; maxSprintSideSpeed = 6; sprintStrafeScale = 0.25; sprintYawScale = 0.05; sprintPitchScale = 0.05; sprintCanJump = true; crouchForce = 405; maxCrouchForwardSpeed = 4.0; maxCrouchBackwardSpeed = 2.0; maxCrouchSideSpeed = 2.0; swimForce = 4320; maxUnderwaterForwardSpeed = 8.4; maxUnderwaterBackwardSpeed = 7.8; maxUnderwaterSideSpeed = 4.0; jumpForce = "747"; jumpEnergyDrain = 0; minJumpEnergy = 0; jumpDelay = "15"; airControl = 0.3; fallingSpeedThreshold = -6.0; landSequenceTime = 0.33; transitionToLand = false; recoverDelay = 0; recoverRunForceScale = 0; minImpactSpeed = 10; minLateralImpactSpeed = 20; speedDamageScale = 0.4; boundingBox = "0.65 0.75 1.85"; crouchBoundingBox = "0.65 0.75 1.3"; swimBoundingBox = "1 2 2"; pickupRadius = 1; // Damage location details boxHeadPercentage = 0.83; boxTorsoPercentage = 0.49; boxHeadLeftPercentage = 0.30; boxHeadRightPercentage = 0.60; boxHeadBackPercentage = 0.30; boxHeadFrontPercentage = 0.60; // Foot Prints decalOffset = 0.25; footPuffEmitter = "LightPuffEmitter"; footPuffNumParts = 10; footPuffRadius = "0.25"; dustEmitter = "LightPuffEmitter"; splash = PlayerSplash; splashVelocity = 4.0; splashAngle = 67.0; splashFreqMod = 300.0; splashVelEpsilon = 0.60; bubbleEmitTime = 0.4; splashEmitter[0] = PlayerWakeEmitter; splashEmitter[1] = PlayerFoamEmitter; splashEmitter[2] = PlayerBubbleEmitter; mediumSplashSoundVelocity = 10.0; hardSplashSoundVelocity = 20.0; exitSplashSoundVelocity = 5.0; // Controls over slope of runnable/jumpable surfaces runSurfaceAngle = 38; jumpSurfaceAngle = 80; maxStepHeight = 0.35; //two meters minJumpSpeed = 20; maxJumpSpeed = 30; horizMaxSpeed = 68; horizResistSpeed = 33; horizResistFactor = 0.35; upMaxSpeed = 80; upResistSpeed = 25; upResistFactor = 0.3; footstepSplashHeight = 0.35; //NOTE: some sounds commented out until wav's are available // Footstep Sounds FootSoftSound = FootLightSoftSound; FootHardSound = FootLightHardSound; FootMetalSound = FootLightMetalSound; FootSnowSound = FootLightSnowSound; FootShallowSound = FootLightShallowSplashSound; FootWadingSound = FootLightWadingSound; FootUnderwaterSound = FootLightUnderwaterSound; //FootBubblesSound = FootLightBubblesSound; //movingBubblesSound = ArmorMoveBubblesSound; //waterBreathSound = WaterBreathMaleSound; //impactSoftSound = ImpactLightSoftSound; //impactHardSound = ImpactLightHardSound; //impactMetalSound = ImpactLightMetalSound; //impactSnowSound = ImpactLightSnowSound; //impactWaterEasy = ImpactLightWaterEasySound; //impactWaterMedium = ImpactLightWaterMediumSound; //impactWaterHard = ImpactLightWaterHardSound; groundImpactMinSpeed = "45"; groundImpactShakeFreq = "4.0 4.0 4.0"; groundImpactShakeAmp = "1.0 1.0 1.0"; groundImpactShakeDuration = 0.8; groundImpactShakeFalloff = 10.0; //exitingWater = ExitingWaterLightSound; cameraMinDist = "0"; DecalData = "PlayerFootprint"; // Allowable Inventory Items mainWeapon = Ryder; maxInv[Lurker] = 1; maxInv[LurkerClip] = 20; maxInv[LurkerGrenadeLauncher] = 1; maxInv[LurkerGrenadeAmmo] = 20; maxInv[Ryder] = 1; maxInv[RyderClip] = 10; maxInv[ProxMine] = 5; maxInv[DeployableTurret] = 5; // available skins (see materials.cs in model folder) availableSkins = "base DarkBlue DarkGreen LightGreen Orange Red Teal Violet Yellow"; };
/* Copyright 2019 Esri Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.Windows.Forms; using System.Runtime.InteropServices; using ESRI.ArcGIS.DataSourcesFile; using ESRI.ArcGIS.esriSystem; using ESRI.ArcGIS.Framework; using ESRI.ArcGIS.ArcMapUI; using ESRI.ArcGIS.Carto; using ESRI.ArcGIS.Geometry; using ESRI.ArcGIS.Catalog; using ESRI.ArcGIS.CatalogUI; using ESRI.ArcGIS.Location; using ESRI.ArcGIS.LocationUI; using ESRI.ArcGIS.Geodatabase; using ESRI.ArcGIS.Display; namespace RoutingSample { [Microsoft.VisualBasic.CompilerServices.DesignerGenerated()] public partial class RoutingForm : System.Windows.Forms.Form { //Form overrides dispose to clean up the component list. [System.Diagnostics.DebuggerNonUserCode()] protected override void Dispose(bool disposing) { if (disposing && components != null) components.Dispose(); base.Dispose(disposing); } //Required by the Windows Form Designer private System.ComponentModel.IContainer components; //NOTE: The following procedure is required by the Windows Form Designer //It can be modified using the Windows Form Designer. //Do not modify it using the code editor. [System.Diagnostics.DebuggerStepThrough()] private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(RoutingForm)); this.m_btnFindRoute = new System.Windows.Forms.Button(); this.m_btnClose = new System.Windows.Forms.Button(); this.Label1 = new System.Windows.Forms.Label(); this.m_txtRoutingService = new System.Windows.Forms.TextBox(); this.m_dlgRoutingSrvc = new System.Windows.Forms.OpenFileDialog(); this.m_btnRoutingService = new System.Windows.Forms.Button(); this.ImageList1 = new System.Windows.Forms.ImageList(this.components); this.m_btnAddressLocator = new System.Windows.Forms.Button(); this.m_txtAddressLocator = new System.Windows.Forms.TextBox(); this.Label2 = new System.Windows.Forms.Label(); this.GroupBox1 = new System.Windows.Forms.GroupBox(); this.m_txtStartAddress = new System.Windows.Forms.TextBox(); this.Label6 = new System.Windows.Forms.Label(); this.Label5 = new System.Windows.Forms.Label(); this.Label4 = new System.Windows.Forms.Label(); this.Label3 = new System.Windows.Forms.Label(); this.m_txtStartCity = new System.Windows.Forms.TextBox(); this.m_txtStartState = new System.Windows.Forms.TextBox(); this.m_txtStartCode = new System.Windows.Forms.TextBox(); this.GroupBox2 = new System.Windows.Forms.GroupBox(); this.m_txtFinishAddress = new System.Windows.Forms.TextBox(); this.Label7 = new System.Windows.Forms.Label(); this.Label8 = new System.Windows.Forms.Label(); this.Label9 = new System.Windows.Forms.Label(); this.Label10 = new System.Windows.Forms.Label(); this.m_txtFinishCity = new System.Windows.Forms.TextBox(); this.m_txtFinishState = new System.Windows.Forms.TextBox(); this.m_txtFinishCode = new System.Windows.Forms.TextBox(); this.GroupBox3 = new System.Windows.Forms.GroupBox(); this.m_cmbDistanceUnit = new System.Windows.Forms.ComboBox(); this.Label14 = new System.Windows.Forms.Label(); this.m_trackUseRoad = new System.Windows.Forms.TrackBar(); this.Label12 = new System.Windows.Forms.Label(); this.m_btnRestrictions = new System.Windows.Forms.Button(); this.m_rbtnQuickest = new System.Windows.Forms.RadioButton(); this.Label11 = new System.Windows.Forms.Label(); this.m_rbtnShortest = new System.Windows.Forms.RadioButton(); this.Label13 = new System.Windows.Forms.Label(); this.Label15 = new System.Windows.Forms.Label(); this.m_txtBarriers = new System.Windows.Forms.TextBox(); this.m_btnBarriersOpen = new System.Windows.Forms.Button(); this.m_btnShowDirections = new System.Windows.Forms.Button(); this.m_btnBarriersClear = new System.Windows.Forms.Button(); this.GroupBox4 = new System.Windows.Forms.GroupBox(); this.GroupBox1.SuspendLayout(); this.GroupBox2.SuspendLayout(); this.GroupBox3.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)this.m_trackUseRoad).BeginInit(); this.SuspendLayout(); // //m_btnFindRoute // this.m_btnFindRoute.Anchor = (System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)); this.m_btnFindRoute.Enabled = false; this.m_btnFindRoute.Location = new System.Drawing.Point(96, 488); this.m_btnFindRoute.Name = "m_btnFindRoute"; this.m_btnFindRoute.Size = new System.Drawing.Size(104, 23); this.m_btnFindRoute.TabIndex = 14; this.m_btnFindRoute.Text = "Find Route"; // //m_btnClose // this.m_btnClose.Anchor = (System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)); this.m_btnClose.Location = new System.Drawing.Point(320, 488); this.m_btnClose.Name = "m_btnClose"; this.m_btnClose.Size = new System.Drawing.Size(75, 23); this.m_btnClose.TabIndex = 16; this.m_btnClose.Text = "Close"; // //Label1 // this.Label1.Location = new System.Drawing.Point(8, 8); this.Label1.Name = "Label1"; this.Label1.Size = new System.Drawing.Size(100, 23); this.Label1.TabIndex = 0; this.Label1.Text = "Routing Service:"; // //m_txtRoutingService // this.m_txtRoutingService.Anchor = (System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right)); this.m_txtRoutingService.Location = new System.Drawing.Point(112, 8); this.m_txtRoutingService.Name = "m_txtRoutingService"; this.m_txtRoutingService.ReadOnly = true; this.m_txtRoutingService.Size = new System.Drawing.Size(248, 20); this.m_txtRoutingService.TabIndex = 1; // //m_dlgRoutingSrvc // this.m_dlgRoutingSrvc.Filter = "Routing Service Files (*.rs)|*.rs"; this.m_dlgRoutingSrvc.RestoreDirectory = true; this.m_dlgRoutingSrvc.Title = "Choose Routing Service"; // //m_btnRoutingService // this.m_btnRoutingService.Anchor = (System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)); this.m_btnRoutingService.ImageIndex = 0; this.m_btnRoutingService.ImageList = this.ImageList1; this.m_btnRoutingService.Location = new System.Drawing.Point(368, 8); this.m_btnRoutingService.Name = "m_btnRoutingService"; this.m_btnRoutingService.Size = new System.Drawing.Size(24, 23); this.m_btnRoutingService.TabIndex = 2; // //ImageList1 // this.ImageList1.ImageStream = (System.Windows.Forms.ImageListStreamer)(resources.GetObject("ImageList1.ImageStream")); this.ImageList1.TransparentColor = System.Drawing.Color.Transparent; this.ImageList1.Images.SetKeyName(0, ""); // //m_btnAddressLocator // this.m_btnAddressLocator.Anchor = (System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)); this.m_btnAddressLocator.ImageIndex = 0; this.m_btnAddressLocator.ImageList = this.ImageList1; this.m_btnAddressLocator.Location = new System.Drawing.Point(368, 37); this.m_btnAddressLocator.Name = "m_btnAddressLocator"; this.m_btnAddressLocator.Size = new System.Drawing.Size(24, 23); this.m_btnAddressLocator.TabIndex = 5; // //m_txtAddressLocator // this.m_txtAddressLocator.Anchor = (System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right)); this.m_txtAddressLocator.Location = new System.Drawing.Point(112, 40); this.m_txtAddressLocator.Name = "m_txtAddressLocator"; this.m_txtAddressLocator.ReadOnly = true; this.m_txtAddressLocator.Size = new System.Drawing.Size(248, 20); this.m_txtAddressLocator.TabIndex = 4; // //Label2 // this.Label2.Location = new System.Drawing.Point(8, 40); this.Label2.Name = "Label2"; this.Label2.Size = new System.Drawing.Size(100, 23); this.Label2.TabIndex = 3; this.Label2.Text = "Address Locator:"; // //GroupBox1 // this.GroupBox1.Anchor = (System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right)); this.GroupBox1.Controls.Add(this.m_txtStartAddress); this.GroupBox1.Controls.Add(this.Label6); this.GroupBox1.Controls.Add(this.Label5); this.GroupBox1.Controls.Add(this.Label4); this.GroupBox1.Controls.Add(this.Label3); this.GroupBox1.Controls.Add(this.m_txtStartCity); this.GroupBox1.Controls.Add(this.m_txtStartState); this.GroupBox1.Controls.Add(this.m_txtStartCode); this.GroupBox1.Location = new System.Drawing.Point(8, 64); this.GroupBox1.Name = "GroupBox1"; this.GroupBox1.Size = new System.Drawing.Size(386, 128); this.GroupBox1.TabIndex = 6; this.GroupBox1.TabStop = false; this.GroupBox1.Text = "Start:"; // //m_txtStartAddress // this.m_txtStartAddress.Anchor = (System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right)); this.m_txtStartAddress.Location = new System.Drawing.Point(136, 24); this.m_txtStartAddress.Name = "m_txtStartAddress"; this.m_txtStartAddress.Size = new System.Drawing.Size(240, 20); this.m_txtStartAddress.TabIndex = 1; this.m_txtStartAddress.Text = "2001 ARDEN WAY"; // //Label6 // this.Label6.Location = new System.Drawing.Point(8, 96); this.Label6.Name = "Label6"; this.Label6.Size = new System.Drawing.Size(100, 23); this.Label6.TabIndex = 6; this.Label6.Text = "Postal Code:"; // //Label5 // this.Label5.Location = new System.Drawing.Point(8, 72); this.Label5.Name = "Label5"; this.Label5.Size = new System.Drawing.Size(100, 23); this.Label5.TabIndex = 4; this.Label5.Text = "State or Province:"; // //Label4 // this.Label4.Location = new System.Drawing.Point(8, 48); this.Label4.Name = "Label4"; this.Label4.Size = new System.Drawing.Size(100, 23); this.Label4.TabIndex = 2; this.Label4.Text = "City:"; // //Label3 // this.Label3.Location = new System.Drawing.Point(8, 24); this.Label3.Name = "Label3"; this.Label3.Size = new System.Drawing.Size(128, 23); this.Label3.TabIndex = 0; this.Label3.Text = "Address or Intersection:"; // //m_txtStartCity // this.m_txtStartCity.Anchor = (System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right)); this.m_txtStartCity.Location = new System.Drawing.Point(136, 48); this.m_txtStartCity.Name = "m_txtStartCity"; this.m_txtStartCity.Size = new System.Drawing.Size(240, 20); this.m_txtStartCity.TabIndex = 3; this.m_txtStartCity.Text = "Sacramento"; // //m_txtStartState // this.m_txtStartState.Anchor = (System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right)); this.m_txtStartState.Location = new System.Drawing.Point(136, 72); this.m_txtStartState.Name = "m_txtStartState"; this.m_txtStartState.Size = new System.Drawing.Size(240, 20); this.m_txtStartState.TabIndex = 5; this.m_txtStartState.Text = "CA"; // //m_txtStartCode // this.m_txtStartCode.Anchor = (System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right)); this.m_txtStartCode.Location = new System.Drawing.Point(136, 96); this.m_txtStartCode.Name = "m_txtStartCode"; this.m_txtStartCode.Size = new System.Drawing.Size(240, 20); this.m_txtStartCode.TabIndex = 7; // //GroupBox2 // this.GroupBox2.Anchor = (System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right)); this.GroupBox2.Controls.Add(this.m_txtFinishAddress); this.GroupBox2.Controls.Add(this.Label7); this.GroupBox2.Controls.Add(this.Label8); this.GroupBox2.Controls.Add(this.Label9); this.GroupBox2.Controls.Add(this.Label10); this.GroupBox2.Controls.Add(this.m_txtFinishCity); this.GroupBox2.Controls.Add(this.m_txtFinishState); this.GroupBox2.Controls.Add(this.m_txtFinishCode); this.GroupBox2.Location = new System.Drawing.Point(8, 200); this.GroupBox2.Name = "GroupBox2"; this.GroupBox2.Size = new System.Drawing.Size(386, 128); this.GroupBox2.TabIndex = 7; this.GroupBox2.TabStop = false; this.GroupBox2.Text = "Finish:"; // //m_txtFinishAddress // this.m_txtFinishAddress.Anchor = (System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right)); this.m_txtFinishAddress.Location = new System.Drawing.Point(136, 24); this.m_txtFinishAddress.Name = "m_txtFinishAddress"; this.m_txtFinishAddress.Size = new System.Drawing.Size(240, 20); this.m_txtFinishAddress.TabIndex = 1; this.m_txtFinishAddress.Text = "4760 MACK RD"; // //Label7 // this.Label7.Location = new System.Drawing.Point(8, 96); this.Label7.Name = "Label7"; this.Label7.Size = new System.Drawing.Size(100, 23); this.Label7.TabIndex = 6; this.Label7.Text = "Postal Code:"; // //Label8 // this.Label8.Location = new System.Drawing.Point(8, 72); this.Label8.Name = "Label8"; this.Label8.Size = new System.Drawing.Size(100, 23); this.Label8.TabIndex = 4; this.Label8.Text = "State or Province:"; // //Label9 // this.Label9.Location = new System.Drawing.Point(8, 48); this.Label9.Name = "Label9"; this.Label9.Size = new System.Drawing.Size(100, 23); this.Label9.TabIndex = 2; this.Label9.Text = "City:"; // //Label10 // this.Label10.Location = new System.Drawing.Point(8, 24); this.Label10.Name = "Label10"; this.Label10.Size = new System.Drawing.Size(128, 23); this.Label10.TabIndex = 0; this.Label10.Text = "Address or Intersection:"; // //m_txtFinishCity // this.m_txtFinishCity.Anchor = (System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right)); this.m_txtFinishCity.Location = new System.Drawing.Point(136, 48); this.m_txtFinishCity.Name = "m_txtFinishCity"; this.m_txtFinishCity.Size = new System.Drawing.Size(240, 20); this.m_txtFinishCity.TabIndex = 3; this.m_txtFinishCity.Text = "Sacramento"; // //m_txtFinishState // this.m_txtFinishState.Anchor = (System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right)); this.m_txtFinishState.Location = new System.Drawing.Point(136, 72); this.m_txtFinishState.Name = "m_txtFinishState"; this.m_txtFinishState.Size = new System.Drawing.Size(240, 20); this.m_txtFinishState.TabIndex = 5; this.m_txtFinishState.Text = "CA"; // //m_txtFinishCode // this.m_txtFinishCode.Anchor = (System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right)); this.m_txtFinishCode.Location = new System.Drawing.Point(136, 96); this.m_txtFinishCode.Name = "m_txtFinishCode"; this.m_txtFinishCode.Size = new System.Drawing.Size(240, 20); this.m_txtFinishCode.TabIndex = 7; // //GroupBox3 // this.GroupBox3.Anchor = (System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right)); this.GroupBox3.Controls.Add(this.m_rbtnShortest); this.GroupBox3.Controls.Add(this.m_rbtnQuickest); this.GroupBox3.Controls.Add(this.m_cmbDistanceUnit); this.GroupBox3.Controls.Add(this.Label14); this.GroupBox3.Controls.Add(this.m_trackUseRoad); this.GroupBox3.Controls.Add(this.Label12); this.GroupBox3.Controls.Add(this.m_btnRestrictions); this.GroupBox3.Controls.Add(this.Label11); this.GroupBox3.Controls.Add(this.Label13); this.GroupBox3.Location = new System.Drawing.Point(8, 336); this.GroupBox3.Name = "GroupBox3"; this.GroupBox3.Size = new System.Drawing.Size(386, 100); this.GroupBox3.TabIndex = 8; this.GroupBox3.TabStop = false; this.GroupBox3.Text = "Options:"; // //m_cmbDistanceUnit // this.m_cmbDistanceUnit.Anchor = (System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right)); this.m_cmbDistanceUnit.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.m_cmbDistanceUnit.Items.AddRange(new object[] {"Feet", "Yards", "Miles", "Meters", "Kilometers"}); this.m_cmbDistanceUnit.Location = new System.Drawing.Point(264, 16); this.m_cmbDistanceUnit.Name = "m_cmbDistanceUnit"; this.m_cmbDistanceUnit.Size = new System.Drawing.Size(114, 21); this.m_cmbDistanceUnit.TabIndex = 3; // //Label14 // this.Label14.Location = new System.Drawing.Point(176, 16); this.Label14.Name = "Label14"; this.Label14.Size = new System.Drawing.Size(88, 23); this.Label14.TabIndex = 2; this.Label14.Text = "Distance Units:"; // //m_trackUseRoad // this.m_trackUseRoad.AutoSize = false; this.m_trackUseRoad.Location = new System.Drawing.Point(96, 62); this.m_trackUseRoad.Maximum = 100; this.m_trackUseRoad.Name = "m_trackUseRoad"; this.m_trackUseRoad.Size = new System.Drawing.Size(104, 32); this.m_trackUseRoad.TabIndex = 5; this.m_trackUseRoad.TickFrequency = 10; this.m_trackUseRoad.Value = 50; // //Label12 // this.Label12.Location = new System.Drawing.Point(8, 64); this.Label12.Name = "Label12"; this.Label12.Size = new System.Drawing.Size(96, 23); this.Label12.TabIndex = 4; this.Label12.Text = "Use Local Roads"; // //m_btnRestrictions // this.m_btnRestrictions.Anchor = (System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)); this.m_btnRestrictions.Enabled = false; this.m_btnRestrictions.Location = new System.Drawing.Point(282, 64); this.m_btnRestrictions.Name = "m_btnRestrictions"; this.m_btnRestrictions.Size = new System.Drawing.Size(96, 23); this.m_btnRestrictions.TabIndex = 7; this.m_btnRestrictions.Text = "Restrictions"; // //m_rbtnQuickest // this.m_rbtnQuickest.Checked = true; this.m_rbtnQuickest.Location = new System.Drawing.Point(46, 13); this.m_rbtnQuickest.Name = "m_rbtnQuickest"; this.m_rbtnQuickest.Size = new System.Drawing.Size(104, 24); this.m_rbtnQuickest.TabIndex = 0; this.m_rbtnQuickest.TabStop = true; this.m_rbtnQuickest.Text = "Quickest Route"; // //Label11 // this.Label11.Location = new System.Drawing.Point(8, 16); this.Label11.Name = "Label11"; this.Label11.Size = new System.Drawing.Size(32, 23); this.Label11.TabIndex = 0; this.Label11.Text = "Find:"; // //m_rbtnShortest // this.m_rbtnShortest.Location = new System.Drawing.Point(46, 37); this.m_rbtnShortest.Name = "m_rbtnShortest"; this.m_rbtnShortest.Size = new System.Drawing.Size(104, 24); this.m_rbtnShortest.TabIndex = 1; this.m_rbtnShortest.TabStop = true; this.m_rbtnShortest.Text = "Shortest Route"; // //Label13 // this.Label13.Location = new System.Drawing.Point(200, 64); this.Label13.Name = "Label13"; this.Label13.Size = new System.Drawing.Size(96, 23); this.Label13.TabIndex = 6; this.Label13.Text = "Use Highways"; // //Label15 // this.Label15.Location = new System.Drawing.Point(8, 448); this.Label15.Name = "Label15"; this.Label15.Size = new System.Drawing.Size(100, 23); this.Label15.TabIndex = 9; this.Label15.Text = "Barriers Table:"; // //m_txtBarriers // this.m_txtBarriers.Anchor = (System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right)); this.m_txtBarriers.Location = new System.Drawing.Point(112, 448); this.m_txtBarriers.Name = "m_txtBarriers"; this.m_txtBarriers.ReadOnly = true; this.m_txtBarriers.Size = new System.Drawing.Size(168, 20); this.m_txtBarriers.TabIndex = 10; // //m_btnBarriersOpen // this.m_btnBarriersOpen.Anchor = (System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)); this.m_btnBarriersOpen.Enabled = false; this.m_btnBarriersOpen.ImageIndex = 0; this.m_btnBarriersOpen.ImageList = this.ImageList1; this.m_btnBarriersOpen.Location = new System.Drawing.Point(288, 448); this.m_btnBarriersOpen.Name = "m_btnBarriersOpen"; this.m_btnBarriersOpen.Size = new System.Drawing.Size(24, 23); this.m_btnBarriersOpen.TabIndex = 11; // //m_btnShowDirections // this.m_btnShowDirections.Anchor = (System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)); this.m_btnShowDirections.Enabled = false; this.m_btnShowDirections.Location = new System.Drawing.Point(208, 488); this.m_btnShowDirections.Name = "m_btnShowDirections"; this.m_btnShowDirections.Size = new System.Drawing.Size(104, 23); this.m_btnShowDirections.TabIndex = 15; this.m_btnShowDirections.Text = "Show Directions"; // //m_btnBarriersClear // this.m_btnBarriersClear.Anchor = (System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)); this.m_btnBarriersClear.Location = new System.Drawing.Point(320, 448); this.m_btnBarriersClear.Name = "m_btnBarriersClear"; this.m_btnBarriersClear.Size = new System.Drawing.Size(75, 23); this.m_btnBarriersClear.TabIndex = 12; this.m_btnBarriersClear.Text = "Clear"; // //GroupBox4 // this.GroupBox4.Anchor = (System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right)); this.GroupBox4.Location = new System.Drawing.Point(8, 480); this.GroupBox4.Name = "GroupBox4"; this.GroupBox4.Size = new System.Drawing.Size(384, 2); this.GroupBox4.TabIndex = 13; this.GroupBox4.TabStop = false; // //RoutingForm // this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Inherit; this.ClientSize = new System.Drawing.Size(402, 522); this.Controls.Add(this.GroupBox4); this.Controls.Add(this.m_btnBarriersClear); this.Controls.Add(this.GroupBox3); this.Controls.Add(this.GroupBox1); this.Controls.Add(this.m_btnRoutingService); this.Controls.Add(this.m_txtRoutingService); this.Controls.Add(this.m_txtAddressLocator); this.Controls.Add(this.m_txtBarriers); this.Controls.Add(this.Label1); this.Controls.Add(this.m_btnClose); this.Controls.Add(this.m_btnFindRoute); this.Controls.Add(this.m_btnAddressLocator); this.Controls.Add(this.Label2); this.Controls.Add(this.GroupBox2); this.Controls.Add(this.Label15); this.Controls.Add(this.m_btnBarriersOpen); this.Controls.Add(this.m_btnShowDirections); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.KeyPreview = true; this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "RoutingForm"; this.ShowInTaskbar = false; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "Routing Sample"; this.GroupBox1.ResumeLayout(false); this.GroupBox1.PerformLayout(); this.GroupBox2.ResumeLayout(false); this.GroupBox2.PerformLayout(); this.GroupBox3.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)this.m_trackUseRoad).EndInit(); this.ResumeLayout(false); this.PerformLayout(); //INSTANT C# NOTE: Converted event handlers: base.Closing += new System.ComponentModel.CancelEventHandler(RoutingForm_Closing); base.KeyDown += new System.Windows.Forms.KeyEventHandler(RoutingForm_KeyDown); m_btnRoutingService.Click += new System.EventHandler(m_btnRoutingService_Click); m_btnAddressLocator.Click += new System.EventHandler(m_btnAddressLocator_Click); m_btnBarriersOpen.Click += new System.EventHandler(m_btnBarriersOpen_Click); m_btnBarriersClear.Click += new System.EventHandler(m_btnBarriersClear_Click); m_btnFindRoute.Click += new System.EventHandler(m_btnFindRoute_Click); m_btnShowDirections.Click += new System.EventHandler(m_btnShowDirections_Click); m_btnClose.Click += new System.EventHandler(m_btnClose_Click); base.Load += new System.EventHandler(RoutingForm_Load); m_btnRestrictions.Click += new System.EventHandler(m_btnRestrictions_Click); } internal System.Windows.Forms.TabControl m_ctrlPages; internal System.Windows.Forms.Button m_btnFindRoute; internal System.Windows.Forms.TabPage m_ctrlPageStops; internal System.Windows.Forms.TabPage m_ctrlPageBarriers; internal System.Windows.Forms.TabPage m_ctrlPageDD; internal System.Windows.Forms.TabPage m_ctrlPageOptions; internal System.Windows.Forms.ImageList m_imgList; internal System.Windows.Forms.Button m_btnStopAdd; internal System.Windows.Forms.Button m_btnStopsRemoveAll; internal System.Windows.Forms.ListBox ListBox1; internal System.Windows.Forms.Label Label1; internal System.Windows.Forms.Label Label2; internal System.Windows.Forms.Label Label3; internal System.Windows.Forms.Label Label4; internal System.Windows.Forms.Label Label5; internal System.Windows.Forms.Label Label6; internal System.Windows.Forms.Label Label7; internal System.Windows.Forms.Label Label8; internal System.Windows.Forms.Label Label9; internal System.Windows.Forms.Label Label10; internal System.Windows.Forms.Label Label11; internal System.Windows.Forms.Button m_btnStopRemove; internal System.Windows.Forms.Button m_btnStopUp; internal System.Windows.Forms.Button m_btnStopDown; internal System.Windows.Forms.GroupBox GroupBox1; internal System.Windows.Forms.GroupBox GroupBox2; internal System.Windows.Forms.GroupBox GroupBox3; internal System.Windows.Forms.GroupBox GroupBox4; internal System.Windows.Forms.OpenFileDialog m_dlgRoutingSrvc; internal System.Windows.Forms.Label Label15; internal System.Windows.Forms.Label Label14; internal System.Windows.Forms.Label Label13; internal System.Windows.Forms.Label Label12; internal System.Windows.Forms.ImageList ImageList1; internal System.Windows.Forms.Button m_btnClose; internal System.Windows.Forms.TextBox m_txtRoutingService; internal System.Windows.Forms.Button m_btnRoutingService; internal System.Windows.Forms.Button m_btnAddressLocator; internal System.Windows.Forms.TextBox m_txtAddressLocator; internal System.Windows.Forms.TextBox m_txtStartAddress; internal System.Windows.Forms.TextBox m_txtStartCity; internal System.Windows.Forms.TextBox m_txtStartState; internal System.Windows.Forms.TextBox m_txtStartCode; internal System.Windows.Forms.TextBox m_txtFinishAddress; internal System.Windows.Forms.TextBox m_txtFinishCity; internal System.Windows.Forms.TextBox m_txtFinishState; internal System.Windows.Forms.TextBox m_txtFinishCode; internal System.Windows.Forms.ComboBox m_cmbDistanceUnit; internal System.Windows.Forms.TrackBar m_trackUseRoad; internal System.Windows.Forms.Button m_btnRestrictions; internal System.Windows.Forms.RadioButton m_rbtnQuickest; internal System.Windows.Forms.RadioButton m_rbtnShortest; internal System.Windows.Forms.TextBox m_txtBarriers; internal System.Windows.Forms.Button m_btnBarriersOpen; internal System.Windows.Forms.Button m_btnShowDirections; internal System.Windows.Forms.Button m_btnBarriersClear; } } //end of root namespace
#if UNITY_EDITOR || !(UNITY_WEBPLAYER || UNITY_WEBGL) #region License /* * CookieCollection.cs * * This code is derived from System.Net.CookieCollection.cs of Mono * (http://www.mono-project.com). * * The MIT License * * Copyright (c) 2004,2009 Novell, Inc. (http://www.novell.com) * Copyright (c) 2012-2014 sta.blockhead * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #endregion #region Authors /* * Authors: * - Lawrence Pit <loz@cable.a2000.nl> * - Gonzalo Paniagua Javier <gonzalo@ximian.com> * - Sebastien Pouliot <sebastien@ximian.com> */ #endregion using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Text; namespace WebSocketSharp.Net { /// <summary> /// Provides a collection container for instances of the <see cref="Cookie"/> class. /// </summary> [Serializable] public class CookieCollection : ICollection, IEnumerable { #region Private Fields private List<Cookie> _list; private object _sync; #endregion #region Public Constructors /// <summary> /// Initializes a new instance of the <see cref="CookieCollection"/> class. /// </summary> public CookieCollection () { _list = new List<Cookie> (); } #endregion #region Internal Properties internal IList<Cookie> List { get { return _list; } } internal IEnumerable<Cookie> Sorted { get { var list = new List<Cookie> (_list); if (list.Count > 1) list.Sort (compareCookieWithinSorted); return list; } } #endregion #region Public Properties /// <summary> /// Gets the number of cookies in the collection. /// </summary> /// <value> /// An <see cref="int"/> that represents the number of cookies in the collection. /// </value> public int Count { get { return _list.Count; } } /// <summary> /// Gets a value indicating whether the collection is read-only. /// </summary> /// <value> /// <c>true</c> if the collection is read-only; otherwise, <c>false</c>. /// The default value is <c>true</c>. /// </value> public bool IsReadOnly { // LAMESPEC: So how is one supposed to create a writable CookieCollection instance? // We simply ignore this property, as this collection is always writable. get { return true; } } /// <summary> /// Gets a value indicating whether the access to the collection is thread safe. /// </summary> /// <value> /// <c>true</c> if the access to the collection is thread safe; otherwise, <c>false</c>. /// The default value is <c>false</c>. /// </value> public bool IsSynchronized { get { return false; } } /// <summary> /// Gets the <see cref="Cookie"/> at the specified <paramref name="index"/> from /// the collection. /// </summary> /// <value> /// A <see cref="Cookie"/> at the specified <paramref name="index"/> in the collection. /// </value> /// <param name="index"> /// An <see cref="int"/> that represents the zero-based index of the <see cref="Cookie"/> /// to find. /// </param> /// <exception cref="ArgumentOutOfRangeException"> /// <paramref name="index"/> is out of allowable range of indexes for the collection. /// </exception> public Cookie this[int index] { get { if (index < 0 || index >= _list.Count) throw new ArgumentOutOfRangeException ("index"); return _list[index]; } } /// <summary> /// Gets the <see cref="Cookie"/> with the specified <paramref name="name"/> from /// the collection. /// </summary> /// <value> /// A <see cref="Cookie"/> with the specified <paramref name="name"/> in the collection. /// </value> /// <param name="name"> /// A <see cref="string"/> that represents the name of the <see cref="Cookie"/> to find. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="name"/> is <see langword="null"/>. /// </exception> public Cookie this[string name] { get { if (name == null) throw new ArgumentNullException ("name"); foreach (var cookie in Sorted) if (cookie.Name.Equals (name, StringComparison.InvariantCultureIgnoreCase)) return cookie; return null; } } /// <summary> /// Gets an object used to synchronize access to the collection. /// </summary> /// <value> /// An <see cref="Object"/> used to synchronize access to the collection. /// </value> public Object SyncRoot { get { return _sync ?? (_sync = ((ICollection) _list).SyncRoot); } } #endregion #region Private Methods private static int compareCookieWithinSort (Cookie x, Cookie y) { return (x.Name.Length + x.Value.Length) - (y.Name.Length + y.Value.Length); } private static int compareCookieWithinSorted (Cookie x, Cookie y) { var ret = 0; return (ret = x.Version - y.Version) != 0 ? ret : (ret = x.Name.CompareTo (y.Name)) != 0 ? ret : y.Path.Length - x.Path.Length; } private static CookieCollection parseRequest (string value) { var cookies = new CookieCollection (); Cookie cookie = null; var ver = 0; var pairs = splitCookieHeaderValue (value); for (var i = 0; i < pairs.Length; i++) { var pair = pairs[i].Trim (); if (pair.Length == 0) continue; if (pair.StartsWith ("$version", StringComparison.InvariantCultureIgnoreCase)) { ver = Int32.Parse (pair.GetValue ('=', true)); } else if (pair.StartsWith ("$path", StringComparison.InvariantCultureIgnoreCase)) { if (cookie != null) cookie.Path = pair.GetValue ('='); } else if (pair.StartsWith ("$domain", StringComparison.InvariantCultureIgnoreCase)) { if (cookie != null) cookie.Domain = pair.GetValue ('='); } else if (pair.StartsWith ("$port", StringComparison.InvariantCultureIgnoreCase)) { var port = pair.Equals ("$port", StringComparison.InvariantCultureIgnoreCase) ? "\"\"" : pair.GetValue ('='); if (cookie != null) cookie.Port = port; } else { if (cookie != null) cookies.Add (cookie); string name; string val = String.Empty; var pos = pair.IndexOf ('='); if (pos == -1) { name = pair; } else if (pos == pair.Length - 1) { name = pair.Substring (0, pos).TrimEnd (' '); } else { name = pair.Substring (0, pos).TrimEnd (' '); val = pair.Substring (pos + 1).TrimStart (' '); } cookie = new Cookie (name, val); if (ver != 0) cookie.Version = ver; } } if (cookie != null) cookies.Add (cookie); return cookies; } private static CookieCollection parseResponse (string value) { var cookies = new CookieCollection (); Cookie cookie = null; var pairs = splitCookieHeaderValue (value); for (var i = 0; i < pairs.Length; i++) { var pair = pairs[i].Trim (); if (pair.Length == 0) continue; if (pair.StartsWith ("version", StringComparison.InvariantCultureIgnoreCase)) { if (cookie != null) cookie.Version = Int32.Parse (pair.GetValue ('=', true)); } else if (pair.StartsWith ("expires", StringComparison.InvariantCultureIgnoreCase)) { var buff = new StringBuilder (pair.GetValue ('='), 32); if (i < pairs.Length - 1) buff.AppendFormat (", {0}", pairs[++i].Trim ()); DateTime expires; if (!DateTime.TryParseExact ( buff.ToString (), new[] { "ddd, dd'-'MMM'-'yyyy HH':'mm':'ss 'GMT'", "r" }, CultureInfo.CreateSpecificCulture ("en-US"), DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal, out expires)) expires = DateTime.Now; if (cookie != null && cookie.Expires == DateTime.MinValue) cookie.Expires = expires.ToLocalTime (); } else if (pair.StartsWith ("max-age", StringComparison.InvariantCultureIgnoreCase)) { var max = Int32.Parse (pair.GetValue ('=', true)); var expires = DateTime.Now.AddSeconds ((double) max); if (cookie != null) cookie.Expires = expires; } else if (pair.StartsWith ("path", StringComparison.InvariantCultureIgnoreCase)) { if (cookie != null) cookie.Path = pair.GetValue ('='); } else if (pair.StartsWith ("domain", StringComparison.InvariantCultureIgnoreCase)) { if (cookie != null) cookie.Domain = pair.GetValue ('='); } else if (pair.StartsWith ("port", StringComparison.InvariantCultureIgnoreCase)) { var port = pair.Equals ("port", StringComparison.InvariantCultureIgnoreCase) ? "\"\"" : pair.GetValue ('='); if (cookie != null) cookie.Port = port; } else if (pair.StartsWith ("comment", StringComparison.InvariantCultureIgnoreCase)) { if (cookie != null) cookie.Comment = pair.GetValue ('=').UrlDecode (); } else if (pair.StartsWith ("commenturl", StringComparison.InvariantCultureIgnoreCase)) { if (cookie != null) cookie.CommentUri = pair.GetValue ('=', true).ToUri (); } else if (pair.StartsWith ("discard", StringComparison.InvariantCultureIgnoreCase)) { if (cookie != null) cookie.Discard = true; } else if (pair.StartsWith ("secure", StringComparison.InvariantCultureIgnoreCase)) { if (cookie != null) cookie.Secure = true; } else if (pair.StartsWith ("httponly", StringComparison.InvariantCultureIgnoreCase)) { if (cookie != null) cookie.HttpOnly = true; } else { if (cookie != null) cookies.Add (cookie); string name; string val = String.Empty; var pos = pair.IndexOf ('='); if (pos == -1) { name = pair; } else if (pos == pair.Length - 1) { name = pair.Substring (0, pos).TrimEnd (' '); } else { name = pair.Substring (0, pos).TrimEnd (' '); val = pair.Substring (pos + 1).TrimStart (' '); } cookie = new Cookie (name, val); } } if (cookie != null) cookies.Add (cookie); return cookies; } private int searchCookie (Cookie cookie) { var name = cookie.Name; var path = cookie.Path; var domain = cookie.Domain; var ver = cookie.Version; for (var i = _list.Count - 1; i >= 0; i--) { var c = _list[i]; if (c.Name.Equals (name, StringComparison.InvariantCultureIgnoreCase) && c.Path.Equals (path, StringComparison.InvariantCulture) && c.Domain.Equals (domain, StringComparison.InvariantCultureIgnoreCase) && c.Version == ver) return i; } return -1; } private static string[] splitCookieHeaderValue (string value) { return new List<string> (value.SplitHeaderValue (',', ';')).ToArray (); } #endregion #region Internal Methods internal static CookieCollection Parse (string value, bool response) { return response ? parseResponse (value) : parseRequest (value); } internal void SetOrRemove (Cookie cookie) { var pos = searchCookie (cookie); if (pos == -1) { if (!cookie.Expired) _list.Add (cookie); return; } if (!cookie.Expired) { _list[pos] = cookie; return; } _list.RemoveAt (pos); } internal void SetOrRemove (CookieCollection cookies) { foreach (Cookie cookie in cookies) SetOrRemove (cookie); } internal void Sort () { if (_list.Count > 1) _list.Sort (compareCookieWithinSort); } #endregion #region Public Methods /// <summary> /// Adds the specified <paramref name="cookie"/> to the collection. /// </summary> /// <param name="cookie"> /// A <see cref="Cookie"/> to add. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="cookie"/> is <see langword="null"/>. /// </exception> public void Add (Cookie cookie) { if (cookie == null) throw new ArgumentNullException ("cookie"); var pos = searchCookie (cookie); if (pos == -1) { _list.Add (cookie); return; } _list[pos] = cookie; } /// <summary> /// Adds the specified <paramref name="cookies"/> to the collection. /// </summary> /// <param name="cookies"> /// A <see cref="CookieCollection"/> that contains the cookies to add. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="cookies"/> is <see langword="null"/>. /// </exception> public void Add (CookieCollection cookies) { if (cookies == null) throw new ArgumentNullException ("cookies"); foreach (Cookie cookie in cookies) Add (cookie); } /// <summary> /// Copies the elements of the collection to the specified <see cref="Array"/>, starting at /// the specified <paramref name="index"/> in the <paramref name="array"/>. /// </summary> /// <param name="array"> /// An <see cref="Array"/> that represents the destination of the elements copied from /// the collection. /// </param> /// <param name="index"> /// An <see cref="int"/> that represents the zero-based index in <paramref name="array"/> /// at which copying begins. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="array"/> is <see langword="null"/>. /// </exception> /// <exception cref="ArgumentOutOfRangeException"> /// <paramref name="index"/> is less than zero. /// </exception> /// <exception cref="ArgumentException"> /// <para> /// <paramref name="array"/> is multidimensional. /// </para> /// <para> /// -or- /// </para> /// <para> /// The number of elements in the collection is greater than the available space from /// <paramref name="index"/> to the end of the destination <paramref name="array"/>. /// </para> /// </exception> /// <exception cref="InvalidCastException"> /// The elements in the collection cannot be cast automatically to the type of the destination /// <paramref name="array"/>. /// </exception> public void CopyTo (Array array, int index) { if (array == null) throw new ArgumentNullException ("array"); if (index < 0) throw new ArgumentOutOfRangeException ("index", "Less than zero."); if (array.Rank > 1) throw new ArgumentException ("Multidimensional.", "array"); if (array.Length - index < _list.Count) throw new ArgumentException ( "The number of elements in this collection is greater than the available space of the destination array."); if (!array.GetType ().GetElementType ().IsAssignableFrom (typeof (Cookie))) throw new InvalidCastException ( "The elements in this collection cannot be cast automatically to the type of the destination array."); ((IList) _list).CopyTo (array, index); } /// <summary> /// Copies the elements of the collection to the specified array of <see cref="Cookie"/>, /// starting at the specified <paramref name="index"/> in the <paramref name="array"/>. /// </summary> /// <param name="array"> /// An array of <see cref="Cookie"/> that represents the destination of the elements /// copied from the collection. /// </param> /// <param name="index"> /// An <see cref="int"/> that represents the zero-based index in <paramref name="array"/> /// at which copying begins. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="array"/> is <see langword="null"/>. /// </exception> /// <exception cref="ArgumentOutOfRangeException"> /// <paramref name="index"/> is less than zero. /// </exception> /// <exception cref="ArgumentException"> /// The number of elements in the collection is greater than the available space from /// <paramref name="index"/> to the end of the destination <paramref name="array"/>. /// </exception> public void CopyTo (Cookie[] array, int index) { if (array == null) throw new ArgumentNullException ("array"); if (index < 0) throw new ArgumentOutOfRangeException ("index", "Less than zero."); if (array.Length - index < _list.Count) throw new ArgumentException ( "The number of elements in this collection is greater than the available space of the destination array."); _list.CopyTo (array, index); } /// <summary> /// Gets the enumerator used to iterate through the collection. /// </summary> /// <returns> /// An <see cref="IEnumerator"/> instance used to iterate through the collection. /// </returns> public IEnumerator GetEnumerator () { return _list.GetEnumerator (); } #endregion } } #endif
using Microsoft.TeamFoundation.DistributedTask.WebApi; using Microsoft.VisualStudio.Services.Agent.Listener; using Microsoft.VisualStudio.Services.Agent.Listener.Configuration; using Moq; using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Xunit; namespace Microsoft.VisualStudio.Services.Agent.Tests.Listener { public sealed class AgentL0 { private Mock<IConfigurationManager> _configurationManager; private Mock<IJobNotification> _jobNotification; private Mock<IMessageListener> _messageListener; private Mock<IPromptManager> _promptManager; private Mock<IJobDispatcher> _jobDispatcher; private Mock<IAgentServer> _agentServer; private Mock<ITerminal> _term; private Mock<IConfigurationStore> _configStore; private Mock<IVstsAgentWebProxy> _proxy; public AgentL0() { _configurationManager = new Mock<IConfigurationManager>(); _jobNotification = new Mock<IJobNotification>(); _messageListener = new Mock<IMessageListener>(); _promptManager = new Mock<IPromptManager>(); _jobDispatcher = new Mock<IJobDispatcher>(); _agentServer = new Mock<IAgentServer>(); _term = new Mock<ITerminal>(); _configStore = new Mock<IConfigurationStore>(); _proxy = new Mock<IVstsAgentWebProxy>(); } private AgentJobRequestMessage CreateJobRequestMessage(string jobName) { TaskOrchestrationPlanReference plan = new TaskOrchestrationPlanReference(); TimelineReference timeline = null; JobEnvironment environment = new JobEnvironment(); List<TaskInstance> tasks = new List<TaskInstance>(); Guid JobId = Guid.NewGuid(); var jobRequest = new AgentJobRequestMessage(plan, timeline, JobId, jobName, jobName, environment, tasks); return jobRequest as AgentJobRequestMessage; } private JobCancelMessage CreateJobCancelMessage() { var message = new JobCancelMessage(Guid.NewGuid(), TimeSpan.FromSeconds(0)); return message; } [Fact] [Trait("Level", "L0")] [Trait("Category", "Agent")] //process 2 new job messages, and one cancel message public async void TestRunAsync() { using (var hc = new TestHostContext(this)) { //Arrange var agent = new Agent.Listener.Agent(); hc.SetSingleton<IConfigurationManager>(_configurationManager.Object); hc.SetSingleton<IJobNotification>(_jobNotification.Object); hc.SetSingleton<IMessageListener>(_messageListener.Object); hc.SetSingleton<IPromptManager>(_promptManager.Object); hc.SetSingleton<IAgentServer>(_agentServer.Object); hc.SetSingleton<IVstsAgentWebProxy>(_proxy.Object); hc.SetSingleton<IConfigurationStore>(_configStore.Object); agent.Initialize(hc); var settings = new AgentSettings { PoolId = 43242 }; var message = new TaskAgentMessage() { Body = JsonUtility.ToString(CreateJobRequestMessage("job1")), MessageId = 4234, MessageType = JobRequestMessageTypes.AgentJobRequest }; var messages = new Queue<TaskAgentMessage>(); messages.Enqueue(message); var signalWorkerComplete = new SemaphoreSlim(0, 1); _configurationManager.Setup(x => x.LoadSettings()) .Returns(settings); _configurationManager.Setup(x => x.IsConfigured()) .Returns(true); _messageListener.Setup(x => x.CreateSessionAsync(It.IsAny<CancellationToken>())) .Returns(Task.FromResult<bool>(true)); _messageListener.Setup(x => x.GetNextMessageAsync(It.IsAny<CancellationToken>())) .Returns(async () => { if (0 == messages.Count) { signalWorkerComplete.Release(); await Task.Delay(2000, hc.AgentShutdownToken); } return messages.Dequeue(); }); _messageListener.Setup(x => x.DeleteSessionAsync()) .Returns(Task.CompletedTask); _messageListener.Setup(x => x.DeleteMessageAsync(It.IsAny<TaskAgentMessage>())) .Returns(Task.CompletedTask); _jobDispatcher.Setup(x => x.Run(It.IsAny<AgentJobRequestMessage>())) .Callback(() => { }); _jobNotification.Setup(x => x.StartClient(It.IsAny<String>(), It.IsAny<CancellationToken>())) .Callback(() => { }); _jobNotification.Setup(x => x.StartClient(It.IsAny<String>())) .Callback(() => { }); hc.EnqueueInstance<IJobDispatcher>(_jobDispatcher.Object); _configStore.Setup(x => x.IsServiceConfigured()).Returns(false); //Act var command = new CommandSettings(hc, new string[] { "run" }); Task agentTask = agent.ExecuteCommand(command); //Assert //wait for the agent to run one job if (!await signalWorkerComplete.WaitAsync(2000)) { Assert.True(false, $"{nameof(_messageListener.Object.GetNextMessageAsync)} was not invoked."); } else { //Act hc.ShutdownAgent(ShutdownReason.UserCancelled); //stop Agent //Assert Task[] taskToWait2 = { agentTask, Task.Delay(2000) }; //wait for the Agent to exit await Task.WhenAny(taskToWait2); Assert.True(agentTask.IsCompleted, $"{nameof(agent.ExecuteCommand)} timed out."); Assert.True(!agentTask.IsFaulted, agentTask.Exception?.ToString()); Assert.True(agentTask.IsCanceled); _jobDispatcher.Verify(x => x.Run(It.IsAny<AgentJobRequestMessage>()), Times.Once(), $"{nameof(_jobDispatcher.Object.Run)} was not invoked."); _messageListener.Verify(x => x.GetNextMessageAsync(It.IsAny<CancellationToken>()), Times.AtLeastOnce()); _messageListener.Verify(x => x.CreateSessionAsync(It.IsAny<CancellationToken>()), Times.Once()); _messageListener.Verify(x => x.DeleteSessionAsync(), Times.Once()); _messageListener.Verify(x => x.DeleteMessageAsync(It.IsAny<TaskAgentMessage>()), Times.AtLeastOnce()); } } } public static TheoryData<string[], bool, Times> RunAsServiceTestData = new TheoryData<string[], bool, Times>() { // staring with run command, configured as run as service, should start the agent { new [] { "run" }, true, Times.Once() }, // starting with no argument, configured not to run as service, should start agent interactively { new [] { "run" }, false, Times.Once() } }; [Theory] [MemberData("RunAsServiceTestData")] [Trait("Level", "L0")] [Trait("Category", "Agent")] public async void TestExecuteCommandForRunAsService(string[] args, bool configureAsService, Times expectedTimes) { using (var hc = new TestHostContext(this)) { hc.SetSingleton<IConfigurationManager>(_configurationManager.Object); hc.SetSingleton<IPromptManager>(_promptManager.Object); hc.SetSingleton<IMessageListener>(_messageListener.Object); hc.SetSingleton<IVstsAgentWebProxy>(_proxy.Object); hc.SetSingleton<IConfigurationStore>(_configStore.Object); var command = new CommandSettings(hc, args); _configurationManager.Setup(x => x.IsConfigured()).Returns(true); _configurationManager.Setup(x => x.LoadSettings()) .Returns(new AgentSettings { }); _configStore.Setup(x => x.IsServiceConfigured()).Returns(configureAsService); _messageListener.Setup(x => x.CreateSessionAsync(It.IsAny<CancellationToken>())) .Returns(Task.FromResult(false)); var agent = new Agent.Listener.Agent(); agent.Initialize(hc); await agent.ExecuteCommand(command); _messageListener.Verify(x => x.CreateSessionAsync(It.IsAny<CancellationToken>()), expectedTimes); } } [Fact] [Trait("Level", "L0")] [Trait("Category", "Agent")] //process 2 new job messages, and one cancel message public async void TestMachineProvisionerCLI() { using (var hc = new TestHostContext(this)) { hc.SetSingleton<IConfigurationManager>(_configurationManager.Object); hc.SetSingleton<IPromptManager>(_promptManager.Object); hc.SetSingleton<IMessageListener>(_messageListener.Object); hc.SetSingleton<IVstsAgentWebProxy>(_proxy.Object); hc.SetSingleton<IConfigurationStore>(_configStore.Object); var command = new CommandSettings(hc, new[] { "run" }); _configurationManager.Setup(x => x.IsConfigured()). Returns(true); _configurationManager.Setup(x => x.LoadSettings()) .Returns(new AgentSettings { }); _configStore.Setup(x => x.IsServiceConfigured()) .Returns(false); _messageListener.Setup(x => x.CreateSessionAsync(It.IsAny<CancellationToken>())) .Returns(Task.FromResult(false)); var agent = new Agent.Listener.Agent(); agent.Initialize(hc); await agent.ExecuteCommand(command); _messageListener.Verify(x => x.CreateSessionAsync(It.IsAny<CancellationToken>()), Times.Once()); } } [Fact] [Trait("Level", "L0")] [Trait("Category", "Agent")] //process 2 new job messages, and one cancel message public async void TestMachineProvisionerCLICompat() { using (var hc = new TestHostContext(this)) { hc.SetSingleton<IConfigurationManager>(_configurationManager.Object); hc.SetSingleton<IPromptManager>(_promptManager.Object); hc.SetSingleton<IMessageListener>(_messageListener.Object); hc.SetSingleton<IVstsAgentWebProxy>(_proxy.Object); hc.SetSingleton<IConfigurationStore>(_configStore.Object); var command = new CommandSettings(hc, new string[] { }); _configurationManager.Setup(x => x.IsConfigured()). Returns(true); _configurationManager.Setup(x => x.LoadSettings()) .Returns(new AgentSettings { }); _configStore.Setup(x => x.IsServiceConfigured()) .Returns(false); _messageListener.Setup(x => x.CreateSessionAsync(It.IsAny<CancellationToken>())) .Returns(Task.FromResult(false)); var agent = new Agent.Listener.Agent(); agent.Initialize(hc); await agent.ExecuteCommand(command); _messageListener.Verify(x => x.CreateSessionAsync(It.IsAny<CancellationToken>()), Times.Once()); } } } }
using System; using System.Collections; using System.IO; using System.Text; using Org.BouncyCastle.Asn1; using Org.BouncyCastle.Asn1.X509; using Org.BouncyCastle.Crypto.Agreement; using Org.BouncyCastle.Crypto.Agreement.Srp; using Org.BouncyCastle.Crypto.Digests; using Org.BouncyCastle.Crypto.Encodings; using Org.BouncyCastle.Crypto.Engines; using Org.BouncyCastle.Crypto.Generators; using Org.BouncyCastle.Crypto.IO; using Org.BouncyCastle.Crypto.Parameters; using Org.BouncyCastle.Crypto.Prng; using Org.BouncyCastle.Math; using Org.BouncyCastle.Security; using Org.BouncyCastle.Utilities; using Org.BouncyCastle.Utilities.Date; namespace Org.BouncyCastle.Crypto.Tls { /// <remarks>An implementation of all high level protocols in TLS 1.0.</remarks> public class TlsProtocolHandler { /* * Our Connection states */ private const short CS_CLIENT_HELLO_SEND = 1; private const short CS_SERVER_HELLO_RECEIVED = 2; private const short CS_SERVER_CERTIFICATE_RECEIVED = 3; private const short CS_SERVER_KEY_EXCHANGE_RECEIVED = 4; private const short CS_CERTIFICATE_REQUEST_RECEIVED = 5; private const short CS_SERVER_HELLO_DONE_RECEIVED = 6; private const short CS_CLIENT_KEY_EXCHANGE_SEND = 7; private const short CS_CERTIFICATE_VERIFY_SEND = 8; private const short CS_CLIENT_CHANGE_CIPHER_SPEC_SEND = 9; private const short CS_CLIENT_FINISHED_SEND = 10; private const short CS_SERVER_CHANGE_CIPHER_SPEC_RECEIVED = 11; private const short CS_DONE = 12; private static readonly byte[] emptybuf = new byte[0]; private static readonly string TLS_ERROR_MESSAGE = "Internal TLS error, this could be an attack"; /* * Queues for data from some protocols. */ private ByteQueue applicationDataQueue = new ByteQueue(); private ByteQueue changeCipherSpecQueue = new ByteQueue(); private ByteQueue alertQueue = new ByteQueue(); private ByteQueue handshakeQueue = new ByteQueue(); /* * The Record Stream we use */ private RecordStream rs; private SecureRandom random; private TlsStream tlsStream = null; private bool closed = false; private bool failedWithError = false; private bool appDataReady = false; private IDictionary clientExtensions; private SecurityParameters securityParameters = null; private TlsClientContextImpl tlsClientContext = null; private TlsClient tlsClient = null; private CipherSuite[] offeredCipherSuites = null; private CompressionMethod[] offeredCompressionMethods = null; private TlsKeyExchange keyExchange = null; private TlsAuthentication authentication = null; private CertificateRequest certificateRequest = null; private short connection_state = 0; private static SecureRandom CreateSecureRandom() { /* * We use our threaded seed generator to generate a good random seed. If the user * has a better random seed, he should use the constructor with a SecureRandom. * * Hopefully, 20 bytes in fast mode are good enough. */ byte[] seed = new ThreadedSeedGenerator().GenerateSeed(20, true); return new SecureRandom(seed); } public TlsProtocolHandler( Stream s) : this(s, s) { } public TlsProtocolHandler( Stream s, SecureRandom sr) : this(s, s, sr) { } /// <remarks>Both streams can be the same object</remarks> public TlsProtocolHandler( Stream inStr, Stream outStr) : this(inStr, outStr, CreateSecureRandom()) { } /// <remarks>Both streams can be the same object</remarks> public TlsProtocolHandler( Stream inStr, Stream outStr, SecureRandom sr) { this.rs = new RecordStream(this, inStr, outStr); this.random = sr; } internal void ProcessData( ContentType protocol, byte[] buf, int offset, int len) { /* * Have a look at the protocol type, and add it to the correct queue. */ switch (protocol) { case ContentType.change_cipher_spec: changeCipherSpecQueue.AddData(buf, offset, len); ProcessChangeCipherSpec(); break; case ContentType.alert: alertQueue.AddData(buf, offset, len); ProcessAlert(); break; case ContentType.handshake: handshakeQueue.AddData(buf, offset, len); ProcessHandshake(); break; case ContentType.application_data: if (!appDataReady) { this.FailWithError(AlertLevel.fatal, AlertDescription.unexpected_message); } applicationDataQueue.AddData(buf, offset, len); ProcessApplicationData(); break; default: /* * Uh, we don't know this protocol. * * RFC2246 defines on page 13, that we should ignore this. */ break; } } private void ProcessHandshake() { bool read; do { read = false; /* * We need the first 4 bytes, they contain type and length of * the message. */ if (handshakeQueue.Available >= 4) { byte[] beginning = new byte[4]; handshakeQueue.Read(beginning, 0, 4, 0); MemoryStream bis = new MemoryStream(beginning, false); HandshakeType type = (HandshakeType)TlsUtilities.ReadUint8(bis); int len = TlsUtilities.ReadUint24(bis); /* * Check if we have enough bytes in the buffer to read * the full message. */ if (handshakeQueue.Available >= (len + 4)) { /* * Read the message. */ byte[] buf = new byte[len]; handshakeQueue.Read(buf, 0, len, 4); handshakeQueue.RemoveData(len + 4); /* * RFC 2246 7.4.9. The value handshake_messages includes all * handshake messages starting at client hello up to, but not * including, this finished message. [..] Note: [Also,] Hello Request * messages are omitted from handshake hashes. */ switch (type) { case HandshakeType.hello_request: case HandshakeType.finished: break; default: rs.UpdateHandshakeData(beginning, 0, 4); rs.UpdateHandshakeData(buf, 0, len); break; } /* * Now, parse the message. */ ProcessHandshakeMessage(type, buf); read = true; } } } while (read); } private void ProcessHandshakeMessage(HandshakeType type, byte[] buf) { MemoryStream inStr = new MemoryStream(buf, false); /* * Check the type. */ switch (type) { case HandshakeType.certificate: { switch (connection_state) { case CS_SERVER_HELLO_RECEIVED: { // Parse the Certificate message and send to cipher suite Certificate serverCertificate = Certificate.Parse(inStr); AssertEmpty(inStr); this.keyExchange.ProcessServerCertificate(serverCertificate); this.authentication = tlsClient.GetAuthentication(); this.authentication.NotifyServerCertificate(serverCertificate); break; } default: this.FailWithError(AlertLevel.fatal, AlertDescription.unexpected_message); break; } connection_state = CS_SERVER_CERTIFICATE_RECEIVED; break; } case HandshakeType.finished: switch (connection_state) { case CS_SERVER_CHANGE_CIPHER_SPEC_RECEIVED: /* * Read the checksum from the finished message, it has always 12 bytes. */ byte[] serverVerifyData = new byte[12]; TlsUtilities.ReadFully(serverVerifyData, inStr); AssertEmpty(inStr); /* * Calculate our own checksum. */ byte[] expectedServerVerifyData = TlsUtilities.PRF( securityParameters.masterSecret, "server finished", rs.GetCurrentHash(), 12); /* * Compare both checksums. */ if (!Arrays.ConstantTimeAreEqual(expectedServerVerifyData, serverVerifyData)) { /* * Wrong checksum in the finished message. */ this.FailWithError(AlertLevel.fatal, AlertDescription.handshake_failure); } connection_state = CS_DONE; /* * We are now ready to receive application data. */ this.appDataReady = true; break; default: this.FailWithError(AlertLevel.fatal, AlertDescription.unexpected_message); break; } break; case HandshakeType.server_hello: switch (connection_state) { case CS_CLIENT_HELLO_SEND: /* * Read the server hello message */ TlsUtilities.CheckVersion(inStr, this); /* * Read the server random */ securityParameters.serverRandom = new byte[32]; TlsUtilities.ReadFully(securityParameters.serverRandom, inStr); byte[] sessionID = TlsUtilities.ReadOpaque8(inStr); if (sessionID.Length > 32) { this.FailWithError(AlertLevel.fatal, AlertDescription.illegal_parameter); } this.tlsClient.NotifySessionID(sessionID); /* * Find out which CipherSuite the server has chosen and check that * it was one of the offered ones. */ CipherSuite selectedCipherSuite = (CipherSuite)TlsUtilities.ReadUint16(inStr); if (!ArrayContains(offeredCipherSuites, selectedCipherSuite) || selectedCipherSuite == CipherSuite.TLS_EMPTY_RENEGOTIATION_INFO_SCSV) { this.FailWithError(AlertLevel.fatal, AlertDescription.illegal_parameter); } this.tlsClient.NotifySelectedCipherSuite(selectedCipherSuite); /* * Find out which CompressionMethod the server has chosen and check that * it was one of the offered ones. */ CompressionMethod selectedCompressionMethod = (CompressionMethod)TlsUtilities.ReadUint8(inStr); if (!ArrayContains(offeredCompressionMethods, selectedCompressionMethod)) { this.FailWithError(AlertLevel.fatal, AlertDescription.illegal_parameter); } this.tlsClient.NotifySelectedCompressionMethod(selectedCompressionMethod); /* * RFC3546 2.2 The extended server hello message format MAY be * sent in place of the server hello message when the client has * requested extended functionality via the extended client hello * message specified in Section 2.1. * ... * Note that the extended server hello message is only sent in response * to an extended client hello message. This prevents the possibility * that the extended server hello message could "break" existing TLS 1.0 * clients. */ /* * TODO RFC 3546 2.3 * If [...] the older session is resumed, then the server MUST ignore * extensions appearing in the client hello, and send a server hello * containing no extensions. */ // ExtensionType -> byte[] IDictionary serverExtensions = Platform.CreateHashtable(); if (inStr.Position < inStr.Length) { // Process extensions from extended server hello byte[] extBytes = TlsUtilities.ReadOpaque16(inStr); MemoryStream ext = new MemoryStream(extBytes, false); while (ext.Position < ext.Length) { ExtensionType extType = (ExtensionType)TlsUtilities.ReadUint16(ext); byte[] extValue = TlsUtilities.ReadOpaque16(ext); // Note: RFC 5746 makes a special case for EXT_RenegotiationInfo if (extType != ExtensionType.renegotiation_info && !clientExtensions.Contains(extType)) { /* * RFC 3546 2.3 * Note that for all extension types (including those defined in * future), the extension type MUST NOT appear in the extended server * hello unless the same extension type appeared in the corresponding * client hello. Thus clients MUST abort the handshake if they receive * an extension type in the extended server hello that they did not * request in the associated (extended) client hello. */ this.FailWithError(AlertLevel.fatal, AlertDescription.unsupported_extension); } if (serverExtensions.Contains(extType)) { /* * RFC 3546 2.3 * Also note that when multiple extensions of different types are * present in the extended client hello or the extended server hello, * the extensions may appear in any order. There MUST NOT be more than * one extension of the same type. */ this.FailWithError(AlertLevel.fatal, AlertDescription.illegal_parameter); } serverExtensions.Add(extType, extValue); } } AssertEmpty(inStr); /* * RFC 5746 3.4. When a ServerHello is received, the client MUST check if it * includes the "renegotiation_info" extension: */ { bool secure_negotiation = serverExtensions.Contains(ExtensionType.renegotiation_info); /* * If the extension is present, set the secure_renegotiation flag * to TRUE. The client MUST then verify that the length of the * "renegotiated_connection" field is zero, and if it is not, MUST * abort the handshake (by sending a fatal handshake_failure * alert). */ if (secure_negotiation) { byte[] renegExtValue = (byte[])serverExtensions[ExtensionType.renegotiation_info]; if (!Arrays.ConstantTimeAreEqual(renegExtValue, CreateRenegotiationInfo(emptybuf))) { this.FailWithError(AlertLevel.fatal, AlertDescription.handshake_failure); } } tlsClient.NotifySecureRenegotiation(secure_negotiation); } if (clientExtensions != null) { tlsClient.ProcessServerExtensions(serverExtensions); } this.keyExchange = tlsClient.GetKeyExchange(); connection_state = CS_SERVER_HELLO_RECEIVED; break; default: this.FailWithError(AlertLevel.fatal, AlertDescription.unexpected_message); break; } break; case HandshakeType.server_hello_done: switch (connection_state) { case CS_SERVER_CERTIFICATE_RECEIVED: case CS_SERVER_KEY_EXCHANGE_RECEIVED: case CS_CERTIFICATE_REQUEST_RECEIVED: // NB: Original code used case label fall-through if (connection_state == CS_SERVER_CERTIFICATE_RECEIVED) { // There was no server key exchange message; check it's OK this.keyExchange.SkipServerKeyExchange(); } AssertEmpty(inStr); connection_state = CS_SERVER_HELLO_DONE_RECEIVED; TlsCredentials clientCreds = null; if (certificateRequest == null) { this.keyExchange.SkipClientCredentials(); } else { clientCreds = this.authentication.GetClientCredentials(certificateRequest); Certificate clientCert; if (clientCreds == null) { this.keyExchange.SkipClientCredentials(); clientCert = Certificate.EmptyChain; } else { this.keyExchange.ProcessClientCredentials(clientCreds); clientCert = clientCreds.Certificate; } SendClientCertificate(clientCert); } /* * Send the client key exchange message, depending on the key * exchange we are using in our CipherSuite. */ SendClientKeyExchange(); connection_state = CS_CLIENT_KEY_EXCHANGE_SEND; if (clientCreds != null && clientCreds is TlsSignerCredentials) { TlsSignerCredentials signerCreds = (TlsSignerCredentials)clientCreds; byte[] md5andsha1 = rs.GetCurrentHash(); byte[] clientCertificateSignature = signerCreds.GenerateCertificateSignature( md5andsha1); SendCertificateVerify(clientCertificateSignature); connection_state = CS_CERTIFICATE_VERIFY_SEND; } /* * Now, we send change cipher state */ byte[] cmessage = new byte[1]; cmessage[0] = 1; rs.WriteMessage(ContentType.change_cipher_spec, cmessage, 0, cmessage.Length); connection_state = CS_CLIENT_CHANGE_CIPHER_SPEC_SEND; /* * Calculate the master_secret */ byte[] pms = this.keyExchange.GeneratePremasterSecret(); securityParameters.masterSecret = TlsUtilities.PRF(pms, "master secret", TlsUtilities.Concat(securityParameters.clientRandom, securityParameters.serverRandom), 48); // TODO Is there a way to ensure the data is really overwritten? /* * RFC 2246 8.1. The pre_master_secret should be deleted from * memory once the master_secret has been computed. */ Array.Clear(pms, 0, pms.Length); /* * Initialize our cipher suite */ rs.ClientCipherSpecDecided(tlsClient.GetCompression(), tlsClient.GetCipher()); /* * Send our finished message. */ byte[] clientVerifyData = TlsUtilities.PRF(securityParameters.masterSecret, "client finished", rs.GetCurrentHash(), 12); MemoryStream bos = new MemoryStream(); TlsUtilities.WriteUint8((byte)HandshakeType.finished, bos); TlsUtilities.WriteOpaque24(clientVerifyData, bos); byte[] message = bos.ToArray(); rs.WriteMessage(ContentType.handshake, message, 0, message.Length); this.connection_state = CS_CLIENT_FINISHED_SEND; break; default: this.FailWithError(AlertLevel.fatal, AlertDescription.handshake_failure); break; } break; case HandshakeType.server_key_exchange: { switch (connection_state) { case CS_SERVER_HELLO_RECEIVED: case CS_SERVER_CERTIFICATE_RECEIVED: { // NB: Original code used case label fall-through if (connection_state == CS_SERVER_HELLO_RECEIVED) { // There was no server certificate message; check it's OK this.keyExchange.SkipServerCertificate(); this.authentication = null; } this.keyExchange.ProcessServerKeyExchange(inStr); AssertEmpty(inStr); break; } default: this.FailWithError(AlertLevel.fatal, AlertDescription.unexpected_message); break; } this.connection_state = CS_SERVER_KEY_EXCHANGE_RECEIVED; break; } case HandshakeType.certificate_request: switch (connection_state) { case CS_SERVER_CERTIFICATE_RECEIVED: case CS_SERVER_KEY_EXCHANGE_RECEIVED: { // NB: Original code used case label fall-through if (connection_state == CS_SERVER_CERTIFICATE_RECEIVED) { // There was no server key exchange message; check it's OK this.keyExchange.SkipServerKeyExchange(); } if (this.authentication == null) { /* * RFC 2246 7.4.4. It is a fatal handshake_failure alert * for an anonymous server to request client identification. */ this.FailWithError(AlertLevel.fatal, AlertDescription.handshake_failure); } int numTypes = TlsUtilities.ReadUint8(inStr); ClientCertificateType[] certificateTypes = new ClientCertificateType[numTypes]; for (int i = 0; i < numTypes; ++i) { certificateTypes[i] = (ClientCertificateType)TlsUtilities.ReadUint8(inStr); } byte[] authorities = TlsUtilities.ReadOpaque16(inStr); AssertEmpty(inStr); IList authorityDNs = Platform.CreateArrayList(); MemoryStream bis = new MemoryStream(authorities, false); while (bis.Position < bis.Length) { byte[] dnBytes = TlsUtilities.ReadOpaque16(bis); // TODO Switch to X500Name when available authorityDNs.Add(X509Name.GetInstance(Asn1Object.FromByteArray(dnBytes))); } this.certificateRequest = new CertificateRequest(certificateTypes, authorityDNs); this.keyExchange.ValidateCertificateRequest(this.certificateRequest); break; } default: this.FailWithError(AlertLevel.fatal, AlertDescription.unexpected_message); break; } this.connection_state = CS_CERTIFICATE_REQUEST_RECEIVED; break; case HandshakeType.hello_request: /* * RFC 2246 7.4.1.1 Hello request * This message will be ignored by the client if the client is currently * negotiating a session. This message may be ignored by the client if it * does not wish to renegotiate a session, or the client may, if it wishes, * respond with a no_renegotiation alert. */ if (connection_state == CS_DONE) { // Renegotiation not supported yet SendAlert(AlertLevel.warning, AlertDescription.no_renegotiation); } break; case HandshakeType.client_key_exchange: case HandshakeType.certificate_verify: case HandshakeType.client_hello: default: // We do not support this! this.FailWithError(AlertLevel.fatal, AlertDescription.unexpected_message); break; } } private void ProcessApplicationData() { /* * There is nothing we need to do here. * * This function could be used for callbacks when application * data arrives in the future. */ } private void ProcessAlert() { while (alertQueue.Available >= 2) { /* * An alert is always 2 bytes. Read the alert. */ byte[] tmp = new byte[2]; alertQueue.Read(tmp, 0, 2, 0); alertQueue.RemoveData(2); byte level = tmp[0]; byte description = tmp[1]; if (level == (byte)AlertLevel.fatal) { /* * This is a fatal error. */ this.failedWithError = true; this.closed = true; /* * Now try to Close the stream, ignore errors. */ try { rs.Close(); } catch (Exception) { } throw new IOException(TLS_ERROR_MESSAGE); } else { /* * This is just a warning. */ if (description == (byte)AlertDescription.close_notify) { /* * Close notify */ this.FailWithError(AlertLevel.warning, AlertDescription.close_notify); } /* * If it is just a warning, we continue. */ } } } /** * This method is called, when a change cipher spec message is received. * * @throws IOException If the message has an invalid content or the * handshake is not in the correct state. */ private void ProcessChangeCipherSpec() { while (changeCipherSpecQueue.Available > 0) { /* * A change cipher spec message is only one byte with the value 1. */ byte[] b = new byte[1]; changeCipherSpecQueue.Read(b, 0, 1, 0); changeCipherSpecQueue.RemoveData(1); if (b[0] != 1) { /* * This should never happen. */ this.FailWithError(AlertLevel.fatal, AlertDescription.unexpected_message); } /* * Check if we are in the correct connection state. */ if (this.connection_state != CS_CLIENT_FINISHED_SEND) { this.FailWithError(AlertLevel.fatal, AlertDescription.handshake_failure); } rs.ServerClientSpecReceived(); this.connection_state = CS_SERVER_CHANGE_CIPHER_SPEC_RECEIVED; } } private void SendClientCertificate(Certificate clientCert) { MemoryStream bos = new MemoryStream(); TlsUtilities.WriteUint8((byte)HandshakeType.certificate, bos); clientCert.Encode(bos); byte[] message = bos.ToArray(); rs.WriteMessage(ContentType.handshake, message, 0, message.Length); } private void SendClientKeyExchange() { MemoryStream bos = new MemoryStream(); TlsUtilities.WriteUint8((byte)HandshakeType.client_key_exchange, bos); this.keyExchange.GenerateClientKeyExchange(bos); byte[] message = bos.ToArray(); rs.WriteMessage(ContentType.handshake, message, 0, message.Length); } private void SendCertificateVerify(byte[] data) { /* * Send signature of handshake messages so far to prove we are the owner of * the cert See RFC 2246 sections 4.7, 7.4.3 and 7.4.8 */ MemoryStream bos = new MemoryStream(); TlsUtilities.WriteUint8((byte)HandshakeType.certificate_verify, bos); TlsUtilities.WriteUint24(data.Length + 2, bos); TlsUtilities.WriteOpaque16(data, bos); byte[] message = bos.ToArray(); rs.WriteMessage(ContentType.handshake, message, 0, message.Length); } /// <summary>Connects to the remote system.</summary> /// <param name="verifyer">Will be used when a certificate is received to verify /// that this certificate is accepted by the client.</param> /// <exception cref="IOException">If handshake was not successful</exception> [Obsolete("Use version taking TlsClient")] public virtual void Connect( ICertificateVerifyer verifyer) { this.Connect(new LegacyTlsClient(verifyer)); } public virtual void Connect(TlsClient tlsClient) { if (tlsClient == null) throw new ArgumentNullException("tlsClient"); if (this.tlsClient != null) throw new InvalidOperationException("Connect can only be called once"); /* * Send Client hello * * First, generate some random data. */ this.securityParameters = new SecurityParameters(); this.securityParameters.clientRandom = new byte[32]; random.NextBytes(securityParameters.clientRandom, 4, 28); TlsUtilities.WriteGmtUnixTime(securityParameters.clientRandom, 0); this.tlsClientContext = new TlsClientContextImpl(random, securityParameters); this.tlsClient = tlsClient; this.tlsClient.Init(tlsClientContext); MemoryStream outStr = new MemoryStream(); TlsUtilities.WriteVersion(outStr); outStr.Write(securityParameters.clientRandom, 0, 32); /* * Length of Session id */ TlsUtilities.WriteUint8(0, outStr); this.offeredCipherSuites = this.tlsClient.GetCipherSuites(); // ExtensionType -> byte[] this.clientExtensions = this.tlsClient.GetClientExtensions(); // Cipher Suites (and SCSV) { /* * RFC 5746 3.4. * The client MUST include either an empty "renegotiation_info" * extension, or the TLS_EMPTY_RENEGOTIATION_INFO_SCSV signaling * cipher suite value in the ClientHello. Including both is NOT * RECOMMENDED. */ bool noRenegExt = clientExtensions == null || !clientExtensions.Contains(ExtensionType.renegotiation_info); int count = offeredCipherSuites.Length; if (noRenegExt) { // Note: 1 extra slot for TLS_EMPTY_RENEGOTIATION_INFO_SCSV ++count; } TlsUtilities.WriteUint16(2 * count, outStr); for (int i = 0; i < offeredCipherSuites.Length; ++i) { TlsUtilities.WriteUint16((int)offeredCipherSuites[i], outStr); } if (noRenegExt) { TlsUtilities.WriteUint16((int)CipherSuite.TLS_EMPTY_RENEGOTIATION_INFO_SCSV, outStr); } } /* * Compression methods, just the null method. */ this.offeredCompressionMethods = tlsClient.GetCompressionMethods(); { TlsUtilities.WriteUint8((byte)offeredCompressionMethods.Length, outStr); for (int i = 0; i < offeredCompressionMethods.Length; ++i) { TlsUtilities.WriteUint8((byte)offeredCompressionMethods[i], outStr); } } // Extensions if (clientExtensions != null) { MemoryStream ext = new MemoryStream(); foreach (ExtensionType extType in clientExtensions.Keys) { WriteExtension(ext, extType, (byte[])clientExtensions[extType]); } TlsUtilities.WriteOpaque16(ext.ToArray(), outStr); } MemoryStream bos = new MemoryStream(); TlsUtilities.WriteUint8((byte)HandshakeType.client_hello, bos); TlsUtilities.WriteUint24((int)outStr.Length, bos); byte[] outBytes = outStr.ToArray(); bos.Write(outBytes, 0, outBytes.Length); byte[] message = bos.ToArray(); SafeWriteMessage(ContentType.handshake, message, 0, message.Length); connection_state = CS_CLIENT_HELLO_SEND; /* * We will now read data, until we have completed the handshake. */ while (connection_state != CS_DONE) { SafeReadData(); } this.tlsStream = new TlsStream(this); } /** * Read data from the network. The method will return immediately, if there is * still some data left in the buffer, or block until some application * data has been read from the network. * * @param buf The buffer where the data will be copied to. * @param offset The position where the data will be placed in the buffer. * @param len The maximum number of bytes to read. * @return The number of bytes read. * @throws IOException If something goes wrong during reading data. */ internal int ReadApplicationData(byte[] buf, int offset, int len) { while (applicationDataQueue.Available == 0) { if (this.closed) { /* * We need to read some data. */ if (this.failedWithError) { /* * Something went terribly wrong, we should throw an IOException */ throw new IOException(TLS_ERROR_MESSAGE); } /* * Connection has been closed, there is no more data to read. */ return 0; } SafeReadData(); } len = System.Math.Min(len, applicationDataQueue.Available); applicationDataQueue.Read(buf, offset, len, 0); applicationDataQueue.RemoveData(len); return len; } private void SafeReadData() { try { rs.ReadData(); } catch (TlsFatalAlert e) { if (!this.closed) { this.FailWithError(AlertLevel.fatal, e.AlertDescription); } throw e; } catch (IOException e) { if (!this.closed) { this.FailWithError(AlertLevel.fatal, AlertDescription.internal_error); } throw e; } catch (Exception e) { if (!this.closed) { this.FailWithError(AlertLevel.fatal, AlertDescription.internal_error); } throw e; } } private void SafeWriteMessage(ContentType type, byte[] buf, int offset, int len) { try { rs.WriteMessage(type, buf, offset, len); } catch (TlsFatalAlert e) { if (!this.closed) { this.FailWithError(AlertLevel.fatal, e.AlertDescription); } throw e; } catch (IOException e) { if (!closed) { this.FailWithError(AlertLevel.fatal, AlertDescription.internal_error); } throw e; } catch (Exception e) { if (!closed) { this.FailWithError(AlertLevel.fatal, AlertDescription.internal_error); } throw e; } } /** * Send some application data to the remote system. * <p/> * The method will handle fragmentation internally. * * @param buf The buffer with the data. * @param offset The position in the buffer where the data is placed. * @param len The length of the data. * @throws IOException If something goes wrong during sending. */ internal void WriteData(byte[] buf, int offset, int len) { if (this.closed) { if (this.failedWithError) throw new IOException(TLS_ERROR_MESSAGE); throw new IOException("Sorry, connection has been closed, you cannot write more data"); } /* * Protect against known IV attack! * * DO NOT REMOVE THIS LINE, EXCEPT YOU KNOW EXACTLY WHAT * YOU ARE DOING HERE. */ SafeWriteMessage(ContentType.application_data, emptybuf, 0, 0); do { /* * We are only allowed to write fragments up to 2^14 bytes. */ int toWrite = System.Math.Min(len, 1 << 14); SafeWriteMessage(ContentType.application_data, buf, offset, toWrite); offset += toWrite; len -= toWrite; } while (len > 0); } /// <summary>A Stream which can be used to send data.</summary> [Obsolete("Use 'Stream' property instead")] public virtual Stream OutputStream { get { return this.tlsStream; } } /// <summary>A Stream which can be used to read data.</summary> [Obsolete("Use 'Stream' property instead")] public virtual Stream InputStream { get { return this.tlsStream; } } /// <summary>The secure bidirectional stream for this connection</summary> public virtual Stream Stream { get { return this.tlsStream; } } /** * Terminate this connection with an alert. * <p/> * Can be used for normal closure too. * * @param alertLevel The level of the alert, an be AlertLevel.fatal or AL_warning. * @param alertDescription The exact alert message. * @throws IOException If alert was fatal. */ private void FailWithError(AlertLevel alertLevel, AlertDescription alertDescription) { /* * Check if the connection is still open. */ if (!closed) { /* * Prepare the message */ this.closed = true; if (alertLevel == AlertLevel.fatal) { /* * This is a fatal message. */ this.failedWithError = true; } SendAlert(alertLevel, alertDescription); rs.Close(); if (alertLevel == AlertLevel.fatal) { throw new IOException(TLS_ERROR_MESSAGE); } } else { throw new IOException(TLS_ERROR_MESSAGE); } } internal void SendAlert(AlertLevel alertLevel, AlertDescription alertDescription) { byte[] error = new byte[2]; error[0] = (byte)alertLevel; error[1] = (byte)alertDescription; rs.WriteMessage(ContentType.alert, error, 0, 2); } /// <summary>Closes this connection</summary> /// <exception cref="IOException">If something goes wrong during closing.</exception> public virtual void Close() { if (!closed) { this.FailWithError(AlertLevel.warning, AlertDescription.close_notify); } } /** * Make sure the Stream is now empty. Fail otherwise. * * @param is The Stream to check. * @throws IOException If is is not empty. */ internal void AssertEmpty( MemoryStream inStr) { if (inStr.Position < inStr.Length) { throw new TlsFatalAlert(AlertDescription.decode_error); } } internal void Flush() { rs.Flush(); } internal bool IsClosed { get { return closed; } } private static bool ArrayContains(CipherSuite[] a, CipherSuite n) { for (int i = 0; i < a.Length; ++i) { if (a[i] == n) return true; } return false; } private static bool ArrayContains(CompressionMethod[] a, CompressionMethod n) { for (int i = 0; i < a.Length; ++i) { if (a[i] == n) return true; } return false; } private static byte[] CreateRenegotiationInfo(byte[] renegotiated_connection) { MemoryStream buf = new MemoryStream(); TlsUtilities.WriteOpaque8(renegotiated_connection, buf); return buf.ToArray(); } private static void WriteExtension(Stream output, ExtensionType extType, byte[] extValue) { TlsUtilities.WriteUint16((int)extType, output); TlsUtilities.WriteOpaque16(extValue, output); } } }
using UnityEngine; using System.Collections; using System.Collections.Generic; using System.IO; public class GameManager : MonoBehaviour { public static GameManager Instance { get; private set; } public GameObject[] TaskParents; public GameObject GameOverPrefab; public GameObject NewGamePrefab; public GameObject TaskCompleteFX; public GameObject TaskIncompleteFX; public GameObject TutorialTask; public GameObject ScoreObject, HighScoreObject, CompletedTasksObject; private UnityEngine.UI.Text scoreText, highScoreText, completedTasksText; //Official Game TIme public float GameTime { get; private set; } public float SpawnInterval = 2.0f; private float startTime, elapsedTime, lastSpawnTime; private int completedTasks = 0; private int score = 0; private float combinedTime; private int day = 0; private int dataDay = 0; // the day we access from data, might be less than the actual day if there is not enough data. private int hours, minutes; private TasksResource Tasks; private List<GameObject> ActiveTasks = new List<GameObject>(); private GameObject ClockGO; private TextMesh ClockText; private GameObject DayGO; private TextMesh DayText; private GameObject TimeBarGO; private GridDefinition Grid; private const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; private static string highScoreFilename = "highscore.txt"; private static int dayStart = 6; private static int dayEnd = 8; private bool gameOver = false; private int highScore = 0; void Awake () { if (Instance != null && Instance != this) { Destroy(gameObject); } Instance = this; DontDestroyOnLoad(gameObject); startTime = Time.time; Tasks = Resources.Load<TasksResource>("Tasks"); Grid = new GridDefinition(); ClockGO = GameObject.Find("Time"); ClockText = ClockGO.GetComponent<TextMesh>(); DayGO = GameObject.Find("Day"); DayText = DayGO.GetComponent<TextMesh>(); TimeBarGO = GameObject.Find("TimeBar"); scoreText = ScoreObject.GetComponent<UnityEngine.UI.Text>(); highScoreText = HighScoreObject.GetComponent<UnityEngine.UI.Text>(); completedTasksText = CompletedTasksObject.GetComponent<UnityEngine.UI.Text>(); highScore = ReadHighScore(); highScoreText.text = "High Score: " + highScore.ToString(); lastSpawnTime = 0.0f; } void Start() { scoreText.text = "Score: " + score.ToString(); //spawn tutorial task GameObject FTUETask = GameObject.Instantiate(TutorialTask); ActiveTasks.Add(FTUETask); Grid.TaskInPosition[4] = FTUETask; FTUETask.transform.parent = TaskParents[4].transform; FTUETask.transform.localPosition = Vector3.zero; TaskManagerBase newTaskManager = FTUETask.GetComponent<TaskManagerBase>(); if (newTaskManager != null) { newTaskManager.SetGridPosition(4); } } //Main game loop. void Update () { GameTime = Time.time - startTime; int rawMinutes = (int) System.Math.Floor(GameTime * 3.0f); minutes = rawMinutes % 60; hours = dayStart + (rawMinutes - minutes) / 60; ClockText.text = hours.ToString("D2") + ":" + minutes.ToString("D2"); if(hours >= dayEnd && !gameOver) { NextDay(); } if (GameTime > lastSpawnTime + SpawnInterval && !gameOver) { int nextEmptyGridPosition = Grid.GetNextEmpty(); if (nextEmptyGridPosition != -1) { GameObject randomTask = Tasks.Days[dataDay].Tasks[Random.Range(0, Tasks.Days[dataDay].Tasks.Length)]; GameObject newTask = GameObject.Instantiate(randomTask); ActiveTasks.Add(newTask); Grid.TaskInPosition[nextEmptyGridPosition] = newTask; newTask.transform.parent = TaskParents[nextEmptyGridPosition].transform; newTask.transform.localPosition = Vector3.zero; TaskManagerBase newTaskManager = newTask.GetComponent<TaskManagerBase>(); if (newTaskManager != null) { newTaskManager.SetGridPosition(nextEmptyGridPosition); } lastSpawnTime = GameTime; SpawnInterval *= 0.96f; } else if(!gameOver) { GameOver(); } } TimeBarGO.transform.localScale = new Vector3(1.0f - rawMinutes / (60.0f*(dayEnd-dayStart) ), 1.0f, 1.0f ); } public void TaskCompleted(TaskResult result) { GameObject completedTask = Grid.TaskInPosition[result.gridPosition]; GameObject.Destroy(completedTask); ActiveTasks.Remove(completedTask); Grid.TaskInPosition[result.gridPosition] = null; //Debug.Log("Task at " + result.gridPosition + " completed in " + result.completionTime + " seconds"); bool success = result.completionPercentage > 0.99f; GameObject FX = success ? GameObject.Instantiate(TaskCompleteFX) : GameObject.Instantiate(TaskIncompleteFX); FX.transform.parent = TaskParents[result.gridPosition].transform; FX.transform.localPosition = Vector3.zero; //update scores if (success) completedTasks++; combinedTime += result.completionTime; int taskScore = (int) (10.0f * (result.TimeoutTime / (result.completionTime + 0.01f))); if(success) score += taskScore; scoreText.text = "Score: " + score.ToString(); completedTasksText.text = "Completed: " + completedTasks.ToString(); if (AudioManager.Instance != null) { AudioManager.Instance.PlaySound(SoundEffect.TaskComplete); } } private void NextDay() { day++; startTime = Time.time; lastSpawnTime = 0.0f; GameTime = Time.time - startTime; dataDay = System.Math.Min(day, Tasks.Days.Length-1); SpawnInterval = Tasks.Days[dataDay].SpawnInterval; KillAllTasks(); DayText.text = "Day " + (day+1).ToString(); // +1 because the first day is day 1, not day 0 GameObject.Instantiate(Tasks.Days[dataDay].DayStartBillboard); } private int ReadHighScore() { int highscore = PlayerPrefs.GetInt("highscore"); return highscore; } private void WriteHighScore(int newhighscore) { PlayerPrefs.SetInt ("highscore", newhighscore); } private void GameOver() { GameOverPrefab.SetActive(true); NewGamePrefab.SetActive(true); KillAllTasks(); gameOver = true; if (score > highScore) { highScore = score; WriteHighScore(score); highScoreText.text = "High Score: " + highScore.ToString(); } } public void NewGame() { score = 0; day = dataDay = 0; startTime = Time.time; GameTime = lastSpawnTime = 0.0f; gameOver = false; SpawnInterval = Tasks.Days[0].SpawnInterval; GameOverPrefab.SetActive(false); NewGamePrefab.SetActive(false); DayText.text = "Day " + (day + 1).ToString(); // +1 because the first day is day 1, not day 0 Start(); } private void KillAllTasks() { for (int i = 0; i < 9; i++) { GameObject completedTask = Grid.TaskInPosition[i]; if (completedTask != null) { GameObject.Destroy(completedTask); ActiveTasks.Remove(completedTask); } } } private string GetRandomString(int length) { string str = ""; for (int i = 0; i < length; i++) { str += chars[(int)(Random.value * 26)].ToString(); } return str; } } public class TaskResult { public int gridPosition; public float completionTime; public float TimeoutTime; public float completionPercentage; // 0...1 }
/* * REST API Documentation for the MOTI Hired Equipment Tracking System (HETS) Application * * The Hired Equipment Program is for owners/operators who have a dump truck, bulldozer, backhoe or other piece of equipment they want to hire out to the transportation ministry for day labour and emergency projects. The Hired Equipment Program distributes available work to local equipment owners. The program is based on seniority and is designed to deliver work to registered users fairly and efficiently through the development of local area call-out lists. * * OpenAPI spec version: v1 * * */ using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.IO; using System.Linq; using System.Net; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using Newtonsoft.Json; using HETSAPI.Models; using HETSAPI.ViewModels; using HETSAPI.Mappings; using Microsoft.AspNetCore.Http; namespace HETSAPI.Services.Impl { /// <summary> /// /// </summary> public class EquipmentService : ServiceBase, IEquipmentService { private readonly DbAppContext _context; /// <summary> /// Create a service and set the database context /// </summary> public EquipmentService(IHttpContextAccessor httpContextAccessor, DbAppContext context) : base(httpContextAccessor, context) { _context = context; } private void AdjustRecord(Equipment item) { if (item != null) { // Adjust the record to allow it to be updated / inserted if (item.LocalArea != null) { item.LocalArea = _context.LocalAreas.FirstOrDefault(a => a.Id == item.LocalArea.Id); } // DistrictEquiptmentType if (item.DistrictEquipmentType != null) { item.DistrictEquipmentType = _context.DistrictEquipmentTypes.FirstOrDefault(a => a.Id == item.DistrictEquipmentType.Id); } // dump truck details if (item.DumpTruck != null) { item.DumpTruck = _context.DumpTrucks.FirstOrDefault(a => a.Id == item.DumpTruck.Id); } // owner if (item.Owner != null) { item.Owner = _context.Owners .Include(x => x.EquipmentList) .FirstOrDefault(a => a.Id == item.Owner.Id); } // EquipmentAttachments is a list if (item.EquipmentAttachments != null) { for (int i = 0; i < item.EquipmentAttachments.Count; i++) { if (item.EquipmentAttachments[i] != null) { item.EquipmentAttachments[i] = _context.EquipmentAttachments.FirstOrDefault(a => a.Id == item.EquipmentAttachments[i].Id); } } } // Attachments is a list if (item.Attachments != null) { for (int i = 0; i < item.Attachments.Count; i++) { if (item.Attachments[i] != null) { item.Attachments[i] = _context.Attachments.FirstOrDefault(a => a.Id == item.Attachments[i].Id); } } } // Notes is a list if (item.Notes != null) { for (int i = 0; i < item.Notes.Count; i++) { if (item.Notes[i] != null) { item.Notes[i] = _context.Notes.FirstOrDefault(a => a.Id == item.Notes[i].Id); } } } // History is a list if (item.History != null) { for (int i = 0; i < item.History.Count; i++) { if (item.History[i] != null) { item.History[i] = _context.Historys.FirstOrDefault(a => a.Id == item.History[i].Id); } } } } } /// <summary> /// /// </summary> /// <param name="items"></param> /// <response code="201">Equipment created</response> public virtual IActionResult EquipmentBulkPostAsync(Equipment[] items) { if (items == null) { return new BadRequestResult(); } foreach (Equipment item in items) { AdjustRecord(item); // determine if this is an insert or an update bool exists = _context.Equipments.Any(a => a.Id == item.Id); if (exists) { _context.Update(item); } else { _context.Add(item); } } // Save the changes _context.SaveChanges(); return new NoContentResult(); } /// <summary> /// /// </summary> /// <response code="200">OK</response> public virtual IActionResult EquipmentGetAsync() { var result = _context.Equipments .Include(x => x.LocalArea.ServiceArea.District.Region) .Include(x => x.DistrictEquipmentType) .Include(x => x.DumpTruck) .Include(x => x.Owner) .Include(x => x.EquipmentAttachments) .Include(x => x.Notes) .Include(x => x.Attachments) .Include(x => x.History) .ToList(); return new ObjectResult(result); } /// <summary> /// Remove seniority audits associated with an equipment ID /// </summary> /// <param name="equipmentId"></param> private void RemoveSeniorityAudits(int equipmentId) { var seniorityAudits = _context.SeniorityAudits .Include(x => x.Equipment) .Where(x => x.Equipment.Id == equipmentId) .ToList(); if (seniorityAudits != null) { foreach (SeniorityAudit seniorityAudit in seniorityAudits) { _context.SeniorityAudits.Remove(seniorityAudit); } } _context.SaveChanges(); } /// <summary> /// /// </summary> /// <remarks>Returns attachments for a particular Equipment</remarks> /// <param name="id">id of Equipment to fetch attachments for</param> /// <response code="200">OK</response> /// <response code="404">Equipment not found</response> public virtual IActionResult EquipmentIdAttachmentsGetAsync(int id) { bool exists = _context.Owners.Any(a => a.Id == id); if (exists) { Equipment equipment = _context.Equipments .Include(x => x.Attachments) .First(a => a.Id == id); var result = MappingExtensions.GetAttachmentListAsViewModel(equipment.Attachments); return new ObjectResult(result); } else { // record not found return new StatusCodeResult(404); } } /// <summary> /// /// </summary> /// <param name="id">id of Equipment to delete</param> /// <response code="200">OK</response> /// <response code="404">Equipment not found</response> public virtual IActionResult EquipmentIdDeletePostAsync(int id) { var exists = _context.Equipments.Any(a => a.Id == id); if (exists) { // remove associated seniority audits. RemoveSeniorityAudits(id); var item = _context.Equipments .Include(x => x.LocalArea) .Include(x => x.DistrictEquipmentType.EquipmentType) .First(a => a.Id == id); int localAreaId = -1; int equipmentTypeId = -1; if (item.LocalArea != null && item.DistrictEquipmentType != null && item.DistrictEquipmentType.EquipmentType != null) { localAreaId = item.LocalArea.Id; equipmentTypeId = item.DistrictEquipmentType.EquipmentType.Id; } _context.Equipments.Remove(item); // Save the changes _context.SaveChanges(); // update the seniority list if (localAreaId != -1 && equipmentTypeId != -1) { _context.CalculateSeniorityList(localAreaId, equipmentTypeId); } return new ObjectResult(item); } else { // record not found return new StatusCodeResult(404); } } /// <summary> /// /// </summary> /// <remarks>Returns History for a particular Equipment</remarks> /// <param name="id">id of SchoolBus to fetch History for</param> /// <response code="200">OK</response> public virtual IActionResult EquipmentIdHistoryGetAsync(int id, int? offset, int? limit) { bool exists = _context.Equipments.Any(a => a.Id == id); if (exists) { Equipment schoolBus = _context.Equipments .Include(x => x.History) .First(a => a.Id == id); List<History> data = schoolBus.History.OrderByDescending(y => y.LastUpdateTimestamp).ToList(); if (offset == null) { offset = 0; } if (limit == null) { limit = data.Count() - offset; } List<HistoryViewModel> result = new List<HistoryViewModel>(); for (int i = (int)offset; i < data.Count() && i < offset + limit; i++) { result.Add(data[i].ToViewModel(id)); } return new ObjectResult(result); } else { // record not found return new StatusCodeResult(404); } } /// <summary> /// /// </summary> /// <remarks>Add a History record to the Equipment</remarks> /// <param name="id">id of Equipment to add History for</param> /// <param name="item"></param> /// <response code="200">OK</response> /// <response code="201">History created</response> public virtual IActionResult EquipmentIdHistoryPostAsync(int id, History item) { HistoryViewModel result = new HistoryViewModel(); bool exists = _context.Equipments.Any(a => a.Id == id); if (exists) { Equipment equipment = _context.Equipments .Include(x => x.History) .First(a => a.Id == id); if (equipment.History == null) { equipment.History = new List<History>(); } // force add item.Id = 0; equipment.History.Add(item); _context.Equipments.Update(equipment); _context.SaveChanges(); } result.HistoryText = item.HistoryText; result.Id = item.Id; result.LastUpdateTimestamp = item.LastUpdateTimestamp; result.LastUpdateUserid = item.LastUpdateUserid; result.AffectedEntityId = id; return new ObjectResult(result); } /// <summary> /// /// </summary> /// <param name="id">id of Equipment to fetch EquipmentAttachments for</param> /// <response code="200">OK</response> public virtual IActionResult EquipmentIdEquipmentattachmentsGetAsync(int id) { bool exists = _context.Equipments.Any(x => x.Id == id); if (exists) { var result = _context.EquipmentAttachments .Include(x => x.Equipment) .Where(x => x.Equipment.Id == id); return new ObjectResult(result); } else { // record not found return new StatusCodeResult(404); } } /// <summary> /// /// </summary> /// <param name="id">id of Equipment to fetch</param> /// <response code="200">OK</response> /// <response code="404">Equipment not found</response> public virtual IActionResult EquipmentIdGetAsync(int id) { var exists = _context.Equipments.Any(a => a.Id == id); if (exists) { var result = _context.Equipments .Include(x => x.LocalArea.ServiceArea.District.Region) .Include(x => x.DistrictEquipmentType.EquipmentType) .Include(x => x.DumpTruck) .Include(x => x.Owner) .Include(x => x.EquipmentAttachments) .Include(x => x.Notes) .Include(x => x.Attachments) .Include(x => x.History) .First(a => a.Id == id); return new ObjectResult(result); } else { // record not found return new StatusCodeResult(404); } } /// <summary> /// /// </summary> /// <param name="id">id of Equipment to fetch</param> /// <param name="item"></param> /// <response code="200">OK</response> /// <response code="404">Equipment not found</response> public virtual IActionResult EquipmentIdPutAsync(int id, Equipment item) { if (item != null) { AdjustRecord(item); DateTime? originalSeniorityEffectiveDate = _context.GetEquipmentSeniorityEffectiveDate(id); var exists = _context.Equipments .Any(a => a.Id == id); if (exists && id == item.Id) { _context.Equipments.Update(item); // Save the changes _context.SaveChanges(); // if seniority has changed, update blocks. if ((originalSeniorityEffectiveDate == null && item.SeniorityEffectiveDate != null) || (originalSeniorityEffectiveDate != null && item.SeniorityEffectiveDate != null && originalSeniorityEffectiveDate < item.SeniorityEffectiveDate)) { _context.UpdateBlocksFromEquipment(item); } var result = _context.Equipments .Include(x => x.LocalArea.ServiceArea.District.Region) .Include(x => x.DistrictEquipmentType) .Include(x => x.DumpTruck) .Include(x => x.Owner) .Include(x => x.EquipmentAttachments) .Include(x => x.Notes) .Include(x => x.Attachments) .Include(x => x.History) .First(a => a.Id == id); return new ObjectResult(result); } else { // record not found return new StatusCodeResult(404); } } else { // record not found return new StatusCodeResult(404); } } private void CalculateViewModel(EquipmentViewModel result) { // populate the calculated fields. // ServiceHoursThisYear is the sum of TimeCard hours for the current fiscal year (April 1 - March 31) for the equipment. // At this time the structure for timecard hours is not set, so it is set to a constant. // TODO: change to a real calculation once the structure for timecard hours is established. result.ServiceHoursThisYear = 99; // lastTimeRecordDateThisYear is the most recent time card date this year. Can be null. // TODO: change to a real calculation once the structure for timecard hours is established. result.LastTimeRecordDateThisYear = null; // isWorking is true if there is an active Rental Agreements for the equipment. result.IsWorking = _context.RentalAgreements .Include(x => x.Equipment) .Any(x => x.Equipment.Id == result.Id); // hasDuplicates is true if there is other equipment with the same serial number. result.HasDuplicates = _context.Equipments.Any(x => x.SerialNumber == result.SerialNumber && x.Status == "Active"); // duplicate Equipment uses the same criteria as hasDuplicates. if (result.HasDuplicates == true) { result.DuplicateEquipment = _context.Equipments .Include(x => x.LocalArea.ServiceArea.District.Region) .Include(x => x.DistrictEquipmentType) .Include(x => x.DumpTruck) .Include(x => x.Owner) .Include(x => x.EquipmentAttachments) .Include(x => x.Notes) .Include(x => x.Attachments) .Include(x => x.History) .Where(x => x.SerialNumber == result.SerialNumber && x.Status == "Active") .ToList(); } } /// <summary> /// /// </summary> /// <param name="id">id of Equipment to fetch EquipmentViewModel for</param> /// <response code="200">OK</response> public virtual IActionResult EquipmentIdViewGetAsync(int id) { var exists = _context.Equipments.Any(a => a.Id == id); if (exists) { var equipment = _context.Equipments .Include(x => x.LocalArea.ServiceArea.District.Region) .Include(x => x.DistrictEquipmentType) .Include(x => x.DumpTruck) .Include(x => x.Owner) .Include(x => x.EquipmentAttachments) .Include(x => x.Notes) .Include(x => x.Attachments) .Include(x => x.History) .First(a => a.Id == id); var result = equipment.ToViewModel(); CalculateViewModel(result); return new ObjectResult(result); } else { // record not found return new StatusCodeResult(404); } } private string GenerateEquipmentCode(string ownerEquipmentCodePrefix, int equipmentNumber) { string result = ownerEquipmentCodePrefix + "-" + equipmentNumber.ToString("D4"); return result; } /// <summary> /// Set the Equipment fields for a new record for fields that are not provided by the front end. /// </summary> /// <param name="item"></param> private void SetNewRecordFields(Equipment item) { item.ReceivedDate = DateTime.UtcNow; item.LastVerifiedDate = DateTime.UtcNow; // generate a new equipment code. if (item.Owner != null) { int equipmentNumber = 1; if (item.Owner.EquipmentList != null) { bool looking = true; equipmentNumber = item.Owner.EquipmentList.Count + 1; // generate a unique equipment number while (looking) { string candidate = GenerateEquipmentCode(item.Owner.OwnerEquipmentCodePrefix, equipmentNumber); if ((item.Owner.EquipmentList).Any(x => x.EquipmentCode == candidate)) { equipmentNumber++; } else { looking = false; } } } // set the equipment code item.EquipmentCode = GenerateEquipmentCode(item.Owner.OwnerEquipmentCodePrefix, equipmentNumber); } } /// <summary> /// /// </summary> /// <param name="item"></param> /// <response code="201">Equipment created</response> public virtual IActionResult EquipmentPostAsync(Equipment item) { if (item != null) { AdjustRecord(item); bool exists = _context.Equipments.Any(a => a.Id == item.Id); if (exists) { _context.Equipments.Update(item); _context.SaveChanges(); } else { // record not found // Certain fields are set on new record. SetNewRecordFields(item); _context.Equipments.Add(item); _context.SaveChanges(); // add the equipment to the Owner's equipment list. Owner owner = item.Owner; if (owner != null) { if (owner.EquipmentList == null) { owner.EquipmentList = new List<Equipment>(); } if (!owner.EquipmentList.Contains(item)) { owner.EquipmentList.Add(item); _context.Owners.Update(owner); } } _context.SaveChanges(); // now update the seniority list. if (item.LocalArea != null && item.DistrictEquipmentType != null && item.DistrictEquipmentType.EquipmentType != null) { _context.CalculateSeniorityList(item.LocalArea.Id, item.DistrictEquipmentType.EquipmentType.Id); } } // return the full object for the client side code. int item_id = item.Id; var result = _context.Equipments .Include(x => x.LocalArea.ServiceArea.District.Region) .Include(x => x.DistrictEquipmentType) .Include(x => x.DumpTruck) .Include(x => x.Owner) .Include(x => x.EquipmentAttachments) .Include(x => x.Notes) .Include(x => x.Attachments) .Include(x => x.History) .First(a => a.Id == item_id); return new ObjectResult(result); } else { // record not found return new StatusCodeResult(404); } } /// <summary> /// Recalculates seniority for the database /// </summary> /// <remarks>Used to calculate seniority for all database records.</remarks> /// <response code="200">OK</response> public virtual IActionResult EquipmentRecalcSeniorityGetAsync(int region) { // calculate all of the rotation lists. var localAreas = _context.LocalAreas .Where(x => x.ServiceArea.District.Region.Id == region) .Select(x => x) .ToList(); var equipmentTypes = _context.EquipmentTypes.Select(x => x).ToList(); foreach (LocalArea localArea in localAreas) { foreach (EquipmentType equipmentType in equipmentTypes) { _context.CalculateSeniorityList(localArea.Id, equipmentType.Id); } } return new ObjectResult("Done Recalc."); } /// <summary> /// Searches Equipment /// </summary> /// <remarks>Used for the equipment search page.</remarks> /// <param name="localareasCSV">Local Areas (array of id numbers)</param> /// <param name="typesCSV">Equipment Types (array of id numbers)</param> /// <param name="equipmentAttachment">Equipment Attachments </param> /// <param name="owner"></param> /// <param name="status">Status</param> /// <param name="hired">Hired</param> /// <param name="notverifiedsincedate">Not Verified Since Date</param> /// <response code="200">OK</response> public virtual IActionResult EquipmentSearchGetAsync(string localareasCSV, string typesCSV, string equipmentAttachment, int? owner, string status, bool? hired, DateTime? notverifiedsincedate) { int?[] localareas = ParseIntArray(localareasCSV); int?[] types = ParseIntArray(typesCSV); var data = _context.Equipments .Include(x => x.LocalArea.ServiceArea.District.Region) .Include(x => x.DistrictEquipmentType) .Include(x => x.DumpTruck) .Include(x => x.Owner) .Include(x => x.EquipmentAttachments) .Include(x => x.Notes) .Include(x => x.Attachments) .Include(x => x.History) .Select(x => x); // Default search results must be limited to user int? districtId = _context.GetDistrictIdByUserId(GetCurrentUserId()).Single(); data = data.Where(x => x.LocalArea.ServiceArea.DistrictId.Equals(districtId)); if (localareas != null && localareas.Length > 0) { data = data.Where(x => localareas.Contains(x.LocalArea.Id)); } if (equipmentAttachment != null) { data = data.Where(x => x.EquipmentAttachments.Any(y => y.TypeName.ToLower().Contains(equipmentAttachment.ToLower()))); } if (owner != null) { data = data.Where(x => x.Owner.Id == owner); } if (status != null) { // TODO: Change to enumerated type data = data.Where(x => x.Status.ToLower() == status.ToLower()); } if (hired == true) { IQueryable<int?> hiredEquipmentQuery = _context.RentalAgreements .Where(agreement => agreement.Status == "Active") .Select(agreement => agreement.EquipmentId) .Distinct(); data = data.Where(e => hiredEquipmentQuery.Contains(e.Id)); } if (types != null && types.Length > 0) { data = data.Where(x => types.Contains(x.DistrictEquipmentType.Id)); } if (notverifiedsincedate != null) { data = data.Where(x => x.LastVerifiedDate >= notverifiedsincedate); } List<EquipmentViewModel> result = new List<EquipmentViewModel>(); foreach (var item in data) { EquipmentViewModel newItem = item.ToViewModel(); result.Add(newItem); } // second pass to do calculated fields. foreach (var equipmentViewModel in result) { CalculateViewModel(equipmentViewModel); } return new ObjectResult(result); } } }
using System; using System.Collections; using Org.BouncyCastle.Utilities.Collections; using Org.BouncyCastle.Utilities.Date; using Org.BouncyCastle.X509.Store; namespace Org.BouncyCastle.Pkix { /// <summary> /// Summary description for PkixParameters. /// </summary> public class PkixParameters // : ICertPathParameters { /** * This is the default PKIX validity model. Actually there are two variants * of this: The PKIX model and the modified PKIX model. The PKIX model * verifies that all involved certificates must have been valid at the * current time. The modified PKIX model verifies that all involved * certificates were valid at the signing time. Both are indirectly choosen * with the {@link PKIXParameters#setDate(java.util.Date)} method, so this * methods sets the Date when <em>all</em> certificates must have been * valid. */ public const int PkixValidityModel = 0; /** * This model uses the following validity model. Each certificate must have * been valid at the moment where is was used. That means the end * certificate must have been valid at the time the signature was done. The * CA certificate which signed the end certificate must have been valid, * when the end certificate was signed. The CA (or Root CA) certificate must * have been valid, when the CA certificate was signed and so on. So the * {@link PKIXParameters#setDate(java.util.Date)} method sets the time, when * the <em>end certificate</em> must have been valid. <p/> It is used e.g. * in the German signature law. */ public const int ChainValidityModel = 1; private ISet trustAnchors; private DateTimeObject date; private IList certPathCheckers; private bool revocationEnabled = true; private ISet initialPolicies; //private bool checkOnlyEECertificateCrl = false; private bool explicitPolicyRequired = false; private bool anyPolicyInhibited = false; private bool policyMappingInhibited = false; private bool policyQualifiersRejected = true; private IX509Selector certSelector; private IList stores; private IX509Selector selector; private bool additionalLocationsEnabled; private IList additionalStores; private ISet trustedACIssuers; private ISet necessaryACAttributes; private ISet prohibitedACAttributes; private ISet attrCertCheckers; private int validityModel = PkixValidityModel; private bool useDeltas = false; /** * Creates an instance of PKIXParameters with the specified Set of * most-trusted CAs. Each element of the set is a TrustAnchor.<br /> * <br /> * Note that the Set is copied to protect against subsequent modifications. * * @param trustAnchors * a Set of TrustAnchors * * @exception InvalidAlgorithmParameterException * if the specified Set is empty * <code>(trustAnchors.isEmpty() == true)</code> * @exception NullPointerException * if the specified Set is <code>null</code> * @exception ClassCastException * if any of the elements in the Set are not of type * <code>java.security.cert.TrustAnchor</code> */ public PkixParameters( ISet trustAnchors) { SetTrustAnchors(trustAnchors); this.initialPolicies = new HashSet(); this.certPathCheckers = new ArrayList(); this.stores = new ArrayList(); this.additionalStores = new ArrayList(); this.trustedACIssuers = new HashSet(); this.necessaryACAttributes = new HashSet(); this.prohibitedACAttributes = new HashSet(); this.attrCertCheckers = new HashSet(); } // // TODO implement for other keystores (see Java build)? // /** // * Creates an instance of <code>PKIXParameters</code> that // * populates the set of most-trusted CAs from the trusted // * certificate entries contained in the specified <code>KeyStore</code>. // * Only keystore entries that contain trusted <code>X509Certificates</code> // * are considered; all other certificate types are ignored. // * // * @param keystore a <code>KeyStore</code> from which the set of // * most-trusted CAs will be populated // * @throws KeyStoreException if the keystore has not been initialized // * @throws InvalidAlgorithmParameterException if the keystore does // * not contain at least one trusted certificate entry // * @throws NullPointerException if the keystore is <code>null</code> // */ // public PkixParameters( // Pkcs12Store keystore) //// throws KeyStoreException, InvalidAlgorithmParameterException // { // if (keystore == null) // throw new ArgumentNullException("keystore"); // ISet trustAnchors = new HashSet(); // foreach (string alias in keystore.Aliases) // { // if (keystore.IsCertificateEntry(alias)) // { // X509CertificateEntry x509Entry = keystore.GetCertificate(alias); // trustAnchors.Add(new TrustAnchor(x509Entry.Certificate, null)); // } // } // SetTrustAnchors(trustAnchors); // // this.initialPolicies = new HashSet(); // this.certPathCheckers = new ArrayList(); // this.stores = new ArrayList(); // this.additionalStores = new ArrayList(); // this.trustedACIssuers = new HashSet(); // this.necessaryACAttributes = new HashSet(); // this.prohibitedACAttributes = new HashSet(); // this.attrCertCheckers = new HashSet(); // } public virtual bool IsRevocationEnabled { get { return revocationEnabled; } set { revocationEnabled = value; } } public virtual bool IsExplicitPolicyRequired { get { return explicitPolicyRequired; } set { this.explicitPolicyRequired = value; } } public virtual bool IsAnyPolicyInhibited { get { return anyPolicyInhibited; } set { this.anyPolicyInhibited = value; } } public virtual bool IsPolicyMappingInhibited { get { return policyMappingInhibited; } set { this.policyMappingInhibited = value; } } public virtual bool IsPolicyQualifiersRejected { get { return policyQualifiersRejected; } set { this.policyQualifiersRejected = value; } } //public bool IsCheckOnlyEECertificateCrl //{ // get { return this.checkOnlyEECertificateCrl; } // set { this.checkOnlyEECertificateCrl = value; } //} public virtual DateTimeObject Date { get { return this.date; } set { this.date = value; } } // Returns a Set of the most-trusted CAs. public virtual ISet GetTrustAnchors() { return new HashSet(this.trustAnchors); } // Sets the set of most-trusted CAs. // Set is copied to protect against subsequent modifications. public virtual void SetTrustAnchors( ISet tas) { if (tas == null) throw new ArgumentNullException("value"); if (tas.IsEmpty) throw new ArgumentException("non-empty set required", "value"); // Explicit copy to enforce type-safety this.trustAnchors = new HashSet(); foreach (TrustAnchor ta in tas) { if (ta != null) { trustAnchors.Add(ta); } } } /** * Returns the required constraints on the target certificate. The * constraints are returned as an instance of CertSelector. If * <code>null</code>, no constraints are defined.<br /> * <br /> * Note that the CertSelector returned is cloned to protect against * subsequent modifications. * * @return a CertSelector specifying the constraints on the target * certificate (or <code>null</code>) * * @see #setTargetCertConstraints(CertSelector) */ public virtual X509CertStoreSelector GetTargetCertConstraints() { if (certSelector == null) { return null; } return (X509CertStoreSelector)certSelector.Clone(); } /** * Sets the required constraints on the target certificate. The constraints * are specified as an instance of CertSelector. If null, no constraints are * defined.<br /> * <br /> * Note that the CertSelector specified is cloned to protect against * subsequent modifications. * * @param selector * a CertSelector specifying the constraints on the target * certificate (or <code>null</code>) * * @see #getTargetCertConstraints() */ public virtual void SetTargetCertConstraints( IX509Selector selector) { if (selector == null) { certSelector = null; } else { certSelector = (IX509Selector)selector.Clone(); } } /** * Returns an immutable Set of initial policy identifiers (OID strings), * indicating that any one of these policies would be acceptable to the * certificate user for the purposes of certification path processing. The * default return value is an empty <code>Set</code>, which is * interpreted as meaning that any policy would be acceptable. * * @return an immutable <code>Set</code> of initial policy OIDs in String * format, or an empty <code>Set</code> (implying any policy is * acceptable). Never returns <code>null</code>. * * @see #setInitialPolicies(java.util.Set) */ public virtual ISet GetInitialPolicies() { ISet returnSet = initialPolicies; // TODO Can it really be null? if (initialPolicies == null) { returnSet = new HashSet(); } return new HashSet(returnSet); } /** * Sets the <code>Set</code> of initial policy identifiers (OID strings), * indicating that any one of these policies would be acceptable to the * certificate user for the purposes of certification path processing. By * default, any policy is acceptable (i.e. all policies), so a user that * wants to allow any policy as acceptable does not need to call this * method, or can call it with an empty <code>Set</code> (or * <code>null</code>).<br /> * <br /> * Note that the Set is copied to protect against subsequent modifications.<br /> * <br /> * * @param initialPolicies * a Set of initial policy OIDs in String format (or * <code>null</code>) * * @exception ClassCastException * if any of the elements in the set are not of type String * * @see #getInitialPolicies() */ public virtual void SetInitialPolicies( ISet initialPolicies) { this.initialPolicies = new HashSet(); if (initialPolicies != null) { foreach (string obj in initialPolicies) { if (obj != null) { this.initialPolicies.Add(obj); } } } } /** * Sets a <code>List</code> of additional certification path checkers. If * the specified List contains an object that is not a PKIXCertPathChecker, * it is ignored.<br /> * <br /> * Each <code>PKIXCertPathChecker</code> specified implements additional * checks on a certificate. Typically, these are checks to process and * verify private extensions contained in certificates. Each * <code>PKIXCertPathChecker</code> should be instantiated with any * initialization parameters needed to execute the check.<br /> * <br /> * This method allows sophisticated applications to extend a PKIX * <code>CertPathValidator</code> or <code>CertPathBuilder</code>. Each * of the specified PKIXCertPathCheckers will be called, in turn, by a PKIX * <code>CertPathValidator</code> or <code>CertPathBuilder</code> for * each certificate processed or validated.<br /> * <br /> * Regardless of whether these additional PKIXCertPathCheckers are set, a * PKIX <code>CertPathValidator</code> or <code>CertPathBuilder</code> * must perform all of the required PKIX checks on each certificate. The one * exception to this rule is if the RevocationEnabled flag is set to false * (see the {@link #setRevocationEnabled(boolean) setRevocationEnabled} * method).<br /> * <br /> * Note that the List supplied here is copied and each PKIXCertPathChecker * in the list is cloned to protect against subsequent modifications. * * @param checkers * a List of PKIXCertPathCheckers. May be null, in which case no * additional checkers will be used. * @exception ClassCastException * if any of the elements in the list are not of type * <code>java.security.cert.PKIXCertPathChecker</code> * @see #getCertPathCheckers() */ public virtual void SetCertPathCheckers(IList checkers) { certPathCheckers = new ArrayList(); if (checkers != null) { foreach (PkixCertPathChecker obj in checkers) { certPathCheckers.Add(obj.Clone()); } } } /** * Returns the List of certification path checkers. The returned List is * immutable, and each PKIXCertPathChecker in the List is cloned to protect * against subsequent modifications. * * @return an immutable List of PKIXCertPathCheckers (may be empty, but not * <code>null</code>) * * @see #setCertPathCheckers(java.util.List) */ public virtual IList GetCertPathCheckers() { IList checkers = new ArrayList(); foreach (PkixCertPathChecker obj in certPathCheckers) { checkers.Add(obj.Clone()); } return ArrayList.ReadOnly(checkers); } /** * Adds a <code>PKIXCertPathChecker</code> to the list of certification * path checkers. See the {@link #setCertPathCheckers setCertPathCheckers} * method for more details. * <p> * Note that the <code>PKIXCertPathChecker</code> is cloned to protect * against subsequent modifications.</p> * * @param checker a <code>PKIXCertPathChecker</code> to add to the list of * checks. If <code>null</code>, the checker is ignored (not added to list). */ public virtual void AddCertPathChecker( PkixCertPathChecker checker) { if (checker != null) { certPathCheckers.Add(checker.Clone()); } } public virtual object Clone() { // FIXME Check this whole method against the Java implementation! PkixParameters parameters = new PkixParameters(GetTrustAnchors()); parameters.SetParams(this); return parameters; // PkixParameters obj = new PkixParameters(new HashSet()); //// (PkixParameters) this.MemberwiseClone(); // obj.x509Stores = new ArrayList(x509Stores); // obj.certPathCheckers = new ArrayList(certPathCheckers); // // //Iterator iter = certPathCheckers.iterator(); // //obj.certPathCheckers = new ArrayList(); // //while (iter.hasNext()) // //{ // // obj.certPathCheckers.add(((PKIXCertPathChecker)iter.next()) // // .clone()); // //} // //if (initialPolicies != null) // //{ // // obj.initialPolicies = new HashSet(initialPolicies); // //} //// if (trustAnchors != null) //// { //// obj.trustAnchors = new HashSet(trustAnchors); //// } //// if (certSelector != null) //// { //// obj.certSelector = (X509CertStoreSelector) certSelector.Clone(); //// } // return obj; } /** * Method to support <code>Clone()</code> under J2ME. * <code>super.Clone()</code> does not exist and fields are not copied. * * @param params Parameters to set. If this are * <code>ExtendedPkixParameters</code> they are copied to. */ protected virtual void SetParams( PkixParameters parameters) { Date = parameters.Date; SetCertPathCheckers(parameters.GetCertPathCheckers()); IsAnyPolicyInhibited = parameters.IsAnyPolicyInhibited; IsExplicitPolicyRequired = parameters.IsExplicitPolicyRequired; IsPolicyMappingInhibited = parameters.IsPolicyMappingInhibited; IsRevocationEnabled = parameters.IsRevocationEnabled; SetInitialPolicies(parameters.GetInitialPolicies()); IsPolicyQualifiersRejected = parameters.IsPolicyQualifiersRejected; SetTargetCertConstraints(parameters.GetTargetCertConstraints()); SetTrustAnchors(parameters.GetTrustAnchors()); validityModel = parameters.validityModel; useDeltas = parameters.useDeltas; additionalLocationsEnabled = parameters.additionalLocationsEnabled; selector = parameters.selector == null ? null : (IX509Selector) parameters.selector.Clone(); stores = new ArrayList(parameters.stores); additionalStores = new ArrayList(parameters.additionalStores); trustedACIssuers = new HashSet(parameters.trustedACIssuers); prohibitedACAttributes = new HashSet(parameters.prohibitedACAttributes); necessaryACAttributes = new HashSet(parameters.necessaryACAttributes); attrCertCheckers = new HashSet(parameters.attrCertCheckers); } /** * Whether delta CRLs should be used for checking the revocation status. * Defaults to <code>false</code>. */ public virtual bool IsUseDeltasEnabled { get { return useDeltas; } set { useDeltas = value; } } /** * The validity model. * @see #CHAIN_VALIDITY_MODEL * @see #PKIX_VALIDITY_MODEL */ public virtual int ValidityModel { get { return validityModel; } set { validityModel = value; } } /** * Sets the Bouncy Castle Stores for finding CRLs, certificates, attribute * certificates or cross certificates. * <p> * The <code>IList</code> is cloned. * </p> * * @param stores A list of stores to use. * @see #getStores * @throws ClassCastException if an element of <code>stores</code> is not * a {@link Store}. */ public virtual void SetStores( IList stores) { if (stores == null) { this.stores = new ArrayList(); } else { foreach (object obj in stores) { if (!(obj is IX509Store)) { throw new InvalidCastException( "All elements of list must be of type " + typeof(IX509Store).FullName); } } this.stores = new ArrayList(stores); } } /** * Adds a Bouncy Castle {@link Store} to find CRLs, certificates, attribute * certificates or cross certificates. * <p> * This method should be used to add local stores, like collection based * X.509 stores, if available. Local stores should be considered first, * before trying to use additional (remote) locations, because they do not * need possible additional network traffic. * </p><p> * If <code>store</code> is <code>null</code> it is ignored. * </p> * * @param store The store to add. * @see #getStores */ public virtual void AddStore( IX509Store store) { if (store != null) { stores.Add(store); } } /** * Adds an additional Bouncy Castle {@link Store} to find CRLs, certificates, * attribute certificates or cross certificates. * <p> * You should not use this method. This method is used for adding additional * X.509 stores, which are used to add (remote) locations, e.g. LDAP, found * during X.509 object processing, e.g. in certificates or CRLs. This method * is used in PKIX certification path processing. * </p><p> * If <code>store</code> is <code>null</code> it is ignored. * </p> * * @param store The store to add. * @see #getStores() */ public virtual void AddAdditionalStore( IX509Store store) { if (store != null) { additionalStores.Add(store); } } /** * Returns an immutable <code>IList</code> of additional Bouncy Castle * <code>Store</code>s used for finding CRLs, certificates, attribute * certificates or cross certificates. * * @return an immutable <code>IList</code> of additional Bouncy Castle * <code>Store</code>s. Never <code>null</code>. * * @see #addAddionalStore(Store) */ public virtual IList GetAdditionalStores() { return ArrayList.ReadOnly(new ArrayList(additionalStores)); } /** * Returns an immutable <code>IList</code> of Bouncy Castle * <code>Store</code>s used for finding CRLs, certificates, attribute * certificates or cross certificates. * * @return an immutable <code>IList</code> of Bouncy Castle * <code>Store</code>s. Never <code>null</code>. * * @see #setStores(IList) */ public virtual IList GetStores() { return ArrayList.ReadOnly(new ArrayList(stores)); } /** * Returns if additional {@link X509Store}s for locations like LDAP found * in certificates or CRLs should be used. * * @return Returns <code>true</code> if additional stores are used. */ public virtual bool IsAdditionalLocationsEnabled { get { return additionalLocationsEnabled; } } /** * Sets if additional {@link X509Store}s for locations like LDAP found in * certificates or CRLs should be used. * * @param enabled <code>true</code> if additional stores are used. */ public virtual void SetAdditionalLocationsEnabled( bool enabled) { additionalLocationsEnabled = enabled; } /** * Returns the required constraints on the target certificate or attribute * certificate. The constraints are returned as an instance of * <code>IX509Selector</code>. If <code>null</code>, no constraints are * defined. * * <p> * The target certificate in a PKIX path may be a certificate or an * attribute certificate. * </p><p> * Note that the <code>IX509Selector</code> returned is cloned to protect * against subsequent modifications. * </p> * @return a <code>IX509Selector</code> specifying the constraints on the * target certificate or attribute certificate (or <code>null</code>) * @see #setTargetConstraints * @see X509CertStoreSelector * @see X509AttributeCertStoreSelector */ public virtual IX509Selector GetTargetConstraints() { if (selector != null) { return (IX509Selector) selector.Clone(); } else { return null; } } /** * Sets the required constraints on the target certificate or attribute * certificate. The constraints are specified as an instance of * <code>IX509Selector</code>. If <code>null</code>, no constraints are * defined. * <p> * The target certificate in a PKIX path may be a certificate or an * attribute certificate. * </p><p> * Note that the <code>IX509Selector</code> specified is cloned to protect * against subsequent modifications. * </p> * * @param selector a <code>IX509Selector</code> specifying the constraints on * the target certificate or attribute certificate (or * <code>null</code>) * @see #getTargetConstraints * @see X509CertStoreSelector * @see X509AttributeCertStoreSelector */ public virtual void SetTargetConstraints(IX509Selector selector) { if (selector != null) { this.selector = (IX509Selector) selector.Clone(); } else { this.selector = null; } } /** * Returns the trusted attribute certificate issuers. If attribute * certificates is verified the trusted AC issuers must be set. * <p> * The returned <code>ISet</code> consists of <code>TrustAnchor</code>s. * </p><p> * The returned <code>ISet</code> is immutable. Never <code>null</code> * </p> * * @return Returns an immutable set of the trusted AC issuers. */ public virtual ISet GetTrustedACIssuers() { return new HashSet(trustedACIssuers); } /** * Sets the trusted attribute certificate issuers. If attribute certificates * is verified the trusted AC issuers must be set. * <p> * The <code>trustedACIssuers</code> must be a <code>ISet</code> of * <code>TrustAnchor</code> * </p><p> * The given set is cloned. * </p> * * @param trustedACIssuers The trusted AC issuers to set. Is never * <code>null</code>. * @throws ClassCastException if an element of <code>stores</code> is not * a <code>TrustAnchor</code>. */ public virtual void SetTrustedACIssuers( ISet trustedACIssuers) { if (trustedACIssuers == null) { this.trustedACIssuers = new HashSet(); } else { foreach (object obj in trustedACIssuers) { if (!(obj is TrustAnchor)) { throw new InvalidCastException("All elements of set must be " + "of type " + typeof(TrustAnchor).Name + "."); } } this.trustedACIssuers = new HashSet(trustedACIssuers); } } /** * Returns the neccessary attributes which must be contained in an attribute * certificate. * <p> * The returned <code>ISet</code> is immutable and contains * <code>String</code>s with the OIDs. * </p> * * @return Returns the necessary AC attributes. */ public virtual ISet GetNecessaryACAttributes() { return new HashSet(necessaryACAttributes); } /** * Sets the neccessary which must be contained in an attribute certificate. * <p> * The <code>ISet</code> must contain <code>String</code>s with the * OIDs. * </p><p> * The set is cloned. * </p> * * @param necessaryACAttributes The necessary AC attributes to set. * @throws ClassCastException if an element of * <code>necessaryACAttributes</code> is not a * <code>String</code>. */ public virtual void SetNecessaryACAttributes( ISet necessaryACAttributes) { if (necessaryACAttributes == null) { this.necessaryACAttributes = new HashSet(); } else { foreach (object obj in necessaryACAttributes) { if (!(obj is string)) { throw new InvalidCastException("All elements of set must be " + "of type string."); } } this.necessaryACAttributes = new HashSet(necessaryACAttributes); } } /** * Returns the attribute certificates which are not allowed. * <p> * The returned <code>ISet</code> is immutable and contains * <code>String</code>s with the OIDs. * </p> * * @return Returns the prohibited AC attributes. Is never <code>null</code>. */ public virtual ISet GetProhibitedACAttributes() { return new HashSet(prohibitedACAttributes); } /** * Sets the attribute certificates which are not allowed. * <p> * The <code>ISet</code> must contain <code>String</code>s with the * OIDs. * </p><p> * The set is cloned. * </p> * * @param prohibitedACAttributes The prohibited AC attributes to set. * @throws ClassCastException if an element of * <code>prohibitedACAttributes</code> is not a * <code>String</code>. */ public virtual void SetProhibitedACAttributes( ISet prohibitedACAttributes) { if (prohibitedACAttributes == null) { this.prohibitedACAttributes = new HashSet(); } else { foreach (object obj in prohibitedACAttributes) { if (!(obj is String)) { throw new InvalidCastException("All elements of set must be " + "of type string."); } } this.prohibitedACAttributes = new HashSet(prohibitedACAttributes); } } /** * Returns the attribute certificate checker. The returned set contains * {@link PKIXAttrCertChecker}s and is immutable. * * @return Returns the attribute certificate checker. Is never * <code>null</code>. */ public virtual ISet GetAttrCertCheckers() { return new HashSet(attrCertCheckers); } /** * Sets the attribute certificate checkers. * <p> * All elements in the <code>ISet</code> must a {@link PKIXAttrCertChecker}. * </p> * <p> * The given set is cloned. * </p> * * @param attrCertCheckers The attribute certificate checkers to set. Is * never <code>null</code>. * @throws ClassCastException if an element of <code>attrCertCheckers</code> * is not a <code>PKIXAttrCertChecker</code>. */ public virtual void SetAttrCertCheckers( ISet attrCertCheckers) { if (attrCertCheckers == null) { this.attrCertCheckers = new HashSet(); } else { foreach (object obj in attrCertCheckers) { if (!(obj is PkixAttrCertChecker)) { throw new InvalidCastException("All elements of set must be " + "of type " + typeof(PkixAttrCertChecker).FullName + "."); } } this.attrCertCheckers = new HashSet(attrCertCheckers); } } } }
#region usings using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.Linq; using VVVV.PluginInterfaces.V1; using VVVV.PluginInterfaces.V2; using VVVV.Utils.VColor; using VVVV.Utils.VMath; using VVVV.Core.Logging; using mp.pddn; using VVVV.Utils.Reflection; using NGISpread = VVVV.PluginInterfaces.V2.NonGeneric.ISpread; using NGIDiffSpread = VVVV.PluginInterfaces.V2.NonGeneric.IDiffSpread; #endregion usings namespace mp.essentials.Nodes.Generic { #region PluginInfo [PluginInfo( Name = "Evaluate", Category = "Node", Help = "Simple AutoEvaluate", AutoEvaluate = true)] #endregion PluginInfo public class NodeEvaluateNode : IPluginEvaluate, IPartImportsSatisfiedNotification { [Import] public IPluginHost PluginHost; public INodeIn Pin; public void OnImportsSatisfied() { PluginHost.CreateNodeInput("Input", TSliceMode.Dynamic, TPinVisibility.True, out Pin); Pin.SetSubType2(null, new Guid[] { }, "Variant"); } //called when data for any output pin is requested public void Evaluate(int SpreadMax) { } } public abstract class PerformerNode<T> : IPluginEvaluate { [Input("Input", AutoValidate = false)] public ISpread<T> FInput; [Input("Default")] public ISpread<T> FDefault; [Input("Execute", IsBang = true)] public ISpread<bool> FEval; [Output("Output")] public ISpread<T> FOutput; private bool Initial = true; public void Evaluate(int SpreadMax) { FOutput.Stream.IsChanged = false; if (Initial) { FOutput.AssignFrom(FDefault); Initial = false; FOutput.Flush(); FOutput.Stream.IsChanged = true; } if (FEval[0]) { FInput.Sync(); FOutput.AssignFrom(FInput); FOutput.Flush(); FOutput.Stream.IsChanged = true; } } } [PluginInfo( Name = "Performer", Category = "Transform", Help = "Manually evaluate upstream nodes", AutoEvaluate = true)] public class TransformPerformerNode : PerformerNode<Matrix4x4> { } [PluginInfo( Name = "Performer", Category = "Value", Help = "Manually evaluate upstream nodes", AutoEvaluate = true)] public class ValuePerformerNode : PerformerNode<double> { } [PluginInfo( Name = "Performer", Category = "String", Help = "Manually evaluate upstream nodes", AutoEvaluate = true)] public class StringPerformerNode : PerformerNode<string> { } [PluginInfo( Name = "Performer", Category = "Node", Help = "Manually evaluate upstream nodes of any CLR type", AutoEvaluate = true)] public class NodePerformerNode : ConfigurableDynamicPinNode<string>, IPluginEvaluate { [Import] protected IPluginHost2 FPluginHost; [Import] protected IIOFactory FIOFactory; [Config("Type", DefaultString = "")] public IDiffSpread<string> FType; public GenericInput FRefType; [Input("Learnt Type Inheritence Level", Order = 2, Visibility = PinVisibility.Hidden, DefaultValue = 0)] public ISpread<int> FTypeInheritence; [Input("Learn Type", Order = 3, IsBang = true)] public ISpread<bool> FLearnType; [Input("Execute", IsBang = true, Order = 4)] public ISpread<bool> FEval; protected Type CType; protected int InitDescSet = 0; protected PinDictionary Pd; protected override void PreInitialize() { ConfigPinCopy = FType; FRefType = new GenericInput(FPluginHost, new InputAttribute("Reference Type") { Order = 1 }); Pd = new PinDictionary(FIOFactory); foreach (var pin in FPluginHost.GetPins()) { if (pin.Name != "Descriptive Name") continue; pin.SetSlice(0, ""); break; } } protected override bool IsConfigDefault() { return FType[0] == ""; } protected override void OnConfigPinChanged() { FType.Stream.IsChanged = false; foreach (var pin in FPluginHost.GetPins()) { if (pin.Name != "Descriptive Name") continue; pin.SetSlice(0, ""); break; } if (IsConfigDefault()) return; Pd.RemoveAllInput(); Pd.RemoveAllOutput(); CType = Type.GetType(FType[0]); if (CType == null) return; foreach (var pin in FPluginHost.GetPins()) { if (pin.Name != "Descriptive Name") continue; pin.SetSlice(0, CType.GetCSharpName()); break; } Pd.AddInput(CType, new InputAttribute("Input") { Order = 0, AutoValidate = false }); Pd.AddOutput(CType, new OutputAttribute("Output")); } //called when data for any output pin is requested public void Evaluate(int SpreadMax) { if (FLearnType[0]) { try { var types = FRefType[0].GetType().GetTypes().ToArray(); FType[0] = types[Math.Min(FTypeInheritence[0], types.Length - 1)].AssemblyQualifiedName; FType.Stream.IsChanged = true; } catch (Exception e) { } } if (IsConfigDefault()) return; if (InitDescSet < 5) { foreach (var pin in FPluginHost.GetPins()) { if (pin.Name != "Descriptive Name") continue; pin.SetSlice(0, CType?.GetCSharpName()); InitDescSet++; break; } } if (FEval[0]) { Pd.InputPins["Input"].Spread.Sync(); Pd.OutputPins["Output"].Spread.SliceCount = Pd.InputPins["Input"].Spread.SliceCount; for (int i = 0; i < Pd.InputPins["Input"].Spread.SliceCount; i++) { Pd.OutputPins["Output"].Spread[i] = Pd.InputPins["Input"].Spread[i]; } Pd.OutputPins["Output"].Spread.Flush(); } } } }
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information. using System; using System.Collections; using System.Collections.Generic; using System.Windows.Controls; using Microsoft.VisualStudio.TestTools.UnitTesting; using Prism.Regions; using Prism.Regions.Behaviors; using Prism.Wpf.Tests.Mocks; namespace Prism.Wpf.Tests.Regions.Behaviors { [TestClass] public class RegionManagerRegistrationBehaviorFixture { [TestMethod] public void ShouldRegisterRegionIfRegionManagerIsSet() { var control = new ItemsControl(); var regionManager = new MockRegionManager(); var accessor = new MockRegionManagerAccessor { GetRegionManager = d => regionManager }; var region = new MockPresentationRegion() {Name = "myRegionName"}; var behavior = new RegionManagerRegistrationBehavior() { RegionManagerAccessor = accessor, Region = region, HostControl = control }; behavior.Attach(); Assert.IsTrue(regionManager.MockRegionCollection.AddCalled); Assert.AreSame(region, regionManager.MockRegionCollection.AddArgument); } [TestMethod] public void DoesNotFailIfRegionManagerIsNotSet() { var control = new ItemsControl(); var accessor = new MockRegionManagerAccessor(); var behavior = new RegionManagerRegistrationBehavior() { RegionManagerAccessor = accessor, Region = new MockPresentationRegion() { Name = "myRegionWithoutManager" }, HostControl = control }; behavior.Attach(); } [TestMethod] public void RegionGetsAddedInRegionManagerWhenAddedIntoAScopeAndAccessingRegions() { var regionManager = new MockRegionManager(); var control = new MockFrameworkElement(); var regionScopeControl = new ContentControl(); var accessor = new MockRegionManagerAccessor { GetRegionManager = d => d == regionScopeControl ? regionManager : null }; var behavior = new RegionManagerRegistrationBehavior() { RegionManagerAccessor = accessor, Region = new MockPresentationRegion() { Name = "myRegionName" }, HostControl = control }; behavior.Attach(); Assert.IsFalse(regionManager.MockRegionCollection.AddCalled); regionScopeControl.Content = control; accessor.UpdateRegions(); Assert.IsTrue(regionManager.MockRegionCollection.AddCalled); } [TestMethod] public void RegionDoesNotGetAddedTwiceWhenUpdatingRegions() { var regionManager = new MockRegionManager(); var control = new MockFrameworkElement(); var regionScopeControl = new ContentControl(); var accessor = new MockRegionManagerAccessor { GetRegionManager = d => d == regionScopeControl ? regionManager : null }; var behavior = new RegionManagerRegistrationBehavior() { RegionManagerAccessor = accessor, Region = new MockPresentationRegion() { Name = "myRegionName" }, HostControl = control }; behavior.Attach(); Assert.IsFalse(regionManager.MockRegionCollection.AddCalled); regionScopeControl.Content = control; accessor.UpdateRegions(); Assert.IsTrue(regionManager.MockRegionCollection.AddCalled); regionManager.MockRegionCollection.AddCalled = false; accessor.UpdateRegions(); Assert.IsFalse(regionManager.MockRegionCollection.AddCalled); } [TestMethod] public void RegionGetsRemovedFromRegionManagerWhenRemovedFromScope() { var regionManager = new MockRegionManager(); var control = new MockFrameworkElement(); var regionScopeControl = new ContentControl(); var accessor = new MockRegionManagerAccessor { GetRegionManager = d => d == regionScopeControl ? regionManager : null }; var region = new MockPresentationRegion() {Name = "myRegionName"}; var behavior = new RegionManagerRegistrationBehavior() { RegionManagerAccessor = accessor, Region = region, HostControl = control }; behavior.Attach(); regionScopeControl.Content = control; accessor.UpdateRegions(); Assert.IsTrue(regionManager.MockRegionCollection.AddCalled); Assert.AreSame(region, regionManager.MockRegionCollection.AddArgument); regionScopeControl.Content = null; accessor.UpdateRegions(); Assert.IsTrue(regionManager.MockRegionCollection.RemoveCalled); } [TestMethod] public void CanAttachBeforeSettingName() { var control = new ItemsControl(); var regionManager = new MockRegionManager(); var accessor = new MockRegionManagerAccessor { GetRegionManager = d => regionManager }; var region = new MockPresentationRegion() { Name = null }; var behavior = new RegionManagerRegistrationBehavior() { RegionManagerAccessor = accessor, Region = region, HostControl = control }; behavior.Attach(); Assert.IsFalse(regionManager.MockRegionCollection.AddCalled); region.Name = "myRegionName"; Assert.IsTrue(regionManager.MockRegionCollection.AddCalled); Assert.AreSame(region, regionManager.MockRegionCollection.AddArgument); } [TestMethod] [ExpectedException(typeof(InvalidOperationException))] public void HostControlSetAfterAttachThrows() { var behavior = new RegionManagerRegistrationBehavior(); var hostControl1 = new MockDependencyObject(); var hostControl2 = new MockDependencyObject(); behavior.HostControl = hostControl1; behavior.Attach(); behavior.HostControl = hostControl2; } [TestMethod] public void BehaviorDoesNotPreventRegionManagerFromBeingGarbageCollected() { var control = new MockFrameworkElement(); var regionManager = new MockRegionManager(); var regionManagerWeakReference = new WeakReference(regionManager); var accessor = new MockRegionManagerAccessor { GetRegionName = d => "myRegionName", GetRegionManager = d => regionManager }; var behavior = new RegionManagerRegistrationBehavior() { RegionManagerAccessor = accessor, Region = new MockPresentationRegion(), HostControl = control }; behavior.Attach(); Assert.IsTrue(regionManagerWeakReference.IsAlive); GC.KeepAlive(regionManager); regionManager = null; GC.Collect(); Assert.IsFalse(regionManagerWeakReference.IsAlive); } internal class MockRegionManager : IRegionManager { public MockRegionCollection MockRegionCollection = new MockRegionCollection(); #region IRegionManager Members public IRegionCollection Regions { get { return this.MockRegionCollection; } } IRegionManager IRegionManager.CreateRegionManager() { throw new System.NotImplementedException(); } #endregion public bool Navigate(Uri source) { throw new NotImplementedException(); } } } internal class MockRegionCollection : IRegionCollection { public bool RemoveCalled; public bool AddCalled; public IRegion AddArgument; IEnumerator<IRegion> IEnumerable<IRegion>.GetEnumerator() { throw new System.NotImplementedException(); } IEnumerator IEnumerable.GetEnumerator() { throw new System.NotImplementedException(); } public IRegion this[string regionName] { get { throw new System.NotImplementedException(); } } public void Add(IRegion region) { AddCalled = true; AddArgument = region; } public bool Remove(string regionName) { RemoveCalled = true; return true; } public bool ContainsRegionWithName(string regionName) { throw new System.NotImplementedException(); } public event System.Collections.Specialized.NotifyCollectionChangedEventHandler CollectionChanged; } }
// // AddinTreeWidget.cs // // Author: // Lluis Sanchez Gual // // Copyright (C) 2007 Novell, Inc (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Collections; using Gtk; using Gdk; using Mono.Addins; using Mono.Addins.Setup; using Mono.Unix; using System.Collections.Generic; using System.Text; using System.IO; namespace Mono.Addins.Gui { public class AddinTreeWidget { protected Gtk.TreeView treeView; protected Gtk.TreeStore treeStore; bool allowSelection; ArrayList selected = new ArrayList (); Hashtable addinData = new Hashtable (); TreeViewColumn versionColumn; string filter; Dictionary<string,Gdk.Pixbuf> cachedIcons = new Dictionary<string, Gdk.Pixbuf> (); bool disposed; Gdk.Pixbuf iconInstalled; Gdk.Pixbuf updateOverlay; Gdk.Pixbuf installedOverlay; public event EventHandler SelectionChanged; const int ColAddin = 0; const int ColData = 1; const int ColName = 2; const int ColVersion = 3; const int ColAllowSelection = 4; const int ColSelected = 5; const int ColImage = 6; const int ColShowImage = 7; public AddinTreeWidget (Gtk.TreeView treeView) { iconInstalled = Gdk.Pixbuf.LoadFromResource ("plugin-32.png"); updateOverlay = Gdk.Pixbuf.LoadFromResource ("software-update-available-overlay.png"); installedOverlay = Gdk.Pixbuf.LoadFromResource ("installed-overlay.png"); this.treeView = treeView; ArrayList list = new ArrayList (); AddStoreTypes (list); Type[] types = (Type[]) list.ToArray (typeof(Type)); treeStore = new Gtk.TreeStore (types); treeView.Model = treeStore; CreateColumns (); ShowCategories = true; treeView.Destroyed += HandleTreeViewDestroyed; } void HandleTreeViewDestroyed (object sender, EventArgs e) { disposed = true; foreach (var px in cachedIcons.Values) if (px != null) px.Dispose (); } internal void SetFilter (string text) { this.filter = text; } internal void ShowEmptyMessage () { treeStore.AppendValues (null, null, Catalog.GetString ("No add-ins found"), "", false, false, null, false); } protected virtual void AddStoreTypes (ArrayList list) { list.Add (typeof(object)); list.Add (typeof(object)); list.Add (typeof(string)); list.Add (typeof(string)); list.Add (typeof(bool)); list.Add (typeof(bool)); list.Add (typeof (Pixbuf)); list.Add (typeof(bool)); } protected virtual void CreateColumns () { TreeViewColumn col = new TreeViewColumn (); col.Title = Catalog.GetString ("Add-in"); CellRendererToggle crtog = new CellRendererToggle (); crtog.Activatable = true; crtog.Toggled += new ToggledHandler (OnAddinToggled); col.PackStart (crtog, false); CellRendererPixbuf pr = new CellRendererPixbuf (); col.PackStart (pr, false); col.AddAttribute (pr, "pixbuf", ColImage); col.AddAttribute (pr, "visible", ColShowImage); CellRendererText crt = new CellRendererText (); crt.Ellipsize = Pango.EllipsizeMode.End; col.PackStart (crt, true); col.AddAttribute (crt, "markup", ColName); col.AddAttribute (crtog, "visible", ColAllowSelection); col.AddAttribute (crtog, "active", ColSelected); col.Expand = true; treeView.AppendColumn (col); col = new TreeViewColumn (); col.Title = Catalog.GetString ("Version"); col.PackStart (crt, true); col.AddAttribute (crt, "markup", ColVersion); versionColumn = col; treeView.AppendColumn (col); } public bool AllowSelection { get { return allowSelection; } set { allowSelection = value; } } public bool VersionVisible { get { return versionColumn.Visible; } set { versionColumn.Visible = value; treeView.HeadersVisible = value; } } public bool ShowCategories { get; set; } void OnAddinToggled (object o, ToggledArgs args) { TreeIter it; if (treeStore.GetIter (out it, new TreePath (args.Path))) { bool sel = !(bool) treeStore.GetValue (it, 5); treeStore.SetValue (it, 5, sel); AddinHeader info = (AddinHeader) treeStore.GetValue (it, 0); if (sel) selected.Add (info); else selected.Remove (info); OnSelectionChanged (EventArgs.Empty); } } protected virtual void OnSelectionChanged (EventArgs e) { if (SelectionChanged != null) SelectionChanged (this, e); } public void Clear () { addinData.Clear (); selected.Clear (); treeStore.Clear (); } public TreeIter AddAddin (AddinHeader info, object dataItem, bool enabled) { return AddAddin (info, dataItem, enabled, true); } public TreeIter AddAddin (AddinHeader info, object dataItem, bool enabled, bool userDir) { return AddAddin (info, dataItem, enabled ? AddinStatus.Installed : AddinStatus.Disabled | AddinStatus.Installed); } public TreeIter AddAddin (AddinHeader info, object dataItem, AddinStatus status) { addinData [info] = dataItem; TreeIter iter; if (ShowCategories) { TreeIter piter = TreeIter.Zero; if (info.Category == "") { string otherCat = Catalog.GetString ("Other"); piter = FindCategory (otherCat); } else { piter = FindCategory (info.Category); } iter = treeStore.AppendNode (piter); } else { iter = treeStore.AppendNode (); } UpdateRow (iter, info, dataItem, status); return iter; } protected virtual void UpdateRow (TreeIter iter, AddinHeader info, object dataItem, AddinStatus status) { bool sel = selected.Contains (info); treeStore.SetValue (iter, ColAddin, info); treeStore.SetValue (iter, ColData, dataItem); string name = EscapeWithFilterMarker (info.Name); if (!string.IsNullOrEmpty (info.Description)) { string desc = info.Description; int i = desc.IndexOf ('\n'); if (i != -1) desc = desc.Substring (0, i); name += "\n<small><span foreground=\"darkgrey\">" + EscapeWithFilterMarker (desc) + "</span></small>"; } if (status != AddinStatus.Disabled) { treeStore.SetValue (iter, ColName, name); treeStore.SetValue (iter, ColVersion, info.Version); treeStore.SetValue (iter, ColAllowSelection, allowSelection); } else { treeStore.SetValue (iter, ColName, "<span foreground=\"grey\">" + name + "</span>"); treeStore.SetValue (iter, ColVersion, "<span foreground=\"grey\">" + info.Version + "</span>"); treeStore.SetValue (iter, ColAllowSelection, false); } treeStore.SetValue (iter, ColShowImage, true); treeStore.SetValue (iter, ColSelected, sel); SetRowIcon (iter, info, dataItem, status); } void SetRowIcon (TreeIter it, AddinHeader info, object dataItem, AddinStatus status) { string customIcom = info.Properties.GetPropertyValue ("Icon32"); string iconId = info.Id + " " + info.Version + " " + customIcom; Gdk.Pixbuf customPix; if (customIcom.Length == 0) { customPix = null; iconId = "__"; } else if (!cachedIcons.TryGetValue (iconId, out customPix)) { if (dataItem is Addin) { string file = Path.Combine (((Addin)dataItem).Description.BasePath, customIcom); if (File.Exists (file)) { try { customPix = new Gdk.Pixbuf (file); } catch (Exception ex) { Console.WriteLine (ex); } } cachedIcons [iconId] = customPix; } else if (dataItem is AddinRepositoryEntry) { AddinRepositoryEntry arep = (AddinRepositoryEntry) dataItem; string tmpId = iconId; arep.BeginDownloadSupportFile (customIcom, delegate (IAsyncResult res) { Gtk.Application.Invoke (delegate { LoadRemoteIcon (it, tmpId, arep, res, info, dataItem, status); }); }, null); iconId = "__"; } } StoreIcon (it, iconId, customPix, status); } Gdk.Pixbuf GetCachedIcon (string id, string effect, Func<Gdk.Pixbuf> pixbufGenerator) { Gdk.Pixbuf pix; if (!cachedIcons.TryGetValue (id + "_" + effect, out pix)) cachedIcons [id + "_" + effect] = pix = pixbufGenerator (); return pix; } internal bool ShowInstalledMarkers = false; void StoreIcon (TreeIter it, string iconId, Gdk.Pixbuf customPix, AddinStatus status) { if (customPix == null) customPix = iconInstalled; if ((status & AddinStatus.Installed) == 0) { treeStore.SetValue (it, ColImage, customPix); return; } else if (ShowInstalledMarkers && (status & AddinStatus.HasUpdate) == 0) { customPix = GetCachedIcon (iconId, "InstalledOverlay", delegate { return Services.AddIconOverlay (customPix, installedOverlay); }); iconId = iconId + "_Installed"; } if ((status & AddinStatus.Disabled) != 0) { customPix = GetCachedIcon (iconId, "Desaturate", delegate { return Services.DesaturateIcon (customPix); }); iconId = iconId + "_Desaturate"; } if ((status & AddinStatus.HasUpdate) != 0) customPix = GetCachedIcon (iconId, "UpdateOverlay", delegate { return Services.AddIconOverlay (customPix, updateOverlay); }); treeStore.SetValue (it, ColImage, customPix); } void LoadRemoteIcon (TreeIter it, string iconId, AddinRepositoryEntry arep, IAsyncResult res, AddinHeader info, object dataItem, AddinStatus status) { if (!disposed && treeStore.IterIsValid (it)) { Gdk.Pixbuf customPix = null; try { Gdk.PixbufLoader loader = new Gdk.PixbufLoader (arep.EndDownloadSupportFile (res)); customPix = loader.Pixbuf; } catch (Exception ex) { Console.WriteLine (ex); } cachedIcons [iconId] = customPix; StoreIcon (it, iconId, customPix, status); } } string EscapeWithFilterMarker (string txt) { if (string.IsNullOrEmpty (filter)) return GLib.Markup.EscapeText (txt); StringBuilder sb = new StringBuilder (); int last = 0; int i = txt.IndexOf (filter, StringComparison.CurrentCultureIgnoreCase); while (i != -1) { sb.Append (GLib.Markup.EscapeText (txt.Substring (last, i - last))); sb.Append ("<span color='blue'>").Append (txt.Substring (i, filter.Length)).Append ("</span>"); last = i + filter.Length; i = txt.IndexOf (filter, last, StringComparison.CurrentCultureIgnoreCase); } if (last < txt.Length) sb.Append (GLib.Markup.EscapeText (txt.Substring (last, txt.Length - last))); return sb.ToString (); } public object GetAddinData (AddinHeader info) { return addinData [info]; } public AddinHeader[] GetSelectedAddins () { return (AddinHeader[]) selected.ToArray (typeof(AddinHeader)); } TreeIter FindCategory (string namePath) { TreeIter iter = TreeIter.Zero; string[] paths = namePath.Split ('/'); foreach (string name in paths) { TreeIter child; if (!FindCategory (iter, name, out child)) { if (iter.Equals (TreeIter.Zero)) iter = treeStore.AppendValues (null, null, name, "", false, false, null, false); else iter = treeStore.AppendValues (iter, null, null, name, "", false, false, null, false); } else iter = child; } return iter; } bool FindCategory (TreeIter piter, string name, out TreeIter child) { if (piter.Equals (TreeIter.Zero)) { if (!treeStore.GetIterFirst (out child)) return false; } else if (!treeStore.IterChildren (out child, piter)) return false; do { if (((string) treeStore.GetValue (child, ColName)) == name) { return true; } } while (treeStore.IterNext (ref child)); return false; } public AddinHeader ActiveAddin { get { AddinHeader[] sel = ActiveAddins; if (sel.Length > 0) return sel[0]; else return null; } } public AddinHeader[] ActiveAddins { get { List<AddinHeader> list = new List<AddinHeader> (); foreach (TreePath p in treeView.Selection.GetSelectedRows ()) { TreeIter iter; treeStore.GetIter (out iter, p); AddinHeader ah = (AddinHeader) treeStore.GetValue (iter, 0); if (ah != null) list.Add (ah); } return list.ToArray (); } } public object ActiveAddinData { get { AddinHeader ai = ActiveAddin; return ai != null ? GetAddinData (ai) : null; } } public object[] ActiveAddinsData { get { List<object> res = new List<object> (); foreach (AddinHeader ai in ActiveAddins) { res.Add (GetAddinData (ai)); } return res.ToArray (); } } public object[] AddinsData { get { object[] data = new object [addinData.Count]; addinData.Values.CopyTo (data, 0); return data; } } public object SaveStatus () { TreeIter iter; ArrayList list = new ArrayList (); // Save the current selection list.Add (treeView.Selection.GetSelectedRows ()); if (!treeStore.GetIterFirst (out iter)) return null; // Save the expand state do { SaveStatus (list, iter); } while (treeStore.IterNext (ref iter)); return list; } void SaveStatus (ArrayList list, TreeIter iter) { Gtk.TreePath path = treeStore.GetPath (iter); if (treeView.GetRowExpanded (path)) list.Add (path); if (treeStore.IterChildren (out iter, iter)) { do { SaveStatus (list, iter); } while (treeStore.IterNext (ref iter)); } } public void RestoreStatus (object ob) { if (ob == null) return; // The first element is the selection ArrayList list = (ArrayList) ob; TreePath[] selpaths = (TreePath[]) list [0]; list.RemoveAt (0); foreach (TreePath path in list) treeView.ExpandRow (path, false); foreach (TreePath p in selpaths) treeView.Selection.SelectPath (p); } public void SelectAll () { TreeIter iter; if (!treeStore.GetIterFirst (out iter)) return; do { SelectAll (iter); } while (treeStore.IterNext (ref iter)); OnSelectionChanged (EventArgs.Empty); } void SelectAll (TreeIter iter) { AddinHeader info = (AddinHeader) treeStore.GetValue (iter, ColAddin); if (info != null) { treeStore.SetValue (iter, ColSelected, true); if (!selected.Contains (info)) selected.Add (info); treeView.ExpandToPath (treeStore.GetPath (iter)); } else { if (treeStore.IterChildren (out iter, iter)) { do { SelectAll (iter); } while (treeStore.IterNext (ref iter)); } } } public void UnselectAll () { TreeIter iter; if (!treeStore.GetIterFirst (out iter)) return; do { UnselectAll (iter); } while (treeStore.IterNext (ref iter)); OnSelectionChanged (EventArgs.Empty); } void UnselectAll (TreeIter iter) { AddinHeader info = (AddinHeader) treeStore.GetValue (iter, ColAddin); if (info != null) { treeStore.SetValue (iter, ColSelected, false); selected.Remove (info); } else { if (treeStore.IterChildren (out iter, iter)) { do { UnselectAll (iter); } while (treeStore.IterNext (ref iter)); } } } } [Flags] public enum AddinStatus { NotInstalled = 0, Installed = 1, Disabled = 2, HasUpdate = 4 } }
// 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 System.Runtime; using System.Runtime.Diagnostics; using System.ServiceModel; using System.ServiceModel.Diagnostics; namespace System.ServiceModel.Channels { // code that pools items and closes/aborts them as necessary. // shared by IConnection and IChannel users public abstract class CommunicationPool<TKey, TItem> where TKey : class where TItem : class { private Dictionary<TKey, EndpointConnectionPool> _endpointPools; private int _maxCount; private int _openCount; // need to make sure we prune over a certain number of endpoint pools private int _pruneAccrual; private const int pruneThreshold = 30; protected CommunicationPool(int maxCount) { _maxCount = maxCount; _endpointPools = new Dictionary<TKey, EndpointConnectionPool>(); _openCount = 1; } public int MaxIdleConnectionPoolCount { get { return _maxCount; } } protected object ThisLock { get { return this; } } protected abstract void AbortItem(TItem item); protected abstract void CloseItem(TItem item, TimeSpan timeout); protected abstract void CloseItemAsync(TItem item, TimeSpan timeout); protected abstract TKey GetPoolKey(EndpointAddress address, Uri via); protected virtual EndpointConnectionPool CreateEndpointConnectionPool(TKey key) { return new EndpointConnectionPool(this, key); } public bool Close(TimeSpan timeout) { lock (ThisLock) { if (_openCount <= 0) { return true; } _openCount--; if (_openCount == 0) { this.OnClose(timeout); return true; } return false; } } private List<TItem> PruneIfNecessary() { List<TItem> itemsToClose = null; _pruneAccrual++; if (_pruneAccrual > pruneThreshold) { _pruneAccrual = 0; itemsToClose = new List<TItem>(); // first prune the connection pool contents foreach (EndpointConnectionPool pool in _endpointPools.Values) { pool.Prune(itemsToClose); } // figure out which connection pools are now empty List<TKey> endpointKeysToRemove = null; foreach (KeyValuePair<TKey, EndpointConnectionPool> poolEntry in _endpointPools) { if (poolEntry.Value.CloseIfEmpty()) { if (endpointKeysToRemove == null) { endpointKeysToRemove = new List<TKey>(); } endpointKeysToRemove.Add(poolEntry.Key); } } // and then prune the connection pools themselves if (endpointKeysToRemove != null) { for (int i = 0; i < endpointKeysToRemove.Count; i++) { _endpointPools.Remove(endpointKeysToRemove[i]); } } } return itemsToClose; } private EndpointConnectionPool GetEndpointPool(TKey key, TimeSpan timeout) { EndpointConnectionPool result = null; List<TItem> itemsToClose = null; lock (ThisLock) { if (!_endpointPools.TryGetValue(key, out result)) { itemsToClose = PruneIfNecessary(); result = CreateEndpointConnectionPool(key); _endpointPools.Add(key, result); } } Contract.Assert(result != null, "EndpointPool must be non-null at this point"); if (itemsToClose != null && itemsToClose.Count > 0) { // allocate half the remaining timeout for our graceful shutdowns TimeoutHelper timeoutHelper = new TimeoutHelper(TimeoutHelper.Divide(timeout, 2)); for (int i = 0; i < itemsToClose.Count; i++) { result.CloseIdleConnection(itemsToClose[i], timeoutHelper.RemainingTime()); } } return result; } public bool TryOpen() { lock (ThisLock) { if (_openCount <= 0) { // can't reopen connection pools since the registry purges them on close return false; } else { _openCount++; return true; } } } protected virtual void OnClosed() { } private void OnClose(TimeSpan timeout) { TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); foreach (EndpointConnectionPool pool in _endpointPools.Values) { try { pool.Close(timeoutHelper.RemainingTime()); } catch (CommunicationException) { } catch (TimeoutException exception) { if (WcfEventSource.Instance.CloseTimeoutIsEnabled()) { WcfEventSource.Instance.CloseTimeout(exception.Message); } } } _endpointPools.Clear(); } public void AddConnection(TKey key, TItem connection, TimeSpan timeout) { TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); EndpointConnectionPool endpointPool = GetEndpointPool(key, timeoutHelper.RemainingTime()); endpointPool.AddConnection(connection, timeoutHelper.RemainingTime()); } public TItem TakeConnection(EndpointAddress address, Uri via, TimeSpan timeout, out TKey key) { TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); key = this.GetPoolKey(address, via); EndpointConnectionPool endpointPool = GetEndpointPool(key, timeoutHelper.RemainingTime()); return endpointPool.TakeConnection(timeoutHelper.RemainingTime()); } public void ReturnConnection(TKey key, TItem connection, bool connectionIsStillGood, TimeSpan timeout) { TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); EndpointConnectionPool endpointPool = GetEndpointPool(key, timeoutHelper.RemainingTime()); endpointPool.ReturnConnection(connection, connectionIsStillGood, timeoutHelper.RemainingTime()); } // base class for our collection of Idle connections protected abstract class IdleConnectionPool { public abstract int Count { get; } public abstract bool Add(TItem item); public abstract bool Return(TItem item); public abstract TItem Take(out bool closeItem); } protected class EndpointConnectionPool { private TKey _key; private List<TItem> _busyConnections; private bool _closed; private IdleConnectionPool _idleConnections; private CommunicationPool<TKey, TItem> _parent; public EndpointConnectionPool(CommunicationPool<TKey, TItem> parent, TKey key) { _key = key; _parent = parent; _busyConnections = new List<TItem>(); } protected TKey Key { get { return _key; } } private IdleConnectionPool IdleConnections { get { if (_idleConnections == null) { _idleConnections = GetIdleConnectionPool(); } return _idleConnections; } } protected CommunicationPool<TKey, TItem> Parent { get { return _parent; } } protected object ThisLock { get { return this; } } // close down the pool if empty public bool CloseIfEmpty() { lock (ThisLock) { if (!_closed) { if (_busyConnections.Count > 0) { return false; } if (_idleConnections != null && _idleConnections.Count > 0) { return false; } _closed = true; } } return true; } protected virtual void AbortItem(TItem item) { _parent.AbortItem(item); } protected virtual void CloseItem(TItem item, TimeSpan timeout) { _parent.CloseItem(item, timeout); } protected virtual void CloseItemAsync(TItem item, TimeSpan timeout) { _parent.CloseItemAsync(item, timeout); } public void Abort() { if (_closed) { return; } List<TItem> idleItemsToClose = null; lock (ThisLock) { if (_closed) return; _closed = true; idleItemsToClose = SnapshotIdleConnections(); } AbortConnections(idleItemsToClose); } public void Close(TimeSpan timeout) { List<TItem> itemsToClose = null; lock (ThisLock) { if (_closed) return; _closed = true; itemsToClose = SnapshotIdleConnections(); } try { TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); for (int i = 0; i < itemsToClose.Count; i++) { this.CloseItem(itemsToClose[i], timeoutHelper.RemainingTime()); } itemsToClose.Clear(); } finally { AbortConnections(itemsToClose); } } private void AbortConnections(List<TItem> idleItemsToClose) { for (int i = 0; i < idleItemsToClose.Count; i++) { this.AbortItem(idleItemsToClose[i]); } for (int i = 0; i < _busyConnections.Count; i++) { this.AbortItem(_busyConnections[i]); } _busyConnections.Clear(); } // must call under lock (ThisLock) since we are calling IdleConnections.Take() private List<TItem> SnapshotIdleConnections() { List<TItem> itemsToClose = new List<TItem>(); bool dummy; for (;;) { TItem item = IdleConnections.Take(out dummy); if (item == null) break; itemsToClose.Add(item); } return itemsToClose; } public void AddConnection(TItem connection, TimeSpan timeout) { bool closeConnection = false; lock (ThisLock) { if (!_closed) { if (!IdleConnections.Add(connection)) { closeConnection = true; } } else { closeConnection = true; } } if (closeConnection) { CloseIdleConnection(connection, timeout); } } protected virtual IdleConnectionPool GetIdleConnectionPool() { return new PoolIdleConnectionPool(_parent.MaxIdleConnectionPoolCount); } public virtual void Prune(List<TItem> itemsToClose) { } public TItem TakeConnection(TimeSpan timeout) { TItem item = null; List<TItem> itemsToClose = null; lock (ThisLock) { if (_closed) return null; bool closeItem; while (true) { item = IdleConnections.Take(out closeItem); if (item == null) { break; } if (!closeItem) { _busyConnections.Add(item); break; } if (itemsToClose == null) { itemsToClose = new List<TItem>(); } itemsToClose.Add(item); } } // cleanup any stale items accrued from IdleConnections if (itemsToClose != null) { // and only allocate half the timeout passed in for our graceful shutdowns TimeoutHelper timeoutHelper = new TimeoutHelper(TimeoutHelper.Divide(timeout, 2)); for (int i = 0; i < itemsToClose.Count; i++) { CloseIdleConnection(itemsToClose[i], timeoutHelper.RemainingTime()); } } if (WcfEventSource.Instance.ConnectionPoolMissIsEnabled()) { if (item == null && _busyConnections != null) { WcfEventSource.Instance.ConnectionPoolMiss(_key != null ? _key.ToString() : string.Empty, _busyConnections.Count); } } return item; } public void ReturnConnection(TItem connection, bool connectionIsStillGood, TimeSpan timeout) { bool closeConnection = false; bool abortConnection = false; lock (ThisLock) { if (!_closed) { if (_busyConnections.Remove(connection) && connectionIsStillGood) { if (!IdleConnections.Return(connection)) { closeConnection = true; } } else { abortConnection = true; } } else { abortConnection = true; } } if (closeConnection) { CloseIdleConnection(connection, timeout); } else if (abortConnection) { this.AbortItem(connection); OnConnectionAborted(); } } public void CloseIdleConnection(TItem connection, TimeSpan timeout) { bool throwing = true; try { this.CloseItemAsync(connection, timeout); throwing = false; } catch (Exception e) { if (Fx.IsFatal(e)) { throw; } } finally { if (throwing) { this.AbortItem(connection); } } } protected virtual void OnConnectionAborted() { } protected class PoolIdleConnectionPool : IdleConnectionPool { private Pool<TItem> _idleConnections; private int _maxCount; public PoolIdleConnectionPool(int maxCount) { _idleConnections = new Pool<TItem>(maxCount); _maxCount = maxCount; } public override int Count { get { return _idleConnections.Count; } } public override bool Add(TItem connection) { return ReturnToPool(connection); } public override bool Return(TItem connection) { return ReturnToPool(connection); } private bool ReturnToPool(TItem connection) { bool result = _idleConnections.Return(connection); if (!result) { if (WcfEventSource.Instance.MaxOutboundConnectionsPerEndpointExceededIsEnabled()) { WcfEventSource.Instance.MaxOutboundConnectionsPerEndpointExceeded(SR.Format(SR.TraceCodeConnectionPoolMaxOutboundConnectionsPerEndpointQuotaReached, _maxCount)); } } else if (WcfEventSource.Instance.OutboundConnectionsPerEndpointRatioIsEnabled()) { WcfEventSource.Instance.OutboundConnectionsPerEndpointRatio(_idleConnections.Count, _maxCount); } return result; } public override TItem Take(out bool closeItem) { closeItem = false; TItem ret = _idleConnections.Take(); if (WcfEventSource.Instance.OutboundConnectionsPerEndpointRatioIsEnabled()) { WcfEventSource.Instance.OutboundConnectionsPerEndpointRatio(_idleConnections.Count, _maxCount); } return ret; } } } } // all our connection pools support Idling out of connections and lease timeout // (though Named Pipes doesn't leverage the lease timeout) public abstract class ConnectionPool : IdlingCommunicationPool<string, IConnection> { private int _connectionBufferSize; private TimeSpan _maxOutputDelay; private string _name; protected ConnectionPool(IConnectionOrientedTransportChannelFactorySettings settings, TimeSpan leaseTimeout) : base(settings.MaxOutboundConnectionsPerEndpoint, settings.IdleTimeout, leaseTimeout) { _connectionBufferSize = settings.ConnectionBufferSize; _maxOutputDelay = settings.MaxOutputDelay; _name = settings.ConnectionPoolGroupName; } public string Name { get { return _name; } } protected override void AbortItem(IConnection item) { item.Abort(); } protected override void CloseItem(IConnection item, TimeSpan timeout) { item.Close(timeout, false); } protected override void CloseItemAsync(IConnection item, TimeSpan timeout) { item.Close(timeout, true); } public virtual bool IsCompatible(IConnectionOrientedTransportChannelFactorySettings settings) { return ( (_name == settings.ConnectionPoolGroupName) && (_connectionBufferSize == settings.ConnectionBufferSize) && (this.MaxIdleConnectionPoolCount == settings.MaxOutboundConnectionsPerEndpoint) && (this.IdleTimeout == settings.IdleTimeout) && (_maxOutputDelay == settings.MaxOutputDelay) ); } } }
/* * Swaggy Jenkins * * Jenkins API clients generated from Swagger / Open API specification * * The version of the OpenAPI document: 1.1.2-pre.0 * Contact: blah@cliffano.com * Generated by: https://github.com/openapitools/openapi-generator.git */ using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; using System.ComponentModel.DataAnnotations; using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; namespace Org.OpenAPITools.Models { /// <summary> /// PipelineBranchesitempullRequest /// </summary> [DataContract(Name = "PipelineBranchesitempullRequest")] public partial class PipelineBranchesitempullRequest : IEquatable<PipelineBranchesitempullRequest>, IValidatableObject { /// <summary> /// Initializes a new instance of the <see cref="PipelineBranchesitempullRequest" /> class. /// </summary> /// <param name="links">links.</param> /// <param name="author">author.</param> /// <param name="id">id.</param> /// <param name="title">title.</param> /// <param name="url">url.</param> /// <param name="_class">_class.</param> public PipelineBranchesitempullRequest(PipelineBranchesitempullRequestlinks links = default(PipelineBranchesitempullRequestlinks), string author = default(string), string id = default(string), string title = default(string), string url = default(string), string _class = default(string)) { this.Links = links; this.Author = author; this.Id = id; this.Title = title; this.Url = url; this.Class = _class; } /// <summary> /// Gets or Sets Links /// </summary> [DataMember(Name = "_links", EmitDefaultValue = false)] public PipelineBranchesitempullRequestlinks Links { get; set; } /// <summary> /// Gets or Sets Author /// </summary> [DataMember(Name = "author", EmitDefaultValue = false)] public string Author { get; set; } /// <summary> /// Gets or Sets Id /// </summary> [DataMember(Name = "id", EmitDefaultValue = false)] public string Id { get; set; } /// <summary> /// Gets or Sets Title /// </summary> [DataMember(Name = "title", EmitDefaultValue = false)] public string Title { get; set; } /// <summary> /// Gets or Sets Url /// </summary> [DataMember(Name = "url", EmitDefaultValue = false)] public string Url { get; set; } /// <summary> /// Gets or Sets Class /// </summary> [DataMember(Name = "_class", EmitDefaultValue = false)] public string Class { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class PipelineBranchesitempullRequest {\n"); sb.Append(" Links: ").Append(Links).Append("\n"); sb.Append(" Author: ").Append(Author).Append("\n"); sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append(" Title: ").Append(Title).Append("\n"); sb.Append(" Url: ").Append(Url).Append("\n"); sb.Append(" Class: ").Append(Class).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public virtual string ToJson() { return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="input">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object input) { return this.Equals(input as PipelineBranchesitempullRequest); } /// <summary> /// Returns true if PipelineBranchesitempullRequest instances are equal /// </summary> /// <param name="input">Instance of PipelineBranchesitempullRequest to be compared</param> /// <returns>Boolean</returns> public bool Equals(PipelineBranchesitempullRequest input) { if (input == null) return false; return ( this.Links == input.Links || (this.Links != null && this.Links.Equals(input.Links)) ) && ( this.Author == input.Author || (this.Author != null && this.Author.Equals(input.Author)) ) && ( this.Id == input.Id || (this.Id != null && this.Id.Equals(input.Id)) ) && ( this.Title == input.Title || (this.Title != null && this.Title.Equals(input.Title)) ) && ( this.Url == input.Url || (this.Url != null && this.Url.Equals(input.Url)) ) && ( this.Class == input.Class || (this.Class != null && this.Class.Equals(input.Class)) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { int hashCode = 41; if (this.Links != null) hashCode = hashCode * 59 + this.Links.GetHashCode(); if (this.Author != null) hashCode = hashCode * 59 + this.Author.GetHashCode(); if (this.Id != null) hashCode = hashCode * 59 + this.Id.GetHashCode(); if (this.Title != null) hashCode = hashCode * 59 + this.Title.GetHashCode(); if (this.Url != null) hashCode = hashCode * 59 + this.Url.GetHashCode(); if (this.Class != null) hashCode = hashCode * 59 + this.Class.GetHashCode(); return hashCode; } } /// <summary> /// To validate all properties of the instance /// </summary> /// <param name="validationContext">Validation context</param> /// <returns>Validation Result</returns> IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext) { yield break; } } }