context
stringlengths
2.52k
185k
gt
stringclasses
1 value
// // Authors: // Marek Habersack grendel@twistedcode.net // // Copyright (c) 2010, Novell, Inc (http://novell.com/) // // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in // the documentation and/or other materials provided with the distribution. // * Neither the name of Novell, Inc nor names of the contributors may be used to endorse or promote products derived from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // using System; using System.Collections.Generic; using System.Reflection; using System.Text; using CaptainHook.Base; using CaptainHook.GitHub; using CaptainHook.Utils; namespace CaptainHook.Mail { public class TemplateElementFactory <TData> : CommonBase { sealed class MacroMapEntry { public Type ValidFor; public Func <TemplateFragmentMacro, TemplateElement> Processor; public MacroMapEntry (Type validFor, Func<TemplateFragmentMacro, TemplateElement> processor) { this.ValidFor = validFor; this.Processor = processor; } } static readonly string newline = Environment.NewLine; static readonly char[] argumentSplitChars = { ',' }; Dictionary <string, MacroMapEntry> macroMap; string basePath; string commitSourceID; public TemplateElementFactory (string basePath, string commitSourceID) { this.basePath = basePath; this.commitSourceID = commitSourceID; macroMap = new Dictionary<string, MacroMapEntry> (StringComparer.Ordinal) { // Global macros {"Header", new MacroMapEntry (null, Macro_Global_Header) }, {"Version", new MacroMapEntry (null, Macro_Global_Version) }, {"IfDifferent", new MacroMapEntry (null, Macro_Global_IfDifferent) }, // Push macros {"Subject", new MacroMapEntry (typeof (Push), Macro_Push_Subject) }, {"FirstCommit", new MacroMapEntry (typeof (Push), Macro_Push_FirstCommit) }, {"FirstCommit.MessageSummary", new MacroMapEntry (typeof (Push), Macro_Push_FirstCommit_MessageSummary) }, {"AffectedDirectories", new MacroMapEntry (typeof (Push), Macro_Push_AffectedDirectories) }, {"NumberOfCommits", new MacroMapEntry (typeof (Push), Macro_Push_NumberOfCommits) }, // Commit macros {"ChangedPaths", new MacroMapEntry (typeof (Commit), Macro_Commit_ChangedPaths)}, {"AddedPaths", new MacroMapEntry (typeof (Commit), Macro_Commit_AddedPaths)}, {"RemovedPaths", new MacroMapEntry (typeof (Commit), Macro_Commit_RemovedPaths)}, {"FullDiff", new MacroMapEntry (typeof (Commit), Macro_Commit_FullDiff)} }; } public TemplateElement GetElement (TemplateFragment fragment) { if (fragment == null) throw new ArgumentNullException ("fragment"); TemplateFragmentPlainText text = fragment as TemplateFragmentPlainText; if (text != null) return new TemplateElementText (text.Data); TemplateElement ret = null; TemplateFragmentMacro macro = fragment as TemplateFragmentMacro; if (macro != null) ret = ProcessMacro (macro); if (ret == null) throw new InvalidOperationException ( String.Format ("Failed to generate a template element from fragment {0} at {1}:{2},{3}", fragment, fragment.InFile, fragment.LineStart, fragment.ColumnStart) ); return ret; } TemplateElementArgument GetElementArgument (TemplateFragmentArgument arg) { var components = new List<TemplateElement> (); foreach (TemplateFragment fragment in arg.Fragments) components.Add (GetElement (fragment)); return new TemplateElementArgument (components); } List<TemplateElementArgument> GetElementArgumentList (TemplateFragmentMacro fragment) { List<TemplateElementArgument> arguments = null; if (fragment.HasArguments) { arguments = new List<TemplateElementArgument> (); foreach (TemplateFragmentArgument arg in fragment.Arguments) arguments.Add (GetElementArgument (arg)); } if (arguments != null && arguments.Count > 0) return arguments; return null; } Func<TemplateFragmentMacro, TemplateElement> GetProcessor (string name) { MacroMapEntry mapEntry; if (macroMap.TryGetValue (name, out mapEntry) && mapEntry != null && mapEntry.Processor != null && (mapEntry.ValidFor == null || mapEntry.ValidFor == typeof(TData))) return mapEntry.Processor; return null; } TemplateElement ProcessMacro (TemplateFragmentMacro macro) { string name = macro.MacroName; if (name.StartsWith ("this.", StringComparison.Ordinal)) name = name.Substring (5); Func<TemplateFragmentMacro, TemplateElement> processor = GetProcessor (name); if (processor != null) return processor (macro); int dot = name.IndexOf ('.'); if (dot != -1) { string nameLead = name.Substring (0, dot); processor = GetProcessor (nameLead); if (processor != null) return processor (macro); } var ret = new TemplateElementPropertyReference<TData> (name); if (ret.IsCollection) { Type tt = typeof(Template<>); tt = tt.MakeGenericType (new Type[] { GetCollectionElementType (ret.PropertyType) }); ITemplate template = Activator.CreateInstance (tt, new object[] { basePath, commitSourceID }) as ITemplate; if (!template.Compile ()) return null; ret.Template = template; } return ret; } Type GetCollectionElementType (Type type) { if (!type.IsGenericType) throw new ArgumentException ("Type must be a generic collection.", "type"); if (typeof(IDictionary<, >).IsAssignableFrom (type)) { Type kvt = typeof(KeyValuePair<, >); return kvt.MakeGenericType (type.GetGenericArguments ()); } return type.GetGenericArguments ()[0]; } TemplateElement Macro_Global_Header (TemplateFragmentMacro fragment) { List<TemplateElementArgument> arguments = GetElementArgumentList (fragment); return new TemplateElementMailHeader (arguments) { SkipNewlineIfLineEmpty = true }; } TemplateElement Macro_Global_Version (TemplateFragmentMacro fragment) { return new TemplateElementText (Config.Instance.Version); } TemplateElement Macro_Global_IfDifferent (TemplateFragmentMacro fragment) { return new TemplateElementSynthetic<TData> (GetElementArgumentList (fragment), (TData data, List<TemplateElementArgument> args) => { if (args == null || args.Count == 0) return null; var sb = new StringBuilder (); foreach (TemplateElementArgument a in args) sb.Append (a.Generate (data)); string argstr = sb.ToString (); if (argstr.Length == 0) return null; string[] arglist = argstr.Split (argumentSplitChars); if (arglist.Length < 3) { Log (LogSeverity.Error, "Not enough arguments for the IfDifferent macro (expected 3, got {0}", arglist.Length); return null; } string heading = arglist[0]; string left = arglist[1]; string right = String.Join (",", arglist, 2, arglist.Length - 2); if (String.Compare (left, right, StringComparison.Ordinal) == 0) return null; return heading + left; }) { SkipNewlineIfLineEmpty = true }; } TemplateElement Macro_Push_Subject (TemplateFragmentMacro fragment) { List<TemplateElementArgument> arguments = GetElementArgumentList (fragment); return new TemplateElementMailHeader ("Subject", arguments) { SkipNewlineIfLineEmpty = true, IgnoreEqualsSign = true }; } string ShortenString (string data, List<TemplateElementArgument> args, int defvalue) { if (String.IsNullOrEmpty (data)) return data; int nchars = defvalue; if (args != null && args.Count > 0) { TemplateElementArgument arg = args[0]; try { int result; if (Int32.TryParse (arg.Generate (data), out result)) nchars = result; } catch { // ignore } } if (nchars < 0) return data; int len = data.Length; if (nchars >= len) return data; int newline = data.IndexOf ('\n'); if (newline > -1 && newline < nchars) nchars = newline; return data.Substring (0, nchars); } TemplateElement Macro_Push_FirstCommit (TemplateFragmentMacro fragment) { string macroName = fragment.MacroName; if (!macroName.StartsWith ("FirstCommit", StringComparison.Ordinal)) throw new ArgumentException ("Macro name must start with FirstCommit", "fragment"); string propName = macroName.Substring (12); if (String.IsNullOrEmpty (propName)) throw new InvalidOperationException ("A non-empty property name is required."); var propref = new TemplateElementPropertyReference<Commit> (propName); return new TemplateElementSynthetic<Push> (GetElementArgumentList (fragment), (Push data, List<TemplateElementArgument> args) => { List<Commit> commits = data.Commits; if (commits == null || commits.Count == 0) return null; Commit first = commits[0]; return ShortenString(propref.Generate (first), args, -1); }) { SkipNewlineIfLineEmpty = true }; } TemplateElement Macro_Push_FirstCommit_MessageSummary (TemplateFragmentMacro fragment) { string macroName = fragment.MacroName; if (String.Compare ("FirstCommit.MessageSummary", macroName, StringComparison.Ordinal) != 0) throw new ArgumentException ("Macro name must be 'FirstCommit.MessageSummary'", "fragment"); var propref = new TemplateElementPropertyReference<Commit> ("Message"); return new TemplateElementSynthetic<Push> (GetElementArgumentList (fragment), (Push data, List<TemplateElementArgument> args) => { List<Commit> commits = data.Commits; if (commits == null || commits.Count == 0) return null; Commit first = commits[0]; string ret = propref.Generate (first); if (String.IsNullOrEmpty (ret)) return null; return ShortenString (ret, args, 72); }) { SkipNewlineIfLineEmpty = true }; } void AddUniqueDirectoriesToCache (List<string> paths, IDictionary<string, bool> cache) { if (paths == null || paths.Count == 0) return; string dir; int lastSlash; foreach (string p in paths) { if (String.IsNullOrEmpty (p)) continue; lastSlash = p.LastIndexOf ('/'); if (lastSlash == -1) dir = "/"; else dir = p.Substring (0, lastSlash + 1); if (cache.ContainsKey (dir)) continue; cache.Add (dir, true); } } TemplateElement Macro_Push_AffectedDirectories (TemplateFragmentMacro fragment) { string macroName = fragment.MacroName; if (String.Compare ("AffectedDirectories", macroName, StringComparison.Ordinal) != 0) throw new ArgumentException ("Macro name must be 'AffectedDirectories'", "fragment"); return new TemplateElementListMailHeader<Push> (GetElementArgumentList (fragment), (Push data, List<string> values) => { List<Commit> commits = data.Commits; if (commits == null || commits.Count == 0) return; var paths = new SortedDictionary<string, bool> (StringComparer.Ordinal); foreach (Commit c in commits) { AddUniqueDirectoriesToCache (c.Added, paths); AddUniqueDirectoriesToCache (c.Modified, paths); AddUniqueDirectoriesToCache (c.Removed, paths); } foreach (string dir in paths.Keys) values.Add (dir); }) { SkipNewlineIfLineEmpty = true }; } TemplateElement Macro_Push_NumberOfCommits (TemplateFragmentMacro fragment) { string macroName = fragment.MacroName; if (String.Compare ("NumberOfCommits", macroName, StringComparison.Ordinal) != 0) throw new ArgumentException ("Macro name must be 'NumberOfCommits'", "fragment"); return new TemplateElementSynthetic<Push> (GetElementArgumentList (fragment), (Push data, List<TemplateElementArgument> args) => { List<Commit> commits = data.Commits; if (commits == null || commits.Count == 0) return null; if (args == null || args.Count == 0) return null; var sb = new StringBuilder (); foreach (TemplateElementArgument a in args) sb.Append (a.Generate (data)); string arg = sb.ToString (); int comma = arg.IndexOf (','); int min = 2; if (comma != -1) { int v; if (Int32.TryParse (arg.Substring (0, comma), out v)) { min = v; arg = arg.Substring (comma + 1); } } if (commits.Count < min) return null; return arg; }) { SkipNewlineIfLineEmpty = true }; } TemplateElement Macro_Commit_ChangedPaths (TemplateFragmentMacro fragment) { return new TemplateElementSynthetic<Commit> (GetElementArgumentList (fragment), (Commit data, List<TemplateElementArgument> args) => { List<string> modified = data.Modified; if (modified == null || modified.Count == 0) return null; var sb = new StringBuilder (); if (args == null) sb.AppendLine ("Changed paths:"); else sb.AppendLine (args[0].Generate (data)); foreach (string file in modified) sb.Append (" M " + file + newline); return sb.ToString (); }) { SkipNewlineIfLineEmpty = true }; } TemplateElement Macro_Commit_AddedPaths (TemplateFragmentMacro fragment) { return new TemplateElementSynthetic<Commit> (GetElementArgumentList (fragment), (Commit data, List<TemplateElementArgument> args) => { List<string> added = data.Added; if (added == null || added.Count == 0) return null; var sb = new StringBuilder (); if (args == null) sb.AppendLine ("Added paths:"); else sb.AppendLine (args[0].Generate (data)); foreach (string file in added) sb.Append (" A " + file + newline); return sb.ToString (); }) { SkipNewlineIfLineEmpty = true }; } TemplateElement Macro_Commit_RemovedPaths (TemplateFragmentMacro fragment) { return new TemplateElementSynthetic<Commit> (GetElementArgumentList (fragment), (Commit data, List<TemplateElementArgument> args) => { List<string> removed = data.Removed; if (removed == null || removed.Count == 0) return null; var sb = new StringBuilder (); if (args == null) sb.AppendLine ("Removed paths:"); else sb.AppendLine (args[0].Generate (data)); foreach (string file in removed) sb.Append (" D " + file + newline); return sb.ToString (); }) { SkipNewlineIfLineEmpty = true }; } TemplateElement Macro_Commit_FullDiff (TemplateFragmentMacro fragment) { return new TemplateElementSynthetic<Commit> (GetElementArgumentList (fragment), (Commit data, List<TemplateElementArgument> args) => { CommitWithDiff diff = data.Diff; if (diff != null) return diff.GetFullDiff (); return null; }) { SkipNewlineIfLineEmpty = true }; } } }
using System; using System.Collections.Generic; using UnityEngine; namespace UnityStandardAssets.Water { [ExecuteInEditMode] [RequireComponent(typeof(WaterBase))] public class PlanarReflection : MonoBehaviour { public LayerMask reflectionMask; public bool reflectSkybox = false; public Color clearColor = Color.grey; public String reflectionSampler = "_ReflectionTex"; public float clipPlaneOffset = 0.07F; Vector3 m_Oldpos; Camera m_ReflectionCamera; Material m_SharedMaterial; Dictionary<Camera, bool> m_HelperCameras; public void Start() { m_SharedMaterial = ((WaterBase)gameObject.GetComponent(typeof(WaterBase))).sharedMaterial; } Camera CreateReflectionCameraFor(Camera cam) { String reflName = gameObject.name + "Reflection" + cam.name; GameObject go = GameObject.Find(reflName); if (!go) { go = new GameObject(reflName, typeof(Camera)); } if (!go.GetComponent(typeof(Camera))) { go.AddComponent(typeof(Camera)); } Camera reflectCamera = go.GetComponent<Camera>(); reflectCamera.backgroundColor = clearColor; reflectCamera.clearFlags = reflectSkybox ? CameraClearFlags.Skybox : CameraClearFlags.SolidColor; SetStandardCameraParameter(reflectCamera, reflectionMask); if (!reflectCamera.targetTexture) { reflectCamera.targetTexture = CreateTextureFor(cam); } return reflectCamera; } void SetStandardCameraParameter(Camera cam, LayerMask mask) { cam.cullingMask = mask & ~(1 << LayerMask.NameToLayer("Water")); cam.backgroundColor = Color.black; cam.enabled = false; } RenderTexture CreateTextureFor(Camera cam) { RenderTexture rt = new RenderTexture(Mathf.FloorToInt(cam.pixelWidth * 0.5F), Mathf.FloorToInt(cam.pixelHeight * 0.5F), 24); rt.hideFlags = HideFlags.DontSave; return rt; } public void RenderHelpCameras(Camera currentCam) { if (null == m_HelperCameras) { m_HelperCameras = new Dictionary<Camera, bool>(); } if (!m_HelperCameras.ContainsKey(currentCam)) { m_HelperCameras.Add(currentCam, false); } if (m_HelperCameras[currentCam]) { return; } if (!m_ReflectionCamera) { m_ReflectionCamera = CreateReflectionCameraFor(currentCam); } RenderReflectionFor(currentCam, m_ReflectionCamera); m_HelperCameras[currentCam] = true; } public void LateUpdate() { if (null != m_HelperCameras) { m_HelperCameras.Clear(); } } public void WaterTileBeingRendered(Transform tr, Camera currentCam) { RenderHelpCameras(currentCam); if (m_ReflectionCamera && m_SharedMaterial) { m_SharedMaterial.SetTexture(reflectionSampler, m_ReflectionCamera.targetTexture); } } public void OnEnable() { Shader.EnableKeyword("WATER_REFLECTIVE"); Shader.DisableKeyword("WATER_SIMPLE"); } public void OnDisable() { Shader.EnableKeyword("WATER_SIMPLE"); Shader.DisableKeyword("WATER_REFLECTIVE"); } void RenderReflectionFor(Camera cam, Camera reflectCamera) { if (!reflectCamera) { return; } if (m_SharedMaterial && !m_SharedMaterial.HasProperty(reflectionSampler)) { return; } reflectCamera.cullingMask = reflectionMask & ~(1 << LayerMask.NameToLayer("Water")); SaneCameraSettings(reflectCamera); reflectCamera.backgroundColor = clearColor; reflectCamera.clearFlags = reflectSkybox ? CameraClearFlags.Skybox : CameraClearFlags.SolidColor; if (reflectSkybox) { if (cam.gameObject.GetComponent(typeof(Skybox))) { Skybox sb = (Skybox)reflectCamera.gameObject.GetComponent(typeof(Skybox)); if (!sb) { sb = (Skybox)reflectCamera.gameObject.AddComponent(typeof(Skybox)); } sb.material = ((Skybox)cam.GetComponent(typeof(Skybox))).material; } } GL.invertCulling = true; Transform reflectiveSurface = transform; //waterHeight; Vector3 eulerA = cam.transform.eulerAngles; reflectCamera.transform.eulerAngles = new Vector3(-eulerA.x, eulerA.y, eulerA.z); reflectCamera.transform.position = cam.transform.position; Vector3 pos = reflectiveSurface.transform.position; pos.y = reflectiveSurface.position.y; Vector3 normal = reflectiveSurface.transform.up; float d = -Vector3.Dot(normal, pos) - clipPlaneOffset; Vector4 reflectionPlane = new Vector4(normal.x, normal.y, normal.z, d); Matrix4x4 reflection = Matrix4x4.zero; reflection = CalculateReflectionMatrix(reflection, reflectionPlane); m_Oldpos = cam.transform.position; Vector3 newpos = reflection.MultiplyPoint(m_Oldpos); reflectCamera.worldToCameraMatrix = cam.worldToCameraMatrix * reflection; Vector4 clipPlane = CameraSpacePlane(reflectCamera, pos, normal, 1.0f); Matrix4x4 projection = cam.projectionMatrix; projection = CalculateObliqueMatrix(projection, clipPlane); reflectCamera.projectionMatrix = projection; reflectCamera.transform.position = newpos; Vector3 euler = cam.transform.eulerAngles; reflectCamera.transform.eulerAngles = new Vector3(-euler.x, euler.y, euler.z); reflectCamera.Render(); GL.invertCulling = false; } void SaneCameraSettings(Camera helperCam) { helperCam.depthTextureMode = DepthTextureMode.None; helperCam.backgroundColor = Color.black; helperCam.clearFlags = CameraClearFlags.SolidColor; helperCam.renderingPath = RenderingPath.Forward; } static Matrix4x4 CalculateObliqueMatrix(Matrix4x4 projection, Vector4 clipPlane) { Vector4 q = projection.inverse * new Vector4( Sgn(clipPlane.x), Sgn(clipPlane.y), 1.0F, 1.0F ); Vector4 c = clipPlane * (2.0F / (Vector4.Dot(clipPlane, q))); // third row = clip plane - fourth row projection[2] = c.x - projection[3]; projection[6] = c.y - projection[7]; projection[10] = c.z - projection[11]; projection[14] = c.w - projection[15]; return projection; } static Matrix4x4 CalculateReflectionMatrix(Matrix4x4 reflectionMat, Vector4 plane) { reflectionMat.m00 = (1.0F - 2.0F * plane[0] * plane[0]); reflectionMat.m01 = (- 2.0F * plane[0] * plane[1]); reflectionMat.m02 = (- 2.0F * plane[0] * plane[2]); reflectionMat.m03 = (- 2.0F * plane[3] * plane[0]); reflectionMat.m10 = (- 2.0F * plane[1] * plane[0]); reflectionMat.m11 = (1.0F - 2.0F * plane[1] * plane[1]); reflectionMat.m12 = (- 2.0F * plane[1] * plane[2]); reflectionMat.m13 = (- 2.0F * plane[3] * plane[1]); reflectionMat.m20 = (- 2.0F * plane[2] * plane[0]); reflectionMat.m21 = (- 2.0F * plane[2] * plane[1]); reflectionMat.m22 = (1.0F - 2.0F * plane[2] * plane[2]); reflectionMat.m23 = (- 2.0F * plane[3] * plane[2]); reflectionMat.m30 = 0.0F; reflectionMat.m31 = 0.0F; reflectionMat.m32 = 0.0F; reflectionMat.m33 = 1.0F; return reflectionMat; } static float Sgn(float a) { if (a > 0.0F) { return 1.0F; } if (a < 0.0F) { return -1.0F; } return 0.0F; } Vector4 CameraSpacePlane(Camera cam, Vector3 pos, Vector3 normal, float sideSign) { Vector3 offsetPos = pos + normal * clipPlaneOffset; Matrix4x4 m = cam.worldToCameraMatrix; Vector3 cpos = m.MultiplyPoint(offsetPos); Vector3 cnormal = m.MultiplyVector(normal).normalized * sideSign; return new Vector4(cnormal.x, cnormal.y, cnormal.z, -Vector3.Dot(cpos, cnormal)); } } }
/* 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.Collections.Generic; using System.Linq; using System.Threading.Tasks; using ArcGIS.Core.CIM; using ArcGIS.Desktop.Framework; using ArcGIS.Desktop.Framework.Contracts; using ArcGIS.Desktop.Core; using System.Collections.ObjectModel; using System.Windows; namespace SLR_Analyst { internal class SLR_PaneViewModel : ViewStatePane { private const string _viewPaneID = "SLR_Analyst_SLR_Pane"; private ObservableCollection<KeyValueWithTooltip> _landusechartResult; private ObservableCollection<KeyValueWithTooltip> _parcelchartResult; private ObservableCollection<KeyValueWithTooltip> _streetchartResult; public bool CkbParcelChecked; public bool CkbLandUseChecked; public bool CkbStreetChecked; /// <summary> /// Consume the passed in CIMView. Call the base constructor to wire up the CIMView. /// </summary> public SLR_PaneViewModel(CIMView view) : base(view) { _landusechartResult = new ObservableCollection<KeyValueWithTooltip>(); _parcelchartResult = new ObservableCollection<KeyValueWithTooltip>(); _streetchartResult = new ObservableCollection<KeyValueWithTooltip>(); } /// <summary> /// Create a new instance of the pane. /// </summary> internal static SLR_PaneViewModel Create() { var view = new CIMGenericView { ViewType = _viewPaneID }; return FrameworkApplication.Panes.Create(_viewPaneID, new object[] { view }) as SLR_PaneViewModel; } #region Public Methods to update UI Content /// <summary> /// Updates the LandUse observable collection on the UI thread. This is because of a bug in the /// WPFToolKit DataVisualization library which doesn't allow updating on a brackground thread /// </summary> /// <param name="keyValueWithTooltips"></param> public void UpdateLandUse(IList<KeyValueWithTooltip> keyValueWithTooltips) { LandUseChartResult.Clear(); foreach (var kv in keyValueWithTooltips) { LandUseChartResult.Add(kv.Clone()); } } /// <summary> /// Updates the Street observable collection on the UI thread. This is because of a bug in the /// WPFToolKit DataVisualization library which doesn't allow updating on a brackground thread /// </summary> /// <param name="keyValueWithTooltips"></param> public void UpdateStreet(IList<KeyValueWithTooltip> keyValueWithTooltips) { StreetChartResult.Clear(); foreach (var kv in keyValueWithTooltips) { StreetChartResult.Add(kv.Clone()); } } /// <summary> /// Updates the Parcel observable collection on the UI thread. This is because of a bug in the /// WPFToolKit DataVisualization library which doesn't allow updating on a brackground thread /// </summary> /// <param name="keyValueWithTooltips"></param> public void UpdateParcel(IList<KeyValueWithTooltip> keyValueWithTooltips) { ParcelChartResult.Clear(); foreach (var kv in keyValueWithTooltips) { ParcelChartResult.Add(kv.Clone()); } } #endregion Public Methods to update UI Content #region Public UI Properties /// <summary> /// Land Use Chart /// </summary> public ObservableCollection<KeyValueWithTooltip> LandUseChartResult { get { return _landusechartResult; } set { SetProperty(ref _landusechartResult, value, () => LandUseChartResult); } } /// <summary> /// Parcel Chart /// </summary> public ObservableCollection<KeyValueWithTooltip> ParcelChartResult { get { return _parcelchartResult; } set { SetProperty(ref _parcelchartResult, value, () => ParcelChartResult); } } /// <summary> /// Street Chart /// </summary> public ObservableCollection<KeyValueWithTooltip> StreetChartResult { get { return _streetchartResult; } set { SetProperty(ref _streetchartResult, value, () => StreetChartResult); } } public Visibility IsVisibleStreet => CkbStreetChecked ? Visibility.Visible : Visibility.Hidden; public Visibility IsVisibleParcel => CkbParcelChecked ? Visibility.Visible : Visibility.Hidden; public Visibility IsVisibleLandUse => CkbLandUseChecked ? Visibility.Visible : Visibility.Hidden; public void UpdateVisibility () { NotifyPropertyChanged("IsVisibleStreet"); NotifyPropertyChanged("IsVisibleParcel"); NotifyPropertyChanged("IsVisibleLandUse"); } private string _paneTitle; public string PaneTitle { get { return _paneTitle; } set { SetProperty(ref _paneTitle, value, () => PaneTitle); } } public string _paneConfiguration; public string PaneConfiguration { get { return _paneConfiguration; } set { SetProperty(ref _paneConfiguration, value, () => PaneConfiguration); } } /// <summary> /// Report Text Box Updates /// </summary> private string _reportText; public string ReportText { get { return _reportText; } set { SetProperty(ref _reportText, value, () => ReportText); } } #endregion Public UI Properties #region Pane Overrides /// <summary> /// Must be overridden in child classes used to persist the state of the view to the CIM. /// </summary> public override CIMView ViewState { get { _cimView.InstanceID = (int)InstanceID; return _cimView; } } /// <summary> /// Called when the pane is initialized. /// </summary> protected async override Task InitializeAsync() { await base.InitializeAsync(); } /// <summary> /// Called when the pane is uninitialized. /// </summary> protected async override Task UninitializeAsync() { await base.UninitializeAsync(); } #endregion Pane Overrides } /// <summary> /// Button implementation to create a new instance of the pane and activate it. /// </summary> internal class SLR_Pane_OpenButton : Button { protected override void OnClick() { SLR_PaneViewModel.Create(); } } }
// 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. /*============================================================ ** ** ** ** Purpose: The CLR implementation of Variant. ** ** ===========================================================*/ namespace System { using System; using System.Reflection; using System.Threading; using System.Runtime.InteropServices; using System.Globalization; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Diagnostics; using System.Diagnostics.Contracts; [Serializable] [StructLayout(LayoutKind.Sequential)] internal struct Variant { //Do Not change the order of these fields. //They are mapped to the native VariantData * data structure. private Object m_objref; private int m_data1; private int m_data2; private int m_flags; // The following bits have been taken up as follows // bits 0-15 - Type code // bit 16 - Array // bits 19-23 - Enums // bits 24-31 - Optional VT code (for roundtrip VT preservation) //What are the consequences of making this an enum? /////////////////////////////////////////////////////////////////////// // If you update this, update the corresponding stuff in OAVariantLib.cs, // COMOAVariant.cpp (2 tables, forwards and reverse), and perhaps OleVariant.h /////////////////////////////////////////////////////////////////////// internal const int CV_EMPTY=0x0; internal const int CV_VOID=0x1; internal const int CV_BOOLEAN=0x2; internal const int CV_CHAR=0x3; internal const int CV_I1=0x4; internal const int CV_U1=0x5; internal const int CV_I2=0x6; internal const int CV_U2=0x7; internal const int CV_I4=0x8; internal const int CV_U4=0x9; internal const int CV_I8=0xa; internal const int CV_U8=0xb; internal const int CV_R4=0xc; internal const int CV_R8=0xd; internal const int CV_STRING=0xe; internal const int CV_PTR=0xf; internal const int CV_DATETIME = 0x10; internal const int CV_TIMESPAN = 0x11; internal const int CV_OBJECT=0x12; internal const int CV_DECIMAL = 0x13; internal const int CV_ENUM=0x15; internal const int CV_MISSING=0x16; internal const int CV_NULL=0x17; internal const int CV_LAST=0x18; internal const int TypeCodeBitMask=0xffff; internal const int VTBitMask=unchecked((int)0xff000000); internal const int VTBitShift=24; internal const int ArrayBitMask =0x10000; // Enum enum and Mask internal const int EnumI1 =0x100000; internal const int EnumU1 =0x200000; internal const int EnumI2 =0x300000; internal const int EnumU2 =0x400000; internal const int EnumI4 =0x500000; internal const int EnumU4 =0x600000; internal const int EnumI8 =0x700000; internal const int EnumU8 =0x800000; internal const int EnumMask =0xF00000; internal static readonly Type [] ClassTypes = { typeof(System.Empty), typeof(void), typeof(Boolean), typeof(Char), typeof(SByte), typeof(Byte), typeof(Int16), typeof(UInt16), typeof(Int32), typeof(UInt32), typeof(Int64), typeof(UInt64), typeof(Single), typeof(Double), typeof(String), typeof(void), // ptr for the moment typeof(DateTime), typeof(TimeSpan), typeof(Object), typeof(Decimal), typeof(Object), // Treat enum as Object typeof(System.Reflection.Missing), typeof(System.DBNull), }; internal static readonly Variant Empty = new Variant(); internal static readonly Variant Missing = new Variant(Variant.CV_MISSING, Type.Missing, 0, 0); internal static readonly Variant DBNull = new Variant(Variant.CV_NULL, System.DBNull.Value, 0, 0); // // Native Methods // [MethodImplAttribute(MethodImplOptions.InternalCall)] internal extern double GetR8FromVar(); [MethodImplAttribute(MethodImplOptions.InternalCall)] internal extern float GetR4FromVar(); [MethodImplAttribute(MethodImplOptions.InternalCall)] internal extern void SetFieldsR4(float val); [MethodImplAttribute(MethodImplOptions.InternalCall)] internal extern void SetFieldsR8(double val); [MethodImplAttribute(MethodImplOptions.InternalCall)] internal extern void SetFieldsObject(Object val); // Use this function instead of an ECALL - saves about 150 clock cycles // by avoiding the ecall transition and because the JIT inlines this. // Ends up only taking about 1/8 the time of the ECALL version. internal long GetI8FromVar() { return ((long)m_data2<<32 | ((long)m_data1 & 0xFFFFFFFFL)); } // // Constructors // internal Variant(int flags, Object or, int data1, int data2) { m_flags = flags; m_objref=or; m_data1=data1; m_data2=data2; } public Variant(bool val) { m_objref= null; m_flags = CV_BOOLEAN; m_data1 = (val)?Boolean.True:Boolean.False; m_data2 = 0; } public Variant(sbyte val) { m_objref=null; m_flags=CV_I1; m_data1=(int)val; m_data2=(int)(((long)val)>>32); } public Variant(byte val) { m_objref=null; m_flags=CV_U1; m_data1=(int)val; m_data2=0; } public Variant(short val) { m_objref=null; m_flags=CV_I2; m_data1=(int)val; m_data2=(int)(((long)val)>>32); } public Variant(ushort val) { m_objref=null; m_flags=CV_U2; m_data1=(int)val; m_data2=0; } public Variant(char val) { m_objref=null; m_flags=CV_CHAR; m_data1=(int)val; m_data2=0; } public Variant(int val) { m_objref=null; m_flags=CV_I4; m_data1=val; m_data2=val >> 31; } public Variant(uint val) { m_objref=null; m_flags=CV_U4; m_data1=(int)val; m_data2=0; } public Variant(long val) { m_objref=null; m_flags=CV_I8; m_data1 = (int)val; m_data2 = (int)(val >> 32); } public Variant(ulong val) { m_objref=null; m_flags=CV_U8; m_data1 = (int)val; m_data2 = (int)(val >> 32); } public Variant(float val) { m_objref=null; m_flags=CV_R4; m_data1=0; m_data2=0; SetFieldsR4(val); } public Variant(double val) { m_objref=null; m_flags=CV_R8; m_data1=0; m_data2=0; SetFieldsR8(val); } public Variant(DateTime val) { m_objref=null; m_flags=CV_DATETIME; ulong ticks = (ulong)val.Ticks; m_data1 = (int)ticks; m_data2 = (int)(ticks>>32); } public Variant(Decimal val) { m_objref = (Object)val; m_flags = CV_DECIMAL; m_data1=0; m_data2=0; } public Variant(Object obj) { m_data1=0; m_data2=0; VarEnum vt = VarEnum.VT_EMPTY; if (obj is DateTime) { m_objref=null; m_flags=CV_DATETIME; ulong ticks = (ulong)((DateTime)obj).Ticks; m_data1 = (int)ticks; m_data2 = (int)(ticks>>32); return; } if (obj is String) { m_flags=CV_STRING; m_objref=obj; return; } if (obj == null) { this = Empty; return; } if (obj == System.DBNull.Value) { this = DBNull; return; } if (obj == Type.Missing) { this = Missing; return; } if (obj is Array) { m_flags=CV_OBJECT | ArrayBitMask; m_objref=obj; return; } // Compiler appeasement m_flags = CV_EMPTY; m_objref = null; // Check to see if the object passed in is a wrapper object. if (obj is UnknownWrapper) { vt = VarEnum.VT_UNKNOWN; obj = ((UnknownWrapper)obj).WrappedObject; } else if (obj is DispatchWrapper) { vt = VarEnum.VT_DISPATCH; obj = ((DispatchWrapper)obj).WrappedObject; } else if (obj is ErrorWrapper) { vt = VarEnum.VT_ERROR; obj = (Object)(((ErrorWrapper)obj).ErrorCode); Debug.Assert(obj != null, "obj != null"); } else if (obj is CurrencyWrapper) { vt = VarEnum.VT_CY; obj = (Object)(((CurrencyWrapper)obj).WrappedObject); Debug.Assert(obj != null, "obj != null"); } else if (obj is BStrWrapper) { vt = VarEnum.VT_BSTR; obj = (Object)(((BStrWrapper)obj).WrappedObject); } if (obj != null) { SetFieldsObject(obj); } // If the object passed in is one of the wrappers then set the VARIANT type. if (vt != VarEnum.VT_EMPTY) m_flags |= ((int)vt << VTBitShift); } unsafe public Variant(void* voidPointer,Type pointerType) { if (pointerType == null) throw new ArgumentNullException(nameof(pointerType)); if (!pointerType.IsPointer) throw new ArgumentException(Environment.GetResourceString("Arg_MustBePointer"),nameof(pointerType)); Contract.EndContractBlock(); m_objref = pointerType; m_flags=CV_PTR; m_data1=(int)voidPointer; m_data2=0; } //This is a family-only accessor for the CVType. //This is never to be exposed externally. internal int CVType { get { return (m_flags&TypeCodeBitMask); } } public Object ToObject() { switch (CVType) { case CV_EMPTY: return null; case CV_BOOLEAN: return (Object)(m_data1!=0); case CV_I1: return (Object)((sbyte)m_data1); case CV_U1: return (Object)((byte)m_data1); case CV_CHAR: return (Object)((char)m_data1); case CV_I2: return (Object)((short)m_data1); case CV_U2: return (Object)((ushort)m_data1); case CV_I4: return (Object)(m_data1); case CV_U4: return (Object)((uint)m_data1); case CV_I8: return (Object)(GetI8FromVar()); case CV_U8: return (Object)((ulong)GetI8FromVar()); case CV_R4: return (Object)(GetR4FromVar()); case CV_R8: return (Object)(GetR8FromVar()); case CV_DATETIME: return new DateTime(GetI8FromVar()); case CV_TIMESPAN: return new TimeSpan(GetI8FromVar()); case CV_ENUM: return BoxEnum(); case CV_MISSING: return Type.Missing; case CV_NULL: return System.DBNull.Value; case CV_DECIMAL: case CV_STRING: case CV_OBJECT: default: return m_objref; } } // This routine will return an boxed enum. [MethodImplAttribute(MethodImplOptions.InternalCall)] private extern Object BoxEnum(); // Helper code for marshaling managed objects to VARIANT's (we use // managed variants as an intermediate type. internal static void MarshalHelperConvertObjectToVariant(Object o, ref Variant v) { IConvertible ic = o as IConvertible; if (o == null) { v = Empty; } else if (ic == null) { // This path should eventually go away. But until // the work is done to have all of our wrapper types implement // IConvertible, this is a cheapo way to get the work done. v = new Variant(o); } else { IFormatProvider provider = CultureInfo.InvariantCulture; switch (ic.GetTypeCode()) { case TypeCode.Empty: v = Empty; break; case TypeCode.Object: v = new Variant((Object)o); break; case TypeCode.DBNull: v = DBNull; break; case TypeCode.Boolean: v = new Variant(ic.ToBoolean(provider)); break; case TypeCode.Char: v = new Variant(ic.ToChar(provider)); break; case TypeCode.SByte: v = new Variant(ic.ToSByte(provider)); break; case TypeCode.Byte: v = new Variant(ic.ToByte(provider)); break; case TypeCode.Int16: v = new Variant(ic.ToInt16(provider)); break; case TypeCode.UInt16: v = new Variant(ic.ToUInt16(provider)); break; case TypeCode.Int32: v = new Variant(ic.ToInt32(provider)); break; case TypeCode.UInt32: v = new Variant(ic.ToUInt32(provider)); break; case TypeCode.Int64: v = new Variant(ic.ToInt64(provider)); break; case TypeCode.UInt64: v = new Variant(ic.ToUInt64(provider)); break; case TypeCode.Single: v = new Variant(ic.ToSingle(provider)); break; case TypeCode.Double: v = new Variant(ic.ToDouble(provider)); break; case TypeCode.Decimal: v = new Variant(ic.ToDecimal(provider)); break; case TypeCode.DateTime: v = new Variant(ic.ToDateTime(provider)); break; case TypeCode.String: v = new Variant(ic.ToString(provider)); break; default: throw new NotSupportedException(Environment.GetResourceString("NotSupported_UnknownTypeCode", ic.GetTypeCode())); } } } // Helper code for marshaling VARIANTS to managed objects (we use // managed variants as an intermediate type. internal static Object MarshalHelperConvertVariantToObject(ref Variant v) { return v.ToObject(); } // Helper code: on the back propagation path where a VT_BYREF VARIANT* // is marshaled to a "ref Object", we use this helper to force the // updated object back to the original type. internal static void MarshalHelperCastVariant(Object pValue, int vt, ref Variant v) { IConvertible iv = pValue as IConvertible; if (iv == null) { switch (vt) { case 9: /*VT_DISPATCH*/ v = new Variant(new DispatchWrapper(pValue)); break; case 12: /*VT_VARIANT*/ v = new Variant(pValue); break; case 13: /*VT_UNKNOWN*/ v = new Variant(new UnknownWrapper(pValue)); break; case 36: /*VT_RECORD*/ v = new Variant(pValue); break; case 8: /*VT_BSTR*/ if (pValue == null) { v = new Variant(null); v.m_flags = CV_STRING; } else { throw new InvalidCastException(Environment.GetResourceString("InvalidCast_CannotCoerceByRefVariant")); } break; default: throw new InvalidCastException(Environment.GetResourceString("InvalidCast_CannotCoerceByRefVariant")); } } else { IFormatProvider provider = CultureInfo.InvariantCulture; switch (vt) { case 0: /*VT_EMPTY*/ v = Empty; break; case 1: /*VT_NULL*/ v = DBNull; break; case 2: /*VT_I2*/ v = new Variant(iv.ToInt16(provider)); break; case 3: /*VT_I4*/ v = new Variant(iv.ToInt32(provider)); break; case 4: /*VT_R4*/ v = new Variant(iv.ToSingle(provider)); break; case 5: /*VT_R8*/ v = new Variant(iv.ToDouble(provider)); break; case 6: /*VT_CY*/ v = new Variant(new CurrencyWrapper(iv.ToDecimal(provider))); break; case 7: /*VT_DATE*/ v = new Variant(iv.ToDateTime(provider)); break; case 8: /*VT_BSTR*/ v = new Variant(iv.ToString(provider)); break; case 9: /*VT_DISPATCH*/ v = new Variant(new DispatchWrapper((Object)iv)); break; case 10: /*VT_ERROR*/ v = new Variant(new ErrorWrapper(iv.ToInt32(provider))); break; case 11: /*VT_BOOL*/ v = new Variant(iv.ToBoolean(provider)); break; case 12: /*VT_VARIANT*/ v = new Variant((Object)iv); break; case 13: /*VT_UNKNOWN*/ v = new Variant(new UnknownWrapper((Object)iv)); break; case 14: /*VT_DECIMAL*/ v = new Variant(iv.ToDecimal(provider)); break; // case 15: /*unused*/ // NOT SUPPORTED case 16: /*VT_I1*/ v = new Variant(iv.ToSByte(provider)); break; case 17: /*VT_UI1*/ v = new Variant(iv.ToByte(provider)); break; case 18: /*VT_UI2*/ v = new Variant(iv.ToUInt16(provider)); break; case 19: /*VT_UI4*/ v = new Variant(iv.ToUInt32(provider)); break; case 20: /*VT_I8*/ v = new Variant(iv.ToInt64(provider)); break; case 21: /*VT_UI8*/ v = new Variant(iv.ToUInt64(provider)); break; case 22: /*VT_INT*/ v = new Variant(iv.ToInt32(provider)); break; case 23: /*VT_UINT*/ v = new Variant(iv.ToUInt32(provider)); break; default: throw new InvalidCastException(Environment.GetResourceString("InvalidCast_CannotCoerceByRefVariant")); } } } } }
/*=============================================================================== Copyright (c) 2015-2016 PTC Inc. All Rights Reserved. Copyright (c) 2012-2015 Qualcomm Connected Experiences, Inc. All Rights Reserved. Vuforia is a trademark of PTC Inc., registered in the United States and other countries. ===============================================================================*/ using System; using UnityEngine; using Vuforia; /// <summary> /// This MonoBehaviour implements the Cloud Reco Event handling for this sample. /// It registers itself at the CloudRecoBehaviour and is notified of new search results as well as error messages /// The current state is visualized and new results are enabled using the TargetFinder API. /// </summary> public class CloudRecoEventHandler : MonoBehaviour, ICloudRecoEventHandler { #region PRIVATE_MEMBERS // ObjectTracker reference to avoid lookups private ObjectTracker mObjectTracker; private ContentManager mContentManager; private TrackableSettings mTrackableSettings; private bool mMustRestartApp = false; // the parent gameobject of the referenced ImageTargetTemplate - reused for all target search results private GameObject mParentOfImageTargetTemplate; #endregion // PRIVATE_MEMBERS #region PUBLIC_MEMBERS /// <summary> /// Can be set in the Unity inspector to reference a ImageTargetBehaviour that is used for augmentations of new cloud reco results. /// </summary> public ImageTargetBehaviour ImageTargetTemplate; /// <summary> /// The scan-line rendered in overlay when Cloud Reco is in scanning mode. /// </summary> public ScanLine scanLine; /// <summary> /// Cloud Reco error UI elements. /// </summary> public Canvas cloudErrorCanvas; public UnityEngine.UI.Text cloudErrorTitle; public UnityEngine.UI.Text cloudErrorText; #endregion //PUBLIC_MEMBERS #region MONOBEHAVIOUR_METHODS /// <summary> /// register for events at the CloudRecoBehaviour /// </summary> void Start() { mTrackableSettings = FindObjectOfType<TrackableSettings>(); // look up the gameobject containing the ImageTargetTemplate: mParentOfImageTargetTemplate = ImageTargetTemplate.gameObject; // register this event handler at the cloud reco behaviour CloudRecoBehaviour cloudRecoBehaviour = GetComponent<CloudRecoBehaviour>(); if (cloudRecoBehaviour) { cloudRecoBehaviour.RegisterEventHandler(this); } } #endregion //MONOBEHAVIOUR_METHODS #region ICloudRecoEventHandler_implementation /// <summary> /// Called when TargetFinder has been initialized successfully /// </summary> public void OnInitialized() { Debug.Log("Cloud Reco initialized successfully."); // get a reference to the Object Tracker, remember it mObjectTracker = TrackerManager.Instance.GetTracker<ObjectTracker>(); mContentManager = FindObjectOfType<ContentManager>(); } /// <summary> /// Called if Cloud Reco initialization fails /// </summary> public void OnInitError(TargetFinder.InitState initError) { Debug.Log("Cloud Reco initialization error: " + initError.ToString()); switch (initError) { case TargetFinder.InitState.INIT_ERROR_NO_NETWORK_CONNECTION: { mMustRestartApp = true; ShowError("Network Unavailable", "Please check your internet connection and try again."); break; } case TargetFinder.InitState.INIT_ERROR_SERVICE_NOT_AVAILABLE: ShowError("Service Unavailable", "Failed to initialize app because the service is not available."); break; } } /// <summary> /// Called if a Cloud Reco update error occurs /// </summary> public void OnUpdateError(TargetFinder.UpdateState updateError) { Debug.Log("Cloud Reco update error: " + updateError.ToString()); switch (updateError) { case TargetFinder.UpdateState.UPDATE_ERROR_AUTHORIZATION_FAILED: ShowError("Authorization Error", "The cloud recognition service access keys are incorrect or have expired."); break; case TargetFinder.UpdateState.UPDATE_ERROR_NO_NETWORK_CONNECTION: ShowError("Network Unavailable", "Please check your internet connection and try again."); break; case TargetFinder.UpdateState.UPDATE_ERROR_PROJECT_SUSPENDED: ShowError("Authorization Error", "The cloud recognition service has been suspended."); break; case TargetFinder.UpdateState.UPDATE_ERROR_REQUEST_TIMEOUT: ShowError("Request Timeout", "The network request has timed out, please check your internet connection and try again."); break; case TargetFinder.UpdateState.UPDATE_ERROR_SERVICE_NOT_AVAILABLE: ShowError("Service Unavailable", "The service is unavailable, please try again later."); break; case TargetFinder.UpdateState.UPDATE_ERROR_TIMESTAMP_OUT_OF_RANGE: ShowError("Clock Sync Error", "Please update the date and time and try again."); break; case TargetFinder.UpdateState.UPDATE_ERROR_UPDATE_SDK: ShowError("Unsupported Version", "The application is using an unsupported version of Vuforia."); break; } } /// <summary> /// when we start scanning, unregister Trackable from the ImageTargetTemplate, then delete all trackables /// </summary> public void OnStateChanged(bool scanning) { if (scanning) { // clear all known trackables mObjectTracker.TargetFinder.ClearTrackables(false); // hide the ImageTargetTemplate mContentManager.ShowObject(false); } ShowScanLine(scanning); } /// <summary> /// Handles new search results /// </summary> /// <param name="targetSearchResult"></param> public void OnNewSearchResult(TargetFinder.TargetSearchResult targetSearchResult) { // This code demonstrates how to reuse an ImageTargetBehaviour for new search results and modifying it according to the metadata // Depending on your application, it can make more sense to duplicate the ImageTargetBehaviour using Instantiate(), // or to create a new ImageTargetBehaviour for each new result // Vuforia will return a new object with the right script automatically if you use // TargetFinder.EnableTracking(TargetSearchResult result, string gameObjectName) //Check if the metadata isn't null if (targetSearchResult.MetaData == null) { Debug.Log("Target metadata not available."); return; } // First clear all trackables mObjectTracker.TargetFinder.ClearTrackables(false); // enable the new result with the same ImageTargetBehaviour: ImageTargetBehaviour imageTargetBehaviour = mObjectTracker.TargetFinder.EnableTracking(targetSearchResult, mParentOfImageTargetTemplate) as ImageTargetBehaviour; //if extended tracking was enabled from the menu, we need to start the extendedtracking on the newly found trackble. if (mTrackableSettings && mTrackableSettings.IsExtendedTrackingEnabled()) { imageTargetBehaviour.ImageTarget.StartExtendedTracking(); } } #endregion //ICloudRecoEventHandler_implementation #region PUBLIC_METHODS public void CloseErrorDialog() { if (cloudErrorCanvas) { cloudErrorCanvas.transform.parent.position = Vector3.right * 2 * Screen.width; cloudErrorCanvas.gameObject.SetActive(false); cloudErrorCanvas.enabled = false; if (mMustRestartApp) { mMustRestartApp = false; RestartApplication(); } } } #endregion //PUBLIC_METHODS #region PRIVATE_METHODS private void ShowScanLine(bool show) { // Toggle scanline rendering if (scanLine != null) { Renderer scanLineRenderer = scanLine.GetComponent<Renderer>(); if (show) { // Enable scan line rendering if (!scanLineRenderer.enabled) scanLineRenderer.enabled = true; scanLine.ResetAnimation(); } else { // Disable scanline rendering if (scanLineRenderer.enabled) scanLineRenderer.enabled = false; } } } private void ShowError(string title, string msg) { if (!cloudErrorCanvas) return; if (cloudErrorTitle) cloudErrorTitle.text = title; if (cloudErrorText) cloudErrorText.text = msg; // Show the error canvas cloudErrorCanvas.transform.parent.position = Vector3.zero; cloudErrorCanvas.gameObject.SetActive(true); cloudErrorCanvas.enabled = true; } // Callback for network-not-available error message private void RestartApplication() { #if (UNITY_5_2 || UNITY_5_1 || UNITY_5_0) int startLevel = Application.loadedLevel - 2; if (startLevel < 0) startLevel = 0; Application.LoadLevel(startLevel); #else // UNITY_5_3 or above int startLevel = UnityEngine.SceneManagement.SceneManager.GetActiveScene().buildIndex - 2; if (startLevel < 0) startLevel = 0; UnityEngine.SceneManagement.SceneManager.LoadScene(startLevel); #endif } #endregion //PRIVATE_METHODS }
// ReSharper disable RedundantUsingDirective // ReSharper disable DoNotCallOverridableMethodsInConstructor // ReSharper disable InconsistentNaming // ReSharper disable PartialTypeWithSinglePart // ReSharper disable PartialMethodWithSinglePart // ReSharper disable RedundantNameQualifier // TargetFrameworkVersion = 4.51 #pragma warning disable 1591 // Ignore "Missing XML Comment" warning using System; using System.CodeDom.Compiler; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Data.Entity.Infrastructure; using System.Linq.Expressions; using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity; using System.Data; using System.Data.SqlClient; using System.Data.SqlTypes; using System.Data.Entity.ModelConfiguration; using System.Threading; using DatabaseGeneratedOption = System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption; namespace MapperExemple.Entity.EF { [GeneratedCodeAttribute("EF.Reverse.POCO.Generator", "2.15.1.0")] public class FakeExempleDbContext : IExempleDbContext { public DbSet<AlphabeticalListOfProduct> AlphabeticalListOfProducts { get; set; } public DbSet<Category> Categories { get; set; } public DbSet<CategorySalesFor1997> CategorySalesFor1997 { get; set; } public DbSet<CurrentProductList> CurrentProductLists { get; set; } public DbSet<Customer> Customers { get; set; } public DbSet<CustomerAndSuppliersByCity> CustomerAndSuppliersByCities { get; set; } public DbSet<CustomerDemographic> CustomerDemographics { get; set; } public DbSet<Employee> Employees { get; set; } public DbSet<Invoice> Invoices { get; set; } public DbSet<Order> Orders { get; set; } public DbSet<OrderDetail> OrderDetails { get; set; } public DbSet<OrderDetailsExtended> OrderDetailsExtendeds { get; set; } public DbSet<OrdersQry> OrdersQries { get; set; } public DbSet<OrderSubtotal> OrderSubtotals { get; set; } public DbSet<Product> Products { get; set; } public DbSet<ProductsAboveAveragePrice> ProductsAboveAveragePrices { get; set; } public DbSet<ProductSalesFor1997> ProductSalesFor1997 { get; set; } public DbSet<ProductsByCategory> ProductsByCategories { get; set; } public DbSet<Region> Regions { get; set; } public DbSet<SalesByCategory> SalesByCategories { get; set; } public DbSet<SalesTotalsByAmount> SalesTotalsByAmounts { get; set; } public DbSet<Shipper> Shippers { get; set; } public DbSet<SummaryOfSalesByQuarter> SummaryOfSalesByQuarters { get; set; } public DbSet<SummaryOfSalesByYear> SummaryOfSalesByYears { get; set; } public DbSet<Supplier> Suppliers { get; set; } public DbSet<Sysdiagram> Sysdiagrams { get; set; } public DbSet<Territory> Territories { get; set; } public FakeExempleDbContext() { AlphabeticalListOfProducts = new FakeDbSet<AlphabeticalListOfProduct>(); Categories = new FakeDbSet<Category>(); CategorySalesFor1997 = new FakeDbSet<CategorySalesFor1997>(); CurrentProductLists = new FakeDbSet<CurrentProductList>(); Customers = new FakeDbSet<Customer>(); CustomerAndSuppliersByCities = new FakeDbSet<CustomerAndSuppliersByCity>(); CustomerDemographics = new FakeDbSet<CustomerDemographic>(); Employees = new FakeDbSet<Employee>(); Invoices = new FakeDbSet<Invoice>(); Orders = new FakeDbSet<Order>(); OrderDetails = new FakeDbSet<OrderDetail>(); OrderDetailsExtendeds = new FakeDbSet<OrderDetailsExtended>(); OrdersQries = new FakeDbSet<OrdersQry>(); OrderSubtotals = new FakeDbSet<OrderSubtotal>(); Products = new FakeDbSet<Product>(); ProductsAboveAveragePrices = new FakeDbSet<ProductsAboveAveragePrice>(); ProductSalesFor1997 = new FakeDbSet<ProductSalesFor1997>(); ProductsByCategories = new FakeDbSet<ProductsByCategory>(); Regions = new FakeDbSet<Region>(); SalesByCategories = new FakeDbSet<SalesByCategory>(); SalesTotalsByAmounts = new FakeDbSet<SalesTotalsByAmount>(); Shippers = new FakeDbSet<Shipper>(); SummaryOfSalesByQuarters = new FakeDbSet<SummaryOfSalesByQuarter>(); SummaryOfSalesByYears = new FakeDbSet<SummaryOfSalesByYear>(); Suppliers = new FakeDbSet<Supplier>(); Sysdiagrams = new FakeDbSet<Sysdiagram>(); Territories = new FakeDbSet<Territory>(); } public int SaveChangesCount { get; private set; } public int SaveChanges() { ++SaveChangesCount; return 1; } public System.Threading.Tasks.Task<int> SaveChangesAsync() { throw new NotImplementedException(); } public System.Threading.Tasks.Task<int> SaveChangesAsync(CancellationToken cancellationToken) { throw new NotImplementedException(); } protected virtual void Dispose(bool disposing) { } public void Dispose() { Dispose(true); } // Stored Procedures public List<CustOrderHistReturnModel> CustOrderHist(string customerId) { int procResult; return CustOrderHist(customerId, out procResult); } public List<CustOrderHistReturnModel> CustOrderHist(string customerId, out int procResult) { procResult = 0; return new List<CustOrderHistReturnModel>(); } public List<CustOrdersDetailReturnModel> CustOrdersDetail(int? orderId) { int procResult; return CustOrdersDetail(orderId, out procResult); } public List<CustOrdersDetailReturnModel> CustOrdersDetail(int? orderId, out int procResult) { procResult = 0; return new List<CustOrdersDetailReturnModel>(); } public List<CustOrdersOrdersReturnModel> CustOrdersOrders(string customerId) { int procResult; return CustOrdersOrders(customerId, out procResult); } public List<CustOrdersOrdersReturnModel> CustOrdersOrders(string customerId, out int procResult) { procResult = 0; return new List<CustOrdersOrdersReturnModel>(); } public List<EmployeeSalesByCountryReturnModel> EmployeeSalesByCountry(DateTime? beginningDate, DateTime? endingDate) { int procResult; return EmployeeSalesByCountry(beginningDate, endingDate, out procResult); } public List<EmployeeSalesByCountryReturnModel> EmployeeSalesByCountry(DateTime? beginningDate, DateTime? endingDate, out int procResult) { procResult = 0; return new List<EmployeeSalesByCountryReturnModel>(); } public List<SalesByYearReturnModel> SalesByYear(DateTime? beginningDate, DateTime? endingDate) { int procResult; return SalesByYear(beginningDate, endingDate, out procResult); } public List<SalesByYearReturnModel> SalesByYear(DateTime? beginningDate, DateTime? endingDate, out int procResult) { procResult = 0; return new List<SalesByYearReturnModel>(); } public List<SalesByCategoryReturnModel> SalesByCategory(string categoryName, string ordYear) { int procResult; return SalesByCategory(categoryName, ordYear, out procResult); } public List<SalesByCategoryReturnModel> SalesByCategory(string categoryName, string ordYear, out int procResult) { procResult = 0; return new List<SalesByCategoryReturnModel>(); } public List<TenMostExpensiveProductsReturnModel> TenMostExpensiveProducts() { int procResult; return TenMostExpensiveProducts(out procResult); } public List<TenMostExpensiveProductsReturnModel> TenMostExpensiveProducts( out int procResult) { procResult = 0; return new List<TenMostExpensiveProductsReturnModel>(); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.EventSystems; using UnityEngine.UI; using wvr; using WaveVR_Log; using System; public enum EControllerButtons { Menu = WVR_InputId.WVR_InputId_Alias1_Menu, Touchpad = WVR_InputId.WVR_InputId_Alias1_Touchpad, Trigger = WVR_InputId.WVR_InputId_Alias1_Trigger } public enum ERaycastMode { Beam, Fixed, Mouse } public enum ERaycastStartPoint { CenterOfEyes, LeftEye, RightEye } public class WaveVR_ControllerInputModule : BaseInputModule { private const string LOG_TAG = "WaveVR_ControllerInputModule"; private void PrintDebugLog(string msg) { #if UNITY_EDITOR Debug.Log(LOG_TAG + " " + msg); #endif Log.d (LOG_TAG, msg); } #region Developer specified parameters public GameObject RightController; public LayerMask RightRaycastMask = ~0; public GameObject LeftController; public LayerMask LeftRaycastMask = ~0; public EControllerButtons ButtonToTrigger = EControllerButtons.Touchpad; public GameObject Head = null; [HideInInspector] public ERaycastMode RaycastMode = ERaycastMode.Mouse; [HideInInspector] public ERaycastStartPoint RaycastStartPoint = ERaycastStartPoint.CenterOfEyes; [Tooltip("Will be obsoleted soon!")] public string CanvasTag = "EventCanvas"; #endregion // Do NOT allow event DOWN being sent multiple times during CLICK_TIME. // Since UI element of Unity needs time to perform transitions. private const float CLICK_TIME = 0.1f; private const float raycastStartPointOffset = 0.0315f; private GameObject pointCameraL = null; private GameObject pointCameraR = null; private float userBeamLength; public float FixedBeamLength = 9.0f; private Color32 FixedBeamColor = new Color32 (255, 255, 255, 255); private Color32 OtherBeamColor = new Color32 (255, 255, 255, 0); private bool original_useSystemConfig; private ERaycastMode preRaycastMode; private bool toChangeBeamMesh = true; // Should change beam mesh on start. #region basic declaration [SerializeField] private bool mForceModuleActive = true; public bool ForceModuleActive { get { return mForceModuleActive; } set { mForceModuleActive = value; } } public override bool IsModuleSupported() { return mForceModuleActive; } public override bool ShouldActivateModule() { if (!base.ShouldActivateModule ()) return false; if (mForceModuleActive) return true; return false; } public override void DeactivateModule() { base.DeactivateModule(); foreach (WVR_DeviceType _dt in Enum.GetValues(typeof(WVR_DeviceType))) { EventController _event_controller = (EventController)EventControllers [_dt]; if (_event_controller != null) { PointerEventData _ped = _event_controller.event_data; if (_ped != null) { // OnTriggerUp(); PrintDebugLog ("DeactivateModule() exit " + _ped.pointerEnter); HandlePointerExitAndEnter (_ped, null); } } } } #endregion public class EventController { public WVR_DeviceType device { get; set; } public GameObject controller { get; set; } public GameObject prevRaycastedObject { get; set; } public PointerEventData event_data { get; set; } public WaveVR_ControllerPointer pointer { get; set; } public WaveVR_Beam beam { get; set; } public bool eligibleForButtonClick { get; set; } public EventController(WVR_DeviceType type) { device = type; controller = null; prevRaycastedObject = null; event_data = null; eligibleForButtonClick = false; } } private Hashtable EventControllers = new Hashtable(); private void SetupEventController(EventController event_controller, GameObject controller_model) { LayerMask _mask = ~0; if (event_controller.controller != null) { PhysicsRaycaster _raycaster = event_controller.controller.GetComponentInChildren<PhysicsRaycaster> (); if (_raycaster != null) _mask = _raycaster.eventMask; } SetupEventController (event_controller, controller_model, _mask); } private void SetupEventController(EventController eventController, GameObject controller_model, LayerMask mask) { // Diactivate old controller, replace with new controller, activate new controller if (eventController.controller != null) { PrintDebugLog ("SetupEventController() deactivate " + eventController.controller.name); eventController.controller.SetActive (false); } eventController.controller = controller_model; if (eventController.controller != null) { PrintDebugLog ("SetupEventController() activate " + eventController.controller.name); eventController.controller.SetActive (true); // Get PhysicsRaycaster of controller. If none, add new one. PhysicsRaycaster _raycaster = eventController.controller.GetComponentInChildren<PhysicsRaycaster> (); if (_raycaster == null) { _raycaster = eventController.controller.AddComponent<PhysicsRaycaster> (); _raycaster.eventMask = mask; } // Get pointer and beam of controller. eventController.pointer = eventController.controller.GetComponentInChildren<WaveVR_ControllerPointer> (true); if (eventController.pointer != null) PrintDebugLog ("SetupEventController() found WaveVR_ControllerPointer."); eventController.beam = eventController.controller.GetComponentInChildren<WaveVR_Beam> (true); if (eventController.beam != null) { PrintDebugLog ("SetupEventController() set up WaveVR_Beam."); userBeamLength = eventController.beam.endOffset; original_useSystemConfig = eventController.beam.useSystemConfig; } Camera eventCam = eventController.controller.GetComponent<Camera>(); if (eventCam != null) { PrintDebugLog ("SetupEventController() found event camera."); eventCam.enabled = false; } } } private int GetIndexOfPointerCamera(WVR_DeviceType type) { switch(type) { case WVR_DeviceType.WVR_DeviceType_Controller_Left: return 0; case WVR_DeviceType.WVR_DeviceType_Controller_Right: return 1; default: return 0; } } private void SetupPointerCamera(WVR_DeviceType type) { if (this.Head == null) { #if UNITY_EDITOR Debug.Log(LOG_TAG + " SetupPointerCamera() no Head!!"); #endif Log.e (LOG_TAG, "SetupPointerCamera() no Head!!"); return; } if (type == WVR_DeviceType.WVR_DeviceType_Controller_Right) { pointCameraR = new GameObject ("PointerCameraR"); pointCameraR.AddComponent<WaveVR_PointerCameraTracker> (); pointCameraR.AddComponent<WaveVR_PoseTrackerManager> (); pointCameraR.AddComponent<PhysicsRaycaster> (); pointCameraR.transform.SetParent (this.Head.transform, true); if (RaycastStartPoint == ERaycastStartPoint.LeftEye) { pointCameraR.transform.localPosition = new Vector3 (-raycastStartPointOffset, 0f, 0.15f); } else if (RaycastStartPoint == ERaycastStartPoint.RightEye) { pointCameraR.transform.localPosition = new Vector3 (raycastStartPointOffset, 0f, 0.15f); } else { pointCameraR.transform.localPosition = new Vector3 (0f, 0f, 0.15f); } Camera pc = pointCameraR.GetComponent<Camera> (); if (pc != null) { pc.enabled = false; pc.fieldOfView = 1f; pc.nearClipPlane = 0.01f; } WaveVR_PointerCameraTracker pcTracker = pointCameraR.GetComponent<WaveVR_PointerCameraTracker> (); if (pcTracker != null) { pcTracker.setDeviceType (type); } WaveVR_PoseTrackerManager poseTracker = pointCameraR.GetComponent<WaveVR_PoseTrackerManager> (); if (poseTracker != null) { poseTracker.Type = type; poseTracker.TrackPosition = false; poseTracker.TrackRotation = false; poseTracker.enabled = false; } } else if (type == WVR_DeviceType.WVR_DeviceType_Controller_Left) { pointCameraL = new GameObject ("PointerCameraL"); pointCameraL.AddComponent<WaveVR_PointerCameraTracker> (); pointCameraL.AddComponent<WaveVR_PoseTrackerManager> (); pointCameraL.AddComponent<PhysicsRaycaster> (); pointCameraL.transform.SetParent (this.Head.transform, true); if (RaycastStartPoint == ERaycastStartPoint.LeftEye) { pointCameraL.transform.localPosition = new Vector3 (-raycastStartPointOffset, 0f, 0.15f); } else if (RaycastStartPoint == ERaycastStartPoint.RightEye) { pointCameraL.transform.localPosition = new Vector3 (raycastStartPointOffset, 0f, 0.15f); } else { pointCameraL.transform.localPosition = new Vector3 (0f, 0f, 0.15f); } Camera pc = pointCameraL.GetComponent<Camera> (); if (pc != null) { pc.enabled = false; pc.fieldOfView = 1f; pc.nearClipPlane = 0.01f; } WaveVR_PointerCameraTracker pcTracker = pointCameraL.GetComponent<WaveVR_PointerCameraTracker> (); if (pcTracker != null) { pcTracker.setDeviceType (type); } WaveVR_PoseTrackerManager poseTracker = pointCameraL.GetComponent<WaveVR_PoseTrackerManager> (); if (poseTracker != null) { poseTracker.Type = type; poseTracker.TrackPosition = false; poseTracker.TrackRotation = false; poseTracker.enabled = false; } } } #region Override BaseInputModule private bool enableControllerInputModule = false; protected override void OnEnable() { if (!enableControllerInputModule) { base.OnEnable (); PrintDebugLog ("OnEnable()"); enableControllerInputModule = true; foreach (WVR_DeviceType _dt in Enum.GetValues(typeof(WVR_DeviceType))) { EventControllers.Add (_dt, new EventController (_dt)); } // Right controller if (RightController != null) { SetupEventController ( (EventController)EventControllers [WVR_DeviceType.WVR_DeviceType_Controller_Right], RightController, RightRaycastMask ); } // Left controller if (LeftController != null) { SetupEventController ( (EventController)EventControllers [WVR_DeviceType.WVR_DeviceType_Controller_Left], LeftController, LeftRaycastMask ); } if (this.Head == null) { if (WaveVR_Render.Instance != null) this.Head = WaveVR_Render.Instance.gameObject; } } } protected override void OnDisable() { if (enableControllerInputModule) { base.OnDisable (); PrintDebugLog ("OnDisable()"); enableControllerInputModule = false; foreach (WVR_DeviceType _dt in Enum.GetValues(typeof(WVR_DeviceType))) { EventController _event_controller = (EventController)EventControllers [_dt]; if (_event_controller != null) { PointerEventData _ped = _event_controller.event_data; if (_ped != null) { PrintDebugLog ("OnDisable() exit " + _ped.pointerEnter); HandlePointerExitAndEnter (_ped, null); } if (_event_controller.beam != null) { _event_controller.beam.endOffset = userBeamLength; _event_controller.beam.useSystemConfig = original_useSystemConfig; this.toChangeBeamMesh = true; } } } pointCameraL = null; pointCameraR = null; EventControllers.Clear (); } } public override void Process() { if (!enableControllerInputModule) return; SetControllerModel (); SetPointerCameraTracker (); foreach (WVR_DeviceType _dt in Enum.GetValues(typeof(WVR_DeviceType))) { // -------------------- Conditions for running loop begins ----------------- // HMD uses Gaze, not controller input module. if (_dt == WVR_DeviceType.WVR_DeviceType_HMD) continue; EventController _eventController = (EventController)EventControllers [_dt]; if (_eventController == null) continue; GameObject _controller = _eventController.controller; if (_controller == null) continue; if (WaveVR.Instance != null) { if (WaveVR.Instance.FocusCapturedBySystem) { HandlePointerExitAndEnter (_eventController.event_data, null); continue; } } bool _connected = false; #if UNITY_EDITOR if (Application.isEditor) { // "connected" from WaveVR_Controller means the real connection status of controller. _connected = WaveVR_Controller.Input (_dt).connected; } else #endif { // "connected" from WaveVR means the "pose" is valid or not. WaveVR.Device _device = WaveVR.Instance.getDeviceByType (_dt); _connected = _device.connected; } if (!_connected) continue; // -------------------- Conditions for running loop ends ----------------- _eventController.prevRaycastedObject = GetRaycastedObject (_dt); if (_eventController.pointer == null) _eventController.pointer = _eventController.controller.GetComponentInChildren<WaveVR_ControllerPointer> (); if (_eventController.pointer != null) _eventController.pointer.setRaycastMode(RaycastMode); if (_connected) { if ((_dt == WVR_DeviceType.WVR_DeviceType_Controller_Left && pointCameraL == null) || (_dt == WVR_DeviceType.WVR_DeviceType_Controller_Right && pointCameraR == null)) SetupPointerCamera(_dt); } if (_eventController.beam != null && this.toChangeBeamMesh) { switch (this.RaycastMode) { case ERaycastMode.Mouse: PrintDebugLog ("Process() " + _dt + " mouse beam mode"); _eventController.beam.setRaycastMode(RaycastMode); _eventController.beam.enabled = false; _eventController.beam.EndColor = OtherBeamColor; _eventController.beam.endOffset = userBeamLength; _eventController.beam.useSystemConfig = original_useSystemConfig; _eventController.beam.enabled = true; break; case ERaycastMode.Fixed: PrintDebugLog ("Process() " + _dt + " fixed beam mode"); _eventController.beam.enabled = false; _eventController.beam.EndColor = FixedBeamColor; _eventController.beam.endOffset = FixedBeamLength; _eventController.beam.useSystemConfig = false; _eventController.beam.enabled = true; break; case ERaycastMode.Beam: PrintDebugLog ("Process() " + _dt + " flexible beam mode"); _eventController.beam.enabled = false; _eventController.beam.EndColor = OtherBeamColor; _eventController.beam.endOffset = userBeamLength; _eventController.beam.useSystemConfig = original_useSystemConfig; _eventController.beam.enabled = true; break; default: break; } } Camera _event_camera; // Mouse mode: raycasting from HMD after direct raycasting from controller if (RaycastMode == ERaycastMode.Mouse) { _event_camera = _dt == WVR_DeviceType.WVR_DeviceType_Controller_Left ? pointCameraL.GetComponent<Camera>() : pointCameraR.GetComponent<Camera>(); ResetPointerEventData_Hybrid (_dt, _event_camera); } else { _event_camera = (Camera)_controller.GetComponent (typeof(Camera)); if (_event_camera == null) continue; // Using beam of controller in Flexible & Fixed beam mode. if (_eventController.beam != null) _eventController.beam.setRaycastMode(RaycastMode); ResetPointerEventData (_dt); } // 1. Get graphic raycast object. GraphicRaycast (_eventController, _event_camera); if (GetRaycastedObject (_dt) == null) { // 2. Get physic raycast object. PhysicsRaycaster _raycaster = null; if (RaycastMode == ERaycastMode.Mouse) { _raycaster = _event_camera.GetComponent<PhysicsRaycaster>(); } else { _raycaster = _controller.GetComponent<PhysicsRaycaster>(); } if (_raycaster == null) continue; if (RaycastMode == ERaycastMode.Mouse) ResetPointerEventData_Hybrid (_dt, _event_camera); else ResetPointerEventData (_dt); PhysicRaycast (_eventController, _raycaster); } // 3. Exit previous object, enter new object. OnTriggerEnterAndExit (_dt, _eventController.event_data); // 4. Hover object. GameObject _curRaycastedObject = GetRaycastedObject (_dt); if (_curRaycastedObject != null && _curRaycastedObject == _eventController.prevRaycastedObject) { OnTriggerHover (_dt, _eventController.event_data); } // 5. Get button state. bool btnPressDown = false, btnPressed = false, btnPressUp = false; btnPressDown |= WaveVR_Controller.Input (_dt).GetPressDown ((WVR_InputId)ButtonToTrigger); btnPressed |= WaveVR_Controller.Input (_dt).GetPress ((WVR_InputId)ButtonToTrigger); btnPressUp |= WaveVR_Controller.Input (_dt).GetPressUp ((WVR_InputId)ButtonToTrigger); if (btnPressDown) _eventController.eligibleForButtonClick = true; // Pointer Click equals to Button.onClick, we sent Pointer Click in OnTriggerUp() //if (btnPressUp && _eventController.eligibleForButtonClick) //onButtonClick (_eventController); if (!btnPressDown && btnPressed) { // button hold means to drag. OnDrag (_dt, _eventController.event_data); } else if (Time.unscaledTime - _eventController.event_data.clickTime < CLICK_TIME) { // Delay new events until CLICK_TIME has passed. } else if (btnPressDown && !_eventController.event_data.eligibleForClick) { // 1. button not pressed -> pressed. // 2. no pending Click should be procced. OnTriggerDown (_dt, _eventController.event_data); } else if (!btnPressed) { // 1. If Down before, send Up event and clear Down state. // 2. If Dragging, send Drop & EndDrag event and clear Dragging state. // 3. If no Down or Dragging state, do NOTHING. OnTriggerUp (_dt, _eventController.event_data); } // Fixed beam: beam never changes, no pointer. // Mouse beam: beam never changes, pointer never changes. // Flexible beam: beam changes when pointing to different GameObject. if (RaycastMode == ERaycastMode.Beam && this.toChangeBeamMesh) { UpdateReticlePointer (_eventController); } } toChangeBeamMesh = (preRaycastMode != RaycastMode) ? true : false; preRaycastMode = RaycastMode; } #endregion private void UpdateReticlePointer(EventController event_controller) { WVR_DeviceType _type = event_controller.device; GameObject _prevObject = event_controller.prevRaycastedObject; PointerEventData _event_data = event_controller.event_data; WaveVR_ControllerPointer _pointer = event_controller.pointer; WaveVR_Beam _beam = event_controller.beam; if (_pointer != null && _beam != null) { Vector3 _intersectionPosition = GetIntersectionPosition (_event_data.enterEventCamera, _event_data.pointerCurrentRaycast); GameObject _go = GetRaycastedObject (_type); PrintDebugLog ("UpdateReticlePointer() " + event_controller.device); if (_go != null) { _pointer.SetPointerColor (new Color32 (11, 220, 249, 255)); _pointer.OnPointerEnter (_event_data.enterEventCamera, _go, _intersectionPosition, true); _beam.SetEndOffset (_intersectionPosition, false); } else { _pointer.SetPointerColor (Color.white); _pointer.OnPointerExit (_event_data.enterEventCamera, _prevObject); _beam.ResetEndOffset (); } } } #region EventSystem private void OnTriggerDown(WVR_DeviceType type, PointerEventData event_data) { GameObject _go = GetRaycastedObject (type); if (_go == null) return; // Send Pointer Down. If not received, get handler of Pointer Click. event_data.pressPosition = event_data.position; event_data.pointerPressRaycast = event_data.pointerCurrentRaycast; event_data.pointerPress = ExecuteEvents.ExecuteHierarchy(_go, event_data, ExecuteEvents.pointerDownHandler) ?? ExecuteEvents.GetEventHandler<IPointerClickHandler>(_go); PrintDebugLog ("OnTriggerDown() device: " + type + " send Pointer Down to " + event_data.pointerPress + ", current GameObject is " + _go); // If Drag Handler exists, send initializePotentialDrag event. event_data.pointerDrag = ExecuteEvents.GetEventHandler<IDragHandler>(_go); if (event_data.pointerDrag != null) { PrintDebugLog ("OnTriggerDown() device: " + type + " send initializePotentialDrag to " + event_data.pointerDrag + ", current GameObject is " + _go); ExecuteEvents.Execute(event_data.pointerDrag, event_data, ExecuteEvents.initializePotentialDrag); } // press happened (even not handled) object. event_data.rawPointerPress = _go; // allow to send Pointer Click event event_data.eligibleForClick = true; // reset the screen position of press, can be used to estimate move distance event_data.delta = Vector2.zero; // current Down, reset drag state event_data.dragging = false; event_data.useDragThreshold = true; // record the count of Pointer Click should be processed, clean when Click event is sent. event_data.clickCount = 1; // set clickTime to current time of Pointer Down instead of Pointer Click. // since Down & Up event should not be sent too closely. (< CLICK_TIME) event_data.clickTime = Time.unscaledTime; } private void OnTriggerUp(WVR_DeviceType type, PointerEventData event_data) { if (!event_data.eligibleForClick && !event_data.dragging) { // 1. no pending click // 2. no dragging // Mean user has finished all actions and do NOTHING in current frame. return; } GameObject _go = GetRaycastedObject (type); // _go may be different with event_data.pointerDrag so we don't check null if (event_data.pointerPress != null) { // In the frame of button is pressed -> unpressed, send Pointer Up PrintDebugLog ("OnTriggerUp type: " + type + " send Pointer Up to " + event_data.pointerPress); ExecuteEvents.Execute (event_data.pointerPress, event_data, ExecuteEvents.pointerUpHandler); } if (event_data.eligibleForClick) { // In the frame of button from being pressed to unpressed, send Pointer Click if Click is pending. PrintDebugLog ("OnTriggerUp type: " + type + " send Pointer Click to " + event_data.pointerPress); ExecuteEvents.Execute(event_data.pointerPress, event_data, ExecuteEvents.pointerClickHandler); } else if (event_data.dragging) { // In next frame of button from being pressed to unpressed, send Drop and EndDrag if dragging. PrintDebugLog ("OnTriggerUp type: " + type + " send Pointer Drop to " + _go + ", EndDrag to " + event_data.pointerDrag); ExecuteEvents.ExecuteHierarchy(_go, event_data, ExecuteEvents.dropHandler); ExecuteEvents.Execute(event_data.pointerDrag, event_data, ExecuteEvents.endDragHandler); event_data.pointerDrag = null; event_data.dragging = false; } // Down of pending Click object. event_data.pointerPress = null; // press happened (even not handled) object. event_data.rawPointerPress = null; // clear pending state. event_data.eligibleForClick = false; // Click is processed, clearcount. event_data.clickCount = 0; // Up is processed thus clear the time limitation of Down event. event_data.clickTime = 0; } private void OnDrag(WVR_DeviceType type, PointerEventData event_data) { if (event_data.pointerDrag != null && !event_data.dragging) { PrintDebugLog ("OnDrag() device: " + type + " send BeginDrag to " + event_data.pointerDrag); ExecuteEvents.Execute(event_data.pointerDrag, event_data, ExecuteEvents.beginDragHandler); event_data.dragging = true; } // Drag notification if (event_data.dragging && event_data.pointerDrag != null) { // Before doing drag we should cancel any pointer down state if (event_data.pointerPress != event_data.pointerDrag) { PrintDebugLog ("OnDrag device: " + type + " send Pointer Up to " + event_data.pointerPress); ExecuteEvents.Execute(event_data.pointerPress, event_data, ExecuteEvents.pointerUpHandler); // since Down state is cleaned, no Click should be processed. event_data.eligibleForClick = false; event_data.pointerPress = null; event_data.rawPointerPress = null; } /* PrintDebugLog ("OnDrag() device: " + type + " send Pointer Drag to " + event_data.pointerDrag + "camera: " + event_data.enterEventCamera + " (" + event_data.enterEventCamera.ScreenToWorldPoint ( new Vector3 ( event_data.position.x, event_data.position.y, event_data.pointerDrag.transform.position.z )) + ")"); */ ExecuteEvents.Execute(event_data.pointerDrag, event_data, ExecuteEvents.dragHandler); } } private void OnTriggerHover(WVR_DeviceType type, PointerEventData event_data) { GameObject _go = GetRaycastedObject (type); ExecuteEvents.ExecuteHierarchy(_go, event_data, WaveVR_ExecuteEvents.pointerHoverHandler); } private void OnTriggerEnterAndExit(WVR_DeviceType type, PointerEventData event_data) { GameObject _go = GetRaycastedObject (type); if (event_data.pointerEnter != _go) { PrintDebugLog ("OnTriggerEnterAndExit() enter: " + _go + ", exit: " + event_data.pointerEnter); HandlePointerExitAndEnter (event_data, _go); PrintDebugLog ("OnTriggerEnterAndExit() pointerEnter: " + event_data.pointerEnter + ", camera: " + event_data.enterEventCamera); this.toChangeBeamMesh = true; } } #endregion private void onButtonClick(EventController event_controller) { GameObject _go = GetRaycastedObject (event_controller.device); event_controller.eligibleForButtonClick = false; if (_go == null) return; Button _btn = _go.GetComponent<Button> (); if (_btn != null) { PrintDebugLog ("onButtonClick() trigger Button.onClick to " + _btn + " from " + event_controller.device); _btn.onClick.Invoke (); } else { PrintDebugLog ("onButtonClick() " + event_controller.device + ", " + _go.name + " does NOT contain Button!"); } } private void PhysicRaycast(EventController event_controller, PhysicsRaycaster raycaster) { List<RaycastResult> _raycast_results = new List<RaycastResult>(); raycaster.Raycast (event_controller.event_data, _raycast_results); RaycastResult _firstResult = FindFirstRaycast (_raycast_results); event_controller.event_data.pointerCurrentRaycast = _firstResult; #if UNITY_EDITOR if (_firstResult.module != null) { //Debug.Log ("PhysicRaycast() device: " + event_controller.device + ", camera: " + _firstResult.module.eventCamera + ", first result = " + _firstResult); } #endif if (_firstResult.gameObject != null) { if (_firstResult.worldPosition == Vector3.zero) { _firstResult.worldPosition = GetIntersectionPosition ( _firstResult.module.eventCamera, //_eventController.event_data.enterEventCamera, _firstResult ); event_controller.event_data.pointerCurrentRaycast = _firstResult; } event_controller.event_data.position = _firstResult.screenPosition; } } private void GraphicRaycast(EventController event_controller, Camera event_camera) { // --------------------- Find GUIs those can be raycasted begins. --------------------- // 1. find Canvas by TAG GameObject[] _tag_GUIs = GameObject.FindGameObjectsWithTag (CanvasTag); // 2. Get Canvas from Pointer Canvas Provider GameObject[] _event_GUIs = WaveVR_EventSystemGUIProvider.GetEventGUIs(); GameObject[] _GUIs = MergeArray (_tag_GUIs, _event_GUIs); // --------------------- Find GUIs those can be raycasted ends. --------------------- List<RaycastResult> _raycast_results = new List<RaycastResult>(); // Reset pointerCurrentRaycast even no GUI. RaycastResult _firstResult = new RaycastResult (); event_controller.event_data.pointerCurrentRaycast = _firstResult; foreach (GameObject _GUI in _GUIs) { Canvas _canvas = (Canvas)_GUI.GetComponent (typeof(Canvas)); if (_canvas == null) continue; GraphicRaycaster _gr = _canvas.GetComponent<GraphicRaycaster> (); if (_gr == null) continue; // 1. Change event camera. _canvas.worldCamera = event_camera; // 2. _gr.Raycast (event_controller.event_data, _raycast_results); _firstResult = FindFirstRaycast (_raycast_results); event_controller.event_data.pointerCurrentRaycast = _firstResult; _raycast_results.Clear (); #if UNITY_EDITOR if (_firstResult.module != null) { //Debug.Log ("GraphicRaycast() device: " + event_controller.device + ", camera: " + _firstResult.module.eventCamera + ", first result = " + _firstResult); } #endif // Found graphic raycasted object! if (_firstResult.gameObject != null) { if (_firstResult.worldPosition == Vector3.zero) { _firstResult.worldPosition = GetIntersectionPosition ( _firstResult.module.eventCamera, //_eventController.event_data.enterEventCamera, _firstResult ); event_controller.event_data.pointerCurrentRaycast = _firstResult; } event_controller.event_data.position = _firstResult.screenPosition; break; } } } private void ResetPointerEventData(WVR_DeviceType type) { EventController _eventController = (EventController)EventControllers [type]; if (_eventController != null) { if (_eventController.event_data == null) _eventController.event_data = new PointerEventData (eventSystem); _eventController.event_data.Reset (); _eventController.event_data.position = new Vector2 (0.5f * Screen.width, 0.5f * Screen.height); // center of screen } } private void ResetPointerEventData_Hybrid(WVR_DeviceType type, Camera eventCam) { EventController _eventController = (EventController)EventControllers[type]; if (_eventController != null && eventCam != null) { if (_eventController.event_data == null) _eventController.event_data = new PointerEventData(EventSystem.current); _eventController.event_data.Reset(); _eventController.event_data.position = new Vector2(0.5f * eventCam.pixelWidth, 0.5f * eventCam.pixelHeight); // center of screen } } /** * @brief get intersection position in world space **/ private Vector3 GetIntersectionPosition(Camera cam, RaycastResult raycastResult) { // Check for camera if (cam == null) { return Vector3.zero; } float intersectionDistance = raycastResult.distance + cam.nearClipPlane; Vector3 intersectionPosition = cam.transform.position + cam.transform.forward * intersectionDistance; return intersectionPosition; } private GameObject GetRaycastedObject(WVR_DeviceType type) { PointerEventData _ped = ((EventController)EventControllers [type]).event_data; if (_ped != null) return _ped.pointerCurrentRaycast.gameObject; return null; } private void SetControllerModel() { foreach (WVR_DeviceType _dt in Enum.GetValues(typeof(WVR_DeviceType))) { // HMD uses Gaze, not controller input module. if (_dt == WVR_DeviceType.WVR_DeviceType_HMD) continue; if (EventControllers [_dt] == null) continue; GameObject _controller = (GameObject)((EventController)EventControllers [_dt]).controller; GameObject _model = WaveVR_EventSystemControllerProvider.Instance.GetControllerModel (_dt); if (_controller == null) { if (_model != null) { // replace with new controller instance. PrintDebugLog("SetControllerModel() replace null with new controller instance."); SetupEventController ((EventController)EventControllers [_dt], _model); } } else { if (_model == null) { if (WaveVR_EventSystemControllerProvider.Instance.HasControllerLoader(_dt)) { // clear controller instance. PrintDebugLog("SetControllerModel() clear controller instance."); SetupEventController ((EventController)EventControllers [_dt], null); } } else { if (!GameObject.ReferenceEquals (_controller, _model)) { // replace with new controller instance. PrintDebugLog("SetControllerModel() replaced with new controller instance."); SetupEventController ((EventController)EventControllers [_dt], _model); } } } } } private void SetPointerCameraTracker() { foreach (WVR_DeviceType _dt in Enum.GetValues(typeof(WVR_DeviceType))) { // HMD uses Gaze, not controller input module. if (_dt == WVR_DeviceType.WVR_DeviceType_HMD) continue; if (EventControllers [_dt] == null) continue; WaveVR_PointerCameraTracker pcTracker = null; switch (_dt) { case WVR_DeviceType.WVR_DeviceType_Controller_Right: if (pointCameraR != null) pcTracker = pointCameraR.GetComponent<WaveVR_PointerCameraTracker> (); break; case WVR_DeviceType.WVR_DeviceType_Controller_Left: if (pointCameraL != null) pcTracker = pointCameraL.GetComponent<WaveVR_PointerCameraTracker> (); break; default: break; } if (pcTracker != null && pcTracker.reticleObject == null) { EventController _eventController = (EventController)EventControllers [_dt]; bool isConnected = true; #if UNITY_EDITOR if (Application.isEditor) { isConnected = WaveVR_Controller.Input(_dt).connected; } else #endif { WaveVR.Device _device = WaveVR.Instance.getDeviceByType (_dt); isConnected = _device.connected; } if (_eventController != null && isConnected) { if (_eventController.pointer == null && _eventController.controller != null) _eventController.pointer = _eventController.controller.GetComponentInChildren<WaveVR_ControllerPointer> (); if (_eventController.pointer != null) { pcTracker.reticleObject = _eventController.pointer.gameObject; } } } } } private GameObject[] MergeArray(GameObject[] start, GameObject[] end) { GameObject[] _merged = null; if (start == null) { if (end != null) _merged = end; } else { if (end == null) { _merged = start; } else { uint _duplicate = 0; for (int i = 0; i < start.Length; i++) { for (int j = 0; j < end.Length; j++) { if (GameObject.ReferenceEquals (start [i], end [j])) { _duplicate++; end [j] = null; } } } _merged = new GameObject[start.Length + end.Length - _duplicate]; uint _merge_index = 0; for (int i = 0; i < start.Length; i++) _merged [_merge_index++] = start [i]; for (int j = 0; j < end.Length; j++) { if (end [j] != null) _merged [_merge_index++] = end [j]; } //Array.Copy (start, _merged, start.Length); //Array.Copy (end, 0, _merged, start.Length, end.Length); } } return _merged; } }
using System; using System.Collections.Generic; using System.Text; using System.Drawing.Drawing2D; using System.Drawing; using System.ComponentModel; using Svg.Transforms; using System.Linq; namespace Svg { /// <summary> /// A pattern is used to fill or stroke an object using a pre-defined graphic object which can be replicated ("tiled") at fixed intervals in x and y to cover the areas to be painted. /// </summary> [SvgElement("pattern")] public sealed class SvgPatternServer : SvgPaintServer, ISvgViewPort, ISvgSupportsCoordinateUnits { private SvgUnit _width; private SvgUnit _height; private SvgUnit _x; private SvgUnit _y; private SvgPaintServer _inheritGradient; private SvgViewBox _viewBox; private SvgCoordinateUnits _patternUnits = SvgCoordinateUnits.Inherit; private SvgCoordinateUnits _patternContentUnits = SvgCoordinateUnits.Inherit; [SvgAttribute("overflow")] public SvgOverflow Overflow { get { return this.Attributes.GetAttribute<SvgOverflow>("overflow"); } set { this.Attributes["overflow"] = value; } } /// <summary> /// Specifies a supplemental transformation which is applied on top of any /// transformations necessary to create a new pattern coordinate system. /// </summary> [SvgAttribute("viewBox")] public SvgViewBox ViewBox { get { return this._viewBox; } set { this._viewBox = value; } } /// <summary> /// Gets or sets the aspect of the viewport. /// </summary> /// <value></value> [SvgAttribute("preserveAspectRatio")] public SvgAspectRatio AspectRatio { get; set; } /// <summary> /// Gets or sets the width of the pattern. /// </summary> [SvgAttribute("width")] public SvgUnit Width { get { return this._width; } set { this._width = value; } } /// <summary> /// Gets or sets the width of the pattern. /// </summary> [SvgAttribute("patternUnits")] public SvgCoordinateUnits PatternUnits { get { return this._patternUnits; } set { this._patternUnits = value; } } /// <summary> /// Gets or sets the width of the pattern. /// </summary> [SvgAttribute("patternContentUnits")] public SvgCoordinateUnits PatternContentUnits { get { return this._patternContentUnits; } set { this._patternContentUnits = value; } } /// <summary> /// Gets or sets the height of the pattern. /// </summary> [SvgAttribute("height")] public SvgUnit Height { get { return this._height; } set { this._height = value; } } /// <summary> /// Gets or sets the X-axis location of the pattern. /// </summary> [SvgAttribute("x")] public SvgUnit X { get { return this._x; } set { this._x = value; } } /// <summary> /// Gets or sets the Y-axis location of the pattern. /// </summary> [SvgAttribute("y")] public SvgUnit Y { get { return this._y; } set { this._y = value; } } /// <summary> /// Gets or sets another gradient fill from which to inherit the stops from. /// </summary> [SvgAttribute("href", SvgAttributeAttribute.XLinkNamespace)] public SvgPaintServer InheritGradient { get { return this._inheritGradient; } set { this._inheritGradient = value; } } [SvgAttribute("patternTransform")] public SvgTransformCollection PatternTransform { get { return (this.Attributes.GetAttribute<SvgTransformCollection>("patternTransform")); } set { this.Attributes["patternTransform"] = value; } } private Matrix EffectivePatternTransform { get { var transform = new Matrix(); if (PatternTransform != null) { transform.Multiply(PatternTransform.GetMatrix()); } return transform; } } /// <summary> /// Initializes a new instance of the <see cref="SvgPatternServer"/> class. /// </summary> public SvgPatternServer() { this._x = SvgUnit.None; this._y = SvgUnit.None; this._width = SvgUnit.None; this._height = SvgUnit.None; } private SvgUnit NormalizeUnit(SvgUnit orig) { return (orig.Type == SvgUnitType.Percentage && this.PatternUnits == SvgCoordinateUnits.ObjectBoundingBox ? new SvgUnit(SvgUnitType.User, orig.Value / 100) : orig); } /// <summary> /// Gets a <see cref="Brush"/> representing the current paint server. /// </summary> /// <param name="renderingElement">The owner <see cref="SvgVisualElement"/>.</param> /// <param name="renderer">The renderer object.</param> /// <param name="opacity">The opacity of the brush.</param> /// <param name="forStroke">Not used.</param> public override Brush GetBrush(SvgVisualElement renderingElement, ISvgRenderer renderer, float opacity, bool forStroke = false) { var chain = new List<SvgPatternServer>(); var curr = this; while (curr != null) { chain.Add(curr); curr = SvgDeferredPaintServer.TryGet<SvgPatternServer>(curr._inheritGradient, renderingElement); } var childElem = chain.Where((p) => p.Children != null && p.Children.Count > 0).FirstOrDefault(); if (childElem == null) return null; var widthElem = chain.Where((p) => p.Width != null && p.Width != SvgUnit.None).FirstOrDefault(); var heightElem = chain.Where((p) => p.Height != null && p.Height != SvgUnit.None).FirstOrDefault(); if (widthElem == null && heightElem == null) return null; var viewBoxElem = chain.Where((p) => p.ViewBox != null && p.ViewBox != SvgViewBox.Empty).FirstOrDefault(); var viewBox = viewBoxElem == null ? SvgViewBox.Empty : viewBoxElem.ViewBox; var xElem = chain.Where((p) => p.X != null && p.X != SvgUnit.None).FirstOrDefault(); var yElem = chain.Where((p) => p.Y != null && p.Y != SvgUnit.None).FirstOrDefault(); var xUnit = xElem == null ? SvgUnit.Empty : xElem.X; var yUnit = yElem == null ? SvgUnit.Empty : yElem.Y; var patternUnitElem = chain.Where((p) => p.PatternUnits != SvgCoordinateUnits.Inherit).FirstOrDefault(); var patternUnits = (patternUnitElem == null ? SvgCoordinateUnits.ObjectBoundingBox : patternUnitElem.PatternUnits); var patternContentUnitElem = chain.Where((p) => p.PatternContentUnits != SvgCoordinateUnits.Inherit).FirstOrDefault(); var patternContentUnits = (patternContentUnitElem == null ? SvgCoordinateUnits.UserSpaceOnUse : patternContentUnitElem.PatternContentUnits); try { if (patternUnits == SvgCoordinateUnits.ObjectBoundingBox) renderer.SetBoundable(renderingElement); using (var patternMatrix = new Matrix()) { var bounds = renderer.GetBoundable().Bounds; var xScale = (patternUnits == SvgCoordinateUnits.ObjectBoundingBox ? bounds.Width : 1); var yScale = (patternUnits == SvgCoordinateUnits.ObjectBoundingBox ? bounds.Height : 1); float x = xScale * NormalizeUnit(xUnit).ToDeviceValue(renderer, UnitRenderingType.Horizontal, this); float y = yScale * NormalizeUnit(yUnit).ToDeviceValue(renderer, UnitRenderingType.Vertical, this); float width = xScale * NormalizeUnit(widthElem.Width).ToDeviceValue(renderer, UnitRenderingType.Horizontal, this); float height = yScale * NormalizeUnit(heightElem.Height).ToDeviceValue(renderer, UnitRenderingType.Vertical, this); // Apply a scale if needed patternMatrix.Scale((patternContentUnits == SvgCoordinateUnits.ObjectBoundingBox ? bounds.Width : 1) * (viewBox.Width > 0 ? width / viewBox.Width : 1), (patternContentUnits == SvgCoordinateUnits.ObjectBoundingBox ? bounds.Height : 1) * (viewBox.Height > 0 ? height / viewBox.Height : 1), MatrixOrder.Prepend); Bitmap image = new Bitmap((int)width, (int)height); using (var iRenderer = SvgRenderer.FromImage(image)) { iRenderer.SetBoundable((_patternContentUnits == SvgCoordinateUnits.ObjectBoundingBox) ? new GenericBoundable(0, 0, width, height) : renderer.GetBoundable()); iRenderer.Transform = patternMatrix; iRenderer.SmoothingMode = SmoothingMode.AntiAlias; iRenderer.SetClip(new Region(new RectangleF(0, 0, viewBox.Width > 0 ? viewBox.Width : width, viewBox.Height > 0 ? viewBox.Height : height))); foreach (SvgElement child in childElem.Children) { child.RenderElement(iRenderer); } } TextureBrush textureBrush = new TextureBrush(image); var brushTransform = EffectivePatternTransform.Clone(); brushTransform.Translate(x, y, MatrixOrder.Append); textureBrush.Transform = brushTransform; return textureBrush; } } finally { if (this.PatternUnits == SvgCoordinateUnits.ObjectBoundingBox) renderer.PopBoundable(); } } public override SvgElement DeepCopy() { return DeepCopy<SvgPatternServer>(); } public override SvgElement DeepCopy<T>() { var newObj = base.DeepCopy<T>() as SvgPatternServer; newObj.Overflow = this.Overflow; newObj.ViewBox = this.ViewBox; newObj.AspectRatio = this.AspectRatio; newObj.X = this.X; newObj.Y = this.Y; newObj.Width = this.Width; newObj.Height = this.Height; return newObj; } public SvgCoordinateUnits GetUnits() { return _patternUnits; } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Reflection; using System.Timers; using log4net; using Nini.Config; using OpenMetaverse; using OpenSim.Data; using OpenSim.Framework; using OpenSim.Services.Interfaces; namespace OpenSim.Groups { public class GroupsService : GroupsServiceBase { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); public const GroupPowers DefaultEveryonePowers = GroupPowers.AllowSetHome | GroupPowers.Accountable | GroupPowers.JoinChat | GroupPowers.AllowVoiceChat | GroupPowers.ReceiveNotices | GroupPowers.StartProposal | GroupPowers.VoteOnProposal; public const GroupPowers OfficersPowers = DefaultEveryonePowers | GroupPowers.AllowFly | GroupPowers.AllowLandmark | GroupPowers.AllowRez | GroupPowers.AssignMemberLimited | GroupPowers.ChangeIdentity | GroupPowers.ChangeMedia | GroupPowers.ChangeOptions | GroupPowers.DeedObject | GroupPowers.Eject | GroupPowers.FindPlaces | GroupPowers.Invite | GroupPowers.LandChangeIdentity | GroupPowers.LandDeed | GroupPowers.LandDivideJoin | GroupPowers.LandEdit | GroupPowers.LandEjectAndFreeze | GroupPowers.LandGardening | GroupPowers.LandManageAllowed | GroupPowers.LandManageBanned | GroupPowers.LandManagePasses | GroupPowers.LandOptions | GroupPowers.LandRelease | GroupPowers.LandSetSale | GroupPowers.MemberVisible | GroupPowers.ModerateChat | GroupPowers.ObjectManipulate | GroupPowers.ObjectSetForSale | GroupPowers.ReturnGroupOwned | GroupPowers.ReturnGroupSet | GroupPowers.ReturnNonGroup | GroupPowers.RoleProperties | GroupPowers.SendNotices | GroupPowers.SetLandingPoint; public const GroupPowers OwnerPowers = OfficersPowers | GroupPowers.Accountable | GroupPowers.AllowEditLand | GroupPowers.AssignMember | GroupPowers.ChangeActions | GroupPowers.CreateRole | GroupPowers.DeleteRole | GroupPowers.ExperienceAdmin | GroupPowers.ExperienceCreator | GroupPowers.GroupBanAccess | GroupPowers.HostEvent | GroupPowers.RemoveMember; #region Daily Cleanup private Timer m_CleanupTimer; public GroupsService(IConfigSource config, string configName) : base(config, configName) { } public GroupsService(IConfigSource config) : this(config, string.Empty) { // Once a day m_CleanupTimer = new Timer(24 * 60 * 60 * 1000); m_CleanupTimer.AutoReset = true; m_CleanupTimer.Elapsed += new ElapsedEventHandler(m_CleanupTimer_Elapsed); m_CleanupTimer.Enabled = true; m_CleanupTimer.Start(); } private void m_CleanupTimer_Elapsed(object sender, ElapsedEventArgs e) { m_Database.DeleteOldNotices(); m_Database.DeleteOldInvites(); } #endregion public UUID CreateGroup(string RequestingAgentID, string name, string charter, bool showInList, UUID insigniaID, int membershipFee, bool openEnrollment, bool allowPublish, bool maturePublish, UUID founderID, out string reason) { reason = string.Empty; // Check if the group already exists if (m_Database.RetrieveGroup(name) != null) { reason = "A group with that name already exists"; return UUID.Zero; } // Create the group GroupData data = new GroupData(); data.GroupID = UUID.Random(); data.Data = new Dictionary<string, string>(); data.Data["Name"] = name; data.Data["Charter"] = charter; data.Data["InsigniaID"] = insigniaID.ToString(); data.Data["FounderID"] = founderID.ToString(); data.Data["MembershipFee"] = membershipFee.ToString(); data.Data["OpenEnrollment"] = openEnrollment ? "1" : "0"; data.Data["ShowInList"] = showInList ? "1" : "0"; data.Data["AllowPublish"] = allowPublish ? "1" : "0"; data.Data["MaturePublish"] = maturePublish ? "1" : "0"; UUID ownerRoleID = UUID.Random(); data.Data["OwnerRoleID"] = ownerRoleID.ToString(); if (!m_Database.StoreGroup(data)) return UUID.Zero; // Create Everyone role _AddOrUpdateGroupRole(RequestingAgentID, data.GroupID, UUID.Zero, "Everyone", "Everyone in the group is in the everyone role.", "Member of " + name, (ulong)DefaultEveryonePowers, true); // Create Officers role UUID officersRoleID = UUID.Random(); _AddOrUpdateGroupRole(RequestingAgentID, data.GroupID, officersRoleID, "Officers", "The officers of the group, with more powers than regular members.", "Officer of " + name, (ulong)OfficersPowers, true); // Create Owner role _AddOrUpdateGroupRole(RequestingAgentID, data.GroupID, ownerRoleID, "Owners", "Owners of the group", "Owner of " + name, (ulong)OwnerPowers, true); // Add founder to group _AddAgentToGroup(RequestingAgentID, founderID.ToString(), data.GroupID, ownerRoleID); _AddAgentToGroup(RequestingAgentID, founderID.ToString(), data.GroupID, officersRoleID); return data.GroupID; } public void UpdateGroup(string RequestingAgentID, UUID groupID, string charter, bool showInList, UUID insigniaID, int membershipFee, bool openEnrollment, bool allowPublish, bool maturePublish) { GroupData data = m_Database.RetrieveGroup(groupID); if (data == null) return; // Check perms if (!HasPower(RequestingAgentID, groupID, GroupPowers.ChangeActions)) { m_log.DebugFormat("[Groups]: ({0}) Attempt at updating group {1} denied because of lack of permission", RequestingAgentID, groupID); return; } data.GroupID = groupID; data.Data["Charter"] = charter; data.Data["ShowInList"] = showInList ? "1" : "0"; data.Data["InsigniaID"] = insigniaID.ToString(); data.Data["MembershipFee"] = membershipFee.ToString(); data.Data["OpenEnrollment"] = openEnrollment ? "1" : "0"; data.Data["AllowPublish"] = allowPublish ? "1" : "0"; data.Data["MaturePublish"] = maturePublish ? "1" : "0"; m_Database.StoreGroup(data); } public ExtendedGroupRecord GetGroupRecord(string RequestingAgentID, UUID GroupID) { GroupData data = m_Database.RetrieveGroup(GroupID); return _GroupDataToRecord(data); } public ExtendedGroupRecord GetGroupRecord(string RequestingAgentID, string GroupName) { GroupData data = m_Database.RetrieveGroup(GroupName); return _GroupDataToRecord(data); } public List<DirGroupsReplyData> FindGroups(string RequestingAgentID, string search) { List<DirGroupsReplyData> groups = new List<DirGroupsReplyData>(); GroupData[] data = m_Database.RetrieveGroups(search); if (data != null && data.Length > 0) { foreach (GroupData d in data) { // Don't list group proxies if (d.Data.ContainsKey("Location") && d.Data["Location"] != string.Empty) continue; DirGroupsReplyData g = new DirGroupsReplyData(); g.groupID = d.GroupID; if (d.Data.ContainsKey("Name")) g.groupName = d.Data["Name"]; else m_log.DebugFormat("[Groups]: Key Name not found"); g.members = m_Database.MemberCount(d.GroupID); groups.Add(g); } } return groups; } public List<ExtendedGroupMembersData> GetGroupMembers(string RequestingAgentID, UUID GroupID) { List<ExtendedGroupMembersData> members = new List<ExtendedGroupMembersData>(); GroupData group = m_Database.RetrieveGroup(GroupID); if (group == null) return members; // Unfortunately this doesn't quite work on legacy group data because of a bug // that's also being fixed here on CreateGroup. The OwnerRoleID sent to the DB was wrong. // See how to find the ownerRoleID a few lines below. UUID ownerRoleID = new UUID(group.Data["OwnerRoleID"]); RoleData[] roles = m_Database.RetrieveRoles(GroupID); if (roles == null) // something wrong with this group return members; List<RoleData> rolesList = new List<RoleData>(roles); // Let's find the "real" ownerRoleID RoleData ownerRole = rolesList.Find(r => r.Data["Powers"] == ((long)OwnerPowers).ToString()); if (ownerRole != null) ownerRoleID = ownerRole.RoleID; // Check visibility? // When we don't want to check visibility, we pass it "all" as the requestingAgentID bool checkVisibility = !RequestingAgentID.Equals(UUID.Zero.ToString()); if (checkVisibility) { // Is the requester a member of the group? bool isInGroup = false; if (m_Database.RetrieveMember(GroupID, RequestingAgentID) != null) isInGroup = true; if (!isInGroup) // reduce the roles to the visible ones rolesList = rolesList.FindAll(r => (UInt64.Parse(r.Data["Powers"]) & (ulong)GroupPowers.MemberVisible) != 0); } MembershipData[] datas = m_Database.RetrieveMembers(GroupID); if (datas == null || (datas != null && datas.Length == 0)) return members; // OK, we have everything we need foreach (MembershipData d in datas) { RoleMembershipData[] rolememberships = m_Database.RetrieveMemberRoles(GroupID, d.PrincipalID); List<RoleMembershipData> rolemembershipsList = new List<RoleMembershipData>(rolememberships); ExtendedGroupMembersData m = new ExtendedGroupMembersData(); // What's this person's current role in the group? UUID selectedRole = new UUID(d.Data["SelectedRoleID"]); RoleData selected = rolesList.Find(r => r.RoleID == selectedRole); if (selected != null) { m.Title = selected.Data["Title"]; m.AgentPowers = UInt64.Parse(selected.Data["Powers"]); } m.AgentID = d.PrincipalID; m.AcceptNotices = d.Data["AcceptNotices"] == "1" ? true : false; m.Contribution = Int32.Parse(d.Data["Contribution"]); m.ListInProfile = d.Data["ListInProfile"] == "1" ? true : false; GridUserData gud = m_GridUserService.Get(d.PrincipalID); if (gud != null) { if (bool.Parse(gud.Data["Online"])) { m.OnlineStatus = @"Online"; } else { int unixtime = int.Parse(gud.Data["Login"]); // The viewer is very picky about how these strings are formed. Eg. it will crash on malformed dates! m.OnlineStatus = (unixtime == 0) ? @"unknown" : Util.ToDateTime(unixtime).ToString("MM/dd/yyyy"); } } // Is this person an owner of the group? m.IsOwner = (rolemembershipsList.Find(r => r.RoleID == ownerRoleID) != null) ? true : false; members.Add(m); } return members; } public bool AddGroupRole(string RequestingAgentID, UUID groupID, UUID roleID, string name, string description, string title, ulong powers, out string reason) { reason = string.Empty; // check that the requesting agent has permissions to add role if (!HasPower(RequestingAgentID, groupID, GroupPowers.CreateRole)) { m_log.DebugFormat("[Groups]: ({0}) Attempt at creating role in group {1} denied because of lack of permission", RequestingAgentID, groupID); reason = "Insufficient permission to create role"; return false; } return _AddOrUpdateGroupRole(RequestingAgentID, groupID, roleID, name, description, title, powers, true); } public bool UpdateGroupRole(string RequestingAgentID, UUID groupID, UUID roleID, string name, string description, string title, ulong powers) { // check perms if (!HasPower(RequestingAgentID, groupID, GroupPowers.ChangeActions)) { m_log.DebugFormat("[Groups]: ({0}) Attempt at changing role in group {1} denied because of lack of permission", RequestingAgentID, groupID); return false; } return _AddOrUpdateGroupRole(RequestingAgentID, groupID, roleID, name, description, title, powers, false); } public void RemoveGroupRole(string RequestingAgentID, UUID groupID, UUID roleID) { // check perms if (!HasPower(RequestingAgentID, groupID, GroupPowers.DeleteRole)) { m_log.DebugFormat("[Groups]: ({0}) Attempt at deleting role from group {1} denied because of lack of permission", RequestingAgentID, groupID); return; } // Can't delete Everyone and Owners roles if (roleID == UUID.Zero) { m_log.DebugFormat("[Groups]: Attempt at deleting Everyone role from group {0} denied", groupID); return; } GroupData group = m_Database.RetrieveGroup(groupID); if (group == null) { m_log.DebugFormat("[Groups]: Attempt at deleting role from non-existing group {0}", groupID); return; } if (roleID == new UUID(group.Data["OwnerRoleID"])) { m_log.DebugFormat("[Groups]: Attempt at deleting Owners role from group {0} denied", groupID); return; } _RemoveGroupRole(groupID, roleID); } public List<GroupRolesData> GetGroupRoles(string RequestingAgentID, UUID GroupID) { // TODO: check perms return _GetGroupRoles(GroupID); } public List<ExtendedGroupRoleMembersData> GetGroupRoleMembers(string RequestingAgentID, UUID GroupID) { // TODO: check perms // Is the requester a member of the group? bool isInGroup = false; if (m_Database.RetrieveMember(GroupID, RequestingAgentID) != null) isInGroup = true; return _GetGroupRoleMembers(GroupID, isInGroup); } public bool AddAgentToGroup(string RequestingAgentID, string AgentID, UUID GroupID, UUID RoleID, string token, out string reason) { reason = string.Empty; _AddAgentToGroup(RequestingAgentID, AgentID, GroupID, RoleID, token); return true; } public bool RemoveAgentFromGroup(string RequestingAgentID, string AgentID, UUID GroupID) { // check perms if (RequestingAgentID != AgentID && !HasPower(RequestingAgentID, GroupID, GroupPowers.Eject)) return false; _RemoveAgentFromGroup(RequestingAgentID, AgentID, GroupID); return true; } public bool AddAgentToGroupInvite(string RequestingAgentID, UUID inviteID, UUID groupID, UUID roleID, string agentID) { // Check whether the invitee is already a member of the group MembershipData m = m_Database.RetrieveMember(groupID, agentID); if (m != null) return false; // Check permission to invite if (!HasPower(RequestingAgentID, groupID, GroupPowers.Invite)) { m_log.DebugFormat("[Groups]: ({0}) Attempt at inviting to group {1} denied because of lack of permission", RequestingAgentID, groupID); return false; } // Check whether there are pending invitations and delete them InvitationData invite = m_Database.RetrieveInvitation(groupID, agentID); if (invite != null) m_Database.DeleteInvite(invite.InviteID); invite = new InvitationData(); invite.InviteID = inviteID; invite.PrincipalID = agentID; invite.GroupID = groupID; invite.RoleID = roleID; invite.Data = new Dictionary<string, string>(); return m_Database.StoreInvitation(invite); } public GroupInviteInfo GetAgentToGroupInvite(string RequestingAgentID, UUID inviteID) { InvitationData data = m_Database.RetrieveInvitation(inviteID); if (data == null) return null; GroupInviteInfo inviteInfo = new GroupInviteInfo(); inviteInfo.AgentID = data.PrincipalID; inviteInfo.GroupID = data.GroupID; inviteInfo.InviteID = data.InviteID; inviteInfo.RoleID = data.RoleID; return inviteInfo; } public void RemoveAgentToGroupInvite(string RequestingAgentID, UUID inviteID) { m_Database.DeleteInvite(inviteID); } public bool AddAgentToGroupRole(string RequestingAgentID, string AgentID, UUID GroupID, UUID RoleID) { //if (!m_Database.CheckOwnerRole(RequestingAgentID, GroupID, RoleID)) // return; // check permissions bool limited = HasPower(RequestingAgentID, GroupID, GroupPowers.AssignMemberLimited); bool unlimited = HasPower(RequestingAgentID, GroupID, GroupPowers.AssignMember) | IsOwner(RequestingAgentID, GroupID); if (!limited && !unlimited) { m_log.DebugFormat("[Groups]: ({0}) Attempt at assigning {1} to role {2} denied because of lack of permission", RequestingAgentID, AgentID, RoleID); return false; } // AssignMemberLimited means that the person can assign another person to the same roles that she has in the group if (!unlimited && limited) { // check whether person's has this role RoleMembershipData rolemembership = m_Database.RetrieveRoleMember(GroupID, RoleID, RequestingAgentID); if (rolemembership == null) { m_log.DebugFormat("[Groups]: ({0}) Attempt at assigning {1} to role {2} denied because of limited permission", RequestingAgentID, AgentID, RoleID); return false; } } _AddAgentToGroupRole(RequestingAgentID, AgentID, GroupID, RoleID); return true; } public bool RemoveAgentFromGroupRole(string RequestingAgentID, string AgentID, UUID GroupID, UUID RoleID) { // Don't remove from Everyone role! if (RoleID == UUID.Zero) return false; // check permissions bool limited = HasPower(RequestingAgentID, GroupID, GroupPowers.AssignMemberLimited); bool unlimited = HasPower(RequestingAgentID, GroupID, GroupPowers.AssignMember) || IsOwner(RequestingAgentID, GroupID); if (!limited && !unlimited) { m_log.DebugFormat("[Groups]: ({0}) Attempt at removing {1} from role {2} denied because of lack of permission", RequestingAgentID, AgentID, RoleID); return false; } // AssignMemberLimited means that the person can assign another person to the same roles that she has in the group if (!unlimited && limited) { // check whether person's has this role RoleMembershipData rolemembership = m_Database.RetrieveRoleMember(GroupID, RoleID, RequestingAgentID); if (rolemembership == null) { m_log.DebugFormat("[Groups]: ({0}) Attempt at removing {1} from role {2} denied because of limited permission", RequestingAgentID, AgentID, RoleID); return false; } } RoleMembershipData rolemember = m_Database.RetrieveRoleMember(GroupID, RoleID, AgentID); if (rolemember == null) return false; m_Database.DeleteRoleMember(rolemember); // Find another role for this person UUID newRoleID = UUID.Zero; // Everyone RoleMembershipData[] rdata = m_Database.RetrieveMemberRoles(GroupID, AgentID); if (rdata != null) foreach (RoleMembershipData r in rdata) { if (r.RoleID != UUID.Zero) { newRoleID = r.RoleID; break; } } MembershipData member = m_Database.RetrieveMember(GroupID, AgentID); if (member != null) { member.Data["SelectedRoleID"] = newRoleID.ToString(); m_Database.StoreMember(member); } return true; } public List<GroupRolesData> GetAgentGroupRoles(string RequestingAgentID, string AgentID, UUID GroupID) { List<GroupRolesData> roles = new List<GroupRolesData>(); // TODO: check permissions RoleMembershipData[] data = m_Database.RetrieveMemberRoles(GroupID, AgentID); if (data == null || (data != null && data.Length ==0)) return roles; foreach (RoleMembershipData d in data) { RoleData rdata = m_Database.RetrieveRole(GroupID, d.RoleID); if (rdata == null) // hippos continue; GroupRolesData r = new GroupRolesData(); r.Name = rdata.Data["Name"]; r.Powers = UInt64.Parse(rdata.Data["Powers"]); r.RoleID = rdata.RoleID; r.Title = rdata.Data["Title"]; roles.Add(r); } return roles; } public ExtendedGroupMembershipData SetAgentActiveGroup(string RequestingAgentID, string AgentID, UUID GroupID) { // TODO: check perms PrincipalData principal = new PrincipalData(); principal.PrincipalID = AgentID; principal.ActiveGroupID = GroupID; m_Database.StorePrincipal(principal); return GetAgentGroupMembership(RequestingAgentID, AgentID, GroupID); } public ExtendedGroupMembershipData GetAgentActiveMembership(string RequestingAgentID, string AgentID) { // 1. get the principal data for the active group PrincipalData principal = m_Database.RetrievePrincipal(AgentID); if (principal == null) return null; return GetAgentGroupMembership(RequestingAgentID, AgentID, principal.ActiveGroupID); } public ExtendedGroupMembershipData GetAgentGroupMembership(string RequestingAgentID, string AgentID, UUID GroupID) { return GetAgentGroupMembership(RequestingAgentID, AgentID, GroupID, null); } private ExtendedGroupMembershipData GetAgentGroupMembership(string RequestingAgentID, string AgentID, UUID GroupID, MembershipData membership) { // 2. get the active group GroupData group = m_Database.RetrieveGroup(GroupID); if (group == null) return null; // 3. get the membership info if we don't have it already if (membership == null) { membership = m_Database.RetrieveMember(group.GroupID, AgentID); if (membership == null) return null; } // 4. get the active role UUID activeRoleID = new UUID(membership.Data["SelectedRoleID"]); RoleData role = m_Database.RetrieveRole(group.GroupID, activeRoleID); ExtendedGroupMembershipData data = new ExtendedGroupMembershipData(); data.AcceptNotices = membership.Data["AcceptNotices"] == "1" ? true : false; data.AccessToken = membership.Data["AccessToken"]; data.Active = true; data.ActiveRole = activeRoleID; data.AllowPublish = group.Data["AllowPublish"] == "1" ? true : false; data.Charter = group.Data["Charter"]; data.Contribution = Int32.Parse(membership.Data["Contribution"]); data.FounderID = new UUID(group.Data["FounderID"]); data.GroupID = new UUID(group.GroupID); data.GroupName = group.Data["Name"]; data.GroupPicture = new UUID(group.Data["InsigniaID"]); if (role != null) { data.GroupPowers = UInt64.Parse(role.Data["Powers"]); data.GroupTitle = role.Data["Title"]; } data.ListInProfile = membership.Data["ListInProfile"] == "1" ? true : false; data.MaturePublish = group.Data["MaturePublish"] == "1" ? true : false; data.MembershipFee = Int32.Parse(group.Data["MembershipFee"]); data.OpenEnrollment = group.Data["OpenEnrollment"] == "1" ? true : false; data.ShowInList = group.Data["ShowInList"] == "1" ? true : false; return data; } public List<GroupMembershipData> GetAgentGroupMemberships(string RequestingAgentID, string AgentID) { List<GroupMembershipData> memberships = new List<GroupMembershipData>(); // 1. Get all the groups that this person is a member of MembershipData[] mdata = m_Database.RetrieveMemberships(AgentID); if (mdata == null || (mdata != null && mdata.Length == 0)) return memberships; foreach (MembershipData d in mdata) { GroupMembershipData gmember = GetAgentGroupMembership(RequestingAgentID, AgentID, d.GroupID, d); if (gmember != null) { memberships.Add(gmember); //m_log.DebugFormat("[XXX]: Member of {0} as {1}", gmember.GroupName, gmember.GroupTitle); //Util.PrintCallStack(); } } return memberships; } public void SetAgentActiveGroupRole(string RequestingAgentID, string AgentID, UUID GroupID, UUID RoleID) { MembershipData data = m_Database.RetrieveMember(GroupID, AgentID); if (data == null) return; data.Data["SelectedRoleID"] = RoleID.ToString(); m_Database.StoreMember(data); } public void UpdateMembership(string RequestingAgentID, string AgentID, UUID GroupID, bool AcceptNotices, bool ListInProfile) { // TODO: check perms MembershipData membership = m_Database.RetrieveMember(GroupID, AgentID); if (membership == null) return; membership.Data["AcceptNotices"] = AcceptNotices ? "1" : "0"; membership.Data["ListInProfile"] = ListInProfile ? "1" : "0"; m_Database.StoreMember(membership); } public bool AddGroupNotice(string RequestingAgentID, UUID groupID, UUID noticeID, string fromName, string subject, string message, bool hasAttachment, byte attType, string attName, UUID attItemID, string attOwnerID) { // Check perms if (!HasPower(RequestingAgentID, groupID, GroupPowers.SendNotices)) { m_log.DebugFormat("[Groups]: ({0}) Attempt at sending notice to group {1} denied because of lack of permission", RequestingAgentID, groupID); return false; } return _AddNotice(groupID, noticeID, fromName, subject, message, hasAttachment, attType, attName, attItemID, attOwnerID); } public GroupNoticeInfo GetGroupNotice(string RequestingAgentID, UUID noticeID) { NoticeData data = m_Database.RetrieveNotice(noticeID); if (data == null) return null; return _NoticeDataToInfo(data); } public List<ExtendedGroupNoticeData> GetGroupNotices(string RequestingAgentID, UUID groupID) { NoticeData[] data = m_Database.RetrieveNotices(groupID); List<ExtendedGroupNoticeData> infos = new List<ExtendedGroupNoticeData>(); if (data == null || (data != null && data.Length == 0)) return infos; foreach (NoticeData d in data) { ExtendedGroupNoticeData info = _NoticeDataToData(d); infos.Add(info); } return infos; } public void ResetAgentGroupChatSessions(string agentID) { } public bool hasAgentBeenInvitedToGroupChatSession(string agentID, UUID groupID) { return false; } public bool hasAgentDroppedGroupChatSession(string agentID, UUID groupID) { return false; } public void AgentDroppedFromGroupChatSession(string agentID, UUID groupID) { } public void AgentInvitedToGroupChatSession(string agentID, UUID groupID) { } #region Actions without permission checks protected void _AddAgentToGroup(string RequestingAgentID, string AgentID, UUID GroupID, UUID RoleID) { _AddAgentToGroup(RequestingAgentID, AgentID, GroupID, RoleID, string.Empty); } protected void _RemoveAgentFromGroup(string RequestingAgentID, string AgentID, UUID GroupID) { // 1. Delete membership m_Database.DeleteMember(GroupID, AgentID); // 2. Remove from rolememberships m_Database.DeleteMemberAllRoles(GroupID, AgentID); // 3. if it was active group, inactivate it PrincipalData principal = m_Database.RetrievePrincipal(AgentID); if (principal != null && principal.ActiveGroupID == GroupID) { principal.ActiveGroupID = UUID.Zero; m_Database.StorePrincipal(principal); } } protected void _AddAgentToGroup(string RequestingAgentID, string AgentID, UUID GroupID, UUID RoleID, string accessToken) { // Check if it's already there MembershipData data = m_Database.RetrieveMember(GroupID, AgentID); if (data != null) return; // Add the membership data = new MembershipData(); data.PrincipalID = AgentID; data.GroupID = GroupID; data.Data = new Dictionary<string, string>(); data.Data["SelectedRoleID"] = RoleID.ToString(); data.Data["Contribution"] = "0"; data.Data["ListInProfile"] = "1"; data.Data["AcceptNotices"] = "1"; data.Data["AccessToken"] = accessToken; m_Database.StoreMember(data); // Add principal to everyone role _AddAgentToGroupRole(RequestingAgentID, AgentID, GroupID, UUID.Zero); // Add principal to role, if different from everyone role if (RoleID != UUID.Zero) _AddAgentToGroupRole(RequestingAgentID, AgentID, GroupID, RoleID); // Make this the active group PrincipalData pdata = new PrincipalData(); pdata.PrincipalID = AgentID; pdata.ActiveGroupID = GroupID; m_Database.StorePrincipal(pdata); } protected bool _AddOrUpdateGroupRole(string RequestingAgentID, UUID groupID, UUID roleID, string name, string description, string title, ulong powers, bool add) { RoleData data = m_Database.RetrieveRole(groupID, roleID); if (add && data != null) // it already exists, can't create { m_log.DebugFormat("[Groups]: Group {0} already exists. Can't create it again", groupID); return false; } if (!add && data == null) // it doesn't exist, can't update { m_log.DebugFormat("[Groups]: Group {0} doesn't exist. Can't update it", groupID); return false; } if (add) data = new RoleData(); data.GroupID = groupID; data.RoleID = roleID; data.Data = new Dictionary<string, string>(); data.Data["Name"] = name; data.Data["Description"] = description; data.Data["Title"] = title; data.Data["Powers"] = powers.ToString(); return m_Database.StoreRole(data); } protected void _RemoveGroupRole(UUID groupID, UUID roleID) { m_Database.DeleteRole(groupID, roleID); } protected void _AddAgentToGroupRole(string RequestingAgentID, string AgentID, UUID GroupID, UUID RoleID) { RoleMembershipData data = m_Database.RetrieveRoleMember(GroupID, RoleID, AgentID); if (data != null) return; data = new RoleMembershipData(); data.GroupID = GroupID; data.PrincipalID = AgentID; data.RoleID = RoleID; m_Database.StoreRoleMember(data); // Make it the SelectedRoleID MembershipData membership = m_Database.RetrieveMember(GroupID, AgentID); if (membership == null) { m_log.DebugFormat("[Groups]: ({0}) No such member {0} in group {1}", AgentID, GroupID); return; } membership.Data["SelectedRoleID"] = RoleID.ToString(); m_Database.StoreMember(membership); } protected List<GroupRolesData> _GetGroupRoles(UUID groupID) { List<GroupRolesData> roles = new List<GroupRolesData>(); RoleData[] data = m_Database.RetrieveRoles(groupID); if (data == null || (data != null && data.Length == 0)) return roles; foreach (RoleData d in data) { GroupRolesData r = new GroupRolesData(); r.Description = d.Data["Description"]; r.Members = m_Database.RoleMemberCount(groupID, d.RoleID); r.Name = d.Data["Name"]; r.Powers = UInt64.Parse(d.Data["Powers"]); r.RoleID = d.RoleID; r.Title = d.Data["Title"]; roles.Add(r); } return roles; } protected List<ExtendedGroupRoleMembersData> _GetGroupRoleMembers(UUID GroupID, bool isInGroup) { List<ExtendedGroupRoleMembersData> rmembers = new List<ExtendedGroupRoleMembersData>(); RoleData[] rdata = new RoleData[0]; if (!isInGroup) { rdata = m_Database.RetrieveRoles(GroupID); if (rdata == null || (rdata != null && rdata.Length == 0)) return rmembers; } List<RoleData> rlist = new List<RoleData>(rdata); if (!isInGroup) rlist = rlist.FindAll(r => (UInt64.Parse(r.Data["Powers"]) & (ulong)GroupPowers.MemberVisible) != 0); RoleMembershipData[] data = m_Database.RetrieveRolesMembers(GroupID); if (data == null || (data != null && data.Length == 0)) return rmembers; foreach (RoleMembershipData d in data) { if (!isInGroup) { RoleData rd = rlist.Find(_r => _r.RoleID == d.RoleID); // visible role if (rd == null) continue; } ExtendedGroupRoleMembersData r = new ExtendedGroupRoleMembersData(); r.MemberID = d.PrincipalID; r.RoleID = d.RoleID; rmembers.Add(r); } return rmembers; } protected bool _AddNotice(UUID groupID, UUID noticeID, string fromName, string subject, string message, bool hasAttachment, byte attType, string attName, UUID attItemID, string attOwnerID) { NoticeData data = new NoticeData(); data.GroupID = groupID; data.NoticeID = noticeID; data.Data = new Dictionary<string, string>(); data.Data["FromName"] = fromName; data.Data["Subject"] = subject; data.Data["Message"] = message; data.Data["HasAttachment"] = hasAttachment ? "1" : "0"; if (hasAttachment) { data.Data["AttachmentType"] = attType.ToString(); data.Data["AttachmentName"] = attName; data.Data["AttachmentItemID"] = attItemID.ToString(); data.Data["AttachmentOwnerID"] = attOwnerID; } data.Data["TMStamp"] = ((uint)Util.UnixTimeSinceEpoch()).ToString(); return m_Database.StoreNotice(data); } #endregion #region structure translations ExtendedGroupRecord _GroupDataToRecord(GroupData data) { if (data == null) return null; ExtendedGroupRecord rec = new ExtendedGroupRecord(); rec.AllowPublish = data.Data["AllowPublish"] == "1" ? true : false; rec.Charter = data.Data["Charter"]; rec.FounderID = new UUID(data.Data["FounderID"]); rec.GroupID = data.GroupID; rec.GroupName = data.Data["Name"]; rec.GroupPicture = new UUID(data.Data["InsigniaID"]); rec.MaturePublish = data.Data["MaturePublish"] == "1" ? true : false; rec.MembershipFee = Int32.Parse(data.Data["MembershipFee"]); rec.OpenEnrollment = data.Data["OpenEnrollment"] == "1" ? true : false; rec.OwnerRoleID = new UUID(data.Data["OwnerRoleID"]); rec.ShowInList = data.Data["ShowInList"] == "1" ? true : false; rec.ServiceLocation = data.Data["Location"]; rec.MemberCount = m_Database.MemberCount(data.GroupID); rec.RoleCount = m_Database.RoleCount(data.GroupID); return rec; } GroupNoticeInfo _NoticeDataToInfo(NoticeData data) { GroupNoticeInfo notice = new GroupNoticeInfo(); notice.GroupID = data.GroupID; notice.Message = data.Data["Message"]; notice.noticeData = _NoticeDataToData(data); return notice; } ExtendedGroupNoticeData _NoticeDataToData(NoticeData data) { ExtendedGroupNoticeData notice = new ExtendedGroupNoticeData(); notice.FromName = data.Data["FromName"]; notice.NoticeID = data.NoticeID; notice.Subject = data.Data["Subject"]; notice.Timestamp = uint.Parse((string)data.Data["TMStamp"]); notice.HasAttachment = data.Data["HasAttachment"] == "1" ? true : false; if (notice.HasAttachment) { notice.AttachmentName = data.Data["AttachmentName"]; notice.AttachmentItemID = new UUID(data.Data["AttachmentItemID"].ToString()); notice.AttachmentType = byte.Parse(data.Data["AttachmentType"].ToString()); notice.AttachmentOwnerID = data.Data["AttachmentOwnerID"].ToString(); } return notice; } #endregion #region permissions private bool HasPower(string agentID, UUID groupID, GroupPowers power) { RoleMembershipData[] rmembership = m_Database.RetrieveMemberRoles(groupID, agentID); if (rmembership == null || (rmembership != null && rmembership.Length == 0)) return false; foreach (RoleMembershipData rdata in rmembership) { RoleData role = m_Database.RetrieveRole(groupID, rdata.RoleID); if ( (UInt64.Parse(role.Data["Powers"]) & (ulong)power) != 0 ) return true; } return false; } private bool IsOwner(string agentID, UUID groupID) { GroupData group = m_Database.RetrieveGroup(groupID); if (group == null) return false; RoleMembershipData rmembership = m_Database.RetrieveRoleMember(groupID, new UUID(group.Data["OwnerRoleID"]), agentID); if (rmembership == null) return false; return true; } #endregion } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Web.Http.Description; using System.Xml.Linq; using Newtonsoft.Json; namespace Api.Receiver.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>> { DefaultSampleObjectFactory, }; } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order, /// stopping when the factory successfully returns a non-<see langref="null"/> object. /// </summary> /// <remarks> /// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use /// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and /// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames. // If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames. // If still not found, try to get the sample provided for the specified mediaType and type. // Finally, try to get the sample provided for the specified mediaType. if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create /// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other /// factories in <see cref="SampleObjectFactories"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")] public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // No specific object available, try our factories. foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories) { if (factory == null) { continue; } try { sampleObject = factory(this, type); if (sampleObject != null) { break; } } catch { // Ignore any problems encountered in the factory; go on to the next one (if any). } } } return sampleObject; } /// <summary> /// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The type.</returns> public virtual Type ResolveHttpRequestMessageType(ApiDescription api) { string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters); } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, UnwrapException(e).Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } internal static Exception UnwrapException(Exception exception) { AggregateException aggregateException = exception as AggregateException; if (aggregateException != null) { return aggregateException.Flatten().InnerException; } return exception; } // Default factory for sample objects private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type) { // Try to create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. // Template Source: Templates\CSharp\Requests\EntityCollectionRequest.cs.tt namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.Net.Http; using System.Threading; using System.Linq.Expressions; /// <summary> /// The type GraphServiceSubscriptionsCollectionRequest. /// </summary> public partial class GraphServiceSubscriptionsCollectionRequest : BaseRequest, IGraphServiceSubscriptionsCollectionRequest { /// <summary> /// Constructs a new GraphServiceSubscriptionsCollectionRequest. /// </summary> /// <param name="requestUrl">The URL for the built request.</param> /// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param> /// <param name="options">Query and header option name value pairs for the request.</param> public GraphServiceSubscriptionsCollectionRequest( string requestUrl, IBaseClient client, IEnumerable<Option> options) : base(requestUrl, client, options) { } /// <summary> /// Adds the specified Subscription to the collection via POST. /// </summary> /// <param name="subscription">The Subscription to add.</param> /// <returns>The created Subscription.</returns> public System.Threading.Tasks.Task<Subscription> AddAsync(Subscription subscription) { return this.AddAsync(subscription, CancellationToken.None); } /// <summary> /// Adds the specified Subscription to the collection via POST. /// </summary> /// <param name="subscription">The Subscription to add.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The created Subscription.</returns> public System.Threading.Tasks.Task<Subscription> AddAsync(Subscription subscription, CancellationToken cancellationToken) { this.ContentType = "application/json"; this.Method = "POST"; return this.SendAsync<Subscription>(subscription, cancellationToken); } /// <summary> /// Gets the collection page. /// </summary> /// <returns>The collection page.</returns> public System.Threading.Tasks.Task<IGraphServiceSubscriptionsCollectionPage> GetAsync() { return this.GetAsync(CancellationToken.None); } /// <summary> /// Gets the collection page. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The collection page.</returns> public async System.Threading.Tasks.Task<IGraphServiceSubscriptionsCollectionPage> GetAsync(CancellationToken cancellationToken) { this.Method = "GET"; var response = await this.SendAsync<GraphServiceSubscriptionsCollectionResponse>(null, cancellationToken).ConfigureAwait(false); if (response != null && response.Value != null && response.Value.CurrentPage != null) { if (response.AdditionalData != null) { object nextPageLink; response.AdditionalData.TryGetValue("@odata.nextLink", out nextPageLink); var nextPageLinkString = nextPageLink as string; if (!string.IsNullOrEmpty(nextPageLinkString)) { response.Value.InitializeNextPageRequest( this.Client, nextPageLinkString); } // Copy the additional data collection to the page itself so that information is not lost response.Value.AdditionalData = response.AdditionalData; } return response.Value; } return null; } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="value">The expand value.</param> /// <returns>The request object to send.</returns> public IGraphServiceSubscriptionsCollectionRequest Expand(string value) { this.QueryOptions.Add(new QueryOption("$expand", value)); return this; } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="expandExpression">The expression from which to calculate the expand value.</param> /// <returns>The request object to send.</returns> public IGraphServiceSubscriptionsCollectionRequest Expand(Expression<Func<Subscription, object>> expandExpression) { if (expandExpression == null) { throw new ArgumentNullException(nameof(expandExpression)); } string error; string value = ExpressionExtractHelper.ExtractMembers(expandExpression, out error); if (value == null) { throw new ArgumentException(error, nameof(expandExpression)); } else { this.QueryOptions.Add(new QueryOption("$expand", value)); } return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="value">The select value.</param> /// <returns>The request object to send.</returns> public IGraphServiceSubscriptionsCollectionRequest Select(string value) { this.QueryOptions.Add(new QueryOption("$select", value)); return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="selectExpression">The expression from which to calculate the select value.</param> /// <returns>The request object to send.</returns> public IGraphServiceSubscriptionsCollectionRequest Select(Expression<Func<Subscription, object>> selectExpression) { if (selectExpression == null) { throw new ArgumentNullException(nameof(selectExpression)); } string error; string value = ExpressionExtractHelper.ExtractMembers(selectExpression, out error); if (value == null) { throw new ArgumentException(error, nameof(selectExpression)); } else { this.QueryOptions.Add(new QueryOption("$select", value)); } return this; } /// <summary> /// Adds the specified top value to the request. /// </summary> /// <param name="value">The top value.</param> /// <returns>The request object to send.</returns> public IGraphServiceSubscriptionsCollectionRequest Top(int value) { this.QueryOptions.Add(new QueryOption("$top", value.ToString())); return this; } /// <summary> /// Adds the specified filter value to the request. /// </summary> /// <param name="value">The filter value.</param> /// <returns>The request object to send.</returns> public IGraphServiceSubscriptionsCollectionRequest Filter(string value) { this.QueryOptions.Add(new QueryOption("$filter", value)); return this; } /// <summary> /// Adds the specified skip value to the request. /// </summary> /// <param name="value">The skip value.</param> /// <returns>The request object to send.</returns> public IGraphServiceSubscriptionsCollectionRequest Skip(int value) { this.QueryOptions.Add(new QueryOption("$skip", value.ToString())); return this; } /// <summary> /// Adds the specified orderby value to the request. /// </summary> /// <param name="value">The orderby value.</param> /// <returns>The request object to send.</returns> public IGraphServiceSubscriptionsCollectionRequest OrderBy(string value) { this.QueryOptions.Add(new QueryOption("$orderby", value)); return this; } } }
#region Copyright /*Copyright (C) 2015 Konstantin Udilovich Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #endregion using System; using Kodestruct.Common.Entities; using Kodestruct.Wood.NDS.Entities; namespace Kodestruct.Wood.NDS.NDS2015 { public partial class SawnLumberMember : WoodMember { public double GetFlatUseFactor( double Depth, double Thickness, SawnLumberType SawnLumberType, CommercialGrade CommercialGrade, ReferenceDesignValueType ReferenceDesignValueType ) { double b = Depth; double C_fu = 1.0; if (b >= 2 || b <= 4) { C_fu = GetFlatUseCoefficientFromReferenceTable( Depth, Thickness, SawnLumberType, CommercialGrade, ReferenceDesignValueType); } return C_fu; } private double GetFlatUseCoefficientFromReferenceTable( double Depth, double Thickness, SawnLumberType SawnLumberType, CommercialGrade CommercialGrade, ReferenceDesignValueType ReferenceDesignValueType ) { double b = Depth; double t = Thickness; double C_fu = 1.0; switch (SawnLumberType) { case SawnLumberType.DimensionLumber: C_fu = GetDimensionalLumberC_fu(b, t); break;//4A case SawnLumberType.SouthernPineDimensionLumber://4B C_fu = GetSPDimensionalLumberC_fu(b, t); break; case SawnLumberType.MechanicallyGradedDimensionLumber: //4C C_fu = GetMechanicallyGradedLumberC_fu(b, t); break; case SawnLumberType.VisuallyGradedTimbers: //4D C_fu = GetTimberC_fu(b, t, CommercialGrade, ReferenceDesignValueType); break; case SawnLumberType.VisuallyGradedDecking: //4E C_fu = GetDeckingC_fu(); break; case SawnLumberType.NonNorthAmericanVisuallyGradedDimensionLumber: //4F C_fu = GetNonNorthAmericanLumberC_fu(b, t); break; default://4A C_fu = GetDimensionalLumberC_fu(b, t); break; } return C_fu; } private double GetTimberC_fu(double b, double t, CommercialGrade CommercialGrade, ReferenceDesignValueType ReferenceDesignValueType) { double C_fu = 1.0; if (CommercialGrade == Entities.CommercialGrade.SelectStructural) { if (ReferenceDesignValueType == Entities.ReferenceDesignValueType.Bending) { C_fu = 0.86; } else if (ReferenceDesignValueType == ReferenceDesignValueType.ModulusOfElasticityMin || ReferenceDesignValueType == ReferenceDesignValueType.ModulusOfElasticityMin) { C_fu = 1.0; } else { C_fu = 1.0; } } if (CommercialGrade == Entities.CommercialGrade.No2) { if (ReferenceDesignValueType == Entities.ReferenceDesignValueType.Bending) { C_fu =1.0; } else if (ReferenceDesignValueType == ReferenceDesignValueType.ModulusOfElasticityMin || ReferenceDesignValueType == ReferenceDesignValueType.ModulusOfElasticityMin) { C_fu = 1.0; } else { C_fu = 1.0; } } else { //(CommercialGrade == Entities.CommercialGrade.No1) if (ReferenceDesignValueType == Entities.ReferenceDesignValueType.Bending) { C_fu =0.74; } else if (ReferenceDesignValueType == ReferenceDesignValueType.ModulusOfElasticityMin || ReferenceDesignValueType == ReferenceDesignValueType.ModulusOfElasticityMin) { C_fu = 0.9; } else { C_fu = 1.0; } } return C_fu; } private double GetNonNorthAmericanLumberC_fu(double Depth, double Thickness) { double b = Math.Round(Depth); double t = Thickness; double C_fu = 1.0; if (b <= 3) { if (t < 4) { C_fu = 1.0; } else { C_fu = 1.0; } } if (b == 4) { if (t < 4) { C_fu = 1.1; } else { C_fu = 1.0; } } if (b == 5) { if (t < 4) { C_fu = 1.1; } else { C_fu = 1.05; } } if (b == 6) { if (t < 4) { C_fu = 1.15; } else { C_fu = 1.05; } } if (b == 8) { if (t < 4) { C_fu = 1.15; } else { C_fu = 1.05; } } if (b <= 10) { if (t < 4) { C_fu = 1.2; } else { C_fu = 1.1; } } return C_fu; } private double GetDeckingC_fu() { return 1.0; } private double GetMechanicallyGradedLumberC_fu(double Depth, double Thickness) { double b = Math.Round(Depth); double t = Thickness; double C_fu = 1.0; if (b <= 3) { C_fu = 1.0; } if (b == 4) { C_fu = 1.1; } if (b == 5) { C_fu = 1.1; } if (b == 6) { C_fu = 1.15; } if (b == 8) { C_fu = 1.15; } if (b >= 10){ C_fu = 1.2; } return C_fu; } private double GetSPDimensionalLumberC_fu(double Depth, double Thickness) { double b = Math.Round(Depth); double t = Thickness; double C_fu = 1.0; if (b <= 3) { if (t < 4) { C_fu = 1.0; } else { C_fu = 1.0; } } if (b == 4) { if (t < 4) { C_fu = 1.1; } else { C_fu = 1.0; } } if (b == 5) { if (t < 4) { C_fu = 1.1; } else { C_fu = 1.05; } } if (b == 6) { if (t < 4) { C_fu = 1.15; } else { C_fu = 1.05; } } if (b == 8) { if (t < 4) { C_fu = 1.15; } else { C_fu = 1.05; } } if (b <= 10) { if (t < 4) { C_fu = 1.2; } else { C_fu = 1.1; } } return C_fu; } private double GetDimensionalLumberC_fu(double Depth, double Thickness) { double b = Math.Round(Depth); double t = Thickness; double C_fu = 1.0; if(b<= 3 ) {if (t<4) { C_fu = 1.0 ;} else { C_fu = 1.0 ;}} if(b== 4 ) {if (t< 4) { C_fu = 1.1 ;} else { C_fu = 1.0 ;}} if(b== 5 ) {if (t< 4) { C_fu = 1.1 ;} else { C_fu = 1.05 ;}} if(b== 6 ) {if (t< 4) { C_fu = 1.15;} else { C_fu = 1.05;}} if(b== 8 ) {if (t< 4) { C_fu = 1.15;} else { C_fu = 1.05;}} if(b<=10) {if (t<4) { C_fu = 1.2 ;} else { C_fu = 1.1 ;}} return C_fu; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Net.Security; using System.Runtime.InteropServices; using System.Security.Authentication; using Microsoft.Win32.SafeHandles; using SafeSslHandle = System.Net.SafeSslHandle; internal static partial class Interop { internal static partial class AppleCrypto { private static readonly IdnMapping s_idnMapping = new IdnMapping(); // Read data from connection (or an instance delegate captured context) and write it to data // dataLength comes in as the capacity of data, goes out as bytes written. // Note: the true type of dataLength is `size_t*`, but on macOS that's most equal to `void**` internal unsafe delegate int SSLReadFunc(void* connection, byte* data, void** dataLength); // (In the C decl for this function data is "const byte*", justifying the second type). // Read *dataLength from data and write it to connection (or an instance delegate captured context), // and set *dataLength to the number of bytes actually transferred. internal unsafe delegate int SSLWriteFunc(void* connection, byte* data, void** dataLength); private static readonly SafeCreateHandle s_cfHttp2Str = CoreFoundation.CFStringCreateWithCString("h2"); private static readonly SafeCreateHandle s_cfHttp11Str = CoreFoundation.CFStringCreateWithCString("http/1.1"); private static readonly IntPtr[] s_cfAlpnHttp2Protocol = new IntPtr[] { s_cfHttp2Str.DangerousGetHandle() }; private static readonly IntPtr[] s_cfAlpnHttp11Protocol = new IntPtr[] { s_cfHttp11Str.DangerousGetHandle() }; private static readonly IntPtr[] s_cfAlpnHttp211Protocol = new IntPtr[] { s_cfHttp2Str.DangerousGetHandle(), s_cfHttp11Str.DangerousGetHandle() }; private static readonly SafeCreateHandle s_cfAlpnHttp11Protocols = CoreFoundation.CFArrayCreate(s_cfAlpnHttp11Protocol, (UIntPtr)1); private static readonly SafeCreateHandle s_cfAlpnHttp2Protocols = CoreFoundation.CFArrayCreate(s_cfAlpnHttp2Protocol, (UIntPtr)1); private static readonly SafeCreateHandle s_cfAlpnHttp211Protocols = CoreFoundation.CFArrayCreate(s_cfAlpnHttp211Protocol, (UIntPtr)2); internal enum PAL_TlsHandshakeState { Unknown, Complete, WouldBlock, ServerAuthCompleted, ClientAuthCompleted, } internal enum PAL_TlsIo { Unknown, Success, WouldBlock, ClosedGracefully, Renegotiate, } [DllImport(Interop.Libraries.AppleCryptoNative, EntryPoint = "AppleCryptoNative_SslCreateContext")] internal static extern System.Net.SafeSslHandle SslCreateContext(int isServer); [DllImport(Interop.Libraries.AppleCryptoNative)] private static extern int AppleCryptoNative_SslSetMinProtocolVersion( SafeSslHandle sslHandle, SslProtocols minProtocolId); [DllImport(Interop.Libraries.AppleCryptoNative)] private static extern int AppleCryptoNative_SslSetMaxProtocolVersion( SafeSslHandle sslHandle, SslProtocols maxProtocolId); [DllImport(Interop.Libraries.AppleCryptoNative)] private static extern int AppleCryptoNative_SslCopyCertChain( SafeSslHandle sslHandle, out SafeX509ChainHandle pTrustOut, out int pOSStatus); [DllImport(Interop.Libraries.AppleCryptoNative)] private static extern int AppleCryptoNative_SslCopyCADistinguishedNames( SafeSslHandle sslHandle, out SafeCFArrayHandle pArrayOut, out int pOSStatus); [DllImport(Interop.Libraries.AppleCryptoNative)] private static extern int AppleCryptoNative_SslSetBreakOnServerAuth( SafeSslHandle sslHandle, int setBreak, out int pOSStatus); [DllImport(Interop.Libraries.AppleCryptoNative)] private static extern int AppleCryptoNative_SslSetBreakOnClientAuth( SafeSslHandle sslHandle, int setBreak, out int pOSStatus); [DllImport(Interop.Libraries.AppleCryptoNative)] private static extern int AppleCryptoNative_SslSetCertificate( SafeSslHandle sslHandle, SafeCreateHandle cfCertRefs); [DllImport(Interop.Libraries.AppleCryptoNative)] private static extern int AppleCryptoNative_SslSetTargetName( SafeSslHandle sslHandle, string targetName, int cbTargetName, out int osStatus); [DllImport(Interop.Libraries.AppleCryptoNative, EntryPoint = "AppleCryptoNative_SSLSetALPNProtocols")] internal static extern int SSLSetALPNProtocols(SafeSslHandle ctx, SafeCreateHandle cfProtocolsRefs, out int osStatus); [DllImport(Interop.Libraries.AppleCryptoNative, EntryPoint = "AppleCryptoNative_SslGetAlpnSelected")] internal static extern int SslGetAlpnSelected(SafeSslHandle ssl, out SafeCFDataHandle protocol); [DllImport(Interop.Libraries.AppleCryptoNative, EntryPoint = "AppleCryptoNative_SslHandshake")] internal static extern PAL_TlsHandshakeState SslHandshake(SafeSslHandle sslHandle); [DllImport(Interop.Libraries.AppleCryptoNative)] private static extern int AppleCryptoNative_SslSetAcceptClientCert(SafeSslHandle sslHandle); [DllImport(Interop.Libraries.AppleCryptoNative, EntryPoint = "AppleCryptoNative_SslSetIoCallbacks")] internal static extern int SslSetIoCallbacks( SafeSslHandle sslHandle, SSLReadFunc readCallback, SSLWriteFunc writeCallback); [DllImport(Interop.Libraries.AppleCryptoNative, EntryPoint = "AppleCryptoNative_SslWrite")] internal static extern unsafe PAL_TlsIo SslWrite(SafeSslHandle sslHandle, byte* writeFrom, int count, out int bytesWritten); [DllImport(Interop.Libraries.AppleCryptoNative, EntryPoint = "AppleCryptoNative_SslRead")] internal static extern unsafe PAL_TlsIo SslRead(SafeSslHandle sslHandle, byte* writeFrom, int count, out int bytesWritten); [DllImport(Interop.Libraries.AppleCryptoNative)] private static extern int AppleCryptoNative_SslIsHostnameMatch( SafeSslHandle handle, SafeCreateHandle cfHostname, SafeCFDateHandle cfValidTime); [DllImport(Interop.Libraries.AppleCryptoNative, EntryPoint = "AppleCryptoNative_SslShutdown")] internal static extern int SslShutdown(SafeSslHandle sslHandle); [DllImport(Interop.Libraries.AppleCryptoNative, EntryPoint = "AppleCryptoNative_SslGetCipherSuite")] internal static extern int SslGetCipherSuite(SafeSslHandle sslHandle, out TlsCipherSuite cipherSuite); [DllImport(Interop.Libraries.AppleCryptoNative, EntryPoint = "AppleCryptoNative_SslGetProtocolVersion")] internal static extern int SslGetProtocolVersion(SafeSslHandle sslHandle, out SslProtocols protocol); [DllImport(Interop.Libraries.AppleCryptoNative, EntryPoint = "AppleCryptoNative_SslSetEnabledCipherSuites")] internal static extern unsafe int SslSetEnabledCipherSuites(SafeSslHandle sslHandle, uint* cipherSuites, int numCipherSuites); internal static void SslSetAcceptClientCert(SafeSslHandle sslHandle) { int osStatus = AppleCryptoNative_SslSetAcceptClientCert(sslHandle); if (osStatus != 0) { throw CreateExceptionForOSStatus(osStatus); } } internal static void SslSetMinProtocolVersion(SafeSslHandle sslHandle, SslProtocols minProtocolId) { int osStatus = AppleCryptoNative_SslSetMinProtocolVersion(sslHandle, minProtocolId); if (osStatus != 0) { throw CreateExceptionForOSStatus(osStatus); } } internal static void SslSetMaxProtocolVersion(SafeSslHandle sslHandle, SslProtocols maxProtocolId) { int osStatus = AppleCryptoNative_SslSetMaxProtocolVersion(sslHandle, maxProtocolId); if (osStatus != 0) { throw CreateExceptionForOSStatus(osStatus); } } internal static SafeX509ChainHandle SslCopyCertChain(SafeSslHandle sslHandle) { SafeX509ChainHandle chainHandle; int osStatus; int result = AppleCryptoNative_SslCopyCertChain(sslHandle, out chainHandle, out osStatus); if (result == 1) { return chainHandle; } chainHandle.Dispose(); if (result == 0) { throw CreateExceptionForOSStatus(osStatus); } Debug.Fail($"AppleCryptoNative_SslCopyCertChain returned {result}"); throw new SslException(); } internal static SafeCFArrayHandle SslCopyCADistinguishedNames(SafeSslHandle sslHandle) { SafeCFArrayHandle dnArray; int osStatus; int result = AppleCryptoNative_SslCopyCADistinguishedNames(sslHandle, out dnArray, out osStatus); if (result == 1) { return dnArray; } dnArray.Dispose(); if (result == 0) { throw CreateExceptionForOSStatus(osStatus); } Debug.Fail($"AppleCryptoNative_SslCopyCADistinguishedNames returned {result}"); throw new SslException(); } internal static void SslBreakOnServerAuth(SafeSslHandle sslHandle, bool setBreak) { int osStatus; int result = AppleCryptoNative_SslSetBreakOnServerAuth(sslHandle, setBreak ? 1 : 0, out osStatus); if (result == 1) { return; } if (result == 0) { throw CreateExceptionForOSStatus(osStatus); } Debug.Fail($"AppleCryptoNative_SslSetBreakOnServerAuth returned {result}"); throw new SslException(); } internal static void SslBreakOnClientAuth(SafeSslHandle sslHandle, bool setBreak) { int osStatus; int result = AppleCryptoNative_SslSetBreakOnClientAuth(sslHandle, setBreak ? 1 : 0, out osStatus); if (result == 1) { return; } if (result == 0) { throw CreateExceptionForOSStatus(osStatus); } Debug.Fail($"AppleCryptoNative_SslSetBreakOnClientAuth returned {result}"); throw new SslException(); } internal static void SslSetCertificate(SafeSslHandle sslHandle, IntPtr[] certChainPtrs) { using (SafeCreateHandle cfCertRefs = CoreFoundation.CFArrayCreate(certChainPtrs, (UIntPtr)certChainPtrs.Length)) { int osStatus = AppleCryptoNative_SslSetCertificate(sslHandle, cfCertRefs); if (osStatus != 0) { throw CreateExceptionForOSStatus(osStatus); } } } internal static void SslSetTargetName(SafeSslHandle sslHandle, string targetName) { Debug.Assert(!string.IsNullOrEmpty(targetName)); int osStatus; int cbTargetName = System.Text.Encoding.UTF8.GetByteCount(targetName); int result = AppleCryptoNative_SslSetTargetName(sslHandle, targetName, cbTargetName, out osStatus); if (result == 1) { return; } if (result == 0) { throw CreateExceptionForOSStatus(osStatus); } Debug.Fail($"AppleCryptoNative_SslSetTargetName returned {result}"); throw new SslException(); } internal static unsafe void SslCtxSetAlpnProtos(SafeSslHandle ctx, List<SslApplicationProtocol> protocols) { SafeCreateHandle cfProtocolsRefs = null; SafeCreateHandle[] cfProtocolsArrayRef = null; try { if (protocols.Count == 1 && protocols[0] == SslApplicationProtocol.Http2) { cfProtocolsRefs = s_cfAlpnHttp2Protocols; } else if (protocols.Count == 1 && protocols[0] == SslApplicationProtocol.Http11) { cfProtocolsRefs = s_cfAlpnHttp11Protocols; } else if (protocols.Count == 2 && protocols[0] == SslApplicationProtocol.Http2 && protocols[1] == SslApplicationProtocol.Http11) { cfProtocolsRefs = s_cfAlpnHttp211Protocols; } else { // we did not match common case. This is more expensive path allocating Core Foundation objects. cfProtocolsArrayRef = new SafeCreateHandle[protocols.Count]; IntPtr[] protocolsPtr = new System.IntPtr[protocols.Count]; for (int i = 0; i < protocols.Count; i++) { cfProtocolsArrayRef[i] = CoreFoundation.CFStringCreateWithCString(protocols[i].ToString()); protocolsPtr[i] = cfProtocolsArrayRef[i].DangerousGetHandle(); } cfProtocolsRefs = CoreFoundation.CFArrayCreate(protocolsPtr, (UIntPtr)protocols.Count); } int osStatus; int result = SSLSetALPNProtocols(ctx, cfProtocolsRefs, out osStatus); if (result != 1) { throw CreateExceptionForOSStatus(osStatus); } } finally { if (cfProtocolsArrayRef != null) { for (int i = 0; i < cfProtocolsArrayRef.Length; i++) { cfProtocolsArrayRef[i]?.Dispose(); } cfProtocolsRefs?.Dispose(); } } } internal static byte[] SslGetAlpnSelected(SafeSslHandle ssl) { SafeCFDataHandle protocol; if (SslGetAlpnSelected(ssl, out protocol) != 1 || protocol == null) { return null; } try { byte[] result = Interop.CoreFoundation.CFGetData(protocol); return result; } finally { protocol.Dispose(); } } public static bool SslCheckHostnameMatch(SafeSslHandle handle, string hostName, DateTime notBefore) { int result; // The IdnMapping converts Unicode input into the IDNA punycode sequence. // It also does host case normalization. The bypass logic would be something // like "all characters being within [a-z0-9.-]+" // // The SSL Policy (SecPolicyCreateSSL) has been verified as not inherently supporting // IDNA as of macOS 10.12.1 (Sierra). If it supports low-level IDNA at a later date, // this code could be removed. // // It was verified as supporting case invariant match as of 10.12.1 (Sierra). string matchName = s_idnMapping.GetAscii(hostName); using (SafeCFDateHandle cfNotBefore = CoreFoundation.CFDateCreate(notBefore)) using (SafeCreateHandle cfHostname = CoreFoundation.CFStringCreateWithCString(matchName)) { result = AppleCryptoNative_SslIsHostnameMatch(handle, cfHostname, cfNotBefore); } switch (result) { case 0: return false; case 1: return true; default: Debug.Fail($"AppleCryptoNative_SslIsHostnameMatch returned {result}"); throw new SslException(); } } } } namespace System.Net { internal sealed class SafeSslHandle : SafeHandle { internal SafeSslHandle() : base(IntPtr.Zero, ownsHandle: true) { } internal SafeSslHandle(IntPtr invalidHandleValue, bool ownsHandle) : base(invalidHandleValue, ownsHandle) { } protected override bool ReleaseHandle() { Interop.CoreFoundation.CFRelease(handle); SetHandle(IntPtr.Zero); return true; } public override bool IsInvalid => handle == IntPtr.Zero; } }
/* * * (c) Copyright Ascensio System Limited 2010-2021 * * 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 ASC.Mail.Net.MIME { #region usings using System; using System.IO; using System.Text; using IO; #endregion /// <summary> /// This class represents MIME application/xxx bodies. Defined in RFC 2046 5.1. /// </summary> /// <remarks> /// The "multipart" represents single MIME body containing multiple child MIME entities. /// The "multipart" body must contain at least 1 MIME entity. /// </remarks> public class MIME_b_Multipart : MIME_b { #region Nested type: _MultipartReader /// <summary> /// Implements multipart "body parts" reader. /// </summary> public class _MultipartReader : Stream { #region Nested type: State /// <summary> /// This enum specified multipart reader sate. /// </summary> private enum State { /// <summary> /// First boundary must be seeked. /// </summary> SeekFirst = 0, /// <summary> /// Read next boundary. /// </summary> ReadNext = 1, /// <summary> /// All boundraies readed. /// </summary> Done = 2, } #endregion #region Members private readonly string m_Boundary = ""; private readonly SmartStream.ReadLineAsyncOP m_pReadLineOP; private readonly SmartStream m_pStream; private readonly StringBuilder m_pTextEpilogue; private readonly StringBuilder m_pTextPreamble; private State m_State = State.SeekFirst; #endregion #region Properties /// <summary> /// Gets a value indicating whether the current stream supports reading. /// </summary> public override bool CanRead { get { return true; } } /// <summary> /// Gets a value indicating whether the current stream supports seeking. /// </summary> public override bool CanSeek { get { return false; } } /// <summary> /// Gets a value indicating whether the current stream supports writing. /// </summary> public override bool CanWrite { get { return false; } } /// <summary> /// Gets the length in bytes of the stream. This method is not supported and always throws a NotSupportedException. /// </summary> /// <exception cref="NotSupportedException">Is raised when this property is accessed.</exception> public override long Length { get { throw new NotSupportedException(); } } /// <summary> /// Gets or sets the position within the current stream. This method is not supported and always throws a NotSupportedException. /// </summary> /// <exception cref="NotSupportedException">Is raised when this property is accessed.</exception> public override long Position { get { throw new NotSupportedException(); } set { throw new NotSupportedException(); } } /// <summary> /// Gets "preamble" text. Defined in RFC 2046 5.1.1. /// </summary> /// <remarks>Preamble text is text between MIME entiy headers and first boundary.</remarks> public string TextPreamble { get { return m_pTextPreamble.ToString(); } } /// <summary> /// Gets "epilogue" text. Defined in RFC 2046 5.1.1. /// </summary> /// <remarks>Epilogue text is text after last boundary end.</remarks> public string TextEpilogue { get { return m_pTextEpilogue.ToString(); } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="stream">Stream from where to read body part.</param> /// <param name="boundary">Boundry ID what separates body parts.</param> /// <exception cref="ArgumentNullException">Is raised when <b>stream</b> or <b>boundary</b> is null reference.</exception> public _MultipartReader(SmartStream stream, string boundary) { if (stream == null) { throw new ArgumentNullException("stream"); } if (boundary == null) { throw new ArgumentNullException("boundary"); } m_pStream = stream; m_Boundary = boundary; m_pReadLineOP = new SmartStream.ReadLineAsyncOP(new byte[Workaround.Definitions.MaxStreamLineLength], SizeExceededAction.ThrowException); m_pTextPreamble = new StringBuilder(); m_pTextEpilogue = new StringBuilder(); } #endregion #region Methods /// <summary> /// Moves to next "body part". Returns true if moved to next "body part" or false if there are no more parts. /// </summary> /// <returns>Returns true if moved to next "body part" or false if there are no more body parts.</returns> public bool Next() { if (m_State == State.Done) { return false; } else if (m_State == State.SeekFirst) { while (true) { m_pStream.ReadLine(m_pReadLineOP, false); if (m_pReadLineOP.Error != null) { throw m_pReadLineOP.Error; } // We reached end of stream. Bad boundary: boundary end tag missing. else if (m_pReadLineOP.BytesInBuffer == 0) { m_State = State.Done; return false; } else { // Check if we have boundary start/end. if (m_pReadLineOP.Buffer[0] == '-') { string boundary = m_pReadLineOP.LineUtf8; // We have readed all MIME entity body parts. if ("--" + m_Boundary + "--" == boundary) { m_State = State.Done; return false; } // We have next boundary. else if ("--" + m_Boundary == boundary) { m_State = State.ReadNext; return true; } // Not boundary or not boundary we want. //else{ } m_pTextPreamble.Append(m_pReadLineOP.LineUtf8 + "\r\n"); } } } else if (m_State == State.ReadNext) { return true; } return false; } /// <summary> /// Clears all buffers for this stream and causes any buffered data to be written to the underlying device. /// </summary> public override void Flush() {} /// <summary> /// Sets the position within the current stream. This method is not supported and always throws a NotSupportedException. /// </summary> /// <param name="offset">A byte offset relative to the <b>origin</b> parameter.</param> /// <param name="origin">A value of type SeekOrigin indicating the reference point used to obtain the new position.</param> /// <returns>The new position within the current stream.</returns> /// <exception cref="NotSupportedException">Is raised when this method is accessed.</exception> public override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException(); } /// <summary> /// Sets the length of the current stream. This method is not supported and always throws a NotSupportedException. /// </summary> /// <param name="value">The desired length of the current stream in bytes.</param> /// <exception cref="Seek">Is raised when this method is accessed.</exception> public override void SetLength(long value) { throw new NotSupportedException(); } /// <summary> /// Reads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read. /// </summary> /// <param name="buffer">An array of bytes. When this method returns, the buffer contains the specified byte array with the values between offset and (offset + count - 1) replaced by the bytes read from the current source.</param> /// <param name="offset">The zero-based byte offset in buffer at which to begin storing the data read from the current stream.</param> /// <param name="count">The maximum number of bytes to be read from the current stream.</param> /// <returns>The total number of bytes read into the buffer. This can be less than the number of bytes requested if that many bytes are not currently available, or zero (0) if the end of the stream has been reached.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>buffer</b> is null reference.</exception> public override int Read(byte[] buffer, int offset, int count) { if (buffer == null) { throw new ArgumentNullException("buffer"); } if (m_State == State.Done) { return 0; } m_pStream.ReadLine(m_pReadLineOP, false); if (m_pReadLineOP.Error != null) { throw m_pReadLineOP.Error; } // We reached end of stream. Bad boundary: boundary end tag missing. else if (m_pReadLineOP.BytesInBuffer == 0) { m_State = State.Done; return 0; } else { // Check if we have boundary start/end. if (m_pReadLineOP.Buffer[0] == '-') { string boundary = m_pReadLineOP.LineUtf8; // We have readed all MIME entity body parts. if ("--" + m_Boundary + "--" == boundary) { m_State = State.Done; // Read "epilogoue" if any. while (true) { m_pStream.ReadLine(m_pReadLineOP, false); if (m_pReadLineOP.Error != null) { throw m_pReadLineOP.Error; } // We reached end of stream. Epilogue reading completed. else if (m_pReadLineOP.BytesInBuffer == 0) { break; } else { m_pTextEpilogue.Append(m_pReadLineOP.LineUtf8 + "\r\n"); } } return 0; } // We have next boundary. else if ("--" + m_Boundary == boundary) { return 0; } // Not boundary or not boundary we want. //else{ } // We have body part data line //else{ if (count < m_pReadLineOP.BytesInBuffer) { //throw new ArgumentException("Argument 'buffer' is to small. This should never happen."); } Array.Copy(m_pReadLineOP.Buffer, 0, buffer, offset, m_pReadLineOP.BytesInBuffer); return m_pReadLineOP.BytesInBuffer; } } /// <summary> /// Writes sequence of bytes to the current stream and advances the current position within this stream by the number of bytes written. /// </summary> /// <param name="buffer">An array of bytes. This method copies count bytes from buffer to the current stream.</param> /// <param name="offset">The zero-based byte offset in buffer at which to begin copying bytes to the current stream.</param> /// <param name="count">The number of bytes to be written to the current stream.</param> /// <exception cref="NotSupportedException">Is raised when this method is accessed.</exception> public override void Write(byte[] buffer, int offset, int count) { throw new NotSupportedException(); } #endregion } #endregion #region Members private readonly MIME_EntityCollection m_pBodyParts; private string m_TextEpilogue = ""; private string m_TextPreamble = ""; #endregion #region Properties /// <summary> /// Gets if body has modified. /// </summary> public override bool IsModified { get { return m_pBodyParts.IsModified; } } /// <summary> /// Gets default body part Content-Type. For more info see RFC 2046 5.1. /// </summary> public virtual MIME_h_ContentType DefaultBodyPartContentType { /* RFC 2026 5.1. The absence of a Content-Type header usually indicates that the corresponding body has a content-type of "text/plain; charset=US-ASCII". */ get { MIME_h_ContentType retVal = new MIME_h_ContentType("text/plain"); retVal.Param_Charset = "US-ASCII"; return retVal; } } /// <summary> /// Gets multipart body body-parts collection. /// </summary> /// <remarks>Multipart entity child entities are called "body parts" in RFC 2045.</remarks> public MIME_EntityCollection BodyParts { get { return m_pBodyParts; } } /// <summary> /// Gets or sets "preamble" text. Defined in RFC 2046 5.1.1. /// </summary> /// <remarks>Preamble text is text between MIME entiy headers and first boundary.</remarks> public string TextPreamble { get { return m_TextPreamble; } set { m_TextPreamble = value; } } /// <summary> /// Gets or sets "epilogue" text. Defined in RFC 2046 5.1.1. /// </summary> /// <remarks>Epilogue text is text after last boundary end.</remarks> public string TextEpilogue { get { return m_TextEpilogue; } set { m_TextEpilogue = value; } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="contentType">Content type.</param> /// <exception cref="ArgumentNullException">Is raised when <b>contentType</b> is null reference.</exception> /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception> public MIME_b_Multipart(MIME_h_ContentType contentType) : base(contentType) { if (contentType == null) { throw new ArgumentNullException("contentType"); } if (string.IsNullOrEmpty(contentType.Param_Boundary)) { throw new ArgumentException( "Argument 'contentType' doesn't contain required boundary parameter."); } m_pBodyParts = new MIME_EntityCollection(); } #endregion #region Overrides /// <summary> /// Stores MIME entity body to the specified stream. /// </summary> /// <param name="stream">Stream where to store body data.</param> /// <param name="headerWordEncoder">Header 8-bit words ecnoder. Value null means that words are not encoded.</param> /// <param name="headerParmetersCharset">Charset to use to encode 8-bit header parameters. Value null means parameters not encoded.</param> /// <exception cref="ArgumentNullException">Is raised when <b>stream</b> is null reference.</exception> protected internal override void ToStream(Stream stream, MIME_Encoding_EncodedWord headerWordEncoder, Encoding headerParmetersCharset) { if (stream == null) { throw new ArgumentNullException("stream"); } // Set "preamble" text if any. if (!string.IsNullOrEmpty(m_TextPreamble)) { byte[] preableBytes = null; if (m_TextPreamble.EndsWith("\r\n")) { preableBytes = Encoding.UTF8.GetBytes(m_TextPreamble); } else { preableBytes = Encoding.UTF8.GetBytes(m_TextPreamble + "\r\n"); } stream.Write(preableBytes, 0, preableBytes.Length); } for (int i = 0; i < m_pBodyParts.Count; i++) { MIME_Entity bodyPart = m_pBodyParts[i]; // Start new body part. byte[] bStart = Encoding.UTF8.GetBytes("--" + ContentType.Param_Boundary + "\r\n"); stream.Write(bStart, 0, bStart.Length); bodyPart.ToStream(stream, headerWordEncoder, headerParmetersCharset); // Last body part, close boundary. if (i == (m_pBodyParts.Count - 1)) { byte[] bEnd = Encoding.UTF8.GetBytes("--" + ContentType.Param_Boundary + "--\r\n"); stream.Write(bEnd, 0, bEnd.Length); } } // Set "epilogoue" text if any. if (!string.IsNullOrEmpty(m_TextEpilogue)) { byte[] epilogoueBytes = null; if (m_TextEpilogue.EndsWith("\r\n")) { epilogoueBytes = Encoding.UTF8.GetBytes(m_TextEpilogue); } else { epilogoueBytes = Encoding.UTF8.GetBytes(m_TextEpilogue + "\r\n"); } stream.Write(epilogoueBytes, 0, epilogoueBytes.Length); } } #endregion /// <summary> /// Parses body from the specified stream /// </summary> /// <param name="owner">Owner MIME entity.</param> /// <param name="mediaType">MIME media type. For example: text/plain.</param> /// <param name="stream">Stream from where to read body.</param> /// <returns>Returns parsed body.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>stream</b>, <b>mediaType</b> or <b>stream</b> is null reference.</exception> /// <exception cref="ParseException">Is raised when any parsing errors.</exception> protected new static MIME_b Parse(MIME_Entity owner, string mediaType, SmartStream stream) { if (owner == null) { throw new ArgumentNullException("owner"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } if (stream == null) { throw new ArgumentNullException("stream"); } if (owner.ContentType == null || owner.ContentType.Param_Boundary == null) { throw new ParseException("Multipart entity has not required 'boundary' paramter."); } MIME_b_Multipart retVal = new MIME_b_Multipart(owner.ContentType); ParseInternal(owner, mediaType, stream, retVal); return retVal; } /// <summary> /// Internal body parsing. /// </summary> /// <param name="owner">Owner MIME entity.</param> /// <param name="mediaType">MIME media type. For example: text/plain.</param> /// <param name="stream">Stream from where to read body.</param> /// <param name="body">Multipart body instance.</param> /// <exception cref="ArgumentNullException">Is raised when <b>stream</b>, <b>mediaType</b>, <b>stream</b> or <b>body</b> is null reference.</exception> /// <exception cref="ParseException">Is raised when any parsing errors.</exception> protected static void ParseInternal(MIME_Entity owner, string mediaType, SmartStream stream, MIME_b_Multipart body) { if (owner == null) { throw new ArgumentNullException("owner"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } if (stream == null) { throw new ArgumentNullException("stream"); } if (owner.ContentType == null || owner.ContentType.Param_Boundary == null) { throw new ParseException("Multipart entity has not required 'boundary' parameter."); } if (body == null) { throw new ArgumentNullException("body"); } _MultipartReader multipartReader = new _MultipartReader(stream, owner.ContentType.Param_Boundary); while (multipartReader.Next()) { MIME_Entity entity = new MIME_Entity(); entity.Parse(new SmartStream(multipartReader, false), body.DefaultBodyPartContentType); body.m_pBodyParts.Add(entity); entity.SetParent(owner); } body.m_TextPreamble = multipartReader.TextPreamble; body.m_TextEpilogue = multipartReader.TextEpilogue; } } }
/* * Copyright (c) InWorldz Halcyon Developers * Copyright (c) Contributors, http://opensimulator.org/ * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Reflection; using System.Collections; using System.Collections.Generic; using OpenMetaverse; using OpenMetaverse.StructuredData; using log4net; namespace OpenSim.Framework { /// <summary> /// Contains the Avatar's Appearance and methods to manipulate the appearance. /// </summary> public class AvatarAppearance { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); public readonly static int VISUALPARAM_COUNT_1X = 218; // 1.x viewers, i.e. before avatar physics layers public readonly static int VISUALPARAM_COUNT = 251; public readonly static byte VISUALPARAM_DEFAULT = 100; // what to use for a default value? 0=alien, 150=fat scientist public readonly static int TEXTURE_COUNT = 21; public readonly static byte[] BAKE_INDICES = new byte[] { 8, 9, 10, 11, 19, 20 }; protected UUID m_owner; protected int m_serial = 0; protected byte[] m_visualparams; protected Primitive.TextureEntry m_texture; protected Dictionary<int, AvatarWearable> m_wearables; protected Dictionary<int, List<AvatarAttachment>> m_attachments; protected float m_avatarHeight = 0; protected float m_hipOffset = 0; public bool IsBotAppearance { get; set; } public virtual UUID Owner { get { return m_owner; } set { m_owner = value; } } public virtual int Serial { get { return m_serial; } set { m_serial = value; } } public virtual byte[] VisualParams { get { return m_visualparams; } set { m_visualparams = value; } } public virtual Primitive.TextureEntry Texture { get { return m_texture; } set { m_texture = value; } } public virtual float AvatarHeight { get { return m_avatarHeight; } set { m_avatarHeight = value; } } public virtual float HipOffset { get { return m_hipOffset; } } public static byte[] GetDefaultVisualParams() { byte[] visualParams = new byte[VISUALPARAM_COUNT]; // m_visualparams = new byte[] { // 33,61,85,23,58,127,63,85,63,42,0,85,63,36,85,95,153,63,34,0,63,109,88,132,63,136,81,85,103,136,127,0,150,150,150,127,0,0,0,0,0,127,0,0,255,127,114,127,99,63,127,140,127,127,0,0,0,191,0,104,0,0,0,0,0,0,0,0,0,145,216,133,0,127,0,127,170,0,0,127,127,109,85,127,127,63,85,42,150,150,150,150,150,150,150,25,150,150,150,0,127,0,0,144,85,127,132,127,85,0,127,127,127,127,127,127,59,127,85,127,127,106,47,79,127,127,204,2,141,66,0,0,127,127,0,0,0,0,127,0,159,0,0,178,127,36,85,131,127,127,127,153,95,0,140,75,27,127,127,0,150,150,198,0,0,63,30,127,165,209,198,127,127,153,204,51,51,255,255,255,204,0,255,150,150,150,150,150,150,150,150,150,150,0,150,150,150,150,150,0,127,127,150,150,150,150,150,150,150,150,0,0,150,51,132,150,150,150 }; // This sets Visual Params with *less* weirder values then default. for (int i = 0; i < visualParams.Length; i++) visualParams[i] = VISUALPARAM_DEFAULT; return visualParams; } public static Primitive.TextureEntry GetDefaultTexture() { Primitive.TextureEntry textu = new Primitive.TextureEntry(new UUID("C228D1CF-4B5D-4BA8-84F4-899A0796AA97")); textu.CreateFace(0).TextureID = new UUID("00000000-0000-1111-9999-000000000012"); textu.CreateFace(1).TextureID = Util.BLANK_TEXTURE_UUID; textu.CreateFace(2).TextureID = Util.BLANK_TEXTURE_UUID; textu.CreateFace(3).TextureID = new UUID("6522E74D-1660-4E7F-B601-6F48C1659A77"); textu.CreateFace(4).TextureID = new UUID("7CA39B4C-BD19-4699-AFF7-F93FD03D3E7B"); textu.CreateFace(5).TextureID = new UUID("00000000-0000-1111-9999-000000000010"); textu.CreateFace(6).TextureID = new UUID("00000000-0000-1111-9999-000000000011"); return textu; } public AvatarAppearance() : this(UUID.Zero) { } public AvatarAppearance(UUID owner) { m_owner = owner; m_serial = 0; m_attachments = new Dictionary<int, List<AvatarAttachment>>(); m_wearables = new Dictionary<int, AvatarWearable>(); SetDefaultWearables(); SetDefaultTexture(); SetDefaultParams(); SetHeight(); } public AvatarAppearance(OSDMap map) { Unpack(map); SetHeight(); } public AvatarAppearance(UUID owner, AvatarWearable[] wearables, Primitive.TextureEntry textureEntry, byte[] visualParams) { // m_log.WarnFormat("[AVATAR APPEARANCE] create initialized appearance"); m_owner = owner; m_serial = 0; m_attachments = new Dictionary<int, List<AvatarAttachment>>(); m_wearables = new Dictionary<int, AvatarWearable>(); if (wearables != null) { ClearWearables(); SetWearables(new List<AvatarWearable>(wearables)); } else SetDefaultWearables(); if (textureEntry != null) m_texture = textureEntry; else SetDefaultTexture(); if (visualParams != null) m_visualparams = visualParams; else SetDefaultParams(); SetHeight(); } public AvatarAppearance(AvatarAppearance appearance) : this(appearance, true) { } public AvatarAppearance(AvatarAppearance appearance, bool copyWearables) { // m_log.WarnFormat("[AVATAR APPEARANCE] create from an existing appearance"); m_attachments = new Dictionary<int, List<AvatarAttachment>>(); m_wearables = new Dictionary<int, AvatarWearable>(); if (appearance == null) { m_serial = 0; m_owner = UUID.Zero; SetDefaultWearables(); SetDefaultTexture(); SetDefaultParams(); SetHeight(); return; } m_owner = appearance.Owner; m_serial = appearance.Serial; if (copyWearables == true) { ClearWearables(); SetWearables(appearance.GetWearables()); } else SetDefaultWearables(); m_texture = null; if (appearance.Texture != null) { byte[] tbytes = appearance.Texture.GetBytes(); m_texture = new Primitive.TextureEntry(tbytes, 0, tbytes.Length); } else { SetDefaultTexture(); } m_visualparams = null; if (appearance.VisualParams != null) m_visualparams = (byte[])appearance.VisualParams.Clone(); else SetDefaultParams(); IsBotAppearance = appearance.IsBotAppearance; SetHeight(); SetAttachments(appearance.GetAttachments()); } protected virtual void SetDefaultWearables() { SetWearables(AvatarWearable.GetDefaultWearables()); } /// <summary> /// Invalidate all of the baked textures in the appearance, useful /// if you know that none are valid /// </summary> public virtual void ResetAppearance() { // m_log.WarnFormat("[AVATAR APPEARANCE]: Reset appearance"); m_serial = 0; SetDefaultTexture(); } protected virtual void SetDefaultParams() { m_visualparams = GetDefaultVisualParams(); SetHeight(); } protected virtual void SetDefaultTexture() { m_texture = GetDefaultTexture(); } /// <summary> /// Set up appearance texture ids. /// </summary> /// <returns> /// True if any existing texture id was changed by the new data. /// False if there were no changes or no existing texture ids. /// </returns> public virtual bool SetTextureEntries(Primitive.TextureEntry textureEntry) { if (textureEntry == null) return false; // There are much simpler versions of this copy that could be // made. We determine if any of the textures actually // changed to know if the appearance should be saved later bool changed = false; for (uint i = 0; i < AvatarAppearance.TEXTURE_COUNT; i++) { Primitive.TextureEntryFace newface = textureEntry.FaceTextures[i]; Primitive.TextureEntryFace oldface = m_texture.FaceTextures[i]; if (newface == null) { if (oldface == null) continue; } else { if (oldface != null && oldface.TextureID == newface.TextureID) continue; } changed = true; } m_texture = textureEntry; return changed; } /// <summary> /// Set up visual parameters for the avatar and refresh the avatar height /// </summary> /// <returns> /// True if any existing visual parameter was changed by the new data. /// False if there were no changes or no existing visual parameters. /// </returns> public virtual bool SetVisualParams(byte[] visualParams) { bool changed = false; if (visualParams == null) return changed; // If the arrays are different sizes replace the whole thing. // its likely from different viewers if (visualParams.Length != m_visualparams.Length) { m_visualparams = (byte[])visualParams.Clone(); changed = true; } else { for (int i = 0; i < visualParams.Length; i++) { if (visualParams[i] != m_visualparams[i]) { m_visualparams[i] = visualParams[i]; changed = true; } } } // Reset the height if the visual parameters actually changed if (changed) SetHeight(); return changed; } public virtual void SetAppearance(Primitive.TextureEntry textureEntry, byte[] visualParams) { SetTextureEntries(textureEntry); SetVisualParams(visualParams); SetHeight(); } public virtual void SetHeight() { m_avatarHeight = 1.23077f // Shortest possible avatar height + 0.516945f * (float)m_visualparams[25] / 255.0f // Body height + 0.072514f * (float)m_visualparams[120] / 255.0f // Head size + 0.3836f * (float)m_visualparams[125] / 255.0f // Leg length + 0.08f * (float)m_visualparams[77] / 255.0f // Shoe heel height + 0.07f * (float)m_visualparams[78] / 255.0f // Shoe platform height + 0.076f * (float)m_visualparams[148] / 255.0f; // Neck length m_hipOffset = (0.615385f // Half of avatar + 0.08f * (float)m_visualparams[77] / 255.0f // Shoe heel height + 0.07f * (float)m_visualparams[78] / 255.0f // Shoe platform height + 0.3836f * (float)m_visualparams[125] / 255.0f // Leg length - m_avatarHeight / 2) * 0.3f - 0.04f; //System.Console.WriteLine(">>>>>>> [APPEARANCE]: Height {0} Hip offset {1}" + m_avatarHeight + " " + m_hipOffset); //m_log.Debug("------------- Set Appearance Texture ---------------"); //Primitive.TextureEntryFace[] faces = Texture.FaceTextures; //foreach (Primitive.TextureEntryFace face in faces) //{ // if (face != null) // m_log.Debug(" ++ " + face.TextureID); // else // m_log.Debug(" ++ NULL "); //} //m_log.Debug("----------------------------"); } // this is used for OGS1 // It should go away soon in favor of the pack/unpack sections below public virtual Hashtable ToHashTable() { Hashtable h = new Hashtable(); AvatarWearable wearable; h["owner"] = Owner.ToString(); h["serial"] = Serial.ToString(); h["visual_params"] = VisualParams; h["texture"] = Texture.GetBytes(); h["avatar_height"] = AvatarHeight.ToString(); wearable = GetWearableOfType(AvatarWearable.BODY); h["body_item"] = wearable.ItemID.ToString(); h["body_asset"] = wearable.AssetID.ToString(); wearable = GetWearableOfType(AvatarWearable.SKIN); h["skin_item"] = wearable.ItemID.ToString(); h["skin_asset"] = wearable.AssetID.ToString(); wearable = GetWearableOfType(AvatarWearable.HAIR); h["hair_item"] = wearable.ItemID.ToString(); h["hair_asset"] = wearable.AssetID.ToString(); wearable = GetWearableOfType(AvatarWearable.EYES); h["eyes_item"] = wearable.ItemID.ToString(); h["eyes_asset"] = wearable.AssetID.ToString(); wearable = GetWearableOfType(AvatarWearable.SHIRT); h["shirt_item"] = wearable.ItemID.ToString(); h["shirt_asset"] = wearable.AssetID.ToString(); wearable = GetWearableOfType(AvatarWearable.PANTS); h["pants_item"] = wearable.ItemID.ToString(); h["pants_asset"] = wearable.AssetID.ToString(); wearable = GetWearableOfType(AvatarWearable.SHOES); h["shoes_item"] = wearable.ItemID.ToString(); h["shoes_asset"] = wearable.AssetID.ToString(); wearable = GetWearableOfType(AvatarWearable.SOCKS); h["socks_item"] = wearable.ItemID.ToString(); h["socks_asset"] = wearable.AssetID.ToString(); wearable = GetWearableOfType(AvatarWearable.JACKET); h["jacket_item"] = wearable.ItemID.ToString(); h["jacket_asset"] = wearable.AssetID.ToString(); wearable = GetWearableOfType(AvatarWearable.GLOVES); h["gloves_item"] = wearable.ItemID.ToString(); h["gloves_asset"] = wearable.AssetID.ToString(); wearable = GetWearableOfType(AvatarWearable.UNDERSHIRT); h["undershirt_item"] = wearable.ItemID.ToString(); h["undershirt_asset"] = wearable.AssetID.ToString(); wearable = GetWearableOfType(AvatarWearable.UNDERPANTS); h["underpants_item"] = wearable.ItemID.ToString(); h["underpants_asset"] = wearable.AssetID.ToString(); wearable = GetWearableOfType(AvatarWearable.SKIRT); h["skirt_item"] = wearable.ItemID.ToString(); h["skirt_asset"] = wearable.AssetID.ToString(); wearable = GetWearableOfType(AvatarWearable.ALPHA); h["alpha_item"] = wearable.ItemID.ToString(); h["alpha_asset"] = wearable.AssetID.ToString(); wearable = GetWearableOfType(AvatarWearable.TATTOO); h["tattoo_item"] = wearable.ItemID.ToString(); h["tattoo_asset"] = wearable.AssetID.ToString(); wearable = GetWearableOfType(AvatarWearable.PHYSICS); h["physics_item"] = wearable.ItemID.ToString(); h["physics_asset"] = wearable.AssetID.ToString(); string attachments = GetAttachmentsString(); if (attachments != String.Empty) h["attachments"] = attachments; return h; } public AvatarAppearance(Hashtable h) { if (h == null) return; if (h.ContainsKey("owner")) Owner = new UUID((string)h["owner"]); else Owner = UUID.Zero; if (h.ContainsKey("serial")) Serial = Convert.ToInt32((string)h["serial"]); if (h.ContainsKey("visual_params")) VisualParams = (byte[])h["visual_params"]; else VisualParams = GetDefaultVisualParams(); if (h.ContainsKey("texture") && ((byte[])h["texture"] != null)) { byte[] textureData = (byte[])h["texture"]; Texture = new Primitive.TextureEntry(textureData, 0, textureData.Length); } else { Texture = GetDefaultTexture(); } if (h.ContainsKey("avatar_height")) AvatarHeight = (float)Convert.ToDouble((string)h["avatar_height"]); m_attachments = new Dictionary<int, List<AvatarAttachment>>(); m_wearables = new Dictionary<int, AvatarWearable>(); ClearWearables(); SetWearable(new AvatarWearable(AvatarWearable.BODY, new UUID((string)h["body_item"]), new UUID((string)h["body_asset"]))); SetWearable(new AvatarWearable(AvatarWearable.SKIN, new UUID((string)h["skin_item"]), new UUID((string)h["skin_asset"]))); SetWearable(new AvatarWearable(AvatarWearable.HAIR, new UUID((string)h["hair_item"]), new UUID((string)h["hair_asset"]))); SetWearable(new AvatarWearable(AvatarWearable.EYES, new UUID((string)h["eyes_item"]), new UUID((string)h["eyes_asset"]))); SetWearable(new AvatarWearable(AvatarWearable.SHIRT, new UUID((string)h["shirt_item"]), new UUID((string)h["shirt_asset"]))); SetWearable(new AvatarWearable(AvatarWearable.PANTS, new UUID((string)h["pants_item"]), new UUID((string)h["pants_asset"]))); SetWearable(new AvatarWearable(AvatarWearable.SHOES, new UUID((string)h["shoes_item"]), new UUID((string)h["shoes_asset"]))); SetWearable(new AvatarWearable(AvatarWearable.SOCKS, new UUID((string)h["socks_item"]), new UUID((string)h["socks_asset"]))); SetWearable(new AvatarWearable(AvatarWearable.JACKET, new UUID((string)h["jacket_item"]), new UUID((string)h["jacket_asset"]))); SetWearable(new AvatarWearable(AvatarWearable.GLOVES, new UUID((string)h["gloves_item"]), new UUID((string)h["gloves_asset"]))); SetWearable(new AvatarWearable(AvatarWearable.UNDERSHIRT, new UUID((string)h["undershirt_item"]), new UUID((string)h["undershirt_asset"]))); SetWearable(new AvatarWearable(AvatarWearable.UNDERPANTS, new UUID((string)h["underpants_item"]), new UUID((string)h["underpants_asset"]))); SetWearable(new AvatarWearable(AvatarWearable.SKIRT, new UUID((string)h["skirt_item"]), new UUID((string)h["skirt_asset"]))); SetWearable(new AvatarWearable(AvatarWearable.ALPHA, new UUID((string)h["alpha_item"]), new UUID((string)h["alpha_asset"]))); SetWearable(new AvatarWearable(AvatarWearable.TATTOO, new UUID((string)h["tattoo_item"]), new UUID((string)h["tattoo_asset"]))); SetWearable(new AvatarWearable(AvatarWearable.PHYSICS, new UUID((string)h["physics_item"]), new UUID((string)h["physics_asset"]))); if (h.ContainsKey("attachments")) { SetAttachmentsString(h["attachments"].ToString()); } } #region Wearables public void ClearWearables() { lock (m_wearables) { m_wearables.Clear(); SetWearable(AvatarWearable.DEFAULT_BODY); SetWearable(AvatarWearable.DEFAULT_HAIR); SetWearable(AvatarWearable.DEFAULT_SKIN); SetWearable(AvatarWearable.DEFAULT_EYES); } } /// <summary> /// Get the wearable of type "i". /// </summary> /// <remarks> /// </remarks> public AvatarWearable GetWearableOfType(int i) { lock (m_wearables) { if (m_wearables.ContainsKey(i)) return (m_wearables[i]); } return (new AvatarWearable(i, UUID.Zero, UUID.Zero)); } public void SetWearable(AvatarWearable wearable) { if ((wearable.WearableType < 0) || (wearable.WearableType >= AvatarWearable.MAX_WEARABLES)) { m_log.WarnFormat("[AVATAR APPEARANCE]: AvatarWearable type {0} is out of range", wearable.WearableType); return; } if (AvatarWearable.IsRequiredWearable(wearable.WearableType) && (wearable.ItemID == UUID.Zero)) { m_log.WarnFormat("[AVATAR APPEARANCE]: Refusing to set a ZERO wearable for a required item of type {0}", wearable.WearableType); return; } lock (m_wearables) { m_wearables[wearable.WearableType] = wearable; } } public List<AvatarWearable> GetWearables() { List<AvatarWearable> alist = new List<AvatarWearable>(); lock (m_wearables) { return (new List<AvatarWearable>(m_wearables.Values)); } } public List<int> GetWearableTypes() { lock (m_wearables) { return new List<int>(m_wearables.Keys); } } /// <summary> /// Rebuilds the entire list with locks held. Use this. /// </summary> /// <param name="attachments"></param> public void SetWearables(List<AvatarWearable> wearables) { lock (m_wearables) { // Will also make sure reasonable defaults are applied ClearWearables(); foreach (AvatarWearable wearable in wearables) { SetWearable(wearable); } } } public AvatarWearable GetWearableForItem(UUID itemID) { lock (m_wearables) { foreach (KeyValuePair<int, AvatarWearable> kvp in m_wearables) { if (kvp.Value.ItemID == itemID) return (kvp.Value); } } return null; } public int GetWearableType(UUID itemID) { AvatarWearable wearable = GetWearableForItem(itemID); if (wearable == null) return AvatarWearable.NONE; else return (wearable.WearableType); } #endregion #region Attachments /// <summary> /// Get a list of the attachments. /// </summary> /// <remarks> /// There may be duplicate attachpoints /// </remarks> public List<AvatarAttachment> GetAttachments() { List<AvatarAttachment> alist = new List<AvatarAttachment>(); lock (m_attachments) { foreach (KeyValuePair<int, List<AvatarAttachment>> kvp in m_attachments) { foreach (AvatarAttachment attach in kvp.Value) alist.Add(attach); } } return alist; } public List<int> GetAttachedPoints() { lock (m_attachments) { return new List<int>(m_attachments.Keys); } } public List<AvatarAttachment> GetAttachmentsAtPoint(int attachPoint) { lock (m_attachments) { return (new List<AvatarAttachment>(m_attachments[attachPoint])); } } internal void AppendAttachment(AvatarAttachment attach) { // m_log.DebugFormat( // "[AVATAR APPEARNCE]: Appending itemID={0}, assetID={1} at {2}", // attach.ItemID, attach.AssetID, attach.AttachPoint); lock (m_attachments) { if (!m_attachments.ContainsKey(attach.AttachPoint)) m_attachments[attach.AttachPoint] = new List<AvatarAttachment>(); m_attachments[attach.AttachPoint].Add(attach); } } internal void ReplaceAttachment(AvatarAttachment attach) { // m_log.DebugFormat( // "[AVATAR APPEARANCE]: Replacing itemID={0}, assetID={1} at {2}", // attach.ItemID, attach.AssetID, attach.AttachPoint); lock (m_attachments) { m_attachments[attach.AttachPoint] = new List<AvatarAttachment>(); m_attachments[attach.AttachPoint].Add(attach); } } /// <summary> /// Set an attachment /// </summary> /// <remarks> /// Append or Replace based on the append flag /// If item is passed in as UUID.Zero, then an any attachment at the /// attachpoint is removed. /// </remarks> /// <param name="attachpoint"></param> /// <param name="item"></param> /// <param name="asset"></param> /// <returns> /// return true if something actually changed /// </returns> public bool SetAttachment(int attachpoint, bool append, UUID item, UUID asset) { // m_log.DebugFormat( // "[AVATAR APPEARANCE]: Setting attachment at {0} with item ID {1}, asset ID {2}", // attachpoint, item, asset); if (attachpoint == 0) return false; if (item == UUID.Zero) { lock (m_attachments) { if (m_attachments.ContainsKey(attachpoint)) { m_attachments.Remove(attachpoint); return true; } } return false; } if (append) AppendAttachment(new AvatarAttachment(attachpoint, item, asset)); else ReplaceAttachment(new AvatarAttachment(attachpoint, item, asset)); return true; } /// <summary> /// Rebuilds the entire list with locks held. Use this. /// </summary> /// <param name="attachments"></param> public void SetAttachments(List<AvatarAttachment> attachments) { lock (m_attachments) { m_attachments.Clear(); foreach (AvatarAttachment attachment in attachments) { if (!m_attachments.ContainsKey(attachment.AttachPoint)) m_attachments.Add(attachment.AttachPoint, new List<AvatarAttachment>()); m_attachments[attachment.AttachPoint].Add(attachment); } } } /// <summary> /// Rebuilds the entire list with locks held. Use this. /// </summary> /// <param name="attachments"></param> public void SetAttachmentsForPoint(int attachPoint, List<AvatarAttachment> attachments) { lock (m_attachments) { m_attachments.Remove(attachPoint); foreach (AvatarAttachment attachment in attachments) { if (!m_attachments.ContainsKey(attachment.AttachPoint)) m_attachments.Add(attachment.AttachPoint, new List<AvatarAttachment>()); m_attachments[attachment.AttachPoint].Add(attachment); } } } /// <summary> /// If the item is already attached, return it. /// </summary> /// <param name="itemID"></param> /// <returns>Returns null if this item is not attached.</returns> public AvatarAttachment GetAttachmentForItem(UUID itemID) { lock (m_attachments) { foreach (KeyValuePair<int, List<AvatarAttachment>> kvp in m_attachments) { int index = kvp.Value.FindIndex(delegate(AvatarAttachment a) { return a.ItemID == itemID; }); if (index >= 0) return kvp.Value[index]; } } return null; } public int GetAttachpoint(UUID itemID) { lock (m_attachments) { foreach (KeyValuePair<int, List<AvatarAttachment>> kvp in m_attachments) { int index = kvp.Value.FindIndex(delegate(AvatarAttachment a) { return a.ItemID == itemID; }); if (index >= 0) return kvp.Key; } } return 0; } /// <summary> /// Remove an attachment if it exists /// </summary> /// <param name="itemID"></param> /// <returns>The AssetID for detached asset or UUID.Zero</returns> public UUID DetachAttachment(UUID itemID) { UUID assetID; lock (m_attachments) { foreach (KeyValuePair<int, List<AvatarAttachment>> kvp in m_attachments) { int index = kvp.Value.FindIndex(delegate(AvatarAttachment a) { return a.ItemID == itemID; }); if (index >= 0) { AvatarAttachment attachment = m_attachments[kvp.Key][index]; assetID = attachment.AssetID; // Remove it from the list of attachments at that attach point m_attachments[kvp.Key].RemoveAt(index); // And remove the list if there are no more attachments here if (m_attachments[kvp.Key].Count == 0) m_attachments.Remove(kvp.Key); return assetID; } } } return UUID.Zero; } string GetAttachmentsString() { List<string> strings = new List<string>(); lock (m_attachments) { foreach (KeyValuePair<int, List<AvatarAttachment>> kvp in m_attachments) { foreach (AvatarAttachment attachment in kvp.Value) { strings.Add(attachment.AttachPoint.ToString()); strings.Add(attachment.ItemID.ToString()); strings.Add(attachment.AssetID.ToString()); } } } return String.Join(",", strings.ToArray()); } void SetAttachmentsString(string data) { string[] strings = data.Split(new char[] { ',' }); int i = 0; List<AvatarAttachment> attachments = new List<AvatarAttachment>(); while (strings.Length - i > 2) { int attachpoint = Int32.Parse(strings[i]); UUID item = new UUID(strings[i + 1]); UUID sogId = new UUID(strings[i + 2]); i += 3; AvatarAttachment attachment = new AvatarAttachment(attachpoint, item, sogId); attachments.Add(attachment); } SetAttachments(attachments); } public void ClearAttachments() { lock (m_attachments) m_attachments.Clear(); } #endregion #region Packing Functions /// <summary> /// Create an OSDMap from the appearance data /// </summary> public OSDMap Pack() { OSDMap data = new OSDMap(); data["owner"] = OSD.FromUUID(Owner); data["serial"] = OSD.FromInteger(m_serial); data["height"] = OSD.FromReal(m_avatarHeight); // Wearables List<AvatarWearable> wearables = GetWearables(); OSDArray wears = new OSDArray(wearables.Count); foreach (AvatarWearable wearable in wearables) wears.Add(wearable.Pack()); data["wearables"] = wears; // Avatar Textures OSDArray textures = new OSDArray(AvatarAppearance.TEXTURE_COUNT); for (uint i = 0; i < AvatarAppearance.TEXTURE_COUNT; i++) { if (m_texture.FaceTextures[i] != null) textures.Add(OSD.FromUUID(m_texture.FaceTextures[i].TextureID)); else textures.Add(OSD.FromUUID(AppearanceManager.DEFAULT_AVATAR_TEXTURE)); } data["textures"] = textures; // Visual Parameters OSDBinary visualparams = new OSDBinary(m_visualparams); data["visualparams"] = visualparams; // Attachments List<AvatarAttachment> attachments = GetAttachments(); OSDArray attachs = new OSDArray(attachments.Count); foreach (AvatarAttachment attach in attachments) attachs.Add(attach.Pack()); data["attachments"] = attachs; return data; } /// <summary> /// Unpack and OSDMap and initialize the appearance /// from it /// </summary> public void Unpack(OSDMap data) { if (data == null) { m_log.Warn("[AVATAR APPEARANCE]: failed to unpack avatar appearance"); return; } if (data.ContainsKey("owner")) m_owner = data["owner"].AsUUID(); else m_owner = UUID.Zero; if (data.ContainsKey("serial")) m_serial = data["serial"].AsInteger(); if (data.ContainsKey("height")) m_avatarHeight = (float)data["height"].AsReal(); try { // Wearablles m_wearables = new Dictionary<int, AvatarWearable>(); ClearWearables(); if (data.ContainsKey("wearables") && ((data["wearables"]).Type == OSDType.Array)) { OSDArray wears = (OSDArray)data["wearables"]; for (int i = 0; i < wears.Count; i++) { AvatarWearable wearable = new AvatarWearable((OSDMap)wears[i]); SetWearable(wearable); } } else { m_log.Warn("[AVATAR APPEARANCE]: failed to unpack wearables"); } // Avatar Textures SetDefaultTexture(); if (data.ContainsKey("textures") && ((data["textures"]).Type == OSDType.Array)) { OSDArray textures = (OSDArray)(data["textures"]); for (int i = 0; i < AvatarAppearance.TEXTURE_COUNT && i < textures.Count; i++) { UUID textureID = AppearanceManager.DEFAULT_AVATAR_TEXTURE; if (textures[i] != null) textureID = textures[i].AsUUID(); m_texture.CreateFace((uint)i).TextureID = new UUID(textureID); } } else { m_log.Warn("[AVATAR APPEARANCE]: failed to unpack textures"); } // Visual Parameters SetDefaultParams(); if (data.ContainsKey("visualparams")) { if ((data["visualparams"].Type == OSDType.Binary) || (data["visualparams"].Type == OSDType.Array)) m_visualparams = data["visualparams"].AsBinary(); } else { m_log.Warn("[AVATAR APPEARANCE]: failed to unpack visual parameters"); } // Attachments m_attachments = new Dictionary<int, List<AvatarAttachment>>(); if (data.ContainsKey("attachments") && ((data["attachments"]).Type == OSDType.Array)) { OSDArray attachs = (OSDArray)(data["attachments"]); for (int i = 0; i < attachs.Count; i++) { AvatarAttachment att = new AvatarAttachment((OSDMap)attachs[i]); AppendAttachment(att); } } } catch (Exception e) { m_log.ErrorFormat("[AVATAR APPEARANCE]: unpack failed badly: {0}{1}", e.Message, e.StackTrace); } } #endregion } }
using DALBenchmark; using Revenj.DomainPatterns; using System; using System.Collections.Generic; using System.Data.Entity; using System.Data.Entity.Infrastructure; using System.Data.Objects.DataClasses; using System.Linq; using System.Linq.Expressions; namespace Benchmark { static class EntityBench { private static readonly DateTime Now = Factories.Now; private static readonly DateTime Today = Factories.Today; internal static void Run(BenchType type, int data) { Initialize.Postgres(); switch (type) { case BenchType.Simple: Program.RunBenchmark<EfPost>( new SimpleEntityBench(), Factories.NewSimple, Factories.UpdateSimple, SimpleEntityBench.Filter, data); break; case BenchType.Standard_Relations: Program.RunBenchmark<EfInvoice>( new StandardEntityBench(), StandardEntityBench.NewStandard, Factories.UpdateStandard, StandardEntityBench.Filter, data); break; case BenchType.Complex_Relations: // TODO handle non-scalar properties Program.RunBenchmark<EfBankScrape>( new ComplexRelationsEntityBench(), ComplexRelationsEntityBench.NewComplex, Factories.UpdateComplex, ComplexRelationsEntityBench.Filter, data); break; default: throw new NotSupportedException("not supported"); } } public partial class BenchEntities : DbContext { public BenchEntities() : base("name=EfContext") { this.Configuration.LazyLoadingEnabled = false; this.Configuration.ProxyCreationEnabled = false; this.Configuration.AutoDetectChangesEnabled = false; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { } public virtual DbSet<EfPost> Posts { get; set; } public virtual DbSet<EfInvoice> Invoices { get; set; } public virtual DbSet<EfBankScrape> BankScrapes { get; set; } } class SimpleEntityBench : BaseEntityBench<EfPost>, IBench<EfPost> { public void Clean() { using (var ctx = new BenchEntities()) { ctx.Database.ExecuteSqlCommand("TRUNCATE TABLE \"Simple\".\"Post\""); } } public SimpleEntityBench() : base(ctx => ctx.Posts, ctx => ctx.Posts) { } public override Expression<Func<EfPost, bool>> FindById(string ids) { var guid = new Guid(ids); return it => it.id == guid; } public override Expression<Func<EfPost, bool>> FindByIds(string[] ids) { var guids = ids.Select(it => new Guid(it)).ToList(); return it => guids.Contains(it.id); } public static Expression<Func<EfPost, bool>> Filter(int i) { var start = Today.AddDays(i); var end = Today.AddDays(i + 10); return it => it.created >= start && it.created <= end; } public override Expression<Func<EfPost, bool>> SubsetFilter(int i) { return Filter(i); } public Report<EfPost> Report(int i) { Func<int, Guid> gg = Factories.GetGuid; var id = gg(i); var ids = new[] { gg(i), gg(i + 2), gg(i + 5), gg(i + 7) }; var start = Today.AddDays(i); var end = Today.AddDays(i + 6); var dbQuery = GetDbSet(SharedContext).AsNoTracking(); var report = new Report<EfPost>(); report.findOne = dbQuery.Where(it => it.id == id).FirstOrDefault(); report.findMany = dbQuery.Where(it => ids.Contains(it.id)).ToList(); report.findFirst = dbQuery.Where(it => it.created >= start).OrderBy(it => it.created).FirstOrDefault(); report.findLast = dbQuery.Where(it => it.created <= end).OrderByDescending(it => it.created).FirstOrDefault(); report.topFive = dbQuery.Where(it => it.created >= start && it.created <= end).OrderBy(it => it.created).Take(5).ToList(); report.lastTen = dbQuery.Where(it => it.created >= start && it.created <= end).OrderByDescending(it => it.created).Take(10).ToList(); return report; } } class StandardEntityBench : BaseEntityBench<EfInvoice>, IBench<EfInvoice> { public StandardEntityBench() : base(ctx => ctx.Invoices, ctx => ctx.Invoices.Include("Item")) { } public void Clean() { using (var ctx = new BenchEntities()) { ctx.Database.ExecuteSqlCommand("TRUNCATE TABLE \"StandardRelations\".\"Invoice\" CASCADE"); } } public static void NewStandard(EfInvoice inv, int i) { Factories.NewStandard<EfItem>(inv, i); int cnt = 0; foreach (var it in inv.items) { it.Index = cnt++; it.Invoicenumber = inv.number; } } public override Expression<Func<EfInvoice, bool>> FindById(string id) { return it => it.number == id; } public override Expression<Func<EfInvoice, bool>> FindByIds(string[] ids) { return it => ids.Contains(it.number); } public static Expression<Func<EfInvoice, bool>> Filter(int i) { return it => it.version >= i && it.version <= i; } public override Expression<Func<EfInvoice, bool>> SubsetFilter(int i) { return Filter(i); } public Report<EfInvoice> Report(int i) { var id = i.ToString(); var ids = new[] { i.ToString(), (i + 2).ToString(), (i + 5).ToString(), (i + 7).ToString() }; var start = i; var end = i + 6; var dbQuery = GetDbSet(SharedContext).Include(p => p.Item).AsNoTracking(); var report = new Report<EfInvoice>(); report.findOne = dbQuery.Where(it => it.number == id).FirstOrDefault(); report.findMany = dbQuery.Where(it => ids.Contains(it.number)).ToList(); report.findFirst = dbQuery.Where(it => it.version >= start).OrderBy(it => it.createdAt).FirstOrDefault(); report.findLast = dbQuery.Where(it => it.version <= end).OrderByDescending(it => it.createdAt).FirstOrDefault(); report.topFive = dbQuery.Where(it => it.version >= start && it.version <= end).OrderBy(it => it.createdAt).Take(5).ToList(); report.lastTen = dbQuery.Where(it => it.version >= start && it.version <= end).OrderByDescending(it => it.createdAt).Take(10).ToList(); return report; } } class ComplexRelationsEntityBench : BaseEntityBench<EfBankScrape>, IBench<EfBankScrape> { public ComplexRelationsEntityBench() : base(ctx => ctx.BankScrapes, ctx => ctx.BankScrapes.Include("Account.Transaction")) { } public void Clean() { using (var ctx = new BenchEntities()) { ctx.Database.ExecuteSqlCommand("TRUNCATE TABLE \"ComplexRelations\".\"BankScrape\" CASCADE"); } } public static void NewComplex(EfBankScrape scrape, int i) { Factories.NewComplex<EfAccount, EfTransaction>(scrape, i); int cntAcc = 0; foreach (var acc in scrape.accounts) { acc.Index = cntAcc++; acc.BankScrapeid = scrape.id; int cntTran = 0; foreach (var tr in acc.transactions) { tr.AccountBankScrapeid = scrape.id; tr.AccountIndex = acc.Index; tr.Index = cntTran++; } } } public override Expression<Func<EfBankScrape, bool>> FindById(string id) { var key = int.Parse(id); return it => it.id == key; } public override Expression<Func<EfBankScrape, bool>> FindByIds(string[] ids) { var keys = ids.Select(it => int.Parse(it)).ToList(); return it => keys.Contains(it.id); } public static Expression<Func<EfBankScrape, bool>> Filter(int i) { var start = Now.AddMinutes(i); var end = Now.AddMinutes(i + 10); return it => it.createdAt >= start && it.createdAt <= end; } public override Expression<Func<EfBankScrape, bool>> SubsetFilter(int i) { return Filter(i); } public Report<EfBankScrape> Report(int i) { var ids = new[] { i, i + 2, i + 5, i + 7 }; var start = Now.AddMinutes(i); var end = Now.AddMinutes(i + 6); var dbQuery = GetDbSet(SharedContext).Include("Account.Transaction").AsNoTracking(); var report = new Report<EfBankScrape>(); report.findOne = dbQuery.Where(it => it.id == i).FirstOrDefault(); report.findMany = dbQuery.Where(it => ids.Contains(it.id)).ToList(); report.findFirst = dbQuery.Where(it => it.createdAt >= start).OrderBy(it => it.createdAt).FirstOrDefault(); report.findLast = dbQuery.Where(it => it.createdAt <= end).OrderByDescending(it => it.createdAt).FirstOrDefault(); report.topFive = dbQuery.Where(it => it.createdAt >= start && it.createdAt <= end).OrderBy(it => it.createdAt).Take(5).ToList(); report.lastTen = dbQuery.Where(it => it.createdAt >= start && it.createdAt <= end).OrderByDescending(it => it.createdAt).Take(10).ToList(); return report; } } abstract class BaseEntityBench<TEnt> where TEnt : EntityObject, IAggregateRoot, IEquatable<TEnt> { protected readonly Func<BenchEntities, DbSet<TEnt>> GetDbSet; protected readonly DbQuery<TEnt> DbQuery; protected readonly BenchEntities SharedContext = new BenchEntities(); public BaseEntityBench( Func<BenchEntities, DbSet<TEnt>> getDbSet, Func<BenchEntities, DbQuery<TEnt>> getDbQuery) { this.GetDbSet = getDbSet; //Disable tracking so objects are not read from cache, but rematerialized every time this.DbQuery = getDbQuery(SharedContext).AsNoTracking(); } public abstract Expression<Func<TEnt, bool>> FindById(string id); public abstract Expression<Func<TEnt, bool>> FindByIds(string[] id); public abstract Expression<Func<TEnt, bool>> SubsetFilter(int i); public TEnt FindSingle(string id) { //ISSUE: Find can't be used since it doesn't support include or cant be used without tracking return DbQuery.Where(FindById(id)).FirstOrDefault(); } public IEnumerable<TEnt> FindMany(string[] id) { return DbQuery.Where(FindByIds(id)).ToList(); } protected BenchEntities GetContext() { return new BenchEntities(); } public void Analyze() { using (var ctx = new BenchEntities()) { ctx.Database.ExecuteSqlCommand("ANALYZE"); } } public IQueryable<TEnt> Query() { return DbQuery; } public IEnumerable<TEnt> SearchAll() { return DbQuery.ToList(); } public IEnumerable<TEnt> SearchSubset(int i) { return DbQuery.Where(SubsetFilter(i)).ToList(); } public void Insert(IEnumerable<TEnt> values) { var ctx = GetContext(); GetDbSet(ctx).AddRange(values); ctx.SaveChanges(); ctx.Dispose(); } public void Update(IEnumerable<TEnt> values) { var ctx = GetContext(); foreach (var root in values) ctx.Entry(root).State = EntityState.Modified; ctx.SaveChanges(); ctx.Dispose(); } public void Insert(TEnt value) { var ctx = GetContext(); GetDbSet(ctx).Add(value); ctx.SaveChanges(); ctx.Dispose(); } public void Update(TEnt value) { var ctx = GetContext(); ctx.Entry(value).State = EntityState.Modified; ctx.SaveChanges(); ctx.Dispose(); } } } } namespace DALBenchmark { partial class EfPost : IAggregateRoot, IEquatable<EfPost> { public bool Equals(EfPost other) { return true;//TODO } public bool Equals(IEntity other) { var ef = other as EfPost; return ef != null && ef.id == this.id; } public string URI { get { return this.id.ToString(); } } } partial class EfInvoice : IAggregateRoot, IEquatable<EfInvoice> { public bool Equals(EfInvoice other) { return true;//TODO } public bool Equals(IEntity other) { var ef = other as EfInvoice; return ef != null && ef.number == this.number; } public string URI { get { return this.number; } } public EntityCollection<EfItem> items { get { return Item; } } } partial class EfBankScrape : IAggregateRoot, IEquatable<EfBankScrape> { public bool Equals(EfBankScrape other) { return true;//TODO } public bool Equals(IEntity other) { var ef = other as EfBankScrape; return ef != null && ef.id == this.id; } public string URI { get { return this.id.ToString(); } } public EntityCollection<EfAccount> accounts { get { return Account; } } } partial class EfAccount { public EntityCollection<EfTransaction> transactions { get { return Transaction; } } } }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. /* * The registry wrapper provides a common interface to both the transacted * and non-transacted registry APIs. It is used exclusively by the registry provider * to perform registry operations. In most cases, the wrapper simply forwards the * call to the appropriate registry API. */ using System; using System.Globalization; using Microsoft.Win32; using System.Security.AccessControl; using System.Management.Automation.Provider; using Microsoft.PowerShell.Commands.Internal; namespace Microsoft.PowerShell.Commands { #nullable enable internal interface IRegistryWrapper { void SetValue(string? name, object value); void SetValue(string? name, object value, RegistryValueKind valueKind); string[] GetValueNames(); void DeleteValue(string name); string[] GetSubKeyNames(); IRegistryWrapper? CreateSubKey(string subkey); IRegistryWrapper? OpenSubKey(string name, bool writable); void DeleteSubKeyTree(string subkey); object? GetValue(string? name); object? GetValue(string? name, object? defaultValue, RegistryValueOptions options); RegistryValueKind GetValueKind(string? name); object RegistryKey { get; } void SetAccessControl(ObjectSecurity securityDescriptor); ObjectSecurity GetAccessControl(AccessControlSections includeSections); void Close(); string Name { get; } int SubKeyCount { get; } } #nullable restore internal static class RegistryWrapperUtils { public static object ConvertValueToUIntFromRegistryIfNeeded(string name, object value, RegistryValueKind kind) { try { // Workaround for CLR bug that doesn't support full range of DWORD or QWORD if (kind == RegistryValueKind.DWord) { value = (int)value; if ((int)value < 0) { value = BitConverter.ToUInt32(BitConverter.GetBytes((int)value), 0); } } else if (kind == RegistryValueKind.QWord) { value = (long)value; if ((long)value < 0) { value = BitConverter.ToUInt64(BitConverter.GetBytes((long)value), 0); } } } catch (System.IO.IOException) { // This is expected if the value does not exist. } return value; } public static object ConvertUIntToValueForRegistryIfNeeded(object value, RegistryValueKind kind) { // Workaround for CLR bug that doesn't support full range of DWORD or QWORD if (kind == RegistryValueKind.DWord) { UInt32 intValue = 0; // See if it's already a positive number try { intValue = Convert.ToUInt32(value, CultureInfo.InvariantCulture); value = BitConverter.ToInt32(BitConverter.GetBytes(intValue), 0); } catch (OverflowException) { // It must be a negative Int32, and therefore need no more conversion } } else if (kind == RegistryValueKind.QWord) { UInt64 intValue = 0; // See if it's already a positive number try { intValue = Convert.ToUInt64(value, CultureInfo.InvariantCulture); value = BitConverter.ToInt64(BitConverter.GetBytes(intValue), 0); } catch (OverflowException) { // It must be a negative Int64, and therefore need no more conversion } } return value; } } internal class RegistryWrapper : IRegistryWrapper { private readonly RegistryKey _regKey; internal RegistryWrapper(RegistryKey regKey) { _regKey = regKey; } #region IRegistryWrapper Members public void SetValue(string name, object value) { _regKey.SetValue(name, value); } public void SetValue(string name, object value, RegistryValueKind valueKind) { value = System.Management.Automation.PSObject.Base(value); value = RegistryWrapperUtils.ConvertUIntToValueForRegistryIfNeeded(value, valueKind); _regKey.SetValue(name, value, valueKind); } public string[] GetValueNames() { return _regKey.GetValueNames(); } public void DeleteValue(string name) { _regKey.DeleteValue(name); } public string[] GetSubKeyNames() { return _regKey.GetSubKeyNames(); } public IRegistryWrapper CreateSubKey(string subkey) { RegistryKey newKey = _regKey.CreateSubKey(subkey); if (newKey == null) return null; else return new RegistryWrapper(newKey); } public IRegistryWrapper OpenSubKey(string name, bool writable) { RegistryKey newKey = _regKey.OpenSubKey(name, writable); if (newKey == null) return null; else return new RegistryWrapper(newKey); } public void DeleteSubKeyTree(string subkey) { _regKey.DeleteSubKeyTree(subkey); } public object GetValue(string name) { object value = _regKey.GetValue(name); try { value = RegistryWrapperUtils.ConvertValueToUIntFromRegistryIfNeeded(name, value, GetValueKind(name)); } catch (System.IO.IOException) { // This is expected if the value does not exist. } return value; } public object GetValue(string name, object defaultValue, RegistryValueOptions options) { object value = _regKey.GetValue(name, defaultValue, options); try { value = RegistryWrapperUtils.ConvertValueToUIntFromRegistryIfNeeded(name, value, GetValueKind(name)); } catch (System.IO.IOException) { // This is expected if the value does not exist. } return value; } public RegistryValueKind GetValueKind(string name) { return _regKey.GetValueKind(name); } public void Close() { _regKey.Dispose(); } public string Name { get { return _regKey.Name; } } public int SubKeyCount { get { return _regKey.SubKeyCount; } } public object RegistryKey { get { return _regKey; } } public void SetAccessControl(ObjectSecurity securityDescriptor) { _regKey.SetAccessControl((RegistrySecurity)securityDescriptor); } public ObjectSecurity GetAccessControl(AccessControlSections includeSections) { return _regKey.GetAccessControl(includeSections); } #endregion } internal class TransactedRegistryWrapper : IRegistryWrapper { private readonly TransactedRegistryKey _txRegKey; private readonly CmdletProvider _provider; internal TransactedRegistryWrapper(TransactedRegistryKey txRegKey, CmdletProvider provider) { _txRegKey = txRegKey; _provider = provider; } #region IRegistryWrapper Members public void SetValue(string name, object value) { using (_provider.CurrentPSTransaction) { _txRegKey.SetValue(name, value); } } public void SetValue(string name, object value, RegistryValueKind valueKind) { using (_provider.CurrentPSTransaction) { value = System.Management.Automation.PSObject.Base(value); value = RegistryWrapperUtils.ConvertUIntToValueForRegistryIfNeeded(value, valueKind); _txRegKey.SetValue(name, value, valueKind); } } public string[] GetValueNames() { using (_provider.CurrentPSTransaction) { return _txRegKey.GetValueNames(); } } public void DeleteValue(string name) { using (_provider.CurrentPSTransaction) { _txRegKey.DeleteValue(name); } } public string[] GetSubKeyNames() { using (_provider.CurrentPSTransaction) { return _txRegKey.GetSubKeyNames(); } } public IRegistryWrapper CreateSubKey(string subkey) { using (_provider.CurrentPSTransaction) { TransactedRegistryKey newKey = _txRegKey.CreateSubKey(subkey); if (newKey == null) return null; else return new TransactedRegistryWrapper(newKey, _provider); } } public IRegistryWrapper OpenSubKey(string name, bool writable) { using (_provider.CurrentPSTransaction) { TransactedRegistryKey newKey = _txRegKey.OpenSubKey(name, writable); if (newKey == null) return null; else return new TransactedRegistryWrapper(newKey, _provider); } } public void DeleteSubKeyTree(string subkey) { using (_provider.CurrentPSTransaction) { _txRegKey.DeleteSubKeyTree(subkey); } } public object GetValue(string name) { using (_provider.CurrentPSTransaction) { object value = _txRegKey.GetValue(name); try { value = RegistryWrapperUtils.ConvertValueToUIntFromRegistryIfNeeded(name, value, GetValueKind(name)); } catch (System.IO.IOException) { // This is expected if the value does not exist. } return value; } } public object GetValue(string name, object defaultValue, RegistryValueOptions options) { using (_provider.CurrentPSTransaction) { object value = _txRegKey.GetValue(name, defaultValue, options); try { value = RegistryWrapperUtils.ConvertValueToUIntFromRegistryIfNeeded(name, value, GetValueKind(name)); } catch (System.IO.IOException) { // This is expected if the value does not exist. } return value; } } public RegistryValueKind GetValueKind(string name) { using (_provider.CurrentPSTransaction) { return _txRegKey.GetValueKind(name); } } public void Close() { using (_provider.CurrentPSTransaction) { _txRegKey.Close(); } } public string Name { get { using (_provider.CurrentPSTransaction) { return _txRegKey.Name; } } } public int SubKeyCount { get { using (_provider.CurrentPSTransaction) { return _txRegKey.SubKeyCount; } } } public object RegistryKey { get { return _txRegKey; } } public void SetAccessControl(ObjectSecurity securityDescriptor) { using (_provider.CurrentPSTransaction) { _txRegKey.SetAccessControl((TransactedRegistrySecurity)securityDescriptor); } } public ObjectSecurity GetAccessControl(AccessControlSections includeSections) { using (_provider.CurrentPSTransaction) { return _txRegKey.GetAccessControl(includeSections); } } #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.Diagnostics; using System.Dynamic.Utils; namespace System.Linq.Expressions.Interpreter { internal abstract class MulInstruction : Instruction { private static Instruction s_Int16, s_Int32, s_Int64, s_UInt16, s_UInt32, s_UInt64, s_Single, s_Double; public override int ConsumedStack => 2; public override int ProducedStack => 1; public override string InstructionName => "Mul"; private MulInstruction() { } private sealed class MulInt16 : MulInstruction { public override int Run(InterpretedFrame frame) { int index = frame.StackIndex; object[] stack = frame.Data; object left = stack[index - 2]; if (left != null) { object right = stack[index - 1]; stack[index - 2] = right == null ? null : (object)unchecked((short)((short)left * (short)right)); } frame.StackIndex = index - 1; return 1; } } private sealed class MulInt32 : MulInstruction { public override int Run(InterpretedFrame frame) { int index = frame.StackIndex; object[] stack = frame.Data; object left = stack[index - 2]; if (left != null) { object right = stack[index - 1]; stack[index - 2] = right == null ? null : ScriptingRuntimeHelpers.Int32ToObject(unchecked((int)left * (int)right)); } frame.StackIndex = index - 1; return 1; } } private sealed class MulInt64 : MulInstruction { public override int Run(InterpretedFrame frame) { int index = frame.StackIndex; object[] stack = frame.Data; object left = stack[index - 2]; if (left != null) { object right = stack[index - 1]; stack[index - 2] = right == null ? null : (object)unchecked((long)left * (long)right); } frame.StackIndex = index - 1; return 1; } } private sealed class MulUInt16 : MulInstruction { public override int Run(InterpretedFrame frame) { int index = frame.StackIndex; object[] stack = frame.Data; object left = stack[index - 2]; if (left != null) { object right = stack[index - 1]; stack[index - 2] = right == null ? null : (object)unchecked((ushort)((ushort)left * (ushort)right)); } frame.StackIndex = index - 1; return 1; } } private sealed class MulUInt32 : MulInstruction { public override int Run(InterpretedFrame frame) { int index = frame.StackIndex; object[] stack = frame.Data; object left = stack[index - 2]; if (left != null) { object right = stack[index - 1]; stack[index - 2] = right == null ? null : (object)unchecked((uint)left * (uint)right); } frame.StackIndex = index - 1; return 1; } } private sealed class MulUInt64 : MulInstruction { public override int Run(InterpretedFrame frame) { int index = frame.StackIndex; object[] stack = frame.Data; object left = stack[index - 2]; if (left != null) { object right = stack[index - 1]; stack[index - 2] = right == null ? null : (object)unchecked((ulong)left * (ulong)right); } frame.StackIndex = index - 1; return 1; } } private sealed class MulSingle : MulInstruction { public override int Run(InterpretedFrame frame) { int index = frame.StackIndex; object[] stack = frame.Data; object left = stack[index - 2]; if (left != null) { object right = stack[index - 1]; stack[index - 2] = right == null ? null : (object)((float)left * (float)right); } frame.StackIndex = index - 1; return 1; } } private sealed class MulDouble : MulInstruction { public override int Run(InterpretedFrame frame) { int index = frame.StackIndex; object[] stack = frame.Data; object left = stack[index - 2]; if (left != null) { object right = stack[index - 1]; stack[index - 2] = right == null ? null : (object)((double)left * (double)right); } frame.StackIndex = index - 1; return 1; } } public static Instruction Create(Type type) { Debug.Assert(type.IsArithmetic()); return type.GetNonNullableType().GetTypeCode() switch { TypeCode.Int16 => s_Int16 ?? (s_Int16 = new MulInt16()), TypeCode.Int32 => s_Int32 ?? (s_Int32 = new MulInt32()), TypeCode.Int64 => s_Int64 ?? (s_Int64 = new MulInt64()), TypeCode.UInt16 => s_UInt16 ?? (s_UInt16 = new MulUInt16()), TypeCode.UInt32 => s_UInt32 ?? (s_UInt32 = new MulUInt32()), TypeCode.UInt64 => s_UInt64 ?? (s_UInt64 = new MulUInt64()), TypeCode.Single => s_Single ?? (s_Single = new MulSingle()), TypeCode.Double => s_Double ?? (s_Double = new MulDouble()), _ => throw ContractUtils.Unreachable, }; } } internal abstract class MulOvfInstruction : Instruction { private static Instruction s_Int16, s_Int32, s_Int64, s_UInt16, s_UInt32, s_UInt64; public override int ConsumedStack => 2; public override int ProducedStack => 1; public override string InstructionName => "MulOvf"; private MulOvfInstruction() { } private sealed class MulOvfInt16 : MulOvfInstruction { public override int Run(InterpretedFrame frame) { int index = frame.StackIndex; object[] stack = frame.Data; object left = stack[index - 2]; if (left != null) { object right = stack[index - 1]; stack[index - 2] = right == null ? null : (object)checked((short)((short)left * (short)right)); } frame.StackIndex = index - 1; return 1; } } private sealed class MulOvfInt32 : MulOvfInstruction { public override int Run(InterpretedFrame frame) { int index = frame.StackIndex; object[] stack = frame.Data; object left = stack[index - 2]; if (left != null) { object right = stack[index - 1]; stack[index - 2] = right == null ? null : ScriptingRuntimeHelpers.Int32ToObject(checked((int)left * (int)right)); } frame.StackIndex = index - 1; return 1; } } private sealed class MulOvfInt64 : MulOvfInstruction { public override int Run(InterpretedFrame frame) { int index = frame.StackIndex; object[] stack = frame.Data; object left = stack[index - 2]; if (left != null) { object right = stack[index - 1]; stack[index - 2] = right == null ? null : (object)checked((long)left * (long)right); } frame.StackIndex = index - 1; return 1; } } private sealed class MulOvfUInt16 : MulOvfInstruction { public override int Run(InterpretedFrame frame) { int index = frame.StackIndex; object[] stack = frame.Data; object left = stack[index - 2]; if (left != null) { object right = stack[index - 1]; stack[index - 2] = right == null ? null : (object)checked((ushort)((ushort)left * (ushort)right)); } frame.StackIndex = index - 1; return 1; } } private sealed class MulOvfUInt32 : MulOvfInstruction { public override int Run(InterpretedFrame frame) { int index = frame.StackIndex; object[] stack = frame.Data; object left = stack[index - 2]; if (left != null) { object right = stack[index - 1]; stack[index - 2] = right == null ? null : (object)checked((uint)left * (uint)right); } frame.StackIndex = index - 1; return 1; } } private sealed class MulOvfUInt64 : MulOvfInstruction { public override int Run(InterpretedFrame frame) { int index = frame.StackIndex; object[] stack = frame.Data; object left = stack[index - 2]; if (left != null) { object right = stack[index - 1]; stack[index - 2] = right == null ? null : (object)checked((ulong)left * (ulong)right); } frame.StackIndex = index - 1; return 1; } } public static Instruction Create(Type type) { Debug.Assert(type.IsArithmetic()); return type.GetNonNullableType().GetTypeCode() switch { TypeCode.Int16 => s_Int16 ?? (s_Int16 = new MulOvfInt16()), TypeCode.Int32 => s_Int32 ?? (s_Int32 = new MulOvfInt32()), TypeCode.Int64 => s_Int64 ?? (s_Int64 = new MulOvfInt64()), TypeCode.UInt16 => s_UInt16 ?? (s_UInt16 = new MulOvfUInt16()), TypeCode.UInt32 => s_UInt32 ?? (s_UInt32 = new MulOvfUInt32()), TypeCode.UInt64 => s_UInt64 ?? (s_UInt64 = new MulOvfUInt64()), _ => MulInstruction.Create(type), }; } } }
// Copyright 2018 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 Google.Api.Gax; using Google.Api.Gax.Grpc; using Google.LongRunning; using Google.Protobuf.WellKnownTypes; using Grpc.Core; using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace Google.Cloud.VideoIntelligence.V1 { /// <summary> /// Settings for a <see cref="VideoIntelligenceServiceClient"/>. /// </summary> public sealed partial class VideoIntelligenceServiceSettings : ServiceSettingsBase { /// <summary> /// Get a new instance of the default <see cref="VideoIntelligenceServiceSettings"/>. /// </summary> /// <returns> /// A new instance of the default <see cref="VideoIntelligenceServiceSettings"/>. /// </returns> public static VideoIntelligenceServiceSettings GetDefault() => new VideoIntelligenceServiceSettings(); /// <summary> /// Constructs a new <see cref="VideoIntelligenceServiceSettings"/> object with default settings. /// </summary> public VideoIntelligenceServiceSettings() { } private VideoIntelligenceServiceSettings(VideoIntelligenceServiceSettings existing) : base(existing) { GaxPreconditions.CheckNotNull(existing, nameof(existing)); AnnotateVideoSettings = existing.AnnotateVideoSettings; AnnotateVideoOperationsSettings = existing.AnnotateVideoOperationsSettings?.Clone(); OnCopy(existing); } partial void OnCopy(VideoIntelligenceServiceSettings existing); /// <summary> /// The filter specifying which RPC <see cref="StatusCode"/>s are eligible for retry /// for "Idempotent" <see cref="VideoIntelligenceServiceClient"/> RPC methods. /// </summary> /// <remarks> /// The eligible RPC <see cref="StatusCode"/>s for retry for "Idempotent" RPC methods are: /// <list type="bullet"> /// <item><description><see cref="StatusCode.DeadlineExceeded"/></description></item> /// <item><description><see cref="StatusCode.Unavailable"/></description></item> /// </list> /// </remarks> public static Predicate<RpcException> IdempotentRetryFilter { get; } = RetrySettings.FilterForStatusCodes(StatusCode.DeadlineExceeded, StatusCode.Unavailable); /// <summary> /// The filter specifying which RPC <see cref="StatusCode"/>s are eligible for retry /// for "NonIdempotent" <see cref="VideoIntelligenceServiceClient"/> RPC methods. /// </summary> /// <remarks> /// There are no RPC <see cref="StatusCode"/>s eligible for retry for "NonIdempotent" RPC methods. /// </remarks> public static Predicate<RpcException> NonIdempotentRetryFilter { get; } = RetrySettings.FilterForStatusCodes(); /// <summary> /// "Default" retry backoff for <see cref="VideoIntelligenceServiceClient"/> RPC methods. /// </summary> /// <returns> /// The "Default" retry backoff for <see cref="VideoIntelligenceServiceClient"/> RPC methods. /// </returns> /// <remarks> /// The "Default" retry backoff for <see cref="VideoIntelligenceServiceClient"/> RPC methods is defined as: /// <list type="bullet"> /// <item><description>Initial delay: 1000 milliseconds</description></item> /// <item><description>Maximum delay: 120000 milliseconds</description></item> /// <item><description>Delay multiplier: 2.5</description></item> /// </list> /// </remarks> public static BackoffSettings GetDefaultRetryBackoff() => new BackoffSettings( delay: TimeSpan.FromMilliseconds(1000), maxDelay: TimeSpan.FromMilliseconds(120000), delayMultiplier: 2.5 ); /// <summary> /// "Default" timeout backoff for <see cref="VideoIntelligenceServiceClient"/> RPC methods. /// </summary> /// <returns> /// The "Default" timeout backoff for <see cref="VideoIntelligenceServiceClient"/> RPC methods. /// </returns> /// <remarks> /// The "Default" timeout backoff for <see cref="VideoIntelligenceServiceClient"/> RPC methods is defined as: /// <list type="bullet"> /// <item><description>Initial timeout: 120000 milliseconds</description></item> /// <item><description>Timeout multiplier: 1.0</description></item> /// <item><description>Maximum timeout: 120000 milliseconds</description></item> /// </list> /// </remarks> public static BackoffSettings GetDefaultTimeoutBackoff() => new BackoffSettings( delay: TimeSpan.FromMilliseconds(120000), maxDelay: TimeSpan.FromMilliseconds(120000), delayMultiplier: 1.0 ); /// <summary> /// <see cref="CallSettings"/> for synchronous and asynchronous calls to /// <c>VideoIntelligenceServiceClient.AnnotateVideo</c> and <c>VideoIntelligenceServiceClient.AnnotateVideoAsync</c>. /// </summary> /// <remarks> /// The default <c>VideoIntelligenceServiceClient.AnnotateVideo</c> and /// <c>VideoIntelligenceServiceClient.AnnotateVideoAsync</c> <see cref="RetrySettings"/> are: /// <list type="bullet"> /// <item><description>Initial retry delay: 1000 milliseconds</description></item> /// <item><description>Retry delay multiplier: 2.5</description></item> /// <item><description>Retry maximum delay: 120000 milliseconds</description></item> /// <item><description>Initial timeout: 120000 milliseconds</description></item> /// <item><description>Timeout multiplier: 1.0</description></item> /// <item><description>Timeout maximum delay: 120000 milliseconds</description></item> /// </list> /// Retry will be attempted on the following response status codes: /// <list> /// <item><description><see cref="StatusCode.DeadlineExceeded"/></description></item> /// <item><description><see cref="StatusCode.Unavailable"/></description></item> /// </list> /// Default RPC expiration is 600000 milliseconds. /// </remarks> public CallSettings AnnotateVideoSettings { get; set; } = CallSettings.FromCallTiming( CallTiming.FromRetry(new RetrySettings( retryBackoff: GetDefaultRetryBackoff(), timeoutBackoff: GetDefaultTimeoutBackoff(), totalExpiration: Expiration.FromTimeout(TimeSpan.FromMilliseconds(600000)), retryFilter: IdempotentRetryFilter ))); /// <summary> /// Long Running Operation settings for calls to <c>VideoIntelligenceServiceClient.AnnotateVideo</c>. /// </summary> /// <remarks> /// Uses default <see cref="PollSettings"/> of: /// <list type="bullet"> /// <item><description>Initial delay: 20000 milliseconds</description></item> /// <item><description>Delay multiplier: 1.5</description></item> /// <item><description>Maximum delay: 45000 milliseconds</description></item> /// <item><description>Total timeout: 86400000 milliseconds</description></item> /// </list> /// </remarks> public OperationsSettings AnnotateVideoOperationsSettings { get; set; } = new OperationsSettings { DefaultPollSettings = new PollSettings( Expiration.FromTimeout(TimeSpan.FromMilliseconds(86400000L)), TimeSpan.FromMilliseconds(20000L), 1.5, TimeSpan.FromMilliseconds(45000L)) }; /// <summary> /// Creates a deep clone of this object, with all the same property values. /// </summary> /// <returns>A deep clone of this <see cref="VideoIntelligenceServiceSettings"/> object.</returns> public VideoIntelligenceServiceSettings Clone() => new VideoIntelligenceServiceSettings(this); } /// <summary> /// VideoIntelligenceService client wrapper, for convenient use. /// </summary> public abstract partial class VideoIntelligenceServiceClient { /// <summary> /// The default endpoint for the VideoIntelligenceService service, which is a host of "videointelligence.googleapis.com" and a port of 443. /// </summary> public static ServiceEndpoint DefaultEndpoint { get; } = new ServiceEndpoint("videointelligence.googleapis.com", 443); /// <summary> /// The default VideoIntelligenceService scopes. /// </summary> /// <remarks> /// The default VideoIntelligenceService scopes are: /// <list type="bullet"> /// <item><description>"https://www.googleapis.com/auth/cloud-platform"</description></item> /// </list> /// </remarks> public static IReadOnlyList<string> DefaultScopes { get; } = new ReadOnlyCollection<string>(new string[] { "https://www.googleapis.com/auth/cloud-platform", }); private static readonly ChannelPool s_channelPool = new ChannelPool(DefaultScopes); // Note: we could have parameterless overloads of Create and CreateAsync, // documented to just use the default endpoint, settings and credentials. // Pros: // - Might be more reassuring on first use // - Allows method group conversions // Con: overloads! /// <summary> /// Asynchronously creates a <see cref="VideoIntelligenceServiceClient"/>, applying defaults for all unspecified settings, /// and creating a channel connecting to the given endpoint with application default credentials where /// necessary. /// </summary> /// <param name="endpoint">Optional <see cref="ServiceEndpoint"/>.</param> /// <param name="settings">Optional <see cref="VideoIntelligenceServiceSettings"/>.</param> /// <returns>The task representing the created <see cref="VideoIntelligenceServiceClient"/>.</returns> public static async Task<VideoIntelligenceServiceClient> CreateAsync(ServiceEndpoint endpoint = null, VideoIntelligenceServiceSettings settings = null) { Channel channel = await s_channelPool.GetChannelAsync(endpoint ?? DefaultEndpoint).ConfigureAwait(false); return Create(channel, settings); } /// <summary> /// Synchronously creates a <see cref="VideoIntelligenceServiceClient"/>, applying defaults for all unspecified settings, /// and creating a channel connecting to the given endpoint with application default credentials where /// necessary. /// </summary> /// <param name="endpoint">Optional <see cref="ServiceEndpoint"/>.</param> /// <param name="settings">Optional <see cref="VideoIntelligenceServiceSettings"/>.</param> /// <returns>The created <see cref="VideoIntelligenceServiceClient"/>.</returns> public static VideoIntelligenceServiceClient Create(ServiceEndpoint endpoint = null, VideoIntelligenceServiceSettings settings = null) { Channel channel = s_channelPool.GetChannel(endpoint ?? DefaultEndpoint); return Create(channel, settings); } /// <summary> /// Creates a <see cref="VideoIntelligenceServiceClient"/> which uses the specified channel for remote operations. /// </summary> /// <param name="channel">The <see cref="Channel"/> for remote operations. Must not be null.</param> /// <param name="settings">Optional <see cref="VideoIntelligenceServiceSettings"/>.</param> /// <returns>The created <see cref="VideoIntelligenceServiceClient"/>.</returns> public static VideoIntelligenceServiceClient Create(Channel channel, VideoIntelligenceServiceSettings settings = null) { GaxPreconditions.CheckNotNull(channel, nameof(channel)); VideoIntelligenceService.VideoIntelligenceServiceClient grpcClient = new VideoIntelligenceService.VideoIntelligenceServiceClient(channel); return new VideoIntelligenceServiceClientImpl(grpcClient, settings); } /// <summary> /// Shuts down any channels automatically created by <see cref="Create(ServiceEndpoint, VideoIntelligenceServiceSettings)"/> /// and <see cref="CreateAsync(ServiceEndpoint, VideoIntelligenceServiceSettings)"/>. Channels which weren't automatically /// created are not affected. /// </summary> /// <remarks>After calling this method, further calls to <see cref="Create(ServiceEndpoint, VideoIntelligenceServiceSettings)"/> /// and <see cref="CreateAsync(ServiceEndpoint, VideoIntelligenceServiceSettings)"/> will create new channels, which could /// in turn be shut down by another call to this method.</remarks> /// <returns>A task representing the asynchronous shutdown operation.</returns> public static Task ShutdownDefaultChannelsAsync() => s_channelPool.ShutdownChannelsAsync(); /// <summary> /// The underlying gRPC VideoIntelligenceService client. /// </summary> public virtual VideoIntelligenceService.VideoIntelligenceServiceClient GrpcClient { get { throw new NotImplementedException(); } } /// <summary> /// Performs asynchronous video annotation. Progress and results can be /// retrieved through the `google.longrunning.Operations` interface. /// `Operation.metadata` contains `AnnotateVideoProgress` (progress). /// `Operation.response` contains `AnnotateVideoResponse` (results). /// </summary> /// <param name="inputUri"> /// Input video location. Currently, only /// [Google Cloud Storage](https://cloud.google.com/storage/) URIs are /// supported, which must be specified in the following format: /// `gs://bucket-id/object-id` (other URI formats return /// [google.rpc.Code.INVALID_ARGUMENT][google.rpc.Code.INVALID_ARGUMENT]). For more information, see /// [Request URIs](/storage/docs/reference-uris). /// A video URI may include wildcards in `object-id`, and thus identify /// multiple videos. Supported wildcards: '*' to match 0 or more characters; /// '?' to match 1 character. If unset, the input video should be embedded /// in the request as `input_content`. If set, `input_content` should be unset. /// </param> /// <param name="features"> /// Requested video annotation features. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public virtual Task<Operation<AnnotateVideoResponse, AnnotateVideoProgress>> AnnotateVideoAsync( string inputUri, IEnumerable<Feature> features, CallSettings callSettings = null) => AnnotateVideoAsync( new AnnotateVideoRequest { InputUri = inputUri ?? "", // Optional Features = { features ?? Enumerable.Empty<Feature>() }, // Optional }, callSettings); /// <summary> /// Performs asynchronous video annotation. Progress and results can be /// retrieved through the `google.longrunning.Operations` interface. /// `Operation.metadata` contains `AnnotateVideoProgress` (progress). /// `Operation.response` contains `AnnotateVideoResponse` (results). /// </summary> /// <param name="inputUri"> /// Input video location. Currently, only /// [Google Cloud Storage](https://cloud.google.com/storage/) URIs are /// supported, which must be specified in the following format: /// `gs://bucket-id/object-id` (other URI formats return /// [google.rpc.Code.INVALID_ARGUMENT][google.rpc.Code.INVALID_ARGUMENT]). For more information, see /// [Request URIs](/storage/docs/reference-uris). /// A video URI may include wildcards in `object-id`, and thus identify /// multiple videos. Supported wildcards: '*' to match 0 or more characters; /// '?' to match 1 character. If unset, the input video should be embedded /// in the request as `input_content`. If set, `input_content` should be unset. /// </param> /// <param name="features"> /// Requested video annotation features. /// </param> /// <param name="cancellationToken"> /// A <see cref="CancellationToken"/> to use for this RPC. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public virtual Task<Operation<AnnotateVideoResponse, AnnotateVideoProgress>> AnnotateVideoAsync( string inputUri, IEnumerable<Feature> features, CancellationToken cancellationToken) => AnnotateVideoAsync( inputUri, features, CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Performs asynchronous video annotation. Progress and results can be /// retrieved through the `google.longrunning.Operations` interface. /// `Operation.metadata` contains `AnnotateVideoProgress` (progress). /// `Operation.response` contains `AnnotateVideoResponse` (results). /// </summary> /// <param name="inputUri"> /// Input video location. Currently, only /// [Google Cloud Storage](https://cloud.google.com/storage/) URIs are /// supported, which must be specified in the following format: /// `gs://bucket-id/object-id` (other URI formats return /// [google.rpc.Code.INVALID_ARGUMENT][google.rpc.Code.INVALID_ARGUMENT]). For more information, see /// [Request URIs](/storage/docs/reference-uris). /// A video URI may include wildcards in `object-id`, and thus identify /// multiple videos. Supported wildcards: '*' to match 0 or more characters; /// '?' to match 1 character. If unset, the input video should be embedded /// in the request as `input_content`. If set, `input_content` should be unset. /// </param> /// <param name="features"> /// Requested video annotation features. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// The RPC response. /// </returns> public virtual Operation<AnnotateVideoResponse, AnnotateVideoProgress> AnnotateVideo( string inputUri, IEnumerable<Feature> features, CallSettings callSettings = null) => AnnotateVideo( new AnnotateVideoRequest { InputUri = inputUri ?? "", // Optional Features = { features ?? Enumerable.Empty<Feature>() }, // Optional }, callSettings); /// <summary> /// Performs asynchronous video annotation. Progress and results can be /// retrieved through the `google.longrunning.Operations` interface. /// `Operation.metadata` contains `AnnotateVideoProgress` (progress). /// `Operation.response` contains `AnnotateVideoResponse` (results). /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public virtual Task<Operation<AnnotateVideoResponse, AnnotateVideoProgress>> AnnotateVideoAsync( AnnotateVideoRequest request, CallSettings callSettings = null) { throw new NotImplementedException(); } /// <summary> /// Asynchronously poll an operation once, using an <c>operationName</c> from a previous invocation of <c>AnnotateVideoAsync</c>. /// </summary> /// <param name="operationName">The name of a previously invoked operation. Must not be <c>null</c> or empty.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A task representing the result of polling the operation.</returns> public virtual Task<Operation<AnnotateVideoResponse, AnnotateVideoProgress>> PollOnceAnnotateVideoAsync( string operationName, CallSettings callSettings = null) => Operation<AnnotateVideoResponse, AnnotateVideoProgress>.PollOnceFromNameAsync( GaxPreconditions.CheckNotNullOrEmpty(operationName, nameof(operationName)), AnnotateVideoOperationsClient, callSettings); /// <summary> /// Performs asynchronous video annotation. Progress and results can be /// retrieved through the `google.longrunning.Operations` interface. /// `Operation.metadata` contains `AnnotateVideoProgress` (progress). /// `Operation.response` contains `AnnotateVideoResponse` (results). /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// The RPC response. /// </returns> public virtual Operation<AnnotateVideoResponse, AnnotateVideoProgress> AnnotateVideo( AnnotateVideoRequest request, CallSettings callSettings = null) { throw new NotImplementedException(); } /// <summary> /// The long-running operations client for <c>AnnotateVideo</c>. /// </summary> public virtual OperationsClient AnnotateVideoOperationsClient { get { throw new NotImplementedException(); } } /// <summary> /// Poll an operation once, using an <c>operationName</c> from a previous invocation of <c>AnnotateVideo</c>. /// </summary> /// <param name="operationName">The name of a previously invoked operation. Must not be <c>null</c> or empty.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The result of polling the operation.</returns> public virtual Operation<AnnotateVideoResponse, AnnotateVideoProgress> PollOnceAnnotateVideo( string operationName, CallSettings callSettings = null) => Operation<AnnotateVideoResponse, AnnotateVideoProgress>.PollOnceFromName( GaxPreconditions.CheckNotNullOrEmpty(operationName, nameof(operationName)), AnnotateVideoOperationsClient, callSettings); } /// <summary> /// VideoIntelligenceService client wrapper implementation, for convenient use. /// </summary> public sealed partial class VideoIntelligenceServiceClientImpl : VideoIntelligenceServiceClient { private readonly ApiCall<AnnotateVideoRequest, Operation> _callAnnotateVideo; /// <summary> /// Constructs a client wrapper for the VideoIntelligenceService service, with the specified gRPC client and settings. /// </summary> /// <param name="grpcClient">The underlying gRPC client.</param> /// <param name="settings">The base <see cref="VideoIntelligenceServiceSettings"/> used within this client </param> public VideoIntelligenceServiceClientImpl(VideoIntelligenceService.VideoIntelligenceServiceClient grpcClient, VideoIntelligenceServiceSettings settings) { GrpcClient = grpcClient; VideoIntelligenceServiceSettings effectiveSettings = settings ?? VideoIntelligenceServiceSettings.GetDefault(); ClientHelper clientHelper = new ClientHelper(effectiveSettings); AnnotateVideoOperationsClient = new OperationsClientImpl( grpcClient.CreateOperationsClient(), effectiveSettings.AnnotateVideoOperationsSettings); _callAnnotateVideo = clientHelper.BuildApiCall<AnnotateVideoRequest, Operation>( GrpcClient.AnnotateVideoAsync, GrpcClient.AnnotateVideo, effectiveSettings.AnnotateVideoSettings); OnConstruction(grpcClient, effectiveSettings, clientHelper); } partial void OnConstruction(VideoIntelligenceService.VideoIntelligenceServiceClient grpcClient, VideoIntelligenceServiceSettings effectiveSettings, ClientHelper clientHelper); /// <summary> /// The underlying gRPC VideoIntelligenceService client. /// </summary> public override VideoIntelligenceService.VideoIntelligenceServiceClient GrpcClient { get; } // Partial modifier methods contain '_' to ensure no name conflicts with RPC methods. partial void Modify_AnnotateVideoRequest(ref AnnotateVideoRequest request, ref CallSettings settings); /// <summary> /// Performs asynchronous video annotation. Progress and results can be /// retrieved through the `google.longrunning.Operations` interface. /// `Operation.metadata` contains `AnnotateVideoProgress` (progress). /// `Operation.response` contains `AnnotateVideoResponse` (results). /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public override async Task<Operation<AnnotateVideoResponse, AnnotateVideoProgress>> AnnotateVideoAsync( AnnotateVideoRequest request, CallSettings callSettings = null) { Modify_AnnotateVideoRequest(ref request, ref callSettings); return new Operation<AnnotateVideoResponse, AnnotateVideoProgress>( await _callAnnotateVideo.Async(request, callSettings).ConfigureAwait(false), AnnotateVideoOperationsClient); } /// <summary> /// Performs asynchronous video annotation. Progress and results can be /// retrieved through the `google.longrunning.Operations` interface. /// `Operation.metadata` contains `AnnotateVideoProgress` (progress). /// `Operation.response` contains `AnnotateVideoResponse` (results). /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// The RPC response. /// </returns> public override Operation<AnnotateVideoResponse, AnnotateVideoProgress> AnnotateVideo( AnnotateVideoRequest request, CallSettings callSettings = null) { Modify_AnnotateVideoRequest(ref request, ref callSettings); return new Operation<AnnotateVideoResponse, AnnotateVideoProgress>( _callAnnotateVideo.Sync(request, callSettings), AnnotateVideoOperationsClient); } /// <summary> /// The long-running operations client for <c>AnnotateVideo</c>. /// </summary> public override OperationsClient AnnotateVideoOperationsClient { get; } } // Partial classes to enable page-streaming // Partial Grpc class to enable LRO client creation public static partial class VideoIntelligenceService { public partial class VideoIntelligenceServiceClient { /// <summary> /// Creates a new instance of <see cref="Operations.OperationsClient"/> using the same call invoker as this client. /// </summary> /// <returns>A new Operations client for the same target as this client.</returns> public virtual Operations.OperationsClient CreateOperationsClient() => new Operations.OperationsClient(CallInvoker); } } }
#region License // Distributed under the MIT License // ============================================================ // Copyright (c) 2019 Hotcakes Commerce, 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. #endregion using System; using System.Globalization; using System.Web.UI.WebControls; using Hotcakes.Commerce.Shipping; using Hotcakes.Commerce.Utilities; using Hotcakes.Modules.Core.Admin.AppCode; using Hotcakes.Shipping; using Hotcakes.Shipping.Services; namespace Hotcakes.Modules.Core.Modules.Shipping.Rate_Table_by_Total_Price { partial class Edit : HccShippingPart { protected override void OnInit(EventArgs e) { base.OnInit(e); LocalizeView(); AddHighlightColors(lstHighlights); LoadZones(); LoadData(); LoadLevels(); } protected void btnCancel_Click(object sender, EventArgs e) { NotifyFinishedEditing("Canceled"); } protected void btnSave_Click(object sender, EventArgs e) { SaveData(); NotifyFinishedEditing(NameField.Text.Trim()); } private void LoadZones() { lstZones.DataSource = HccApp.OrderServices.ShippingZones.FindForStore(HccApp.CurrentStore.Id); lstZones.DataTextField = "Name"; lstZones.DataValueField = "id"; lstZones.DataBind(); } private void LoadData() { NameField.Text = ShippingMethod.Name; if (NameField.Text == string.Empty) { NameField.Text = Localization.GetString("RateTableByTotalPrice"); } AdjustmentDropDownList.SelectedValue = ((int) ShippingMethod.AdjustmentType).ToString(); if (ShippingMethod.AdjustmentType == ShippingMethodAdjustmentType.Amount) { AdjustmentTextBox.Text = string.Format("{0:c}", ShippingMethod.Adjustment); } else { AdjustmentTextBox.Text = string.Format("{0:f}", ShippingMethod.Adjustment); } // ZONES if (lstZones.Items.FindByValue(ShippingMethod.ZoneId.ToString()) != null) { lstZones.ClearSelection(); lstZones.Items.FindByValue(ShippingMethod.ZoneId.ToString()).Selected = true; } // Select Hightlights var highlight = ShippingMethod.Settings.GetSettingOrEmpty("highlight"); if (lstHighlights.Items.FindByText(highlight) != null) { lstHighlights.ClearSelection(); lstHighlights.Items.FindByText(highlight).Selected = true; } } private void LoadLevels() { var settings = new RateTableSettings(); settings.Merge(ShippingMethod.Settings); var levels = settings.GetLevels(); gvRates.DataSource = levels; gvRates.DataBind(); } private void SaveData() { ShippingMethod.Name = NameField.Text.Trim(); ShippingMethod.AdjustmentType = (ShippingMethodAdjustmentType) int.Parse(AdjustmentDropDownList.SelectedValue); ShippingMethod.Adjustment = decimal.Parse(AdjustmentTextBox.Text, NumberStyles.Currency); if (ShippingMethod.AdjustmentType == ShippingMethodAdjustmentType.Amount) { ShippingMethod.Adjustment = Money.RoundCurrency(ShippingMethod.Adjustment); } ShippingMethod.ZoneId = long.Parse(lstZones.SelectedItem.Value); ShippingMethod.Settings["highlight"] = lstHighlights.SelectedValue; } protected void btnNew_Click(object sender, EventArgs e) { var r = new RateTableLevel { Level = decimal.Parse(NewLevelField.Text), Rate = decimal.Parse(NewAmountField.Text), Percent = decimal.Parse(NewPercentField.Text) }; var settings = new RateTableSettings(); settings.Merge(ShippingMethod.Settings); settings.AddLevel(r); ShippingMethod.Settings = settings; HccApp.OrderServices.ShippingMethods.Update(ShippingMethod); LoadLevels(); } private void RemoveLevel(string level, string rate, string percent) { var settings = new RateTableSettings(); settings.Merge(ShippingMethod.Settings); var r = new RateTableLevel { Level = decimal.Parse(level), Rate = decimal.Parse(rate, NumberStyles.Currency), Percent = decimal.Parse(percent) }; settings.RemoveLevel(r); ShippingMethod.Settings = settings; HccApp.OrderServices.ShippingMethods.Update(ShippingMethod); LoadLevels(); } protected void gvRates_RowDeleting(object sender, GridViewDeleteEventArgs e) { var lblLevel = (Label) gvRates.Rows[e.RowIndex].FindControl("lblLevel"); var lblRate = (Label) gvRates.Rows[e.RowIndex].FindControl("lblAmount"); var lblPercent = (Label) gvRates.Rows[e.RowIndex].FindControl("lblPercent"); if (lblLevel != null) { if (lblRate != null) { if (lblPercent != null) { RemoveLevel(lblLevel.Text, lblRate.Text, lblPercent.Text); } } } } protected void cvAdjustmentTextBox_ServerValidate(object source, ServerValidateEventArgs args) { var val = 0m; if (decimal.TryParse(AdjustmentTextBox.Text, NumberStyles.Currency, CultureInfo.CurrentCulture, out val)) { args.IsValid = true; } else { args.IsValid = false; } } private void LocalizeView() { cvAdjustmentTextBox.ErrorMessage = Localization.GetString("cvAdjustmentTextBox.ErrorMessage"); if (AdjustmentDropDownList.Items.Count == 0) { AdjustmentDropDownList.Items.Add(new ListItem(Localization.GetString("Amount"), "1")); AdjustmentDropDownList.Items.Add(new ListItem(Localization.GetString("Percentage"), "2")); AdjustmentDropDownList.Items[0].Selected = true; } rfvNewLevelField.ErrorMessage = Localization.GetString("rfvNewLevelField.ErrorMessage"); cvNewLevelField.ErrorMessage = Localization.GetString("cvNewLevelField.ErrorMessage"); rfvNewAmountField.ErrorMessage = Localization.GetString("rfvNewAmountField.ErrorMessage"); cvNewAmountField.ErrorMessage = Localization.GetString("cvNewAmountField.ErrorMessage"); rfvNewPercentField.ErrorMessage = Localization.GetString("rfvNewPercentField.ErrorMessage"); cvNewPercentField.ErrorMessage = Localization.GetString("cvNewPercentField.ErrorMessage"); } protected void gvRates_OnRowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.Header) { e.Row.Cells[0].Text = Localization.GetString("OrderTotalAtLeast"); e.Row.Cells[1].Text = Localization.GetString("ChargeThisAmount"); e.Row.Cells[2].Text = Localization.GetString("AndThisPercent"); } } protected void btnDelete_OnPreRender(object sender, EventArgs e) { var link = (LinkButton) sender; link.Text = Localization.GetString("Delete"); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Microsoft.DocAsCode.Metadata.ManagedReference { using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Text.RegularExpressions; using Microsoft.CodeAnalysis; using Microsoft.DocAsCode.DataContracts.ManagedReference; using Microsoft.DocAsCode.Exceptions; public class SymbolVisitorAdapter : SymbolVisitor<MetadataItem> { #region Fields private static readonly Regex MemberSigRegex = new Regex(@"^([\w\{\}`]+\.)+", RegexOptions.Compiled); private static readonly IReadOnlyList<string> EmptyListOfString = new string[0]; private readonly YamlModelGenerator _generator; private Dictionary<string, ReferenceItem> _references; private bool _preserveRawInlineComments; private readonly IReadOnlyDictionary<Compilation, IEnumerable<IMethodSymbol>> _extensionMethods; private readonly Compilation _currentCompilation; private readonly CompilationReference _currentCompilationRef; private readonly string _codeSourceBasePath; #endregion #region Constructor public SymbolVisitorAdapter(YamlModelGenerator generator, SyntaxLanguage language, Compilation compilation, ExtractMetadataOptions options) { _generator = generator; Language = language; _currentCompilation = compilation; _currentCompilationRef = compilation.ToMetadataReference(); _preserveRawInlineComments = options.PreserveRawInlineComments; var configFilterRule = ConfigFilterRule.LoadWithDefaults(options.FilterConfigFile); var filterVisitor = options.DisableDefaultFilter ? (IFilterVisitor)new AllMemberFilterVisitor() : new DefaultFilterVisitor(); FilterVisitor = filterVisitor.WithConfig(configFilterRule).WithCache(); _extensionMethods = options.RoslynExtensionMethods != null ? options.RoslynExtensionMethods.ToDictionary(p => p.Key, p => p.Value.Where(e => FilterVisitor.CanVisitApi(e))) : new Dictionary<Compilation, IEnumerable<IMethodSymbol>>(); _codeSourceBasePath = options.CodeSourceBasePath; } #endregion #region Properties public SyntaxLanguage Language { get; private set; } public IFilterVisitor FilterVisitor { get; private set; } #endregion #region Overrides public override MetadataItem DefaultVisit(ISymbol symbol) { if (!FilterVisitor.CanVisitApi(symbol)) { return null; } var item = new MetadataItem { Name = VisitorHelper.GetId(symbol), CommentId = VisitorHelper.GetCommentId(symbol), RawComment = symbol.GetDocumentationCommentXml(), Language = Language, }; item.DisplayNames = new SortedList<SyntaxLanguage, string>(); item.DisplayNamesWithType = new SortedList<SyntaxLanguage, string>(); item.DisplayQualifiedNames = new SortedList<SyntaxLanguage, string>(); item.Source = VisitorHelper.GetSourceDetail(symbol); var assemblyName = symbol.ContainingAssembly?.Name; item.AssemblyNameList = string.IsNullOrEmpty(assemblyName) ? null : new List<string> { assemblyName }; if (!(symbol is INamespaceSymbol)) { var namespaceName = VisitorHelper.GetId(symbol.ContainingNamespace); item.NamespaceName = string.IsNullOrEmpty(namespaceName) ? null : namespaceName; } VisitorHelper.FeedComments(item, GetTripleSlashCommentParserContext(item, _preserveRawInlineComments)); if (item.Exceptions != null) { foreach (var exceptions in item.Exceptions) { AddReference(exceptions.Type, exceptions.CommentId); } } if (item.Sees != null) { foreach (var i in item.Sees.Where(l => l.LinkType == LinkType.CRef)) { AddReference(i.LinkId, i.CommentId); } } if (item.SeeAlsos != null) { foreach (var i in item.SeeAlsos.Where(l => l.LinkType == LinkType.CRef)) { AddReference(i.LinkId, i.CommentId); } } _generator.DefaultVisit(symbol, item, this); return item; } public override MetadataItem VisitAssembly(IAssemblySymbol symbol) { var item = new MetadataItem { Name = VisitorHelper.GetId(symbol), RawComment = symbol.GetDocumentationCommentXml(), Language = Language, }; item.DisplayNames = new SortedList<SyntaxLanguage, string> { { SyntaxLanguage.Default, symbol.MetadataName }, }; item.DisplayQualifiedNames = new SortedList<SyntaxLanguage, string> { { SyntaxLanguage.Default, symbol.MetadataName }, }; item.Type = MemberType.Assembly; _references = new Dictionary<string, ReferenceItem>(); IEnumerable<INamespaceSymbol> namespaces; if (!string.IsNullOrEmpty(VisitorHelper.GlobalNamespaceId)) { namespaces = Enumerable.Repeat(symbol.GlobalNamespace, 1); } else { namespaces = symbol.GlobalNamespace.GetNamespaceMembers(); } item.Items = VisitDescendants( namespaces, ns => ns.GetMembers().OfType<INamespaceSymbol>(), ns => ns.GetMembers().OfType<INamedTypeSymbol>().Any(t => FilterVisitor.CanVisitApi(t))); item.References = _references; return item; } public override MetadataItem VisitNamespace(INamespaceSymbol symbol) { var item = DefaultVisit(symbol); if (item == null) { return null; } item.Type = MemberType.Namespace; item.Items = VisitDescendants( symbol.GetMembers().OfType<ITypeSymbol>(), t => t.GetMembers().OfType<ITypeSymbol>(), t => true); AddReference(symbol); return item; } public override MetadataItem VisitNamedType(INamedTypeSymbol symbol) { var item = DefaultVisit(symbol); if (item == null) { return null; } GenerateInheritance(symbol, item); if (!symbol.IsStatic) { GenerateExtensionMethods(symbol, item); } item.Type = VisitorHelper.GetMemberTypeFromTypeKind(symbol.TypeKind); if (item.Syntax == null) { item.Syntax = new SyntaxDetail { Content = new SortedList<SyntaxLanguage, string>() }; } if (item.Syntax.Content == null) { item.Syntax.Content = new SortedList<SyntaxLanguage, string>(); } _generator.GenerateSyntax(item.Type, symbol, item.Syntax, this); if (symbol.TypeParameters.Length > 0) { if (item.Syntax.TypeParameters == null) { item.Syntax.TypeParameters = new List<ApiParameter>(); } foreach (var p in symbol.TypeParameters) { var param = VisitorHelper.GetTypeParameterDescription(p, item, GetTripleSlashCommentParserContext(item, _preserveRawInlineComments)); item.Syntax.TypeParameters.Add(param); } } if (symbol.TypeKind == TypeKind.Delegate) { var typeGenericParameters = symbol.IsGenericType ? symbol.Accept(TypeGenericParameterNameVisitor.Instance) : EmptyListOfString; AddMethodSyntax(symbol.DelegateInvokeMethod, item, typeGenericParameters, EmptyListOfString); } _generator.GenerateNamedType(symbol, item, this); item.Items = new List<MetadataItem>(); foreach (var member in symbol.GetMembers().Where(s => !(s is INamedTypeSymbol))) { var memberItem = member.Accept(this); if (memberItem != null) { item.Items.Add(memberItem); } } AddReference(symbol); item.Attributes = GetAttributeInfo(symbol.GetAttributes()); return item; } public override MetadataItem VisitMethod(IMethodSymbol symbol) { MetadataItem result = GetYamlItem(symbol); if (result == null) { return null; } if (result.Syntax == null) { result.Syntax = new SyntaxDetail { Content = new SortedList<SyntaxLanguage, string>() }; } if (symbol.TypeParameters.Length > 0) { if (result.Syntax.TypeParameters == null) { result.Syntax.TypeParameters = new List<ApiParameter>(); } foreach (var p in symbol.TypeParameters) { var param = VisitorHelper.GetTypeParameterDescription(p, result, GetTripleSlashCommentParserContext(result, _preserveRawInlineComments)); result.Syntax.TypeParameters.Add(param); } } var typeGenericParameters = symbol.ContainingType.IsGenericType ? symbol.ContainingType.Accept(TypeGenericParameterNameVisitor.Instance) : EmptyListOfString; var methodGenericParameters = symbol.IsGenericMethod ? (from p in symbol.TypeParameters select p.Name).ToList() : EmptyListOfString; AddMethodSyntax(symbol, result, typeGenericParameters, methodGenericParameters); if (result.Syntax.Content == null) { result.Syntax.Content = new SortedList<SyntaxLanguage, string>(); } _generator.GenerateSyntax(result.Type, symbol, result.Syntax, this); _generator.GenerateMethod(symbol, result, this); if (symbol.IsOverride && symbol.OverriddenMethod != null) { result.Overridden = AddSpecReference(symbol.OverriddenMethod, typeGenericParameters, methodGenericParameters); } result.Overload = AddOverloadReference(symbol.OriginalDefinition); AddMemberImplements(symbol, result, typeGenericParameters, methodGenericParameters); result.Attributes = GetAttributeInfo(symbol.GetAttributes()); result.IsExplicitInterfaceImplementation = !symbol.ExplicitInterfaceImplementations.IsEmpty; result.IsExtensionMethod = symbol.IsExtensionMethod; return result; } public override MetadataItem VisitField(IFieldSymbol symbol) { MetadataItem result = GetYamlItem(symbol); if (result == null) { return null; } if (result.Syntax == null) { result.Syntax = new SyntaxDetail { Content = new SortedList<SyntaxLanguage, string>() }; } if (result.Syntax.Content == null) { result.Syntax.Content = new SortedList<SyntaxLanguage, string>(); } _generator.GenerateSyntax(result.Type, symbol, result.Syntax, this); _generator.GenerateField(symbol, result, this); var typeGenericParameters = symbol.ContainingType.IsGenericType ? symbol.ContainingType.Accept(TypeGenericParameterNameVisitor.Instance) : EmptyListOfString; var id = AddSpecReference(symbol.Type, typeGenericParameters); result.Syntax.Return = VisitorHelper.GetParameterDescription(symbol, result, id, true, GetTripleSlashCommentParserContext(result, _preserveRawInlineComments)); Debug.Assert(result.Syntax.Return.Type != null); result.Attributes = GetAttributeInfo(symbol.GetAttributes()); return result; } public override MetadataItem VisitEvent(IEventSymbol symbol) { MetadataItem result = GetYamlItem(symbol); if (result == null) { return null; } if (result.Syntax == null) { result.Syntax = new SyntaxDetail { Content = new SortedList<SyntaxLanguage, string>() }; } if (result.Syntax.Content == null) { result.Syntax.Content = new SortedList<SyntaxLanguage, string>(); } _generator.GenerateSyntax(result.Type, symbol, result.Syntax, this); _generator.GenerateEvent(symbol, result, this); var typeGenericParameters = symbol.ContainingType.IsGenericType ? symbol.ContainingType.Accept(TypeGenericParameterNameVisitor.Instance) : EmptyListOfString; if (symbol.IsOverride && symbol.OverriddenEvent != null) { result.Overridden = AddSpecReference(symbol.OverriddenEvent, typeGenericParameters); } var id = AddSpecReference(symbol.Type, typeGenericParameters); result.Syntax.Return = VisitorHelper.GetParameterDescription(symbol, result, id, true, GetTripleSlashCommentParserContext(result, _preserveRawInlineComments)); Debug.Assert(result.Syntax.Return.Type != null); AddMemberImplements(symbol, result, typeGenericParameters); result.Attributes = GetAttributeInfo(symbol.GetAttributes()); result.IsExplicitInterfaceImplementation = !symbol.ExplicitInterfaceImplementations.IsEmpty; return result; } public override MetadataItem VisitProperty(IPropertySymbol symbol) { MetadataItem result = GetYamlItem(symbol); if (result == null) { return null; } if (result.Syntax == null) { result.Syntax = new SyntaxDetail { Content = new SortedList<SyntaxLanguage, string>() }; } if (result.Syntax.Parameters == null) { result.Syntax.Parameters = new List<ApiParameter>(); } if (result.Syntax.Content == null) { result.Syntax.Content = new SortedList<SyntaxLanguage, string>(); } _generator.GenerateSyntax(result.Type, symbol, result.Syntax, this); var typeGenericParameters = symbol.ContainingType.IsGenericType ? symbol.ContainingType.Accept(TypeGenericParameterNameVisitor.Instance) : EmptyListOfString; if (symbol.Parameters.Length > 0) { foreach (var p in symbol.Parameters) { var id = AddSpecReference(p.Type, typeGenericParameters); var param = VisitorHelper.GetParameterDescription(p, result, id, false, GetTripleSlashCommentParserContext(result, _preserveRawInlineComments)); Debug.Assert(param.Type != null); result.Syntax.Parameters.Add(param); } } { var id = AddSpecReference(symbol.Type, typeGenericParameters); result.Syntax.Return = VisitorHelper.GetParameterDescription(symbol, result, id, true, GetTripleSlashCommentParserContext(result, _preserveRawInlineComments)); Debug.Assert(result.Syntax.Return.Type != null); } if (symbol.IsOverride && symbol.OverriddenProperty != null) { result.Overridden = AddSpecReference(symbol.OverriddenProperty, typeGenericParameters); } result.Overload = AddOverloadReference(symbol.OriginalDefinition); _generator.GenerateProperty(symbol, result, this); AddMemberImplements(symbol, result, typeGenericParameters); result.Attributes = GetAttributeInfo(symbol.GetAttributes()); result.IsExplicitInterfaceImplementation = !symbol.ExplicitInterfaceImplementations.IsEmpty; return result; } #endregion #region Public Methods public string AddReference(ISymbol symbol) { var memberType = GetMemberTypeFromSymbol(symbol); if (memberType == MemberType.Default) { Debug.Fail("Unexpected membertype."); throw new InvalidOperationException("Unexpected membertype."); } return _generator.AddReference(symbol, _references, this); } public string AddReference(string id, string commentId) { return _generator.AddReference(id, commentId, _references); } public string AddOverloadReference(ISymbol symbol) { var memberType = GetMemberTypeFromSymbol(symbol); switch (memberType) { case MemberType.Property: case MemberType.Constructor: case MemberType.Method: case MemberType.Operator: return _generator.AddOverloadReference(symbol, _references, this); default: Debug.Fail("Unexpected membertype."); throw new InvalidOperationException("Unexpected membertype."); } } public string AddSpecReference( ISymbol symbol, IReadOnlyList<string> typeGenericParameters = null, IReadOnlyList<string> methodGenericParameters = null) { try { return _generator.AddSpecReference(symbol, typeGenericParameters, methodGenericParameters, _references, this); } catch (Exception ex) { throw new DocfxException($"Unable to generate spec reference for {VisitorHelper.GetCommentId(symbol)}", ex); } } #endregion #region Private Methods private MemberType GetMemberTypeFromSymbol(ISymbol symbol) { switch (symbol.Kind) { case SymbolKind.Namespace: return MemberType.Namespace; case SymbolKind.NamedType: INamedTypeSymbol nameTypeSymbol = symbol as INamedTypeSymbol; Debug.Assert(nameTypeSymbol != null); if (nameTypeSymbol != null) { return VisitorHelper.GetMemberTypeFromTypeKind(nameTypeSymbol.TypeKind); } else { return MemberType.Default; } case SymbolKind.Event: return MemberType.Event; case SymbolKind.Field: return MemberType.Field; case SymbolKind.Property: return MemberType.Property; case SymbolKind.Method: { var methodSymbol = symbol as IMethodSymbol; Debug.Assert(methodSymbol != null); if (methodSymbol == null) return MemberType.Default; switch (methodSymbol.MethodKind) { case MethodKind.AnonymousFunction: case MethodKind.DelegateInvoke: case MethodKind.Destructor: case MethodKind.ExplicitInterfaceImplementation: case MethodKind.Ordinary: case MethodKind.ReducedExtension: case MethodKind.DeclareMethod: return MemberType.Method; case MethodKind.BuiltinOperator: case MethodKind.UserDefinedOperator: case MethodKind.Conversion: return MemberType.Operator; case MethodKind.Constructor: case MethodKind.StaticConstructor: return MemberType.Constructor; // ignore: Property's get/set, and event's add/remove/raise case MethodKind.PropertyGet: case MethodKind.PropertySet: case MethodKind.EventAdd: case MethodKind.EventRemove: case MethodKind.EventRaise: default: return MemberType.Default; } } default: return MemberType.Default; } } private MetadataItem GetYamlItem(ISymbol symbol) { var item = DefaultVisit(symbol); if (item == null) return null; item.Type = GetMemberTypeFromSymbol(symbol); if (item.Type == MemberType.Default) { // If Default, then it is Property get/set or Event add/remove/raise, ignore return null; } return item; } private List<MetadataItem> VisitDescendants<T>( IEnumerable<T> children, Func<T, IEnumerable<T>> getChildren, Func<T, bool> filter) where T : ISymbol { var result = new List<MetadataItem>(); var stack = new Stack<T>(children.Reverse()); while (stack.Count > 0) { var child = stack.Pop(); if (filter(child)) { var item = child.Accept(this); if (item != null) { result.Add(item); } } foreach (var m in getChildren(child).Reverse()) { stack.Push(m); } } return result; } private bool IsInheritable(ISymbol memberSymbol) { var kind = (memberSymbol as IMethodSymbol)?.MethodKind; if (kind != null) { switch (kind.Value) { case MethodKind.ExplicitInterfaceImplementation: case MethodKind.DeclareMethod: case MethodKind.Ordinary: return true; default: return false; } } return true; } private void GenerateInheritance(INamedTypeSymbol symbol, MetadataItem item) { Dictionary<string, string> dict = null; if (symbol.TypeKind == TypeKind.Class || symbol.TypeKind == TypeKind.Struct) { var type = symbol; var inheritance = new List<string>(); dict = new Dictionary<string, string>(); var typeParamterNames = symbol.IsGenericType ? symbol.Accept(TypeGenericParameterNameVisitor.Instance) : EmptyListOfString; while (type != null) { // TODO: special handles for errorType: change to System.Object if (type.Kind == SymbolKind.ErrorType) { inheritance.Add("System.Object"); break; } if (type != symbol) { inheritance.Add(AddSpecReference(type, typeParamterNames)); } AddInheritedMembers(symbol, type, dict, typeParamterNames); type = type.BaseType; } if (symbol.TypeKind == TypeKind.Class) { inheritance.Reverse(); item.Inheritance = inheritance; } if (symbol.AllInterfaces.Length > 0) { item.Implements = (from t in symbol.AllInterfaces where FilterVisitor.CanVisitApi(t) select AddSpecReference(t, typeParamterNames)).ToList(); if (item.Implements.Count == 0) { item.Implements = null; } } } else if (symbol.TypeKind == TypeKind.Interface) { dict = new Dictionary<string, string>(); var typeParamterNames = symbol.IsGenericType ? symbol.Accept(TypeGenericParameterNameVisitor.Instance) : EmptyListOfString; AddInheritedMembers(symbol, symbol, dict, typeParamterNames); for (int i = 0; i < symbol.AllInterfaces.Length; i++) { AddInheritedMembers(symbol, symbol.AllInterfaces[i], dict, typeParamterNames); } } if (dict != null) { var inheritedMembers = (from r in dict.Values where r != null select r).ToList(); item.InheritedMembers = inheritedMembers.Count > 0 ? inheritedMembers : null; } } private void AddMemberImplements(ISymbol symbol, MetadataItem item, IReadOnlyList<string> typeGenericParameters = null) { if (symbol.ContainingType.AllInterfaces.Length <= 0) return; item.Implements = (from type in symbol.ContainingType.AllInterfaces where FilterVisitor.CanVisitApi(type) from member in type.GetMembers() where FilterVisitor.CanVisitApi(member) where symbol.Equals(symbol.ContainingType.FindImplementationForInterfaceMember(member)) select AddSpecReference(member, typeGenericParameters)).ToList(); if (item.Implements.Count == 0) { item.Implements = null; } } private void AddMemberImplements(IMethodSymbol symbol, MetadataItem item, IReadOnlyList<string> typeGenericParameters = null, IReadOnlyList<string> methodGenericParameters = null) { if (symbol.ContainingType.AllInterfaces.Length <= 0) return; item.Implements = (from type in symbol.ContainingType.AllInterfaces where FilterVisitor.CanVisitApi(type) from member in type.GetMembers() where FilterVisitor.CanVisitApi(member) where symbol.Equals(symbol.ContainingType.FindImplementationForInterfaceMember(member)) select AddSpecReference( symbol.TypeParameters.Length == 0 ? member : ((IMethodSymbol)member).Construct(symbol.TypeParameters.ToArray<ITypeSymbol>()), typeGenericParameters, methodGenericParameters)).ToList(); if (item.Implements.Count == 0) { item.Implements = null; } } private void GenerateExtensionMethods(INamedTypeSymbol symbol, MetadataItem item) { var extensions = new List<string>(); foreach (var pair in _extensionMethods.Where(p => p.Key.Language == symbol.Language)) { ITypeSymbol retargetedSymbol = symbol; // get retargeted symbol for cross-assembly case. if (pair.Key != _currentCompilation) { var compilation = pair.Key.References.Any(r => r.Display == _currentCompilationRef.Display) ? pair.Key : pair.Key.AddReferences(new[] { _currentCompilationRef }); retargetedSymbol = compilation.FindSymbol<INamedTypeSymbol>(symbol); } if (retargetedSymbol == null) { continue; } foreach (var e in pair.Value) { var reduced = e.ReduceExtensionMethod(retargetedSymbol); if ((object)reduced != null) { // update reference // Roslyn could get the instantiated type. e.g. // <code> // public class Foo<T> {} // public class FooImple<T> : Foo<Foo<T[]>> {} // public static class Extension { public static void Play<Tool, Way>(this Foo<Tool> foo, Tool t, Way w) {} } // </code> // Roslyn generated id for the reduced extension method of FooImple<T> is like "Play``2(Foo{`0[]},``1)" var typeParameterNames = symbol.IsGenericType ? symbol.Accept(TypeGenericParameterNameVisitor.Instance) : EmptyListOfString; var methodGenericParameters = reduced.IsGenericMethod ? (from p in reduced.TypeParameters select p.Name).ToList() : EmptyListOfString; var id = AddSpecReference(reduced, typeParameterNames, methodGenericParameters); extensions.Add(id); } } } item.ExtensionMethods = extensions.Count > 0 ? extensions : null; } private void AddInheritedMembers(INamedTypeSymbol symbol, INamedTypeSymbol type, Dictionary<string, string> dict, IReadOnlyList<string> typeParamterNames) { foreach (var m in from m in type.GetMembers() where !(m is INamedTypeSymbol) where FilterVisitor.CanVisitApi(m, symbol == type || !symbol.IsSealed || symbol.TypeKind != TypeKind.Struct) where IsInheritable(m) select m) { var sig = MemberSigRegex.Replace(SpecIdHelper.GetSpecId(m, typeParamterNames), string.Empty); if (!dict.ContainsKey(sig)) { dict.Add(sig, type == symbol ? null : AddSpecReference(m, typeParamterNames)); } } } private void AddMethodSyntax(IMethodSymbol symbol, MetadataItem result, IReadOnlyList<string> typeGenericParameters, IReadOnlyList<string> methodGenericParameters) { if (!symbol.ReturnsVoid) { var id = AddSpecReference(symbol.ReturnType, typeGenericParameters, methodGenericParameters); result.Syntax.Return = VisitorHelper.GetParameterDescription(symbol, result, id, true, GetTripleSlashCommentParserContext(result, _preserveRawInlineComments)); result.Syntax.Return.Attributes = GetAttributeInfo(symbol.GetReturnTypeAttributes()); } if (symbol.Parameters.Length > 0) { if (result.Syntax.Parameters == null) { result.Syntax.Parameters = new List<ApiParameter>(); } foreach (var p in symbol.Parameters) { var id = AddSpecReference(p.Type, typeGenericParameters, methodGenericParameters); var param = VisitorHelper.GetParameterDescription(p, result, id, false, GetTripleSlashCommentParserContext(result, _preserveRawInlineComments)); Debug.Assert(param.Type != null); param.Attributes = GetAttributeInfo(p.GetAttributes()); result.Syntax.Parameters.Add(param); } } } private ITripleSlashCommentParserContext GetTripleSlashCommentParserContext(MetadataItem item, bool preserve) { return new TripleSlashCommentParserContext { AddReferenceDelegate = GetAddReferenceDelegate(item), PreserveRawInlineComments = preserve, Source = item.Source, CodeSourceBasePath = _codeSourceBasePath }; } private List<AttributeInfo> GetAttributeInfo(ImmutableArray<AttributeData> attributes) { if (attributes.Length == 0) { return null; } var result = (from attr in attributes where !(attr.AttributeClass is IErrorTypeSymbol) where attr.AttributeConstructor != null where FilterVisitor.CanVisitAttribute(attr.AttributeConstructor) select new AttributeInfo { Type = AddSpecReference(attr.AttributeClass), Constructor = AddSpecReference(attr.AttributeConstructor), Arguments = GetArguments(attr), NamedArguments = GetNamedArguments(attr) } into attr where attr.Arguments != null select attr).ToList(); if (result.Count == 0) { return null; } return result; } private List<ArgumentInfo> GetArguments(AttributeData attr) { var result = new List<ArgumentInfo>(); foreach (var arg in attr.ConstructorArguments) { var argInfo = GetArgumentInfo(arg); if (argInfo == null) { return null; } result.Add(argInfo); } return result; } private ArgumentInfo GetArgumentInfo(TypedConstant arg) { var result = new ArgumentInfo(); if (arg.Type.TypeKind == TypeKind.Array) { // todo : value of array. return null; } if (arg.Value != null) { if (arg.Value is ITypeSymbol type) { if (!FilterVisitor.CanVisitApi(type)) { return null; } } result.Value = GetConstantValueForArgumentInfo(arg); } result.Type = AddSpecReference(arg.Type); return result; } private object GetConstantValueForArgumentInfo(TypedConstant arg) { if (arg.Value is ITypeSymbol type) { return AddSpecReference(type); } switch (Convert.GetTypeCode(arg.Value)) { case TypeCode.UInt32: case TypeCode.Int64: case TypeCode.UInt64: // work around: yaml cannot deserialize them. return arg.Value.ToString(); default: return arg.Value; } } private List<NamedArgumentInfo> GetNamedArguments(AttributeData attr) { var result = (from pair in attr.NamedArguments select GetNamedArgumentInfo(pair) into namedArgument where namedArgument != null select namedArgument).ToList(); if (result.Count == 0) { return null; } return result; } private NamedArgumentInfo GetNamedArgumentInfo(KeyValuePair<string, TypedConstant> pair) { var result = new NamedArgumentInfo { Name = pair.Key, }; var arg = pair.Value; if (arg.Type.TypeKind == TypeKind.Array) { // todo : value of array. return null; } else if (arg.Value != null) { if (arg.Value is ITypeSymbol type) { if (!FilterVisitor.CanVisitApi(type)) { return null; } } result.Value = GetConstantValueForArgumentInfo(arg); } result.Type = AddSpecReference(arg.Type); return result; } private Action<string, string> GetAddReferenceDelegate(MetadataItem item) { return (id, commentId) => { var r = AddReference(id, commentId); if (item.References == null) { item.References = new Dictionary<string, ReferenceItem>(); } // only record the id now, the value would be fed at later phase after merge item.References[id] = null; }; } #endregion } }
// AGUISprite.cs // // Author: // Atte Vuorinen <AtteVuorinen@gmail.com> // // Copyright (c) 2014 Atte Vuorinen // // 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 UnityEngine; using System.Collections; //TODO: Tilling, etc. [AddComponentMenu("AGUI/UI/Sprite")] [RequireComponent(typeof(SpriteRenderer))] public class AGUISprite : AGUIObject { #region Header /// <summary> /// The cachedRenderer. /// </summary> [HideInInspector] public SpriteRenderer cachedRenderer; /// <summary> /// The pixel to unit. /// </summary> [SerializeField][GReadOnlyAttribute] private float m_pixelToUnit; /// <summary> /// The sprite. /// </summary> [SerializeField] private Sprite m_sprite; /// <summary> /// The material. /// </summary> [SerializeField] private Material m_material; /// <summary> /// The pivot. /// </summary> public Vector2 pivot = new Vector2(0.5f,0.5f); #region Advanced /// <summary> /// The type of the sprite. /// </summary> [SerializeField] private SpriteMeshType m_spriteType = SpriteMeshType.FullRect; /// <summary> /// The extrude. /// </summary> [SerializeField][Range(0,32)] private int m_extrude = 0; //[GMinValueAttribute(1)] //public float scale = 100; #endregion /// <summary> /// The rect. /// </summary> [SerializeField] private Rect m_rect; /// <summary> /// The orginal rect. /// </summary> [SerializeField][GReadOnlyAttribute(32)] private Rect m_orginalRect; /// <summary> /// The create sprite. /// </summary> private Sprite m_createSprite; #endregion #region Properties /// <summary> /// Gets the pixel to unit. /// </summary> /// <value>The pixel to unit.</value> public float PixelToUnit { get { return m_pixelToUnit; } private set { m_pixelToUnit = value; } } /// <summary> /// Gets or sets the current sprite. /// </summary> /// <value>The current sprite.</value> public Sprite CurrentSprite { get { return m_sprite; } set { m_sprite = value; Init(); } } /// <summary> /// Gets or sets the current material. /// </summary> /// <value>The current material.</value> public Material CurrentMaterial { get { return m_material; } set { m_material = value; if(cachedRenderer != null) { cachedRenderer.material = m_material; } } } /// <summary> /// Gets or sets the current rect. /// </summary> /// <value>The current rect.</value> public Rect CurrentRect { get { return m_rect; } set { m_rect = value; Init(); } } /// <summary> /// Gets the orginal rect. /// </summary> /// <value>The orginal rect.</value> public Rect OrginalRect { get { return m_orginalRect; } } /// <summary> /// Custom color rule for object. /// For example, UILabel have multiple objects that color it changes. /// </summary> /// <value>The color tint.</value> protected override Color ColorTint { get { if(cachedRenderer == null) { return Color.black; } return cachedRenderer.color; } set { if(cachedRenderer == null) { return; } cachedRenderer.color = value; } } #endregion #region Body /// <summary> /// Updates the sprite. /// </summary> public void UpdateSprite() { if(m_sprite == null || cachedRenderer == null) { if(!cachedRenderer) { cachedRenderer = GetComponent<SpriteRenderer>(); } /* if(cachedRenderer) { cachedRenderer.sprite = null; } */ return; } m_pixelToUnit = Mathf.Min(m_sprite.textureRect.width / m_sprite.bounds.size.x,m_sprite.textureRect.height / m_sprite.bounds.size.y); if(cachedRenderer.sprite != null && m_createSprite != null && (m_createSprite.texture != m_sprite.texture || m_orginalRect != m_sprite.rect)) { m_orginalRect = m_sprite.rect; m_rect = m_sprite.rect; } //Remove old sprite! GameObject.DestroyImmediate(m_createSprite); //Update Sprite// cachedRenderer.sprite = m_createSprite = Sprite.Create(m_sprite.texture,m_rect,pivot,m_pixelToUnit,(uint)m_extrude,m_spriteType); cachedRenderer.sharedMaterial = m_material; m_createSprite.name = m_sprite.name; } /// <summary> /// Init rule for AGUIObject. /// (This is called when you edit values in editor) /// </summary> protected override void Init() { if(!Application.isPlaying) { UpdateSprite(); } } /// <summary> /// Used for first time init. /// Always remember call base.Reset(); !! /// </summary> protected override void Reset () { if(!cachedRenderer) { cachedRenderer = GetComponent<SpriteRenderer>(); } if(cachedRenderer) { m_material = GHelper.GetDefaultMaterial(); if(m_sprite == null) { m_sprite = cachedRenderer.sprite; color = cachedRenderer.color; if(m_sprite != null) { m_rect = m_sprite.rect; m_orginalRect = m_sprite.rect; } cachedRenderer.enabled = true; cachedRenderer.hideFlags = HideFlags.HideInInspector; } Init(); } base.Reset (); } /// <summary> /// OnEnable base. /// </summary> protected override void OnEnable() { if(cachedRenderer) { cachedRenderer.enabled = true; cachedRenderer.hideFlags = HideFlags.HideInInspector; } base.OnEnable(); } /// <summary> /// OnDisable base. /// </summary> protected override void OnDisable() { if(cachedRenderer) { cachedRenderer.enabled = false; cachedRenderer.hideFlags = HideFlags.None; } base.OnDisable(); } /// <summary> /// OnDestroy base. /// </summary> protected override void OnDestroy () { if(cachedRenderer != null) { cachedRenderer.enabled = true; cachedRenderer.sprite = m_sprite; } if(m_createSprite != null) { //Remove old sprite! GameObject.DestroyImmediate(m_createSprite); } } #if UNITY_EDITOR /// <summary> ///Creates sprite if game isn't running. /// </summary> private void Update() { if(!Application.isPlaying) { if(m_sprite != m_createSprite) { Init(); } } } #endif #endregion }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gax = Google.Api.Gax; using gcdv = Google.Cloud.DataQnA.V1Alpha; using sys = System; namespace Google.Cloud.DataQnA.V1Alpha { /// <summary>Resource name for the <c>Question</c> resource.</summary> public sealed partial class QuestionName : gax::IResourceName, sys::IEquatable<QuestionName> { /// <summary>The possible contents of <see cref="QuestionName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern <c>projects/{project}/locations/{location}/questions/{question}</c>. /// </summary> ProjectLocationQuestion = 1, } private static gax::PathTemplate s_projectLocationQuestion = new gax::PathTemplate("projects/{project}/locations/{location}/questions/{question}"); /// <summary>Creates a <see cref="QuestionName"/> containing an unparsed resource name.</summary> /// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param> /// <returns> /// A new instance of <see cref="QuestionName"/> containing the provided <paramref name="unparsedResourceName"/> /// . /// </returns> public static QuestionName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new QuestionName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="QuestionName"/> with the pattern /// <c>projects/{project}/locations/{location}/questions/{question}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="questionId">The <c>Question</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="QuestionName"/> constructed from the provided ids.</returns> public static QuestionName FromProjectLocationQuestion(string projectId, string locationId, string questionId) => new QuestionName(ResourceNameType.ProjectLocationQuestion, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), questionId: gax::GaxPreconditions.CheckNotNullOrEmpty(questionId, nameof(questionId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="QuestionName"/> with pattern /// <c>projects/{project}/locations/{location}/questions/{question}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="questionId">The <c>Question</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="QuestionName"/> with pattern /// <c>projects/{project}/locations/{location}/questions/{question}</c>. /// </returns> public static string Format(string projectId, string locationId, string questionId) => FormatProjectLocationQuestion(projectId, locationId, questionId); /// <summary> /// Formats the IDs into the string representation of this <see cref="QuestionName"/> with pattern /// <c>projects/{project}/locations/{location}/questions/{question}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="questionId">The <c>Question</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="QuestionName"/> with pattern /// <c>projects/{project}/locations/{location}/questions/{question}</c>. /// </returns> public static string FormatProjectLocationQuestion(string projectId, string locationId, string questionId) => s_projectLocationQuestion.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(questionId, nameof(questionId))); /// <summary>Parses the given resource name string into a new <see cref="QuestionName"/> instance.</summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>projects/{project}/locations/{location}/questions/{question}</c></description></item> /// </list> /// </remarks> /// <param name="questionName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="QuestionName"/> if successful.</returns> public static QuestionName Parse(string questionName) => Parse(questionName, false); /// <summary> /// Parses the given resource name string into a new <see cref="QuestionName"/> instance; optionally allowing an /// unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>projects/{project}/locations/{location}/questions/{question}</c></description></item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="questionName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <returns>The parsed <see cref="QuestionName"/> if successful.</returns> public static QuestionName Parse(string questionName, bool allowUnparsed) => TryParse(questionName, allowUnparsed, out QuestionName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern."); /// <summary> /// Tries to parse the given resource name string into a new <see cref="QuestionName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>projects/{project}/locations/{location}/questions/{question}</c></description></item> /// </list> /// </remarks> /// <param name="questionName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="QuestionName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string questionName, out QuestionName result) => TryParse(questionName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="QuestionName"/> instance; optionally /// allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>projects/{project}/locations/{location}/questions/{question}</c></description></item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="questionName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <param name="result"> /// When this method returns, the parsed <see cref="QuestionName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string questionName, bool allowUnparsed, out QuestionName result) { gax::GaxPreconditions.CheckNotNull(questionName, nameof(questionName)); gax::TemplatedResourceName resourceName; if (s_projectLocationQuestion.TryParseName(questionName, out resourceName)) { result = FromProjectLocationQuestion(resourceName[0], resourceName[1], resourceName[2]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(questionName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private QuestionName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string locationId = null, string projectId = null, string questionId = null) { Type = type; UnparsedResource = unparsedResourceName; LocationId = locationId; ProjectId = projectId; QuestionId = questionId; } /// <summary> /// Constructs a new instance of a <see cref="QuestionName"/> class from the component parts of pattern /// <c>projects/{project}/locations/{location}/questions/{question}</c> /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="questionId">The <c>Question</c> ID. Must not be <c>null</c> or empty.</param> public QuestionName(string projectId, string locationId, string questionId) : this(ResourceNameType.ProjectLocationQuestion, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), questionId: gax::GaxPreconditions.CheckNotNullOrEmpty(questionId, nameof(questionId))) { } /// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary> public ResourceNameType Type { get; } /// <summary> /// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an /// unparsed resource name. /// </summary> public gax::UnparsedResourceName UnparsedResource { get; } /// <summary> /// The <c>Location</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string LocationId { get; } /// <summary> /// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string ProjectId { get; } /// <summary> /// The <c>Question</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string QuestionId { get; } /// <summary>Whether this instance contains a resource name with a known pattern.</summary> public bool IsKnownPattern => Type != ResourceNameType.Unparsed; /// <summary>The string representation of the resource name.</summary> /// <returns>The string representation of the resource name.</returns> public override string ToString() { switch (Type) { case ResourceNameType.Unparsed: return UnparsedResource.ToString(); case ResourceNameType.ProjectLocationQuestion: return s_projectLocationQuestion.Expand(ProjectId, LocationId, QuestionId); default: throw new sys::InvalidOperationException("Unrecognized resource-type."); } } /// <summary>Returns a hash code for this resource name.</summary> public override int GetHashCode() => ToString().GetHashCode(); /// <inheritdoc/> public override bool Equals(object obj) => Equals(obj as QuestionName); /// <inheritdoc/> public bool Equals(QuestionName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(QuestionName a, QuestionName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(QuestionName a, QuestionName b) => !(a == b); } public partial class Question { /// <summary> /// <see cref="gcdv::QuestionName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcdv::QuestionName QuestionName { get => string.IsNullOrEmpty(Name) ? null : gcdv::QuestionName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Runtime.InteropServices; using System.IO; using System.Drawing.Internal; namespace System.Drawing.Imaging { /// <summary> /// Defines a graphic metafile. A metafile contains records that describe a sequence of graphics operations that /// can be recorded and played back. /// </summary> public sealed partial class Metafile : Image { /// <summary> /// Initializes a new instance of the <see cref='Metafile'/> class from the specified handle and /// <see cref='WmfPlaceableFileHeader'/>. /// </summary> public Metafile(IntPtr hmetafile, WmfPlaceableFileHeader wmfHeader) : this(hmetafile, wmfHeader, false) { } /// <summary> /// Initializes a new instance of the <see cref='Metafile'/> class from the specified handle and /// <see cref='WmfPlaceableFileHeader'/>. /// </summary> public Metafile(IntPtr hmetafile, WmfPlaceableFileHeader wmfHeader, bool deleteWmf) { IntPtr metafile = IntPtr.Zero; int status = SafeNativeMethods.Gdip.GdipCreateMetafileFromWmf(new HandleRef(null, hmetafile), deleteWmf, wmfHeader, out metafile); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); SetNativeImage(metafile); } /// <summary> /// Initializes a new instance of the <see cref='Metafile'/> class from the specified handle and /// <see cref='WmfPlaceableFileHeader'/>. /// </summary> public Metafile(IntPtr henhmetafile, bool deleteEmf) { IntPtr metafile = IntPtr.Zero; int status = SafeNativeMethods.Gdip.GdipCreateMetafileFromEmf(new HandleRef(null, henhmetafile), deleteEmf, out metafile); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); SetNativeImage(metafile); } /// <summary> /// Initializes a new instance of the <see cref='Metafile'/> class from the specified filename. /// </summary> public Metafile(string filename) { IntPtr metafile = IntPtr.Zero; int status = SafeNativeMethods.Gdip.GdipCreateMetafileFromFile(filename, out metafile); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); SetNativeImage(metafile); } /// <summary> /// Initializes a new instance of the <see cref='Metafile'/> class from the specified stream. /// </summary> public Metafile(Stream stream) { if (stream == null) { throw new ArgumentNullException(nameof(stream)); } IntPtr metafile = IntPtr.Zero; int status = SafeNativeMethods.Gdip.GdipCreateMetafileFromStream(new GPStream(stream), out metafile); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); SetNativeImage(metafile); } /// <summary> /// Initializes a new instance of the <see cref='Metafile'/> class from the specified handle to a device context. /// </summary> public Metafile(IntPtr referenceHdc, EmfType emfType) : this(referenceHdc, emfType, null) { } /// <summary> /// Initializes a new instance of the <see cref='Metafile'/> class from the specified handle to a device context. /// </summary> public Metafile(IntPtr referenceHdc, EmfType emfType, String description) { IntPtr metafile = IntPtr.Zero; int status = SafeNativeMethods.Gdip.GdipRecordMetafile(new HandleRef(null, referenceHdc), unchecked((int)emfType), NativeMethods.NullHandleRef, unchecked((int)MetafileFrameUnit.GdiCompatible), description, out metafile); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); SetNativeImage(metafile); } /// <summary> /// Initializes a new instance of the <see cref='Metafile'/> class from the specified device context, bounded /// by the specified rectangle. /// </summary> public Metafile(IntPtr referenceHdc, RectangleF frameRect) : this(referenceHdc, frameRect, MetafileFrameUnit.GdiCompatible) { } /// <summary> /// Initializes a new instance of the <see cref='Metafile'/> class from the specified device context, bounded /// by the specified rectangle. /// </summary> public Metafile(IntPtr referenceHdc, RectangleF frameRect, MetafileFrameUnit frameUnit) : this(referenceHdc, frameRect, frameUnit, EmfType.EmfPlusDual) { } /// <summary> /// Initializes a new instance of the <see cref='Metafile'/> class from the specified device context, bounded /// by the specified rectangle. /// </summary> public Metafile(IntPtr referenceHdc, RectangleF frameRect, MetafileFrameUnit frameUnit, EmfType type) : this(referenceHdc, frameRect, frameUnit, type, null) { } /// <summary> /// Initializes a new instance of the <see cref='Metafile'/> class from the specified device context, bounded /// by the specified rectangle. /// </summary> public Metafile(IntPtr referenceHdc, RectangleF frameRect, MetafileFrameUnit frameUnit, EmfType type, String description) { IntPtr metafile = IntPtr.Zero; GPRECTF rectf = new GPRECTF(frameRect); int status = SafeNativeMethods.Gdip.GdipRecordMetafile(new HandleRef(null, referenceHdc), unchecked((int)type), ref rectf, unchecked((int)frameUnit), description, out metafile); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); SetNativeImage(metafile); } /// <summary> /// Initializes a new instance of the <see cref='Metafile'/> class from the specified device context, bounded /// by the specified rectangle. /// </summary> public Metafile(IntPtr referenceHdc, Rectangle frameRect) : this(referenceHdc, frameRect, MetafileFrameUnit.GdiCompatible) { } /// <summary> /// Initializes a new instance of the <see cref='Metafile'/> class from the specified device context, bounded /// by the specified rectangle. /// </summary> public Metafile(IntPtr referenceHdc, Rectangle frameRect, MetafileFrameUnit frameUnit) : this(referenceHdc, frameRect, frameUnit, EmfType.EmfPlusDual) { } /// <summary> /// Initializes a new instance of the <see cref='Metafile'/> class from the specified device context, bounded /// by the specified rectangle. /// </summary> public Metafile(IntPtr referenceHdc, Rectangle frameRect, MetafileFrameUnit frameUnit, EmfType type) : this(referenceHdc, frameRect, frameUnit, type, null) { } /// <summary> /// Initializes a new instance of the <see cref='Metafile'/> class from the specified device context, bounded /// by the specified rectangle. /// </summary> public Metafile(IntPtr referenceHdc, Rectangle frameRect, MetafileFrameUnit frameUnit, EmfType type, string desc) { IntPtr metafile = IntPtr.Zero; int status; if (frameRect.IsEmpty) { status = SafeNativeMethods.Gdip.GdipRecordMetafile(new HandleRef(null, referenceHdc), unchecked((int)type), NativeMethods.NullHandleRef, unchecked((int)MetafileFrameUnit.GdiCompatible), desc, out metafile); } else { GPRECT gprect = new GPRECT(frameRect); status = SafeNativeMethods.Gdip.GdipRecordMetafileI(new HandleRef(null, referenceHdc), unchecked((int)type), ref gprect, unchecked((int)frameUnit), desc, out metafile); } if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); SetNativeImage(metafile); } /// <summary> /// Initializes a new instance of the <see cref='Metafile'/> class with the specified filename. /// </summary> public Metafile(string fileName, IntPtr referenceHdc) : this(fileName, referenceHdc, EmfType.EmfPlusDual, null) { } /// <summary> /// Initializes a new instance of the <see cref='Metafile'/> class with the specified filename. /// </summary> public Metafile(string fileName, IntPtr referenceHdc, EmfType type) : this(fileName, referenceHdc, type, null) { } /// <summary> /// Initializes a new instance of the <see cref='Metafile'/> class with the specified filename. /// </summary> public Metafile(string fileName, IntPtr referenceHdc, EmfType type, String description) { IntPtr metafile = IntPtr.Zero; int status = SafeNativeMethods.Gdip.GdipRecordMetafileFileName(fileName, new HandleRef(null, referenceHdc), unchecked((int)type), NativeMethods.NullHandleRef, unchecked((int)MetafileFrameUnit.GdiCompatible), description, out metafile); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); SetNativeImage(metafile); } /// <summary> /// Initializes a new instance of the <see cref='Metafile'/> class with the specified filename. /// </summary> public Metafile(string fileName, IntPtr referenceHdc, RectangleF frameRect) : this(fileName, referenceHdc, frameRect, MetafileFrameUnit.GdiCompatible) { } /// <summary> /// Initializes a new instance of the <see cref='Metafile'/> class with the specified filename. /// </summary> public Metafile(string fileName, IntPtr referenceHdc, RectangleF frameRect, MetafileFrameUnit frameUnit) : this(fileName, referenceHdc, frameRect, frameUnit, EmfType.EmfPlusDual) { } /// <summary> /// Initializes a new instance of the <see cref='Metafile'/> class with the specified filename. /// </summary> public Metafile(string fileName, IntPtr referenceHdc, RectangleF frameRect, MetafileFrameUnit frameUnit, EmfType type) : this(fileName, referenceHdc, frameRect, frameUnit, type, null) { } /// <summary> /// Initializes a new instance of the <see cref='Metafile'/> class with the specified filename. /// </summary> public Metafile(string fileName, IntPtr referenceHdc, RectangleF frameRect, MetafileFrameUnit frameUnit, string desc) : this(fileName, referenceHdc, frameRect, frameUnit, EmfType.EmfPlusDual, desc) { } /// <summary> /// Initializes a new instance of the <see cref='Metafile'/> class with the specified filename. /// </summary> public Metafile(string fileName, IntPtr referenceHdc, RectangleF frameRect, MetafileFrameUnit frameUnit, EmfType type, String description) { IntPtr metafile = IntPtr.Zero; GPRECTF rectf = new GPRECTF(frameRect); int status = SafeNativeMethods.Gdip.GdipRecordMetafileFileName(fileName, new HandleRef(null, referenceHdc), unchecked((int)type), ref rectf, unchecked((int)frameUnit), description, out metafile); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); SetNativeImage(metafile); } /// <summary> /// Initializes a new instance of the <see cref='Metafile'/> class with the specified filename. /// </summary> public Metafile(string fileName, IntPtr referenceHdc, Rectangle frameRect) : this(fileName, referenceHdc, frameRect, MetafileFrameUnit.GdiCompatible) { } /// <summary> /// Initializes a new instance of the <see cref='Metafile'/> class with the specified filename. /// </summary> public Metafile(string fileName, IntPtr referenceHdc, Rectangle frameRect, MetafileFrameUnit frameUnit) : this(fileName, referenceHdc, frameRect, frameUnit, EmfType.EmfPlusDual) { } /// <summary> /// Initializes a new instance of the <see cref='Metafile'/> class with the specified filename. /// </summary> public Metafile(string fileName, IntPtr referenceHdc, Rectangle frameRect, MetafileFrameUnit frameUnit, EmfType type) : this(fileName, referenceHdc, frameRect, frameUnit, type, null) { } /// <summary> /// Initializes a new instance of the <see cref='Metafile'/> class with the specified filename. /// </summary> public Metafile(string fileName, IntPtr referenceHdc, Rectangle frameRect, MetafileFrameUnit frameUnit, string description) : this(fileName, referenceHdc, frameRect, frameUnit, EmfType.EmfPlusDual, description) { } /// <summary> /// Initializes a new instance of the <see cref='Metafile'/> class with the specified filename. /// </summary> public Metafile(string fileName, IntPtr referenceHdc, Rectangle frameRect, MetafileFrameUnit frameUnit, EmfType type, string description) { IntPtr metafile = IntPtr.Zero; int status; if (frameRect.IsEmpty) { status = SafeNativeMethods.Gdip.GdipRecordMetafileFileName(fileName, new HandleRef(null, referenceHdc), unchecked((int)type), NativeMethods.NullHandleRef, unchecked((int)frameUnit), description, out metafile); } else { GPRECT gprect = new GPRECT(frameRect); status = SafeNativeMethods.Gdip.GdipRecordMetafileFileNameI(fileName, new HandleRef(null, referenceHdc), unchecked((int)type), ref gprect, unchecked((int)frameUnit), description, out metafile); } if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); SetNativeImage(metafile); } /// <summary> /// Initializes a new instance of the <see cref='Metafile'/> class from the specified data stream. /// </summary> public Metafile(Stream stream, IntPtr referenceHdc) : this(stream, referenceHdc, EmfType.EmfPlusDual, null) { } /// <summary> /// Initializes a new instance of the <see cref='Metafile'/> class from the specified data stream. /// </summary> public Metafile(Stream stream, IntPtr referenceHdc, EmfType type) : this(stream, referenceHdc, type, null) { } /// <summary> /// Initializes a new instance of the <see cref='Metafile'/> class from the specified data stream. /// </summary> public Metafile(Stream stream, IntPtr referenceHdc, EmfType type, string description) { IntPtr metafile = IntPtr.Zero; int status = SafeNativeMethods.Gdip.GdipRecordMetafileStream(new GPStream(stream), new HandleRef(null, referenceHdc), unchecked((int)type), NativeMethods.NullHandleRef, unchecked((int)MetafileFrameUnit.GdiCompatible), description, out metafile); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); SetNativeImage(metafile); } /// <summary> /// Initializes a new instance of the <see cref='Metafile'/> class from the specified data stream. /// </summary> public Metafile(Stream stream, IntPtr referenceHdc, RectangleF frameRect) : this(stream, referenceHdc, frameRect, MetafileFrameUnit.GdiCompatible) { } /// <summary> /// Initializes a new instance of the <see cref='Metafile'/> class with the specified filename. /// </summary> public Metafile(Stream stream, IntPtr referenceHdc, RectangleF frameRect, MetafileFrameUnit frameUnit) : this(stream, referenceHdc, frameRect, frameUnit, EmfType.EmfPlusDual) { } /// <summary> /// Initializes a new instance of the <see cref='Metafile'/> class with the specified filename. /// </summary> public Metafile(Stream stream, IntPtr referenceHdc, RectangleF frameRect, MetafileFrameUnit frameUnit, EmfType type) : this(stream, referenceHdc, frameRect, frameUnit, type, null) { } /// <summary> /// Initializes a new instance of the <see cref='Metafile'/> class with the specified filename. /// </summary> public Metafile(Stream stream, IntPtr referenceHdc, RectangleF frameRect, MetafileFrameUnit frameUnit, EmfType type, string description) { IntPtr metafile = IntPtr.Zero; GPRECTF rectf = new GPRECTF(frameRect); int status = SafeNativeMethods.Gdip.GdipRecordMetafileStream(new GPStream(stream), new HandleRef(null, referenceHdc), unchecked((int)type), ref rectf, unchecked((int)frameUnit), description, out metafile); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); SetNativeImage(metafile); } /// <summary> /// Initializes a new instance of the <see cref='Metafile'/> class from the specified data stream. /// </summary> public Metafile(Stream stream, IntPtr referenceHdc, Rectangle frameRect) : this(stream, referenceHdc, frameRect, MetafileFrameUnit.GdiCompatible) { } /// <summary> /// Initializes a new instance of the <see cref='Metafile'/> class with the specified filename. /// </summary> public Metafile(Stream stream, IntPtr referenceHdc, Rectangle frameRect, MetafileFrameUnit frameUnit) : this(stream, referenceHdc, frameRect, frameUnit, EmfType.EmfPlusDual) { } /// <summary> /// Initializes a new instance of the <see cref='Metafile'/> class with the specified filename. /// </summary> public Metafile(Stream stream, IntPtr referenceHdc, Rectangle frameRect, MetafileFrameUnit frameUnit, EmfType type) : this(stream, referenceHdc, frameRect, frameUnit, type, null) { } /// <summary> /// Initializes a new instance of the <see cref='Metafile'/> class with the specified filename. /// </summary> public Metafile(Stream stream, IntPtr referenceHdc, Rectangle frameRect, MetafileFrameUnit frameUnit, EmfType type, string description) { IntPtr metafile = IntPtr.Zero; int status; if (frameRect.IsEmpty) { status = SafeNativeMethods.Gdip.GdipRecordMetafileStream(new GPStream(stream), new HandleRef(null, referenceHdc), unchecked((int)type), NativeMethods.NullHandleRef, unchecked((int)frameUnit), description, out metafile); } else { GPRECT gprect = new GPRECT(frameRect); status = SafeNativeMethods.Gdip.GdipRecordMetafileStreamI(new GPStream(stream), new HandleRef(null, referenceHdc), unchecked((int)type), ref gprect, unchecked((int)frameUnit), description, out metafile); } if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); SetNativeImage(metafile); } /// <summary> /// Returns the <see cref='MetafileHeader'/> associated with the specified <see cref='Metafile'/>. /// </summary> public static MetafileHeader GetMetafileHeader(IntPtr hmetafile, WmfPlaceableFileHeader wmfHeader) { MetafileHeader header = new MetafileHeader(); header.wmf = new MetafileHeaderWmf(); int status = SafeNativeMethods.Gdip.GdipGetMetafileHeaderFromWmf(new HandleRef(null, hmetafile), wmfHeader, header.wmf); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); return header; } /// <summary> /// Returns the <see cref='MetafileHeader'/> associated with the specified <see cref='Metafile'/>. /// </summary> public static MetafileHeader GetMetafileHeader(IntPtr henhmetafile) { MetafileHeader header = new MetafileHeader(); header.emf = new MetafileHeaderEmf(); int status = SafeNativeMethods.Gdip.GdipGetMetafileHeaderFromEmf(new HandleRef(null, henhmetafile), header.emf); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); return header; } /// <summary> /// Returns the <see cref='MetafileHeader'/> associated with the specified <see cref='Metafile'/>. /// </summary> public static MetafileHeader GetMetafileHeader(string fileName) { MetafileHeader header = new MetafileHeader(); IntPtr memory = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(MetafileHeaderEmf))); try { int status = SafeNativeMethods.Gdip.GdipGetMetafileHeaderFromFile(fileName, memory); if (status != SafeNativeMethods.Gdip.Ok) { throw SafeNativeMethods.Gdip.StatusException(status); } int[] type = new int[] { 0 }; Marshal.Copy(memory, type, 0, 1); MetafileType metafileType = (MetafileType)type[0]; if (metafileType == MetafileType.Wmf || metafileType == MetafileType.WmfPlaceable) { // WMF header header.wmf = (MetafileHeaderWmf)Marshal.PtrToStructure(memory, typeof(MetafileHeaderWmf)); header.emf = null; } else { // EMF header header.wmf = null; header.emf = (MetafileHeaderEmf)Marshal.PtrToStructure(memory, typeof(MetafileHeaderEmf)); } } finally { Marshal.FreeHGlobal(memory); } return header; } /// <summary> /// Returns the <see cref='MetafileHeader'/> associated with the specified <see cref='Metafile'/>. /// </summary> public static MetafileHeader GetMetafileHeader(Stream stream) { MetafileHeader header; IntPtr memory = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(MetafileHeaderEmf))); try { int status = SafeNativeMethods.Gdip.GdipGetMetafileHeaderFromStream(new GPStream(stream), memory); if (status != SafeNativeMethods.Gdip.Ok) { throw SafeNativeMethods.Gdip.StatusException(status); } int[] type = new int[] { 0 }; Marshal.Copy(memory, type, 0, 1); MetafileType metafileType = (MetafileType)type[0]; header = new MetafileHeader(); if (metafileType == MetafileType.Wmf || metafileType == MetafileType.WmfPlaceable) { // WMF header header.wmf = (MetafileHeaderWmf)Marshal.PtrToStructure(memory, typeof(MetafileHeaderWmf)); header.emf = null; } else { // EMF header header.wmf = null; header.emf = (MetafileHeaderEmf)Marshal.PtrToStructure(memory, typeof(MetafileHeaderEmf)); } } finally { Marshal.FreeHGlobal(memory); } return header; } /// <summary> /// Returns the <see cref='MetafileHeader'/> associated with this <see cref='Metafile'/>. /// </summary> public MetafileHeader GetMetafileHeader() { MetafileHeader header; IntPtr memory = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(MetafileHeaderEmf))); try { int status = SafeNativeMethods.Gdip.GdipGetMetafileHeaderFromMetafile(new HandleRef(this, nativeImage), memory); if (status != SafeNativeMethods.Gdip.Ok) { throw SafeNativeMethods.Gdip.StatusException(status); } int[] type = new int[] { 0 }; Marshal.Copy(memory, type, 0, 1); MetafileType metafileType = (MetafileType)type[0]; header = new MetafileHeader(); if (metafileType == MetafileType.Wmf || metafileType == MetafileType.WmfPlaceable) { // WMF header header.wmf = (MetafileHeaderWmf)Marshal.PtrToStructure(memory, typeof(MetafileHeaderWmf)); header.emf = null; } else { // EMF header header.wmf = null; header.emf = (MetafileHeaderEmf)Marshal.PtrToStructure(memory, typeof(MetafileHeaderEmf)); } } finally { Marshal.FreeHGlobal(memory); } return header; } /// <summary> /// Returns a Windows handle to an enhanced <see cref='Metafile'/>. /// </summary> public IntPtr GetHenhmetafile() { IntPtr hEmf = IntPtr.Zero; int status = SafeNativeMethods.Gdip.GdipGetHemfFromMetafile(new HandleRef(this, nativeImage), out hEmf); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); return hEmf; } /// <summary> /// Plays an EMF+ file. /// </summary> public void PlayRecord(EmfPlusRecordType recordType, int flags, int dataSize, byte[] data) { // Used in conjunction with Graphics.EnumerateMetafile to play an EMF+ // The data must be DWORD aligned if it's an EMF or EMF+. It must be // WORD aligned if it's a WMF. int status = SafeNativeMethods.Gdip.GdipPlayMetafileRecord(new HandleRef(this, nativeImage), recordType, flags, dataSize, data); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); } /* * Create a new metafile object from a native metafile handle. * This is only for internal purpose. */ internal static Metafile FromGDIplus(IntPtr nativeImage) { Metafile metafile = new Metafile(); metafile.SetNativeImage(nativeImage); return metafile; } private Metafile() { } } }
// 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.Automation { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; /// <summary> /// HybridRunbookWorkerGroupOperations operations. /// </summary> internal partial class HybridRunbookWorkerGroupOperations : IServiceOperations<AutomationClient>, IHybridRunbookWorkerGroupOperations { /// <summary> /// Initializes a new instance of the HybridRunbookWorkerGroupOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal HybridRunbookWorkerGroupOperations(AutomationClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the AutomationClient /// </summary> public AutomationClient Client { get; private set; } /// <summary> /// Delete a hybrid runbook worker group. /// <see href="http://aka.ms/azureautomationsdk/hybridrunbookworkergroupoperations" /> /// </summary> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='automationAccountName'> /// Automation account name. /// </param> /// <param name='hybridRunbookWorkerGroupName'> /// The hybrid runbook worker group name /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string automationAccountName, string hybridRunbookWorkerGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (resourceGroupName != null) { if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._]+$")) { throw new ValidationException(ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._]+$"); } } if (automationAccountName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "automationAccountName"); } if (hybridRunbookWorkerGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "hybridRunbookWorkerGroupName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2015-10-31"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("automationAccountName", automationAccountName); tracingParameters.Add("hybridRunbookWorkerGroupName", hybridRunbookWorkerGroupName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Delete", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Automation/automationAccounts/{automationAccountName}/hybridRunbookWorkerGroups/{hybridRunbookWorkerGroupName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{automationAccountName}", System.Uri.EscapeDataString(automationAccountName)); _url = _url.Replace("{hybridRunbookWorkerGroupName}", System.Uri.EscapeDataString(hybridRunbookWorkerGroupName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("DELETE"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse(); _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> /// Retrieve a hybrid runbook worker group. /// <see href="http://aka.ms/azureautomationsdk/hybridrunbookworkergroupoperations" /> /// </summary> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='automationAccountName'> /// The automation account name. /// </param> /// <param name='hybridRunbookWorkerGroupName'> /// The hybrid runbook worker group name /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<HybridRunbookWorkerGroup>> GetWithHttpMessagesAsync(string resourceGroupName, string automationAccountName, string hybridRunbookWorkerGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (resourceGroupName != null) { if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._]+$")) { throw new ValidationException(ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._]+$"); } } if (automationAccountName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "automationAccountName"); } if (hybridRunbookWorkerGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "hybridRunbookWorkerGroupName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2015-10-31"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("automationAccountName", automationAccountName); tracingParameters.Add("hybridRunbookWorkerGroupName", hybridRunbookWorkerGroupName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Automation/automationAccounts/{automationAccountName}/hybridRunbookWorkerGroups/{hybridRunbookWorkerGroupName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{automationAccountName}", System.Uri.EscapeDataString(automationAccountName)); _url = _url.Replace("{hybridRunbookWorkerGroupName}", System.Uri.EscapeDataString(hybridRunbookWorkerGroupName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<HybridRunbookWorkerGroup>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<HybridRunbookWorkerGroup>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Update a hybrid runbook worker group. /// <see href="http://aka.ms/azureautomationsdk/hybridrunbookworkergroupoperations" /> /// </summary> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='automationAccountName'> /// The automation account name. /// </param> /// <param name='hybridRunbookWorkerGroupName'> /// The hybrid runbook worker group name /// </param> /// <param name='parameters'> /// The hybrid runbook worker group /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<HybridRunbookWorkerGroup>> UpdateWithHttpMessagesAsync(string resourceGroupName, string automationAccountName, string hybridRunbookWorkerGroupName, HybridRunbookWorkerGroupUpdateParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (resourceGroupName != null) { if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._]+$")) { throw new ValidationException(ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._]+$"); } } if (automationAccountName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "automationAccountName"); } if (hybridRunbookWorkerGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "hybridRunbookWorkerGroupName"); } if (parameters == null) { throw new ValidationException(ValidationRules.CannotBeNull, "parameters"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2015-10-31"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("automationAccountName", automationAccountName); tracingParameters.Add("hybridRunbookWorkerGroupName", hybridRunbookWorkerGroupName); tracingParameters.Add("parameters", parameters); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Update", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Automation/automationAccounts/{automationAccountName}/hybridRunbookWorkerGroups/{hybridRunbookWorkerGroupName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{automationAccountName}", System.Uri.EscapeDataString(automationAccountName)); _url = _url.Replace("{hybridRunbookWorkerGroupName}", System.Uri.EscapeDataString(hybridRunbookWorkerGroupName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PATCH"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(parameters != null) { _requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<HybridRunbookWorkerGroup>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<HybridRunbookWorkerGroup>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Retrieve a list of hybrid runbook worker groups. /// <see href="http://aka.ms/azureautomationsdk/hybridrunbookworkergroupoperations" /> /// </summary> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='automationAccountName'> /// The automation account name. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<HybridRunbookWorkerGroup>>> ListByAutomationAccountWithHttpMessagesAsync(string resourceGroupName, string automationAccountName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (resourceGroupName != null) { if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._]+$")) { throw new ValidationException(ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._]+$"); } } if (automationAccountName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "automationAccountName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2015-10-31"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("automationAccountName", automationAccountName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListByAutomationAccount", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Automation/automationAccounts/{automationAccountName}/hybridRunbookWorkerGroups").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{automationAccountName}", System.Uri.EscapeDataString(automationAccountName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<HybridRunbookWorkerGroup>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<HybridRunbookWorkerGroup>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Retrieve a list of hybrid runbook worker groups. /// <see href="http://aka.ms/azureautomationsdk/hybridrunbookworkergroupoperations" /> /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<HybridRunbookWorkerGroup>>> ListByAutomationAccountNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextPageLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListByAutomationAccountNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<HybridRunbookWorkerGroup>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<HybridRunbookWorkerGroup>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
//------------------------------------------------------------------------------ // <copyright file="XmlCustomFormatter.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // <owner current="true" primary="true">[....]</owner> //------------------------------------------------------------------------------ namespace System.Xml.Serialization { using System; using System.Xml; using System.Globalization; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Text; using System.Collections; using System.Configuration; using System.Xml.Serialization.Configuration; /// <summary> /// The <see cref="XmlCustomFormatter"/> class provides a set of static methods for converting /// primitive type values to and from their XML string representations.</summary> internal class XmlCustomFormatter { private static DateTimeSerializationSection.DateTimeSerializationMode mode; static DateTimeSerializationSection.DateTimeSerializationMode Mode { [SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "Reviewed for thread-safety")] get { if (mode == DateTimeSerializationSection.DateTimeSerializationMode.Default) { DateTimeSerializationSection section = PrivilegedConfigurationManager.GetSection(ConfigurationStrings.DateTimeSerializationSectionPath) as DateTimeSerializationSection; if (section != null) { mode = section.Mode; } else { mode = DateTimeSerializationSection.DateTimeSerializationMode.Roundtrip; } } return mode; } } private XmlCustomFormatter() {} internal static string FromDefaultValue(object value, string formatter) { if (value == null) return null; Type type = value.GetType(); if (type == typeof(DateTime)) { if (formatter == "DateTime") { return FromDateTime((DateTime)value); } if (formatter == "Date") { return FromDate((DateTime)value); } if (formatter == "Time") { return FromTime((DateTime)value); } } else if (type == typeof(string)) { if (formatter == "XmlName") { return FromXmlName((string)value); } if (formatter == "XmlNCName") { return FromXmlNCName((string)value); } if (formatter == "XmlNmToken") { return FromXmlNmToken((string)value); } if (formatter == "XmlNmTokens") { return FromXmlNmTokens((string)value); } } throw new Exception(Res.GetString(Res.XmlUnsupportedDefaultType, type.FullName)); } internal static string FromDate(DateTime value) { return XmlConvert.ToString(value, "yyyy-MM-dd"); } internal static string FromTime(DateTime value) { return XmlConvert.ToString(DateTime.MinValue + value.TimeOfDay, "HH:mm:ss.fffffffzzzzzz"); } internal static string FromDateTime(DateTime value) { if (Mode == DateTimeSerializationSection.DateTimeSerializationMode.Local) { return XmlConvert.ToString(value, "yyyy-MM-ddTHH:mm:ss.fffffffzzzzzz"); } else { // for mode DateTimeSerializationMode.Roundtrip and DateTimeSerializationMode.Default return XmlConvert.ToString(value, XmlDateTimeSerializationMode.RoundtripKind); } } internal static string FromChar(char value) { return XmlConvert.ToString((UInt16)value); } internal static string FromXmlName(string name) { return XmlConvert.EncodeName(name); } internal static string FromXmlNCName(string ncName) { return XmlConvert.EncodeLocalName(ncName); } internal static string FromXmlNmToken(string nmToken) { return XmlConvert.EncodeNmToken(nmToken); } internal static string FromXmlNmTokens(string nmTokens) { if (nmTokens == null) return null; if (nmTokens.IndexOf(' ') < 0) return FromXmlNmToken(nmTokens); else { string[] toks = nmTokens.Split(new char[] { ' ' }); StringBuilder sb = new StringBuilder(); for (int i = 0; i < toks.Length; i++) { if (i > 0) sb.Append(' '); sb.Append(FromXmlNmToken(toks[i])); } return sb.ToString(); } } internal static void WriteArrayBase64(XmlWriter writer, byte[] inData, int start, int count) { if (inData == null || count == 0) { return; } writer.WriteBase64(inData, start, count); } internal static string FromByteArrayHex(byte[] value) { if (value == null) return null; if (value.Length == 0) return ""; return XmlConvert.ToBinHexString(value); } internal static string FromEnum(long val, string[] vals, long[] ids, string typeName) { #if DEBUG // use exception in the place of Debug.Assert to avoid throwing asserts from a server process such as aspnet_ewp.exe if (ids.Length != vals.Length) throw new InvalidOperationException(Res.GetString(Res.XmlInternalErrorDetails, "Invalid enum")); #endif long originalValue = val; StringBuilder sb = new StringBuilder(); int iZero = -1; for (int i = 0; i < ids.Length; i++) { if (ids[i] == 0) { iZero = i; continue; } if (val == 0) { break; } if ((ids[i] & originalValue) == ids[i]) { if (sb.Length != 0) sb.Append(" "); sb.Append(vals[i]); val &= ~ids[i]; } } if (val != 0) { // failed to parse the enum value throw new InvalidOperationException(Res.GetString(Res.XmlUnknownConstant, originalValue, typeName == null ? "enum" : typeName)); } if (sb.Length == 0 && iZero >= 0) { sb.Append(vals[iZero]); } return sb.ToString(); } internal static object ToDefaultValue(string value, string formatter) { if (formatter == "DateTime") { return ToDateTime(value); } if (formatter == "Date") { return ToDate(value); } if (formatter == "Time") { return ToTime(value); } if (formatter == "XmlName") { return ToXmlName(value); } if (formatter == "XmlNCName") { return ToXmlNCName(value); } if (formatter == "XmlNmToken") { return ToXmlNmToken(value); } if (formatter == "XmlNmTokens") { return ToXmlNmTokens(value); } throw new Exception(Res.GetString(Res.XmlUnsupportedDefaultValue, formatter)); // Debug.WriteLineIf(CompModSwitches.XmlSerialization.TraceVerbose, "XmlSerialization::Unhandled default value " + value + " formatter " + formatter); // return DBNull.Value; } static string[] allDateTimeFormats = new string[] { "yyyy-MM-ddTHH:mm:ss.fffffffzzzzzz", "yyyy", "---dd", "---ddZ", "---ddzzzzzz", "--MM-dd", "--MM-ddZ", "--MM-ddzzzzzz", "--MM--", "--MM--Z", "--MM--zzzzzz", "yyyy-MM", "yyyy-MMZ", "yyyy-MMzzzzzz", "yyyyzzzzzz", "yyyy-MM-dd", "yyyy-MM-ddZ", "yyyy-MM-ddzzzzzz", "HH:mm:ss", "HH:mm:ss.f", "HH:mm:ss.ff", "HH:mm:ss.fff", "HH:mm:ss.ffff", "HH:mm:ss.fffff", "HH:mm:ss.ffffff", "HH:mm:ss.fffffff", "HH:mm:ssZ", "HH:mm:ss.fZ", "HH:mm:ss.ffZ", "HH:mm:ss.fffZ", "HH:mm:ss.ffffZ", "HH:mm:ss.fffffZ", "HH:mm:ss.ffffffZ", "HH:mm:ss.fffffffZ", "HH:mm:sszzzzzz", "HH:mm:ss.fzzzzzz", "HH:mm:ss.ffzzzzzz", "HH:mm:ss.fffzzzzzz", "HH:mm:ss.ffffzzzzzz", "HH:mm:ss.fffffzzzzzz", "HH:mm:ss.ffffffzzzzzz", "HH:mm:ss.fffffffzzzzzz", "yyyy-MM-ddTHH:mm:ss", "yyyy-MM-ddTHH:mm:ss.f", "yyyy-MM-ddTHH:mm:ss.ff", "yyyy-MM-ddTHH:mm:ss.fff", "yyyy-MM-ddTHH:mm:ss.ffff", "yyyy-MM-ddTHH:mm:ss.fffff", "yyyy-MM-ddTHH:mm:ss.ffffff", "yyyy-MM-ddTHH:mm:ss.fffffff", "yyyy-MM-ddTHH:mm:ssZ", "yyyy-MM-ddTHH:mm:ss.fZ", "yyyy-MM-ddTHH:mm:ss.ffZ", "yyyy-MM-ddTHH:mm:ss.fffZ", "yyyy-MM-ddTHH:mm:ss.ffffZ", "yyyy-MM-ddTHH:mm:ss.fffffZ", "yyyy-MM-ddTHH:mm:ss.ffffffZ", "yyyy-MM-ddTHH:mm:ss.fffffffZ", "yyyy-MM-ddTHH:mm:sszzzzzz", "yyyy-MM-ddTHH:mm:ss.fzzzzzz", "yyyy-MM-ddTHH:mm:ss.ffzzzzzz", "yyyy-MM-ddTHH:mm:ss.fffzzzzzz", "yyyy-MM-ddTHH:mm:ss.ffffzzzzzz", "yyyy-MM-ddTHH:mm:ss.fffffzzzzzz", "yyyy-MM-ddTHH:mm:ss.ffffffzzzzzz", }; static string[] allDateFormats = new string[] { "yyyy-MM-ddzzzzzz", "yyyy-MM-dd", "yyyy-MM-ddZ", "yyyy", "---dd", "---ddZ", "---ddzzzzzz", "--MM-dd", "--MM-ddZ", "--MM-ddzzzzzz", "--MM--", "--MM--Z", "--MM--zzzzzz", "yyyy-MM", "yyyy-MMZ", "yyyy-MMzzzzzz", "yyyyzzzzzz", }; static string[] allTimeFormats = new string[] { "HH:mm:ss.fffffffzzzzzz", "HH:mm:ss", "HH:mm:ss.f", "HH:mm:ss.ff", "HH:mm:ss.fff", "HH:mm:ss.ffff", "HH:mm:ss.fffff", "HH:mm:ss.ffffff", "HH:mm:ss.fffffff", "HH:mm:ssZ", "HH:mm:ss.fZ", "HH:mm:ss.ffZ", "HH:mm:ss.fffZ", "HH:mm:ss.ffffZ", "HH:mm:ss.fffffZ", "HH:mm:ss.ffffffZ", "HH:mm:ss.fffffffZ", "HH:mm:sszzzzzz", "HH:mm:ss.fzzzzzz", "HH:mm:ss.ffzzzzzz", "HH:mm:ss.fffzzzzzz", "HH:mm:ss.ffffzzzzzz", "HH:mm:ss.fffffzzzzzz", "HH:mm:ss.ffffffzzzzzz", }; internal static DateTime ToDateTime(string value) { if (Mode == DateTimeSerializationSection.DateTimeSerializationMode.Local) { return ToDateTime(value, allDateTimeFormats); } else { // for mode DateTimeSerializationMode.Roundtrip and DateTimeSerializationMode.Default return XmlConvert.ToDateTime(value, XmlDateTimeSerializationMode.RoundtripKind); } } internal static DateTime ToDateTime(string value, string[] formats) { return XmlConvert.ToDateTime(value, formats); } internal static DateTime ToDate(string value) { return ToDateTime(value, allDateFormats); } internal static DateTime ToTime(string value) { return DateTime.ParseExact(value, allTimeFormats, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.AllowLeadingWhite|DateTimeStyles.AllowTrailingWhite|DateTimeStyles.NoCurrentDateDefault); } internal static char ToChar(string value) { return (char)XmlConvert.ToUInt16(value); } internal static string ToXmlName(string value) { return XmlConvert.DecodeName(CollapseWhitespace(value)); } internal static string ToXmlNCName(string value) { return XmlConvert.DecodeName(CollapseWhitespace(value)); } internal static string ToXmlNmToken(string value) { return XmlConvert.DecodeName(CollapseWhitespace(value)); } internal static string ToXmlNmTokens(string value) { return XmlConvert.DecodeName(CollapseWhitespace(value)); } internal static byte[] ToByteArrayBase64(string value) { if (value == null) return null; value = value.Trim(); if (value.Length == 0) return new byte[0]; return Convert.FromBase64String(value); } internal static byte[] ToByteArrayHex(string value) { if (value == null) return null; value = value.Trim(); return XmlConvert.FromBinHexString(value); } internal static long ToEnum(string val, Hashtable vals, string typeName, bool validate) { long value = 0; string[] parts = val.Split(null); for (int i = 0; i < parts.Length; i++) { object id = vals[parts[i]]; if (id != null) value |= (long)id; else if (validate && parts[i].Length > 0) throw new InvalidOperationException(Res.GetString(Res.XmlUnknownConstant, parts[i], typeName)); } return value; } static string CollapseWhitespace(string value) { if (value == null) return null; return value.Trim(); } } }
namespace Nancy.Bootstrapper { using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; /// <summary> /// Nancy bootstrapper base with per-request container support. /// Stores/retrieves the child container in the context to ensure that /// only one child container is stored per request, and that the child /// container will be disposed at the end of the request. /// </summary> /// <typeparam name="TContainer">IoC container type</typeparam> public abstract class NancyBootstrapperWithRequestContainerBase<TContainer> : NancyBootstrapperBase<TContainer> where TContainer : class { protected NancyBootstrapperWithRequestContainerBase() { this.RequestScopedTypes = new TypeRegistration[0]; this.RequestScopedCollectionTypes = new CollectionTypeRegistration[0]; } /// <summary> /// Context key for storing the child container in the context /// </summary> private readonly string contextKey = typeof(TContainer).FullName + "BootstrapperChildContainer"; /// <summary> /// Stores the module registrations to be registered into the request container /// </summary> private IEnumerable<ModuleRegistration> moduleRegistrationTypeCache; /// <summary> /// Stores the per-request type registrations /// </summary> private TypeRegistration[] RequestScopedTypes { get; set; } /// <summary> /// Stores the per-request collection registrations /// </summary> private CollectionTypeRegistration[] RequestScopedCollectionTypes { get; set; } /// <summary> /// Gets the context key for storing the child container in the context /// </summary> protected virtual string ContextKey { get { return this.contextKey; } } /// <summary> /// Get all <see cref="INancyModule"/> implementation instances /// </summary> /// <param name="context">The current context</param> /// <returns>An <see cref="IEnumerable{T}"/> instance containing <see cref="INancyModule"/> instances.</returns> public override sealed IEnumerable<INancyModule> GetAllModules(NancyContext context) { var requestContainer = this.GetConfiguredRequestContainer(context); this.RegisterRequestContainerModules(requestContainer, this.moduleRegistrationTypeCache); return this.GetAllModules(requestContainer); } /// <summary> /// Retrieves a specific <see cref="INancyModule"/> implementation - should be per-request lifetime /// </summary> /// <param name="moduleType">Module type</param> /// <param name="context">The current context</param> /// <returns>The <see cref="INancyModule"/> instance</returns> public override sealed INancyModule GetModule(Type moduleType, NancyContext context) { var requestContainer = this.GetConfiguredRequestContainer(context); return this.GetModule(requestContainer, moduleType); } /// <summary> /// Creates and initializes the request pipelines. /// </summary> /// <param name="context">The <see cref="NancyContext"/> used by the request.</param> /// <returns>An <see cref="IPipelines"/> instance.</returns> protected override sealed IPipelines InitializeRequestPipelines(NancyContext context) { var requestContainer = this.GetConfiguredRequestContainer(context); var requestPipelines = new Pipelines(this.ApplicationPipelines); if (this.RequestStartupTaskTypeCache.Any()) { var startupTasks = this.RegisterAndGetRequestStartupTasks(requestContainer, this.RequestStartupTaskTypeCache); foreach (var requestStartup in startupTasks) { requestStartup.Initialize(requestPipelines, context); } } this.RequestStartup(requestContainer, requestPipelines, context); return requestPipelines; } /// <summary> /// Takes the registration tasks and calls the relevant methods to register them /// </summary> /// <param name="registrationTasks">Registration tasks</param> protected override sealed void RegisterRegistrationTasks(IEnumerable<IRegistrations> registrationTasks) { foreach (var applicationRegistrationTask in registrationTasks.ToList()) { var applicationTypeRegistrations = applicationRegistrationTask.TypeRegistrations == null ? new TypeRegistration[] { } : applicationRegistrationTask.TypeRegistrations.ToArray(); this.RegisterTypes(this.ApplicationContainer, applicationTypeRegistrations.Where(tr => tr.Lifetime != Lifetime.PerRequest)); this.RequestScopedTypes = this.RequestScopedTypes.Concat(applicationTypeRegistrations.Where(tr => tr.Lifetime == Lifetime.PerRequest) .Select(tr => new TypeRegistration(tr.RegistrationType, tr.ImplementationType, Lifetime.Singleton))) .ToArray(); var applicationCollectionRegistrations = applicationRegistrationTask.CollectionTypeRegistrations == null ? new CollectionTypeRegistration[] { } : applicationRegistrationTask.CollectionTypeRegistrations.ToArray(); this.RegisterCollectionTypes(this.ApplicationContainer, applicationCollectionRegistrations.Where(tr => tr.Lifetime != Lifetime.PerRequest)); this.RequestScopedCollectionTypes = this.RequestScopedCollectionTypes.Concat(applicationCollectionRegistrations.Where(tr => tr.Lifetime == Lifetime.PerRequest) .Select(tr => new CollectionTypeRegistration(tr.RegistrationType, tr.ImplementationTypes, Lifetime.Singleton))) .ToArray(); var applicationInstanceRegistrations = applicationRegistrationTask.InstanceRegistrations; if (applicationInstanceRegistrations != null) { this.RegisterInstances(this.ApplicationContainer, applicationInstanceRegistrations); } } } /// <summary> /// Gets the per-request container /// </summary> /// <param name="context">Current context</param> /// <returns>Request container instance</returns> protected TContainer GetConfiguredRequestContainer(NancyContext context) { object contextObject; context.Items.TryGetValue(this.ContextKey, out contextObject); var requestContainer = contextObject as TContainer; if (requestContainer == null) { requestContainer = this.CreateRequestContainer(context); context.Items[this.ContextKey] = requestContainer; this.ConfigureRequestContainer(requestContainer, context); this.RegisterTypes(requestContainer, this.RequestScopedTypes); this.RegisterCollectionTypes(requestContainer, this.RequestScopedCollectionTypes); } return requestContainer; } /// <summary> /// Configure the request container /// </summary> /// <param name="container">Request container instance</param> /// <param name="context"></param> protected virtual void ConfigureRequestContainer(TContainer container, NancyContext context) { } /// <summary> /// Register the given module types into the container /// </summary> /// <param name="container">Container to register into</param> /// <param name="moduleRegistrationTypes">NancyModule types</param> protected override sealed void RegisterModules(TContainer container, IEnumerable<ModuleRegistration> moduleRegistrationTypes) { this.moduleRegistrationTypeCache = moduleRegistrationTypes; } /// <summary> /// Creates a per request child/nested container /// </summary> /// <param name="context">Current context</param> /// <returns>Request container instance</returns> protected abstract TContainer CreateRequestContainer(NancyContext context); /// <summary> /// Register the given module types into the request container /// </summary> /// <param name="container">Container to register into</param> /// <param name="moduleRegistrationTypes">NancyModule types</param> protected abstract void RegisterRequestContainerModules(TContainer container, IEnumerable<ModuleRegistration> moduleRegistrationTypes); /// <summary> /// Retrieve all module instances from the container /// </summary> /// <param name="container">Container to use</param> /// <returns>Collection of NancyModule instances</returns> protected abstract IEnumerable<INancyModule> GetAllModules(TContainer container); /// <summary> /// Retrieve a specific module instance from the container /// </summary> /// <param name="container">Container to use</param> /// <param name="moduleType">Type of the module</param> /// <returns>NancyModule instance</returns> protected abstract INancyModule GetModule(TContainer container, Type moduleType); } }
using System; using System.Collections; using System.IO; using NUnit.Framework; using Org.BouncyCastle.Asn1.Sec; using Org.BouncyCastle.Crypto; using Org.BouncyCastle.Crypto.Generators; using Org.BouncyCastle.Crypto.Parameters; using Org.BouncyCastle.Math; using Org.BouncyCastle.Security; using Org.BouncyCastle.Utilities.Encoders; using Org.BouncyCastle.Utilities.Test; namespace Org.BouncyCastle.Bcpg.OpenPgp.Tests { [TestFixture] public class PgpKeyRingTest : SimpleTest { private static readonly byte[] _pub1 = Base64.Decode( "mQGiBEA83v0RBADzKVLVCnpWQxX0LCsevw/3OLs0H7MOcLBQ4wMO9sYmzGYn" + "xpVj+4e4PiCP7QBayWyy4lugL6Lnw7tESvq3A4v3fefcxaCTkJrryiKn4+Cg" + "y5rIBbrSKNtCEhVi7xjtdnDjP5kFKgHYjVOeIKn4Cz/yzPG3qz75kDknldLf" + "yHxp2wCgwW1vAE5EnZU4/UmY7l8kTNkMltMEAJP4/uY4zcRwLI9Q2raPqAOJ" + "TYLd7h+3k/BxI0gIw96niQ3KmUZDlobbWBI+VHM6H99vcttKU3BgevNf8M9G" + "x/AbtW3SS4De64wNSU3189XDG8vXf0vuyW/K6Pcrb8exJWY0E1zZQ1WXT0gZ" + "W0kH3g5ro//Tusuil9q2lVLF2ovJA/0W+57bPzi318dWeNs0tTq6Njbc/GTG" + "FUAVJ8Ss5v2u6h7gyJ1DB334ExF/UdqZGldp0ugkEXaSwBa2R7d3HBgaYcoP" + "Ck1TrovZzEY8gm7JNVy7GW6mdOZuDOHTxyADEEP2JPxh6eRcZbzhGuJuYIif" + "IIeLOTI5Dc4XKeV32a+bWrQidGVzdCAoVGVzdCBrZXkpIDx0ZXN0QHViaWNh" + "bGwuY29tPohkBBMRAgAkBQJAPN79AhsDBQkB4TOABgsJCAcDAgMVAgMDFgIB" + "Ah4BAheAAAoJEJh8Njfhe8KmGDcAoJWr8xgPr75y/Cp1kKn12oCCOb8zAJ4p" + "xSvk4K6tB2jYbdeSrmoWBZLdMLACAAC5AQ0EQDzfARAEAJeUAPvUzJJbKcc5" + "5Iyb13+Gfb8xBWE3HinQzhGr1v6A1aIZbRj47UPAD/tQxwz8VAwJySx82ggN" + "LxCk4jW9YtTL3uZqfczsJngV25GoIN10f4/j2BVqZAaX3q79a3eMiql1T0oE" + "AGmD7tO1LkTvWfm3VvA0+t8/6ZeRLEiIqAOHAAQNBACD0mVMlAUgd7REYy/1" + "mL99Zlu9XU0uKyUex99sJNrcx1aj8rIiZtWaHz6CN1XptdwpDeSYEOFZ0PSu" + "qH9ByM3OfjU/ya0//xdvhwYXupn6P1Kep85efMBA9jUv/DeBOzRWMFG6sC6y" + "k8NGG7Swea7EHKeQI40G3jgO/+xANtMyTIhPBBgRAgAPBQJAPN8BAhsMBQkB" + "4TOAAAoJEJh8Njfhe8KmG7kAn00mTPGJCWqmskmzgdzeky5fWd7rAKCNCp3u" + "ZJhfg0htdgAfIy8ppm05vLACAAA="); private static readonly byte[] _sec1 = Base64.Decode( "lQHhBEA83v0RBADzKVLVCnpWQxX0LCsevw/3OLs0H7MOcLBQ4wMO9sYmzGYn" + "xpVj+4e4PiCP7QBayWyy4lugL6Lnw7tESvq3A4v3fefcxaCTkJrryiKn4+Cg" + "y5rIBbrSKNtCEhVi7xjtdnDjP5kFKgHYjVOeIKn4Cz/yzPG3qz75kDknldLf" + "yHxp2wCgwW1vAE5EnZU4/UmY7l8kTNkMltMEAJP4/uY4zcRwLI9Q2raPqAOJ" + "TYLd7h+3k/BxI0gIw96niQ3KmUZDlobbWBI+VHM6H99vcttKU3BgevNf8M9G" + "x/AbtW3SS4De64wNSU3189XDG8vXf0vuyW/K6Pcrb8exJWY0E1zZQ1WXT0gZ" + "W0kH3g5ro//Tusuil9q2lVLF2ovJA/0W+57bPzi318dWeNs0tTq6Njbc/GTG" + "FUAVJ8Ss5v2u6h7gyJ1DB334ExF/UdqZGldp0ugkEXaSwBa2R7d3HBgaYcoP" + "Ck1TrovZzEY8gm7JNVy7GW6mdOZuDOHTxyADEEP2JPxh6eRcZbzhGuJuYIif" + "IIeLOTI5Dc4XKeV32a+bWv4CAwJ5KgazImo+sGBfMhDiBcBTqyDGhKHNgHic" + "0Pky9FeRvfXTc2AO+jGmFPjcs8BnTWuDD0/jkQnRZpp1TrQidGVzdCAoVGVz" + "dCBrZXkpIDx0ZXN0QHViaWNhbGwuY29tPohkBBMRAgAkBQJAPN79AhsDBQkB" + "4TOABgsJCAcDAgMVAgMDFgIBAh4BAheAAAoJEJh8Njfhe8KmGDcAn3XeXDMg" + "BZgrZzFWU2IKtA/5LG2TAJ0Vf/jjyq0jZNZfGfoqGTvD2MAl0rACAACdAVgE" + "QDzfARAEAJeUAPvUzJJbKcc55Iyb13+Gfb8xBWE3HinQzhGr1v6A1aIZbRj4" + "7UPAD/tQxwz8VAwJySx82ggNLxCk4jW9YtTL3uZqfczsJngV25GoIN10f4/j" + "2BVqZAaX3q79a3eMiql1T0oEAGmD7tO1LkTvWfm3VvA0+t8/6ZeRLEiIqAOH" + "AAQNBACD0mVMlAUgd7REYy/1mL99Zlu9XU0uKyUex99sJNrcx1aj8rIiZtWa" + "Hz6CN1XptdwpDeSYEOFZ0PSuqH9ByM3OfjU/ya0//xdvhwYXupn6P1Kep85e" + "fMBA9jUv/DeBOzRWMFG6sC6yk8NGG7Swea7EHKeQI40G3jgO/+xANtMyTP4C" + "AwJ5KgazImo+sGBl2C7CFuI+5KM4ZhbtVie7l+OiTpr5JW2z5VgnV3EX9p04" + "LcGKfQvD65+ELwli6yh8B2zGcipqTaYk3QoYNIhPBBgRAgAPBQJAPN8BAhsM" + "BQkB4TOAAAoJEJh8Njfhe8KmG7kAniuRkaFFv1pdCBN8JJXpcorHmyouAJ9L" + "xxmusffR6OI7WgD3XZ0AL8zUC7ACAAA="); // private static readonly char[] pass1 = "qwertzuiop".ToCharArray(); private static readonly byte[] _pub2 = Base64.Decode( "mQGiBEBtfW8RBADfWjTxFedIbGBNVgh064D/OCf6ul7x4PGsCl+BkAyheYkr" + "mVUsChmBKoeXaY+Fb85wwusXzyM/6JFK58Rg+vEb3Z19pue8Ixxq7cRtCtOA" + "tOP1eKXLNtTRWJutvLkQmeOa19UZ6ziIq23aWuWKSq+KKMWek2GUnGycnx5M" + "W0pn1QCg/39r9RKhY9cdKYqRcqsr9b2B/AsD/Ru24Q15Jmrsl9zZ6EC47J49" + "iNW5sLQx1qf/mgfVWQTmU2j6gq4ND1OuK7+0OP/1yMOUpkjjcqxFgTnDAAoM" + "hHDTzCv/aZzIzmMvgLsYU3aIMfbz+ojpuASMCMh+te01cEMjiPWwDtdWWOdS" + "OSyX9ylzhO3PiNDks8R83onsacYpA/9WhTcg4bvkjaj66I7wGZkm3BmTxNSb" + "pE4b5HZDh31rRYhY9tmrryCfFnU4BS2Enjj5KQe9zFv7pUBCBW2oFo8i8Osn" + "O6fa1wVN4fBHC6wqWmmpnkFerNPkiC9V75KUFIfeWHmT3r2DVSO3dfdHDERA" + "jFIAioMLjhaX6DnODF5KQrABh7QmU2FpIFB1bGxhYmhvdGxhIDxwc2FpQG15" + "amF2YXdvcmxkLmNvbT6wAwP//4kAVwQQEQIAFwUCQG19bwcLCQgHAwIKAhkB" + "BRsDAAAAAAoJEKXQf/RT99uYmfAAoMKxV5g2owIfmy2w7vSLvOQUpvvOAJ4n" + "jB6xJot523rPAQW9itPoGGekirABZ7kCDQRAbX1vEAgA9kJXtwh/CBdyorrW" + "qULzBej5UxE5T7bxbrlLOCDaAadWoxTpj0BV89AHxstDqZSt90xkhkn4DIO9" + "ZekX1KHTUPj1WV/cdlJPPT2N286Z4VeSWc39uK50T8X8dryDxUcwYc58yWb/" + "Ffm7/ZFexwGq01uejaClcjrUGvC/RgBYK+X0iP1YTknbzSC0neSRBzZrM2w4" + "DUUdD3yIsxx8Wy2O9vPJI8BD8KVbGI2Ou1WMuF040zT9fBdXQ6MdGGzeMyEs" + "tSr/POGxKUAYEY18hKcKctaGxAMZyAcpesqVDNmWn6vQClCbAkbTCD1mpF1B" + "n5x8vYlLIhkmuquiXsNV6TILOwACAgf9F7/nJHDayJ3pBVTTVSq2g5WKUXMg" + "xxGKTvOahiVRcbO03w0pKAkH85COakVfe56sMYpWRl36adjNoKOxaciow74D" + "1R5snY/hv/kBXPBkzo4UMkbANIVaZ0IcnLp+rkkXcDVbRCibZf8FfCY1zXbq" + "d680UtEgRbv1D8wFBqfMt7kLsuf9FnIw6vK4DU06z5ZDg25RHGmswaDyY6Mw" + "NGCrKGbHf9I/T7MMuhGF/in8UU8hv8uREOjseOqklG3/nsI1hD/MdUC7fzXi" + "MRO4RvahLoeXOuaDkMYALdJk5nmNuCL1YPpbFGttI3XsK7UrP/Fhd8ND6Nro" + "wCqrN6keduK+uLABh4kATAQYEQIADAUCQG19bwUbDAAAAAAKCRCl0H/0U/fb" + "mC/0AJ4r1yvyu4qfOXlDgmVuCsvHFWo63gCfRIrCB2Jv/N1cgpmq0L8LGHM7" + "G/KwAWeZAQ0EQG19owEIAMnavLYqR7ffaDPbbq+lQZvLCK/3uA0QlyngNyTa" + "sDW0WC1/ryy2dx7ypOOCicjnPYfg3LP5TkYAGoMjxH5+xzM6xfOR+8/EwK1z" + "N3A5+X/PSBDlYjQ9dEVKrvvc7iMOp+1K1VMf4Ug8Yah22Ot4eLGP0HRCXiv5" + "vgdBNsAl/uXnBJuDYQmLrEniqq/6UxJHKHxZoS/5p13Cq7NfKB1CJCuJXaCE" + "TW2do+cDpN6r0ltkF/r+ES+2L7jxyoHcvQ4YorJoDMlAN6xpIZQ8dNaTYP/n" + "Mx/pDS3shUzbU+UYPQrreJLMF1pD+YWP5MTKaZTo+U/qPjDFGcadInhPxvh3" + "1ssAEQEAAbABh7QuU2FuZGh5YSBQdWxsYWJob3RsYSA8cHNhbmRoeWFAbXlq" + "YXZhd29ybGQuY29tPrADA///iQEtBBABAgAXBQJAbX2jBwsJCAcDAgoCGQEF" + "GwMAAAAACgkQx87DL9gOvoeVUwgAkQXYiF0CxhKbDnuabAssnOEwJrutgCRO" + "CJRQvIwTe3fe6hQaWn2Yowt8OQtNFiR8GfAY6EYxyFLKzZbAI/qtq5fHmN3e" + "RSyNWe6d6e17hqZZL7kf2sVkyGTChHj7Jiuo7vWkdqT2MJN6BW5tS9CRH7Me" + "D839STv+4mAAO9auGvSvicP6UEQikAyCy/ihoJxLQlspfbSNpi0vrUjCPT7N" + "tWwfP0qF64i9LYkjzLqihnu+UareqOPhXcWnyFKrjmg4ezQkweNU2pdvCLbc" + "W24FhT92ivHgpLyWTswXcqjhFjVlRr0+2sIz7v1k0budCsJ7PjzOoH0hJxCv" + "sJQMlZR/e7ABZ7kBDQRAbX2kAQgAm5j+/LO2M4pKm/VUPkYuj3eefHkzjM6n" + "KbvRZX1Oqyf+6CJTxQskUWKAtkzzKafPdS5Wg0CMqeXov+EFod4bPEYccszn" + "cKd1U8NRwacbEpCvvvB84Yl2YwdWpDpkryyyLI4PbCHkeuwx9Dc2z7t4XDB6" + "FyAJTMAkia7nzYa/kbeUO3c2snDb/dU7uyCsyKtTZyTyhTgtl/f9L03Bgh95" + "y3mOUz0PimJ0Sg4ANczF4d04BpWkjLNVJi489ifWodPlHm1hag5drYekYpWJ" + "+3g0uxs5AwayV9BcOkPKb1uU3EoYQw+nn0Kn314Nvx2M1tKYunuVNLEm0PhA" + "/+B8PTq8BQARAQABsAGHiQEiBBgBAgAMBQJAbX2kBRsMAAAAAAoJEMfOwy/Y" + "Dr6HkLoH/RBY8lvUv1r8IdTs5/fN8e/MnGeThLl+JrlYF/4t3tjXYIf5xUj/" + "c9NdjreKYgHfMtrbVM08LlxUVQlkjuF3DIk5bVH9Blq8aXmyiwiM5GrCry+z" + "WiqkpZze1G577C38mMJbHDwbqNCLALMzo+W2q04Avl5sniNnDNGbGz9EjhRg" + "o7oS16KkkD6Ls4RnHTEZ0vyZOXodDHu+sk/2kzj8K07kKaM8rvR7aDKiI7HH" + "1GxJz70fn1gkKuV2iAIIiU25bty+S3wr+5h030YBsUZF1qeKCdGOmpK7e9Of" + "yv9U7rf6Z5l8q+akjqLZvej9RnxeH2Um7W+tGg2me482J+z6WOawAWc="); private static readonly byte[] _sec2 = Base64.Decode( "lQHpBEBtfW8RBADfWjTxFedIbGBNVgh064D/OCf6ul7x4PGsCl+BkAyheYkr" + "mVUsChmBKoeXaY+Fb85wwusXzyM/6JFK58Rg+vEb3Z19pue8Ixxq7cRtCtOA" + "tOP1eKXLNtTRWJutvLkQmeOa19UZ6ziIq23aWuWKSq+KKMWek2GUnGycnx5M" + "W0pn1QCg/39r9RKhY9cdKYqRcqsr9b2B/AsD/Ru24Q15Jmrsl9zZ6EC47J49" + "iNW5sLQx1qf/mgfVWQTmU2j6gq4ND1OuK7+0OP/1yMOUpkjjcqxFgTnDAAoM" + "hHDTzCv/aZzIzmMvgLsYU3aIMfbz+ojpuASMCMh+te01cEMjiPWwDtdWWOdS" + "OSyX9ylzhO3PiNDks8R83onsacYpA/9WhTcg4bvkjaj66I7wGZkm3BmTxNSb" + "pE4b5HZDh31rRYhY9tmrryCfFnU4BS2Enjj5KQe9zFv7pUBCBW2oFo8i8Osn" + "O6fa1wVN4fBHC6wqWmmpnkFerNPkiC9V75KUFIfeWHmT3r2DVSO3dfdHDERA" + "jFIAioMLjhaX6DnODF5KQv4JAwIJH6A/rzqmMGAG4e+b8Whdvp8jaTGVT4CG" + "M1b65rbiDyAuf5KTFymQBOIi9towgFzG9NXAZC07nEYSukN56tUTUDNVsAGH" + "tCZTYWkgUHVsbGFiaG90bGEgPHBzYWlAbXlqYXZhd29ybGQuY29tPrADA///" + "iQBXBBARAgAXBQJAbX1vBwsJCAcDAgoCGQEFGwMAAAAACgkQpdB/9FP325iZ" + "8ACgwrFXmDajAh+bLbDu9Iu85BSm+84AnieMHrEmi3nbes8BBb2K0+gYZ6SK" + "sAFnnQJqBEBtfW8QCAD2Qle3CH8IF3KiutapQvMF6PlTETlPtvFuuUs4INoB" + "p1ajFOmPQFXz0AfGy0OplK33TGSGSfgMg71l6RfUodNQ+PVZX9x2Uk89PY3b" + "zpnhV5JZzf24rnRPxfx2vIPFRzBhznzJZv8V+bv9kV7HAarTW56NoKVyOtQa" + "8L9GAFgr5fSI/VhOSdvNILSd5JEHNmszbDgNRR0PfIizHHxbLY7288kjwEPw" + "pVsYjY67VYy4XTjTNP18F1dDox0YbN4zISy1Kv884bEpQBgRjXyEpwpy1obE" + "AxnIByl6ypUM2Zafq9AKUJsCRtMIPWakXUGfnHy9iUsiGSa6q6Jew1XpMgs7" + "AAICB/0Xv+ckcNrInekFVNNVKraDlYpRcyDHEYpO85qGJVFxs7TfDSkoCQfz" + "kI5qRV97nqwxilZGXfpp2M2go7FpyKjDvgPVHmydj+G/+QFc8GTOjhQyRsA0" + "hVpnQhycun6uSRdwNVtEKJtl/wV8JjXNdup3rzRS0SBFu/UPzAUGp8y3uQuy" + "5/0WcjDq8rgNTTrPlkODblEcaazBoPJjozA0YKsoZsd/0j9Pswy6EYX+KfxR" + "TyG/y5EQ6Ox46qSUbf+ewjWEP8x1QLt/NeIxE7hG9qEuh5c65oOQxgAt0mTm" + "eY24IvVg+lsUa20jdewrtSs/8WF3w0Po2ujAKqs3qR524r64/gkDAmmp39NN" + "U2pqYHokufIOab2VpD7iQo8UjHZNwR6dpjyky9dVfIe4MA0H+t0ju8UDdWoe" + "IkRu8guWsI83mjGPbIq8lmsZOXPCA8hPuBmL0iaj8TnuotmsBjIBsAGHiQBM" + "BBgRAgAMBQJAbX1vBRsMAAAAAAoJEKXQf/RT99uYL/QAnivXK/K7ip85eUOC" + "ZW4Ky8cVajreAJ9EisIHYm/83VyCmarQvwsYczsb8rABZ5UDqARAbX2jAQgA" + "ydq8tipHt99oM9tur6VBm8sIr/e4DRCXKeA3JNqwNbRYLX+vLLZ3HvKk44KJ" + "yOc9h+Dcs/lORgAagyPEfn7HMzrF85H7z8TArXM3cDn5f89IEOViND10RUqu" + "+9zuIw6n7UrVUx/hSDxhqHbY63h4sY/QdEJeK/m+B0E2wCX+5ecEm4NhCYus" + "SeKqr/pTEkcofFmhL/mnXcKrs18oHUIkK4ldoIRNbZ2j5wOk3qvSW2QX+v4R" + "L7YvuPHKgdy9DhiismgMyUA3rGkhlDx01pNg/+czH+kNLeyFTNtT5Rg9Cut4" + "kswXWkP5hY/kxMpplOj5T+o+MMUZxp0ieE/G+HfWywARAQABCWEWL2cKQKcm" + "XFTNsWgRoOcOkKyJ/osERh2PzNWvOF6/ir1BMRsg0qhd+hEcoWHaT+7Vt12i" + "5Y2Ogm2HFrVrS5/DlV/rw0mkALp/3cR6jLOPyhmq7QGwhG27Iy++pLIksXQa" + "RTboa7ZasEWw8zTqa4w17M5Ebm8dtB9Mwl/kqU9cnIYnFXj38BWeia3iFBNG" + "PD00hqwhPUCTUAcH9qQPSqKqnFJVPe0KQWpq78zhCh1zPUIa27CE86xRBf45" + "XbJwN+LmjCuQEnSNlloXJSPTRjEpla+gWAZz90fb0uVIR1dMMRFxsuaO6aCF" + "QMN2Mu1wR/xzTzNCiQf8cVzq7YkkJD8ChJvu/4BtWp3BlU9dehAz43mbMhaw" + "Qx3NmhKR/2dv1cJy/5VmRuljuzC+MRtuIjJ+ChoTa9ubNjsT6BF5McRAnVzf" + "raZK+KVWCGA8VEZwe/K6ouYLsBr6+ekCKIkGZdM29927m9HjdFwEFjnzQlWO" + "NZCeYgDcK22v7CzobKjdo2wdC7XIOUVCzMWMl+ch1guO/Y4KVuslfeQG5X1i" + "PJqV+bwJriCx5/j3eE/aezK/vtZU6cchifmvefKvaNL34tY0Myz2bOx44tl8" + "qNcGZbkYF7xrNCutzI63xa2ruN1p3hNxicZV1FJSOje6+ITXkU5Jmufto7IJ" + "t/4Q2dQefBQ1x/d0EdX31yK6+1z9dF/k3HpcSMb5cAWa2u2g4duAmREHc3Jz" + "lHCsNgyzt5mkb6kS43B6og8Mm2SOx78dBIOA8ANzi5B6Sqk3/uN5eQFLY+sQ" + "qGxXzimyfbMjyq9DdqXThx4vlp3h/GC39KxL5MPeB0oe6P3fSP3C2ZGjsn3+" + "XcYk0Ti1cBwBOFOZ59WYuc61B0wlkiU/WGeaebABh7QuU2FuZGh5YSBQdWxs" + "YWJob3RsYSA8cHNhbmRoeWFAbXlqYXZhd29ybGQuY29tPrADA///iQEtBBAB" + "AgAXBQJAbX2jBwsJCAcDAgoCGQEFGwMAAAAACgkQx87DL9gOvoeVUwgAkQXY" + "iF0CxhKbDnuabAssnOEwJrutgCROCJRQvIwTe3fe6hQaWn2Yowt8OQtNFiR8" + "GfAY6EYxyFLKzZbAI/qtq5fHmN3eRSyNWe6d6e17hqZZL7kf2sVkyGTChHj7" + "Jiuo7vWkdqT2MJN6BW5tS9CRH7MeD839STv+4mAAO9auGvSvicP6UEQikAyC" + "y/ihoJxLQlspfbSNpi0vrUjCPT7NtWwfP0qF64i9LYkjzLqihnu+UareqOPh" + "XcWnyFKrjmg4ezQkweNU2pdvCLbcW24FhT92ivHgpLyWTswXcqjhFjVlRr0+" + "2sIz7v1k0budCsJ7PjzOoH0hJxCvsJQMlZR/e7ABZ50DqARAbX2kAQgAm5j+" + "/LO2M4pKm/VUPkYuj3eefHkzjM6nKbvRZX1Oqyf+6CJTxQskUWKAtkzzKafP" + "dS5Wg0CMqeXov+EFod4bPEYccszncKd1U8NRwacbEpCvvvB84Yl2YwdWpDpk" + "ryyyLI4PbCHkeuwx9Dc2z7t4XDB6FyAJTMAkia7nzYa/kbeUO3c2snDb/dU7" + "uyCsyKtTZyTyhTgtl/f9L03Bgh95y3mOUz0PimJ0Sg4ANczF4d04BpWkjLNV" + "Ji489ifWodPlHm1hag5drYekYpWJ+3g0uxs5AwayV9BcOkPKb1uU3EoYQw+n" + "n0Kn314Nvx2M1tKYunuVNLEm0PhA/+B8PTq8BQARAQABCXo6bD6qi3s4U8Pp" + "Uf9l3DyGuwiVPGuyb2P+sEmRFysi2AvxMe9CkF+CLCVYfZ32H3Fcr6XQ8+K8" + "ZGH6bJwijtV4QRnWDZIuhUQDS7dsbGqTh4Aw81Fm0Bz9fpufViM9RPVEysxs" + "CZRID+9jDrACthVsbq/xKomkKdBfNTK7XzGeZ/CBr9F4EPlnBWClURi9txc0" + "pz9YP5ZRy4XTFgx+jCbHgKWUIz4yNaWQqpSgkHEDrGZwstXeRaaPftcfQN+s" + "EO7OGl/Hd9XepGLez4vKSbT35CnqTwMzCK1IwUDUzyB4BYEFZ+p9TI18HQDW" + "hA0Wmf6E8pjS16m/SDXoiRY43u1jUVZFNFzz25uLFWitfRNHCLl+VfgnetZQ" + "jMFr36HGVQ65fogs3avkgvpgPwDc0z+VMj6ujTyXXgnCP/FdhzgkRFJqgmdJ" + "yOlC+wFmZJEs0MX7L/VXEXdpR27XIGYm24CC7BTFKSdlmR1qqenXHmCCg4Wp" + "00fV8+aAsnesgwPvxhCbZQVp4v4jqhVuB/rvsQu9t0rZnKdDnWeom/F3StYo" + "A025l1rrt0wRP8YS4XlslwzZBqgdhN4urnzLH0/F3X/MfjP79Efj7Zk07vOH" + "o/TPjz8lXroPTscOyXWHwtQqcMhnVsj9jvrzhZZSdUuvnT30DR7b8xcHyvAo" + "WG2cnF/pNSQX11RlyyAOlw9TOEiDJ4aLbFdkUt+qZdRKeC8mEC2xsQ87HqFR" + "pWKWABWaoUO0nxBEmvNOy97PkIeGVFNHDLlIeL++Ry03+JvuNNg4qAnwacbJ" + "TwQzWP4vJqre7Gl/9D0tVlD4Yy6Xz3qyosxdoFpeMSKHhgKVt1bk0SQP7eXA" + "C1c+eDc4gN/ZWpl+QLqdk2T9vr4wRAaK5LABh4kBIgQYAQIADAUCQG19pAUb" + "DAAAAAAKCRDHzsMv2A6+h5C6B/0QWPJb1L9a/CHU7Of3zfHvzJxnk4S5fia5" + "WBf+Ld7Y12CH+cVI/3PTXY63imIB3zLa21TNPC5cVFUJZI7hdwyJOW1R/QZa" + "vGl5sosIjORqwq8vs1oqpKWc3tRue+wt/JjCWxw8G6jQiwCzM6PltqtOAL5e" + "bJ4jZwzRmxs/RI4UYKO6EteipJA+i7OEZx0xGdL8mTl6HQx7vrJP9pM4/CtO" + "5CmjPK70e2gyoiOxx9RsSc+9H59YJCrldogCCIlNuW7cvkt8K/uYdN9GAbFG" + "RdanignRjpqSu3vTn8r/VO63+meZfKvmpI6i2b3o/UZ8Xh9lJu1vrRoNpnuP" + "Nifs+ljmsAFn"); private static readonly char[] _sec2Pass1 = "sandhya".ToCharArray(); private static readonly char[] _sec2Pass2 = "psai".ToCharArray(); private static readonly byte[] _pub3 = Base64.Decode( "mQGiBEB9BH0RBACtYQtE7tna6hgGyGLpq+ds3r2cLC0ISn5dNw7tm9vwiNVF" + "JA2N37RRrifw4PvgelRSvLaX3M3ZBqC9s1Metg3v4FSlIRtSLWCNpHSvNw7i" + "X8C2Xy9Hdlbh6Y/50o+iscojLRE14upfR1bIkcCZQGSyvGV52V2wBImUUZjV" + "s2ZngwCg7mu852vK7+euz4WaL7ERVYtq9CMEAJ5swrljerDpz/RQ4Lhp6KER" + "KyuI0PUttO57xINGshEINgYlZdGaZHRueHe7uKfI19mb0T4N3NJWaZ0wF+Cn" + "rixsq0VrTUfiwfZeGluNG73aTCeY45fVXMGTTSYXzS8T0LW100Xn/0g9HRyA" + "xUpuWo8IazxkMqHJis2uwriYKpAfA/9anvj5BS9p5pfPjp9dGM7GTMIYl5f2" + "fcP57f+AW1TVR6IZiMJAvAdeWuLtwLnJiFpGlnFz273pfl+sAuqm1yNceImR" + "2SDDP4+vtyycWy8nZhgEuhZx3W3cWMQz5WyNJSY1JJHh9TCQkCoN8E7XpVP4" + "zEPboB2GzD93mfD8JLHP+7QtVGVzdCBLZXkgKG5vIGNvbW1lbnQpIDx0ZXN0" + "QGJvdW5jeWNhc3RsZS5vcmc+iFkEExECABkFAkB9BH0ECwcDAgMVAgMDFgIB" + "Ah4BAheAAAoJEKnMV8vjZQOpSRQAnidAQswYkrXQAFcLBzhxQTknI9QMAKDR" + "ryV3l6xuCCgHST8JlxpbjcXhlLACAAPRwXPBcQEQAAEBAAAAAAAAAAAAAAAA" + "/9j/4AAQSkZJRgABAQEASABIAAD//gAXQ3JlYXRlZCB3aXRoIFRoZSBHSU1Q" + "/9sAQwAIBgYHBgUIBwcHCQkICgwUDQwLCwwZEhMPFB0aHx4dGhwcICQuJyAi" + "LCMcHCg3KSwwMTQ0NB8nOT04MjwuMzQy/9sAQwEJCQkMCwwYDQ0YMiEcITIy" + "MjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIy" + "MjIy/8AAEQgAFAAUAwEiAAIRAQMRAf/EABoAAQACAwEAAAAAAAAAAAAAAAAE" + "BQIDBgf/xAAoEAABAgUDBAEFAAAAAAAAAAABAgMABBEhMQUSQQYTIiNhFFGB" + "kcH/xAAXAQEAAwAAAAAAAAAAAAAAAAAEAgMF/8QAJBEAAQQAAwkAAAAAAAAA" + "AAAAAQACERIEIfATMTJBUZGx0fH/2gAMAwEAAhEDEQA/APMuotJlJVxstqaP" + "o22NlAUp+YsNO0qSUtBcMu6n6EtOHcfPAHHFI16++oajQtTA3DapK02HFR8U" + "pE9pTbQWtKm2WG2rlxVyQTcfGbn7Qm0OIjL77Wrs2NNm9lzTmmSxQ0PX4opS" + "prk5tmESF6syggzGwOLG6gXgHFbZhBixk8XlIDcOQLRKt+rX+3qC5ZLTQblp" + "Qlvwvxn9CMpZturVGkJHapQJphRH8hCLXbzrqpYsCx1zC5rtpJNuYQhASc0U" + "AQv/2YhcBBMRAgAcBQJAfQV+AhsDBAsHAwIDFQIDAxYCAQIeAQIXgAAKCRCp" + "zFfL42UDqfa2AJ9hjtEeDTbTEAuuSbzhYFxN/qc0FACgsmzysdbBpuN65yK0" + "1tbEaeIMtqCwAgADuM0EQH0EfhADAKpG5Y6vGbm//xZYG08RRmdi67dZjF59" + "Eqfo43mRrliangB8qkqoqqf3za2OUbXcZUQ/ajDXUvjJAoY2b5XJURqmbtKk" + "wPRIeD2+wnKABat8wmcFhZKATX1bqjdyRRGxawADBgMAoMJKJLELdnn885oJ" + "6HDmIez++ZWTlafzfUtJkQTCRKiE0NsgSvKJr/20VdK3XUA/iy0m1nQwfzv/" + "okFuIhEPgldzH7N/NyEvtN5zOv/TpAymFKewAQ26luEu6l+lH4FsiEYEGBEC" + "AAYFAkB9BH4ACgkQqcxXy+NlA6mtMgCgtQMFBaKymktM+DQmCgy2qjW7WY0A" + "n3FaE6UZE9GMDmCIAjhI+0X9aH6CsAIAAw=="); private static readonly byte[] _sec3 = Base64.Decode( "lQHhBEB9BH0RBACtYQtE7tna6hgGyGLpq+ds3r2cLC0ISn5dNw7tm9vwiNVF" + "JA2N37RRrifw4PvgelRSvLaX3M3ZBqC9s1Metg3v4FSlIRtSLWCNpHSvNw7i" + "X8C2Xy9Hdlbh6Y/50o+iscojLRE14upfR1bIkcCZQGSyvGV52V2wBImUUZjV" + "s2ZngwCg7mu852vK7+euz4WaL7ERVYtq9CMEAJ5swrljerDpz/RQ4Lhp6KER" + "KyuI0PUttO57xINGshEINgYlZdGaZHRueHe7uKfI19mb0T4N3NJWaZ0wF+Cn" + "rixsq0VrTUfiwfZeGluNG73aTCeY45fVXMGTTSYXzS8T0LW100Xn/0g9HRyA" + "xUpuWo8IazxkMqHJis2uwriYKpAfA/9anvj5BS9p5pfPjp9dGM7GTMIYl5f2" + "fcP57f+AW1TVR6IZiMJAvAdeWuLtwLnJiFpGlnFz273pfl+sAuqm1yNceImR" + "2SDDP4+vtyycWy8nZhgEuhZx3W3cWMQz5WyNJSY1JJHh9TCQkCoN8E7XpVP4" + "zEPboB2GzD93mfD8JLHP+/4DAwIvYrn+YqRaaGAu19XUj895g/GROyP8WEaU" + "Bd/JNqWc4kE/0guetGnPzq7G3bLVwiKfFd4X7BrgHAo3mrQtVGVzdCBLZXkg" + "KG5vIGNvbW1lbnQpIDx0ZXN0QGJvdW5jeWNhc3RsZS5vcmc+iFkEExECABkF" + "AkB9BH0ECwcDAgMVAgMDFgIBAh4BAheAAAoJEKnMV8vjZQOpSRQAoKZy6YS1" + "irF5/Q3JlWiwbkN6dEuLAJ9lldRLOlXsuQ5JW1+SLEc6K9ho4rACAADRwXPB" + "cQEQAAEBAAAAAAAAAAAAAAAA/9j/4AAQSkZJRgABAQEASABIAAD//gAXQ3Jl" + "YXRlZCB3aXRoIFRoZSBHSU1Q/9sAQwAIBgYHBgUIBwcHCQkICgwUDQwLCwwZ" + "EhMPFB0aHx4dGhwcICQuJyAiLCMcHCg3KSwwMTQ0NB8nOT04MjwuMzQy/9sA" + "QwEJCQkMCwwYDQ0YMiEcITIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIy" + "MjIyMjIyMjIyMjIyMjIyMjIyMjIy/8AAEQgAFAAUAwEiAAIRAQMRAf/EABoA" + "AQACAwEAAAAAAAAAAAAAAAAEBQIDBgf/xAAoEAABAgUDBAEFAAAAAAAAAAAB" + "AgMABBEhMQUSQQYTIiNhFFGBkcH/xAAXAQEAAwAAAAAAAAAAAAAAAAAEAgMF" + "/8QAJBEAAQQAAwkAAAAAAAAAAAAAAQACERIEIfATMTJBUZGx0fH/2gAMAwEA" + "AhEDEQA/APMuotJlJVxstqaPo22NlAUp+YsNO0qSUtBcMu6n6EtOHcfPAHHF" + "I16++oajQtTA3DapK02HFR8UpE9pTbQWtKm2WG2rlxVyQTcfGbn7Qm0OIjL7" + "7Wrs2NNm9lzTmmSxQ0PX4opSprk5tmESF6syggzGwOLG6gXgHFbZhBixk8Xl" + "IDcOQLRKt+rX+3qC5ZLTQblpQlvwvxn9CMpZturVGkJHapQJphRH8hCLXbzr" + "qpYsCx1zC5rtpJNuYQhASc0UAQv/2YhcBBMRAgAcBQJAfQV+AhsDBAsHAwID" + "FQIDAxYCAQIeAQIXgAAKCRCpzFfL42UDqfa2AJ9hjtEeDTbTEAuuSbzhYFxN" + "/qc0FACgsmzysdbBpuN65yK01tbEaeIMtqCwAgAAnQEUBEB9BH4QAwCqRuWO" + "rxm5v/8WWBtPEUZnYuu3WYxefRKn6ON5ka5Ymp4AfKpKqKqn982tjlG13GVE" + "P2ow11L4yQKGNm+VyVEapm7SpMD0SHg9vsJygAWrfMJnBYWSgE19W6o3ckUR" + "sWsAAwYDAKDCSiSxC3Z5/POaCehw5iHs/vmVk5Wn831LSZEEwkSohNDbIEry" + "ia/9tFXSt11AP4stJtZ0MH87/6JBbiIRD4JXcx+zfzchL7Teczr/06QMphSn" + "sAENupbhLupfpR+BbP4DAwIvYrn+YqRaaGBjvFK1fbxCt7ZM4I2W/3BC0lCX" + "m/NypKNspGflec8u96uUlA0fNCnxm6f9nbB0jpvoKi0g4iqAf+P2iEYEGBEC" + "AAYFAkB9BH4ACgkQqcxXy+NlA6mtMgCgvccZA/Sg7BXVpxli47SYhxSHoM4A" + "oNCOMplSnYTuh5ikKeBWtz36gC1psAIAAA=="); private static readonly char[] _sec3Pass1 = "123456".ToCharArray(); // // GPG comment packets. // private static readonly byte[] _sec4 = Base64.Decode( "lQG7BD0PbK8RBAC0cW4Y2MZXmAmqYp5Txyw0kSQsFvwZKHNMFRv996IsN57URVF5" + "BGMVPRBi9dNucWbjiSYpiYN13wE9IuLZsvVaQojV4XWGRDc+Rxz9ElsXnsYQ3mZU" + "7H1bNQEofstChk4z+dlvPBN4GFahrIzn/CeVUn6Ut7dVdYbiTqviANqNXwCglfVA" + "2OEePvqFnGxs1jhJyPSOnTED/RwRvsLH/k43mk6UEvOyN1RIpBXN+Ieqs7h1gFrQ" + "kB+WMgeP5ZUsotTffVDSUS9UMxRQggVUW1Xml0geGwQsNfkr/ztWMs/T4xp1v5j+" + "QyJx6OqNlkGdqOsoqkzJx0SQ1zBxdinFyyC4H95SDAb/RQOu5LQmxFG7quexztMs" + "infEA/9cVc9+qCo92yRAaXRqKNVVQIQuPxeUsGMyVeJQvJBD4An8KTMCdjpF10Cp" + "qA3t+n1S0zKr5WRUtvS6y60MOONO+EJWVWBNkx8HJDaIMNkfoqQoz3Krn7w6FE/v" + "/5uwMd6jY3N3yJZn5nDZT9Yzv9Nx3j+BrY+henRlSU0c6xDc9QAAnjJYg0Z83VJG" + "6HrBcgc4+4K6lHulCqH9JiM6RFNBX2ZhY3RvcjoAAK9hV206agp99GI6x5qE9+pU" + "vs6O+Ich/SYjOkRTQV9mYWN0b3I6AACvYAfGn2FGrpBYbjnpTuFOHJMS/T5xg/0m" + "IzpEU0FfZmFjdG9yOgAAr0dAQz6XxMwxWIn8xIZR/v2iN2L9C6O0EkZvbyBCYXIg" + "PGJhekBxdXV4PohXBBMRAgAXBQI9D2yvBQsHCgMEAxUDAgMWAgECF4AACgkQUGLI" + "YCIktfoGogCfZiXMJUKrScqozv5tMwzTTk2AaT8AniM5iRr0Du/Y08SL/NMhtF6H" + "hJ89nO4EPQ9ssRADAI6Ggxj6ZBfoavuXd/ye99osW8HsNlbqhXObu5mCMNySX2wa" + "HoWyRUEaUkI9eQw+MlHzIwzA32E7y2mU3OQBKdgLcBg4jxtcWVEg8ESKF9MpFXxl" + "pExxWrr4DFBfCRcsTwAFEQL9G3OvwJuEZXgx2JSS41D3pG4/qiHYICVa0u3p/14i" + "cq0kXajIk5ZJ6frCIAHIzuQ3n7jjzr05yR8s/qCrNbBA+nlkVNa/samk+jCzxxxa" + "cR/Dbh2wkvTFuDFFETwQYLuZAADcDck4YGQAmHivVT2NNDCf/aTz0+CJWl+xRc2l" + "Qw7D/SQjOkVMR19mYWN0b3I6AACbBnv9m5/bb/pjYAm2PtDp0CysQ9X9JCM6RUxH" + "X2ZhY3RvcjoAAJsFyHnSmaWguTFf6lJ/j39LtUNtmf0kIzpFTEdfZmFjdG9yOgAA" + "mwfwMD3LxmWtuCWBE9BptWMNH07Z/SQjOkVMR19mYWN0b3I6AACbBdhBrbSiM4UN" + "y7khDW2Sk0e4v9mIRgQYEQIABgUCPQ9ssQAKCRBQYshgIiS1+jCMAJ9txwHnb1Kl" + "6i/fSoDs8SkdM7w48wCdFvPEV0sSxE73073YhBgPZtMWbBo="); // // PGP freeware version 7 // private static readonly byte[] _pub5 = Base64.Decode( "mQENBEBrBE4BCACjXVcNIFDQSofaIyZnALb2CRg+WY9uUqgHEEAOlPe03Cs5STM5" + "HDlNmrh4TdFceJ46rxk1mQOjULES1YfHay8lCIzrD7FX4oj0r4DC14Fs1vXaSar2" + "1szIpttOw3obL4A1e0p6N4jjsoG7N/pA0fEL0lSw92SoBrMbAheXRg4qNTZvdjOR" + "grcuOuwgJRvPLtRXlhyLBoyhkd5mmrIDGv8QHJ/UjpeIcRXY9kn9oGXnEYcRbMaU" + "VwXB4pLzWqz3ZejFI3lOxRWjm760puPOnGYlzSVBxlt2LgzUgSj1Mn+lIpWmAzsa" + "xEiU4xUwEomQns72yYRZ6D3euNCibcte4SeXABEBAAG0KXBhbGFzaCBrYXNvZGhh" + "biA8cGthc29kaGFuQHRpYWEtY3JlZi5vcmc+iQEuBBABAgAYBQJAawROCAsBAwkI" + "BwIKAhkBBRsDAAAAAAoJEOfelumuiOrYqPEH+wYrdP5Tq5j+E5yN1pyCg1rwbSOt" + "Dka0y0p7Oq/VIGLk692IWPItLEunnBXQtGBcWqklrvogvlhxtf16FgoyScfLJx1e" + "1cJa+QQnVuH+VOESN6iS9Gp9lUfVOHv74mEMXw0l2Djfy/lnrkAMBatggyGnF9xF" + "VXOLk1J2WVFm9KUE23o6qdB7RGkf31pN2eA7SWmkdJSkUH7o/QSFBI+UTRZ/IY5P" + "ZIJpsdiIOqd9YMG/4RoSZuPqNRR6x7BSs8nQVR9bYs4PPlp4GfdRnOcRonoTeJCZ" + "83RnsraWJnJTg34gRLBcqumhTuFKc8nuCNK98D6zkQESdcHLLTquCOaF5L+5AQ0E" + "QGsETwEIAOVwNCTaDZvW4dowPbET1bI5UeYY8rAGLYsWSUfgaFv2srMiApyBVltf" + "i6OLcPjcUCHDBjCv4pwx/C4qcHWb8av4xQIpqQXOpO9NxYE1eZnel/QB7DtH12ZO" + "nrDNmHtaXlulcKNGe1i1utlFhgzfFx6rWkRL0ENmkTkaQmPY4gTGymJTUhBbsSRq" + "2ivWqQA1TPwBuda73UgslIAHRd/SUaxjXoLpMbGOTeqzcKGjr5XMPTs7/YgBpWPP" + "UxMlEQIiU3ia1bxpEhx05k97ceK6TSH2oCPQA7gumjxOSjKT+jEm+8jACVzymEmc" + "XRy4D5Ztqkw/Z16pvNcu1DI5m6xHwr8AEQEAAYkBIgQYAQIADAUCQGsETwUbDAAA" + "AAAKCRDn3pbprojq2EynB/4/cEOtKbI5UisUd3vkTzvWOcqWUqGqi5wjjioNtIM5" + "pur2nFvhQE7SZ+PbAa87HRJU/4WcWMcoLkHD48JrQwHCHOLHSV5muYowb78X4Yh9" + "epYtSJ0uUahcn4Gp48p4BkhgsPYXkxEImSYzAOWStv21/7WEMqItMYl89BV6Upm8" + "HyTJx5MPTDbMR7X51hRg3OeQs6po3WTCWRzFIMyGm1rd/VK1L5ZDFPqO3S6YUJ0z" + "cxecYruvfK0Wp7q834wE8Zkl/PQ3NhfEPL1ZiLr/L00Ty+77/FZqt8SHRCICzOfP" + "OawcVGI+xHVXW6lijMpB5VaVIH8i2KdBMHXHtduIkPr9"); // // Werner Koch "odd keys" // private static readonly byte[] _pub6 = Base64.Decode( "mQGiBDWiHh4RBAD+l0rg5p9rW4M3sKvmeyzhs2mDxhRKDTVVUnTwpMIR2kIA9pT4" + "3No/coPajDvhZTaDM/vSz25IZDZWJ7gEu86RpoEdtr/eK8GuDcgsWvFs5+YpCDwW" + "G2dx39ME7DN+SRvEE1xUm4E9G2Nnd2UNtLgg82wgi/ZK4Ih9CYDyo0a9awCgisn3" + "RvZ/MREJmQq1+SjJgDx+c2sEAOEnxGYisqIKcOTdPOTTie7o7x+nem2uac7uOW68" + "N+wRWxhGPIxsOdueMIa7U94Wg/Ydn4f2WngJpBvKNaHYmW8j1Q5zvZXXpIWRXSvy" + "TR641BceGHNdYiR/PiDBJsGQ3ac7n7pwhV4qex3IViRDJWz5Dzr88x+Oju63KtxY" + "urUIBACi7d1rUlHr4ok7iBRlWHYXU2hpUIQ8C+UOE1XXT+HB7mZLSRONQnWMyXnq" + "bAAW+EUUX2xpb54CevAg4eOilt0es8GZMmU6c0wdUsnMWWqOKHBFFlDIvyI27aZ9" + "quf0yvby63kFCanQKc0QnqGXQKzuXbFqBYW2UQrYgjXji8rd8bQnV2VybmVyIEtv" + "Y2ggKGdudXBnIHNpZykgPGRkOWpuQGdudS5vcmc+iGUEExECAB0FAjZVoKYFCQht" + "DIgDCwQDBRUDAgYBAxYCAQIXgAASCRBot6uJV1SNzQdlR1BHAAEBLj4AoId15gcy" + "YpBX2YLtEQTlXPp3mtEGAJ9UxzJE/t3EHCHK2bAIOkBwIW8ItIkBXwMFEDWiHkMD" + "bxG4/z6qCxADYzIFHR6I9Si9gzPQNRcFs2znrTp5pV5Mk6f1aqRgZxL3E4qUZ3xe" + "PQhwAo3fSy3kCwLmFGqvzautSMHn8K5V1u+T5CSHqLFYKqj5FGtuB/xwoKDXH6UO" + "P0+l5IP8H1RTjme3Fhqahec+zPG3NT57vc2Ru2t6PmuAwry2BMuSFMBs7wzXkyC3" + "DbI54MV+IKPjHMORivK8uI8jmna9hdNVyBifCk1GcxkHBSCFvU8xJePsA/Q//zCe" + "lvrnrIiMfY4CQTmKzke9MSzbAZQIRddgrGAsiX1tE8Z3YMd8lDpuujHLVEdWZo6s" + "54OJuynHrtFFObdapu0uIrT+dEXSASMUbEuNCLL3aCnrEtGJCwxB2TPQvCCvR2BK" + "zol6MGWxA+nmddeQib2r+GXoKXLdnHcpsAjA7lkXk3IFyJ7MLFK6uDrjGbGJs2FK" + "SduUjS/Ib4hGBBARAgAGBQI1oic8AAoJEGx+4bhiHMATftYAn1fOaKDUOt+dS38r" + "B+CJ2Q+iElWJAKDRPpp8q5GylbM8DPlMpClWN3TYqYhGBBARAgAGBQI27U5sAAoJ" + "EF3iSZZbA1iiarYAn35qU3ZOlVECELE/3V6q98Q30eAaAKCtO+lacH0Qq1E6v4BP" + "/9y6MoLIhohiBBMRAgAiAhsDBAsHAwIDFQIDAxYCAQIeAQIXgAUCP+mCaQUJDDMj" + "ywAKCRBot6uJV1SNzaLvAJwLsPV1yfc2D+yT+2W11H/ftNMDvwCbBweORhCb/O/E" + "Okg2UTXJBR4ekoCIXQQTEQIAHQMLBAMFFQMCBgEDFgIBAheABQI/6YJzBQkMMyPL" + "AAoJEGi3q4lXVI3NgroAn2Z+4KgVo2nzW72TgCJwkAP0cOc2AJ0ZMilsOWmxmEG6" + "B4sHMLkB4ir4GIhdBBMRAgAdAwsEAwUVAwIGAQMWAgECF4AFAj/pgnMFCQwzI8sA" + "CgkQaLeriVdUjc2CugCfRrOIfllp3mSmGpHgIxvg5V8vtMcAn0BvKVehOn+12Yvn" + "9BCHfg34jUZbiF0EExECAB0DCwQDBRUDAgYBAxYCAQIXgAUCP+mCcwUJDDMjywAK" + "CRBot6uJV1SNzYK6AJ9x7R+daNIjkieNW6lJeVUIoj1UHgCeLZm025uULML/5DFs" + "4tUvXs8n9XiZAaIENaIg8xEEALYPe0XNsPjx+inTQ+Izz527ZJnoc6BhWik/4a2b" + "ZYENSOQXAMKTDQMv2lLeI0i6ceB967MNubhHeVdNeOWYHFSM1UGRfhmZERISho3b" + "p+wVZvVG8GBVwpw34PJjgYU/0tDwnJaJ8BzX6j0ecTSTjQPnaUEtdJ/u/gmG9j02" + "18TzAKDihdNoKJEU9IKUiSjdGomSuem/VwQArHfaucSiDmY8+zyZbVLLnK6UJMqt" + "sIv1LvAg20xwXoUk2bY8H3tXL4UZ8YcoSXYozwALq3cIo5UZJ0q9Of71mI8WLK2i" + "FSYVplpTX0WMClAdkGt3HgVb7xtOhGt1mEKeRQjNZ2LteUQrRDD9MTQ+XxcvEN0I" + "pAj4kBJe9bR6HzAD/iecCmGwSlHUZZrgqWzv78o79XxDdcuLdl4i2fL7kwEOf9js" + "De7hGs27yrdJEmAG9QF9TOF9LJFmE1CqkgW+EpKxsY01Wjm0BFJB1R7iPUaUtFRZ" + "xYqfgXarmPjql2iBi+cVjLzGu+4BSojVAPgP/hhcnIowf4M4edPiICMP1GVjtCFX" + "ZXJuZXIgS29jaCA8d2VybmVyLmtvY2hAZ3V1Zy5kZT6IYwQTEQIAGwUCNs8JNwUJ" + "CCCxRAMLCgMDFQMCAxYCAQIXgAASCRBsfuG4YhzAEwdlR1BHAAEBaSAAn3YkpT5h" + "xgehGFfnX7izd+c8jI0SAJ9qJZ6jJvXnGB07p60aIPYxgJbLmYkAdQMFEDWjdxQd" + "GfTBDJhXpQEBPfMC/0cxo+4xYVAplFO0nIYyjQgP7D8O0ufzPsIwF3kvb7b5FNNj" + "fp+DAhN6G0HOIgkL3GsWtCfH5UHali+mtNFIKDpTtr+F/lPpZP3OPzzsLZS4hYTq" + "mMs1O/ACq8axKgAilYkBXwMFEDWiJw4DbxG4/z6qCxADB9wFH0i6mmn6rWYKFepJ" + "hXyhE4wWqRPJAnvfoiWUntDp4aIQys6lORigVXIWo4k4SK/FH59YnzF7578qrTZW" + "/RcA0bIqJqzqaqsOdTYEFa49cCjvLnBW4OebJlLTUs/nnmU0FWKW8OwwL+pCu8d7" + "fLSSnggBsrUQwbepuw0cJoctFPAz5T1nQJieQKVsHaCNwL2du0XefOgF5ujB1jK1" + "q3p4UysF9hEcBR9ltE3THr+iv4jtZXmC1P4at9W5LFWsYuwr0U3yJcaKSKp0v/wG" + "EWe2J/gFQZ0hB1+35RrCZPgiWsEv87CHaG6XtQ+3HhirBCJsYhmOikVKoEan6PhU" + "VR1qlXEytpAt389TBnvyceAX8hcHOE3diuGvILEgYes3gw3s5ZmM7bUX3jm2BrX8" + "WchexUFUQIuKW2cL379MFXR8TbxpVxrsRYE/4jHZBYhGBBARAgAGBQI27U4LAAoJ" + "EF3iSZZbA1iifJoAoLEsGy16hV/CfmDku6D1CBUIxXvpAJ9GBApdC/3OXig7sBrV" + "CWOb3MQzcLkBjQQ2zwcIEAYA9zWEKm5eZpMMBRsipL0IUeSKEyeKUjABX4vYNurl" + "44+2h6Y8rHn7rG1l/PNj39UJXBkLFj1jk8Q32v+3BQDjvwv8U5e/kTgGlf7hH3WS" + "W38RkZw18OXYCvnoWkYneIuDj6/HH2bVNXmTac05RkBUPUv4yhqlaFpkVcswKGuE" + "NRxujv/UWvVF+/2P8uSQgkmGp/cbwfMTkC8JBVLLBRrJhl1uap2JjZuSVklUUBez" + "Vf3NJMagVzx47HPqLVl4yr4bAAMGBf9PujlH5I5OUnvZpz+DXbV/WQVfV1tGRCra" + "kIj3mpN6GnUDF1LAbe6vayUUJ+LxkM1SqQVcmuy/maHXJ+qrvNLlPqUZPmU5cINl" + "sA7bCo1ljVUp54J1y8PZUx6HxfEl/LzLVkr+ITWnyqeiRikDecUf4kix2teTlx6I" + "3ecqT5oNqZSRXWwnN4SbkXtAd7rSgEptUYhQXgSEarp1pXJ4J4rgqFa49jKISDJq" + "rn/ElltHe5Fx1bpfkCIYlYk45Cga9bOIVAQYEQIADAUCNs8HCAUJBvPJAAASCRBs" + "fuG4YhzAEwdlR1BHAAEBeRUAoIGpCDmMy195TatlloHAJEjZu5KaAJwOvW989hOb" + "8cg924YIFVA1+4/Ia7kBjQQ1oiE8FAYAkQmAlOXixb8wra83rE1i7LCENLzlvBZW" + "KBXN4ONelZAnnkOm7IqRjMhtKRJN75zqVyKUaUwDKjpf9J5K2t75mSxBtnbNRqL3" + "XodjHK93OcAUkz3ci7iuC/b24JI2q4XeQG/v4YR1VodM0zEQ1IC0JCq4Pl39QZyX" + "JdZCrUFvMcXq5ruNSldztBqTFFUiFbkw1Fug/ZyXJve2FVcbsRXFrB7EEuy+iiU/" + "kZ/NViKk0L4T6KRHVsEiriNlCiibW19fAAMFBf9Tbv67KFMDrLqQan/0oSSodjDQ" + "KDGqtoh7KQYIKPXqfqT8ced9yd5MLFwPKf3t7AWG1ucW2x118ANYkPSU122UTndP" + "sax0cY4XkaHxaNwpNFCotGQ0URShxKNpcqbdfvy+1d8ppEavgOyxnV1JOkLjZJLw" + "K8bgxFdbPWcsJJnjuuH3Pwz87CzTgOSYQxMPnIwQcx5buZIV5NeELJtcbbd3RVua" + "K/GQht8QJpuXSji8Nl1FihYDjACR8TaRlAh50GmIRgQoEQIABgUCOCv7gwAKCRBs" + "fuG4YhzAE9hTAJ9cRHu+7q2hkxpFfnok4mRisofCTgCgzoPjNIuYiiV6+wLB5o11" + "7MNWPZCIVAQYEQIADAUCNaIhPAUJB4TOAAASCRBsfuG4YhzAEwdlR1BHAAEBDfUA" + "oLstR8cg5QtHwSQ3nFCOKEREUFIwAKDID3K3hM+b6jW1o+tNX9dnjb+YMZkAbQIw" + "bYOUAAABAwC7ltmO5vdKssohwzXEZeYvDW2ll3CYD2I+ruiNq0ybxkfFBopq9cxt" + "a0OvVML4LK/TH+60f/Fqx9wg2yk9APXyaomdLrXfWyfZ91YtNCfj3ElC4XB4qqm0" + "HRn0wQyYV6UABRG0IVdlcm5lciBLb2NoIDx3ZXJuZXIua29jaEBndXVnLmRlPokA" + "lQMFEDRfoOmOB31Gi6BmjQEBzwgD/2fHcdDXuRRY+SHvIVESweijstB+2/sVRp+F" + "CDjR74Kg576sJHfTJCxtSSmzpaVpelb5z4URGJ/Byi5L9AU7hC75S1ZnJ+MjBT6V" + "ePyk/r0uBrMkU/lMG7lk/y2By3Hll+edjzJsdwn6aoNPiyen4Ch4UGTEguxYsLq0" + "HES/UvojiQEVAwUTNECE2gnp+QqKck5FAQH+1Af/QMlYPlLG+5E19qP6AilKQUzN" + "kd1TWMenXTS66hGIVwkLVQDi6RCimhnLMq/F7ENA8bSbyyMuncaBz5dH4kjfiDp1" + "o64LULcTmN1LW9ctpTAIeLLJZnwxoJLkUbLUYKADKqIBXHMt2B0zRmhFOqEjRN+P" + "hI7XCcHeHWHiDeUB58QKMyeoJ/QG/7zLwnNgDN2PVqq2E72C3ye5FOkYLcHfWKyB" + "Rrn6BdUphAB0LxZujSGk8ohZFbia+zxpWdE8xSBhZbjVGlwLurmS2UTjjxByBNih" + "eUD6IC3u5P6psld0OfqnpriZofP0CBP2oTk65r529f/1lsy2kfWrVPYIFJXEnIkA" + "lQMFEDQyneGkWMS9SnJfMQEBMBMD/1ADuhhuY9kyN7Oj6DPrDt5SpPQDGS0Jtw3y" + "uIPoed+xyzlrEuL2HeaOj1O9urpn8XLN7V21ajkzlqsxnGkOuifbE9UT67o2b2vC" + "ldCcY4nV5n+U1snMDwNv+RkcEgNa8ANiWkm03UItd7/FpHDQP0FIgbPEPwRoBN87" + "I4gaebfRiQCVAwUQNDUSwxRNm5Suj3z1AQGMTAP/UaXXMhPzcjjLxBW0AccTdHUt" + "Li+K+rS5PNxxef2nnasEhCdK4GkM9nwJgsP0EZxCG3ZSAIlWIgQ3MK3ZAV1Au5pL" + "KolRjFyEZF420wAtiE7V+4lw3FCqNoXDJEFC3BW431kx1wAhDk9VaIHHadYcof4d" + "dmMLQOW2cJ7LDEEBW/WJAJUDBRA0M/VQImbGhU33abUBARcoA/9eerDBZGPCuGyE" + "mQBcr24KPJHWv/EZIKl5DM/Ynz1YZZbzLcvEFww34mvY0jCfoVcCKIeFFBMKiSKr" + "OMtoVC6cQMKpmhE9hYRStw4E0bcf0BD/stepdVtpwRnG8SDP2ZbmtgyjYT/7T4Yt" + "6/0f6N/0NC7E9qfq4ZlpU3uCGGu/44kAlQMFEDQz8kp2sPVxuCQEdQEBc5YD/Rix" + "vFcLTO1HznbblrO0WMzQc+R4qQ50CmCpWcFMwvVeQHo/bxoxGggNMmuVT0bqf7Mo" + "lZDSJNS96IAN32uf25tYHgERnQaMhmi1aSHvRDh4jxFu8gGVgL6lWit/vBDW/BiF" + "BCH6sZJJrGSuSdpecTtaWC8OJGDoKTO9PqAA/HQRiQB1AwUQNDJSx011eFs7VOAZ" + "AQGdKQL/ea3qD2OP3wVTzXvfjQL1CosX4wyKusBBhdt9u2vOT+KWkiRk1o35nIOG" + "uZLHtSFQDY8CVDOkqg6g4sVbOcTl8QUwHA+A4AVDInwTm1m4Bk4oeCIwk4Bp6mDd" + "W11g28k/iQEVAgUSNDIWPm/Y4wPDeaMxAQGvBQgAqGhzA/21K7oL/L5S5Xz//eO7" + "J8hgvqqGXWd13drNy3bHbKPn7TxilkA3ca24st+6YPZDdSUHLMCqg16YOMyQF8gE" + "kX7ZHWPacVoUpCmSz1uQ3p6W3+u5UCkRpgQN8wBbJx5ZpBBqeq5q/31okaoNjzA2" + "ghEWyR5Ll+U0C87MY7pc7PlNHGCr0ZNOhhtf1jU+H9ag5UyT6exIYim3QqWYruiC" + "LSUcim0l3wK7LMW1w/7Q6cWfAFQvl3rGjt3rg6OWg9J4H2h5ukf5JNiRybkupmat" + "UM+OVMRkf93jzU62kbyZpJBHiQZuxxJaLkhpv2RgWib9pbkftwEy/ZnmjkxlIIkA" + "lQMFEDQvWjh4313xYR8/NQEB37QEAIi9vR9h9ennz8Vi7RNU413h1ZoZjxfEbOpk" + "QAjE/LrZ/L5WiWdoStSiyqCLPoyPpQafiU8nTOr1KmY4RgceJNgxIW4OiSMoSvrh" + "c2kqP+skb8A2B4+47Aqjr5fSAVfVfrDMqDGireOguhQ/hf9BOYsM0gs+ROdtyLWP" + "tMjRnFlviD8DBRAz8qQSj6lRT5YOKXIRAntSAJ9StSEMBoFvk8iRWpXb6+LDNLUW" + "zACfT8iY3IxwvMF6jjCHrbuxQkL7chSJARUDBRA0MMO7569NIyeqD3EBATIAB/4t" + "CPZ1sLWO07g2ZCpiP1HlYpf5PENaXtaasFvhWch7eUe3DksuMEPzB5GnauoQZAku" + "hEGkoEfrfL3AXtXH+WMm2t7dIcTBD4p3XkeZ+PgJpKiASXDyul9rumXXvMxSL4KV" + "7ar+F1ZJ0ycCx2r2au0prPao70hDAzLTy16hrWgvdHSK7+wwaYO5TPCL5JDmcB+d" + "HKW72qNUOD0pxbe0uCkkb+gDxeVX28pZEkIIOMMV/eAs5bs/smV+eJqWT/EyfVBD" + "o7heF2aeyJj5ecxNOODr88xKF7qEpqazCQ4xhvFY+Yn6+vNCcYfkoZbOn0XQAvqf" + "a2Vab9woVIVSaDji/mlPiQB1AwUQNDC233FfeD4HYGBJAQFh6QL/XCgm5O3q9kWp" + "gts1MHKoHoh7vxSSQGSP2k7flNP1UB2nv4sKvyGM8eJKApuROIodcTkccM4qXaBu" + "XunMr5kJlvDJPm+NLzKyhtQP2fWI7xGYwiCiB29gm1GFMjdur4amiQEVAwUQNDBR" + "9fjDdqGixRdJAQE+mAf+JyqJZEVFwNwZ2hSIMewekC1r7N97p924nqfZKnzn6weF" + "pE80KIJSWtEVzI0XvHlVCOnS+WRxn7zxwrOTbrcEOy0goVbNgUsP5ypZa2/EM546" + "uyyJTvgD0nwA45Q4bP5sGhjh0G63r9Vwov7itFe4RDBGM8ibGnZTr9hHo469jpom" + "HSNeavcaUYyEqcr4GbpQmdpJTnn/H0A+fMl7ZHRoaclNx9ZksxihuCRrkQvUOb3u" + "RD9lFIhCvNwEardN62dKOKJXmn1TOtyanZvnmWigU5AmGuk6FpsClm3p5vvlid64" + "i49fZt9vW5krs2XfUevR4oL0IyUl+qW2HN0DIlDiAYkAlQMFEDQvbv2wcgJwUPMh" + "JQEBVBID/iOtS8CQfMxtG0EmrfaeVUU8R/pegBmVWDBULAp8CLTtdfxjVzs/6DXw" + "0RogXMRRl2aFfu1Yp0xhBYjII6Kque/FzAFXY9VNF1peqnPt7ADdeptYMppZa8sG" + "n9BBRu9Fsw69z6JkyqvMiVxGcKy3XEpVGr0JHx8Xt6BYdrULiKr2iQB1AwUQNC68" + "n6jZR/ntlUftAQFaYgL+NUYEj/sX9M5xq1ORX0SsVPMpNamHO3JBSmZSIzjiox5M" + "AqoFOCigAkonuzk5aBy/bRHy1cmDBOxf4mNhzrH8N6IkGvPE70cimDnbFvr+hoZS" + "jIqxtELNZsLuLVavLPAXiQCVAwUQNC6vWocCuHlnLQXBAQHb1gQAugp62aVzDCuz" + "4ntfXsmlGbLY7o5oZXYIKdPP4riOj4imcJh6cSgYFL6OMzeIp9VW/PHo2mk8kkdk" + "z5uif5LqOkEuIxgra7p1Yq/LL4YVhWGQeD8hwpmu+ulYoPOw40dVYS36PwrHIH9a" + "fNhl8Or5O2VIHIWnoQ++9r6gwngFQOyJAJUDBRAzHnkh1sNKtX1rroUBAWphBACd" + "huqm7GHoiXptQ/Y5F6BivCjxr9ch+gPSjaLMhq0kBHVO+TbXyVefVVGVgCYvFPjo" + "zM8PEVykQAtY//eJ475aGXjF+BOAhl2z0IMkQKCJMExoEDHbcj0jIIMZ2/+ptgtb" + "FSyJ2DQ3vvCdbw/1kyPHTPfP+L2u40GWMIYVBbyouokAlQMFEDMe7+UZsymln7HG" + "2QEBzMED/3L0DyPK/u6PyAd1AdpjUODTkWTZjZ6XA2ubc6IXXsZWpmCgB/24v8js" + "J3DIsvUD3Ke55kTr6xV+au+mAkwOQqWUTUWfQCkSrSDlbUJ1VPBzhyTpuzjBopte" + "7o3R6XXfcLiC5jY6eCX0QtLGhKpLjTr5uRhf1fYODGsAGXmCByDviQB1AgUQMy6U" + "MB0Z9MEMmFelAQHV4AMAjdFUIyFtpTr5jkyZSd3y//0JGO0z9U9hLVxeBBCwvdEQ" + "xsrpeTtVdqpeKZxHN1GhPCYvgLFZAQlcPh/Gc8u9uO7wVSgJc3zYKFThKpQevdF/" + "rzjTCHfgigf5Iui0qiqBiQCVAwUQMx22bAtzgG/ED06dAQFi0gQAkosqTMWy+1eU" + "Xbi2azFK3RX5ERf9wlN7mqh7TvwcPXvVWzUARnwRv+4kk3uOWI18q5UPis7KH3KY" + "OVeRrPd8bbp6SjhBh82ourTEQUXLBDQiI1V1cZZmwwEdlnAnhFnkXgMBNM2q7oBe" + "fRHADfYDfGo90wXyrVVL+GihDNpzUwOJAJUDBRAzHUFnOWvfULwOR3EBAbOYA/90" + "JIrKmxhwP6quaheFOjjPoxDGEZpGJEOwejEByYj+AgONCRmQS3BydtubA+nm/32D" + "FeG8pe/dnFvGc+QgNW560hK21C2KJj72mhjRlg/na7jz4/MmBAv5k61Q7roWi0rw" + "x+R9NSHxpshC8A92zmvo8w/XzVSogC8pJ04jcnY6YokAlQMFEDMdPtta9LwlvuSC" + "3QEBvPMD/3TJGroHhHYjHhiEpDZZVszeRQ0cvVI/uLLi5yq3W4F6Jy47DF8VckA7" + "mw0bXrOMNACN7Je7uyaU85qvJC2wgoQpFGdFlkjmkAwDAjR+koEysiE8FomiOHhv" + "EpEY/SjSS4jj4IPmgV8Vq66XjPw+i7Z0RsPLOIf67yZHxypNiBiYiQCVAwUQMxxw" + "pKrq6G7/78D5AQHo2QQAjnp6KxOl6Vvv5rLQ/4rj3OemvF7IUUq34xb25i/BSvGB" + "UpDQVUmhv/qIfWvDqWGZedyM+AlNSfUWPWnP41S8OH+lcERH2g2dGKGl7kH1F2Bx" + "ByZlqREHm2q624wPPA35RLXtXIx06yYjLtJ7b+FCAX6PUgZktZYk5gwjdoAGrC2J" + "AJUDBRAzGvcCKC6c7f53PGUBAUozA/9l/qKmcqbi8RtLsKQSh3vHds9d22zcbkuJ" + "PBSoOv2D7i2VLshaQFjq+62uYZGE6nU1WP5sZcBDuWjoX4t4NrffnOG/1R9D0t1t" + "9F47D77HJzjvo+J52SN520YHcbT8VoHdPRoEOXPN4tzhvn2GapVVdaAlWM0MLloh" + "NH3I9jap9okAdQMFEDMZlUAnyXglSykrxQEBnuwC/jXbFL+jzs2HQCuo4gyVrPlU" + "ksQCLYZjNnZtw1ca697GV3NhBhSXR9WHLQH+ZWnpTzg2iL3WYSdi9tbPs78iY1FS" + "d4EG8H9V700oQG8dlICF5W2VjzR7fByNosKM70WSXYkBFQMFEDMWBsGCy1t9eckW" + "HQEBHzMH/jmrsHwSPrA5R055VCTuDzdS0AJ+tuWkqIyqQQpqbost89Hxper3MmjL" + "Jas/VJv8EheuU3vQ9a8sG2SnlWKLtzFqpk7TCkyq/H3blub0agREbNnYhHHTGQFC" + "YJb4lWjWvMjfP+N5jvlLcnDqQPloXfAOgy7W90POoqFrsvhxdpnXgoLrzyNNja1O" + "1NRj+Cdv/GmJYNi6sQe43zmXWeA7syLKMw6058joDqEJFKndgSp3Zy/yXmObOZ/H" + "C2OJwA3gzEaAu8Pqd1svwGIGznqtTNCn9k1+rMvJPaxglg7PXIJS282hmBl9AcJl" + "wmh2GUCswl9/sj+REWTb8SgJUbkFcp6JAJUDBRAwdboVMPfsgxioXMEBAQ/LA/9B" + "FTZ9T95P/TtsxeC7lm9imk2mpNQCBEvXk286FQnGFtDodGfBfcH5SeKHaUNxFaXr" + "39rDGUtoTE98iAX3qgCElf4V2rzgoHLpuQzCg3U35dfs1rIxlpcSDk5ivaHpPV3S" + "v+mlqWL049y+3bGaZeAnwM6kvGMP2uccS9U6cbhpw4hGBBARAgAGBQI3GtRfAAoJ" + "EF3iSZZbA1iikWUAoIpSuXzuN/CI63dZtT7RL7c/KtWUAJ929SAtTr9SlpSgxMC8" + "Vk1T1i5/SYkBFQMFEzccnFnSJilEzmrGwQEBJxwH/2oauG+JlUC3zBUsoWhRQwqo" + "7DdqaPl7sH5oCGDKS4x4CRA23U15NicDI7ox6EizkwCjk0dRr1EeRK+RqL1b/2T4" + "2B6nynOLhRG2A0BPHRRJLcoL4nKfoPSo/6dIC+3iVliGEl90KZZD5bnONrVJQkRj" + "ZL8Ao+9IpmoYh8XjS5xMLEF9oAQqAkA93nVBm56lKmaL1kl+M3dJFtNKtVB8de1Z" + "XifDs8HykD42qYVtcseCKxZXhC3UTG5YLNhPvgZKH8WBCr3zcR13hFDxuecUmu0M" + "VhvEzoKyBYYt0rrqnyWrxwbv4gSTUWH5ZbgsTjc1SYKZxz6hrPQnfYWzNkznlFWJ" + "ARUDBRM0xL43CdxwOTnzf10BATOCB/0Q6WrpzwPMofjHj54MiGLKVP++Yfwzdvns" + "HxVpTZLZ5Ux8ErDsnLmvUGphnLVELZwEkEGRjln7a19h9oL8UYZaV+IcR6tQ06Fb" + "1ldR+q+3nXtBYzGhleXdgJQSKLJkzPF72tvY0DHUB//GUV9IBLQMvfG8If/AFsih" + "4iXi96DOtUAbeuIhnMlWwLJFeGjLLsX1u6HSX33xy4bGX6v/UcHbTSSYaxzb92GR" + "/xpP2Xt332hOFRkDZL52g27HS0UrEJWdAVZbh25KbZEl7C6zX/82OZ5nTEziHo20" + "eOS6Nrt2+gLSeA9X5h/+qUx30kTPz2LUPBQyIqLCJkHM8+0q5j9ciQCiAwUTNMS+" + "HZFeTizbCJMJAQFrGgRlEAkG1FYU4ufTxsaxhFZy7xv18527Yxpls6mSCi1HL55n" + "Joce6TI+Z34MrLOaiZljeQP3EUgzA+cs1sFRago4qz2wS8McmQ9w0FNQQMz4vVg9" + "CVi1JUVd4EWYvJpA8swDd5b9+AodYFEsfxt9Z3aP+AcWFb10RlVVsNw9EhObc6IM" + "nwAOHCEI9vp5FzzFiQCVAwUQNxyr6UyjTSyISdw9AQHf+wP+K+q6hIQ09tkgaYaD" + "LlWKLbuxePXqM4oO72qi70Gkg0PV5nU4l368R6W5xgR8ZkxlQlg85sJ0bL6wW/Sj" + "Mz7pP9hkhNwk0x3IFkGMTYG8i6Gt8Nm7x70dzJoiC+A496PryYC0rvGVf+Om8j5u" + "TexBBjb/jpJhAQ/SGqeDeCHheOC0Lldlcm5lciBLb2NoIChtZWluIGFsdGVyIGtl" + "eSkgPHdrQGNvbXB1dGVyLm9yZz6JAHUDBRM2G2MyHRn0wQyYV6UBASKKAv4wzmK7" + "a9Z+g0KH+6W8ffIhzrQo8wDAU9X1WJKzJjS205tx4mmdnAt58yReBc/+5HXTI8IK" + "R8IgF+LVXKWAGv5P5AqGhnPMeQSCs1JYdf9MPvbe34jD8wA1LTWFXn9e/cWIRgQQ" + "EQIABgUCNxrUaQAKCRBd4kmWWwNYovRiAJ9dJBVfjx9lGARoFXmAieYrMGDrmwCZ" + "AQyO4Wo0ntQ+iq4do9M3/FTFjiCZAaIENu1I6REEAJRGEqcYgXJch5frUYBj2EkD" + "kWAbhRqVXnmiF3PjCEGAPMMYsTddiU7wcKfiCAqKWWXow7BjTJl6Do8RT1jdKpPO" + "lBJXqqPYzsyBxLzE6mLps0K7SLJlSKTQqSVRcx0jx78JWYGlAlP0Kh9sPV2w/rPh" + "0LrPeOKXT7lZt/DrIhfPAKDL/sVqCrmY3QfvrT8kSKJcgtLWfQP/cfbqVNrGjW8a" + "m631N3UVA3tWfpgM/T9OjmKmw44NE5XfPJTAXlCV5j7zNMUkDeoPkrFF8DvbpYQs" + "4XWYHozDjhR2Q+eI6gZ0wfmhLHqqc2eVVkEG7dT57Wp9DAtCMe7RZfhnarTQMqlY" + "tOEa/suiHk0qLo59NsyF8eh68IDNCeYD/Apzonwaq2EQ1OEpfFlp6LcSnS34+UGZ" + "tTO4BgJdmEjr/QrIPp6bJDstgho+/2oR8yQwuHGJwbS/8ADA4IFEpLduSpzrABho" + "7RuNQcm96bceRY+7Hza3zf7pg/JGdWOb+bC3S4TIpK+3sx3YNWs7eURwpGREeJi5" + "/Seic+GXlGzltBpXZXJuZXIgS29jaCA8d2tAZ251cGcub3JnPohjBBMRAgAbBQI3" + "Gs+QBQkMyXyAAwsKAwMVAwIDFgIBAheAABIJEF3iSZZbA1iiB2VHUEcAAQFdwgCe" + "O/s43kCLDMIsHCb2H3LC59clC5UAn1EyrqWk+qcOXLpQIrP6Qa3QSmXIiEYEEBEC" + "AAYFAjca0T0ACgkQbH7huGIcwBOF9ACeNwO8G2G0ei03z0g/n3QZIpjbzvEAnRaE" + "qX2PuBbClWoIP6h9yrRlAEbUiQB1AwUQNxrRYx0Z9MEMmFelAQHRrgL/QDNKPV5J" + "gWziyzbHvEKfTIw/Ewv6El2MadVvQI8kbPN4qkPr2mZWwPzuc9rneCPQ1eL8AOdC" + "8+ZyxWzx2vsrk/FcU5donMObva2ct4kqJN6xl8xjsxDTJhBSFRaiBJjxiEYEEBEC" + "AAYFAjca0aMACgkQaLeriVdUjc0t+ACghK37H2vTYeXXieNJ8aZkiPJSte4An0WH" + "FOotQdTW4NmZJK+Uqk5wbWlgiEYEEBECAAYFAjdPH10ACgkQ9u7fIBhLxNktvgCe" + "LnQ5eOxAJz+Cvkb7FnL/Ko6qc5YAnjhWWW5c1o3onvKEH2Je2wQa8T6iiEYEEBEC" + "AAYFAjenJv4ACgkQmDRl2yFDlCJ+yQCfSy1zLftEfLuIHZsUHis9U0MlqLMAn2EI" + "f7TI1M5OKysQcuFLRC58CfcfiEUEEBECAAYFAjfhQTMACgkQNmdg8X0u14h55wCf" + "d5OZCV3L8Ahi4QW/JoXUU+ZB0M0AmPe2uw7WYDLOzv48H76tm6cy956IRgQQEQIA" + "BgUCOCpiDwAKCRDj8lhUEo8OeRsdAJ9FHupRibBPG2t/4XDqF+xiMLL/8ACfV5F2" + "SR0ITE4k/C+scS1nJ1KZUDW0C1dlcm5lciBLb2NoiGMEExECABsFAjbtSOoFCQzJ" + "fIADCwoDAxUDAgMWAgECF4AAEgkQXeJJllsDWKIHZUdQRwABAbXWAJ9SCW0ieOpL" + "7AY6vF+OIaMmw2ZW1gCgkto0eWfgpjAuVg6jXqR1wHt2pQOJAh4EEBQDAAYFAjcv" + "WdQACgkQbEwxpbHVFWcNxQf/bg14WGJ0GWMNSuuOOR0WYzUaNtzYpiLSVyLrreXt" + "o8LBNwzbgzj2ramW7Ri+tYJAHLhtua8ZgSeibmgBuZasF8db1m5NN1ZcHBXGTysA" + "jp+KnicTZ9Orj75D9o3oSmMyRcisEhr+gkj0tVhGfOAOC6eKbufVuyYFDVIyOyUB" + "GlW7ApemzAzYemfs3DdjHn87lkjHMVESO4fM5rtLuSc7cBfL/e6ljaWQc5W8S0gI" + "Dv0VtL39pMW4BlpKa25r14oJywuUpvWCZusvDm7ZJnqZ/WmgOHQUsyYudTROpGIb" + "lsNg8iqC6huWpGSBRdu3oRQRhkqpfVdszz6BB/nAx01q2wf/Q+U9XId1jyzxUL1S" + "GgaYMf6QdyjHQ1oxuFLNxzM6C/M069twbNgXJ71RsDDXVxFZfSTjSiH100AP9+9h" + "b5mycaXLUOXYDvOSFzHBd/LsjFNVrrFbDs5Xw+cLGVHOIgR5IWAfgu5d1PAZU9uQ" + "VgdGnQfmZg383RSPxvR3fnZz1rHNUGmS6w7x6FVbxa1QU2t38gNacIwHATAPcBpy" + "JLfXoznbpg3ADbgCGyDjBwnuPQEQkYwRakbczRrge8IaPZbt2HYPoUsduXMZyJI8" + "z5tvu7pUDws51nV1EX15BcN3++aY5pUyA1ItaaDymQVmoFbQC0BNMzMO53dMnFko" + "4i42kohGBBARAgAGBQI3OvmjAAoJEHUPZJXInZM+hosAnRntCkj/70shGTPxgpUF" + "74zA+EbzAKCcMkyHXIz2W0Isw3gDt27Z9ggsE4hGBBARAgAGBQI3NyPFAAoJEPbu" + "3yAYS8TZh2UAoJVmzw85yHJzsXQ1vpO2IAPfv59NAJ9WY0oiYqb3q1MSxBRwG0gV" + "iNCJ7YkBFQMFEDdD3tNSgFdEdlNAHQEByHEH/2JMfg71GgiyGJTKxCAymdyf2j2y" + "fH6wI782JK4BWV4c0E/V38q+jpIYslihV9t8s8w1XK5niMaLwlCOyBWOkDP3ech6" + "+GPPtfB3cmlL2hS896PWZ1adQHgCeQpB837n56yj0aTs4L1xarbSVT22lUwMiU6P" + "wYdH2Rh8nh8FvN0IZsbln2nOj73qANQzNflmseUKF1Xh4ck8yLrRd4r6amhxAVAf" + "cYFRJN4zdLL3cmhgkt0ADZlzAwXnEjwdHHy7SvAJk1ecNOA9pFsOJbvnzufd1afs" + "/CbG78I+0JDhg75Z2Nwq8eKjsKqiO0zz/vG5yWSndZvWkTWz3D3b1xr1Id2IRgQQ" + "EQIABgUCOCpiHgAKCRDj8lhUEo8OeQ+QAKCbOTscyUnWHSrDo4fIy0MThEjhOgCe" + "L4Kb7TWkd/OHQScVBO8sTUz0+2g="); // private static readonly byte[] pub6check = Base64.Decode("62O9"); // // revoked sub key // private static readonly byte[] _pub7 = Base64.Decode( "mQGiBEFOsIwRBADcjRx7nAs4RaWsQU6p8/ECLZD9sSeYc6CN6UDI96RKj0/hCzMs" + "qlA0+9fzGZ7ZEJ34nuvDKlhKGC7co5eOiE0a9EijxgcrZU/LClZWa4YfyNg/ri6I" + "yTyfOfrPQ33GNQt2iImDf3FKp7XKuY9nIxicGQEaW0kkuAmbV3oh0+9q8QCg/+fS" + "epDEqEE/+nKONULGizKUjMED/RtL6RThRftZ9DOSdBytGYd48z35pca/qZ6HA36K" + "PVQwi7V77VKQyKFLTOXPLnVyO85hyYB/Nv4DFHN+vcC7/49lfoyYMZlN+LarckHi" + "NL154wmmzygB/KKysvWBLgkErEBCD0xBDd89iTQNlDtVQAWGORVffl6WWjOAkliG" + "3dL6A/9A288HfFRnywqi3xddriV6wCPmStC3dkCS4vHk2ofS8uw4ZNoRlp1iEPna" + "ai2Xa9DX1tkhaGk2k96MqqbBdGpbW8sMA9otJ9xdMjWEm/CgJUFUFQf3zaVy3mkM" + "S2Lvb6P4Wc2l/diEEIyK8+PqJItSh0OVU3K9oM7ngHwVcalKILQVUkV2b2tlZCA8" + "UmV2b2tlZEB0ZWQ+iQBOBBARAgAOBQJBTrCMBAsDAgECGQEACgkQvglkcFA/c63+" + "QgCguh8rsJbPTtbhZcrqBi5Mo1bntLEAoPZQ0Kjmu2knRUpHBeUemHDB6zQeuQIN" + "BEFOsIwQCAD2Qle3CH8IF3KiutapQvMF6PlTETlPtvFuuUs4INoBp1ajFOmPQFXz" + "0AfGy0OplK33TGSGSfgMg71l6RfUodNQ+PVZX9x2Uk89PY3bzpnhV5JZzf24rnRP" + "xfx2vIPFRzBhznzJZv8V+bv9kV7HAarTW56NoKVyOtQa8L9GAFgr5fSI/VhOSdvN" + "ILSd5JEHNmszbDgNRR0PfIizHHxbLY7288kjwEPwpVsYjY67VYy4XTjTNP18F1dD" + "ox0YbN4zISy1Kv884bEpQBgRjXyEpwpy1obEAxnIByl6ypUM2Zafq9AKUJsCRtMI" + "PWakXUGfnHy9iUsiGSa6q6Jew1XpMgs7AAICB/93zriSvSHqsi1FeEmUBo431Jkh" + "VerIzb6Plb1j6FIq+s3vyvx9K+dMvjotZqylWZj4GXpH+2xLJTjWkrGSfUZVI2Nk" + "nyOFxUCKLLqaqVBFAQIjULfvQfGEWiGQKk9aRLkdG+D+8Y2N9zYoBXoQ9arvvS/t" + "4mlOsiuaTe+BZ4x+BXTpF4b9sKZl7V8QP/TkoJWUdydkvxciHdWp7ssqyiKOFRhG" + "818knDfFQ3cn2w/RnOb+7AF9wDncXDPYLfpPv9b2qZoLrXcyvlLffGDUdWs553ut" + "1F5AprMURs8BGmY9BnjggfVubHdhTUoA4gVvrdaf+D9NwZAl0xK/5Y/oPuMZiQBG" + "BBgRAgAGBQJBTrCMAAoJEL4JZHBQP3Ot09gAoMmLKloVDP+WhDXnsM5VikxysZ4+" + "AKCrJAUO+lYAyPYwEwgK+bKmUGeKrIkARgQoEQIABgUCQU6wpQAKCRC+CWRwUD9z" + "rQK4AJ98kKFxGU6yhHPr6jYBJPWemTNOXgCfeGB3ox4PXeS4DJDuLy9yllytOjo="); // private static readonly byte[] pub7check = Base64.Decode("f/YQ"); private static readonly byte[] _pub8 = Base64.Decode( "mQGiBEEcraYRBADFYj+uFOhHz5SdECvJ3Z03P47gzmWLQ5HH8fPYC9rrv7AgqFFX" + "aWlJJVMLua9e6xoCiDWJs/n4BbZ/weL/11ELg6XqUnzFhYyz0H2KFsPgQ/b9lWLY" + "MtcPMFy5jE33hv/ixHgYLFqoNaAIbg0lzYEW/otQ9IhRl16fO1Q/CQZZrQCg/9M2" + "V2BTmm9RYog86CXJtjawRBcD/RIqU0zulxZ2Zt4javKVxrGIwW3iBU935ebmJEIK" + "Y5EVkGKBOCvsApZ+RGzpYeR2uMsTnQi8RJgiAnjaoVPCdsVJE7uQ0h8XuJ5n5mJ2" + "kLCFlF2hj5ViicZzse+crC12CGtgRe8z23ubLRcd6IUGhVutK8/b5knZ22vE14JD" + "ykKdA/96ObzJQdiuuPsEWN799nUUCaYWPAoLAmiXuICSP4GEnxLbYHWo8zhMrVMT" + "9Q5x3h8cszUz7Acu2BXjP1m96msUNoxPOZtt88NlaFz1Q/JSbQTsVOMd9b/IRN6S" + "A/uU0BiKEMHXuT8HUHVPK49oCKhZrGFP3RT8HZxDKLmR/qrgZ7ABh7QhSmlhIFlp" + "eXUgPHl5amlhQG5vd21lZGlhdGVjaC5jb20+sAMD//+JAF0EEBECAB0FAkEcraYH" + "CwkIBwMCCgIZAQUbAwAAAAUeAQAAAAAKCRD0/lb4K/9iFJlhAKCRMifQewiX5o8F" + "U099FG3QnLVUZgCfWpMOsHulGHfNrxdBSkE5Urqh1ymwAWe5Ag0EQRytphAIAPZC" + "V7cIfwgXcqK61qlC8wXo+VMROU+28W65Szgg2gGnVqMU6Y9AVfPQB8bLQ6mUrfdM" + "ZIZJ+AyDvWXpF9Sh01D49Vlf3HZSTz09jdvOmeFXklnN/biudE/F/Ha8g8VHMGHO" + "fMlm/xX5u/2RXscBqtNbno2gpXI61Brwv0YAWCvl9Ij9WE5J280gtJ3kkQc2azNs" + "OA1FHQ98iLMcfFstjvbzySPAQ/ClWxiNjrtVjLhdONM0/XwXV0OjHRhs3jMhLLUq" + "/zzhsSlAGBGNfISnCnLWhsQDGcgHKXrKlQzZlp+r0ApQmwJG0wg9ZqRdQZ+cfL2J" + "SyIZJrqrol7DVekyCzsAAgIH/3K2wKRSzkIpDfZR25+tnQ8brv3TYoDZo3/wN3F/" + "r6PGjx0150Q8g8EAC0bqm4rXWzOqdSxYxvIPOAGm5P4y+884yS6j3vKcXitT7vj+" + "ODc2pVwGDLDjrMRrosSK89ycPCK6R/5pD7Rv4l9DWi2fgLvXqJHS2/ujUf2uda9q" + "i9xNMnBXIietR82Sih4undFUOwh6Mws/o3eed9DIdaqv2Y2Aw43z/rJ6cjSGV3C7" + "Rkf9x85AajYA3LwpS8d99tgFig2u6V/A16oi6/M51oT0aR/ZAk50qUc4WBk9uRUX" + "L3Y+P6v6FCBE/06fgVltwcQHO1oKYKhH532tDL+9mW5/dYGwAYeJAEwEGBECAAwF" + "AkEcraYFGwwAAAAACgkQ9P5W+Cv/YhShrgCg+JW8m5nF3R/oZGuG87bXQBszkjMA" + "oLhGPncuGKowJXMRVc70/8qwXQJLsAFnmQGiBD2K5rYRBADD6kznWZA9nH/pMlk0" + "bsG4nI3ELgyI7KpgRSS+Dr17+CCNExxCetT+fRFpiEvUcSxeW4pOe55h0bQWSqLo" + "MNErXVJEXrm1VPkC08W8D/gZuPIsdtKJu4nowvdoA+WrI473pbeONGjaEDbuIJak" + "yeKM1VMSGhsImdKtxqhndq2/6QCg/xARUIzPRvKr2TJ52K393895X1kEAMCdjSs+" + "vABnhaeNNR5+NNkkIOCCjCS8qZRZ4ZnIayvn9ueG3KrhZeBIHoajUHrlTXBVj7XO" + "wXVfGpW17jCDiqhU8Pu6VwEwX1iFbuUwqBffiRLXKg0zfcN+MyFKToi+VsJi4jiZ" + "zcwUFMb8jE8tvR/muXti7zKPRPCbNBExoCt4A/0TgkzAosG/W4dUkkbc6XoHrjob" + "iYuy6Xbs/JYlV0vf2CyuKCZC6UoznO5x2GkvOyVtAgyG4HSh1WybdrutZ8k0ysks" + "mOthE7n7iczdj9Uwg2h+TfgDUnxcCAwxnOsX5UaBqGdkX1PjCWs+O3ZhUDg6UsZc" + "7O5a3kstf16lHpf4q7ABAIkAYQQfEQIAIQUCPYrmtgIHABcMgBHRi/xlIgI+Q6LT" + "kNJ7zKvTd87NHAAKCRDJM3gHb/sRj7bxAJ9f6mdlXQH7gMaYiY5tBe/FRtPr1gCf" + "UhDJQG0ARvORFWHjwhhBMLxW7j2wAWC0KkRlc21vbmQgS2VlIDxkZXNtb25kLmtl" + "ZUBub3dtZWRpYXRlY2guY29tPrADAQD9iQBYBBARAgAYBQI9iua2CAsDCQgHAgEK" + "AhkBBRsDAAAAAAoJEMkzeAdv+xGP7v4An19iqadBCCgDIe2DTpspOMidwQYPAJ4/" + "5QXbcn4ClhOKTO3ZEZefQvvL27ABYLkCDQQ9iua2EAgA9kJXtwh/CBdyorrWqULz" + "Bej5UxE5T7bxbrlLOCDaAadWoxTpj0BV89AHxstDqZSt90xkhkn4DIO9ZekX1KHT" + "UPj1WV/cdlJPPT2N286Z4VeSWc39uK50T8X8dryDxUcwYc58yWb/Ffm7/ZFexwGq" + "01uejaClcjrUGvC/RgBYK+X0iP1YTknbzSC0neSRBzZrM2w4DUUdD3yIsxx8Wy2O" + "9vPJI8BD8KVbGI2Ou1WMuF040zT9fBdXQ6MdGGzeMyEstSr/POGxKUAYEY18hKcK" + "ctaGxAMZyAcpesqVDNmWn6vQClCbAkbTCD1mpF1Bn5x8vYlLIhkmuquiXsNV6TIL" + "OwACAgf/SO+bbg+owbFKVN5HgOjOElQZVnCsegwCLqTeQzPPzsWmkGX2qZJPDIRN" + "RZfJzti6+oLJwaRA/3krjviUty4VKhZ3lKg8fd9U0jEdnw+ePA7yJ6gZmBHL15U5" + "OKH4Zo+OVgDhO0c+oetFpend+eKcvtoUcRoQoi8VqzYUNG0b/nmZGDlxQe1/ZNbP" + "HpNf1BAtJXivCEKMD6PVzsLPg2L4tFIvD9faeeuKYQ4jcWtTkBLuIaZba3i3a4wG" + "xTN20j9HpISVuLW/EfZAK1ef4DNjLmHEU9dMzDqfi+hPmMbGlFqcKr+VjcYIDuje" + "o+92xm/EWAmlti88r2hZ3MySamHDrLABAIkATAQYEQIADAUCPYrmtgUbDAAAAAAK" + "CRDJM3gHb/sRjzVTAKDVS+OJLMeS9VLAmT8atVCB42MwIQCgoh1j3ccWnhc/h6B7" + "9Uqz3fUvGoewAWA="); private static readonly byte[] _sec8 = Base64.Decode( "lQHpBEEcraYRBADFYj+uFOhHz5SdECvJ3Z03P47gzmWLQ5HH8fPYC9rrv7AgqFFX" + "aWlJJVMLua9e6xoCiDWJs/n4BbZ/weL/11ELg6XqUnzFhYyz0H2KFsPgQ/b9lWLY" + "MtcPMFy5jE33hv/ixHgYLFqoNaAIbg0lzYEW/otQ9IhRl16fO1Q/CQZZrQCg/9M2" + "V2BTmm9RYog86CXJtjawRBcD/RIqU0zulxZ2Zt4javKVxrGIwW3iBU935ebmJEIK" + "Y5EVkGKBOCvsApZ+RGzpYeR2uMsTnQi8RJgiAnjaoVPCdsVJE7uQ0h8XuJ5n5mJ2" + "kLCFlF2hj5ViicZzse+crC12CGtgRe8z23ubLRcd6IUGhVutK8/b5knZ22vE14JD" + "ykKdA/96ObzJQdiuuPsEWN799nUUCaYWPAoLAmiXuICSP4GEnxLbYHWo8zhMrVMT" + "9Q5x3h8cszUz7Acu2BXjP1m96msUNoxPOZtt88NlaFz1Q/JSbQTsVOMd9b/IRN6S" + "A/uU0BiKEMHXuT8HUHVPK49oCKhZrGFP3RT8HZxDKLmR/qrgZ/4JAwLXyWhb4pf4" + "nmCmD0lDwoYvatLiR7UQVM2MamxClIiT0lCPN9C2AYIFgRWAJNS215Tjx7P/dh7e" + "8sYfh5XEHErT3dMbsAGHtCFKaWEgWWl5dSA8eXlqaWFAbm93bWVkaWF0ZWNoLmNv" + "bT6wAwP//4kAXQQQEQIAHQUCQRytpgcLCQgHAwIKAhkBBRsDAAAABR4BAAAAAAoJ" + "EPT+Vvgr/2IUmWEAoJEyJ9B7CJfmjwVTT30UbdCctVRmAJ9akw6we6UYd82vF0FK" + "QTlSuqHXKbABZ50CawRBHK2mEAgA9kJXtwh/CBdyorrWqULzBej5UxE5T7bxbrlL" + "OCDaAadWoxTpj0BV89AHxstDqZSt90xkhkn4DIO9ZekX1KHTUPj1WV/cdlJPPT2N" + "286Z4VeSWc39uK50T8X8dryDxUcwYc58yWb/Ffm7/ZFexwGq01uejaClcjrUGvC/" + "RgBYK+X0iP1YTknbzSC0neSRBzZrM2w4DUUdD3yIsxx8Wy2O9vPJI8BD8KVbGI2O" + "u1WMuF040zT9fBdXQ6MdGGzeMyEstSr/POGxKUAYEY18hKcKctaGxAMZyAcpesqV" + "DNmWn6vQClCbAkbTCD1mpF1Bn5x8vYlLIhkmuquiXsNV6TILOwACAgf/crbApFLO" + "QikN9lHbn62dDxuu/dNigNmjf/A3cX+vo8aPHTXnRDyDwQALRuqbitdbM6p1LFjG" + "8g84Aabk/jL7zzjJLqPe8pxeK1Pu+P44NzalXAYMsOOsxGuixIrz3Jw8IrpH/mkP" + "tG/iX0NaLZ+Au9eokdLb+6NR/a51r2qL3E0ycFciJ61HzZKKHi6d0VQ7CHozCz+j" + "d5530Mh1qq/ZjYDDjfP+snpyNIZXcLtGR/3HzkBqNgDcvClLx3322AWKDa7pX8DX" + "qiLr8znWhPRpH9kCTnSpRzhYGT25FRcvdj4/q/oUIET/Tp+BWW3BxAc7WgpgqEfn" + "fa0Mv72Zbn91gf4JAwITijME9IlFBGAwH6YmBtWIlnDiRbsq/Pxozuhbnes831il" + "KmdpUKXkiIfHY0MqrEWl3Dfn6PMJGTnhgqXMrDxx3uHrq0Jl2swRnAWIIO8gID7j" + "uPetUqEviPiwAYeJAEwEGBECAAwFAkEcraYFGwwAAAAACgkQ9P5W+Cv/YhShrgCg" + "+JW8m5nF3R/oZGuG87bXQBszkjMAoLhGPncuGKowJXMRVc70/8qwXQJLsAFn"); private static readonly char[] _sec8Pass = "qwertyui".ToCharArray(); private static readonly byte[] _sec9 = Base64.Decode( "lQGqBEHCokERBAC9rh5SzC1sX1y1zoFuBB/v0SGhoKMEvLYf8Qv/j4deAMrc" + "w5dxasYoD9oxivIUfTbZKo8cqr+dKLgu8tycigTM5b/T2ms69SUAxSBtj2uR" + "LZrh4vjC/93kF+vzYJ4fNaBs9DGfCnsTouKjXqmfN3SlPMKNcGutO7FaUC3d" + "zcpYfwCg7qyONHvXPhS0Iw4QL3mJ/6wMl0UD/0PaonqW0lfGeSjJSM9Jx5Bt" + "fTSlwl6GmvYmI8HKvOBXAUSTZSbEkMsMVcIgf577iupzgWCgNF6WsNqQpKaq" + "QIq1Kjdd0Y00xU1AKflOkhl6eufTigjviM+RdDlRYsOO5rzgwDTRTu9giErs" + "XIyJAIZIdu2iaBHX1zHTfJ1r7nlAA/9H4T8JIhppUk/fLGsoPNZzypzVip8O" + "mFb9PgvLn5GmuIC2maiocT7ibbPa7XuXTO6+k+323v7PoOUaKD3uD93zHViY" + "Ma4Q5pL5Ajc7isnLXJgJb/hvvB1oo+wSDo9vJX8OCSq1eUPUERs4jm90/oqy" + "3UG2QVqs5gcKKR4o48jTiv4DZQJHTlUBtB1mb28ga2V5IDxmb28ua2V5QGlu" + "dmFsaWQuY29tPoheBBMRAgAeBQJBwqJCAhsDBgsJCAcDAgMVAgMDFgIBAh4B" + "AheAAAoJEOKcXvehtw4ajJMAoK9nLfsrRY6peq56l/KzmjzuaLacAKCXnmiU" + "waI7+uITZ0dihJ3puJgUz50BWARBwqJDEAQA0DPcNIn1BQ4CDEzIiQkegNPY" + "mkYyYWDQjb6QFUXkuk1WEB73TzMoemsA0UKXwNuwrUgVhdpkB1+K0OR/e5ik" + "GhlFdrDCqyT+mw6dRWbJ2i4AmFXZaRKO8AozZeWojsfP1/AMxQoIiBEteMFv" + "iuXnZ3pGxSfZYm2+33IuPAV8KKMAAwUD/0C2xZQXgVWTiVz70HUviOmeTQ+f" + "b1Hj0U9NMXWB383oQRBZCvQDM12cqGsvPZuZZ0fkGehGAIoyXtIjJ9lejzZN" + "1TE9fnXZ9okXI4yCl7XLSE26OAbNsis4EtKTNScNaU9Dk3CS5XD/pkRjrkPN" + "2hdUFtshuGmYkqhb9BIlrwE7/gMDAglbVSwecr9mYJcDYCH62U9TScWDTzsQ" + "NFEfhMez3hGnNHNfHe+7yN3+Q9/LIhbba3IJEN5LsE5BFvudLbArp56EusIn" + "JCxgiEkEGBECAAkFAkHCokMCGwwACgkQ4pxe96G3Dho2UQCeN3VPwx3dROZ+" + "4Od8Qj+cLrBndGEAn0vaQdy6eIGeDw2I9u3Quwy6JnROnQHhBEHCozMRBADH" + "ZBlB6xsAnqFYtYQOHr4pX6Q8TrqXCiHHc/q56G2iGbI9IlbfykQzaPHgWqZw" + "9P0QGgF/QZh8TitiED+imLlGDqj3nhzpazqDh5S6sg6LYkQPqhwG/wT5sZQQ" + "fzdeupxupjI5YN8RdIqkWF+ILOjk0+awZ4z0TSY/f6OSWpOXlwCgjIquR3KR" + "tlCLk+fBlPnOXaOjX+kEAJw7umykNIHNaoY/2sxNhQhjqHVxKyN44y6FCSv9" + "jRyW8Q/Qc8YhqBIHdmlcXoNWkDtlvErjdYMvOKFqKB1e2bGpjvhtIhNVQWdk" + "oHap9ZuM1nV0+fD/7g/NM6D9rOOVCahBG2fEEeIwxa2CQ7zHZYfg9Umn3vbh" + "TYi68R3AmgLOA/wKIVkfFKioI7iX4crQviQHJK3/A90SkrjdMQwLoiUjdgtk" + "s7hJsTP1OPb2RggS1wCsh4sv9nOyDULj0T0ySGv7cpyv5Nq0FY8gw2oogHs5" + "fjUnG4VeYW0zcIzI8KCaJT4UhR9An0A1jF6COrYCcjuzkflFbQLtQb9uNj8a" + "hCpU4/4DAwIUxXlRMYE8uWCranzPo83FnBPRnGJ2aC9SqZWJYVUKIn4Vf2nu" + "pVvCGFja0usl1WfV72hqlNKEONq7lohJBBgRAgAJBQJBwqMzAhsCAAoJEOKc" + "Xvehtw4afisAoME/t8xz/rj/N7QRN9p8Ji8VPGSqAJ9K8eFJ+V0mxR+octJr" + "6neEEX/i1Q=="); private static readonly char[] _sec9Pass = "foo".ToCharArray(); // version 4 keys with expiry dates private static readonly byte[] _pub10 = Base64.Decode( "mQGiBEKqia0RBACc3hkufmscRSC4UvPZqMDsHm4+d/GXIr+3iNMSSEySJu8yk+k0" + "Xs11C/K+n+v1rnn2jGGknv+1lDY6w75TIcTE6o6HGKeIDxsAm8P3MhoGU1GNPamA" + "eTDeNybtrN/g6C65fCY9uI11hsUboYgQZ8ND22PB0VtvdOgq9D85qNUzxwCg1BbJ" + "ycAKd4VqEvQ2Zglp3dCSrFMD/Ambq1kZqYa69sp3b9BPKuAgUgUPoytOArEej3Bk" + "easAgAxNhWJy4GxigES3vk50rVi7w8XBuqbD1mQCzldF0HX0/A7PxLBv6od5uqqF" + "HFxIyxg/KBZLd9ZOrsSaoUWH58jZq98X/sFtJtRi5VuJagMxCIJD4mLgtMv7Unlb" + "/GrsA/9DEnObA/fNTgK70T+ZmPIS5tSt+bio30Aw4YGpPCGqpnm1u73b5kqX3U3B" + "P+vGDvFuqZYpqQA8byAueH0MbaDHI4CFugvShXvgysJxN7ov7/8qsZZUMfK1t2Nr" + "SAsPuKRbcY4gNKXIElKeXbyaET7vX7uAEKuxEwdYGFp/lNTkHLQgdGVzdCBrZXkg" + "KHRlc3QpIDx0ZXN0QHRlc3QudGVzdD6IZAQTEQIAJAUCQqqJrQIbAwUJACTqAAYL" + "CQgHAwIDFQIDAxYCAQIeAQIXgAAKCRDjDROQZRqIzDzLAJ42AeCRIBBjv8r8qw9y" + "laNj2GZ1sACgiWYHVXMA6B1H9I1kS3YsCd3Oq7qwAgAAuM0EQqqJrhADAKWkix8l" + "pJN7MMTXob4xFF1TvGll0UD1bDGOMMbes6aeXSbT9QXee/fH3GnijLY7wB+qTPv9" + "ohubrSpnv3yen3CEBW6Q2YK+NlCskma42Py8YMV2idmYjtJi1ckvHFWt5wADBQL/" + "fkB5Q5xSGgspMaTZmtmX3zG7ZDeZ0avP8e8mRL8UszCTpqs6vMZrXwyQLZPbtMYv" + "PQpuRGEeKj0ysimwYRA5rrLQjnRER3nyuuEUUgc4j+aeRxPf9WVsJ/a1FCHtaAP1" + "iE8EGBECAA8FAkKqia4CGwwFCQAk6gAACgkQ4w0TkGUaiMzdqgCfd66H7DL7kFGd" + "IoS+NIp8JO+noxAAn25si4QAF7og8+4T5YQUuhIhx/NesAIAAA=="); private static readonly byte[] _sec10 = Base64.Decode( "lQHhBEKqia0RBACc3hkufmscRSC4UvPZqMDsHm4+d/GXIr+3iNMSSEySJu8yk+k0" + "Xs11C/K+n+v1rnn2jGGknv+1lDY6w75TIcTE6o6HGKeIDxsAm8P3MhoGU1GNPamA" + "eTDeNybtrN/g6C65fCY9uI11hsUboYgQZ8ND22PB0VtvdOgq9D85qNUzxwCg1BbJ" + "ycAKd4VqEvQ2Zglp3dCSrFMD/Ambq1kZqYa69sp3b9BPKuAgUgUPoytOArEej3Bk" + "easAgAxNhWJy4GxigES3vk50rVi7w8XBuqbD1mQCzldF0HX0/A7PxLBv6od5uqqF" + "HFxIyxg/KBZLd9ZOrsSaoUWH58jZq98X/sFtJtRi5VuJagMxCIJD4mLgtMv7Unlb" + "/GrsA/9DEnObA/fNTgK70T+ZmPIS5tSt+bio30Aw4YGpPCGqpnm1u73b5kqX3U3B" + "P+vGDvFuqZYpqQA8byAueH0MbaDHI4CFugvShXvgysJxN7ov7/8qsZZUMfK1t2Nr" + "SAsPuKRbcY4gNKXIElKeXbyaET7vX7uAEKuxEwdYGFp/lNTkHP4DAwLssmOjVC+d" + "mWB783Lpzjb9evKzsxisTdx8/jHpUSS+r//6/Guyx3aA/zUw5bbftItW57mhuNNb" + "JTu7WrQgdGVzdCBrZXkgKHRlc3QpIDx0ZXN0QHRlc3QudGVzdD6IZAQTEQIAJAUC" + "QqqJrQIbAwUJACTqAAYLCQgHAwIDFQIDAxYCAQIeAQIXgAAKCRDjDROQZRqIzDzL" + "AJ0cYPwKeoSReY14LqJtAjnkX7URHACgsRZWfpbalrSyDnq3TtZeGPUqGX+wAgAA" + "nQEUBEKqia4QAwClpIsfJaSTezDE16G+MRRdU7xpZdFA9WwxjjDG3rOmnl0m0/UF" + "3nv3x9xp4oy2O8Afqkz7/aIbm60qZ798np9whAVukNmCvjZQrJJmuNj8vGDFdonZ" + "mI7SYtXJLxxVrecAAwUC/35AeUOcUhoLKTGk2ZrZl98xu2Q3mdGrz/HvJkS/FLMw" + "k6arOrzGa18MkC2T27TGLz0KbkRhHio9MrIpsGEQOa6y0I50REd58rrhFFIHOI/m" + "nkcT3/VlbCf2tRQh7WgD9f4DAwLssmOjVC+dmWDXVLRopzxbBGOvodp/LZoSDb56" + "gNJjDMJ1aXqWW9qTAg1CFjBq73J3oFpVzInXZ8+Q8inxv7bnWiHbiE8EGBECAA8F" + "AkKqia4CGwwFCQAk6gAACgkQ4w0TkGUaiMzdqgCgl2jw5hfk/JsyjulQqe1Nps1q" + "Lx0AoMdnFMZmTMLHn8scUW2j9XO312tmsAIAAA=="); // private static readonly char[] sec10pass = "test".ToCharArray(); private static readonly byte[] _subKeyBindingKey = Base64.Decode( "mQGiBDWagYwRBAD7UcH4TAIp7tmUoHBNxVxCVz2ZrNo79M6fV63riOiH2uDxfIpr" + "IrL0cM4ehEKoqlhngjDhX60eJrOw1nC5BpYZRnDnyDYT4wTWRguxObzGq9pqA1dM" + "oPTJhkFZVIBgFY99/ULRqaUYIhFGgBtnwS70J8/L/PGVc3DmWRLMkTDjSQCg/5Nh" + "MCjMK++MdYMcMl/ziaKRT6EEAOtw6PnU9afdohbpx9CK4UvCCEagfbnUtkSCQKSk" + "6cUp6VsqyzY0pai/BwJ3h4apFMMMpVrtBAtchVgqo4xTr0Sve2j0k+ase6FSImiB" + "g+AR7hvTUTcBjwtIExBc8TuCTqmn4GG8F7UMdl5Z0AZYj/FfAQYaRVZYP/pRVFNx" + "Lw65BAC/Fi3qgiGCJFvXnHIckTfcAmZnKSEXWY9NJ4YQb4+/nH7Vsw0wR/ZObUHR" + "bWgTc9Vw1uZIMe0XVj6Yk1dhGRehUnrm3mE7UJxu7pgkBCbFECFSlSSqP4MEJwZV" + "09YP/msu50kjoxyoTpt+16uX/8B4at24GF1aTHBxwDLd8X0QWrQsTWVycmlsbCBM" + "eW5jaCBDTEVBUiBzeXN0ZW0gREggPGNsZWFyQG1sLmNvbT6JAEsEEBECAAsFAjWa" + "gYwECwMBAgAKCRDyAGjiP47/XanfAKCs6BPURWVQlGh635VgL+pdkUVNUwCdFcNa" + "1isw+eAcopXPMj6ACOapepu5Ag0ENZqBlBAIAPZCV7cIfwgXcqK61qlC8wXo+VMR" + "OU+28W65Szgg2gGnVqMU6Y9AVfPQB8bLQ6mUrfdMZIZJ+AyDvWXpF9Sh01D49Vlf" + "3HZSTz09jdvOmeFXklnN/biudE/F/Ha8g8VHMGHOfMlm/xX5u/2RXscBqtNbno2g" + "pXI61Brwv0YAWCvl9Ij9WE5J280gtJ3kkQc2azNsOA1FHQ98iLMcfFstjvbzySPA" + "Q/ClWxiNjrtVjLhdONM0/XwXV0OjHRhs3jMhLLUq/zzhsSlAGBGNfISnCnLWhsQD" + "GcgHKXrKlQzZlp+r0ApQmwJG0wg9ZqRdQZ+cfL2JSyIZJrqrol7DVekyCzsAAgIH" + "/RYtVo+HROZ6jrNjrATEwQm1fUQrk6n5+2dniN881lF0CNkB4NkHw1Xxz4Ejnu/0" + "iLg8fkOAsmanOsKpOkRtqUnVpsVL5mLJpFEyCY5jbcfj+KY9/25bs0ga7kLHNZia" + "zbCxJdF+W179z3nudQxRaXG/0XISIH7ziZbSVni69sKc1osk1+OoOMbSuZ86z535" + "Pln4fXclkFE927HxfbWoO+60hkOLKh7x+8fC82b3x9vCETujEaxrscO2xS7/MYXP" + "8t1ffriTDmhuIuQS2q4fLgeWdqrODrMhrD8Dq7e558gzp30ZCqpiS7EmKGczL7B8" + "gXxbBCVSTxYMJheXt2xMXsuJAD8DBRg1moGU8gBo4j+O/10RAgWdAKCPhaFIXuC8" + "/cdiNMxTDw9ug3De5QCfYXmDzRSFUu/nrCi8yz/l09wsnxo="); // private static readonly byte[] subKeyBindingCheckSum = Base64.Decode("3HU+"); // // PGP8 with SHA1 checksum. // private static readonly byte[] _rewrapKey = Base64.Decode( "lQOWBEUPOQgBCADdjPTtl8oOwqJFA5WU8p7oDK5KRWfmXeXUZr+ZJipemY5RSvAM" + "rxqsM47LKYbmXOJznXCQ8+PPa+VxXAsI1CXFHIFqrXSwvB/DUmb4Ec9EuvNd18Zl" + "hJAybzmV2KMkaUp9oG/DUvxZJqkpUddNfwqZu0KKKZWF5gwW5Oy05VCpaJxQVXFS" + "whdbRfwEENJiNx4RB3OlWhIjY2p+TgZfgQjiGB9i15R+37sV7TqzBUZF4WWcnIRQ" + "DnpUfxHgxQ0wO/h/aooyRHSpIx5i4oNpMYq9FNIyakEx/Bomdbs5hW9dFxhrE8Es" + "UViAYITgTsyROxmgGatGG09dcmVDJVYF4i7JAAYpAAf/VnVyUDs8HrxYTOIt4rYY" + "jIHToBsV0IiLpA8fEA7k078L1MwSwERVVe6oHVTjeR4A9OxE52Vroh2eOLnF3ftf" + "6QThVVZr+gr5qeG3yvQ36N7PXNEVOlkyBzGmFQNe4oCA+NR2iqnAIspnekVmwJV6" + "xVvPCjWw/A7ZArDARpfthspwNcJAp4SWfoa2eKzvUTznTyqFu2PSS5fwQZUgOB0P" + "Y2FNaKeqV8vEZu4SUWwLOqXBQIZXiaLvdKNgwFvUe3kSHdCNsrVzW7SYxFwaEog2" + "o6YLKPVPqjlGX1cMOponGp+7n9nDYkQjtEsGSSMQkQRDAcBdSVJmLO07kFOQSOhL" + "WQQA49BcgTZyhyH6TnDBMBHsGCYj43FnBigypGT9FrQHoWybfX47yZaZFROAaaMa" + "U6man50YcYZPwzDzXHrK2MoGALY+DzB3mGeXVB45D/KYtlMHPLgntV9T5b14Scbc" + "w1ES2OUtsSIUs0zelkoXqjLuKnSIYK3mMb67Au7AEp6LXM8EAPj2NypvC86VEnn+" + "FH0QHvUwBpmDw0EZe25xQs0brvAG00uIbiZnTH66qsIfRhXV/gbKK9J5DTGIqQ15" + "DuPpz7lcxg/n2+SmjQLNfXCnG8hmtBjhTe+udXAUrmIcfafXyu68SAtebgm1ga56" + "zUfqsgN3FFuMUffLl3myjyGsg5DnA/oCFWL4WCNClOgL6A5VkNIUait8QtSdCACT" + "Y7jdSOguSNXfln0QT5lTv+q1AjU7zjRl/LsFNmIJ5g2qdDyK937FOXM44FEEjZty" + "/4P2dzYpThUI4QUohIj8Qi9f2pZQueC5ztH6rpqANv9geZKcciAeAbZ8Md0K2TEU" + "RD3Lh+RSBzILtBtUZXN0IEtleSA8dGVzdEBleGFtcGxlLmNvbT6JATYEEwECACAF" + "AkUPOQgCGwMGCwkIBwMCBBUCCAMEFgIDAQIeAQIXgAAKCRDYpknHeQaskD9NB/9W" + "EbFuLaqZAl3yjLU5+vb75BdvcfL1lUs44LZVwobNp3/0XbZdY76xVPNZURtU4u3L" + "sJfGlaF+EqZDE0Mqc+vs5SIb0OnCzNJ00KaUFraUtkByRV32T5ECHK0gMBjCs5RT" + "I0vVv+Qmzl4+X1Y2bJ2mlpBejHIrOzrBD5NTJimTAzyfnNfipmbqL8p/cxXKKzS+" + "OM++ZFNACj6lRM1W9GioXnivBRC88gFSQ4/GXc8yjcrMlKA27JxV+SZ9kRWwKH2f" + "6o6mojUQxnHr+ZFKUpo6ocvTgBDlC57d8IpwJeZ2TvqD6EdA8rZ0YriVjxGMDrX1" + "8esfw+iLchfEwXtBIRwS"); private static readonly char[] _rewrapPass = "voltage123".ToCharArray(); private static readonly byte[] _pubWithX509 = Base64.Decode( "mQENBERabjABCACtmfyo6Nph9MQjv4nmCWjZrRYnhXbivomAdIwYkLZUj1bjqE+j" + "uaLzjZV8xSI59odZvrmOiqlzOc4txitQ1OX7nRgbOJ7qku0dvwjtIn46+HQ+cAFn" + "2mTi81RyXEpO2uiZXfsNTxUtMi+ZuFLufiMc2kdk27GZYWEuasdAPOaPJnA+wW6i" + "ZHlt0NfXIGNz864gRwhD07fmBIr1dMFfATWxCbgMd/rH7Z/j4rvceHD2n9yrhPze" + "YN7W4Nuhsr2w/Ft5Cm9xO7vXT/cpto45uxn8f7jERep6bnUwNOhH8G+6xLQgTLD0" + "qFBGVSIneK3lobs6+xn6VaGN8W0tH3UOaxA1ABEBAAG0D0NOPXFhLWRlZXBzaWdo" + "dIkFDgQQZAIFAQUCRFpuMAUDCWdU0gMF/3gCGwPELGQBAQQwggTkMIIDzKADAgEC" + "AhBVUMV/M6rIiE+IzmnPheQWMA0GCSqGSIb3DQEBBQUAMG4xEzARBgoJkiaJk/Is" + "ZAEZFgNjb20xEjAQBgoJkiaJk/IsZAEZFgJxYTEVMBMGCgmSJomT8ixkARkWBXRt" + "czAxMRUwEwYKCZImiZPyLGQBGRYFV2ViZmUxFTATBgNVBAMTDHFhLWRlZXBzaWdo" + "dDAeFw0wNjA1MDQyMTEyMTZaFw0xMTA1MDQyMTIwMDJaMG4xEzARBgoJkiaJk/Is" + "ZAEZFgNjb20xEjAQBgoJkiaJk/IsZAEZFgJxYTEVMBMGCgmSJomT8ixkARkWBXRt" + "czAxMRUwEwYKCZImiZPyLGQBGRYFV2ViZmUxFTATBgNVBAMTDHFhLWRlZXBzaWdo" + "dDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAK2Z/Kjo2mH0xCO/ieYJ" + "aNmtFieFduK+iYB0jBiQtlSPVuOoT6O5ovONlXzFIjn2h1m+uY6KqXM5zi3GK1DU" + "5fudGBs4nuqS7R2/CO0ifjr4dD5wAWfaZOLzVHJcSk7a6Jld+w1PFS0yL5m4Uu5+" + "IxzaR2TbsZlhYS5qx0A85o8mcD7BbqJkeW3Q19cgY3PzriBHCEPTt+YEivV0wV8B" + "NbEJuAx3+sftn+Piu9x4cPaf3KuE/N5g3tbg26GyvbD8W3kKb3E7u9dP9ym2jjm7" + "Gfx/uMRF6npudTA06Efwb7rEtCBMsPSoUEZVIid4reWhuzr7GfpVoY3xbS0fdQ5r" + "EDUCAwEAAaOCAXwwggF4MAsGA1UdDwQEAwIBhjAPBgNVHRMBAf8EBTADAQH/MB0G" + "A1UdDgQWBBSmFTRv5y65DHtTYae48zl0ExNWZzCCASUGA1UdHwSCARwwggEYMIIB" + "FKCCARCgggEMhoHFbGRhcDovLy9DTj1xYS1kZWVwc2lnaHQsQ049cWEtd3VtYW4x" + "LWRjLENOPUNEUCxDTj1QdWJsaWMlMjBLZXklMjBTZXJ2aWNlcyxDTj1TZXJ2aWNl" + "cyxDTj1Db25maWd1cmF0aW9uLERDPVdlYmZlLERDPXRtczAxLERDPXFhLERDPWNv" + "bT9jZXJ0aWZpY2F0ZVJldm9jYXRpb25MaXN0P2Jhc2U/b2JqZWN0Q2xhc3M9Y1JM" + "RGlzdHJpYnV0aW9uUG9pbnSGQmh0dHA6Ly9xYS13dW1hbjEtZGMud2ViZmUudG1z" + "MDEucWEuY29tL0NlcnRFbnJvbGwvcWEtZGVlcHNpZ2h0LmNybDAQBgkrBgEEAYI3" + "FQEEAwIBADANBgkqhkiG9w0BAQUFAAOCAQEAfuZCW3XlB7Eok35zQbvYt9rhAndT" + "DNw3wPNI4ZzD1nXoYWnwhNNvWRpsOt4ExOSNdaHErfgDXAMyyg66Sro0TkAx8eAj" + "fPQsyRAh0nm0glzFmJN6TdOZbj7hqGZjc4opQ6nZo8h/ULnaEwMIUW4gcSkZt0ww" + "CuErl5NUrN3DpkREeCG/fVvQZ8ays3ibQ5ZCZnYBkLYq/i0r3NLW34WfYhjDY48J" + "oQWtvFSAxvRfz2NGmqnrCHPQZxqlfdta97kDa4VQ0zSeBaC70gZkLmD1GJMxWoXW" + "6tmEcgPY5SghInUf+L2u52V55MjyAFzVp7kTK2KY+p7qw35vzckrWkwu8AAAAAAA" + "AQE="); private static readonly byte[] _secWithPersonalCertificate = Base64.Decode( "lQOYBEjGLGsBCACp1I1dZKsK4N/I0/4g02hDVNLdQkDZfefduJgyJUyBGo/I" + "/ZBpc4vT1YwVIdic4ADjtGB4+7WohN4v8siGzwRSeXardSdZVIw2va0JDsQC" + "yeoTnwVkUgn+w/MDgpL0BBhTpr9o3QYoo28/qKMni3eA8JevloZqlAbQ/sYq" + "rToMAqn0EIdeVVh6n2lRQhUJaNkH/kA5qWBpI+eI8ot/Gm9kAy3i4e0Xqr3J" + "Ff1lkGlZuV5H5p/ItZui9BDIRn4IDaeR511NQnKlxFalM/gP9R9yDVI1aXfy" + "STcp3ZcsTOTGNzACtpvMvl6LZyL42DyhlOKlJQJS81wp4dg0LNrhMFOtABEB" + "AAEAB/0QIH5UEg0pTqAG4r/3v1uKmUbKJVJ3KhJB5xeSG3dKWIqy3AaXR5ZN" + "mrJfXK7EfC5ZcSAqx5br1mzVl3PHVBKQVQxvIlmG4r/LKvPVhQYZUFyJWckZ" + "9QMR+EA0Dcran9Ds5fa4hH84jgcwalkj64XWRAKDdVh098g17HDw+IYnQanl" + "7IXbYvh+1Lr2HyPo//vHX8DxXIJBv+E4skvqGoNfCIfwcMeLsrI5EKo+D2pu" + "kAuBYI0VBiZkrJHFXWmQLW71Mc/Bj7wTG8Q1pCpu7YQ7acFSv+/IOCsB9l9S" + "vdB7pNhB3lEjYFGoTgr03VfeixA7/x8uDuSXjnBdTZqmGqkZBADNwCqlzdaQ" + "X6CjS5jc3vzwDSPgM7ovieypEL6NU3QDEUhuP6fVvD2NYOgVnAEbJzgOleZS" + "W2AFXKAf5NDxfqHnBmo/jlYb5yZV5Y+8/poLLj/m8t7sAfAmcZqGXfYMbSbe" + "tr6TGTUXcXgbRyU5oH1e4iq691LOwZ39QjL8lNQQywQA006XYEr/PS9uJkyM" + "Cg+M+nmm40goW4hU/HboFh9Ru6ataHj+CLF42O9sfMAV02UcD3Agj6w4kb5L" + "VswuwfmY+17IryT81d+dSmDLhpo6ufKoAp4qrdP+bzdlbfIim4Rdrw5vF/Yk" + "rC/Nfm3CLJxTimHJhqFx4MG7yEC89lxgdmcD/iJ3m41fwS+bPN2rrCAf7j1u" + "JNr/V/8GAnoXR8VV9150BcOneijftIIYKKyKkV5TGwcTfjaxRKp87LTeC3MV" + "szFDw04MhlIKRA6nBdU0Ay8Yu+EjXHK2VSpLG/Ny+KGuNiFzhqgBxM8KJwYA" + "ISa1UEqWjXoLU3qu1aD7cCvANPVCOASwAYe0GlBHUCBEZXNrdG9wIDxpbmZv" + "QHBncC5jb20+sAMD//+JAW4EEAECAFgFAkjGLGswFIAAAAAAIAAHcHJlZmVy" + "cmVkLWVtYWlsLWVuY29kaW5nQHBncC5jb21wZ3BtaW1lBwsJCAcDAgoCGQEF" + "GwMAAAADFgECBR4BAAAABRUCCAkKAAoJEHHHqp2m1tlWsx8H/icpHl1Nw17A" + "D6MJN6zJm+aGja+5BOFxOsntW+IV6JI+l5WwiIVE8xTDhoXW4zdH3IZTqoyY" + "frtkqLGpvsPtAQmV6eiPgE3+25ahL+MmjXKsceyhbZeCPDtM2M382VCHYCZK" + "DZ4vrHVgK/BpyTeP/mqoWra9+F5xErhody71/cLyIdImLqXgoAny6YywjuAD" + "2TrFnzPEBmZrkISHVEso+V9sge/8HsuDqSI03BAVWnxcg6aipHtxm907sdVo" + "jzl2yFbxCCCaDIKR7XVbmdX7VZgCYDvNSxX3WEOgFq9CYl4ZlXhyik6Vr4XP" + "7EgqadtfwfMcf4XrYoImSQs0gPOd4QqwAWedA5gESMYsawEIALiazFREqBfi" + "WouTjIdLuY09Ks7PCkn0eo/i40/8lEj1R6JKFQ5RlHNnabh+TLvjvb3nOSU0" + "sDg+IKK/JUc8/Fo7TBdZvARX6BmltEGakqToDC3eaF9EQgHLEhyE/4xXiE4H" + "EeIQeCHdC7k0pggEuWUn5lt6oeeiPUWhqdlUOvzjG+jqMPJL0bk9STbImHUR" + "EiugCPTekC0X0Zn0yrwyqlJQMWnh7wbSl/uo4q45K7qOhxcijo+hNNrkRAMi" + "fdNqD4s5qDERqqHdAAgpWqydo7zV5tx0YSz5fjh59Z7FxkUXpcu1WltT6uVn" + "hubiMTWpXzXOQI8wZL2fb12JmRY47BEAEQEAAQAH+wZBeanj4zne+fBHrWAS" + "2vx8LYiRV9EKg8I/PzKBVdGUnUs0vTqtXU1dXGXsAsPtu2r1bFh0TQH06gR1" + "24iq2obgwkr6x54yj+sZlE6SU0SbF/mQc0NCNAXtSKV2hNXvy+7P+sVJR1bn" + "b5ukuvkj1tgEln/0W4r20qJ60F+M5QxXg6kGh8GAlo2tetKEv1NunAyWY6iv" + "FTnSaIJ/YaKQNcudNvOJjeIakkIzfzBL+trUiI5n1LTBB6+u3CF/BdZBTxOy" + "QwjAh6epZr+GnQqeaomFxBc3mU00sjrsB1Loso84UIs6OKfjMkPoZWkQrQQW" + "+xvQ78D33YwqNfXk/5zQAxkEANZxJGNKaAeDpN2GST/tFZg0R5GPC7uWYC7T" + "pG100mir9ugRpdeIFvfAa7IX2jujxo9AJWo/b8hq0q0koUBdNAX3xxUaWy+q" + "KVCRxBifpYVBfEViD3lsbMy+vLYUrXde9087YD0c0/XUrj+oowWJavblmZtS" + "V9OjkQW9zoCigpf5BADcYV+6bkmJtstxJopJG4kD/lr1o35vOEgLkNsMLayc" + "NuzES084qP+8yXPehkzSsDB83kc7rKfQCQMZ54V7KCCz+Rr4wVG7FCrFAw4e" + "4YghfGVU/5whvbJohl/sXXCYGtVljvY/BSQrojRdP+/iZxFbeD4IKiTjV+XL" + "WKSS56Fq2QQAzeoKBJFUq8nqc8/OCmc52WHSOLnB4AuHL5tNfdE9tjqfzZAE" + "tx3QB7YGGP57tPQxPFDFJVRJDqw0YxI2tG9Pum8iriKGjHg+oEfFhxvCmPxf" + "zDKaGibkLeD7I6ATpXq9If+Nqb5QjzPjFbXBIz/q2nGjamZmp4pujKt/aZxF" + "+YRCebABh4kCQQQYAQIBKwUCSMYsbAUbDAAAAMBdIAQZAQgABgUCSMYsawAK" + "CRCrkqZshpdZSNAiB/9+5nAny2O9/lp2K2z5KVXqlNAHUmd4S/dpqtsZCbAo" + "8Lcr/VYayrNojga1U7cyhsvFky3N9wczzPHq3r9Z+R4WnRM1gpRWl+9+xxtd" + "ZxGfGzMRlxX1n5rCqltKKk6IKuBAr2DtTnxThaQiISO2hEw+P1MT2HnSzMXt" + "zse5CZ5OiOd/bm/rdvTRD/JmLqhXmOFaIwzdVP0dR9Ld4Dug2onOlIelIntC" + "cywY6AmnL0DThaTy5J8MiMSPamSmATl4Bicm8YRbHHz58gCYxI5UMLwtwR1+" + "rSEmrB6GwVHZt0/BzOpuGpvFZI5ZmC5yO/waR1hV+VYj025cIz+SNuDPyjy4" + "AAoJEHHHqp2m1tlW/w0H/3w38SkB5n9D9JL3chp+8fex03t7CQowVMdsBYNY" + "qI4QoVQkakkxzCz5eF7rijXt5eC3NE/quWhlMigT8LARiwBROBWgDRFW4WuX" + "6MwYtjKKUkZSkBKxP3lmaqZrJpF6jfhPEN76zr/NxWPC/nHRNldUdqkzSu/r" + "PeJyePMofJevzMkUzw7EVtbtWhZavCz+EZXRTZXub9M4mDMj64BG6JHMbVZI" + "1iDF2yka5RmhXz9tOhYgq80m7UQUb1ttNn86v1zVbe5lmB8NG4Ndv+JaaSuq" + "SBZOYQ0ZxtMAB3vVVLZCWxma1P5HdXloegh+hosqeu/bl0Wh90z5Bspt6eI4" + "imqwAWeVAdgESMYtmwEEAM9ZeMFxor7oSoXnhQAXD9lXLLfBky6IcIWISY4F" + "JWc8sK8+XiVzpOrefKro0QvmEGSYcDFQMHdScBLOTsiVJiqenA7fg1bkBr/M" + "bnD7vTKMJe0DARlU27tE5hsWCDYTluxIFjGcAcecY2UqHkqpctYKY0WY9EIm" + "dBA5TYaw3c0PABEBAAEAA/0Zg6318nC57cWLIp5dZiO/dRhTPZD0hI+BWZrg" + "zJtPT8rXVY+qK3Jwquig8z29/r+nppEE+xQWVWDlv4M28BDJAbGE+qWKAZqT" + "67lyKgc0c50W/lfbGvvs+F7ldCcNpFvlk79GODKxcEeTGDQKb9R6FnHFee/K" + "cZum71O3Ku3vUQIA3B3PNM+tKocIUNDHnInuLyqLORwQBNGfjU/pLMM0MkpP" + "lWeIfgUmn2zL/e0JrRoO0LQqX1LN/TlfcurDM0SEtwIA8Sba9OpDq99Yz360" + "FiePJiGNNlbj9EZsuGJyMVXL1mTLA6WHnz5XZOfYqJXHlmKvaKDbARW4+0U7" + "0/vPdYWSaQIAwYeo2Ce+b7M5ifbGMDWYBisEvGISg5xfvbe6qApmHS4QVQzE" + "Ym81rdJJ8OfvgSbHcgn37S3OBXIQvNdejF4BWqM9sAGHtCBIeW5lay1JbnRy" + "YW5ldCA8aHluZWtAYWxzb2Z0LmN6PrADA///iQDrBBABAgBVBQJIxi2bBQkB" + "mgKAMBSAAAAAACAAB3ByZWZlcnJlZC1lbWFpbC1lbmNvZGluZ0BwZ3AuY29t" + "cGdwbWltZQULBwgJAgIZAQUbAQAAAAUeAQAAAAIVAgAKCRDlTa3BE84gWVKW" + "BACcoCFKvph9r9QiHT1Z3N4wZH36Uxqu/059EFALnBkEdVudX/p6S9mynGRk" + "EfhmWFC1O6dMpnt+ZBEed/4XyFWVSLPwirML+6dxfXogdUsdFF1NCRHc3QGc" + "txnNUT/zcZ9IRIQjUhp6RkIvJPHcyfTXKSbLviI+PxzHU2Padq8pV7ABZ7kA" + "jQRIfg8tAQQAutJR/aRnfZYwlVv+KlUDYjG8YQUfHpTxpnmVu7W6N0tNg/Xr" + "5dg50wq3I4HOamRxUwHpdPkXyNF1szpDSRZmlM+VmiIvJDBnyH5YVlxT6+zO" + "8LUJ2VTbfPxoLFp539SQ0oJOm7IGMAGO7c0n/QV0N3hKUfWgCyJ+sENDa0Ft" + "JycAEQEAAbABj4kEzQQYAQIENwUCSMYtnAUJAeEzgMLFFAAAAAAAFwNleDUw" + "OWNlcnRpZmljYXRlQHBncC5jb20wggNhMIICyqADAgECAgkA1AoCoRKJCgsw" + "DQYJKoZIhvcNAQEFBQAwgakxCzAJBgNVBAYTAkNaMRcwFQYDVQQIEw5DemVj" + "aCBSZXB1YmxpYzESMBAGA1UEChQJQSYmTCBzb2Z0MSAwHgYDVQQLExdJbnRl" + "cm5hbCBEZXZlbG9wbWVudCBDQTEqMCgGA1UEAxQhQSYmTCBzb2Z0IEludGVy" + "bmFsIERldmVsb3BtZW50IENBMR8wHQYJKoZIhvcNAQkBFhBrYWRsZWNAYWxz" + "b2Z0LmN6MB4XDTA4MDcxNjE1MDkzM1oXDTA5MDcxNjE1MDkzM1owaTELMAkG" + "A1UEBhMCQ1oxFzAVBgNVBAgTDkN6ZWNoIFJlcHVibGljMRIwEAYDVQQKFAlB" + "JiZMIHNvZnQxFDASBgNVBAsTC0RldmVsb3BtZW50MRcwFQYDVQQDEw5IeW5l" + "ay1JbnRyYW5ldDCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAutJR/aRn" + "fZYwlVv+KlUDYjG8YQUfHpTxpnmVu7W6N0tNg/Xr5dg50wq3I4HOamRxUwHp" + "dPkXyNF1szpDSRZmlM+VmiIvJDBnyH5YVlxT6+zO8LUJ2VTbfPxoLFp539SQ" + "0oJOm7IGMAGO7c0n/QV0N3hKUfWgCyJ+sENDa0FtJycCAwEAAaOBzzCBzDAJ" + "BgNVHRMEAjAAMCwGCWCGSAGG+EIBDQQfFh1PcGVuU1NMIEdlbmVyYXRlZCBD" + "ZXJ0aWZpY2F0ZTAdBgNVHQ4EFgQUNaw7A6r10PtYZzAvr9CrSKeRYJgwHwYD" + "VR0jBBgwFoAUmqSRM8rN3+T1+tkGiqef8S5suYgwGgYDVR0RBBMwEYEPaHlu" + "ZWtAYWxzb2Z0LmN6MCgGA1UdHwQhMB8wHaAboBmGF2h0dHA6Ly9wZXRyazIv" + "Y2EvY2EuY3JsMAsGA1UdDwQEAwIF4DANBgkqhkiG9w0BAQUFAAOBgQCUdOWd" + "7mBLWj1/GSiYgfwgdTrgk/VZOJvMKBiiFyy1iFEzldz6Xx+mAexnFJKfZXZb" + "EMEGWHfWPmgJzAtuTT0Jz6tUwDmeLH3MP4m8uOZtmyUJ2aq41kciV3rGxF0G" + "BVlZ/bWTaOzHdm6cjylt6xxLt6MJzpPBA/9ZfybSBh1DaAUbDgAAAJ0gBBkB" + "AgAGBQJIxi2bAAoJEAdYkEWLb2R2fJED/RK+JErZ98uGo3Z81cHkdP3rk8is" + "DUL/PR3odBPFH2SIA5wrzklteLK/ZXmBUzcvxqHEgI1F7goXbsBgeTuGgZdx" + "pINErxkNpcMl9FTldWKGiapKrhkZ+G8knDizF/Y7Lg6uGd2nKVxzutLXdHJZ" + "pU89Q5nzq6aJFAZo5TBIcchQAAoJEOVNrcETziBZXvQD/1mvFqBfWqwXxoj3" + "8fHUuFrE2pcp32y3ciO2i+uNVEkNDoaVVNw5eHQaXXWpllI/Pe6LnBl4vkyc" + "n3pjONa4PKrePkEsCUhRbIySqXIHuNwZumDOlKzZHDpCUw72LaC6S6zwuoEf" + "ucOcxTeGIUViANWXyTIKkHfo7HfigixJIL8nsAFn"); private static readonly byte[] _eccSec1 = Base64.Decode( @"lKUEUYgt3xMIKoZIzj0DAQcCAwTN9nCBTQwwFD9MBQH2glGS9kiQ5S+XLRFHZybZWejbXvP06uzi FUb7mHCOqKqzxi5C2Y3ZdfGgn93ys+9VJP3e/gkDAugwt5451IWpYMySmg4UP4gdNF0lJLosqEQc f3fq50zouwCvfZNGYG9G6VjQpg7mIEHzpenNOLloZBlj31gphdv8dKToBUAV2GciGPsXyQi0DXRl c3QgaWRlbnRpdHmIfwQTEwgAJwUCUYgt3w4cdGVzdCBpZGVudGl0eQQWAgEABRUIAwoCBgsJCAcD AgAKCRCtLBE1z/+r3Jq5AP9jls4F4lCHrJU/1eLuLXjdiMK7kAO/T55EUcUwIy7ibAD9GczCN/DT W2Wcrilj341BE2cMz7OA7tcZ8vwxdcZyJ2w="); private void CheckSecretKeyRingWithPersonalCertificate(byte[] keyRing) { var secCol = new PgpSecretKeyRingBundle(keyRing); var count = 0; foreach (PgpSecretKeyRing ring in secCol.GetKeyRings()) { IEnumerator e = ring.GetExtraPublicKeys().GetEnumerator(); while (e.MoveNext()) { ++count; } } if (count != 1) { Fail("personal certificate data subkey not found - count = " + count); } } private void CheckPublicKeyRingWithX509(byte[] keyRing) { var pubRing = new PgpPublicKeyRing(keyRing); var en = pubRing.GetPublicKeys().GetEnumerator(); if (en.MoveNext()) { var key = (PgpPublicKey) en.Current; var sEn = key.GetSignatures().GetEnumerator(); if (sEn.MoveNext()) { var sig = (PgpSignature) sEn.Current; if (sig.KeyAlgorithm != PublicKeyAlgorithmTag.Experimental_1) { Fail("experimental signature not found"); } if (!AreEqual(sig.GetSignature(), Hex.Decode("000101"))) { Fail("experimental encoding check failed"); } } else { Fail("no signature found"); } } else { Fail("no key found"); } } public override void PerformTest() { PerformTest1(); PerformTest2(); PerformTest3(); PerformTest4(); PerformTest5(); PerformTest6(); // NB: This was commented out in the original Java source //PerformTest7(); PerformTest8(); PerformTest9(); PerformTest10(); PerformTest11(); GenerateTest(); GenerateSha1Test(); RewrapTest(); PublicKeyRingWithX509Test(); SecretKeyRingWithPersonalCertificateTest(); InsertMasterTest(); EccKeyTest(); GenerateEccKeyTest(); } public override string Name { get { return "PgpKeyRingTest"; } } public static void Main(string[] args) { RunTest(new PgpKeyRingTest()); } [Test] public void GenerateSha1Test() { var passPhrase = "hello".ToCharArray(); var dsaKpg = GeneratorUtilities.GetKeyPairGenerator("DSA"); var pGen = new DsaParametersGenerator(); pGen.Init(512, 80, new SecureRandom()); DsaParameters dsaParams = pGen.GenerateParameters(); var kgp = new DsaKeyGenerationParameters(new SecureRandom(), dsaParams); dsaKpg.Init(kgp); // // this takes a while as the key generator has to generate some DSA params // before it generates the key. // IAsymmetricCipherKeyPair dsaKp = dsaKpg.GenerateKeyPair(); IAsymmetricCipherKeyPairGenerator elgKpg = GeneratorUtilities.GetKeyPairGenerator("ELGAMAL"); IBigInteger g = new BigInteger( "153d5d6172adb43045b68ae8e1de1070b6137005686d29d3d73a7749199681ee5b212c9b96bfdcfa5b20cd5e3fd2044895d609cf9b410b7a0f12ca1cb9a428cc", 16); IBigInteger p = new BigInteger( "9494fec095f3b85ee286542b3836fc81a5dd0a0349b4c239dd38744d488cf8e31db8bcb7d33b41abb9e5a33cca9144b1cef332c94bf0573bf047a3aca98cdf3b", 16); var elParams = new ElGamalParameters(p, g); var elKgp = new ElGamalKeyGenerationParameters(new SecureRandom(), elParams); elgKpg.Init(elKgp); // // this is quicker because we are using preGenerated parameters. // IAsymmetricCipherKeyPair elgKp = elgKpg.GenerateKeyPair(); var dsaKeyPair = new PgpKeyPair(PublicKeyAlgorithmTag.Dsa, dsaKp, DateTime.UtcNow); var elgKeyPair = new PgpKeyPair(PublicKeyAlgorithmTag.ElGamalEncrypt, elgKp, DateTime.UtcNow); var keyRingGen = new PgpKeyRingGenerator(PgpSignature.PositiveCertification, dsaKeyPair, "test", SymmetricKeyAlgorithmTag.Aes256, passPhrase, true, null, null, new SecureRandom()); keyRingGen.AddSubKey(elgKeyPair); IPgpSecretKeyRing keyRing = keyRingGen.GenerateSecretKeyRing(); keyRing.GetSecretKey().ExtractPrivateKey(passPhrase); PgpPublicKeyRing pubRing = keyRingGen.GeneratePublicKeyRing(); PgpPublicKey vKey = null; PgpPublicKey sKey = null; foreach (PgpPublicKey pk in pubRing.GetPublicKeys()) { if (pk.IsMasterKey) { vKey = pk; } else { sKey = pk; } } Assert.IsNotNull(sKey); Assert.IsNotNull(vKey); foreach (PgpSignature sig in sKey.GetSignatures()) { if (sig.KeyId != vKey.KeyId || sig.SignatureType != PgpSignature.SubkeyBinding) continue; sig.InitVerify(vKey); if (!sig.VerifyCertification(vKey, sKey)) { Fail("failed to verify sub-key signature."); } } } [Test] public void GenerateTest() { char[] passPhrase = "hello".ToCharArray(); var pGen = new DsaParametersGenerator(); pGen.Init(512, 80, new SecureRandom()); DsaParameters dsaParams = pGen.GenerateParameters(); var dsaKgp = new DsaKeyGenerationParameters(new SecureRandom(), dsaParams); IAsymmetricCipherKeyPairGenerator dsaKpg = GeneratorUtilities.GetKeyPairGenerator("DSA"); dsaKpg.Init(dsaKgp); // // this takes a while as the key generator has to Generate some DSA parameters // before it Generates the key. // IAsymmetricCipherKeyPair dsaKp = dsaKpg.GenerateKeyPair(); IAsymmetricCipherKeyPairGenerator elgKpg = GeneratorUtilities.GetKeyPairGenerator("ELGAMAL"); IBigInteger g = new BigInteger( "153d5d6172adb43045b68ae8e1de1070b6137005686d29d3d73a7749199681ee5b212c9b96bfdcfa5b20cd5e3fd2044895d609cf9b410b7a0f12ca1cb9a428cc", 16); IBigInteger p = new BigInteger( "9494fec095f3b85ee286542b3836fc81a5dd0a0349b4c239dd38744d488cf8e31db8bcb7d33b41abb9e5a33cca9144b1cef332c94bf0573bf047a3aca98cdf3b", 16); var elParams = new ElGamalParameters(p, g); var elKgp = new ElGamalKeyGenerationParameters(new SecureRandom(), elParams); elgKpg.Init(elKgp); // // this is quicker because we are using preGenerated parameters. // IAsymmetricCipherKeyPair elgKp = elgKpg.GenerateKeyPair(); var dsaKeyPair = new PgpKeyPair(PublicKeyAlgorithmTag.Dsa, dsaKp, DateTime.UtcNow); var elgKeyPair = new PgpKeyPair(PublicKeyAlgorithmTag.ElGamalEncrypt, elgKp, DateTime.UtcNow); var keyRingGen = new PgpKeyRingGenerator(PgpSignature.PositiveCertification, dsaKeyPair, "test", SymmetricKeyAlgorithmTag.Aes256, passPhrase, null, null, new SecureRandom()); keyRingGen.AddSubKey(elgKeyPair); IPgpSecretKeyRing keyRing = keyRingGen.GenerateSecretKeyRing(); keyRing.GetSecretKey().ExtractPrivateKey(passPhrase); PgpPublicKeyRing pubRing = keyRingGen.GeneratePublicKeyRing(); PgpPublicKey vKey = null; PgpPublicKey sKey = null; foreach (PgpPublicKey pk in pubRing.GetPublicKeys()) { if (pk.IsMasterKey) { vKey = pk; } else { sKey = pk; } } Assert.IsNotNull(sKey); Assert.IsNotNull(vKey); foreach (PgpSignature sig in sKey.GetSignatures()) { if (sig.KeyId == vKey.KeyId && sig.SignatureType == PgpSignature.SubkeyBinding) { sig.InitVerify(vKey); if (!sig.VerifyCertification(vKey, sKey)) { Fail("failed to verify sub-key signature."); } } } } [Test] public void InsertMasterTest() { var random = new SecureRandom(); char[] passPhrase = "hello".ToCharArray(); IAsymmetricCipherKeyPairGenerator rsaKpg = GeneratorUtilities.GetKeyPairGenerator("RSA"); rsaKpg.Init(new KeyGenerationParameters(random, 512)); // // this is quicker because we are using pregenerated parameters. // IAsymmetricCipherKeyPair rsaKp = rsaKpg.GenerateKeyPair(); var rsaKeyPair1 = new PgpKeyPair(PublicKeyAlgorithmTag.RsaGeneral, rsaKp, DateTime.UtcNow); rsaKp = rsaKpg.GenerateKeyPair(); var rsaKeyPair2 = new PgpKeyPair(PublicKeyAlgorithmTag.RsaGeneral, rsaKp, DateTime.UtcNow); var keyRingGen = new PgpKeyRingGenerator(PgpSignature.PositiveCertification, rsaKeyPair1, "test", SymmetricKeyAlgorithmTag.Aes256, passPhrase, null, null, random); IPgpSecretKeyRing secRing1 = keyRingGen.GenerateSecretKeyRing(); PgpPublicKeyRing pubRing1 = keyRingGen.GeneratePublicKeyRing(); keyRingGen = new PgpKeyRingGenerator(PgpSignature.PositiveCertification, rsaKeyPair2, "test", SymmetricKeyAlgorithmTag.Aes256, passPhrase, null, null, random); IPgpSecretKeyRing secRing2 = keyRingGen.GenerateSecretKeyRing(); PgpPublicKeyRing pubRing2 = keyRingGen.GeneratePublicKeyRing(); try { PgpPublicKeyRing.InsertPublicKey(pubRing1, pubRing2.GetPublicKey()); Fail("adding second master key (public) should throw an ArgumentException"); } catch (ArgumentException e) { if (!e.Message.Equals("cannot add a master key to a ring that already has one")) { Fail("wrong message in public test"); } } try { PgpSecretKeyRing.InsertSecretKey(secRing1, secRing2.GetSecretKey()); Fail("adding second master key (secret) should throw an ArgumentException"); } catch (ArgumentException e) { if (!e.Message.Equals("cannot add a master key to a ring that already has one")) { Fail("wrong message in secret test"); } } } [Test] public void PerformTest1() { var pubRings = new PgpPublicKeyRingBundle(_pub1); int count = 0; foreach (PgpPublicKeyRing pgpPub1 in pubRings.GetKeyRings()) { count++; int keyCount = 0; byte[] bytes = pgpPub1.GetEncoded(); var pgpPub2 = new PgpPublicKeyRing(bytes); foreach (PgpPublicKey pubKey in pgpPub2.GetPublicKeys()) { keyCount++; foreach (PgpSignature sig in pubKey.GetSignatures()) { if (sig == null) Fail("null signature found"); } } if (keyCount != 2) { Fail("wrong number of public keys"); } } if (count != 1) { Fail("wrong number of public keyrings"); } // // exact match // count = 0; foreach (PgpPublicKeyRing pgpPub3 in pubRings.GetKeyRings("test (Test key) <test@ubicall.com>")) { if (pgpPub3 == null) Fail("null keyring found"); count++; } if (count != 1) { Fail("wrong number of public keyrings on exact match"); } // // partial match 1 expected // count = 0; foreach (PgpPublicKeyRing pgpPub4 in pubRings.GetKeyRings("test", true)) { if (pgpPub4 == null) Fail("null keyring found"); count++; } if (count != 1) { Fail("wrong number of public keyrings on partial match 1"); } // // partial match 0 expected // count = 0; foreach (PgpPublicKeyRing pgpPub5 in pubRings.GetKeyRings("XXX", true)) { if (pgpPub5 == null) Fail("null keyring found"); count++; } if (count != 0) { Fail("wrong number of public keyrings on partial match 0"); } // // case-insensitive partial match // count = 0; foreach (PgpPublicKeyRing pgpPub6 in pubRings.GetKeyRings("TEST@ubicall.com", true, true)) { if (pgpPub6 == null) Fail("null keyring found"); count++; } if (count != 1) { Fail("wrong number of public keyrings on case-insensitive partial match"); } var secretRings = new PgpSecretKeyRingBundle(_sec1); count = 0; foreach (PgpSecretKeyRing pgpSec1 in secretRings.GetKeyRings()) { count++; int keyCount = 0; byte[] bytes = pgpSec1.GetEncoded(); var pgpSec2 = new PgpSecretKeyRing(bytes); foreach (PgpSecretKey k in pgpSec2.GetSecretKeys()) { keyCount++; IPgpPublicKey pk = k.PublicKey; pk.GetSignatures(); byte[] pkBytes = pk.GetEncoded(); var pkR = new PgpPublicKeyRing(pkBytes); Assert.IsNotNull(pkR); } if (keyCount != 2) { Fail("wrong number of secret keys"); } } if (count != 1) { Fail("wrong number of secret keyrings"); } // // exact match // count = 0; foreach (PgpSecretKeyRing o1 in secretRings.GetKeyRings("test (Test key) <test@ubicall.com>")) { if (o1 == null) Fail("null keyring found"); count++; } if (count != 1) { Fail("wrong number of secret keyrings on exact match"); } // // partial match 1 expected // count = 0; foreach (PgpSecretKeyRing o2 in secretRings.GetKeyRings("test", true)) { if (o2 == null) Fail("null keyring found"); count++; } if (count != 1) { Fail("wrong number of secret keyrings on partial match 1"); } // // exact match 0 expected // count = 0; foreach (PgpSecretKeyRing o3 in secretRings.GetKeyRings("test", false)) { if (o3 == null) Fail("null keyring found"); count++; } if (count != 0) { Fail("wrong number of secret keyrings on partial match 0"); } // // case-insensitive partial match // count = 0; foreach (PgpSecretKeyRing o4 in secretRings.GetKeyRings("TEST@ubicall.com", true, true)) { if (o4 == null) Fail("null keyring found"); count++; } if (count != 1) { Fail("wrong number of secret keyrings on case-insensitive partial match"); } } [Test] public void PerformTest10() { var secretRing = new PgpSecretKeyRing(_sec10); foreach (PgpSecretKey secretKey in secretRing.GetSecretKeys()) { IPgpPublicKey pubKey = secretKey.PublicKey; if (pubKey.ValidDays != 28) { Fail("days wrong on secret key ring"); } if (pubKey.GetValidSeconds() != 28*24*60*60) { Fail("seconds wrong on secret key ring"); } } var publicRing = new PgpPublicKeyRing(_pub10); foreach (PgpPublicKey pubKey in publicRing.GetPublicKeys()) { if (pubKey.ValidDays != 28) { Fail("days wrong on public key ring"); } if (pubKey.GetValidSeconds() != 28*24*60*60) { Fail("seconds wrong on public key ring"); } } } [Test] public void PerformTest11() { var pubRing = new PgpPublicKeyRing(_subKeyBindingKey); foreach (PgpPublicKey key in pubRing.GetPublicKeys()) { if (key.GetValidSeconds() != 0) { Fail("expiration time non-zero"); } } } [Test] public void PerformTest2() { var pubRings = new PgpPublicKeyRingBundle(_pub2); int count = 0; byte[] encRing = pubRings.GetEncoded(); pubRings = new PgpPublicKeyRingBundle(encRing); foreach (PgpPublicKeyRing pgpPub1 in pubRings.GetKeyRings()) { count++; int keyCount = 0; byte[] bytes = pgpPub1.GetEncoded(); var pgpPub2 = new PgpPublicKeyRing(bytes); foreach (PgpPublicKey pk in pgpPub2.GetPublicKeys()) { byte[] pkBytes = pk.GetEncoded(); var pkR = new PgpPublicKeyRing(pkBytes); Assert.IsNotNull(pkR); keyCount++; } if (keyCount != 2) { Fail("wrong number of public keys"); } } if (count != 2) { Fail("wrong number of public keyrings"); } var secretRings2 = new PgpSecretKeyRingBundle(_sec2); count = 0; encRing = secretRings2.GetEncoded(); var secretRings = new PgpSecretKeyRingBundle(encRing); Assert.IsNotNull(secretRings); foreach (PgpSecretKeyRing pgpSec1 in secretRings2.GetKeyRings()) { count++; int keyCount = 0; byte[] bytes = pgpSec1.GetEncoded(); var pgpSec2 = new PgpSecretKeyRing(bytes); foreach (PgpSecretKey k in pgpSec2.GetSecretKeys()) { keyCount++; IPgpPublicKey pk = k.PublicKey; if (pk.KeyId == -1413891222336124627L) { int sCount = 0; foreach (PgpSignature pgpSignature in pk.GetSignaturesOfType(PgpSignature.SubkeyBinding)) { int type = pgpSignature.SignatureType; if (type != PgpSignature.SubkeyBinding) { Fail("failed to return correct signature type"); } sCount++; } if (sCount != 1) { Fail("failed to find binding signature"); } } pk.GetSignatures(); switch (k.KeyId) { case -1413891222336124627L: case -4049084404703773049L: k.ExtractPrivateKey(_sec2Pass1); break; case 59034765524361024L: case -6498553574938125416L: k.ExtractPrivateKey(_sec2Pass2); break; } } if (keyCount != 2) { Fail("wrong number of secret keys"); } } if (count != 2) { Fail("wrong number of secret keyrings"); } } [Test] public void PerformTest3() { var pubRings = new PgpPublicKeyRingBundle(_pub3); int count = 0; byte[] encRing = pubRings.GetEncoded(); pubRings = new PgpPublicKeyRingBundle(encRing); foreach (PgpPublicKeyRing pgpPub1 in pubRings.GetKeyRings()) { count++; int keyCount = 0; byte[] bytes = pgpPub1.GetEncoded(); var pgpPub2 = new PgpPublicKeyRing(bytes); foreach (PgpPublicKey pubK in pgpPub2.GetPublicKeys()) { keyCount++; pubK.GetSignatures(); } if (keyCount != 2) { Fail("wrong number of public keys"); } } if (count != 1) { Fail("wrong number of public keyrings"); } var secretRings2 = new PgpSecretKeyRingBundle(_sec3); count = 0; encRing = secretRings2.GetEncoded(); var secretRings = new PgpSecretKeyRingBundle(encRing); Assert.IsNotNull(secretRings); foreach (PgpSecretKeyRing pgpSec1 in secretRings2.GetKeyRings()) { count++; int keyCount = 0; byte[] bytes = pgpSec1.GetEncoded(); var pgpSec2 = new PgpSecretKeyRing(bytes); foreach (PgpSecretKey k in pgpSec2.GetSecretKeys()) { keyCount++; k.ExtractPrivateKey(_sec3Pass1); } if (keyCount != 2) { Fail("wrong number of secret keys"); } } if (count != 1) { Fail("wrong number of secret keyrings"); } } [Test] public void PerformTest4() { var secretRings1 = new PgpSecretKeyRingBundle(_sec4); int count = 0; byte[] encRing = secretRings1.GetEncoded(); var secretRings2 = new PgpSecretKeyRingBundle(encRing); Assert.IsNotNull(secretRings2); foreach (PgpSecretKeyRing pgpSec1 in secretRings1.GetKeyRings()) { count++; int keyCount = 0; byte[] bytes = pgpSec1.GetEncoded(); var pgpSec2 = new PgpSecretKeyRing(bytes); foreach (PgpSecretKey k in pgpSec2.GetSecretKeys()) { keyCount++; k.ExtractPrivateKey(_sec3Pass1); } if (keyCount != 2) { Fail("wrong number of secret keys"); } } if (count != 1) { Fail("wrong number of secret keyrings"); } } [Test] public void PerformTest5() { var pubRings = new PgpPublicKeyRingBundle(_pub5); int count = 0; byte[] encRing = pubRings.GetEncoded(); pubRings = new PgpPublicKeyRingBundle(encRing); foreach (PgpPublicKeyRing pgpPub1 in pubRings.GetKeyRings()) { count++; int keyCount = 0; byte[] bytes = pgpPub1.GetEncoded(); var pgpPub2 = new PgpPublicKeyRing(bytes); foreach (PgpPublicKey o in pgpPub2.GetPublicKeys()) { if (o == null) Fail("null keyring found"); keyCount++; } if (keyCount != 2) { Fail("wrong number of public keys"); } } if (count != 1) { Fail("wrong number of public keyrings"); } #if INCLUDE_IDEA PgpSecretKeyRingBundle secretRings1 = new PgpSecretKeyRingBundle(sec5); count = 0; encRing = secretRings1.GetEncoded(); PgpSecretKeyRingBundle secretRings2 = new PgpSecretKeyRingBundle(encRing); foreach (PgpSecretKeyRing pgpSec1 in secretRings1.GetKeyRings()) { count++; int keyCount = 0; byte[] bytes = pgpSec1.GetEncoded(); PgpSecretKeyRing pgpSec2 = new PgpSecretKeyRing(bytes); foreach (PgpSecretKey k in pgpSec2.GetSecretKeys()) { keyCount++; k.ExtractPrivateKey(sec5pass1); } if (keyCount != 2) { Fail("wrong number of secret keys"); } } if (count != 1) { Fail("wrong number of secret keyrings"); } #endif } [Test] public void PerformTest6() { var pubRings = new PgpPublicKeyRingBundle(_pub6); foreach (PgpPublicKeyRing pgpPub in pubRings.GetKeyRings()) { foreach (PgpPublicKey k in pgpPub.GetPublicKeys()) { if (k.KeyId == 0x5ce086b5b5a18ff4L) { int count = 0; foreach (PgpSignature sig in k.GetSignaturesOfType(PgpSignature.SubkeyRevocation)) { if (sig == null) Fail("null signature found"); count++; } if (count != 1) { Fail("wrong number of revocations in test6."); } } } } byte[] encRing = pubRings.GetEncoded(); Assert.IsNotNull(encRing); } [Test, Explicit] public void PerformTest7() { var pgpPub = new PgpPublicKeyRing(_pub7); PgpPublicKey masterKey = null; foreach (PgpPublicKey k in pgpPub.GetPublicKeys()) { if (k.IsMasterKey) { masterKey = k; continue; } int count = 0; PgpSignature sig = null; foreach (PgpSignature sigTemp in k.GetSignaturesOfType(PgpSignature.SubkeyRevocation)) { sig = sigTemp; count++; } if (count != 1) { Fail("wrong number of revocations in test7."); } Assert.IsNotNull(sig); sig.InitVerify(masterKey); if (!sig.VerifyCertification(k)) { Fail("failed to verify revocation certification"); } } } [Test] public void PerformTest8() { var pubRings = new PgpPublicKeyRingBundle(_pub8); int count = 0; byte[] encRing = pubRings.GetEncoded(); pubRings = new PgpPublicKeyRingBundle(encRing); foreach (PgpPublicKeyRing pgpPub1 in pubRings.GetKeyRings()) { count++; int keyCount = 0; byte[] bytes = pgpPub1.GetEncoded(); var pgpPub2 = new PgpPublicKeyRing(bytes); foreach (PgpPublicKey o in pgpPub2.GetPublicKeys()) { if (o == null) Fail("null key found"); keyCount++; } if (keyCount != 2) { Fail("wrong number of public keys"); } } if (count != 2) { Fail("wrong number of public keyrings"); } var secretRings1 = new PgpSecretKeyRingBundle(_sec8); count = 0; encRing = secretRings1.GetEncoded(); var secretRings2 = new PgpSecretKeyRingBundle(encRing); Assert.IsNotNull(secretRings2); foreach (PgpSecretKeyRing pgpSec1 in secretRings1.GetKeyRings()) { count++; int keyCount = 0; byte[] bytes = pgpSec1.GetEncoded(); var pgpSec2 = new PgpSecretKeyRing(bytes); foreach (PgpSecretKey k in pgpSec2.GetSecretKeys()) { keyCount++; k.ExtractPrivateKey(_sec8Pass); } if (keyCount != 2) { Fail("wrong number of secret keys"); } } if (count != 1) { Fail("wrong number of secret keyrings"); } } [Test] public void PerformTest9() { var secretRings1 = new PgpSecretKeyRingBundle(_sec9); int count = 0; byte[] encRing = secretRings1.GetEncoded(); var secretRings2 = new PgpSecretKeyRingBundle(encRing); Assert.IsNotNull(secretRings2); foreach (PgpSecretKeyRing pgpSec1 in secretRings1.GetKeyRings()) { count++; int keyCount = 0; byte[] bytes = pgpSec1.GetEncoded(); var pgpSec2 = new PgpSecretKeyRing(bytes); foreach (PgpSecretKey k in pgpSec2.GetSecretKeys()) { keyCount++; IPgpPrivateKey pKey = k.ExtractPrivateKey(_sec9Pass); if (keyCount == 1 && pKey != null) { Fail("primary secret key found, null expected"); } } if (keyCount != 3) { Fail("wrong number of secret keys"); } } if (count != 1) { Fail("wrong number of secret keyrings"); } } [Test] public void PublicKeyRingWithX509Test() { CheckPublicKeyRingWithX509(_pubWithX509); var pubRing = new PgpPublicKeyRing(_pubWithX509); CheckPublicKeyRingWithX509(pubRing.GetEncoded()); } [Test] public void RewrapTest() { var rand = new SecureRandom(); // Read the secret key rings var privRings = new PgpSecretKeyRingBundle( new MemoryStream(_rewrapKey, false)); foreach (PgpSecretKeyRing pgpPrivEnum in privRings.GetKeyRings()) { foreach (PgpSecretKey pgpKeyEnum in pgpPrivEnum.GetSecretKeys()) { // re-encrypt the key with an empty password PgpSecretKeyRing pgpPriv = PgpSecretKeyRing.RemoveSecretKey(pgpPrivEnum, pgpKeyEnum); PgpSecretKey pgpKey = PgpSecretKey.CopyWithNewPassword( pgpKeyEnum, _rewrapPass, null, SymmetricKeyAlgorithmTag.Null, rand); pgpPriv = PgpSecretKeyRing.InsertSecretKey(pgpPriv, pgpKey); Assert.IsNotNull(pgpPriv); // this should succeed var privTmp = pgpKey.ExtractPrivateKey(null); Assert.IsNotNull(privTmp); } } } [Test] public void SecretKeyRingWithPersonalCertificateTest() { CheckSecretKeyRingWithPersonalCertificate(_secWithPersonalCertificate); var secRing = new PgpSecretKeyRingBundle(_secWithPersonalCertificate); CheckSecretKeyRingWithPersonalCertificate(secRing.GetEncoded()); } [Test] public void GenerateEccKeyTest() { const string identity = "GenerateEccKeyTest Identity"; var secureRandom = new SecureRandom(); var keyParamSet = SecObjectIdentifiers.SecP256r1; var ecParams = new ECKeyGenerationParameters(keyParamSet, secureRandom); var now = DateTime.UtcNow; var masterKey = GenerateKeyPair(PublicKeyAlgorithmTag.Ecdsa, ecParams, now); var subKey = GenerateKeyPair(PublicKeyAlgorithmTag.Ecdh, ecParams, now); var keyRingGenerator = new PgpKeyRingGenerator( PgpSignature.PositiveCertification, masterKey, identity, SymmetricKeyAlgorithmTag.Aes256, HashAlgorithmTag.Sha256, "".ToCharArray(), true, GenerateSignatureSubpackets(identity), null, secureRandom); keyRingGenerator.AddSubKey(subKey); var secretKeyRing = keyRingGenerator.GenerateSecretKeyRing(); CheckEccKey(secretKeyRing); } [Test] public void EccKeyTest() { var secretRings = new PgpSecretKeyRingBundle(_eccSec1); var count = 0; foreach (PgpSecretKeyRing secretKeyRing in secretRings.GetKeyRings()) { count++; CheckEccKey(secretKeyRing); } if (count != 1) { Fail("wrong number of secret keyrings"); } } private void CheckEccKey(IPgpSecretKeyRing secretKeyRing) { var keyCount = 0; var bytes = secretKeyRing.GetEncoded(); var pgpSec2 = new PgpSecretKeyRing(bytes); foreach (PgpSecretKey k in pgpSec2.GetSecretKeys()) { keyCount++; var pk = k.PublicKey; pk.GetSignatures(); var pkBytes = pk.GetEncoded(); var pkR1 = new PgpPublicKeyRing(pkBytes); Assert.IsNotNull(pkR1); var pk1 = pkR1.GetPublicKey(); AreEqual(pk1.GetFingerprint(), pk.GetFingerprint()); var pkBytes1 = pkR1.GetEncoded(); var pkR2 = new PgpPublicKeyRing(pkBytes1); Assert.IsNotNull(pkR2); var pkBytes2 = pkR2.GetEncoded(); AreEqual(pkBytes1, pkBytes2); } if (keyCount != secretKeyRing.SecretKeyCount) { Fail("wrong number of secret keys"); } } private static PgpKeyPair GenerateKeyPair(PublicKeyAlgorithmTag algorithm, IKeyGenerationParameters parameters, DateTime dateTime) { var generator = GeneratorUtilities.GetKeyPairGenerator(algorithm); generator.Init(parameters); var keyPair = generator.GenerateKeyPair(); return new PgpKeyPair(algorithm, keyPair, dateTime); } private static PgpSignatureSubpacketVector GenerateSignatureSubpackets(string identity) { var hashedSubkeysGenerator = new PgpSignatureSubpacketGenerator(); hashedSubkeysGenerator.SetSignerUserId(false, identity); return hashedSubkeysGenerator.Generate(); } } }
using System; using Umbraco.Core.Models; using Umbraco.Core.Models.EntityBase; namespace Umbraco.Core { /// <summary> /// Provides extension methods that return udis for Umbraco entities. /// </summary> public static class UdiGetterExtensions { /// <summary> /// Gets the entity identifier of the entity. /// </summary> /// <param name="entity">The entity.</param> /// <returns>The entity identifier of the entity.</returns> public static GuidUdi GetUdi(this ITemplate entity) { if (entity == null) throw new ArgumentNullException("entity"); return new GuidUdi(Constants.UdiEntityType.Template, entity.Key).EnsureClosed(); } /// <summary> /// Gets the entity identifier of the entity. /// </summary> /// <param name="entity">The entity.</param> /// <returns>The entity identifier of the entity.</returns> public static GuidUdi GetUdi(this IContentType entity) { if (entity == null) throw new ArgumentNullException("entity"); return new GuidUdi(Constants.UdiEntityType.DocumentType, entity.Key).EnsureClosed(); } /// <summary> /// Gets the entity identifier of the entity. /// </summary> /// <param name="entity">The entity.</param> /// <returns>The entity identifier of the entity.</returns> public static GuidUdi GetUdi(this IMediaType entity) { if (entity == null) throw new ArgumentNullException("entity"); return new GuidUdi(Constants.UdiEntityType.MediaType, entity.Key).EnsureClosed(); } /// <summary> /// Gets the entity identifier of the entity. /// </summary> /// <param name="entity">The entity.</param> /// <returns>The entity identifier of the entity.</returns> public static GuidUdi GetUdi(this IMemberType entity) { if (entity == null) throw new ArgumentNullException("entity"); return new GuidUdi(Constants.UdiEntityType.MemberType, entity.Key).EnsureClosed(); } /// <summary> /// Gets the entity identifier of the entity. /// </summary> /// <param name="entity">The entity.</param> /// <returns>The entity identifier of the entity.</returns> public static GuidUdi GetUdi(this IMemberGroup entity) { if (entity == null) throw new ArgumentNullException("entity"); return new GuidUdi(Constants.UdiEntityType.MemberGroup, entity.Key).EnsureClosed(); } /// <summary> /// Gets the entity identifier of the entity. /// </summary> /// <param name="entity">The entity.</param> /// <returns>The entity identifier of the entity.</returns> public static GuidUdi GetUdi(this IContentTypeComposition entity) { if (entity == null) throw new ArgumentNullException("entity"); string type; if (entity is IContentType) type = Constants.UdiEntityType.DocumentType; else if (entity is IMediaType) type = Constants.UdiEntityType.MediaType; else if (entity is IMemberType) type = Constants.UdiEntityType.MemberType; else throw new NotSupportedException(string.Format("Composition type {0} is not supported.", entity.GetType().FullName)); return new GuidUdi(type, entity.Key).EnsureClosed(); } /// <summary> /// Gets the entity identifier of the entity. /// </summary> /// <param name="entity">The entity.</param> /// <returns>The entity identifier of the entity.</returns> public static GuidUdi GetUdi(this IDataTypeDefinition entity) { if (entity == null) throw new ArgumentNullException("entity"); return new GuidUdi(Constants.UdiEntityType.DataType, entity.Key).EnsureClosed(); } /// <summary> /// Gets the entity identifier of the entity. /// </summary> /// <param name="entity">The entity.</param> /// <returns>The entity identifier of the entity.</returns> public static GuidUdi GetUdi(this EntityContainer entity) { if (entity == null) throw new ArgumentNullException("entity"); string entityType; if (entity.ContainedObjectType == Constants.ObjectTypes.DataTypeGuid) entityType = Constants.UdiEntityType.DataTypeContainer; else if (entity.ContainedObjectType == Constants.ObjectTypes.DocumentTypeGuid) entityType = Constants.UdiEntityType.DocumentTypeContainer; else if (entity.ContainedObjectType == Constants.ObjectTypes.MediaTypeGuid) entityType = Constants.UdiEntityType.MediaTypeContainer; else throw new NotSupportedException(string.Format("Contained object type {0} is not supported.", entity.ContainedObjectType)); return new GuidUdi(entityType, entity.Key).EnsureClosed(); } /// <summary> /// Gets the entity identifier of the entity. /// </summary> /// <param name="entity">The entity.</param> /// <returns>The entity identifier of the entity.</returns> public static GuidUdi GetUdi(this IMedia entity) { if (entity == null) throw new ArgumentNullException("entity"); return new GuidUdi(Constants.UdiEntityType.Media, entity.Key).EnsureClosed(); } /// <summary> /// Gets the entity identifier of the entity. /// </summary> /// <param name="entity">The entity.</param> /// <returns>The entity identifier of the entity.</returns> public static GuidUdi GetUdi(this IContent entity) { if (entity == null) throw new ArgumentNullException("entity"); return new GuidUdi(entity.IsBlueprint ? Constants.UdiEntityType.DocumentBlueprint : Constants.UdiEntityType.Document, entity.Key).EnsureClosed(); } /// <summary> /// Gets the entity identifier of the entity. /// </summary> /// <param name="entity">The entity.</param> /// <returns>The entity identifier of the entity.</returns> public static GuidUdi GetUdi(this IMember entity) { if (entity == null) throw new ArgumentNullException("entity"); return new GuidUdi(Constants.UdiEntityType.Member, entity.Key).EnsureClosed(); } /// <summary> /// Gets the entity identifier of the entity. /// </summary> /// <param name="entity">The entity.</param> /// <returns>The entity identifier of the entity.</returns> public static StringUdi GetUdi(this Stylesheet entity) { if (entity == null) throw new ArgumentNullException("entity"); return new StringUdi(Constants.UdiEntityType.Stylesheet, entity.Path.TrimStart('/')).EnsureClosed(); } /// <summary> /// Gets the entity identifier of the entity. /// </summary> /// <param name="entity">The entity.</param> /// <returns>The entity identifier of the entity.</returns> public static StringUdi GetUdi(this Script entity) { if (entity == null) throw new ArgumentNullException("entity"); return new StringUdi(Constants.UdiEntityType.Script, entity.Path.TrimStart('/')).EnsureClosed(); } /// <summary> /// Gets the entity identifier of the entity. /// </summary> /// <param name="entity">The entity.</param> /// <returns>The entity identifier of the entity.</returns> public static GuidUdi GetUdi(this IDictionaryItem entity) { if (entity == null) throw new ArgumentNullException("entity"); return new GuidUdi(Constants.UdiEntityType.DictionaryItem, entity.Key).EnsureClosed(); } /// <summary> /// Gets the entity identifier of the entity. /// </summary> /// <param name="entity">The entity.</param> /// <returns>The entity identifier of the entity.</returns> public static GuidUdi GetUdi(this IMacro entity) { if (entity == null) throw new ArgumentNullException("entity"); return new GuidUdi(Constants.UdiEntityType.Macro, entity.Key).EnsureClosed(); } /// <summary> /// Gets the entity identifier of the entity. /// </summary> /// <param name="entity">The entity.</param> /// <returns>The entity identifier of the entity.</returns> public static StringUdi GetUdi(this IUserControl entity) { if (entity == null) throw new ArgumentNullException("entity"); return new StringUdi(Constants.UdiEntityType.UserControl, entity.Path.TrimStart('/')).EnsureClosed(); } /// <summary> /// Gets the entity identifier of the entity. /// </summary> /// <param name="entity">The entity.</param> /// <returns>The entity identifier of the entity.</returns> public static StringUdi GetUdi(this IPartialView entity) { if (entity == null) throw new ArgumentNullException("entity"); // we should throw on Unknown but for the time being, assume it means PartialView var entityType = entity.ViewType == PartialViewType.PartialViewMacro ? Constants.UdiEntityType.PartialViewMacro : Constants.UdiEntityType.PartialView; return new StringUdi(entityType, entity.Path.TrimStart('/')).EnsureClosed(); } /// <summary> /// Gets the entity identifier of the entity. /// </summary> /// <param name="entity">The entity.</param> /// <returns>The entity identifier of the entity.</returns> public static StringUdi GetUdi(this IXsltFile entity) { if (entity == null) throw new ArgumentNullException("entity"); return new StringUdi(Constants.UdiEntityType.Xslt, entity.Path.TrimStart('/')).EnsureClosed(); } /// <summary> /// Gets the entity identifier of the entity. /// </summary> /// <param name="entity">The entity.</param> /// <returns>The entity identifier of the entity.</returns> public static GuidUdi GetUdi(this IContentBase entity) { if (entity == null) throw new ArgumentNullException("entity"); string type; if (entity is IContent) type = Constants.UdiEntityType.Document; else if (entity is IMedia) type = Constants.UdiEntityType.Media; else if (entity is IMember) type = Constants.UdiEntityType.Member; else throw new NotSupportedException(string.Format("ContentBase type {0} is not supported.", entity.GetType().FullName)); return new GuidUdi(type, entity.Key).EnsureClosed(); } /// <summary> /// Gets the entity identifier of the entity. /// </summary> /// <param name="entity">The entity.</param> /// <returns>The entity identifier of the entity.</returns> public static GuidUdi GetUdi(this IRelationType entity) { if (entity == null) throw new ArgumentNullException("entity"); return new GuidUdi(Constants.UdiEntityType.RelationType, entity.Key).EnsureClosed(); } /// <summary> /// Gets the entity identifier of the entity. /// </summary> /// <param name="entity">The entity.</param> /// <returns>The entity identifier of the entity.</returns> public static StringUdi GetUdi(this ILanguage entity) { if (entity == null) throw new ArgumentNullException("entity"); return new StringUdi(Constants.UdiEntityType.Language, entity.IsoCode).EnsureClosed(); } /// <summary> /// Gets the entity identifier of the entity. /// </summary> /// <param name="entity">The entity.</param> /// <returns>The entity identifier of the entity.</returns> public static Udi GetUdi(this IEntity entity) { if (entity == null) throw new ArgumentNullException("entity"); // entity could eg be anything implementing IThing // so we have to go through casts here var template = entity as ITemplate; if (template != null) return template.GetUdi(); var contentType = entity as IContentType; if (contentType != null) return contentType.GetUdi(); var mediaType = entity as IMediaType; if (mediaType != null) return mediaType.GetUdi(); var memberType = entity as IMemberType; if (memberType != null) return memberType.GetUdi(); var memberGroup = entity as IMemberGroup; if (memberGroup != null) return memberGroup.GetUdi(); var contentTypeComposition = entity as IContentTypeComposition; if (contentTypeComposition != null) return contentTypeComposition.GetUdi(); var dataTypeComposition = entity as IDataTypeDefinition; if (dataTypeComposition != null) return dataTypeComposition.GetUdi(); var container = entity as EntityContainer; if (container != null) return container.GetUdi(); var media = entity as IMedia; if (media != null) return media.GetUdi(); var content = entity as IContent; if (content != null) return content.GetUdi(); var member = entity as IMember; if (member != null) return member.GetUdi(); var stylesheet = entity as Stylesheet; if (stylesheet != null) return stylesheet.GetUdi(); var script = entity as Script; if (script != null) return script.GetUdi(); var dictionaryItem = entity as IDictionaryItem; if (dictionaryItem != null) return dictionaryItem.GetUdi(); var macro = entity as IMacro; if (macro != null) return macro.GetUdi(); var partialView = entity as IPartialView; if (partialView != null) return partialView.GetUdi(); var xsltFile = entity as IXsltFile; if (xsltFile != null) return xsltFile.GetUdi(); var contentBase = entity as IContentBase; if (contentBase != null) return contentBase.GetUdi(); var relationType = entity as IRelationType; if (relationType != null) return relationType.GetUdi(); var language = entity as ILanguage; if (language != null) return language.GetUdi(); throw new NotSupportedException(string.Format("Entity type {0} is not supported.", entity.GetType().FullName)); } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Apache.Ignite.Core.Tests.Binary.Serializable { using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Reflection; using System.Reflection.Emit; using System.Runtime.Serialization; using System.Xml; using Apache.Ignite.Core.Cluster; using Apache.Ignite.Core.Compute; using NUnit.Framework; /// <summary> /// Tests additional [Serializable] scenarios. /// </summary> public class AdvancedSerializationTest { /// <summary> /// Set up routine. /// </summary> [TestFixtureSetUp] public void SetUp() { Ignition.Start(TestUtils.GetTestConfiguration()); } /// <summary> /// Tear down routine. /// </summary> [TestFixtureTearDown] public void TearDown() { Ignition.StopAll(true); } /// <summary> /// Test complex file serialization. /// </summary> [Test] public void TestSerializableXmlDoc() { var grid = Ignition.GetIgnite(null); var cache = grid.GetOrCreateCache<int, SerializableXmlDoc>("cache"); var doc = new SerializableXmlDoc(); doc.LoadXml("<document><test1>val</test1><test2 attr=\"x\" /></document>"); for (var i = 0; i < 50; i++) { // Test cache cache.Put(i, doc); var resultDoc = cache.Get(i); Assert.AreEqual(doc.OuterXml, resultDoc.OuterXml); // Test task with document arg CheckTask(grid, doc); } } /// <summary> /// Checks task execution. /// </summary> /// <param name="grid">Grid.</param> /// <param name="arg">Task arg.</param> private static void CheckTask(IIgnite grid, object arg) { var jobResult = grid.GetCompute().Execute(new CombineStringsTask(), arg); var nodeCount = grid.GetCluster().GetNodes().Count; var expectedRes = CombineStringsTask.CombineStrings(Enumerable.Range(0, nodeCount).Select(x => arg.ToString())); Assert.AreEqual(expectedRes, jobResult.InnerXml); } #if !NETCOREAPP2_0 && !NETCOREAPP2_1 && !NETCOREAPP3_0 // AppDomains are not supported in .NET Core /// <summary> /// Tests custom serialization binder. /// </summary> [Test] public void TestSerializationBinder() { const int count = 50; var cache = Ignition.GetIgnite(null).GetOrCreateCache<int, object>("cache"); // Put multiple objects from multiple same-named assemblies to cache for (var i = 0; i < count; i++) { dynamic val = Activator.CreateInstance(GenerateDynamicType()); val.Id = i; val.Name = "Name_" + i; cache.Put(i, val); } // Verify correct deserialization for (var i = 0; i < count; i++) { dynamic val = cache.Get(i); Assert.AreEqual(val.Id, i); Assert.AreEqual(val.Name, "Name_" + i); } } /// <summary> /// Generates a Type in runtime, puts it into a dynamic assembly. /// </summary> /// <returns></returns> private static Type GenerateDynamicType() { var asmBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly( new AssemblyName("GridSerializationTestDynamicAssembly"), AssemblyBuilderAccess.Run); var moduleBuilder = asmBuilder.DefineDynamicModule("GridSerializationTestDynamicModule"); var typeBuilder = moduleBuilder.DefineType("GridSerializationTestDynamicType", TypeAttributes.Class | TypeAttributes.Public | TypeAttributes.Serializable); typeBuilder.DefineField("Id", typeof (int), FieldAttributes.Public); typeBuilder.DefineField("Name", typeof (string), FieldAttributes.Public); return typeBuilder.CreateType(); } #endif /// <summary> /// Tests the DataTable serialization. /// </summary> [Test] public void TestDataTable() { var dt = new DataTable("foo"); dt.Columns.Add("intCol", typeof(int)); dt.Columns.Add("stringCol", typeof(string)); dt.Rows.Add(1, "1"); dt.Rows.Add(2, "2"); var cache = Ignition.GetIgnite().GetOrCreateCache<int, DataTable>("dataTables"); cache.Put(1, dt); var res = cache.Get(1); Assert.AreEqual("foo", res.TableName); Assert.AreEqual(2, res.Columns.Count); Assert.AreEqual("intCol", res.Columns[0].ColumnName); Assert.AreEqual("stringCol", res.Columns[1].ColumnName); Assert.AreEqual(2, res.Rows.Count); Assert.AreEqual(new object[] {1, "1"}, res.Rows[0].ItemArray); Assert.AreEqual(new object[] {2, "2"}, res.Rows[1].ItemArray); } } [Serializable] [DataContract] public sealed class SerializableXmlDoc : XmlDocument, ISerializable { /// <summary> /// Default ctor. /// </summary> public SerializableXmlDoc() { // No-op } /// <summary> /// Serialization ctor. /// </summary> private SerializableXmlDoc(SerializationInfo info, StreamingContext context) { LoadXml(info.GetString("xmlDocument")); } /** <inheritdoc /> */ public void GetObjectData(SerializationInfo info, StreamingContext context) { info.AddValue("xmlDocument", OuterXml, typeof(string)); } } [Serializable] public class CombineStringsTask : IComputeTask<object, string, SerializableXmlDoc> { public IDictionary<IComputeJob<string>, IClusterNode> Map(IList<IClusterNode> subgrid, object arg) { return subgrid.ToDictionary(x => (IComputeJob<string>) new ToStringJob {Arg = arg}, x => x); } public ComputeJobResultPolicy OnResult(IComputeJobResult<string> res, IList<IComputeJobResult<string>> rcvd) { return ComputeJobResultPolicy.Wait; } public SerializableXmlDoc Reduce(IList<IComputeJobResult<string>> results) { var result = new SerializableXmlDoc(); result.LoadXml(CombineStrings(results.Select(x => x.Data))); return result; } public static string CombineStrings(IEnumerable<string> strings) { var text = string.Concat(strings.Select(x => string.Format("<val>{0}</val>", x))); return string.Format("<document>{0}</document>", text); } } [Serializable] public class ToStringJob : IComputeJob<string> { /// <summary> /// Job argument. /// </summary> public object Arg { get; set; } /** <inheritdoc /> */ public string Execute() { return Arg.ToString(); } /** <inheritdoc /> */ public void Cancel() { // No-op. } } }
// 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.Diagnostics; using System.Data.Common; using System.Xml; using System.Xml.Schema; using System.Xml.Serialization; using System.Runtime.Serialization; using System.Runtime.CompilerServices; namespace System.Data.SqlTypes { [XmlSchemaProvider("GetXsdType")] public sealed class SqlChars : INullable, IXmlSerializable, ISerializable { // -------------------------------------------------------------- // Data members // -------------------------------------------------------------- // SqlChars has five possible states // 1) SqlChars is Null // - m_stream must be null, m_lCuLen must be x_lNull // 2) SqlChars contains a valid buffer, // - m_rgchBuf must not be null, and m_stream must be null // 3) SqlChars contains a valid pointer // - m_rgchBuf could be null or not, // if not null, content is garbage, should never look into it. // - m_stream must be null. // 4) SqlChars contains a SqlStreamChars // - m_stream must not be null // - m_rgchBuf could be null or not. if not null, content is garbage, should never look into it. // - m_lCurLen must be x_lNull. // 5) SqlChars contains a Lazy Materialized Blob (ie, StorageState.Delayed) // internal char[] _rgchBuf; // Data buffer private long _lCurLen; // Current data length internal SqlStreamChars _stream; private SqlBytesCharsState _state; private char[] _rgchWorkBuf; // A 1-char work buffer. // The max data length that we support at this time. private const long x_lMaxLen = int.MaxValue; private const long x_lNull = -1L; // -------------------------------------------------------------- // Constructor(s) // -------------------------------------------------------------- // Public default constructor used for XML serialization public SqlChars() { SetNull(); } // Create a SqlChars with an in-memory buffer public SqlChars(char[] buffer) { _rgchBuf = buffer; _stream = null; if (_rgchBuf == null) { _state = SqlBytesCharsState.Null; _lCurLen = x_lNull; } else { _state = SqlBytesCharsState.Buffer; _lCurLen = _rgchBuf.Length; } _rgchWorkBuf = null; AssertValid(); } // Create a SqlChars from a SqlString public SqlChars(SqlString value) : this(value.IsNull ? null : value.Value.ToCharArray()) { } // Create a SqlChars from a SqlStreamChars internal SqlChars(SqlStreamChars s) { _rgchBuf = null; _lCurLen = x_lNull; _stream = s; _state = (s == null) ? SqlBytesCharsState.Null : SqlBytesCharsState.Stream; _rgchWorkBuf = null; AssertValid(); } // -------------------------------------------------------------- // Public properties // -------------------------------------------------------------- // INullable public bool IsNull { get { return _state == SqlBytesCharsState.Null; } } // Property: the in-memory buffer of SqlChars // Return Buffer even if SqlChars is Null. public char[] Buffer { get { if (FStream()) { CopyStreamToBuffer(); } return _rgchBuf; } } // Property: the actual length of the data public long Length { get { return _state switch { SqlBytesCharsState.Null => throw new SqlNullValueException(), SqlBytesCharsState.Stream => _stream.Length, _ => _lCurLen, }; } } // Property: the max length of the data // Return MaxLength even if SqlChars is Null. // When the buffer is also null, return -1. // If containing a Stream, return -1. public long MaxLength { get { return _state switch { SqlBytesCharsState.Stream => -1L, _ => (_rgchBuf == null) ? -1L : _rgchBuf.Length, }; } } // Property: get a copy of the data in a new char[] array. public char[] Value { get { char[] buffer; switch (_state) { case SqlBytesCharsState.Null: throw new SqlNullValueException(); case SqlBytesCharsState.Stream: if (_stream.Length > x_lMaxLen) throw new SqlTypeException(SR.SqlMisc_BufferInsufficientMessage); buffer = new char[_stream.Length]; if (_stream.Position != 0) _stream.Seek(0, SeekOrigin.Begin); _stream.Read(buffer, 0, checked((int)_stream.Length)); break; default: buffer = new char[_lCurLen]; Array.Copy(_rgchBuf, 0, buffer, 0, (int)_lCurLen); break; } return buffer; } } // class indexer public char this[long offset] { get { if (offset < 0 || offset >= Length) throw new ArgumentOutOfRangeException(nameof(offset)); if (_rgchWorkBuf == null) _rgchWorkBuf = new char[1]; Read(offset, _rgchWorkBuf, 0, 1); return _rgchWorkBuf[0]; } set { if (_rgchWorkBuf == null) _rgchWorkBuf = new char[1]; _rgchWorkBuf[0] = value; Write(offset, _rgchWorkBuf, 0, 1); } } internal SqlStreamChars Stream { get { return FStream() ? _stream : new SqlStreamChars(this); } set { _lCurLen = x_lNull; _stream = value; _state = (value == null) ? SqlBytesCharsState.Null : SqlBytesCharsState.Stream; AssertValid(); } } public StorageState Storage { get { return _state switch { SqlBytesCharsState.Null => throw new SqlNullValueException(), SqlBytesCharsState.Stream => StorageState.Stream, SqlBytesCharsState.Buffer => StorageState.Buffer, _ => StorageState.UnmanagedBuffer, }; } } // -------------------------------------------------------------- // Public methods // -------------------------------------------------------------- public void SetNull() { _lCurLen = x_lNull; _stream = null; _state = SqlBytesCharsState.Null; AssertValid(); } // Set the current length of the data // If the SqlChars is Null, setLength will make it non-Null. public void SetLength(long value) { if (value < 0) throw new ArgumentOutOfRangeException(nameof(value)); if (FStream()) { _stream.SetLength(value); } else { // If there is a buffer, even the value of SqlChars is Null, // still allow setting length to zero, which will make it not Null. // If the buffer is null, raise exception // if (null == _rgchBuf) throw new SqlTypeException(SR.SqlMisc_NoBufferMessage); if (value > _rgchBuf.Length) throw new ArgumentOutOfRangeException(nameof(value)); else if (IsNull) // At this point we know that value is small enough // Go back in buffer mode _state = SqlBytesCharsState.Buffer; _lCurLen = value; } AssertValid(); } // Read data of specified length from specified offset into a buffer public long Read(long offset, char[] buffer, int offsetInBuffer, int count) { if (IsNull) throw new SqlNullValueException(); // Validate the arguments if (buffer == null) throw new ArgumentNullException(nameof(buffer)); if (offset > Length || offset < 0) throw new ArgumentOutOfRangeException(nameof(offset)); if (offsetInBuffer > buffer.Length || offsetInBuffer < 0) throw new ArgumentOutOfRangeException(nameof(offsetInBuffer)); if (count < 0 || count > buffer.Length - offsetInBuffer) throw new ArgumentOutOfRangeException(nameof(count)); // Adjust count based on data length if (count > Length - offset) count = (int)(Length - offset); if (count != 0) { switch (_state) { case SqlBytesCharsState.Stream: if (_stream.Position != offset) _stream.Seek(offset, SeekOrigin.Begin); _stream.Read(buffer, offsetInBuffer, count); break; default: Array.Copy(_rgchBuf, offset, buffer, offsetInBuffer, count); break; } } return count; } // Write data of specified length into the SqlChars from specified offset public void Write(long offset, char[] buffer, int offsetInBuffer, int count) { if (FStream()) { if (_stream.Position != offset) _stream.Seek(offset, SeekOrigin.Begin); _stream.Write(buffer, offsetInBuffer, count); } else { // Validate the arguments if (buffer == null) throw new ArgumentNullException(nameof(buffer)); if (_rgchBuf == null) throw new SqlTypeException(SR.SqlMisc_NoBufferMessage); if (offset < 0) throw new ArgumentOutOfRangeException(nameof(offset)); if (offset > _rgchBuf.Length) throw new SqlTypeException(SR.SqlMisc_BufferInsufficientMessage); if (offsetInBuffer < 0 || offsetInBuffer > buffer.Length) throw new ArgumentOutOfRangeException(nameof(offsetInBuffer)); if (count < 0 || count > buffer.Length - offsetInBuffer) throw new ArgumentOutOfRangeException(nameof(count)); if (count > _rgchBuf.Length - offset) throw new SqlTypeException(SR.SqlMisc_BufferInsufficientMessage); if (IsNull) { // If NULL and there is buffer inside, we only allow writing from // offset zero. // if (offset != 0) throw new SqlTypeException(SR.SqlMisc_WriteNonZeroOffsetOnNullMessage); // treat as if our current length is zero. // Note this has to be done after all inputs are validated, so that // we won't throw exception after this point. // _lCurLen = 0; _state = SqlBytesCharsState.Buffer; } else if (offset > _lCurLen) { // Don't allow writing from an offset that this larger than current length. // It would leave uninitialized data in the buffer. // throw new SqlTypeException(SR.SqlMisc_WriteOffsetLargerThanLenMessage); } if (count != 0) { Array.Copy(buffer, offsetInBuffer, _rgchBuf, offset, count); // If the last position that has been written is after // the current data length, reset the length if (_lCurLen < offset + count) _lCurLen = offset + count; } } AssertValid(); } public SqlString ToSqlString() { return IsNull ? SqlString.Null : new string(Value); } // -------------------------------------------------------------- // Conversion operators // -------------------------------------------------------------- // Alternative method: ToSqlString() public static explicit operator SqlString(SqlChars value) { return value.ToSqlString(); } // Alternative method: constructor SqlChars(SqlString) public static explicit operator SqlChars(SqlString value) { return new SqlChars(value); } // -------------------------------------------------------------- // Private utility functions // -------------------------------------------------------------- [Conditional("DEBUG")] private void AssertValid() { Debug.Assert(_state >= SqlBytesCharsState.Null && _state <= SqlBytesCharsState.Stream); if (IsNull) { } else { Debug.Assert((_lCurLen >= 0 && _lCurLen <= x_lMaxLen) || FStream()); Debug.Assert(FStream() || (_rgchBuf != null && _lCurLen <= _rgchBuf.Length)); Debug.Assert(!FStream() || (_lCurLen == x_lNull)); } Debug.Assert(_rgchWorkBuf == null || _rgchWorkBuf.Length == 1); } // whether the SqlChars contains a Stream internal bool FStream() { return _state == SqlBytesCharsState.Stream; } // Copy the data from the Stream to the array buffer. // If the SqlChars doesn't hold a buffer or the buffer // is not big enough, allocate new char array. private void CopyStreamToBuffer() { Debug.Assert(FStream()); long lStreamLen = _stream.Length; if (lStreamLen >= x_lMaxLen) throw new SqlTypeException(SR.SqlMisc_BufferInsufficientMessage); if (_rgchBuf == null || _rgchBuf.Length < lStreamLen) _rgchBuf = new char[lStreamLen]; if (_stream.Position != 0) _stream.Seek(0, SeekOrigin.Begin); _stream.Read(_rgchBuf, 0, (int)lStreamLen); _stream = null; _lCurLen = lStreamLen; _state = SqlBytesCharsState.Buffer; AssertValid(); } private void SetBuffer(char[] buffer) { _rgchBuf = buffer; _lCurLen = (_rgchBuf == null) ? x_lNull : _rgchBuf.Length; _stream = null; _state = (_rgchBuf == null) ? SqlBytesCharsState.Null : SqlBytesCharsState.Buffer; AssertValid(); } // -------------------------------------------------------------- // XML Serialization // -------------------------------------------------------------- XmlSchema IXmlSerializable.GetSchema() { return null; } void IXmlSerializable.ReadXml(XmlReader r) { char[] value = null; string isNull = r.GetAttribute("nil", XmlSchema.InstanceNamespace); if (isNull != null && XmlConvert.ToBoolean(isNull)) { // Read the next value. r.ReadElementString(); SetNull(); } else { value = r.ReadElementString().ToCharArray(); SetBuffer(value); } } void IXmlSerializable.WriteXml(XmlWriter writer) { if (IsNull) { writer.WriteAttributeString("xsi", "nil", XmlSchema.InstanceNamespace, "true"); } else { char[] value = Buffer; writer.WriteString(new string(value, 0, (int)(Length))); } } public static XmlQualifiedName GetXsdType(XmlSchemaSet schemaSet) { return new XmlQualifiedName("string", XmlSchema.Namespace); } // -------------------------------------------------------------- // Serialization using ISerializable // -------------------------------------------------------------- // State information is not saved. The current state is converted to Buffer and only the underlying // array is serialized, except for Null, in which case this state is kept. void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { throw new PlatformNotSupportedException(); } // -------------------------------------------------------------- // Static fields, properties // -------------------------------------------------------------- // Get a Null instance. // Since SqlChars is mutable, have to be property and create a new one each time. public static SqlChars Null { get { return new SqlChars((char[])null); } } } // class SqlChars // SqlStreamChars is a stream build on top of SqlChars, and // provides the Stream interface. The purpose is to help users // to read/write SqlChars object. internal sealed class SqlStreamChars { // -------------------------------------------------------------- // Data members // -------------------------------------------------------------- private readonly SqlChars _sqlchars; // the SqlChars object private long _lPosition; // -------------------------------------------------------------- // Constructor(s) // -------------------------------------------------------------- internal SqlStreamChars(SqlChars s) { _sqlchars = s; _lPosition = 0; } // -------------------------------------------------------------- // Public properties // -------------------------------------------------------------- public long Length { get { CheckIfStreamClosed("get_Length"); return _sqlchars.Length; } } public long Position { get { CheckIfStreamClosed("get_Position"); return _lPosition; } set { CheckIfStreamClosed("set_Position"); if (value < 0 || value > _sqlchars.Length) throw new ArgumentOutOfRangeException(nameof(value)); else _lPosition = value; } } // -------------------------------------------------------------- // Public methods // -------------------------------------------------------------- public long Seek(long offset, SeekOrigin origin) { CheckIfStreamClosed(); long lPosition = 0; switch (origin) { case SeekOrigin.Begin: if (offset < 0 || offset > _sqlchars.Length) throw ADP.ArgumentOutOfRange(nameof(offset)); _lPosition = offset; break; case SeekOrigin.Current: lPosition = _lPosition + offset; if (lPosition < 0 || lPosition > _sqlchars.Length) throw ADP.ArgumentOutOfRange(nameof(offset)); _lPosition = lPosition; break; case SeekOrigin.End: lPosition = _sqlchars.Length + offset; if (lPosition < 0 || lPosition > _sqlchars.Length) throw ADP.ArgumentOutOfRange(nameof(offset)); _lPosition = lPosition; break; default: throw ADP.ArgumentOutOfRange(nameof(offset)); } return _lPosition; } // The Read/Write/Readchar/Writechar simply delegates to SqlChars public int Read(char[] buffer, int offset, int count) { CheckIfStreamClosed(); if (buffer == null) throw new ArgumentNullException(nameof(buffer)); if (offset < 0 || offset > buffer.Length) throw new ArgumentOutOfRangeException(nameof(offset)); if (count < 0 || count > buffer.Length - offset) throw new ArgumentOutOfRangeException(nameof(count)); int icharsRead = (int)_sqlchars.Read(_lPosition, buffer, offset, count); _lPosition += icharsRead; return icharsRead; } public void Write(char[] buffer, int offset, int count) { CheckIfStreamClosed(); if (buffer == null) throw new ArgumentNullException(nameof(buffer)); if (offset < 0 || offset > buffer.Length) throw new ArgumentOutOfRangeException(nameof(offset)); if (count < 0 || count > buffer.Length - offset) throw new ArgumentOutOfRangeException(nameof(count)); _sqlchars.Write(_lPosition, buffer, offset, count); _lPosition += count; } public void SetLength(long value) { CheckIfStreamClosed(); _sqlchars.SetLength(value); if (_lPosition > value) _lPosition = value; } // -------------------------------------------------------------- // Private utility functions // -------------------------------------------------------------- private bool FClosed() { return _sqlchars == null; } private void CheckIfStreamClosed([CallerMemberName] string methodname = "") { if (FClosed()) throw ADP.StreamClosed(methodname); } } // class SqlStreamChars } // namespace System.Data.SqlTypes
/* ==================================================================== Copyright (C) 2004-2008 fyiReporting Software, LLC Copyright (C) 2011 Peter Gill <peter@majorsilence.com> This file is part of the fyiReporting RDL project. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. For additional information, email info@fyireporting.com or visit the website www.fyiReporting.com. */ using System; using System.Xml; using System.Data; using System.Collections; #if !NETSTANDARD2_0 using System.Web.Services; using System.Web.Services.Description; using System.Web.Services.Protocols; #endif using System.CodeDom; using System.CodeDom.Compiler; using System.Text; using System.Reflection; using System.IO; using System.Net; using Microsoft.CSharp; namespace fyiReporting.Data { /// <summary> /// WebServiceWsdl handles generation and caching of Assemblies containing WSDL proxies /// It also will invoke proxies with the proper arguments. These arguments must be /// provided as a WebServiceParameter. /// </summary> public class WebServiceWsdl { // Cache the compiled assemblies const string _Namespace = "fyireporting.ws"; static Hashtable _cache = Hashtable.Synchronized(new Hashtable()); string _url; // url for this assembly Assembly _WsdlAssembly; // Assembly ready for invokation static internal WebServiceWsdl GetWebServiceWsdl(string url) { WebServiceWsdl w = _cache[url] as WebServiceWsdl; if (w != null) return w; return new WebServiceWsdl(url); } static public void ClearCache() { _cache.Clear(); } public MethodInfo GetMethodInfo(string service, string operation) { // Create an instance of the service object proxy object o = _WsdlAssembly.CreateInstance(_Namespace + "." + service, false); if (o == null) throw new Exception(string.Format("Unable to create instance of service '{0}'.", service)); // Get information about the method MethodInfo mi = o.GetType().GetMethod(operation); if (mi == null) throw new Exception(string.Format("Unable to find operation '{0}' in service '{1}'.", operation, service)); return mi; } // Invoke the operation for the requested service public object Invoke(string service, string operation, DataParameterCollection dpc, int timeout) { // Create an instance of the service object proxy object o = _WsdlAssembly.CreateInstance(_Namespace + "." + service, false); if (o == null) throw new Exception(string.Format("Unable to create instance of service '{0}'.", service)); // Get information about the method MethodInfo mi = o.GetType().GetMethod(operation); if (mi == null) throw new Exception(string.Format("Unable to find operation '{0}' in service '{1}'.", operation, service)); // Go thru the parameters building up an object array with the proper parameters ParameterInfo[] pis = mi.GetParameters(); object[] args = new object[pis.Length]; int ai=0; foreach (ParameterInfo pi in pis) { BaseDataParameter dp = dpc[pi.Name] as BaseDataParameter; if (dp == null) // retry with '@' in front! dp = dpc["@"+pi.Name] as BaseDataParameter; if (dp == null || dp.Value == null) args[ai] = null; else if (pi.ParameterType == dp.Value.GetType()) args[ai] = dp.Value; else // we need to do conversion args[ai] = Convert.ChangeType(dp.Value, pi.ParameterType); ai++; } #if !NETSTANDARD2_0 SoapHttpClientProtocol so = o as SoapHttpClientProtocol; if (so != null && timeout != 0) so.Timeout = timeout; return mi.Invoke(o, args); #else throw new NotImplementedException("Some classes are not available on .NET STANDARD"); #endif } // constructor private WebServiceWsdl(string url) { _url = url; _WsdlAssembly = GetAssembly(); _cache.Add(url, this); } private Assembly GetAssembly() { #if !NETSTANDARD2_0 ServiceDescription sd = GetServiceDescription(); // ServiceDescriptionImporter provide means for generating client proxy classes for XML Web services CodeNamespace cns = new CodeNamespace(_Namespace); ServiceDescriptionImporter sdi = new ServiceDescriptionImporter(); sdi.AddServiceDescription(sd, null, null); sdi.ProtocolName = "Soap"; sdi.Import(cns, null); // Generate the proxy source code CSharpCodeProvider cscp = new CSharpCodeProvider(); StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); cscp.GenerateCodeFromNamespace(cns, sw, null); string proxy = sb.ToString(); sw.Close(); // debug code !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // StreamWriter tsw = File.CreateText(@"c:\temp\proxy.cs"); // tsw.Write(proxy); // tsw.Close(); // debug code !!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // Create Assembly CompilerParameters cp = new CompilerParameters(); cp.ReferencedAssemblies.Add("System.dll"); cp.ReferencedAssemblies.Add("System.Xml.dll"); cp.ReferencedAssemblies.Add("System.Web.Services.dll"); cp.GenerateExecutable = false; cp.GenerateInMemory = false; // just loading into memory causes problems when instantiating cp.IncludeDebugInformation = false; CompilerResults cr = cscp.CompileAssemblyFromSource(cp, proxy); if(cr.Errors.Count > 0) { StringBuilder err = new StringBuilder(string.Format("WSDL proxy compile has {0} error(s).", cr.Errors.Count)); foreach (CompilerError ce in cr.Errors) { err.AppendFormat("\r\n{0} {1}", ce.ErrorNumber, ce.ErrorText); } throw new Exception(err.ToString()); } return Assembly.LoadFrom(cr.PathToAssembly); // We need an assembly loaded from the file system // or instantiation of object complains #else throw new NotImplementedException("Some classes are missing on .NET STANDARD"); #endif } #if !NETSTANDARD2_0 public ServiceDescription GetServiceDescription() { ServiceDescription sd = new ServiceDescription(); Stream sr=null; try { sr = GetStream(); sd = ServiceDescription.Read(sr); } finally { if (sr != null) sr.Close(); } return sd; } #endif Stream GetStream() { string fname = _url; Stream strm=null; if (fname.StartsWith("http:") || fname.StartsWith("file:") || fname.StartsWith("https:")) { WebRequest wreq = WebRequest.Create(fname); WebResponse wres = wreq.GetResponse(); strm = wres.GetResponseStream(); } else strm = new FileStream(fname, System.IO.FileMode.Open, FileAccess.Read); return strm; } } }
// Copyright (c) MOSA Project. Licensed under the New BSD License. using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; namespace Mosa.Compiler.Framework.Analysis { /// <summary> /// The Loop Aware Block Ordering reorders blocks to optimize loops and reduce the distance of jumps and branches. /// </summary> public sealed class LoopAwareBlockOrder : IBlockOrderAnalysis { #region Data members private BasicBlocks basicBlocks; private BitArray active; private BitArray visited; private BitArray loopHeader; private List<BasicBlock> loopEnds; private int loopCount; private int[] forwardBranchesCount; private int[] loopBlockIndex; private BitArray loopMap; private int blockCount; private int[] loopDepth; private int[] loopIndex; private BasicBlock[] blockOrder; private HashSet<BasicBlock> orderSet; private int orderIndex; #endregion Data members #region Priority class /// <summary> /// /// </summary> private class Priority : IComparable<Priority> { public int Depth; public int Order; /// <summary> /// Initializes a new instance of the <see cref="Priority" /> class. /// </summary> /// <param name="depth">The depth.</param> /// <param name="order">The order.</param> public Priority(int depth, int order) { Depth = depth; Order = order; } /// <summary> /// Compares the current object with another object of the same type. /// </summary> /// <param name="other">An object to compare with this object.</param> /// <returns> /// A 32-bit signed integer that indicates the relative order of the objects being compared. The return value has the following meanings: /// Value /// Meaning /// Less than zero /// This object is less than the <paramref name="other"/> parameter. /// Zero /// This object is equal to <paramref name="other"/>. /// Greater than zero /// This object is greater than <paramref name="other"/>. /// </returns> public int CompareTo(Priority other) { if (Depth > other.Depth) return 1; if (Depth < other.Depth) return -1; if (Order < other.Order) return 1; if (Order > other.Order) return -1; return 0; } } #endregion Priority class /// <summary> /// Initializes a new instance of the <see cref="LoopAwareBlockOrder"/> class. /// </summary> public LoopAwareBlockOrder() { } /// <summary> /// Initializes a new instance of the <see cref="LoopAwareBlockOrder"/> class. /// </summary> /// <param name="basicBlocks">The basic blocks.</param> public LoopAwareBlockOrder(BasicBlocks basicBlocks) { PerformAnalysis(basicBlocks); } #region IBlockOrderAnalysis public IList<BasicBlock> NewBlockOrder { get { return blockOrder; } } public int GetLoopDepth(BasicBlock block) { return loopDepth[block.Sequence]; } public int GetLoopIndex(BasicBlock block) { return loopIndex[block.Sequence]; } public void PerformAnalysis(BasicBlocks basicBlocks) { this.basicBlocks = basicBlocks; blockCount = basicBlocks.Count; loopEnds = new List<BasicBlock>(); loopCount = 0; loopHeader = new BitArray(blockCount, false); forwardBranchesCount = new int[blockCount]; loopBlockIndex = new int[blockCount]; loopDepth = new int[blockCount]; loopIndex = new int[blockCount]; blockOrder = new BasicBlock[blockCount]; orderIndex = 0; orderSet = new HashSet<BasicBlock>(); foreach (var head in basicBlocks.HeadBlocks) { Start(head); } loopHeader = null; loopEnds = null; loopHeader = null; loopBlockIndex = null; forwardBranchesCount = null; orderSet = null; } #endregion IBlockOrderAnalysis #region Members /// <summary> /// Determines the loop depths. /// </summary> private void Start(BasicBlock start) { StartCountEdges(start); loopMap = new BitArray(loopCount * blockCount, false); MarkLoops(); AssignLoopDepth(start); ComputeOrder(start); } private void StartCountEdges(BasicBlock start) { active = new BitArray(blockCount, false); visited = new BitArray(blockCount, false); CountEdges(start, null); } private void CountEdges(BasicBlock current, BasicBlock parent) { int blockId = current.Sequence; if (active.Get(blockId)) { Debug.Assert(visited.Get(blockId)); Debug.Assert(parent != null); loopHeader.Set(blockId, true); loopEnds.Add(parent); return; } forwardBranchesCount[blockId]++; if (visited.Get(blockId)) return; visited.Set(blockId, true); active.Set(blockId, true); foreach (var next in current.NextBlocks) { CountEdges(next, current); } Debug.Assert(active.Get(blockId)); active.Set(blockId, false); if (loopHeader.Get(blockId)) { loopBlockIndex[blockId] = loopCount; loopCount++; } } #region Helpers private void SetLoopMap(int l, BasicBlock b) { loopMap.Set((l * blockCount) + b.Sequence, true); } private bool GetLoopMap(int l, BasicBlock b) { return loopMap.Get((l * blockCount) + b.Sequence); } #endregion Helpers private void MarkLoops() { if (loopCount == 0) return; var worklist = new Stack<BasicBlock>(); foreach (var loopEnd in loopEnds) { var loopStart = loopEnd.NextBlocks[0]; // assuming the first one? int loopStartIndex = loopBlockIndex[loopStart.Sequence]; worklist.Push(loopEnd); SetLoopMap(loopStartIndex, loopEnd); while (worklist.Count != 0) { var current = worklist.Pop(); if (current == loopStart) continue; foreach (var previous in current.PreviousBlocks) { if (!GetLoopMap(loopStartIndex, previous)) { worklist.Push(previous); SetLoopMap(loopStartIndex, previous); } } } } } private void AssignLoopDepth(BasicBlock start) { visited = new BitArray(blockCount, false); var worklist = new Stack<BasicBlock>(); worklist.Push(start); while (worklist.Count != 0) { var current = worklist.Pop(); if (!visited.Get(current.Sequence)) { visited.Set(current.Sequence, true); int currentLoopDepth = 0; int minLoopIndex = -1; for (int i = loopCount - 1; i >= 0; i--) { if (GetLoopMap(i, current)) { currentLoopDepth++; minLoopIndex = i; } } loopDepth[current.Sequence] = currentLoopDepth; loopIndex[current.Sequence] = minLoopIndex; foreach (var next in current.NextBlocks) { worklist.Push(next); } } } } private void ComputeOrder(BasicBlock start) { // Create sorted worklist var workList = new SortedList<Priority, BasicBlock>(); // Start worklist with first block workList.Add(new Priority(0, 0), start); while (workList.Count != 0) { var block = workList.Values[workList.Count - 1]; workList.RemoveAt(workList.Count - 1); if (orderSet.Contains(block)) continue; orderSet.Add(block); blockOrder[orderIndex++] = block; foreach (var successor in block.NextBlocks) { forwardBranchesCount[successor.Sequence]--; if (forwardBranchesCount[successor.Sequence] == 0) { workList.Add(new Priority(loopDepth[successor.Sequence], successor.Sequence), successor); } } } } #endregion Members } }
//The MIT License (MIT) // //Copyright (c) 2014 Andrew Leap // //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 UnityEngine; using System.Linq; using System.Collections.Generic; using System.Text; using System.Reflection; namespace DebRefund { [KSPAddon(KSPAddon.Startup.SpaceCentre, true)] public class DebRefundManager : MonoBehaviour { public bool check = false; public void Awake() { DontDestroyOnLoad(this); print("DebRefund v" + Assembly.GetExecutingAssembly().GetName().Version.ToString(3) + "Awake"); GameEvents.onVesselDestroy.Add(this.onVesselDestroy); } public void Update() { if (Settings.Instance.UpdateCheck && !check && MessageSystem.Ready) { check = true; KSVersionCheck.Check.CheckVersion(57, latest => { if (latest.friendly_version != Assembly.GetExecutingAssembly().GetName().Version.ToString(3)) { MessageSystem.Instance.AddMessage(new MessageSystem.Message( "New DebRefund Version", "There is a new DebRefund Version Available\nCurrent Version: " + Assembly.GetExecutingAssembly().GetName().Version.ToString(3) + "\nNew Version: " + latest.friendly_version + "\nChanges:\n" + latest.changelog + "\nGo to http://beta.kerbalstuff.com/mod/57 to download", MessageSystemButton.MessageButtonColor.ORANGE, MessageSystemButton.ButtonIcons.ALERT )); } }); } } public void OnDestroy() { print("DebRefund Destroy"); GameEvents.onVesselDestroy.Remove(this.onVesselDestroy); } public void onVesselDestroy(Vessel v) { print("DebRefund Vessel Destroyed"); if (HighLogic.CurrentGame.Mode != Game.Modes.CAREER) { return; } if (!v.mainBody.bodyName.Contains("Kerbin")) { return; } if (!v.packed) { return; } if (v.state != Vessel.State.DEAD) { return; } if ((FlightGlobals.getAltitudeAtPos(v.transform.position, v.mainBody)) <= 0.01) { return; } bool Ignored = true; bool nonAtmoKill = false; if (FlightGlobals.ActiveVessel != null) { Vector3d activePos = FlightGlobals.ActiveVessel.GetWorldPos3D(); Vector3d pos = v.GetWorldPos3D(); if ((activePos - pos).magnitude < 2000) { nonAtmoKill = true; } } if (!HighLogic.LoadedSceneIsEditor && !v.isActiveVessel && (v.situation == Vessel.Situations.FLYING || v.situation == Vessel.Situations.SUB_ORBITAL) && (v.mainBody.GetAltitude(v.CoM) - (v.terrainAltitude < 0 ? 0 : v.terrainAltitude) > 10) && !nonAtmoKill) { bool RealChutes = AssemblyLoader.loadedAssemblies.Any(a => a.name.Contains("RealChute")); object MatLibraryInstance = null; Type matLibraryType = null; System.Reflection.MethodInfo matMethod = null; System.Reflection.PropertyInfo matDragProp = null; if (RealChutes) { matLibraryType = AssemblyLoader.loadedAssemblies .SelectMany(a => a.assembly.GetExportedTypes()) .SingleOrDefault(t => t.FullName == "RealChute.Libraries.MaterialsLibrary"); matMethod = matLibraryType.GetMethod("GetMaterial", new Type[] { typeof(string) }); MatLibraryInstance = matLibraryType.GetProperty("instance").GetValue(null, null); Type matDefType = AssemblyLoader.loadedAssemblies .SelectMany(a => a.assembly.GetExportedTypes()) .SingleOrDefault(t => t.FullName == "RealChute.Libraries.MaterialDefinition"); matDragProp = matDefType.GetProperty("dragCoefficient"); } float drag = 0; float mass = 0; float cost = 0; Dictionary<string, float> Resources = new Dictionary<string, float>(); Dictionary<string, float> ResourceCosts = new Dictionary<string, float>(); Dictionary<string, int> Parts = new Dictionary<string, int>(); Dictionary<string, float> PartCosts = new Dictionary<string, float>(); foreach (ProtoPartSnapshot p in v.protoVessel.protoPartSnapshots) { if (Ignored && !Settings.Instance.IgnoredParts.Contains(p.partName)) { Ignored = false; } mass += p.mass; float dryCost; float fuelCost; bool RealChute = false; ShipConstruction.GetPartCosts(p, p.partInfo, out dryCost, out fuelCost); cost += dryCost; if (!PartCosts.ContainsKey(p.partInfo.title)) { PartCosts.Add(p.partInfo.title, dryCost); Parts.Add(p.partInfo.title, 0); } Parts[p.partInfo.title] += 1; ProtoPartModuleSnapshot pm = p.modules.FirstOrDefault(pms => pms.moduleName == "RealChuteModule"); if (pm != null) { RealChute = true; ConfigNode[] parachutes = pm.moduleValues.GetNodes("PARACHUTE"); foreach (ConfigNode chute in parachutes) { if (float.Parse(chute.GetValue("cutAlt")) < 0) { float d = float.Parse(chute.GetValue("deployedDiameter")); float area = Mathf.PI * Mathf.Pow(d / 2, 2); string mat = chute.GetValue("material"); object matObj = matMethod.Invoke(MatLibraryInstance, new object[] { mat }); float dragC = (float)matDragProp.GetValue(matObj, null); drag += dragC * area * (1/16198.8680f); } } } pm = p.modules.FirstOrDefault(pms => pms.moduleName == "ModuleParachute"); if (pm != null && !RealChute) { ModuleParachute mp = (ModuleParachute)pm.moduleRef; drag += mp.fullyDeployedDrag * p.mass * (1/2317.4596f); } foreach (ProtoPartResourceSnapshot pr in p.resources) { if (pr.resourceValues.HasValue("amount")) { PartResourceDefinition prd = PartResourceLibrary.Instance.resourceDefinitions[pr.resourceName]; float amt = float.Parse(pr.resourceValues.GetValue("amount")); cost += (float)amt * prd.unitCost; mass += (float)amt * prd.density; if (!ResourceCosts.ContainsKey(pr.resourceName)) { ResourceCosts.Add(pr.resourceName, prd.unitCost); Resources.Add(pr.resourceName, 0); } Resources[pr.resourceName] += amt; } } } print("DebRefund: " + drag + " " + mass); if (Ignored) { print("DebRefund: Vessel Ignored"); return; } StringBuilder partlist = new StringBuilder(); partlist.AppendLine("Parts:"); foreach (var kvp in Parts) { partlist.AppendFormat("{0} x {1} @ {2} = {3}", kvp.Value, kvp.Key, PartCosts[kvp.Key], PartCosts[kvp.Key] * kvp.Value); partlist.AppendLine(); } if (Resources.Any(r => r.Value > 0)) { partlist.AppendLine("Resources:"); foreach (var kvp in Resources.Where(r => r.Value > 0)) { partlist.AppendFormat("{0} x {1} @ {2} = {3}", kvp.Value, kvp.Key, ResourceCosts[kvp.Key], ResourceCosts[kvp.Key] * kvp.Value); partlist.AppendLine(); } } float TouchDown = 100; if (drag > 0) { TouchDown = Mathf.Sqrt(mass / drag); } if (TouchDown < Settings.Instance.MinimumSpeedYellow) { List<String> crew = RecoverKerbals(v); float recFactor = CalculateRecoveryFactor(v); if (TouchDown < Settings.Instance.MinimumSpeedGreen) { float Science = RecoverScience(v, 0.95f); StringBuilder Message = new StringBuilder(); Message.AppendLine("Debris was landed safely at " + TouchDown.ToString("N2") + "m/s"); Message.Append(partlist.ToString()); Message.AppendFormat("{0} refunded({1:P2})", recFactor * cost, recFactor); Message.AppendLine(); Message.AppendFormat("Science Recovered: {0}(95%)", Science); Message.AppendLine(); foreach (string member in crew) { Message.AppendLine(member + " Recovered"); } Funding.Instance.AddFunds(recFactor * cost, TransactionReasons.VesselRecovery); MessageSystem.Message m = new MessageSystem.Message( "Debris landed safely", Message.ToString(), MessageSystemButton.MessageButtonColor.GREEN, MessageSystemButton.ButtonIcons.MESSAGE); MessageSystem.Instance.AddMessage(m); } else { float damageFactor = Mathf.Lerp(Settings.Instance.YellowMaxPercent / 100, Settings.Instance.YellowMinPercent / 100, Mathf.InverseLerp(Settings.Instance.MinimumSpeedYellow, Settings.Instance.MinimumSpeedGreen, drag)); float Science = RecoverScience(v, damageFactor); StringBuilder Message = new StringBuilder(); Message.AppendLine("Debris was landed at " + TouchDown.ToString("N2") + "m/s"); Message.Append(partlist.ToString()); Message.AppendFormat("{0} refunded({1:P2})", recFactor * cost * damageFactor, recFactor * damageFactor); Funding.Instance.AddFunds(recFactor * cost * damageFactor, TransactionReasons.VesselRecovery); Message.AppendLine(); Message.AppendFormat("Science Recovered: {0}({1:P2})", Science, damageFactor); Message.AppendLine(); foreach (string member in crew) { Message.AppendLine(member + " Recovered"); } MessageSystem.Message m = new MessageSystem.Message( "Debris landed", Message.ToString(), MessageSystemButton.MessageButtonColor.YELLOW, MessageSystemButton.ButtonIcons.ALERT); MessageSystem.Instance.AddMessage(m); } } else { StringBuilder Message = new StringBuilder(); Message.AppendLine("Debris hit hard at " + TouchDown.ToString("N2") + "m/s, nothing to be salvaged"); Message.Append(partlist.ToString()); MessageSystem.Message m = new MessageSystem.Message( "Debris hit HARD", Message.ToString(), MessageSystemButton.MessageButtonColor.RED, MessageSystemButton.ButtonIcons.ALERT); MessageSystem.Instance.AddMessage(m); } } } public List<String> RecoverKerbals(Vessel v) { List<String> crew = new List<string>(); if (v.protoVessel != null) { foreach (ProtoCrewMember pcm in v.protoVessel.GetVesselCrew()) { pcm.rosterStatus = ProtoCrewMember.RosterStatus.Available; crew.Add(pcm.KerbalRef.crewMemberName); } } return crew; } public float RecoverScience(Vessel v, float Damage) { float SciRecovered = 0f; foreach (ProtoPartSnapshot p in v.protoVessel.protoPartSnapshots) { foreach (ProtoPartModuleSnapshot pm in p.modules) { foreach (ConfigNode sciNode in pm.moduleValues.GetNodes("ScienceData")) { ScienceData sci = new ScienceData(sciNode); ScienceSubject sciSub = ResearchAndDevelopment.GetSubjectByID(sci.subjectID); SciRecovered += ResearchAndDevelopment.Instance.SubmitScienceData(sci.dataAmount, sciSub, Damage); } } } return SciRecovered; } public float CalculateRecoveryFactor(Vessel v) { var cb = SpaceCenter.Instance.cb; double dist = SpaceCenter.Instance.GreatCircleDistance(cb.GetRelSurfaceNVector(v.latitude, v.longitude)); double max = cb.Radius * Math.PI; return Mathf.Lerp(0.98f * (Settings.Instance.SafeRecoveryPercent/100), 0.1f * (Settings.Instance.SafeRecoveryPercent/100), (float)(dist / max)); } } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! namespace Google.Cloud.Dialogflow.Cx.V3.Snippets { using Google.Api.Gax; using Google.Api.Gax.ResourceNames; using Google.LongRunning; using Google.Protobuf.WellKnownTypes; using System; using System.Linq; using System.Threading.Tasks; /// <summary>Generated snippets.</summary> public sealed class GeneratedAgentsClientSnippets { /// <summary>Snippet for ListAgents</summary> public void ListAgentsRequestObject() { // Snippet: ListAgents(ListAgentsRequest, CallSettings) // Create client AgentsClient agentsClient = AgentsClient.Create(); // Initialize request argument(s) ListAgentsRequest request = new ListAgentsRequest { ParentAsLocationName = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), }; // Make the request PagedEnumerable<ListAgentsResponse, Agent> response = agentsClient.ListAgents(request); // Iterate over all response items, lazily performing RPCs as required foreach (Agent 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 (ListAgentsResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Agent 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<Agent> 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 (Agent 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 ListAgentsAsync</summary> public async Task ListAgentsRequestObjectAsync() { // Snippet: ListAgentsAsync(ListAgentsRequest, CallSettings) // Create client AgentsClient agentsClient = await AgentsClient.CreateAsync(); // Initialize request argument(s) ListAgentsRequest request = new ListAgentsRequest { ParentAsLocationName = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), }; // Make the request PagedAsyncEnumerable<ListAgentsResponse, Agent> response = agentsClient.ListAgentsAsync(request); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((Agent 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((ListAgentsResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Agent 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<Agent> 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 (Agent 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 ListAgents</summary> public void ListAgents() { // Snippet: ListAgents(string, string, int?, CallSettings) // Create client AgentsClient agentsClient = AgentsClient.Create(); // Initialize request argument(s) string parent = "projects/[PROJECT]/locations/[LOCATION]"; // Make the request PagedEnumerable<ListAgentsResponse, Agent> response = agentsClient.ListAgents(parent); // Iterate over all response items, lazily performing RPCs as required foreach (Agent 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 (ListAgentsResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Agent 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<Agent> 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 (Agent 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 ListAgentsAsync</summary> public async Task ListAgentsAsync() { // Snippet: ListAgentsAsync(string, string, int?, CallSettings) // Create client AgentsClient agentsClient = await AgentsClient.CreateAsync(); // Initialize request argument(s) string parent = "projects/[PROJECT]/locations/[LOCATION]"; // Make the request PagedAsyncEnumerable<ListAgentsResponse, Agent> response = agentsClient.ListAgentsAsync(parent); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((Agent 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((ListAgentsResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Agent 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<Agent> 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 (Agent 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 ListAgents</summary> public void ListAgentsResourceNames() { // Snippet: ListAgents(LocationName, string, int?, CallSettings) // Create client AgentsClient agentsClient = AgentsClient.Create(); // Initialize request argument(s) LocationName parent = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"); // Make the request PagedEnumerable<ListAgentsResponse, Agent> response = agentsClient.ListAgents(parent); // Iterate over all response items, lazily performing RPCs as required foreach (Agent 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 (ListAgentsResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Agent 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<Agent> 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 (Agent 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 ListAgentsAsync</summary> public async Task ListAgentsResourceNamesAsync() { // Snippet: ListAgentsAsync(LocationName, string, int?, CallSettings) // Create client AgentsClient agentsClient = await AgentsClient.CreateAsync(); // Initialize request argument(s) LocationName parent = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"); // Make the request PagedAsyncEnumerable<ListAgentsResponse, Agent> response = agentsClient.ListAgentsAsync(parent); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((Agent 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((ListAgentsResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Agent 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<Agent> 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 (Agent 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 GetAgent</summary> public void GetAgentRequestObject() { // Snippet: GetAgent(GetAgentRequest, CallSettings) // Create client AgentsClient agentsClient = AgentsClient.Create(); // Initialize request argument(s) GetAgentRequest request = new GetAgentRequest { AgentName = AgentName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]"), }; // Make the request Agent response = agentsClient.GetAgent(request); // End snippet } /// <summary>Snippet for GetAgentAsync</summary> public async Task GetAgentRequestObjectAsync() { // Snippet: GetAgentAsync(GetAgentRequest, CallSettings) // Additional: GetAgentAsync(GetAgentRequest, CancellationToken) // Create client AgentsClient agentsClient = await AgentsClient.CreateAsync(); // Initialize request argument(s) GetAgentRequest request = new GetAgentRequest { AgentName = AgentName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]"), }; // Make the request Agent response = await agentsClient.GetAgentAsync(request); // End snippet } /// <summary>Snippet for GetAgent</summary> public void GetAgent() { // Snippet: GetAgent(string, CallSettings) // Create client AgentsClient agentsClient = AgentsClient.Create(); // Initialize request argument(s) string name = "projects/[PROJECT]/locations/[LOCATION]/agents/[AGENT]"; // Make the request Agent response = agentsClient.GetAgent(name); // End snippet } /// <summary>Snippet for GetAgentAsync</summary> public async Task GetAgentAsync() { // Snippet: GetAgentAsync(string, CallSettings) // Additional: GetAgentAsync(string, CancellationToken) // Create client AgentsClient agentsClient = await AgentsClient.CreateAsync(); // Initialize request argument(s) string name = "projects/[PROJECT]/locations/[LOCATION]/agents/[AGENT]"; // Make the request Agent response = await agentsClient.GetAgentAsync(name); // End snippet } /// <summary>Snippet for GetAgent</summary> public void GetAgentResourceNames() { // Snippet: GetAgent(AgentName, CallSettings) // Create client AgentsClient agentsClient = AgentsClient.Create(); // Initialize request argument(s) AgentName name = AgentName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]"); // Make the request Agent response = agentsClient.GetAgent(name); // End snippet } /// <summary>Snippet for GetAgentAsync</summary> public async Task GetAgentResourceNamesAsync() { // Snippet: GetAgentAsync(AgentName, CallSettings) // Additional: GetAgentAsync(AgentName, CancellationToken) // Create client AgentsClient agentsClient = await AgentsClient.CreateAsync(); // Initialize request argument(s) AgentName name = AgentName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]"); // Make the request Agent response = await agentsClient.GetAgentAsync(name); // End snippet } /// <summary>Snippet for CreateAgent</summary> public void CreateAgentRequestObject() { // Snippet: CreateAgent(CreateAgentRequest, CallSettings) // Create client AgentsClient agentsClient = AgentsClient.Create(); // Initialize request argument(s) CreateAgentRequest request = new CreateAgentRequest { ParentAsLocationName = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), Agent = new Agent(), }; // Make the request Agent response = agentsClient.CreateAgent(request); // End snippet } /// <summary>Snippet for CreateAgentAsync</summary> public async Task CreateAgentRequestObjectAsync() { // Snippet: CreateAgentAsync(CreateAgentRequest, CallSettings) // Additional: CreateAgentAsync(CreateAgentRequest, CancellationToken) // Create client AgentsClient agentsClient = await AgentsClient.CreateAsync(); // Initialize request argument(s) CreateAgentRequest request = new CreateAgentRequest { ParentAsLocationName = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), Agent = new Agent(), }; // Make the request Agent response = await agentsClient.CreateAgentAsync(request); // End snippet } /// <summary>Snippet for CreateAgent</summary> public void CreateAgent() { // Snippet: CreateAgent(string, Agent, CallSettings) // Create client AgentsClient agentsClient = AgentsClient.Create(); // Initialize request argument(s) string parent = "projects/[PROJECT]/locations/[LOCATION]"; Agent agent = new Agent(); // Make the request Agent response = agentsClient.CreateAgent(parent, agent); // End snippet } /// <summary>Snippet for CreateAgentAsync</summary> public async Task CreateAgentAsync() { // Snippet: CreateAgentAsync(string, Agent, CallSettings) // Additional: CreateAgentAsync(string, Agent, CancellationToken) // Create client AgentsClient agentsClient = await AgentsClient.CreateAsync(); // Initialize request argument(s) string parent = "projects/[PROJECT]/locations/[LOCATION]"; Agent agent = new Agent(); // Make the request Agent response = await agentsClient.CreateAgentAsync(parent, agent); // End snippet } /// <summary>Snippet for CreateAgent</summary> public void CreateAgentResourceNames() { // Snippet: CreateAgent(LocationName, Agent, CallSettings) // Create client AgentsClient agentsClient = AgentsClient.Create(); // Initialize request argument(s) LocationName parent = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"); Agent agent = new Agent(); // Make the request Agent response = agentsClient.CreateAgent(parent, agent); // End snippet } /// <summary>Snippet for CreateAgentAsync</summary> public async Task CreateAgentResourceNamesAsync() { // Snippet: CreateAgentAsync(LocationName, Agent, CallSettings) // Additional: CreateAgentAsync(LocationName, Agent, CancellationToken) // Create client AgentsClient agentsClient = await AgentsClient.CreateAsync(); // Initialize request argument(s) LocationName parent = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"); Agent agent = new Agent(); // Make the request Agent response = await agentsClient.CreateAgentAsync(parent, agent); // End snippet } /// <summary>Snippet for UpdateAgent</summary> public void UpdateAgentRequestObject() { // Snippet: UpdateAgent(UpdateAgentRequest, CallSettings) // Create client AgentsClient agentsClient = AgentsClient.Create(); // Initialize request argument(s) UpdateAgentRequest request = new UpdateAgentRequest { Agent = new Agent(), UpdateMask = new FieldMask(), }; // Make the request Agent response = agentsClient.UpdateAgent(request); // End snippet } /// <summary>Snippet for UpdateAgentAsync</summary> public async Task UpdateAgentRequestObjectAsync() { // Snippet: UpdateAgentAsync(UpdateAgentRequest, CallSettings) // Additional: UpdateAgentAsync(UpdateAgentRequest, CancellationToken) // Create client AgentsClient agentsClient = await AgentsClient.CreateAsync(); // Initialize request argument(s) UpdateAgentRequest request = new UpdateAgentRequest { Agent = new Agent(), UpdateMask = new FieldMask(), }; // Make the request Agent response = await agentsClient.UpdateAgentAsync(request); // End snippet } /// <summary>Snippet for UpdateAgent</summary> public void UpdateAgent() { // Snippet: UpdateAgent(Agent, FieldMask, CallSettings) // Create client AgentsClient agentsClient = AgentsClient.Create(); // Initialize request argument(s) Agent agent = new Agent(); FieldMask updateMask = new FieldMask(); // Make the request Agent response = agentsClient.UpdateAgent(agent, updateMask); // End snippet } /// <summary>Snippet for UpdateAgentAsync</summary> public async Task UpdateAgentAsync() { // Snippet: UpdateAgentAsync(Agent, FieldMask, CallSettings) // Additional: UpdateAgentAsync(Agent, FieldMask, CancellationToken) // Create client AgentsClient agentsClient = await AgentsClient.CreateAsync(); // Initialize request argument(s) Agent agent = new Agent(); FieldMask updateMask = new FieldMask(); // Make the request Agent response = await agentsClient.UpdateAgentAsync(agent, updateMask); // End snippet } /// <summary>Snippet for DeleteAgent</summary> public void DeleteAgentRequestObject() { // Snippet: DeleteAgent(DeleteAgentRequest, CallSettings) // Create client AgentsClient agentsClient = AgentsClient.Create(); // Initialize request argument(s) DeleteAgentRequest request = new DeleteAgentRequest { AgentName = AgentName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]"), }; // Make the request agentsClient.DeleteAgent(request); // End snippet } /// <summary>Snippet for DeleteAgentAsync</summary> public async Task DeleteAgentRequestObjectAsync() { // Snippet: DeleteAgentAsync(DeleteAgentRequest, CallSettings) // Additional: DeleteAgentAsync(DeleteAgentRequest, CancellationToken) // Create client AgentsClient agentsClient = await AgentsClient.CreateAsync(); // Initialize request argument(s) DeleteAgentRequest request = new DeleteAgentRequest { AgentName = AgentName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]"), }; // Make the request await agentsClient.DeleteAgentAsync(request); // End snippet } /// <summary>Snippet for DeleteAgent</summary> public void DeleteAgent() { // Snippet: DeleteAgent(string, CallSettings) // Create client AgentsClient agentsClient = AgentsClient.Create(); // Initialize request argument(s) string name = "projects/[PROJECT]/locations/[LOCATION]/agents/[AGENT]"; // Make the request agentsClient.DeleteAgent(name); // End snippet } /// <summary>Snippet for DeleteAgentAsync</summary> public async Task DeleteAgentAsync() { // Snippet: DeleteAgentAsync(string, CallSettings) // Additional: DeleteAgentAsync(string, CancellationToken) // Create client AgentsClient agentsClient = await AgentsClient.CreateAsync(); // Initialize request argument(s) string name = "projects/[PROJECT]/locations/[LOCATION]/agents/[AGENT]"; // Make the request await agentsClient.DeleteAgentAsync(name); // End snippet } /// <summary>Snippet for DeleteAgent</summary> public void DeleteAgentResourceNames() { // Snippet: DeleteAgent(AgentName, CallSettings) // Create client AgentsClient agentsClient = AgentsClient.Create(); // Initialize request argument(s) AgentName name = AgentName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]"); // Make the request agentsClient.DeleteAgent(name); // End snippet } /// <summary>Snippet for DeleteAgentAsync</summary> public async Task DeleteAgentResourceNamesAsync() { // Snippet: DeleteAgentAsync(AgentName, CallSettings) // Additional: DeleteAgentAsync(AgentName, CancellationToken) // Create client AgentsClient agentsClient = await AgentsClient.CreateAsync(); // Initialize request argument(s) AgentName name = AgentName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]"); // Make the request await agentsClient.DeleteAgentAsync(name); // End snippet } /// <summary>Snippet for ExportAgent</summary> public void ExportAgentRequestObject() { // Snippet: ExportAgent(ExportAgentRequest, CallSettings) // Create client AgentsClient agentsClient = AgentsClient.Create(); // Initialize request argument(s) ExportAgentRequest request = new ExportAgentRequest { AgentName = AgentName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]"), AgentUri = "", EnvironmentAsEnvironmentName = EnvironmentName.FromProjectLocationAgentEnvironment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]"), }; // Make the request Operation<ExportAgentResponse, Struct> response = agentsClient.ExportAgent(request); // Poll until the returned long-running operation is complete Operation<ExportAgentResponse, Struct> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result ExportAgentResponse result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<ExportAgentResponse, Struct> retrievedResponse = agentsClient.PollOnceExportAgent(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result ExportAgentResponse retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for ExportAgentAsync</summary> public async Task ExportAgentRequestObjectAsync() { // Snippet: ExportAgentAsync(ExportAgentRequest, CallSettings) // Additional: ExportAgentAsync(ExportAgentRequest, CancellationToken) // Create client AgentsClient agentsClient = await AgentsClient.CreateAsync(); // Initialize request argument(s) ExportAgentRequest request = new ExportAgentRequest { AgentName = AgentName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]"), AgentUri = "", EnvironmentAsEnvironmentName = EnvironmentName.FromProjectLocationAgentEnvironment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]"), }; // Make the request Operation<ExportAgentResponse, Struct> response = await agentsClient.ExportAgentAsync(request); // Poll until the returned long-running operation is complete Operation<ExportAgentResponse, Struct> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result ExportAgentResponse result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<ExportAgentResponse, Struct> retrievedResponse = await agentsClient.PollOnceExportAgentAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result ExportAgentResponse retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for RestoreAgent</summary> public void RestoreAgentRequestObject() { // Snippet: RestoreAgent(RestoreAgentRequest, CallSettings) // Create client AgentsClient agentsClient = AgentsClient.Create(); // Initialize request argument(s) RestoreAgentRequest request = new RestoreAgentRequest { AgentName = AgentName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]"), AgentUri = "", RestoreOption = RestoreAgentRequest.Types.RestoreOption.Unspecified, }; // Make the request Operation<Empty, Struct> response = agentsClient.RestoreAgent(request); // Poll until the returned long-running operation is complete Operation<Empty, Struct> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result Empty result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<Empty, Struct> retrievedResponse = agentsClient.PollOnceRestoreAgent(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Empty retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for RestoreAgentAsync</summary> public async Task RestoreAgentRequestObjectAsync() { // Snippet: RestoreAgentAsync(RestoreAgentRequest, CallSettings) // Additional: RestoreAgentAsync(RestoreAgentRequest, CancellationToken) // Create client AgentsClient agentsClient = await AgentsClient.CreateAsync(); // Initialize request argument(s) RestoreAgentRequest request = new RestoreAgentRequest { AgentName = AgentName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]"), AgentUri = "", RestoreOption = RestoreAgentRequest.Types.RestoreOption.Unspecified, }; // Make the request Operation<Empty, Struct> response = await agentsClient.RestoreAgentAsync(request); // Poll until the returned long-running operation is complete Operation<Empty, Struct> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result Empty result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<Empty, Struct> retrievedResponse = await agentsClient.PollOnceRestoreAgentAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Empty retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for ValidateAgent</summary> public void ValidateAgentRequestObject() { // Snippet: ValidateAgent(ValidateAgentRequest, CallSettings) // Create client AgentsClient agentsClient = AgentsClient.Create(); // Initialize request argument(s) ValidateAgentRequest request = new ValidateAgentRequest { AgentName = AgentName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]"), LanguageCode = "", }; // Make the request AgentValidationResult response = agentsClient.ValidateAgent(request); // End snippet } /// <summary>Snippet for ValidateAgentAsync</summary> public async Task ValidateAgentRequestObjectAsync() { // Snippet: ValidateAgentAsync(ValidateAgentRequest, CallSettings) // Additional: ValidateAgentAsync(ValidateAgentRequest, CancellationToken) // Create client AgentsClient agentsClient = await AgentsClient.CreateAsync(); // Initialize request argument(s) ValidateAgentRequest request = new ValidateAgentRequest { AgentName = AgentName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]"), LanguageCode = "", }; // Make the request AgentValidationResult response = await agentsClient.ValidateAgentAsync(request); // End snippet } /// <summary>Snippet for GetAgentValidationResult</summary> public void GetAgentValidationResultRequestObject() { // Snippet: GetAgentValidationResult(GetAgentValidationResultRequest, CallSettings) // Create client AgentsClient agentsClient = AgentsClient.Create(); // Initialize request argument(s) GetAgentValidationResultRequest request = new GetAgentValidationResultRequest { AgentValidationResultName = AgentValidationResultName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]"), LanguageCode = "", }; // Make the request AgentValidationResult response = agentsClient.GetAgentValidationResult(request); // End snippet } /// <summary>Snippet for GetAgentValidationResultAsync</summary> public async Task GetAgentValidationResultRequestObjectAsync() { // Snippet: GetAgentValidationResultAsync(GetAgentValidationResultRequest, CallSettings) // Additional: GetAgentValidationResultAsync(GetAgentValidationResultRequest, CancellationToken) // Create client AgentsClient agentsClient = await AgentsClient.CreateAsync(); // Initialize request argument(s) GetAgentValidationResultRequest request = new GetAgentValidationResultRequest { AgentValidationResultName = AgentValidationResultName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]"), LanguageCode = "", }; // Make the request AgentValidationResult response = await agentsClient.GetAgentValidationResultAsync(request); // End snippet } /// <summary>Snippet for GetAgentValidationResult</summary> public void GetAgentValidationResult() { // Snippet: GetAgentValidationResult(string, CallSettings) // Create client AgentsClient agentsClient = AgentsClient.Create(); // Initialize request argument(s) string name = "projects/[PROJECT]/locations/[LOCATION]/agents/[AGENT]/validationResult"; // Make the request AgentValidationResult response = agentsClient.GetAgentValidationResult(name); // End snippet } /// <summary>Snippet for GetAgentValidationResultAsync</summary> public async Task GetAgentValidationResultAsync() { // Snippet: GetAgentValidationResultAsync(string, CallSettings) // Additional: GetAgentValidationResultAsync(string, CancellationToken) // Create client AgentsClient agentsClient = await AgentsClient.CreateAsync(); // Initialize request argument(s) string name = "projects/[PROJECT]/locations/[LOCATION]/agents/[AGENT]/validationResult"; // Make the request AgentValidationResult response = await agentsClient.GetAgentValidationResultAsync(name); // End snippet } /// <summary>Snippet for GetAgentValidationResult</summary> public void GetAgentValidationResultResourceNames() { // Snippet: GetAgentValidationResult(AgentValidationResultName, CallSettings) // Create client AgentsClient agentsClient = AgentsClient.Create(); // Initialize request argument(s) AgentValidationResultName name = AgentValidationResultName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]"); // Make the request AgentValidationResult response = agentsClient.GetAgentValidationResult(name); // End snippet } /// <summary>Snippet for GetAgentValidationResultAsync</summary> public async Task GetAgentValidationResultResourceNamesAsync() { // Snippet: GetAgentValidationResultAsync(AgentValidationResultName, CallSettings) // Additional: GetAgentValidationResultAsync(AgentValidationResultName, CancellationToken) // Create client AgentsClient agentsClient = await AgentsClient.CreateAsync(); // Initialize request argument(s) AgentValidationResultName name = AgentValidationResultName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]"); // Make the request AgentValidationResult response = await agentsClient.GetAgentValidationResultAsync(name); // End snippet } } }
using System; using Signum.Utilities; namespace Signum.Engine.Maps { public static class TableExtensions { internal static string UnScapeSql(this string name, bool isPostgres) { if (isPostgres) { if (name.StartsWith('\"')) return name.Trim('\"'); return name.ToLower(); } return name.Trim('[', ']'); } } public class ServerName : IEquatable<ServerName> { public string Name { get; private set; } public bool IsPostgres { get; private set; } /// <summary> /// Linked Servers: http://msdn.microsoft.com/en-us/library/ms188279.aspx /// </summary> /// <param name="name"></param> public ServerName(string name, bool isPostgres) { if (string.IsNullOrEmpty(name)) throw new ArgumentNullException(nameof(name)); this.Name = name; this.IsPostgres = isPostgres; } public override string ToString() { return Name.SqlEscape(IsPostgres); } public override bool Equals(object? obj) => obj is ServerName sn && Equals(sn); public bool Equals(ServerName? other) { if (other == null) return false; return other.Name == Name; } public override int GetHashCode() { return Name.GetHashCode(); } public static ServerName? Parse(string? name, bool isPostgres) { if (!name.HasText()) return null; return new ServerName(name.UnScapeSql(isPostgres), isPostgres); } } public class DatabaseName : IEquatable<DatabaseName> { public string Name { get; private set; } public bool IsPostgres { get; private set; } public ServerName? Server { get; private set; } public DatabaseName(ServerName? server, string name, bool isPostgres) { if (string.IsNullOrEmpty(name)) throw new ArgumentNullException(nameof(name)); this.Name = name; this.Server = server; this.IsPostgres = isPostgres; } public override string ToString() { var options = ObjectName.CurrentOptions; var name = !options.DatabaseNameReplacement.HasText() ? Name.SqlEscape(IsPostgres): Name.Replace(Connector.Current.DatabaseName(), options.DatabaseNameReplacement).SqlEscape(IsPostgres); if (Server == null) return name; return Server.ToString() + "." + name; } public override bool Equals(object? obj) => obj is DatabaseName dn && Equals(dn); public bool Equals(DatabaseName? other) { if (other == null) return false; return other.Name == Name && object.Equals(Server, other.Server); } public override int GetHashCode() { return Name.GetHashCode() ^ (Server == null ? 0 : Server.GetHashCode()); } public static DatabaseName? Parse(string? name, bool isPostgres) { if (!name.HasText()) return null; var tuple = ObjectName.SplitLast(name, isPostgres); return new DatabaseName(ServerName.Parse(tuple.prefix, isPostgres), tuple.name, isPostgres); } } public class SchemaName : IEquatable<SchemaName> { public string Name { get; private set; } public bool IsPostgres { get; private set; } readonly DatabaseName? database; public DatabaseName? Database { get { if (database == null || ObjectName.CurrentOptions.AvoidDatabaseName) return null; return database; } } static readonly SchemaName defaultSqlServer = new SchemaName(null, "dbo", isPostgres: false); static readonly SchemaName defaultPostgreeSql = new SchemaName(null, "public", isPostgres: true); public static SchemaName Default(bool isPostgres) => isPostgres ? defaultPostgreeSql : defaultSqlServer; public bool IsDefault() { return Database == null && (IsPostgres ? defaultPostgreeSql : defaultSqlServer).Name == Name; } public SchemaName(DatabaseName? database, string name, bool isPostgres) { if (string.IsNullOrEmpty(name)) throw new ArgumentNullException(nameof(name)); this.Name = name; this.database = database; this.IsPostgres = isPostgres; } public override string ToString() { var result = Name.SqlEscape(IsPostgres); if (Database == null) return result; return Database.ToString() + "." + result; } public override bool Equals(object? obj) => obj is SchemaName sn && Equals(sn); public bool Equals(SchemaName? other) { if (other == null) return false; return other.Name == Name && object.Equals(Database, other.Database); } public override int GetHashCode() { return Name.GetHashCode() ^ (Database == null ? 0 : Database.GetHashCode()); } public static SchemaName Parse(string? name, bool isPostgres) { if (!name.HasText()) return SchemaName.Default(isPostgres); var tuple = ObjectName.SplitLast(name, isPostgres); return new SchemaName(DatabaseName.Parse(tuple.prefix, isPostgres), tuple.name, isPostgres); } internal SchemaName OnDatabase(DatabaseName? database) { return new SchemaName(database, this.Name, this.IsPostgres); } } public class ObjectName : IEquatable<ObjectName> { public static int MaxPostgreeSize = 63; public string Name { get; private set; } public bool IsPostgres { get; private set; } public SchemaName Schema { get; private set; } // null only for postgres temporary public ObjectName(SchemaName schema, string name, bool isPostgres) { this.Name = name.HasText() ? name : throw new ArgumentNullException(nameof(name)); if (isPostgres && this.Name.Length > MaxPostgreeSize) throw new InvalidOperationException($"The name '{name}' is too long, consider using TableNameAttribute/ColumnNameAttribute"); this.Schema = schema ?? (isPostgres && name.StartsWith("#") ? (SchemaName)null! : throw new ArgumentNullException(nameof(schema))); this.IsPostgres = isPostgres; } public override string ToString() { if (Schema == null) return Name.SqlEscape(IsPostgres); return Schema.ToString() + "." + Name.SqlEscape(IsPostgres); } public override bool Equals(object? obj) => obj is ObjectName on && Equals(on); public bool Equals(ObjectName? other) { if (other == null) return false; return other.Name == Name && object.Equals(Schema, other.Schema); } public override int GetHashCode() { return Name.GetHashCode() ^ Schema?.GetHashCode() ?? 0; } public static ObjectName Parse(string? name, bool isPostgres) { if (!name.HasText()) throw new ArgumentNullException(nameof(name)); var tuple = SplitLast(name, isPostgres); return new ObjectName(SchemaName.Parse(tuple.prefix, isPostgres), tuple.name, isPostgres); } //FROM "[a.b.c].[d.e.f].[a.b.c].[c.d.f]" //TO ("[a.b.c].[d.e.f].[a.b.c]", "c.d.f") internal static (string? prefix, string name) SplitLast(string str, bool isPostgres) { if (isPostgres) { if (!str.EndsWith('\"')) { return ( prefix: str.TryBeforeLast('.'), name: str.TryAfterLast('.') ?? str ); } var index = str.LastIndexOf('\"', str.Length - 2); return ( prefix: index == 0 ? null : str.Substring(0, index - 1), name: str.Substring(index).UnScapeSql(isPostgres) ); } else { if (!str.EndsWith("]")) { return ( prefix: str.TryBeforeLast('.'), name: str.TryAfterLast('.') ?? str ); } var index = str.LastIndexOf('['); return ( prefix: index == 0 ? null : str.Substring(0, index - 1), name: str.Substring(index).UnScapeSql(isPostgres) ); } } public ObjectName OnDatabase(DatabaseName? databaseName) { if (databaseName != null && databaseName.IsPostgres != this.IsPostgres) throw new Exception("Inconsitent IsPostgres"); return new ObjectName(new SchemaName(databaseName, Schema!.Name, IsPostgres), Name, IsPostgres); } public ObjectName OnSchema(SchemaName schemaName) { if (schemaName.IsPostgres != this.IsPostgres) throw new Exception("Inconsitent IsPostgres"); return new ObjectName(schemaName, Name, IsPostgres); } static readonly ThreadVariable<ObjectNameOptions> optionsVariable = Statics.ThreadVariable<ObjectNameOptions>("objectNameOptions"); public static IDisposable OverrideOptions(ObjectNameOptions options) { var old = optionsVariable.Value; optionsVariable.Value = options; return new Disposable(() => optionsVariable.Value = old); } public static ObjectNameOptions CurrentOptions { get { return optionsVariable.Value; } } public bool IsTemporal => this.Name.StartsWith("#"); } public struct ObjectNameOptions { public string DatabaseNameReplacement; public bool AvoidDatabaseName; } }
// // CustomTreeModel.cs // // Author: // Lluis Sanchez <lluis@xamarin.com> // // Copyright (c) 2011 Xamarin Inc // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using System.Collections.Generic; using System.Runtime.InteropServices; using Gtk; #if XWT_GTK3 using TreeModelImplementor = Gtk.ITreeModelImplementor; #endif namespace Xwt.GtkBackend { public class CustomTreeModel: TreeModelImplementor { ITreeDataSource source; Dictionary<GCHandle,TreePosition> nodeHash = new Dictionary<GCHandle,TreePosition> (); Dictionary<TreePosition,GCHandle> handleHash = new Dictionary<TreePosition,GCHandle> (); Type[] colTypes; Gtk.TreeModelAdapter adapter; public CustomTreeModel (ITreeDataSource source) { this.source = source; adapter = new Gtk.TreeModelAdapter (this); colTypes = source.ColumnTypes; source.NodeChanged += HandleNodeChanged; source.NodeDeleted += HandleNodeDeleted; source.NodeInserted += HandleNodeInserted; source.NodesReordered += HandleNodesReordered; } public Gtk.TreeModelAdapter Store { get { return adapter; } } public IntPtr Handle { get { return IntPtr.Zero; } } Gtk.TreeIter IterFromNode (TreePosition node) { GCHandle gch; if (!handleHash.TryGetValue (node, out gch)) { gch = GCHandle.Alloc (node); handleHash [node] = gch; nodeHash [gch] = node; } Gtk.TreeIter result = Gtk.TreeIter.Zero; result.UserData = (IntPtr)gch; return result; } TreePosition NodeFromIter (Gtk.TreeIter iter) { TreePosition node; GCHandle gch = (GCHandle)iter.UserData; nodeHash.TryGetValue (gch, out node); return node; } #region TreeModelImplementor implementation void HandleNodesReordered (object sender, TreeNodeOrderEventArgs e) { Gtk.TreeIter it = IterFromNode (e.Node); adapter.EmitRowsReordered (GetPath (it), it, e.ChildrenOrder); } void HandleNodeInserted (object sender, TreeNodeEventArgs e) { Gtk.TreeIter it = IterFromNode (e.Node); adapter.EmitRowInserted (GetPath (it), it); } void HandleNodeDeleted (object sender, TreeNodeChildEventArgs e) { if (e.Node == null) { adapter.EmitRowDeleted (new Gtk.TreePath (new int[] { e.ChildIndex })); } else { Gtk.TreeIter it = IterFromNode (e.Node); var p = GetPath (it); int[] idx = new int [p.Indices.Length + 1]; p.Indices.CopyTo (idx, 0); idx [idx.Length - 1] = e.ChildIndex; adapter.EmitRowDeleted (new Gtk.TreePath (idx)); } } void HandleNodeChanged (object sender, TreeNodeEventArgs e) { Gtk.TreeIter it = IterFromNode (e.Node); adapter.EmitRowChanged (GetPath (it), it); } public GLib.GType GetColumnType (int index) { return (GLib.GType) colTypes [index]; } public bool GetIter (out Gtk.TreeIter iter, Gtk.TreePath path) { iter = Gtk.TreeIter.Zero; TreePosition pos = null; int[] indices = path.Indices; if (indices.Length == 0) return false; for (int n=0; n<indices.Length; n++) { pos = source.GetChild (pos, indices [n]); if (pos == null) return false; } iter = IterFromNode (pos); return true; } public Gtk.TreePath GetPath (Gtk.TreeIter iter) { TreePosition pos = NodeFromIter (iter); List<int> idx = new List<int> (); while (pos != null) { var parent = source.GetParent (pos); idx.Add (GetIndex (parent, pos)); pos = parent; } idx.Reverse (); return new Gtk.TreePath (idx.ToArray ()); } int GetIndex (TreePosition parent, TreePosition pos) { int n = 0; do { var c = source.GetChild (parent, n); if (c == null) return -1; if (c == pos || c.Equals(pos)) return n; n++; } while (true); } public void GetValue (Gtk.TreeIter iter, int column, ref GLib.Value value) { TreePosition pos = NodeFromIter (iter); var v = source.GetValue (pos, column); value = new GLib.Value (v); } public bool IterNext (ref Gtk.TreeIter iter) { TreePosition pos = NodeFromIter (iter); TreePosition parent = source.GetParent (pos); int i = GetIndex (parent, pos); if (source.GetChildrenCount (parent) >= i) return false; pos = source.GetChild (parent, i + 1); if (pos != null) { iter = IterFromNode (pos); return true; } else return false; } #if XWT_GTK3 public bool IterPrevious (ref Gtk.TreeIter iter) { TreePosition pos = NodeFromIter (iter); TreePosition parent = source.GetParent (pos); int i = GetIndex (parent, pos); pos = source.GetChild (parent, i - 1); if (pos != null) { iter = IterFromNode (pos); return true; } else return false; } #endif public bool IterChildren (out Gtk.TreeIter iter, Gtk.TreeIter parent) { iter = Gtk.TreeIter.Zero; TreePosition pos = NodeFromIter (parent); pos = source.GetChild (pos, 0); if (pos != null) { iter = IterFromNode (pos); return true; } else return false; } public bool IterHasChild (Gtk.TreeIter iter) { TreePosition pos = NodeFromIter (iter); return source.GetChildrenCount (pos) != 0; } public int IterNChildren (Gtk.TreeIter iter) { TreePosition pos = NodeFromIter (iter); return source.GetChildrenCount (pos); } public bool IterNthChild (out Gtk.TreeIter iter, Gtk.TreeIter parent, int n) { iter = Gtk.TreeIter.Zero; TreePosition pos = NodeFromIter (parent); pos = source.GetChild (pos, n); if (pos != null) { iter = IterFromNode (pos); return true; } else return false; } public bool IterParent (out Gtk.TreeIter iter, Gtk.TreeIter child) { iter = Gtk.TreeIter.Zero; TreePosition pos = NodeFromIter (iter); pos = source.GetParent (pos); if (pos != null) { iter = IterFromNode (pos); return true; } else return false; } public void RefNode (Gtk.TreeIter iter) { } public void UnrefNode (Gtk.TreeIter iter) { } public Gtk.TreeModelFlags Flags { get { return Gtk.TreeModelFlags.ItersPersist; } } public int NColumns { get { return colTypes.Length; } } #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.Collections.Generic; using System.Diagnostics; using System.Runtime.InteropServices; using System.Text; namespace System.IO { /* This class is used by for reading from the stdin. * It is designed to read stdin in raw mode for interpreting * key press events and maintain its own buffer for the same. * which is then used for all the Read operations */ internal class StdInStreamReader : StreamReader { private static string s_moveLeftString; // string written to move the cursor to the left private readonly StringBuilder _readLineSB; // SB that holds readLine output. This is a field simply to enable reuse; it's only used in ReadLine. private readonly Stack<ConsoleKeyInfo> _tmpKeys = new Stack<ConsoleKeyInfo>(); // temporary working stack; should be empty outside of ReadLine private readonly Stack<ConsoleKeyInfo> _availableKeys = new Stack<ConsoleKeyInfo>(); // a queue of already processed key infos available for reading private char[] _unprocessedBufferToBeRead; // Buffer that might have already been read from stdin but not yet processed. private const int BytesToBeRead = 1024; // No. of bytes to be read from the stream at a time. private int _startIndex; // First unprocessed index in the buffer; private int _endIndex; // Index after last unprocessed index in the buffer; internal StdInStreamReader(Stream stream, Encoding encoding, int bufferSize) : base(stream: stream, encoding: encoding, detectEncodingFromByteOrderMarks: false, bufferSize: bufferSize, leaveOpen: true) { _unprocessedBufferToBeRead = new char[encoding.GetMaxCharCount(BytesToBeRead)]; _startIndex = 0; _endIndex = 0; _readLineSB = new StringBuilder(); } /// <summary> Checks whether the unprocessed buffer is empty. </summary> internal bool IsUnprocessedBufferEmpty() { return _startIndex >= _endIndex; // Everything has been processed; } internal unsafe void AppendExtraBuffer(byte* buffer, int bufferLength) { // Then convert the bytes to chars int charLen = CurrentEncoding.GetMaxCharCount(bufferLength); char* charPtr = stackalloc char[charLen]; charLen = CurrentEncoding.GetChars(buffer, bufferLength, charPtr, charLen); // Ensure our buffer is large enough to hold all of the data if (IsUnprocessedBufferEmpty()) { _startIndex = _endIndex = 0; } else { Debug.Assert(_endIndex > 0); int spaceRemaining = _unprocessedBufferToBeRead.Length - _endIndex; if (spaceRemaining < charLen) { Array.Resize(ref _unprocessedBufferToBeRead, _unprocessedBufferToBeRead.Length * 2); } } // Copy the data into our buffer Marshal.Copy((IntPtr)charPtr, _unprocessedBufferToBeRead, _endIndex, charLen); _endIndex += charLen; } internal unsafe int ReadStdin(byte* buffer, int bufferSize) { int result = Interop.CheckIo(Interop.Sys.ReadStdin(buffer, bufferSize)); Debug.Assert(result >= 0 && result <= bufferSize); // may be 0 if hits EOL return result; } public override string ReadLine() { return ReadLine(consumeKeys: true); } private string ReadLine(bool consumeKeys) { Debug.Assert(_tmpKeys.Count == 0); string readLineStr = null; // Disable echo and buffering. These will be disabled for the duration of the line read. Interop.Sys.InitializeConsoleBeforeRead(); try { // Read key-by-key until we've read a line. while (true) { // Read the next key. This may come from previously read keys, from previously read but // unprocessed data, or from an actual stdin read. bool previouslyProcessed; ConsoleKeyInfo keyInfo = ReadKey(out previouslyProcessed); if (!consumeKeys && keyInfo.Key != ConsoleKey.Backspace) // backspace is the only character not written out in the below if/elses. { _tmpKeys.Push(keyInfo); } // Handle the next key. Since for other functions we may have ended up reading some of the user's // input, we need to be able to handle manually processing that input, and so we do that processing // for all input. As such, we need to special-case a few characters, e.g. recognizing when Enter is // pressed to end a line. We also need to handle Backspace specially, to fix up both our buffer of // characters and the position of the cursor. More advanced processing would be possible, but we // try to keep this very simple, at least for now. if (keyInfo.Key == ConsoleKey.Enter) { readLineStr = _readLineSB.ToString(); _readLineSB.Clear(); if (!previouslyProcessed) { Console.WriteLine(); } break; } else if (IsEol(keyInfo.KeyChar)) { string line = _readLineSB.ToString(); _readLineSB.Clear(); if (line.Length > 0) { readLineStr = line; } break; } else if (keyInfo.Key == ConsoleKey.Backspace) { int len = _readLineSB.Length; if (len > 0) { _readLineSB.Length = len - 1; if (!previouslyProcessed) { if (s_moveLeftString == null) { string moveLeft = ConsolePal.TerminalFormatStrings.Instance.CursorLeft; s_moveLeftString = !string.IsNullOrEmpty(moveLeft) ? moveLeft + " " + moveLeft : string.Empty; } Console.Write(s_moveLeftString); } } } else if (keyInfo.Key == ConsoleKey.Tab) { _readLineSB.Append(keyInfo.KeyChar); if (!previouslyProcessed) { Console.Write(' '); } } else if (keyInfo.Key == ConsoleKey.Clear) { _readLineSB.Clear(); if (!previouslyProcessed) { Console.Clear(); } } else { _readLineSB.Append(keyInfo.KeyChar); if (!previouslyProcessed) { Console.Write(keyInfo.KeyChar); } } } } finally { Interop.Sys.UninitializeConsoleAfterRead(); // If we're not consuming the read input, make the keys available for a future read while (_tmpKeys.Count > 0) { _availableKeys.Push(_tmpKeys.Pop()); } } return readLineStr; } public override int Read() { // If there aren't any keys in our processed keys stack, read a line to populate it. if (_availableKeys.Count == 0) { ReadLine(consumeKeys: false); } // Now if there are keys, use the first. if (_availableKeys.Count > 0) { ConsoleKeyInfo keyInfo = _availableKeys.Pop(); if (!IsEol(keyInfo.KeyChar)) { return keyInfo.KeyChar; } } // EOL return -1; } private static bool IsEol(char c) { return c != ConsolePal.s_posixDisableValue && (c == ConsolePal.s_veolCharacter || c == ConsolePal.s_veol2Character || c == ConsolePal.s_veofCharacter); } internal ConsoleKey GetKeyFromCharValue(char x, out bool isShift, out bool isCtrl) { isShift = false; isCtrl = false; switch (x) { case '\b': return ConsoleKey.Backspace; case '\t': return ConsoleKey.Tab; case '\n': return ConsoleKey.Enter; case (char)(0x1B): return ConsoleKey.Escape; case '*': return ConsoleKey.Multiply; case '+': return ConsoleKey.Add; case '-': return ConsoleKey.Subtract; case '/': return ConsoleKey.Divide; case (char)(0x7F): return ConsoleKey.Delete; case ' ': return ConsoleKey.Spacebar; default: // 1. Ctrl A to Ctrl Z. if (x >= 1 && x <= 26) { isCtrl = true; return ConsoleKey.A + x - 1; } // 2. Numbers from 0 to 9. if (x >= '0' && x <= '9') { return ConsoleKey.D0 + x - '0'; } //3. A to Z if (x >= 'A' && x <= 'Z') { isShift = true; return ConsoleKey.A + (x - 'A'); } // 4. a to z. if (x >= 'a' && x <= 'z') { return ConsoleKey.A + (x - 'a'); } break; } return default(ConsoleKey); } internal bool MapBufferToConsoleKey(out ConsoleKey key, out char ch, out bool isShift, out bool isAlt, out bool isCtrl) { Debug.Assert(!IsUnprocessedBufferEmpty()); // Try to get the special key match from the TermInfo static information. ConsoleKeyInfo keyInfo; int keyLength; if (ConsolePal.TryGetSpecialConsoleKey(_unprocessedBufferToBeRead, _startIndex, _endIndex, out keyInfo, out keyLength)) { key = keyInfo.Key; isShift = (keyInfo.Modifiers & ConsoleModifiers.Shift) != 0; isAlt = (keyInfo.Modifiers & ConsoleModifiers.Alt) != 0; isCtrl = (keyInfo.Modifiers & ConsoleModifiers.Control) != 0; ch = ((keyLength == 1) ? _unprocessedBufferToBeRead[_startIndex] : '\0'); // ignore keyInfo.KeyChar _startIndex += keyLength; return true; } // Check if we can match Esc + combination and guess if alt was pressed. isAlt = isCtrl = isShift = false; if (_unprocessedBufferToBeRead[_startIndex] == (char)0x1B && // Alt is send as an escape character _endIndex - _startIndex >= 2) // We have at least two characters to read { _startIndex++; if (MapBufferToConsoleKey(out key, out ch, out isShift, out isAlt, out isCtrl)) { isAlt = true; return true; } else { // We could not find a matching key here so, Alt+ combination assumption is in-correct. // The current key needs to be marked as Esc key. // Also, we do not increment _startIndex as we already did it. key = ConsoleKey.Escape; ch = (char)0x1B; isAlt = false; return true; } } // Try reading the first char in the buffer and interpret it as a key. ch = _unprocessedBufferToBeRead[_startIndex++]; key = GetKeyFromCharValue(ch, out isShift, out isCtrl); return key != default(ConsoleKey); } /// <summary> /// Try to intercept the key pressed. /// /// Unlike Windows Unix has no concept of virtual key codes. /// Hence, in case we do not recognize a key, we can't really /// get the ConsoleKey key code associated with it. /// As a result, we try to recognize the key, and if that does /// not work, we simply return the char associated with that /// key with ConsoleKey set to default value. /// </summary> public unsafe ConsoleKeyInfo ReadKey(out bool previouslyProcessed) { // Order of reading: // 1. A read should first consult _availableKeys, as this contains input that has already been both read from stdin and processed into ConsoleKeyInfos. // 2. If _availableKeys is empty, then _unprocessedBufferToRead should be consulted. This is input from stdin that was read in bulk but has yet to be processed. // 3. Finally if _unprocessedBufferToRead is empty, input must be obtained from ReadStdinUnbuffered. if (_availableKeys.Count > 0) { previouslyProcessed = true; return _availableKeys.Pop(); } previouslyProcessed = false; Interop.Sys.InitializeConsoleBeforeRead(); try { ConsoleKey key; char ch; bool isAlt, isCtrl, isShift; if (IsUnprocessedBufferEmpty()) { // Read in bytes byte* bufPtr = stackalloc byte[BytesToBeRead]; int result = ReadStdin(bufPtr, BytesToBeRead); if (result > 0) { // Append them AppendExtraBuffer(bufPtr, result); } else { // Could be empty if EOL entered on its own. Pick one of the EOL characters we have, // or just use 0 if none are available. return new ConsoleKeyInfo((char) (ConsolePal.s_veolCharacter != ConsolePal.s_posixDisableValue ? ConsolePal.s_veolCharacter : ConsolePal.s_veol2Character != ConsolePal.s_posixDisableValue ? ConsolePal.s_veol2Character : ConsolePal.s_veofCharacter != ConsolePal.s_posixDisableValue ? ConsolePal.s_veofCharacter : 0), default(ConsoleKey), false, false, false); } } MapBufferToConsoleKey(out key, out ch, out isShift, out isAlt, out isCtrl); return new ConsoleKeyInfo(ch, key, isShift, isAlt, isCtrl); } finally { Interop.Sys.UninitializeConsoleAfterRead(); } } /// <summary>Gets whether there's input waiting on stdin.</summary> internal bool StdinReady { get { return Interop.Sys.StdinReady(); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.IO; using System.Runtime.Serialization; // For SR using System.Text; namespace System.Xml { // This wrapper does not support seek. // Constructors consume/emit byte order mark. // Supports: UTF-8, Unicode, BigEndianUnicode // ASSUMPTION (Microsoft): This class will only be used for EITHER reading OR writing. It can be done, it would just mean more buffers. // ASSUMPTION (Microsoft): The byte buffer is large enough to hold the declaration // ASSUMPTION (Microsoft): The buffer manipulation methods (FillBuffer/Compare/etc.) will only be used to parse the declaration // during construction. internal class EncodingStreamWrapper : Stream { private enum SupportedEncoding { UTF8, UTF16LE, UTF16BE, None } private static readonly UTF8Encoding s_safeUTF8 = new UTF8Encoding(false, false); private static readonly UnicodeEncoding s_safeUTF16 = new UnicodeEncoding(false, false, false); private static readonly UnicodeEncoding s_safeBEUTF16 = new UnicodeEncoding(true, false, false); private static readonly UTF8Encoding s_validatingUTF8 = new UTF8Encoding(false, true); private static readonly UnicodeEncoding s_validatingUTF16 = new UnicodeEncoding(false, false, true); private static readonly UnicodeEncoding s_validatingBEUTF16 = new UnicodeEncoding(true, false, true); private const int BufferLength = 128; // UTF-8 is fastpath, so that's how these are stored // Compare methods adapt to Unicode. private static readonly byte[] s_encodingAttr = new byte[] { (byte)'e', (byte)'n', (byte)'c', (byte)'o', (byte)'d', (byte)'i', (byte)'n', (byte)'g' }; private static readonly byte[] s_encodingUTF8 = new byte[] { (byte)'u', (byte)'t', (byte)'f', (byte)'-', (byte)'8' }; private static readonly byte[] s_encodingUnicode = new byte[] { (byte)'u', (byte)'t', (byte)'f', (byte)'-', (byte)'1', (byte)'6' }; private static readonly byte[] s_encodingUnicodeLE = new byte[] { (byte)'u', (byte)'t', (byte)'f', (byte)'-', (byte)'1', (byte)'6', (byte)'l', (byte)'e' }; private static readonly byte[] s_encodingUnicodeBE = new byte[] { (byte)'u', (byte)'t', (byte)'f', (byte)'-', (byte)'1', (byte)'6', (byte)'b', (byte)'e' }; private SupportedEncoding _encodingCode; private Encoding _encoding; private Encoder _enc; private Decoder _dec; private bool _isReading; private Stream _stream; private char[] _chars; private byte[] _bytes; private int _byteOffset; private int _byteCount; private byte[] _byteBuffer = new byte[1]; // Reading constructor public EncodingStreamWrapper(Stream stream, Encoding encoding) { try { _isReading = true; _stream = stream; // Decode the expected encoding SupportedEncoding expectedEnc = GetSupportedEncoding(encoding); // Get the byte order mark so we can determine the encoding // May want to try to delay allocating everything until we know the BOM SupportedEncoding declEnc = ReadBOMEncoding(encoding == null); // Check that the expected encoding matches the decl encoding. if (expectedEnc != SupportedEncoding.None && expectedEnc != declEnc) ThrowExpectedEncodingMismatch(expectedEnc, declEnc); // Fastpath: UTF-8 BOM if (declEnc == SupportedEncoding.UTF8) { // Fastpath: UTF-8 BOM, No declaration FillBuffer(2); if (_bytes[_byteOffset + 1] != '?' || _bytes[_byteOffset] != '<') { return; } FillBuffer(BufferLength); CheckUTF8DeclarationEncoding(_bytes, _byteOffset, _byteCount, declEnc, expectedEnc); } else { // Convert to UTF-8 EnsureBuffers(); FillBuffer((BufferLength - 1) * 2); SetReadDocumentEncoding(declEnc); CleanupCharBreak(); int count = _encoding.GetChars(_bytes, _byteOffset, _byteCount, _chars, 0); _byteOffset = 0; _byteCount = s_validatingUTF8.GetBytes(_chars, 0, count, _bytes, 0); // Check for declaration if (_bytes[1] == '?' && _bytes[0] == '<') { CheckUTF8DeclarationEncoding(_bytes, 0, _byteCount, declEnc, expectedEnc); } else { // Declaration required if no out-of-band encoding if (expectedEnc == SupportedEncoding.None) throw new XmlException(SR.XmlDeclarationRequired); } } } catch (DecoderFallbackException ex) { throw new XmlException(SR.XmlInvalidBytes, ex); } } private void SetReadDocumentEncoding(SupportedEncoding e) { EnsureBuffers(); _encodingCode = e; _encoding = GetEncoding(e); } private static Encoding GetEncoding(SupportedEncoding e) { switch (e) { case SupportedEncoding.UTF8: return s_validatingUTF8; case SupportedEncoding.UTF16LE: return s_validatingUTF16; case SupportedEncoding.UTF16BE: return s_validatingBEUTF16; default: throw new XmlException(SR.XmlEncodingNotSupported); } } private static Encoding GetSafeEncoding(SupportedEncoding e) { switch (e) { case SupportedEncoding.UTF8: return s_safeUTF8; case SupportedEncoding.UTF16LE: return s_safeUTF16; case SupportedEncoding.UTF16BE: return s_safeBEUTF16; default: throw new XmlException(SR.XmlEncodingNotSupported); } } private static string GetEncodingName(SupportedEncoding enc) { switch (enc) { case SupportedEncoding.UTF8: return "utf-8"; case SupportedEncoding.UTF16LE: return "utf-16LE"; case SupportedEncoding.UTF16BE: return "utf-16BE"; default: throw new XmlException(SR.XmlEncodingNotSupported); } } private static SupportedEncoding GetSupportedEncoding(Encoding encoding) { if (encoding == null) return SupportedEncoding.None; else if (encoding.WebName == s_validatingUTF8.WebName) return SupportedEncoding.UTF8; else if (encoding.WebName == s_validatingUTF16.WebName) return SupportedEncoding.UTF16LE; else if (encoding.WebName == s_validatingBEUTF16.WebName) return SupportedEncoding.UTF16BE; else throw new XmlException(SR.XmlEncodingNotSupported); } // Writing constructor public EncodingStreamWrapper(Stream stream, Encoding encoding, bool emitBOM) { _isReading = false; _encoding = encoding; _stream = stream; // Set the encoding code _encodingCode = GetSupportedEncoding(encoding); if (_encodingCode != SupportedEncoding.UTF8) { EnsureBuffers(); _dec = s_validatingUTF8.GetDecoder(); _enc = _encoding.GetEncoder(); // Emit BOM if (emitBOM) { byte[] bom = _encoding.GetPreamble(); if (bom.Length > 0) _stream.Write(bom, 0, bom.Length); } } } private SupportedEncoding ReadBOMEncoding(bool notOutOfBand) { int b1 = _stream.ReadByte(); int b2 = _stream.ReadByte(); int b3 = _stream.ReadByte(); int b4 = _stream.ReadByte(); // Premature end of stream if (b4 == -1) throw new XmlException(SR.UnexpectedEndOfFile); int preserve; SupportedEncoding e = ReadBOMEncoding((byte)b1, (byte)b2, (byte)b3, (byte)b4, notOutOfBand, out preserve); EnsureByteBuffer(); switch (preserve) { case 1: _bytes[0] = (byte)b4; break; case 2: _bytes[0] = (byte)b3; _bytes[1] = (byte)b4; break; case 4: _bytes[0] = (byte)b1; _bytes[1] = (byte)b2; _bytes[2] = (byte)b3; _bytes[3] = (byte)b4; break; } _byteCount = preserve; return e; } private static SupportedEncoding ReadBOMEncoding(byte b1, byte b2, byte b3, byte b4, bool notOutOfBand, out int preserve) { SupportedEncoding e = SupportedEncoding.UTF8; // Default preserve = 0; if (b1 == '<' && b2 != 0x00) // UTF-8, no BOM { e = SupportedEncoding.UTF8; preserve = 4; } else if (b1 == 0xFF && b2 == 0xFE) // UTF-16 little endian { e = SupportedEncoding.UTF16LE; preserve = 2; } else if (b1 == 0xFE && b2 == 0xFF) // UTF-16 big endian { e = SupportedEncoding.UTF16BE; preserve = 2; } else if (b1 == 0x00 && b2 == '<') // UTF-16 big endian, no BOM { e = SupportedEncoding.UTF16BE; if (notOutOfBand && (b3 != 0x00 || b4 != '?')) throw new XmlException(SR.XmlDeclMissing); preserve = 4; } else if (b1 == '<' && b2 == 0x00) // UTF-16 little endian, no BOM { e = SupportedEncoding.UTF16LE; if (notOutOfBand && (b3 != '?' || b4 != 0x00)) throw new XmlException(SR.XmlDeclMissing); preserve = 4; } else if (b1 == 0xEF && b2 == 0xBB) // UTF8 with BOM { // Encoding error if (notOutOfBand && b3 != 0xBF) throw new XmlException(SR.XmlBadBOM); preserve = 1; } else // Assume UTF8 { preserve = 4; } return e; } private void FillBuffer(int count) { count -= _byteCount; while (count > 0) { int read = _stream.Read(_bytes, _byteOffset + _byteCount, count); if (read == 0) break; _byteCount += read; count -= read; } } private void EnsureBuffers() { EnsureByteBuffer(); if (_chars == null) _chars = new char[BufferLength]; } private void EnsureByteBuffer() { if (_bytes != null) return; _bytes = new byte[BufferLength * 4]; _byteOffset = 0; _byteCount = 0; } private static void CheckUTF8DeclarationEncoding(byte[] buffer, int offset, int count, SupportedEncoding e, SupportedEncoding expectedEnc) { byte quot = 0; int encEq = -1; int max = offset + Math.Min(count, BufferLength); // Encoding should be second "=", abort at first "?" int i = 0; int eq = 0; for (i = offset + 2; i < max; i++) // Skip the "<?" so we don't get caught by the first "?" { if (quot != 0) { if (buffer[i] == quot) { quot = 0; } continue; } if (buffer[i] == (byte)'\'' || buffer[i] == (byte)'"') { quot = buffer[i]; } else if (buffer[i] == (byte)'=') { if (eq == 1) { encEq = i; break; } eq++; } else if (buffer[i] == (byte)'?') // Not legal character in a decl before second "=" { break; } } // No encoding found if (encEq == -1) { if (e != SupportedEncoding.UTF8 && expectedEnc == SupportedEncoding.None) throw new XmlException(SR.XmlDeclarationRequired); return; } if (encEq < 28) // Earliest second "=" can appear throw new XmlException(SR.XmlMalformedDecl); // Back off whitespace for (i = encEq - 1; IsWhitespace(buffer[i]); i--) ; // Check for encoding attribute if (!Compare(s_encodingAttr, buffer, i - s_encodingAttr.Length + 1)) { if (e != SupportedEncoding.UTF8 && expectedEnc == SupportedEncoding.None) throw new XmlException(SR.XmlDeclarationRequired); return; } // Move ahead of whitespace for (i = encEq + 1; i < max && IsWhitespace(buffer[i]); i++) ; // Find the quotes if (buffer[i] != '\'' && buffer[i] != '"') throw new XmlException(SR.XmlMalformedDecl); quot = buffer[i]; int q = i; for (i = q + 1; buffer[i] != quot && i < max; ++i) ; if (buffer[i] != quot) throw new XmlException(SR.XmlMalformedDecl); int encStart = q + 1; int encCount = i - encStart; // lookup the encoding SupportedEncoding declEnc = e; if (encCount == s_encodingUTF8.Length && CompareCaseInsensitive(s_encodingUTF8, buffer, encStart)) { declEnc = SupportedEncoding.UTF8; } else if (encCount == s_encodingUnicodeLE.Length && CompareCaseInsensitive(s_encodingUnicodeLE, buffer, encStart)) { declEnc = SupportedEncoding.UTF16LE; } else if (encCount == s_encodingUnicodeBE.Length && CompareCaseInsensitive(s_encodingUnicodeBE, buffer, encStart)) { declEnc = SupportedEncoding.UTF16BE; } else if (encCount == s_encodingUnicode.Length && CompareCaseInsensitive(s_encodingUnicode, buffer, encStart)) { if (e == SupportedEncoding.UTF8) ThrowEncodingMismatch(s_safeUTF8.GetString(buffer, encStart, encCount), s_safeUTF8.GetString(s_encodingUTF8, 0, s_encodingUTF8.Length)); } else { ThrowEncodingMismatch(s_safeUTF8.GetString(buffer, encStart, encCount), e); } if (e != declEnc) ThrowEncodingMismatch(s_safeUTF8.GetString(buffer, encStart, encCount), e); } private static bool CompareCaseInsensitive(byte[] key, byte[] buffer, int offset) { for (int i = 0; i < key.Length; i++) { if (key[i] == buffer[offset + i]) continue; if (key[i] != Char.ToLowerInvariant((char)buffer[offset + i])) return false; } return true; } private static bool Compare(byte[] key, byte[] buffer, int offset) { for (int i = 0; i < key.Length; i++) { if (key[i] != buffer[offset + i]) return false; } return true; } private static bool IsWhitespace(byte ch) { return ch == (byte)' ' || ch == (byte)'\n' || ch == (byte)'\t' || ch == (byte)'\r'; } internal static ArraySegment<byte> ProcessBuffer(byte[] buffer, int offset, int count, Encoding encoding) { if (count < 4) throw new XmlException(SR.UnexpectedEndOfFile); try { int preserve; ArraySegment<byte> seg; SupportedEncoding expectedEnc = GetSupportedEncoding(encoding); SupportedEncoding declEnc = ReadBOMEncoding(buffer[offset], buffer[offset + 1], buffer[offset + 2], buffer[offset + 3], encoding == null, out preserve); if (expectedEnc != SupportedEncoding.None && expectedEnc != declEnc) ThrowExpectedEncodingMismatch(expectedEnc, declEnc); offset += 4 - preserve; count -= 4 - preserve; // Fastpath: UTF-8 char[] chars; byte[] bytes; Encoding localEnc; if (declEnc == SupportedEncoding.UTF8) { // Fastpath: No declaration if (buffer[offset + 1] != '?' || buffer[offset] != '<') { seg = new ArraySegment<byte>(buffer, offset, count); return seg; } CheckUTF8DeclarationEncoding(buffer, offset, count, declEnc, expectedEnc); seg = new ArraySegment<byte>(buffer, offset, count); return seg; } // Convert to UTF-8 localEnc = GetSafeEncoding(declEnc); int inputCount = Math.Min(count, BufferLength * 2); chars = new char[localEnc.GetMaxCharCount(inputCount)]; int ccount = localEnc.GetChars(buffer, offset, inputCount, chars, 0); bytes = new byte[s_validatingUTF8.GetMaxByteCount(ccount)]; int bcount = s_validatingUTF8.GetBytes(chars, 0, ccount, bytes, 0); // Check for declaration if (bytes[1] == '?' && bytes[0] == '<') { CheckUTF8DeclarationEncoding(bytes, 0, bcount, declEnc, expectedEnc); } else { // Declaration required if no out-of-band encoding if (expectedEnc == SupportedEncoding.None) throw new XmlException(SR.XmlDeclarationRequired); } seg = new ArraySegment<byte>(s_validatingUTF8.GetBytes(GetEncoding(declEnc).GetChars(buffer, offset, count))); return seg; } catch (DecoderFallbackException e) { throw new XmlException(SR.XmlInvalidBytes, e); } } private static void ThrowExpectedEncodingMismatch(SupportedEncoding expEnc, SupportedEncoding actualEnc) { throw new XmlException(SR.Format(SR.XmlExpectedEncoding, GetEncodingName(expEnc), GetEncodingName(actualEnc))); } private static void ThrowEncodingMismatch(string declEnc, SupportedEncoding enc) { ThrowEncodingMismatch(declEnc, GetEncodingName(enc)); } private static void ThrowEncodingMismatch(string declEnc, string docEnc) { throw new XmlException(SR.Format(SR.XmlEncodingMismatch, declEnc, docEnc)); } // This stream wrapper does not support duplex public override bool CanRead { get { if (!_isReading) return false; return _stream.CanRead; } } // The encoding conversion and buffering breaks seeking. public override bool CanSeek { get { return false; } } // This stream wrapper does not support duplex public override bool CanWrite { get { if (_isReading) return false; return _stream.CanWrite; } } // The encoding conversion and buffering breaks seeking. public override long Position { get { throw new NotSupportedException(); } set { throw new NotSupportedException(); } } protected override void Dispose(bool disposing) { Flush(); _stream.Dispose(); base.Dispose(disposing); } public override void Flush() { _stream.Flush(); } public override int ReadByte() { if (_byteCount == 0 && _encodingCode == SupportedEncoding.UTF8) return _stream.ReadByte(); if (Read(_byteBuffer, 0, 1) == 0) return -1; return _byteBuffer[0]; } public override int Read(byte[] buffer, int offset, int count) { try { if (_byteCount == 0) { if (_encodingCode == SupportedEncoding.UTF8) return _stream.Read(buffer, offset, count); // No more bytes than can be turned into characters _byteOffset = 0; _byteCount = _stream.Read(_bytes, _byteCount, (_chars.Length - 1) * 2); // Check for end of stream if (_byteCount == 0) return 0; // Fix up incomplete chars CleanupCharBreak(); // Change encoding int charCount = _encoding.GetChars(_bytes, 0, _byteCount, _chars, 0); _byteCount = Encoding.UTF8.GetBytes(_chars, 0, charCount, _bytes, 0); } // Give them bytes if (_byteCount < count) count = _byteCount; Buffer.BlockCopy(_bytes, _byteOffset, buffer, offset, count); _byteOffset += count; _byteCount -= count; return count; } catch (DecoderFallbackException ex) { throw new XmlException(SR.XmlInvalidBytes, ex); } } private void CleanupCharBreak() { int max = _byteOffset + _byteCount; // Read on 2 byte boundaries if ((_byteCount % 2) != 0) { int b = _stream.ReadByte(); if (b < 0) throw new XmlException(SR.UnexpectedEndOfFile); _bytes[max++] = (byte)b; _byteCount++; } // Don't cut off a surrogate character int w; if (_encodingCode == SupportedEncoding.UTF16LE) { w = _bytes[max - 2] + (_bytes[max - 1] << 8); } else { w = _bytes[max - 1] + (_bytes[max - 2] << 8); } if ((w & 0xDC00) != 0xDC00 && w >= 0xD800 && w <= 0xDBFF) // First 16-bit number of surrogate pair { int b1 = _stream.ReadByte(); int b2 = _stream.ReadByte(); if (b2 < 0) throw new XmlException(SR.UnexpectedEndOfFile); _bytes[max++] = (byte)b1; _bytes[max++] = (byte)b2; _byteCount += 2; } } public override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException(); } public override void WriteByte(byte b) { if (_encodingCode == SupportedEncoding.UTF8) { _stream.WriteByte(b); return; } _byteBuffer[0] = b; Write(_byteBuffer, 0, 1); } public override void Write(byte[] buffer, int offset, int count) { // Optimize UTF-8 case if (_encodingCode == SupportedEncoding.UTF8) { _stream.Write(buffer, offset, count); return; } while (count > 0) { int size = _chars.Length < count ? _chars.Length : count; int charCount = _dec.GetChars(buffer, offset, size, _chars, 0, false); _byteCount = _enc.GetBytes(_chars, 0, charCount, _bytes, 0, false); _stream.Write(_bytes, 0, _byteCount); offset += size; count -= size; } } // Delegate properties public override bool CanTimeout { get { return _stream.CanTimeout; } } public override long Length { get { return _stream.Length; } } public override int ReadTimeout { get { return _stream.ReadTimeout; } set { _stream.ReadTimeout = value; } } public override int WriteTimeout { get { return _stream.WriteTimeout; } set { _stream.WriteTimeout = value; } } // Delegate methods public override void SetLength(long value) { throw new NotSupportedException(); } } // Add format exceptions // Do we need to modify the stream position/Seek to account for the buffer? // ASSUMPTION (Microsoft): This class will only be used for EITHER reading OR writing. }
// 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.Azure.Authentication; using System.Buffers; using System.Buffers.Cryptography; using System.Buffers.Text; using System.Globalization; using System.Security.Cryptography; using System.Text; using System.Text.Encodings.Web.Utf8; using System.Text.Utf8; using System.Runtime.InteropServices; using BenchmarkDotNet.Attributes; namespace System.Azure.Experimental.Benchmarks { public class CosmosDb { static string fakeKey = ""; static string keyType = "master"; static string resourceType = "dbs"; static string version = "1.0"; static string resourceId = ""; static string verb = "GET"; static Utf8String keyTypeU8 = (Utf8String)"master"; static Utf8String resourceTypeU8 = (Utf8String)"dbs"; static Utf8String versionU8 = (Utf8String)"1.0"; static Utf8String resourceIdU8 = Utf8String.Empty; static Utf8String verbU8 = (Utf8String)"GET"; static DateTime utc = DateTime.UtcNow; static byte[] output = new byte[256]; static Sha256 sha; [GlobalSetup] public void Setup() { var keyBytes = Key.ComputeKeyBytes(fakeKey); sha = Sha256.Create(keyBytes); } [Benchmark(Baseline = true)] public string Msdn() => CosmosDbBaselineFromMsdn(fakeKey, keyType, verb, resourceId, resourceType, version, utc); [Benchmark] public bool Primitives() => TryWritePrimitives(output, sha, keyType, verb, resourceId, resourceType, version, utc, out int bytesWritten); [Benchmark] public bool Writer() => CosmosDbAuthorizationHeader.TryWrite(output, sha, keyType, verb, resourceId, resourceType, version, utc, out int bytesWritten); [Benchmark] public bool WriterUtf8() => CosmosDbAuthorizationHeader.TryWrite(output, sha, keyTypeU8, verbU8, resourceIdU8, resourceTypeU8, versionU8, utc, out int bytesWritten); static string CosmosDbBaselineFromMsdn(string key, string keyType, string verb, string resourceId, string resourceType, string tokenVersion, DateTime utc) { var keyBytes = Convert.FromBase64String(key); var hmacSha256 = new HMACSHA256 { Key = keyBytes }; string utc_date = utc.ToString("r"); string payLoad = string.Format(CultureInfo.InvariantCulture, "{0}\n{1}\n{2}\n{3}\n{4}\n", verb.ToLowerInvariant(), resourceType.ToLowerInvariant(), resourceId, utc_date.ToLowerInvariant(), "" ); byte[] hashPayLoad = hmacSha256.ComputeHash(Encoding.UTF8.GetBytes(payLoad)); string signature = Convert.ToBase64String(hashPayLoad); var full = String.Format(CultureInfo.InvariantCulture, "type={0}&ver={1}&sig={2}", keyType, tokenVersion, signature); var result = Text.Encodings.Web.UrlEncoder.Default.Encode(full); return result; } static bool TryWritePrimitives(Span<byte> output, Sha256 hash, string keyType, string verb, string resourceId, string resourceType, string tokenVersion, DateTime utc, out int bytesWritten) { int totalWritten = 0; bytesWritten = 0; Span<byte> buffer = stackalloc byte[AuthenticationHeaderBufferSize]; s_type.CopyTo(buffer); totalWritten += s_type.Length; if (TextEncodings.Utf16.ToUtf8(MemoryMarshal.AsBytes(keyType.AsSpan()), buffer.Slice(totalWritten), out int consumed, out int written) != OperationStatus.Done) { throw new NotImplementedException("need to resize buffer"); } totalWritten += written; s_ver.CopyTo(buffer.Slice(totalWritten)); totalWritten += s_ver.Length; if (TextEncodings.Utf16.ToUtf8(MemoryMarshal.AsBytes(tokenVersion.AsSpan()), buffer.Slice(totalWritten), out consumed, out written) != OperationStatus.Done) { throw new NotImplementedException("need to resize buffer"); } totalWritten += written; s_sig.CopyTo(buffer.Slice(totalWritten)); totalWritten += s_sig.Length; var front = buffer.Slice(0, totalWritten); var payload = buffer.Slice(totalWritten); totalWritten = 0; if (verb.Equals("GET", StringComparison.Ordinal) || verb.Equals("get", StringComparison.Ordinal)) { s_get.CopyTo(payload); totalWritten += s_get.Length; } else if (verb.Equals("POST", StringComparison.Ordinal) || verb.Equals("post", StringComparison.Ordinal)) { s_post.CopyTo(payload); totalWritten += s_post.Length; } else if (verb.Equals("DELETE", StringComparison.Ordinal) || verb.Equals("delete", StringComparison.Ordinal)) { s_delete.CopyTo(payload); totalWritten += s_delete.Length; } else { if (TextEncodings.Utf16.ToUtf8(MemoryMarshal.AsBytes(verb.AsSpan()), payload, out consumed, out written) != OperationStatus.Done) { throw new NotImplementedException("need to resize buffer"); } if (TextEncodings.Ascii.ToLowerInPlace(payload.Slice(0, written), out written) != OperationStatus.Done) { throw new NotImplementedException("need to resize buffer"); } payload[written] = (byte)'\n'; totalWritten += written + 1; } var bufferSlice = payload.Slice(totalWritten); if (TextEncodings.Utf16.ToUtf8(MemoryMarshal.AsBytes(resourceType.AsSpan()), bufferSlice, out consumed, out written) != OperationStatus.Done) { throw new NotImplementedException("need to resize buffer"); } if (TextEncodings.Ascii.ToLowerInPlace(bufferSlice.Slice(0, written), out written) != OperationStatus.Done) { throw new NotImplementedException("need to resize buffer"); } bufferSlice[written] = (byte)'\n'; totalWritten += written + 1; bufferSlice = payload.Slice(totalWritten); if (TextEncodings.Utf16.ToUtf8(MemoryMarshal.AsBytes(resourceId.AsSpan()), bufferSlice, out consumed, out written) != OperationStatus.Done) { throw new NotImplementedException("need to resize buffer"); } bufferSlice[written] = (byte)'\n'; totalWritten += written + 1; bufferSlice = payload.Slice(totalWritten); if (!Utf8Formatter.TryFormat(utc, bufferSlice, out written, 'l')) { throw new NotImplementedException("need to resize buffer"); } bufferSlice[written] = (byte)'\n'; totalWritten += written + 1; bufferSlice = payload.Slice(totalWritten); bufferSlice[0] = (byte)'\n'; totalWritten += 1; hash.Append(buffer.Slice(front.Length, totalWritten)); if (!hash.TryWrite(buffer.Slice(front.Length), out written)) { throw new NotImplementedException("need to resize buffer"); } if (Base64.EncodeToUtf8InPlace(buffer.Slice(front.Length), written, out written) != OperationStatus.Done) { throw new NotImplementedException("need to resize buffer"); } var len = front.Length + written; if (UrlEncoder.Utf8.Encode(buffer.Slice(0, len), output, out consumed, out bytesWritten) != OperationStatus.Done) { bytesWritten = 0; return false; } return true; } static readonly byte[] s_type = Encoding.UTF8.GetBytes("type="); static readonly byte[] s_ver = Encoding.UTF8.GetBytes("&ver="); static readonly byte[] s_sig = Encoding.UTF8.GetBytes("&sig="); static readonly byte[] s_get = Encoding.UTF8.GetBytes("get\n"); static readonly byte[] s_post = Encoding.UTF8.GetBytes("post\n"); static readonly byte[] s_delete = Encoding.UTF8.GetBytes("delete\n"); const int AuthenticationHeaderBufferSize = 256; } }
// 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; /// <summary> /// System.Collections.Generic.ICollection.Add(T) /// </summary> public class ICollectionAdd { private int c_MINI_STRING_LENGTH = 8; private int c_MAX_STRING_LENGTH = 256; public static int Main(string[] args) { ICollectionAdd testObj = new ICollectionAdd(); TestLibrary.TestFramework.BeginTestCase("Testing for Methord: System.Collections.Generic.ICollection.Add(T)"); if (testObj.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; retVal = PosTest3() && retVal; TestLibrary.TestFramework.LogInformation("[Netativ]"); retVal = NegTest1() && retVal; return retVal; } #region Positive tests public bool PosTest1() { bool retVal = true; const string c_TEST_DESC = "PosTest1: Using List<T> which implemented the add method in ICollection<T> and Type is int..."; const string c_TEST_ID = "P001"; List<int> list = new List<int>(); int item1 = TestLibrary.Generator.GetInt32(-55); TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { ((ICollection<int>)list).Add(item1); if (list[0] != item1) { string errorDesc = "Value is not " + list[0] + " as expected: Actual(" + item1 + ")"; TestLibrary.TestFramework.LogError("001" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("002", "Unecpected exception occurs :" + e); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; const string c_TEST_DESC = "PosTest2: Using List<T> which implemented the add method in ICollection<T> and Type is a reference type..."; const string c_TEST_ID = "P002"; List<String> list = new List<String>(); String item1 = TestLibrary.Generator.GetString(-55, false,c_MINI_STRING_LENGTH,c_MAX_STRING_LENGTH); TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { ((ICollection<String>)list).Add(item1); if (list[0] != item1) { string errorDesc = "Value is not " + list[0] + " as expected: Actual(" + item1 + ")"; TestLibrary.TestFramework.LogError("003" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("004", "Unecpected exception occurs :" + e); retVal = false; } return retVal; } public bool PosTest3() { bool retVal = true; const string c_TEST_DESC = "PosTest3: Using List<T> which implemented the add method in ICollection<T> and Type is a reference type..."; const string c_TEST_ID = "P003"; MyCollection<int> myC = new MyCollection<int>(); int item1 = TestLibrary.Generator.GetInt32(-55); int count = 1; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { ((ICollection<int>)myC).Add(item1); if (myC.Count != count) { string errorDesc = "Value have not been add to ICollection<T>"; TestLibrary.TestFramework.LogError("005" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("006", "Unecpected exception occurs :" + e); retVal = false; } return retVal; } #endregion #region Nagetive Test Cases public bool NegTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest1: Using user-defined type which is readonly"); MyCollection<int> myC = new MyCollection<int>(); myC.isReadOnly = true; int item1 = TestLibrary.Generator.GetInt32(-55); try { ((ICollection<int>)myC).Add(item1); TestLibrary.TestFramework.LogError("007", "The NotSupportedException was not thrown as expected"); retVal = false; } catch (NotSupportedException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("008", "Unexpected exception: " + e); retVal = false; } return retVal; } #endregion #region Help Class public class MyCollection<T> : ICollection<T> { public T[] value; protected int length; public bool isReadOnly = false; public MyCollection() { value =new T[10]; length = 0; } #region ICollection<T> Members public void Add(T item) { if (isReadOnly) { throw new NotSupportedException(); } else { value[length] = item; length++; } } public void Clear() { throw new Exception("The method or operation is not implemented."); } public bool Contains(T item) { throw new Exception("The method or operation is not implemented."); } public void CopyTo(T[] array, int arrayIndex) { throw new Exception("The method or operation is not implemented."); } public int Count { get { return length;} } public bool IsReadOnly { get { return isReadOnly; } } public bool Remove(T item) { throw new Exception("The method or operation is not implemented."); } #endregion #region IEnumerable<T> Members public IEnumerator<T> GetEnumerator() { throw new Exception("The method or operation is not implemented."); } #endregion #region IEnumerable Members System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw new Exception("The method or operation is not implemented."); } #endregion } #endregion }
using Microsoft.IdentityModel.S2S.Protocols.OAuth2; using Microsoft.IdentityModel.Tokens; using Microsoft.SharePoint.Client; using System; using System.Net; using System.Security.Principal; using System.Web; using System.Web.Configuration; namespace StockRequestApprovalWeb { /// <summary> /// Encapsulates all the information from SharePoint. /// </summary> public abstract class SharePointContext { public const string SPHostUrlKey = "SPHostUrl"; public const string SPAppWebUrlKey = "SPAppWebUrl"; public const string SPLanguageKey = "SPLanguage"; public const string SPClientTagKey = "SPClientTag"; public const string SPProductNumberKey = "SPProductNumber"; protected static readonly TimeSpan AccessTokenLifetimeTolerance = TimeSpan.FromMinutes(5.0); private readonly Uri spHostUrl; private readonly Uri spAppWebUrl; private readonly string spLanguage; private readonly string spClientTag; private readonly string spProductNumber; // <AccessTokenString, UtcExpiresOn> protected Tuple<string, DateTime> userAccessTokenForSPHost; protected Tuple<string, DateTime> userAccessTokenForSPAppWeb; protected Tuple<string, DateTime> appOnlyAccessTokenForSPHost; protected Tuple<string, DateTime> appOnlyAccessTokenForSPAppWeb; /// <summary> /// Gets the SharePoint host url from QueryString of the specified HTTP request. /// </summary> /// <param name="httpRequest">The specified HTTP request.</param> /// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns> public static Uri GetSPHostUrl(HttpRequestBase httpRequest) { if (httpRequest == null) { throw new ArgumentNullException("httpRequest"); } string spHostUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SPHostUrlKey]); Uri spHostUrl; if (Uri.TryCreate(spHostUrlString, UriKind.Absolute, out spHostUrl) && (spHostUrl.Scheme == Uri.UriSchemeHttp || spHostUrl.Scheme == Uri.UriSchemeHttps)) { return spHostUrl; } return null; } /// <summary> /// Gets the SharePoint host url from QueryString of the specified HTTP request. /// </summary> /// <param name="httpRequest">The specified HTTP request.</param> /// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns> public static Uri GetSPHostUrl(HttpRequest httpRequest) { return GetSPHostUrl(new HttpRequestWrapper(httpRequest)); } /// <summary> /// The SharePoint host url. /// </summary> public Uri SPHostUrl { get { return this.spHostUrl; } } /// <summary> /// The SharePoint app web url. /// </summary> public Uri SPAppWebUrl { get { return this.spAppWebUrl; } } /// <summary> /// The SharePoint language. /// </summary> public string SPLanguage { get { return this.spLanguage; } } /// <summary> /// The SharePoint client tag. /// </summary> public string SPClientTag { get { return this.spClientTag; } } /// <summary> /// The SharePoint product number. /// </summary> public string SPProductNumber { get { return this.spProductNumber; } } /// <summary> /// The user access token for the SharePoint host. /// </summary> public abstract string UserAccessTokenForSPHost { get; } /// <summary> /// The user access token for the SharePoint app web. /// </summary> public abstract string UserAccessTokenForSPAppWeb { get; } /// <summary> /// The app only access token for the SharePoint host. /// </summary> public abstract string AppOnlyAccessTokenForSPHost { get; } /// <summary> /// The app only access token for the SharePoint app web. /// </summary> public abstract string AppOnlyAccessTokenForSPAppWeb { get; } /// <summary> /// Constructor. /// </summary> /// <param name="spHostUrl">The SharePoint host url.</param> /// <param name="spAppWebUrl">The SharePoint app web url.</param> /// <param name="spLanguage">The SharePoint language.</param> /// <param name="spClientTag">The SharePoint client tag.</param> /// <param name="spProductNumber">The SharePoint product number.</param> protected SharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber) { if (spHostUrl == null) { throw new ArgumentNullException("spHostUrl"); } if (string.IsNullOrEmpty(spLanguage)) { throw new ArgumentNullException("spLanguage"); } if (string.IsNullOrEmpty(spClientTag)) { throw new ArgumentNullException("spClientTag"); } if (string.IsNullOrEmpty(spProductNumber)) { throw new ArgumentNullException("spProductNumber"); } this.spHostUrl = spHostUrl; this.spAppWebUrl = spAppWebUrl; this.spLanguage = spLanguage; this.spClientTag = spClientTag; this.spProductNumber = spProductNumber; } /// <summary> /// Creates a user ClientContext for the SharePoint host. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateUserClientContextForSPHost() { return CreateClientContext(this.SPHostUrl, this.UserAccessTokenForSPHost); } /// <summary> /// Creates a user ClientContext for the SharePoint app web. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateUserClientContextForSPAppWeb() { return CreateClientContext(this.SPAppWebUrl, this.UserAccessTokenForSPAppWeb); } /// <summary> /// Creates app only ClientContext for the SharePoint host. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateAppOnlyClientContextForSPHost() { return CreateClientContext(this.SPHostUrl, this.AppOnlyAccessTokenForSPHost); } /// <summary> /// Creates an app only ClientContext for the SharePoint app web. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateAppOnlyClientContextForSPAppWeb() { return CreateClientContext(this.SPAppWebUrl, this.AppOnlyAccessTokenForSPAppWeb); } /// <summary> /// Gets the database connection string from SharePoint for autohosted add-in. /// This method is deprecated because the autohosted option is no longer available. /// </summary> [ObsoleteAttribute("This method is deprecated because the autohosted option is no longer available.", true)] public string GetDatabaseConnectionString() { throw new NotSupportedException("This method is deprecated because the autohosted option is no longer available."); } /// <summary> /// Determines if the specified access token is valid. /// It considers an access token as not valid if it is null, or it has expired. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <returns>True if the access token is valid.</returns> protected static bool IsAccessTokenValid(Tuple<string, DateTime> accessToken) { return accessToken != null && !string.IsNullOrEmpty(accessToken.Item1) && accessToken.Item2 > DateTime.UtcNow; } /// <summary> /// Creates a ClientContext with the specified SharePoint site url and the access token. /// </summary> /// <param name="spSiteUrl">The site url.</param> /// <param name="accessToken">The access token.</param> /// <returns>A ClientContext instance.</returns> private static ClientContext CreateClientContext(Uri spSiteUrl, string accessToken) { if (spSiteUrl != null && !string.IsNullOrEmpty(accessToken)) { return TokenHelper.GetClientContextWithAccessToken(spSiteUrl.AbsoluteUri, accessToken); } return null; } } /// <summary> /// Redirection status. /// </summary> public enum RedirectionStatus { Ok, ShouldRedirect, CanNotRedirect } /// <summary> /// Provides SharePointContext instances. /// </summary> public abstract class SharePointContextProvider { private static SharePointContextProvider current; /// <summary> /// The current SharePointContextProvider instance. /// </summary> public static SharePointContextProvider Current { get { return SharePointContextProvider.current; } } /// <summary> /// Initializes the default SharePointContextProvider instance. /// </summary> static SharePointContextProvider() { if (!TokenHelper.IsHighTrustApp()) { SharePointContextProvider.current = new SharePointAcsContextProvider(); } else { SharePointContextProvider.current = new SharePointHighTrustContextProvider(); } } /// <summary> /// Registers the specified SharePointContextProvider instance as current. /// It should be called by Application_Start() in Global.asax. /// </summary> /// <param name="provider">The SharePointContextProvider to be set as current.</param> public static void Register(SharePointContextProvider provider) { if (provider == null) { throw new ArgumentNullException("provider"); } SharePointContextProvider.current = provider; } /// <summary> /// Checks if it is necessary to redirect to SharePoint for user to authenticate. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param> /// <returns>Redirection status.</returns> public static RedirectionStatus CheckRedirectionStatus(HttpContextBase httpContext, out Uri redirectUrl) { if (httpContext == null) { throw new ArgumentNullException("httpContext"); } redirectUrl = null; bool contextTokenExpired = false; try { if (SharePointContextProvider.Current.GetSharePointContext(httpContext) != null) { return RedirectionStatus.Ok; } } catch (SecurityTokenExpiredException) { contextTokenExpired = true; } const string SPHasRedirectedToSharePointKey = "SPHasRedirectedToSharePoint"; if (!string.IsNullOrEmpty(httpContext.Request.QueryString[SPHasRedirectedToSharePointKey]) && !contextTokenExpired) { return RedirectionStatus.CanNotRedirect; } Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); if (spHostUrl == null) { return RedirectionStatus.CanNotRedirect; } if (StringComparer.OrdinalIgnoreCase.Equals(httpContext.Request.HttpMethod, "POST")) { return RedirectionStatus.CanNotRedirect; } Uri requestUrl = httpContext.Request.Url; var queryNameValueCollection = HttpUtility.ParseQueryString(requestUrl.Query); // Removes the values that are included in {StandardTokens}, as {StandardTokens} will be inserted at the beginning of the query string. queryNameValueCollection.Remove(SharePointContext.SPHostUrlKey); queryNameValueCollection.Remove(SharePointContext.SPAppWebUrlKey); queryNameValueCollection.Remove(SharePointContext.SPLanguageKey); queryNameValueCollection.Remove(SharePointContext.SPClientTagKey); queryNameValueCollection.Remove(SharePointContext.SPProductNumberKey); // Adds SPHasRedirectedToSharePoint=1. queryNameValueCollection.Add(SPHasRedirectedToSharePointKey, "1"); UriBuilder returnUrlBuilder = new UriBuilder(requestUrl); returnUrlBuilder.Query = queryNameValueCollection.ToString(); // Inserts StandardTokens. const string StandardTokens = "{StandardTokens}"; string returnUrlString = returnUrlBuilder.Uri.AbsoluteUri; returnUrlString = returnUrlString.Insert(returnUrlString.IndexOf("?") + 1, StandardTokens + "&"); // Constructs redirect url. string redirectUrlString = TokenHelper.GetAppContextTokenRequestUrl(spHostUrl.AbsoluteUri, Uri.EscapeDataString(returnUrlString)); redirectUrl = new Uri(redirectUrlString, UriKind.Absolute); return RedirectionStatus.ShouldRedirect; } /// <summary> /// Checks if it is necessary to redirect to SharePoint for user to authenticate. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param> /// <returns>Redirection status.</returns> public static RedirectionStatus CheckRedirectionStatus(HttpContext httpContext, out Uri redirectUrl) { return CheckRedirectionStatus(new HttpContextWrapper(httpContext), out redirectUrl); } /// <summary> /// Creates a SharePointContext instance with the specified HTTP request. /// </summary> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> public SharePointContext CreateSharePointContext(HttpRequestBase httpRequest) { if (httpRequest == null) { throw new ArgumentNullException("httpRequest"); } // SPHostUrl Uri spHostUrl = SharePointContext.GetSPHostUrl(httpRequest); if (spHostUrl == null) { return null; } // SPAppWebUrl string spAppWebUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SharePointContext.SPAppWebUrlKey]); Uri spAppWebUrl; if (!Uri.TryCreate(spAppWebUrlString, UriKind.Absolute, out spAppWebUrl) || !(spAppWebUrl.Scheme == Uri.UriSchemeHttp || spAppWebUrl.Scheme == Uri.UriSchemeHttps)) { spAppWebUrl = null; } // SPLanguage string spLanguage = httpRequest.QueryString[SharePointContext.SPLanguageKey]; if (string.IsNullOrEmpty(spLanguage)) { return null; } // SPClientTag string spClientTag = httpRequest.QueryString[SharePointContext.SPClientTagKey]; if (string.IsNullOrEmpty(spClientTag)) { return null; } // SPProductNumber string spProductNumber = httpRequest.QueryString[SharePointContext.SPProductNumberKey]; if (string.IsNullOrEmpty(spProductNumber)) { return null; } return CreateSharePointContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, httpRequest); } /// <summary> /// Creates a SharePointContext instance with the specified HTTP request. /// </summary> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> public SharePointContext CreateSharePointContext(HttpRequest httpRequest) { return CreateSharePointContext(new HttpRequestWrapper(httpRequest)); } /// <summary> /// Gets a SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns> public SharePointContext GetSharePointContext(HttpContextBase httpContext) { if (httpContext == null) { throw new ArgumentNullException("httpContext"); } Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); if (spHostUrl == null) { return null; } SharePointContext spContext = LoadSharePointContext(httpContext); if (spContext == null || !ValidateSharePointContext(spContext, httpContext)) { spContext = CreateSharePointContext(httpContext.Request); if (spContext != null) { SaveSharePointContext(spContext, httpContext); } } return spContext; } /// <summary> /// Gets a SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns> public SharePointContext GetSharePointContext(HttpContext httpContext) { return GetSharePointContext(new HttpContextWrapper(httpContext)); } /// <summary> /// Creates a SharePointContext instance. /// </summary> /// <param name="spHostUrl">The SharePoint host url.</param> /// <param name="spAppWebUrl">The SharePoint app web url.</param> /// <param name="spLanguage">The SharePoint language.</param> /// <param name="spClientTag">The SharePoint client tag.</param> /// <param name="spProductNumber">The SharePoint product number.</param> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> protected abstract SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest); /// <summary> /// Validates if the given SharePointContext can be used with the specified HTTP context. /// </summary> /// <param name="spContext">The SharePointContext.</param> /// <param name="httpContext">The HTTP context.</param> /// <returns>True if the given SharePointContext can be used with the specified HTTP context.</returns> protected abstract bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext); /// <summary> /// Loads the SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found.</returns> protected abstract SharePointContext LoadSharePointContext(HttpContextBase httpContext); /// <summary> /// Saves the specified SharePointContext instance associated with the specified HTTP context. /// <c>null</c> is accepted for clearing the SharePointContext instance associated with the HTTP context. /// </summary> /// <param name="spContext">The SharePointContext instance to be saved, or <c>null</c>.</param> /// <param name="httpContext">The HTTP context.</param> protected abstract void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext); } #region ACS /// <summary> /// Encapsulates all the information from SharePoint in ACS mode. /// </summary> public class SharePointAcsContext : SharePointContext { private readonly string contextToken; private readonly SharePointContextToken contextTokenObj; /// <summary> /// The context token. /// </summary> public string ContextToken { get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextToken : null; } } /// <summary> /// The context token's "CacheKey" claim. /// </summary> public string CacheKey { get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.CacheKey : null; } } /// <summary> /// The context token's "refreshtoken" claim. /// </summary> public string RefreshToken { get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.RefreshToken : null; } } public override string UserAccessTokenForSPHost { get { return GetAccessTokenString(ref this.userAccessTokenForSPHost, () => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPHostUrl.Authority)); } } public override string UserAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb, () => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPAppWebUrl.Authority)); } } public override string AppOnlyAccessTokenForSPHost { get { return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost, () => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPHostUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPHostUrl))); } } public override string AppOnlyAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb, () => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPAppWebUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPAppWebUrl))); } } public SharePointAcsContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, string contextToken, SharePointContextToken contextTokenObj) : base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber) { if (string.IsNullOrEmpty(contextToken)) { throw new ArgumentNullException("contextToken"); } if (contextTokenObj == null) { throw new ArgumentNullException("contextTokenObj"); } this.contextToken = contextToken; this.contextTokenObj = contextTokenObj; } /// <summary> /// Ensures the access token is valid and returns it. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> /// <returns>The access token string.</returns> private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler) { RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler); return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null; } /// <summary> /// Renews the access token if it is not valid. /// </summary> /// <param name="accessToken">The access token to renew.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler) { if (IsAccessTokenValid(accessToken)) { return; } try { OAuth2AccessTokenResponse oAuth2AccessTokenResponse = tokenRenewalHandler(); DateTime expiresOn = oAuth2AccessTokenResponse.ExpiresOn; if ((expiresOn - oAuth2AccessTokenResponse.NotBefore) > AccessTokenLifetimeTolerance) { // Make the access token get renewed a bit earlier than the time when it expires // so that the calls to SharePoint with it will have enough time to complete successfully. expiresOn -= AccessTokenLifetimeTolerance; } accessToken = Tuple.Create(oAuth2AccessTokenResponse.AccessToken, expiresOn); } catch (WebException) { } } } /// <summary> /// Default provider for SharePointAcsContext. /// </summary> public class SharePointAcsContextProvider : SharePointContextProvider { private const string SPContextKey = "SPContext"; private const string SPCacheKeyKey = "SPCacheKey"; protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest) { string contextTokenString = TokenHelper.GetContextTokenFromRequest(httpRequest); if (string.IsNullOrEmpty(contextTokenString)) { return null; } SharePointContextToken contextToken = null; try { contextToken = TokenHelper.ReadAndValidateContextToken(contextTokenString, httpRequest.Url.Authority); } catch (WebException) { return null; } catch (AudienceUriValidationFailedException) { return null; } return new SharePointAcsContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, contextTokenString, contextToken); } protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointAcsContext spAcsContext = spContext as SharePointAcsContext; if (spAcsContext != null) { Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); string contextToken = TokenHelper.GetContextTokenFromRequest(httpContext.Request); HttpCookie spCacheKeyCookie = httpContext.Request.Cookies[SPCacheKeyKey]; string spCacheKey = spCacheKeyCookie != null ? spCacheKeyCookie.Value : null; return spHostUrl == spAcsContext.SPHostUrl && !string.IsNullOrEmpty(spAcsContext.CacheKey) && spCacheKey == spAcsContext.CacheKey && !string.IsNullOrEmpty(spAcsContext.ContextToken) && (string.IsNullOrEmpty(contextToken) || contextToken == spAcsContext.ContextToken); } return false; } protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext) { return httpContext.Session[SPContextKey] as SharePointAcsContext; } protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointAcsContext spAcsContext = spContext as SharePointAcsContext; if (spAcsContext != null) { HttpCookie spCacheKeyCookie = new HttpCookie(SPCacheKeyKey) { Value = spAcsContext.CacheKey, Secure = true, HttpOnly = true }; httpContext.Response.AppendCookie(spCacheKeyCookie); } httpContext.Session[SPContextKey] = spAcsContext; } } #endregion ACS #region HighTrust /// <summary> /// Encapsulates all the information from SharePoint in HighTrust mode. /// </summary> public class SharePointHighTrustContext : SharePointContext { private readonly WindowsIdentity logonUserIdentity; /// <summary> /// The Windows identity for the current user. /// </summary> public WindowsIdentity LogonUserIdentity { get { return this.logonUserIdentity; } } public override string UserAccessTokenForSPHost { get { return GetAccessTokenString(ref this.userAccessTokenForSPHost, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, this.LogonUserIdentity)); } } public override string UserAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, this.LogonUserIdentity)); } } public override string AppOnlyAccessTokenForSPHost { get { return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, null)); } } public override string AppOnlyAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, null)); } } public SharePointHighTrustContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, WindowsIdentity logonUserIdentity) : base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber) { if (logonUserIdentity == null) { throw new ArgumentNullException("logonUserIdentity"); } this.logonUserIdentity = logonUserIdentity; } /// <summary> /// Ensures the access token is valid and returns it. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> /// <returns>The access token string.</returns> private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler) { RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler); return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null; } /// <summary> /// Renews the access token if it is not valid. /// </summary> /// <param name="accessToken">The access token to renew.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler) { if (IsAccessTokenValid(accessToken)) { return; } DateTime expiresOn = DateTime.UtcNow.Add(TokenHelper.HighTrustAccessTokenLifetime); if (TokenHelper.HighTrustAccessTokenLifetime > AccessTokenLifetimeTolerance) { // Make the access token get renewed a bit earlier than the time when it expires // so that the calls to SharePoint with it will have enough time to complete successfully. expiresOn -= AccessTokenLifetimeTolerance; } accessToken = Tuple.Create(tokenRenewalHandler(), expiresOn); } } /// <summary> /// Default provider for SharePointHighTrustContext. /// </summary> public class SharePointHighTrustContextProvider : SharePointContextProvider { private const string SPContextKey = "SPContext"; protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest) { WindowsIdentity logonUserIdentity = httpRequest.LogonUserIdentity; if (logonUserIdentity == null || !logonUserIdentity.IsAuthenticated || logonUserIdentity.IsGuest || logonUserIdentity.User == null) { return null; } return new SharePointHighTrustContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, logonUserIdentity); } protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointHighTrustContext spHighTrustContext = spContext as SharePointHighTrustContext; if (spHighTrustContext != null) { Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); WindowsIdentity logonUserIdentity = httpContext.Request.LogonUserIdentity; return spHostUrl == spHighTrustContext.SPHostUrl && logonUserIdentity != null && logonUserIdentity.IsAuthenticated && !logonUserIdentity.IsGuest && logonUserIdentity.User == spHighTrustContext.LogonUserIdentity.User; } return false; } protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext) { return httpContext.Session[SPContextKey] as SharePointHighTrustContext; } protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { httpContext.Session[SPContextKey] = spContext as SharePointHighTrustContext; } } #endregion HighTrust }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // 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 Google.Ads.GoogleAds.Lib; using Google.Ads.GoogleAds.V8.Errors; using Google.Ads.GoogleAds.V8.Services; using Google.Protobuf.WellKnownTypes; using NUnit.Framework; using System.Linq; using static Google.Ads.GoogleAds.V8.Errors.ErrorLocation.Types; namespace Google.Ads.GoogleAds.Tests.V8.Errors { /// <summary> /// UnitTests for extensions in GoogleAdsFailureExtensionsTests.cs. /// </summary> [TestFixture] internal class GoogleAdsFailureExtensionsTests { private static readonly FieldPathElement OPERATIONS = new FieldPathElement() { FieldName = "operations", }; private static readonly FieldPathElement OPERATIONS_WITH_INDEX = new FieldPathElement() { FieldName = "operations", Index = 2 }; private static readonly FieldPathElement CREATE = new FieldPathElement() { FieldName = "create", }; private static readonly FieldPathElement NAME = new FieldPathElement() { FieldName = "name", }; private static readonly FieldPathElement NAME_WITH_INDEX = new FieldPathElement() { FieldName = "name", Index = 1 }; private static readonly GoogleAdsError OPERATIONS_2_NAME = CreateError( // operations[2].create.name new FieldPathElement[] { OPERATIONS_WITH_INDEX, CREATE, NAME } ); private static readonly GoogleAdsError OPERATIONS_NAME = CreateError( // operations.create.name new FieldPathElement[] { OPERATIONS, CREATE, NAME } ); private static readonly GoogleAdsError OPERATIONS_2_NAME_INDEX = CreateError( // operations[2].create.name new FieldPathElement[] { OPERATIONS_WITH_INDEX, CREATE, NAME_WITH_INDEX } ); /// <summary> /// Check if GetErrorsByOperationIndex method can retrieve errors by specified index. /// </summary> [Test] public void TestGetErrorsByOperationIndexWithErrors() { GoogleAdsFailure failure = new GoogleAdsFailure(); failure.Errors.Add(OPERATIONS_2_NAME); // There are no errors for index = 0. Assert.AreEqual(failure.GetErrorsByOperationIndex(0).ToList().Count, 0); // There is one error for index = 2. Assert.AreEqual(failure.GetErrorsByOperationIndex(2).ToList().Count, 1); } /// <summary> /// Check if GetErrorsByOperationIndex method can retrieve errors when the GoogleAdsFailure /// has no errors. /// </summary> [Test] public void TestGetErrorsByOperationIndexWhenNoErrors() { GoogleAdsFailure failure = new GoogleAdsFailure(); Assert.AreEqual(failure.GetErrorsByOperationIndex(0).ToList().Count, 0); } /// <summary> /// Check if GetErrorsByOperationIndex method can retrieve an empty list of errors when /// errors don't have any Location field set. /// </summary> [Test] public void TestGetErrorsByOperationIndexNoLocation() { GoogleAdsFailure failure = new GoogleAdsFailure(); failure.Errors.Add(new GoogleAdsError()); Assert.AreEqual(failure.GetErrorsByOperationIndex(0).ToList().Count, 0); } /// <summary> /// Check if GetErrorsByOperationIndex method can retrieve an empty list of errors when /// operations don't have an index. /// </summary> [Test] public void TestGetErrorsByOperationIndexNoOperationIndex() { GoogleAdsFailure failure = new GoogleAdsFailure(); failure.Errors.AddRange(new GoogleAdsError[] { OPERATIONS_NAME }); Assert.AreEqual(failure.GetErrorsByOperationIndex(0).ToList().Count, 0); } /// <summary> /// Tests for <see cref="GoogleAdsError.CombinedFieldPath"/> property. /// </summary> [Test] public void TestCombinedFieldPath() { Assert.AreEqual("operations[2].create.name", OPERATIONS_2_NAME.CombinedFieldPath); Assert.AreEqual("operations.create.name", OPERATIONS_NAME.CombinedFieldPath); Assert.AreEqual("operations[2].create.name[1]", OPERATIONS_2_NAME_INDEX.CombinedFieldPath); // If the location is empty, you get back Assert.IsEmpty(new GoogleAdsError().CombinedFieldPath); } /// <summary> /// Check if IsEmpty message evaluates to false for a non-empty message. /// </summary> [Test] public void TestIsEmptyForNonEmptyMessage() { MutateAdGroupResult successResult = new MutateAdGroupResult() { ResourceName = "TEST", }; Assert.False(successResult.IsEmpty()); } /// <summary> /// Check if IsEmpty message evaluates to true for an empty message. /// </summary> [Test] public void TestIsEmptyForEmptyMessage() { MutateAdGroupResult failedResult = new MutateAdGroupResult(); Assert.True(failedResult.IsEmpty()); } /// <summary> /// Verify that PartialFailure property can correctly deserialize a GoogleAdsFailure object. /// </summary> [Test] public void TestPartialFailureDeserialization() { GoogleAdsFailure failure = new GoogleAdsFailure(); failure.Errors.Add(OPERATIONS_2_NAME); MutateAdGroupsResponse failedResponse = new MutateAdGroupsResponse() { PartialFailureError = GetStatus(failure) }; Assert.True(failedResponse.PartialFailure.Equals(failure)); } /// <summary> /// Tests for PartialFailure property of Response objects when there is no error. /// </summary> [Test] public void TestPartialFailureWithNoErrors() { MutateAdGroupsResponse failedResponse = new MutateAdGroupsResponse() { PartialFailureError = null }; Assert.Null(failedResponse.PartialFailure); } /// <summary> /// Wraps a <see cref="GoogleAdsFailure"/> in an Rpc.Status object. /// </summary> /// <param name="failure">The failure.</param> /// <returns>The wrapped Rpc.Status.</returns> private static Rpc.Status GetStatus(GoogleAdsFailure failure) { Rpc.Status status = new Rpc.Status(); status.Details.Add(Any.Pack(failure)); return status; } /// <summary> /// Creates a <see cref="GoogleAdsError"/> object for testing purposes. /// </summary> /// <param name="fieldName">Name of the field.</param> /// <param name="operationIndex">Index of the operation.</param> /// <returns>A GoogleAdsError instance.</returns> private static GoogleAdsError CreateError(FieldPathElement[] fieldPathElements) { GoogleAdsError error = new GoogleAdsError() { Location = new ErrorLocation() { } }; error.Location.FieldPathElements.AddRange(fieldPathElements); return error; } } }
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the sts-2011-06-15.normal.json service model. */ using System; using System.Runtime.ExceptionServices; using System.Threading; using System.Threading.Tasks; using System.Collections.Generic; using Amazon.SecurityToken.Model; using Amazon.SecurityToken.Model.Internal.MarshallTransformations; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Auth; using Amazon.Runtime.Internal.Transform; namespace Amazon.SecurityToken { /// <summary> /// Implementation for accessing SecurityTokenService /// /// AWS Security Token Service /// <para> /// The AWS Security Token Service (STS) is a web service that enables you to request /// temporary, limited-privilege credentials for AWS Identity and Access Management (IAM) /// users or for users that you authenticate (federated users). This guide provides descriptions /// of the STS API. For more detailed information about using this service, go to <a href="http://docs.aws.amazon.com/STS/latest/UsingSTS/Welcome.html" /// target="_blank">Using Temporary Security Credentials</a>. /// </para> /// <note> As an alternative to using the API, you can use one of the AWS SDKs, which /// consist of libraries and sample code for various programming languages and platforms /// (Java, Ruby, .NET, iOS, Android, etc.). The SDKs provide a convenient way to create /// programmatic access to STS. For example, the SDKs take care of cryptographically signing /// requests, managing errors, and retrying requests automatically. For information about /// the AWS SDKs, including how to download and install them, see the <a href="http://aws.amazon.com/tools/">Tools /// for Amazon Web Services page</a>. </note> /// <para> /// For information about setting up signatures and authorization through the API, go /// to <a href="http://docs.aws.amazon.com/general/latest/gr/signing_aws_api_requests.html" /// target="_blank">Signing AWS API Requests</a> in the <i>AWS General Reference</i>. /// For general information about the Query API, go to <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/IAM_UsingQueryAPI.html" /// target="_blank">Making Query Requests</a> in <i>Using IAM</i>. For information about /// using security tokens with other AWS products, go to <a href="http://docs.aws.amazon.com/STS/latest/UsingSTS/UsingTokens.html">Using /// Temporary Security Credentials to Access AWS</a> in <i>Using Temporary Security Credentials</i>. /// /// </para> /// /// <para> /// If you're new to AWS and need additional technical information about a specific AWS /// product, you can find the product's technical documentation at <a href="http://aws.amazon.com/documentation/" /// target="_blank">http://aws.amazon.com/documentation/</a>. /// </para> /// /// <para> /// <b>Endpoints</b> /// </para> /// /// <para> /// The AWS Security Token Service (STS) has a default endpoint of https://sts.amazonaws.com /// that maps to the US East (N. Virginia) region. Additional regions are available, but /// must first be activated in the AWS Management Console before you can use a different /// region's endpoint. For more information about activating a region for STS see <a href="http://docs.aws.amazon.com/STS/latest/UsingSTS/sts-enableregions.html">Activating /// STS in a New Region</a> in the <i>Using Temporary Security Credentials</i> guide. /// /// </para> /// /// <para> /// For information about STS endpoints, see <a href="http://docs.aws.amazon.com/general/latest/gr/rande.html#sts_region">Regions /// and Endpoints</a> in the <i>AWS General Reference</i>. /// </para> /// /// <para> /// <b>Recording API requests</b> /// </para> /// /// <para> /// STS supports AWS CloudTrail, which is a service that records AWS calls for your AWS /// account and delivers log files to an Amazon S3 bucket. By using information collected /// by CloudTrail, you can determine what requests were successfully made to STS, who /// made the request, when it was made, and so on. To learn more about CloudTrail, including /// how to turn it on and find your log files, see the <a href="http://docs.aws.amazon.com/awscloudtrail/latest/userguide/what_is_cloud_trail_top_level.html">AWS /// CloudTrail User Guide</a>. /// </para> /// </summary> public partial class AmazonSecurityTokenServiceClient : AmazonServiceClient, IAmazonSecurityTokenService { #region Constructors /// <summary> /// Constructs AmazonSecurityTokenServiceClient with AWS Credentials /// </summary> /// <param name="credentials">AWS Credentials</param> public AmazonSecurityTokenServiceClient(AWSCredentials credentials) : this(credentials, new AmazonSecurityTokenServiceConfig()) { } /// <summary> /// Constructs AmazonSecurityTokenServiceClient with AWS Credentials /// </summary> /// <param name="credentials">AWS Credentials</param> /// <param name="region">The region to connect.</param> public AmazonSecurityTokenServiceClient(AWSCredentials credentials, RegionEndpoint region) : this(credentials, new AmazonSecurityTokenServiceConfig{RegionEndpoint = region}) { } /// <summary> /// Constructs AmazonSecurityTokenServiceClient with AWS Credentials and an /// AmazonSecurityTokenServiceClient Configuration object. /// </summary> /// <param name="credentials">AWS Credentials</param> /// <param name="clientConfig">The AmazonSecurityTokenServiceClient Configuration Object</param> public AmazonSecurityTokenServiceClient(AWSCredentials credentials, AmazonSecurityTokenServiceConfig clientConfig) : base(credentials, clientConfig) { } /// <summary> /// Constructs AmazonSecurityTokenServiceClient with AWS Access Key ID and AWS Secret Key /// </summary> /// <param name="awsAccessKeyId">AWS Access Key ID</param> /// <param name="awsSecretAccessKey">AWS Secret Access Key</param> public AmazonSecurityTokenServiceClient(string awsAccessKeyId, string awsSecretAccessKey) : this(awsAccessKeyId, awsSecretAccessKey, new AmazonSecurityTokenServiceConfig()) { } /// <summary> /// Constructs AmazonSecurityTokenServiceClient with AWS Access Key ID and AWS Secret Key /// </summary> /// <param name="awsAccessKeyId">AWS Access Key ID</param> /// <param name="awsSecretAccessKey">AWS Secret Access Key</param> /// <param name="region">The region to connect.</param> public AmazonSecurityTokenServiceClient(string awsAccessKeyId, string awsSecretAccessKey, RegionEndpoint region) : this(awsAccessKeyId, awsSecretAccessKey, new AmazonSecurityTokenServiceConfig() {RegionEndpoint=region}) { } /// <summary> /// Constructs AmazonSecurityTokenServiceClient with AWS Access Key ID, AWS Secret Key and an /// AmazonSecurityTokenServiceClient Configuration object. /// </summary> /// <param name="awsAccessKeyId">AWS Access Key ID</param> /// <param name="awsSecretAccessKey">AWS Secret Access Key</param> /// <param name="clientConfig">The AmazonSecurityTokenServiceClient Configuration Object</param> public AmazonSecurityTokenServiceClient(string awsAccessKeyId, string awsSecretAccessKey, AmazonSecurityTokenServiceConfig clientConfig) : base(awsAccessKeyId, awsSecretAccessKey, clientConfig) { } /// <summary> /// Constructs AmazonSecurityTokenServiceClient with AWS Access Key ID and AWS Secret Key /// </summary> /// <param name="awsAccessKeyId">AWS Access Key ID</param> /// <param name="awsSecretAccessKey">AWS Secret Access Key</param> /// <param name="awsSessionToken">AWS Session Token</param> public AmazonSecurityTokenServiceClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken) : this(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, new AmazonSecurityTokenServiceConfig()) { } /// <summary> /// Constructs AmazonSecurityTokenServiceClient with AWS Access Key ID and AWS Secret Key /// </summary> /// <param name="awsAccessKeyId">AWS Access Key ID</param> /// <param name="awsSecretAccessKey">AWS Secret Access Key</param> /// <param name="awsSessionToken">AWS Session Token</param> /// <param name="region">The region to connect.</param> public AmazonSecurityTokenServiceClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken, RegionEndpoint region) : this(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, new AmazonSecurityTokenServiceConfig{RegionEndpoint = region}) { } /// <summary> /// Constructs AmazonSecurityTokenServiceClient with AWS Access Key ID, AWS Secret Key and an /// AmazonSecurityTokenServiceClient Configuration object. /// </summary> /// <param name="awsAccessKeyId">AWS Access Key ID</param> /// <param name="awsSecretAccessKey">AWS Secret Access Key</param> /// <param name="awsSessionToken">AWS Session Token</param> /// <param name="clientConfig">The AmazonSecurityTokenServiceClient Configuration Object</param> public AmazonSecurityTokenServiceClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken, AmazonSecurityTokenServiceConfig clientConfig) : base(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, clientConfig) { } #endregion #region Overrides /// <summary> /// Creates the signer for the service. /// </summary> protected override AbstractAWSSigner CreateSigner() { return new AWS4Signer(); } #endregion #region Dispose /// <summary> /// Disposes the service client. /// </summary> protected override void Dispose(bool disposing) { base.Dispose(disposing); } #endregion #region AssumeRole internal AssumeRoleResponse AssumeRole(AssumeRoleRequest request) { var marshaller = new AssumeRoleRequestMarshaller(); var unmarshaller = AssumeRoleResponseUnmarshaller.Instance; return Invoke<AssumeRoleRequest,AssumeRoleResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the AssumeRole operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the AssumeRole operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<AssumeRoleResponse> AssumeRoleAsync(AssumeRoleRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new AssumeRoleRequestMarshaller(); var unmarshaller = AssumeRoleResponseUnmarshaller.Instance; return InvokeAsync<AssumeRoleRequest,AssumeRoleResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region AssumeRoleWithSAML internal AssumeRoleWithSAMLResponse AssumeRoleWithSAML(AssumeRoleWithSAMLRequest request) { var marshaller = new AssumeRoleWithSAMLRequestMarshaller(); var unmarshaller = AssumeRoleWithSAMLResponseUnmarshaller.Instance; return Invoke<AssumeRoleWithSAMLRequest,AssumeRoleWithSAMLResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the AssumeRoleWithSAML operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the AssumeRoleWithSAML operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<AssumeRoleWithSAMLResponse> AssumeRoleWithSAMLAsync(AssumeRoleWithSAMLRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new AssumeRoleWithSAMLRequestMarshaller(); var unmarshaller = AssumeRoleWithSAMLResponseUnmarshaller.Instance; return InvokeAsync<AssumeRoleWithSAMLRequest,AssumeRoleWithSAMLResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region AssumeRoleWithWebIdentity internal AssumeRoleWithWebIdentityResponse AssumeRoleWithWebIdentity(AssumeRoleWithWebIdentityRequest request) { var marshaller = new AssumeRoleWithWebIdentityRequestMarshaller(); var unmarshaller = AssumeRoleWithWebIdentityResponseUnmarshaller.Instance; return Invoke<AssumeRoleWithWebIdentityRequest,AssumeRoleWithWebIdentityResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the AssumeRoleWithWebIdentity operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the AssumeRoleWithWebIdentity operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<AssumeRoleWithWebIdentityResponse> AssumeRoleWithWebIdentityAsync(AssumeRoleWithWebIdentityRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new AssumeRoleWithWebIdentityRequestMarshaller(); var unmarshaller = AssumeRoleWithWebIdentityResponseUnmarshaller.Instance; return InvokeAsync<AssumeRoleWithWebIdentityRequest,AssumeRoleWithWebIdentityResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region DecodeAuthorizationMessage internal DecodeAuthorizationMessageResponse DecodeAuthorizationMessage(DecodeAuthorizationMessageRequest request) { var marshaller = new DecodeAuthorizationMessageRequestMarshaller(); var unmarshaller = DecodeAuthorizationMessageResponseUnmarshaller.Instance; return Invoke<DecodeAuthorizationMessageRequest,DecodeAuthorizationMessageResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the DecodeAuthorizationMessage operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DecodeAuthorizationMessage operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<DecodeAuthorizationMessageResponse> DecodeAuthorizationMessageAsync(DecodeAuthorizationMessageRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new DecodeAuthorizationMessageRequestMarshaller(); var unmarshaller = DecodeAuthorizationMessageResponseUnmarshaller.Instance; return InvokeAsync<DecodeAuthorizationMessageRequest,DecodeAuthorizationMessageResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region GetFederationToken internal GetFederationTokenResponse GetFederationToken(GetFederationTokenRequest request) { var marshaller = new GetFederationTokenRequestMarshaller(); var unmarshaller = GetFederationTokenResponseUnmarshaller.Instance; return Invoke<GetFederationTokenRequest,GetFederationTokenResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the GetFederationToken operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the GetFederationToken operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<GetFederationTokenResponse> GetFederationTokenAsync(GetFederationTokenRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new GetFederationTokenRequestMarshaller(); var unmarshaller = GetFederationTokenResponseUnmarshaller.Instance; return InvokeAsync<GetFederationTokenRequest,GetFederationTokenResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region GetSessionToken internal GetSessionTokenResponse GetSessionToken() { return GetSessionToken(new GetSessionTokenRequest()); } internal GetSessionTokenResponse GetSessionToken(GetSessionTokenRequest request) { var marshaller = new GetSessionTokenRequestMarshaller(); var unmarshaller = GetSessionTokenResponseUnmarshaller.Instance; return Invoke<GetSessionTokenRequest,GetSessionTokenResponse>(request, marshaller, unmarshaller); } /// <summary> /// Returns a set of temporary credentials for an AWS account or IAM user. The credentials /// consist of an access key ID, a secret access key, and a security token. Typically, /// you use <code>GetSessionToken</code> if you want to use MFA to protect programmatic /// calls to specific AWS APIs like Amazon EC2 <code>StopInstances</code>. MFA-enabled /// IAM users would need to call <code>GetSessionToken</code> and submit an MFA code that /// is associated with their MFA device. Using the temporary security credentials that /// are returned from the call, IAM users can then make programmatic calls to APIs that /// require MFA authentication. /// /// /// <para> /// The <code>GetSessionToken</code> action must be called by using the long-term AWS /// security credentials of the AWS account or an IAM user. Credentials that are created /// by IAM users are valid for the duration that you specify, between 900 seconds (15 /// minutes) and 129600 seconds (36 hours); credentials that are created by using account /// credentials have a maximum duration of 3600 seconds (1 hour). /// </para> /// <note> /// <para> /// We recommend that you do not call <code>GetSessionToken</code> with root account credentials. /// Instead, follow our <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/IAMBestPractices.html#create-iam-users">best /// practices</a> by creating one or more IAM users, giving them the necessary permissions, /// and using IAM users for everyday interaction with AWS. /// </para> /// </note> /// <para> /// The permissions associated with the temporary security credentials returned by <code>GetSessionToken</code> /// are based on the permissions associated with account or IAM user whose credentials /// are used to call the action. If <code>GetSessionToken</code> is called using root /// account credentials, the temporary credentials have root account permissions. Similarly, /// if <code>GetSessionToken</code> is called using the credentials of an IAM user, the /// temporary credentials have the same permissions as the IAM user. /// </para> /// /// <para> /// For more information about using <code>GetSessionToken</code> to create temporary /// credentials, go to <a href="http://docs.aws.amazon.com/STS/latest/UsingSTS/CreatingSessionTokens.html" /// target="_blank">Creating Temporary Credentials to Enable Access for IAM Users</a>. /// /// </para> /// </summary> /// <param name="cancellationToken"> ttd1 /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the GetSessionToken service method, as returned by SecurityTokenService.</returns> public Task<GetSessionTokenResponse> GetSessionTokenAsync(System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { return GetSessionTokenAsync(new GetSessionTokenRequest(), cancellationToken); } /// <summary> /// Initiates the asynchronous execution of the GetSessionToken operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the GetSessionToken operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<GetSessionTokenResponse> GetSessionTokenAsync(GetSessionTokenRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new GetSessionTokenRequestMarshaller(); var unmarshaller = GetSessionTokenResponseUnmarshaller.Instance; return InvokeAsync<GetSessionTokenRequest,GetSessionTokenResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using log4net; using NDesk.Options; using Nini.Config; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Framework.Console; using OpenSim.Framework.Monitoring; using OpenSim.Framework.Servers; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Services.Interfaces; using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Text.RegularExpressions; using System.Timers; namespace OpenSim { /// <summary> /// Interactive OpenSim region server /// </summary> public class OpenSim : OpenSimBase { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); protected string m_startupCommandsFile; protected string m_shutdownCommandsFile; protected bool m_gui = false; protected string m_consoleType = "local"; protected uint m_consolePort = 0; /// <summary> /// Prompt to use for simulator command line. /// </summary> private string m_consolePrompt; /// <summary> /// Regex for parsing out special characters in the prompt. /// </summary> private Regex m_consolePromptRegex = new Regex(@"([^\\])\\(\w)", RegexOptions.Compiled); private string m_timedScript = "disabled"; private int m_timeInterval = 1200; private Timer m_scriptTimer; public OpenSim(IConfigSource configSource) : base(configSource) { } protected override void ReadExtraConfigSettings() { base.ReadExtraConfigSettings(); IConfig startupConfig = Config.Configs["Startup"]; IConfig networkConfig = Config.Configs["Network"]; int stpMinThreads = 2; int stpMaxThreads = 15; if (startupConfig != null) { m_startupCommandsFile = startupConfig.GetString("startup_console_commands_file", "startup_commands.txt"); m_shutdownCommandsFile = startupConfig.GetString("shutdown_console_commands_file", "shutdown_commands.txt"); if (startupConfig.GetString("console", String.Empty) == String.Empty) m_gui = startupConfig.GetBoolean("gui", false); else m_consoleType= startupConfig.GetString("console", String.Empty); if (networkConfig != null) m_consolePort = (uint)networkConfig.GetInt("console_port", 0); m_timedScript = startupConfig.GetString("timer_Script", "disabled"); if (m_timedScript != "disabled") { m_timeInterval = startupConfig.GetInt("timer_Interval", 1200); } string asyncCallMethodStr = startupConfig.GetString("async_call_method", String.Empty); FireAndForgetMethod asyncCallMethod; if (!String.IsNullOrEmpty(asyncCallMethodStr) && Utils.EnumTryParse<FireAndForgetMethod>(asyncCallMethodStr, out asyncCallMethod)) Util.FireAndForgetMethod = asyncCallMethod; stpMinThreads = startupConfig.GetInt("MinPoolThreads", 15); stpMaxThreads = startupConfig.GetInt("MaxPoolThreads", 15); m_consolePrompt = startupConfig.GetString("ConsolePrompt", @"Region (\R) "); } if (Util.FireAndForgetMethod == FireAndForgetMethod.SmartThreadPool) Util.InitThreadPool(stpMinThreads, stpMaxThreads); m_log.Info("[OPENSIM MAIN]: Using async_call_method " + Util.FireAndForgetMethod); } /// <summary> /// Performs initialisation of the scene, such as loading configuration from disk. /// </summary> protected override void StartupSpecific() { m_log.Info("===================================================================="); m_log.Info("========================= STARTING OPENSIM ========================="); m_log.Info("===================================================================="); //m_log.InfoFormat("[OPENSIM MAIN]: GC Is Server GC: {0}", GCSettings.IsServerGC.ToString()); // http://msdn.microsoft.com/en-us/library/bb384202.aspx //GCSettings.LatencyMode = GCLatencyMode.Batch; //m_log.InfoFormat("[OPENSIM MAIN]: GC Latency Mode: {0}", GCSettings.LatencyMode.ToString()); if (m_gui) // Driven by external GUI { m_console = new CommandConsole("Region"); } else { switch (m_consoleType) { case "basic": m_console = new CommandConsole("Region"); break; case "rest": m_console = new RemoteConsole("Region"); ((RemoteConsole)m_console).ReadConfig(Config); break; default: m_console = new LocalConsole("Region"); break; } } MainConsole.Instance = m_console; LogEnvironmentInformation(); RegisterCommonAppenders(Config.Configs["Startup"]); RegisterConsoleCommands(); base.StartupSpecific(); MainServer.Instance.AddStreamHandler(new OpenSim.SimStatusHandler()); MainServer.Instance.AddStreamHandler(new OpenSim.XSimStatusHandler(this)); if (userStatsURI != String.Empty) MainServer.Instance.AddStreamHandler(new OpenSim.UXSimStatusHandler(this)); if (managedStatsURI != String.Empty) { string urlBase = String.Format("/{0}/", managedStatsURI); MainServer.Instance.AddHTTPHandler(urlBase, StatsManager.HandleStatsRequest); m_log.InfoFormat("[OPENSIM] Enabling remote managed stats fetch. URL = {0}", urlBase); } if (m_console is RemoteConsole) { if (m_consolePort == 0) { ((RemoteConsole)m_console).SetServer(m_httpServer); } else { ((RemoteConsole)m_console).SetServer(MainServer.GetHttpServer(m_consolePort)); } } // Hook up to the watchdog timer Watchdog.OnWatchdogTimeout += WatchdogTimeoutHandler; PrintFileToConsole("startuplogo.txt"); // For now, start at the 'root' level by default if (SceneManager.Scenes.Count == 1) // If there is only one region, select it ChangeSelectedRegion("region", new string[] {"change", "region", SceneManager.Scenes[0].RegionInfo.RegionName}); else ChangeSelectedRegion("region", new string[] {"change", "region", "root"}); //Run Startup Commands if (String.IsNullOrEmpty(m_startupCommandsFile)) { m_log.Info("[STARTUP]: No startup command script specified. Moving on..."); } else { RunCommandScript(m_startupCommandsFile); } // Start timer script (run a script every xx seconds) if (m_timedScript != "disabled") { m_scriptTimer = new Timer(); m_scriptTimer.Enabled = true; m_scriptTimer.Interval = m_timeInterval*1000; m_scriptTimer.Elapsed += RunAutoTimerScript; } } /// <summary> /// Register standard set of region console commands /// </summary> private void RegisterConsoleCommands() { MainServer.RegisterHttpConsoleCommands(m_console); m_console.Commands.AddCommand("Objects", false, "force update", "force update", "Force the update of all objects on clients", HandleForceUpdate); m_console.Commands.AddCommand("General", false, "change region", "change region <region name>", "Change current console region", ChangeSelectedRegion); m_console.Commands.AddCommand("Archiving", false, "save xml", "save xml", "Save a region's data in XML format", SaveXml); m_console.Commands.AddCommand("Archiving", false, "save xml2", "save xml2", "Save a region's data in XML2 format", SaveXml2); m_console.Commands.AddCommand("Archiving", false, "load xml", "load xml [-newIDs [<x> <y> <z>]]", "Load a region's data from XML format", LoadXml); m_console.Commands.AddCommand("Archiving", false, "load xml2", "load xml2", "Load a region's data from XML2 format", LoadXml2); m_console.Commands.AddCommand("Archiving", false, "save prims xml2", "save prims xml2 [<prim name> <file name>]", "Save named prim to XML2", SavePrimsXml2); m_console.Commands.AddCommand("Archiving", false, "load oar", "load oar [--merge] [--persist-uuids] [--skip-assets]" + " [--force-terrain] [--force-parcels]" + " [--no-objects]" + " [--rotation degrees] [--rotation-center \"<x,y,z>\"]" + " [--displacement \"<x,y,z>\"]" + " [--default-user \"User Name\"]" + " [<OAR path>]", "Load a region's data from an OAR archive.", "--merge will merge the OAR with the existing scene (suppresses terrain and parcel info loading)." + Environment.NewLine + "--skip-assets will load the OAR but ignore the assets it contains." + Environment.NewLine + "--persist-uuids will restore the saved uuids from the oar (not to be combined with --merge)" + Environment.NewLine + "--displacement will add this value to the position of every object loaded" + Environment.NewLine + "--force-terrain forces the loading of terrain from the oar (undoes suppression done by --merge)" + Environment.NewLine + "--force-parcels forces the loading of parcels from the oar (undoes suppression done by --merge)" + Environment.NewLine + "--rotation specified rotation to be applied to the oar. Specified in degrees." + Environment.NewLine + "--rotation-center Location (relative to original OAR) to apply rotation. Default is <128,128,0>" + Environment.NewLine + "--no-objects suppresses the addition of any objects (good for loading only the terrain)" + Environment.NewLine + "The path can be either a filesystem location or a URI." + " If this is not given then the command looks for an OAR named region.oar in the current directory.", LoadOar); m_console.Commands.AddCommand("Archiving", false, "save oar", //"save oar [-v|--version=<N>] [-p|--profile=<url>] [<OAR path>]", "save oar [-h|--home=<url>] [--noassets] [--publish] [--perm=<permissions>] [--all] [<OAR path>]", "Save a region's data to an OAR archive.", // "-v|--version=<N> generates scene objects as per older versions of the serialization (e.g. -v=0)" + Environment.NewLine "-h|--home=<url> adds the url of the profile service to the saved user information.\n" + "--noassets stops assets being saved to the OAR.\n" + "--publish saves an OAR stripped of owner and last owner information.\n" + " on reload, the estate owner will be the owner of all objects\n" + " this is useful if you're making oars generally available that might be reloaded to the same grid from which you published\n" + "--perm=<permissions> stops objects with insufficient permissions from being saved to the OAR.\n" + " <permissions> can contain one or more of these characters: \"C\" = Copy, \"T\" = Transfer\n" + "--all saves all the regions in the simulator, instead of just the current region.\n" + "The OAR path must be a filesystem path." + " If this is not given then the oar is saved to region.oar in the current directory.", SaveOar); m_console.Commands.AddCommand("Objects", false, "edit scale", "edit scale <name> <x> <y> <z>", "Change the scale of a named prim", HandleEditScale); m_console.Commands.AddCommand("Objects", false, "rotate scene", "rotate scene <degrees> [centerX, centerY]", "Rotates all scene objects around centerX, centerY (defailt 128, 128) (please back up your region before using)", HandleRotateScene); m_console.Commands.AddCommand("Objects", false, "scale scene", "scale scene <factor>", "Scales the scene objects (please back up your region before using)", HandleScaleScene); m_console.Commands.AddCommand("Objects", false, "translate scene", "translate scene xOffset yOffset zOffset", "translates the scene objects (please back up your region before using)", HandleTranslateScene); m_console.Commands.AddCommand("Users", false, "kick user", "kick user <first> <last> [--force] [message]", "Kick a user off the simulator", "The --force option will kick the user without any checks to see whether it's already in the process of closing\n" + "Only use this option if you are sure the avatar is inactive and a normal kick user operation does not removed them", KickUserCommand); m_console.Commands.AddCommand("Users", false, "show users", "show users [full]", "Show user data for users currently on the region", "Without the 'full' option, only users actually on the region are shown." + " With the 'full' option child agents of users in neighbouring regions are also shown.", HandleShow); m_console.Commands.AddCommand("Comms", false, "show connections", "show connections", "Show connection data", HandleShow); m_console.Commands.AddCommand("Comms", false, "show circuits", "show circuits", "Show agent circuit data", HandleShow); m_console.Commands.AddCommand("Comms", false, "show pending-objects", "show pending-objects", "Show # of objects on the pending queues of all scene viewers", HandleShow); m_console.Commands.AddCommand("General", false, "show modules", "show modules", "Show module data", HandleShow); m_console.Commands.AddCommand("Regions", false, "show regions", "show regions", "Show region data", HandleShow); m_console.Commands.AddCommand("Regions", false, "show ratings", "show ratings", "Show rating data", HandleShow); m_console.Commands.AddCommand("Objects", false, "backup", "backup", "Persist currently unsaved object changes immediately instead of waiting for the normal persistence call.", RunCommand); m_console.Commands.AddCommand("Regions", false, "create region", "create region [\"region name\"] <region_file.ini>", "Create a new region.", "The settings for \"region name\" are read from <region_file.ini>. Paths specified with <region_file.ini> are relative to your Regions directory, unless an absolute path is given." + " If \"region name\" does not exist in <region_file.ini>, it will be added." + Environment.NewLine + "Without \"region name\", the first region found in <region_file.ini> will be created." + Environment.NewLine + "If <region_file.ini> does not exist, it will be created.", HandleCreateRegion); m_console.Commands.AddCommand("Regions", false, "restart", "restart", "Restart all sims in this instance", RunCommand); m_console.Commands.AddCommand("General", false, "command-script", "command-script <script>", "Run a command script from file", RunCommand); m_console.Commands.AddCommand("Regions", false, "remove-region", "remove-region <name>", "Remove a region from this simulator", RunCommand); m_console.Commands.AddCommand("Regions", false, "delete-region", "delete-region <name>", "Delete a region from disk", RunCommand); m_console.Commands.AddCommand("Estates", false, "estate create", "estate create <owner UUID> <estate name>", "Creates a new estate with the specified name, owned by the specified user." + " Estate name must be unique.", CreateEstateCommand); m_console.Commands.AddCommand("Estates", false, "estate set owner", "estate set owner <estate-id>[ <UUID> | <Firstname> <Lastname> ]", "Sets the owner of the specified estate to the specified UUID or user. ", SetEstateOwnerCommand); m_console.Commands.AddCommand("Estates", false, "estate set name", "estate set name <estate-id> <new name>", "Sets the name of the specified estate to the specified value. New name must be unique.", SetEstateNameCommand); m_console.Commands.AddCommand("Estates", false, "estate link region", "estate link region <estate ID> <region ID>", "Attaches the specified region to the specified estate.", EstateLinkRegionCommand); } protected override void ShutdownSpecific() { if (m_shutdownCommandsFile != String.Empty) { RunCommandScript(m_shutdownCommandsFile); } base.ShutdownSpecific(); } /// <summary> /// Timer to run a specific text file as console commands. Configured in in the main ini file /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void RunAutoTimerScript(object sender, EventArgs e) { if (m_timedScript != "disabled") { RunCommandScript(m_timedScript); } } private void WatchdogTimeoutHandler(Watchdog.ThreadWatchdogInfo twi) { int now = Environment.TickCount; m_log.ErrorFormat( "[WATCHDOG]: Timeout detected for thread \"{0}\". ThreadState={1}. Last tick was {2}ms ago. {3}", twi.Thread.Name, twi.Thread.ThreadState, now - twi.LastTick, twi.AlarmMethod != null ? string.Format("Data: {0}", twi.AlarmMethod()) : ""); } #region Console Commands /// <summary> /// Kicks users off the region /// </summary> /// <param name="module"></param> /// <param name="cmdparams">name of avatar to kick</param> private void KickUserCommand(string module, string[] cmdparams) { bool force = false; OptionSet options = new OptionSet().Add("f|force", delegate (string v) { force = v != null; }); List<string> mainParams = options.Parse(cmdparams); if (mainParams.Count < 4) return; string alert = null; if (mainParams.Count > 4) alert = String.Format("\n{0}\n", String.Join(" ", cmdparams, 4, cmdparams.Length - 4)); IList agents = SceneManager.GetCurrentSceneAvatars(); foreach (ScenePresence presence in agents) { RegionInfo regionInfo = presence.Scene.RegionInfo; if (presence.Firstname.ToLower().Equals(mainParams[2].ToLower()) && presence.Lastname.ToLower().Equals(mainParams[3].ToLower())) { MainConsole.Instance.Output( String.Format( "Kicking user: {0,-16} {1,-16} {2,-37} in region: {3,-16}", presence.Firstname, presence.Lastname, presence.UUID, regionInfo.RegionName)); // kick client... if (alert != null) presence.ControllingClient.Kick(alert); else presence.ControllingClient.Kick("\nThe OpenSim manager kicked you out.\n"); presence.Scene.CloseAgent(presence.UUID, force); break; } } MainConsole.Instance.Output(""); } /// <summary> /// Opens a file and uses it as input to the console command parser. /// </summary> /// <param name="fileName">name of file to use as input to the console</param> private static void PrintFileToConsole(string fileName) { if (File.Exists(fileName)) { using (StreamReader readFile = File.OpenText(fileName)) { string currentLine; while ((currentLine = readFile.ReadLine()) != null) { m_log.Info("[!]" + currentLine); } } } } /// <summary> /// Force resending of all updates to all clients in active region(s) /// </summary> /// <param name="module"></param> /// <param name="args"></param> private void HandleForceUpdate(string module, string[] args) { MainConsole.Instance.Output("Updating all clients"); SceneManager.ForceCurrentSceneClientUpdate(); } /// <summary> /// Edits the scale of a primative with the name specified /// </summary> /// <param name="module"></param> /// <param name="args">0,1, name, x, y, z</param> private void HandleEditScale(string module, string[] args) { if (args.Length == 6) { SceneManager.HandleEditCommandOnCurrentScene(args); } else { MainConsole.Instance.Output("Argument error: edit scale <prim name> <x> <y> <z>"); } } private void HandleRotateScene(string module, string[] args) { string usage = "Usage: rotate scene <angle in degrees> [centerX centerY] (centerX and centerY are optional and default to Constants.RegionSize / 2"; float centerX = Constants.RegionSize * 0.5f; float centerY = Constants.RegionSize * 0.5f; if (args.Length < 3 || args.Length == 4) { MainConsole.Instance.Output(usage); return; } float angle = (float)(Convert.ToSingle(args[2]) / 180.0 * Math.PI); OpenMetaverse.Quaternion rot = OpenMetaverse.Quaternion.CreateFromAxisAngle(0, 0, 1, angle); if (args.Length > 4) { centerX = Convert.ToSingle(args[3]); centerY = Convert.ToSingle(args[4]); } Vector3 center = new Vector3(centerX, centerY, 0.0f); SceneManager.ForEachSelectedScene(delegate(Scene scene) { scene.ForEachSOG(delegate(SceneObjectGroup sog) { if (!sog.IsAttachment) { sog.RootPart.UpdateRotation(rot * sog.GroupRotation); Vector3 offset = sog.AbsolutePosition - center; offset *= rot; sog.UpdateGroupPosition(center + offset); } }); }); } private void HandleScaleScene(string module, string[] args) { string usage = "Usage: scale scene <factor>"; if (args.Length < 3) { MainConsole.Instance.Output(usage); return; } float factor = (float)(Convert.ToSingle(args[2])); float minZ = float.MaxValue; SceneManager.ForEachSelectedScene(delegate(Scene scene) { scene.ForEachSOG(delegate(SceneObjectGroup sog) { if (!sog.IsAttachment) { if (sog.RootPart.AbsolutePosition.Z < minZ) minZ = sog.RootPart.AbsolutePosition.Z; } }); }); SceneManager.ForEachSelectedScene(delegate(Scene scene) { scene.ForEachSOG(delegate(SceneObjectGroup sog) { if (!sog.IsAttachment) { Vector3 tmpRootPos = sog.RootPart.AbsolutePosition; tmpRootPos.Z -= minZ; tmpRootPos *= factor; tmpRootPos.Z += minZ; foreach (SceneObjectPart sop in sog.Parts) { if (sop.ParentID != 0) sop.OffsetPosition *= factor; sop.Scale *= factor; } sog.UpdateGroupPosition(tmpRootPos); } }); }); } private void HandleTranslateScene(string module, string[] args) { string usage = "Usage: translate scene <xOffset, yOffset, zOffset>"; if (args.Length < 5) { MainConsole.Instance.Output(usage); return; } float xOFfset = (float)Convert.ToSingle(args[2]); float yOffset = (float)Convert.ToSingle(args[3]); float zOffset = (float)Convert.ToSingle(args[4]); Vector3 offset = new Vector3(xOFfset, yOffset, zOffset); SceneManager.ForEachSelectedScene(delegate(Scene scene) { scene.ForEachSOG(delegate(SceneObjectGroup sog) { if (!sog.IsAttachment) sog.UpdateGroupPosition(sog.AbsolutePosition + offset); }); }); } /// <summary> /// Creates a new region based on the parameters specified. This will ask the user questions on the console /// </summary> /// <param name="module"></param> /// <param name="cmd">0,1,region name, region ini or XML file</param> private void HandleCreateRegion(string module, string[] cmd) { string regionName = string.Empty; string regionFile = string.Empty; if (cmd.Length == 3) { regionFile = cmd[2]; } else if (cmd.Length > 3) { regionName = cmd[2]; regionFile = cmd[3]; } string extension = Path.GetExtension(regionFile).ToLower(); bool isXml = extension.Equals(".xml"); bool isIni = extension.Equals(".ini"); if (!isXml && !isIni) { MainConsole.Instance.Output("Usage: create region [\"region name\"] <region_file.ini>"); return; } if (!Path.IsPathRooted(regionFile)) { string regionsDir = ConfigSource.Source.Configs["Startup"].GetString("regionload_regionsdir", "Regions").Trim(); regionFile = Path.Combine(regionsDir, regionFile); } RegionInfo regInfo; if (isXml) { regInfo = new RegionInfo(regionName, regionFile, false, ConfigSource.Source); } else { regInfo = new RegionInfo(regionName, regionFile, false, ConfigSource.Source, regionName); } Scene existingScene; if (SceneManager.TryGetScene(regInfo.RegionID, out existingScene)) { MainConsole.Instance.OutputFormat( "ERROR: Cannot create region {0} with ID {1}, this ID is already assigned to region {2}", regInfo.RegionName, regInfo.RegionID, existingScene.RegionInfo.RegionName); return; } bool changed = PopulateRegionEstateInfo(regInfo); IScene scene; CreateRegion(regInfo, true, out scene); if (changed) regInfo.EstateSettings.Save(); } /// <summary> /// Runs commands issued by the server console from the operator /// </summary> /// <param name="command">The first argument of the parameter (the command)</param> /// <param name="cmdparams">Additional arguments passed to the command</param> public void RunCommand(string module, string[] cmdparams) { List<string> args = new List<string>(cmdparams); if (args.Count < 1) return; string command = args[0]; args.RemoveAt(0); cmdparams = args.ToArray(); switch (command) { case "backup": MainConsole.Instance.Output("Triggering save of pending object updates to persistent store"); SceneManager.BackupCurrentScene(); break; case "remove-region": string regRemoveName = CombineParams(cmdparams, 0); Scene removeScene; if (SceneManager.TryGetScene(regRemoveName, out removeScene)) RemoveRegion(removeScene, false); else MainConsole.Instance.Output("No region with that name"); break; case "delete-region": string regDeleteName = CombineParams(cmdparams, 0); Scene killScene; if (SceneManager.TryGetScene(regDeleteName, out killScene)) RemoveRegion(killScene, true); else MainConsole.Instance.Output("no region with that name"); break; case "restart": SceneManager.RestartCurrentScene(); break; } } /// <summary> /// Change the currently selected region. The selected region is that operated upon by single region commands. /// </summary> /// <param name="cmdParams"></param> protected void ChangeSelectedRegion(string module, string[] cmdparams) { if (cmdparams.Length > 2) { string newRegionName = CombineParams(cmdparams, 2); if (!SceneManager.TrySetCurrentScene(newRegionName)) MainConsole.Instance.Output(String.Format("Couldn't select region {0}", newRegionName)); else RefreshPrompt(); } else { MainConsole.Instance.Output("Usage: change region <region name>"); } } /// <summary> /// Refreshs prompt with the current selection details. /// </summary> private void RefreshPrompt() { string regionName = (SceneManager.CurrentScene == null ? "root" : SceneManager.CurrentScene.RegionInfo.RegionName); MainConsole.Instance.Output(String.Format("Currently selected region is {0}", regionName)); // m_log.DebugFormat("Original prompt is {0}", m_consolePrompt); string prompt = m_consolePrompt; // Replace "\R" with the region name // Replace "\\" with "\" prompt = m_consolePromptRegex.Replace(prompt, m => { // m_log.DebugFormat("Matched {0}", m.Groups[2].Value); if (m.Groups[2].Value == "R") return m.Groups[1].Value + regionName; else return m.Groups[0].Value; }); m_console.DefaultPrompt = prompt; m_console.ConsoleScene = SceneManager.CurrentScene; } protected override void HandleRestartRegion(RegionInfo whichRegion) { base.HandleRestartRegion(whichRegion); // Where we are restarting multiple scenes at once, a previous call to RefreshPrompt may have set the // m_console.ConsoleScene to null (indicating all scenes). if (m_console.ConsoleScene != null && whichRegion.RegionName == ((Scene)m_console.ConsoleScene).Name) SceneManager.TrySetCurrentScene(whichRegion.RegionName); RefreshPrompt(); } // see BaseOpenSimServer /// <summary> /// Many commands list objects for debugging. Some of the types are listed here /// </summary> /// <param name="mod"></param> /// <param name="cmd"></param> public override void HandleShow(string mod, string[] cmd) { base.HandleShow(mod, cmd); List<string> args = new List<string>(cmd); args.RemoveAt(0); string[] showParams = args.ToArray(); switch (showParams[0]) { case "users": IList agents; if (showParams.Length > 1 && showParams[1] == "full") { agents = SceneManager.GetCurrentScenePresences(); } else { agents = SceneManager.GetCurrentSceneAvatars(); } MainConsole.Instance.Output(String.Format("\nAgents connected: {0}\n", agents.Count)); MainConsole.Instance.Output( String.Format("{0,-16} {1,-16} {2,-37} {3,-11} {4,-16} {5,-30}", "Firstname", "Lastname", "Agent ID", "Root/Child", "Region", "Position") ); foreach (ScenePresence presence in agents) { RegionInfo regionInfo = presence.Scene.RegionInfo; string regionName; if (regionInfo == null) { regionName = "Unresolvable"; } else { regionName = regionInfo.RegionName; } MainConsole.Instance.Output( String.Format( "{0,-16} {1,-16} {2,-37} {3,-11} {4,-16} {5,-30}", presence.Firstname, presence.Lastname, presence.UUID, presence.IsChildAgent ? "Child" : "Root", regionName, presence.AbsolutePosition.ToString()) ); } MainConsole.Instance.Output(String.Empty); break; case "connections": HandleShowConnections(); break; case "circuits": HandleShowCircuits(); break; case "modules": SceneManager.ForEachSelectedScene( scene => { MainConsole.Instance.OutputFormat("Loaded region modules in {0} are:", scene.Name); List<IRegionModuleBase> sharedModules = new List<IRegionModuleBase>(); List<IRegionModuleBase> nonSharedModules = new List<IRegionModuleBase>(); foreach (IRegionModuleBase module in scene.RegionModules.Values) { if (module.GetType().GetInterface("ISharedRegionModule") == null) nonSharedModules.Add(module); else sharedModules.Add(module); } foreach (IRegionModuleBase module in sharedModules.OrderBy(m => m.Name)) MainConsole.Instance.OutputFormat("New Region Module (Shared): {0}", module.Name); foreach (IRegionModuleBase module in nonSharedModules.OrderBy(m => m.Name)) MainConsole.Instance.OutputFormat("New Region Module (Non-Shared): {0}", module.Name); } ); MainConsole.Instance.Output(""); break; case "regions": ConsoleDisplayTable cdt = new ConsoleDisplayTable(); cdt.AddColumn("Name", ConsoleDisplayUtil.RegionNameSize); cdt.AddColumn("ID", ConsoleDisplayUtil.UuidSize); cdt.AddColumn("Position", ConsoleDisplayUtil.CoordTupleSize); cdt.AddColumn("Port", ConsoleDisplayUtil.PortSize); cdt.AddColumn("Ready?", 6); cdt.AddColumn("Estate", ConsoleDisplayUtil.EstateNameSize); SceneManager.ForEachScene( scene => { RegionInfo ri = scene.RegionInfo; cdt.AddRow( ri.RegionName, ri.RegionID, string.Format("{0},{1}", ri.RegionLocX, ri.RegionLocY), ri.InternalEndPoint.Port, scene.Ready ? "Yes" : "No", ri.EstateSettings.EstateName); } ); MainConsole.Instance.Output(cdt.ToString()); break; case "ratings": SceneManager.ForEachScene( delegate(Scene scene) { string rating = ""; if (scene.RegionInfo.RegionSettings.Maturity == 1) { rating = "MATURE"; } else if (scene.RegionInfo.RegionSettings.Maturity == 2) { rating = "ADULT"; } else { rating = "PG"; } MainConsole.Instance.Output(String.Format( "Region Name: {0}, Region Rating {1}", scene.RegionInfo.RegionName, rating)); }); break; } } private void HandleShowCircuits() { ConsoleDisplayTable cdt = new ConsoleDisplayTable(); cdt.AddColumn("Region", 20); cdt.AddColumn("Avatar name", 24); cdt.AddColumn("Type", 5); cdt.AddColumn("Code", 10); cdt.AddColumn("IP", 16); cdt.AddColumn("Viewer Name", 24); SceneManager.ForEachScene( s => { foreach (AgentCircuitData aCircuit in s.AuthenticateHandler.GetAgentCircuits().Values) cdt.AddRow( s.Name, aCircuit.Name, aCircuit.child ? "child" : "root", aCircuit.circuitcode.ToString(), aCircuit.IPAddress != null ? aCircuit.IPAddress.ToString() : "not set", Util.GetViewerName(aCircuit)); }); MainConsole.Instance.Output(cdt.ToString()); } private void HandleShowConnections() { ConsoleDisplayTable cdt = new ConsoleDisplayTable(); cdt.AddColumn("Region", 20); cdt.AddColumn("Avatar name", 24); cdt.AddColumn("Circuit code", 12); cdt.AddColumn("Endpoint", 23); cdt.AddColumn("Active?", 7); SceneManager.ForEachScene( s => s.ForEachClient( c => cdt.AddRow( s.Name, c.Name, c.CircuitCode.ToString(), c.RemoteEndPoint.ToString(), c.IsActive.ToString()))); MainConsole.Instance.Output(cdt.ToString()); } /// <summary> /// Use XML2 format to serialize data to a file /// </summary> /// <param name="module"></param> /// <param name="cmdparams"></param> protected void SavePrimsXml2(string module, string[] cmdparams) { if (cmdparams.Length > 5) { SceneManager.SaveNamedPrimsToXml2(cmdparams[3], cmdparams[4]); } else { SceneManager.SaveNamedPrimsToXml2("Primitive", DEFAULT_PRIM_BACKUP_FILENAME); } } /// <summary> /// Use XML format to serialize data to a file /// </summary> /// <param name="module"></param> /// <param name="cmdparams"></param> protected void SaveXml(string module, string[] cmdparams) { MainConsole.Instance.Output("PLEASE NOTE, save-xml is DEPRECATED and may be REMOVED soon. If you are using this and there is some reason you can't use save-xml2, please file a mantis detailing the reason."); if (cmdparams.Length > 0) { SceneManager.SaveCurrentSceneToXml(cmdparams[2]); } else { SceneManager.SaveCurrentSceneToXml(DEFAULT_PRIM_BACKUP_FILENAME); } } /// <summary> /// Loads data and region objects from XML format. /// </summary> /// <param name="module"></param> /// <param name="cmdparams"></param> protected void LoadXml(string module, string[] cmdparams) { MainConsole.Instance.Output("PLEASE NOTE, load-xml is DEPRECATED and may be REMOVED soon. If you are using this and there is some reason you can't use load-xml2, please file a mantis detailing the reason."); Vector3 loadOffset = new Vector3(0, 0, 0); if (cmdparams.Length > 2) { bool generateNewIDS = false; if (cmdparams.Length > 3) { if (cmdparams[3] == "-newUID") { generateNewIDS = true; } if (cmdparams.Length > 4) { loadOffset.X = (float)Convert.ToDecimal(cmdparams[4], Culture.NumberFormatInfo); if (cmdparams.Length > 5) { loadOffset.Y = (float)Convert.ToDecimal(cmdparams[5], Culture.NumberFormatInfo); } if (cmdparams.Length > 6) { loadOffset.Z = (float)Convert.ToDecimal(cmdparams[6], Culture.NumberFormatInfo); } MainConsole.Instance.Output(String.Format("loadOffsets <X,Y,Z> = <{0},{1},{2}>",loadOffset.X,loadOffset.Y,loadOffset.Z)); } } SceneManager.LoadCurrentSceneFromXml(cmdparams[2], generateNewIDS, loadOffset); } else { try { SceneManager.LoadCurrentSceneFromXml(DEFAULT_PRIM_BACKUP_FILENAME, false, loadOffset); } catch (FileNotFoundException) { MainConsole.Instance.Output("Default xml not found. Usage: load-xml <filename>"); } } } /// <summary> /// Serialize region data to XML2Format /// </summary> /// <param name="module"></param> /// <param name="cmdparams"></param> protected void SaveXml2(string module, string[] cmdparams) { if (cmdparams.Length > 2) { SceneManager.SaveCurrentSceneToXml2(cmdparams[2]); } else { SceneManager.SaveCurrentSceneToXml2(DEFAULT_PRIM_BACKUP_FILENAME); } } /// <summary> /// Load region data from Xml2Format /// </summary> /// <param name="module"></param> /// <param name="cmdparams"></param> protected void LoadXml2(string module, string[] cmdparams) { if (cmdparams.Length > 2) { try { SceneManager.LoadCurrentSceneFromXml2(cmdparams[2]); } catch (FileNotFoundException) { MainConsole.Instance.Output("Specified xml not found. Usage: load xml2 <filename>"); } } else { try { SceneManager.LoadCurrentSceneFromXml2(DEFAULT_PRIM_BACKUP_FILENAME); } catch (FileNotFoundException) { MainConsole.Instance.Output("Default xml not found. Usage: load xml2 <filename>"); } } } /// <summary> /// Load a whole region from an opensimulator archive. /// </summary> /// <param name="cmdparams"></param> protected void LoadOar(string module, string[] cmdparams) { try { SceneManager.LoadArchiveToCurrentScene(cmdparams); } catch (Exception e) { MainConsole.Instance.Output(e.Message); } } /// <summary> /// Save a region to a file, including all the assets needed to restore it. /// </summary> /// <param name="cmdparams"></param> protected void SaveOar(string module, string[] cmdparams) { SceneManager.SaveCurrentSceneToArchive(cmdparams); } protected void CreateEstateCommand(string module, string[] args) { string response = null; UUID userID; if (args.Length == 2) { response = "No user specified."; } else if (!UUID.TryParse(args[2], out userID)) { response = String.Format("{0} is not a valid UUID", args[2]); } else if (args.Length == 3) { response = "No estate name specified."; } else { Scene scene = SceneManager.CurrentOrFirstScene; // TODO: Is there a better choice here? UUID scopeID = UUID.Zero; UserAccount account = scene.UserAccountService.GetUserAccount(scopeID, userID); if (account == null) { response = String.Format("Could not find user {0}", userID); } else { // concatenate it all to "name" StringBuilder sb = new StringBuilder(args[3]); for (int i = 4; i < args.Length; i++) sb.Append (" " + args[i]); string estateName = sb.ToString().Trim(); // send it off for processing. IEstateModule estateModule = scene.RequestModuleInterface<IEstateModule>(); response = estateModule.CreateEstate(estateName, userID); if (response == String.Empty) { List<int> estates = scene.EstateDataService.GetEstates(estateName); response = String.Format("Estate {0} created as \"{1}\"", estates.ElementAt(0), estateName); } } } // give the user some feedback if (response != null) MainConsole.Instance.Output(response); } protected void SetEstateOwnerCommand(string module, string[] args) { string response = null; Scene scene = SceneManager.CurrentOrFirstScene; IEstateModule estateModule = scene.RequestModuleInterface<IEstateModule>(); if (args.Length == 3) { response = "No estate specified."; } else { int estateId; if (!int.TryParse(args[3], out estateId)) { response = String.Format("\"{0}\" is not a valid ID for an Estate", args[3]); } else { if (args.Length == 4) { response = "No user specified."; } else { UserAccount account = null; // TODO: Is there a better choice here? UUID scopeID = UUID.Zero; string s1 = args[4]; if (args.Length == 5) { // attempt to get account by UUID UUID u; if (UUID.TryParse(s1, out u)) { account = scene.UserAccountService.GetUserAccount(scopeID, u); if (account == null) response = String.Format("Could not find user {0}", s1); } else { response = String.Format("Invalid UUID {0}", s1); } } else { // attempt to get account by Firstname, Lastname string s2 = args[5]; account = scene.UserAccountService.GetUserAccount(scopeID, s1, s2); if (account == null) response = String.Format("Could not find user {0} {1}", s1, s2); } // If it's valid, send it off for processing. if (account != null) response = estateModule.SetEstateOwner(estateId, account); if (response == String.Empty) { response = String.Format("Estate owner changed to {0} ({1} {2})", account.PrincipalID, account.FirstName, account.LastName); } } } } // give the user some feedback if (response != null) MainConsole.Instance.Output(response); } protected void SetEstateNameCommand(string module, string[] args) { string response = null; Scene scene = SceneManager.CurrentOrFirstScene; IEstateModule estateModule = scene.RequestModuleInterface<IEstateModule>(); if (args.Length == 3) { response = "No estate specified."; } else { int estateId; if (!int.TryParse(args[3], out estateId)) { response = String.Format("\"{0}\" is not a valid ID for an Estate", args[3]); } else { if (args.Length == 4) { response = "No name specified."; } else { // everything after the estate ID is "name" StringBuilder sb = new StringBuilder(args[4]); for (int i = 5; i < args.Length; i++) sb.Append (" " + args[i]); string estateName = sb.ToString(); // send it off for processing. response = estateModule.SetEstateName(estateId, estateName); if (response == String.Empty) { response = String.Format("Estate {0} renamed to \"{1}\"", estateId, estateName); } } } } // give the user some feedback if (response != null) MainConsole.Instance.Output(response); } private void EstateLinkRegionCommand(string module, string[] args) { int estateId =-1; UUID regionId = UUID.Zero; Scene scene = null; string response = null; if (args.Length == 3) { response = "No estate specified."; } else if (!int.TryParse(args [3], out estateId)) { response = String.Format("\"{0}\" is not a valid ID for an Estate", args [3]); } else if (args.Length == 4) { response = "No region specified."; } else if (!UUID.TryParse(args[4], out regionId)) { response = String.Format("\"{0}\" is not a valid UUID for a Region", args [4]); } else if (!SceneManager.TryGetScene(regionId, out scene)) { // region may exist, but on a different sim. response = String.Format("No access to Region \"{0}\"", args [4]); } if (response != null) { MainConsole.Instance.Output(response); return; } // send it off for processing. IEstateModule estateModule = scene.RequestModuleInterface<IEstateModule>(); response = estateModule.SetRegionEstate(scene.RegionInfo, estateId); if (response == String.Empty) { estateModule.TriggerRegionInfoChange(); estateModule.sendRegionHandshakeToAll(); response = String.Format ("Region {0} is now attached to estate {1}", regionId, estateId); } // give the user some feedback if (response != null) MainConsole.Instance.Output (response); } #endregion private static string CombineParams(string[] commandParams, int pos) { string result = String.Empty; for (int i = pos; i < commandParams.Length; i++) { result += commandParams[i] + " "; } result = result.TrimEnd(' '); return result; } } }
// 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\General\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; namespace JIT.HardwareIntrinsics.General { public static partial class Program { private static void GetAndWithElementByte31() { var test = new VectorGetAndWithElement__GetAndWithElementByte31(); // Validates basic functionality works test.RunBasicScenario(); // Validates calling via reflection works test.RunReflectionScenario(); // Validates that invalid indices throws ArgumentOutOfRangeException test.RunArgumentOutOfRangeScenario(); if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class VectorGetAndWithElement__GetAndWithElementByte31 { private static readonly int LargestVectorSize = 32; private static readonly int ElementCount = Unsafe.SizeOf<Vector256<Byte>>() / sizeof(Byte); public bool Succeeded { get; set; } = true; public void RunBasicScenario(int imm = 31, bool expectedOutOfRangeException = false) { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario)); Byte[] values = new Byte[ElementCount]; for (int i = 0; i < ElementCount; i++) { values[i] = TestLibrary.Generator.GetByte(); } Vector256<Byte> value = Vector256.Create(values[0], values[1], values[2], values[3], values[4], values[5], values[6], values[7], values[8], values[9], values[10], values[11], values[12], values[13], values[14], values[15], values[16], values[17], values[18], values[19], values[20], values[21], values[22], values[23], values[24], values[25], values[26], values[27], values[28], values[29], values[30], values[31]); bool succeeded = !expectedOutOfRangeException; try { Byte result = value.GetElement(imm); ValidateGetResult(result, values); } catch (ArgumentOutOfRangeException) { succeeded = expectedOutOfRangeException; } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector256<Byte.GetElement({imm}): {nameof(RunBasicScenario)} failed to throw ArgumentOutOfRangeException."); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } succeeded = !expectedOutOfRangeException; Byte insertedValue = TestLibrary.Generator.GetByte(); try { Vector256<Byte> result2 = value.WithElement(imm, insertedValue); ValidateWithResult(result2, values, insertedValue); } catch (ArgumentOutOfRangeException) { succeeded = expectedOutOfRangeException; } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector256<Byte.WithElement({imm}): {nameof(RunBasicScenario)} failed to throw ArgumentOutOfRangeException."); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } public void RunReflectionScenario(int imm = 31, bool expectedOutOfRangeException = false) { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario)); Byte[] values = new Byte[ElementCount]; for (int i = 0; i < ElementCount; i++) { values[i] = TestLibrary.Generator.GetByte(); } Vector256<Byte> value = Vector256.Create(values[0], values[1], values[2], values[3], values[4], values[5], values[6], values[7], values[8], values[9], values[10], values[11], values[12], values[13], values[14], values[15], values[16], values[17], values[18], values[19], values[20], values[21], values[22], values[23], values[24], values[25], values[26], values[27], values[28], values[29], values[30], values[31]); bool succeeded = !expectedOutOfRangeException; try { object result = typeof(Vector256) .GetMethod(nameof(Vector256.GetElement)) .MakeGenericMethod(typeof(Byte)) .Invoke(null, new object[] { value, imm }); ValidateGetResult((Byte)(result), values); } catch (TargetInvocationException e) { succeeded = expectedOutOfRangeException && e.InnerException is ArgumentOutOfRangeException; } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector256<Byte.GetElement({imm}): {nameof(RunReflectionScenario)} failed to throw ArgumentOutOfRangeException."); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } succeeded = !expectedOutOfRangeException; Byte insertedValue = TestLibrary.Generator.GetByte(); try { object result2 = typeof(Vector256) .GetMethod(nameof(Vector256.WithElement)) .MakeGenericMethod(typeof(Byte)) .Invoke(null, new object[] { value, imm, insertedValue }); ValidateWithResult((Vector256<Byte>)(result2), values, insertedValue); } catch (TargetInvocationException e) { succeeded = expectedOutOfRangeException && e.InnerException is ArgumentOutOfRangeException; } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector256<Byte.WithElement({imm}): {nameof(RunReflectionScenario)} failed to throw ArgumentOutOfRangeException."); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } public void RunArgumentOutOfRangeScenario() { RunBasicScenario(31 - ElementCount, expectedOutOfRangeException: true); RunBasicScenario(31 + ElementCount, expectedOutOfRangeException: true); RunReflectionScenario(31 - ElementCount, expectedOutOfRangeException: true); RunReflectionScenario(31 + ElementCount, expectedOutOfRangeException: true); } private void ValidateGetResult(Byte result, Byte[] values, [CallerMemberName] string method = "") { if (result != values[31]) { Succeeded = false; TestLibrary.TestFramework.LogInformation($"Vector256<Byte.GetElement(31): {method} failed:"); TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", values)})"); TestLibrary.TestFramework.LogInformation($" result: ({result})"); TestLibrary.TestFramework.LogInformation(string.Empty); } } private void ValidateWithResult(Vector256<Byte> result, Byte[] values, Byte insertedValue, [CallerMemberName] string method = "") { Byte[] resultElements = new Byte[ElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref resultElements[0]), result); ValidateWithResult(resultElements, values, insertedValue, method); } private void ValidateWithResult(Byte[] result, Byte[] values, Byte insertedValue, [CallerMemberName] string method = "") { bool succeeded = true; for (int i = 0; i < ElementCount; i++) { if ((i != 31) && (result[i] != values[i])) { succeeded = false; break; } } if (result[31] != insertedValue) { succeeded = false; } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector256<Byte.WithElement(31): {method} failed:"); TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", values)})"); TestLibrary.TestFramework.LogInformation($" insert: insertedValue"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using Microsoft.AspNetCore.Mvc.DataAnnotations; using Microsoft.AspNetCore.Mvc.Localization; using Microsoft.AspNetCore.Mvc.Razor; using Microsoft.Extensions.Localization; namespace Microsoft.Extensions.DependencyInjection { /// <summary> /// Extension methods for configuring MVC view and data annotations localization services. /// </summary> public static class MvcLocalizationMvcCoreBuilderExtensions { /// <summary> /// Adds MVC view localization services to the application. /// </summary> /// <param name="builder">The <see cref="IMvcCoreBuilder"/>.</param> /// <returns>The <see cref="IMvcCoreBuilder"/>.</returns> /// <remarks> /// Adding localization also adds support for views via /// <see cref="MvcViewFeaturesMvcCoreBuilderExtensions.AddViews(IMvcCoreBuilder)"/> and the Razor view engine /// via <see cref="MvcRazorMvcCoreBuilderExtensions.AddRazorViewEngine(IMvcCoreBuilder)"/>. /// </remarks> public static IMvcCoreBuilder AddViewLocalization(this IMvcCoreBuilder builder) { if (builder == null) { throw new ArgumentNullException(nameof(builder)); } return AddViewLocalization(builder, LanguageViewLocationExpanderFormat.Suffix); } /// <summary> /// Adds MVC view localization services to the application. /// </summary> /// <param name="builder">The <see cref="IMvcCoreBuilder"/>.</param> /// <param name="format">The view format for localized views.</param> /// <returns>The <see cref="IMvcCoreBuilder"/>.</returns> /// <remarks> /// Adding localization also adds support for views via /// <see cref="MvcViewFeaturesMvcCoreBuilderExtensions.AddViews(IMvcCoreBuilder)"/> and the Razor view engine /// via <see cref="MvcRazorMvcCoreBuilderExtensions.AddRazorViewEngine(IMvcCoreBuilder)"/>. /// </remarks> public static IMvcCoreBuilder AddViewLocalization( this IMvcCoreBuilder builder, LanguageViewLocationExpanderFormat format) { if (builder == null) { throw new ArgumentNullException(nameof(builder)); } builder.AddViews(); builder.AddRazorViewEngine(); MvcLocalizationServices.AddLocalizationServices(builder.Services, format, setupAction: null); return builder; } /// <summary> /// Adds MVC view localization services to the application. /// </summary> /// <param name="builder">The <see cref="IMvcCoreBuilder"/>.</param> /// <param name="setupAction">An action to configure the <see cref="LocalizationOptions"/>.</param> /// <returns>The <see cref="IMvcCoreBuilder"/>.</returns> /// <remarks> /// Adding localization also adds support for views via /// <see cref="MvcViewFeaturesMvcCoreBuilderExtensions.AddViews(IMvcCoreBuilder)"/> and the Razor view engine /// via <see cref="MvcRazorMvcCoreBuilderExtensions.AddRazorViewEngine(IMvcCoreBuilder)"/>. /// </remarks> public static IMvcCoreBuilder AddViewLocalization( this IMvcCoreBuilder builder, Action<LocalizationOptions>? setupAction) { if (builder == null) { throw new ArgumentNullException(nameof(builder)); } return AddViewLocalization(builder, LanguageViewLocationExpanderFormat.Suffix, setupAction); } /// <summary> /// Adds MVC view localization services to the application. /// </summary> /// <param name="builder">The <see cref="IMvcCoreBuilder"/>.</param> /// <param name="format">The view format for localized views.</param> /// <param name="setupAction">An action to configure the <see cref="LocalizationOptions"/>.</param> /// <returns>The <see cref="IMvcCoreBuilder"/>.</returns> /// <remarks> /// Adding localization also adds support for views via /// <see cref="MvcViewFeaturesMvcCoreBuilderExtensions.AddViews(IMvcCoreBuilder)"/> and the Razor view engine /// via <see cref="MvcRazorMvcCoreBuilderExtensions.AddRazorViewEngine(IMvcCoreBuilder)"/>. /// </remarks> public static IMvcCoreBuilder AddViewLocalization( this IMvcCoreBuilder builder, LanguageViewLocationExpanderFormat format, Action<LocalizationOptions>? setupAction) { if (builder == null) { throw new ArgumentNullException(nameof(builder)); } builder.AddViews(); builder.AddRazorViewEngine(); MvcLocalizationServices.AddLocalizationServices(builder.Services, format, setupAction); return builder; } /// <summary> /// Adds MVC view and data annotations localization services to the application. /// </summary> /// <param name="builder">The <see cref="IMvcCoreBuilder"/>.</param> /// <returns>The <see cref="IMvcCoreBuilder"/>.</returns> /// <remarks> /// Adding localization also adds support for views via /// <see cref="MvcViewFeaturesMvcCoreBuilderExtensions.AddViews(IMvcCoreBuilder)"/> and the Razor view engine /// via <see cref="MvcRazorMvcCoreBuilderExtensions.AddRazorViewEngine(IMvcCoreBuilder)"/>. /// </remarks> public static IMvcCoreBuilder AddMvcLocalization(this IMvcCoreBuilder builder) { if (builder == null) { throw new ArgumentNullException(nameof(builder)); } return AddMvcLocalization( builder, localizationOptionsSetupAction: null, format: LanguageViewLocationExpanderFormat.Suffix, dataAnnotationsLocalizationOptionsSetupAction: null); } /// <summary> /// Adds MVC view and data annotations localization services to the application. /// </summary> /// <param name="builder">The <see cref="IMvcCoreBuilder"/>.</param> /// <param name="localizationOptionsSetupAction">An action to configure the <see cref="LocalizationOptions"/>.</param> /// <returns>The <see cref="IMvcCoreBuilder"/>.</returns> /// <remarks> /// Adding localization also adds support for views via /// <see cref="MvcViewFeaturesMvcCoreBuilderExtensions.AddViews(IMvcCoreBuilder)"/> and the Razor view engine /// via <see cref="MvcRazorMvcCoreBuilderExtensions.AddRazorViewEngine(IMvcCoreBuilder)"/>. /// </remarks> public static IMvcCoreBuilder AddMvcLocalization( this IMvcCoreBuilder builder, Action<LocalizationOptions>? localizationOptionsSetupAction) { if (builder == null) { throw new ArgumentNullException(nameof(builder)); } return AddMvcLocalization( builder, localizationOptionsSetupAction, LanguageViewLocationExpanderFormat.Suffix, dataAnnotationsLocalizationOptionsSetupAction: null); } /// <summary> /// Adds MVC view and data annotations localization services to the application. /// </summary> /// <param name="builder">The <see cref="IMvcCoreBuilder"/>.</param> /// <param name="format">The view format for localized views.</param> /// <returns>The <see cref="IMvcCoreBuilder"/>.</returns> /// <remarks> /// Adding localization also adds support for views via /// <see cref="MvcViewFeaturesMvcCoreBuilderExtensions.AddViews(IMvcCoreBuilder)"/> and the Razor view engine /// via <see cref="MvcRazorMvcCoreBuilderExtensions.AddRazorViewEngine(IMvcCoreBuilder)"/>. /// </remarks> public static IMvcCoreBuilder AddMvcLocalization( this IMvcCoreBuilder builder, LanguageViewLocationExpanderFormat format) { if (builder == null) { throw new ArgumentNullException(nameof(builder)); } return AddMvcLocalization( builder, localizationOptionsSetupAction: null, format: format, dataAnnotationsLocalizationOptionsSetupAction: null); } /// <summary> /// Adds MVC view and data annotations localization services to the application. /// </summary> /// <param name="builder">The <see cref="IMvcCoreBuilder"/>.</param> /// <param name="localizationOptionsSetupAction">An action to configure the /// <see cref="LocalizationOptions"/>.</param> /// <param name="format">The view format for localized views.</param> /// <returns>The <see cref="IMvcCoreBuilder"/>.</returns> /// <remarks> /// Adding localization also adds support for views via /// <see cref="MvcViewFeaturesMvcCoreBuilderExtensions.AddViews(IMvcCoreBuilder)"/> and the Razor view engine /// via <see cref="MvcRazorMvcCoreBuilderExtensions.AddRazorViewEngine(IMvcCoreBuilder)"/>. /// </remarks> public static IMvcCoreBuilder AddMvcLocalization( this IMvcCoreBuilder builder, Action<LocalizationOptions>? localizationOptionsSetupAction, LanguageViewLocationExpanderFormat format) { if (builder == null) { throw new ArgumentNullException(nameof(builder)); } return AddMvcLocalization( builder, localizationOptionsSetupAction: localizationOptionsSetupAction, format: format, dataAnnotationsLocalizationOptionsSetupAction: null); } /// <summary> /// Adds MVC view and data annotations localization services to the application. /// </summary> /// <param name="builder">The <see cref="IMvcCoreBuilder"/>.</param> /// <param name="dataAnnotationsLocalizationOptionsSetupAction">An action to configure /// the <see cref="MvcDataAnnotationsLocalizationOptions"/>.</param> /// <returns>The <see cref="IMvcCoreBuilder"/>.</returns> /// <remarks> /// Adding localization also adds support for views via /// <see cref="MvcViewFeaturesMvcCoreBuilderExtensions.AddViews(IMvcCoreBuilder)"/> and the Razor view engine /// via <see cref="MvcRazorMvcCoreBuilderExtensions.AddRazorViewEngine(IMvcCoreBuilder)"/>. /// </remarks> public static IMvcCoreBuilder AddMvcLocalization( this IMvcCoreBuilder builder, Action<MvcDataAnnotationsLocalizationOptions>? dataAnnotationsLocalizationOptionsSetupAction) { if (builder == null) { throw new ArgumentNullException(nameof(builder)); } return AddMvcLocalization( builder, localizationOptionsSetupAction: null, format: LanguageViewLocationExpanderFormat.Suffix, dataAnnotationsLocalizationOptionsSetupAction: dataAnnotationsLocalizationOptionsSetupAction); } /// <summary> /// Adds MVC view and data annotations localization services to the application. /// </summary> /// <param name="builder">The <see cref="IMvcCoreBuilder"/>.</param> /// <param name="localizationOptionsSetupAction">An action to configure the /// <see cref="LocalizationOptions"/>.</param> /// <param name="dataAnnotationsLocalizationOptionsSetupAction">An action to configure the /// <see cref="MvcDataAnnotationsLocalizationOptions"/>.</param> /// <returns>The <see cref="IMvcCoreBuilder"/>.</returns> /// <remarks> /// Adding localization also adds support for views via /// <see cref="MvcViewFeaturesMvcCoreBuilderExtensions.AddViews(IMvcCoreBuilder)"/> and the Razor view engine /// via <see cref="MvcRazorMvcCoreBuilderExtensions.AddRazorViewEngine(IMvcCoreBuilder)"/>. /// </remarks> public static IMvcCoreBuilder AddMvcLocalization( this IMvcCoreBuilder builder, Action<LocalizationOptions>? localizationOptionsSetupAction, Action<MvcDataAnnotationsLocalizationOptions>? dataAnnotationsLocalizationOptionsSetupAction) { if (builder == null) { throw new ArgumentNullException(nameof(builder)); } return AddMvcLocalization( builder, localizationOptionsSetupAction: localizationOptionsSetupAction, format: LanguageViewLocationExpanderFormat.Suffix, dataAnnotationsLocalizationOptionsSetupAction: dataAnnotationsLocalizationOptionsSetupAction); } /// <summary> /// Adds MVC view and data annotations localization services to the application. /// </summary> /// <param name="builder">The <see cref="IMvcCoreBuilder"/>.</param> /// <param name="format">The view format for localized views.</param> /// <param name="dataAnnotationsLocalizationOptionsSetupAction">An action to configure the /// <see cref="MvcDataAnnotationsLocalizationOptions"/>.</param> /// <returns>The <see cref="IMvcCoreBuilder"/>.</returns> /// <remarks> /// Adding localization also adds support for views via /// <see cref="MvcViewFeaturesMvcCoreBuilderExtensions.AddViews(IMvcCoreBuilder)"/> and the Razor view engine /// via <see cref="MvcRazorMvcCoreBuilderExtensions.AddRazorViewEngine(IMvcCoreBuilder)"/>. /// </remarks> public static IMvcCoreBuilder AddMvcLocalization( this IMvcCoreBuilder builder, LanguageViewLocationExpanderFormat format, Action<MvcDataAnnotationsLocalizationOptions>? dataAnnotationsLocalizationOptionsSetupAction) { if (builder == null) { throw new ArgumentNullException(nameof(builder)); } return AddMvcLocalization( builder, localizationOptionsSetupAction: null, format: format, dataAnnotationsLocalizationOptionsSetupAction: dataAnnotationsLocalizationOptionsSetupAction); } /// <summary> /// Adds MVC view and data annotations localization services to the application. /// </summary> /// <param name="builder">The <see cref="IMvcCoreBuilder"/>.</param> /// <param name="localizationOptionsSetupAction">An action to configure /// the <see cref="LocalizationOptions"/>. Can be <c>null</c>.</param> /// <param name="format">The view format for localized views.</param> /// <param name="dataAnnotationsLocalizationOptionsSetupAction">An action to configure /// the <see cref="MvcDataAnnotationsLocalizationOptions"/>. Can be <c>null</c>.</param> /// <returns>The <see cref="IMvcCoreBuilder"/>.</returns> /// <remarks> /// Adding localization also adds support for views via /// <see cref="MvcViewFeaturesMvcCoreBuilderExtensions.AddViews(IMvcCoreBuilder)"/> and the Razor view engine /// via <see cref="MvcRazorMvcCoreBuilderExtensions.AddRazorViewEngine(IMvcCoreBuilder)"/>. /// </remarks> public static IMvcCoreBuilder AddMvcLocalization( this IMvcCoreBuilder builder, Action<LocalizationOptions>? localizationOptionsSetupAction, LanguageViewLocationExpanderFormat format, Action<MvcDataAnnotationsLocalizationOptions>? dataAnnotationsLocalizationOptionsSetupAction) { if (builder == null) { throw new ArgumentNullException(nameof(builder)); } return builder .AddViewLocalization(format, localizationOptionsSetupAction) .AddDataAnnotationsLocalization(dataAnnotationsLocalizationOptionsSetupAction); } } }
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Runtime.CompilerServices; using System.Text; using ICSharpCode.NRefactory.TypeSystem; using Saltarelle.Compiler; using Saltarelle.Compiler.Compiler; using Saltarelle.Compiler.JSModel.Expressions; using Saltarelle.Compiler.JSModel.ExtensionMethods; using Saltarelle.Compiler.ScriptSemantics; namespace CoreLib.Plugin { public class MetadataImporter : IMetadataImporter { private static readonly ReadOnlySet<string> _unusableStaticFieldNames = new ReadOnlySet<string>(new HashSet<string>(new[] { "__defineGetter__", "__defineSetter__", "apply", "arguments", "bind", "call", "caller", "constructor", "hasOwnProperty", "isPrototypeOf", "length", "name", "propertyIsEnumerable", "prototype", "toLocaleString", "valueOf" }.Concat(Saltarelle.Compiler.JSModel.Utils.AllKeywords))); private static readonly ReadOnlySet<string> _unusableInstanceFieldNames = new ReadOnlySet<string>(new HashSet<string>(new[] { "__defineGetter__", "__defineSetter__", "constructor", "hasOwnProperty", "isPrototypeOf", "propertyIsEnumerable", "toLocaleString", "valueOf" }.Concat(Saltarelle.Compiler.JSModel.Utils.AllKeywords))); /// <summary> /// Used to deterministically order members. It is assumed that all members belong to the same type. /// </summary> private class MemberOrderer : IComparer<IMember> { public static readonly MemberOrderer Instance = new MemberOrderer(); private MemberOrderer() { } private int CompareMethods(IMethod x, IMethod y) { int result = string.CompareOrdinal(x.Name, y.Name); if (result != 0) return result; if (x.Parameters.Count > y.Parameters.Count) return 1; else if (x.Parameters.Count < y.Parameters.Count) return -1; var xparms = string.Join(",", x.Parameters.Select(p => p.Type.FullName)); var yparms = string.Join(",", y.Parameters.Select(p => p.Type.FullName)); var presult = string.CompareOrdinal(xparms, yparms); if (presult != 0) return presult; var rresult = string.CompareOrdinal(x.ReturnType.FullName, y.ReturnType.FullName); if (rresult != 0) return rresult; if (x.TypeParameters.Count > y.TypeParameters.Count) return 1; else if (x.TypeParameters.Count < y.TypeParameters.Count) return -1; return 0; } public int Compare(IMember x, IMember y) { if (x is IMethod) { if (y is IMethod) { return CompareMethods((IMethod)x, (IMethod)y); } else return -1; } else if (y is IMethod) { return 1; } if (x is IProperty) { if (y is IProperty) { return string.CompareOrdinal(x.Name, y.Name); } else return -1; } else if (y is IProperty) { return 1; } if (x is IField) { if (y is IField) { return string.CompareOrdinal(x.Name, y.Name); } else return -1; } else if (y is IField) { return 1; } if (x is IEvent) { if (y is IEvent) { return string.CompareOrdinal(x.Name, y.Name); } else return -1; } else if (y is IEvent) { return 1; } throw new ArgumentException("Invalid member type" + x.GetType().FullName); } } private class TypeSemantics { public TypeScriptSemantics Semantics { get; private set; } public bool IsSerializable { get; private set; } public bool IsNamedValues { get; private set; } public bool IsImported { get; private set; } public TypeSemantics(TypeScriptSemantics semantics, bool isSerializable, bool isNamedValues, bool isImported) { Semantics = semantics; IsSerializable = isSerializable; IsNamedValues = isNamedValues; IsImported = isImported; } } private Dictionary<ITypeDefinition, TypeSemantics> _typeSemantics; private Dictionary<ITypeDefinition, DelegateScriptSemantics> _delegateSemantics; private Dictionary<ITypeDefinition, HashSet<string>> _instanceMemberNamesByType; private Dictionary<ITypeDefinition, HashSet<string>> _staticMemberNamesByType; private Dictionary<IMethod, MethodScriptSemantics> _methodSemantics; private Dictionary<IProperty, PropertyScriptSemantics> _propertySemantics; private Dictionary<IField, FieldScriptSemantics> _fieldSemantics; private Dictionary<IEvent, EventScriptSemantics> _eventSemantics; private Dictionary<IMethod, ConstructorScriptSemantics> _constructorSemantics; private Dictionary<ITypeParameter, string> _typeParameterNames; private Dictionary<IProperty, string> _propertyBackingFieldNames; private Dictionary<IEvent, string> _eventBackingFieldNames; private Dictionary<ITypeDefinition, int> _backingFieldCountPerType; private Dictionary<Tuple<IAssembly, string>, int> _internalTypeCountPerAssemblyAndNamespace; private HashSet<IMember> _ignoredMembers; private IErrorReporter _errorReporter; private IType _systemObject; private ICompilation _compilation; private bool _minimizeNames; public MetadataImporter(IErrorReporter errorReporter, ICompilation compilation, CompilerOptions options) { _errorReporter = errorReporter; _compilation = compilation; _minimizeNames = options.MinimizeScript; _systemObject = compilation.MainAssembly.Compilation.FindType(KnownTypeCode.Object); _typeSemantics = new Dictionary<ITypeDefinition, TypeSemantics>(); _delegateSemantics = new Dictionary<ITypeDefinition, DelegateScriptSemantics>(); _instanceMemberNamesByType = new Dictionary<ITypeDefinition, HashSet<string>>(); _staticMemberNamesByType = new Dictionary<ITypeDefinition, HashSet<string>>(); _methodSemantics = new Dictionary<IMethod, MethodScriptSemantics>(); _propertySemantics = new Dictionary<IProperty, PropertyScriptSemantics>(); _fieldSemantics = new Dictionary<IField, FieldScriptSemantics>(); _eventSemantics = new Dictionary<IEvent, EventScriptSemantics>(); _constructorSemantics = new Dictionary<IMethod, ConstructorScriptSemantics>(); _typeParameterNames = new Dictionary<ITypeParameter, string>(); _propertyBackingFieldNames = new Dictionary<IProperty, string>(); _eventBackingFieldNames = new Dictionary<IEvent, string>(); _backingFieldCountPerType = new Dictionary<ITypeDefinition, int>(); _internalTypeCountPerAssemblyAndNamespace = new Dictionary<Tuple<IAssembly, string>, int>(); _ignoredMembers = new HashSet<IMember>(); var sna = compilation.MainAssembly.AssemblyAttributes.SingleOrDefault(a => a.AttributeType.FullName == typeof(ScriptNamespaceAttribute).FullName); if (sna != null) { var data = AttributeReader.ReadAttribute<ScriptNamespaceAttribute>(sna); if (data.Name == null || (data.Name != "" && !data.Name.IsValidNestedJavaScriptIdentifier())) { Message(Messages._7002, sna.Region, "assembly"); } } } private void Message(Tuple<int, MessageSeverity, string> message, DomRegion r, params object[] additionalArgs) { _errorReporter.Region = r; _errorReporter.Message(message, additionalArgs); } private void Message(Tuple<int, MessageSeverity, string> message, ITypeDefinition t, params object[] additionalArgs) { _errorReporter.Region = t.Region; _errorReporter.Message(message, new object[] { t.FullName }.Concat(additionalArgs).ToArray()); } private void Message(Tuple<int, MessageSeverity, string> message, IMember m, params object[] additionalArgs) { var name = (m is IMethod && ((IMethod)m).IsConstructor ? m.DeclaringType.Name : m.Name); _errorReporter.Region = m.Region; _errorReporter.Message(message, new object[] { m.DeclaringType.FullName + "." + name }.Concat(additionalArgs).ToArray()); } private string GetDefaultTypeName(ITypeDefinition def, bool ignoreGenericArguments) { if (ignoreGenericArguments) { return def.Name; } else { int outerCount = (def.DeclaringTypeDefinition != null ? def.DeclaringTypeDefinition.TypeParameters.Count : 0); return def.Name + (def.TypeParameterCount != outerCount ? "$" + (def.TypeParameterCount - outerCount).ToString(CultureInfo.InvariantCulture) : ""); } } private string DetermineNamespace(ITypeDefinition typeDefinition) { while (typeDefinition.DeclaringTypeDefinition != null) { typeDefinition = typeDefinition.DeclaringTypeDefinition; } var ina = AttributeReader.ReadAttribute<IgnoreNamespaceAttribute>(typeDefinition); var sna = AttributeReader.ReadAttribute<ScriptNamespaceAttribute>(typeDefinition); if (ina != null) { if (sna != null) { Message(Messages._7001, typeDefinition); return typeDefinition.FullName; } else { return ""; } } else { if (sna != null) { if (sna.Name == null || (sna.Name != "" && !sna.Name.IsValidNestedJavaScriptIdentifier())) Message(Messages._7002, typeDefinition); return sna.Name; } else { var asna = AttributeReader.ReadAttribute<ScriptNamespaceAttribute>(typeDefinition.ParentAssembly.AssemblyAttributes); if (asna != null) { if (asna.Name != null && (asna.Name == "" || asna.Name.IsValidNestedJavaScriptIdentifier())) return asna.Name; } return typeDefinition.Namespace; } } } private Tuple<string, string> SplitNamespacedName(string fullName) { string nmspace; string name; int dot = fullName.IndexOf('.'); if (dot >= 0) { nmspace = fullName.Substring(0, dot); name = fullName.Substring(dot + 1 ); } else { nmspace = ""; name = fullName; } return Tuple.Create(nmspace, name); } private void ProcessDelegate(ITypeDefinition delegateDefinition) { bool bindThisToFirstParameter = AttributeReader.HasAttribute<BindThisToFirstParameterAttribute>(delegateDefinition); bool expandParams = AttributeReader.HasAttribute<ExpandParamsAttribute>(delegateDefinition); if (bindThisToFirstParameter && delegateDefinition.GetDelegateInvokeMethod().Parameters.Count == 0) { Message(Messages._7147, delegateDefinition, delegateDefinition.FullName); bindThisToFirstParameter = false; } if (expandParams && !delegateDefinition.GetDelegateInvokeMethod().Parameters.Any(p => p.IsParams)) { Message(Messages._7148, delegateDefinition, delegateDefinition.FullName); expandParams = false; } _delegateSemantics[delegateDefinition] = new DelegateScriptSemantics(expandParams: expandParams, bindThisToFirstParameter: bindThisToFirstParameter); } private void ProcessType(ITypeDefinition typeDefinition) { if (typeDefinition.Kind == TypeKind.Delegate) { ProcessDelegate(typeDefinition); return; } if (AttributeReader.HasAttribute<NonScriptableAttribute>(typeDefinition) || typeDefinition.DeclaringTypeDefinition != null && GetTypeSemantics(typeDefinition.DeclaringTypeDefinition).Type == TypeScriptSemantics.ImplType.NotUsableFromScript) { _typeSemantics[typeDefinition] = new TypeSemantics(TypeScriptSemantics.NotUsableFromScript(), false, false, false); return; } var scriptNameAttr = AttributeReader.ReadAttribute<ScriptNameAttribute>(typeDefinition); var importedAttr = AttributeReader.ReadAttribute<ImportedAttribute>(typeDefinition.Attributes); bool isImported = importedAttr != null; bool preserveName = isImported || AttributeReader.HasAttribute<PreserveNameAttribute>(typeDefinition); bool? includeGenericArguments = typeDefinition.TypeParameterCount > 0 ? MetadataUtils.ShouldGenericArgumentsBeIncluded(typeDefinition) : false; if (includeGenericArguments == null) { _errorReporter.Region = typeDefinition.Region; Message(Messages._7026, typeDefinition); includeGenericArguments = true; } if (AttributeReader.HasAttribute<ResourcesAttribute>(typeDefinition)) { if (!typeDefinition.IsStatic) { Message(Messages._7003, typeDefinition); } else if (typeDefinition.TypeParameterCount > 0) { Message(Messages._7004, typeDefinition); } else if (typeDefinition.Members.Any(m => !(m is IField && ((IField)m).IsConst))) { Message(Messages._7005, typeDefinition); } } string typeName, nmspace; if (scriptNameAttr != null && scriptNameAttr.Name != null && scriptNameAttr.Name.IsValidJavaScriptIdentifier()) { typeName = scriptNameAttr.Name; nmspace = DetermineNamespace(typeDefinition); } else { if (scriptNameAttr != null) { Message(Messages._7006, typeDefinition); } if (_minimizeNames && MetadataUtils.CanBeMinimized(typeDefinition) && !preserveName) { nmspace = DetermineNamespace(typeDefinition); var key = Tuple.Create(typeDefinition.ParentAssembly, nmspace); int index; _internalTypeCountPerAssemblyAndNamespace.TryGetValue(key, out index); _internalTypeCountPerAssemblyAndNamespace[key] = index + 1; typeName = "$" + index.ToString(CultureInfo.InvariantCulture); } else { typeName = GetDefaultTypeName(typeDefinition, !includeGenericArguments.Value); if (typeDefinition.DeclaringTypeDefinition != null) { if (AttributeReader.HasAttribute<IgnoreNamespaceAttribute>(typeDefinition) || AttributeReader.HasAttribute<ScriptNamespaceAttribute>(typeDefinition)) { Message(Messages._7007, typeDefinition); } var declaringName = SplitNamespacedName(GetTypeSemantics(typeDefinition.DeclaringTypeDefinition).Name); nmspace = declaringName.Item1; typeName = declaringName.Item2 + "$" + typeName; } else { nmspace = DetermineNamespace(typeDefinition); } if (MetadataUtils.CanBeMinimized(typeDefinition) && !preserveName && !typeName.StartsWith("$")) { typeName = "$" + typeName; } } } bool isSerializable = MetadataUtils.IsSerializable(typeDefinition); if (isSerializable) { var baseClass = typeDefinition.DirectBaseTypes.Single(c => c.Kind == TypeKind.Class).GetDefinition(); if (!baseClass.Equals(_systemObject) && baseClass.FullName != "System.Record" && !GetTypeSemanticsInternal(baseClass).IsSerializable) { Message(Messages._7009, typeDefinition); isSerializable = false; } if (typeDefinition.DirectBaseTypes.Any(b => b.Kind == TypeKind.Interface)) { Message(Messages._7010, typeDefinition); isSerializable = false; } if (typeDefinition.Events.Any(evt => !evt.IsStatic)) { Message(Messages._7011, typeDefinition); isSerializable = false; } foreach (var m in typeDefinition.Members.Where(m => m.IsVirtual)) { Message(Messages._7023, typeDefinition, m.Name); isSerializable = false; } foreach (var m in typeDefinition.Members.Where(m => m.IsOverride)) { Message(Messages._7024, typeDefinition, m.Name); isSerializable = false; } } else { var baseClass = typeDefinition.DirectBaseTypes.SingleOrDefault(c => c.Kind == TypeKind.Class); if (baseClass != null && GetTypeSemanticsInternal(baseClass.GetDefinition()).IsSerializable) { Message(Messages._7008, typeDefinition, baseClass.FullName); } var globalMethodsAttr = AttributeReader.ReadAttribute<GlobalMethodsAttribute>(typeDefinition); var mixinAttr = AttributeReader.ReadAttribute<MixinAttribute>(typeDefinition); if (mixinAttr != null) { if (!typeDefinition.IsStatic) { Message(Messages._7012, typeDefinition); } else if (typeDefinition.Members.Any(m => !(m is IMethod) || ((IMethod)m).IsConstructor)) { Message(Messages._7013, typeDefinition); } else if (typeDefinition.TypeParameterCount > 0) { Message(Messages._7014, typeDefinition); } else if (string.IsNullOrEmpty(mixinAttr.Expression)) { Message(Messages._7025, typeDefinition); } else { var split = SplitNamespacedName(mixinAttr.Expression); nmspace = split.Item1; typeName = split.Item2; } } else if (globalMethodsAttr != null) { if (!typeDefinition.IsStatic) { Message(Messages._7015, typeDefinition); } else if (typeDefinition.TypeParameterCount > 0) { Message(Messages._7017, typeDefinition); } else { nmspace = ""; typeName = ""; } } } for (int i = 0; i < typeDefinition.TypeParameterCount; i++) { var tp = typeDefinition.TypeParameters[i]; _typeParameterNames[tp] = _minimizeNames ? MetadataUtils.EncodeNumber(i, true) : tp.Name; } _typeSemantics[typeDefinition] = new TypeSemantics(TypeScriptSemantics.NormalType(!string.IsNullOrEmpty(nmspace) ? nmspace + "." + typeName : typeName, ignoreGenericArguments: !includeGenericArguments.Value, generateCode: !isImported), isSerializable: isSerializable, isNamedValues: MetadataUtils.IsNamedValues(typeDefinition), isImported: isImported); } private HashSet<string> GetInstanceMemberNames(ITypeDefinition typeDefinition) { HashSet<string> result; if (!_instanceMemberNamesByType.TryGetValue(typeDefinition, out result)) throw new ArgumentException("Error getting instance member names: type " + typeDefinition.FullName + " has not yet been processed."); return result; } private Tuple<string, bool> DeterminePreferredMemberName(IMember member) { var asa = AttributeReader.ReadAttribute<AlternateSignatureAttribute>(member); if (asa != null) { var otherMembers = member.DeclaringTypeDefinition.Methods.Where(m => m.Name == member.Name && !AttributeReader.HasAttribute<AlternateSignatureAttribute>(m) && !AttributeReader.HasAttribute<NonScriptableAttribute>(m) && !AttributeReader.HasAttribute<InlineCodeAttribute>(m)).ToList(); if (otherMembers.Count != 1) { Message(Messages._7100, member); return Tuple.Create(member.Name, false); } } return MetadataUtils.DeterminePreferredMemberName(member, _minimizeNames); } private void ProcessTypeMembers(ITypeDefinition typeDefinition) { if (typeDefinition.Kind == TypeKind.Delegate) return; var baseMembersByType = typeDefinition.GetAllBaseTypeDefinitions().Where(x => x != typeDefinition).Select(t => new { Type = t, MemberNames = GetInstanceMemberNames(t) }).ToList(); for (int i = 0; i < baseMembersByType.Count; i++) { var b = baseMembersByType[i]; for (int j = i + 1; j < baseMembersByType.Count; j++) { var b2 = baseMembersByType[j]; if (!b.Type.GetAllBaseTypeDefinitions().Contains(b2.Type) && !b2.Type.GetAllBaseTypeDefinitions().Contains(b.Type)) { foreach (var dup in b.MemberNames.Where(x => b2.MemberNames.Contains(x))) { Message(Messages._7018, typeDefinition, b.Type.FullName, b2.Type.FullName, dup); } } } } var instanceMembers = baseMembersByType.SelectMany(m => m.MemberNames).Distinct().ToDictionary(m => m, m => false); if (_instanceMemberNamesByType.ContainsKey(typeDefinition)) _instanceMemberNamesByType[typeDefinition].ForEach(s => instanceMembers[s] = true); _unusableInstanceFieldNames.ForEach(n => instanceMembers[n] = false); var staticMembers = _unusableStaticFieldNames.ToDictionary(n => n, n => false); if (_staticMemberNamesByType.ContainsKey(typeDefinition)) _staticMemberNamesByType[typeDefinition].ForEach(s => staticMembers[s] = true); var membersByName = from m in typeDefinition.GetMembers(options: GetMemberOptions.IgnoreInheritedMembers) where !_ignoredMembers.Contains(m) let name = DeterminePreferredMemberName(m) group new { m, name } by name.Item1 into g select new { Name = g.Key, Members = g.Select(x => new { Member = x.m, NameSpecified = x.name.Item2 }).ToList() }; bool isSerializable = GetTypeSemanticsInternal(typeDefinition).IsSerializable; foreach (var current in membersByName) { foreach (var m in current.Members.OrderByDescending(x => x.NameSpecified).ThenBy(x => x.Member, MemberOrderer.Instance)) { if (m.Member is IMethod) { var method = (IMethod)m.Member; if (method.IsConstructor) { ProcessConstructor(method, current.Name, m.NameSpecified, staticMembers); } else { ProcessMethod(method, current.Name, m.NameSpecified, m.Member.IsStatic || isSerializable ? staticMembers : instanceMembers); } } else if (m.Member is IProperty) { var p = (IProperty)m.Member; ProcessProperty(p, current.Name, m.NameSpecified, m.Member.IsStatic ? staticMembers : instanceMembers); var ps = GetPropertySemantics(p); if (p.CanGet) _methodSemantics[p.Getter] = ps.Type == PropertyScriptSemantics.ImplType.GetAndSetMethods ? ps.GetMethod : MethodScriptSemantics.NotUsableFromScript(); if (p.CanSet) _methodSemantics[p.Setter] = ps.Type == PropertyScriptSemantics.ImplType.GetAndSetMethods ? ps.SetMethod : MethodScriptSemantics.NotUsableFromScript(); } else if (m.Member is IField) { ProcessField((IField)m.Member, current.Name, m.NameSpecified, m.Member.IsStatic ? staticMembers : instanceMembers); } else if (m.Member is IEvent) { var e = (IEvent)m.Member; ProcessEvent((IEvent)m.Member, current.Name, m.NameSpecified, m.Member.IsStatic ? staticMembers : instanceMembers); var es = GetEventSemantics(e); _methodSemantics[e.AddAccessor] = es.Type == EventScriptSemantics.ImplType.AddAndRemoveMethods ? es.AddMethod : MethodScriptSemantics.NotUsableFromScript(); _methodSemantics[e.RemoveAccessor] = es.Type == EventScriptSemantics.ImplType.AddAndRemoveMethods ? es.RemoveMethod : MethodScriptSemantics.NotUsableFromScript(); } } } _instanceMemberNamesByType[typeDefinition] = new HashSet<string>(instanceMembers.Where(kvp => kvp.Value).Select(kvp => kvp.Key)); _staticMemberNamesByType[typeDefinition] = new HashSet<string>(staticMembers.Where(kvp => kvp.Value).Select(kvp => kvp.Key)); } private string GetUniqueName(string preferredName, Dictionary<string, bool> usedNames) { return MetadataUtils.GetUniqueName(preferredName, n => !usedNames.ContainsKey(n)); } private bool ValidateInlineCode(IMethod method, string code, Tuple<int, MessageSeverity, string> errorTemplate) { var typeErrors = new List<string>(); var errors = InlineCodeMethodCompiler.ValidateLiteralCode(method, code, n => { var type = ReflectionHelper.ParseReflectionName(n).Resolve(_compilation); if (type.Kind == TypeKind.Unknown) { typeErrors.Add("Unknown type '" + n + "' specified in inline implementation"); } return JsExpression.Null; }, t => JsExpression.Null); if (errors.Count > 0 || typeErrors.Count > 0) { Message(errorTemplate, method, string.Join(", ", errors.Concat(typeErrors))); return false; } return true; } private void ProcessConstructor(IMethod constructor, string preferredName, bool nameSpecified, Dictionary<string, bool> usedNames) { if (constructor.Parameters.Count == 1 && constructor.Parameters[0].Type.FullName == typeof(DummyTypeUsedToAddAttributeToDefaultValueTypeConstructor).FullName) { _constructorSemantics[constructor] = ConstructorScriptSemantics.NotUsableFromScript(); return; } var source = (IMethod)MetadataUtils.UnwrapValueTypeConstructor(constructor); var nsa = AttributeReader.ReadAttribute<NonScriptableAttribute>(source); var asa = AttributeReader.ReadAttribute<AlternateSignatureAttribute>(source); var epa = AttributeReader.ReadAttribute<ExpandParamsAttribute>(source); var ola = AttributeReader.ReadAttribute<ObjectLiteralAttribute>(source); if (nsa != null || GetTypeSemanticsInternal(source.DeclaringTypeDefinition).Semantics.Type == TypeScriptSemantics.ImplType.NotUsableFromScript) { _constructorSemantics[constructor] = ConstructorScriptSemantics.NotUsableFromScript(); return; } if (source.IsStatic) { _constructorSemantics[constructor] = ConstructorScriptSemantics.Unnamed(); // Whatever, it is not really used. return; } if (epa != null && !source.Parameters.Any(p => p.IsParams)) { Message(Messages._7102, constructor); } bool isSerializable = GetTypeSemanticsInternal(source.DeclaringTypeDefinition).IsSerializable; bool isImported = GetTypeSemanticsInternal(source.DeclaringTypeDefinition).IsImported; var ica = AttributeReader.ReadAttribute<InlineCodeAttribute>(source); if (ica != null) { if (!ValidateInlineCode(source, ica.Code, Messages._7103)) { _constructorSemantics[constructor] = ConstructorScriptSemantics.Unnamed(); return; } _constructorSemantics[constructor] = ConstructorScriptSemantics.InlineCode(ica.Code); return; } else if (asa != null) { _constructorSemantics[constructor] = preferredName == "$ctor" ? ConstructorScriptSemantics.Unnamed(generateCode: false, expandParams: epa != null) : ConstructorScriptSemantics.Named(preferredName, generateCode: false, expandParams: epa != null); return; } else if (ola != null || (isSerializable && GetTypeSemanticsInternal(source.DeclaringTypeDefinition).IsImported)) { if (isSerializable) { bool hasError = false; var members = source.DeclaringTypeDefinition.Members.Where(m => m.EntityType == EntityType.Property || m.EntityType == EntityType.Field).ToDictionary(m => m.Name.ToLowerInvariant()); var parameterToMemberMap = new List<IMember>(); foreach (var p in source.Parameters) { IMember member; if (p.IsOut || p.IsRef) { Message(Messages._7145, p.Region, p.Name); hasError = true; } else if (members.TryGetValue(p.Name.ToLowerInvariant(), out member)) { if (member.ReturnType.Equals(p.Type)) { parameterToMemberMap.Add(member); } else { Message(Messages._7144, p.Region, p.Name, p.Type.FullName, member.ReturnType.FullName); hasError = true; } } else { Message(Messages._7143, p.Region, source.DeclaringTypeDefinition.FullName, p.Name); hasError = true; } } _constructorSemantics[constructor] = hasError ? ConstructorScriptSemantics.Unnamed() : ConstructorScriptSemantics.Json(parameterToMemberMap); } else { Message(Messages._7146, constructor.Region, source.DeclaringTypeDefinition.FullName); _constructorSemantics[constructor] = ConstructorScriptSemantics.Unnamed(); } return; } else if (source.Parameters.Count == 1 && source.Parameters[0].Type is ArrayType && ((ArrayType)source.Parameters[0].Type).ElementType.IsKnownType(KnownTypeCode.Object) && source.Parameters[0].IsParams && isImported) { _constructorSemantics[constructor] = ConstructorScriptSemantics.InlineCode("ss.mkdict({" + source.Parameters[0].Name + "})"); return; } else if (nameSpecified) { if (isSerializable) _constructorSemantics[constructor] = ConstructorScriptSemantics.StaticMethod(preferredName, expandParams: epa != null); else _constructorSemantics[constructor] = preferredName == "$ctor" ? ConstructorScriptSemantics.Unnamed(expandParams: epa != null) : ConstructorScriptSemantics.Named(preferredName, expandParams: epa != null); usedNames[preferredName] = true; return; } else { if (!usedNames.ContainsKey("$ctor") && !(isSerializable && _minimizeNames && MetadataUtils.CanBeMinimized(source))) { // The last part ensures that the first constructor of a serializable type can have its name minimized. _constructorSemantics[constructor] = isSerializable ? ConstructorScriptSemantics.StaticMethod("$ctor", expandParams: epa != null) : ConstructorScriptSemantics.Unnamed(expandParams: epa != null); usedNames["$ctor"] = true; return; } else { string name; if (_minimizeNames && MetadataUtils.CanBeMinimized(source)) { name = GetUniqueName(null, usedNames); } else { int i = 1; do { name = "$ctor" + MetadataUtils.EncodeNumber(i, false); i++; } while (usedNames.ContainsKey(name)); } _constructorSemantics[constructor] = isSerializable ? ConstructorScriptSemantics.StaticMethod(name, expandParams: epa != null) : ConstructorScriptSemantics.Named(name, expandParams: epa != null); usedNames[name] = true; return; } } } private void ProcessProperty(IProperty property, string preferredName, bool nameSpecified, Dictionary<string, bool> usedNames) { if (GetTypeSemanticsInternal(property.DeclaringTypeDefinition).Semantics.Type == TypeScriptSemantics.ImplType.NotUsableFromScript || AttributeReader.HasAttribute<NonScriptableAttribute>(property)) { _propertySemantics[property] = PropertyScriptSemantics.NotUsableFromScript(); return; } else if (preferredName == "") { if (property.IsIndexer) { Message(Messages._7104, property); } else { Message(Messages._7105, property); } _propertySemantics[property] = PropertyScriptSemantics.GetAndSetMethods(property.CanGet ? MethodScriptSemantics.NormalMethod("get") : null, property.CanSet ? MethodScriptSemantics.NormalMethod("set") : null); return; } else if (GetTypeSemanticsInternal(property.DeclaringTypeDefinition).IsSerializable && !property.IsStatic) { var getica = property.Getter != null ? AttributeReader.ReadAttribute<InlineCodeAttribute>(property.Getter) : null; var setica = property.Setter != null ? AttributeReader.ReadAttribute<InlineCodeAttribute>(property.Setter) : null; if (property.Getter != null && property.Setter != null && (getica != null) != (setica != null)) { Message(Messages._7028, property); } else if (getica != null || setica != null) { bool hasError = false; if (property.Getter != null && !ValidateInlineCode(property.Getter, getica.Code, Messages._7130)) { hasError = true; } if (property.Setter != null && !ValidateInlineCode(property.Setter, setica.Code, Messages._7130)) { hasError = true; } if (!hasError) { _propertySemantics[property] = PropertyScriptSemantics.GetAndSetMethods(getica != null ? MethodScriptSemantics.InlineCode(getica.Code) : null, setica != null ? MethodScriptSemantics.InlineCode(setica.Code) : null); return; } } usedNames[preferredName] = true; _propertySemantics[property] = PropertyScriptSemantics.Field(preferredName); return; } var saa = AttributeReader.ReadAttribute<ScriptAliasAttribute>(property); if (saa != null) { if (property.IsIndexer) { Message(Messages._7106, property.Region); } else if (!property.IsStatic) { Message(Messages._7107, property); } else { _propertySemantics[property] = PropertyScriptSemantics.GetAndSetMethods(property.CanGet ? MethodScriptSemantics.InlineCode(saa.Alias) : null, property.CanSet ? MethodScriptSemantics.InlineCode(saa.Alias + " = {value}") : null); return; } } if (AttributeReader.HasAttribute<IntrinsicPropertyAttribute>(property)) { if (property.DeclaringType.Kind == TypeKind.Interface) { if (property.IsIndexer) Message(Messages._7108, property.Region); else Message(Messages._7109, property); } else if (property.IsOverride && GetPropertySemantics((IProperty)InheritanceHelper.GetBaseMember(property).MemberDefinition).Type != PropertyScriptSemantics.ImplType.NotUsableFromScript) { if (property.IsIndexer) Message(Messages._7110, property.Region); else Message(Messages._7111, property); } else if (property.IsOverridable) { if (property.IsIndexer) Message(Messages._7112, property.Region); else Message(Messages._7113, property); } else if (property.IsExplicitInterfaceImplementation || property.ImplementedInterfaceMembers.Any(m => GetPropertySemantics((IProperty)m.MemberDefinition).Type != PropertyScriptSemantics.ImplType.NotUsableFromScript)) { if (property.IsIndexer) Message(Messages._7114, property.Region); else Message(Messages._7115, property); } else if (property.IsIndexer) { if (property.Parameters.Count == 1) { _propertySemantics[property] = PropertyScriptSemantics.GetAndSetMethods(property.CanGet ? MethodScriptSemantics.NativeIndexer() : null, property.CanSet ? MethodScriptSemantics.NativeIndexer() : null); return; } else { Message(Messages._7116, property.Region); } } else { usedNames[preferredName] = true; _propertySemantics[property] = PropertyScriptSemantics.Field(preferredName); return; } } if (property.IsExplicitInterfaceImplementation && property.ImplementedInterfaceMembers.Any(m => GetPropertySemantics((IProperty)m.MemberDefinition).Type == PropertyScriptSemantics.ImplType.NotUsableFromScript)) { // Inherit [NonScriptable] for explicit interface implementations. _propertySemantics[property] = PropertyScriptSemantics.NotUsableFromScript(); return; } MethodScriptSemantics getter, setter; if (property.CanGet) { var getterName = DeterminePreferredMemberName(property.Getter); if (!getterName.Item2) getterName = Tuple.Create(!nameSpecified && _minimizeNames && property.DeclaringType.Kind != TypeKind.Interface && MetadataUtils.CanBeMinimized(property) ? null : (nameSpecified ? "get_" + preferredName : GetUniqueName("get_" + preferredName, usedNames)), false); // If the name was not specified, generate one. ProcessMethod(property.Getter, getterName.Item1, getterName.Item2, usedNames); getter = GetMethodSemantics(property.Getter); } else { getter = null; } if (property.CanSet) { var setterName = DeterminePreferredMemberName(property.Setter); if (!setterName.Item2) setterName = Tuple.Create(!nameSpecified && _minimizeNames && property.DeclaringType.Kind != TypeKind.Interface && MetadataUtils.CanBeMinimized(property) ? null : (nameSpecified ? "set_" + preferredName : GetUniqueName("set_" + preferredName, usedNames)), false); // If the name was not specified, generate one. ProcessMethod(property.Setter, setterName.Item1, setterName.Item2, usedNames); setter = GetMethodSemantics(property.Setter); } else { setter = null; } _propertySemantics[property] = PropertyScriptSemantics.GetAndSetMethods(getter, setter); } private void ProcessMethod(IMethod method, string preferredName, bool nameSpecified, Dictionary<string, bool> usedNames) { for (int i = 0; i < method.TypeParameters.Count; i++) { var tp = method.TypeParameters[i]; _typeParameterNames[tp] = _minimizeNames ? MetadataUtils.EncodeNumber(method.DeclaringType.TypeParameterCount + i, true) : tp.Name; } var eaa = AttributeReader.ReadAttribute<EnumerateAsArrayAttribute>(method); var ssa = AttributeReader.ReadAttribute<ScriptSkipAttribute>(method); var saa = AttributeReader.ReadAttribute<ScriptAliasAttribute>(method); var ica = AttributeReader.ReadAttribute<InlineCodeAttribute>(method); var ifa = AttributeReader.ReadAttribute<InstanceMethodOnFirstArgumentAttribute>(method); var nsa = AttributeReader.ReadAttribute<NonScriptableAttribute>(method); var ioa = AttributeReader.ReadAttribute<IntrinsicOperatorAttribute>(method); var epa = AttributeReader.ReadAttribute<ExpandParamsAttribute>(method); var asa = AttributeReader.ReadAttribute<AlternateSignatureAttribute>(method); bool? includeGenericArguments = method.TypeParameters.Count > 0 ? MetadataUtils.ShouldGenericArgumentsBeIncluded(method) : false; if (eaa != null && (method.Name != "GetEnumerator" || method.IsStatic || method.TypeParameters.Count > 0 || method.Parameters.Count > 0)) { Message(Messages._7151, method); eaa = null; } if (nsa != null || GetTypeSemanticsInternal(method.DeclaringTypeDefinition).Semantics.Type == TypeScriptSemantics.ImplType.NotUsableFromScript) { _methodSemantics[method] = MethodScriptSemantics.NotUsableFromScript(); return; } if (ioa != null) { if (!method.IsOperator) { Message(Messages._7117, method); _methodSemantics[method] = MethodScriptSemantics.NormalMethod(method.Name); } if (method.Name == "op_Implicit" || method.Name == "op_Explicit") { Message(Messages._7118, method); _methodSemantics[method] = MethodScriptSemantics.NormalMethod(method.Name); } else { _methodSemantics[method] = MethodScriptSemantics.NativeOperator(); } return; } else { var interfaceImplementations = method.ImplementedInterfaceMembers.Where(m => method.IsExplicitInterfaceImplementation || _methodSemantics[(IMethod)m.MemberDefinition].Type != MethodScriptSemantics.ImplType.NotUsableFromScript).ToList(); if (ssa != null) { // [ScriptSkip] - Skip invocation of the method entirely. if (method.DeclaringTypeDefinition.Kind == TypeKind.Interface) { Message(Messages._7119, method); _methodSemantics[method] = MethodScriptSemantics.NormalMethod(method.Name); return; } else if (method.IsOverride && GetMethodSemantics((IMethod)InheritanceHelper.GetBaseMember(method).MemberDefinition).Type != MethodScriptSemantics.ImplType.NotUsableFromScript) { Message(Messages._7120, method); _methodSemantics[method] = MethodScriptSemantics.NormalMethod(method.Name); return; } else if (method.IsOverridable) { Message(Messages._7121, method); _methodSemantics[method] = MethodScriptSemantics.NormalMethod(method.Name); return; } else if (interfaceImplementations.Count > 0) { Message(Messages._7122, method); _methodSemantics[method] = MethodScriptSemantics.NormalMethod(method.Name); return; } else { if (method.IsStatic) { if (method.Parameters.Count != 1) { Message(Messages._7123, method); _methodSemantics[method] = MethodScriptSemantics.NormalMethod(method.Name); return; } _methodSemantics[method] = MethodScriptSemantics.InlineCode("{" + method.Parameters[0].Name + "}", enumerateAsArray: eaa != null); return; } else { if (method.Parameters.Count != 0) Message(Messages._7124, method); _methodSemantics[method] = MethodScriptSemantics.InlineCode("{this}", enumerateAsArray: eaa != null); return; } } } else if (saa != null) { if (method.IsStatic) { _methodSemantics[method] = MethodScriptSemantics.InlineCode(saa.Alias + "(" + string.Join(", ", method.Parameters.Select(p => "{" + p.Name + "}")) + ")"); return; } else { Message(Messages._7125, method); _methodSemantics[method] = MethodScriptSemantics.NormalMethod(method.Name); return; } } else if (ica != null) { string code = ica.Code ?? "", nonVirtualCode = ica.NonVirtualCode ?? ica.Code ?? ""; if (method.DeclaringTypeDefinition.Kind == TypeKind.Interface && string.IsNullOrEmpty(ica.GeneratedMethodName)) { Message(Messages._7126, method); _methodSemantics[method] = MethodScriptSemantics.NormalMethod(method.Name); return; } else if (method.IsOverride && GetMethodSemantics((IMethod)InheritanceHelper.GetBaseMember(method).MemberDefinition).Type != MethodScriptSemantics.ImplType.NotUsableFromScript) { Message(Messages._7127, method); _methodSemantics[method] = MethodScriptSemantics.NormalMethod(method.Name); return; } else if (method.IsOverridable && string.IsNullOrEmpty(ica.GeneratedMethodName)) { Message(Messages._7128, method); _methodSemantics[method] = MethodScriptSemantics.NormalMethod(method.Name); return; } else { if (!ValidateInlineCode(method, code, Messages._7130)) { code = nonVirtualCode = "X"; } if (!string.IsNullOrEmpty(ica.NonVirtualCode) && !ValidateInlineCode(method, ica.NonVirtualCode, Messages._7130)) { code = nonVirtualCode = "X"; } _methodSemantics[method] = MethodScriptSemantics.InlineCode(code, enumerateAsArray: eaa != null, generatedMethodName: !string.IsNullOrEmpty(ica.GeneratedMethodName) ? ica.GeneratedMethodName : null, nonVirtualInvocationLiteralCode: nonVirtualCode); if (!string.IsNullOrEmpty(ica.GeneratedMethodName)) usedNames[ica.GeneratedMethodName] = true; return; } } else if (ifa != null) { if (method.IsStatic) { if (epa != null && !method.Parameters.Any(p => p.IsParams)) { Message(Messages._7137, method); } if (method.Parameters.Count == 0) { Message(Messages._7149, method); _methodSemantics[method] = MethodScriptSemantics.NormalMethod(method.Name); return; } else if (method.Parameters[0].IsParams) { Message(Messages._7150, method); _methodSemantics[method] = MethodScriptSemantics.NormalMethod(method.Name); return; } else { var sb = new StringBuilder(); sb.Append("{" + method.Parameters[0].Name + "}." + preferredName + "("); for (int i = 1; i < method.Parameters.Count; i++) { var p = method.Parameters[i]; if (i > 1) sb.Append(", "); sb.Append((epa != null && p.IsParams ? "{*" : "{") + p.Name + "}"); } sb.Append(")"); _methodSemantics[method] = MethodScriptSemantics.InlineCode(sb.ToString()); return; } } else { Message(Messages._7131, method); _methodSemantics[method] = MethodScriptSemantics.NormalMethod(method.Name); return; } } else { if (method.IsOverride && GetMethodSemantics((IMethod)InheritanceHelper.GetBaseMember(method).MemberDefinition).Type != MethodScriptSemantics.ImplType.NotUsableFromScript) { if (nameSpecified) { Message(Messages._7132, method); } if (AttributeReader.HasAttribute<IncludeGenericArgumentsAttribute>(method)) { Message(Messages._7133, method); } var semantics = GetMethodSemantics((IMethod)InheritanceHelper.GetBaseMember(method).MemberDefinition); if (semantics.Type == MethodScriptSemantics.ImplType.InlineCode && semantics.GeneratedMethodName != null) semantics = MethodScriptSemantics.NormalMethod(semantics.GeneratedMethodName, ignoreGenericArguments: semantics.IgnoreGenericArguments, expandParams: semantics.ExpandParams); // Methods derived from methods with [InlineCode(..., GeneratedMethodName = "Something")] are treated as normal methods. if (eaa != null) semantics = semantics.WithEnumerateAsArray(); if (semantics.Type == MethodScriptSemantics.ImplType.NormalMethod) { var errorMethod = method.ImplementedInterfaceMembers.FirstOrDefault(im => GetMethodSemantics((IMethod)im.MemberDefinition).Name != semantics.Name); if (errorMethod != null) { Message(Messages._7134, method, errorMethod.FullName); } } _methodSemantics[method] = semantics; return; } else if (interfaceImplementations.Count > 0) { if (nameSpecified) { Message(Messages._7135, method); } var candidateNames = method.ImplementedInterfaceMembers .Select(im => GetMethodSemantics((IMethod)im.MemberDefinition)) .Select(s => s.Type == MethodScriptSemantics.ImplType.NormalMethod ? s.Name : (s.Type == MethodScriptSemantics.ImplType.InlineCode ? s.GeneratedMethodName : null)) .Where(name => name != null) .Distinct(); if (candidateNames.Count() > 1) { Message(Messages._7136, method); } // If the method implements more than one interface member, prefer to take the implementation from one that is not unusable. var sem = method.ImplementedInterfaceMembers.Select(im => GetMethodSemantics((IMethod)im.MemberDefinition)).FirstOrDefault(x => x.Type != MethodScriptSemantics.ImplType.NotUsableFromScript) ?? MethodScriptSemantics.NotUsableFromScript(); if (sem.Type == MethodScriptSemantics.ImplType.InlineCode && sem.GeneratedMethodName != null) sem = MethodScriptSemantics.NormalMethod(sem.GeneratedMethodName, ignoreGenericArguments: sem.IgnoreGenericArguments, expandParams: sem.ExpandParams); // Methods implementing methods with [InlineCode(..., GeneratedMethodName = "Something")] are treated as normal methods. if (eaa != null) sem = sem.WithEnumerateAsArray(); _methodSemantics[method] = sem; return; } else { if (includeGenericArguments == null) { _errorReporter.Region = method.Region; Message(Messages._7027, method); includeGenericArguments = true; } if (epa != null) { if (!method.Parameters.Any(p => p.IsParams)) { Message(Messages._7137, method); } } if (preferredName == "") { // Special case - Script# supports setting the name of a method to an empty string, which means that it simply removes the name (eg. "x.M(a)" becomes "x(a)"). We model this with literal code. if (method.DeclaringTypeDefinition.Kind == TypeKind.Interface) { Message(Messages._7138, method); _methodSemantics[method] = MethodScriptSemantics.NormalMethod(method.Name); return; } else if (method.IsOverridable) { Message(Messages._7139, method); _methodSemantics[method] = MethodScriptSemantics.NormalMethod(method.Name); return; } else if (method.IsStatic) { Message(Messages._7140, method); _methodSemantics[method] = MethodScriptSemantics.NormalMethod(method.Name); return; } else { _methodSemantics[method] = MethodScriptSemantics.InlineCode("{this}(" + string.Join(", ", method.Parameters.Select(p => "{" + p.Name + "}")) + ")", enumerateAsArray: eaa != null); return; } } else { string name = nameSpecified ? preferredName : GetUniqueName(preferredName, usedNames); if (asa == null) usedNames[name] = true; if (GetTypeSemanticsInternal(method.DeclaringTypeDefinition).IsSerializable && !method.IsStatic) { _methodSemantics[method] = MethodScriptSemantics.StaticMethodWithThisAsFirstArgument(name, generateCode: !AttributeReader.HasAttribute<AlternateSignatureAttribute>(method), ignoreGenericArguments: !includeGenericArguments.Value, expandParams: epa != null, enumerateAsArray: eaa != null); } else { _methodSemantics[method] = MethodScriptSemantics.NormalMethod(name, generateCode: !AttributeReader.HasAttribute<AlternateSignatureAttribute>(method), ignoreGenericArguments: !includeGenericArguments.Value, expandParams: epa != null, enumerateAsArray: eaa != null); } } } } } } private void ProcessEvent(IEvent evt, string preferredName, bool nameSpecified, Dictionary<string, bool> usedNames) { if (GetTypeSemanticsInternal(evt.DeclaringTypeDefinition).Semantics.Type == TypeScriptSemantics.ImplType.NotUsableFromScript || AttributeReader.HasAttribute<NonScriptableAttribute>(evt)) { _eventSemantics[evt] = EventScriptSemantics.NotUsableFromScript(); return; } else if (preferredName == "") { Message(Messages._7141, evt); _eventSemantics[evt] = EventScriptSemantics.AddAndRemoveMethods(MethodScriptSemantics.NormalMethod("add"), MethodScriptSemantics.NormalMethod("remove")); return; } MethodScriptSemantics adder, remover; if (evt.CanAdd) { var getterName = DeterminePreferredMemberName(evt.AddAccessor); if (!getterName.Item2) getterName = Tuple.Create(!nameSpecified && _minimizeNames && evt.DeclaringType.Kind != TypeKind.Interface && MetadataUtils.CanBeMinimized(evt) ? null : (nameSpecified ? "add_" + preferredName : GetUniqueName("add_" + preferredName, usedNames)), false); // If the name was not specified, generate one. ProcessMethod(evt.AddAccessor, getterName.Item1, getterName.Item2, usedNames); adder = GetMethodSemantics(evt.AddAccessor); } else { adder = null; } if (evt.CanRemove) { var setterName = DeterminePreferredMemberName(evt.RemoveAccessor); if (!setterName.Item2) setterName = Tuple.Create(!nameSpecified && _minimizeNames && evt.DeclaringType.Kind != TypeKind.Interface && MetadataUtils.CanBeMinimized(evt) ? null : (nameSpecified ? "remove_" + preferredName : GetUniqueName("remove_" + preferredName, usedNames)), false); // If the name was not specified, generate one. ProcessMethod(evt.RemoveAccessor, setterName.Item1, setterName.Item2, usedNames); remover = GetMethodSemantics(evt.RemoveAccessor); } else { remover = null; } _eventSemantics[evt] = EventScriptSemantics.AddAndRemoveMethods(adder, remover); } private void ProcessField(IField field, string preferredName, bool nameSpecified, Dictionary<string, bool> usedNames) { if (GetTypeSemanticsInternal(field.DeclaringTypeDefinition).Semantics.Type == TypeScriptSemantics.ImplType.NotUsableFromScript || AttributeReader.HasAttribute<NonScriptableAttribute>(field)) { _fieldSemantics[field] = FieldScriptSemantics.NotUsableFromScript(); } else if (preferredName == "") { Message(Messages._7142, field); _fieldSemantics[field] = FieldScriptSemantics.Field("X"); } else { string name = (nameSpecified ? preferredName : GetUniqueName(preferredName, usedNames)); if (AttributeReader.HasAttribute<InlineConstantAttribute>(field)) { if (field.IsConst) { name = null; } else { Message(Messages._7152, field); } } else { usedNames[name] = true; } if (GetTypeSemanticsInternal(field.DeclaringTypeDefinition).IsNamedValues) { string value = preferredName; if (!nameSpecified) { // This code handles the feature that it is possible to specify an invalid ScriptName for a member of a NamedValues enum, in which case that value has to be use as the constant value. var sna = AttributeReader.ReadAttribute<ScriptNameAttribute>(field); if (sna != null) value = sna.Name; } _fieldSemantics[field] = FieldScriptSemantics.StringConstant(value, name); } else if (name == null || (field.IsConst && (field.DeclaringType.Kind == TypeKind.Enum || _minimizeNames))) { object value = Saltarelle.Compiler.JSModel.Utils.ConvertToDoubleOrStringOrBoolean(field.ConstantValue); if (value is bool) _fieldSemantics[field] = FieldScriptSemantics.BooleanConstant((bool)value, name); else if (value is double) _fieldSemantics[field] = FieldScriptSemantics.NumericConstant((double)value, name); else if (value is string) _fieldSemantics[field] = FieldScriptSemantics.StringConstant((string)value, name); else _fieldSemantics[field] = FieldScriptSemantics.NullConstant(name); } else { _fieldSemantics[field] = FieldScriptSemantics.Field(name); } } } public void Prepare(ITypeDefinition type) { try { ProcessType(type); ProcessTypeMembers(type); } catch (Exception ex) { _errorReporter.Region = type.Region; _errorReporter.InternalError(ex, "Error importing type " + type.FullName); } } public void ReserveMemberName(ITypeDefinition type, string name, bool isStatic) { HashSet<string> names; if (!isStatic) { if (!_instanceMemberNamesByType.TryGetValue(type, out names)) _instanceMemberNamesByType[type] = names = new HashSet<string>(); } else { if (!_staticMemberNamesByType.TryGetValue(type, out names)) _staticMemberNamesByType[type] = names = new HashSet<string>(); } names.Add(name); } public bool IsMemberNameAvailable(ITypeDefinition type, string name, bool isStatic) { if (isStatic) { if (_unusableStaticFieldNames.Contains(name)) return false; HashSet<string> names; if (!_staticMemberNamesByType.TryGetValue(type, out names)) return true; return !names.Contains(name); } else { if (_unusableInstanceFieldNames.Contains(name)) return false; if (type.DirectBaseTypes.Select(d => d.GetDefinition()).Any(t => !IsMemberNameAvailable(t, name, false))) return false; HashSet<string> names; if (!_instanceMemberNamesByType.TryGetValue(type, out names)) return true; return !names.Contains(name); } } public virtual void SetMethodSemantics(IMethod method, MethodScriptSemantics semantics) { _methodSemantics[method] = semantics; _ignoredMembers.Add(method); } public virtual void SetConstructorSemantics(IMethod method, ConstructorScriptSemantics semantics) { _constructorSemantics[method] = semantics; _ignoredMembers.Add(method); } public virtual void SetPropertySemantics(IProperty property, PropertyScriptSemantics semantics) { _propertySemantics[property] = semantics; _ignoredMembers.Add(property); } public virtual void SetFieldSemantics(IField field, FieldScriptSemantics semantics) { _fieldSemantics[field] = semantics; _ignoredMembers.Add(field); } public virtual void SetEventSemantics(IEvent evt,EventScriptSemantics semantics) { _eventSemantics[evt] = semantics; _ignoredMembers.Add(evt); } private TypeSemantics GetTypeSemanticsInternal(ITypeDefinition typeDefinition) { TypeSemantics ts; if (_typeSemantics.TryGetValue(typeDefinition, out ts)) return ts; throw new ArgumentException(string.Format("Type semantics for type {0} were not correctly imported", typeDefinition.FullName)); } public TypeScriptSemantics GetTypeSemantics(ITypeDefinition typeDefinition) { if (typeDefinition.Kind == TypeKind.Delegate) return TypeScriptSemantics.NormalType("Function"); else if (typeDefinition.Kind == TypeKind.Array) return TypeScriptSemantics.NormalType("Array"); return GetTypeSemanticsInternal(typeDefinition).Semantics; } public string GetTypeParameterName(ITypeParameter typeParameter) { return _typeParameterNames[typeParameter]; } public MethodScriptSemantics GetMethodSemantics(IMethod method) { switch (method.DeclaringType.Kind) { case TypeKind.Delegate: return MethodScriptSemantics.NotUsableFromScript(); default: MethodScriptSemantics result; if (!_methodSemantics.TryGetValue((IMethod)method.MemberDefinition, out result)) throw new ArgumentException(string.Format("Semantics for method " + method + " were not imported")); return result; } } public ConstructorScriptSemantics GetConstructorSemantics(IMethod method) { switch (method.DeclaringType.Kind) { case TypeKind.Anonymous: return ConstructorScriptSemantics.Json(new IMember[0]); case TypeKind.Delegate: return ConstructorScriptSemantics.NotUsableFromScript(); default: ConstructorScriptSemantics result; if (!_constructorSemantics.TryGetValue((IMethod)method.MemberDefinition, out result)) throw new ArgumentException(string.Format("Semantics for constructor " + method + " were not imported")); return result; } } public PropertyScriptSemantics GetPropertySemantics(IProperty property) { switch (property.DeclaringType.Kind) { case TypeKind.Anonymous: return PropertyScriptSemantics.Field(property.Name.Replace("<>", "$")); case TypeKind.Delegate: return PropertyScriptSemantics.NotUsableFromScript(); default: PropertyScriptSemantics result; if (!_propertySemantics.TryGetValue((IProperty)property.MemberDefinition, out result)) throw new ArgumentException(string.Format("Semantics for property " + property + " were not imported")); return result; } } public DelegateScriptSemantics GetDelegateSemantics(ITypeDefinition delegateType) { DelegateScriptSemantics result; if (!_delegateSemantics.TryGetValue(delegateType, out result)) throw new ArgumentException(string.Format("Semantics for delegate " + delegateType + " were not imported")); return result; } private string GetBackingFieldName(ITypeDefinition declaringTypeDefinition, string memberName) { int inheritanceDepth = declaringTypeDefinition.GetAllBaseTypes().Count(b => b.Kind != TypeKind.Interface) - 1; if (_minimizeNames) { int count; _backingFieldCountPerType.TryGetValue(declaringTypeDefinition, out count); count++; _backingFieldCountPerType[declaringTypeDefinition] = count; return string.Format(CultureInfo.InvariantCulture, "${0}${1}", inheritanceDepth, count); } else { return string.Format(CultureInfo.InvariantCulture, "${0}${1}Field", inheritanceDepth, memberName); } } public string GetAutoPropertyBackingFieldName(IProperty property) { property = (IProperty)property.MemberDefinition; string result; if (_propertyBackingFieldNames.TryGetValue(property, out result)) return result; result = GetBackingFieldName(property.DeclaringTypeDefinition, property.Name); _propertyBackingFieldNames[property] = result; return result; } public FieldScriptSemantics GetFieldSemantics(IField field) { switch (field.DeclaringType.Kind) { case TypeKind.Delegate: return FieldScriptSemantics.NotUsableFromScript(); default: FieldScriptSemantics result; if (!_fieldSemantics.TryGetValue((IField)field.MemberDefinition, out result)) throw new ArgumentException(string.Format("Semantics for field " + field + " were not imported")); return result; } } public EventScriptSemantics GetEventSemantics(IEvent evt) { switch (evt.DeclaringType.Kind) { case TypeKind.Delegate: return EventScriptSemantics.NotUsableFromScript(); default: EventScriptSemantics result; if (!_eventSemantics.TryGetValue((IEvent)evt.MemberDefinition, out result)) throw new ArgumentException(string.Format("Semantics for field " + evt + " were not imported")); return result; } } public string GetAutoEventBackingFieldName(IEvent evt) { evt = (IEvent)evt.MemberDefinition; string result; if (_eventBackingFieldNames.TryGetValue(evt, out result)) return result; result = GetBackingFieldName(evt.DeclaringTypeDefinition, evt.Name); _eventBackingFieldNames[evt] = result; return result; } } }
/* Copyright (C) 2013-2015 MetaMorph Software, Inc Permission is hereby granted, free of charge, to any person obtaining a copy of this data, including any software or models in source or binary form, as well as any drawings, specifications, and documentation (collectively "the Data"), to deal in the Data without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Data, and to permit persons to whom the Data 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 Data. THE DATA 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, SPONSORS, DEVELOPERS, CONTRIBUTORS, 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 DATA OR THE USE OR OTHER DEALINGS IN THE DATA. ======================= This version of the META tools is a fork of an original version produced by Vanderbilt University's Institute for Software Integrated Systems (ISIS). Their license statement: Copyright (C) 2011-2014 Vanderbilt University Developed with the sponsorship of the Defense Advanced Research Projects Agency (DARPA) and delivered to the U.S. Government with Unlimited Rights as defined in DFARS 252.227-7013. Permission is hereby granted, free of charge, to any person obtaining a copy of this data, including any software or models in source or binary form, as well as any drawings, specifications, and documentation (collectively "the Data"), to deal in the Data without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Data, and to permit persons to whom the Data 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 Data. THE DATA 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, SPONSORS, DEVELOPERS, CONTRIBUTORS, 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 DATA OR THE USE OR OTHER DEALINGS IN THE DATA. */ using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Text; using GME.CSharp; using GME; using GME.MGA; using GME.MGA.Core; using System.Windows.Forms; using Cyber = ISIS.GME.Dsml.CyberComposition.Interfaces; using CyberClasses = ISIS.GME.Dsml.CyberComposition.Classes; using CyberModelUtil; using Cyber2AVM; namespace CyberComponentExporter { /// <summary> /// This class implements the necessary COM interfaces for a GME interpreter component. /// </summary> [Guid(ComponentConfig.guid), ProgId(ComponentConfig.progID), ClassInterface(ClassInterfaceType.AutoDual)] [ComVisible(true)] public class CyberComponentExporterInterpreter : IMgaComponentEx, IGMEVersionInfo { /// <summary> /// Contains information about the GUI event that initiated the invocation. /// </summary> public enum ComponentStartMode { GME_MAIN_START = 0, // Not used by GME GME_BROWSER_START = 1, // Right click in the GME Tree Browser window GME_CONTEXT_START = 2, // Using the context menu by right clicking a model element in the GME modeling window GME_EMBEDDED_START = 3, // Not used by GME GME_MENU_START = 16, // Clicking on the toolbar icon, or using the main menu GME_BGCONTEXT_START = 18, // Using the context menu by right clicking the background of the GME modeling window GME_ICON_START = 32, // Not used by GME GME_SILENT_MODE = 128 // Not used by GME, available to testers not using GME } /// <summary> /// This function is called for each interpreter invocation before Main. /// Don't perform MGA operations here unless you open a tansaction. /// </summary> /// <param name="project">The handle of the project opened in GME, for which the interpreter was called.</param> public void Initialize(MgaProject project) { // TODO: Add your initialization code here... } /// <summary> /// The main entry point of the interpreter. A transaction is already open, /// GMEConsole is available. A general try-catch block catches all the exceptions /// coming from this function, you don't need to add it. For more information, see InvokeEx. /// </summary> /// <param name="project">The handle of the project opened in GME, for which the interpreter was called.</param> /// <param name="currentobj">The model open in the active tab in GME. Its value is null if no model is open (no GME modeling windows open). </param> /// <param name="selectedobjs"> /// A collection for the selected model elements. It is never null. /// If the interpreter is invoked by the context menu of the GME Tree Browser, then the selected items in the tree browser. Folders /// are never passed (they are not FCOs). /// If the interpreter is invoked by clicking on the toolbar icon or the context menu of the modeling window, then the selected items /// in the active GME modeling window. If nothing is selected, the collection is empty (contains zero elements). /// </param> /// <param name="startMode">Contains information about the GUI event that initiated the invocation.</param> [ComVisible(false)] public void Main(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, ComponentStartMode startMode) { // TODO: Add your interpreter code GMEConsole.Out.WriteLine("Running Cyber Component Exporter..."); //// Get RootFolder //IMgaFolder rootFolder = project.RootFolder; //GMEConsole.Out.WriteLine(rootFolder.Name); // To use the domain-specific API: // Create another project with the same name as the paradigm name // Copy the paradigm .mga file to the directory containing the new project // In the new project, install the GME DSMLGenerator NuGet package (search for DSMLGenerator) // Add a Reference in this project to the other project // Add "using [ParadigmName] = ISIS.GME.Dsml.[ParadigmName].Classes.Interfaces;" to the top of this file // if (currentobj.Meta.Name == "KindName") // [ParadigmName].[KindName] dsCurrentObj = ISIS.GME.Dsml.[ParadigmName].Classes.[KindName].Cast(currentobj); // Adapted from CyPhyComponentExporter.cs //#region Prompt for Output Path //string startupPath = Path.GetDirectoryName(project.ProjectConnStr.Substring("MGA=".Length)); // Make sure Cyber output paths exist. String s_outPath = "."; if (!Directory.Exists(s_outPath + "\\Cyber")) { Directory.CreateDirectory(s_outPath + "\\Cyber"); } //#endregion GMEConsole.Info.WriteLine("Beginning Export..."); string filename = project.ProjectConnStr; if (filename.Length > 4) { filename = filename.Substring(4); } else { GMEConsole.Info.WriteLine("Invalid MGA connection string for project. Can not determine file name. Bailing out..."); throw new System.Exception("Invalid MGA connection string."); } HashSet<Cyber.ModelicaComponent> cyberComponentSet = null; if (currentobj != null) { cyberComponentSet = ComponentLister.getCyberComponentSet(currentobj); } else if (selectedobjs.Count > 0) { cyberComponentSet = new HashSet<Cyber.ModelicaComponent>(); foreach (MgaFCO mf in selectedobjs) { cyberComponentSet.UnionWith(ComponentLister.getCyberComponentSet(mf)); } } else { cyberComponentSet = ComponentLister.getCyberComponentSet(project.RootFolder); } // Debug foreach (Cyber.ModelicaComponent cyberComponent in cyberComponentSet) { GMEConsole.Info.WriteLine(""); GMEConsole.Info.Write("Processing Component ... " + cyberComponent.Path); AVMComponentBuilder avmComponentBuilder = new AVMComponentBuilder(); avmComponentBuilder.GMEConsole = GMEConsole; avmComponentBuilder.createAVMCyberModel(cyberComponent, filename); String s_outFilePath = String.Format("{0}\\{1}.component.acm", s_outPath, META2AVM_Util.UtilFuncs.Safeify(cyberComponent.Name)); META2AVM_Util.UtilFuncs.SerializeAvmComponent(avmComponentBuilder.getAVMComponent(), s_outFilePath); GMEConsole.Info.Write("... Exported " + cyberComponent.Path + " to " + s_outFilePath); } try { string[] path_parts = filename.Split('\\'); string filename_part = path_parts[path_parts.Length - 1]; path_parts[path_parts.Length - 1] = "Cyber"; string path_part = System.IO.Path.Combine(path_parts); //GMEConsole.Info.Write("Copying " + filename + " to " + System.IO.Path.Combine(path_part, filename_part) ); GMEConsole.Info.Write("Copying " + filename_part + " to " + System.IO.Path.Combine("Cyber", filename_part)); // copy the project file to the Cyber subdirectory System.IO.File.Copy(filename_part, System.IO.Path.Combine("Cyber", filename_part), true); } catch (Exception err_copy_model_file) { GMEConsole.Error.Write("Error copying model file to Cyber subdirectory: " + err_copy_model_file.Message); return; } // Try to create the corresponding XML file InvokeUDMCopy invokeUdmCopy = new InvokeUDMCopy(); if (invokeUdmCopy.GenerateXML(project, filename) == true) { GMEConsole.Out.WriteLine("Finished XML generation."); } else { GMEConsole.Out.WriteLine("XML not generated."); } GMEConsole.Info.WriteLine("Cyber Component Exporter finished!"); } #region IMgaComponentEx Members MgaGateway MgaGateway { get; set; } GMEConsole GMEConsole { get; set; } public void InvokeEx(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, int param) { if (!enabled) { return; } try { GMEConsole = GMEConsole.CreateFromProject(project); MgaGateway = new MgaGateway(project); project.CreateTerritoryWithoutSink(out MgaGateway.territory); MgaGateway.PerformInTransaction(delegate { Main(project, currentobj, selectedobjs, Convert(param)); }); } finally { if (MgaGateway.territory != null) { MgaGateway.territory.Destroy(); } MgaGateway = null; project = null; currentobj = null; selectedobjs = null; GMEConsole = null; GC.Collect(); GC.WaitForPendingFinalizers(); } } private ComponentStartMode Convert(int param) { switch (param) { case (int)ComponentStartMode.GME_BGCONTEXT_START: return ComponentStartMode.GME_BGCONTEXT_START; case (int)ComponentStartMode.GME_BROWSER_START: return ComponentStartMode.GME_BROWSER_START; case (int)ComponentStartMode.GME_CONTEXT_START: return ComponentStartMode.GME_CONTEXT_START; case (int)ComponentStartMode.GME_EMBEDDED_START: return ComponentStartMode.GME_EMBEDDED_START; case (int)ComponentStartMode.GME_ICON_START: return ComponentStartMode.GME_ICON_START; case (int)ComponentStartMode.GME_MAIN_START: return ComponentStartMode.GME_MAIN_START; case (int)ComponentStartMode.GME_MENU_START: return ComponentStartMode.GME_MENU_START; case (int)ComponentStartMode.GME_SILENT_MODE: return ComponentStartMode.GME_SILENT_MODE; } return ComponentStartMode.GME_SILENT_MODE; } #region Component Information public string ComponentName { get { return GetType().Name; } } public string ComponentProgID { get { return ComponentConfig.progID; } } public componenttype_enum ComponentType { get { return ComponentConfig.componentType; } } public string Paradigm { get { return ComponentConfig.paradigmName; } } #endregion #region Enabling bool enabled = true; public void Enable(bool newval) { enabled = newval; } #endregion #region Interactive Mode protected bool interactiveMode = true; public bool InteractiveMode { get { return interactiveMode; } set { interactiveMode = value; } } #endregion #region Custom Parameters SortedDictionary<string, object> componentParameters = null; public object get_ComponentParameter(string Name) { if (Name == "type") return "csharp"; if (Name == "path") return GetType().Assembly.Location; if (Name == "fullname") return GetType().FullName; object value; if (componentParameters != null && componentParameters.TryGetValue(Name, out value)) { return value; } return null; } public void set_ComponentParameter(string Name, object pVal) { if (componentParameters == null) { componentParameters = new SortedDictionary<string, object>(); } componentParameters[Name] = pVal; } #endregion #region Unused Methods // Old interface, it is never called for MgaComponentEx interfaces public void Invoke(MgaProject Project, MgaFCOs selectedobjs, int param) { throw new NotImplementedException(); } // Not used by GME public void ObjectsInvokeEx(MgaProject Project, MgaObject currentobj, MgaObjects selectedobjs, int param) { throw new NotImplementedException(); } #endregion #endregion #region IMgaVersionInfo Members public GMEInterfaceVersion_enum version { get { return GMEInterfaceVersion_enum.GMEInterfaceVersion_Current; } } #endregion #region Registration Helpers [ComRegisterFunctionAttribute] public static void GMERegister(Type t) { Registrar.RegisterComponentsInGMERegistry(); } [ComUnregisterFunctionAttribute] public static void GMEUnRegister(Type t) { Registrar.UnregisterComponentsInGMERegistry(); } #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 Microsoft.Win32.SafeHandles; using System.ComponentModel; using System.Diagnostics; using System.Net.Security; using System.Runtime.InteropServices; using System.Security.Authentication; using System.Security.Authentication.ExtendedProtection; using System.Security.Cryptography.X509Certificates; using System.Security.Principal; namespace System.Net.Security { internal static class SslStreamPal { private const string SecurityPackage = "Microsoft Unified Security Protocol Provider"; private const Interop.SspiCli.ContextFlags RequiredFlags = Interop.SspiCli.ContextFlags.ReplayDetect | Interop.SspiCli.ContextFlags.SequenceDetect | Interop.SspiCli.ContextFlags.Confidentiality | Interop.SspiCli.ContextFlags.AllocateMemory; private const Interop.SspiCli.ContextFlags ServerRequiredFlags = RequiredFlags | Interop.SspiCli.ContextFlags.AcceptStream; public static Exception GetException(SecurityStatusPal status) { int win32Code = (int)SecurityStatusAdapterPal.GetInteropFromSecurityStatusPal(status); return new Win32Exception(win32Code); } internal const bool StartMutualAuthAsAnonymous = true; internal const bool CanEncryptEmptyMessage = true; public static void VerifyPackageInfo() { SSPIWrapper.GetVerifyPackageInfo(GlobalSSPI.SSPISecureChannel, SecurityPackage, true); } public static SecurityStatusPal AcceptSecurityContext(ref SafeFreeCredentials credentialsHandle, ref SafeDeleteContext context, SecurityBuffer inputBuffer, SecurityBuffer outputBuffer, bool remoteCertRequired) { Interop.SspiCli.ContextFlags unusedAttributes = default(Interop.SspiCli.ContextFlags); int errorCode = SSPIWrapper.AcceptSecurityContext( GlobalSSPI.SSPISecureChannel, ref credentialsHandle, ref context, ServerRequiredFlags | (remoteCertRequired ? Interop.SspiCli.ContextFlags.MutualAuth : Interop.SspiCli.ContextFlags.Zero), Interop.SspiCli.Endianness.SECURITY_NATIVE_DREP, inputBuffer, outputBuffer, ref unusedAttributes); return SecurityStatusAdapterPal.GetSecurityStatusPalFromNativeInt(errorCode); } public static SecurityStatusPal InitializeSecurityContext(ref SafeFreeCredentials credentialsHandle, ref SafeDeleteContext context, string targetName, SecurityBuffer inputBuffer, SecurityBuffer outputBuffer) { Interop.SspiCli.ContextFlags unusedAttributes = default(Interop.SspiCli.ContextFlags); int errorCode = SSPIWrapper.InitializeSecurityContext( GlobalSSPI.SSPISecureChannel, ref credentialsHandle, ref context, targetName, RequiredFlags | Interop.SspiCli.ContextFlags.InitManualCredValidation, Interop.SspiCli.Endianness.SECURITY_NATIVE_DREP, inputBuffer, outputBuffer, ref unusedAttributes); return SecurityStatusAdapterPal.GetSecurityStatusPalFromNativeInt(errorCode); } public static SecurityStatusPal InitializeSecurityContext(SafeFreeCredentials credentialsHandle, ref SafeDeleteContext context, string targetName, SecurityBuffer[] inputBuffers, SecurityBuffer outputBuffer) { Interop.SspiCli.ContextFlags unusedAttributes = default(Interop.SspiCli.ContextFlags); int errorCode = SSPIWrapper.InitializeSecurityContext( GlobalSSPI.SSPISecureChannel, credentialsHandle, ref context, targetName, RequiredFlags | Interop.SspiCli.ContextFlags.InitManualCredValidation, Interop.SspiCli.Endianness.SECURITY_NATIVE_DREP, inputBuffers, outputBuffer, ref unusedAttributes); return SecurityStatusAdapterPal.GetSecurityStatusPalFromNativeInt(errorCode); } public static SafeFreeCredentials AcquireCredentialsHandle(X509Certificate certificate, SslProtocols protocols, EncryptionPolicy policy, bool isServer) { int protocolFlags = GetProtocolFlagsFromSslProtocols(protocols, isServer); Interop.SspiCli.SCHANNEL_CRED.Flags flags; Interop.SspiCli.CredentialUse direction; if (!isServer) { direction = Interop.SspiCli.CredentialUse.SECPKG_CRED_OUTBOUND; flags = Interop.SspiCli.SCHANNEL_CRED.Flags.SCH_CRED_MANUAL_CRED_VALIDATION | Interop.SspiCli.SCHANNEL_CRED.Flags.SCH_CRED_NO_DEFAULT_CREDS | Interop.SspiCli.SCHANNEL_CRED.Flags.SCH_SEND_AUX_RECORD; // CoreFX: always opt-in SCH_USE_STRONG_CRYPTO except for SSL3. if (((protocolFlags & (Interop.SChannel.SP_PROT_TLS1_0 | Interop.SChannel.SP_PROT_TLS1_1 | Interop.SChannel.SP_PROT_TLS1_2)) != 0) && (policy != EncryptionPolicy.AllowNoEncryption) && (policy != EncryptionPolicy.NoEncryption)) { flags |= Interop.SspiCli.SCHANNEL_CRED.Flags.SCH_USE_STRONG_CRYPTO; } } else { direction = Interop.SspiCli.CredentialUse.SECPKG_CRED_INBOUND; flags = Interop.SspiCli.SCHANNEL_CRED.Flags.SCH_SEND_AUX_RECORD; } Interop.SspiCli.SCHANNEL_CRED secureCredential = CreateSecureCredential( Interop.SspiCli.SCHANNEL_CRED.CurrentVersion, certificate, flags, protocolFlags, policy); return AcquireCredentialsHandle(direction, secureCredential); } public static unsafe SecurityStatusPal EncryptMessage(SafeDeleteContext securityContext, byte[] input, int offset, int size, int headerSize, int trailerSize, ref byte[] output, out int resultSize) { // Ensure that there is sufficient space for the message output. int bufferSizeNeeded; try { bufferSizeNeeded = checked(size + headerSize + trailerSize); } catch { NetEventSource.Fail(securityContext, "Arguments out of range"); throw; } if (output == null || output.Length < bufferSizeNeeded) { output = new byte[bufferSizeNeeded]; } // Copy the input into the output buffer to prepare for SCHANNEL's expectations Buffer.BlockCopy(input, offset, output, headerSize, size); const int NumSecBuffers = 4; // header + data + trailer + empty var unmanagedBuffer = stackalloc Interop.SspiCli.SecBuffer[NumSecBuffers]; var sdcInOut = new Interop.SspiCli.SecBufferDesc(NumSecBuffers); sdcInOut.pBuffers = unmanagedBuffer; fixed (byte* outputPtr = output) { Interop.SspiCli.SecBuffer* headerSecBuffer = &unmanagedBuffer[0]; headerSecBuffer->BufferType = SecurityBufferType.SECBUFFER_STREAM_HEADER; headerSecBuffer->pvBuffer = (IntPtr)outputPtr; headerSecBuffer->cbBuffer = headerSize; Interop.SspiCli.SecBuffer* dataSecBuffer = &unmanagedBuffer[1]; dataSecBuffer->BufferType = SecurityBufferType.SECBUFFER_DATA; dataSecBuffer->pvBuffer = (IntPtr)(outputPtr + headerSize); dataSecBuffer->cbBuffer = size; Interop.SspiCli.SecBuffer* trailerSecBuffer = &unmanagedBuffer[2]; trailerSecBuffer->BufferType = SecurityBufferType.SECBUFFER_STREAM_TRAILER; trailerSecBuffer->pvBuffer = (IntPtr)(outputPtr + headerSize + size); trailerSecBuffer->cbBuffer = trailerSize; Interop.SspiCli.SecBuffer* emptySecBuffer = &unmanagedBuffer[3]; emptySecBuffer->BufferType = SecurityBufferType.SECBUFFER_EMPTY; emptySecBuffer->cbBuffer = 0; emptySecBuffer->pvBuffer = IntPtr.Zero; int errorCode = GlobalSSPI.SSPISecureChannel.EncryptMessage(securityContext, ref sdcInOut, 0); if (errorCode != 0) { if (NetEventSource.IsEnabled) NetEventSource.Info(securityContext, $"Encrypt ERROR {errorCode:X}"); resultSize = 0; return SecurityStatusAdapterPal.GetSecurityStatusPalFromNativeInt(errorCode); } Debug.Assert(headerSecBuffer->cbBuffer >= 0 && dataSecBuffer->cbBuffer >= 0 && trailerSecBuffer->cbBuffer >= 0); Debug.Assert(checked(headerSecBuffer->cbBuffer + dataSecBuffer->cbBuffer + trailerSecBuffer->cbBuffer) <= output.Length); resultSize = checked(headerSecBuffer->cbBuffer + dataSecBuffer->cbBuffer + trailerSecBuffer->cbBuffer); return new SecurityStatusPal(SecurityStatusPalErrorCode.OK); } } public static unsafe SecurityStatusPal DecryptMessage(SafeDeleteContext securityContext, byte[] buffer, ref int offset, ref int count) { const int NumSecBuffers = 4; // data + empty + empty + empty var unmanagedBuffer = stackalloc Interop.SspiCli.SecBuffer[NumSecBuffers]; var sdcInOut = new Interop.SspiCli.SecBufferDesc(NumSecBuffers); sdcInOut.pBuffers = unmanagedBuffer; fixed (byte* bufferPtr = buffer) { Interop.SspiCli.SecBuffer* dataBuffer = &unmanagedBuffer[0]; dataBuffer->BufferType = SecurityBufferType.SECBUFFER_DATA; dataBuffer->pvBuffer = (IntPtr)bufferPtr + offset; dataBuffer->cbBuffer = count; for (int i = 1; i < NumSecBuffers; i++) { Interop.SspiCli.SecBuffer* emptyBuffer = &unmanagedBuffer[i]; emptyBuffer->BufferType = SecurityBufferType.SECBUFFER_EMPTY; emptyBuffer->pvBuffer = IntPtr.Zero; emptyBuffer->cbBuffer = 0; } Interop.SECURITY_STATUS errorCode = (Interop.SECURITY_STATUS)GlobalSSPI.SSPISecureChannel.DecryptMessage(securityContext, ref sdcInOut, 0); // Decrypt may repopulate the sec buffers, likely with header + data + trailer + empty. // We need to find the data. count = 0; for (int i = 0; i < NumSecBuffers; i++) { // Successfully decoded data and placed it at the following position in the buffer, if ((errorCode == Interop.SECURITY_STATUS.OK && unmanagedBuffer[i].BufferType == SecurityBufferType.SECBUFFER_DATA) // or we failed to decode the data, here is the encoded data. || (errorCode != Interop.SECURITY_STATUS.OK && unmanagedBuffer[i].BufferType == SecurityBufferType.SECBUFFER_EXTRA)) { offset = (int)((byte*)unmanagedBuffer[i].pvBuffer - bufferPtr); count = unmanagedBuffer[i].cbBuffer; Debug.Assert(offset >= 0 && count >= 0, $"Expected offset and count greater than 0, got {offset} and {count}"); Debug.Assert(checked(offset + count) <= buffer.Length, $"Expected offset+count <= buffer.Length, got {offset}+{count}>={buffer.Length}"); break; } } return SecurityStatusAdapterPal.GetSecurityStatusPalFromInterop(errorCode); } } public static SecurityStatusPal ApplyAlertToken(ref SafeFreeCredentials credentialsHandle, SafeDeleteContext securityContext, TlsAlertType alertType, TlsAlertMessage alertMessage) { Interop.SChannel.SCHANNEL_ALERT_TOKEN alertToken; alertToken.dwTokenType = Interop.SChannel.SCHANNEL_ALERT; alertToken.dwAlertType = (uint)alertType; alertToken.dwAlertNumber = (uint)alertMessage; var bufferDesc = new SecurityBuffer[1]; int alertTokenByteSize = Marshal.SizeOf<Interop.SChannel.SCHANNEL_ALERT_TOKEN>(); IntPtr p = Marshal.AllocHGlobal(alertTokenByteSize); try { var buffer = new byte[alertTokenByteSize]; Marshal.StructureToPtr<Interop.SChannel.SCHANNEL_ALERT_TOKEN>(alertToken, p, false); Marshal.Copy(p, buffer, 0, alertTokenByteSize); bufferDesc[0] = new SecurityBuffer(buffer, SecurityBufferType.SECBUFFER_TOKEN); var errorCode = (Interop.SECURITY_STATUS)SSPIWrapper.ApplyControlToken( GlobalSSPI.SSPISecureChannel, ref securityContext, bufferDesc); return SecurityStatusAdapterPal.GetSecurityStatusPalFromInterop(errorCode, attachException:true); } finally { Marshal.FreeHGlobal(p); } } public static SecurityStatusPal ApplyShutdownToken(ref SafeFreeCredentials credentialsHandle, SafeDeleteContext securityContext) { int shutdownToken = Interop.SChannel.SCHANNEL_SHUTDOWN; var bufferDesc = new SecurityBuffer[1]; var buffer = BitConverter.GetBytes(shutdownToken); bufferDesc[0] = new SecurityBuffer(buffer, SecurityBufferType.SECBUFFER_TOKEN); var errorCode = (Interop.SECURITY_STATUS)SSPIWrapper.ApplyControlToken( GlobalSSPI.SSPISecureChannel, ref securityContext, bufferDesc); return SecurityStatusAdapterPal.GetSecurityStatusPalFromInterop(errorCode, attachException:true); } public static unsafe SafeFreeContextBufferChannelBinding QueryContextChannelBinding(SafeDeleteContext securityContext, ChannelBindingKind attribute) { return SSPIWrapper.QueryContextChannelBinding(GlobalSSPI.SSPISecureChannel, securityContext, (Interop.SspiCli.ContextAttribute)attribute); } public static void QueryContextStreamSizes(SafeDeleteContext securityContext, out StreamSizes streamSizes) { var interopStreamSizes = SSPIWrapper.QueryContextAttributes( GlobalSSPI.SSPISecureChannel, securityContext, Interop.SspiCli.ContextAttribute.SECPKG_ATTR_STREAM_SIZES) as SecPkgContext_StreamSizes; streamSizes = new StreamSizes(interopStreamSizes); } public static void QueryContextConnectionInfo(SafeDeleteContext securityContext, out SslConnectionInfo connectionInfo) { var interopConnectionInfo = SSPIWrapper.QueryContextAttributes( GlobalSSPI.SSPISecureChannel, securityContext, Interop.SspiCli.ContextAttribute.SECPKG_ATTR_CONNECTION_INFO) as SecPkgContext_ConnectionInfo; connectionInfo = new SslConnectionInfo(interopConnectionInfo); } private static int GetProtocolFlagsFromSslProtocols(SslProtocols protocols, bool isServer) { int protocolFlags = (int)protocols; if (isServer) { protocolFlags &= Interop.SChannel.ServerProtocolMask; } else { protocolFlags &= Interop.SChannel.ClientProtocolMask; } return protocolFlags; } private static Interop.SspiCli.SCHANNEL_CRED CreateSecureCredential( int version, X509Certificate certificate, Interop.SspiCli.SCHANNEL_CRED.Flags flags, int protocols, EncryptionPolicy policy) { var credential = new Interop.SspiCli.SCHANNEL_CRED() { hRootStore = IntPtr.Zero, aphMappers = IntPtr.Zero, palgSupportedAlgs = IntPtr.Zero, paCred = IntPtr.Zero, cCreds = 0, cMappers = 0, cSupportedAlgs = 0, dwSessionLifespan = 0, reserved = 0 }; if (policy == EncryptionPolicy.RequireEncryption) { // Prohibit null encryption cipher. credential.dwMinimumCipherStrength = 0; credential.dwMaximumCipherStrength = 0; } else if (policy == EncryptionPolicy.AllowNoEncryption) { // Allow null encryption cipher in addition to other ciphers. credential.dwMinimumCipherStrength = -1; credential.dwMaximumCipherStrength = 0; } else if (policy == EncryptionPolicy.NoEncryption) { // Suppress all encryption and require null encryption cipher only credential.dwMinimumCipherStrength = -1; credential.dwMaximumCipherStrength = -1; } else { throw new ArgumentException(SR.Format(SR.net_invalid_enum, "EncryptionPolicy"), nameof(policy)); } credential.dwVersion = version; credential.dwFlags = flags; credential.grbitEnabledProtocols = protocols; if (certificate != null) { credential.paCred = certificate.Handle; credential.cCreds = 1; } return credential; } // // Security: we temporarily reset thread token to open the handle under process account. // private static SafeFreeCredentials AcquireCredentialsHandle(Interop.SspiCli.CredentialUse credUsage, Interop.SspiCli.SCHANNEL_CRED secureCredential) { // First try without impersonation, if it fails, then try the process account. // I.E. We don't know which account the certificate context was created under. try { // // For app-compat we want to ensure the credential are accessed under >>process<< account. // return WindowsIdentity.RunImpersonated<SafeFreeCredentials>(SafeAccessTokenHandle.InvalidHandle, () => { return SSPIWrapper.AcquireCredentialsHandle(GlobalSSPI.SSPISecureChannel, SecurityPackage, credUsage, secureCredential); }); } catch(Exception ex) { Debug.Fail("AcquireCredentialsHandle failed.", ex.ToString()); return SSPIWrapper.AcquireCredentialsHandle(GlobalSSPI.SSPISecureChannel, SecurityPackage, credUsage, secureCredential); } } } }
/* * * (c) Copyright Ascensio System Limited 2010-2021 * * 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.IO; using System.Net; using ASC.Common; using ASC.FederatedLogin; using Box.V2; using Box.V2.Auth; using Box.V2.Config; using Box.V2.Models; using BoxSDK = Box.V2; namespace ASC.Files.Thirdparty.Box { internal class BoxStorage { private OAuth20Token _token; private BoxClient _boxClient; private readonly List<string> _boxFields = new List<string> { "created_at", "modified_at", "name", "parent", "size" }; public bool IsOpened { get; private set; } public long MaxChunkedUploadFileSize = 250L * 1024L * 1024L; public void Open(OAuth20Token token) { if (IsOpened) return; _token = token; var config = new BoxConfig(_token.ClientID, _token.ClientSecret, new Uri(_token.RedirectUri)); var session = new OAuthSession(_token.AccessToken, _token.RefreshToken, (int)_token.ExpiresIn, "bearer"); _boxClient = new BoxClient(config, session); IsOpened = true; } public void Close() { IsOpened = false; } public string GetRootFolderId() { var root = GetFolder("0"); return root.Id; } public BoxFolder GetFolder(string folderId) { try { return _boxClient.FoldersManager.GetInformationAsync(folderId, _boxFields).Result; } catch (Exception ex) { var boxException = ex.InnerException as BoxSDK.Exceptions.BoxException; if (boxException != null && boxException.Error.Status == ((int)HttpStatusCode.NotFound).ToString()) { return null; } throw; } } public BoxFile GetFile(string fileId) { try { return _boxClient.FilesManager.GetInformationAsync(fileId, _boxFields).Result; } catch (Exception ex) { var boxException = ex.InnerException as BoxSDK.Exceptions.BoxException; if (boxException != null && boxException.Error.Status == ((int)HttpStatusCode.NotFound).ToString()) { return null; } throw; } } public List<BoxItem> GetItems(string folderId, int limit = 500) { return _boxClient.FoldersManager.GetFolderItemsAsync(folderId, limit, 0, _boxFields).Result.Entries; } public Stream DownloadStream(BoxFile file, int offset = 0) { if (file == null) throw new ArgumentNullException("file"); if (offset > 0 && file.Size.HasValue) { return _boxClient.FilesManager.DownloadAsync(file.Id, startOffsetInBytes: offset, endOffsetInBytes: (int)file.Size - 1).Result; } var str = _boxClient.FilesManager.DownloadAsync(file.Id).Result; if (offset == 0) { return str; } var tempBuffer = TempStream.Create(); if (str != null) { str.CopyTo(tempBuffer); tempBuffer.Flush(); tempBuffer.Seek(offset, SeekOrigin.Begin); str.Dispose(); } return tempBuffer; } public BoxFolder CreateFolder(string title, string parentId) { var boxFolderRequest = new BoxFolderRequest { Name = title, Parent = new BoxRequestEntity { Id = parentId } }; return _boxClient.FoldersManager.CreateAsync(boxFolderRequest, _boxFields).Result; } public BoxFile CreateFile(Stream fileStream, string title, string parentId) { var boxFileRequest = new BoxFileRequest { Name = title, Parent = new BoxRequestEntity { Id = parentId } }; return _boxClient.FilesManager.UploadAsync(boxFileRequest, fileStream, _boxFields, setStreamPositionToZero: false).Result; } public void DeleteItem(BoxItem boxItem) { if (boxItem is BoxFolder) { _boxClient.FoldersManager.DeleteAsync(boxItem.Id, true).Wait(); } else { _boxClient.FilesManager.DeleteAsync(boxItem.Id).Wait(); } } public BoxFolder MoveFolder(string boxFolderId, string newFolderName, string toFolderId) { var boxFolderRequest = new BoxFolderRequest { Id = boxFolderId, Name = newFolderName, Parent = new BoxRequestEntity { Id = toFolderId } }; return _boxClient.FoldersManager.UpdateInformationAsync(boxFolderRequest, _boxFields).Result; } public BoxFile MoveFile(string boxFileId, string newFileName, string toFolderId) { var boxFileRequest = new BoxFileRequest { Id = boxFileId, Name = newFileName, Parent = new BoxRequestEntity { Id = toFolderId } }; return _boxClient.FilesManager.UpdateInformationAsync(boxFileRequest, null, _boxFields).Result; } public BoxFolder CopyFolder(string boxFolderId, string newFolderName, string toFolderId) { var boxFolderRequest = new BoxFolderRequest { Id = boxFolderId, Name = newFolderName, Parent = new BoxRequestEntity { Id = toFolderId } }; return _boxClient.FoldersManager.CopyAsync(boxFolderRequest, _boxFields).Result; } public BoxFile CopyFile(string boxFileId, string newFileName, string toFolderId) { var boxFileRequest = new BoxFileRequest { Id = boxFileId, Name = newFileName, Parent = new BoxRequestEntity { Id = toFolderId } }; return _boxClient.FilesManager.CopyAsync(boxFileRequest, _boxFields).Result; } public BoxFolder RenameFolder(string boxFolderId, string newName) { var boxFolderRequest = new BoxFolderRequest { Id = boxFolderId, Name = newName }; return _boxClient.FoldersManager.UpdateInformationAsync(boxFolderRequest, _boxFields).Result; } public BoxFile RenameFile(string boxFileId, string newName) { var boxFileRequest = new BoxFileRequest { Id = boxFileId, Name = newName }; return _boxClient.FilesManager.UpdateInformationAsync(boxFileRequest, null, _boxFields).Result; } public BoxFile SaveStream(string fileId, Stream fileStream) { return _boxClient.FilesManager.UploadNewVersionAsync(null, fileId, fileStream, fields: _boxFields, setStreamPositionToZero: false).Result; } public long GetMaxUploadSize() { var boxUser = _boxClient.UsersManager.GetCurrentUserInformationAsync(new List<string>() { "max_upload_size" }).Result; var max = boxUser.MaxUploadSize.HasValue ? boxUser.MaxUploadSize.Value : MaxChunkedUploadFileSize; //todo: without chunked uploader: return Math.Min(max, MaxChunkedUploadFileSize); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using System.Xml; using Orleans.MultiCluster; using Orleans.Runtime.Configuration; using Orleans.Runtime.MembershipService; using Orleans.Runtime.MultiClusterNetwork; namespace Orleans.Runtime.Management { /// <summary> /// Implementation class for the Orleans management grain. /// </summary> [OneInstancePerCluster] internal class ManagementGrain : Grain, IManagementGrain { private readonly GlobalConfiguration globalConfig; private readonly IMultiClusterOracle multiClusterOracle; private readonly IInternalGrainFactory internalGrainFactory; private readonly ISiloStatusOracle siloStatusOracle; private readonly MembershipTableFactory membershipTableFactory; private Logger logger; public ManagementGrain( GlobalConfiguration globalConfig, IMultiClusterOracle multiClusterOracle, IInternalGrainFactory internalGrainFactory, ISiloStatusOracle siloStatusOracle, MembershipTableFactory membershipTableFactory) { this.globalConfig = globalConfig; this.multiClusterOracle = multiClusterOracle; this.internalGrainFactory = internalGrainFactory; this.siloStatusOracle = siloStatusOracle; this.membershipTableFactory = membershipTableFactory; } public override Task OnActivateAsync() { logger = LogManager.GetLogger("ManagementGrain", LoggerType.Runtime); return TaskDone.Done; } public async Task<Dictionary<SiloAddress, SiloStatus>> GetHosts(bool onlyActive = false) { // If the status oracle isn't MembershipOracle, then it is assumed that it does not use IMembershipTable. // In that event, return the approximate silo statuses from the status oracle. if (!(this.siloStatusOracle is MembershipOracle)) return this.siloStatusOracle.GetApproximateSiloStatuses(onlyActive); // Explicitly read the membership table and return the results. var table = await GetMembershipTable(); var members = await table.ReadAll(); var results = onlyActive ? members.Members.Where(item => item.Item1.Status == SiloStatus.Active) : members.Members; return results.ToDictionary(item => item.Item1.SiloAddress, item => item.Item1.Status); } public async Task<MembershipEntry[]> GetDetailedHosts(bool onlyActive = false) { logger.Info("GetDetailedHosts onlyActive={0}", onlyActive); var mTable = await GetMembershipTable(); var table = await mTable.ReadAll(); if (onlyActive) { return table.Members .Where(item => item.Item1.Status == SiloStatus.Active) .Select(x => x.Item1) .ToArray(); } return table.Members .Select(x => x.Item1) .ToArray(); } public Task SetSystemLogLevel(SiloAddress[] siloAddresses, int traceLevel) { var silos = GetSiloAddresses(siloAddresses); logger.Info("SetSystemTraceLevel={1} {0}", Utils.EnumerableToString(silos), traceLevel); List<Task> actionPromises = PerformPerSiloAction(silos, s => GetSiloControlReference(s).SetSystemLogLevel(traceLevel)); return Task.WhenAll(actionPromises); } public Task SetAppLogLevel(SiloAddress[] siloAddresses, int traceLevel) { var silos = GetSiloAddresses(siloAddresses); logger.Info("SetAppTraceLevel={1} {0}", Utils.EnumerableToString(silos), traceLevel); List<Task> actionPromises = PerformPerSiloAction(silos, s => GetSiloControlReference(s).SetAppLogLevel(traceLevel)); return Task.WhenAll(actionPromises); } public Task SetLogLevel(SiloAddress[] siloAddresses, string logName, int traceLevel) { var silos = GetSiloAddresses(siloAddresses); logger.Info("SetLogLevel[{1}]={2} {0}", Utils.EnumerableToString(silos), logName, traceLevel); List<Task> actionPromises = PerformPerSiloAction(silos, s => GetSiloControlReference(s).SetLogLevel(logName, traceLevel)); return Task.WhenAll(actionPromises); } public Task ForceGarbageCollection(SiloAddress[] siloAddresses) { var silos = GetSiloAddresses(siloAddresses); logger.Info("Forcing garbage collection on {0}", Utils.EnumerableToString(silos)); List<Task> actionPromises = PerformPerSiloAction(silos, s => GetSiloControlReference(s).ForceGarbageCollection()); return Task.WhenAll(actionPromises); } public Task ForceActivationCollection(SiloAddress[] siloAddresses, TimeSpan ageLimit) { var silos = GetSiloAddresses(siloAddresses); return Task.WhenAll(GetSiloAddresses(silos).Select(s => GetSiloControlReference(s).ForceActivationCollection(ageLimit))); } public async Task ForceActivationCollection(TimeSpan ageLimit) { Dictionary<SiloAddress, SiloStatus> hosts = await GetHosts(true); SiloAddress[] silos = hosts.Keys.ToArray(); await ForceActivationCollection(silos, ageLimit); } public Task ForceRuntimeStatisticsCollection(SiloAddress[] siloAddresses) { var silos = GetSiloAddresses(siloAddresses); logger.Info("Forcing runtime statistics collection on {0}", Utils.EnumerableToString(silos)); List<Task> actionPromises = PerformPerSiloAction( silos, s => GetSiloControlReference(s).ForceRuntimeStatisticsCollection()); return Task.WhenAll(actionPromises); } public Task<SiloRuntimeStatistics[]> GetRuntimeStatistics(SiloAddress[] siloAddresses) { var silos = GetSiloAddresses(siloAddresses); if (logger.IsVerbose) logger.Verbose("GetRuntimeStatistics on {0}", Utils.EnumerableToString(silos)); var promises = new List<Task<SiloRuntimeStatistics>>(); foreach (SiloAddress siloAddress in silos) promises.Add(GetSiloControlReference(siloAddress).GetRuntimeStatistics()); return Task.WhenAll(promises); } public async Task<SimpleGrainStatistic[]> GetSimpleGrainStatistics(SiloAddress[] hostsIds) { var all = GetSiloAddresses(hostsIds).Select(s => GetSiloControlReference(s).GetSimpleGrainStatistics()).ToList(); await Task.WhenAll(all); return all.SelectMany(s => s.Result).ToArray(); } public async Task<SimpleGrainStatistic[]> GetSimpleGrainStatistics() { Dictionary<SiloAddress, SiloStatus> hosts = await GetHosts(true); SiloAddress[] silos = hosts.Keys.ToArray(); return await GetSimpleGrainStatistics(silos); } public async Task<DetailedGrainStatistic[]> GetDetailedGrainStatistics(string[] types = null, SiloAddress[] hostsIds = null) { if (hostsIds == null) { Dictionary<SiloAddress, SiloStatus> hosts = await GetHosts(true); hostsIds = hosts.Keys.ToArray(); } var all = GetSiloAddresses(hostsIds).Select(s => GetSiloControlReference(s).GetDetailedGrainStatistics(types)).ToList(); await Task.WhenAll(all); return all.SelectMany(s => s.Result).ToArray(); } public async Task<int> GetGrainActivationCount(GrainReference grainReference) { Dictionary<SiloAddress, SiloStatus> hosts = await GetHosts(true); List<SiloAddress> hostsIds = hosts.Keys.ToList(); var tasks = new List<Task<DetailedGrainReport>>(); foreach (var silo in hostsIds) tasks.Add(GetSiloControlReference(silo).GetDetailedGrainReport(grainReference.GrainId)); await Task.WhenAll(tasks); return tasks.Select(s => s.Result).Select(r => r.LocalActivations.Count).Sum(); } public async Task UpdateConfiguration(SiloAddress[] hostIds, Dictionary<string, string> configuration, Dictionary<string, string> tracing) { var global = new[] { "Globals/", "/Globals/", "OrleansConfiguration/Globals/", "/OrleansConfiguration/Globals/" }; if (hostIds != null && configuration.Keys.Any(k => global.Any(k.StartsWith))) throw new ArgumentException("Must update global configuration settings on all silos"); var silos = GetSiloAddresses(hostIds); if (silos.Length == 0) return; var document = XPathValuesToXml(configuration); if (tracing != null) { AddXPathValue(document, new[] { "OrleansConfiguration", "Defaults", "Tracing" }, null); var parent = document["OrleansConfiguration"]["Defaults"]["Tracing"]; foreach (var trace in tracing) { var child = document.CreateElement("TraceLevelOverride"); child.SetAttribute("LogPrefix", trace.Key); child.SetAttribute("TraceLevel", trace.Value); parent.AppendChild(child); } } using(var sw = new StringWriter()) { using(var xw = XmlWriter.Create(sw)) { document.WriteTo(xw); xw.Flush(); var xml = sw.ToString(); // do first one, then all the rest to avoid spamming all the silos in case of a parameter error await GetSiloControlReference(silos[0]).UpdateConfiguration(xml); await Task.WhenAll(silos.Skip(1).Select(s => GetSiloControlReference(s).UpdateConfiguration(xml))); } } } public async Task UpdateStreamProviders(SiloAddress[] hostIds, IDictionary<string, ProviderCategoryConfiguration> streamProviderConfigurations) { SiloAddress[] silos = GetSiloAddresses(hostIds); List<Task> actionPromises = PerformPerSiloAction(silos, s => GetSiloControlReference(s).UpdateStreamProviders(streamProviderConfigurations)); await Task.WhenAll(actionPromises); } public async Task<string[]> GetActiveGrainTypes(SiloAddress[] hostsIds=null) { if (hostsIds == null) { Dictionary<SiloAddress, SiloStatus> hosts = await GetHosts(true); SiloAddress[] silos = hosts.Keys.ToArray(); } var all = GetSiloAddresses(hostsIds).Select(s => GetSiloControlReference(s).GetGrainTypeList()).ToArray(); await Task.WhenAll(all); return all.SelectMany(s => s.Result).Distinct().ToArray(); } public async Task<int> GetTotalActivationCount() { Dictionary<SiloAddress, SiloStatus> hosts = await GetHosts(true); List<SiloAddress> silos = hosts.Keys.ToList(); var tasks = new List<Task<int>>(); foreach (var silo in silos) tasks.Add(GetSiloControlReference(silo).GetActivationCount()); await Task.WhenAll(tasks); int sum = 0; foreach (Task<int> task in tasks) sum += task.Result; return sum; } public Task<object[]> SendControlCommandToProvider(string providerTypeFullName, string providerName, int command, object arg) { return ExecutePerSiloCall(isc => isc.SendControlCommandToProvider(providerTypeFullName, providerName, command, arg), String.Format("SendControlCommandToProvider of type {0} and name {1} command {2}.", providerTypeFullName, providerName, command)); } private async Task<object[]> ExecutePerSiloCall(Func<ISiloControl, Task<object>> action, string actionToLog) { var silos = await GetHosts(true); if(logger.IsVerbose) { logger.Verbose("Executing {0} against {1}", actionToLog, Utils.EnumerableToString(silos.Keys)); } var actionPromises = new List<Task<object>>(); foreach (SiloAddress siloAddress in silos.Keys.ToArray()) actionPromises.Add(action(GetSiloControlReference(siloAddress))); return await Task.WhenAll(actionPromises); } private Task<IMembershipTable> GetMembershipTable() { var membershipOracle = this.siloStatusOracle as MembershipOracle; if (!(this.siloStatusOracle is MembershipOracle)) throw new InvalidOperationException("The current membership oracle does not support detailed silo status reporting."); return this.membershipTableFactory.GetMembershipTable(); } private SiloAddress[] GetSiloAddresses(SiloAddress[] silos) { if (silos != null && silos.Length > 0) return silos; return this.siloStatusOracle .GetApproximateSiloStatuses(true).Select(s => s.Key).ToArray(); } /// <summary> /// Perform an action for each silo. /// </summary> /// <remarks> /// Because SiloControl contains a reference to a system target, each method call using that reference /// will get routed either locally or remotely to the appropriate silo instance auto-magically. /// </remarks> /// <param name="siloAddresses">List of silos to perform the action for</param> /// <param name="perSiloAction">The action functiona to be performed for each silo</param> /// <returns>Array containing one Task for each silo the action was performed for</returns> private List<Task> PerformPerSiloAction(SiloAddress[] siloAddresses, Func<SiloAddress, Task> perSiloAction) { var requestsToSilos = new List<Task>(); foreach (SiloAddress siloAddress in siloAddresses) requestsToSilos.Add( perSiloAction(siloAddress) ); return requestsToSilos; } private static XmlDocument XPathValuesToXml(Dictionary<string,string> values) { var doc = new XmlDocument(); if (values == null) return doc; foreach (var p in values) { var path = p.Key.Split('/').ToList(); if (path[0] == "") path.RemoveAt(0); if (path[0] != "OrleansConfiguration") path.Insert(0, "OrleansConfiguration"); if (!path[path.Count - 1].StartsWith("@")) throw new ArgumentException("XPath " + p.Key + " must end with @attribute"); AddXPathValue(doc, path, p.Value); } return doc; } private static void AddXPathValue(XmlNode xml, IEnumerable<string> path, string value) { if (path == null) return; var first = path.FirstOrDefault(); if (first == null) return; if (first.StartsWith("@")) { first = first.Substring(1); if (path.Count() != 1) throw new ArgumentException("Attribute " + first + " must be last in path"); var e = xml as XmlElement; if (e == null) throw new ArgumentException("Attribute " + first + " must be on XML element"); e.SetAttribute(first, value); return; } foreach (var child in xml.ChildNodes) { var e = child as XmlElement; if (e != null && e.LocalName == first) { AddXPathValue(e, path.Skip(1), value); return; } } var empty = (xml as XmlDocument ?? xml.OwnerDocument).CreateElement(first); xml.AppendChild(empty); AddXPathValue(empty, path.Skip(1), value); } private ISiloControl GetSiloControlReference(SiloAddress silo) { return this.internalGrainFactory.GetSystemTarget<ISiloControl>(Constants.SiloControlId, silo); } #region MultiCluster private IMultiClusterOracle GetMultiClusterOracle() { if (!this.globalConfig.HasMultiClusterNetwork) throw new OrleansException("No multicluster network configured"); return this.multiClusterOracle; } public Task<List<IMultiClusterGatewayInfo>> GetMultiClusterGateways() { return Task.FromResult(GetMultiClusterOracle().GetGateways().Cast<IMultiClusterGatewayInfo>().ToList()); } public Task<MultiClusterConfiguration> GetMultiClusterConfiguration() { return Task.FromResult(GetMultiClusterOracle().GetMultiClusterConfiguration()); } public async Task<MultiClusterConfiguration> InjectMultiClusterConfiguration(IEnumerable<string> clusters, string comment = "", bool checkForLaggingSilosFirst = true) { var multiClusterOracle = GetMultiClusterOracle(); var configuration = new MultiClusterConfiguration(DateTime.UtcNow, clusters.ToList(), comment); if (!MultiClusterConfiguration.OlderThan(multiClusterOracle.GetMultiClusterConfiguration(), configuration)) throw new OrleansException("Could not inject multi-cluster configuration: current configuration is newer than clock"); if (checkForLaggingSilosFirst) { try { var laggingSilos = await multiClusterOracle.FindLaggingSilos(multiClusterOracle.GetMultiClusterConfiguration()); if (laggingSilos.Count > 0) { var msg = string.Format("Found unstable silos {0}", string.Join(",", laggingSilos)); throw new OrleansException(msg); } } catch (Exception e) { throw new OrleansException("Could not inject multi-cluster configuration: stability check failed", e); } } await multiClusterOracle.InjectMultiClusterConfiguration(configuration); return configuration; } public Task<List<SiloAddress>> FindLaggingSilos() { var multiClusterOracle = GetMultiClusterOracle(); var expected = multiClusterOracle.GetMultiClusterConfiguration(); return multiClusterOracle.FindLaggingSilos(expected); } #endregion } }
using System; using System.CodeDom.Compiler; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Globalization; using System.Linq; using System.Text; namespace EduHub.Data.Entities { /// <summary> /// Creditor Trade Types Data Set /// </summary> [GeneratedCode("EduHub Data", "0.9")] public sealed partial class CRTTDataSet : EduHubDataSet<CRTT> { /// <inheritdoc /> public override string Name { get { return "CRTT"; } } /// <inheritdoc /> public override bool SupportsEntityLastModified { get { return true; } } internal CRTTDataSet(EduHubContext Context) : base(Context) { Index_CRKEY = new Lazy<Dictionary<string, IReadOnlyList<CRTT>>>(() => this.ToGroupedDictionary(i => i.CRKEY)); Index_STAFF = new Lazy<NullDictionary<string, IReadOnlyList<CRTT>>>(() => this.ToGroupedNullDictionary(i => i.STAFF)); Index_TID = new Lazy<Dictionary<int, CRTT>>(() => this.ToDictionary(i => i.TID)); Index_TRADE_TYPE = new Lazy<NullDictionary<string, IReadOnlyList<CRTT>>>(() => this.ToGroupedNullDictionary(i => i.TRADE_TYPE)); } /// <summary> /// Matches CSV file headers to actions, used to deserialize <see cref="CRTT" /> /// </summary> /// <param name="Headers">The CSV column headers</param> /// <returns>An array of actions which deserialize <see cref="CRTT" /> fields for each CSV column header</returns> internal override Action<CRTT, string>[] BuildMapper(IReadOnlyList<string> Headers) { var mapper = new Action<CRTT, string>[Headers.Count]; for (var i = 0; i < Headers.Count; i++) { switch (Headers[i]) { case "TID": mapper[i] = (e, v) => e.TID = int.Parse(v); break; case "CRKEY": mapper[i] = (e, v) => e.CRKEY = v; break; case "TRADE_TYPE": mapper[i] = (e, v) => e.TRADE_TYPE = v; break; case "STAFF": mapper[i] = (e, v) => e.STAFF = v; break; case "LW_DATE": mapper[i] = (e, v) => e.LW_DATE = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture); break; case "LW_TIME": mapper[i] = (e, v) => e.LW_TIME = v == null ? (short?)null : short.Parse(v); break; case "LW_USER": mapper[i] = (e, v) => e.LW_USER = v; break; default: mapper[i] = MapperNoOp; break; } } return mapper; } /// <summary> /// Merges <see cref="CRTT" /> delta entities /// </summary> /// <param name="Entities">Iterator for base <see cref="CRTT" /> entities</param> /// <param name="DeltaEntities">List of delta <see cref="CRTT" /> entities</param> /// <returns>A merged <see cref="IEnumerable{CRTT}"/> of entities</returns> internal override IEnumerable<CRTT> ApplyDeltaEntities(IEnumerable<CRTT> Entities, List<CRTT> DeltaEntities) { HashSet<int> Index_TID = new HashSet<int>(DeltaEntities.Select(i => i.TID)); using (var deltaIterator = DeltaEntities.GetEnumerator()) { using (var entityIterator = Entities.GetEnumerator()) { while (deltaIterator.MoveNext()) { var deltaClusteredKey = deltaIterator.Current.CRKEY; bool yieldEntity = false; while (entityIterator.MoveNext()) { var entity = entityIterator.Current; bool overwritten = Index_TID.Remove(entity.TID); if (entity.CRKEY.CompareTo(deltaClusteredKey) <= 0) { if (!overwritten) { yield return entity; } } else { yieldEntity = !overwritten; break; } } yield return deltaIterator.Current; if (yieldEntity) { yield return entityIterator.Current; } } while (entityIterator.MoveNext()) { yield return entityIterator.Current; } } } } #region Index Fields private Lazy<Dictionary<string, IReadOnlyList<CRTT>>> Index_CRKEY; private Lazy<NullDictionary<string, IReadOnlyList<CRTT>>> Index_STAFF; private Lazy<Dictionary<int, CRTT>> Index_TID; private Lazy<NullDictionary<string, IReadOnlyList<CRTT>>> Index_TRADE_TYPE; #endregion #region Index Methods /// <summary> /// Find CRTT by CRKEY field /// </summary> /// <param name="CRKEY">CRKEY value used to find CRTT</param> /// <returns>List of related CRTT entities</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<CRTT> FindByCRKEY(string CRKEY) { return Index_CRKEY.Value[CRKEY]; } /// <summary> /// Attempt to find CRTT by CRKEY field /// </summary> /// <param name="CRKEY">CRKEY value used to find CRTT</param> /// <param name="Value">List of related CRTT entities</param> /// <returns>True if the list of related CRTT entities is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindByCRKEY(string CRKEY, out IReadOnlyList<CRTT> Value) { return Index_CRKEY.Value.TryGetValue(CRKEY, out Value); } /// <summary> /// Attempt to find CRTT by CRKEY field /// </summary> /// <param name="CRKEY">CRKEY value used to find CRTT</param> /// <returns>List of related CRTT entities, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<CRTT> TryFindByCRKEY(string CRKEY) { IReadOnlyList<CRTT> value; if (Index_CRKEY.Value.TryGetValue(CRKEY, out value)) { return value; } else { return null; } } /// <summary> /// Find CRTT by STAFF field /// </summary> /// <param name="STAFF">STAFF value used to find CRTT</param> /// <returns>List of related CRTT entities</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<CRTT> FindBySTAFF(string STAFF) { return Index_STAFF.Value[STAFF]; } /// <summary> /// Attempt to find CRTT by STAFF field /// </summary> /// <param name="STAFF">STAFF value used to find CRTT</param> /// <param name="Value">List of related CRTT entities</param> /// <returns>True if the list of related CRTT entities is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindBySTAFF(string STAFF, out IReadOnlyList<CRTT> Value) { return Index_STAFF.Value.TryGetValue(STAFF, out Value); } /// <summary> /// Attempt to find CRTT by STAFF field /// </summary> /// <param name="STAFF">STAFF value used to find CRTT</param> /// <returns>List of related CRTT entities, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<CRTT> TryFindBySTAFF(string STAFF) { IReadOnlyList<CRTT> value; if (Index_STAFF.Value.TryGetValue(STAFF, out value)) { return value; } else { return null; } } /// <summary> /// Find CRTT by TID field /// </summary> /// <param name="TID">TID value used to find CRTT</param> /// <returns>Related CRTT entity</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public CRTT FindByTID(int TID) { return Index_TID.Value[TID]; } /// <summary> /// Attempt to find CRTT by TID field /// </summary> /// <param name="TID">TID value used to find CRTT</param> /// <param name="Value">Related CRTT entity</param> /// <returns>True if the related CRTT entity is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindByTID(int TID, out CRTT Value) { return Index_TID.Value.TryGetValue(TID, out Value); } /// <summary> /// Attempt to find CRTT by TID field /// </summary> /// <param name="TID">TID value used to find CRTT</param> /// <returns>Related CRTT entity, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public CRTT TryFindByTID(int TID) { CRTT value; if (Index_TID.Value.TryGetValue(TID, out value)) { return value; } else { return null; } } /// <summary> /// Find CRTT by TRADE_TYPE field /// </summary> /// <param name="TRADE_TYPE">TRADE_TYPE value used to find CRTT</param> /// <returns>List of related CRTT entities</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<CRTT> FindByTRADE_TYPE(string TRADE_TYPE) { return Index_TRADE_TYPE.Value[TRADE_TYPE]; } /// <summary> /// Attempt to find CRTT by TRADE_TYPE field /// </summary> /// <param name="TRADE_TYPE">TRADE_TYPE value used to find CRTT</param> /// <param name="Value">List of related CRTT entities</param> /// <returns>True if the list of related CRTT entities is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindByTRADE_TYPE(string TRADE_TYPE, out IReadOnlyList<CRTT> Value) { return Index_TRADE_TYPE.Value.TryGetValue(TRADE_TYPE, out Value); } /// <summary> /// Attempt to find CRTT by TRADE_TYPE field /// </summary> /// <param name="TRADE_TYPE">TRADE_TYPE value used to find CRTT</param> /// <returns>List of related CRTT entities, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<CRTT> TryFindByTRADE_TYPE(string TRADE_TYPE) { IReadOnlyList<CRTT> value; if (Index_TRADE_TYPE.Value.TryGetValue(TRADE_TYPE, out value)) { return value; } else { return null; } } #endregion #region SQL Integration /// <summary> /// Returns a <see cref="SqlCommand"/> which checks for the existence of a CRTT table, and if not found, creates the table and associated indexes. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> public override SqlCommand GetSqlCreateTableCommand(SqlConnection SqlConnection) { return new SqlCommand( connection: SqlConnection, cmdText: @"IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[CRTT]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1) BEGIN CREATE TABLE [dbo].[CRTT]( [TID] int IDENTITY NOT NULL, [CRKEY] varchar(10) NOT NULL, [TRADE_TYPE] varchar(10) NULL, [STAFF] varchar(4) NULL, [LW_DATE] datetime NULL, [LW_TIME] smallint NULL, [LW_USER] varchar(128) NULL, CONSTRAINT [CRTT_Index_TID] PRIMARY KEY NONCLUSTERED ( [TID] ASC ) ); CREATE CLUSTERED INDEX [CRTT_Index_CRKEY] ON [dbo].[CRTT] ( [CRKEY] ASC ); CREATE NONCLUSTERED INDEX [CRTT_Index_STAFF] ON [dbo].[CRTT] ( [STAFF] ASC ); CREATE NONCLUSTERED INDEX [CRTT_Index_TRADE_TYPE] ON [dbo].[CRTT] ( [TRADE_TYPE] ASC ); END"); } /// <summary> /// Returns a <see cref="SqlCommand"/> which disables all non-clustered table indexes. /// Typically called before <see cref="SqlBulkCopy"/> to improve performance. /// <see cref="GetSqlRebuildIndexesCommand(SqlConnection)"/> should be called to rebuild and enable indexes after performance sensitive work is completed. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <returns>A <see cref="SqlCommand"/> which (when executed) will disable all non-clustered table indexes</returns> public override SqlCommand GetSqlDisableIndexesCommand(SqlConnection SqlConnection) { return new SqlCommand( connection: SqlConnection, cmdText: @"IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[CRTT]') AND name = N'CRTT_Index_STAFF') ALTER INDEX [CRTT_Index_STAFF] ON [dbo].[CRTT] DISABLE; IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[CRTT]') AND name = N'CRTT_Index_TID') ALTER INDEX [CRTT_Index_TID] ON [dbo].[CRTT] DISABLE; IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[CRTT]') AND name = N'CRTT_Index_TRADE_TYPE') ALTER INDEX [CRTT_Index_TRADE_TYPE] ON [dbo].[CRTT] DISABLE; "); } /// <summary> /// Returns a <see cref="SqlCommand"/> which rebuilds and enables all non-clustered table indexes. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <returns>A <see cref="SqlCommand"/> which (when executed) will rebuild and enable all non-clustered table indexes</returns> public override SqlCommand GetSqlRebuildIndexesCommand(SqlConnection SqlConnection) { return new SqlCommand( connection: SqlConnection, cmdText: @"IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[CRTT]') AND name = N'CRTT_Index_STAFF') ALTER INDEX [CRTT_Index_STAFF] ON [dbo].[CRTT] REBUILD PARTITION = ALL; IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[CRTT]') AND name = N'CRTT_Index_TID') ALTER INDEX [CRTT_Index_TID] ON [dbo].[CRTT] REBUILD PARTITION = ALL; IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[CRTT]') AND name = N'CRTT_Index_TRADE_TYPE') ALTER INDEX [CRTT_Index_TRADE_TYPE] ON [dbo].[CRTT] REBUILD PARTITION = ALL; "); } /// <summary> /// Returns a <see cref="SqlCommand"/> which deletes the <see cref="CRTT"/> entities passed /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <param name="Entities">The <see cref="CRTT"/> entities to be deleted</param> public override SqlCommand GetSqlDeleteCommand(SqlConnection SqlConnection, IEnumerable<CRTT> Entities) { SqlCommand command = new SqlCommand(); int parameterIndex = 0; StringBuilder builder = new StringBuilder(); List<int> Index_TID = new List<int>(); foreach (var entity in Entities) { Index_TID.Add(entity.TID); } builder.AppendLine("DELETE [dbo].[CRTT] WHERE"); // Index_TID builder.Append("[TID] IN ("); for (int index = 0; index < Index_TID.Count; index++) { if (index != 0) builder.Append(", "); // TID var parameterTID = $"@p{parameterIndex++}"; builder.Append(parameterTID); command.Parameters.Add(parameterTID, SqlDbType.Int).Value = Index_TID[index]; } builder.Append(");"); command.Connection = SqlConnection; command.CommandText = builder.ToString(); return command; } /// <summary> /// Provides a <see cref="IDataReader"/> for the CRTT data set /// </summary> /// <returns>A <see cref="IDataReader"/> for the CRTT data set</returns> public override EduHubDataSetDataReader<CRTT> GetDataSetDataReader() { return new CRTTDataReader(Load()); } /// <summary> /// Provides a <see cref="IDataReader"/> for the CRTT data set /// </summary> /// <returns>A <see cref="IDataReader"/> for the CRTT data set</returns> public override EduHubDataSetDataReader<CRTT> GetDataSetDataReader(List<CRTT> Entities) { return new CRTTDataReader(new EduHubDataSetLoadedReader<CRTT>(this, Entities)); } // Modest implementation to primarily support SqlBulkCopy private class CRTTDataReader : EduHubDataSetDataReader<CRTT> { public CRTTDataReader(IEduHubDataSetReader<CRTT> Reader) : base (Reader) { } public override int FieldCount { get { return 7; } } public override object GetValue(int i) { switch (i) { case 0: // TID return Current.TID; case 1: // CRKEY return Current.CRKEY; case 2: // TRADE_TYPE return Current.TRADE_TYPE; case 3: // STAFF return Current.STAFF; case 4: // LW_DATE return Current.LW_DATE; case 5: // LW_TIME return Current.LW_TIME; case 6: // LW_USER return Current.LW_USER; default: throw new ArgumentOutOfRangeException(nameof(i)); } } public override bool IsDBNull(int i) { switch (i) { case 2: // TRADE_TYPE return Current.TRADE_TYPE == null; case 3: // STAFF return Current.STAFF == null; case 4: // LW_DATE return Current.LW_DATE == null; case 5: // LW_TIME return Current.LW_TIME == null; case 6: // LW_USER return Current.LW_USER == null; default: return false; } } public override string GetName(int ordinal) { switch (ordinal) { case 0: // TID return "TID"; case 1: // CRKEY return "CRKEY"; case 2: // TRADE_TYPE return "TRADE_TYPE"; case 3: // STAFF return "STAFF"; case 4: // LW_DATE return "LW_DATE"; case 5: // LW_TIME return "LW_TIME"; case 6: // LW_USER return "LW_USER"; default: throw new ArgumentOutOfRangeException(nameof(ordinal)); } } public override int GetOrdinal(string name) { switch (name) { case "TID": return 0; case "CRKEY": return 1; case "TRADE_TYPE": return 2; case "STAFF": return 3; case "LW_DATE": return 4; case "LW_TIME": return 5; case "LW_USER": return 6; default: throw new ArgumentOutOfRangeException(nameof(name)); } } } #endregion } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Net; using System.Threading; using Microsoft.WindowsAzure; using Microsoft.WindowsAzure.Diagnostics; using Microsoft.WindowsAzure.ServiceRuntime; using Microsoft.WindowsAzure.Storage; using Microsoft.WindowsAzure.Storage.Queue; using Microsoft.WindowsAzure.Storage.Table; using System.Xml; using System.IO; using System.Configuration; using HtmlAgilityPack; using Search_Engine_Front_End.cs; namespace Web_Crawler { /// <summary> /// This is the web crawler portion of my search engine, running on a worker role on azure. /// Currently, it is hard coded to only crawl cnn.com and sportsillustrated.cnn.com /// /// This is for INFO 344's Programming Assignment 4, Spring 2014 /// Josh Edwards /// /// </summary> public class WorkerRole : RoleEntryPoint { private HashSet<string> disallowList; private HashSet<string> alreadyVisitedList; public override void Run() { // These are the objects for handling the table/queue storage - no need to create them every time! CloudStorageAccount storageAccount = CloudStorageAccount.Parse(ConfigurationManager.AppSettings["StorageConnectionString"]); CloudQueueClient queueClient = storageAccount.CreateCloudQueueClient(); CloudQueue queue = queueClient.GetQueueReference("urls"); CloudQueue recentQueue = queueClient.GetQueueReference("recent"); CloudTableClient tableClient = storageAccount.CreateCloudTableClient(); CloudTable table = tableClient.GetTableReference("processed"); CloudTable statsTable = tableClient.GetTableReference("stats"); CloudTable errorsTable = tableClient.GetTableReference("errors"); //if the tables don't exist, create them. recentQueue.CreateIfNotExists(); table.CreateIfNotExists(); statsTable.CreateIfNotExists(); errorsTable.CreateIfNotExists(); if (queue.Exists() && disallowList == null) { initDisallowList(); } PerformanceCounter cpuUsage = new PerformanceCounter("Processor", "% Processor Time", "_Total"); PerformanceCounter memoryUsage = new PerformanceCounter("Memory", "Available MBytes"); Trace.TraceInformation("WorkerRole1 entry point called"); HashSet<string> visitedURLs = new HashSet<string>(); string currentState = "stop"; while (true) //we want the crawler always running. { Thread.Sleep(100); //check for new instructions TableOperation retrieveOperation = TableOperation.Retrieve<PageStats>("stats", "instruction"); TableResult result = statsTable.Execute(retrieveOperation); PageStats state = (PageStats)result.Result; if (state != null && currentState != state.statNumber) { currentState = state.statNumber; } //now do what the instruction is if (currentState == "start") //if start, let's initialize the queue { queue = initQueue(); //now switch to "running" TableOperation insertion = TableOperation.InsertOrReplace(new PageStats("instruction", "running")); statsTable.Execute(insertion); currentState = "running"; } else if (currentState == "clear") { //delete everything! queue.DeleteIfExists(); table.DeleteIfExists(); errorsTable.DeleteIfExists(); //statsTable.DeleteIfExists(); TableOperation waiting = TableOperation.InsertOrReplace(new PageStats("indexSize", "0")); statsTable.Execute(waiting); PageStats wait = new PageStats("instruction", "wait"); for (int i = 60; i > 0; i--) { wait.statNumber = "wait, " + i.ToString(); waiting = TableOperation.InsertOrReplace(wait); statsTable.Execute(waiting); Thread.Sleep(1000); } queue.CreateIfNotExists(); statsTable.CreateIfNotExists(); table.CreateIfNotExists(); errorsTable.CreateIfNotExists(); //now stop and wait for instructions currentState = "stop"; waiting = TableOperation.InsertOrReplace(new PageStats("instruction", "stop")); statsTable.Execute(waiting); } else if (currentState == "running") { CloudQueueMessage message = queue.GetMessage(TimeSpan.FromMinutes(5)); if (message != null) { string parseMe = message.AsString; //should be a url //let's double check it's not on the disallow list first bool isValid = true; foreach (string disallow in disallowList) { if (parseMe.Contains(disallow)) { isValid = false; } } //next remove any trailing stuff if (!parseMe.EndsWith(".htm") || !parseMe.EndsWith(".html")) { if (parseMe.Contains(".html")) { int end = parseMe.IndexOf(".html") + 5; parseMe = parseMe.Substring(0, end); } else if(parseMe.Contains(".htm")) { int end = parseMe.IndexOf(".html") + 5; parseMe = parseMe.Substring(0, end); } } if (alreadyVisitedList != null && alreadyVisitedList.Contains(parseMe)) { isValid = false; } TableQuery<Page> rangeQuery = new TableQuery<Page>().Where( TableQuery.GenerateFilterCondition("url", QueryComparisons.Equal, parseMe)); var results = table.ExecuteQuery(rangeQuery); if (results.Count() > 0) { isValid = false; } if (isValid) // if the link from the queue is valid to crawl { var client = new WebClient(); var webGet = new HtmlWeb(); try { //grab the page var document = webGet.Load(parseMe); //grab the page title var pageTitle = from t in document.DocumentNode.Descendants() where t.Name == "title" select new { Title = t.InnerText }; //grab all the links on the page var linksOnPage = from lnks in document.DocumentNode.Descendants() where lnks.Name == "a" && lnks.Attributes["href"] != null && lnks.InnerText.Trim().Length > 0 && (lnks.Attributes["rel"] == null || lnks.Attributes["rel"].Value.Contains("nofollow") == false) select new { Url = lnks.Attributes["href"].Value, Text = lnks.InnerText }; //get the date modified, if it's there var dateModified = from meta in document.DocumentNode.Descendants() where meta.Name == "meta" && meta.Attributes["content"] != null && meta.Attributes["name"] != null && meta.Attributes["name"].Value == "lastmod" select new { Date = meta.Attributes["content"].Value }; //now go through each link on the page, see if it's valid, and if so add it to the queue foreach (var link in linksOnPage) { bool validLink = true; string prefix = ""; //first let's see if it has *.htm or *.html if (!link.Url.Contains(".htm") || link.Url.EndsWith(".com")) { validLink = false; } if (!parseMe.EndsWith(".htm") || !parseMe.EndsWith(".html")) { if (parseMe.Contains(".html")) { int end = parseMe.IndexOf(".html") + 5; parseMe = parseMe.Substring(0, end); } else if (parseMe.Contains(".htm")) { int end = parseMe.IndexOf(".html") + 4; parseMe = parseMe.Substring(0, end); } } //next check if it's an out-of-domain link if (!link.Url.Contains("cnn.com")) { validLink = false; } //next check if we need to append a prefix if (!link.Url.StartsWith("http://")) { int end = parseMe.IndexOf(".com"); prefix = parseMe.Substring(0, (parseMe.Length - (end + 4))); } string finalLink = prefix + link.Url; //check if it's valid foreach (string disallow in disallowList) { if (finalLink.Contains(disallow)) { validLink = false; } } if (alreadyVisitedList != null && alreadyVisitedList.Contains(finalLink)) { validLink = false; } if (validLink) { CloudQueueMessage msg = new CloudQueueMessage(link.Url); queue.AddMessage(msg); } } string theDate = ""; if (dateModified.FirstOrDefault() != null) { theDate = dateModified.First().Date; } //now split it and create key-value pairs for each word in the title to the url/date combo //let's first remove everything that's not alphanumeric //and any CNN.com references string title = pageTitle.First().Title; string newTitle = title.Replace('-', ' '); newTitle = newTitle.Replace("'s", ""); char[] arr = newTitle.ToCharArray(); arr = Array.FindAll<char>(arr, (c => (char.IsLetterOrDigit(c) || char.IsWhiteSpace(c)))); newTitle = new string(arr); newTitle = newTitle.Replace("CNNcom", ""); newTitle = newTitle.Replace("SIcom", ""); var words = newTitle.ToLower().Trim().Split(' '); foreach (string word in words) { if (word.Length > 0) { Page thisPage = new Page(parseMe, word, title, theDate); TableOperation insertOperation = TableOperation.InsertOrMerge(thisPage); table.Execute(insertOperation); } } //now add it to the local already visited list, so we can try to make sure to not crawl //the same page twice if (alreadyVisitedList == null) { alreadyVisitedList = new HashSet<string>(); } alreadyVisitedList.Add(parseMe); //successfully crawled, delete the url from the queue queue.DeleteMessage(message); //update the number of sites crawled TableOperation getIndexSize = TableOperation.Retrieve<PageStats>("stats", "indexSize"); TableResult indexSize = statsTable.Execute(getIndexSize); PageStats updateMe; if (indexSize.Result != null) { updateMe = (PageStats)indexSize.Result; } else { updateMe = new PageStats("indexSize", "0"); } int num = Convert.ToInt32(updateMe.statNumber) + 1; updateMe.statNumber = num.ToString(); TableOperation insertOrReplaceOperation = TableOperation.InsertOrReplace(updateMe); statsTable.Execute(insertOrReplaceOperation); } catch (WebException ex) { ErrorStat er = new ErrorStat(ex.ToString()); TableOperation insert = TableOperation.Insert(er); errorsTable.Execute(insert); } catch (UriFormatException ex) { ErrorStat er = new ErrorStat(ex.ToString()); TableOperation insert = TableOperation.Insert(er); errorsTable.Execute(insert); } catch (Exception ex) { ErrorStat er = new ErrorStat(ex.ToString()); TableOperation insert = TableOperation.Insert(er); errorsTable.Execute(insert); } } //end of (if link is valid) if statement }//end of (if message != null) statement }//end of "running" if statement //at the end of the loop, update the cpu/memory stats PageStats updateMeCPUMem = new PageStats("cpumem", "CPU: "+cpuUsage.NextValue().ToString() + "%, Free Memory: " + memoryUsage.NextValue().ToString() + "MB"); TableOperation insertOrReplaceOperationCPU = TableOperation.InsertOrReplace(updateMeCPUMem); statsTable.Execute(insertOrReplaceOperationCPU); } // end of crawler while loop } // end of run() function public override bool OnStart() { // Set the maximum number of concurrent connections ServicePointManager.DefaultConnectionLimit = 12; // For information on handling configuration changes // see the MSDN topic at http://go.microsoft.com/fwlink/?LinkId=166357. return base.OnStart(); } private CloudQueue initQueue() { //hard coding the 2 robots.txt for now List<string> robots = new List<string>(); robots.Add("http://www.cnn.com/robots.txt"); robots.Add("http://sportsillustrated.cnn.com/robots.txt"); CloudStorageAccount storageAccount = CloudStorageAccount.Parse(ConfigurationManager.AppSettings["StorageConnectionString"]); CloudQueueClient queueClient = storageAccount.CreateCloudQueueClient(); CloudQueue queue = queueClient.GetQueueReference("urls"); //we also want to keep track of the current instruction, so that if a user clicks "stop", we //abort out of the sitemap loading phase CloudTableClient tableClient = storageAccount.CreateCloudTableClient(); CloudTable statsTable = tableClient.GetTableReference("stats"); queue.DeleteIfExists(); PageStats wait = new PageStats("instruction", "wait"); for (int i = 60; i > 0; i--) { wait.statNumber = "wait, " + i.ToString(); TableOperation waiting = TableOperation.InsertOrReplace(wait); statsTable.Execute(waiting); Thread.Sleep(1000); } queue.CreateIfNotExists(); TableOperation insertion = TableOperation.InsertOrReplace(new PageStats("instruction", "start")); statsTable.Execute(insertion); disallowList = new HashSet<string>(); List<string> siteMaps = new List<string>(); foreach (string robot in robots) // for each site robot we're passed { var client = new WebClient(); string prefix = robot.Substring(0, (robot.Length - 11)); using (var stream = client.OpenRead(robot)) using (var reader = new StreamReader(stream)) { string line; string currentUserAgent = ""; while ((line = reader.ReadLine()) != null) { if (line.StartsWith("#") == false) // not a comment { if (line.StartsWith("Sitemap: ")) { line = line.Substring(9); siteMaps.Add(line); } else if (line.StartsWith("User-agent:")) { currentUserAgent = line; } else if (line.StartsWith("Disallow: ")) { if (currentUserAgent == "User-agent: *") { line = line.Substring(10); line = prefix + line; disallowList.Add(line); } } } } } } // end of robots while loop //now we load the urls from the sitemaps List<string> moreSiteMaps = new List<string>(); bool hasMoreSiteMaps = true; //now let's load the url's from the site maps. while (hasMoreSiteMaps) { hasMoreSiteMaps = false; foreach (string siteMapURL in siteMaps) { //every site map, let's check if we should abort out TableOperation retrieveOperation = TableOperation.Retrieve<PageStats>("stats", "instruction"); TableResult result = statsTable.Execute(retrieveOperation); PageStats state = (PageStats)result.Result; if (!state.statNumber.Equals("start")) { return queue; } bool mapOfMaps = false; XmlDocument doc = new XmlDocument(); try { doc.Load(siteMapURL); XmlNodeList testList = doc.GetElementsByTagName("url"); if (testList.Count == 0) { testList = doc.GetElementsByTagName("sitemap"); mapOfMaps = true; } foreach (XmlNode node in testList) { if (mapOfMaps) //add it to the list of maps { string loc = node["loc"].InnerText; moreSiteMaps.Add(loc); } else { string loc = node["loc"].InnerText; DateTime pubdate = new System.DateTime(1990, 1, 1); if (node["news:news"] != null) { var nodes = node["news:news"].ChildNodes; foreach (XmlNode secondNode in nodes) { if (secondNode.Name == "news:publication_date") { pubdate = Convert.ToDateTime(secondNode.InnerText); } } } else if (node["lastmod"] != null) { pubdate = Convert.ToDateTime(node["lastmod"].InnerText); } // XmlNode test = node.ChildNodes[" // string modified = node["lastmod"].Value; // DateTime pubdate = Convert.ToDateTime(node.ChildNodes[1].ChildNodes[1].InnerText); // DateTime pubdate = DateTime.Now; //hard code checks for this assignment bool valid = true; if (loc.Contains("sportsillustrated") && loc.Contains(".xml")) { if (!loc.Contains("nba")) { valid = false; } } if ((DateTime.Now - pubdate).TotalDays > 60) { valid = false; } if (valid) { CloudQueueMessage message = new CloudQueueMessage(loc); queue.AddMessage(message); } //queue.FetchAttributes(); //var c = queue.ApproximateMessageCount; //if ((int)c > 1000) //{ // return queue; //} } }//end of node loop } catch (Exception ex) { CloudTable errorsTable = tableClient.GetTableReference("errors"); ErrorStat er = new ErrorStat(ex.ToString()); TableOperation insert = TableOperation.Insert(er); errorsTable.Execute(insert); } }//end of site map loop if (moreSiteMaps.Count > 0) { hasMoreSiteMaps = true; siteMaps = moreSiteMaps; moreSiteMaps = new List<string>(); } }//end of while hasMoreSiteMaps loop return queue; } private void initDisallowList() { //hard coding the 2 robots.txt for now List<string> robots = new List<string>(); robots.Add("http://www.cnn.com/robots.txt"); robots.Add("http://sportsillustrated.cnn.com/robots.txt"); CloudStorageAccount storageAccount = CloudStorageAccount.Parse(ConfigurationManager.AppSettings["StorageConnectionString"]); CloudQueueClient queueClient = storageAccount.CreateCloudQueueClient(); CloudQueue queue = queueClient.GetQueueReference("urls"); queue.CreateIfNotExists(); disallowList = new HashSet<string>(); foreach (string robot in robots) // for each site robot we're passed { var client = new WebClient(); string prefix = robot.Substring(0, (robot.Length - 11)); using (var stream = client.OpenRead(robot)) using (var reader = new StreamReader(stream)) { string line; string currentUserAgent = ""; while ((line = reader.ReadLine()) != null) { if (line.StartsWith("#") == false) // not a comment { if (line.StartsWith("User-agent:")) { currentUserAgent = line; } else if (line.StartsWith("Disallow: ")) { if (currentUserAgent == "User-agent: *") { line = line.Substring(10); line = prefix + line; disallowList.Add(line); } } } } } } } } }
using System; using System.Collections.Generic; using System.Linq; using Xyglo.Brazil; using System.Runtime.Serialization; namespace Xyglo.Brazil { /// <summary> /// This is the top level class for our Paulo game. It inherits a BrazilApp object which /// inherits the XNA Game implementation. /// </summary> [DataContract(Namespace = "http://www.xyglo.com")] [KnownType(typeof(BrazilApp))] public class BrazilPaulo : BrazilApp { /// <summary> /// BrazilPaulo constructor - note we used the Hosted mode so we don't reinitialise /// anything at the drawing level. /// </summary> public BrazilPaulo(BrazilVector3 gravity, string homePath): base(homePath, BrazilAppMode.Hosted) { m_world.setGravity(gravity); m_world.setBounds(new BrazilBoundingBox(new BrazilVector3(-400, -400, -300), new BrazilVector3(400, 400, 300))); // Initialise the states // initialiseStates(); } /// <summary> /// Allows the game to perform any initialisation of objects and positions before starting. /// </summary> public override void initialise(State state) { // Now set the initial state // setState(state); // Connect some keys // setupConnections(); // Generate our components for our levels and other things blocks // generateComponents(); // Set up an interloper - we give it a name to aid debugging // BrazilInterloper paulo = new BrazilInterloper(BrazilColour.White, new BrazilVector3(0, 0, 0), new BrazilVector3(10, 10, 10)); paulo.setName("Interloper"); addComponent("PlayingGame", paulo); // Big dummy interloper // // Set up an interloper - we give it a name to aid debugging // BrazilInterloper paulo2 = new BrazilInterloper(BrazilColour.Yellow, new BrazilVector3(0, 0, 0), new BrazilVector3(100, 100, 100)); paulo.setName("Interloper2"); addComponent("ComponentTest", paulo2); // Banner screen // //BrazilBannerText menuScreen = new BrazilBannerText(BrazilColour.Blue, new BrazilVector3(360.0f, 240.0f, 0), 4.0, "Paulo"); BrazilBannerText menuScreen = new BrazilBannerText(BrazilColour.Blue, BrazilPosition.Middle, 4.0, "Paulo"); addComponent("Menu", menuScreen); //BrazilBannerText byLine = new BrazilBannerText(BrazilColour.Yellow, new BrazilVector3(430.0f, 345.0f, 0), 1.0, "@xyglo"); BrazilBannerText byLine = new BrazilBannerText(BrazilColour.Yellow, BrazilRelativePosition.BeneathCentred, menuScreen, 0, 1.0f, "@xyglo"); addComponent("Menu", byLine); //BrazilBannerText toPlay = new BrazilBannerText(BrazilColour.White, new BrazilVector3(380.0f, 500.0f, 0), 1.0, "Hit '1' to Play"); BrazilBannerText toPlay = new BrazilBannerText(BrazilColour.White, BrazilPosition.BottomMiddle, 1.0f, "Hit '1' to Play"); addComponent("Menu", toPlay); } /// <summary> /// Initialise the states - might find a way to genericise this /// </summary> protected void initialiseStates() { // States of the application - where are we in the navigation around the app. States will affect what // components are showing and how we interact with them. // string[] states = { "Menu", "PlayingGame", "LevelComplete", "ComponentTest", "GameOver" }; foreach (string state in states) { addState(state); } // Targets are actions we can perform in the application - a default target will usually mean the object // in focus within the current State. This should be defined by the component. // string[] targets = { "StartPlaying", "QuitToMenu", "Exit", "MoveLeft", "MoveRight", "Jump", "MoveForward", "MoveBack" }; foreach (string target in targets) { addTarget(target); } // Confirm states are substates used when confirming actions or movements between states. These // give greater control over movement between States. // string[] confirmStates = { }; foreach (string confirmState in confirmStates) { addConfirmState(confirmState); } } /// <summary> /// Set up the key and mouse connections /// </summary> protected void setupConnections() { // Connect up a transition - this key connection starts the game for us // connectKey("Menu", Keys.D1, "StartPlaying"); // Connect up the escape key to exit the game or into the menu // connectKey("Menu", Keys.Escape, "Exit"); connectKey("PlayingGame", Keys.Escape, "QuitToMenu"); // Connect up the Interloper // connectKey("PlayingGame", Keys.Left, "MoveLeft"); connectKey("PlayingGame", Keys.Right, "MoveRight"); //connectKey("PlayingGame", Keys.Up, "MoveForward"); //connectKey("PlayingGame", Keys.Down, "MoveBack"); connectKey("PlayingGame", Keys.Left, KeyButtonState.Held, "MoveLeft"); connectKey("PlayingGame", Keys.Right, KeyButtonState.Held, "MoveRight"); connectKey("PlayingGame", Keys.Up, "Jump"); // Connect up our test state // connectKey("ComponentTest", Keys.Escape, "QuitToMenu"); } /// <summary> /// Set up some test blocks /// </summary> protected void generateComponents() { BrazilFlyingBlock block1 = new BrazilFlyingBlock(BrazilColour.Blue, new BrazilVector3(-10, -100, 0), new BrazilVector3(200.0f, 100.0f, 10.0f)); //block1.setVelocity(new BrazilVector3(-1, 0, 0)); // Push onto component list // //m_componentList.Add(block1); block1.setMoveable(false); addResource("logo", "xyglo-logo.png", ResourceType.Image, ResourceMode.Centre, block1); addComponent("PlayingGame", block1); /* BrazilFlyingBlock block2 = new BrazilFlyingBlock(BrazilColour.Brown, new BrazilVector3(0, 0, 0), new BrazilVector3(100, 20, 20)); //block2.setVelocity(new BrazilVector3(0.5f, 0, 0.1f)); //m_componentList.Add(block2); addComponent("PlayingGame", block2); */ BrazilFlyingBlock block3 = new BrazilFlyingBlock(BrazilColour.Brown, new BrazilVector3(0, 150, 0), new BrazilVector3(400, 50, 100)); //block3.setRotation(0.2); block3.setHardness(300000.0f); block3.setMoveable(false); //block3.setInitialAngle(Math.PI / 8); //block3.setName("LandingBlock1"); addComponent("PlayingGame", block3); BrazilFlyingBlock block4 = new BrazilFlyingBlock(BrazilColour.Green, new BrazilVector3(0, 50, 0), new BrazilVector3(100, 10, 100)); //block4.setRotation(0.03); //block4.setVelocity(new BrazilVector3(-0.5f, -1f, -0.4f)); //m_componentList.Add(block4); block4.setHardness(3.0f); block4.setMoveable(false); block4.setName("LandingBlock2"); block4.setInitialAngle(Math.PI / 8); addComponent("PlayingGame", block4); BrazilVector3 position = new BrazilVector3(80, 120, 0); BrazilGoody newGoody = new BrazilGoody(BrazilGoodyType.Coin, 50, position, new BrazilVector3(4, 10, 10), DateTime.Now); newGoody.setRotation(0.2); addComponent("PlayingGame", newGoody); BrazilVector3 position2 = new BrazilVector3(100, 120, 0); BrazilGoody newGoody2 = new BrazilGoody(BrazilGoodyType.Coin, 50, position2, new BrazilVector3(4, 10, 10), DateTime.Now); newGoody2.setRotation(0.2); addComponent("PlayingGame", newGoody2); // Setup the HUD // BrazilHud hud = new BrazilHud(BrazilColour.White, BrazilVector3.Zero, 1.0, "HUD"); addComponent("PlayingGame", hud); // Add the finishing block // //BrazilFinishBlock finishBlock = new BrazilFinishBlock(BrazilColour.Pink, new BrazilVector3(0, 230, 0), new BrazilVector3(200, 10, 10), getState("LevelComplete")); //block4.setHardness(10); //addComponent("PlayingGame", finishBlock); /* // Add some prizes // BrazilGoody goody1 = new BrazilGoody(BrazilGoodyType.Coin, 50, new BrazilVector3(0, 100, 0), new BrazilVector3(5, 10, 10), DateTime.Now); goody1.setRotation(0.2); addComponent("PlayingGame", goody1); // Test state for new components // BrazilGoody goody2 = new BrazilGoody(BrazilGoodyType.Coin, 50, new BrazilVector3(0, 100, 0), new BrazilVector3(100, 50, 50), DateTime.Now); goody2.setRotation(0.01); addComponent("ComponentTest", goody2); for (int i = 0; i < 10; i++) { BrazilVector3 position = new BrazilVector3(-100.0f + (i * 12.0f), 120, 0); BrazilGoody newGoody = new BrazilGoody(BrazilGoodyType.Coin, 50, position, new BrazilVector3(4, 10, 10), DateTime.Now); newGoody.setRotation(0.2); addComponent("PlayingGame", newGoody); } BrazilBannerText gameOverText = new BrazilBannerText(BrazilColour.Red, BrazilPosition.Middle, 2.0f, "GAME OVER"); addComponent("GameOver", gameOverText); * */ } } }
// 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 (GlobalLog.SetThreadKind(ThreadKinds.User)) { #endif _negoState = new NegoState(innerStream, leaveInnerStreamOpen); _package = NegoState.DefaultPackage; InitializeStreamPart(); #if DEBUG } #endif } private IAsyncResult BeginAuthenticateAsClient(AsyncCallback asyncCallback, object asyncState) { return BeginAuthenticateAsClient((NetworkCredential)CredentialCache.DefaultCredentials, null, string.Empty, ProtectionLevel.EncryptAndSign, TokenImpersonationLevel.Identification, asyncCallback, asyncState); } private IAsyncResult BeginAuthenticateAsClient(NetworkCredential credential, string targetName, AsyncCallback asyncCallback, object asyncState) { return BeginAuthenticateAsClient(credential, null, targetName, ProtectionLevel.EncryptAndSign, TokenImpersonationLevel.Identification, asyncCallback, asyncState); } private IAsyncResult BeginAuthenticateAsClient(NetworkCredential credential, ChannelBinding binding, string targetName, AsyncCallback asyncCallback, object asyncState) { return BeginAuthenticateAsClient(credential, binding, targetName, ProtectionLevel.EncryptAndSign, TokenImpersonationLevel.Identification, asyncCallback, asyncState); } private IAsyncResult BeginAuthenticateAsClient( NetworkCredential credential, string targetName, ProtectionLevel requiredProtectionLevel, TokenImpersonationLevel allowedImpersonationLevel, AsyncCallback asyncCallback, object asyncState) { return BeginAuthenticateAsClient(credential, null, targetName, requiredProtectionLevel, allowedImpersonationLevel, asyncCallback, asyncState); } private IAsyncResult BeginAuthenticateAsClient( NetworkCredential credential, ChannelBinding binding, string targetName, ProtectionLevel requiredProtectionLevel, TokenImpersonationLevel allowedImpersonationLevel, AsyncCallback asyncCallback, object asyncState) { #if DEBUG using (GlobalLog.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 } private void EndAuthenticateAsClient(IAsyncResult asyncResult) { #if DEBUG using (GlobalLog.SetThreadKind(ThreadKinds.User)) { #endif _negoState.EndProcessAuthentication(asyncResult); #if DEBUG } #endif } private IAsyncResult BeginAuthenticateAsServer(AsyncCallback asyncCallback, object asyncState) { return BeginAuthenticateAsServer((NetworkCredential)CredentialCache.DefaultCredentials, null, ProtectionLevel.EncryptAndSign, TokenImpersonationLevel.Identification, asyncCallback, asyncState); } private IAsyncResult BeginAuthenticateAsServer(ExtendedProtectionPolicy policy, AsyncCallback asyncCallback, object asyncState) { return BeginAuthenticateAsServer((NetworkCredential)CredentialCache.DefaultCredentials, policy, ProtectionLevel.EncryptAndSign, TokenImpersonationLevel.Identification, asyncCallback, asyncState); } private IAsyncResult BeginAuthenticateAsServer( NetworkCredential credential, ProtectionLevel requiredProtectionLevel, TokenImpersonationLevel requiredImpersonationLevel, AsyncCallback asyncCallback, object asyncState) { return BeginAuthenticateAsServer(credential, null, requiredProtectionLevel, requiredImpersonationLevel, asyncCallback, asyncState); } private IAsyncResult BeginAuthenticateAsServer( NetworkCredential credential, ExtendedProtectionPolicy policy, ProtectionLevel requiredProtectionLevel, TokenImpersonationLevel requiredImpersonationLevel, AsyncCallback asyncCallback, object asyncState) { #if DEBUG using (GlobalLog.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 } // private void EndAuthenticateAsServer(IAsyncResult asyncResult) { #if DEBUG using (GlobalLog.SetThreadKind(ThreadKinds.User)) { #endif _negoState.EndProcessAuthentication(asyncResult); #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 (GlobalLog.SetThreadKind(ThreadKinds.User | ThreadKinds.Async)) { #endif return _negoState.IsAuthenticated; #if DEBUG } #endif } } public override bool IsMutuallyAuthenticated { get { #if DEBUG using (GlobalLog.SetThreadKind(ThreadKinds.User | ThreadKinds.Async)) { #endif return _negoState.IsMutuallyAuthenticated; #if DEBUG } #endif } } public override bool IsEncrypted { get { #if DEBUG using (GlobalLog.SetThreadKind(ThreadKinds.User | ThreadKinds.Async)) { #endif return _negoState.IsEncrypted; #if DEBUG } #endif } } public override bool IsSigned { get { #if DEBUG using (GlobalLog.SetThreadKind(ThreadKinds.User | ThreadKinds.Async)) { #endif return _negoState.IsSigned; #if DEBUG } #endif } } public override bool IsServer { get { #if DEBUG using (GlobalLog.SetThreadKind(ThreadKinds.User | ThreadKinds.Async)) { #endif return _negoState.IsServer; #if DEBUG } #endif } } public virtual TokenImpersonationLevel ImpersonationLevel { get { #if DEBUG using (GlobalLog.SetThreadKind(ThreadKinds.User | ThreadKinds.Async)) { #endif return _negoState.AllowedImpersonation; #if DEBUG } #endif } } public virtual IIdentity RemoteIdentity { get { #if DEBUG using (GlobalLog.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 (GlobalLog.SetThreadKind(ThreadKinds.User | ThreadKinds.Sync)) { #endif InnerStream.Flush(); #if DEBUG } #endif } protected override void Dispose(bool disposing) { #if DEBUG using (GlobalLog.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 (GlobalLog.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 (GlobalLog.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 } private IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback asyncCallback, object asyncState) { #if DEBUG using (GlobalLog.SetThreadKind(ThreadKinds.User | ThreadKinds.Async)) { #endif _negoState.CheckThrow(true); if (!_negoState.CanGetSecureStream) { return InnerStream.BeginRead(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 } private int EndRead(IAsyncResult asyncResult) { #if DEBUG using (GlobalLog.SetThreadKind(ThreadKinds.User)) { #endif _negoState.CheckThrow(true); if (!_negoState.CanGetSecureStream) { return InnerStream.EndRead(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 (int)bufferResult.Result; #if DEBUG } #endif } // // private IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback asyncCallback, object asyncState) { #if DEBUG using (GlobalLog.SetThreadKind(ThreadKinds.User | ThreadKinds.Async)) { #endif _negoState.CheckThrow(true); if (!_negoState.CanGetSecureStream) { return InnerStream.BeginWrite(buffer, offset, count, asyncCallback, asyncState); } BufferAsyncResult bufferResult = new BufferAsyncResult(this, buffer, offset, count, true, asyncState, asyncCallback); AsyncProtocolRequest asyncRequest = new AsyncProtocolRequest(bufferResult); ProcessWrite(buffer, offset, count, asyncRequest); return bufferResult; #if DEBUG } #endif } private void EndWrite(IAsyncResult asyncResult) { #if DEBUG using (GlobalLog.SetThreadKind(ThreadKinds.User)) { #endif _negoState.CheckThrow(true); if (!_negoState.CanGetSecureStream) { InnerStream.EndWrite(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 } // ReadAsync - provide async read functionality. // // This method provides async read functionality. All we do is // call through to the Begin/EndRead methods. // // Input: // // buffer - Buffer to read into. // offset - Offset into the buffer where we're to read. // size - Number of bytes to read. // cancellationToken - Token used to request cancellation of the operation // // Returns: // // A Task<int> representing the read. public override Task<int> ReadAsync(byte[] buffer, int offset, int size, CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { return Task.FromCanceled<int>(cancellationToken); } return Task.Factory.FromAsync( (bufferArg, offsetArg, sizeArg, callback, state) => ((NegotiateStream)state).BeginRead(bufferArg, offsetArg, sizeArg, callback, state), iar => ((NegotiateStream)iar.AsyncState).EndRead(iar), buffer, offset, size, this); } // WriteAsync - provide async write functionality. // // This method provides async write functionality. All we do is // call through to the Begin/EndWrite methods. // // Input: // // buffer - Buffer to write into. // offset - Offset into the buffer where we're to write. // size - Number of bytes to write. // cancellationToken - Token used to request cancellation of the operation // // Returns: // // A Task representing the write. public override Task WriteAsync(byte[] buffer, int offset, int size, CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { return Task.FromCanceled<int>(cancellationToken); } return Task.Factory.FromAsync( (bufferArg, offsetArg, sizeArg, callback, state) => ((NegotiateStream)state).BeginWrite(bufferArg, offsetArg, sizeArg, callback, state), iar => ((NegotiateStream)iar.AsyncState).EndWrite(iar), buffer, offset, size, this); } } }
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; using Microsoft.VisualStudio.Services.WebApi; using Pipelines = Microsoft.TeamFoundation.DistributedTask.Pipelines; 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; private Mock<IAgentCertificateManager> _cert; 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>(); _cert = new Mock<IAgentCertificateManager>(); } 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<IAgentCertificateManager>(_cert.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<Pipelines.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<Pipelines.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<IAgentCertificateManager>(_cert.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<IAgentCertificateManager>(_cert.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<IAgentCertificateManager>(_cert.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()); } } } }
/// This code was generated by /// \ / _ _ _| _ _ /// | (_)\/(_)(_|\/| |(/_ v1.0.0 /// / / using System; using System.Collections.Generic; using System.Linq; using Twilio.Base; using Twilio.Converters; namespace Twilio.Rest.Chat.V1.Service.Channel { /// <summary> /// FetchInviteOptions /// </summary> public class FetchInviteOptions : IOptions<InviteResource> { /// <summary> /// The SID of the Service to fetch the resource from /// </summary> public string PathServiceSid { get; } /// <summary> /// The SID of the Channel the resource to fetch belongs to /// </summary> public string PathChannelSid { get; } /// <summary> /// The unique string that identifies the resource /// </summary> public string PathSid { get; } /// <summary> /// Construct a new FetchInviteOptions /// </summary> /// <param name="pathServiceSid"> The SID of the Service to fetch the resource from </param> /// <param name="pathChannelSid"> The SID of the Channel the resource to fetch belongs to </param> /// <param name="pathSid"> The unique string that identifies the resource </param> public FetchInviteOptions(string pathServiceSid, string pathChannelSid, string pathSid) { PathServiceSid = pathServiceSid; PathChannelSid = pathChannelSid; PathSid = pathSid; } /// <summary> /// Generate the necessary parameters /// </summary> public List<KeyValuePair<string, string>> GetParams() { var p = new List<KeyValuePair<string, string>>(); return p; } } /// <summary> /// CreateInviteOptions /// </summary> public class CreateInviteOptions : IOptions<InviteResource> { /// <summary> /// The SID of the Service to create the resource under /// </summary> public string PathServiceSid { get; } /// <summary> /// The SID of the Channel the new resource belongs to /// </summary> public string PathChannelSid { get; } /// <summary> /// The `identity` value that identifies the new resource's User /// </summary> public string Identity { get; } /// <summary> /// The Role assigned to the new member /// </summary> public string RoleSid { get; set; } /// <summary> /// Construct a new CreateInviteOptions /// </summary> /// <param name="pathServiceSid"> The SID of the Service to create the resource under </param> /// <param name="pathChannelSid"> The SID of the Channel the new resource belongs to </param> /// <param name="identity"> The `identity` value that identifies the new resource's User </param> public CreateInviteOptions(string pathServiceSid, string pathChannelSid, string identity) { PathServiceSid = pathServiceSid; PathChannelSid = pathChannelSid; Identity = identity; } /// <summary> /// Generate the necessary parameters /// </summary> public List<KeyValuePair<string, string>> GetParams() { var p = new List<KeyValuePair<string, string>>(); if (Identity != null) { p.Add(new KeyValuePair<string, string>("Identity", Identity)); } if (RoleSid != null) { p.Add(new KeyValuePair<string, string>("RoleSid", RoleSid.ToString())); } return p; } } /// <summary> /// ReadInviteOptions /// </summary> public class ReadInviteOptions : ReadOptions<InviteResource> { /// <summary> /// The SID of the Service to read the resources from /// </summary> public string PathServiceSid { get; } /// <summary> /// The SID of the Channel the resources to read belong to /// </summary> public string PathChannelSid { get; } /// <summary> /// The `identity` value of the resources to read /// </summary> public List<string> Identity { get; set; } /// <summary> /// Construct a new ReadInviteOptions /// </summary> /// <param name="pathServiceSid"> The SID of the Service to read the resources from </param> /// <param name="pathChannelSid"> The SID of the Channel the resources to read belong to </param> public ReadInviteOptions(string pathServiceSid, string pathChannelSid) { PathServiceSid = pathServiceSid; PathChannelSid = pathChannelSid; Identity = new List<string>(); } /// <summary> /// Generate the necessary parameters /// </summary> public override List<KeyValuePair<string, string>> GetParams() { var p = new List<KeyValuePair<string, string>>(); if (Identity != null) { p.AddRange(Identity.Select(prop => new KeyValuePair<string, string>("Identity", prop))); } if (PageSize != null) { p.Add(new KeyValuePair<string, string>("PageSize", PageSize.ToString())); } return p; } } /// <summary> /// DeleteInviteOptions /// </summary> public class DeleteInviteOptions : IOptions<InviteResource> { /// <summary> /// The SID of the Service to delete the resource from /// </summary> public string PathServiceSid { get; } /// <summary> /// The SID of the Channel the resource to delete belongs to /// </summary> public string PathChannelSid { get; } /// <summary> /// The unique string that identifies the resource /// </summary> public string PathSid { get; } /// <summary> /// Construct a new DeleteInviteOptions /// </summary> /// <param name="pathServiceSid"> The SID of the Service to delete the resource from </param> /// <param name="pathChannelSid"> The SID of the Channel the resource to delete belongs to </param> /// <param name="pathSid"> The unique string that identifies the resource </param> public DeleteInviteOptions(string pathServiceSid, string pathChannelSid, string pathSid) { PathServiceSid = pathServiceSid; PathChannelSid = pathChannelSid; PathSid = pathSid; } /// <summary> /// Generate the necessary parameters /// </summary> public List<KeyValuePair<string, string>> GetParams() { var p = new List<KeyValuePair<string, string>>(); return p; } } }
// 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. /*============================================================ ** ** ** ** Purpose: The boolean class serves as a wrapper for the primitive ** type boolean. ** ** ===========================================================*/ using System.Runtime.CompilerServices; using System.Runtime.Versioning; namespace System { [Serializable] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public readonly struct Boolean : IComparable, IConvertible, IComparable<bool>, IEquatable<bool> { // // Member Variables // private readonly bool m_value; // Do not rename (binary serialization) // The true value. // internal const int True = 1; // The false value. // internal const int False = 0; // // Internal Constants are real consts for performance. // // The internal string representation of true. // internal const string TrueLiteral = "True"; // The internal string representation of false. // internal const string FalseLiteral = "False"; // // Public Constants // // The public string representation of true. // public static readonly string TrueString = TrueLiteral; // The public string representation of false. // public static readonly string FalseString = FalseLiteral; // // Overriden Instance Methods // /*=================================GetHashCode================================== **Args: None **Returns: 1 or 0 depending on whether this instance represents true or false. **Exceptions: None **Overriden From: Value ==============================================================================*/ // Provides a hash code for this instance. public override int GetHashCode() { return (m_value) ? True : False; } /*===================================ToString=================================== **Args: None **Returns: "True" or "False" depending on the state of the boolean. **Exceptions: None. ==============================================================================*/ // Converts the boolean value of this instance to a String. public override string ToString() { if (false == m_value) { return FalseLiteral; } return TrueLiteral; } public string ToString(IFormatProvider provider) { return ToString(); } public bool TryFormat(Span<char> destination, out int charsWritten) { if (m_value) { if ((uint)destination.Length > 3) // uint cast, per https://github.com/dotnet/coreclr/issues/18688 { destination[0] = 'T'; destination[1] = 'r'; destination[2] = 'u'; destination[3] = 'e'; charsWritten = 4; return true; } } else { if ((uint)destination.Length > 4) { destination[0] = 'F'; destination[1] = 'a'; destination[2] = 'l'; destination[3] = 's'; destination[4] = 'e'; charsWritten = 5; return true; } } charsWritten = 0; return false; } // Determines whether two Boolean objects are equal. public override bool Equals(object obj) { //If it's not a boolean, we're definitely not equal if (!(obj is bool)) { return false; } return (m_value == ((bool)obj).m_value); } [NonVersionable] public bool Equals(bool obj) { return m_value == obj; } // Compares this object to another object, returning an integer that // indicates the relationship. For booleans, false sorts before true. // null is considered to be less than any instance. // If object is not of type boolean, this method throws an ArgumentException. // // Returns a value less than zero if this object // public int CompareTo(object obj) { if (obj == null) { return 1; } if (!(obj is bool)) { throw new ArgumentException(SR.Arg_MustBeBoolean); } if (m_value == ((bool)obj).m_value) { return 0; } else if (m_value == false) { return -1; } return 1; } public int CompareTo(bool value) { if (m_value == value) { return 0; } else if (m_value == false) { return -1; } return 1; } // // Static Methods // // Custom string compares for early application use by config switches, etc // internal static bool IsTrueStringIgnoreCase(ReadOnlySpan<char> value) { return (value.Length == 4 && (value[0] == 't' || value[0] == 'T') && (value[1] == 'r' || value[1] == 'R') && (value[2] == 'u' || value[2] == 'U') && (value[3] == 'e' || value[3] == 'E')); } internal static bool IsFalseStringIgnoreCase(ReadOnlySpan<char> value) { return (value.Length == 5 && (value[0] == 'f' || value[0] == 'F') && (value[1] == 'a' || value[1] == 'A') && (value[2] == 'l' || value[2] == 'L') && (value[3] == 's' || value[3] == 'S') && (value[4] == 'e' || value[4] == 'E')); } // Determines whether a String represents true or false. // public static bool Parse(string value) { if (value == null) throw new ArgumentNullException(nameof(value)); return Parse(value.AsSpan()); } public static bool Parse(ReadOnlySpan<char> value) => TryParse(value, out bool result) ? result : throw new FormatException(SR.Format(SR.Format_BadBoolean, new string(value))); // Determines whether a String represents true or false. // public static bool TryParse(string value, out bool result) { if (value == null) { result = false; return false; } return TryParse(value.AsSpan(), out result); } public static bool TryParse(ReadOnlySpan<char> value, out bool result) { if (IsTrueStringIgnoreCase(value)) { result = true; return true; } if (IsFalseStringIgnoreCase(value)) { result = false; return true; } // Special case: Trim whitespace as well as null characters. value = TrimWhiteSpaceAndNull(value); if (IsTrueStringIgnoreCase(value)) { result = true; return true; } if (IsFalseStringIgnoreCase(value)) { result = false; return true; } result = false; return false; } private static ReadOnlySpan<char> TrimWhiteSpaceAndNull(ReadOnlySpan<char> value) { const char nullChar = (char)0x0000; int start = 0; while (start < value.Length) { if (!char.IsWhiteSpace(value[start]) && value[start] != nullChar) { break; } start++; } int end = value.Length - 1; while (end >= start) { if (!char.IsWhiteSpace(value[end]) && value[end] != nullChar) { break; } end--; } return value.Slice(start, end - start + 1); } // // IConvertible implementation // public TypeCode GetTypeCode() { return TypeCode.Boolean; } bool IConvertible.ToBoolean(IFormatProvider provider) { return m_value; } char IConvertible.ToChar(IFormatProvider provider) { throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Boolean", "Char")); } sbyte IConvertible.ToSByte(IFormatProvider provider) { return Convert.ToSByte(m_value); } byte IConvertible.ToByte(IFormatProvider provider) { return Convert.ToByte(m_value); } short IConvertible.ToInt16(IFormatProvider provider) { return Convert.ToInt16(m_value); } ushort IConvertible.ToUInt16(IFormatProvider provider) { return Convert.ToUInt16(m_value); } int IConvertible.ToInt32(IFormatProvider provider) { return Convert.ToInt32(m_value); } uint IConvertible.ToUInt32(IFormatProvider provider) { return Convert.ToUInt32(m_value); } long IConvertible.ToInt64(IFormatProvider provider) { return Convert.ToInt64(m_value); } ulong IConvertible.ToUInt64(IFormatProvider provider) { return Convert.ToUInt64(m_value); } float IConvertible.ToSingle(IFormatProvider provider) { return Convert.ToSingle(m_value); } double IConvertible.ToDouble(IFormatProvider provider) { return Convert.ToDouble(m_value); } decimal IConvertible.ToDecimal(IFormatProvider provider) { return Convert.ToDecimal(m_value); } DateTime IConvertible.ToDateTime(IFormatProvider provider) { throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Boolean", "DateTime")); } object IConvertible.ToType(Type type, IFormatProvider provider) { return Convert.DefaultToType((IConvertible)this, type, provider); } } }
// 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.Collections; using System.Diagnostics; using System.Globalization; using System.Security.Principal; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; namespace System.DirectoryServices.AccountManagement { internal class AuthZSet : ResultSet { internal AuthZSet( byte[] userSid, NetCred credentials, ContextOptions contextOptions, string flatUserAuthority, StoreCtx userStoreCtx, object userCtxBase) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "AuthZSet", "AuthZSet: SID={0}, authority={1}, storeCtx={2}", Utils.ByteArrayToString(userSid), flatUserAuthority, userStoreCtx.GetType()); _userType = userStoreCtx.OwningContext.ContextType; _userCtxBase = userCtxBase; _userStoreCtx = userStoreCtx; _credentials = credentials; _contextOptions = contextOptions; // flatUserAuthority is flat domain name if userType == Domain, // flat host name if userType == LocalMachine _flatUserAuthority = flatUserAuthority; // Preload the PrincipalContext cache with the user's PrincipalContext _contexts[flatUserAuthority] = userStoreCtx.OwningContext; IntPtr hUser = IntPtr.Zero; // // Get the SIDs of the groups to which the user belongs // IntPtr pClientContext = IntPtr.Zero; IntPtr pResManager = IntPtr.Zero; IntPtr pBuffer = IntPtr.Zero; try { UnsafeNativeMethods.LUID luid = new UnsafeNativeMethods.LUID(); luid.low = 0; luid.high = 0; _psMachineSid = new SafeMemoryPtr(Utils.GetMachineDomainSid()); _psUserSid = new SafeMemoryPtr(Utils.ConvertByteArrayToIntPtr(userSid)); bool f; int lastError = 0; GlobalDebug.WriteLineIf(GlobalDebug.Info, "AuthZSet", "Initializing resource manager"); // Create a resource manager f = UnsafeNativeMethods.AuthzInitializeResourceManager( UnsafeNativeMethods.AUTHZ_RM_FLAG.AUTHZ_RM_FLAG_NO_AUDIT, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, null, out pResManager ); if (f) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "AuthZSet", "Getting ctx from SID"); // Construct a context for the user based on the user's SID f = UnsafeNativeMethods.AuthzInitializeContextFromSid( 0, // default flags _psUserSid.DangerousGetHandle(), pResManager, IntPtr.Zero, luid, IntPtr.Zero, out pClientContext ); if (f) { int bufferSize = 0; GlobalDebug.WriteLineIf(GlobalDebug.Info, "AuthZSet", "Getting info from ctx"); // Extract the group SIDs from the user's context. Determine the size of the buffer we need. f = UnsafeNativeMethods.AuthzGetInformationFromContext( pClientContext, 2, // AuthzContextInfoGroupsSids 0, out bufferSize, IntPtr.Zero ); if (!f && (bufferSize > 0) && (Marshal.GetLastWin32Error() == 122) /*ERROR_INSUFFICIENT_BUFFER*/) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "AuthZSet", "Getting info from ctx (size={0})", bufferSize); Debug.Assert(bufferSize > 0); // Set up the needed buffer pBuffer = Marshal.AllocHGlobal(bufferSize); // Extract the group SIDs from the user's context, into our buffer.0 f = UnsafeNativeMethods.AuthzGetInformationFromContext( pClientContext, 2, // AuthzContextInfoGroupsSids bufferSize, out bufferSize, pBuffer ); if (f) { // Marshall the native buffer into managed SID_AND_ATTR structures. // The native buffer holds a TOKEN_GROUPS structure: // // struct TOKEN_GROUPS { // DWORD GroupCount; // SID_AND_ATTRIBUTES Groups[ANYSIZE_ARRAY]; // }; // // Extract TOKEN_GROUPS.GroupCount UnsafeNativeMethods.TOKEN_GROUPS tokenGroups = (UnsafeNativeMethods.TOKEN_GROUPS)Marshal.PtrToStructure(pBuffer, typeof(UnsafeNativeMethods.TOKEN_GROUPS)); int groupCount = tokenGroups.groupCount; GlobalDebug.WriteLineIf(GlobalDebug.Info, "AuthZSet", "Found {0} groups", groupCount); // Extract TOKEN_GROUPS.Groups, by iterating over the array and marshalling // each native SID_AND_ATTRIBUTES into a managed SID_AND_ATTR. UnsafeNativeMethods.SID_AND_ATTR[] groups = new UnsafeNativeMethods.SID_AND_ATTR[groupCount]; IntPtr currentItem = new IntPtr(pBuffer.ToInt64() + Marshal.SizeOf(typeof(UnsafeNativeMethods.TOKEN_GROUPS)) - IntPtr.Size); for (int i = 0; i < groupCount; i++) { groups[i] = (UnsafeNativeMethods.SID_AND_ATTR)Marshal.PtrToStructure(currentItem, typeof(UnsafeNativeMethods.SID_AND_ATTR)); currentItem = new IntPtr(currentItem.ToInt64() + Marshal.SizeOf(typeof(UnsafeNativeMethods.SID_AND_ATTR))); } _groupSidList = new SidList(groups); } else { lastError = Marshal.GetLastWin32Error(); } } else { lastError = Marshal.GetLastWin32Error(); Debug.Fail("With a zero-length buffer, this should have never succeeded"); } } else { lastError = Marshal.GetLastWin32Error(); } } else { lastError = Marshal.GetLastWin32Error(); } if (!f) { GlobalDebug.WriteLineIf(GlobalDebug.Warn, "AuthZSet", "Failed to retrieve group list, {0}", lastError); throw new PrincipalOperationException( SR.Format( SR.AuthZFailedToRetrieveGroupList, lastError)); } // Save off the buffer since it still holds the native SIDs referenced by SidList _psBuffer = new SafeMemoryPtr(pBuffer); pBuffer = IntPtr.Zero; } catch (Exception e) { GlobalDebug.WriteLineIf(GlobalDebug.Error, "AuthZSet", "Caught exception {0} with message {1}", e.GetType(), e.Message); if (_psBuffer != null && !_psBuffer.IsInvalid) _psBuffer.Close(); if (_psUserSid != null && !_psUserSid.IsInvalid) _psUserSid.Close(); if (_psMachineSid != null && !_psMachineSid.IsInvalid) _psMachineSid.Close(); // We're on a platform that doesn't have the AuthZ library if (e is DllNotFoundException) throw new NotSupportedException(SR.AuthZNotSupported, e); if (e is EntryPointNotFoundException) throw new NotSupportedException(SR.AuthZNotSupported, e); throw; } finally { if (pClientContext != IntPtr.Zero) UnsafeNativeMethods.AuthzFreeContext(pClientContext); if (pResManager != IntPtr.Zero) UnsafeNativeMethods.AuthzFreeResourceManager(pResManager); if (pBuffer != IntPtr.Zero) Marshal.FreeHGlobal(pBuffer); } } override internal object CurrentAsPrincipal { get { Debug.Assert(_currentGroup >= 0 && _currentGroup < _groupSidList.Length); GlobalDebug.WriteLineIf( GlobalDebug.Info, "AuthZSet", "CurrentAsPrincipal: currentGroup={0}, list length={1}", _currentGroup, _groupSidList.Length); // Convert native SID to byte[] SID IntPtr pSid = _groupSidList[_currentGroup].pSid; byte[] sid = Utils.ConvertNativeSidToByteArray(pSid); // sidIssuerName is null only if SID was not resolved // return a fake principal back if (null == _groupSidList[_currentGroup].sidIssuerName) { string name = _groupSidList[_currentGroup].name; // Create a Principal object to represent it GroupPrincipal g = GroupPrincipal.MakeGroup(_userStoreCtx.OwningContext); g.fakePrincipal = true; g.LoadValueIntoProperty(PropertyNames.PrincipalDisplayName, name); g.LoadValueIntoProperty(PropertyNames.PrincipalName, name); SecurityIdentifier sidObj = new SecurityIdentifier(Utils.ConvertSidToSDDL(sid)); g.LoadValueIntoProperty(PropertyNames.PrincipalSid, sidObj); g.LoadValueIntoProperty(PropertyNames.GroupIsSecurityGroup, true); return g; } GroupPrincipal group = null; // Classify the SID SidType sidType = Utils.ClassifySID(pSid); // It's a fake principal. Construct and respond the corresponding fake Principal object. if (sidType == SidType.FakeObject) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "AuthZSet", "CurrentAsPrincipal: fake principal {0}", Utils.ByteArrayToString(sid)); return _userStoreCtx.ConstructFakePrincipalFromSID(sid); } // Try to figure out who issued the SID string sidIssuerName = null; if (sidType == SidType.RealObjectFakeDomain) { // BUILTIN principal --> issuer is the same authority as the user's SID GlobalDebug.WriteLineIf(GlobalDebug.Info, "AuthZSet", "CurrentAsPrincipal: builtin principal {0}", Utils.ByteArrayToString(sid)); sidIssuerName = _flatUserAuthority; } else { GlobalDebug.WriteLineIf(GlobalDebug.Info, "AuthZSet", "CurrentAsPrincipal: real principal {0}", Utils.ByteArrayToString(sid)); // Is the SID from the same domain as the user? bool sameDomain = false; bool success = UnsafeNativeMethods.EqualDomainSid(_psUserSid.DangerousGetHandle(), pSid, ref sameDomain); // if failed, psUserSid must not be a domain sid if (!success) { #if !SUPPORT_WK_USER_OBJS Debug.Fail("AuthZSet.CurrentAsPrincipal: hit a user with a non-domain SID"); #endif // SUPPORT_WK_USER_OBJS sameDomain = false; } // same domain --> issuer is the same authority as the user's SID if (sameDomain) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "AuthZSet", "CurrentAsPrincipal: same domain as user ({0})", _flatUserAuthority); sidIssuerName = _flatUserAuthority; } } // The SID comes from another domain. Use the domain name that the OS resolved the SID to. if (sidIssuerName == null) { sidIssuerName = _groupSidList[_currentGroup].sidIssuerName; GlobalDebug.WriteLineIf(GlobalDebug.Info, "AuthZSet", "CurrentAsPrincipal: different domain ({0}) than user ({1})", sidIssuerName, _flatUserAuthority); } Debug.Assert(sidIssuerName != null); Debug.Assert(sidIssuerName.Length > 0); // Determine whether it's a local (WinNT) or Active Directory domain (LDAP) group bool isLocalGroup = false; if (_userType == ContextType.Machine) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "AuthZSet", "CurrentAsPrincipal: local group (user is SAM)"); // Machine local user ---> must be a local group isLocalGroup = true; } else { Debug.Assert(_userType == ContextType.Domain); // Domain user, but the group SID is from the machine domain --> must be a local group // EqualDomainSid will return false if pSid is a BUILTIN SID, but that's okay, we treat those as domain (not local) // groups for domain users. bool inMachineDomain = false; if (UnsafeNativeMethods.EqualDomainSid(_psMachineSid.DangerousGetHandle(), pSid, ref inMachineDomain)) if (inMachineDomain) { // At this point we know that the group was issued by the local machine. Now determine if this machine is // a DC. Cache the results of the read. if (!_localMachineIsDC.HasValue) { _localMachineIsDC = (bool?)Utils.IsMachineDC(null); GlobalDebug.WriteLineIf(GlobalDebug.Info, "AuthZSet", "CurrentAsPrincipal: IsLocalMachine a DC, localMachineIsDC={0}", _localMachineIsDC.Value); } isLocalGroup = !_localMachineIsDC.Value; } GlobalDebug.WriteLineIf(GlobalDebug.Info, "AuthZSet", "CurrentAsPrincipal: user is non-SAM, isLocalGroup={0}", isLocalGroup); } if (isLocalGroup) { // It's a local group, because either (1) it's a local machine user, and local users can't be a member of a domain group, // or (2) it's a domain user that's a member of a group on the local machine. Pass the default machine context options // If we initially targetted AD then those options will not be valid for the machine store. #if USE_CTX_CACHE PrincipalContext ctx = SDSCache.LocalMachine.GetContext( sidIssuerName, _credentials, DefaultContextOptions.MachineDefaultContextOption); #else PrincipalContext ctx = (PrincipalContext) this.contexts[sidIssuerName]; if (ctx == null) { // Build a PrincipalContext for the machine ctx = new PrincipalContext( ContextType.Machine, sidIssuerName, null, (this.credentials != null ? credentials.UserName : null), (this.credentials != null ? credentials.Password : null), DefaultContextOptions.MachineDefaultContextOption); this.contexts[sidIssuerName] = ctx; } #endif SecurityIdentifier sidObj = new SecurityIdentifier(sid, 0); group = GroupPrincipal.FindByIdentity(ctx, IdentityType.Sid, sidObj.ToString()); } else { Debug.Assert((_userType == ContextType.Domain) && !string.Equals(Utils.GetComputerFlatName(), sidIssuerName, StringComparison.OrdinalIgnoreCase)); // It's a domain group, because it's a domain user and the SID issuer isn't the local machine #if USE_CTX_CACHE PrincipalContext ctx = SDSCache.Domain.GetContext( sidIssuerName, _credentials, _contextOptions); #else PrincipalContext ctx = (PrincipalContext) this.contexts[sidIssuerName]; if (ctx == null) { // Determine the domain DNS name // DS_RETURN_DNS_NAME | DS_DIRECTORY_SERVICE_REQUIRED | DS_BACKGROUND_ONLY int flags = unchecked((int) (0x40000000 | 0x00000010 | 0x00000100)); UnsafeNativeMethods.DomainControllerInfo info = Utils.GetDcName(null, sidIssuerName, null, flags); // Build a PrincipalContext for the domain ctx = new PrincipalContext( ContextType.Domain, info.DomainName, null, (this.credentials != null ? credentials.UserName : null), (this.credentials != null ? credentials.Password : null), this.contextOptions); this.contexts[sidIssuerName] = ctx; } #endif // Retrieve the group. We'd normally just do a Group.FindByIdentity here, but // because the AZMan API can return "old" SIDs, we also need to check the SID // history. So we'll use the special FindPrincipalBySID method that the ADStoreCtx // exposes for that purpose. Debug.Assert(ctx.QueryCtx is ADStoreCtx); IdentityReference ir = new IdentityReference(); // convert byte sid to SDDL string. SecurityIdentifier sidObj = new SecurityIdentifier(sid, 0); ir.UrnScheme = UrnScheme.SidScheme; ir.UrnValue = sidObj.ToString(); group = (GroupPrincipal)((ADStoreCtx)ctx.QueryCtx).FindPrincipalBySID(typeof(GroupPrincipal), ir, true); } if (group == null) { GlobalDebug.WriteLineIf(GlobalDebug.Warn, "AuthZSet", "CurrentAsPrincipal: Couldn't find group {0}"); throw new NoMatchingPrincipalException(SR.AuthZCantFindGroup); } return group; } } override internal bool MoveNext() { bool needToRetry; do { needToRetry = false; _currentGroup++; if (_currentGroup >= _groupSidList.Length) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "AuthZSet", "MoveNext: ran off end of list ({0})", _groupSidList.Length); return false; } // Test for the NONE group for a local user. We recognize it by: // * we're enumerating the authz groups for a local machine user // * it's a domain sid (SidType.RealObject) for the same domain as the user // * it has the RID of the "Domain Users" group, 513 if (_userType == ContextType.Machine) { IntPtr pSid = _groupSidList[_currentGroup].pSid; bool sameDomain = false; if (Utils.ClassifySID(pSid) == SidType.RealObject && UnsafeNativeMethods.EqualDomainSid(_psUserSid.DangerousGetHandle(), pSid, ref sameDomain)) { if (sameDomain) { int lastRid = Utils.GetLastRidFromSid(pSid); if (lastRid == 513) // DOMAIN_GROUP_RID_USERS { // This is the NONE group for a local user. This isn't a real group, and // has no impact on authorization (per ColinBr). Skip it. needToRetry = true; GlobalDebug.WriteLineIf(GlobalDebug.Info, "AuthZSet", "MoveNext: found NONE group, skipping"); } } } } } while (needToRetry); return true; } override internal void Reset() { GlobalDebug.WriteLineIf(GlobalDebug.Info, "AuthZSet", "Reset"); _currentGroup = -1; } // IDisposable implementation public override void Dispose() { try { if (!_disposed) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "AuthZSet", "Dispose: disposing"); _psBuffer.Close(); _psUserSid.Close(); _psMachineSid.Close(); _disposed = true; } } finally { base.Dispose(); } } // // Private fields // // The user whose groups we're retrieving private SafeMemoryPtr _psUserSid = null; // The SID of the machine domain of the machine we're running on private SafeMemoryPtr _psMachineSid = null; // The user's StoreCtx private StoreCtx _userStoreCtx; // The user's credentials private NetCred _credentials; // The user's options private ContextOptions _contextOptions; // The ctxBase (e.g., DirectoryEntry) from the user's StoreCtx private object _userCtxBase; // The type (domain, local, etc.) of the user private ContextType _userType; // The authority's name (hostname or domainname) private string _flatUserAuthority; // The index (into this.groupSidList) of the group we're currently enumerating private int _currentGroup = -1; // The groups we're enumerating over private SidList _groupSidList; // The native TOKEN_GROUPS returned by AuthzGetInformationFromContext private SafeMemoryPtr _psBuffer = null; // Have we been disposed? private bool _disposed = false; // Maps sidIssuerName --> PrincipalContext private Hashtable _contexts = new Hashtable(); // Contains cached results if the local machine is a DC. private bool? _localMachineIsDC = null; // // Guarantees finalization of the native resources // private sealed class SafeMemoryPtr : SafeHandle { private SafeMemoryPtr() : base(IntPtr.Zero, true) { } internal SafeMemoryPtr(IntPtr handle) : base(IntPtr.Zero, true) { SetHandle(handle); } // for the critial finalizer object public override bool IsInvalid { get { return (handle == IntPtr.Zero); } } override protected bool ReleaseHandle() { if (handle != IntPtr.Zero) Marshal.FreeHGlobal(handle); return true; } } /* // // Holds the list of group SIDs. Also translates them in bulk into domain name and group name. // class SidList { public SidList(UnsafeNativeMethods.SID_AND_ATTR[] groupSidAndAttrs) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "AuthZSet", "SidList: processing {0} SIDs", groupSidAndAttrs.Length); // Build the list of SIDs to resolve int groupCount = groupSidAndAttrs.Length; IntPtr[] pGroupSids = new IntPtr[groupCount]; for(int i=0; i < groupCount; i++) { pGroupSids[i] = groupSidAndAttrs[i].pSid; } // Translate the SIDs in bulk IntPtr pOA = IntPtr.Zero; IntPtr pPolicyHandle = IntPtr.Zero; IntPtr pDomains = IntPtr.Zero; UnsafeNativeMethods.LSA_TRUST_INFORMATION[] domains; IntPtr pNames = IntPtr.Zero; UnsafeNativeMethods.LSA_TRANSLATED_NAME[] names; try { // // Get the policy handle // UnsafeNativeMethods.LSA_OBJECT_ATTRIBUTES oa = new UnsafeNativeMethods.LSA_OBJECT_ATTRIBUTES(); pOA = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(UnsafeNativeMethods.LSA_OBJECT_ATTRIBUTES))); Marshal.StructureToPtr(oa, pOA, false); int err = UnsafeNativeMethods.LsaOpenPolicy( IntPtr.Zero, pOA, 0x800, // POLICY_LOOKUP_NAMES ref pPolicyHandle); if (err != 0) { GlobalDebug.WriteLineIf(GlobalDebug.Warn, "AuthZSet", "SidList: couldn't get policy handle, err={0}", err); throw new PrincipalOperationException(SR.Format( SR.AuthZErrorEnumeratingGroups, SafeNativeMethods.LsaNtStatusToWinError(err))); } Debug.Assert(pPolicyHandle != IntPtr.Zero); // // Translate the SIDs // err = UnsafeNativeMethods.LsaLookupSids( pPolicyHandle, groupCount, pGroupSids, out pDomains, out pNames); if (err != 0) { GlobalDebug.WriteLineIf(GlobalDebug.Warn, "AuthZSet", "SidList: LsaLookupSids failed, err={0}", err); throw new PrincipalOperationException(SR.Format( SR.AuthZErrorEnumeratingGroups, SafeNativeMethods.LsaNtStatusToWinError(err))); } // // Get the group names in managed form // names = new UnsafeNativeMethods.LSA_TRANSLATED_NAME[groupCount]; IntPtr pCurrentName = pNames; for (int i=0; i < groupCount; i++) { names[i] = (UnsafeNativeMethods.LSA_TRANSLATED_NAME) Marshal.PtrToStructure(pCurrentName, typeof(UnsafeNativeMethods.LSA_TRANSLATED_NAME)); pCurrentName = new IntPtr(pCurrentName.ToInt64() + Marshal.SizeOf(typeof(UnsafeNativeMethods.LSA_TRANSLATED_NAME))); } // // Get the domain names in managed form // // Extract LSA_REFERENCED_DOMAIN_LIST.Entries int domainCount = Marshal.ReadInt32(pDomains); // Extract LSA_REFERENCED_DOMAIN_LIST.Domains, by iterating over the array and marshalling // each native LSA_TRUST_INFORMATION into a managed LSA_TRUST_INFORMATION. domains = new UnsafeNativeMethods.LSA_TRUST_INFORMATION[domainCount]; IntPtr pCurrentDomain = Marshal.ReadIntPtr(pDomains, Marshal.SizeOf(typeof(Int32))); for(int i=0; i < domainCount; i++) { domains[i] =(UnsafeNativeMethods.LSA_TRUST_INFORMATION) Marshal.PtrToStructure(pCurrentDomain, typeof(UnsafeNativeMethods.LSA_TRUST_INFORMATION)); pCurrentDomain = new IntPtr(pCurrentDomain.ToInt64() + Marshal.SizeOf(typeof(UnsafeNativeMethods.LSA_TRUST_INFORMATION))); } GlobalDebug.WriteLineIf(GlobalDebug.Info, "AuthZSet", "SidList: got {0} groups in {1} domains", groupCount, domainCount); // // Build the list of entries // Debug.Assert(names.Length == groupCount); for (int i = 0; i < names.Length; i++) { UnsafeNativeMethods.LSA_TRANSLATED_NAME name = names[i]; // Get the domain associated with this name Debug.Assert(name.domainIndex >= 0); Debug.Assert(name.domainIndex < domains.Length); UnsafeNativeMethods.LSA_TRUST_INFORMATION domain = domains[name.domainIndex]; // Build an entry. Note that LSA_UNICODE_STRING.length is in bytes, // while PtrToStringUni expects a length in characters. SidListEntry entry = new SidListEntry(); Debug.Assert(name.name.length % 2 == 0); entry.name = Marshal.PtrToStringUni(name.name.buffer, name.name.length/2); Debug.Assert(domain.name.length % 2 == 0); entry.sidIssuerName = Marshal.PtrToStringUni(domain.name.buffer, domain.name.length/2); entry.pSid = groupSidAndAttrs[i].pSid; this.entries.Add(entry); } } finally { if (pDomains != IntPtr.Zero) UnsafeNativeMethods.LsaFreeMemory(pDomains); if (pNames != IntPtr.Zero) UnsafeNativeMethods.LsaFreeMemory(pNames); if (pPolicyHandle != IntPtr.Zero) UnsafeNativeMethods.LsaClose(pPolicyHandle); if (pOA != IntPtr.Zero) Marshal.FreeHGlobal(pOA); } } List<SidListEntry> entries = new List<SidListEntry>(); public SidListEntry this[int index] { get { return this.entries[index]; } } public int Length { get { return this.entries.Count; } } } class SidListEntry { public IntPtr pSid; public string name; public string sidIssuerName; } */ } }
// 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.Globalization; using System.Linq; using System.Threading; using System.Threading.Tasks; using System.Reflection; using Microsoft.CodeAnalysis; using Roslyn.Utilities; using Microsoft.CodeAnalysis.Scripting.Hosting; namespace Microsoft.CodeAnalysis.Scripting { /// <summary> /// A class that represents a script that you can run. /// /// Create a script using a language specific script class such as CSharpScript or VisualBasicScript. /// </summary> public abstract class Script { internal readonly ScriptCompiler Compiler; internal readonly ScriptBuilder Builder; private Compilation _lazyCompilation; internal Script(ScriptCompiler compiler, ScriptBuilder builder, string code, ScriptOptions options, Type globalsTypeOpt, Script previousOpt) { Debug.Assert(code != null); Debug.Assert(options != null); Debug.Assert(compiler != null); Debug.Assert(builder != null); Compiler = compiler; Builder = builder; Previous = previousOpt; Code = code; Options = options; GlobalsType = globalsTypeOpt; } internal static Script<T> CreateInitialScript<T>(ScriptCompiler compiler, string codeOpt, ScriptOptions optionsOpt, Type globalsTypeOpt, InteractiveAssemblyLoader assemblyLoaderOpt) { return new Script<T>(compiler, new ScriptBuilder(assemblyLoaderOpt ?? new InteractiveAssemblyLoader()), codeOpt ?? "", optionsOpt ?? ScriptOptions.Default, globalsTypeOpt, previousOpt: null); } /// <summary> /// A script that will run first when this script is run. /// Any declarations made in the previous script can be referenced in this script. /// The end state from running this script includes all declarations made by both scripts. /// </summary> public Script Previous { get; } /// <summary> /// The options used by this script. /// </summary> public ScriptOptions Options { get; } /// <summary> /// The source code of the script. /// </summary> public string Code { get; } /// <summary> /// The type of an object whose members can be accessed by the script as global variables. /// </summary> public Type GlobalsType { get; } /// <summary> /// The expected return type of the script. /// </summary> public abstract Type ReturnType { get; } /// <summary> /// Creates a new version of this script with the specified options. /// </summary> public Script WithOptions(ScriptOptions options) => WithOptionsInternal(options); internal abstract Script WithOptionsInternal(ScriptOptions options); /// <summary> /// Continues the script with given code snippet. /// </summary> public Script<object> ContinueWith(string code, ScriptOptions options = null) => ContinueWith<object>(code, options); /// <summary> /// Continues the script with given code snippet. /// </summary> public Script<TResult> ContinueWith<TResult>(string code, ScriptOptions options = null) => new Script<TResult>(Compiler, Builder, code ?? "", options ?? Options, GlobalsType, this); /// <summary> /// Get's the <see cref="Compilation"/> that represents the semantics of the script. /// </summary> public Compilation GetCompilation() { if (_lazyCompilation == null) { var compilation = Compiler.CreateSubmission(this); Interlocked.CompareExchange(ref _lazyCompilation, compilation, null); } return _lazyCompilation; } /// <summary> /// Runs the script from the beginning and returns the result of the last code snippet. /// </summary> /// <param name="globals"> /// An instance of <see cref="Script.GlobalsType"/> holding on values of global variables accessible from the script. /// Must be specified if and only if the script was created with a <see cref="Script.GlobalsType"/>. /// </param> /// <param name="cancellationToken">Cancellation token.</param> /// <returns>The result of the last code snippet.</returns> internal Task<object> EvaluateAsync(object globals = null, CancellationToken cancellationToken = default(CancellationToken)) => CommonEvaluateAsync(globals, cancellationToken); internal abstract Task<object> CommonEvaluateAsync(object globals, CancellationToken cancellationToken); /// <summary> /// Runs the script from the beginning. /// </summary> /// <param name="globals"> /// An instance of <see cref="Script.GlobalsType"/> holding on values for global variables accessible from the script. /// Must be specified if and only if the script was created with <see cref="Script.GlobalsType"/>. /// </param> /// <param name="cancellationToken">Cancellation token.</param> /// <returns>A <see cref="ScriptState"/> that represents the state after running the script, including all declared variables and return value.</returns> public Task<ScriptState> RunAsync(object globals = null, CancellationToken cancellationToken = default(CancellationToken)) => CommonRunAsync(globals, cancellationToken); internal abstract Task<ScriptState> CommonRunAsync(object globals, CancellationToken cancellationToken); /// <summary> /// Continue script execution from the specified state. /// </summary> /// <param name="previousState"> /// Previous state of the script execution. /// </param> /// <param name="cancellationToken">Cancellation token.</param> /// <returns>A <see cref="ScriptState"/> that represents the state after running the script, including all declared variables and return value.</returns> internal Task<ScriptState> ContinueAsync(ScriptState previousState, CancellationToken cancellationToken = default(CancellationToken)) => CommonContinueAsync(previousState, cancellationToken); internal abstract Task<ScriptState> CommonContinueAsync(ScriptState previousState, CancellationToken cancellationToken); /// <summary> /// Forces the script through the compilation step. /// If not called directly, the compilation step will occur on the first call to Run. /// </summary> public ImmutableArray<Diagnostic> Compile(CancellationToken cancellationToken = default(CancellationToken)) => CommonCompile(cancellationToken); internal abstract ImmutableArray<Diagnostic> CommonCompile(CancellationToken cancellationToken); internal abstract Func<object[], Task> CommonGetExecutor(CancellationToken cancellationToken); // Apply recursive alias <host> to the host assembly reference, so that we hide its namespaces and global types behind it. internal static readonly MetadataReferenceProperties HostAssemblyReferenceProperties = MetadataReferenceProperties.Assembly.WithAliases(ImmutableArray.Create("<host>")).WithRecursiveAliases(true); /// <summary> /// Gets the references that need to be assigned to the compilation. /// This can be different than the list of references defined by the <see cref="ScriptOptions"/> instance. /// </summary> internal ImmutableArray<MetadataReference> GetReferencesForCompilation( CommonMessageProvider messageProvider, DiagnosticBag diagnostics, MetadataReference languageRuntimeReferenceOpt = null) { var resolver = Options.MetadataResolver; var references = ArrayBuilder<MetadataReference>.GetInstance(); try { var previous = Previous; if (previous != null) { // TODO: this should be done in reference manager references.AddRange(previous.GetCompilation().References); } else { var corLib = MetadataReference.CreateFromAssemblyInternal(typeof(object).GetTypeInfo().Assembly); references.Add(corLib); if (GlobalsType != null) { var globalsAssembly = GlobalsType.GetTypeInfo().Assembly; // If the assembly doesn't have metadata (it's an in-memory or dynamic assembly), // the host has to add reference to the metadata where globals type is located explicitly. if (MetadataReference.HasMetadata(globalsAssembly)) { references.Add(MetadataReference.CreateFromAssemblyInternal(globalsAssembly, HostAssemblyReferenceProperties)); } } if (languageRuntimeReferenceOpt != null) { references.Add(languageRuntimeReferenceOpt); } } foreach (var reference in Options.MetadataReferences) { var unresolved = reference as UnresolvedMetadataReference; if (unresolved != null) { var resolved = resolver.ResolveReference(unresolved.Reference, null, unresolved.Properties); if (resolved.IsDefault) { diagnostics.Add(messageProvider.CreateDiagnostic(messageProvider.ERR_MetadataFileNotFound, Location.None, unresolved.Reference)); } else { references.AddRange(resolved); } } else { references.Add(reference); } } return references.ToImmutable(); } finally { references.Free(); } } // TODO: remove internal bool HasReturnValue() { return GetCompilation().HasSubmissionResult(); } } public sealed class Script<T> : Script { private ImmutableArray<Func<object[], Task>> _lazyPrecedingExecutors; private Func<object[], Task<T>> _lazyExecutor; internal Script(ScriptCompiler compiler, ScriptBuilder builder, string code, ScriptOptions options, Type globalsTypeOpt, Script previousOpt) : base(compiler, builder, code, options, globalsTypeOpt, previousOpt) { } public override Type ReturnType => typeof(T); public new Script<T> WithOptions(ScriptOptions options) { return (options == Options) ? this : new Script<T>(Compiler, Builder, Code, options, GlobalsType, Previous); } internal override Script WithOptionsInternal(ScriptOptions options) => WithOptions(options); internal override ImmutableArray<Diagnostic> CommonCompile(CancellationToken cancellationToken) { // TODO: avoid throwing exception, report all diagnostics https://github.com/dotnet/roslyn/issues/5949 try { GetPrecedingExecutors(cancellationToken); GetExecutor(cancellationToken); return ImmutableArray.CreateRange(GetCompilation().GetDiagnostics(cancellationToken).Where(d => d.Severity == DiagnosticSeverity.Warning)); } catch (CompilationErrorException e) { return ImmutableArray.CreateRange(e.Diagnostics.Where(d => d.Severity == DiagnosticSeverity.Error || d.Severity == DiagnosticSeverity.Warning)); } } internal override Func<object[], Task> CommonGetExecutor(CancellationToken cancellationToken) => GetExecutor(cancellationToken); internal override Task<object> CommonEvaluateAsync(object globals, CancellationToken cancellationToken) => EvaluateAsync(globals, cancellationToken).CastAsync<T, object>(); internal override Task<ScriptState> CommonRunAsync(object globals, CancellationToken cancellationToken) => RunAsync(globals, cancellationToken).CastAsync<ScriptState<T>, ScriptState>(); internal override Task<ScriptState> CommonContinueAsync(ScriptState previousState, CancellationToken cancellationToken) => ContinueAsync(previousState, cancellationToken).CastAsync<ScriptState<T>, ScriptState>(); /// <exception cref="CompilationErrorException">Compilation has errors.</exception> private Func<object[], Task<T>> GetExecutor(CancellationToken cancellationToken) { if (_lazyExecutor == null) { Interlocked.CompareExchange(ref _lazyExecutor, Builder.CreateExecutor<T>(Compiler, GetCompilation(), cancellationToken), null); } return _lazyExecutor; } /// <exception cref="CompilationErrorException">Compilation has errors.</exception> private ImmutableArray<Func<object[], Task>> GetPrecedingExecutors(CancellationToken cancellationToken) { if (_lazyPrecedingExecutors.IsDefault) { var preceding = TryGetPrecedingExecutors(null, cancellationToken); Debug.Assert(!preceding.IsDefault); InterlockedOperations.Initialize(ref _lazyPrecedingExecutors, preceding); } return _lazyPrecedingExecutors; } /// <exception cref="CompilationErrorException">Compilation has errors.</exception> private ImmutableArray<Func<object[], Task>> TryGetPrecedingExecutors(Script lastExecutedScriptInChainOpt, CancellationToken cancellationToken) { Script script = Previous; if (script == lastExecutedScriptInChainOpt) { return ImmutableArray<Func<object[], Task>>.Empty; } var scriptsReversed = ArrayBuilder<Script>.GetInstance(); while (script != null && script != lastExecutedScriptInChainOpt) { scriptsReversed.Add(script); script = script.Previous; } if (lastExecutedScriptInChainOpt != null && script != lastExecutedScriptInChainOpt) { scriptsReversed.Free(); return default(ImmutableArray<Func<object[], Task>>); } var executors = ArrayBuilder<Func<object[], Task>>.GetInstance(scriptsReversed.Count); // We need to build executors in the order in which they are chained, // so that assemblies created for the submissions are loaded in the correct order. for (int i = scriptsReversed.Count - 1; i >= 0; i--) { executors.Add(scriptsReversed[i].CommonGetExecutor(cancellationToken)); } return executors.ToImmutableAndFree(); } /// <summary> /// Runs the script from the beginning and returns the result of the last code snippet. /// </summary> /// <param name="globals"> /// An instance of <see cref="Script.GlobalsType"/> holding on values of global variables accessible from the script. /// Must be specified if and only if the script was created with a <see cref="Script.GlobalsType"/>. /// </param> /// <param name="cancellationToken">Cancellation token.</param> /// <returns>The result of the last code snippet.</returns> internal new Task<T> EvaluateAsync(object globals = null, CancellationToken cancellationToken = default(CancellationToken)) => RunAsync(globals, cancellationToken).GetEvaluationResultAsync(); /// <summary> /// Runs the script from the beginning. /// </summary> /// <param name="globals"> /// An instance of <see cref="Script.GlobalsType"/> holding on values for global variables accessible from the script. /// Must be specified if and only if the script was created with <see cref="Script.GlobalsType"/>. /// </param> /// <param name="cancellationToken">Cancellation token.</param> /// <returns>A <see cref="ScriptState"/> that represents the state after running the script, including all declared variables and return value.</returns> /// <exception cref="CompilationErrorException">Compilation has errors.</exception> /// <exception cref="ArgumentException">The type of <paramref name="globals"/> doesn't match <see cref="Script.GlobalsType"/>.</exception> public new Task<ScriptState<T>> RunAsync(object globals = null, CancellationToken cancellationToken = default(CancellationToken)) { // The following validation and executor construction may throw; // do so synchronously so that the exception is not wrapped in the task. ValidateGlobals(globals, GlobalsType); var executionState = ScriptExecutionState.Create(globals); var precedingExecutors = GetPrecedingExecutors(cancellationToken); var currentExecutor = GetExecutor(cancellationToken); return RunSubmissionsAsync(executionState, precedingExecutors, currentExecutor, cancellationToken); } /// <summary> /// Creates a delegate that will run this script from the beginning when invoked. /// </summary> /// <remarks> /// The delegate doesn't hold on this script or its compilation. /// </remarks> public ScriptRunner<T> CreateDelegate(CancellationToken cancellationToken = default(CancellationToken)) { var precedingExecutors = GetPrecedingExecutors(cancellationToken); var currentExecutor = GetExecutor(cancellationToken); var globalsType = GlobalsType; return (globals, token) => { ValidateGlobals(globals, globalsType); return ScriptExecutionState.Create(globals).RunSubmissionsAsync<T>(precedingExecutors, currentExecutor, token); }; } /// <summary> /// Continue script execution from the specified state. /// </summary> /// <param name="previousState"> /// Previous state of the script execution. /// </param> /// <param name="cancellationToken">Cancellation token.</param> /// <returns>A <see cref="ScriptState"/> that represents the state after running the script, including all declared variables and return value.</returns> /// <exception cref="ArgumentNullException"><paramref name="previousState"/> is null.</exception> /// <exception cref="ArgumentException"><paramref name="previousState"/> is not a previous execution state of this script.</exception> internal new Task<ScriptState<T>> ContinueAsync(ScriptState previousState, CancellationToken cancellationToken = default(CancellationToken)) { // The following validation and executor construction may throw; // do so synchronously so that the exception is not wrapped in the task. if (previousState == null) { throw new ArgumentNullException(nameof(previousState)); } if (previousState.Script == this) { // this state is already the output of running this script. return Task.FromResult((ScriptState<T>)previousState); } var precedingExecutors = TryGetPrecedingExecutors(previousState.Script, cancellationToken); if (precedingExecutors.IsDefault) { throw new ArgumentException(ScriptingResources.StartingStateIncompatible, nameof(previousState)); } var currentExecutor = GetExecutor(cancellationToken); ScriptExecutionState newExecutionState = previousState.ExecutionState.FreezeAndClone(); return RunSubmissionsAsync(newExecutionState, precedingExecutors, currentExecutor, cancellationToken); } private async Task<ScriptState<T>> RunSubmissionsAsync(ScriptExecutionState executionState, ImmutableArray<Func<object[], Task>> precedingExecutors, Func<object[], Task> currentExecutor, CancellationToken cancellationToken) { var result = await executionState.RunSubmissionsAsync<T>(precedingExecutors, currentExecutor, cancellationToken).ConfigureAwait(continueOnCapturedContext: true); return new ScriptState<T>(executionState, result, this); } private static void ValidateGlobals(object globals, Type globalsType) { if (globalsType != null) { if (globals == null) { throw new ArgumentException(ScriptingResources.ScriptRequiresGlobalVariables, nameof(globals)); } var runtimeType = globals.GetType().GetTypeInfo(); var globalsTypeInfo = globalsType.GetTypeInfo(); if (!globalsTypeInfo.IsAssignableFrom(runtimeType)) { throw new ArgumentException(string.Format(ScriptingResources.GlobalsNotAssignable, runtimeType, globalsTypeInfo), nameof(globals)); } } else if (globals != null) { throw new ArgumentException(ScriptingResources.GlobalVariablesWithoutGlobalType, nameof(globals)); } } } }
using System; using System.Windows.Forms; using System.Drawing; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; namespace xDockPanel { public class DockContentHandler : IDisposable, IDockDragSource { public DockContentHandler(Form form) { if (!(form is IDockContent)) throw new Exception(); m_form = form; m_events = new EventHandlerList(); Form.Disposed +=new EventHandler(Form_Disposed); Form.TextChanged += new EventHandler(Form_TextChanged); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (disposing) { DockPanel = null; if (m_autoHideTab != null) m_autoHideTab.Dispose(); if (m_tab != null) m_tab.Dispose(); Form.Disposed -= new EventHandler(Form_Disposed); Form.TextChanged -= new EventHandler(Form_TextChanged); m_events.Dispose(); } } private Form m_form; public Form Form { get { return m_form; } } public IDockContent Content { get { return Form as IDockContent; } } private IDockContent m_previousActive = null; public IDockContent PreviousActive { get { return m_previousActive; } internal set { m_previousActive = value; } } private IDockContent m_nextActive = null; public IDockContent NextActive { get { return m_nextActive; } internal set { m_nextActive = value; } } private EventHandlerList m_events; private EventHandlerList Events { get { return m_events; } } private double m_autoHidePortion = 0.25; public double AutoHidePortion { get { return m_autoHidePortion; } set { if (value <= 0) return; if (m_autoHidePortion == value) return; m_autoHidePortion = value; if (DockPanel == null) return; if (DockPanel.ActiveAutoHideContent == Content) DockPanel.PerformLayout(); } } private bool m_closeButton = true; public bool CloseButton { get { return m_closeButton; } set { if (m_closeButton == value) return; m_closeButton = value; if (Pane != null) if (Pane.ActiveContent.DockHandler == this) Pane.RefreshChanges(); } } private bool m_closeButtonVisible = true; /// <summary> /// Determines whether the close button is visible on the content /// </summary> public bool CloseButtonVisible { get { return m_closeButtonVisible; } set { m_closeButtonVisible = value; } } private DockState DefaultDockState { get { if (ShowHint != DockState.Unknown && ShowHint != DockState.Hidden) return ShowHint; if ((DockAreas & DockAreas.Document) != 0) return DockState.Document; if ((DockAreas & DockAreas.Right) != 0) return DockState.Right; if ((DockAreas & DockAreas.Left) != 0) return DockState.Left; if ((DockAreas & DockAreas.Bottom) != 0) return DockState.Bottom; if ((DockAreas & DockAreas.Top) != 0) return DockState.Top; return DockState.Unknown; } } private DockState DefaultShowState { get { if (ShowHint != DockState.Unknown) return ShowHint; if ((DockAreas & DockAreas.Document) != 0) return DockState.Document; if ((DockAreas & DockAreas.Right) != 0) return DockState.Right; if ((DockAreas & DockAreas.Left) != 0) return DockState.Left; if ((DockAreas & DockAreas.Bottom) != 0) return DockState.Bottom; if ((DockAreas & DockAreas.Top) != 0) return DockState.Top; if ((DockAreas & DockAreas.Float) != 0) return DockState.Float; return DockState.Unknown; } } private DockAreas m_allowedAreas = DockAreas.Left | DockAreas.Right | DockAreas.Top | DockAreas.Bottom | DockAreas.Document | DockAreas.Float; public DockAreas DockAreas { get { return m_allowedAreas; } set { if (m_allowedAreas == value) return; if (!DockHelper.IsDockValid(DockState, value)) return; m_allowedAreas = value; if (!DockHelper.IsDockValid(ShowHint, m_allowedAreas)) ShowHint = DockState.Unknown; } } private DockState m_dockState = DockState.Unknown; public DockState DockState { get { return m_dockState; } set { if (m_dockState == value) return; DockPanel.SuspendLayout(true); if (value == DockState.Hidden) IsHidden = true; else SetDockState(false, value, Pane); DockPanel.ResumeLayout(true, true); } } private DockPanel m_dockPanel = null; public DockPanel DockPanel { get { return m_dockPanel; } set { if (m_dockPanel == value) return; Pane = null; if (m_dockPanel != null) m_dockPanel.RemoveContent(Content); if (m_tab != null) { m_tab.Dispose(); m_tab = null; } if (m_autoHideTab != null) { m_autoHideTab.Dispose(); m_autoHideTab = null; } m_dockPanel = value; if (m_dockPanel != null) { m_dockPanel.AddContent(Content); Form.TopLevel = false; Form.FormBorderStyle = FormBorderStyle.None; Form.ShowInTaskbar = false; Form.WindowState = FormWindowState.Normal; NativeMethods.SetWindowPos(Form.Handle, IntPtr.Zero, 0, 0, 0, 0, Win32.FlagsSetWindowPos.SWP_NOACTIVATE | Win32.FlagsSetWindowPos.SWP_NOMOVE | Win32.FlagsSetWindowPos.SWP_NOSIZE | Win32.FlagsSetWindowPos.SWP_NOZORDER | Win32.FlagsSetWindowPos.SWP_NOOWNERZORDER | Win32.FlagsSetWindowPos.SWP_FRAMECHANGED); } } } public Icon Icon { get { return Form.Icon; } } public DockPane Pane { get { return IsFloat ? FloatPane : PanelPane; } set { if (Pane == value) return; DockPanel.SuspendLayout(true); DockPane oldPane = Pane; SuspendSetDockState(); FloatPane = (value == null ? null : (value.IsFloat ? value : FloatPane)); PanelPane = (value == null ? null : (value.IsFloat ? PanelPane : value)); ResumeSetDockState(IsHidden, value != null ? value.DockState : DockState.Unknown, oldPane); DockPanel.ResumeLayout(true, true); } } private bool m_isHidden = true; public bool IsHidden { get { return m_isHidden; } set { if (m_isHidden == value) return; SetDockState(value, VisibleState, Pane); } } private string m_tabText = null; public string TabText { get { return m_tabText == null || m_tabText == "" ? Form.Text : m_tabText; } set { if (m_tabText == value) return; m_tabText = value; if (Pane != null) Pane.RefreshChanges(); } } private DockState m_visibleState = DockState.Unknown; public DockState VisibleState { get { return m_visibleState; } set { if (m_visibleState == value) return; SetDockState(IsHidden, value, Pane); } } private bool m_isFloat = false; public bool IsFloat { get { return m_isFloat; } set { if (m_isFloat == value) return; DockState visibleState = CheckDockState(value); if (visibleState == DockState.Unknown) return; SetDockState(IsHidden, visibleState, Pane); } } [SuppressMessage("Microsoft.Naming", "CA1720:AvoidTypeNamesInParameters")] public DockState CheckDockState(bool isFloat) { DockState dockState; if (isFloat) { if (!IsDockStateValid(DockState.Float)) dockState = DockState.Unknown; else dockState = DockState.Float; } else { dockState = (PanelPane != null) ? PanelPane.DockState : DefaultDockState; if (dockState != DockState.Unknown && !IsDockStateValid(dockState)) dockState = DockState.Unknown; } return dockState; } private DockPane m_panelPane = null; public DockPane PanelPane { get { return m_panelPane; } set { if (m_panelPane == value) return; if (value != null) { if (value.IsFloat || value.DockPanel != DockPanel) return; } DockPane oldPane = Pane; if (m_panelPane != null) RemoveFromPane(m_panelPane); m_panelPane = value; if (m_panelPane != null) { m_panelPane.AddContent(Content); SetDockState(IsHidden, IsFloat ? DockState.Float : m_panelPane.DockState, oldPane); } else SetDockState(IsHidden, DockState.Unknown, oldPane); } } private void RemoveFromPane(DockPane pane) { pane.RemoveContent(Content); SetPane(null); if (pane.Contents.Count == 0) pane.Dispose(); } private DockPane m_floatPane = null; public DockPane FloatPane { get { return m_floatPane; } set { if (m_floatPane == value) return; if (value != null) { if (!value.IsFloat || value.DockPanel != DockPanel) return; } DockPane oldPane = Pane; if (m_floatPane != null) RemoveFromPane(m_floatPane); m_floatPane = value; if (m_floatPane != null) { m_floatPane.AddContent(Content); SetDockState(IsHidden, IsFloat ? DockState.Float : VisibleState, oldPane); } else SetDockState(IsHidden, DockState.Unknown, oldPane); } } private int m_countSetDockState = 0; private void SuspendSetDockState() { m_countSetDockState ++; } private void ResumeSetDockState() { m_countSetDockState --; if (m_countSetDockState < 0) m_countSetDockState = 0; } internal bool IsSuspendSetDockState { get { return m_countSetDockState != 0; } } private void ResumeSetDockState(bool isHidden, DockState visibleState, DockPane oldPane) { ResumeSetDockState(); SetDockState(isHidden, visibleState, oldPane); } internal void SetDockState(bool isHidden, DockState visibleState, DockPane oldPane) { if (IsSuspendSetDockState) return; if (DockPanel == null && visibleState != DockState.Unknown) return; if (visibleState == DockState.Hidden || (visibleState != DockState.Unknown && !IsDockStateValid(visibleState))) return; DockPanel dockPanel = DockPanel; if (dockPanel != null) dockPanel.SuspendLayout(true); SuspendSetDockState(); DockState oldDockState = DockState; if (m_isHidden != isHidden || oldDockState == DockState.Unknown) { m_isHidden = isHidden; } m_visibleState = visibleState; m_dockState = isHidden ? DockState.Hidden : visibleState; if (visibleState == DockState.Unknown) Pane = null; else { m_isFloat = (m_visibleState == DockState.Float); if (Pane == null) Pane = DockPanel.DockPaneFactory.CreateDockPane(Content, visibleState, true); else if (Pane.DockState != visibleState) { if (Pane.Contents.Count == 1) Pane.SetDockState(visibleState); else Pane = DockPanel.DockPaneFactory.CreateDockPane(Content, visibleState, true); } } if (Form.ContainsFocus) if (DockState == DockState.Hidden || DockState == DockState.Unknown) DockPanel.ContentFocusManager.GiveUpFocus(Content); SetPaneAndVisible(Pane); if (oldPane != null && !oldPane.IsDisposed && oldDockState == oldPane.DockState) RefreshDockPane(oldPane); if (Pane != null && DockState == Pane.DockState) { if ((Pane != oldPane) || (Pane == oldPane && oldDockState != oldPane.DockState)) // Avoid early refresh of hidden AutoHide panes if ((Pane.DockWindow == null || Pane.DockWindow.Visible || Pane.IsHidden) && !Pane.IsAutoHide) RefreshDockPane(Pane); } if (oldDockState != DockState) { if (DockState == DockState.Hidden || DockState == DockState.Unknown || DockHelper.IsDockAutoHide(DockState)) DockPanel.ContentFocusManager.RemoveFromList(Content); else DockPanel.ContentFocusManager.AddToList(Content); ResetAutoHidePortion(oldDockState, DockState); OnDockStateChanged(EventArgs.Empty); } ResumeSetDockState(); if (dockPanel != null) dockPanel.ResumeLayout(true, true); } private void ResetAutoHidePortion(DockState oldState, DockState newState) { if (oldState == newState || DockHelper.ToggleAutoHideState(oldState) == newState) return; switch (newState) { case DockState.Top: case DockState.AutoHideTop: AutoHidePortion = DockPanel.DockTopPortion; break; case DockState.Left: case DockState.AutoHideLeft: AutoHidePortion = DockPanel.DockLeftPortion; break; case DockState.Bottom: case DockState.AutoHideBottom: AutoHidePortion = DockPanel.DockBottomPortion; break; case DockState.Right: case DockState.AutoHideRight: AutoHidePortion = DockPanel.DockRightPortion; break; } } private static void RefreshDockPane(DockPane pane) { pane.RefreshChanges(); pane.ValidateActiveContent(); } private bool m_hideOnClose = false; public bool HideOnClose { get { return m_hideOnClose; } set { m_hideOnClose = value; } } private DockState m_showHint = DockState.Unknown; public DockState ShowHint { get { return m_showHint; } set { if (!DockHelper.IsDockValid(value, DockAreas)) return; if (m_showHint == value) return; m_showHint = value; } } private bool m_isActivated = false; public bool IsActivated { get { return m_isActivated; } internal set { if (m_isActivated == value) return; m_isActivated = value; } } public bool IsDockStateValid(DockState dockState) { return DockHelper.IsDockValid(dockState, DockAreas); } private ContextMenu m_tabPageContextMenu = null; public ContextMenu TabPageContextMenu { get { return m_tabPageContextMenu; } set { m_tabPageContextMenu = value; } } private string m_toolTipText = null; public string ToolTipText { get { return m_toolTipText; } set { m_toolTipText = value; } } public void Activate() { if (DockPanel == null) Form.Activate(); else if (Pane == null) Show(DockPanel); else { IsHidden = false; Pane.ActiveContent = Content; if (DockHelper.IsDockAutoHide(DockState)) { if (DockPanel.ActiveAutoHideContent != Content) { DockPanel.ActiveAutoHideContent = null; return; } } if (!Form.ContainsFocus) DockPanel.ContentFocusManager.Activate(Content); } } public void GiveUpFocus() { DockPanel.ContentFocusManager.GiveUpFocus(Content); } private IntPtr m_activeWindowHandle = IntPtr.Zero; internal IntPtr ActiveWindowHandle { get { return m_activeWindowHandle; } set { m_activeWindowHandle = value; } } public void Hide() { IsHidden = true; } internal void SetPaneAndVisible(DockPane pane) { SetPane(pane); SetVisible(); } private void SetPane(DockPane pane) { if (pane != null && pane.DockState == DockState.Document) { if (Form.Parent is DockPane) SetParent(null); if (Form.MdiParent != DockPanel.ParentForm) { FlagClipWindow = true; Form.MdiParent = DockPanel.ParentForm; } } else { FlagClipWindow = true; if (Form.MdiParent != null) Form.MdiParent = null; if (Form.TopLevel) Form.TopLevel = false; SetParent(pane); } } internal void SetVisible() { bool visible; if (IsHidden) visible = false; else if (Pane != null && Pane.DockState == DockState.Document) visible = true; else if (Pane != null && Pane.ActiveContent == Content) visible = true; else if (Pane != null && Pane.ActiveContent != Content) visible = false; else visible = Form.Visible; if (Form.Visible != visible) Form.Visible = visible; } private void SetParent(Control value) { if (Form.Parent == value) return; //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // Workaround of .Net Framework bug: // Change the parent of a control with focus may result in the first // MDI child form get activated. //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! bool bRestoreFocus = false; if (Form.ContainsFocus) { //Suggested as a fix for a memory leak by bugreports if (value == null && !IsFloat) DockPanel.ContentFocusManager.GiveUpFocus(this.Content); else { DockPanel.SaveFocus(); bRestoreFocus = true; } } //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Form.Parent = value; //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // Workaround of .Net Framework bug: // Change the parent of a control with focus may result in the first // MDI child form get activated. //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! if (bRestoreFocus) Activate(); //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! } public void Show() { if (DockPanel == null) Form.Show(); else Show(DockPanel); } public void Show(DockPanel dockPanel) { if (dockPanel == null) return; if (DockState == DockState.Unknown) Show(dockPanel, DefaultShowState); else Activate(); } public void Show(DockPanel dockPanel, DockState dockState) { if (dockPanel == null) return; if (dockState == DockState.Unknown || dockState == DockState.Hidden) return; dockPanel.SuspendLayout(true); DockPanel = dockPanel; if (dockState == DockState.Float && FloatPane == null) Pane = DockPanel.DockPaneFactory.CreateDockPane(Content, DockState.Float, true); else if (PanelPane == null) { DockPane paneExisting = null; foreach (DockPane pane in DockPanel.Panes) if (pane.DockState == dockState) { paneExisting = pane; break; } if (paneExisting == null) Pane = DockPanel.DockPaneFactory.CreateDockPane(Content, dockState, true); else Pane = paneExisting; } DockState = dockState; dockPanel.ResumeLayout(true, true); //we'll resume the layout before activating to ensure that the position Activate(); //and size of the form are finally processed before the form is shown } public void Show(DockPanel dockPanel, Rectangle floatWindowBounds) { if (dockPanel == null) return; dockPanel.SuspendLayout(true); DockPanel = dockPanel; if (FloatPane == null) { IsHidden = true; // to reduce the screen flicker FloatPane = DockPanel.DockPaneFactory.CreateDockPane(Content, DockState.Float, false); FloatPane.FloatWindow.StartPosition = FormStartPosition.Manual; } FloatPane.FloatWindow.Bounds = floatWindowBounds; Show(dockPanel, DockState.Float); Activate(); dockPanel.ResumeLayout(true, true); } public void Show(DockPane pane, IDockContent beforeContent) { if (pane == null) return; if (beforeContent != null && pane.Contents.IndexOf(beforeContent) == -1) return; pane.DockPanel.SuspendLayout(true); DockPanel = pane.DockPanel; Pane = pane; pane.SetContentIndex(Content, pane.Contents.IndexOf(beforeContent)); Show(); pane.DockPanel.ResumeLayout(true, true); } public void Show(DockPane previousPane, DockAlignment alignment, double proportion) { if (previousPane == null) return; if (DockHelper.IsDockAutoHide(previousPane.DockState)) return; previousPane.DockPanel.SuspendLayout(true); DockPanel = previousPane.DockPanel; DockPanel.DockPaneFactory.CreateDockPane(Content, previousPane, alignment, proportion, true); Show(); previousPane.DockPanel.ResumeLayout(true, true); } public void Close() { DockPanel dockPanel = DockPanel; if (dockPanel != null) dockPanel.SuspendLayout(true); Form.Close(); if (dockPanel != null) dockPanel.ResumeLayout(true, true); } private DockPaneStripBase.Tab m_tab = null; internal DockPaneStripBase.Tab GetTab(DockPaneStripBase dockPaneStrip) { if (m_tab == null) m_tab = dockPaneStrip.CreateTab(Content); return m_tab; } private IDisposable m_autoHideTab = null; internal IDisposable AutoHideTab { get { return m_autoHideTab; } set { m_autoHideTab = value; } } #region Events private static readonly object DockStateChangedEvent = new object(); public event EventHandler DockStateChanged { add { Events.AddHandler(DockStateChangedEvent, value); } remove { Events.RemoveHandler(DockStateChangedEvent, value); } } protected virtual void OnDockStateChanged(EventArgs e) { EventHandler handler = (EventHandler)Events[DockStateChangedEvent]; if (handler != null) handler(this, e); } #endregion private void Form_Disposed(object sender, EventArgs e) { Dispose(); } private void Form_TextChanged(object sender, EventArgs e) { if (DockHelper.IsDockAutoHide(DockState)) DockPanel.RefreshAutoHideStrip(); else if (Pane != null) { if (Pane.FloatWindow != null) Pane.FloatWindow.SetText(); Pane.RefreshChanges(); } } private bool m_flagClipWindow = false; internal bool FlagClipWindow { get { return m_flagClipWindow; } set { if (m_flagClipWindow == value) return; m_flagClipWindow = value; if (m_flagClipWindow) Form.Region = new Region(Rectangle.Empty); else Form.Region = null; } } private ContextMenuStrip m_tabPageContextMenuStrip = null; public ContextMenuStrip TabPageContextMenuStrip { get { return m_tabPageContextMenuStrip; } set { m_tabPageContextMenuStrip = value; } } #region IDockDragSource Members Control IDragSource.DragControl { get { return Form; } } bool IDockDragSource.CanDockTo(DockPane pane) { if (!IsDockStateValid(pane.DockState)) return false; if (Pane == pane && pane.DisplayingContents.Count == 1) return false; return true; } Rectangle IDockDragSource.BeginDrag(Point ptMouse) { Size size; DockPane floatPane = this.FloatPane; if (DockState == DockState.Float || floatPane == null || floatPane.FloatWindow.NestedPanes.Count != 1) size = DockPanel.DefaultFloatWindowSize; else size = floatPane.FloatWindow.Size; Point location; Rectangle rectPane = Pane.ClientRectangle; if (DockState == DockState.Document) { if (Pane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom) location = new Point(rectPane.Left, rectPane.Bottom - size.Height); else location = new Point(rectPane.Left, rectPane.Top); } else { location = new Point(rectPane.Left, rectPane.Bottom); location.Y -= size.Height; } location = Pane.PointToScreen(location); if (ptMouse.X > location.X + size.Width) location.X += ptMouse.X - (location.X + size.Width) + Measures.SplitterSize; return new Rectangle(location, size); } void IDockDragSource.EndDrag() { } public void FloatAt(Rectangle floatWindowBounds) { DockPane pane = DockPanel.DockPaneFactory.CreateDockPane(Content, floatWindowBounds, true); } public void DockTo(DockPane pane, DockStyle dockStyle, int contentIndex) { if (dockStyle == DockStyle.Fill) { bool samePane = (Pane == pane); if (!samePane) Pane = pane; if (contentIndex == -1 || !samePane) pane.SetContentIndex(Content, contentIndex); else { DockContentCollection contents = pane.Contents; int oldIndex = contents.IndexOf(Content); int newIndex = contentIndex; if (oldIndex < newIndex) { newIndex += 1; if (newIndex > contents.Count -1) newIndex = -1; } pane.SetContentIndex(Content, newIndex); } } else { DockPane paneFrom = DockPanel.DockPaneFactory.CreateDockPane(Content, pane.DockState, true); INestedPanesContainer container = pane.NestedPanesContainer; if (dockStyle == DockStyle.Left) paneFrom.DockTo(container, pane, DockAlignment.Left, 0.5); else if (dockStyle == DockStyle.Right) paneFrom.DockTo(container, pane, DockAlignment.Right, 0.5); else if (dockStyle == DockStyle.Top) paneFrom.DockTo(container, pane, DockAlignment.Top, 0.5); else if (dockStyle == DockStyle.Bottom) paneFrom.DockTo(container, pane, DockAlignment.Bottom, 0.5); paneFrom.DockState = pane.DockState; } } public void DockTo(DockPanel panel, DockStyle style) { if (panel != DockPanel) return; DockPane pane; if (style == DockStyle.Top) pane = DockPanel.DockPaneFactory.CreateDockPane(Content, DockState.Top, true); else if (style == DockStyle.Bottom) pane = DockPanel.DockPaneFactory.CreateDockPane(Content, DockState.Bottom, true); else if (style == DockStyle.Left) pane = DockPanel.DockPaneFactory.CreateDockPane(Content, DockState.Left, true); else if (style == DockStyle.Right) pane = DockPanel.DockPaneFactory.CreateDockPane(Content, DockState.Right, true); else if (style == DockStyle.Fill) pane = DockPanel.DockPaneFactory.CreateDockPane(Content, DockState.Document, true); else return; } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.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 ShiftRightLogicalInt1616() { var test = new ImmUnaryOpTest__ShiftRightLogicalInt1616(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); // Validates passing an instance member of a class works test.RunClassFldScenario(); // Validates passing the field of a local struct works test.RunStructLclFldScenario(); // Validates passing an instance member of a struct works test.RunStructFldScenario(); } 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 ImmUnaryOpTest__ShiftRightLogicalInt1616 { private struct TestStruct { public Vector256<Int16> _fld; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref testStruct._fld), ref Unsafe.As<Int16, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>()); return testStruct; } public void RunStructFldScenario(ImmUnaryOpTest__ShiftRightLogicalInt1616 testClass) { var result = Avx2.ShiftRightLogical(_fld, 16); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld, testClass._dataTable.outArrayPtr); } } private static readonly int LargestVectorSize = 32; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Int16>>() / sizeof(Int16); private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<Int16>>() / sizeof(Int16); private static Int16[] _data = new Int16[Op1ElementCount]; private static Vector256<Int16> _clsVar; private Vector256<Int16> _fld; private SimpleUnaryOpTest__DataTable<Int16, Int16> _dataTable; static ImmUnaryOpTest__ShiftRightLogicalInt1616() { for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _clsVar), ref Unsafe.As<Int16, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>()); } public ImmUnaryOpTest__ShiftRightLogicalInt1616() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _fld), ref Unsafe.As<Int16, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>()); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt16(); } _dataTable = new SimpleUnaryOpTest__DataTable<Int16, Int16>(_data, new Int16[RetElementCount], LargestVectorSize); } public bool IsSupported => Avx2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Avx2.ShiftRightLogical( Unsafe.Read<Vector256<Int16>>(_dataTable.inArrayPtr), 16 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Avx2.ShiftRightLogical( Avx.LoadVector256((Int16*)(_dataTable.inArrayPtr)), 16 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Avx2.ShiftRightLogical( Avx.LoadAlignedVector256((Int16*)(_dataTable.inArrayPtr)), 16 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Avx2).GetMethod(nameof(Avx2.ShiftRightLogical), new Type[] { typeof(Vector256<Int16>), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector256<Int16>>(_dataTable.inArrayPtr), (byte)16 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int16>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Avx2).GetMethod(nameof(Avx2.ShiftRightLogical), new Type[] { typeof(Vector256<Int16>), typeof(byte) }) .Invoke(null, new object[] { Avx.LoadVector256((Int16*)(_dataTable.inArrayPtr)), (byte)16 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int16>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Avx2).GetMethod(nameof(Avx2.ShiftRightLogical), new Type[] { typeof(Vector256<Int16>), typeof(byte) }) .Invoke(null, new object[] { Avx.LoadAlignedVector256((Int16*)(_dataTable.inArrayPtr)), (byte)16 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int16>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Avx2.ShiftRightLogical( _clsVar, 16 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var firstOp = Unsafe.Read<Vector256<Int16>>(_dataTable.inArrayPtr); var result = Avx2.ShiftRightLogical(firstOp, 16); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var firstOp = Avx.LoadVector256((Int16*)(_dataTable.inArrayPtr)); var result = Avx2.ShiftRightLogical(firstOp, 16); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var firstOp = Avx.LoadAlignedVector256((Int16*)(_dataTable.inArrayPtr)); var result = Avx2.ShiftRightLogical(firstOp, 16); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new ImmUnaryOpTest__ShiftRightLogicalInt1616(); var result = Avx2.ShiftRightLogical(test._fld, 16); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Avx2.ShiftRightLogical(_fld, 16); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld, _dataTable.outArrayPtr); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Avx2.ShiftRightLogical(test._fld, 16); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector256<Int16> firstOp, void* result, [CallerMemberName] string method = "") { Int16[] inArray = new Int16[Op1ElementCount]; Int16[] outArray = new Int16[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray[0]), firstOp); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Int16>>()); ValidateResult(inArray, outArray, method); } private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "") { Int16[] inArray = new Int16[Op1ElementCount]; Int16[] outArray = new Int16[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector256<Int16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Int16>>()); ValidateResult(inArray, outArray, method); } private void ValidateResult(Int16[] firstOp, Int16[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (0 != result[0]) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (0 != result[i]) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Avx2)}.{nameof(Avx2.ShiftRightLogical)}<Int16>(Vector256<Int16><9>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
using Microsoft.IdentityModel; using Microsoft.IdentityModel.S2S.Protocols.OAuth2; using Microsoft.IdentityModel.S2S.Tokens; using Microsoft.SharePoint.Client; using Microsoft.SharePoint.Client.EventReceivers; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Globalization; using System.IdentityModel.Selectors; using System.IdentityModel.Tokens; using System.IO; using System.Linq; using System.Net; using System.Security.Cryptography.X509Certificates; using System.Security.Principal; using System.ServiceModel; using System.Text; using System.Web; using System.Web.Configuration; using System.Web.Script.Serialization; using AudienceRestriction = Microsoft.IdentityModel.Tokens.AudienceRestriction; using AudienceUriValidationFailedException = Microsoft.IdentityModel.Tokens.AudienceUriValidationFailedException; using SecurityTokenHandlerConfiguration = Microsoft.IdentityModel.Tokens.SecurityTokenHandlerConfiguration; using X509SigningCredentials = Microsoft.IdentityModel.SecurityTokenService.X509SigningCredentials; namespace Core.SimpleTimerJob.Console { public static class TokenHelper { #region public fields /// <summary> /// SharePoint principal. /// </summary> public const string SharePointPrincipal = "00000003-0000-0ff1-ce00-000000000000"; /// <summary> /// Lifetime of HighTrust access token, 12 hours. /// </summary> public static readonly TimeSpan HighTrustAccessTokenLifetime = TimeSpan.FromHours(12.0); #endregion public fields #region public methods /// <summary> /// Retrieves the context token string from the specified request by looking for well-known parameter names in the /// POSTed form parameters and the querystring. Returns null if no context token is found. /// </summary> /// <param name="request">HttpRequest in which to look for a context token</param> /// <returns>The context token string</returns> public static string GetContextTokenFromRequest(HttpRequest request) { return GetContextTokenFromRequest(new HttpRequestWrapper(request)); } /// <summary> /// Retrieves the context token string from the specified request by looking for well-known parameter names in the /// POSTed form parameters and the querystring. Returns null if no context token is found. /// </summary> /// <param name="request">HttpRequest in which to look for a context token</param> /// <returns>The context token string</returns> public static string GetContextTokenFromRequest(HttpRequestBase request) { string[] paramNames = { "AppContext", "AppContextToken", "AccessToken", "SPAppToken" }; foreach (string paramName in paramNames) { if (!string.IsNullOrEmpty(request.Form[paramName])) { return request.Form[paramName]; } if (!string.IsNullOrEmpty(request.QueryString[paramName])) { return request.QueryString[paramName]; } } return null; } /// <summary> /// Validate that a specified context token string is intended for this application based on the parameters /// specified in web.config. Parameters used from web.config used for validation include ClientId, /// HostedAppHostNameOverride, HostedAppHostName, ClientSecret, and Realm (if it is specified). If HostedAppHostNameOverride is present, /// it will be used for validation. Otherwise, if the <paramref name="appHostName"/> is not /// null, it is used for validation instead of the web.config's HostedAppHostName. If the token is invalid, an /// exception is thrown. If the token is valid, TokenHelper's static STS metadata url is updated based on the token contents /// and a JsonWebSecurityToken based on the context token is returned. /// </summary> /// <param name="contextTokenString">The context token to validate</param> /// <param name="appHostName">The URL authority, consisting of Domain Name System (DNS) host name or IP address and the port number, to use for token audience validation. /// If null, HostedAppHostName web.config setting is used instead. HostedAppHostNameOverride web.config setting, if present, will be used /// for validation instead of <paramref name="appHostName"/> .</param> /// <returns>A JsonWebSecurityToken based on the context token.</returns> public static SharePointContextToken ReadAndValidateContextToken(string contextTokenString, string appHostName = null) { JsonWebSecurityTokenHandler tokenHandler = CreateJsonWebSecurityTokenHandler(); SecurityToken securityToken = tokenHandler.ReadToken(contextTokenString); JsonWebSecurityToken jsonToken = securityToken as JsonWebSecurityToken; SharePointContextToken token = SharePointContextToken.Create(jsonToken); string stsAuthority = (new Uri(token.SecurityTokenServiceUri)).Authority; int firstDot = stsAuthority.IndexOf('.'); GlobalEndPointPrefix = stsAuthority.Substring(0, firstDot); AcsHostUrl = stsAuthority.Substring(firstDot + 1); tokenHandler.ValidateToken(jsonToken); string[] acceptableAudiences; if (!String.IsNullOrEmpty(HostedAppHostNameOverride)) { acceptableAudiences = HostedAppHostNameOverride.Split(';'); } else if (appHostName == null) { acceptableAudiences = new[] { HostedAppHostName }; } else { acceptableAudiences = new[] { appHostName }; } bool validationSuccessful = false; string realm = Realm ?? token.Realm; foreach (var audience in acceptableAudiences) { string principal = GetFormattedPrincipal(ClientId, audience, realm); if (StringComparer.OrdinalIgnoreCase.Equals(token.Audience, principal)) { validationSuccessful = true; break; } } if (!validationSuccessful) { throw new AudienceUriValidationFailedException( String.Format(CultureInfo.CurrentCulture, "\"{0}\" is not the intended audience \"{1}\"", String.Join(";", acceptableAudiences), token.Audience)); } return token; } /// <summary> /// Retrieves an access token from ACS to call the source of the specified context token at the specified /// targetHost. The targetHost must be registered for the principal that sent the context token. /// </summary> /// <param name="contextToken">Context token issued by the intended access token audience</param> /// <param name="targetHost">Url authority of the target principal</param> /// <returns>An access token with an audience matching the context token's source</returns> public static OAuth2AccessTokenResponse GetAccessToken(SharePointContextToken contextToken, string targetHost) { string targetPrincipalName = contextToken.TargetPrincipalName; // Extract the refreshToken from the context token string refreshToken = contextToken.RefreshToken; if (String.IsNullOrEmpty(refreshToken)) { return null; } string targetRealm = Realm ?? contextToken.Realm; return GetAccessToken(refreshToken, targetPrincipalName, targetHost, targetRealm); } /// <summary> /// Uses the specified authorization code to retrieve an access token from ACS to call the specified principal /// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is /// null, the "Realm" setting in web.config will be used instead. /// </summary> /// <param name="authorizationCode">Authorization code to exchange for access token</param> /// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param> /// <param name="targetHost">Url authority of the target principal</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <param name="redirectUri">Redirect URI registerd for this app</param> /// <returns>An access token with an audience of the target principal</returns> public static OAuth2AccessTokenResponse GetAccessToken( string authorizationCode, string targetPrincipalName, string targetHost, string targetRealm, Uri redirectUri) { if (targetRealm == null) { targetRealm = Realm; } string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm); string clientId = GetFormattedPrincipal(ClientId, null, targetRealm); // Create request for token. The RedirectUri is null here. This will fail if redirect uri is registered OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithAuthorizationCode( clientId, ClientSecret, authorizationCode, redirectUri, resource); // Get token OAuth2S2SClient client = new OAuth2S2SClient(); OAuth2AccessTokenResponse oauth2Response; try { oauth2Response = client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse; } catch (WebException wex) { using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream())) { string responseText = sr.ReadToEnd(); throw new WebException(wex.Message + " - " + responseText, wex); } } return oauth2Response; } /// <summary> /// Uses the specified refresh token to retrieve an access token from ACS to call the specified principal /// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is /// null, the "Realm" setting in web.config will be used instead. /// </summary> /// <param name="refreshToken">Refresh token to exchange for access token</param> /// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param> /// <param name="targetHost">Url authority of the target principal</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <returns>An access token with an audience of the target principal</returns> public static OAuth2AccessTokenResponse GetAccessToken( string refreshToken, string targetPrincipalName, string targetHost, string targetRealm) { if (targetRealm == null) { targetRealm = Realm; } string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm); string clientId = GetFormattedPrincipal(ClientId, null, targetRealm); OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithRefreshToken(clientId, ClientSecret, refreshToken, resource); // Get token OAuth2S2SClient client = new OAuth2S2SClient(); OAuth2AccessTokenResponse oauth2Response; try { oauth2Response = client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse; } catch (WebException wex) { using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream())) { string responseText = sr.ReadToEnd(); throw new WebException(wex.Message + " - " + responseText, wex); } } return oauth2Response; } /// <summary> /// Retrieves an app-only access token from ACS to call the specified principal /// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is /// null, the "Realm" setting in web.config will be used instead. /// </summary> /// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param> /// <param name="targetHost">Url authority of the target principal</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <returns>An access token with an audience of the target principal</returns> public static OAuth2AccessTokenResponse GetAppOnlyAccessToken( string targetPrincipalName, string targetHost, string targetRealm) { if (targetRealm == null) { targetRealm = Realm; } string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm); string clientId = GetFormattedPrincipal(ClientId, HostedAppHostName, targetRealm); OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithClientCredentials(clientId, ClientSecret, resource); oauth2Request.Resource = resource; // Get token OAuth2S2SClient client = new OAuth2S2SClient(); OAuth2AccessTokenResponse oauth2Response; try { oauth2Response = client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse; } catch (WebException wex) { using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream())) { string responseText = sr.ReadToEnd(); throw new WebException(wex.Message + " - " + responseText, wex); } } return oauth2Response; } /// <summary> /// Creates a client context based on the properties of a remote event receiver /// </summary> /// <param name="properties">Properties of a remote event receiver</param> /// <returns>A ClientContext ready to call the web where the event originated</returns> public static ClientContext CreateRemoteEventReceiverClientContext(SPRemoteEventProperties properties) { Uri sharepointUrl; if (properties.ListEventProperties != null) { sharepointUrl = new Uri(properties.ListEventProperties.WebUrl); } else if (properties.ItemEventProperties != null) { sharepointUrl = new Uri(properties.ItemEventProperties.WebUrl); } else if (properties.WebEventProperties != null) { sharepointUrl = new Uri(properties.WebEventProperties.FullUrl); } else { return null; } if (IsHighTrustApp()) { return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null); } return CreateAcsClientContextForUrl(properties, sharepointUrl); } /// <summary> /// Creates a client context based on the properties of an app event /// </summary> /// <param name="properties">Properties of an app event</param> /// <param name="useAppWeb">True to target the app web, false to target the host web</param> /// <returns>A ClientContext ready to call the app web or the parent web</returns> public static ClientContext CreateAppEventClientContext(SPRemoteEventProperties properties, bool useAppWeb) { if (properties.AppEventProperties == null) { return null; } Uri sharepointUrl = useAppWeb ? properties.AppEventProperties.AppWebFullUrl : properties.AppEventProperties.HostWebFullUrl; if (IsHighTrustApp()) { return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null); } return CreateAcsClientContextForUrl(properties, sharepointUrl); } /// <summary> /// Retrieves an access token from ACS using the specified authorization code, and uses that access token to /// create a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param> /// <param name="redirectUri">Redirect URI registerd for this app</param> /// <returns>A ClientContext ready to call targetUrl with a valid access token</returns> public static ClientContext GetClientContextWithAuthorizationCode( string targetUrl, string authorizationCode, Uri redirectUri) { return GetClientContextWithAuthorizationCode(targetUrl, SharePointPrincipal, authorizationCode, GetRealmFromTargetUrl(new Uri(targetUrl)), redirectUri); } /// <summary> /// Retrieves an access token from ACS using the specified authorization code, and uses that access token to /// create a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="targetPrincipalName">Name of the target SharePoint principal</param> /// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <param name="redirectUri">Redirect URI registerd for this app</param> /// <returns>A ClientContext ready to call targetUrl with a valid access token</returns> public static ClientContext GetClientContextWithAuthorizationCode( string targetUrl, string targetPrincipalName, string authorizationCode, string targetRealm, Uri redirectUri) { Uri targetUri = new Uri(targetUrl); string accessToken = GetAccessToken(authorizationCode, targetPrincipalName, targetUri.Authority, targetRealm, redirectUri).AccessToken; return GetClientContextWithAccessToken(targetUrl, accessToken); } /// <summary> /// Uses the specified access token to create a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="accessToken">Access token to be used when calling the specified targetUrl</param> /// <returns>A ClientContext ready to call targetUrl with the specified access token</returns> public static ClientContext GetClientContextWithAccessToken(string targetUrl, string accessToken) { ClientContext clientContext = new ClientContext(targetUrl); clientContext.AuthenticationMode = ClientAuthenticationMode.Anonymous; clientContext.FormDigestHandlingEnabled = false; clientContext.ExecutingWebRequest += delegate(object oSender, WebRequestEventArgs webRequestEventArgs) { webRequestEventArgs.WebRequestExecutor.RequestHeaders["Authorization"] = "Bearer " + accessToken; }; return clientContext; } /// <summary> /// Retrieves an access token from ACS using the specified context token, and uses that access token to create /// a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="contextTokenString">Context token received from the target SharePoint site</param> /// <param name="appHostUrl">Url authority of the hosted app. If this is null, the value in the HostedAppHostName /// of web.config will be used instead</param> /// <returns>A ClientContext ready to call targetUrl with a valid access token</returns> public static ClientContext GetClientContextWithContextToken( string targetUrl, string contextTokenString, string appHostUrl) { SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, appHostUrl); Uri targetUri = new Uri(targetUrl); string accessToken = GetAccessToken(contextToken, targetUri.Authority).AccessToken; return GetClientContextWithAccessToken(targetUrl, accessToken); } /// <summary> /// Returns the SharePoint url to which the app should redirect the browser to request consent and get back /// an authorization code. /// </summary> /// <param name="contextUrl">Absolute Url of the SharePoint site</param> /// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format /// (e.g. "Web.Read Site.Write")</param> /// <returns>Url of the SharePoint site's OAuth authorization page</returns> public static string GetAuthorizationUrl(string contextUrl, string scope) { return string.Format( "{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code", EnsureTrailingSlash(contextUrl), AuthorizationPage, ClientId, scope); } /// <summary> /// Returns the SharePoint url to which the app should redirect the browser to request consent and get back /// an authorization code. /// </summary> /// <param name="contextUrl">Absolute Url of the SharePoint site</param> /// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format /// (e.g. "Web.Read Site.Write")</param> /// <param name="redirectUri">Uri to which SharePoint should redirect the browser to after consent is /// granted</param> /// <returns>Url of the SharePoint site's OAuth authorization page</returns> public static string GetAuthorizationUrl(string contextUrl, string scope, string redirectUri) { return string.Format( "{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code&redirect_uri={4}", EnsureTrailingSlash(contextUrl), AuthorizationPage, ClientId, scope, redirectUri); } /// <summary> /// Returns the SharePoint url to which the app should redirect the browser to request a new context token. /// </summary> /// <param name="contextUrl">Absolute Url of the SharePoint site</param> /// <param name="redirectUri">Uri to which SharePoint should redirect the browser to with a context token</param> /// <returns>Url of the SharePoint site's context token redirect page</returns> public static string GetAppContextTokenRequestUrl(string contextUrl, string redirectUri) { return string.Format( "{0}{1}?client_id={2}&redirect_uri={3}", EnsureTrailingSlash(contextUrl), RedirectPage, ClientId, redirectUri); } /// <summary> /// Retrieves an S2S access token signed by the application's private certificate on behalf of the specified /// WindowsIdentity and intended for the SharePoint at the targetApplicationUri. If no Realm is specified in /// web.config, an auth challenge will be issued to the targetApplicationUri to discover it. /// </summary> /// <param name="targetApplicationUri">Url of the target SharePoint site</param> /// <param name="identity">Windows identity of the user on whose behalf to create the access token</param> /// <returns>An access token with an audience of the target principal</returns> public static string GetS2SAccessTokenWithWindowsIdentity( Uri targetApplicationUri, WindowsIdentity identity) { string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm; JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null; return GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims); } /// <summary> /// Retrieves an S2S client context with an access token signed by the application's private certificate on /// behalf of the specified WindowsIdentity and intended for application at the targetApplicationUri using the /// targetRealm. If no Realm is specified in web.config, an auth challenge will be issued to the /// targetApplicationUri to discover it. /// </summary> /// <param name="targetApplicationUri">Url of the target SharePoint site</param> /// <param name="identity">Windows identity of the user on whose behalf to create the access token</param> /// <returns>A ClientContext using an access token with an audience of the target application</returns> public static ClientContext GetS2SClientContextWithWindowsIdentity( Uri targetApplicationUri, WindowsIdentity identity) { string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm; JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null; string accessToken = GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims); return GetClientContextWithAccessToken(targetApplicationUri.ToString(), accessToken); } /// <summary> /// Get authentication realm from SharePoint /// </summary> /// <param name="targetApplicationUri">Url of the target SharePoint site</param> /// <returns>String representation of the realm GUID</returns> public static string GetRealmFromTargetUrl(Uri targetApplicationUri) { WebRequest request = WebRequest.Create(targetApplicationUri + "/_vti_bin/client.svc"); request.Headers.Add("Authorization: Bearer "); try { using (request.GetResponse()) { } } catch (WebException e) { if (e.Response == null) { return null; } string bearerResponseHeader = e.Response.Headers["WWW-Authenticate"]; if (string.IsNullOrEmpty(bearerResponseHeader)) { return null; } const string bearer = "Bearer realm=\""; int bearerIndex = bearerResponseHeader.IndexOf(bearer, StringComparison.Ordinal); if (bearerIndex < 0) { return null; } int realmIndex = bearerIndex + bearer.Length; if (bearerResponseHeader.Length >= realmIndex + 36) { string targetRealm = bearerResponseHeader.Substring(realmIndex, 36); Guid realmGuid; if (Guid.TryParse(targetRealm, out realmGuid)) { return targetRealm; } } } return null; } /// <summary> /// Determines if this is a high trust app. /// </summary> /// <returns>True if this is a high trust app.</returns> public static bool IsHighTrustApp() { return SigningCredentials != null; } /// <summary> /// Ensures that the specified URL ends with '/' if it is not null or empty. /// </summary> /// <param name="url">The url.</param> /// <returns>The url ending with '/' if it is not null or empty.</returns> public static string EnsureTrailingSlash(string url) { if (!string.IsNullOrEmpty(url) && url[url.Length - 1] != '/') { return url + "/"; } return url; } #endregion #region private fields // // Configuration Constants // private const string AuthorizationPage = "_layouts/15/OAuthAuthorize.aspx"; private const string RedirectPage = "_layouts/15/AppRedirect.aspx"; private const string AcsPrincipalName = "00000001-0000-0000-c000-000000000000"; private const string AcsMetadataEndPointRelativeUrl = "metadata/json/1"; private const string S2SProtocol = "OAuth2"; private const string DelegationIssuance = "DelegationIssuance1.0"; private const string NameIdentifierClaimType = JsonWebTokenConstants.ReservedClaims.NameIdentifier; private const string TrustedForImpersonationClaimType = "trustedfordelegation"; private const string ActorTokenClaimType = JsonWebTokenConstants.ReservedClaims.ActorToken; // // Environment Constants // private static string GlobalEndPointPrefix = "accounts"; private static string AcsHostUrl = "accesscontrol.windows.net"; // // Hosted app configuration // private static readonly string ClientId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientId")) ? WebConfigurationManager.AppSettings.Get("HostedAppName") : WebConfigurationManager.AppSettings.Get("ClientId"); private static readonly string IssuerId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("IssuerId")) ? ClientId : WebConfigurationManager.AppSettings.Get("IssuerId"); private static readonly string HostedAppHostNameOverride = WebConfigurationManager.AppSettings.Get("HostedAppHostNameOverride"); private static readonly string HostedAppHostName = WebConfigurationManager.AppSettings.Get("HostedAppHostName"); private static readonly string ClientSecret = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientSecret")) ? WebConfigurationManager.AppSettings.Get("HostedAppSigningKey") : WebConfigurationManager.AppSettings.Get("ClientSecret"); private static readonly string SecondaryClientSecret = WebConfigurationManager.AppSettings.Get("SecondaryClientSecret"); private static readonly string Realm = WebConfigurationManager.AppSettings.Get("Realm"); private static readonly string ServiceNamespace = WebConfigurationManager.AppSettings.Get("Realm"); private static readonly string ClientSigningCertificatePath = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePath"); private static readonly string ClientSigningCertificatePassword = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePassword"); private static readonly X509Certificate2 ClientCertificate = (string.IsNullOrEmpty(ClientSigningCertificatePath) || string.IsNullOrEmpty(ClientSigningCertificatePassword)) ? null : new X509Certificate2(ClientSigningCertificatePath, ClientSigningCertificatePassword); private static readonly X509SigningCredentials SigningCredentials = (ClientCertificate == null) ? null : new X509SigningCredentials(ClientCertificate, SecurityAlgorithms.RsaSha256Signature, SecurityAlgorithms.Sha256Digest); #endregion #region private methods private static ClientContext CreateAcsClientContextForUrl(SPRemoteEventProperties properties, Uri sharepointUrl) { string contextTokenString = properties.ContextToken; if (String.IsNullOrEmpty(contextTokenString)) { return null; } SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, OperationContext.Current.IncomingMessageHeaders.To.Host); string accessToken = GetAccessToken(contextToken, sharepointUrl.Authority).AccessToken; return GetClientContextWithAccessToken(sharepointUrl.ToString(), accessToken); } private static string GetAcsMetadataEndpointUrl() { return Path.Combine(GetAcsGlobalEndpointUrl(), AcsMetadataEndPointRelativeUrl); } private static string GetFormattedPrincipal(string principalName, string hostName, string realm) { if (!String.IsNullOrEmpty(hostName)) { return String.Format(CultureInfo.InvariantCulture, "{0}/{1}@{2}", principalName, hostName, realm); } return String.Format(CultureInfo.InvariantCulture, "{0}@{1}", principalName, realm); } private static string GetAcsPrincipalName(string realm) { return GetFormattedPrincipal(AcsPrincipalName, new Uri(GetAcsGlobalEndpointUrl()).Host, realm); } private static string GetAcsGlobalEndpointUrl() { return String.Format(CultureInfo.InvariantCulture, "https://{0}.{1}/", GlobalEndPointPrefix, AcsHostUrl); } private static JsonWebSecurityTokenHandler CreateJsonWebSecurityTokenHandler() { JsonWebSecurityTokenHandler handler = new JsonWebSecurityTokenHandler(); handler.Configuration = new SecurityTokenHandlerConfiguration(); handler.Configuration.AudienceRestriction = new AudienceRestriction(AudienceUriMode.Never); handler.Configuration.CertificateValidator = X509CertificateValidator.None; List<byte[]> securityKeys = new List<byte[]>(); securityKeys.Add(Convert.FromBase64String(ClientSecret)); if (!string.IsNullOrEmpty(SecondaryClientSecret)) { securityKeys.Add(Convert.FromBase64String(SecondaryClientSecret)); } List<SecurityToken> securityTokens = new List<SecurityToken>(); securityTokens.Add(new MultipleSymmetricKeySecurityToken(securityKeys)); handler.Configuration.IssuerTokenResolver = SecurityTokenResolver.CreateDefaultSecurityTokenResolver( new ReadOnlyCollection<SecurityToken>(securityTokens), false); SymmetricKeyIssuerNameRegistry issuerNameRegistry = new SymmetricKeyIssuerNameRegistry(); foreach (byte[] securitykey in securityKeys) { issuerNameRegistry.AddTrustedIssuer(securitykey, GetAcsPrincipalName(ServiceNamespace)); } handler.Configuration.IssuerNameRegistry = issuerNameRegistry; return handler; } private static string GetS2SAccessTokenWithClaims( string targetApplicationHostName, string targetRealm, IEnumerable<JsonWebTokenClaim> claims) { return IssueToken( ClientId, IssuerId, targetRealm, SharePointPrincipal, targetRealm, targetApplicationHostName, true, claims, claims == null); } private static JsonWebTokenClaim[] GetClaimsWithWindowsIdentity(WindowsIdentity identity) { JsonWebTokenClaim[] claims = new JsonWebTokenClaim[] { new JsonWebTokenClaim(NameIdentifierClaimType, identity.User.Value.ToLower()), new JsonWebTokenClaim("nii", "urn:office:idp:activedirectory") }; return claims; } private static string IssueToken( string sourceApplication, string issuerApplication, string sourceRealm, string targetApplication, string targetRealm, string targetApplicationHostName, bool trustedForDelegation, IEnumerable<JsonWebTokenClaim> claims, bool appOnly = false) { if (null == SigningCredentials) { throw new InvalidOperationException("SigningCredentials was not initialized"); } #region Actor token string issuer = string.IsNullOrEmpty(sourceRealm) ? issuerApplication : string.Format("{0}@{1}", issuerApplication, sourceRealm); string nameid = string.IsNullOrEmpty(sourceRealm) ? sourceApplication : string.Format("{0}@{1}", sourceApplication, sourceRealm); string audience = string.Format("{0}/{1}@{2}", targetApplication, targetApplicationHostName, targetRealm); List<JsonWebTokenClaim> actorClaims = new List<JsonWebTokenClaim>(); actorClaims.Add(new JsonWebTokenClaim(JsonWebTokenConstants.ReservedClaims.NameIdentifier, nameid)); if (trustedForDelegation && !appOnly) { actorClaims.Add(new JsonWebTokenClaim(TrustedForImpersonationClaimType, "true")); } // Create token JsonWebSecurityToken actorToken = new JsonWebSecurityToken( issuer: issuer, audience: audience, validFrom: DateTime.UtcNow, validTo: DateTime.UtcNow.Add(HighTrustAccessTokenLifetime), signingCredentials: SigningCredentials, claims: actorClaims); string actorTokenString = new JsonWebSecurityTokenHandler().WriteTokenAsString(actorToken); if (appOnly) { // App-only token is the same as actor token for delegated case return actorTokenString; } #endregion Actor token #region Outer token List<JsonWebTokenClaim> outerClaims = null == claims ? new List<JsonWebTokenClaim>() : new List<JsonWebTokenClaim>(claims); outerClaims.Add(new JsonWebTokenClaim(ActorTokenClaimType, actorTokenString)); JsonWebSecurityToken jsonToken = new JsonWebSecurityToken( nameid, // outer token issuer should match actor token nameid audience, DateTime.UtcNow, DateTime.UtcNow.Add(HighTrustAccessTokenLifetime), outerClaims); string accessToken = new JsonWebSecurityTokenHandler().WriteTokenAsString(jsonToken); #endregion Outer token return accessToken; } #endregion #region AcsMetadataParser // This class is used to get MetaData document from the global STS endpoint. It contains // methods to parse the MetaData document and get endpoints and STS certificate. public static class AcsMetadataParser { public static X509Certificate2 GetAcsSigningCert(string realm) { JsonMetadataDocument document = GetMetadataDocument(realm); if (null != document.keys && document.keys.Count > 0) { JsonKey signingKey = document.keys[0]; if (null != signingKey && null != signingKey.keyValue) { return new X509Certificate2(Encoding.UTF8.GetBytes(signingKey.keyValue.value)); } } throw new Exception("Metadata document does not contain ACS signing certificate."); } public static string GetDelegationServiceUrl(string realm) { JsonMetadataDocument document = GetMetadataDocument(realm); JsonEndpoint delegationEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == DelegationIssuance); if (null != delegationEndpoint) { return delegationEndpoint.location; } throw new Exception("Metadata document does not contain Delegation Service endpoint Url"); } private static JsonMetadataDocument GetMetadataDocument(string realm) { string acsMetadataEndpointUrlWithRealm = String.Format(CultureInfo.InvariantCulture, "{0}?realm={1}", GetAcsMetadataEndpointUrl(), realm); byte[] acsMetadata; using (WebClient webClient = new WebClient()) { acsMetadata = webClient.DownloadData(acsMetadataEndpointUrlWithRealm); } string jsonResponseString = Encoding.UTF8.GetString(acsMetadata); JavaScriptSerializer serializer = new JavaScriptSerializer(); JsonMetadataDocument document = serializer.Deserialize<JsonMetadataDocument>(jsonResponseString); if (null == document) { throw new Exception("No metadata document found at the global endpoint " + acsMetadataEndpointUrlWithRealm); } return document; } public static string GetStsUrl(string realm) { JsonMetadataDocument document = GetMetadataDocument(realm); JsonEndpoint s2sEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == S2SProtocol); if (null != s2sEndpoint) { return s2sEndpoint.location; } throw new Exception("Metadata document does not contain STS endpoint url"); } private class JsonMetadataDocument { public string serviceName { get; set; } public List<JsonEndpoint> endpoints { get; set; } public List<JsonKey> keys { get; set; } } private class JsonEndpoint { public string location { get; set; } public string protocol { get; set; } public string usage { get; set; } } private class JsonKeyValue { public string type { get; set; } public string value { get; set; } } private class JsonKey { public string usage { get; set; } public JsonKeyValue keyValue { get; set; } } } #endregion } /// <summary> /// A JsonWebSecurityToken generated by SharePoint to authenticate to a 3rd party application and allow callbacks using a refresh token /// </summary> public class SharePointContextToken : JsonWebSecurityToken { public static SharePointContextToken Create(JsonWebSecurityToken contextToken) { return new SharePointContextToken(contextToken.Issuer, contextToken.Audience, contextToken.ValidFrom, contextToken.ValidTo, contextToken.Claims); } public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims) : base(issuer, audience, validFrom, validTo, claims) { } public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SecurityToken issuerToken, JsonWebSecurityToken actorToken) : base(issuer, audience, validFrom, validTo, claims, issuerToken, actorToken) { } public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SigningCredentials signingCredentials) : base(issuer, audience, validFrom, validTo, claims, signingCredentials) { } public string NameId { get { return GetClaimValue(this, "nameid"); } } /// <summary> /// The principal name portion of the context token's "appctxsender" claim /// </summary> public string TargetPrincipalName { get { string appctxsender = GetClaimValue(this, "appctxsender"); if (appctxsender == null) { return null; } return appctxsender.Split('@')[0]; } } /// <summary> /// The context token's "refreshtoken" claim /// </summary> public string RefreshToken { get { return GetClaimValue(this, "refreshtoken"); } } /// <summary> /// The context token's "CacheKey" claim /// </summary> public string CacheKey { get { string appctx = GetClaimValue(this, "appctx"); if (appctx == null) { return null; } ClientContext ctx = new ClientContext("http://tempuri.org"); Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx); string cacheKey = (string)dict["CacheKey"]; return cacheKey; } } /// <summary> /// The context token's "SecurityTokenServiceUri" claim /// </summary> public string SecurityTokenServiceUri { get { string appctx = GetClaimValue(this, "appctx"); if (appctx == null) { return null; } ClientContext ctx = new ClientContext("http://tempuri.org"); Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx); string securityTokenServiceUri = (string)dict["SecurityTokenServiceUri"]; return securityTokenServiceUri; } } /// <summary> /// The realm portion of the context token's "audience" claim /// </summary> public string Realm { get { string aud = Audience; if (aud == null) { return null; } string tokenRealm = aud.Substring(aud.IndexOf('@') + 1); return tokenRealm; } } private static string GetClaimValue(JsonWebSecurityToken token, string claimType) { if (token == null) { throw new ArgumentNullException("token"); } foreach (JsonWebTokenClaim claim in token.Claims) { if (StringComparer.Ordinal.Equals(claim.ClaimType, claimType)) { return claim.Value; } } return null; } } /// <summary> /// Represents a security token which contains multiple security keys that are generated using symmetric algorithms. /// </summary> public class MultipleSymmetricKeySecurityToken : SecurityToken { /// <summary> /// Initializes a new instance of the MultipleSymmetricKeySecurityToken class. /// </summary> /// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param> public MultipleSymmetricKeySecurityToken(IEnumerable<byte[]> keys) : this(UniqueId.CreateUniqueId(), keys) { } /// <summary> /// Initializes a new instance of the MultipleSymmetricKeySecurityToken class. /// </summary> /// <param name="tokenId">The unique identifier of the security token.</param> /// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param> public MultipleSymmetricKeySecurityToken(string tokenId, IEnumerable<byte[]> keys) { if (keys == null) { throw new ArgumentNullException("keys"); } if (String.IsNullOrEmpty(tokenId)) { throw new ArgumentException("Value cannot be a null or empty string.", "tokenId"); } foreach (byte[] key in keys) { if (key.Length <= 0) { throw new ArgumentException("The key length must be greater then zero.", "keys"); } } id = tokenId; effectiveTime = DateTime.UtcNow; securityKeys = CreateSymmetricSecurityKeys(keys); } /// <summary> /// Gets the unique identifier of the security token. /// </summary> public override string Id { get { return id; } } /// <summary> /// Gets the cryptographic keys associated with the security token. /// </summary> public override ReadOnlyCollection<SecurityKey> SecurityKeys { get { return securityKeys.AsReadOnly(); } } /// <summary> /// Gets the first instant in time at which this security token is valid. /// </summary> public override DateTime ValidFrom { get { return effectiveTime; } } /// <summary> /// Gets the last instant in time at which this security token is valid. /// </summary> public override DateTime ValidTo { get { // Never expire return DateTime.MaxValue; } } /// <summary> /// Returns a value that indicates whether the key identifier for this instance can be resolved to the specified key identifier. /// </summary> /// <param name="keyIdentifierClause">A SecurityKeyIdentifierClause to compare to this instance</param> /// <returns>true if keyIdentifierClause is a SecurityKeyIdentifierClause and it has the same unique identifier as the Id property; otherwise, false.</returns> public override bool MatchesKeyIdentifierClause(SecurityKeyIdentifierClause keyIdentifierClause) { if (keyIdentifierClause == null) { throw new ArgumentNullException("keyIdentifierClause"); } // Since this is a symmetric token and we do not have IDs to distinguish tokens, we just check for the // presence of a SymmetricIssuerKeyIdentifier. The actual mapping to the issuer takes place later // when the key is matched to the issuer. if (keyIdentifierClause is SymmetricIssuerKeyIdentifierClause) { return true; } return base.MatchesKeyIdentifierClause(keyIdentifierClause); } #region private members private List<SecurityKey> CreateSymmetricSecurityKeys(IEnumerable<byte[]> keys) { List<SecurityKey> symmetricKeys = new List<SecurityKey>(); foreach (byte[] key in keys) { symmetricKeys.Add(new InMemorySymmetricSecurityKey(key)); } return symmetricKeys; } private string id; private DateTime effectiveTime; private List<SecurityKey> securityKeys; #endregion } }
#region License /* Illusory Studios C# Crypto Library (CryptSharp) Copyright (c) 2011 James F. Bellinger <jfb@zer7.com> Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #endregion namespace BitPool.Cryptography.KDF.CryptSharp { using System; using System.Security.Cryptography; using System.Threading; /* * Modified for use in ObscurCore (removed fixed output size restriction) on 07-02-2013 (dd-mm-yyyy) */ /// <summary> /// See http://www.tarsnap.com/scrypt/scrypt.pdf for algorithm details. /// TODO: Test on a big-endian machine and make sure it works. /// </summary> public static class SCrypt { // modified (commented out to disable) //private const int HLen = 32; private static readonly Pbkdf2.ComputeHmacCallback HmacCallback = Pbkdf2.CallbackFromHmac<HMACSHA256> (); // modified! public static void ComputeKey (byte[] key, byte[] salt, int cost, int blockSize, int parallel, int? maxThreads, byte[] output) { using (Pbkdf2 kdf = GetStream(key, salt, cost, blockSize, parallel, maxThreads, output.Length)) { kdf.Read (output); } } public static byte[] GetEffectivePbkdf2Salt (byte[] key, byte[] salt, int cost, int blockSize, int parallel, int? maxThreads, int HLen) { Helper.CheckNull ("key", key); Helper.CheckNull ("salt", salt); return MFcrypt (key, salt, cost, blockSize, parallel, maxThreads, HLen); } // modified! public static Pbkdf2 GetStream (byte[] key, byte[] salt, int cost, int blockSize, int parallel, int? maxThreads, int HLen) { byte[] B = GetEffectivePbkdf2Salt (key, salt, cost, blockSize, parallel, maxThreads, HLen); var kdf = new Pbkdf2 (key, B, 1, HmacCallback, HLen); Clear (B); return kdf; } private static void Clear (Array arr) { Array.Clear (arr, 0, arr.Length); } private static byte[] MFcrypt (byte[] P, byte[] S, int cost, int blockSize, int parallel, int? maxThreads, int HLen) { int MFLen = blockSize * 128; if (maxThreads == null) { maxThreads = int.MaxValue; } if (cost <= 0 || (cost & (cost - 1)) != 0) { throw new ArgumentOutOfRangeException ("cost", "Cost must be a positive power of 2."); } Helper.CheckRange ("blockSize", blockSize, 1, int.MaxValue / 32); Helper.CheckRange ("parallel", parallel, 1, int.MaxValue / MFLen); Helper.CheckRange ("maxThreads", (int)maxThreads, 1, int.MaxValue); byte[] B = new byte[parallel * MFLen]; Pbkdf2.ComputeKey (P, S, 1, HmacCallback, HLen, B); uint[] B0 = new uint[B.Length / 4]; for (int i = 0; i < B0.Length; i++) { B0 [i] = Helper.BytesToUInt32LE (B, i * 4); } // code is easier with uint[] ThreadSMixCalls (B0, MFLen, cost, blockSize, parallel, (int)maxThreads); for (int i = 0; i < B0.Length; i++) { Helper.UInt32ToBytesLE (B0 [i], B, i * 4); } Clear (B0); return B; } private static void ThreadSMixCalls (uint[] B0, int MFLen, int cost, int blockSize, int parallel, int maxThreads) { int current = 0; ThreadStart workerThread = delegate { while (true) { int j = Interlocked.Increment (ref current) - 1; if (j >= parallel) { break; } SMix (B0, j * MFLen / 4, B0, j * MFLen / 4, (uint)cost, blockSize); } }; int threadCount = Math.Max (1, Math.Min (Environment.ProcessorCount, Math.Min (maxThreads, parallel))); Thread[] threads = new Thread[threadCount - 1]; for (int i = 0; i < threads.Length; i++) { (threads [i] = new Thread (workerThread, 8192)).Start (); } workerThread (); for (int i = 0; i < threads.Length; i++) { threads [i].Join (); } } private static void SMix (uint[] B, int Boffset, uint[] Bp, int Bpoffset, uint N, int r) { uint Nmask = N - 1; int Bs = 16 * 2 * r; uint[] scratch1 = new uint[16], scratch2 = new uint[16]; uint[] scratchX = new uint[16], scratchY = new uint[Bs]; uint[] scratchZ = new uint[Bs]; uint[] x = new uint[Bs]; uint[][] v = new uint[N][]; for (int i = 0; i < v.Length; i++) { v [i] = new uint[Bs]; } Array.Copy (B, Boffset, x, 0, Bs); for (uint i = 0; i < N; i++) { Array.Copy (x, v [i], Bs); BlockMix (x, 0, x, 0, scratchX, scratchY, scratch1, scratch2, r); } for (uint i = 0; i < N; i++) { uint j = x [Bs - 16] & Nmask; uint[] vj = v [j]; for (int k = 0; k < scratchZ.Length; k++) { scratchZ [k] = x [k] ^ vj [k]; } BlockMix (scratchZ, 0, x, 0, scratchX, scratchY, scratch1, scratch2, r); } Array.Copy (x, 0, Bp, Bpoffset, Bs); for (int i = 0; i < v.Length; i++) { Clear (v [i]); } Clear (v); Clear (x); Clear (scratchX); Clear (scratchY); Clear (scratchZ); Clear (scratch1); Clear (scratch2); } private static void BlockMix (uint[] B, // 16*2*r int Boffset, uint[] Bp, // 16*2*r int Bpoffset, uint[] x, // 16 uint[] y, // 16*2*r -- unnecessary but it allows us to alias B and Bp uint[] scratch1, // 16 uint[] scratch2, // 16 int r) { int k = Boffset, m = 0, n = 16 * r; Array.Copy (B, (2 * r - 1) * 16, x, 0, 16); for (int i = 0; i < r; i++) { for (int j = 0; j < scratch1.Length; j++) { scratch1 [j] = x [j] ^ B [j + k]; } Salsa20Core.Compute (8, scratch1, 0, x, 0, scratch2); Array.Copy (x, 0, y, m, 16); k += 16; for (int j = 0; j < scratch1.Length; j++) { scratch1 [j] = x [j] ^ B [j + k]; } Salsa20Core.Compute (8, scratch1, 0, x, 0, scratch2); Array.Copy (x, 0, y, m + n, 16); k += 16; m += 16; } Array.Copy (y, 0, Bp, Bpoffset, y.Length); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; namespace SemanticVersioning { internal static class Desugarer { private const string versionChars = @"[0-9a-zA-Z\-\+\.\*]"; // Allows patch-level changes if a minor version is specified // on the comparator. Allows minor-level changes if not. public static Tuple<int, Comparator[]> TildeRange(string spec) { string pattern = String.Format(@"^\s*~\s*({0}+)\s*", versionChars); var regex = new Regex(pattern); var match = regex.Match(spec); if (!match.Success) { return null; } Version minVersion = null; Version maxVersion = null; var version = new PartialVersion(match.Groups[1].Value); if (version.Minor.HasValue) { // Doesn't matter whether patch version is null or not, // the logic is the same, min patch version will be zero if null. minVersion = version.ToZeroVersion(); maxVersion = new Version(version.Major.Value, version.Minor.Value + 1, 0); } else { minVersion = version.ToZeroVersion(); maxVersion = new Version(version.Major.Value + 1, 0, 0); } return Tuple.Create( match.Length, MinMaxComparators(minVersion, maxVersion)); } // Allows changes that do not modify the left-most non-zero digit // in the [major, minor, patch] tuple. public static Tuple<int, Comparator[]> CaretRange(string spec) { string pattern = String.Format(@"^\s*\^\s*({0}+)\s*", versionChars); var regex = new Regex(pattern); var match = regex.Match(spec); if (!match.Success) { return null; } Version minVersion = null; Version maxVersion = null; var version = new PartialVersion(match.Groups[1].Value); if (version.Major.Value > 0) { // Don't allow major version change minVersion = version.ToZeroVersion(); maxVersion = new Version(version.Major.Value + 1, 0, 0); } else if (!version.Minor.HasValue) { // Don't allow major version change, even if it's zero minVersion = version.ToZeroVersion(); maxVersion = new Version(version.Major.Value + 1, 0, 0); } else if (!version.Patch.HasValue) { // Don't allow minor version change, even if it's zero minVersion = version.ToZeroVersion(); maxVersion = new Version(0, version.Minor.Value + 1, 0); } else if (version.Minor > 0) { // Don't allow minor version change minVersion = version.ToZeroVersion(); maxVersion = new Version(0, version.Minor.Value + 1, 0); } else { // Only patch non-zero, don't allow patch change minVersion = version.ToZeroVersion(); maxVersion = new Version(0, 0, version.Patch.Value + 1); } return Tuple.Create( match.Length, MinMaxComparators(minVersion, maxVersion, minOperator: Comparator.Operator.GreaterThanOrEqualIncludingPrereleases)); } public static Tuple<int, Comparator[]> HyphenRange(string spec) { string pattern = String.Format(@"^\s*({0}+)\s+\-\s+({0}+)\s*", versionChars); var regex = new Regex(pattern); var match = regex.Match(spec); if (!match.Success) { return null; } PartialVersion minPartialVersion = null; PartialVersion maxPartialVersion = null; // Parse versions from lower and upper ranges, which might // be partial versions. try { minPartialVersion = new PartialVersion(match.Groups[1].Value); maxPartialVersion = new PartialVersion(match.Groups[2].Value); } catch (ArgumentException) { return null; } // Lower range has any non-supplied values replaced with zero var minVersion = minPartialVersion.ToZeroVersion(); Comparator.Operator maxOperator = maxPartialVersion.IsFull() ? Comparator.Operator.LessThanOrEqual : Comparator.Operator.LessThanExcludingPrereleases; Version maxVersion = null; // Partial upper range means supplied version values can't change if (!maxPartialVersion.Major.HasValue) { // eg. upper range = "*", then maxVersion remains null // and there's only a minimum } else if (!maxPartialVersion.Minor.HasValue) { maxVersion = new Version(maxPartialVersion.Major.Value + 1, 0, 0); } else if (!maxPartialVersion.Patch.HasValue) { maxVersion = new Version(maxPartialVersion.Major.Value, maxPartialVersion.Minor.Value + 1, 0); } else { // Fully specified max version maxVersion = maxPartialVersion.ToZeroVersion(); } return Tuple.Create( match.Length, MinMaxComparators( minVersion, maxVersion, minOperator: Comparator.Operator.GreaterThanOrEqualIncludingPrereleases, maxOperator: maxOperator)); } public static Tuple<int, Comparator[]> StarRange(string spec) { // Also match with an equals sign, eg. "=0.7.x" string pattern = String.Format(@"^\s*=?\s*({0}+)\s*", versionChars); var regex = new Regex(pattern); var match = regex.Match(spec); if (!match.Success) { return null; } PartialVersion version = null; try { version = new PartialVersion(match.Groups[1].Value); } catch (ArgumentException) { return null; } // If partial version match is actually a full version, // then this isn't a star range, so return null. if (version.IsFull()) { return null; } Version minVersion = null; Version maxVersion = null; if (!version.Major.HasValue) { minVersion = version.ToZeroVersion(); // no max version } else if (!version.Minor.HasValue) { minVersion = version.ToZeroVersion(); maxVersion = new Version(version.Major.Value + 1, 0, 0); } else { minVersion = version.ToZeroVersion(); maxVersion = new Version(version.Major.Value, version.Minor.Value + 1, 0); } return Tuple.Create( match.Length, MinMaxComparators(minVersion, maxVersion)); } private static Comparator[] MinMaxComparators(Version minVersion, Version maxVersion, Comparator.Operator minOperator=Comparator.Operator.GreaterThanOrEqual, Comparator.Operator maxOperator=Comparator.Operator.LessThanExcludingPrereleases) { var minComparator = new Comparator(minOperator, minVersion); if (maxVersion == null) { return new [] { minComparator }; } else { var maxComparator = new Comparator(maxOperator, maxVersion); return new [] { minComparator, maxComparator }; } } } }
//------------------------------------------------------------------------------ // <copyright file="etwprovider.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ using Microsoft.Win32; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Runtime.InteropServices; using System.Security; using System.Security.Permissions; using System.Threading; 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_AGAINST_DOTNET_V35 using Microsoft.Internal; // for Tuple (can't define alias for open generic types so we "use" the whole namespace) #endif #if ES_BUILD_STANDALONE namespace Microsoft.Diagnostics.Tracing #else namespace System.Diagnostics.Tracing #endif { // New in CLR4.0 internal enum ControllerCommand { // Strictly Positive numbers are for provider-specific commands, negative number are for 'shared' commands. 256 // The first 256 negative numbers are reserved for the framework. Update = 0, // Not used by EventPrividerBase. SendManifest = -1, Enable = -2, Disable = -3, }; /// <summary> /// Only here because System.Diagnostics.EventProvider needs one more extensibility hook (when it gets a /// controller callback) /// </summary> [System.Security.Permissions.HostProtection(MayLeakOnAbort = true)] internal class EventProvider : IDisposable { // This is the windows EVENT_DATA_DESCRIPTOR structure. We expose it because this is what // subclasses of EventProvider use when creating efficient (but unsafe) version of // EventWrite. We do make it a nested type because we really don't expect anyone to use // it except subclasses (and then only rarely). public struct EventData { internal unsafe ulong Ptr; internal uint Size; internal uint Reserved; } /// <summary> /// A struct characterizing ETW sessions (identified by the etwSessionId) as /// activity-tracing-aware or legacy. A session that's activity-tracing-aware /// has specified one non-zero bit in the reserved range 44-47 in the /// 'allKeywords' value it passed in for a specific EventProvider. /// </summary> public struct SessionInfo { internal int sessionIdBit; // the index of the bit used for tracing in the "reserved" field of AllKeywords internal int etwSessionId; // the machine-wide ETW session ID internal SessionInfo(int sessionIdBit_, int etwSessionId_) { sessionIdBit = sessionIdBit_; etwSessionId = etwSessionId_; } } private static bool m_setInformationMissing; [SecurityCritical] UnsafeNativeMethods.ManifestEtw.EtwEnableCallback m_etwCallback; // Trace Callback function private long m_regHandle; // Trace Registration Handle private byte m_level; // Tracing Level private long m_anyKeywordMask; // Trace Enable Flags private long m_allKeywordMask; // Match all keyword private List<SessionInfo> m_liveSessions; // current live sessions (Tuple<sessionIdBit, etwSessionId>) private bool m_enabled; // Enabled flag from Trace callback private Guid m_providerId; // Control Guid internal bool m_disposed; // when true provider has unregistered [ThreadStatic] private static WriteEventErrorCode s_returnCode; // The last return code private const int s_basicTypeAllocationBufferSize = 16; private const int s_etwMaxNumberArguments = 32; private const int s_etwAPIMaxRefObjCount = 8; private const int s_maxEventDataDescriptors = 128; private const int s_traceEventMaximumSize = 65482; private const int s_traceEventMaximumStringSize = 32724; [SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")] public enum WriteEventErrorCode : int { //check mapping to runtime codes NoError = 0, NoFreeBuffers = 1, EventTooBig = 2, NullInput = 3, TooManyArgs = 4, Other = 5, }; // <SecurityKernel Critical="True" Ring="1"> // <ReferencesCritical Name="Method: Register():Void" Ring="1" /> // </SecurityKernel> /// <summary> /// Constructs a new EventProvider. This causes the class to be registered with the OS and /// if an ETW controller turns on the logging then logging will start. /// </summary> /// <param name="providerGuid">The GUID that identifies this provider to the system.</param> [System.Security.SecurityCritical] #pragma warning disable 618 [PermissionSet(SecurityAction.Demand, Unrestricted = true)] #pragma warning restore 618 [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames", MessageId = "guid")] protected EventProvider(Guid providerGuid) { m_providerId = providerGuid; // // Register the ProviderId with ETW // Register(providerGuid); } internal EventProvider() { } /// <summary> /// This method registers the controlGuid of this class with ETW. We need to be running on /// Vista or above. If not a PlatformNotSupported exception will be thrown. If for some /// reason the ETW Register call failed a NotSupported exception will be thrown. /// </summary> // <SecurityKernel Critical="True" Ring="0"> // <CallsSuppressUnmanagedCode Name="UnsafeNativeMethods.ManifestEtw.EventRegister(System.Guid&,Microsoft.Win32.UnsafeNativeMethods.ManifestEtw+EtwEnableCallback,System.Void*,System.Int64&):System.UInt32" /> // <SatisfiesLinkDemand Name="Win32Exception..ctor(System.Int32)" /> // <ReferencesCritical Name="Method: EtwEnableCallBack(Guid&, Int32, Byte, Int64, Int64, Void*, Void*):Void" Ring="1" /> // </SecurityKernel> [System.Security.SecurityCritical] internal unsafe void Register(Guid providerGuid) { m_providerId = providerGuid; uint status; m_etwCallback = new UnsafeNativeMethods.ManifestEtw.EtwEnableCallback(EtwEnableCallBack); status = EventRegister(ref m_providerId, m_etwCallback); if (status != 0) { throw new ArgumentException(Win32Native.GetMessage(unchecked((int)status))); } } [System.Security.SecurityCritical] internal unsafe int SetInformation( UnsafeNativeMethods.ManifestEtw.EVENT_INFO_CLASS eventInfoClass, void* data, int dataSize) { int status = UnsafeNativeMethods.ManifestEtw.ERROR_NOT_SUPPORTED; if (!m_setInformationMissing) { try { status = UnsafeNativeMethods.ManifestEtw.EventSetInformation( m_regHandle, eventInfoClass, data, dataSize); } catch (TypeLoadException) { m_setInformationMissing = true; } } return status; } // // implement Dispose Pattern to early deregister from ETW insted of waiting for // the finalizer to call deregistration. // Once the user is done with the provider it needs to call Close() or Dispose() // If neither are called the finalizer will unregister the provider anyway // public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } // <SecurityKernel Critical="True" TreatAsSafe="Does not expose critical resource" Ring="1"> // <ReferencesCritical Name="Method: Deregister():Void" Ring="1" /> // </SecurityKernel> [System.Security.SecuritySafeCritical] protected virtual void Dispose(bool disposing) { // // explicit cleanup is done by calling Dispose with true from // Dispose() or Close(). The disposing arguement is ignored because there // are no unmanaged resources. // The finalizer calls Dispose with false. // // // check if the object has been allready disposed // if (m_disposed) return; // Disable the provider. m_enabled = false; // Do most of the work under a lock to avoid shutdown ----. lock (EventListener.EventListenersLock) { // Double check if (m_disposed) return; Deregister(); m_disposed = true; } } /// <summary> /// This method deregisters the controlGuid of this class with ETW. /// /// </summary> public virtual void Close() { Dispose(); } ~EventProvider() { Dispose(false); } /// <summary> /// This method un-registers from ETW. /// </summary> // <SecurityKernel Critical="True" Ring="0"> // <CallsSuppressUnmanagedCode Name="UnsafeNativeMethods.ManifestEtw.EventUnregister(System.Int64):System.Int32" /> // </SecurityKernel> // [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1806:DoNotIgnoreMethodResults", MessageId = "Microsoft.Win32.UnsafeNativeMethods.ManifestEtw.EventUnregister(System.Int64)"), System.Security.SecurityCritical] private unsafe void Deregister() { // // Unregister from ETW using the RegHandle saved from // the register call. // if (m_regHandle != 0) { EventUnregister(); m_regHandle = 0; } } // <SecurityKernel Critical="True" Ring="0"> // <UsesUnsafeCode Name="Parameter filterData of type: Void*" /> // <UsesUnsafeCode Name="Parameter callbackContext of type: Void*" /> // </SecurityKernel> [System.Security.SecurityCritical] unsafe void EtwEnableCallBack( [In] ref System.Guid sourceId, [In] int controlCode, [In] byte setLevel, [In] long anyKeyword, [In] long allKeyword, [In] UnsafeNativeMethods.ManifestEtw.EVENT_FILTER_DESCRIPTOR* filterData, [In] void* callbackContext ) { // This is an optional callback API. We will therefore ignore any failures that happen as a // result of turning on this provider as to not crash the app. // EventSource has code to validate whther initialization it expected to occur actually occurred try { ControllerCommand command = ControllerCommand.Update; IDictionary<string, string> args = null; byte[] data; int keyIndex; bool skipFinalOnControllerCommand = false; if (controlCode == UnsafeNativeMethods.ManifestEtw.EVENT_CONTROL_CODE_ENABLE_PROVIDER) { m_enabled = true; m_level = setLevel; m_anyKeywordMask = anyKeyword; m_allKeywordMask = allKeyword; List<Tuple<SessionInfo, bool>> sessionsChanged = GetSessions(); foreach (var session in sessionsChanged) { int sessionChanged = session.Item1.sessionIdBit; int etwSessionId = session.Item1.etwSessionId; bool bEnabling = session.Item2; skipFinalOnControllerCommand = true; args = null; // reinitialize args for every session... // if we get more than one session changed we have no way // of knowing which one "filterData" belongs to if (sessionsChanged.Count > 1) filterData = null; // read filter data only when a session is being *added* if (bEnabling && GetDataFromController(etwSessionId, filterData, out command, out data, out keyIndex)) { args = new Dictionary<string, string>(4); while (keyIndex < data.Length) { int keyEnd = FindNull(data, keyIndex); int valueIdx = keyEnd + 1; int valueEnd = FindNull(data, valueIdx); if (valueEnd < data.Length) { string key = System.Text.Encoding.UTF8.GetString(data, keyIndex, keyEnd - keyIndex); string value = System.Text.Encoding.UTF8.GetString(data, valueIdx, valueEnd - valueIdx); args[key] = value; } keyIndex = valueEnd + 1; } } // execute OnControllerCommand once for every session that has changed. OnControllerCommand(command, args, (bEnabling ? sessionChanged : -sessionChanged), etwSessionId); } } else if (controlCode == UnsafeNativeMethods.ManifestEtw.EVENT_CONTROL_CODE_DISABLE_PROVIDER) { m_enabled = false; m_level = 0; m_anyKeywordMask = 0; m_allKeywordMask = 0; m_liveSessions = null; } else if (controlCode == UnsafeNativeMethods.ManifestEtw.EVENT_CONTROL_CODE_CAPTURE_STATE) { command = ControllerCommand.SendManifest; } else return; // per spec you ignore commands you don't recognise. if (!skipFinalOnControllerCommand) OnControllerCommand(command, args, 0, 0); } catch (Exception) { // We want to ignore any failures that happen as a result of turning on this provider as to // not crash the app. } } // New in CLR4.0 protected virtual void OnControllerCommand(ControllerCommand command, IDictionary<string, string> arguments, int sessionId, int etwSessionId) { } protected EventLevel Level { get { return (EventLevel)m_level; } set { m_level = (byte)value; } } protected EventKeywords MatchAnyKeyword { get { return (EventKeywords)m_anyKeywordMask; } set { m_anyKeywordMask = unchecked((long)value); } } protected EventKeywords MatchAllKeyword { get { return (EventKeywords)m_allKeywordMask; } set { m_allKeywordMask = unchecked((long)value); } } static private int FindNull(byte[] buffer, int idx) { while (idx < buffer.Length && buffer[idx] != 0) idx++; return idx; } /// <summary> /// Determines the ETW sessions that have been added and/or removed to the set of /// sessions interested in the current provider. It does so by (1) enumerating over all /// ETW sessions that enabled 'this.m_Guid' for the current process ID, and (2) /// comparing the current list with a list it cached on the previous invocation. /// /// The return value is a list of tuples, where the SessionInfo specifies the /// ETW session that was added or remove, and the bool specifies whether the /// session was added or whether it was removed from the set. /// </summary> [System.Security.SecuritySafeCritical] private List<Tuple<SessionInfo, bool>> GetSessions() { List<SessionInfo> liveSessionList = null; GetSessionInfo((Action<int, long>) ((etwSessionId, matchAllKeywords) => GetSessionInfoCallback(etwSessionId, matchAllKeywords, ref liveSessionList))); List<Tuple<SessionInfo, bool>> changedSessionList = new List<Tuple<SessionInfo, bool>>(); // first look for sessions that have gone away (or have changed) // (present in the m_liveSessions but not in the new liveSessionList) if (m_liveSessions != null) { foreach(SessionInfo s in m_liveSessions) { int idx; if ((idx = IndexOfSessionInList(liveSessionList, s.etwSessionId)) < 0 || (liveSessionList[idx].sessionIdBit != s.sessionIdBit)) changedSessionList.Add(Tuple.Create(s, false)); } } // next look for sessions that were created since the last callback (or have changed) // (present in the new liveSessionList but not in m_liveSessions) if (liveSessionList != null) { foreach (SessionInfo s in liveSessionList) { int idx; if ((idx = IndexOfSessionInList(m_liveSessions, s.etwSessionId)) < 0 || (m_liveSessions[idx].sessionIdBit != s.sessionIdBit)) changedSessionList.Add(Tuple.Create(s, true)); } } m_liveSessions = liveSessionList; return changedSessionList; } /// <summary> /// This method is the callback used by GetSessions() when it calls into GetSessionInfo(). /// It updates a List{SessionInfo} based on the etwSessionId and matchAllKeywords that /// GetSessionInfo() passes in. /// </summary> private static void GetSessionInfoCallback(int etwSessionId, long matchAllKeywords, ref List<SessionInfo> sessionList) { uint sessionIdBitMask = (uint)SessionMask.FromEventKeywords(unchecked((ulong)matchAllKeywords)); // an ETW controller that specifies more than the mandated bit for our EventSource // will be ignored... if (bitcount(sessionIdBitMask) > 1) return; if (sessionList == null) sessionList = new List<SessionInfo>(8); if (bitcount(sessionIdBitMask) == 1) { // activity-tracing-aware etw session sessionList.Add(new SessionInfo(bitindex(sessionIdBitMask)+1, etwSessionId)); } else { // legacy etw session sessionList.Add(new SessionInfo(bitcount((uint)SessionMask.All)+1, etwSessionId)); } } /// <summary> /// This method enumerates over all active ETW sessions that have enabled 'this.m_Guid' /// for the current process ID, calling 'action' for each session, and passing it the /// ETW session and the 'AllKeywords' the session enabled for the current provider. /// </summary> [System.Security.SecurityCritical] private unsafe void GetSessionInfo(Action<int, long> action) { int buffSize = 256; // An initial guess that probably works most of the time. byte* buffer; for (; ; ) { var space = stackalloc byte[buffSize]; buffer = space; var hr = 0; fixed (Guid* provider = &m_providerId) { hr = UnsafeNativeMethods.ManifestEtw.EnumerateTraceGuidsEx(UnsafeNativeMethods.ManifestEtw.TRACE_QUERY_INFO_CLASS.TraceGuidQueryInfo, provider, sizeof(Guid), buffer, buffSize, ref buffSize); } if (hr == 0) break; if (hr != 122 /* ERROR_INSUFFICIENT_BUFFER */) return; } var providerInfos = (UnsafeNativeMethods.ManifestEtw.TRACE_GUID_INFO*)buffer; var providerInstance = (UnsafeNativeMethods.ManifestEtw.TRACE_PROVIDER_INSTANCE_INFO*)&providerInfos[1]; int processId = unchecked((int)Win32Native.GetCurrentProcessId()); // iterate over the instances of the EventProvider in all processes for (int i = 0; i < providerInfos->InstanceCount; i++) { if (providerInstance->Pid == processId) { var enabledInfos = (UnsafeNativeMethods.ManifestEtw.TRACE_ENABLE_INFO*)&providerInstance[1]; // iterate over the list of active ETW sessions "listening" to the current provider for (int j = 0; j < providerInstance->EnableCount; j++) action(enabledInfos[j].LoggerId, enabledInfos[j].MatchAllKeyword); } if (providerInstance->NextOffset == 0) break; Contract.Assert(0 <= providerInstance->NextOffset && providerInstance->NextOffset < buffSize); var structBase = (byte*)providerInstance; providerInstance = (UnsafeNativeMethods.ManifestEtw.TRACE_PROVIDER_INSTANCE_INFO*)&structBase[providerInstance->NextOffset]; } } /// <summary> /// Returns the index of the SesisonInfo from 'sessions' that has the specified 'etwSessionId' /// or -1 if the value is not present. /// </summary> private static int IndexOfSessionInList(List<SessionInfo> sessions, int etwSessionId) { if (sessions == null) return -1; // for non-coreclr code we could use List<T>.FindIndex(Predicate<T>), but we need this to compile // on coreclr as well for (int i = 0; i < sessions.Count; ++i) if (sessions[i].etwSessionId == etwSessionId) return i; return -1; } /// <summary> /// Gets any data to be passed from the controller to the provider. It starts with what is passed /// into the callback, but unfortunately this data is only present for when the provider is active /// at the time the controller issues the command. To allow for providers to activate after the /// controller issued a command, we also check the registry and use that to get the data. The function /// returns an array of bytes representing the data, the index into that byte array where the data /// starts, and the command being issued associated with that data. /// </summary> [System.Security.SecurityCritical] private unsafe bool GetDataFromController(int etwSessionId, UnsafeNativeMethods.ManifestEtw.EVENT_FILTER_DESCRIPTOR* filterData, out ControllerCommand command, out byte[] data, out int dataStart) { data = null; dataStart = 0; if (filterData == null) { #if !ES_BUILD_PCL string regKey = @"\Microsoft\Windows\CurrentVersion\Winevt\Publishers\{" + m_providerId + "}"; if (System.Runtime.InteropServices.Marshal.SizeOf(typeof(IntPtr)) == 8) regKey = @"HKEY_LOCAL_MACHINE\Software" + @"\Wow6432Node" + regKey; else regKey = @"HKEY_LOCAL_MACHINE\Software" + regKey; string valueName = "ControllerData_Session_" + etwSessionId.ToString(CultureInfo.InvariantCulture); // we need to assert this permission for partial trust scenarios (new RegistryPermission(RegistryPermissionAccess.Read, regKey)).Assert(); data = Microsoft.Win32.Registry.GetValue(regKey, valueName, null) as byte[]; if (data != null) { // We only used the persisted data from the registry for updates. command = ControllerCommand.Update; return true; } #endif } else { if (filterData->Ptr != 0 && 0 < filterData->Size && filterData->Size <= 1024) { data = new byte[filterData->Size]; Marshal.Copy((IntPtr)filterData->Ptr, data, 0, data.Length); } command = (ControllerCommand) filterData->Type; return true; } command = ControllerCommand.Update; return false; } /// <summary> /// IsEnabled, method used to test if provider is enabled /// </summary> public bool IsEnabled() { return m_enabled; } /// <summary> /// IsEnabled, method used to test if event is enabled /// </summary> /// <param name="level"> /// Level to test /// </param> /// <param name="keywords"> /// Keyword to test /// </param> public bool IsEnabled(byte level, long keywords) { // // If not enabled at all, return false. // if (!m_enabled) { return false; } // This also covers the case of Level == 0. if ((level <= m_level) || (m_level == 0)) { // // Check if Keyword is enabled // if ((keywords == 0) || (((keywords & m_anyKeywordMask) != 0) && ((keywords & m_allKeywordMask) == m_allKeywordMask))) { return true; } } return false; } // There's a small window of time in EventSource code where m_provider is non-null but the // m_regHandle has not been set yet. This method allows EventSource to check if this is the case... internal bool IsValid() { return m_regHandle != 0; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")] public static WriteEventErrorCode GetLastWriteEventError() { return s_returnCode; } // // Helper function to set the last error on the thread // private static void SetLastError(int error) { switch (error) { case UnsafeNativeMethods.ManifestEtw.ERROR_ARITHMETIC_OVERFLOW: case UnsafeNativeMethods.ManifestEtw.ERROR_MORE_DATA: s_returnCode = WriteEventErrorCode.EventTooBig; break; case UnsafeNativeMethods.ManifestEtw.ERROR_NOT_ENOUGH_MEMORY: s_returnCode = WriteEventErrorCode.NoFreeBuffers; break; } } // <SecurityKernel Critical="True" Ring="0"> // <UsesUnsafeCode Name="Local intptrPtr of type: IntPtr*" /> // <UsesUnsafeCode Name="Local intptrPtr of type: Int32*" /> // <UsesUnsafeCode Name="Local longptr of type: Int64*" /> // <UsesUnsafeCode Name="Local uintptr of type: UInt32*" /> // <UsesUnsafeCode Name="Local ulongptr of type: UInt64*" /> // <UsesUnsafeCode Name="Local charptr of type: Char*" /> // <UsesUnsafeCode Name="Local byteptr of type: Byte*" /> // <UsesUnsafeCode Name="Local shortptr of type: Int16*" /> // <UsesUnsafeCode Name="Local sbyteptr of type: SByte*" /> // <UsesUnsafeCode Name="Local ushortptr of type: UInt16*" /> // <UsesUnsafeCode Name="Local floatptr of type: Single*" /> // <UsesUnsafeCode Name="Local doubleptr of type: Double*" /> // <UsesUnsafeCode Name="Local boolptr of type: Boolean*" /> // <UsesUnsafeCode Name="Local guidptr of type: Guid*" /> // <UsesUnsafeCode Name="Local decimalptr of type: Decimal*" /> // <UsesUnsafeCode Name="Local booleanptr of type: Boolean*" /> // <UsesUnsafeCode Name="Parameter dataDescriptor of type: EventData*" /> // <UsesUnsafeCode Name="Parameter dataBuffer of type: Byte*" /> // </SecurityKernel> [System.Security.SecurityCritical] private static unsafe object EncodeObject(ref object data, ref EventData* dataDescriptor, ref byte* dataBuffer, ref uint totalEventSize) /*++ Routine Description: This routine is used by WriteEvent to unbox the object type and to fill the passed in ETW data descriptor. Arguments: data - argument to be decoded dataDescriptor - pointer to the descriptor to be filled (updated to point to the next empty entry) dataBuffer - storage buffer for storing user data, needed because cant get the address of the object (updated to point to the next empty entry) Return Value: null if the object is a basic type other than string or byte[]. String otherwise --*/ { Again: dataDescriptor->Reserved = 0; string sRet = data as string; byte[] blobRet = null; if (sRet != null) { dataDescriptor->Size = ((uint)sRet.Length + 1) * 2; } else if ((blobRet = data as byte[]) != null) { // first store array length *(int*)dataBuffer = blobRet.Length; dataDescriptor->Ptr = (ulong)dataBuffer; dataDescriptor->Size = 4; totalEventSize += dataDescriptor->Size; // then the array parameters dataDescriptor++; dataBuffer += s_basicTypeAllocationBufferSize; dataDescriptor->Size = (uint)blobRet.Length; } else if (data is IntPtr) { dataDescriptor->Size = (uint)sizeof(IntPtr); IntPtr* intptrPtr = (IntPtr*)dataBuffer; *intptrPtr = (IntPtr)data; dataDescriptor->Ptr = (ulong)intptrPtr; } else if (data is int) { dataDescriptor->Size = (uint)sizeof(int); int* intptr = (int*)dataBuffer; *intptr = (int)data; dataDescriptor->Ptr = (ulong)intptr; } else if (data is long) { dataDescriptor->Size = (uint)sizeof(long); long* longptr = (long*)dataBuffer; *longptr = (long)data; dataDescriptor->Ptr = (ulong)longptr; } else if (data is uint) { dataDescriptor->Size = (uint)sizeof(uint); uint* uintptr = (uint*)dataBuffer; *uintptr = (uint)data; dataDescriptor->Ptr = (ulong)uintptr; } else if (data is UInt64) { dataDescriptor->Size = (uint)sizeof(ulong); UInt64* ulongptr = (ulong*)dataBuffer; *ulongptr = (ulong)data; dataDescriptor->Ptr = (ulong)ulongptr; } else if (data is char) { dataDescriptor->Size = (uint)sizeof(char); char* charptr = (char*)dataBuffer; *charptr = (char)data; dataDescriptor->Ptr = (ulong)charptr; } else if (data is byte) { dataDescriptor->Size = (uint)sizeof(byte); byte* byteptr = (byte*)dataBuffer; *byteptr = (byte)data; dataDescriptor->Ptr = (ulong)byteptr; } else if (data is short) { dataDescriptor->Size = (uint)sizeof(short); short* shortptr = (short*)dataBuffer; *shortptr = (short)data; dataDescriptor->Ptr = (ulong)shortptr; } else if (data is sbyte) { dataDescriptor->Size = (uint)sizeof(sbyte); sbyte* sbyteptr = (sbyte*)dataBuffer; *sbyteptr = (sbyte)data; dataDescriptor->Ptr = (ulong)sbyteptr; } else if (data is ushort) { dataDescriptor->Size = (uint)sizeof(ushort); ushort* ushortptr = (ushort*)dataBuffer; *ushortptr = (ushort)data; dataDescriptor->Ptr = (ulong)ushortptr; } else if (data is float) { dataDescriptor->Size = (uint)sizeof(float); float* floatptr = (float*)dataBuffer; *floatptr = (float)data; dataDescriptor->Ptr = (ulong)floatptr; } else if (data is double) { dataDescriptor->Size = (uint)sizeof(double); double* doubleptr = (double*)dataBuffer; *doubleptr = (double)data; dataDescriptor->Ptr = (ulong)doubleptr; } else if (data is bool) { // WIN32 Bool is 4 bytes dataDescriptor->Size = 4; int* intptr = (int*)dataBuffer; if (((bool)data)) { *intptr = 1; } else { *intptr = 0; } dataDescriptor->Ptr = (ulong)intptr; } else if (data is Guid) { dataDescriptor->Size = (uint)sizeof(Guid); Guid* guidptr = (Guid*)dataBuffer; *guidptr = (Guid)data; dataDescriptor->Ptr = (ulong)guidptr; } else if (data is decimal) { dataDescriptor->Size = (uint)sizeof(decimal); decimal* decimalptr = (decimal*)dataBuffer; *decimalptr = (decimal)data; dataDescriptor->Ptr = (ulong)decimalptr; } else if (data is DateTime) { const long UTCMinTicks = 504911232000000000; long dateTimeTicks = 0; // We cannot translate dates sooner than 1/1/1601 in UTC. // To avoid getting an ArgumentOutOfRangeException we compare with 1/1/1601 DateTime ticks if (((DateTime)data).Ticks > UTCMinTicks) dateTimeTicks = ((DateTime)data).ToFileTimeUtc(); dataDescriptor->Size = (uint)sizeof(long); long* longptr = (long*)dataBuffer; *longptr = dateTimeTicks; dataDescriptor->Ptr = (ulong)longptr; } else { if (data is System.Enum) { Type underlyingType = Enum.GetUnderlyingType(data.GetType()); if (underlyingType == typeof(int)) { #if !ES_BUILD_PCL data = ((IConvertible)data).ToInt32(null); #else data = (int)data; #endif goto Again; } else if (underlyingType == typeof(long)) { #if !ES_BUILD_PCL data = ((IConvertible)data).ToInt64(null); #else data = (long)data; #endif goto Again; } } // To our eyes, everything else is a just a string if (data == null) sRet = ""; else sRet = data.ToString(); dataDescriptor->Size = ((uint)sRet.Length + 1) * 2; } totalEventSize += dataDescriptor->Size; // advance buffers dataDescriptor++; dataBuffer += s_basicTypeAllocationBufferSize; return (object)sRet ?? (object)blobRet; } /// <summary> /// WriteEvent, method to write a parameters with event schema properties /// </summary> /// <param name="eventDescriptor"> /// Event Descriptor for this event. /// </param> /// <param name="childActivityID"> /// childActivityID is marked as 'related' to the current activity ID. /// </param> /// <param name="eventPayload"> /// Payload for the ETW event. /// </param> // <SecurityKernel Critical="True" Ring="0"> // <CallsSuppressUnmanagedCode Name="UnsafeNativeMethods.ManifestEtw.EventWrite(System.Int64,EventDescriptor&,System.UInt32,System.Void*):System.UInt32" /> // <UsesUnsafeCode Name="Local dataBuffer of type: Byte*" /> // <UsesUnsafeCode Name="Local pdata of type: Char*" /> // <UsesUnsafeCode Name="Local userData of type: EventData*" /> // <UsesUnsafeCode Name="Local userDataPtr of type: EventData*" /> // <UsesUnsafeCode Name="Local currentBuffer of type: Byte*" /> // <UsesUnsafeCode Name="Local v0 of type: Char*" /> // <UsesUnsafeCode Name="Local v1 of type: Char*" /> // <UsesUnsafeCode Name="Local v2 of type: Char*" /> // <UsesUnsafeCode Name="Local v3 of type: Char*" /> // <UsesUnsafeCode Name="Local v4 of type: Char*" /> // <UsesUnsafeCode Name="Local v5 of type: Char*" /> // <UsesUnsafeCode Name="Local v6 of type: Char*" /> // <UsesUnsafeCode Name="Local v7 of type: Char*" /> // <ReferencesCritical Name="Method: EncodeObject(Object&, EventData*, Byte*):String" Ring="1" /> // </SecurityKernel> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "Performance-critical code")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1045:DoNotPassTypesByReference")] [System.Security.SecurityCritical] internal unsafe bool WriteEvent(ref EventDescriptor eventDescriptor, Guid* activityID, Guid* childActivityID, params object[] eventPayload) { int status = 0; if (IsEnabled(eventDescriptor.Level, eventDescriptor.Keywords)) { int argCount = 0; unsafe { argCount = eventPayload.Length; if (argCount > s_etwMaxNumberArguments) { s_returnCode = WriteEventErrorCode.TooManyArgs; return false; } uint totalEventSize = 0; int index; int refObjIndex = 0; List<int> refObjPosition = new List<int>(s_etwAPIMaxRefObjCount); List<object> dataRefObj = new List<object>(s_etwAPIMaxRefObjCount); EventData* userData = stackalloc EventData[2 * argCount]; EventData* userDataPtr = (EventData*)userData; byte* dataBuffer = stackalloc byte[s_basicTypeAllocationBufferSize * 2 * argCount]; // Assume 16 chars for non-string argument byte* currentBuffer = dataBuffer; // // The loop below goes through all the arguments and fills in the data // descriptors. For strings save the location in the dataString array. // Calculates the total size of the event by adding the data descriptor // size value set in EncodeObject method. // bool hasNonStringRefArgs = false; for (index = 0; index < eventPayload.Length; index++) { if (eventPayload[index] != null) { object supportedRefObj; supportedRefObj = EncodeObject(ref eventPayload[index], ref userDataPtr, ref currentBuffer, ref totalEventSize); if (supportedRefObj != null) { // EncodeObject advanced userDataPtr to the next empty slot int idx = (int)(userDataPtr - userData - 1); if (!(supportedRefObj is string)) { if (eventPayload.Length + idx + 1 - index > s_etwMaxNumberArguments) { s_returnCode = WriteEventErrorCode.TooManyArgs; return false; } hasNonStringRefArgs = true; } dataRefObj.Add(supportedRefObj); refObjPosition.Add(idx); refObjIndex++; } } else { s_returnCode = WriteEventErrorCode.NullInput; return false; } } // update argCount based on ctual number of arguments written to 'userData' argCount = (int)(userDataPtr - userData); if (totalEventSize > s_traceEventMaximumSize) { s_returnCode = WriteEventErrorCode.EventTooBig; return false; } // the optimized path (using "fixed" instead of allocating pinned GCHandles if (!hasNonStringRefArgs && (refObjIndex < s_etwAPIMaxRefObjCount)) { // Fast path: at most 8 string arguments // ensure we have at least s_etwAPIMaxStringCount in dataString, so that // the "fixed" statement below works while (refObjIndex < s_etwAPIMaxRefObjCount) { dataRefObj.Add(null); ++refObjIndex; } // // now fix any string arguments and set the pointer on the data descriptor // fixed (char* v0 = (string)dataRefObj[0], v1 = (string)dataRefObj[1], v2 = (string)dataRefObj[2], v3 = (string)dataRefObj[3], v4 = (string)dataRefObj[4], v5 = (string)dataRefObj[5], v6 = (string)dataRefObj[6], v7 = (string)dataRefObj[7]) { userDataPtr = (EventData*)userData; if (dataRefObj[0] != null) { userDataPtr[refObjPosition[0]].Ptr = (ulong)v0; } if (dataRefObj[1] != null) { userDataPtr[refObjPosition[1]].Ptr = (ulong)v1; } if (dataRefObj[2] != null) { userDataPtr[refObjPosition[2]].Ptr = (ulong)v2; } if (dataRefObj[3] != null) { userDataPtr[refObjPosition[3]].Ptr = (ulong)v3; } if (dataRefObj[4] != null) { userDataPtr[refObjPosition[4]].Ptr = (ulong)v4; } if (dataRefObj[5] != null) { userDataPtr[refObjPosition[5]].Ptr = (ulong)v5; } if (dataRefObj[6] != null) { userDataPtr[refObjPosition[6]].Ptr = (ulong)v6; } if (dataRefObj[7] != null) { userDataPtr[refObjPosition[7]].Ptr = (ulong)v7; } status = UnsafeNativeMethods.ManifestEtw.EventWriteTransferWrapper(m_regHandle, ref eventDescriptor, activityID, childActivityID, argCount, userData); } } else { // Slow path: use pinned handles userDataPtr = (EventData*)userData; GCHandle[] rgGCHandle = new GCHandle[refObjIndex]; for (int i = 0; i < refObjIndex; ++i) { // below we still use "fixed" to avoid taking dependency on the offset of the first field // in the object (the way we would need to if we used GCHandle.AddrOfPinnedObject) rgGCHandle[i] = GCHandle.Alloc(dataRefObj[i], GCHandleType.Pinned); if (dataRefObj[i] is string) { fixed (char* p = (string)dataRefObj[i]) userDataPtr[refObjPosition[i]].Ptr = (ulong)p; } else { fixed (byte* p = (byte[])dataRefObj[i]) userDataPtr[refObjPosition[i]].Ptr = (ulong)p; } } status = UnsafeNativeMethods.ManifestEtw.EventWriteTransferWrapper(m_regHandle, ref eventDescriptor, activityID, childActivityID, argCount, userData); for (int i = 0; i < refObjIndex; ++i) { rgGCHandle[i].Free(); } } } } if (status != 0) { SetLastError((int)status); return false; } return true; } /// <summary> /// WriteEvent, method to be used by generated code on a derived class /// </summary> /// <param name="eventDescriptor"> /// Event Descriptor for this event. /// </param> /// <param name="childActivityID"> /// If this event is generating a child activity (WriteEventTransfer related activity) this is child activity /// This can be null for events that do not generate a child activity. /// </param> /// <param name="dataCount"> /// number of event descriptors /// </param> /// <param name="data"> /// pointer do the event data /// </param> // <SecurityKernel Critical="True" Ring="0"> // <CallsSuppressUnmanagedCode Name="UnsafeNativeMethods.ManifestEtw.EventWrite(System.Int64,EventDescriptor&,System.UInt32,System.Void*):System.UInt32" /> // </SecurityKernel> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1045:DoNotPassTypesByReference")] [System.Security.SecurityCritical] internal unsafe protected bool WriteEvent(ref EventDescriptor eventDescriptor, Guid* activityID, Guid* childActivityID, int dataCount, IntPtr data) { if (childActivityID != null) { // activity transfers are supported only for events that specify the Send or Receive opcode Contract.Assert((EventOpcode)eventDescriptor.Opcode == EventOpcode.Send || (EventOpcode)eventDescriptor.Opcode == EventOpcode.Receive || (EventOpcode)eventDescriptor.Opcode == EventOpcode.Start || (EventOpcode)eventDescriptor.Opcode == EventOpcode.Stop); } int status = UnsafeNativeMethods.ManifestEtw.EventWriteTransferWrapper(m_regHandle, ref eventDescriptor, activityID, childActivityID, dataCount, (EventData*)data); if (status != 0) { SetLastError(status); return false; } return true; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1045:DoNotPassTypesByReference")] [System.Security.SecurityCritical] internal unsafe bool WriteEventRaw( ref EventDescriptor eventDescriptor, Guid* activityID, Guid* relatedActivityID, int dataCount, IntPtr data) { int status; status = UnsafeNativeMethods.ManifestEtw.EventWriteTransferWrapper( m_regHandle, ref eventDescriptor, activityID, relatedActivityID, dataCount, (EventData*)data); if (status != 0) { SetLastError(status); return false; } return true; } // These are look-alikes to the Manifest based ETW OS APIs that have been shimmed to work // either with Manifest ETW or Classic ETW (if Manifest based ETW is not available). [SecurityCritical] private unsafe uint EventRegister(ref Guid providerId, UnsafeNativeMethods.ManifestEtw.EtwEnableCallback enableCallback) { m_providerId = providerId; m_etwCallback = enableCallback; return UnsafeNativeMethods.ManifestEtw.EventRegister(ref providerId, enableCallback, null, ref m_regHandle); } [SecurityCritical] private uint EventUnregister() { uint status = UnsafeNativeMethods.ManifestEtw.EventUnregister(m_regHandle); m_regHandle = 0; return status; } static int[] nibblebits = {0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4}; private static int bitcount(uint n) { int count = 0; for(; n != 0; n = n >> 4) count += nibblebits[n & 0x0f]; return count; } private static int bitindex(uint n) { Contract.Assert(bitcount(n) == 1); int idx = 0; while ((n & (1 << idx)) == 0) idx++; return idx; } } }
// 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.Xml; using System.Xml.Schema; using System.Reflection; using System.Reflection.Emit; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Security; namespace System.Runtime.Serialization { #if USE_REFEMIT || NET_NATIVE public delegate void XmlFormatClassWriterDelegate(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context, ClassDataContract dataContract); public delegate void XmlFormatCollectionWriterDelegate(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context, CollectionDataContract dataContract); public sealed class XmlFormatWriterGenerator #else internal delegate void XmlFormatClassWriterDelegate(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context, ClassDataContract dataContract); internal delegate void XmlFormatCollectionWriterDelegate(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context, CollectionDataContract dataContract); internal sealed class XmlFormatWriterGenerator #endif { [SecurityCritical] /// <SecurityNote> /// Critical - holds instance of CriticalHelper which keeps state that was produced within an assert /// </SecurityNote> private CriticalHelper _helper; /// <SecurityNote> /// Critical - initializes SecurityCritical field 'helper' /// </SecurityNote> [SecurityCritical] public XmlFormatWriterGenerator() { _helper = new CriticalHelper(); } /// <SecurityNote> /// Critical - accesses SecurityCritical helper class 'CriticalHelper' /// </SecurityNote> [SecurityCritical] internal XmlFormatClassWriterDelegate GenerateClassWriter(ClassDataContract classContract) { return _helper.GenerateClassWriter(classContract); } /// <SecurityNote> /// Critical - accesses SecurityCritical helper class 'CriticalHelper' /// </SecurityNote> [SecurityCritical] internal XmlFormatCollectionWriterDelegate GenerateCollectionWriter(CollectionDataContract collectionContract) { return _helper.GenerateCollectionWriter(collectionContract); } /// <SecurityNote> /// Review - handles all aspects of IL generation including initializing the DynamicMethod. /// changes to how IL generated could affect how data is serialized and what gets access to data, /// therefore we mark it for review so that changes to generation logic are reviewed. /// </SecurityNote> private class CriticalHelper { #if !USE_REFEMIT && !NET_NATIVE private CodeGenerator _ilg; private ArgBuilder _xmlWriterArg; private ArgBuilder _contextArg; private ArgBuilder _dataContractArg; private LocalBuilder _objectLocal; // Used for classes private LocalBuilder _contractNamespacesLocal; private LocalBuilder _memberNamesLocal; private LocalBuilder _childElementNamespacesLocal; private int _typeIndex = 1; private int _childElementIndex = 0; #endif internal XmlFormatClassWriterDelegate GenerateClassWriter(ClassDataContract classContract) { if (DataContractSerializer.Option == SerializationOption.ReflectionOnly) { return new ReflectionXmlFormatWriter().ReflectionWriteClass; } #if NET_NATIVE else if (DataContractSerializer.Option == SerializationOption.ReflectionAsBackup) { return new ReflectionXmlFormatWriter().ReflectionWriteClass; } #endif else { #if USE_REFEMIT || NET_NATIVE throw new InvalidOperationException("Cannot generate class writer"); #else _ilg = new CodeGenerator(); bool memberAccessFlag = classContract.RequiresMemberAccessForWrite(null); try { _ilg.BeginMethod("Write" + classContract.StableName.Name + "ToXml", Globals.TypeOfXmlFormatClassWriterDelegate, memberAccessFlag); } catch (SecurityException securityException) { if (memberAccessFlag) { classContract.RequiresMemberAccessForWrite(securityException); } else { throw; } } InitArgs(classContract.UnderlyingType); WriteClass(classContract); return (XmlFormatClassWriterDelegate)_ilg.EndMethod(); #endif } } internal XmlFormatCollectionWriterDelegate GenerateCollectionWriter(CollectionDataContract collectionContract) { if (DataContractSerializer.Option == SerializationOption.ReflectionOnly) { return new ReflectionXmlFormatWriter().ReflectionWriteCollection; } #if NET_NATIVE else if (DataContractSerializer.Option == SerializationOption.ReflectionAsBackup) { return new ReflectionXmlFormatWriter().ReflectionWriteCollection; } #endif else { #if USE_REFEMIT || NET_NATIVE throw new InvalidOperationException("Cannot generate class writer"); #else _ilg = new CodeGenerator(); bool memberAccessFlag = collectionContract.RequiresMemberAccessForWrite(null); try { _ilg.BeginMethod("Write" + collectionContract.StableName.Name + "ToXml", Globals.TypeOfXmlFormatCollectionWriterDelegate, memberAccessFlag); } catch (SecurityException securityException) { if (memberAccessFlag) { collectionContract.RequiresMemberAccessForWrite(securityException); } else { throw; } } InitArgs(collectionContract.UnderlyingType); WriteCollection(collectionContract); return (XmlFormatCollectionWriterDelegate)_ilg.EndMethod(); #endif } } #if !USE_REFEMIT && !NET_NATIVE private void InitArgs(Type objType) { _xmlWriterArg = _ilg.GetArg(0); _contextArg = _ilg.GetArg(2); _dataContractArg = _ilg.GetArg(3); _objectLocal = _ilg.DeclareLocal(objType, "objSerialized"); ArgBuilder objectArg = _ilg.GetArg(1); _ilg.Load(objectArg); // Copy the data from the DataTimeOffset object passed in to the DateTimeOffsetAdapter. // DateTimeOffsetAdapter is used here for serialization purposes to bypass the ISerializable implementation // on DateTimeOffset; which does not work in partial trust. if (objType == Globals.TypeOfDateTimeOffsetAdapter) { _ilg.ConvertValue(objectArg.ArgType, Globals.TypeOfDateTimeOffset); _ilg.Call(XmlFormatGeneratorStatics.GetDateTimeOffsetAdapterMethod); } //Copy the KeyValuePair<K,T> to a KeyValuePairAdapter<K,T>. else if (objType.GetTypeInfo().IsGenericType && objType.GetGenericTypeDefinition() == Globals.TypeOfKeyValuePairAdapter) { ClassDataContract dc = (ClassDataContract)DataContract.GetDataContract(objType); _ilg.ConvertValue(objectArg.ArgType, Globals.TypeOfKeyValuePair.MakeGenericType(dc.KeyValuePairGenericArguments)); _ilg.New(dc.KeyValuePairAdapterConstructorInfo); } else { _ilg.ConvertValue(objectArg.ArgType, objType); } _ilg.Stloc(_objectLocal); } private void InvokeOnSerializing(ClassDataContract classContract) { if (classContract.BaseContract != null) InvokeOnSerializing(classContract.BaseContract); if (classContract.OnSerializing != null) { _ilg.LoadAddress(_objectLocal); _ilg.Load(_contextArg); _ilg.Call(XmlFormatGeneratorStatics.GetStreamingContextMethod); _ilg.Call(classContract.OnSerializing); } } private void InvokeOnSerialized(ClassDataContract classContract) { if (classContract.BaseContract != null) InvokeOnSerialized(classContract.BaseContract); if (classContract.OnSerialized != null) { _ilg.LoadAddress(_objectLocal); _ilg.Load(_contextArg); _ilg.Call(XmlFormatGeneratorStatics.GetStreamingContextMethod); _ilg.Call(classContract.OnSerialized); } } private void WriteClass(ClassDataContract classContract) { InvokeOnSerializing(classContract); { if (classContract.ContractNamespaces.Length > 1) { _contractNamespacesLocal = _ilg.DeclareLocal(typeof(XmlDictionaryString[]), "contractNamespaces"); _ilg.Load(_dataContractArg); _ilg.LoadMember(XmlFormatGeneratorStatics.ContractNamespacesField); _ilg.Store(_contractNamespacesLocal); } _memberNamesLocal = _ilg.DeclareLocal(typeof(XmlDictionaryString[]), "memberNames"); _ilg.Load(_dataContractArg); _ilg.LoadMember(XmlFormatGeneratorStatics.MemberNamesField); _ilg.Store(_memberNamesLocal); for (int i = 0; i < classContract.ChildElementNamespaces.Length; i++) { if (classContract.ChildElementNamespaces[i] != null) { _childElementNamespacesLocal = _ilg.DeclareLocal(typeof(XmlDictionaryString[]), "childElementNamespaces"); _ilg.Load(_dataContractArg); _ilg.LoadMember(XmlFormatGeneratorStatics.ChildElementNamespacesProperty); _ilg.Store(_childElementNamespacesLocal); } } WriteMembers(classContract, null, classContract); } InvokeOnSerialized(classContract); } private int WriteMembers(ClassDataContract classContract, LocalBuilder extensionDataLocal, ClassDataContract derivedMostClassContract) { int memberCount = (classContract.BaseContract == null) ? 0 : WriteMembers(classContract.BaseContract, extensionDataLocal, derivedMostClassContract); LocalBuilder namespaceLocal = _ilg.DeclareLocal(typeof(XmlDictionaryString), "ns"); if (_contractNamespacesLocal == null) { _ilg.Load(_dataContractArg); _ilg.LoadMember(XmlFormatGeneratorStatics.NamespaceProperty); } else _ilg.LoadArrayElement(_contractNamespacesLocal, _typeIndex - 1); _ilg.Store(namespaceLocal); _ilg.Call(_contextArg, XmlFormatGeneratorStatics.IncrementItemCountMethod, classContract.Members.Count); for (int i = 0; i < classContract.Members.Count; i++, memberCount++) { DataMember member = classContract.Members[i]; Type memberType = member.MemberType; LocalBuilder memberValue = null; if (member.IsGetOnlyCollection) { _ilg.Load(_contextArg); _ilg.Call(XmlFormatGeneratorStatics.StoreIsGetOnlyCollectionMethod); } if (!member.EmitDefaultValue) { memberValue = LoadMemberValue(member); _ilg.IfNotDefaultValue(memberValue); } bool writeXsiType = CheckIfMemberHasConflict(member, classContract, derivedMostClassContract); if (writeXsiType || !TryWritePrimitive(memberType, memberValue, member.MemberInfo, null /*arrayItemIndex*/, namespaceLocal, null /*nameLocal*/, i + _childElementIndex)) { WriteStartElement(memberType, classContract.Namespace, namespaceLocal, null /*nameLocal*/, i + _childElementIndex); if (classContract.ChildElementNamespaces[i + _childElementIndex] != null) { _ilg.Load(_xmlWriterArg); _ilg.LoadArrayElement(_childElementNamespacesLocal, i + _childElementIndex); _ilg.Call(XmlFormatGeneratorStatics.WriteNamespaceDeclMethod); } if (memberValue == null) memberValue = LoadMemberValue(member); WriteValue(memberValue, writeXsiType); WriteEndElement(); } if (!member.EmitDefaultValue) { if (member.IsRequired) { _ilg.Else(); _ilg.Call(null, XmlFormatGeneratorStatics.ThrowRequiredMemberMustBeEmittedMethod, member.Name, classContract.UnderlyingType); } _ilg.EndIf(); } } _typeIndex++; _childElementIndex += classContract.Members.Count; return memberCount; } private LocalBuilder LoadMemberValue(DataMember member) { _ilg.LoadAddress(_objectLocal); _ilg.LoadMember(member.MemberInfo); LocalBuilder memberValue = _ilg.DeclareLocal(member.MemberType, member.Name + "Value"); _ilg.Stloc(memberValue); return memberValue; } private void WriteCollection(CollectionDataContract collectionContract) { LocalBuilder itemNamespace = _ilg.DeclareLocal(typeof(XmlDictionaryString), "itemNamespace"); _ilg.Load(_dataContractArg); _ilg.LoadMember(XmlFormatGeneratorStatics.NamespaceProperty); _ilg.Store(itemNamespace); LocalBuilder itemName = _ilg.DeclareLocal(typeof(XmlDictionaryString), "itemName"); _ilg.Load(_dataContractArg); _ilg.LoadMember(XmlFormatGeneratorStatics.CollectionItemNameProperty); _ilg.Store(itemName); if (collectionContract.ChildElementNamespace != null) { _ilg.Load(_xmlWriterArg); _ilg.Load(_dataContractArg); _ilg.LoadMember(XmlFormatGeneratorStatics.ChildElementNamespaceProperty); _ilg.Call(XmlFormatGeneratorStatics.WriteNamespaceDeclMethod); } if (collectionContract.Kind == CollectionKind.Array) { Type itemType = collectionContract.ItemType; LocalBuilder i = _ilg.DeclareLocal(Globals.TypeOfInt, "i"); _ilg.Call(_contextArg, XmlFormatGeneratorStatics.IncrementArrayCountMethod, _xmlWriterArg, _objectLocal); if (!TryWritePrimitiveArray(collectionContract.UnderlyingType, itemType, _objectLocal, itemName, itemNamespace)) { _ilg.For(i, 0, _objectLocal); if (!TryWritePrimitive(itemType, null /*value*/, null /*memberInfo*/, i /*arrayItemIndex*/, itemNamespace, itemName, 0 /*nameIndex*/)) { WriteStartElement(itemType, collectionContract.Namespace, itemNamespace, itemName, 0 /*nameIndex*/); _ilg.LoadArrayElement(_objectLocal, i); LocalBuilder memberValue = _ilg.DeclareLocal(itemType, "memberValue"); _ilg.Stloc(memberValue); WriteValue(memberValue, false /*writeXsiType*/); WriteEndElement(); } _ilg.EndFor(); } } else { MethodInfo incrementCollectionCountMethod = null; switch (collectionContract.Kind) { case CollectionKind.Collection: case CollectionKind.List: case CollectionKind.Dictionary: incrementCollectionCountMethod = XmlFormatGeneratorStatics.IncrementCollectionCountMethod; break; case CollectionKind.GenericCollection: case CollectionKind.GenericList: incrementCollectionCountMethod = XmlFormatGeneratorStatics.IncrementCollectionCountGenericMethod.MakeGenericMethod(collectionContract.ItemType); break; case CollectionKind.GenericDictionary: incrementCollectionCountMethod = XmlFormatGeneratorStatics.IncrementCollectionCountGenericMethod.MakeGenericMethod(Globals.TypeOfKeyValuePair.MakeGenericType(collectionContract.ItemType.GetGenericArguments())); break; } if (incrementCollectionCountMethod != null) { _ilg.Call(_contextArg, incrementCollectionCountMethod, _xmlWriterArg, _objectLocal); } bool isDictionary = false, isGenericDictionary = false; Type enumeratorType = null; Type[] keyValueTypes = null; if (collectionContract.Kind == CollectionKind.GenericDictionary) { isGenericDictionary = true; keyValueTypes = collectionContract.ItemType.GetGenericArguments(); enumeratorType = Globals.TypeOfGenericDictionaryEnumerator.MakeGenericType(keyValueTypes); } else if (collectionContract.Kind == CollectionKind.Dictionary) { isDictionary = true; keyValueTypes = new Type[] { Globals.TypeOfObject, Globals.TypeOfObject }; enumeratorType = Globals.TypeOfDictionaryEnumerator; } else { enumeratorType = collectionContract.GetEnumeratorMethod.ReturnType; } MethodInfo moveNextMethod = enumeratorType.GetMethod(Globals.MoveNextMethodName, BindingFlags.Instance | BindingFlags.Public, Array.Empty<Type>()); MethodInfo getCurrentMethod = enumeratorType.GetMethod(Globals.GetCurrentMethodName, BindingFlags.Instance | BindingFlags.Public, Array.Empty<Type>()); if (moveNextMethod == null || getCurrentMethod == null) { if (enumeratorType.GetTypeInfo().IsInterface) { if (moveNextMethod == null) moveNextMethod = XmlFormatGeneratorStatics.MoveNextMethod; if (getCurrentMethod == null) getCurrentMethod = XmlFormatGeneratorStatics.GetCurrentMethod; } else { Type ienumeratorInterface = Globals.TypeOfIEnumerator; CollectionKind kind = collectionContract.Kind; if (kind == CollectionKind.GenericDictionary || kind == CollectionKind.GenericCollection || kind == CollectionKind.GenericEnumerable) { Type[] interfaceTypes = enumeratorType.GetInterfaces(); foreach (Type interfaceType in interfaceTypes) { if (interfaceType.GetTypeInfo().IsGenericType && interfaceType.GetGenericTypeDefinition() == Globals.TypeOfIEnumeratorGeneric && interfaceType.GetGenericArguments()[0] == collectionContract.ItemType) { ienumeratorInterface = interfaceType; break; } } } if (moveNextMethod == null) moveNextMethod = CollectionDataContract.GetTargetMethodWithName(Globals.MoveNextMethodName, enumeratorType, ienumeratorInterface); if (getCurrentMethod == null) getCurrentMethod = CollectionDataContract.GetTargetMethodWithName(Globals.GetCurrentMethodName, enumeratorType, ienumeratorInterface); } } Type elementType = getCurrentMethod.ReturnType; LocalBuilder currentValue = _ilg.DeclareLocal(elementType, "currentValue"); LocalBuilder enumerator = _ilg.DeclareLocal(enumeratorType, "enumerator"); _ilg.Call(_objectLocal, collectionContract.GetEnumeratorMethod); if (isDictionary) { _ilg.ConvertValue(collectionContract.GetEnumeratorMethod.ReturnType, Globals.TypeOfIDictionaryEnumerator); _ilg.New(XmlFormatGeneratorStatics.DictionaryEnumeratorCtor); } else if (isGenericDictionary) { Type ctorParam = Globals.TypeOfIEnumeratorGeneric.MakeGenericType(Globals.TypeOfKeyValuePair.MakeGenericType(keyValueTypes)); ConstructorInfo dictEnumCtor = enumeratorType.GetConstructor(Globals.ScanAllMembers, new Type[] { ctorParam }); _ilg.ConvertValue(collectionContract.GetEnumeratorMethod.ReturnType, ctorParam); _ilg.New(dictEnumCtor); } _ilg.Stloc(enumerator); _ilg.ForEach(currentValue, elementType, enumeratorType, enumerator, getCurrentMethod); if (incrementCollectionCountMethod == null) { _ilg.Call(_contextArg, XmlFormatGeneratorStatics.IncrementItemCountMethod, 1); } if (!TryWritePrimitive(elementType, currentValue, null /*memberInfo*/, null /*arrayItemIndex*/, itemNamespace, itemName, 0 /*nameIndex*/)) { WriteStartElement(elementType, collectionContract.Namespace, itemNamespace, itemName, 0 /*nameIndex*/); if (isGenericDictionary || isDictionary) { _ilg.Call(_dataContractArg, XmlFormatGeneratorStatics.GetItemContractMethod); _ilg.Load(_xmlWriterArg); _ilg.Load(currentValue); _ilg.ConvertValue(currentValue.LocalType, Globals.TypeOfObject); _ilg.Load(_contextArg); _ilg.Call(XmlFormatGeneratorStatics.WriteXmlValueMethod); } else { WriteValue(currentValue, false /*writeXsiType*/); } WriteEndElement(); } _ilg.EndForEach(moveNextMethod); } } private bool TryWritePrimitive(Type type, LocalBuilder value, MemberInfo memberInfo, LocalBuilder arrayItemIndex, LocalBuilder ns, LocalBuilder name, int nameIndex) { PrimitiveDataContract primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(type); if (primitiveContract == null || primitiveContract.UnderlyingType == Globals.TypeOfObject) return false; // load xmlwriter if (type.GetTypeInfo().IsValueType) { _ilg.Load(_xmlWriterArg); } else { _ilg.Load(_contextArg); _ilg.Load(_xmlWriterArg); } // load primitive value if (value != null) { _ilg.Load(value); } else if (memberInfo != null) { _ilg.LoadAddress(_objectLocal); _ilg.LoadMember(memberInfo); } else { _ilg.LoadArrayElement(_objectLocal, arrayItemIndex); } // load name if (name != null) { _ilg.Load(name); } else { _ilg.LoadArrayElement(_memberNamesLocal, nameIndex); } // load namespace _ilg.Load(ns); // call method to write primitive _ilg.Call(primitiveContract.XmlFormatWriterMethod); return true; } private bool TryWritePrimitiveArray(Type type, Type itemType, LocalBuilder value, LocalBuilder itemName, LocalBuilder itemNamespace) { PrimitiveDataContract primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(itemType); if (primitiveContract == null) return false; string writeArrayMethod = null; switch (itemType.GetTypeCode()) { case TypeCode.Boolean: writeArrayMethod = "WriteBooleanArray"; break; case TypeCode.DateTime: writeArrayMethod = "WriteDateTimeArray"; break; case TypeCode.Decimal: writeArrayMethod = "WriteDecimalArray"; break; case TypeCode.Int32: writeArrayMethod = "WriteInt32Array"; break; case TypeCode.Int64: writeArrayMethod = "WriteInt64Array"; break; case TypeCode.Single: writeArrayMethod = "WriteSingleArray"; break; case TypeCode.Double: writeArrayMethod = "WriteDoubleArray"; break; default: break; } if (writeArrayMethod != null) { _ilg.Load(_xmlWriterArg); _ilg.Load(value); _ilg.Load(itemName); _ilg.Load(itemNamespace); _ilg.Call(typeof(XmlWriterDelegator).GetMethod(writeArrayMethod, Globals.ScanAllMembers, new Type[] { type, typeof(XmlDictionaryString), typeof(XmlDictionaryString) })); return true; } return false; } private void WriteValue(LocalBuilder memberValue, bool writeXsiType) { Type memberType = memberValue.LocalType; bool isNullableOfT = (memberType.GetTypeInfo().IsGenericType && memberType.GetGenericTypeDefinition() == Globals.TypeOfNullable); if (memberType.GetTypeInfo().IsValueType && !isNullableOfT) { PrimitiveDataContract primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(memberType); if (primitiveContract != null && !writeXsiType) _ilg.Call(_xmlWriterArg, primitiveContract.XmlFormatContentWriterMethod, memberValue); else InternalSerialize(XmlFormatGeneratorStatics.InternalSerializeMethod, memberValue, memberType, writeXsiType); } else { if (isNullableOfT) { memberValue = UnwrapNullableObject(memberValue);//Leaves !HasValue on stack memberType = memberValue.LocalType; } else { _ilg.Load(memberValue); _ilg.Load(null); _ilg.Ceq(); } _ilg.If(); _ilg.Call(_contextArg, XmlFormatGeneratorStatics.WriteNullMethod, _xmlWriterArg, memberType, DataContract.IsTypeSerializable(memberType)); _ilg.Else(); PrimitiveDataContract primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(memberType); if (primitiveContract != null && primitiveContract.UnderlyingType != Globals.TypeOfObject && !writeXsiType) { if (isNullableOfT) { _ilg.Call(_xmlWriterArg, primitiveContract.XmlFormatContentWriterMethod, memberValue); } else { _ilg.Call(_contextArg, primitiveContract.XmlFormatContentWriterMethod, _xmlWriterArg, memberValue); } } else { if (memberType == Globals.TypeOfObject ||//boxed Nullable<T> memberType == Globals.TypeOfValueType || ((IList)Globals.TypeOfNullable.GetInterfaces()).Contains(memberType)) { _ilg.Load(memberValue); _ilg.ConvertValue(memberValue.LocalType, Globals.TypeOfObject); memberValue = _ilg.DeclareLocal(Globals.TypeOfObject, "unwrappedMemberValue"); memberType = memberValue.LocalType; _ilg.Stloc(memberValue); _ilg.If(memberValue, Cmp.EqualTo, null); _ilg.Call(_contextArg, XmlFormatGeneratorStatics.WriteNullMethod, _xmlWriterArg, memberType, DataContract.IsTypeSerializable(memberType)); _ilg.Else(); } InternalSerialize((isNullableOfT ? XmlFormatGeneratorStatics.InternalSerializeMethod : XmlFormatGeneratorStatics.InternalSerializeReferenceMethod), memberValue, memberType, writeXsiType); if (memberType == Globals.TypeOfObject) //boxed Nullable<T> _ilg.EndIf(); } _ilg.EndIf(); } } private void InternalSerialize(MethodInfo methodInfo, LocalBuilder memberValue, Type memberType, bool writeXsiType) { _ilg.Load(_contextArg); _ilg.Load(_xmlWriterArg); _ilg.Load(memberValue); _ilg.ConvertValue(memberValue.LocalType, Globals.TypeOfObject); //In SL GetTypeHandle throws MethodAccessException as its internal and extern. //So as a workaround, call XmlObjectSerializerWriteContext.IsMemberTypeSameAsMemberValue that //does the actual comparison and returns the bool value we care. _ilg.Call(null, XmlFormatGeneratorStatics.IsMemberTypeSameAsMemberValue, memberValue, memberType); _ilg.Load(writeXsiType); _ilg.Load(DataContract.GetId(memberType.TypeHandle)); _ilg.Ldtoken(memberType); _ilg.Call(methodInfo); } private LocalBuilder UnwrapNullableObject(LocalBuilder memberValue)// Leaves !HasValue on stack { Type memberType = memberValue.LocalType; Label onNull = _ilg.DefineLabel(); Label end = _ilg.DefineLabel(); _ilg.Load(memberValue); while (memberType.GetTypeInfo().IsGenericType && memberType.GetGenericTypeDefinition() == Globals.TypeOfNullable) { Type innerType = memberType.GetGenericArguments()[0]; _ilg.Dup(); _ilg.Call(XmlFormatGeneratorStatics.GetHasValueMethod.MakeGenericMethod(innerType)); _ilg.Brfalse(onNull); _ilg.Call(XmlFormatGeneratorStatics.GetNullableValueMethod.MakeGenericMethod(innerType)); memberType = innerType; } memberValue = _ilg.DeclareLocal(memberType, "nullableUnwrappedMemberValue"); _ilg.Stloc(memberValue); _ilg.Load(false); //isNull _ilg.Br(end); _ilg.MarkLabel(onNull); _ilg.Pop(); _ilg.Call(XmlFormatGeneratorStatics.GetDefaultValueMethod.MakeGenericMethod(memberType)); _ilg.Stloc(memberValue); _ilg.Load(true);//isNull _ilg.MarkLabel(end); return memberValue; } private bool NeedsPrefix(Type type, XmlDictionaryString ns) { return type == Globals.TypeOfXmlQualifiedName && (ns != null && ns.Value != null && ns.Value.Length > 0); } private void WriteStartElement(Type type, XmlDictionaryString ns, LocalBuilder namespaceLocal, LocalBuilder nameLocal, int nameIndex) { bool needsPrefix = NeedsPrefix(type, ns); _ilg.Load(_xmlWriterArg); // prefix if (needsPrefix) _ilg.Load(Globals.ElementPrefix); // localName if (nameLocal == null) _ilg.LoadArrayElement(_memberNamesLocal, nameIndex); else _ilg.Load(nameLocal); // namespace _ilg.Load(namespaceLocal); _ilg.Call(needsPrefix ? XmlFormatGeneratorStatics.WriteStartElementMethod3 : XmlFormatGeneratorStatics.WriteStartElementMethod2); } private void WriteEndElement() { _ilg.Call(_xmlWriterArg, XmlFormatGeneratorStatics.WriteEndElementMethod); } private bool CheckIfMemberHasConflict(DataMember member, ClassDataContract classContract, ClassDataContract derivedMostClassContract) { // Check for conflict with base type members if (CheckIfConflictingMembersHaveDifferentTypes(member)) return true; // Check for conflict with derived type members string name = member.Name; string ns = classContract.StableName.Namespace; ClassDataContract currentContract = derivedMostClassContract; while (currentContract != null && currentContract != classContract) { if (ns == currentContract.StableName.Namespace) { List<DataMember> members = currentContract.Members; for (int j = 0; j < members.Count; j++) { if (name == members[j].Name) return CheckIfConflictingMembersHaveDifferentTypes(members[j]); } } currentContract = currentContract.BaseContract; } return false; } private bool CheckIfConflictingMembersHaveDifferentTypes(DataMember member) { while (member.ConflictingMember != null) { if (member.MemberType != member.ConflictingMember.MemberType) return true; member = member.ConflictingMember; } return false; } #endif } } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gax = Google.Api.Gax; using gaxgrpc = Google.Api.Gax.Grpc; using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore; using proto = Google.Protobuf; using grpccore = Grpc.Core; using grpcinter = Grpc.Core.Interceptors; using sys = System; using sc = System.Collections; using scg = System.Collections.Generic; using sco = System.Collections.ObjectModel; using st = System.Threading; using stt = System.Threading.Tasks; namespace Google.Ads.GoogleAds.V8.Services { /// <summary>Settings for <see cref="KeywordPlanIdeaServiceClient"/> instances.</summary> public sealed partial class KeywordPlanIdeaServiceSettings : gaxgrpc::ServiceSettingsBase { /// <summary>Get a new instance of the default <see cref="KeywordPlanIdeaServiceSettings"/>.</summary> /// <returns>A new instance of the default <see cref="KeywordPlanIdeaServiceSettings"/>.</returns> public static KeywordPlanIdeaServiceSettings GetDefault() => new KeywordPlanIdeaServiceSettings(); /// <summary> /// Constructs a new <see cref="KeywordPlanIdeaServiceSettings"/> object with default settings. /// </summary> public KeywordPlanIdeaServiceSettings() { } private KeywordPlanIdeaServiceSettings(KeywordPlanIdeaServiceSettings existing) : base(existing) { gax::GaxPreconditions.CheckNotNull(existing, nameof(existing)); GenerateKeywordIdeasSettings = existing.GenerateKeywordIdeasSettings; OnCopy(existing); } partial void OnCopy(KeywordPlanIdeaServiceSettings existing); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>KeywordPlanIdeaServiceClient.GenerateKeywordIdeas</c> and /// <c>KeywordPlanIdeaServiceClient.GenerateKeywordIdeasAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>Initial retry delay: 5000 milliseconds.</description></item> /// <item><description>Retry delay multiplier: 1.3</description></item> /// <item><description>Retry maximum delay: 60000 milliseconds.</description></item> /// <item><description>Maximum attempts: Unlimited</description></item> /// <item> /// <description> /// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>, /// <see cref="grpccore::StatusCode.DeadlineExceeded"/>. /// </description> /// </item> /// <item><description>Timeout: 3600 seconds.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings GenerateKeywordIdeasSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded))); /// <summary>Creates a deep clone of this object, with all the same property values.</summary> /// <returns>A deep clone of this <see cref="KeywordPlanIdeaServiceSettings"/> object.</returns> public KeywordPlanIdeaServiceSettings Clone() => new KeywordPlanIdeaServiceSettings(this); } /// <summary> /// Builder class for <see cref="KeywordPlanIdeaServiceClient"/> to provide simple configuration of credentials, /// endpoint etc. /// </summary> internal sealed partial class KeywordPlanIdeaServiceClientBuilder : gaxgrpc::ClientBuilderBase<KeywordPlanIdeaServiceClient> { /// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary> public KeywordPlanIdeaServiceSettings Settings { get; set; } /// <summary>Creates a new builder with default settings.</summary> public KeywordPlanIdeaServiceClientBuilder() { UseJwtAccessWithScopes = KeywordPlanIdeaServiceClient.UseJwtAccessWithScopes; } partial void InterceptBuild(ref KeywordPlanIdeaServiceClient client); partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<KeywordPlanIdeaServiceClient> task); /// <summary>Builds the resulting client.</summary> public override KeywordPlanIdeaServiceClient Build() { KeywordPlanIdeaServiceClient client = null; InterceptBuild(ref client); return client ?? BuildImpl(); } /// <summary>Builds the resulting client asynchronously.</summary> public override stt::Task<KeywordPlanIdeaServiceClient> BuildAsync(st::CancellationToken cancellationToken = default) { stt::Task<KeywordPlanIdeaServiceClient> task = null; InterceptBuildAsync(cancellationToken, ref task); return task ?? BuildAsyncImpl(cancellationToken); } private KeywordPlanIdeaServiceClient BuildImpl() { Validate(); grpccore::CallInvoker callInvoker = CreateCallInvoker(); return KeywordPlanIdeaServiceClient.Create(callInvoker, Settings); } private async stt::Task<KeywordPlanIdeaServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken) { Validate(); grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false); return KeywordPlanIdeaServiceClient.Create(callInvoker, Settings); } /// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary> protected override string GetDefaultEndpoint() => KeywordPlanIdeaServiceClient.DefaultEndpoint; /// <summary> /// Returns the default scopes for this builder type, used if no scopes are otherwise specified. /// </summary> protected override scg::IReadOnlyList<string> GetDefaultScopes() => KeywordPlanIdeaServiceClient.DefaultScopes; /// <summary>Returns the channel pool to use when no other options are specified.</summary> protected override gaxgrpc::ChannelPool GetChannelPool() => KeywordPlanIdeaServiceClient.ChannelPool; /// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary> protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance; } /// <summary>KeywordPlanIdeaService client wrapper, for convenient use.</summary> /// <remarks> /// Service to generate keyword ideas. /// </remarks> public abstract partial class KeywordPlanIdeaServiceClient { /// <summary> /// The default endpoint for the KeywordPlanIdeaService service, which is a host of "googleads.googleapis.com" /// and a port of 443. /// </summary> public static string DefaultEndpoint { get; } = "googleads.googleapis.com:443"; /// <summary>The default KeywordPlanIdeaService scopes.</summary> /// <remarks> /// The default KeywordPlanIdeaService scopes are: /// <list type="bullet"><item><description>https://www.googleapis.com/auth/adwords</description></item></list> /// </remarks> public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[] { "https://www.googleapis.com/auth/adwords", }); internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes); internal static bool UseJwtAccessWithScopes { get { bool useJwtAccessWithScopes = true; MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes); return useJwtAccessWithScopes; } } static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes); /// <summary> /// Asynchronously creates a <see cref="KeywordPlanIdeaServiceClient"/> using the default credentials, endpoint /// and settings. To specify custom credentials or other settings, use /// <see cref="KeywordPlanIdeaServiceClientBuilder"/>. /// </summary> /// <param name="cancellationToken"> /// The <see cref="st::CancellationToken"/> to use while creating the client. /// </param> /// <returns>The task representing the created <see cref="KeywordPlanIdeaServiceClient"/>.</returns> public static stt::Task<KeywordPlanIdeaServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) => new KeywordPlanIdeaServiceClientBuilder().BuildAsync(cancellationToken); /// <summary> /// Synchronously creates a <see cref="KeywordPlanIdeaServiceClient"/> using the default credentials, endpoint /// and settings. To specify custom credentials or other settings, use /// <see cref="KeywordPlanIdeaServiceClientBuilder"/>. /// </summary> /// <returns>The created <see cref="KeywordPlanIdeaServiceClient"/>.</returns> public static KeywordPlanIdeaServiceClient Create() => new KeywordPlanIdeaServiceClientBuilder().Build(); /// <summary> /// Creates a <see cref="KeywordPlanIdeaServiceClient"/> which uses the specified call invoker for remote /// operations. /// </summary> /// <param name="callInvoker"> /// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null. /// </param> /// <param name="settings">Optional <see cref="KeywordPlanIdeaServiceSettings"/>.</param> /// <returns>The created <see cref="KeywordPlanIdeaServiceClient"/>.</returns> internal static KeywordPlanIdeaServiceClient Create(grpccore::CallInvoker callInvoker, KeywordPlanIdeaServiceSettings settings = null) { gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker)); grpcinter::Interceptor interceptor = settings?.Interceptor; if (interceptor != null) { callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor); } KeywordPlanIdeaService.KeywordPlanIdeaServiceClient grpcClient = new KeywordPlanIdeaService.KeywordPlanIdeaServiceClient(callInvoker); return new KeywordPlanIdeaServiceClientImpl(grpcClient, settings); } /// <summary> /// Shuts down any channels automatically created by <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not /// affected. /// </summary> /// <remarks> /// After calling this method, further calls to <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down /// by another call to this method. /// </remarks> /// <returns>A task representing the asynchronous shutdown operation.</returns> public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync(); /// <summary>The underlying gRPC KeywordPlanIdeaService client</summary> public virtual KeywordPlanIdeaService.KeywordPlanIdeaServiceClient GrpcClient => throw new sys::NotImplementedException(); /// <summary> /// Returns a list of keyword ideas. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [CollectionSizeError]() /// [HeaderError]() /// [InternalError]() /// [KeywordPlanIdeaError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A pageable sequence of <see cref="GenerateKeywordIdeaResult"/> resources.</returns> public virtual gax::PagedEnumerable<GenerateKeywordIdeaResponse, GenerateKeywordIdeaResult> GenerateKeywordIdeas(GenerateKeywordIdeasRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Returns a list of keyword ideas. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [CollectionSizeError]() /// [HeaderError]() /// [InternalError]() /// [KeywordPlanIdeaError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A pageable asynchronous sequence of <see cref="GenerateKeywordIdeaResult"/> resources.</returns> public virtual gax::PagedAsyncEnumerable<GenerateKeywordIdeaResponse, GenerateKeywordIdeaResult> GenerateKeywordIdeasAsync(GenerateKeywordIdeasRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); } /// <summary>KeywordPlanIdeaService client wrapper implementation, for convenient use.</summary> /// <remarks> /// Service to generate keyword ideas. /// </remarks> public sealed partial class KeywordPlanIdeaServiceClientImpl : KeywordPlanIdeaServiceClient { private readonly gaxgrpc::ApiCall<GenerateKeywordIdeasRequest, GenerateKeywordIdeaResponse> _callGenerateKeywordIdeas; /// <summary> /// Constructs a client wrapper for the KeywordPlanIdeaService service, with the specified gRPC client and /// settings. /// </summary> /// <param name="grpcClient">The underlying gRPC client.</param> /// <param name="settings"> /// The base <see cref="KeywordPlanIdeaServiceSettings"/> used within this client. /// </param> public KeywordPlanIdeaServiceClientImpl(KeywordPlanIdeaService.KeywordPlanIdeaServiceClient grpcClient, KeywordPlanIdeaServiceSettings settings) { GrpcClient = grpcClient; KeywordPlanIdeaServiceSettings effectiveSettings = settings ?? KeywordPlanIdeaServiceSettings.GetDefault(); gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings); _callGenerateKeywordIdeas = clientHelper.BuildApiCall<GenerateKeywordIdeasRequest, GenerateKeywordIdeaResponse>(grpcClient.GenerateKeywordIdeasAsync, grpcClient.GenerateKeywordIdeas, effectiveSettings.GenerateKeywordIdeasSettings).WithGoogleRequestParam("customer_id", request => request.CustomerId); Modify_ApiCall(ref _callGenerateKeywordIdeas); Modify_GenerateKeywordIdeasApiCall(ref _callGenerateKeywordIdeas); OnConstruction(grpcClient, effectiveSettings, clientHelper); } partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>; partial void Modify_GenerateKeywordIdeasApiCall(ref gaxgrpc::ApiCall<GenerateKeywordIdeasRequest, GenerateKeywordIdeaResponse> call); partial void OnConstruction(KeywordPlanIdeaService.KeywordPlanIdeaServiceClient grpcClient, KeywordPlanIdeaServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper); /// <summary>The underlying gRPC KeywordPlanIdeaService client</summary> public override KeywordPlanIdeaService.KeywordPlanIdeaServiceClient GrpcClient { get; } partial void Modify_GenerateKeywordIdeasRequest(ref GenerateKeywordIdeasRequest request, ref gaxgrpc::CallSettings settings); /// <summary> /// Returns a list of keyword ideas. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [CollectionSizeError]() /// [HeaderError]() /// [InternalError]() /// [KeywordPlanIdeaError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A pageable sequence of <see cref="GenerateKeywordIdeaResult"/> resources.</returns> public override gax::PagedEnumerable<GenerateKeywordIdeaResponse, GenerateKeywordIdeaResult> GenerateKeywordIdeas(GenerateKeywordIdeasRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_GenerateKeywordIdeasRequest(ref request, ref callSettings); return new gaxgrpc::GrpcPagedEnumerable<GenerateKeywordIdeasRequest, GenerateKeywordIdeaResponse, GenerateKeywordIdeaResult>(_callGenerateKeywordIdeas, request, callSettings); } /// <summary> /// Returns a list of keyword ideas. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [CollectionSizeError]() /// [HeaderError]() /// [InternalError]() /// [KeywordPlanIdeaError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A pageable asynchronous sequence of <see cref="GenerateKeywordIdeaResult"/> resources.</returns> public override gax::PagedAsyncEnumerable<GenerateKeywordIdeaResponse, GenerateKeywordIdeaResult> GenerateKeywordIdeasAsync(GenerateKeywordIdeasRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_GenerateKeywordIdeasRequest(ref request, ref callSettings); return new gaxgrpc::GrpcPagedAsyncEnumerable<GenerateKeywordIdeasRequest, GenerateKeywordIdeaResponse, GenerateKeywordIdeaResult>(_callGenerateKeywordIdeas, request, callSettings); } } public partial class GenerateKeywordIdeasRequest : gaxgrpc::IPageRequest { } public partial class GenerateKeywordIdeaResponse : gaxgrpc::IPageResponse<GenerateKeywordIdeaResult> { /// <summary>Returns an enumerator that iterates through the resources in this response.</summary> public scg::IEnumerator<GenerateKeywordIdeaResult> GetEnumerator() => Results.GetEnumerator(); sc::IEnumerator sc::IEnumerable.GetEnumerator() => GetEnumerator(); } }
using System; using System.Collections.Generic; using System.Data; using System.Data.Common; using System.Data.SqlClient; using System.Text; using System.Reflection; using System.Xml; using System.Web; namespace Codes.October.Tools { public static class Database { public static void CopyGenericToDataTable<T>(IEnumerable<T> ie, ref DataTable dt) { PropertyInfo[] properties = typeof(T).GetProperties(); foreach (PropertyInfo prop in properties) { dt.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType); } foreach (var item in ie) { DataRow row = dt.NewRow(); foreach (PropertyInfo prop in properties) { var itemValue = prop.GetValue(item, new object[] { }); row[prop.Name] = itemValue ?? DBNull.Value; } dt.Rows.Add(row); } } } public sealed class GetParameterMapper : IParameterMapper { public void AssignParameters(DbCommand command, object[] parameterValues) { /* * The below needs to be combined with GetParameters under it. * AssignParameters is used by the parameter mapper automatically, so the name is necessary. * GetParameters, on the other hand, is accessed directly. */ Dictionary<string, object> dict; try { dict = (Dictionary<string, object>)parameterValues[0]; foreach (KeyValuePair<string, object> kv in dict) { SqlParameter parameter = (SqlParameter)command.CreateParameter(); parameter.ParameterName = String.Format("@{0}", kv.Key); this.SetParameter(ref parameter, kv); command.Parameters.Add(parameter); } } finally { dict = null; } } public DbParameter[] GetParameters(Dictionary<string, object> dict, bool addOutput) { DbParameter[] parameters; int pos = 0; int paramCount = (addOutput) ? dict.Count + 2 : dict.Count; try { parameters = new DbParameter[paramCount]; foreach (KeyValuePair<string, object> kv in dict) { SqlParameter parameter = new SqlParameter(); parameter.ParameterName = String.Format("@{0}", kv.Key); SetParameter(ref parameter, kv); parameters[pos] = parameter; pos++; } if (addOutput) { parameters[parameters.Length - 2] = new SqlParameter() { ParameterName = "@IDENTITY", DbType = DbType.Int32, Direction = ParameterDirection.Output, }; parameters[parameters.Length - 1] = new SqlParameter() { ParameterName = "@ROWCOUNT", DbType = DbType.Int32, Direction = ParameterDirection.Output, }; } return parameters; } finally { } } public DbParameter[] GetParameters(Dictionary<string, object> dict) { return GetParameters(dict, false); } private void SetParameter(ref SqlParameter parameter, KeyValuePair<string, object> kv) { KeyValuePair<string, object> values = (KeyValuePair<string, object>)kv.Value; switch (values.Key.ToLower()) { case "byte": parameter.DbType = DbType.Byte; if (values.Value != null) { parameter.Value = (byte)values.Value; } else { parameter.Value = DBNull.Value; } break; case "short": parameter.DbType = DbType.Int16; if (values.Value != null) { parameter.Value = (short)values.Value; } else { parameter.Value = DBNull.Value; } break; case "long": parameter.DbType = DbType.Int64; if (values.Value != null) { parameter.Value = (long)values.Value; } else { parameter.Value = DBNull.Value; } break; case "int": parameter.DbType = DbType.Int32; if (values.Value != null) { parameter.Value = (int)values.Value; } else { parameter.Value = DBNull.Value; } break; case "bool": parameter.DbType = DbType.Boolean; if (values.Value != null) { parameter.Value = (bool)values.Value; } else { parameter.Value = DBNull.Value; } break; case "datetime": parameter.DbType = DbType.DateTime; if (values.Value != null) { parameter.Value = (DateTime)values.Value; } else { parameter.Value = DBNull.Value; } break; case "date": parameter.DbType = DbType.Date; if (values.Value != null) { parameter.Value = (DateTime)values.Value; } else { parameter.Value = DBNull.Value; } break; case "timespan": parameter.SqlDbType = SqlDbType.Time; if (values.Value != null) { parameter.Value = (TimeSpan)values.Value; } else { parameter.Value = DBNull.Value; } break; case "string": parameter.DbType = DbType.String; if (values.Value != null) { parameter.Value = (string)values.Value; } else { parameter.Value = DBNull.Value; } break; case "guid": parameter.DbType = DbType.Guid; if (values.Value != null) { parameter.Value = (Guid)values.Value; } else { parameter.Value = DBNull.Value; } break; case "byte[]": parameter.DbType = DbType.Binary; if (values.Value != null) { parameter.Value = values.Value; } else { parameter.Value = DBNull.Value; } break; case "double": parameter.DbType = DbType.Double; if (values.Value != null) { parameter.Value = (double)values.Value; } else { parameter.Value = DBNull.Value; } break; case "decimal": parameter.DbType = DbType.Decimal; if (values.Value != null) { parameter.Value = (decimal)values.Value; } else { parameter.Value = DBNull.Value; } break; default: throw new Exception("Error: Parameter type has not been set."); } } } }
namespace Nancy.Tests.Functional.Tests { using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Nancy.Cookies; using Nancy.ErrorHandling; using Nancy.IO; using Nancy.Responses.Negotiation; using Nancy.Testing; using Nancy.Tests.Functional.Modules; using Nancy.Tests.xUnitExtensions; using Xunit; using Xunit.Extensions; public class ContentNegotiationFixture { [Fact] public async Task Should_return_int_value_from_get_route_as_response_with_status_code_set_to_value() { // Given var module = new ConfigurableNancyModule(with => { with.Get("/int", (x,m) => 200); }); var browser = new Browser(with => { with.Module(module); }); // When var response = await browser.Get("/int"); // Then Assert.Equal((HttpStatusCode)200, response.StatusCode); } [Fact] public async Task Should_return_string_value_from_get_route_as_response_with_content_set_as_value() { // Given var module = new ConfigurableNancyModule(with => { with.Get("/string", (x, m) => "hello"); }); var browser = new Browser(with => { with.Module(module); }); // When var response = await browser.Get("/string"); // Then Assert.Equal("hello", response.Body.AsString()); } [Fact] public async Task Should_return_httpstatuscode_value_from_get_route_as_response_with_content_set_as_value() { // Given var module = new ConfigurableNancyModule(with => { with.Get("/httpstatuscode", (x, m) => HttpStatusCode.Accepted); }); var browser = new Browser(with => { with.Module(module); }); // When var response = await browser.Get("/httpstatuscode"); // Then Assert.Equal(HttpStatusCode.Accepted, response.StatusCode); } [Fact] public async Task Should_return_action_value_as_response_with_content_set_as_value() { // Given var module = new ConfigurableNancyModule(with => { with.Get("/action", (x, m) => { Action<Stream> result = stream => { var wrapper = new UnclosableStreamWrapper(stream); using (var writer = new StreamWriter(wrapper)) { writer.Write("Hiya Nancy!"); } }; return result; }); }); var browser = new Browser(with => { with.Module(module); }); // When var response = await browser.Get("/action"); // Then Assert.Equal("Hiya Nancy!", response.Body.AsString()); } [Fact] public async Task Should_add_negotiated_headers_to_response() { // Given var module = new ConfigurableNancyModule(with => { with.Get("/headers", (x, m) => { var context = new NancyContext(); var negotiator = new Negotiator(context); negotiator.WithHeader("foo", "bar"); return negotiator; }); }); var browser = new Browser(with => { with.ResponseProcessor<TestProcessor>(); with.Module(module); }); // When var response = await browser.Get("/headers"); // Then Assert.True(response.Headers.ContainsKey("foo")); Assert.Equal("bar", response.Headers["foo"]); } [Fact] public async Task Should_set_reason_phrase_on_response() { // Given var module = new ConfigurableNancyModule(with => { with.Get("/customPhrase", (x, m) => { var context = new NancyContext(); var negotiator = new Negotiator(context); negotiator.WithReasonPhrase("The test is passing!").WithStatusCode(404); return negotiator; }); }); var browser = new Browser(with => { with.StatusCodeHandler<DefaultStatusCodeHandler>(); with.ResponseProcessor<TestProcessor>(); with.Module(module); }); // When var response = await browser.Get("/customPhrase"); // Then Assert.Equal("The test is passing!", response.ReasonPhrase); } [Fact] public async Task Should_add_negotiated_content_headers_to_response() { // Given var module = new ConfigurableNancyModule(with => { with.Get("/headers", (x, m) => { var context = new NancyContext(); var negotiator = new Negotiator(context); negotiator.WithContentType("text/xml"); return negotiator; }); }); var browser = new Browser(with => { with.ResponseProcessor<TestProcessor>(); with.Module(module); }); // When var response = await browser.Get("/headers"); // Then Assert.Equal("text/xml", response.Context.Response.ContentType); } [Fact] public async Task Should_apply_default_accept_when_no_accept_header_sent() { // Given var browser = new Browser(with => { with.ResponseProcessor<TestProcessor>(); with.Module(new ConfigurableNancyModule(x => { x.Get("/", (parameters, module) => { var context = new NancyContext(); var negotiator = new Negotiator(context); return negotiator; }); })); }); // When var response = await browser.Get("/"); // Then Assert.Equal(HttpStatusCode.OK, response.StatusCode); } [Fact] public async Task Should_boost_html_priority_if_set_to_the_same_priority_as_others() { // Given var browser = new Browser(with => { with.ResponseProcessor<TestProcessor>(); with.Module(new ConfigurableNancyModule(x => { x.Get("/", (parameters, module) => { var context = new NancyContext(); var negotiator = new Negotiator(context); negotiator.WithAllowedMediaRange("application/xml"); negotiator.WithAllowedMediaRange("text/html"); return negotiator; }); })); }); // When var response = await browser.Get("/", with => { with.Header("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; ru-RU) AppleWebKit/533.19.4 (KHTML, like Gecko) Version/5.0.3 Safari/533.19.4"); with.Accept("application/xml", 0.9m); with.Accept("text/html", 0.9m); }); // Then Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.True(response.Body.AsString().Contains("text/html"), "Media type mismatch"); } [Fact] public async Task Should_override_with_extension() { // Given var browser = new Browser(with => { with.ResponseProcessor<TestProcessor>(); with.Module(new ConfigurableNancyModule(x => { x.Get("/test", (parameters, module) => { var context = new NancyContext(); var negotiator = new Negotiator(context); return negotiator; }); })); }); // When var response = await browser.Get("/test.foo", with => { with.Header("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; ru-RU) AppleWebKit/533.19.4 (KHTML, like Gecko) Version/5.0.3 Safari/533.19.4"); with.Accept("application/xml", 0.9m); with.Accept("text/html", 0.9m); }); // Then Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.True(response.Body.AsString().Contains("foo/bar"), "Media type mismatch"); } [Fact] public async Task Should_response_with_notacceptable_when_route_does_not_allow_any_of_the_accepted_formats() { // Given var browser = new Browser(with => { with.ResponseProcessor<TestProcessor>(); with.Module(new ConfigurableNancyModule(x => { x.Get("/test", CreateNegotiatedResponse(config => { config.WithAllowedMediaRange("application/xml"); })); })); }); // When var response = await browser.Get("/test", with => { with.Accept("foo/bar", 0.9m); }); // Then Assert.Equal(HttpStatusCode.NotAcceptable, response.StatusCode); } [Fact] public async Task Should_respond_with_notacceptable_when_no_processor_can_process_media_range() { // Given var browser = new Browser(with => { with.ResponseProcessor<NullProcessor>(); with.Module<NegotiationModule>(); }); // When var response = await browser.Get("/invalid-view-name", with => with.Accept("foo/bar")); // Then Assert.Equal(HttpStatusCode.NotAcceptable, response.StatusCode); } [Fact] public async Task Should_return_that_contains_default_model_when_no_media_range_specific_model_was_declared() { // Given var browser = new Browser(with => { with.ResponseProcessor<ModelProcessor>(); with.Module(new ConfigurableNancyModule(x => { x.Get("/", CreateNegotiatedResponse(config => { config.WithModel("the model"); config.WithAllowedMediaRange("test/test"); })); })); }); // When var response = await browser.Get("/", with => { with.Accept("test/test", 0.9m); }); // Then Assert.Equal("the model", response.Body.AsString()); } [Fact] public async Task Should_return_media_range_specific_model_when_declared() { // Given var browser = new Browser(with => { with.ResponseProcessor<ModelProcessor>(); with.Module(new ConfigurableNancyModule(x => { x.Get("/", CreateNegotiatedResponse(config => { config.WithModel("the model"); config.WithAllowedMediaRange("test/test"); config.WithMediaRangeModel("test/test", "media model"); })); })); }); // When var response = await browser.Get("/", with => { with.Accept("test/test", 0.9m); }); // Then Assert.Equal("media model", response.Body.AsString()); } [Fact] public async Task Should_add_vary_accept_header() { // Given var browser = new Browser(with => { with.ResponseProcessors(typeof(XmlProcessor), typeof(JsonProcessor), typeof(TestProcessor)); with.Module(new ConfigurableNancyModule(x => { x.Get("/", CreateNegotiatedResponse()); })); }); // When var response = await browser.Get("/", with => with.Header("Accept", "application/json")); // Then Assert.True(response.Headers.ContainsKey("Vary")); Assert.True(response.Headers["Vary"].Contains("Accept")); } [Fact] public async Task Should_add_link_header_for_matching_response_processors() { // Given var browser = new Browser(with => { with.ResponseProcessors(typeof(XmlProcessor), typeof(JsonProcessor), typeof(TestProcessor)); with.Module(new ConfigurableNancyModule(x => { x.Get("/", CreateNegotiatedResponse()); })); }); // When var response = await browser.Get("/"); // Then Assert.True(response.Headers["Link"].Contains(@"</.foo>; rel=""foo/bar""")); Assert.True(response.Headers["Link"].Contains(@"</.json>; rel=""application/json""")); Assert.True(response.Headers["Link"].Contains(@"</.xml>; rel=""application/xml""")); } [Fact] public async Task Should_set_negotiated_status_code_to_response_when_set_as_integer() { // Given var browser = new Browser(with => { with.ResponseProcessor<TestProcessor>(); with.Module(new ConfigurableNancyModule(x => { x.Get("/", CreateNegotiatedResponse(config => { config.WithStatusCode(507); })); })); }); // When var response = await browser.Get("/", with => { with.Accept("test/test", 0.9m); }); // Then Assert.Equal(HttpStatusCode.InsufficientStorage, response.StatusCode); } [Fact] public async Task Should_set_negotiated_status_code_to_response_when_set_as_httpstatuscode() { // Given var browser = new Browser(with => { with.ResponseProcessor<TestProcessor>(); with.Module(new ConfigurableNancyModule(x => { x.Get("/", CreateNegotiatedResponse(config => { config.WithStatusCode(HttpStatusCode.InsufficientStorage); })); })); }); // When var response = await browser.Get("/", with => { with.Accept("test/test", 0.9m); }); // Then Assert.Equal(HttpStatusCode.InsufficientStorage, response.StatusCode); } [Fact] public async Task Should_set_negotiated_cookies_to_response() { // Given var negotiatedCookie = new NancyCookie("test", "test"); var browser = new Browser(with => { with.ResponseProcessor<TestProcessor>(); with.Module(new ConfigurableNancyModule(x => { x.Get("/", CreateNegotiatedResponse(config => { config.WithCookie(negotiatedCookie); })); })); }); // When var response = await browser.Get("/", with => { with.Accept("test/test", 0.9m); }); // Then Assert.Same(negotiatedCookie, response.Cookies.First()); } [Fact] public async Task Should_throw_exception_if_view_location_fails() { var browser = new Browser(with => { with.ResponseProcessor<ViewProcessor>(); with.Module(new ConfigurableNancyModule(x => x.Get("/FakeModuleInvalidViewName", CreateNegotiatedResponse(neg => neg.WithView("blahblahblah"))))); }); // When var result = await RecordAsync.Exception(() => browser.Get( "/FakeModuleInvalidViewName", with => { with.Accept("text/html", 1.0m); }) ); // Then Assert.NotNull(result); Assert.Contains("Unable to locate view", result.ToString()); } [Fact] public async Task Should_use_next_processor_if_processor_returns_null() { // Given var browser = new Browser(with => { with.ResponseProcessors(typeof(NullProcessor), typeof(TestProcessor)); with.Module(new ConfigurableNancyModule(x => { x.Get("/test", CreateNegotiatedResponse(config => { config.WithAllowedMediaRange("application/xml"); })); })); }); // When var response = await browser.Get("/test", with => { with.Accept("application/xml", 0.9m); }); // Then var bodyResult = response.Body.AsString(); Assert.True(bodyResult.StartsWith("application/xml"), string.Format("Body should have started with 'application/xml' but was actually '{0}'", bodyResult)); } [Theory] [InlineData("application/xhtml+xml; profile=\"http://www.wapforum. org/xhtml\"")] [InlineData("application/xhtml+xml; q=1; profile=\"http://www.wapforum. org/xhtml\"")] public async Task Should_not_throw_exception_because_of_uncommon_accept_header(string header) { // Given var browser = new Browser(with => { with.ResponseProcessors(typeof(XmlProcessor), typeof(JsonProcessor), typeof(TestProcessor)); with.Module(new ConfigurableNancyModule(x => { x.Get("/", CreateNegotiatedResponse()); })); }); // When var response = await browser.Get("/", with => { with.Header("Accept", header); }); // Then Assert.Equal((HttpStatusCode)200, response.StatusCode); } [Fact] public async Task Should_not_try_and_serve_view_with_invalid_name() { // Given var browser = new Browser(with => with.Module<NegotiationModule>()); // When var result = await RecordAsync.Exception(() => browser.Get("/invalid-view-name")); // Then Assert.True(result.ToString().Contains("Unable to locate view")); } [Fact] public async Task Should_return_response_negotiated_based_on_media_range() { // Given var browser = new Browser(with => with.Module<NegotiationModule>()); // When var result = await browser.Get("/negotiate", with => { with.Accept("text/html"); }); // Then Assert.Equal(HttpStatusCode.SeeOther, result.StatusCode); } [Fact] public async Task Can_negotiate_in_status_code_handler() { // Given var browser = new Browser(with => with.StatusCodeHandler<NotFoundStatusCodeHandler>()); // When var result = await browser.Get("/not-found", with => with.Accept("application/json")); var response = result.Body.DeserializeJson<NotFoundStatusCodeHandlerResult>(); // Then Assert.Equal(HttpStatusCode.OK, result.StatusCode); Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); Assert.Equal("Not Found.", response.Message); } [Fact] public async Task Can_negotiate_in_error_pipeline() { // Given var browser = new Browser(with => with.Module<ThrowingModule>()); // When var jsonResult = await browser.Get("/", with => with.Accept("application/json")); var xmlResult = await browser.Get("/", with => with.Accept("application/xml")); var jsonResponse = jsonResult.Body.DeserializeJson<ThrowingModule.Error>(); var xmlResponse = xmlResult.Body.DeserializeXml<ThrowingModule.Error>(); // Then Assert.Equal("Oh noes!", jsonResponse.Message); Assert.Equal("Oh noes!", xmlResponse.Message); } [Fact] public async Task Should_return_negotiated_not_found_response_when_accept_header_is_html() { // Given var browser = new Browser(with => with.StatusCodeHandler<DefaultStatusCodeHandler>()); var contentType = "text/html"; // When var result = await browser.Get("/not-found", with => with.Accept(contentType)); // Then Assert.Equal(HttpStatusCode.NotFound, result.StatusCode); Assert.Equal(contentType, result.ContentType); } [Fact] public async Task Should_return_negotiated_not_found_response_when_accept_header_is_json() { // Given var browser = new Browser(with => with.StatusCodeHandler<DefaultStatusCodeHandler>()); var contentType = "application/json"; // When var result = await browser.Get("/not-found", with => with.Accept(contentType)); // Then Assert.Equal(HttpStatusCode.NotFound, result.StatusCode); Assert.Equal(string.Format("{0}; charset=utf-8", contentType), result.ContentType); } [Fact] public async Task Should_return_negotiated_not_found_response_when_accept_header_is_xml() { // Given var browser = new Browser(with => with.StatusCodeHandler<DefaultStatusCodeHandler>()); var contentType = "application/xml"; // When var result = await browser.Get("/not-found", with => with.Accept(contentType)); // Then Assert.Equal(HttpStatusCode.NotFound, result.StatusCode); Assert.Equal(contentType, result.ContentType); } private static Func<dynamic, NancyModule, dynamic> CreateNegotiatedResponse(Action<Negotiator> action = null) { return (parameters, module) => { var negotiator = new Negotiator(module.Context); if (action != null) { action.Invoke(negotiator); } return negotiator; }; } /// <summary> /// Test response processor that will accept any type /// and put the content type and model type into the /// response body for asserting against. /// Hacky McHackmeister but it works :-) /// </summary> public class TestProcessor : IResponseProcessor { private const string ResponseTemplate = "{0}\n{1}"; public IEnumerable<Tuple<string, MediaRange>> ExtensionMappings { get { yield return new Tuple<string, MediaRange>("foo", "foo/bar"); } } public ProcessorMatch CanProcess(MediaRange requestedMediaRange, dynamic model, NancyContext context) { return new ProcessorMatch { RequestedContentTypeResult = MatchResult.DontCare, ModelResult = MatchResult.DontCare }; } public Response Process(MediaRange requestedMediaRange, dynamic model, NancyContext context) { return string.Format(ResponseTemplate, requestedMediaRange, model == null ? "None" : model.GetType()); } } public class NullProcessor : IResponseProcessor { public IEnumerable<Tuple<string, MediaRange>> ExtensionMappings { get { yield break; } } public ProcessorMatch CanProcess(MediaRange requestedMediaRange, dynamic model, NancyContext context) { return new ProcessorMatch { RequestedContentTypeResult = MatchResult.ExactMatch, ModelResult = MatchResult.ExactMatch }; } public Response Process(MediaRange requestedMediaRange, dynamic model, NancyContext context) { return null; } } public class ModelProcessor : IResponseProcessor { public IEnumerable<Tuple<string, MediaRange>> ExtensionMappings { get { yield return new Tuple<string, MediaRange>("foo", "foo/bar"); } } public ProcessorMatch CanProcess(MediaRange requestedMediaRange, dynamic model, NancyContext context) { return new ProcessorMatch { RequestedContentTypeResult = MatchResult.DontCare, ModelResult = MatchResult.DontCare }; } public Response Process(MediaRange requestedMediaRange, dynamic model, NancyContext context) { return (string) model; } } private class NegotiationModule : NancyModule { public NegotiationModule() { Get["/invalid-view-name"] = _ => { return this.GetModel(); }; Get["/negotiate"] = parameters => { return Negotiate .WithMediaRangeResponse("text/html", Response.AsRedirect("/")) .WithMediaRangeModel("application/json", new { Name = "Nancy" }); }; } private IEnumerable<Foo> GetModel() { yield return new Foo(); } private class Foo { } } private class NotFoundStatusCodeHandler : IStatusCodeHandler { private readonly IResponseNegotiator responseNegotiator; public NotFoundStatusCodeHandler(IResponseNegotiator responseNegotiator) { this.responseNegotiator = responseNegotiator; } public bool HandlesStatusCode(HttpStatusCode statusCode, NancyContext context) { return statusCode == HttpStatusCode.NotFound; } public void Handle(HttpStatusCode statusCode, NancyContext context) { var error = new NotFoundStatusCodeHandlerResult { StatusCode = statusCode, Message = "Not Found." }; context.Response = this.responseNegotiator.NegotiateResponse(error, context); } } private class NotFoundStatusCodeHandlerResult { public HttpStatusCode StatusCode { get; set; } public string Message { get; set; } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.Linq; using System.ServiceModel; using System.Text; using Microsoft.VisualStudio.TestTools.UnitTesting; using ObjectCreator.Extensions; using ObjectCreator.Helper; namespace ObjectCreatorTest.Test.ClassCreationTest { [TestClass] public class SystemCollectionsClassTest { [TestMethod] public void TestArrayList() { Assert.IsNotNull(ObjectCreatorExtensions.Create<ArrayList>()); } [TestMethod] public void TestBitArray() { Assert.IsNotNull(ObjectCreatorExtensions.Create<BitArray>()); } [TestMethod] public void TestCollectionBase() { Assert.IsNotNull(ObjectCreatorExtensions.Create<CollectionBase>()); } [TestMethod] public void TestDictionaryBase() { Assert.IsNotNull(ObjectCreatorExtensions.Create<DictionaryBase>()); } [TestMethod] public void TestReadOnlyCollectionBase() { Assert.IsNotNull(ObjectCreatorExtensions.Create<ReadOnlyCollectionBase>()); } [TestMethod] public void TestHashtable() { Assert.IsNotNull(ObjectCreatorExtensions.Create<Hashtable>()); } [TestMethod] public void TestQueue() { Assert.IsNotNull(ObjectCreatorExtensions.Create<Queue>()); } [TestMethod] public void TestSortedList() { Assert.IsNotNull(ObjectCreatorExtensions.Create<SortedList>()); } [TestMethod] public void TestStack() { Assert.IsNotNull(ObjectCreatorExtensions.Create<Stack>()); } [TestMethod] public void TestDictionaryEntry() { Assert.IsNotNull(ObjectCreatorExtensions.Create<DictionaryEntry>()); } [TestMethod] public void TestMyEnumerable() { Assert.IsNotNull(ObjectCreatorExtensions.Create<MyEnumerable>()); } private class MyEnumerable : IEnumerable { public IEnumerator GetEnumerator() { return new List<object>().GetEnumerator(); } } } [TestClass] public class SystemCollectionsStructTest { [TestMethod] public void TestDictionaryEntry() { Assert.IsNotNull(ObjectCreatorExtensions.Create<DictionaryEntry>()); } } [TestClass] public class SystemCollectionInterfacesTest { [TestMethod] public void TestICollection() { Assert.IsNotNull(ObjectCreatorExtensions.Create<ICollection>()); } [TestMethod] public void TestIComparer() { Assert.IsNotNull(ObjectCreatorExtensions.Create<IComparer>()); } [TestMethod] public void TestIDictionary() { Assert.IsNotNull(ObjectCreatorExtensions.Create<IDictionary>()); } [TestMethod] public void TestIDictionaryEnumerator() { Assert.IsNotNull(ObjectCreatorExtensions.Create<IDictionaryEnumerator>()); } [TestMethod] public void TestIEnumerable() { Assert.IsNotNull(ObjectCreatorExtensions.Create<IEnumerable>()); } [TestMethod] public void TestIEnumerator() { Assert.IsNotNull(ObjectCreatorExtensions.Create<IEnumerator>()); } [TestMethod] public void TestIEqualityComparer() { Assert.IsNotNull(ObjectCreatorExtensions.Create<IEqualityComparer>()); } [TestMethod] public void TestIList() { Assert.IsNotNull(ObjectCreatorExtensions.Create<IList>()); } [TestMethod] public void TestIStructuralComparable() { Assert.IsNotNull(ObjectCreatorExtensions.Create<IStructuralComparable>()); } [TestMethod] public void TestIStructuralEquatable() { Assert.IsNotNull(ObjectCreatorExtensions.Create<IStructuralEquatable>()); } [TestMethod] public void TestOwnIEnumerable() { Assert.IsNotNull(ObjectCreatorExtensions.Create<IMyEnumerable>()); } // Test class to test own implementation of IEnumerable. public interface IMyEnumerable : IEnumerable { } } [TestClass] public class SystemCollectionCreateAnyItems { private static readonly ObjectCreationStrategy ObjectCreationStrategy = new ObjectCreationStrategy(false, false, 4, null); private static readonly UniqueDefaultData UniqueDefaultData = new UniqueDefaultData(); private static readonly List<Type> EnumerationTypes = new List<Type> { typeof(ArrayList), typeof(Hashtable), typeof(Queue), typeof(SortedList), typeof(Stack), typeof(HybridDictionary), typeof(ListDictionary), typeof(NameValueCollection), typeof(OrderedDictionary), typeof(StringCollection), typeof(StringDictionary), typeof(UriSchemeKeyedCollection), typeof(IEnumerable), typeof(ICollection), typeof(IList), typeof(IDictionary), typeof(IOrderedDictionary) }; [TestMethod] public void TestEnumerationWithAnyItems() { var analyzeResult = Analyze(EnumerationTypes).ToList(); Assert.IsFalse(analyzeResult.Any(), ToErrorString(analyzeResult)); } private static IEnumerable<string> Analyze(List<Type> typesToCreate) { foreach (var type in typesToCreate) { var result = type.Create(UniqueDefaultData, ObjectCreationStrategy).Cast<IEnumerable>().OfType<object>(); if (result.Count() != ObjectCreationStrategy.EnumerationCount) { yield return $"Expected type:{type} has not expected items count {ObjectCreationStrategy.EnumerationCount}"; } } } private static string ToErrorString(IEnumerable<string> errors) { var stringBuilder = new StringBuilder(); errors.ForEach(e => stringBuilder.AppendLine(e)); return stringBuilder.ToString(); } } }
using System.Collections.Generic; using UnityEngine; #if UNITY_EDITOR using UnityEditor; #endif [System.Serializable] public class tk2dSpriteCollectionIndex { public string name; public string spriteCollectionGUID; public string spriteCollectionDataGUID; public string[] spriteNames = new string[0]; public string[] spriteTextureGUIDs = new string[0]; public string[] spriteTextureTimeStamps = new string[0]; public bool managedSpriteCollection = false; public bool loadable = false; public string assetName = ""; public int version; } [System.Serializable] public class tk2dGenericIndexItem { public tk2dGenericIndexItem(string guid) { this.assetGUID = guid; } public string assetGUID; public string dataGUID; public bool managed = false; public bool loadable = false; public string AssetName { get { string assetName = "unknown"; #if UNITY_EDITOR assetName = System.IO.Path.GetFileNameWithoutExtension(AssetDatabase.GUIDToAssetPath(assetGUID)); #endif return assetName; } } public T GetAsset<T>() where T : UnityEngine.Object { #if UNITY_EDITOR return AssetDatabase.LoadAssetAtPath(AssetDatabase.GUIDToAssetPath(assetGUID), typeof(T)) as T; #else return null; #endif } public T GetData<T>() where T : UnityEngine.Object { #if UNITY_EDITOR return AssetDatabase.LoadAssetAtPath(AssetDatabase.GUIDToAssetPath(dataGUID), typeof(T)) as T; #else return null; #endif } } public class tk2dIndex : ScriptableObject { public int version = 0; public static int CURRENT_VERSION = 4; [SerializeField] List<tk2dGenericIndexItem> spriteAnimationIndex = new List<tk2dGenericIndexItem>(); [SerializeField] List<tk2dGenericIndexItem> fontIndex = new List<tk2dGenericIndexItem>(); [SerializeField] List<tk2dSpriteCollectionIndex> spriteCollectionIndex = new List<tk2dSpriteCollectionIndex>(); public tk2dSpriteCollectionIndex[] GetSpriteCollectionIndex() { #if UNITY_EDITOR int i = 0; string assetsPath = Application.dataPath.Substring(0, Application.dataPath.Length - 6); foreach (var v in spriteCollectionIndex) { if (v != null) { string thisAssetPath = AssetDatabase.GUIDToAssetPath(v.spriteCollectionDataGUID); string p = assetsPath + thisAssetPath; if (thisAssetPath != null && !System.IO.File.Exists(p)) { spriteCollectionIndex[i] = null; } } ++i; } #endif spriteCollectionIndex.RemoveAll(item => item == null); return spriteCollectionIndex.ToArray(); } public void AddSpriteCollectionData(tk2dSpriteCollectionData sc) { #if UNITY_EDITOR // prune list GetSpriteCollectionIndex(); spriteCollectionIndex.RemoveAll(item => item == null); string guid = AssetDatabase.AssetPathToGUID(AssetDatabase.GetAssetPath(sc)); bool existing = false; tk2dSpriteCollectionIndex indexEntry = null; foreach (var v in spriteCollectionIndex) { if (v.spriteCollectionDataGUID == guid) { indexEntry = v; existing = true; break; } } if (indexEntry == null) indexEntry = new tk2dSpriteCollectionIndex(); indexEntry.name = sc.spriteCollectionName; indexEntry.spriteCollectionDataGUID = guid; indexEntry.spriteCollectionGUID = sc.spriteCollectionGUID; indexEntry.spriteNames = new string[sc.spriteDefinitions.Length]; indexEntry.spriteTextureGUIDs = new string[sc.spriteDefinitions.Length]; indexEntry.spriteTextureTimeStamps = new string[sc.spriteDefinitions.Length]; indexEntry.version = sc.version; indexEntry.managedSpriteCollection = sc.managedSpriteCollection; indexEntry.loadable = sc.loadable; indexEntry.assetName = sc.assetName; for (int i = 0; i < sc.spriteDefinitions.Length; ++i) { var s = sc.spriteDefinitions[i]; if (s != null) { indexEntry.spriteNames[i] = sc.spriteDefinitions[i].name; indexEntry.spriteTextureGUIDs[i] = sc.spriteDefinitions[i].sourceTextureGUID; string assetPath = AssetDatabase.GUIDToAssetPath(indexEntry.spriteTextureGUIDs[i]); if (assetPath.Length > 0 && System.IO.File.Exists(assetPath)) indexEntry.spriteTextureTimeStamps[i] = (System.IO.File.GetLastWriteTime(assetPath) - new System.DateTime(1970, 1, 1, 0, 0, 0, 0)).TotalSeconds.ToString(); else indexEntry.spriteTextureTimeStamps[i] = "0"; } else { indexEntry.spriteNames[i] = ""; indexEntry.spriteTextureGUIDs[i] = ""; indexEntry.spriteTextureTimeStamps[i] = ""; } } if (sc.spriteCollectionPlatforms != null && sc.spriteCollectionPlatforms.Length > 0) { indexEntry.spriteNames = new string[] { "dummy" }; indexEntry.spriteTextureGUIDs = new string[] { "" }; indexEntry.spriteTextureTimeStamps = new string[] { "0" }; } if (!existing) spriteCollectionIndex.Add(indexEntry); #endif } void PruneGenericList(ref List<tk2dGenericIndexItem> list) { #if UNITY_EDITOR for (int i = 0; i < list.Count; ++i) { if (list[i] != null && AssetDatabase.GUIDToAssetPath(list[i].assetGUID).Length == 0) list[i] = null; } list.RemoveAll(item => item == null); #endif } public tk2dGenericIndexItem[] GetSpriteAnimations() { PruneGenericList(ref spriteAnimationIndex); return spriteAnimationIndex.ToArray(); } public void AddSpriteAnimation(tk2dSpriteAnimation anim) { #if UNITY_EDITOR string guid = AssetDatabase.AssetPathToGUID(AssetDatabase.GetAssetPath(anim)); PruneGenericList(ref spriteAnimationIndex); foreach (tk2dGenericIndexItem v in spriteAnimationIndex) if (v.assetGUID == guid) return; spriteAnimationIndex.Add(new tk2dGenericIndexItem(guid)); #endif } public tk2dGenericIndexItem[] GetFonts() { PruneGenericList(ref fontIndex); return fontIndex.ToArray(); } public void AddOrUpdateFont(tk2dFont font) { #if UNITY_EDITOR string guid = AssetDatabase.AssetPathToGUID(AssetDatabase.GetAssetPath(font)); PruneGenericList(ref fontIndex); tk2dGenericIndexItem item = null; foreach (tk2dGenericIndexItem v in fontIndex) if (v.assetGUID == guid) { item = v; break; } if (item == null) // not found { item = new tk2dGenericIndexItem(guid); fontIndex.Add(item); } item.loadable = font.loadable; item.managed = (font.data == null) ? false : font.data.managedFont; item.dataGUID = AssetDatabase.AssetPathToGUID(AssetDatabase.GetAssetPath(font.data)); #endif } }
using System; using System.Collections; using System.ComponentModel; using System.Drawing; using System.Data; using System.Windows.Forms; namespace Hydra.Framework.Geometric { public class SplineObject : IMapviewObject,ICloneable, IPersist { #region Private members of Spline Object public event GraphicEvents GraphicSelected; public ArrayList m_points = new ArrayList(); private bool isselected = false; private bool isfilled=false; private bool visible=true; private bool showtooptip=false; private bool iscurrent=true; private bool islocked=false; private bool isdisabled=false; private bool showhandle=false; private int handlesize=6; private Color fillcolor=Color.Cyan; private Color normalcolor= Color.Yellow; private Color selectcolor= Color.Red; private Color disabledcolor= Color.Gray; private int linewidth=2; public PointF[] points; private string xml=""; #endregion #region Constructors of Spline Object public SplineObject(ArrayList points) { m_points.Clear(); foreach(PointF item in points) { m_points.Add(item); } } public SplineObject(SplineObject po){} #endregion #region Methods of ICloneable public object Clone() { return new SplineObject(this); } #endregion #region Properties of Spline Object public PointF[] Vertices { get{return points;} set{points=value;} } [Category("Colors" ),Description("The disabled graphic object will be drawn using this pen")] public Color DisabledColor { get{return disabledcolor;} set{disabledcolor=value;} } [Category("Colors" ),Description("The selected graphic object willbe drawn using this pen")] public Color SelectColor { get{return selectcolor;} set{selectcolor=value;} } [Category("Colors" ),Description("The graphic object willbe drawn using this pen")] public Color NormalColor { get{return normalcolor;} set{normalcolor=value;} } [DefaultValue(2),Category("AbstractStyle"),Description("The gives the line thickness of the graphic object")] public int LineWidth { get{return linewidth;} set{linewidth=value;} } [Category("Appearance"),Description("The graphic object will be filled with a given color or pattern")] public bool IsFilled{get{return isfilled;}set{isfilled=value;} } [Category("Appearance"), Description("Determines whether the object is visible or hidden")] public bool Visible { get{return visible;} set{visible=value;} } [Category("Appearance"), Description("Determines whether the tooltip information to be shown or not")] public bool ShowToopTip { get{return showtooptip;} set{showtooptip=value;} } [Category("Appearance"), Description("Determines whether the object is in current selected legend or not")] public bool IsCurrent { get{return iscurrent;} set{iscurrent=value;} } [Category("Appearance"), Description("Determines whether the object is locked from the current user or not")] public bool IsLocked { get{return islocked;} set{islocked=value;} } [Category("Appearance"), Description("Determines whether the object is disabled from editing")] public bool IsDisabled { get{return isdisabled;} set{isdisabled=value;} } [Category("Appearance"), Description("Determines whether the object is in edit mode")] public bool IsEdit { get{return showhandle;} set{ isselected=true; showhandle=value;} } #endregion #region Method of Spline Object public bool IsSelected() { return isselected; } public void Select(bool m) { isselected = m; } public bool IsObjectAt(PointF pnt,float dist) { double min_dist = 100000; for(int i=0; i<m_points.Count-1; i++) { PointF p1 = (PointF)m_points[i]; PointF p2 = (PointF)m_points[i+1]; double curr_dist = GeoUtil.DistanceBetweenPointToSegment(p1,p2,pnt); if(min_dist>curr_dist) min_dist = curr_dist; } return Math.Sqrt(min_dist) < dist; } public void Insert(PointF pt,int i) { m_points.Insert(i,pt); } public void Insert(PointF[] pt, int i) { m_points.InsertRange(i,pt); } public Rectangle BoundingBox() { int x1=(int)((PointF)(m_points[0])).X; int y1=(int)((PointF)(m_points[0])).Y; int x2=(int)((PointF)(m_points[0])).X; int y2=(int)((PointF)(m_points[0])).Y; for(int i=0; i<m_points.Count; i++) { if((int)((PointF)m_points[i]).X < x1) x1 = (int)((PointF)m_points[i]).X; else if((int)((PointF)m_points[i]).X > x2) x2 = (int)((PointF)m_points[i]).X; if((int)((PointF)m_points[i]).Y < y1) y1 = (int)((PointF)m_points[i]).Y; else if((int)((PointF)m_points[i]).Y > y2) y2 = (int)((PointF)m_points[i]).Y; } return new Rectangle((int)x1,(int)y1,(int)x2,(int)y2); } public float X() { return ((PointF)m_points[0]).X; } public float Y() { return ((PointF)m_points[0]).Y; } public void Move(PointF p) { float dx = p.X-((PointF)m_points[0]).X; float dy = p.Y-((PointF)m_points[0]).Y; for(int i=0; i<m_points.Count; i++) { PointF cp = new PointF(((PointF)m_points[i]).X + dx, ((PointF)m_points[i]).Y + dy); m_points[i] = cp; } } public void MoveBy(float dx,float dy) { for(int i=0; i<m_points.Count; i++) { PointF cp = new PointF(((PointF)m_points[i]).X + dx, ((PointF)m_points[i]).Y + dy); m_points[i] = cp; } } public void Scale(int scale) { for(int i=0; i<m_points.Count; i++) { PointF cp = new PointF(((PointF)m_points[i]).X * scale, ((PointF)m_points[i]).Y + scale); m_points[i] = cp; } } public void Rotate(float radians) { // } public void RotateAt(PointF pt) { // } public void RoateAt(Point pt) { // } public void Draw(Graphics graph,System.Drawing.Drawing2D.Matrix trans) { if (visible) { // create 0,0 and width,height points PointF [] points = new PointF[m_points.Count]; m_points.CopyTo(0,points,0,m_points.Count); trans.TransformPoints(points); if(isselected) { graph.DrawBeziers(new Pen(selectcolor,linewidth),points); if (showhandle) { for (int i=0; i<m_points.Count; i++) { graph.FillRectangle(new SolidBrush(fillcolor),points[i].X-handlesize/2,points[i].Y-handlesize/2,handlesize,handlesize); graph.DrawRectangle(new Pen(Color.Black,1),points[i].X-handlesize/2,points[i].Y-handlesize/2,handlesize,handlesize); } } } else if (isdisabled || islocked) { graph.DrawBeziers(new Pen(disabledcolor,linewidth), points); } else { graph.DrawBeziers(new Pen(normalcolor,linewidth), points); } } } #endregion #region Method of IPersist public string ToXML { get{return xml;} set{xml=value;} } public string ToVML { get{return xml;} set{xml=value;} } public string ToGML { get{return xml;} set{xml=value;} } public string ToSVG { get{return xml;} set{xml=value;} } #endregion } }
using System; using System.Collections.Generic; using System.Text; using SharpMap.Layers; using SharpMap; using SharpMap.Geometries; using System.Collections.ObjectModel; using System.Drawing.Drawing2D; using Ptv.Controls.Map.Interface; namespace Ptv.Controls.Map { public class InteractiveLayer : Layer { /// <summary> /// Initializes a new layer /// </summary> /// <param name="layername">Name of layer</param> public InteractiveLayer(string layername) { this.Style = new SharpMap.Styles.VectorStyle(); this.LayerName = layername; this.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias; } /// <summary> /// Initializes a new layer with a specified datasource /// </summary> /// <param name="layername">Name of layer</param> /// <param name="dataSource">Data source</param> public InteractiveLayer(string layername, SharpMap.Data.Providers.IProvider dataSource) : this(layername) { _DataSource = dataSource; } private SharpMap.Rendering.Thematics.ITheme _theme; /// <summary> /// Gets or sets thematic settings for the layer. Set to null to ignore thematics /// </summary> public SharpMap.Rendering.Thematics.ITheme Theme { get { return _theme; } set { _theme = value; } } private bool _ClippingEnabled = false; /// <summary> /// Specifies whether polygons should be clipped prior to rendering /// </summary> /// <remarks> /// <para>Clipping will clip <see cref="SharpMap.Geometries.Polygon"/> and /// <see cref="SharpMap.Geometries.MultiPolygon"/> to the current view prior /// to rendering the object.</para> /// <para>Enabling clipping might improve rendering speed if you are rendering /// only small portions of very large objects.</para> /// </remarks> public bool ClippingEnabled { get { return _ClippingEnabled; } set { _ClippingEnabled = value; } } private System.Drawing.Drawing2D.SmoothingMode _SmoothingMode; /// <summary> /// Render whether smoothing (antialiasing) is applied to lines and curves and the edges of filled areas /// </summary> public System.Drawing.Drawing2D.SmoothingMode SmoothingMode { get { return _SmoothingMode; } set { _SmoothingMode = value; } } private SharpMap.Data.Providers.IProvider _DataSource; /// <summary> /// Gets or sets the datasource /// </summary> public SharpMap.Data.Providers.IProvider DataSource { get { return _DataSource; } set { _DataSource = value; } } private SharpMap.Styles.VectorStyle _Style; /// <summary> /// Gets or sets the rendering style of the vector layer. /// </summary> public SharpMap.Styles.VectorStyle Style { get { return _Style; } set { _Style = value; } } #region ILayer Members /// <summary> /// Renders the layer to a graphics object /// </summary> /// <param name="g">Graphics object reference</param> /// <param name="map">Map which is rendered</param> public override void Render(System.Drawing.Graphics g, SharpMap.Map map) { if (map.Center == null) throw (new ApplicationException("Cannot render map. View center not specified")); g.SmoothingMode = this.SmoothingMode; SharpMap.Geometries.BoundingBox envelope = map.Envelope; //View to render if (this.CoordinateTransformation != null) envelope = SharpMap.CoordinateSystems.Transformations.GeometryTransform.TransformBox(envelope, this.CoordinateTransformation.MathTransform.Inverse()); //List<SharpMap.Geometries.Geometry> features = this.DataSource.GetGeometriesInView(map.Envelope); if (this.DataSource == null) throw (new ApplicationException("DataSource property not set on layer '" + this.LayerName + "'")); //If thematics is enabled, we use a slighty different rendering approach if (this.Theme != null) { SharpMap.Data.FeatureDataSet ds = new SharpMap.Data.FeatureDataSet(); this.DataSource.Open(); this.DataSource.ExecuteIntersectionQuery(envelope, ds); this.DataSource.Close(); SharpMap.Data.FeatureDataTable features = (SharpMap.Data.FeatureDataTable)ds.Tables[0]; if (this.CoordinateTransformation != null) for (int i = 0; i < features.Count; i++) features[i].Geometry = SharpMap.CoordinateSystems.Transformations.GeometryTransform.TransformGeometry(features[i].Geometry, this.CoordinateTransformation.MathTransform); //Linestring outlines is drawn by drawing the layer once with a thicker line //before drawing the "inline" on top. if (Style.EnableOutline) { //foreach (SharpMap.Geometries.Geometry feature in features) for (int i = 0; i < features.Count; i++) { SharpMap.Data.FeatureDataRow feature = features[i]; //Draw background of all line-outlines first if(feature.Geometry is SharpMap.Geometries.LineString) { SharpMap.Styles.VectorStyle outlinestyle1 = this.Theme.GetStyle(feature) as SharpMap.Styles.VectorStyle; if (outlinestyle1.Enabled && outlinestyle1.EnableOutline) SharpMap.Rendering.VectorRenderer.DrawLineString(g, feature.Geometry as LineString, outlinestyle1.Outline, map); } else if(feature.Geometry is SharpMap.Geometries.MultiLineString) { SharpMap.Styles.VectorStyle outlinestyle2 = this.Theme.GetStyle(feature) as SharpMap.Styles.VectorStyle; if (outlinestyle2.Enabled && outlinestyle2.EnableOutline) SharpMap.Rendering.VectorRenderer.DrawMultiLineString(g, feature.Geometry as MultiLineString, outlinestyle2.Outline, map); } } } for(int i=0;i<features.Count;i++) { SharpMap.Data.FeatureDataRow feature = features[i]; SharpMap.Styles.VectorStyle style = this.Theme.GetStyle(feature) as SharpMap.Styles.VectorStyle; RenderGeometry(g, map, feature.Geometry, style); } } else { this.DataSource.Open(); Collection<SharpMap.Geometries.Geometry> geoms = this.DataSource.GetGeometriesInView(envelope); this.DataSource.Close(); if (this.CoordinateTransformation != null) for (int i = 0; i < geoms.Count; i++) geoms[i] = SharpMap.CoordinateSystems.Transformations.GeometryTransform.TransformGeometry(geoms[i], this.CoordinateTransformation.MathTransform); //Linestring outlines is drawn by drawing the layer once with a thicker line //before drawing the "inline" on top. if (this.Style.EnableOutline) { foreach (SharpMap.Geometries.Geometry geom in geoms) { if (geom != null) { //Draw background of all line-outlines first switch (geom.GetType().FullName) { case "SharpMap.Geometries.LineString": SharpMap.Rendering.VectorRenderer.DrawLineString(g, geom as LineString, this.Style.Outline, map); break; case "SharpMap.Geometries.MultiLineString": SharpMap.Rendering.VectorRenderer.DrawMultiLineString(g, geom as MultiLineString, this.Style.Outline, map); break; default: break; } } } } for (int i = 0; i < geoms.Count; i++) { if(geoms[i]!=null) RenderGeometry(g, map, geoms[i], this.Style); } } base.Render(g, map); } private void RenderGeometry(System.Drawing.Graphics g, SharpMap.Map map, Geometry feature, SharpMap.Styles.VectorStyle style) { System.Drawing.Region gp = null; switch (feature.GetType().FullName) { case "SharpMap.Geometries.Polygon": if (style.EnableOutline) SharpMap.Rendering.VectorRenderer.DrawPolygon(g, (Polygon)feature, style.Fill, style.Outline, _ClippingEnabled, map); else SharpMap.Rendering.VectorRenderer.DrawPolygon(g, (Polygon)feature, style.Fill, null, _ClippingEnabled, map); break; case "SharpMap.Geometries.MultiPolygon": if (style.EnableOutline) SharpMap.Rendering.VectorRenderer.DrawMultiPolygon(g, (MultiPolygon)feature, style.Fill, style.Outline, _ClippingEnabled, map); else SharpMap.Rendering.VectorRenderer.DrawMultiPolygon(g, (MultiPolygon)feature, style.Fill, null, _ClippingEnabled, map); break; case "SharpMap.Geometries.LineString": gp = InteractiveRenderer.DrawLineString(g, (LineString)feature, style.Line, map); break; case "SharpMap.Geometries.MultiLineString": SharpMap.Rendering.VectorRenderer.DrawMultiLineString(g, (MultiLineString)feature, style.Line, map); break; case "SharpMap.Geometries.Point": gp = InteractiveRenderer.DrawPoint(g, (Point)feature, style.Symbol, style.SymbolScale, style.SymbolOffset, style.SymbolRotation, map); break; case "SharpMap.Geometries.MultiPoint": SharpMap.Rendering.VectorRenderer.DrawMultiPoint(g, (MultiPoint)feature, style.Symbol, style.SymbolScale, style.SymbolOffset, style.SymbolRotation, map); break; case "SharpMap.Geometries.GeometryCollection": foreach(SharpMap.Geometries.Geometry geom in (GeometryCollection)feature) RenderGeometry(g, map, geom, style); break; default: break; } if (gp != null && map is InteractiveMap && style is InteractiveStyle) { InteractiveMap imap = map as InteractiveMap; InteractiveStyle istyle = style as InteractiveStyle; ToolTipInfo info = new ToolTipInfo(); info.Bitmap = istyle.Symbol; info.Description = istyle.PopUpText; info.Id = istyle.PopUpId; string layerName = istyle.PopUpCategory; if (string.IsNullOrEmpty(istyle.PopUpCategory)) layerName = LayerName; imap.AddObject(gp, layerName, info, g); } } /// <summary> /// Returns the extent of the layer /// </summary> /// <returns>Bounding box corresponding to the extent of the features in the layer</returns> public override BoundingBox Envelope { get { if (this.DataSource == null) throw (new ApplicationException("DataSource property not set on layer '" + this.LayerName + "'")); bool wasOpen = this.DataSource.IsOpen; if (!wasOpen) this.DataSource.Open(); SharpMap.Geometries.BoundingBox box = this.DataSource.GetExtents(); if (!wasOpen) //Restore state this.DataSource.Close(); if (this.CoordinateTransformation != null) return SharpMap.CoordinateSystems.Transformations.GeometryTransform.TransformBox(box, this.CoordinateTransformation.MathTransform); return box; } } #endregion /// <summary> /// Gets or sets the SRID of this VectorLayer's data source /// </summary> public override int SRID { get { if (this.DataSource == null) throw (new ApplicationException("DataSource property not set on layer '" + this.LayerName + "'")); return this.DataSource.SRID; } set { this.DataSource.SRID = value; } } #region ICloneable Members /// <summary> /// Clones the layer /// </summary> /// <returns>cloned object</returns> public override object Clone() { throw new NotImplementedException(); } #endregion #region IDisposable Members /// <summary> /// Disposes the object /// </summary> public void Dispose() { if(DataSource is IDisposable) ((IDisposable)DataSource).Dispose(); } #endregion } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Web; using System.Web.Caching; using System.Web.Compilation; using System.Web.UI; using System.Xml; using System.Xml.Serialization; using DotNetNuke.Common.Utilities; using DotNetNuke.Entities.Host; using DotNetNuke.Entities.Portals; using DotNetNuke.Entities.Tabs; using DotNetNuke.Entities.Users; using DotNetNuke.Security.Permissions; using DotNetNuke.UI; using DotNetNuke.Web.DDRMenu.DNNCommon; using DotNetNuke.Web.DDRMenu.Localisation; using DotNetNuke.Web.DDRMenu.TemplateEngine; namespace DotNetNuke.Web.DDRMenu { public class MenuBase { public static MenuBase Instantiate(string menuStyle) { try { var templateDef = TemplateDefinition.FromName(menuStyle, "*menudef.xml"); return new MenuBase {TemplateDef = templateDef}; } catch (Exception exc) { throw new ApplicationException(String.Format("Couldn't load menu style '{0}': {1}", menuStyle, exc)); } } private Settings menuSettings; internal MenuNode RootNode { get; set; } internal Boolean SkipLocalisation { get; set; } public TemplateDefinition TemplateDef { get; set; } private HttpContext currentContext; private HttpContext CurrentContext { get { return currentContext ?? (currentContext = HttpContext.Current); } } private PortalSettings hostPortalSettings; internal PortalSettings HostPortalSettings { get { return hostPortalSettings ?? (hostPortalSettings = PortalController.Instance.GetCurrentPortalSettings()); } } private readonly Dictionary<string, string> nodeSelectorAliases = new Dictionary<string, string> { {"rootonly", "*,0,0"}, {"rootchildren", "+0"}, {"currentchildren", "."} }; internal void ApplySettings(Settings settings) { menuSettings = settings; } internal virtual void PreRender() { TemplateDef.AddTemplateArguments(menuSettings.TemplateArguments, true); TemplateDef.AddClientOptions(menuSettings.ClientOptions, true); if (!String.IsNullOrEmpty(menuSettings.NodeXmlPath)) { LoadNodeXml(); } if (!String.IsNullOrEmpty(menuSettings.NodeSelector)) { ApplyNodeSelector(); } if (!String.IsNullOrEmpty(menuSettings.IncludeNodes)) { FilterNodes(menuSettings.IncludeNodes, false); } if (!String.IsNullOrEmpty(menuSettings.ExcludeNodes)) { FilterNodes(menuSettings.ExcludeNodes, true); } if (String.IsNullOrEmpty(menuSettings.NodeXmlPath) && !SkipLocalisation) { new Localiser(HostPortalSettings.PortalId).LocaliseNode(RootNode); } if (!String.IsNullOrEmpty(menuSettings.NodeManipulator)) { ApplyNodeManipulator(); } if (!menuSettings.IncludeHidden) { FilterHiddenNodes(RootNode); } var imagePathOption = menuSettings.ClientOptions.Find(o => o.Name.Equals("PathImage", StringComparison.InvariantCultureIgnoreCase)); RootNode.ApplyContext( imagePathOption == null ? DNNContext.Current.PortalSettings.HomeDirectory : imagePathOption.Value); TemplateDef.PreRender(); } internal void Render(HtmlTextWriter htmlWriter) { if (Host.DebugMode) { htmlWriter.Write("<!-- DDRmenu v07.04.01 - {0} template -->", menuSettings.MenuStyle); } UserInfo user = null; if (menuSettings.IncludeContext) { user = UserController.Instance.GetCurrentUserInfo(); user.Roles = user.Roles; // Touch roles to populate } TemplateDef.AddClientOptions(new List<ClientOption> {new ClientString("MenuStyle", menuSettings.MenuStyle)}, false); TemplateDef.Render(new MenuXml {root = RootNode, user = user}, htmlWriter); } private void LoadNodeXml() { menuSettings.NodeXmlPath = MapPath( new PathResolver(TemplateDef.Folder).Resolve( menuSettings.NodeXmlPath, PathResolver.RelativeTo.Manifest, PathResolver.RelativeTo.Skin, PathResolver.RelativeTo.Module, PathResolver.RelativeTo.Portal, PathResolver.RelativeTo.Dnn)); var cache = CurrentContext.Cache; RootNode = cache[menuSettings.NodeXmlPath] as MenuNode; if (RootNode != null) { return; } using (var reader = XmlReader.Create(menuSettings.NodeXmlPath)) { reader.ReadToFollowing("root"); RootNode = (MenuNode)(new XmlSerializer(typeof(MenuNode), "").Deserialize(reader)); } cache.Insert(menuSettings.NodeXmlPath, RootNode, new CacheDependency(menuSettings.NodeXmlPath)); } private void FilterNodes(string nodeString, bool exclude) { var nodeTextStrings = SplitAndTrim(nodeString); var filteredNodes = new List<MenuNode>(); var tc = new TabController(); var flattenedNodes = new MenuNode(); foreach (var nodeText in nodeTextStrings) { if (nodeText.StartsWith("[")) { var roleName = nodeText.Substring(1, nodeText.Length - 2); filteredNodes.AddRange( RootNode.Children.FindAll( n => { var tab = TabController.Instance.GetTab(n.TabId, Null.NullInteger, false); foreach (TabPermissionInfo perm in tab.TabPermissions) { if (perm.AllowAccess && (perm.PermissionKey == "VIEW") && ((perm.RoleID == -1) || (perm.RoleName.ToLowerInvariant() == roleName))) { return true; } } return false; })); } else if (nodeText.StartsWith("#")) { var tagName = nodeText.Substring(1, nodeText.Length - 1); if (!string.IsNullOrEmpty(tagName)) { //flatten nodes first. tagged pages should be flattened and not heirarchical if (flattenedNodes != new MenuNode()) flattenedNodes.Children = RootNode.FlattenChildren(RootNode); filteredNodes.AddRange( flattenedNodes.Children.FindAll( n => { var tab = tc.GetTab(n.TabId, Null.NullInteger, false); return (tab.Terms.Any(x => x.Name.ToLowerInvariant() == tagName)); })); } } else { filteredNodes.Add(RootNode.FindByNameOrId(nodeText)); } } // if filtered for foksonomy tags, use flat tree to get all related pages in nodeselection if (flattenedNodes.HasChildren()) RootNode = flattenedNodes; if (exclude) { RootNode.RemoveAll(filteredNodes); } else { RootNode.Children.RemoveAll(n => filteredNodes.Contains(n) == exclude); } } private void FilterHiddenNodes(MenuNode parentNode) { var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); var filteredNodes = new List<MenuNode>(); filteredNodes.AddRange( parentNode.Children.FindAll( n => { var tab = TabController.Instance.GetTab(n.TabId, portalSettings.PortalId); return tab == null || !tab.IsVisible; })); parentNode.Children.RemoveAll(n => filteredNodes.Contains(n)); parentNode.Children.ForEach(FilterHiddenNodes); } private void ApplyNodeSelector() { string selector; if (!nodeSelectorAliases.TryGetValue(menuSettings.NodeSelector.ToLowerInvariant(), out selector)) { selector = menuSettings.NodeSelector; } var selectorSplit = SplitAndTrim(selector); var currentTabId = HostPortalSettings.ActiveTab.TabID; var newRoot = RootNode; var rootSelector = selectorSplit[0]; if (rootSelector != "*") { if (rootSelector.StartsWith("+")) { var depth = Convert.ToInt32(rootSelector); newRoot = RootNode; for (var i = 0; i <= depth; i++) { newRoot = newRoot.Children.Find(n => n.Breadcrumb); if (newRoot == null) { RootNode = new MenuNode(); return; } } } else if (rootSelector.StartsWith("-") || rootSelector == "0" || rootSelector == ".") { newRoot = RootNode.FindById(currentTabId); if (newRoot == null) { RootNode = new MenuNode(); return; } if (rootSelector.StartsWith("-")) { for (var n = Convert.ToInt32(rootSelector); n < 0; n++) { if (newRoot.Parent != null) { newRoot = newRoot.Parent; } } } } else { newRoot = RootNode.FindByNameOrId(rootSelector); if (newRoot == null) { RootNode = new MenuNode(); return; } } } // ReSharper disable PossibleNullReferenceException RootNode = new MenuNode(newRoot.Children); // ReSharper restore PossibleNullReferenceException if (selectorSplit.Count > 1) { for (var n = Convert.ToInt32(selectorSplit[1]); n > 0; n--) { var newChildren = new List<MenuNode>(); foreach (var child in RootNode.Children) { newChildren.AddRange(child.Children); } RootNode = new MenuNode(newChildren); } } if (selectorSplit.Count > 2) { var newChildren = RootNode.Children; for (var n = Convert.ToInt32(selectorSplit[2]); n > 0; n--) { var nextChildren = new List<MenuNode>(); foreach (var child in newChildren) { nextChildren.AddRange(child.Children); } newChildren = nextChildren; } foreach (var node in newChildren) { node.Children = null; } } } private void ApplyNodeManipulator() { RootNode = new MenuNode( ((INodeManipulator)Activator.CreateInstance(BuildManager.GetType(menuSettings.NodeManipulator, true, true))). ManipulateNodes(RootNode.Children, HostPortalSettings)); } protected string MapPath(string path) { return String.IsNullOrEmpty(path) ? "" : Path.GetFullPath(CurrentContext.Server.MapPath(path)); } private static List<string> SplitAndTrim(string str) { return new List<String>(str.Split(',')).ConvertAll(s => s.Trim().ToLowerInvariant()); } } }
using Discord; using Discord.Commands; using ImageSharp; using NadekoBot.Attributes; using NadekoBot.Extensions; using NadekoBot.Services; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace NadekoBot.Modules.Gambling { public partial class Gambling { [Group] public class DriceRollCommands { private Regex dndRegex { get; } = new Regex(@"^(?<n1>\d+)d(?<n2>\d+)(?:\+(?<add>\d+))?(?:\-(?<sub>\d+))?$", RegexOptions.Compiled); [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] public async Task Roll(IUserMessage umsg) { var channel = (ITextChannel)umsg.Channel; if (channel == null) return; var rng = new NadekoRandom(); var gen = rng.Next(1, 101); var num1 = gen / 10; var num2 = gen % 10; var imageStream = await Task.Run(() => { try { var ms = new MemoryStream(); new[] { GetDice(num1), GetDice(num2) }.Merge().SaveAsPng(ms); ms.Position = 0; return ms; } catch { return new MemoryStream(); } }); await channel.SendFileAsync(imageStream, "dice.png", $"{umsg.Author.Mention} rolled " + Format.Code(gen.ToString())).ConfigureAwait(false); } //todo merge into internallDndRoll and internalRoll [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] [Priority(1)] public async Task Roll(IUserMessage umsg, string arg) { var channel = (ITextChannel)umsg.Channel; if (channel == null) return; var ordered = true; var rng = new NadekoRandom(); Match match; if ((match = dndRegex.Match(arg)).Length != 0) { int n1; int n2; if (int.TryParse(match.Groups["n1"].ToString(), out n1) && int.TryParse(match.Groups["n2"].ToString(), out n2) && n1 <= 50 && n2 <= 100000 && n1 > 0 && n2 > 0) { var add = 0; var sub = 0; int.TryParse(match.Groups["add"].Value, out add); int.TryParse(match.Groups["sub"].Value, out sub); var arr = new int[n1]; for (int i = 0; i < n1; i++) { arr[i] = rng.Next(1, n2 + 1) + add - sub; } var elemCnt = 0; await channel.SendConfirmAsync($"{umsg.Author.Mention} rolled {n1} {(n1 == 1 ? "die" : "dice")} `1 to {n2}` +`{add}` -`{sub}`.\n`Result:` " + string.Join(", ", (ordered ? arr.OrderBy(x => x).AsEnumerable() : arr).Select(x => elemCnt++ % 2 == 0 ? $"**{x}**" : x.ToString()))).ConfigureAwait(false); } } } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] [Priority(0)] public async Task Roll(IUserMessage umsg, int num) { var channel = (ITextChannel)umsg.Channel; if (channel == null) return; var ordered = true; if (num < 1 || num > 30) { await channel.SendErrorAsync("Invalid number specified. You can roll up to 1-30 dice at a time.").ConfigureAwait(false); return; } var rng = new NadekoRandom(); var dice = new List<Image>(num); var values = new List<int>(num); for (var i = 0; i < num; i++) { var randomNumber = rng.Next(1, 7); var toInsert = dice.Count; if (ordered) { if (randomNumber == 6 || dice.Count == 0) toInsert = 0; else if (randomNumber != 1) for (var j = 0; j < dice.Count; j++) { if (values[j] < randomNumber) { toInsert = j; break; } } } else { toInsert = dice.Count; } dice.Insert(toInsert, GetDice(randomNumber)); values.Insert(toInsert, randomNumber); } var bitmap = dice.Merge(); var ms = new MemoryStream(); bitmap.SaveAsPng(ms); ms.Position = 0; await channel.SendFileAsync(ms, "dice.png", $"{umsg.Author.Mention} rolled {values.Count} {(values.Count == 1 ? "die" : "dice")}. Total: **{values.Sum()}** Average: **{(values.Sum() / (1.0f * values.Count)).ToString("N2")}**").ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] public async Task Rolluo(IUserMessage umsg, string arg) { var channel = (ITextChannel)umsg.Channel; if (channel == null) return; var ordered = false; var rng = new NadekoRandom(); Match match; if ((match = dndRegex.Match(arg)).Length != 0) { int n1; int n2; if (int.TryParse(match.Groups["n1"].ToString(), out n1) && int.TryParse(match.Groups["n2"].ToString(), out n2) && n1 <= 50 && n2 <= 100000 && n1 > 0 && n2 > 0) { var add = 0; var sub = 0; int.TryParse(match.Groups["add"].Value, out add); int.TryParse(match.Groups["sub"].Value, out sub); var arr = new int[n1]; for (int i = 0; i < n1; i++) { arr[i] = rng.Next(1, n2 + 1) + add - sub; } var elemCnt = 0; await channel.SendConfirmAsync($"{umsg.Author.Mention} rolled {n1} {(n1 == 1 ? "die" : "dice")} `1 to {n2}` +`{add}` -`{sub}`.\n`Result:` " + string.Join(", ", (ordered ? arr.OrderBy(x => x).AsEnumerable() : arr).Select(x => elemCnt++ % 2 == 0 ? $"**{x}**" : x.ToString()))).ConfigureAwait(false); } } } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] public async Task Rolluo(IUserMessage umsg, int num) { var channel = (ITextChannel)umsg.Channel; if (channel == null) return; var ordered = false; if (num < 1 || num > 30) { await channel.SendErrorAsync("Invalid number specified. You can roll up to 1-30 dice at a time.").ConfigureAwait(false); return; } var rng = new NadekoRandom(); var dice = new List<Image>(num); var values = new List<int>(num); for (var i = 0; i < num; i++) { var randomNumber = rng.Next(1, 7); var toInsert = dice.Count; if (ordered) { if (randomNumber == 6 || dice.Count == 0) toInsert = 0; else if (randomNumber != 1) for (var j = 0; j < dice.Count; j++) { if (values[j] < randomNumber) { toInsert = j; break; } } } else { toInsert = dice.Count; } dice.Insert(toInsert, GetDice(randomNumber)); values.Insert(toInsert, randomNumber); } var bitmap = dice.Merge(); var ms = new MemoryStream(); bitmap.SaveAsPng(ms); ms.Position = 0; await channel.SendFileAsync(ms, "dice.png", $"{umsg.Author.Mention} rolled {values.Count} {(values.Count == 1 ? "die" : "dice")}. Total: **{values.Sum()}** Average: **{(values.Sum() / (1.0f * values.Count)).ToString("N2")}**").ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] public async Task NRoll(IUserMessage umsg, [Remainder] string range) { var channel = (ITextChannel)umsg.Channel; try { int rolled; if (range.Contains("-")) { var arr = range.Split('-') .Take(2) .Select(int.Parse) .ToArray(); if (arr[0] > arr[1]) throw new ArgumentException("First argument should be bigger than the second one."); rolled = new NadekoRandom().Next(arr[0], arr[1] + 1); } else { rolled = new NadekoRandom().Next(0, int.Parse(range) + 1); } await channel.SendConfirmAsync($"{umsg.Author.Mention} rolled **{rolled}**.").ConfigureAwait(false); } catch (Exception ex) { await channel.SendErrorAsync($":anger: {ex.Message}").ConfigureAwait(false); } } private Image GetDice(int num) { const string pathToImage = "data/images/dice"; if (num != 10) { using (var stream = File.OpenRead(Path.Combine(pathToImage, $"{num}.png"))) return new Image(stream); } using (var one = File.OpenRead(Path.Combine(pathToImage, "1.png"))) using (var zero = File.OpenRead(Path.Combine(pathToImage, "0.png"))) { Image imgOne = new Image(one); Image imgZero = new Image(zero); return new[] { imgOne, imgZero }.Merge(); } } } } }
using System; using System.Collections.Generic; using System.Linq; using CppSharp.AST.Extensions; namespace CppSharp.AST { // A C++ access specifier. public enum AccessSpecifier { Private, Protected, Public, Internal } // A C++ access specifier declaration. public class AccessSpecifierDecl : Declaration { public override T Visit<T>(IDeclVisitor<T> visitor) { throw new NotImplementedException(); } } // Represents a base class of a C++ class. public class BaseClassSpecifier { public BaseClassSpecifier() { } public BaseClassSpecifier(BaseClassSpecifier other) { Access = other.Access; IsVirtual = other.IsVirtual; Type = other.Type; Offset = other.Offset; } public AccessSpecifier Access { get; set; } public bool IsVirtual { get; set; } public Type Type { get; set; } public int Offset { get; set; } public Class Class { get { Class @class; Type.TryGetClass(out @class); return @class; } } public bool IsClass { get { return Type.IsClass(); } } } public enum ClassType { ValueType, RefType, Interface } // Represents a C++ record Decl. public class Class : DeclarationContext { public List<BaseClassSpecifier> Bases; public List<Field> Fields; public List<Property> Properties; public List<Method> Methods; public List<AccessSpecifierDecl> Specifiers; // True if the record is a POD (Plain Old Data) type. public bool IsPOD; // Semantic type of the class. public ClassType Type; // ABI-specific class layout. public ClassLayout Layout; // True if class provides pure virtual methods. public bool IsAbstract; // True if the type is to be treated as a union. public bool IsUnion; // True if the class is final / sealed. public bool IsFinal { get; set; } private bool? isOpaque = null; public bool IsInjected { get; set; } // True if the type is to be treated as opaque. public bool IsOpaque { get { return isOpaque == null ? IsIncomplete && CompleteDeclaration == null : isOpaque.Value; } set { isOpaque = value; } } // True if the class is dynamic. public bool IsDynamic; // True if the class is polymorphic. public bool IsPolymorphic; // True if the class has a non trivial default constructor. public bool HasNonTrivialDefaultConstructor; // True if the class has a non trivial copy constructor. public bool HasNonTrivialCopyConstructor; // True if the class has a non trivial destructor. public bool HasNonTrivialDestructor; // True if the class represents a static class. public bool IsStatic; public Class() { Bases = new List<BaseClassSpecifier>(); Fields = new List<Field>(); Properties = new List<Property>(); Methods = new List<Method>(); Specifiers = new List<AccessSpecifierDecl>(); IsAbstract = false; IsUnion = false; IsFinal = false; IsPOD = false; Type = ClassType.RefType; Layout = new ClassLayout(); templateParameters = new List<Declaration>(); specializations = new List<ClassTemplateSpecialization>(); } public bool HasBase { get { return Bases.Count > 0; } } public bool HasBaseClass { get { return BaseClass != null; } } public Class BaseClass { get { foreach (var @base in Bases) { if (@base.IsClass && @base.Class.IsDeclared) return @base.Class; } return null; } } public bool HasNonIgnoredBase { get { return HasBaseClass && !IsValueType && Bases[0].Class != null && !Bases[0].Class.IsValueType && Bases[0].Class.GenerationKind != GenerationKind.None; } } public bool NeedsBase { get { return HasNonIgnoredBase && IsGenerated; } } // When we have an interface, this is the class mapped to that interface. public Class OriginalClass { get; set; } public bool IsValueType { get { return Type == ClassType.ValueType || IsUnion; } } public bool IsRefType { get { return Type == ClassType.RefType && !IsUnion; } } public bool IsInterface { get { return Type == ClassType.Interface; } } public bool IsAbstractImpl { get { return Methods.Any(m => m.SynthKind == FunctionSynthKind.AbstractImplCall); } } public IEnumerable<Method> Constructors { get { return Methods.Where( method => method.IsConstructor || method.IsCopyConstructor); } } public IEnumerable<Method> Destructors { get { return Methods.Where(method => method.IsDestructor); } } public IEnumerable<Method> Operators { get { return Methods.Where(method => method.IsOperator); } } /// <summary> /// If this class is a template, this list contains all of its template parameters. /// <para> /// <see cref="ClassTemplate"/> cannot be relied upon to contain all of them because /// ClassTemplateDecl in Clang is not a complete declaration, it only serves to forward template classes. /// </para> /// </summary> public List<Declaration> TemplateParameters { get { if (!IsDependent) throw new InvalidOperationException( "Only dependent classes have template parameters."); return templateParameters; } } /// <summary> /// If this class is a template, this list contains all of its specializations. /// <see cref="ClassTemplate"/> cannot be relied upon to contain all of them because /// ClassTemplateDecl in Clang is not a complete declaration, it only serves to forward template classes. /// </summary> public List<ClassTemplateSpecialization> Specializations { get { if (!IsDependent) throw new InvalidOperationException( "Only dependent classes have specializations."); return specializations; } } public override IEnumerable<Function> FindOperator(CXXOperatorKind kind) { return Methods.Where(m => m.OperatorKind == kind); } public override IEnumerable<Function> GetOverloads(Function function) { if (function.IsOperator) return Methods.Where(fn => fn.OperatorKind == function.OperatorKind); var overloads = Methods.Where(m => m.Name == function.Name) .Union(Declarations.Where(d => d is Function && d.Name == function.Name)) .Cast<Function>(); overloads = overloads.Union(base.GetOverloads(function)); return overloads; } public Method FindMethod(string name) { return Methods .Concat(Templates.OfType<FunctionTemplate>() .Select(t => t.TemplatedFunction) .OfType<Method>()) .FirstOrDefault(m => m.Name == name); } public Method FindMethodByUSR(string usr) { return Methods .Concat(Templates.OfType<FunctionTemplate>() .Select(t => t.TemplatedFunction) .OfType<Method>()) .FirstOrDefault(m => m.USR == usr); } public override T Visit<T>(IDeclVisitor<T> visitor) { return visitor.VisitClassDecl(this); } private List<Declaration> templateParameters; private List<ClassTemplateSpecialization> specializations; } }
/* * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; namespace Amazon.SimpleWorkflow.Model { /// <summary> /// <para> Provides details of the <c>RequestCancelExternalWorkflowExecutionFailed</c> event. </para> /// </summary> public class RequestCancelExternalWorkflowExecutionFailedEventAttributes { private string workflowId; private string runId; private string cause; private long? initiatedEventId; private long? decisionTaskCompletedEventId; private string control; /// <summary> /// The <c>workflowId</c> of the external workflow to which the cancel request was to be delivered. /// /// <para> /// <b>Constraints:</b> /// <list type="definition"> /// <item> /// <term>Length</term> /// <description>1 - 256</description> /// </item> /// </list> /// </para> /// </summary> public string WorkflowId { get { return this.workflowId; } set { this.workflowId = value; } } /// <summary> /// Sets the WorkflowId property /// </summary> /// <param name="workflowId">The value to set for the WorkflowId property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public RequestCancelExternalWorkflowExecutionFailedEventAttributes WithWorkflowId(string workflowId) { this.workflowId = workflowId; return this; } // Check to see if WorkflowId property is set internal bool IsSetWorkflowId() { return this.workflowId != null; } /// <summary> /// The <c>runId</c> of the external workflow execution. /// /// <para> /// <b>Constraints:</b> /// <list type="definition"> /// <item> /// <term>Length</term> /// <description>0 - 64</description> /// </item> /// </list> /// </para> /// </summary> public string RunId { get { return this.runId; } set { this.runId = value; } } /// <summary> /// Sets the RunId property /// </summary> /// <param name="runId">The value to set for the RunId property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public RequestCancelExternalWorkflowExecutionFailedEventAttributes WithRunId(string runId) { this.runId = runId; return this; } // Check to see if RunId property is set internal bool IsSetRunId() { return this.runId != null; } /// <summary> /// The cause of the failure to process the decision. This information is generated by the system and can be useful for diagnostic purposes. /// <note>If <b>cause</b> is set to OPERATION_NOT_PERMITTED, the decision failed because it lacked sufficient permissions. For details and /// example IAM policies, see <a href="http://docs.aws.amazon.com/amazonswf/latest/developerguide/swf-dev-iam.html">Using IAM to Manage Access /// to Amazon SWF Workflows</a>.</note> /// /// <para> /// <b>Constraints:</b> /// <list type="definition"> /// <item> /// <term>Allowed Values</term> /// <description>UNKNOWN_EXTERNAL_WORKFLOW_EXECUTION, REQUEST_CANCEL_EXTERNAL_WORKFLOW_EXECUTION_RATE_EXCEEDED, OPERATION_NOT_PERMITTED</description> /// </item> /// </list> /// </para> /// </summary> public string Cause { get { return this.cause; } set { this.cause = value; } } /// <summary> /// Sets the Cause property /// </summary> /// <param name="cause">The value to set for the Cause property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public RequestCancelExternalWorkflowExecutionFailedEventAttributes WithCause(string cause) { this.cause = cause; return this; } // Check to see if Cause property is set internal bool IsSetCause() { return this.cause != null; } /// <summary> /// The id of the <c>RequestCancelExternalWorkflowExecutionInitiated</c> event corresponding to the /// <c>RequestCancelExternalWorkflowExecution</c> decision to cancel this external workflow execution. This information can be useful for /// diagnosing problems by tracing back the chain of events leading up to this event. /// /// </summary> public long InitiatedEventId { get { return this.initiatedEventId ?? default(long); } set { this.initiatedEventId = value; } } /// <summary> /// Sets the InitiatedEventId property /// </summary> /// <param name="initiatedEventId">The value to set for the InitiatedEventId property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public RequestCancelExternalWorkflowExecutionFailedEventAttributes WithInitiatedEventId(long initiatedEventId) { this.initiatedEventId = initiatedEventId; return this; } // Check to see if InitiatedEventId property is set internal bool IsSetInitiatedEventId() { return this.initiatedEventId.HasValue; } /// <summary> /// The id of the <c>DecisionTaskCompleted</c> event corresponding to the decision task that resulted in the /// <c>RequestCancelExternalWorkflowExecution</c> decision for this cancellation request. This information can be useful for diagnosing problems /// by tracing back the cause of events. /// /// </summary> public long DecisionTaskCompletedEventId { get { return this.decisionTaskCompletedEventId ?? default(long); } set { this.decisionTaskCompletedEventId = value; } } /// <summary> /// Sets the DecisionTaskCompletedEventId property /// </summary> /// <param name="decisionTaskCompletedEventId">The value to set for the DecisionTaskCompletedEventId property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public RequestCancelExternalWorkflowExecutionFailedEventAttributes WithDecisionTaskCompletedEventId(long decisionTaskCompletedEventId) { this.decisionTaskCompletedEventId = decisionTaskCompletedEventId; return this; } // Check to see if DecisionTaskCompletedEventId property is set internal bool IsSetDecisionTaskCompletedEventId() { return this.decisionTaskCompletedEventId.HasValue; } public string Control { get { return this.control; } set { this.control = value; } } /// <summary> /// Sets the Control property /// </summary> /// <param name="control">The value to set for the Control property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public RequestCancelExternalWorkflowExecutionFailedEventAttributes WithControl(string control) { this.control = control; return this; } // Check to see if Control property is set internal bool IsSetControl() { return this.control != null; } } }
using Microsoft.Azure.Management.ProviderHub.Models; using Microsoft.Rest.Azure; using Microsoft.Rest.ClientRuntime.Azure.TestFramework; using System.Collections.Generic; using Xunit; namespace Microsoft.Azure.Management.ProviderHub.Tests { public class OperationsTests { [Fact] public void OperationsCRUDTests() { using (var context = MockContext.Start(GetType())) { string providerNamespace = "Microsoft.Contoso"; var content = new List<OperationsDefinition> { new OperationsDefinition { Name = "Microsoft.Contoso/Operations/read", IsDataAction = false, Display = new OperationsDefinitionDisplay { Provider = "Microsoft.Contoso", Resource = "Operations", Operation = "Operations_read", Description = "read Operations" } }, new OperationsDefinition { Name = "Microsoft.Contoso/locations/operationstatuses/read", IsDataAction = false, Display = new OperationsDefinitionDisplay { Provider = "Microsoft.Contoso", Resource = "locations/operationstatuses", Operation = "operationstatuses_read", Description = "read operationstatuses" } }, new OperationsDefinition { Name = "Microsoft.Contoso/locations/operationstatuses/write", IsDataAction = false, Display = new OperationsDefinitionDisplay { Provider = "Microsoft.Contoso", Resource = "locations/operationstatuses", Operation = "operationstatuses_write", Description = "write operationstatuses" } }, new OperationsDefinition { Name = "microsoft.contoso/employees/nestedResourceType/read", IsDataAction = false, Display = new OperationsDefinitionDisplay { Provider = "Microsoft.Contoso/", Resource = "employees/nestedResourceType", Operation = "NestedResourceType_Get", Description = "Returns nested resources for a given employee name" } }, new OperationsDefinition { Name = "microsoft.contoso/employees/nestedResourceType/write", IsDataAction = false, Display = new OperationsDefinitionDisplay { Provider = "microsoft.contoso/", Resource = "employees/nestedResourceType", Operation = "NestedResourceType_CreateAndUpdate", Description = "Create or update nested resource type." } }, new OperationsDefinition { Name = "microsoft.contoso/employees/nestedResourceType/write", IsDataAction = false, Display = new OperationsDefinitionDisplay { Provider = "microsoft.contoso/", Resource = "employees/nestedResourceType", Operation = "NestedResourceType_Update", Description = "Update nested resource type details." } }, new OperationsDefinition { Name = "microsoft.contoso/employees/nestedResourceType/read", IsDataAction = false, Display = new OperationsDefinitionDisplay { Provider = "microsoft.contoso/", Resource = "employees/nestedResourceType", Operation = "NestedResourceType_List", Description = "Returns nested resources for a given employee name" } }, new OperationsDefinition { Name = "microsoft.contoso/employees/read", IsDataAction = false, Display = new OperationsDefinitionDisplay { Provider = "microsoft.contoso/", Resource = "employees", Operation = "Employee_ListBySubscription", Description = "Returns list of employees." } }, new OperationsDefinition { Name = "microsoft.contoso/employees/read", IsDataAction = false, Display = new OperationsDefinitionDisplay { Provider = "microsoft.contoso/", Resource = "employees", Operation = "Employee_List", Description = "Returns list of employees." } }, new OperationsDefinition { Name = "microsoft.contoso/employees/read", IsDataAction = false, Display = new OperationsDefinitionDisplay { Provider = "microsoft.contoso/", Resource = "employees", Operation = "Employee_Get", Description = "Returns employee resource for a given name." } }, new OperationsDefinition { Name = "microsoft.contoso/employees/write", IsDataAction = false, Display = new OperationsDefinitionDisplay { Provider = "microsoft.contoso/", Resource = "employees", Operation = "Employee_CreateAndUpdate", Description = "Create or update employee resource." } }, new OperationsDefinition { Name = "microsoft.contoso/employees/delete", IsDataAction = false, Display = new OperationsDefinitionDisplay { Provider = "microsoft.contoso/", Resource = "employees", Operation = "Employee_Delete", Description = "Deletes employee resource for a given name." } }, new OperationsDefinition { Name = "microsoft.contoso/employees/write", IsDataAction = false, Display = new OperationsDefinitionDisplay { Provider = "microsoft.contoso/", Resource = "employees", Operation = "Employees_Update", Description = "Update employee details." } } }; var resourceProviderOperations = CreateResourceProviderOperations(context, providerNamespace, content); Assert.NotNull(resourceProviderOperations); var operationsListByProviderRegistration = ListOperationsByProviderRegistration(context, providerNamespace); Assert.NotNull(operationsListByProviderRegistration); } } private OperationsContent CreateResourceProviderOperations(MockContext context, string providerNamespace, List<OperationsDefinition> content) { ProviderHubClient client = GetProviderHubManagementClient(context); return client.Operations.CreateOrUpdate(providerNamespace, content); } private IPage<OperationsDefinition> ListOperations(MockContext context) { ProviderHubClient client = GetProviderHubManagementClient(context); return client.Operations.List(); } private IList<OperationsDefinition> ListOperationsByProviderRegistration(MockContext context, string providerNamespace) { ProviderHubClient client = GetProviderHubManagementClient(context); return client.Operations.ListByProviderRegistration(providerNamespace); } private void DeleteResourceProviderOperations(MockContext context, string providerNamespace) { ProviderHubClient client = GetProviderHubManagementClient(context); client.Operations.Delete(providerNamespace); } private ProviderHubClient GetProviderHubManagementClient(MockContext context) { return context.GetServiceClient<ProviderHubClient>(); } } }
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 PnAgenteInscriptor class. /// </summary> [Serializable] public partial class PnAgenteInscriptorCollection : ActiveList<PnAgenteInscriptor, PnAgenteInscriptorCollection> { public PnAgenteInscriptorCollection() {} /// <summary> /// Filters an existing collection based on the set criteria. This is an in-memory filter /// Thanks to developingchris for this! /// </summary> /// <returns>PnAgenteInscriptorCollection</returns> public PnAgenteInscriptorCollection Filter() { for (int i = this.Count - 1; i > -1; i--) { PnAgenteInscriptor o = this[i]; foreach (SubSonic.Where w in this.wheres) { bool remove = false; System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName); if (pi.CanRead) { object val = pi.GetValue(o, null); switch (w.Comparison) { case SubSonic.Comparison.Equals: if (!val.Equals(w.ParameterValue)) { remove = true; } break; } } if (remove) { this.Remove(o); break; } } } return this; } } /// <summary> /// This is an ActiveRecord class which wraps the PN_agente_inscriptor table. /// </summary> [Serializable] public partial class PnAgenteInscriptor : ActiveRecord<PnAgenteInscriptor>, IActiveRecord { #region .ctors and Default Settings public PnAgenteInscriptor() { SetSQLProps(); InitSetDefaults(); MarkNew(); } private void InitSetDefaults() { SetDefaults(); } public PnAgenteInscriptor(bool useDatabaseDefaults) { SetSQLProps(); if(useDatabaseDefaults) ForceDefaults(); MarkNew(); } public PnAgenteInscriptor(object keyID) { SetSQLProps(); InitSetDefaults(); LoadByKey(keyID); } public PnAgenteInscriptor(string columnName, object columnValue) { SetSQLProps(); InitSetDefaults(); LoadByParam(columnName,columnValue); } protected static void SetSQLProps() { GetTableSchema(); } #endregion #region Schema and Query Accessor public static Query CreateQuery() { return new Query(Schema); } public static TableSchema.Table Schema { get { if (BaseSchema == null) SetSQLProps(); return BaseSchema; } } private static void GetTableSchema() { if(!IsSchemaInitialized) { //Schema declaration TableSchema.Table schema = new TableSchema.Table("PN_agente_inscriptor", TableType.Table, DataService.GetInstance("sicProvider")); schema.Columns = new TableSchema.TableColumnCollection(); schema.SchemaName = @"dbo"; //columns TableSchema.TableColumn colvarIdAgenteInscriptor = new TableSchema.TableColumn(schema); colvarIdAgenteInscriptor.ColumnName = "id_agente_inscriptor"; colvarIdAgenteInscriptor.DataType = DbType.Int32; colvarIdAgenteInscriptor.MaxLength = 0; colvarIdAgenteInscriptor.AutoIncrement = true; colvarIdAgenteInscriptor.IsNullable = false; colvarIdAgenteInscriptor.IsPrimaryKey = true; colvarIdAgenteInscriptor.IsForeignKey = false; colvarIdAgenteInscriptor.IsReadOnly = false; colvarIdAgenteInscriptor.DefaultSetting = @""; colvarIdAgenteInscriptor.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdAgenteInscriptor); TableSchema.TableColumn colvarDescripcionAgente = new TableSchema.TableColumn(schema); colvarDescripcionAgente.ColumnName = "descripcion_agente"; colvarDescripcionAgente.DataType = DbType.AnsiString; colvarDescripcionAgente.MaxLength = -1; colvarDescripcionAgente.AutoIncrement = false; colvarDescripcionAgente.IsNullable = true; colvarDescripcionAgente.IsPrimaryKey = false; colvarDescripcionAgente.IsForeignKey = false; colvarDescripcionAgente.IsReadOnly = false; colvarDescripcionAgente.DefaultSetting = @""; colvarDescripcionAgente.ForeignKeyTableName = ""; schema.Columns.Add(colvarDescripcionAgente); BaseSchema = schema; //add this schema to the provider //so we can query it later DataService.Providers["sicProvider"].AddSchema("PN_agente_inscriptor",schema); } } #endregion #region Props [XmlAttribute("IdAgenteInscriptor")] [Bindable(true)] public int IdAgenteInscriptor { get { return GetColumnValue<int>(Columns.IdAgenteInscriptor); } set { SetColumnValue(Columns.IdAgenteInscriptor, value); } } [XmlAttribute("DescripcionAgente")] [Bindable(true)] public string DescripcionAgente { get { return GetColumnValue<string>(Columns.DescripcionAgente); } set { SetColumnValue(Columns.DescripcionAgente, value); } } #endregion //no foreign key tables defined (0) //no ManyToMany tables defined (0) #region ObjectDataSource support /// <summary> /// Inserts a record, can be used with the Object Data Source /// </summary> public static void Insert(string varDescripcionAgente) { PnAgenteInscriptor item = new PnAgenteInscriptor(); item.DescripcionAgente = varDescripcionAgente; 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 varIdAgenteInscriptor,string varDescripcionAgente) { PnAgenteInscriptor item = new PnAgenteInscriptor(); item.IdAgenteInscriptor = varIdAgenteInscriptor; item.DescripcionAgente = varDescripcionAgente; 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 IdAgenteInscriptorColumn { get { return Schema.Columns[0]; } } public static TableSchema.TableColumn DescripcionAgenteColumn { get { return Schema.Columns[1]; } } #endregion #region Columns Struct public struct Columns { public static string IdAgenteInscriptor = @"id_agente_inscriptor"; public static string DescripcionAgente = @"descripcion_agente"; } #endregion #region Update PK Collections #endregion #region Deep Save #endregion } }
/* Copyright (c) Citrix Systems Inc. * All rights reserved. * * Redistribution and use in source and binary forms, * with or without modification, are permitted provided * that the following conditions are met: * * * Redistributions of source code must retain the above * copyright notice, this list of conditions and the * following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the * following disclaimer in the documentation and/or other * materials provided with the distribution. * * 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.Drawing; using System.Windows.Forms; using XenAdmin.XenSearch; namespace XenAdmin.Controls.XenSearch { public partial class SearchFor : UserControl { public event Action QueryChanged; private const ObjectTypes CUSTOM = ObjectTypes.None; // We use None as a special signal value for "Custom..." private readonly Dictionary<ObjectTypes, String> typeNames = new Dictionary<ObjectTypes, String>(); private readonly Dictionary<ObjectTypes, Image> typeImages = new Dictionary<ObjectTypes, Image>(); private ObjectTypes customValue; private ObjectTypes savedTypes; private bool autoSelecting = false; public SearchFor() { InitializeComponent(); InitializeDictionaries(); PopulateSearchForComboButton(); } public void BlankSearch() { QueryScope = new QueryScope(ObjectTypes.None); OnQueryChanged(); } private void OnQueryChanged() { if (QueryChanged != null) QueryChanged(); } private void InitializeDictionaries() { // add all single types, names and images Dictionary<String, ObjectTypes> dict = (Dictionary<String, ObjectTypes>)PropertyAccessors.Geti18nFor(PropertyNames.type); ImageDelegate<ObjectTypes> images = (ImageDelegate<ObjectTypes>)PropertyAccessors.GetImagesFor(PropertyNames.type); foreach (KeyValuePair<String, ObjectTypes> kvp in dict) { typeNames[kvp.Value] = kvp.Key; typeImages[kvp.Value] = Images.GetImage16For(images(kvp.Value)); } // add all combo types, mostly names only typeNames[ObjectTypes.LocalSR | ObjectTypes.RemoteSR] = Messages.ALL_SRS; typeImages[ObjectTypes.LocalSR | ObjectTypes.RemoteSR] = Images.GetImage16For(images(ObjectTypes.LocalSR | ObjectTypes.RemoteSR)); typeNames[ObjectTypes.Server | ObjectTypes.DisconnectedServer | ObjectTypes.VM] = Messages.SERVERS_AND_VMS; typeNames[ObjectTypes.Server | ObjectTypes.DisconnectedServer | ObjectTypes.VM | ObjectTypes.UserTemplate | ObjectTypes.RemoteSR] = Messages.SERVERS_AND_VMS_AND_CUSTOM_TEMPLATES_AND_REMOTE_SRS; typeNames[ObjectTypes.Server | ObjectTypes.DisconnectedServer | ObjectTypes.VM | ObjectTypes.UserTemplate | ObjectTypes.RemoteSR | ObjectTypes.LocalSR] = Messages.SERVERS_AND_VMS_AND_CUSTOM_TEMPLATES_AND_ALL_SRS; typeNames[ObjectTypes.AllExcFolders] = Messages.ALL_TYPES; typeNames[ObjectTypes.AllIncFolders] = Messages.ALL_TYPES_AND_FOLDERS; //typeNames[ObjectTypes.DockerContainer] = "Docker containers"; } private void AddItemToSearchFor(ObjectTypes type) { ToolStripMenuItem item = new ToolStripMenuItem(); item.Text = typeNames[type]; item.Tag = type; if (typeImages.ContainsKey(type)) item.Image = typeImages[type]; searchForComboButton.AddItem(item); } private void AddCustom() { ToolStripMenuItem item = new ToolStripMenuItem(); item.Text = Messages.CUSTOM; item.Tag = CUSTOM; searchForComboButton.AddItem(item); } private void AddSeparator() { searchForComboButton.AddItem(new ToolStripSeparator()); } // The order here is not the same as the order in the Organization View, // which is determined by the ObjectTypes enum (CA-28418). private void PopulateSearchForComboButton() { AddItemToSearchFor(ObjectTypes.Pool); AddItemToSearchFor(ObjectTypes.Server); AddItemToSearchFor(ObjectTypes.DisconnectedServer); AddItemToSearchFor(ObjectTypes.VM); AddItemToSearchFor(ObjectTypes.Snapshot); AddItemToSearchFor(ObjectTypes.UserTemplate); AddItemToSearchFor(ObjectTypes.DefaultTemplate); AddItemToSearchFor(ObjectTypes.RemoteSR); AddItemToSearchFor(ObjectTypes.RemoteSR | ObjectTypes.LocalSR); // local SR on its own is pretty much useless AddItemToSearchFor(ObjectTypes.VDI); AddItemToSearchFor(ObjectTypes.Network); AddItemToSearchFor(ObjectTypes.Folder); //AddItemToSearchFor(ObjectTypes.DockerContainer); AddSeparator(); AddItemToSearchFor(ObjectTypes.Server | ObjectTypes.DisconnectedServer | ObjectTypes.VM); AddItemToSearchFor(ObjectTypes.Server | ObjectTypes.DisconnectedServer | ObjectTypes.VM | ObjectTypes.UserTemplate | ObjectTypes.RemoteSR); AddItemToSearchFor(ObjectTypes.Server | ObjectTypes.DisconnectedServer | ObjectTypes.VM | ObjectTypes.UserTemplate | ObjectTypes.RemoteSR | ObjectTypes.LocalSR); AddSeparator(); AddItemToSearchFor(ObjectTypes.AllExcFolders); AddItemToSearchFor(ObjectTypes.AllIncFolders); AddSeparator(); AddCustom(); } void searchForComboButton_BeforePopup(object sender, System.EventArgs e) { savedTypes = GetSelectedItemTag(); } private void searchForComboButton_itemSelected(object sender, System.EventArgs e) { ObjectTypes types = GetSelectedItemTag(); if (types != CUSTOM) return; if (!autoSelecting) { // Launch custom dlg. Dependent on OK/Cancel, save result and continue, or quit SearchForCustom sfc = new SearchForCustom(typeNames, customValue); sfc.ShowDialog(Program.MainWindow); if (sfc.DialogResult == DialogResult.Cancel) { autoSelecting = true; SetFromScope(savedTypes); // reset combo button to value before Custom... autoSelecting = false; return; } customValue = sfc.Selected; } OnQueryChanged(); } private void searchForComboButton_selChanged(object sender, EventArgs e) { ObjectTypes types = GetSelectedItemTag(); if (types == CUSTOM) return; // CUSTOM is dealt with in searchForComboButton_itemSelected instead OnQueryChanged(); } public QueryScope QueryScope { get { return GetAsScope(); } set { autoSelecting = true; customValue = value.ObjectTypes; SetFromScope(value); autoSelecting = false; } } private ObjectTypes GetSelectedItemTag() { return (searchForComboButton.SelectedItem == null ? ObjectTypes.None : (ObjectTypes)searchForComboButton.SelectedItem.Tag); } private QueryScope GetAsScope() { ObjectTypes types = GetSelectedItemTag(); if (types == CUSTOM) // if we're on Custom..., look it up from the custom setting return new QueryScope(customValue); else // else just report what we're showing return new QueryScope(types); } private void SetFromScope(QueryScope value) { // Can we represent it by one of the fixed types? bool bDone = searchForComboButton.SelectItem<ObjectTypes>( delegate(ObjectTypes types) { return (types == value.ObjectTypes); } ); // If not, set it to "Custom..." if (!bDone) bDone = searchForComboButton.SelectItem<ObjectTypes>( delegate(ObjectTypes types) { return (types == CUSTOM); } ); } private void SetFromScope(ObjectTypes types) { SetFromScope(new QueryScope(types)); } } }
// 32feet.NET - Personal Area Networking for .NET // // InTheHand.Net.Bluetooth.ServiceRecordHelper // // Copyright (c) 2007 Andy Hume // Copyright (c) 2003-2020 In The Hand Ltd, All rights reserved. // This source code is licensed under the MIT License using System; using System.Collections.Generic; using System.Text; using System.Diagnostics; using InTheHand.Net.Bluetooth.AttributeIds; using System.Globalization; namespace InTheHand.Net.Bluetooth.Sdp { /// <summary> /// Some useful methods for working with a SDP <see cref="T:InTheHand.Net.Bluetooth.ServiceRecord"/> /// including creating and accessing the <see cref="F:InTheHand.Net.Bluetooth.AttributeIds.UniversalAttributeId.ProtocolDescriptorList"/> /// for an RFCOMM service. /// </summary> public static class ServiceRecordHelper { //-------------------------------------------------------------- /// <summary> /// Reads the RFCOMM Channel Number element from the service record. /// </summary> /// - /// <param name="record">The <see cref="T:InTheHand.Net.Bluetooth.ServiceRecord"/> /// to search for the element. /// </param> /// - /// <returns>The <see cref="T:InTheHand.Net.Bluetooth.ServiceElement"/> /// holding the Channel Number. /// or <see langword="null"/> if at the <see cref="F:InTheHand.Net.Bluetooth.AttributeIds.UniversalAttributeId.ProtocolDescriptorList"/> /// attribute is missing or contains invalid elements. /// </returns> public static ServiceElement GetRfcommChannelElement(ServiceRecord record) { return GetChannelElement(record, BluetoothProtocolDescriptorType.Rfcomm); } /// <summary> /// Reads the L2CAP Channel Number element from the service record. /// </summary> /// - /// <param name="record">The <see cref="T:InTheHand.Net.Bluetooth.ServiceRecord"/> /// to search for the element. /// </param> /// - /// <returns>The <see cref="T:InTheHand.Net.Bluetooth.ServiceElement"/> /// holding the Channel Number. /// or <see langword="null"/> if at the <see cref="F:InTheHand.Net.Bluetooth.AttributeIds.UniversalAttributeId.ProtocolDescriptorList"/> /// attribute is missing or contains invalid elements. /// </returns> public static ServiceElement GetL2CapChannelElement(ServiceRecord record) { return GetChannelElement(record, BluetoothProtocolDescriptorType.L2Cap); } static ServiceElement GetChannelElement(ServiceRecord record, BluetoothProtocolDescriptorType proto) { if (!record.Contains(UniversalAttributeId.ProtocolDescriptorList)) { goto NotFound; } ServiceAttribute attr = record.GetAttributeById(UniversalAttributeId.ProtocolDescriptorList); bool? isSimpleRfcomm; return GetChannelElement(attr, proto, out isSimpleRfcomm); NotFound: return null; } // TODO GetRfcommChannelElement(ServiceAttribute attr) Could be public -> Tests! internal static ServiceElement GetChannelElement(ServiceAttribute attr, BluetoothProtocolDescriptorType proto, out bool? isSimpleRfcomm) { if (proto != BluetoothProtocolDescriptorType.L2Cap && proto != BluetoothProtocolDescriptorType.Rfcomm) throw new ArgumentException("Can only fetch RFCOMM or L2CAP element."); // isSimpleRfcomm = true; Debug.Assert(attr != null, "attr != null"); ServiceElement e0 = attr.Value; if (e0.ElementType == ElementType.ElementAlternative) { Debug.WriteLine("Don't support ElementAlternative ProtocolDescriptorList values."); goto NotFound; } else if (e0.ElementType != ElementType.ElementSequence) { Debug.WriteLine("Bad ProtocolDescriptorList base element."); goto NotFound; } IList<ServiceElement> protoStack = e0.GetValueAsElementList(); IEnumerator<ServiceElement> etor = protoStack.GetEnumerator(); ServiceElement layer; IList<ServiceElement> layerContent; ServiceElement channelElement; // -- L2CAP Layer -- if (!etor.MoveNext()) { Debug.WriteLine(string.Format(CultureInfo.InvariantCulture, "Protocol stack truncated before {0}.", "L2CAP")); goto NotFound; } layer = etor.Current; //cast here are for non-Generic version. layerContent = layer.GetValueAsElementList(); if (layerContent[0].GetValueAsUuid() != BluetoothProtocol.L2CapProtocol) { Debug.WriteLine(String.Format(CultureInfo.InvariantCulture, "Bad protocol stack, layer {0} is not {1}.", 1, "L2CAP")); goto NotFound; } bool hasPsmEtc = layerContent.Count != 1; // Cast for FX1.1 object isSimpleRfcomm = (bool)isSimpleRfcomm && !hasPsmEtc; if (proto == BluetoothProtocolDescriptorType.L2Cap) { if (layerContent.Count < 2) { Debug.WriteLine("L2CAP PSM element was requested but the L2CAP layer in this case hasn't a second element."); goto NotFound; } channelElement = (ServiceElement)layerContent[1]; goto Success; } // // -- RFCOMM Layer -- if (!etor.MoveNext()) { Debug.WriteLine(string.Format(CultureInfo.InvariantCulture, "Protocol stack truncated before {0}.", "RFCOMM")); goto NotFound; } layer = etor.Current; layerContent = layer.GetValueAsElementList(); if (layerContent[0].GetValueAsUuid() != BluetoothProtocol.RFCommProtocol) { Debug.WriteLine(string.Format(CultureInfo.InvariantCulture, "Bad protocol stack, layer {0} is not {1}.", 2, "RFCOMM")); goto NotFound; } // if (layerContent.Count < 2) { Debug.WriteLine(string.Format(CultureInfo.InvariantCulture, "Bad protocol stack, layer {0} hasn't a second element.", 2)); goto NotFound; } channelElement = layerContent[1]; if (channelElement.ElementType != ElementType.UInt8) { Debug.WriteLine(string.Format(CultureInfo.InvariantCulture, "Bad protocol stack, layer {0} is not UInt8.", 2)); goto NotFound; } // Success // // -- Any remaining layer(s) -- bool extraLayers = etor.MoveNext(); isSimpleRfcomm = (bool)isSimpleRfcomm && !extraLayers; Success: // return channelElement; NotFound: isSimpleRfcomm = null; return null; } /// <summary> /// Reads the RFCOMM Channel Number value from the service record, /// or returns -1 if the element is not present. /// </summary> /// - /// <param name="record">The <see cref="T:InTheHand.Net.Bluetooth.ServiceRecord"/> /// to search for the element. /// </param> /// - /// <returns>The Channel Number as an unsigned byte cast to an Int32, /// or -1 if at the <see cref="F:InTheHand.Net.Bluetooth.AttributeIds.UniversalAttributeId.ProtocolDescriptorList"/> /// attribute is missing or contains invalid elements. /// </returns> public static int GetRfcommChannelNumber(ServiceRecord record) { ServiceElement channelElement = GetRfcommChannelElement(record); if (channelElement == null) { return -1; } return GetRfcommChannelNumber(channelElement); } internal static int GetRfcommChannelNumber(ServiceElement channelElement) { Debug.Assert(channelElement != null, "channelElement != null"); Debug.Assert(channelElement.ElementType == ElementType.UInt8); byte value = (byte)channelElement.Value; return value; } /// <summary> /// Reads the L2CAP Channel Number value from the service record, /// or returns -1 if the element is not present. /// </summary> /// - /// <param name="record">The <see cref="T:InTheHand.Net.Bluetooth.ServiceRecord"/> /// to search for the element. /// </param> /// - /// <returns>The PSM number as an uint16 cast to an Int32, /// or -1 if at the <see cref="F:InTheHand.Net.Bluetooth.AttributeIds.UniversalAttributeId.ProtocolDescriptorList"/> /// attribute is missing or contains invalid elements. /// </returns> public static int GetL2CapChannelNumber(ServiceRecord record) { ServiceElement channelElement = GetL2CapChannelElement(record); if (channelElement == null) { return -1; } return GetL2CapChannelNumber(channelElement); } internal static int GetL2CapChannelNumber(ServiceElement channelElement) { Debug.Assert(channelElement != null, "channelElement != null"); Debug.Assert(channelElement.ElementType == ElementType.UInt16); var value = (ushort)channelElement.Value; return value; } /// <summary> /// Sets the RFCOMM Channel Number value in the service record. /// </summary> /// - /// <param name="record">The <see cref="T:InTheHand.Net.Bluetooth.ServiceRecord"/> /// in which to set the RFCOMM Channel number. /// </param> /// <param name="channelNumber">The Channel number to set in the record. /// </param> /// - /// <exception cref="T:System.InvalidOperationException">The /// <see cref="F:InTheHand.Net.Bluetooth.AttributeIds.UniversalAttributeId.ProtocolDescriptorList"/> /// attribute is missing or contains invalid elements. /// </exception> public static void SetRfcommChannelNumber(ServiceRecord record, byte channelNumber) { ServiceElement channelElement = GetRfcommChannelElement(record); if (channelElement == null) { throw new InvalidOperationException("ProtocolDescriptorList element does not exist or is not in the RFCOMM format."); } Debug.Assert(channelElement.ElementType == ElementType.UInt8); channelElement.SetValue(channelNumber); } /// <summary> /// Sets the RFCOMM Channel Number value in the service record. /// </summary> /// - /// <remarks> /// <para>Note: We use an <see cref="T:System.Int32"/> for the /// <paramref name="psm"/> parameter as its natural type <see cref="T:System.UInt16"/> /// in not usable in CLS Compliant interfaces. /// </para> /// </remarks> /// - /// <param name="record">The <see cref="T:InTheHand.Net.Bluetooth.ServiceRecord"/> /// in which to set the L2CAP PSM value. /// </param> /// <param name="psm">The PSM value to set in the record. /// Note that although the parameter is of type <see cref="T:System.Int32"/> /// the value must actually be in the range of a <see cref="T:System.UInt16"/>, /// see the remarks for more information. /// </param> /// - /// <exception cref="T:System.InvalidOperationException">The /// <see cref="F:InTheHand.Net.Bluetooth.AttributeIds.UniversalAttributeId.ProtocolDescriptorList"/> /// attribute is missing or contains invalid elements. /// </exception> /// <exception cref="T:System.ArgumentOutOfRangeException"> /// The PSM must fit in a 16-bit unsigned integer. /// </exception> public static void SetL2CapPsmNumber(ServiceRecord record, int psm) { if (psm < 0 || psm > ushort.MaxValue) throw new ArgumentOutOfRangeException("psm", "A PSM is a UInt16 value."); var psm16 = checked((ushort)psm); ServiceElement rfcommElement = GetRfcommChannelElement(record); if (rfcommElement != null) { Debug.WriteLine("Setting L2CAP PSM for a PDL that includes RFCOMM."); } ServiceElement channelElement = GetChannelElement(record, BluetoothProtocolDescriptorType.L2Cap); if (channelElement == null || channelElement.ElementType != ElementType.UInt16) { throw new InvalidOperationException("ProtocolDescriptorList element does not exist, is not in the L2CAP format, or it the L2CAP layer has no PSM element."); } channelElement.SetValue(psm16); } //-------------------------------------------------------------- /// <summary> /// Creates the data element for the /// <see cref="F:InTheHand.Net.Bluetooth.AttributeIds.UniversalAttributeId.ProtocolDescriptorList"/> /// attribute in an L2CAP service /// </summary> /// - /// <returns>The new <see cref="T:InTheHand.Net.Bluetooth.ServiceElement"/>.</returns> /// - /// <remarks>Thus is the following structure: /// <code lang="none"> /// ElementSequence /// ElementSequence /// Uuid16 = L2CAP /// UInt16 = 0 -- The L2CAP PSM Number. /// </code> /// </remarks> public static ServiceElement CreateL2CapProtocolDescriptorList() { return CreateL2CapProtocolDescriptorListWithUpperLayers(); } /// <summary> /// Creates the data element for the /// <see cref="F:InTheHand.Net.Bluetooth.AttributeIds.UniversalAttributeId.ProtocolDescriptorList"/> /// attribute in an RFCOMM service /// </summary> /// - /// <returns>The new <see cref="T:InTheHand.Net.Bluetooth.ServiceElement"/>.</returns> /// - /// <remarks>Thus is the following structure: /// <code lang="none"> /// ElementSequence /// ElementSequence /// Uuid16 = L2CAP /// ElementSequence /// Uuid16 = RFCOMM /// UInt8 = 0 -- The RFCOMM Channel Number. /// </code> /// </remarks> public static ServiceElement CreateRfcommProtocolDescriptorList() { return CreateRfcommProtocolDescriptorListWithUpperLayers(); } /// <summary> /// Creates the data element for the /// <see cref="F:InTheHand.Net.Bluetooth.AttributeIds.UniversalAttributeId.ProtocolDescriptorList"/> /// attribute in an GOEP (i.e. OBEX) service /// </summary> /// - /// <returns>The new <see cref="T:InTheHand.Net.Bluetooth.ServiceElement"/>.</returns> /// - /// <remarks>Thus is the following structure: /// <code lang="none"> /// ElementSequence /// ElementSequence /// Uuid16 = L2CAP /// ElementSequence /// Uuid16 = RFCOMM /// UInt8 = 0 -- The RFCOMM Channel Number. /// ElementSequence /// Uuid16 = GOEP /// </code> /// </remarks> public static ServiceElement CreateGoepProtocolDescriptorList() { return CreateRfcommProtocolDescriptorListWithUpperLayers( CreatePdlLayer((ushort)ServiceRecordUtilities.HackProtocolId.Obex)); } private static ServiceElement CreateRfcommProtocolDescriptorListWithUpperLayers(params ServiceElement[] upperLayers) { IList<ServiceElement> baseChildren = new List<ServiceElement>(); baseChildren.Add(CreatePdlLayer((UInt16)ServiceRecordUtilities.HackProtocolId.L2Cap)); baseChildren.Add(CreatePdlLayer((UInt16)ServiceRecordUtilities.HackProtocolId.Rfcomm, new ServiceElement(ElementType.UInt8, (byte)0))); foreach (ServiceElement nextLayer in upperLayers) { if (nextLayer.ElementType != ElementType.ElementSequence) { throw new ArgumentException("Each layer in a ProtocolDescriptorList must be an ElementSequence."); } baseChildren.Add(nextLayer); }//for ServiceElement baseElement = new ServiceElement(ElementType.ElementSequence, baseChildren); return baseElement; } /// <summary> /// Creates the data element for the /// <see cref="F:InTheHand.Net.Bluetooth.AttributeIds.UniversalAttributeId.ProtocolDescriptorList"/> /// attribute in an L2CAP service, /// with upper layer entries. /// </summary> /// - /// <returns>The new <see cref="T:InTheHand.Net.Bluetooth.ServiceElement"/>.</returns> /// - /// <remarks>Thus is the following structure at the first layer: /// <code lang="none"> /// ElementSequence /// ElementSequence /// Uuid16 = L2CAP /// UInt16 = 0 -- The L2CAP PSM Number. /// </code> /// One can add layers above that; remember that all layers are formed /// of an ElementSequence. See the example below. /// </remarks> /// - /// <example> /// <code> /// var netProtoList = new ServiceElement(ElementType.ElementSequence, /// ServiceElement.CreateNumericalServiceElement(ElementType.UInt16, 0x0800), /// ServiceElement.CreateNumericalServiceElement(ElementType.UInt16, 0x0806) /// ); /// var layer1 = new ServiceElement(ElementType.ElementSequence, /// new ServiceElement(ElementType.Uuid16, Uuid16_BnepProto), /// ServiceElement.CreateNumericalServiceElement(ElementType.UInt16, 0x0100), //v1.0 /// netProtoList /// ); /// ServiceElement element = ServiceRecordHelper.CreateL2CapProtocolDescriptorListWithUpperLayers( /// layer1); /// </code> /// </example> /// - /// <param name="upperLayers">The list of upper layer elements, one per layer. /// As an array. /// </param> public static ServiceElement CreateL2CapProtocolDescriptorListWithUpperLayers(params ServiceElement[] upperLayers) { IList<ServiceElement> baseChildren = new List<ServiceElement>(); baseChildren.Add(CreatePdlLayer((UInt16)ServiceRecordUtilities.HackProtocolId.L2Cap, new ServiceElement(ElementType.UInt16, (UInt16)0))); foreach (ServiceElement nextLayer in upperLayers) { if (nextLayer.ElementType != ElementType.ElementSequence) { throw new ArgumentException("Each layer in a ProtocolDescriptorList must be an ElementSequence."); } baseChildren.Add(nextLayer); }//for ServiceElement baseElement = new ServiceElement(ElementType.ElementSequence, baseChildren); return baseElement; } private static ServiceElement CreatePdlLayer(UInt16 uuid, params ServiceElement[] data) { IList<ServiceElement> curSeqChildren; ServiceElement curValueElmt, curSeqElmt; // curSeqChildren = new List<ServiceElement>(); curValueElmt = new ServiceElement(ElementType.Uuid16, uuid); curSeqChildren.Add(curValueElmt); foreach (ServiceElement element in data) { curSeqChildren.Add(element); } curSeqElmt = new ServiceElement(ElementType.ElementSequence, curSeqChildren); return curSeqElmt; } //-------------------------------------------------------------- internal static Guid _GetPrimaryServiceClassId(ServiceRecord sr) { var a = sr.GetAttributeById(UniversalAttributeId.ServiceClassIdList); var eL = a.Value; var eClassList = eL.GetValueAsElementList(); var e0 = eClassList[0]; var classId = e0.GetValueAsUuid(); return classId; } }//class }
// // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Xml; using System.Xml.Serialization; using System.Text; using System.Collections; using System.Globalization; namespace System.Web.Services.Description { internal class ServiceDescriptionReaderBase : XmlSerializationReader { public System.Web.Services.Description.ServiceDescription ReadTree () { Reader.MoveToContent(); return ReadObject_ServiceDescription (true, true); } public System.Web.Services.Description.ServiceDescription ReadObject_ServiceDescription (bool isNullable, bool checkType) { System.Web.Services.Description.ServiceDescription ob = null; if (isNullable && ReadNull()) return null; if (checkType) { System.Xml.XmlQualifiedName t = GetXsiType(); if (t != null) { if (t.Name != "ServiceDescription" || t.Namespace != "http://schemas.xmlsoap.org/wsdl/") throw CreateUnknownTypeException(t); } } ob = new System.Web.Services.Description.ServiceDescription (); Reader.MoveToElement(); while (Reader.MoveToNextAttribute()) { if (Reader.LocalName == "name" && Reader.NamespaceURI == "") { ob.Name = XmlConvert.DecodeName(Reader.Value); } else if (Reader.LocalName == "targetNamespace" && Reader.NamespaceURI == "") { ob.TargetNamespace = Reader.Value; } else if (IsXmlnsAttribute (Reader.Name)) { } else { UnknownNode (ob); } } Reader.MoveToElement(); if (Reader.IsEmptyElement) { Reader.Skip (); return ob; } Reader.ReadStartElement(); Reader.MoveToContent(); bool b0=false, b1=false, b2=false, b3=false, b4=false, b5=false, b6=false; System.Web.Services.Description.ImportCollection o8 = ob.Imports; System.Web.Services.Description.MessageCollection o10 = ob.Messages; System.Web.Services.Description.PortTypeCollection o12 = ob.PortTypes; System.Web.Services.Description.BindingCollection o14 = ob.Bindings; System.Web.Services.Description.ServiceCollection o16 = ob.Services; int n7=0, n9=0, n11=0, n13=0, n15=0; while (Reader.NodeType != System.Xml.XmlNodeType.EndElement) { if (Reader.NodeType == System.Xml.XmlNodeType.Element) { if (Reader.LocalName == "binding" && Reader.NamespaceURI == "http://schemas.xmlsoap.org/wsdl/" && !b4) { if (o14 == null) throw CreateReadOnlyCollectionException ("System.Web.Services.Description.BindingCollection"); o14.Add (ReadObject_Binding (false, true)); n13++; } else if (Reader.LocalName == "service" && Reader.NamespaceURI == "http://schemas.xmlsoap.org/wsdl/" && !b5) { if (o16 == null) throw CreateReadOnlyCollectionException ("System.Web.Services.Description.ServiceCollection"); o16.Add (ReadObject_Service (false, true)); n15++; } else if (Reader.LocalName == "import" && Reader.NamespaceURI == "http://schemas.xmlsoap.org/wsdl/" && !b0) { if (o8 == null) throw CreateReadOnlyCollectionException ("System.Web.Services.Description.ImportCollection"); o8.Add (ReadObject_Import (false, true)); n7++; } else if (Reader.LocalName == "documentation" && Reader.NamespaceURI == "http://schemas.xmlsoap.org/wsdl/" && !b6) { b6 = true; ob.Documentation = Reader.ReadElementString (); } else if (Reader.LocalName == "message" && Reader.NamespaceURI == "http://schemas.xmlsoap.org/wsdl/" && !b2) { if (o10 == null) throw CreateReadOnlyCollectionException ("System.Web.Services.Description.MessageCollection"); o10.Add (ReadObject_Message (false, true)); n9++; } else if (Reader.LocalName == "types" && Reader.NamespaceURI == "http://schemas.xmlsoap.org/wsdl/" && !b1) { b1 = true; ob.Types = ReadObject_Types (false, true); } else if (Reader.LocalName == "portType" && Reader.NamespaceURI == "http://schemas.xmlsoap.org/wsdl/" && !b3) { if (o12 == null) throw CreateReadOnlyCollectionException ("System.Web.Services.Description.PortTypeCollection"); o12.Add (ReadObject_PortType (false, true)); n11++; } else { ServiceDescription.ReadExtension (Reader, ob); } } else UnknownNode(ob); Reader.MoveToContent(); } ReadEndElement(); return ob; } public System.Web.Services.Description.Binding ReadObject_Binding (bool isNullable, bool checkType) { System.Web.Services.Description.Binding ob = null; if (isNullable && ReadNull()) return null; if (checkType) { System.Xml.XmlQualifiedName t = GetXsiType(); if (t != null) { if (t.Name != "Binding" || t.Namespace != "http://schemas.xmlsoap.org/wsdl/") throw CreateUnknownTypeException(t); } } ob = new System.Web.Services.Description.Binding (); Reader.MoveToElement(); while (Reader.MoveToNextAttribute()) { if (Reader.LocalName == "name" && Reader.NamespaceURI == "") { ob.Name = XmlConvert.DecodeName(Reader.Value); } else if (Reader.LocalName == "type" && Reader.NamespaceURI == "") { ob.Type = ToXmlQualifiedName (Reader.Value); } else if (IsXmlnsAttribute (Reader.Name)) { } else { UnknownNode (ob); } } Reader.MoveToElement(); if (Reader.IsEmptyElement) { Reader.Skip (); return ob; } Reader.ReadStartElement(); Reader.MoveToContent(); bool b17=false, b18=false; System.Web.Services.Description.OperationBindingCollection o20 = ob.Operations; int n19=0; while (Reader.NodeType != System.Xml.XmlNodeType.EndElement) { if (Reader.NodeType == System.Xml.XmlNodeType.Element) { if (Reader.LocalName == "operation" && Reader.NamespaceURI == "http://schemas.xmlsoap.org/wsdl/" && !b17) { if (o20 == null) throw CreateReadOnlyCollectionException ("System.Web.Services.Description.OperationBindingCollection"); o20.Add (ReadObject_OperationBinding (false, true)); n19++; } else if (Reader.LocalName == "documentation" && Reader.NamespaceURI == "http://schemas.xmlsoap.org/wsdl/" && !b18) { b18 = true; ob.Documentation = Reader.ReadElementString (); } else { ServiceDescription.ReadExtension (Reader, ob); } } else UnknownNode(ob); Reader.MoveToContent(); } ReadEndElement(); return ob; } public System.Web.Services.Description.Service ReadObject_Service (bool isNullable, bool checkType) { System.Web.Services.Description.Service ob = null; if (isNullable && ReadNull()) return null; if (checkType) { System.Xml.XmlQualifiedName t = GetXsiType(); if (t != null) { if (t.Name != "Service" || t.Namespace != "http://schemas.xmlsoap.org/wsdl/") throw CreateUnknownTypeException(t); } } ob = new System.Web.Services.Description.Service (); Reader.MoveToElement(); while (Reader.MoveToNextAttribute()) { if (Reader.LocalName == "name" && Reader.NamespaceURI == "") { ob.Name = XmlConvert.DecodeName(Reader.Value); } else if (IsXmlnsAttribute (Reader.Name)) { } else { UnknownNode (ob); } } Reader.MoveToElement(); if (Reader.IsEmptyElement) { Reader.Skip (); return ob; } Reader.ReadStartElement(); Reader.MoveToContent(); bool b21=false, b22=false; System.Web.Services.Description.PortCollection o24 = ob.Ports; int n23=0; while (Reader.NodeType != System.Xml.XmlNodeType.EndElement) { if (Reader.NodeType == System.Xml.XmlNodeType.Element) { if (Reader.LocalName == "documentation" && Reader.NamespaceURI == "http://schemas.xmlsoap.org/wsdl/" && !b22) { b22 = true; ob.Documentation = Reader.ReadElementString (); } else if (Reader.LocalName == "port" && Reader.NamespaceURI == "http://schemas.xmlsoap.org/wsdl/" && !b21) { if (o24 == null) throw CreateReadOnlyCollectionException ("System.Web.Services.Description.PortCollection"); o24.Add (ReadObject_Port (false, true)); n23++; } else { UnknownNode (ob); } } else UnknownNode(ob); Reader.MoveToContent(); } ReadEndElement(); return ob; } public System.Web.Services.Description.Import ReadObject_Import (bool isNullable, bool checkType) { System.Web.Services.Description.Import ob = null; if (isNullable && ReadNull()) return null; if (checkType) { System.Xml.XmlQualifiedName t = GetXsiType(); if (t != null) { if (t.Name != "Import" || t.Namespace != "http://schemas.xmlsoap.org/wsdl/") throw CreateUnknownTypeException(t); } } ob = new System.Web.Services.Description.Import (); Reader.MoveToElement(); while (Reader.MoveToNextAttribute()) { if (Reader.LocalName == "namespace" && Reader.NamespaceURI == "") { ob.Namespace = Reader.Value; } else if (Reader.LocalName == "location" && Reader.NamespaceURI == "") { ob.Location = Reader.Value; } else if (IsXmlnsAttribute (Reader.Name)) { } else { UnknownNode (ob); } } Reader.MoveToElement(); if (Reader.IsEmptyElement) { Reader.Skip (); return ob; } Reader.ReadStartElement(); Reader.MoveToContent(); bool b25=false; while (Reader.NodeType != System.Xml.XmlNodeType.EndElement) { if (Reader.NodeType == System.Xml.XmlNodeType.Element) { if (Reader.LocalName == "documentation" && Reader.NamespaceURI == "http://schemas.xmlsoap.org/wsdl/" && !b25) { b25 = true; ob.Documentation = Reader.ReadElementString (); } else { UnknownNode (ob); } } else UnknownNode(ob); Reader.MoveToContent(); } ReadEndElement(); return ob; } public System.Web.Services.Description.Message ReadObject_Message (bool isNullable, bool checkType) { System.Web.Services.Description.Message ob = null; if (isNullable && ReadNull()) return null; if (checkType) { System.Xml.XmlQualifiedName t = GetXsiType(); if (t != null) { if (t.Name != "Message" || t.Namespace != "http://schemas.xmlsoap.org/wsdl/") throw CreateUnknownTypeException(t); } } ob = new System.Web.Services.Description.Message (); Reader.MoveToElement(); while (Reader.MoveToNextAttribute()) { if (Reader.LocalName == "name" && Reader.NamespaceURI == "") { ob.Name = XmlConvert.DecodeName(Reader.Value); } else if (IsXmlnsAttribute (Reader.Name)) { } else { UnknownNode (ob); } } Reader.MoveToElement(); if (Reader.IsEmptyElement) { Reader.Skip (); return ob; } Reader.ReadStartElement(); Reader.MoveToContent(); bool b26=false, b27=false; System.Web.Services.Description.MessagePartCollection o29 = ob.Parts; int n28=0; while (Reader.NodeType != System.Xml.XmlNodeType.EndElement) { if (Reader.NodeType == System.Xml.XmlNodeType.Element) { if (Reader.LocalName == "documentation" && Reader.NamespaceURI == "http://schemas.xmlsoap.org/wsdl/" && !b27) { b27 = true; ob.Documentation = Reader.ReadElementString (); } else if (Reader.LocalName == "part" && Reader.NamespaceURI == "http://schemas.xmlsoap.org/wsdl/" && !b26) { if (o29 == null) throw CreateReadOnlyCollectionException ("System.Web.Services.Description.MessagePartCollection"); o29.Add (ReadObject_MessagePart (false, true)); n28++; } else { UnknownNode (ob); } } else UnknownNode(ob); Reader.MoveToContent(); } ReadEndElement(); return ob; } public System.Web.Services.Description.Types ReadObject_Types (bool isNullable, bool checkType) { System.Web.Services.Description.Types ob = null; if (isNullable && ReadNull()) return null; if (checkType) { System.Xml.XmlQualifiedName t = GetXsiType(); if (t != null) { if (t.Name != "Types" || t.Namespace != "http://schemas.xmlsoap.org/wsdl/") throw CreateUnknownTypeException(t); } } ob = new System.Web.Services.Description.Types (); Reader.MoveToElement(); while (Reader.MoveToNextAttribute()) { if (IsXmlnsAttribute (Reader.Name)) { } else { UnknownNode (ob); } } Reader.MoveToElement(); if (Reader.IsEmptyElement) { Reader.Skip (); return ob; } Reader.ReadStartElement(); Reader.MoveToContent(); bool b30=false, b31=false; System.Xml.Serialization.XmlSchemas o33 = ob.Schemas; int n32=0; while (Reader.NodeType != System.Xml.XmlNodeType.EndElement) { if (Reader.NodeType == System.Xml.XmlNodeType.Element) { if (Reader.LocalName == "documentation" && Reader.NamespaceURI == "http://schemas.xmlsoap.org/wsdl/" && !b31) { b31 = true; ob.Documentation = Reader.ReadElementString (); } else if (Reader.LocalName == "schema" && Reader.NamespaceURI == "http://www.w3.org/2001/XMLSchema" && !b30) { if (o33 == null) throw CreateReadOnlyCollectionException ("System.Xml.Serialization.XmlSchemas"); o33.Add (ReadObject_XmlSchema (false, true)); n32++; } else { ServiceDescription.ReadExtension (Reader, ob); } } else UnknownNode(ob); Reader.MoveToContent(); } ReadEndElement(); return ob; } public System.Web.Services.Description.PortType ReadObject_PortType (bool isNullable, bool checkType) { System.Web.Services.Description.PortType ob = null; if (isNullable && ReadNull()) return null; if (checkType) { System.Xml.XmlQualifiedName t = GetXsiType(); if (t != null) { if (t.Name != "PortType" || t.Namespace != "http://schemas.xmlsoap.org/wsdl/") throw CreateUnknownTypeException(t); } } ob = new System.Web.Services.Description.PortType (); Reader.MoveToElement(); while (Reader.MoveToNextAttribute()) { if (Reader.LocalName == "name" && Reader.NamespaceURI == "") { ob.Name = XmlConvert.DecodeName(Reader.Value); } else if (IsXmlnsAttribute (Reader.Name)) { } else { UnknownNode (ob); } } Reader.MoveToElement(); if (Reader.IsEmptyElement) { Reader.Skip (); return ob; } Reader.ReadStartElement(); Reader.MoveToContent(); bool b34=false, b35=false; System.Web.Services.Description.OperationCollection o37 = ob.Operations; int n36=0; while (Reader.NodeType != System.Xml.XmlNodeType.EndElement) { if (Reader.NodeType == System.Xml.XmlNodeType.Element) { if (Reader.LocalName == "operation" && Reader.NamespaceURI == "http://schemas.xmlsoap.org/wsdl/" && !b34) { if (o37 == null) throw CreateReadOnlyCollectionException ("System.Web.Services.Description.OperationCollection"); o37.Add (ReadObject_Operation (false, true)); n36++; } else if (Reader.LocalName == "documentation" && Reader.NamespaceURI == "http://schemas.xmlsoap.org/wsdl/" && !b35) { b35 = true; ob.Documentation = Reader.ReadElementString (); } else { UnknownNode (ob); } } else UnknownNode(ob); Reader.MoveToContent(); } ReadEndElement(); return ob; } public System.Web.Services.Description.OperationBinding ReadObject_OperationBinding (bool isNullable, bool checkType) { System.Web.Services.Description.OperationBinding ob = null; if (isNullable && ReadNull()) return null; if (checkType) { System.Xml.XmlQualifiedName t = GetXsiType(); if (t != null) { if (t.Name != "OperationBinding" || t.Namespace != "http://schemas.xmlsoap.org/wsdl/") throw CreateUnknownTypeException(t); } } ob = new System.Web.Services.Description.OperationBinding (); Reader.MoveToElement(); while (Reader.MoveToNextAttribute()) { if (Reader.LocalName == "name" && Reader.NamespaceURI == "") { ob.Name = XmlConvert.DecodeName(Reader.Value); } else if (IsXmlnsAttribute (Reader.Name)) { } else { UnknownNode (ob); } } Reader.MoveToElement(); if (Reader.IsEmptyElement) { Reader.Skip (); return ob; } Reader.ReadStartElement(); Reader.MoveToContent(); bool b38=false, b39=false, b40=false, b41=false; System.Web.Services.Description.FaultBindingCollection o43 = ob.Faults; int n42=0; while (Reader.NodeType != System.Xml.XmlNodeType.EndElement) { if (Reader.NodeType == System.Xml.XmlNodeType.Element) { if (Reader.LocalName == "input" && Reader.NamespaceURI == "http://schemas.xmlsoap.org/wsdl/" && !b39) { b39 = true; ob.Input = ReadObject_InputBinding (false, true); } else if (Reader.LocalName == "fault" && Reader.NamespaceURI == "http://schemas.xmlsoap.org/wsdl/" && !b38) { if (o43 == null) throw CreateReadOnlyCollectionException ("System.Web.Services.Description.FaultBindingCollection"); o43.Add (ReadObject_FaultBinding (false, true)); n42++; } else if (Reader.LocalName == "documentation" && Reader.NamespaceURI == "http://schemas.xmlsoap.org/wsdl/" && !b41) { b41 = true; ob.Documentation = Reader.ReadElementString (); } else if (Reader.LocalName == "output" && Reader.NamespaceURI == "http://schemas.xmlsoap.org/wsdl/" && !b40) { b40 = true; ob.Output = ReadObject_OutputBinding (false, true); } else { ServiceDescription.ReadExtension (Reader, ob); } } else UnknownNode(ob); Reader.MoveToContent(); } ReadEndElement(); return ob; } public System.Web.Services.Description.Port ReadObject_Port (bool isNullable, bool checkType) { System.Web.Services.Description.Port ob = null; if (isNullable && ReadNull()) return null; if (checkType) { System.Xml.XmlQualifiedName t = GetXsiType(); if (t != null) { if (t.Name != "Port" || t.Namespace != "http://schemas.xmlsoap.org/wsdl/") throw CreateUnknownTypeException(t); } } ob = new System.Web.Services.Description.Port (); Reader.MoveToElement(); while (Reader.MoveToNextAttribute()) { if (Reader.LocalName == "name" && Reader.NamespaceURI == "") { ob.Name = XmlConvert.DecodeName(Reader.Value); } else if (Reader.LocalName == "binding" && Reader.NamespaceURI == "") { ob.Binding = ToXmlQualifiedName (Reader.Value); } else if (IsXmlnsAttribute (Reader.Name)) { } else { UnknownNode (ob); } } Reader.MoveToElement(); if (Reader.IsEmptyElement) { Reader.Skip (); return ob; } Reader.ReadStartElement(); Reader.MoveToContent(); bool b44=false; while (Reader.NodeType != System.Xml.XmlNodeType.EndElement) { if (Reader.NodeType == System.Xml.XmlNodeType.Element) { if (Reader.LocalName == "documentation" && Reader.NamespaceURI == "http://schemas.xmlsoap.org/wsdl/" && !b44) { b44 = true; ob.Documentation = Reader.ReadElementString (); } else { ServiceDescription.ReadExtension (Reader, ob); } } else UnknownNode(ob); Reader.MoveToContent(); } ReadEndElement(); return ob; } public System.Web.Services.Description.MessagePart ReadObject_MessagePart (bool isNullable, bool checkType) { System.Web.Services.Description.MessagePart ob = null; if (isNullable && ReadNull()) return null; if (checkType) { System.Xml.XmlQualifiedName t = GetXsiType(); if (t != null) { if (t.Name != "MessagePart" || t.Namespace != "http://schemas.xmlsoap.org/wsdl/") throw CreateUnknownTypeException(t); } } ob = new System.Web.Services.Description.MessagePart (); Reader.MoveToElement(); while (Reader.MoveToNextAttribute()) { if (Reader.LocalName == "name" && Reader.NamespaceURI == "") { ob.Name = XmlConvert.DecodeName(Reader.Value); } else if (Reader.LocalName == "element" && Reader.NamespaceURI == "") { ob.Element = ToXmlQualifiedName (Reader.Value); } else if (Reader.LocalName == "type" && Reader.NamespaceURI == "") { ob.Type = ToXmlQualifiedName (Reader.Value); } else if (IsXmlnsAttribute (Reader.Name)) { } else { UnknownNode (ob); } } Reader.MoveToElement(); if (Reader.IsEmptyElement) { Reader.Skip (); return ob; } Reader.ReadStartElement(); Reader.MoveToContent(); bool b45=false; while (Reader.NodeType != System.Xml.XmlNodeType.EndElement) { if (Reader.NodeType == System.Xml.XmlNodeType.Element) { if (Reader.LocalName == "documentation" && Reader.NamespaceURI == "http://schemas.xmlsoap.org/wsdl/" && !b45) { b45 = true; ob.Documentation = Reader.ReadElementString (); } else { UnknownNode (ob); } } else UnknownNode(ob); Reader.MoveToContent(); } ReadEndElement(); return ob; } public System.Xml.Schema.XmlSchema ReadObject_XmlSchema (bool isNullable, bool checkType) { System.Xml.Schema.XmlSchema ob = null; ob = System.Xml.Schema.XmlSchema.Read (Reader, null); return ob; } public System.Web.Services.Description.Operation ReadObject_Operation (bool isNullable, bool checkType) { System.Web.Services.Description.Operation ob = null; if (isNullable && ReadNull()) return null; if (checkType) { System.Xml.XmlQualifiedName t = GetXsiType(); if (t != null) { if (t.Name != "Operation" || t.Namespace != "http://schemas.xmlsoap.org/wsdl/") throw CreateUnknownTypeException(t); } } ob = new System.Web.Services.Description.Operation (); Reader.MoveToElement(); while (Reader.MoveToNextAttribute()) { if (Reader.LocalName == "name" && Reader.NamespaceURI == "") { ob.Name = XmlConvert.DecodeName(Reader.Value); } else if (Reader.LocalName == "parameterOrder" && Reader.NamespaceURI == "") { ob.ParameterOrderString = Reader.Value; } else if (IsXmlnsAttribute (Reader.Name)) { } else { UnknownNode (ob); } } Reader.MoveToElement(); if (Reader.IsEmptyElement) { Reader.Skip (); return ob; } Reader.ReadStartElement(); Reader.MoveToContent(); bool b46=false, b47=false, b48=false; System.Web.Services.Description.OperationFaultCollection o50 = ob.Faults; System.Web.Services.Description.OperationMessageCollection o52 = ob.Messages; int n49=0, n51=0; while (Reader.NodeType != System.Xml.XmlNodeType.EndElement) { if (Reader.NodeType == System.Xml.XmlNodeType.Element) { if (Reader.LocalName == "input" && Reader.NamespaceURI == "http://schemas.xmlsoap.org/wsdl/" && !b47) { if (o52 == null) throw CreateReadOnlyCollectionException ("System.Web.Services.Description.OperationMessageCollection"); o52.Add (ReadObject_OperationInput (false, true)); n51++; } else if (Reader.LocalName == "fault" && Reader.NamespaceURI == "http://schemas.xmlsoap.org/wsdl/" && !b46) { if (o50 == null) throw CreateReadOnlyCollectionException ("System.Web.Services.Description.OperationFaultCollection"); o50.Add (ReadObject_OperationFault (false, true)); n49++; } else if (Reader.LocalName == "documentation" && Reader.NamespaceURI == "http://schemas.xmlsoap.org/wsdl/" && !b48) { b48 = true; ob.Documentation = Reader.ReadElementString (); } else if (Reader.LocalName == "output" && Reader.NamespaceURI == "http://schemas.xmlsoap.org/wsdl/" && !b47) { if (o52 == null) throw CreateReadOnlyCollectionException ("System.Web.Services.Description.OperationMessageCollection"); o52.Add (ReadObject_OperationOutput (false, true)); n51++; } else { UnknownNode (ob); } } else UnknownNode(ob); Reader.MoveToContent(); } ReadEndElement(); return ob; } public System.Web.Services.Description.InputBinding ReadObject_InputBinding (bool isNullable, bool checkType) { System.Web.Services.Description.InputBinding ob = null; if (isNullable && ReadNull()) return null; if (checkType) { System.Xml.XmlQualifiedName t = GetXsiType(); if (t != null) { if (t.Name != "InputBinding" || t.Namespace != "http://schemas.xmlsoap.org/wsdl/") throw CreateUnknownTypeException(t); } } ob = new System.Web.Services.Description.InputBinding (); Reader.MoveToElement(); while (Reader.MoveToNextAttribute()) { if (Reader.LocalName == "name" && Reader.NamespaceURI == "") { ob.Name = XmlConvert.DecodeName(Reader.Value); } else if (IsXmlnsAttribute (Reader.Name)) { } else { UnknownNode (ob); } } Reader.MoveToElement(); if (Reader.IsEmptyElement) { Reader.Skip (); return ob; } Reader.ReadStartElement(); Reader.MoveToContent(); bool b53=false; while (Reader.NodeType != System.Xml.XmlNodeType.EndElement) { if (Reader.NodeType == System.Xml.XmlNodeType.Element) { if (Reader.LocalName == "documentation" && Reader.NamespaceURI == "http://schemas.xmlsoap.org/wsdl/" && !b53) { b53 = true; ob.Documentation = Reader.ReadElementString (); } else { ServiceDescription.ReadExtension (Reader, ob); } } else UnknownNode(ob); Reader.MoveToContent(); } ReadEndElement(); return ob; } public System.Web.Services.Description.FaultBinding ReadObject_FaultBinding (bool isNullable, bool checkType) { System.Web.Services.Description.FaultBinding ob = null; if (isNullable && ReadNull()) return null; if (checkType) { System.Xml.XmlQualifiedName t = GetXsiType(); if (t != null) { if (t.Name != "FaultBinding" || t.Namespace != "http://schemas.xmlsoap.org/wsdl/") throw CreateUnknownTypeException(t); } } ob = new System.Web.Services.Description.FaultBinding (); Reader.MoveToElement(); while (Reader.MoveToNextAttribute()) { if (Reader.LocalName == "name" && Reader.NamespaceURI == "") { ob.Name = XmlConvert.DecodeName(Reader.Value); } else if (IsXmlnsAttribute (Reader.Name)) { } else { UnknownNode (ob); } } Reader.MoveToElement(); if (Reader.IsEmptyElement) { Reader.Skip (); return ob; } Reader.ReadStartElement(); Reader.MoveToContent(); bool b54=false; while (Reader.NodeType != System.Xml.XmlNodeType.EndElement) { if (Reader.NodeType == System.Xml.XmlNodeType.Element) { if (Reader.LocalName == "documentation" && Reader.NamespaceURI == "http://schemas.xmlsoap.org/wsdl/" && !b54) { b54 = true; ob.Documentation = Reader.ReadElementString (); } else { ServiceDescription.ReadExtension (Reader, ob); } } else UnknownNode(ob); Reader.MoveToContent(); } ReadEndElement(); return ob; } public System.Web.Services.Description.OutputBinding ReadObject_OutputBinding (bool isNullable, bool checkType) { System.Web.Services.Description.OutputBinding ob = null; if (isNullable && ReadNull()) return null; if (checkType) { System.Xml.XmlQualifiedName t = GetXsiType(); if (t != null) { if (t.Name != "OutputBinding" || t.Namespace != "http://schemas.xmlsoap.org/wsdl/") throw CreateUnknownTypeException(t); } } ob = new System.Web.Services.Description.OutputBinding (); Reader.MoveToElement(); while (Reader.MoveToNextAttribute()) { if (Reader.LocalName == "name" && Reader.NamespaceURI == "") { ob.Name = XmlConvert.DecodeName(Reader.Value); } else if (IsXmlnsAttribute (Reader.Name)) { } else { UnknownNode (ob); } } Reader.MoveToElement(); if (Reader.IsEmptyElement) { Reader.Skip (); return ob; } Reader.ReadStartElement(); Reader.MoveToContent(); bool b55=false; while (Reader.NodeType != System.Xml.XmlNodeType.EndElement) { if (Reader.NodeType == System.Xml.XmlNodeType.Element) { if (Reader.LocalName == "documentation" && Reader.NamespaceURI == "http://schemas.xmlsoap.org/wsdl/" && !b55) { b55 = true; ob.Documentation = Reader.ReadElementString (); } else { ServiceDescription.ReadExtension (Reader, ob); } } else UnknownNode(ob); Reader.MoveToContent(); } ReadEndElement(); return ob; } public System.Web.Services.Description.OperationInput ReadObject_OperationInput (bool isNullable, bool checkType) { System.Web.Services.Description.OperationInput ob = null; if (isNullable && ReadNull()) return null; if (checkType) { System.Xml.XmlQualifiedName t = GetXsiType(); if (t != null) { if (t.Name != "OperationInput" || t.Namespace != "http://schemas.xmlsoap.org/wsdl/") throw CreateUnknownTypeException(t); } } ob = new System.Web.Services.Description.OperationInput (); Reader.MoveToElement(); while (Reader.MoveToNextAttribute()) { if (Reader.LocalName == "name" && Reader.NamespaceURI == "") { ob.Name = XmlConvert.DecodeName(Reader.Value); } else if (Reader.LocalName == "message" && Reader.NamespaceURI == "") { ob.Message = ToXmlQualifiedName (Reader.Value); } else if (IsXmlnsAttribute (Reader.Name)) { } else { UnknownNode (ob); } } Reader.MoveToElement(); if (Reader.IsEmptyElement) { Reader.Skip (); return ob; } Reader.ReadStartElement(); Reader.MoveToContent(); bool b56=false; while (Reader.NodeType != System.Xml.XmlNodeType.EndElement) { if (Reader.NodeType == System.Xml.XmlNodeType.Element) { if (Reader.LocalName == "documentation" && Reader.NamespaceURI == "http://schemas.xmlsoap.org/wsdl/" && !b56) { b56 = true; ob.Documentation = Reader.ReadElementString (); } else { UnknownNode (ob); } } else UnknownNode(ob); Reader.MoveToContent(); } ReadEndElement(); return ob; } public System.Web.Services.Description.OperationFault ReadObject_OperationFault (bool isNullable, bool checkType) { System.Web.Services.Description.OperationFault ob = null; if (isNullable && ReadNull()) return null; if (checkType) { System.Xml.XmlQualifiedName t = GetXsiType(); if (t != null) { if (t.Name != "OperationFault" || t.Namespace != "http://schemas.xmlsoap.org/wsdl/") throw CreateUnknownTypeException(t); } } ob = new System.Web.Services.Description.OperationFault (); Reader.MoveToElement(); while (Reader.MoveToNextAttribute()) { if (Reader.LocalName == "name" && Reader.NamespaceURI == "") { ob.Name = XmlConvert.DecodeName(Reader.Value); } else if (Reader.LocalName == "message" && Reader.NamespaceURI == "") { ob.Message = ToXmlQualifiedName (Reader.Value); } else if (IsXmlnsAttribute (Reader.Name)) { } else { UnknownNode (ob); } } Reader.MoveToElement(); if (Reader.IsEmptyElement) { Reader.Skip (); return ob; } Reader.ReadStartElement(); Reader.MoveToContent(); bool b57=false; while (Reader.NodeType != System.Xml.XmlNodeType.EndElement) { if (Reader.NodeType == System.Xml.XmlNodeType.Element) { if (Reader.LocalName == "documentation" && Reader.NamespaceURI == "http://schemas.xmlsoap.org/wsdl/" && !b57) { b57 = true; ob.Documentation = Reader.ReadElementString (); } else { UnknownNode (ob); } } else UnknownNode(ob); Reader.MoveToContent(); } ReadEndElement(); return ob; } public System.Web.Services.Description.OperationOutput ReadObject_OperationOutput (bool isNullable, bool checkType) { System.Web.Services.Description.OperationOutput ob = null; if (isNullable && ReadNull()) return null; if (checkType) { System.Xml.XmlQualifiedName t = GetXsiType(); if (t != null) { if (t.Name != "OperationOutput" || t.Namespace != "http://schemas.xmlsoap.org/wsdl/") throw CreateUnknownTypeException(t); } } ob = new System.Web.Services.Description.OperationOutput (); Reader.MoveToElement(); while (Reader.MoveToNextAttribute()) { if (Reader.LocalName == "name" && Reader.NamespaceURI == "") { ob.Name = XmlConvert.DecodeName(Reader.Value); } else if (Reader.LocalName == "message" && Reader.NamespaceURI == "") { ob.Message = ToXmlQualifiedName (Reader.Value); } else if (IsXmlnsAttribute (Reader.Name)) { } else { UnknownNode (ob); } } Reader.MoveToElement(); if (Reader.IsEmptyElement) { Reader.Skip (); return ob; } Reader.ReadStartElement(); Reader.MoveToContent(); bool b58=false; while (Reader.NodeType != System.Xml.XmlNodeType.EndElement) { if (Reader.NodeType == System.Xml.XmlNodeType.Element) { if (Reader.LocalName == "documentation" && Reader.NamespaceURI == "http://schemas.xmlsoap.org/wsdl/" && !b58) { b58 = true; ob.Documentation = Reader.ReadElementString (); } else { UnknownNode (ob); } } else UnknownNode(ob); Reader.MoveToContent(); } ReadEndElement(); return ob; } protected override void InitCallbacks () { } protected override void InitIDs () { } } internal class ServiceDescriptionWriterBase : XmlSerializationWriter { public void WriteTree (System.Web.Services.Description.ServiceDescription ob) { WriteStartDocument (); TopLevelElement (); WriteObject_ServiceDescription (ob, "definitions", "http://schemas.xmlsoap.org/wsdl/", true, false, true); } void WriteObject_ServiceDescription (System.Web.Services.Description.ServiceDescription ob, string element, string namesp, bool isNullable, bool needType, bool writeWrappingElem) { if (ob == null) { if (isNullable) WriteNullTagLiteral(element, namesp); return; } if (writeWrappingElem) { WriteStartElement (element, namesp, ob); } if (needType) WriteXsiType("ServiceDescription", "http://schemas.xmlsoap.org/wsdl/"); WriteAttribute ("name", "", XmlConvert.EncodeNmToken(ob.Name)); WriteAttribute ("targetNamespace", "", ob.TargetNamespace); ServiceDescription.WriteExtensions (Writer, ob); if (ob.Imports != null) { for (int n59 = 0; n59 < ob.Imports.Count; n59++) { WriteObject_Import (ob.Imports[n59], "import", "http://schemas.xmlsoap.org/wsdl/", false, false, true); } } WriteObject_Types (ob.Types, "types", "http://schemas.xmlsoap.org/wsdl/", false, false, true); if (ob.Messages != null) { for (int n60 = 0; n60 < ob.Messages.Count; n60++) { WriteObject_Message (ob.Messages[n60], "message", "http://schemas.xmlsoap.org/wsdl/", false, false, true); } } if (ob.PortTypes != null) { for (int n61 = 0; n61 < ob.PortTypes.Count; n61++) { WriteObject_PortType (ob.PortTypes[n61], "portType", "http://schemas.xmlsoap.org/wsdl/", false, false, true); } } if (ob.Bindings != null) { for (int n62 = 0; n62 < ob.Bindings.Count; n62++) { WriteObject_Binding (ob.Bindings[n62], "binding", "http://schemas.xmlsoap.org/wsdl/", false, false, true); } } if (ob.Services != null) { for (int n63 = 0; n63 < ob.Services.Count; n63++) { WriteObject_Service (ob.Services[n63], "service", "http://schemas.xmlsoap.org/wsdl/", false, false, true); } } if (ob.Documentation != "") { WriteElementString ("documentation", "http://schemas.xmlsoap.org/wsdl/", ob.Documentation); } if (writeWrappingElem) WriteEndElement (ob); } void WriteObject_Import (System.Web.Services.Description.Import ob, string element, string namesp, bool isNullable, bool needType, bool writeWrappingElem) { if (ob == null) { if (isNullable) WriteNullTagLiteral(element, namesp); return; } if (writeWrappingElem) { WriteStartElement (element, namesp, ob); } if (needType) WriteXsiType("Import", "http://schemas.xmlsoap.org/wsdl/"); WriteAttribute ("namespace", "", ob.Namespace); WriteAttribute ("location", "", ob.Location); if (ob.Documentation != "") { WriteElementString ("documentation", "http://schemas.xmlsoap.org/wsdl/", ob.Documentation); } if (writeWrappingElem) WriteEndElement (ob); } void WriteObject_Types (System.Web.Services.Description.Types ob, string element, string namesp, bool isNullable, bool needType, bool writeWrappingElem) { if (ob == null) { if (isNullable) WriteNullTagLiteral(element, namesp); return; } if (writeWrappingElem) { WriteStartElement (element, namesp, ob); } if (needType) WriteXsiType("Types", "http://schemas.xmlsoap.org/wsdl/"); ServiceDescription.WriteExtensions (Writer, ob); if (ob.Schemas != null) { for (int n64 = 0; n64 < ob.Schemas.Count; n64++) { WriteObject_XmlSchema (ob.Schemas[n64], "schema", "http://www.w3.org/2001/XMLSchema", false, false, true); } } if (ob.Documentation != "") { WriteElementString ("documentation", "http://schemas.xmlsoap.org/wsdl/", ob.Documentation); } if (writeWrappingElem) WriteEndElement (ob); } void WriteObject_Message (System.Web.Services.Description.Message ob, string element, string namesp, bool isNullable, bool needType, bool writeWrappingElem) { if (ob == null) { if (isNullable) WriteNullTagLiteral(element, namesp); return; } if (writeWrappingElem) { WriteStartElement (element, namesp, ob); } if (needType) WriteXsiType("Message", "http://schemas.xmlsoap.org/wsdl/"); WriteAttribute ("name", "", XmlConvert.EncodeName(ob.Name)); if (ob.Parts != null) { for (int n65 = 0; n65 < ob.Parts.Count; n65++) { WriteObject_MessagePart (ob.Parts[n65], "part", "http://schemas.xmlsoap.org/wsdl/", false, false, true); } } if (ob.Documentation != "") { WriteElementString ("documentation", "http://schemas.xmlsoap.org/wsdl/", ob.Documentation); } if (writeWrappingElem) WriteEndElement (ob); } void WriteObject_PortType (System.Web.Services.Description.PortType ob, string element, string namesp, bool isNullable, bool needType, bool writeWrappingElem) { if (ob == null) { if (isNullable) WriteNullTagLiteral(element, namesp); return; } if (writeWrappingElem) { WriteStartElement (element, namesp, ob); } if (needType) WriteXsiType("PortType", "http://schemas.xmlsoap.org/wsdl/"); WriteAttribute ("name", "", XmlConvert.EncodeName(ob.Name)); if (ob.Operations != null) { for (int n66 = 0; n66 < ob.Operations.Count; n66++) { WriteObject_Operation (ob.Operations[n66], "operation", "http://schemas.xmlsoap.org/wsdl/", false, false, true); } } if (ob.Documentation != "") { WriteElementString ("documentation", "http://schemas.xmlsoap.org/wsdl/", ob.Documentation); } if (writeWrappingElem) WriteEndElement (ob); } void WriteObject_Binding (System.Web.Services.Description.Binding ob, string element, string namesp, bool isNullable, bool needType, bool writeWrappingElem) { if (ob == null) { if (isNullable) WriteNullTagLiteral(element, namesp); return; } if (writeWrappingElem) { WriteStartElement (element, namesp, ob); } if (needType) WriteXsiType("Binding", "http://schemas.xmlsoap.org/wsdl/"); WriteAttribute ("name", "", XmlConvert.EncodeName(ob.Name)); WriteAttribute ("type", "", FromXmlQualifiedName (ob.Type)); ServiceDescription.WriteExtensions (Writer, ob); if (ob.Operations != null) { for (int n67 = 0; n67 < ob.Operations.Count; n67++) { WriteObject_OperationBinding (ob.Operations[n67], "operation", "http://schemas.xmlsoap.org/wsdl/", false, false, true); } } if (ob.Documentation != "") { WriteElementString ("documentation", "http://schemas.xmlsoap.org/wsdl/", ob.Documentation); } if (writeWrappingElem) WriteEndElement (ob); } void WriteObject_Service (System.Web.Services.Description.Service ob, string element, string namesp, bool isNullable, bool needType, bool writeWrappingElem) { if (ob == null) { if (isNullable) WriteNullTagLiteral(element, namesp); return; } if (writeWrappingElem) { WriteStartElement (element, namesp, ob); } if (needType) WriteXsiType("Service", "http://schemas.xmlsoap.org/wsdl/"); WriteAttribute ("name", "", XmlConvert.EncodeName(ob.Name)); if (ob.Ports != null) { for (int n68 = 0; n68 < ob.Ports.Count; n68++) { WriteObject_Port (ob.Ports[n68], "port", "http://schemas.xmlsoap.org/wsdl/", false, false, true); } } if (ob.Documentation != "") { WriteElementString ("documentation", "http://schemas.xmlsoap.org/wsdl/", ob.Documentation); } if (writeWrappingElem) WriteEndElement (ob); } void WriteObject_XmlSchema (System.Xml.Schema.XmlSchema ob, string element, string namesp, bool isNullable, bool needType, bool writeWrappingElem) { ob.Write (Writer); } void WriteObject_MessagePart (System.Web.Services.Description.MessagePart ob, string element, string namesp, bool isNullable, bool needType, bool writeWrappingElem) { if (ob == null) { if (isNullable) WriteNullTagLiteral(element, namesp); return; } if (writeWrappingElem) { WriteStartElement (element, namesp, ob); } if (needType) WriteXsiType("MessagePart", "http://schemas.xmlsoap.org/wsdl/"); WriteAttribute ("name", "", XmlConvert.EncodeNmToken(ob.Name)); WriteAttribute ("element", "", FromXmlQualifiedName (ob.Element)); WriteAttribute ("type", "", FromXmlQualifiedName (ob.Type)); if (ob.Documentation != "") { WriteElementString ("documentation", "http://schemas.xmlsoap.org/wsdl/", ob.Documentation); } if (writeWrappingElem) WriteEndElement (ob); } void WriteObject_Operation (System.Web.Services.Description.Operation ob, string element, string namesp, bool isNullable, bool needType, bool writeWrappingElem) { if (ob == null) { if (isNullable) WriteNullTagLiteral(element, namesp); return; } if (writeWrappingElem) { WriteStartElement (element, namesp, ob); } if (needType) WriteXsiType("Operation", "http://schemas.xmlsoap.org/wsdl/"); WriteAttribute ("name", "", XmlConvert.EncodeName(ob.Name)); if (ob.ParameterOrderString != "") { WriteAttribute ("parameterOrder", "", ob.ParameterOrderString); } if (ob.Faults != null) { for (int n69 = 0; n69 < ob.Faults.Count; n69++) { WriteObject_OperationFault (ob.Faults[n69], "fault", "http://schemas.xmlsoap.org/wsdl/", false, false, true); } } if (ob.Messages != null) { for (int n70 = 0; n70 < ob.Messages.Count; n70++) { if (ob.Messages[n70] is System.Web.Services.Description.OperationInput) { WriteObject_OperationInput (((System.Web.Services.Description.OperationInput) ob.Messages[n70]), "input", "http://schemas.xmlsoap.org/wsdl/", false, false, true); } else if (ob.Messages[n70] is System.Web.Services.Description.OperationOutput) { WriteObject_OperationOutput (((System.Web.Services.Description.OperationOutput) ob.Messages[n70]), "output", "http://schemas.xmlsoap.org/wsdl/", false, false, true); } else if (ob.Messages[n70] != null) throw CreateUnknownTypeException (ob.Messages[n70]); } } if (ob.Documentation != "") { WriteElementString ("documentation", "http://schemas.xmlsoap.org/wsdl/", ob.Documentation); } if (writeWrappingElem) WriteEndElement (ob); } void WriteObject_OperationBinding (System.Web.Services.Description.OperationBinding ob, string element, string namesp, bool isNullable, bool needType, bool writeWrappingElem) { if (ob == null) { if (isNullable) WriteNullTagLiteral(element, namesp); return; } if (writeWrappingElem) { WriteStartElement (element, namesp, ob); } if (needType) WriteXsiType("OperationBinding", "http://schemas.xmlsoap.org/wsdl/"); WriteAttribute ("name", "", XmlConvert.EncodeName(ob.Name)); ServiceDescription.WriteExtensions (Writer, ob); if (ob.Faults != null) { for (int n71 = 0; n71 < ob.Faults.Count; n71++) { WriteObject_FaultBinding (ob.Faults[n71], "fault", "http://schemas.xmlsoap.org/wsdl/", false, false, true); } } WriteObject_InputBinding (ob.Input, "input", "http://schemas.xmlsoap.org/wsdl/", false, false, true); WriteObject_OutputBinding (ob.Output, "output", "http://schemas.xmlsoap.org/wsdl/", false, false, true); if (ob.Documentation != "") { WriteElementString ("documentation", "http://schemas.xmlsoap.org/wsdl/", ob.Documentation); } if (writeWrappingElem) WriteEndElement (ob); } void WriteObject_Port (System.Web.Services.Description.Port ob, string element, string namesp, bool isNullable, bool needType, bool writeWrappingElem) { if (ob == null) { if (isNullable) WriteNullTagLiteral(element, namesp); return; } if (writeWrappingElem) { WriteStartElement (element, namesp, ob); } if (needType) WriteXsiType("Port", "http://schemas.xmlsoap.org/wsdl/"); WriteAttribute ("name", "", XmlConvert.EncodeName(ob.Name)); WriteAttribute ("binding", "", FromXmlQualifiedName (ob.Binding)); ServiceDescription.WriteExtensions (Writer, ob); if (ob.Documentation != "") { WriteElementString ("documentation", "http://schemas.xmlsoap.org/wsdl/", ob.Documentation); } if (writeWrappingElem) WriteEndElement (ob); } void WriteObject_OperationFault (System.Web.Services.Description.OperationFault ob, string element, string namesp, bool isNullable, bool needType, bool writeWrappingElem) { if (ob == null) { if (isNullable) WriteNullTagLiteral(element, namesp); return; } if (writeWrappingElem) { WriteStartElement (element, namesp, ob); } if (needType) WriteXsiType("OperationFault", "http://schemas.xmlsoap.org/wsdl/"); WriteAttribute ("name", "", XmlConvert.EncodeNmToken(ob.Name)); WriteAttribute ("message", "", FromXmlQualifiedName (ob.Message)); if (ob.Documentation != "") { WriteElementString ("documentation", "http://schemas.xmlsoap.org/wsdl/", ob.Documentation); } if (writeWrappingElem) WriteEndElement (ob); } void WriteObject_OperationInput (System.Web.Services.Description.OperationInput ob, string element, string namesp, bool isNullable, bool needType, bool writeWrappingElem) { if (ob == null) { if (isNullable) WriteNullTagLiteral(element, namesp); return; } if (writeWrappingElem) { WriteStartElement (element, namesp, ob); } if (needType) WriteXsiType("OperationInput", "http://schemas.xmlsoap.org/wsdl/"); WriteAttribute ("name", "", XmlConvert.EncodeNmToken(ob.Name)); WriteAttribute ("message", "", FromXmlQualifiedName (ob.Message)); if (ob.Documentation != "") { WriteElementString ("documentation", "http://schemas.xmlsoap.org/wsdl/", ob.Documentation); } if (writeWrappingElem) WriteEndElement (ob); } void WriteObject_OperationOutput (System.Web.Services.Description.OperationOutput ob, string element, string namesp, bool isNullable, bool needType, bool writeWrappingElem) { if (ob == null) { if (isNullable) WriteNullTagLiteral(element, namesp); return; } if (writeWrappingElem) { WriteStartElement (element, namesp, ob); } if (needType) WriteXsiType("OperationOutput", "http://schemas.xmlsoap.org/wsdl/"); WriteAttribute ("name", "", XmlConvert.EncodeNmToken(ob.Name)); WriteAttribute ("message", "", FromXmlQualifiedName (ob.Message)); if (ob.Documentation != "") { WriteElementString ("documentation", "http://schemas.xmlsoap.org/wsdl/", ob.Documentation); } if (writeWrappingElem) WriteEndElement (ob); } void WriteObject_FaultBinding (System.Web.Services.Description.FaultBinding ob, string element, string namesp, bool isNullable, bool needType, bool writeWrappingElem) { if (ob == null) { if (isNullable) WriteNullTagLiteral(element, namesp); return; } if (writeWrappingElem) { WriteStartElement (element, namesp, ob); } if (needType) WriteXsiType("FaultBinding", "http://schemas.xmlsoap.org/wsdl/"); if (ob.Name != "") { WriteAttribute ("name", "", XmlConvert.EncodeNmToken(ob.Name)); } ServiceDescription.WriteExtensions (Writer, ob); if (ob.Documentation != "") { WriteElementString ("documentation", "http://schemas.xmlsoap.org/wsdl/", ob.Documentation); } if (writeWrappingElem) WriteEndElement (ob); } void WriteObject_InputBinding (System.Web.Services.Description.InputBinding ob, string element, string namesp, bool isNullable, bool needType, bool writeWrappingElem) { if (ob == null) { if (isNullable) WriteNullTagLiteral(element, namesp); return; } if (writeWrappingElem) { WriteStartElement (element, namesp, ob); } if (needType) WriteXsiType("InputBinding", "http://schemas.xmlsoap.org/wsdl/"); if (ob.Name != "") { WriteAttribute ("name", "", XmlConvert.EncodeNmToken(ob.Name)); } ServiceDescription.WriteExtensions (Writer, ob); if (ob.Documentation != "") { WriteElementString ("documentation", "http://schemas.xmlsoap.org/wsdl/", ob.Documentation); } if (writeWrappingElem) WriteEndElement (ob); } void WriteObject_OutputBinding (System.Web.Services.Description.OutputBinding ob, string element, string namesp, bool isNullable, bool needType, bool writeWrappingElem) { if (ob == null) { if (isNullable) WriteNullTagLiteral(element, namesp); return; } if (writeWrappingElem) { WriteStartElement (element, namesp, ob); } if (needType) WriteXsiType("OutputBinding", "http://schemas.xmlsoap.org/wsdl/"); if (ob.Name != "") { WriteAttribute ("name", "", XmlConvert.EncodeNmToken(ob.Name)); } ServiceDescription.WriteExtensions (Writer, ob); if (ob.Documentation != "") { WriteElementString ("documentation", "http://schemas.xmlsoap.org/wsdl/", ob.Documentation); } if (writeWrappingElem) WriteEndElement (ob); } protected override void InitCallbacks () { } } }
using UnityEngine; using System.Collections; using UnityEngine.SceneManagement; // version 1.4 namespace SpaceMarbles.V4 { public class Shooting :MonoBehaviour { // Transforms to manipulate objects. public Transform gun; // Gun. public Transform sphere; // Sphere. Transform clone; // Clone of sphere. public Transform targetSphere; // Target spheres. public Transform wallLeft; // Left wall of level. public Transform wallRight; // Right wall of level. public Transform wallTop; // Top wall of level. public Transform wallDown; // Down wall of level. public Transform capsule; // Shows mouse location. public Transform cameraMain; // Main camera. public Transform cameraWide; // Alternate camera. //public LineRenderer line; // . int frames = 0; // Count for each Update() frame ran. float movespeed; // Move speed of gun. Vector3 gunRotation; // Gun rotation towards mouse. int shotPowerStart = 10; // How much power the shot starts with. int shotPower = 10; // Force used to shoot Sphere. int shotPowerPlus = 1; // How fast shot power increaces. int shotPowerLimit = 100; // Max shot power. int spheres = 0; // Count for Sphere clones. int maxSpheres; // Max spheres that can be created. int targetSpheres = 0; // Count for target Spheres. float targetOrigin = 0; // Origin for target Sphere. #pragma warning disable CS0414 // Variable is assigned but its value is never used string hitChecker = "Nothing"; // Hit check for target Spheres. #pragma warning restore CS0414 // Variable is assigned but its value is never used int scrollLimit = 2; // Max scroll limit. int scrolled = 0; // Count for scroll. // Interface string GUIPower; // Displays shot power. string GUITime; // //Displays frames played so far. // Mouse Position Ray ray; RaycastHit hit; bool gameOver = false; Transform targetSphere2; Transform targetSphere3; float targetOrigin2; float targetOrigin3; void Start() { FindAllGameObjects(); maxSpheres = Menu.startSpheres; movespeed = Menu.startSpeed; if (GameObject.FindGameObjectsWithTag("Finish").Length > 0) targetSphere = GameObject.FindGameObjectsWithTag("Finish")[0].transform; if (GameObject.FindGameObjectsWithTag("Finish").Length > 1) targetSphere2 = GameObject.FindGameObjectsWithTag("Finish")[1].transform; if (GameObject.FindGameObjectsWithTag("Finish").Length > 2) targetSphere3 = GameObject.FindGameObjectsWithTag("Finish")[2].transform; } void FindAllGameObjects() { gun = GameObject.Find("Gun").transform; //sphere = GameObject.Find("Gun").transform; // Sphere. targetSphere = GameObject.Find("TargetSphere").transform; // Target spheres. wallLeft = GameObject.Find("WallLeft").transform; // Left wall of level. wallRight = GameObject.Find("WallRight").transform; // Right wall of level. wallTop = GameObject.Find("WallTop").transform; // Top wall of level. wallDown = GameObject.Find("WallDown").transform; // Down wall of level. capsule = GameObject.Find("Capsule").transform; // Shows mouse location. cameraMain = GameObject.Find("Main Camera").transform; // Main camera. cameraWide = GameObject.Find("CameraWide").transform; // Alternate camera. } // copied from the web float originalWidth = 400.0f; // define here the original resolution 640 float originalHeight = 400.0f; // you used to create the GUI contents 400 private Vector3 scale; // Graphical User Interface void OnGUI() { originalWidth = 300; originalHeight = 400; scale.x = Screen.width / originalWidth; // calculate hor scale scale.y = Screen.height / originalHeight; // calculate vert scale scale.z = 1; var svMat = GUI.matrix; // save current matrix // substitute matrix - only scale is altered from standard GUI.matrix = Matrix4x4.TRS(Vector3.zero, Quaternion.identity, scale); // draw your GUI controls here: //... //GUI.Label(new Rect(0,Screen.height-60,100,60), GUIPower); // Box displaying shot power at top left of screen. /* GUI.Box(new Rect(0,Screen.height-60,100,60), GUIPower); //Box displaying total frames and time at top right of screen. //GUI.Box(new Rect (Screen.width - 100,0,100,50), GUITime); // Restart button. if (GUI.Button (new Rect (100,Screen.height-50,100,50), "Restart (R)")) SceneManager.LoadScene(Application.loadedLevel); // Level selecters. if (GUI.Button (new Rect (210,Screen.height-50,80,25), "Level 1 (1)")) SceneManager.LoadScene(1); if (GUI.Button (new Rect (210,Screen.height-25,80,25), "Level 2 (2)")) SceneManager.LoadScene(2); if (GUI.Button (new Rect (290,Screen.height-50,80,25), "Level 3 (3)")) SceneManager.LoadScene(3); if (GUI.Button (new Rect (290,Screen.height-25,80,25), "Level 4 (4)")) SceneManager.LoadScene(4); // Quit button. if (GUI.Button (new Rect (380,Screen.height-50,100,50), "Menu(ESC)")) SceneManager.LoadScene(0); */ GUILayout.BeginArea(new Rect(0, 0, 100, 600)); GUILayout.BeginVertical(); GUILayout.Box(GUIPower); GUILayout.Box(Unlocks.coins + " Coins"); GUILayout.EndArea(); GUILayout.BeginArea(new Rect(0, 325, 90, 80)); // Quit button. if (GUILayout.Button("Menu")) SceneManager.LoadScene(0); GUILayout.BeginHorizontal(); if (GUILayout.Button("Zoom")) { cameraMain.GetComponent<Camera>().enabled = !cameraMain.GetComponent<Camera>().enabled; cameraWide.GetComponent<Camera>().enabled = !cameraWide.GetComponent<Camera>().enabled; } if (scrolled < scrollLimit) { // can move into button to keep zoom buttons visible if (GUILayout.Button("+")) { // Move camera forward. cameraMain.Translate(Vector3.forward * 5); scrolled++; } } if (scrolled > ~scrollLimit) { if (GUILayout.Button("-")) { cameraMain.Translate(Vector3.back * 5); scrolled--; } } GUILayout.EndHorizontal(); if (GUILayout.Button("Restart")) SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex); GUILayout.EndArea(); GUILayout.BeginArea(new Rect(100, 294, 190, 100)); GUILayout.Box("Levels"); // Level selecters. GUILayout.BeginHorizontal(); GUILayout.BeginVertical(); if (GUILayout.Button("Level 1")) SceneManager.LoadScene(1); if (Unlocks.level2Lock == false) if (GUILayout.Button("Level 2")) SceneManager.LoadScene(2); if (Unlocks.level3Lock == false) if (GUILayout.Button("Level 3")) SceneManager.LoadScene(3); GUILayout.EndVertical(); GUILayout.BeginVertical(); if (Unlocks.level4Lock == false) if (GUILayout.Button("Level 4")) SceneManager.LoadScene(4); if (Unlocks.level5Lock == false) if (GUILayout.Button("Level 5")) SceneManager.LoadScene(5); if (Unlocks.level6Lock == false) if (GUILayout.Button("Level 6")) SceneManager.LoadScene(6); GUILayout.EndVertical(); GUILayout.BeginVertical(); if (Unlocks.level7Lock == false) if (GUILayout.Button("Level 7")) SceneManager.LoadScene(7); if (Unlocks.level8Lock == false) if (GUILayout.Button("Level 8")) SceneManager.LoadScene(8); if (GUILayout.Button("Unlock -20")) { if (Unlocks.coins >= 20) { if (Unlocks.nextUnlock == 8) if (Unlocks.level8Lock == true) { Unlocks.coins -= 20; Unlocks.level8Lock = false; } if (Unlocks.nextUnlock == 7) if (Unlocks.level7Lock == true) { Unlocks.coins -= 20; Unlocks.level7Lock = false; Unlocks.nextUnlock = 8; } if (Unlocks.nextUnlock == 6) if (Unlocks.level6Lock == true) { Unlocks.coins -= 20; Unlocks.level6Lock = false; Unlocks.nextUnlock = 7; } GUILayout.EndHorizontal(); if (Unlocks.nextUnlock == 5) if (Unlocks.level5Lock == true) { Unlocks.coins -= 20; Unlocks.level5Lock = false; Unlocks.nextUnlock = 6; } if (Unlocks.nextUnlock == 4) if (Unlocks.level4Lock == true) { Unlocks.coins -= 20; Unlocks.level4Lock = false; Unlocks.nextUnlock = 5; } if (Unlocks.nextUnlock == 3) if (Unlocks.level3Lock == true) { Unlocks.coins -= 20; Unlocks.level3Lock = false; Unlocks.nextUnlock = 4; } if (Unlocks.nextUnlock == 2) if (Unlocks.level2Lock == true) { Unlocks.coins -= 20; Unlocks.level2Lock = false; Unlocks.nextUnlock = 3; } } } GUILayout.EndVertical(); GUILayout.EndVertical(); GUILayout.EndArea(); // Game over. GUILayout.BeginArea(new Rect(90, 100, 150, 150)); if (gameOver == true) { // Level progression if (Unlocks.level2Lock == true) if (SceneManager.GetActiveScene().buildIndex == 1) { Unlocks.level2Lock = false; Unlocks.coins += 2; Unlocks.nextUnlock = 3; } if (Unlocks.level3Lock == true) if (SceneManager.GetActiveScene().buildIndex == 2) { Unlocks.level3Lock = false; Unlocks.coins += 5; Unlocks.nextUnlock = 4; } if (Unlocks.level4Lock == true) if (SceneManager.GetActiveScene().buildIndex == 3) { Unlocks.level4Lock = false; Unlocks.coins += 10; Unlocks.nextUnlock = 5; } if (Unlocks.level5Lock == true) if (SceneManager.GetActiveScene().buildIndex == 4) { Unlocks.level5Lock = false; Unlocks.coins += 20; Unlocks.nextUnlock = 6; } if (Unlocks.level6Lock == true) if (SceneManager.GetActiveScene().buildIndex == 5) { Unlocks.level6Lock = false; Unlocks.coins += 35; Unlocks.nextUnlock = 7; } if (Unlocks.level7Lock == true) if (SceneManager.GetActiveScene().buildIndex == 6) { Unlocks.level7Lock = false; Unlocks.coins += 50; Unlocks.nextUnlock = 8; } if (Unlocks.level8Lock == true) if (SceneManager.GetActiveScene().buildIndex == 7) { Unlocks.level8Lock = false; Unlocks.coins += 70; } GUILayout.Box("Congratulations!" + "\n" + "You completed level " + SceneManager.GetActiveScene().buildIndex + "!"); if (SceneManager.GetActiveScene().buildIndex < 8) { if (GUILayout.Button("Next Level") || Input.GetKeyDown(KeyCode.Space)) SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex + 1); } else { GUILayout.Box("Game finished!" + "\n" + "Thank you for playing!" + "\n" + "Go back to main menu?"); if (GUILayout.Button("Back to main menu.") || Input.GetKeyDown(KeyCode.Space)) SceneManager.LoadScene(0); } //gameOver = false; } GUILayout.EndArea(); // restore matrix before returning GUI.matrix = svMat; // restore matrix } void Update() { //Debug.DrawLine(transform.position, hit.point); //line.SetPosition(0, transform.position); //line.SetPosition(1, hit.point); if (PlayerPrefs.GetFloat("coins") != Unlocks.coins) { PlayerPrefs.SetFloat("coins", Unlocks.coins); } PlayerPrefs.Save(); // Set ray to mouse position. if (cameraMain.GetComponent<Camera>().enabled == true) { ray = cameraMain.GetComponent<Camera>().ScreenPointToRay(Input.mousePosition); } else { ray = cameraWide.GetComponent<Camera>().ScreenPointToRay(Input.mousePosition); } // Controls // W, A, S, D to move Gun left, right, up, down. // Left click to shoot, right click to switch camera. // 1, 2, 3, 4 for each level. // R to restart current level. // Escape to go back to main menu. // Menu if (Input.GetKeyDown(KeyCode.Escape)) { SceneManager.LoadScene(0); } // Movement for gun. // Press W to go up. if (Input.GetKey("w")) GetComponent<Rigidbody>().MovePosition(new Vector3(GetComponent<Rigidbody>().position.x , GetComponent<Rigidbody>().position.y + movespeed / 5 , GetComponent<Rigidbody>().position.z)); // Press A to go Left. if (Input.GetKey("a")) GetComponent<Rigidbody>().MovePosition(new Vector3(GetComponent<Rigidbody>().position.x - movespeed / 5 , GetComponent<Rigidbody>().position.y , GetComponent<Rigidbody>().position.z)); // Press S to go Down. if (Input.GetKey("s")) GetComponent<Rigidbody>().MovePosition(new Vector3(GetComponent<Rigidbody>().position.x , GetComponent<Rigidbody>().position.y - movespeed / 5 , GetComponent<Rigidbody>().position.z)); // Press D to go Right. if (Input.GetKey("d")) GetComponent<Rigidbody>().MovePosition(new Vector3(GetComponent<Rigidbody>().position.x + movespeed / 5 , GetComponent<Rigidbody>().position.y , GetComponent<Rigidbody>().position.z)); // Limit Spheres created. if (spheres < maxSpheres) { // Increase shot power. // Check if left mouse button if pressed. if (Input.GetKey(KeyCode.Mouse0)) { // Check if shot power is under limit. if (shotPower < shotPowerLimit) // Increase shot power. shotPower += shotPowerPlus; // Display shot power GUIPower = "Power: " + shotPower; } // Launch Sphere clone. // Check if left mouse button is released. if (Input.GetKeyUp(KeyCode.Mouse0)) { // Set Clone instance of a Sphere and position at gun. clone = Instantiate(sphere , transform.position , transform.rotation) as Transform; // Push clone by shot power towards mouse location. clone.GetComponent<Rigidbody>().AddRelativeForce(0 , 0 , shotPower * 20); // Reset shot power. shotPower = shotPowerStart; } } // Change cameras // Right click to invert to other camera. if (Input.GetKeyDown(KeyCode.Mouse1)) { cameraMain.GetComponent<Camera>().enabled = !cameraMain.GetComponent<Camera>().enabled; cameraWide.GetComponent<Camera>().enabled = !cameraWide.GetComponent<Camera>().enabled; } float scrollWheel = Input.GetAxis("Mouse ScrollWheel"); if (scrolled < scrollLimit) { // Mouse scroll forwards. if (scrollWheel > 0) { // Move camera forward. cameraMain.Translate(Vector3.forward * 5); scrolled++; } } if (scrolled > ~scrollLimit) { // ~ means reverse. // Mouse scroll backwards. if (scrollWheel < 0) { // Move camera back. cameraMain.Translate(Vector3.back * 5); scrolled--; } } // 1, 2, 3, 4 for each level. if (Input.GetKeyDown(KeyCode.Alpha1)) { SceneManager.LoadScene(1); } if (Input.GetKeyDown(KeyCode.Alpha2)) { SceneManager.LoadScene(2); } if (Input.GetKeyDown(KeyCode.Alpha3)) { SceneManager.LoadScene(3); } if (Input.GetKeyDown(KeyCode.Alpha4)) { SceneManager.LoadScene(4); } if (Input.GetKeyDown(KeyCode.Alpha5)) { SceneManager.LoadScene(5); } if (Input.GetKeyDown(KeyCode.Alpha6)) { SceneManager.LoadScene(6); } if (Input.GetKeyDown(KeyCode.Alpha7)) { SceneManager.LoadScene(7); } if (Input.GetKeyDown(KeyCode.Alpha8)) { SceneManager.LoadScene(8); } // R to restart current level. if (Input.GetKeyDown(KeyCode.R)) { SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex); } // Change timescale of game. // Press Q to increase timescale. /* if(Input.GetKeyDown(KeyCode.Q)) Time.timeScale++; // Press E to decrease timescale. if(Input.GetKeyDown(KeyCode.E)) Time.timeScale--; // Press R to reset timescale. if(Input.GetKeyDown(KeyCode.R)) Time.timeScale = 1; */ // Restricting movement. // Restrict movement of gun. if (gun && gun.position.x > wallRight.position.x) { gun.GetComponent<Rigidbody>().MovePosition(new Vector3(wallLeft.position.x , gun.position.y , gun.position.z)); } if (gun && gun.position.x < wallLeft.position.x) { gun.GetComponent<Rigidbody>().MovePosition(new Vector3(wallRight.position.x , gun.position.y , gun.position.z)); } if (gun && gun.position.y < wallDown.position.y) { gun.GetComponent<Rigidbody>().MovePosition(new Vector3(gun.GetComponent<Rigidbody>().position.x , wallTop.position.y , gun.position.z)); } if (gun && gun.position.y > wallTop.position.y) { gun.GetComponent<Rigidbody>().MovePosition(new Vector3(gun.GetComponent<Rigidbody>().position.x , wallDown.position.y , gun.position.z)); } string clonePosition = ""; // Restricting clone of Sphere movement. if (clone) { if (clone.position.x > wallRight.position.x || clone.position.x < wallLeft.position.x || clone.position.y < wallDown.position.y || clone.position.y > wallTop.position.y) { clonePosition = "Outside"; } else if (clone.position.x < wallRight.position.x || clone.position.x > wallLeft.position.x || clone.position.y > wallDown.position.y || clone.position.y < wallTop.position.y) { clonePosition = "Inside"; } } if (clonePosition == "Outside") { // When clone is created and is outside the walls, destroy clone. Destroy(clone.gameObject); } if (clonePosition == "Inside") { // When clone is created and inside the walls, destroy clone in 10 seconds. Destroy(clone.gameObject, 5f); } /* // While a target sphere exists if(GameObject.FindGameObjectsWithTag ("Finish").Length > 0){ targetSphere = GameObject.FindGameObjectsWithTag ("Finish")[GameObject.FindGameObjectsWithTag ("Finish").Length-1].transform; Vector3 tmp = targetSphere.transform.position; tmp.x = targetOrigin; targetSphere.transform.position = tmp; //targetSphere.transform.position.x = targetOrigin; } */ // Hitting target. if (targetOrigin != 0 && targetSphere) { //print ("target exists"); // if(hitChecker == "Nothing") // if(targetSphere.transform.position.x == targetOrigin) { // hitChecker = "Not Hit"; // print ("target has position"); // } // if(hitChecker == "Nothing" || hitChecker == "Not Hit") if (targetSphere.transform.position.x != targetOrigin) { Destroy(targetSphere.gameObject, 2f); hitChecker = "Hit"; // print ("target moved"); } } // check hit for target 2 if (targetOrigin2 != 0 && targetSphere2) if (targetSphere2.transform.position.x != targetOrigin2) Destroy(targetSphere2.gameObject, 2f); // check hit for target 3 if (targetOrigin3 != 0 && targetSphere3) if (targetSphere3.transform.position.x != targetOrigin3) Destroy(targetSphere3.gameObject, 2f); // Every frame maintinance. // Check if raycast has been set, then draw line on Scene Screen. if (Physics.Raycast(ray, out hit, 1000)) Debug.DrawLine(transform.position, hit.point); // Draw line from gun to mouse location. capsule.GetComponent<Rigidbody>().MovePosition(hit.point); // Set casule at mouse position. if (cameraMain) { Vector3 cameraPosition = new Vector3(transform.position.x-cameraMain.transform.position.x ,transform.position.y-cameraMain.transform.position.y ,0); cameraMain.Translate(cameraPosition); // Position camera above Gun. } // Rotation of gun towards mouse position. gunRotation = new Vector3(hit.point.x, hit.point.y, 0); transform.LookAt(gunRotation); // Setting target sphere origin if (targetSphere) targetOrigin = targetSphere.transform.position.x; if (targetSphere2) targetOrigin2 = targetSphere2.transform.position.x; if (targetSphere3) targetOrigin3 = targetSphere3.transform.position.x; capsule.Rotate(new Vector3(0, 0, 10)); // Rotate capsule. spheres = GameObject.FindGameObjectsWithTag("Respawn").Length; // Number of spheres in game. targetSpheres = GameObject.FindGameObjectsWithTag("Finish").Length; // Number of target spheres in game. GUIPower = "Power: " + shotPower + "\n Spheres: " + spheres + "\n Targets: " + targetSpheres; // Display shot power, spheres and target spheres. GUITime = "Time: " + (int)Time.time + "\n TimeScale: " + Time.timeScale + "\n Frames: " + frames; // //Display frames run. frames++; // Add to frames run. // Game Over. if (GameObject.FindGameObjectsWithTag("Finish").Length == 0) { gameOver = true; } } } }
//------------------------------------------------------------------------------ // <copyright file="WinFormsSecurity.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ /* */ namespace System.Windows.Forms { using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System; using System.IO; using System.Security.Permissions; using System.Security; using System.Drawing.Printing; using System.Runtime.Versioning; internal static class IntSecurity { public static readonly TraceSwitch SecurityDemand = new TraceSwitch("SecurityDemand", "Trace when security demands occur."); #if DEBUG public static readonly BooleanSwitch MapSafeTopLevelToSafeSub = new BooleanSwitch("MapSafeTopLevelToSafeSub", "Maps the SafeTopLevelWindow UI permission to SafeSubWindow permission. Must restart to take effect."); #endif private static CodeAccessPermission adjustCursorClip; private static CodeAccessPermission affectMachineState; private static CodeAccessPermission affectThreadBehavior; private static CodeAccessPermission allPrinting; private static PermissionSet allPrintingAndUnmanagedCode; // Can't assert twice in the same method private static CodeAccessPermission allWindows; private static CodeAccessPermission clipboardRead; private static CodeAccessPermission clipboardOwn; private static PermissionSet clipboardWrite; // Can't assert twice in the same method private static CodeAccessPermission changeWindowRegionForTopLevel; private static CodeAccessPermission controlFromHandleOrLocation; private static CodeAccessPermission createAnyWindow; private static CodeAccessPermission createGraphicsForControl; private static CodeAccessPermission defaultPrinting; private static CodeAccessPermission fileDialogCustomization; private static CodeAccessPermission fileDialogOpenFile; private static CodeAccessPermission fileDialogSaveFile; private static CodeAccessPermission getCapture; private static CodeAccessPermission getParent; private static CodeAccessPermission manipulateWndProcAndHandles; private static CodeAccessPermission modifyCursor; private static CodeAccessPermission modifyFocus; private static CodeAccessPermission objectFromWin32Handle; private static CodeAccessPermission safePrinting; private static CodeAccessPermission safeSubWindows; private static CodeAccessPermission safeTopLevelWindows; private static CodeAccessPermission sendMessages; private static CodeAccessPermission sensitiveSystemInformation; private static CodeAccessPermission transparentWindows; private static CodeAccessPermission topLevelWindow; private static CodeAccessPermission unmanagedCode; private static CodeAccessPermission unrestrictedWindows; private static CodeAccessPermission windowAdornmentModification; /* Unused permissions private static CodeAccessPermission win32HandleManipulation; private static CodeAccessPermission minimizeWindowProgrammatically; private static CodeAccessPermission restrictedWebBrowserPermission; private static CodeAccessPermission noPrinting; private static CodeAccessPermission topMostWindow; private static CodeAccessPermission unrestrictedEnvironment; private static CodeAccessPermission autoComplete; private static CodeAccessPermission defaultWebBrowserPermission; private static CodeAccessPermission screenDC; */ // // Property accessors for permissions. Don't allocate permissions up front -- always // demand create them. A great many codepaths never need all these permissions so it is wasteful to // create them. // public static CodeAccessPermission AdjustCursorClip { get { if (adjustCursorClip == null) { adjustCursorClip = AllWindows; } return adjustCursorClip; } } public static CodeAccessPermission AdjustCursorPosition { get { return AllWindows; } } public static CodeAccessPermission AffectMachineState { get { if (affectMachineState == null) { affectMachineState = UnmanagedCode; } return affectMachineState; } } public static CodeAccessPermission AffectThreadBehavior { get { if (affectThreadBehavior == null) { affectThreadBehavior = UnmanagedCode; } return affectThreadBehavior; } } public static CodeAccessPermission AllPrinting { get { if (allPrinting == null) { allPrinting = new PrintingPermission(PrintingPermissionLevel.AllPrinting); } return allPrinting; } } public static PermissionSet AllPrintingAndUnmanagedCode { // Can't assert twice in the same method. See ASURT 52788. get { if (allPrintingAndUnmanagedCode == null) { PermissionSet temp = new PermissionSet(PermissionState.None); temp.SetPermission(IntSecurity.UnmanagedCode); temp.SetPermission(IntSecurity.AllPrinting); allPrintingAndUnmanagedCode = temp; } return allPrintingAndUnmanagedCode; } } public static CodeAccessPermission AllWindows { get { if (allWindows == null) { allWindows = new UIPermission(UIPermissionWindow.AllWindows); } return allWindows; } } public static CodeAccessPermission ClipboardRead { get { if (clipboardRead == null) { clipboardRead = new UIPermission(UIPermissionClipboard.AllClipboard); } return clipboardRead; } } public static CodeAccessPermission ClipboardOwn { get { if (clipboardOwn == null) { clipboardOwn = new UIPermission(UIPermissionClipboard.OwnClipboard); } return clipboardOwn; } } public static PermissionSet ClipboardWrite { // Can't assert OwnClipboard & UnmanagedCode in the same context, need permission set. get { if (clipboardWrite == null) { clipboardWrite = new PermissionSet(PermissionState.None); clipboardWrite.SetPermission(IntSecurity.UnmanagedCode); clipboardWrite.SetPermission(IntSecurity.ClipboardOwn); } return clipboardWrite; } } public static CodeAccessPermission ChangeWindowRegionForTopLevel { get { if (changeWindowRegionForTopLevel == null) { changeWindowRegionForTopLevel = AllWindows; } return changeWindowRegionForTopLevel; } } public static CodeAccessPermission ControlFromHandleOrLocation { get { if (controlFromHandleOrLocation == null) { controlFromHandleOrLocation = AllWindows; } return controlFromHandleOrLocation; } } public static CodeAccessPermission CreateAnyWindow { get { if (createAnyWindow == null) { createAnyWindow = SafeSubWindows; } return createAnyWindow; } } public static CodeAccessPermission CreateGraphicsForControl { get { if (createGraphicsForControl == null) { createGraphicsForControl = SafeSubWindows; } return createGraphicsForControl; } } public static CodeAccessPermission DefaultPrinting { get { if (defaultPrinting == null) { defaultPrinting = new PrintingPermission(PrintingPermissionLevel.DefaultPrinting); } return defaultPrinting; } } public static CodeAccessPermission FileDialogCustomization { get { if (fileDialogCustomization == null) { fileDialogCustomization = new FileIOPermission(PermissionState.Unrestricted); } return fileDialogCustomization; } } public static CodeAccessPermission FileDialogOpenFile { get { if (fileDialogOpenFile == null) { fileDialogOpenFile = new FileDialogPermission(FileDialogPermissionAccess.Open); } return fileDialogOpenFile; } } public static CodeAccessPermission FileDialogSaveFile { get { if (fileDialogSaveFile == null) { fileDialogSaveFile = new FileDialogPermission(FileDialogPermissionAccess.Save); } return fileDialogSaveFile; } } /* Unused public static CodeAccessPermission RestrictedWebBrowserPermission { get { if (restrictedWebBrowserPermission == null) { restrictedWebBrowserPermission = new WebBrowserPermission(WebBrowserPermissionLevel.Restricted); } return restrictedWebBrowserPermission; } } public static CodeAccessPermission DefaultWebBrowserPermission { get { if (defaultWebBrowserPermission == null) { defaultWebBrowserPermission = new WebBrowserPermission(WebBrowserPermissionLevel.Default); } return defaultWebBrowserPermission; } } */ public static CodeAccessPermission GetCapture { get { if (getCapture == null) { getCapture = AllWindows; } return getCapture; } } public static CodeAccessPermission GetParent { get { if (getParent == null) { getParent = AllWindows; } return getParent; } } public static CodeAccessPermission ManipulateWndProcAndHandles { get { if (manipulateWndProcAndHandles == null) { manipulateWndProcAndHandles = AllWindows; } return manipulateWndProcAndHandles; } } /* Unused public static CodeAccessPermission MinimizeWindowProgrammatically { get { if (minimizeWindowProgrammatically == null) { minimizeWindowProgrammatically = AllWindows; } return minimizeWindowProgrammatically; } } */ public static CodeAccessPermission ModifyCursor { get { if (modifyCursor == null) { modifyCursor = SafeSubWindows; } return modifyCursor; } } public static CodeAccessPermission ModifyFocus { get { if (modifyFocus == null) { modifyFocus = AllWindows; } return modifyFocus; } } /* Unused public static CodeAccessPermission NoPrinting { get { if (noPrinting == null) { noPrinting = new PrintingPermission(PrintingPermissionLevel.NoPrinting); } return noPrinting; } } */ public static CodeAccessPermission ObjectFromWin32Handle { get { if (objectFromWin32Handle == null) { objectFromWin32Handle = UnmanagedCode; } return objectFromWin32Handle; } } public static CodeAccessPermission SafePrinting { get { if (safePrinting == null) { safePrinting = new PrintingPermission(PrintingPermissionLevel.SafePrinting); } return safePrinting; } } public static CodeAccessPermission SafeSubWindows { get { if (safeSubWindows == null) { safeSubWindows = new UIPermission(UIPermissionWindow.SafeSubWindows); } return safeSubWindows; } } public static CodeAccessPermission SafeTopLevelWindows { get { if (safeTopLevelWindows == null) { safeTopLevelWindows = new UIPermission(UIPermissionWindow.SafeTopLevelWindows); } return safeTopLevelWindows; } } public static CodeAccessPermission SendMessages { get { if (sendMessages == null) { sendMessages = UnmanagedCode; } return sendMessages; } } public static CodeAccessPermission SensitiveSystemInformation { get { if (sensitiveSystemInformation == null) { sensitiveSystemInformation = new EnvironmentPermission(PermissionState.Unrestricted); } return sensitiveSystemInformation; } } /* Unused public static CodeAccessPermission ScreenDC { get { if (screenDC == null) { screenDC = AllWindows; } return screenDC; } } */ public static CodeAccessPermission TransparentWindows { get { if (transparentWindows == null) { transparentWindows = AllWindows; } return transparentWindows; } } public static CodeAccessPermission TopLevelWindow { get { if (topLevelWindow == null) { topLevelWindow = SafeTopLevelWindows; } return topLevelWindow; } } /* Unused public static CodeAccessPermission TopMostWindow { get { if (topMostWindow == null) { topMostWindow = AllWindows; } return topMostWindow; } } */ public static CodeAccessPermission UnmanagedCode { get { if (unmanagedCode == null) { unmanagedCode = new SecurityPermission(SecurityPermissionFlag.UnmanagedCode); } return unmanagedCode; } } /* public static CodeAccessPermission UnrestrictedEnvironment { get { if (unrestrictedEnvironment == null) { unrestrictedEnvironment = new EnvironmentPermission(PermissionState.Unrestricted); } return unrestrictedEnvironment; } } */ public static CodeAccessPermission UnrestrictedWindows { get { if (unrestrictedWindows == null) { unrestrictedWindows = AllWindows; } return unrestrictedWindows; } } /* FXCop avoid unused code public static CodeAccessPermission Win32HandleManipulation { get { if (win32HandleManipulation == null) { win32HandleManipulation = UnmanagedCode; } return win32HandleManipulation; } } */ public static CodeAccessPermission WindowAdornmentModification { get { if (windowAdornmentModification == null) { windowAdornmentModification = AllWindows; } return windowAdornmentModification; } } /* unused public static CodeAccessPermission AutoComplete { get { if (autoComplete == null) { autoComplete = UnmanagedCode; } return autoComplete; } } */ [ResourceExposure(ResourceScope.Machine)] [ResourceConsumption(ResourceScope.Machine)] internal static string UnsafeGetFullPath(string fileName) { string full = fileName; FileIOPermission fiop = new FileIOPermission( PermissionState.None ); fiop.AllFiles = FileIOPermissionAccess.PathDiscovery; fiop.Assert(); try { full = Path.GetFullPath(fileName); } finally { CodeAccessPermission.RevertAssert(); } return full; } /// SECREVIEW: ReviewImperativeSecurity /// vulnerability to watch out for: A method uses imperative security and might be constructing the permission using state information or return values that can change while the demand is active. /// reason for exclude: fileName is a local variable and not subject to race conditions. [SuppressMessage("Microsoft.Security", "CA2103:ReviewImperativeSecurity")] internal static void DemandFileIO(FileIOPermissionAccess access, string fileName) { new FileIOPermission(access, UnsafeGetFullPath(fileName)).Demand(); } } }
// -------------------------------------------------------------------------------------------- // <copyright from='2011' to='2011' company='SIL International'> // Copyright (c) 2011, SIL International. All Rights Reserved. // // Distributable under the terms of either the Common Public License or the // GNU Lesser General Public License, as specified in the LICENSING.txt file. // </copyright> // -------------------------------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Runtime.InteropServices; using NUnit.Framework; using SIL.Windows.Forms.Keyboarding.Linux; using SIL.Keyboarding; using X11.XKlavier; namespace SIL.Windows.Forms.Keyboarding.Tests { [TestFixture] [Platform(Include="Linux", Reason="Linux specific tests")] [SetUICulture("en-US")] public class XkbKeyboardAdapterTests { /// <summary> /// Fakes the installed keyboards /// </summary> private class XklEngineResponder: XklEngine { public static string[] SetGroupNames { set; private get; } public override string[] GroupNames => SetGroupNames; } #region Helper class/method to set the LANGUAGE environment variable /// <summary>Helper class/method to set the LANGUAGE environment variable. This is /// necessary to get localized texts</summary> /// <remarks>A different, probably cleaner approach, would be to derive a class from /// NUnit's ActionAttribute. However, this currently doesn't work when running the tests /// in MonoDevelop (at least up to version 4.3).</remarks> class LanguageHelper : IDisposable { private string OldLanguage { get; set; } public LanguageHelper(string language) { // To get XklConfigRegistry to return values in the expected language we have to // set the LANGUAGE environment variable. OldLanguage = Environment.GetEnvironmentVariable("LANGUAGE"); Environment.SetEnvironmentVariable("LANGUAGE", $"{language.Replace('-', '_')}:{OldLanguage}"); } #region Disposable stuff #if DEBUG /// <summary/> ~LanguageHelper() { Dispose(false); } #endif /// <summary/> public bool IsDisposed { get; private set; } /// <summary/> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } /// <summary/> protected virtual void Dispose(bool fDisposing) { Debug.WriteLineIf(!fDisposing, "****** Missing Dispose() call for " + GetType() + ". *******"); if (fDisposing && !IsDisposed) { // dispose managed and unmanaged objects Environment.SetEnvironmentVariable("LANGUAGE", OldLanguage); } IsDisposed = true; } #endregion /// <summary> /// Checks the list of installed languages and ignores the test if the desired language /// is not installed. /// </summary> /// <param name="desiredLanguage">Desired language.</param> public static void CheckInstalledLanguages(string desiredLanguage) { var language = desiredLanguage.Replace('-', '_'); // Some systems (notably Mint 17/Cinnamon aka Wasta-14) don't have a LANGUAGE environment // variable, so we need to check for a null value. var langFromEnv = Environment.GetEnvironmentVariable ("LANGUAGE"); if (langFromEnv != null && langFromEnv.Contains(language)) return; using (var process = new Process()) { process.StartInfo.FileName = "locale"; process.StartInfo.Arguments = "-a"; process.StartInfo.UseShellExecute = false; process.StartInfo.CreateNoWindow = true; process.StartInfo.RedirectStandardOutput = true; process.Start(); process.WaitForExit(); for (var line = process.StandardOutput.ReadLine(); line != null; line = process.StandardOutput.ReadLine()) { if (line.StartsWith(language, StringComparison.InvariantCultureIgnoreCase)) return; } Assert.Ignore("Can't run test because language pack for {0} is not installed.", desiredLanguage); } } } private static LanguageHelper SetLanguage(string language) { LanguageHelper.CheckInstalledLanguages(language); return new LanguageHelper(language); } #endregion [DllImportAttribute("libgtk-x11-2.0")] [return: MarshalAs(UnmanagedType.I4)] private static extern bool gtk_init_check(ref int argc, ref IntPtr argv) ; private string KeyboardUSA => KeyboardNames[0]; private string KeyboardGermany => KeyboardNames[1]; private string KeyboardFranceEliminateDeadKeys => KeyboardNames[2]; private string KeyboardUK => KeyboardNames[3]; private string KeyboardBelgium => KeyboardNames[4]; private string KeyboardFinlandNorthernSaami => KeyboardNames[5]; private string[] KeyboardNames; private static readonly string[] KeyboardNamesOfUbuntu1404 = { "USA", "Germany", "France - Eliminate dead keys", "United Kingdom", "Belgium", "Finland - Northern Saami" }; private static readonly string[] KeyboardNamesOfUbuntu1604 = { "English (US)", "German", "French (eliminate dead keys)", "English (UK)", "Belgian", "Northern Saami (Finland)" }; private static readonly string[] KeyboardNamesOfUbuntu1804 = { "English (US)", "German", "French (no dead keys)", "English (UK)", "Belgian", "Northern Saami (Finland)" }; private static readonly string[][] AllKeyboardNames = { KeyboardNamesOfUbuntu1404, KeyboardNamesOfUbuntu1604, KeyboardNamesOfUbuntu1804 }; private string ExpectedKeyboardUSA => ExpectedKeyboardNames[0]; private string ExpectedKeyboardGermany => ExpectedKeyboardNames[1]; private string ExpectedKeyboardFranceEliminateDeadKeys => ExpectedKeyboardNames[2]; private string ExpectedKeyboardUK => ExpectedKeyboardNames[3]; //private string ExpectedKeyboardBelgium => ExpectedKeyboardNames[4]; private string ExpectedKeyboardFinlandNorthernSaami => ExpectedKeyboardNames[5]; private string[] ExpectedKeyboardNames; private static readonly string[] ExpectedKeyboardNamesOfUbuntu1404 = { "English (US) - English (United States)", "German - German (Germany)", "Eliminate dead keys - French (France)", "English (UK) - English (United Kingdom)", "", "Northern Saami - Northern Sami (Finland)" }; private static readonly string[] ExpectedKeyboardNamesOfUbuntu1604 = { "English (US) - English (United States)", "German - German (Germany)", "French (eliminate dead keys) - French (France)", "English (UK) - English (United Kingdom)", "", "Northern Saami (Finland) - Northern Sami (Finland)" }; private static readonly string[] ExpectedKeyboardNamesOfUbuntu1804 = { "English (US) - English (United States)", "German - German (Germany)", "French (no dead keys) - French (France)", "English (UK) - English (United Kingdom)", "", "Northern Saami (Finland) - Northern Sami (Finland)" }; private static readonly string[][] AllExpectedKeyboardNames = { ExpectedKeyboardNamesOfUbuntu1404, ExpectedKeyboardNamesOfUbuntu1604, ExpectedKeyboardNamesOfUbuntu1804 }; private static int KeyboardNamesIndex { get { // Debian/Ubuntu version 2.2.1 of xkeyboard-config changed the way keyboard names // are stored in evdev.xml: previously the country name was used ("Belgium"), now // they use the adjective ("Belgian"). We detect this by greping evdev.xml and then // use the appropriate names using (var process = new Process()) { process.StartInfo.FileName = "/bin/grep"; process.StartInfo.Arguments = "-q Belgian /usr/share/X11/xkb/rules/evdev.xml"; process.Start(); process.WaitForExit(); if (process.ExitCode != 0) return 0; // Ubuntu <= 14.04 } // Ubuntu 18.04 changed the naming for layouts without dead keys: "no dead keys" // instead of "eliminate dead keys" using (var process = new Process()) { process.StartInfo.FileName = "/bin/grep"; process.StartInfo.Arguments = "-q 'French (no dead keys)' /usr/share/X11/xkb/rules/evdev.xml"; process.Start(); process.WaitForExit(); if (process.ExitCode != 0) return 1; // Ubuntu 16.04 } return 2; // Ubuntu >= 18.04 } } [TestFixtureSetUp] public void FixtureSetup() { // We're using GTK functions, so we need to initialize when we run in // nunit-console. I'm doing it through p/invoke rather than gtk-sharp (Application.Init()) // so that we don't need to reference gtk-sharp (which might cause // problems on Windows) var argc = 0; var argv = IntPtr.Zero; Assert.IsTrue(gtk_init_check(ref argc, ref argv)); var index = KeyboardNamesIndex; KeyboardNames = AllKeyboardNames[index]; ExpectedKeyboardNames = AllExpectedKeyboardNames[index]; } [TearDown] public void TearDown() { KeyboardController.Shutdown(); } /// <summary> /// Tests converting the keyboard layouts that XKB reports to LCIDs with the help of ICU /// and list of available layouts. /// </summary> [Test] public void InstalledKeyboards_USA() { XklEngineResponder.SetGroupNames = new[] { KeyboardUSA }; KeyboardController.Initialize(new XkbKeyboardRetrievingAdaptor(new XklEngineResponder())); IKeyboardDefinition[] keyboards = Keyboard.Controller.AvailableKeyboards.ToArray(); Assert.AreEqual(1, keyboards.Length); Assert.AreEqual("en-US_us", keyboards[0].Id); Assert.AreEqual(ExpectedKeyboardUSA, keyboards[0].Name); } [Test] public void InstalledKeyboards_Germany() { XklEngineResponder.SetGroupNames = new[] { KeyboardGermany }; KeyboardController.Initialize(new XkbKeyboardRetrievingAdaptor(new XklEngineResponder())); IKeyboardDefinition[] keyboards = Keyboard.Controller.AvailableKeyboards.ToArray(); Assert.AreEqual(1, keyboards.Length); Assert.AreEqual("de-DE_de", keyboards[0].Id); Assert.AreEqual(ExpectedKeyboardGermany, keyboards[0].Name); } [Test] public void InstalledKeyboards_FrenchWithVariant() { XklEngineResponder.SetGroupNames = new[] { KeyboardFranceEliminateDeadKeys }; KeyboardController.Initialize(new XkbKeyboardRetrievingAdaptor(new XklEngineResponder())); var keyboards = Keyboard.Controller.AvailableKeyboards; Assert.AreEqual(1, keyboards.Count()); Assert.AreEqual(ExpectedKeyboardFranceEliminateDeadKeys, keyboards.First().Name); } [Test] public void InstalledKeyboards_GB() { XklEngineResponder.SetGroupNames = new[] { KeyboardUK }; KeyboardController.Initialize(new XkbKeyboardRetrievingAdaptor(new XklEngineResponder())); IKeyboardDefinition[] keyboards = Keyboard.Controller.AvailableKeyboards.ToArray(); Assert.AreEqual(1, keyboards.Length); Assert.AreEqual("en-GB_gb", keyboards[0].Id); Assert.AreEqual(ExpectedKeyboardUK, keyboards[0].Name); } private IKeyboardDefinition CreateKeyboard(string layoutName, string layout, string locale) { return new KeyboardDescription(string.Format("{0}_{1}", layout, locale), layoutName, layout, locale, true, null); } [Test] public void InstalledKeyboards_Belgium() { XklEngineResponder.SetGroupNames = new[] { KeyboardBelgium }; KeyboardController.Initialize(new XkbKeyboardRetrievingAdaptor(new XklEngineResponder())); var keyboards = Keyboard.Controller.AvailableKeyboards.OrderBy(kbd => kbd.Id).ToArray(); // It seems that Dutch (Belgium) got added recently, so some machines are missing // this. Assert.That(keyboards.Length, Is.EqualTo(3).Or.EqualTo(2)); var expectedKeyboardIds = new List<string>() { "de-BE_be", "fr-BE_be" }; if (keyboards.Length > 2) expectedKeyboardIds.Add("nl-BE_be"); Assert.That(keyboards.Select(kbd => kbd.Id), Is.EquivalentTo(expectedKeyboardIds)); } [Test] public void InstalledKeyboards_Multiple() { XklEngineResponder.SetGroupNames = new[] { KeyboardUSA, KeyboardGermany }; KeyboardController.Initialize(new XkbKeyboardRetrievingAdaptor(new XklEngineResponder())); var keyboards = Keyboard.Controller.AvailableKeyboards.ToArray(); Assert.AreEqual(2, keyboards.Length); Assert.AreEqual("en-US_us", keyboards[0].Id); Assert.AreEqual(ExpectedKeyboardUSA, keyboards[0].Name); Assert.AreEqual("de-DE_de", keyboards[1].Id); Assert.AreEqual(ExpectedKeyboardGermany, keyboards[1].Name); } /// <summary> /// Tests the values returned by InstalledKeyboards if the UICulture is set to German /// </summary> [Test] [SetUICulture("de-DE")] public void InstalledKeyboards_Germany_GermanCulture() { XklEngineResponder.SetGroupNames = new[] { KeyboardGermany }; KeyboardController.Initialize(new XkbKeyboardRetrievingAdaptor(new XklEngineResponder())); var keyboards = Keyboard.Controller.AvailableKeyboards; Assert.AreEqual(1, keyboards.Count()); Assert.AreEqual("de-DE_de", keyboards.First().Id); Assert.AreEqual("German - Deutsch (Deutschland)", keyboards.First().Name); } /// <summary> /// Tests the values returned by InstalledKeyboards if the UICulture is set to German /// and we're getting localized keyboard layouts /// </summary> [Test] [SetUICulture("de-DE")] public void InstalledKeyboards_Germany_AllGerman() // FWNX-1388 { XklEngineResponder.SetGroupNames = new[] { KeyboardGermany }; using (SetLanguage("de-DE")) { KeyboardController.Initialize(new XkbKeyboardRetrievingAdaptor(new XklEngineResponder())); IKeyboardDefinition[] keyboards = Keyboard.Controller.AvailableKeyboards.ToArray(); Assert.AreEqual(1, keyboards.Length); Assert.AreEqual("de-DE_de", keyboards[0].Id); Assert.AreEqual("Deutsch - Deutsch (Deutschland)", keyboards[0].Name); } } /// <summary> /// Tests InstalledKeyboards property. "Finland - Northern Saami" gives us two /// layouts (smi_FIN and sme_FIN), but ICU returns a LCID only for one of them. /// </summary> [Test] public void InstalledKeyboards_NorthernSaami() { XklEngineResponder.SetGroupNames = new[] { KeyboardFinlandNorthernSaami }; KeyboardController.Initialize(new XkbKeyboardRetrievingAdaptor(new XklEngineResponder())); IKeyboardDefinition[] keyboards = Keyboard.Controller.AvailableKeyboards.ToArray(); Assert.AreEqual(1, keyboards.Length); Assert.AreEqual(ExpectedKeyboardFinlandNorthernSaami, keyboards[0].Name); } [Test] public void ErrorKeyboards() { XklEngineResponder.SetGroupNames = new[] { "Fake" }; KeyboardController.Initialize(new XkbKeyboardRetrievingAdaptor(new XklEngineResponder())); IEnumerable<IKeyboardDefinition> keyboards = Keyboard.Controller.AvailableKeyboards; Assert.AreEqual(0, keyboards.Count()); //Assert.AreEqual(1, KeyboardController.ErrorKeyboards.Count); //Assert.AreEqual("Fake", KeyboardController.Errorkeyboards.First().Details); } /// <summary/> [Test] public void ActivateKeyboard_FirstTime_NotCrash() { XklEngineResponder.SetGroupNames = new[] { KeyboardUSA }; var adaptor = new XkbKeyboardRetrievingAdaptor(new XklEngineResponder()); KeyboardController.Initialize(adaptor); Assert.That(() => adaptor.SwitchingAdaptor.ActivateKeyboard( KeyboardController.Instance.Keyboards.First()), Throws.Nothing); } /// <summary> /// FWNX-895 /// </summary> [Test] public void ActivateKeyboard_SecondTime_NotCrash() { XklEngineResponder.SetGroupNames = new[] { KeyboardUSA }; var adaptor = new XkbKeyboardRetrievingAdaptor(new XklEngineResponder()); KeyboardController.Initialize(adaptor); adaptor.SwitchingAdaptor.ActivateKeyboard(KeyboardController.Instance.Keyboards.First()); KeyboardController.Shutdown(); adaptor = new XkbKeyboardRetrievingAdaptor(new XklEngineResponder()); KeyboardController.Initialize(adaptor); Assert.That(() => adaptor.SwitchingAdaptor.ActivateKeyboard( KeyboardController.Instance.Keyboards.First()), Throws.Nothing); } [Test] public void CreateKeyboardDefinition() { // Setup XklEngineResponder.SetGroupNames = new[] { KeyboardUSA }; var adaptor = new XkbKeyboardRetrievingAdaptor(new XklEngineResponder()); KeyboardController.Initialize(adaptor); // This mimics a KMFL ibus keyboard (which come through as path to the keyman file) const string kmflKeyboard = "/some/keyboard/without/dash"; const string expectedKeyboardName = "[Missing] /some/keyboard/without/dash ()"; // Exercise var keyboard = XkbKeyboardRetrievingAdaptor.CreateKeyboardDefinition(kmflKeyboard, adaptor.SwitchingAdaptor); // Verify Assert.That(keyboard, Is.Not.Null); Assert.That(keyboard.Name, Is.EqualTo(expectedKeyboardName)); } } }
/******************************************************************************* * Copyright (c) 2013, Daniel Murphy * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. ******************************************************************************/ using System; using System.Diagnostics; namespace SharpBox2D.Common { /** * A 2-by-2 matrix. Stored in column-major order. */ public struct Mat22 : IEquatable<Mat22> { public Vec2 ex, ey; /** Convert the matrix to printable format. */ public override string ToString() { string s = ""; s += "[" + ex.x + "," + ey.x + "]\n"; s += "[" + ex.y + "," + ey.y + "]"; return s; } /** * Create a matrix with given vectors as columns. * * @param c1 Column 1 of matrix * @param c2 Column 2 of matrix */ public Mat22(Vec2 c1, Vec2 c2) { ex = c1.clone(); ey = c2.clone(); } /** * Create a matrix from four floats. * * @param exx * @param col2x * @param exy * @param col2y */ public Mat22(float exx, float col2x, float exy, float col2y) { ex = new Vec2(exx, exy); ey = new Vec2(col2x, col2y); } /** * Set as a copy of another matrix. * * @param m Matrix to copy */ public Mat22 set(Mat22 m) { ex.x = m.ex.x; ex.y = m.ex.y; ey.x = m.ey.x; ey.y = m.ey.y; return this; } public Mat22 set(float exx, float col2x, float exy, float col2y) { ex.x = exx; ex.y = exy; ey.x = col2x; ey.y = col2y; return this; } /** * Return a clone of this matrix. djm fixed double allocation */ // @Override // annotation omitted for GWT-compatibility public Mat22 clone() { return new Mat22(ex, ey); } /** * Set as a matrix representing a rotation. * * @param angle Rotation (in radians) that matrix represents. */ public void set(float angle) { float c = MathUtils.cos(angle), s = MathUtils.sin(angle); ex.x = c; ey.x = -s; ex.y = s; ey.y = c; } /** * Set as the identity matrix. */ public void setIdentity() { ex.x = 1.0f; ey.x = 0.0f; ex.y = 0.0f; ey.y = 1.0f; } /** * Set as the zero matrix. */ public void setZero() { ex.x = 0.0f; ey.x = 0.0f; ex.y = 0.0f; ey.y = 0.0f; } /** * Extract the angle from this matrix (assumed to be a rotation matrix). * * @return */ public float getAngle() { return MathUtils.atan2(ex.y, ex.x); } /** * Set by column vectors. * * @param c1 Column 1 * @param c2 Column 2 */ public void set(Vec2 c1, Vec2 c2) { ex.x = c1.x; ey.x = c2.x; ex.y = c1.y; ey.y = c2.y; } /** Returns the inverted Mat22 - does NOT invert the matrix locally! */ public Mat22 invert() { float a = ex.x, b = ey.x, c = ex.y, d = ey.y; Mat22 B = new Mat22(); float det = a*d - b*c; if (det != 0) { det = 1.0f/det; } B.ex.x = det*d; B.ey.x = -det*b; B.ex.y = -det*c; B.ey.y = det*a; return B; } public void invertLocal() { float a = ex.x, b = ey.x, c = ex.y, d = ey.y; float det = a*d - b*c; if (det != 0) { det = 1.0f/det; } ex.x = det*d; ey.x = -det*b; ex.y = -det*c; ey.y = det*a; } public void invertToOut(ref Mat22 m) { float a = ex.x, b = ey.x, c = ex.y, d = ey.y; float det = a*d - b*c; // b2Debug.Assert(det != 0.0f); det = 1.0f/det; m.ex.x = det*d; m.ey.x = -det*b; m.ex.y = -det*c; m.ey.y = det*a; } /** * Return the matrix composed of the absolute values of all elements. djm: fixed double allocation * * @return Absolute value matrix */ public Mat22 abs() { return new Mat22(MathUtils.abs(ex.x), MathUtils.abs(ey.x), MathUtils.abs(ex.y), MathUtils.abs(ey.y)); } /* djm: added */ public void absLocal() { ex.absLocal(); ey.absLocal(); } /** * Return the matrix composed of the absolute values of all elements. * * @return Absolute value matrix */ public static Mat22 abs(Mat22 R) { return R.abs(); } /* djm created */ public static void absToOut(Mat22 R, Mat22 m) { m.ex.x = MathUtils.abs(R.ex.x); m.ex.y = MathUtils.abs(R.ex.y); m.ey.x = MathUtils.abs(R.ey.x); m.ey.y = MathUtils.abs(R.ey.y); } /** * Multiply a vector by this matrix. * * @param v Vector to multiply by matrix. * @return Resulting vector */ public Vec2 mul(Vec2 v) { return new Vec2(ex.x*v.x + ey.x*v.y, ex.y*v.x + ey.y*v.y); } public void mulToOut(Vec2 v, ref Vec2 v2) { float tempy = ex.y*v.x + ey.y*v.y; v2.x = ex.x*v.x + ey.x*v.y; v2.y = tempy; } public void mulToOutUnsafe(Vec2 v, ref Vec2 v2) { Debug.Assert(v != v2); v2.x = ex.x*v.x + ey.x*v.y; v2.y = ex.y*v.x + ey.y*v.y; } /** * Multiply another matrix by this one (this one on left). djm optimized * * @param R * @return */ public Mat22 mul(Mat22 R) { /* * Mat22 C = new Mat22();C.set(this.mul(R.ex), this.mul(R.ey));return C; */ Mat22 C = new Mat22(); C.ex.x = ex.x*R.ex.x + ey.x*R.ex.y; C.ex.y = ex.y*R.ex.x + ey.y*R.ex.y; C.ey.x = ex.x*R.ey.x + ey.x*R.ey.y; C.ey.y = ex.y*R.ey.x + ey.y*R.ey.y; // C.set(ex,col2); return C; } public void mulLocal(Mat22 R) { mulToOut(R, ref this); } public void mulToOut(Mat22 R, ref Mat22 m) { float tempy1 = this.ex.y*R.ex.x + this.ey.y*R.ex.y; float tempx1 = this.ex.x*R.ex.x + this.ey.x*R.ex.y; m.ex.x = tempx1; m.ex.y = tempy1; float tempy2 = this.ex.y*R.ey.x + this.ey.y*R.ey.y; float tempx2 = this.ex.x*R.ey.x + this.ey.x*R.ey.y; m.ey.x = tempx2; m.ey.y = tempy2; } public void mulToOutUnsafe(Mat22 R, ref Mat22 m) { Debug.Assert(m != R); Debug.Assert(m != this); m.ex.x = this.ex.x*R.ex.x + this.ey.x*R.ex.y; m.ex.y = this.ex.y*R.ex.x + this.ey.y*R.ex.y; m.ey.x = this.ex.x*R.ey.x + this.ey.x*R.ey.y; m.ey.y = this.ex.y*R.ey.x + this.ey.y*R.ey.y; } /** * Multiply another matrix by the transpose of this one (transpose of this one on left). djm: * optimized * * @param B * @return */ public Mat22 mulTrans(Mat22 B) { /* * Vec2 c1 = new Vec2(Vec2.dot(this.ex, B.ex), Vec2.dot(this.ey, B.ex)); Vec2 c2 = new * Vec2(Vec2.dot(this.ex, B.ey), Vec2.dot(this.ey, B.ey)); Mat22 C = new Mat22(); C.set(c1, c2); * return C; */ Mat22 C = new Mat22(); C.ex.x = Vec2.dot(this.ex, B.ex); C.ex.y = Vec2.dot(this.ey, B.ex); C.ey.x = Vec2.dot(this.ex, B.ey); C.ey.y = Vec2.dot(this.ey, B.ey); return C; } public void mulTransLocal(Mat22 B) { mulTransToOut(B, ref this); } public void mulTransToOut(Mat22 B, ref Mat22 m) { /* * ref.ex.x = Vec2.dot(this.ex, B.ex); ref.ex.y = Vec2.dot(this.ey, B.ex); ref.ey.x = * Vec2.dot(this.ex, B.ey); ref.ey.y = Vec2.dot(this.ey, B.ey); */ float x1 = this.ex.x*B.ex.x + this.ex.y*B.ex.y; float y1 = this.ey.x*B.ex.x + this.ey.y*B.ex.y; float x2 = this.ex.x*B.ey.x + this.ex.y*B.ey.y; float y2 = this.ey.x*B.ey.x + this.ey.y*B.ey.y; m.ex.x = x1; m.ey.x = x2; m.ex.y = y1; m.ey.y = y2; } public void mulTransToOutUnsafe(Mat22 B, ref Mat22 m) { Debug.Assert(B != m); Debug.Assert(this != m); m.ex.x = this.ex.x*B.ex.x + this.ex.y*B.ex.y; m.ey.x = this.ex.x*B.ey.x + this.ex.y*B.ey.y; m.ex.y = this.ey.x*B.ex.x + this.ey.y*B.ex.y; m.ey.y = this.ey.x*B.ey.x + this.ey.y*B.ey.y; } /** * Multiply a vector by the transpose of this matrix. * * @param v * @return */ public Vec2 mulTrans(Vec2 v) { // return new Vec2(Vec2.dot(v, ex), Vec2.dot(v, col2)); return new Vec2((v.x*ex.x + v.y*ex.y), (v.x*ey.x + v.y*ey.y)); } /* djm added */ public void mulTransToOut(Vec2 v, ref Vec2 v2) { /* * ref.x = Vec2.dot(v, ex); ref.y = Vec2.dot(v, col2); */ float tempx = v.x*ex.x + v.y*ex.y; v2.y = v.x*ey.x + v.y*ey.y; v2.x = tempx; } /** * Add this matrix to B, return the result. * * @param B * @return */ public Mat22 add(Mat22 B) { // return new Mat22(ex.add(B.ex), col2.add(B.ey)); Mat22 m = new Mat22(); m.ex.x = ex.x + B.ex.x; m.ex.y = ex.y + B.ex.y; m.ey.x = ey.x + B.ey.x; m.ey.y = ey.y + B.ey.y; return m; } /** * Add B to this matrix locally. * * @param B * @return */ public void addLocal(Mat22 B) { // ex.addLocal(B.ex); // col2.addLocal(B.ey); ex.x += B.ex.x; ex.y += B.ex.y; ey.x += B.ey.x; ey.y += B.ey.y; } /** * Solve A * x = b where A = this matrix. * * @return The vector x that solves the above equation. */ public Vec2 solve(Vec2 b) { float a11 = ex.x, a12 = ey.x, a21 = ex.y, a22 = ey.y; float det = a11*a22 - a12*a21; if (det != 0.0f) { det = 1.0f/det; } Vec2 x = new Vec2(det*(a22*b.x - a12*b.y), det*(a11*b.y - a21*b.x)); return x; } public void solveToOut(Vec2 b, ref Vec2 v2) { float a11 = ex.x, a12 = ey.x, a21 = ex.y, a22 = ey.y; float det = a11*a22 - a12*a21; if (det != 0.0f) { det = 1.0f/det; } float tempy = det*(a11*b.y - a21*b.x); v2.x = det*(a22*b.x - a12*b.y); v2.y = tempy; } public static Vec2 mul(Mat22 R, Vec2 v) { // return R.mul(v); return new Vec2(R.ex.x*v.x + R.ey.x*v.y, R.ex.y*v.x + R.ey.y*v.y); } public static void mulToOut(Mat22 R, Vec2 v, ref Vec2 v2) { float tempy = R.ex.y*v.x + R.ey.y*v.y; v2.x = R.ex.x*v.x + R.ey.x*v.y; v2.y = tempy; } public static void mulToOutUnsafe(Mat22 R, Vec2 v, ref Vec2 v2) { Debug.Assert(v != v2); v2.x = R.ex.x*v.x + R.ey.x*v.y; v2.y = R.ex.y*v.x + R.ey.y*v.y; } public static Mat22 mul(Mat22 A, Mat22 B) { // return A.mul(B); Mat22 C = new Mat22(); C.ex.x = A.ex.x*B.ex.x + A.ey.x*B.ex.y; C.ex.y = A.ex.y*B.ex.x + A.ey.y*B.ex.y; C.ey.x = A.ex.x*B.ey.x + A.ey.x*B.ey.y; C.ey.y = A.ex.y*B.ey.x + A.ey.y*B.ey.y; return C; } public static void mulToOut(Mat22 A, Mat22 B, ref Mat22 m) { float tempy1 = A.ex.y*B.ex.x + A.ey.y*B.ex.y; float tempx1 = A.ex.x*B.ex.x + A.ey.x*B.ex.y; float tempy2 = A.ex.y*B.ey.x + A.ey.y*B.ey.y; float tempx2 = A.ex.x*B.ey.x + A.ey.x*B.ey.y; m.ex.x = tempx1; m.ex.y = tempy1; m.ey.x = tempx2; m.ey.y = tempy2; } public static void mulToOutUnsafe(Mat22 A, Mat22 B, ref Mat22 m) { Debug.Assert(m != A); Debug.Assert(m != B); m.ex.x = A.ex.x*B.ex.x + A.ey.x*B.ex.y; m.ex.y = A.ex.y*B.ex.x + A.ey.y*B.ex.y; m.ey.x = A.ex.x*B.ey.x + A.ey.x*B.ey.y; m.ey.y = A.ex.y*B.ey.x + A.ey.y*B.ey.y; } public static Vec2 mulTrans(Mat22 R, Vec2 v) { return new Vec2((v.x*R.ex.x + v.y*R.ex.y), (v.x*R.ey.x + v.y*R.ey.y)); } public static void mulTransToOut(Mat22 R, Vec2 v, ref Vec2 v2) { float outx = v.x*R.ex.x + v.y*R.ex.y; v2.y = v.x*R.ey.x + v.y*R.ey.y; v2.x = outx; } public static void mulTransToOutUnsafe(Mat22 R, Vec2 v, ref Vec2 v2) { Debug.Assert(v2 != v); v2.y = v.x*R.ey.x + v.y*R.ey.y; v2.x = v.x*R.ex.x + v.y*R.ex.y; } public static Mat22 mulTrans(Mat22 A, Mat22 B) { Mat22 C = new Mat22(); C.ex.x = A.ex.x*B.ex.x + A.ex.y*B.ex.y; C.ex.y = A.ey.x*B.ex.x + A.ey.y*B.ex.y; C.ey.x = A.ex.x*B.ey.x + A.ex.y*B.ey.y; C.ey.y = A.ey.x*B.ey.x + A.ey.y*B.ey.y; return C; } public static void mulTransToOut(Mat22 A, Mat22 B, ref Mat22 m) { float x1 = A.ex.x*B.ex.x + A.ex.y*B.ex.y; float y1 = A.ey.x*B.ex.x + A.ey.y*B.ex.y; float x2 = A.ex.x*B.ey.x + A.ex.y*B.ey.y; float y2 = A.ey.x*B.ey.x + A.ey.y*B.ey.y; m.ex.x = x1; m.ex.y = y1; m.ey.x = x2; m.ey.y = y2; } public static void mulTransToOutUnsafe(Mat22 A, Mat22 B, ref Mat22 m) { Debug.Assert(A != m); Debug.Assert(B != m); m.ex.x = A.ex.x*B.ex.x + A.ex.y*B.ex.y; m.ex.y = A.ey.x*B.ex.x + A.ey.y*B.ex.y; m.ey.x = A.ex.x*B.ey.x + A.ex.y*B.ey.y; m.ey.y = A.ey.x*B.ey.x + A.ey.y*B.ey.y; } public static Mat22 createRotationalTransform(float angle) { Mat22 mat = new Mat22(); float c = MathUtils.cos(angle); float s = MathUtils.sin(angle); mat.ex.x = c; mat.ey.x = -s; mat.ex.y = s; mat.ey.y = c; return mat; } public static void createRotationalTransform(float angle, ref Mat22 m) { float c = MathUtils.cos(angle); float s = MathUtils.sin(angle); m.ex.x = c; m.ey.x = -s; m.ex.y = s; m.ey.y = c; } public static Mat22 createScaleTransform(float scale) { Mat22 mat = new Mat22(); mat.ex.x = scale; mat.ey.y = scale; return mat; } public static void createScaleTransform(float scale, ref Mat22 m) { m.ex.x = scale; m.ey.y = scale; } public bool Equals(Mat22 other) { return ex.Equals(other.ex) && ey.Equals(other.ey); } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; return obj is Mat22 && Equals((Mat22) obj); } public override int GetHashCode() { unchecked { return (ex.GetHashCode()*397) ^ ey.GetHashCode(); } } public static bool operator ==(Mat22 left, Mat22 right) { return left.Equals(right); } public static bool operator !=(Mat22 left, Mat22 right) { return !left.Equals(right); } } }
using System; using System.Collections; using System.Collections.Generic; using Volante; namespace Volante.Impl { class ThickIndex<K, V> : PersistentCollection<V>, IIndex<K, V> where V : class,IPersistent { private IIndex<K, IPersistent> index; private int nElems; const int BTREE_THRESHOLD = 128; internal ThickIndex(DatabaseImpl db) : base(db) { index = db.CreateIndex<K, IPersistent>(IndexType.Unique); } ThickIndex() { } public override int Count { get { return nElems; } } public V this[K key] { get { return Get(key); } set { Set(key, value); } } public V[] this[K from, K till] { get { return Get(from, till); } } public V Get(Key key) { IPersistent s = index.Get(key); if (s == null) return null; Relation<V, V> r = s as Relation<V, V>; if (r != null) { if (r.Count == 1) return r[0]; } throw new DatabaseException(DatabaseException.ErrorCode.KEY_NOT_UNIQUE); } public V[] Get(Key from, Key till) { return extend(index.Get(from, till)); } public V Get(K key) { return Get(KeyBuilder.getKeyFromObject(key)); } public V[] Get(K from, K till) { return Get(KeyBuilder.getKeyFromObject(from), KeyBuilder.getKeyFromObject(till)); } private V[] extend(IPersistent[] s) { List<V> list = new List<V>(); for (int i = 0; i < s.Length; i++) { list.AddRange((ICollection<V>)s[i]); } return list.ToArray(); } public V[] GetPrefix(string prefix) { return extend(index.GetPrefix(prefix)); } public V[] PrefixSearch(string word) { return extend(index.PrefixSearch(word)); } public override void Clear() { // TODO: not sure but the index might not own the objects in it, // so it cannot deallocate them //foreach (IPersistent o in this) //{ // o.Deallocate(); //} index.Clear(); nElems = 0; Modify(); } public V[] ToArray() { return extend(index.ToArray()); } class ExtendEnumerator : IEnumerator<V>, IEnumerable<V> { public void Dispose() { } public bool MoveNext() { if (reachedEnd) return false; while (!inner.MoveNext()) { if (!outer.MoveNext()) { reachedEnd = false; return false; } inner = ((IEnumerable<V>)outer.Current).GetEnumerator(); } return true; } public V Current { get { if (reachedEnd) throw new InvalidOperationException(); return inner.Current; } } object IEnumerator.Current { get { if (reachedEnd) throw new InvalidOperationException(); return Current; } } public void Reset() { reachedEnd = true; if (outer.MoveNext()) { reachedEnd = false; inner = ((IEnumerable<V>)outer.Current).GetEnumerator(); } } public IEnumerator<V> GetEnumerator() { return this; } IEnumerator IEnumerable.GetEnumerator() { return this; } internal ExtendEnumerator(IEnumerator<IPersistent> enumerator) { outer = enumerator; Reset(); } private IEnumerator<IPersistent> outer; private IEnumerator<V> inner; private bool reachedEnd; } class ExtendDictionaryEnumerator : IDictionaryEnumerator { public object Current { get { return Entry; } } public DictionaryEntry Entry { get { return new DictionaryEntry(key, inner.Current); } } public object Key { get { if (reachedEnd) throw new InvalidOperationException(); return key; } } public object Value { get { return inner.Current; } } public void Dispose() { } public bool MoveNext() { if (reachedEnd) return false; while (!inner.MoveNext()) { if (!outer.MoveNext()) { reachedEnd = true; return false; } key = outer.Key; inner = ((IEnumerable<V>)outer.Value).GetEnumerator(); } return true; } public void Reset() { reachedEnd = true; if (outer.MoveNext()) { reachedEnd = false; key = outer.Key; inner = ((IEnumerable<V>)outer.Value).GetEnumerator(); } } internal ExtendDictionaryEnumerator(IDictionaryEnumerator enumerator) { outer = enumerator; Reset(); } private IDictionaryEnumerator outer; private IEnumerator<V> inner; private object key; private bool reachedEnd; } public virtual IDictionaryEnumerator GetDictionaryEnumerator() { return new ExtendDictionaryEnumerator(index.GetDictionaryEnumerator()); } public override IEnumerator<V> GetEnumerator() { return new ExtendEnumerator(index.GetEnumerator()); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public IEnumerator<V> GetEnumerator(Key from, Key till, IterationOrder order) { return Range(from, till, order).GetEnumerator(); } public IEnumerator<V> GetEnumerator(K from, K till, IterationOrder order) { return Range(from, till, order).GetEnumerator(); } public IEnumerator<V> GetEnumerator(Key from, Key till) { return Range(from, till).GetEnumerator(); } public IEnumerator<V> GetEnumerator(K from, K till) { return Range(from, till).GetEnumerator(); } public IEnumerator<V> GetEnumerator(string prefix) { return StartsWith(prefix).GetEnumerator(); } public virtual IEnumerable<V> Range(Key from, Key till, IterationOrder order) { return new ExtendEnumerator(index.GetEnumerator(from, till, order)); } public virtual IEnumerable<V> Reverse() { return new ExtendEnumerator(index.Reverse().GetEnumerator()); } public virtual IEnumerable<V> Range(Key from, Key till) { return new ExtendEnumerator(index.GetEnumerator(from, till)); } public IEnumerable<V> Range(K from, K till, IterationOrder order) { return new ExtendEnumerator(index.GetEnumerator(from, till, order)); } public IEnumerable<V> Range(K from, K till) { return new ExtendEnumerator(index.GetEnumerator(from, till)); } public IEnumerable<V> StartsWith(string prefix) { return new ExtendEnumerator(index.GetEnumerator(prefix)); } public virtual IDictionaryEnumerator GetDictionaryEnumerator(Key from, Key till, IterationOrder order) { return new ExtendDictionaryEnumerator(index.GetDictionaryEnumerator(from, till, order)); } public Type KeyType { get { return index.KeyType; } } public bool Put(Key key, V obj) { IPersistent s = index.Get(key); if (s == null) { Relation<V, V> r = Database.CreateRelation<V, V>(null); r.Add(obj); index.Put(key, r); } else if (s is Relation<V, V>) { Relation<V, V> r = (Relation<V, V>)s; if (r.Count == BTREE_THRESHOLD) { ISet<V> ps = ((DatabaseImpl)Database).CreateBtreeSet<V>(); for (int i = 0; i < BTREE_THRESHOLD; i++) { ps.Add(r[i]); } ps.Add(obj); index.Set(key, ps); r.Deallocate(); } else { r.Add(obj); } } else { ((ISet<V>)s).Add(obj); } nElems += 1; Modify(); return true; } public V Set(Key key, V obj) { IPersistent s = index.Get(key); if (s == null) { Relation<V, V> r = Database.CreateRelation<V, V>(null); r.Add(obj); index.Put(key, r); nElems += 1; Modify(); return null; } else if (s is Relation<V, V>) { Relation<V, V> r = (Relation<V, V>)s; if (r.Count == 1) { V prev = r[0]; r[0] = obj; return prev; } } throw new DatabaseException(DatabaseException.ErrorCode.KEY_NOT_UNIQUE); } public void Remove(Key key, V obj) { IPersistent s = index.Get(key); if (s is Relation<V, V>) { Relation<V, V> r = (Relation<V, V>)s; int i = r.IndexOf(obj); if (i >= 0) { r.RemoveAt(i); if (r.Count == 0) { index.Remove(key, r); r.Deallocate(); } nElems -= 1; Modify(); return; } } else if (s is ISet<V>) { ISet<V> ps = (ISet<V>)s; if (ps.Remove(obj)) { if (ps.Count == 0) { index.Remove(key, ps); ps.Deallocate(); } nElems -= 1; Modify(); return; } } throw new DatabaseException(DatabaseException.ErrorCode.KEY_NOT_FOUND); } public V Remove(Key key) { throw new DatabaseException(DatabaseException.ErrorCode.KEY_NOT_UNIQUE); } public bool Put(K key, V obj) { return Put(KeyBuilder.getKeyFromObject(key), obj); } public V Set(K key, V obj) { return Set(KeyBuilder.getKeyFromObject(key), obj); } public void Remove(K key, V obj) { Remove(KeyBuilder.getKeyFromObject(key), obj); } public V RemoveKey(K key) { throw new DatabaseException(DatabaseException.ErrorCode.KEY_NOT_UNIQUE); } public override void Deallocate() { Clear(); index.Deallocate(); base.Deallocate(); } } }
/* * Copyright (c) 2014 All Rights Reserved by the SDL Group. * * 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.Management.Automation; using Trisoft.ISHRemote.Objects; using Trisoft.ISHRemote.Objects.Public; using Trisoft.ISHRemote.Exceptions; using Trisoft.ISHRemote.HelperClasses; using System.Linq; using System.Runtime.Remoting.Messaging; using Trisoft.ISHRemote.BackgroundTask25ServiceReference; using Trisoft.ISHRemote.EventMonitor25ServiceReference; using System.Text; namespace Trisoft.ISHRemote.Cmdlets.BackgroundTask { /// <summary> /// <para type="synopsis">The Add-IshBackgroundTask cmdlet add fire-and-forget asynchronous processing events to the CMS generic queuing system.</para> /// <para type="description">Add-IshBackgroundTask ParameterGroup variation uses BackgroundTask25.CreateBackgroundTask(WithStartAfter) that allows you to submit generic messages. Note that this requires a generic BackgroundTask service message handler.</para> /// <para type="description">Add-IshBackgroundTask IshObjectsGroup requires content object(s) which are transformed as message inputdata and passed to DocumentObj25.RaiseEventByIshLngRefs. This function will server-side validate the incoming objects and trigger an internal BackgroundTask25.CreateBackgroundTask.</para> /// </summary> /// <example> /// <code> /// New-IshSession -WsBaseUrl "https://example.com/ISHWS/" -PSCredential "Admin" /// $ishBackgroundTask = Get-IshFolderContent -FolderPath "General\MyFolder\Topics" -VersionFilter Latest -LanguagesFilter en | /// Add-IshBackgroundTask -EventType "SMARTTAG" /// </code> /// <para>Add BackgroundTask with event type "SMARTTAG" for the objects located under the "General\MyFolder\Topics" path</para> /// </example> /// <example> /// <code> /// New-IshSession -WsBaseUrl "https://example.com/ISHWS/" -PSCredential "Admin" /// $ishBackgroundTask = Get-IshFolder -FolderPath "General\Myfolder" -FolderTypeFilter @("ISHModule", "ISHMasterDoc", "ISHLibrary") -Recurse | /// Get-IshFolderContent -VersionFilter Latest -LanguagesFilter en | /// Add-IshBackgroundTask -EventType "SMARTTAG" /// </code> /// <para>Add BackgroundTask with event type "SMARTTAG" for the latest-version en(glish) content objects of type topic, map and topic library; located under the "General\MyFolder" path. Trigger a legacy correction event of SMARTTAG across many folders. Note that Get-IshFolder gives you a progress bar for follow-up. Note that it is possible to configure the BackgroundTask-handler with a variation of the SMARTTAG event to do more-or-less fields for automatic concept suggestions.</para> /// </example> /// <example> /// <code> /// New-IshSession -WsBaseUrl "https://example.com/ISHWS/" -PSCredential "Admin" /// $rawData = "&lt;data&gt;&lt;export-document-type&gt;ISHPublication&lt;/export-document-type&gt;&lt;export-document-level&gt;lng&lt;/export-document-level&gt;&lt;export-ishlngref&gt;549482&lt;/export-ishlngref&gt;&lt;creationdate&gt;20210303070257182&lt;/creationdate&gt;&lt;/data&gt;" /// $ishBackgroundTask = Add-IshBackgroundTask -EventType "PUBLISH" -EventDescription "Custom publish event description" -RawInputData $rawData /// </code> /// <para>Add background task with the event type "PUBLISH" and provided event description and publish input raw data. Note: example code only, for publish operations usage of Publish-IshPublicationOutput cmdlet is preferred.</para> /// </example> /// <example> /// <code> /// New-IshSession -WsBaseUrl "https://example.com/ISHWS/" -PSCredential "Admin" /// $rawData = "&lt;data&gt;&lt;export-document-type&gt;ISHPublication&lt;/export-document-type&gt;&lt;export-document-level&gt;lng&lt;/export-document-level&gt;&lt;export-ishlngref&gt;549482&lt;/export-ishlngref&gt;&lt;creationdate&gt;20210303070257182&lt;/creationdate&gt;&lt;/data&gt;" /// $date = (Get-Date).AddDays(1) /// $ishBackgroundTask = Add-IshBackgroundTask -EventType "PUBLISH" -EventDescription "Custom publish event description" -RawInputData $rawData -StartAfter $date /// </code> /// <para>Add background task with the event type "PUBLISH" and provided event description and publish input raw data. /// Provided StartAfter parameter with tomorrow's date indicates that background task should not be executed before this date. Note: example code only, for publish operations usage of Publish-IshPublicationOutput cmdlet is preferred.</para> /// </example> [Cmdlet(VerbsCommon.Add, "IshBackgroundTask", SupportsShouldProcess = false)] [OutputType(typeof(IshBackgroundTask))] public sealed class AddIshBackgroundTask : BackgroundTaskCmdlet { /// <summary> /// <para type="description">The IshSession variable holds the authentication and contract information. This object can be initialized using the New-IshSession cmdlet.</para> /// </summary> [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = false, ParameterSetName = "ParameterGroup")] [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = false, ParameterSetName = "IshObjectsGroup")] [ValidateNotNullOrEmpty] public IshSession IshSession { get; set; } /// <summary> /// <para type="description">Type of the event (e.g. SMARTTAG). Needs a match CMS BackgroundTask service handler entry.</para> /// </summary> [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = false, ParameterSetName = "ParameterGroup")] [Parameter(Mandatory = true, ValueFromPipelineByPropertyName = false, ParameterSetName = "IshObjectsGroup")] [ValidateNotNullOrEmpty] public string EventType { get; set; } /// <summary> /// <para type="description">The input data for the background task.</para> /// </summary> [Parameter(Mandatory = true, ValueFromPipelineByPropertyName = false, ParameterSetName = "ParameterGroup")] [ValidateNotNullOrEmpty] public string RawInputData { get; set; } /// <summary> /// <para type="description">Description of the event</para> /// </summary> [Parameter(Mandatory = true, ValueFromPipelineByPropertyName = false, ParameterSetName = "ParameterGroup")] [ValidateNotNullOrEmpty] public string EventDescription { get; set; } /// <summary> /// <para type="description">Date time indicating that the background task should not be picked up and executed before it.</para> /// </summary> [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = false, ParameterSetName = "ParameterGroup")] public DateTime? StartAfter { get; set; } /// <summary> /// <para type="description">The <see cref="IshObjects"/>s that will be used for background task creation.</para> /// </summary> [Parameter(Mandatory = true, ValueFromPipeline = true, ParameterSetName = "IshObjectsGroup")] [AllowEmptyCollection] public IshObject[] IshObject { get; set; } #region Private fields private readonly List<IshObject> _retrievedIshObjects = new List<IshObject>(); private readonly DateTime _modifiedSince = DateTime.Today.AddDays(-1); private readonly BackgroundTask25ServiceReference.eUserFilter _userFilter = EnumConverter.ToUserFilter<BackgroundTask25ServiceReference.eUserFilter>(Enumerations.UserFilter.Current); private readonly int _startEventMaxProgress = 100; #endregion protected override void BeginProcessing() { if (IshSession == null) { IshSession = (IshSession)SessionState.PSVariable.GetValue(ISHRemoteSessionStateIshSession); } if (IshSession == null) { throw new ArgumentException(ISHRemoteSessionStateIshSessionException); } WriteDebug($"Using IshSession[{IshSession.Name}] from SessionState.{ISHRemoteSessionStateIshSession}"); switch (ParameterSetName) { case "ParameterGroup": if ((IshSession.ServerIshVersion.MajorVersion < 13) || ((IshSession.ServerIshVersion.MajorVersion == 13) && (IshSession.ServerIshVersion.RevisionVersion < 2))) { throw new PlatformNotSupportedException($"Add-IshBackgroundTask with the current parameter set requires server-side BackgroundTask API which is only available starting from 13SP2/13.0.2 and up. ServerIshVersion[{IshSession.ServerVersion}]"); } break; case "IshObjectsGroup": if ((IshSession.ServerIshVersion.MajorVersion < 14) || ((IshSession.ServerIshVersion.MajorVersion == 14) && (IshSession.ServerIshVersion.RevisionVersion < 4))) { throw new PlatformNotSupportedException($"Add-IshBackgroundTask with the current parameter set requires server-side DocumentObj API which is only available starting from 14SP4/14.0.4 and up. ServerIshVersion[{IshSession.ServerVersion}]"); } break; } base.BeginProcessing(); } /// <summary> /// Process the cmdlet. /// </summary> protected override void ProcessRecord() { try { if (IshObject != null) { foreach (IshObject ishObject in IshObject) { _retrievedIshObjects.Add(ishObject); } } } catch (TrisoftAutomationException trisoftAutomationException) { ThrowTerminatingError(new ErrorRecord(trisoftAutomationException, base.GetType().Name, ErrorCategory.InvalidOperation, null)); } catch (Exception exception) { ThrowTerminatingError(new ErrorRecord(exception, base.GetType().Name, ErrorCategory.NotSpecified, null)); } } /// <summary> /// Process the Add-IshBackgroundTask command-let. /// </summary> /// <exception cref="TrisoftAutomationException"></exception> /// <exception cref="Exception"></exception> /// <remarks>Writes <see cref="IshBackgroundTask"/> to the pipeline.</remarks> protected override void EndProcessing() { try { IshFields metadataFilter = new IshFields(); IshFields requestedMetadata = IshSession.IshTypeFieldSetup.ToIshRequestedMetadataFields(IshSession.DefaultRequestedMetadata, ISHType, new IshFields(), Enumerations.ActionMode.Find); var startEventResponse = new StartEventResponse(); var progressIds = new List<long>(); if (ParameterSetName == "IshObjectsGroup") { var ishObjectsDividedInBatches = DevideListInBatchesByLogicalId(_retrievedIshObjects, IshSession.MetadataBatchSize); int currentIshObjectsCount = 0; foreach (var ishObjectsGroup in ishObjectsDividedInBatches) { // Create BackgroundTask var lngCardIds = ishObjectsGroup.Select(ishObject => Convert.ToInt64(ishObject.ObjectRef[Enumerations.ReferenceType.Lng])).ToList(); var progressId = IshSession.DocumentObj25.RaiseEventByIshLngRefs(lngCardIds.ToArray(), EventType); progressIds.Add(progressId); currentIshObjectsCount += ishObjectsGroup.Count; WriteDebug($"RaiseEventByIshLngRefs.length[{lngCardIds.Count}] {currentIshObjectsCount}/{_retrievedIshObjects.Count}"); } } if (ParameterSetName == "ParameterGroup") { // Start event var startEventRequest = new StartEventRequest { description = EventDescription, eventType = EventType, maximumProgress = _startEventMaxProgress }; startEventResponse = IshSession.EventMonitor25.StartEvent(startEventRequest); } if (ParameterSetName == "ParameterGroup" && StartAfter.HasValue) { // Create BackgroundTask var newBackgroundTaskWithStartAfterRequest = new CreateBackgroundTaskWithStartAfterRequest { eventType = EventType, hashId = "", inputData = Encoding.Unicode.GetBytes(RawInputData), startAfter = StartAfter.Value, progressId = startEventResponse.progressId }; var createBackgroundTaskStartAfterResponse = IshSession.BackgroundTask25.CreateBackgroundTaskWithStartAfter(newBackgroundTaskWithStartAfterRequest); var progressId = createBackgroundTaskStartAfterResponse.progressId; progressIds.Add(progressId); } if (ParameterSetName == "ParameterGroup" && !StartAfter.HasValue) { // Create BackgroundTask var newBackgroundTaskRequest = new CreateBackgroundTaskRequest { eventType = EventType, hashId = "", inputData = Encoding.Unicode.GetBytes(RawInputData), progressId = startEventResponse.progressId }; var createBackgroundTaskResponse = IshSession.BackgroundTask25.CreateBackgroundTask(newBackgroundTaskRequest); var progressId = createBackgroundTaskResponse.progressId; progressIds.Add(progressId); } // Find and return IshBackgroundTask object if (progressIds.Count > 1) { var progressIdsAsString = string.Join(IshSession.Separator, progressIds.ToArray()); metadataFilter.AddField(new IshMetadataFilterField(FieldElements.BackgroundTaskProgressId, Enumerations.Level.Task, Enumerations.FilterOperator.In, progressIdsAsString, Enumerations.ValueType.Element)); } else { metadataFilter.AddField(new IshMetadataFilterField(FieldElements.BackgroundTaskProgressId, Enumerations.Level.Task, Enumerations.FilterOperator.In, progressIds.First().ToString(), Enumerations.ValueType.Element)); } WriteDebug($"Finding BackgroundTask UserFilter[{_userFilter}] MetadataFilter.length[{metadataFilter.ToXml().Length}] RequestedMetadata.length[{requestedMetadata.ToXml().Length}]"); var xmlIshBackgroundTasks = IshSession.BackgroundTask25.Find( _modifiedSince, _userFilter, metadataFilter.ToXml(), requestedMetadata.ToXml()); List<IshBackgroundTask> returnIshBackgroundTasks = new IshBackgroundTasks(xmlIshBackgroundTasks).BackgroundTasks; WriteVerbose("returned object count[" + returnIshBackgroundTasks.Count + "]"); WriteObject(IshSession, ISHType, returnIshBackgroundTasks.ConvertAll(x => (IshBaseObject)x), true); } catch (TrisoftAutomationException trisoftAutomationException) { ThrowTerminatingError(new ErrorRecord(trisoftAutomationException, base.GetType().Name, ErrorCategory.InvalidOperation, null)); } catch (Exception exception) { ThrowTerminatingError(new ErrorRecord(exception, base.GetType().Name, ErrorCategory.NotSpecified, null)); } } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using MigAz.Azure.Core.Interface; using MigAz.Azure.MigrationTarget; namespace MigAz.Azure.UserControls { public partial class NetworkInterfaceProperties : TargetPropertyControl { private Azure.MigrationTarget.NetworkInterface _TargetNetworkInterface; public NetworkInterfaceProperties() { InitializeComponent(); this.publicIpSelectionControl1.PropertyChanged += PublicIpSelectionControl1_PropertyChanged; this.networkSelectionControl1.PropertyChanged += NetworkSelectionControl1_PropertyChanged; } private void PublicIpSelectionControl1_PropertyChanged() { if (!this.IsBinding) { if (_TargetNetworkInterface.TargetNetworkInterfaceIpConfigurations.Count > 0) { _TargetNetworkInterface.TargetNetworkInterfaceIpConfigurations[0].TargetPublicIp = publicIpSelectionControl1.PublicIp; } this.RaisePropertyChangedEvent(_TargetNetworkInterface); } } private void NetworkSelectionControl1_PropertyChanged() { this.RaisePropertyChangedEvent(_TargetNetworkInterface); } internal async Task Bind(NetworkInterface targetNetworkInterface, TargetTreeView targetTreeView) { try { this.IsBinding = true; _TargetTreeView = targetTreeView; _TargetNetworkInterface = targetNetworkInterface; await publicIpSelectionControl1.Bind(targetTreeView); await networkSelectionControl1.Bind(targetTreeView); if (_TargetNetworkInterface.TargetNetworkInterfaceIpConfigurations.Count > 0) { networkSelectionControl1.VirtualNetworkTarget = _TargetNetworkInterface.TargetNetworkInterfaceIpConfigurations[0]; if (_TargetNetworkInterface.TargetNetworkInterfaceIpConfigurations[0].TargetPublicIp == null) rbPublicIpDisabled.Checked = true; else { rbPublicIpEnabled.Checked = true; } publicIpSelectionControl1.PublicIp = _TargetNetworkInterface.TargetNetworkInterfaceIpConfigurations[0].TargetPublicIp; } lblSourceName.Text = _TargetNetworkInterface.SourceName; txtTargetName.Text = _TargetNetworkInterface.TargetName; if (_TargetNetworkInterface.EnableIPForwarding) rbIPForwardingEnabled.Checked = true; else rbIPForwardingDisabled.Checked = true; if (_TargetNetworkInterface.EnableAcceleratedNetworking) rbAcceleratedNetworkingEnabled.Checked = true; else rbAcceleratedNetworkingDisabled.Checked = true; if (_TargetNetworkInterface.SourceNetworkInterface != null) { if (_TargetNetworkInterface.SourceNetworkInterface.GetType() == typeof(Azure.Asm.NetworkInterface)) { Azure.Asm.NetworkInterface asmNetworkInterface = (Azure.Asm.NetworkInterface)_TargetNetworkInterface.SourceNetworkInterface; lblVirtualNetworkName.Text = asmNetworkInterface.NetworkInterfaceIpConfigurations[0].VirtualNetworkName; lblSubnetName.Text = asmNetworkInterface.NetworkInterfaceIpConfigurations[0].SubnetName; lblStaticIpAddress.Text = asmNetworkInterface.NetworkInterfaceIpConfigurations[0].PrivateIpAddress; } else if (_TargetNetworkInterface.SourceNetworkInterface.GetType() == typeof(Azure.Arm.NetworkInterface)) { Azure.Arm.NetworkInterface armNetworkInterface = (Azure.Arm.NetworkInterface)_TargetNetworkInterface.SourceNetworkInterface; lblVirtualNetworkName.Text = armNetworkInterface.NetworkInterfaceIpConfigurations[0].VirtualNetworkName; lblSubnetName.Text = armNetworkInterface.NetworkInterfaceIpConfigurations[0].SubnetName; lblStaticIpAddress.Text = armNetworkInterface.NetworkInterfaceIpConfigurations[0].PrivateIpAddress; } } virtualMachineSummary.Bind(_TargetNetworkInterface.ParentVirtualMachine, _TargetTreeView); networkSecurityGroup.Bind(_TargetNetworkInterface.NetworkSecurityGroup, _TargetTreeView); await this.publicIpSelectionControl1.Bind(_TargetTreeView); this.UpdatePropertyEnablement(); } finally { this.IsBinding = false; } } internal override void UpdatePropertyEnablement() { this.pnlAcceleratedNetworking.Enabled = _TargetNetworkInterface.AllowAcceleratedNetworking; this.pnlAcceleratedNetworking.Visible = _TargetNetworkInterface.AllowAcceleratedNetworking; } private void txtTargetName_TextChanged(object sender, EventArgs e) { TextBox txtSender = (TextBox)sender; _TargetNetworkInterface.SetTargetName(txtSender.Text, _TargetTreeView.TargetSettings); this.RaisePropertyChangedEvent(_TargetNetworkInterface); } private void txtTargetName_KeyPress(object sender, KeyPressEventArgs e) { if (char.IsWhiteSpace(e.KeyChar)) { e.Handled = true; } } private void rbIPForwardingEnabled_CheckedChanged(object sender, EventArgs e) { if (rbIPForwardingEnabled.Checked) { _TargetNetworkInterface.EnableIPForwarding = true; this.RaisePropertyChangedEvent(_TargetNetworkInterface); } } private void rbIPForwardingDisabled_CheckedChanged(object sender, EventArgs e) { if (rbIPForwardingDisabled.Checked) { _TargetNetworkInterface.EnableIPForwarding = false; this.RaisePropertyChangedEvent(_TargetNetworkInterface); } } private void rbAcceleratedNetworkingEnabled_CheckedChanged(object sender, EventArgs e) { if (rbAcceleratedNetworkingEnabled.Checked) { _TargetNetworkInterface.EnableAcceleratedNetworking = true; this.RaisePropertyChangedEvent(_TargetNetworkInterface); } } private void rbAcceleratedNetworkingDisabled_CheckedChanged(object sender, EventArgs e) { if (rbAcceleratedNetworkingDisabled.Checked) { _TargetNetworkInterface.EnableAcceleratedNetworking = false; this.RaisePropertyChangedEvent(_TargetNetworkInterface); } } private void rbPublicIpDisabled_CheckedChanged(object sender, EventArgs e) { if (rbPublicIpDisabled.Checked) { try { this.IsBinding = true; if (_TargetNetworkInterface.TargetNetworkInterfaceIpConfigurations.Count > 0) _TargetNetworkInterface.TargetNetworkInterfaceIpConfigurations[0].TargetPublicIp = null; publicIpSelectionControl1.PublicIp = null; publicIpSelectionControl1.Enabled = false; } finally { this.IsBinding = false; this.RaisePropertyChangedEvent(_TargetNetworkInterface); } } } private void rbPublicIpEnabled_CheckedChanged(object sender, EventArgs e) { if (rbPublicIpEnabled.Checked) { publicIpSelectionControl1.Enabled = true; this.RaisePropertyChangedEvent(_TargetNetworkInterface); } } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. namespace System.Management.Automation.ComInterop { #region Generated Com Exception Factory // *** BEGIN GENERATED CODE *** // generated by function: gen_expr_factory_com from: generate_exception_factory.py /// <summary> /// Strongly-typed and parameterized string factory. /// </summary> internal static partial class Strings { private static string FormatString(string format, params object[] args) { return string.Format(System.Globalization.CultureInfo.CurrentCulture, format, args); } /// <summary> /// A string like "Unexpected VarEnum {0}." /// </summary> internal static string UnexpectedVarEnum(object p0) { return FormatString(ParserStrings.UnexpectedVarEnum, p0); } /// <summary> /// A string like "Error while invoking {0}." /// </summary> internal static string DispBadParamCount(object p0, int parameterCount) { return FormatString(ParserStrings.DispBadParamCount, p0, parameterCount); } /// <summary> /// A string like "Error while invoking {0}." /// </summary> internal static string DispMemberNotFound(object p0) { return FormatString(ParserStrings.DispMemberNotFound, p0); } /// <summary> /// A string like "Error while invoking {0}. Named arguments are not supported." /// </summary> internal static string DispNoNamedArgs(object p0) { return FormatString(ParserStrings.DispNoNamedArgs, p0); } /// <summary> /// A string like "Error while invoking {0}." /// </summary> internal static string DispOverflow(object p0) { return FormatString(ParserStrings.DispOverflow, p0); } /// <summary> /// A string like "Exception setting "{0}": "Cannot convert the "{1}" value of type "{2}" to type "{3}"." /// </summary> internal static string DispTypeMismatch(object method, string value, string originalTypeName, string destinationTypeName) { return FormatString(ParserStrings.DispTypeMismatch, method, value, originalTypeName, destinationTypeName); } /// <summary> /// A string like "Error while invoking {0}. A required parameter was omitted." /// </summary> internal static string DispParamNotOptional(object p0) { return FormatString(ParserStrings.DispParamNotOptional, p0); } /// <summary> /// A string like "IDispatch::GetIDsOfNames behaved unexpectedly for {0}." /// </summary> internal static string GetIDsOfNamesInvalid(object p0) { return FormatString(ParserStrings.GetIDsOfNamesInvalid, p0); } /// <summary> /// A string like "Could not get dispatch ID for {0} (error: {1})." /// </summary> internal static string CouldNotGetDispId(object p0, object p1) { return FormatString(ParserStrings.CouldNotGetDispId, p0, p1); } /// <summary> /// A string like "There are valid conversions from {0} to {1}." /// </summary> internal static string AmbiguousConversion(object p0, object p1) { return FormatString(ParserStrings.AmbiguousConversion, p0, p1); } /// <summary> /// A string like "Variant.GetAccessor cannot handle {0}." /// </summary> internal static string VariantGetAccessorNYI(object p0) { return FormatString(ParserStrings.VariantGetAccessorNYI, p0); } } /// <summary> /// Strongly-typed and parameterized exception factory. /// </summary> internal static partial class Error { /// <summary> /// ArgumentException with message like "COM object does not support events." /// </summary> internal static Exception COMObjectDoesNotSupportEvents() { return new ArgumentException(ParserStrings.COMObjectDoesNotSupportEvents); } /// <summary> /// ArgumentException with message like "COM object does not support specified source interface." /// </summary> internal static Exception COMObjectDoesNotSupportSourceInterface() { return new ArgumentException(ParserStrings.COMObjectDoesNotSupportSourceInterface); } /// <summary> /// InvalidOperationException with message like "Marshal.SetComObjectData failed." /// </summary> internal static Exception SetComObjectDataFailed() { return new InvalidOperationException(ParserStrings.SetComObjectDataFailed); } /// <summary> /// InvalidOperationException with message like "This method exists only to keep the compiler happy." /// </summary> internal static Exception MethodShouldNotBeCalled() { return new InvalidOperationException(ParserStrings.MethodShouldNotBeCalled); } /// <summary> /// InvalidOperationException with message like "Unexpected VarEnum {0}." /// </summary> internal static Exception UnexpectedVarEnum(object p0) { return new InvalidOperationException(Strings.UnexpectedVarEnum(p0)); } /// <summary> /// System.Reflection.TargetParameterCountException with message like "Error while invoking {0}." /// </summary> internal static Exception DispBadParamCount(object p0, int parameterCount) { return new System.Reflection.TargetParameterCountException(Strings.DispBadParamCount(p0, parameterCount)); } /// <summary> /// MissingMemberException with message like "Error while invoking {0}." /// </summary> internal static Exception DispMemberNotFound(object p0) { return new MissingMemberException(Strings.DispMemberNotFound(p0)); } /// <summary> /// ArgumentException with message like "Error while invoking {0}. Named arguments are not supported." /// </summary> internal static Exception DispNoNamedArgs(object p0) { return new ArgumentException(Strings.DispNoNamedArgs(p0)); } /// <summary> /// OverflowException with message like "Error while invoking {0}." /// </summary> internal static Exception DispOverflow(object p0) { return new OverflowException(Strings.DispOverflow(p0)); } /// <summary> /// ArgumentException with message like "Could not convert argument {0} for call to {1}." /// </summary> internal static Exception DispTypeMismatch(object method, string value, string originalTypeName, string destinationTypeName) { return new ArgumentException(Strings.DispTypeMismatch(method, value, originalTypeName, destinationTypeName)); } /// <summary> /// ArgumentException with message like "Error while invoking {0}. A required parameter was omitted." /// </summary> internal static Exception DispParamNotOptional(object p0) { return new ArgumentException(Strings.DispParamNotOptional(p0)); } /// <summary> /// InvalidOperationException with message like "ResolveComReference.CannotRetrieveTypeInformation." /// </summary> internal static Exception CannotRetrieveTypeInformation() { return new InvalidOperationException(ParserStrings.CannotRetrieveTypeInformation); } /// <summary> /// ArgumentException with message like "IDispatch::GetIDsOfNames behaved unexpectedly for {0}." /// </summary> internal static Exception GetIDsOfNamesInvalid(object p0) { return new ArgumentException(Strings.GetIDsOfNamesInvalid(p0)); } /// <summary> /// InvalidOperationException with message like "Attempting to wrap an unsupported enum type." /// </summary> internal static Exception UnsupportedEnumType() { return new InvalidOperationException(ParserStrings.UnsupportedEnumType); } /// <summary> /// InvalidOperationException with message like "Attempting to pass an event handler of an unsupported type." /// </summary> internal static Exception UnsupportedHandlerType() { return new InvalidOperationException(ParserStrings.UnsupportedHandlerType); } /// <summary> /// MissingMemberException with message like "Could not get dispatch ID for {0} (error: {1})." /// </summary> internal static Exception CouldNotGetDispId(object p0, object p1) { return new MissingMemberException(Strings.CouldNotGetDispId(p0, p1)); } /// <summary> /// System.Reflection.AmbiguousMatchException with message like "There are valid conversions from {0} to {1}." /// </summary> internal static Exception AmbiguousConversion(object p0, object p1) { return new System.Reflection.AmbiguousMatchException(Strings.AmbiguousConversion(p0, p1)); } /// <summary> /// NotImplementedException with message like "Variant.GetAccessor cannot handle {0}." /// </summary> internal static Exception VariantGetAccessorNYI(object p0) { return new NotImplementedException(Strings.VariantGetAccessorNYI(p0)); } } // *** END GENERATED CODE *** #endregion }
using System; using System.Collections; using System.Globalization; using Fonet.DataTypes; namespace Fonet.Fo.Expr { internal class PropertyParser : PropertyTokenizer { private PropertyInfo propInfo; private const string RELUNIT = "em"; private static Numeric negOne = new Numeric((decimal)-1.0); private static Hashtable functionTable = new Hashtable(); static PropertyParser() { functionTable.Add("ceiling", new CeilingFunction()); functionTable.Add("floor", new FloorFunction()); functionTable.Add("round", new RoundFunction()); functionTable.Add("min", new MinFunction()); functionTable.Add("max", new MaxFunction()); functionTable.Add("abs", new AbsFunction()); functionTable.Add("rgb", new RGBColorFunction()); functionTable.Add("from-table-column", new FromTableColumnFunction()); functionTable.Add("inherited-property-value", new InheritedPropFunction()); functionTable.Add("from-parent", new FromParentFunction()); functionTable.Add("from-nearest-specified-value", new NearestSpecPropFunction()); functionTable.Add("proportional-column-width", new PPColWidthFunction()); functionTable.Add("label-end", new LabelEndFunction()); functionTable.Add("body-start", new BodyStartFunction()); functionTable.Add("_fop-property-value", new FonetPropValFunction()); } public static Property parse(string expr, PropertyInfo propInfo) { return new PropertyParser(expr, propInfo).parseProperty(); } private PropertyParser(string propExpr, PropertyInfo pInfo) : base(propExpr) { this.propInfo = pInfo; } private Property parseProperty() { next(); if (currentToken == TOK_EOF) { return new StringProperty(""); } ListProperty propList = null; while (true) { Property prop = parseAdditiveExpr(); if (currentToken == TOK_EOF) { if (propList != null) { propList.addProperty(prop); return propList; } else { return prop; } } else { if (propList == null) { propList = new ListProperty(prop); } else { propList.addProperty(prop); } } } } private Property parseAdditiveExpr() { Property prop = parseMultiplicativeExpr(); bool cont = true; while (cont) { switch (currentToken) { case TOK_PLUS: next(); prop = evalAddition(prop.GetNumeric(), parseMultiplicativeExpr().GetNumeric()); break; case TOK_MINUS: next(); prop = evalSubtraction(prop.GetNumeric(), parseMultiplicativeExpr().GetNumeric()); break; default: cont = false; break; } } return prop; } private Property parseMultiplicativeExpr() { Property prop = parseUnaryExpr(); bool cont = true; while (cont) { switch (currentToken) { case TOK_DIV: next(); prop = evalDivide(prop.GetNumeric(), parseUnaryExpr().GetNumeric()); break; case TOK_MOD: next(); prop = evalModulo(prop.GetNumber(), parseUnaryExpr().GetNumber()); break; case TOK_MULTIPLY: next(); prop = evalMultiply(prop.GetNumeric(), parseUnaryExpr().GetNumeric()); break; default: cont = false; break; } } return prop; } private Property parseUnaryExpr() { if (currentToken == TOK_MINUS) { next(); return evalNegate(parseUnaryExpr().GetNumeric()); } return parsePrimaryExpr(); } private void expectRpar() { if (currentToken != TOK_RPAR) { throw new PropertyException("expected )"); } next(); } private Property parsePrimaryExpr() { Property prop; switch (currentToken) { case TOK_LPAR: next(); prop = parseAdditiveExpr(); expectRpar(); return prop; case TOK_LITERAL: prop = new StringProperty(currentTokenValue); break; case TOK_NCNAME: prop = new NCnameProperty(currentTokenValue); break; case TOK_FLOAT: prop = new NumberProperty(ParseDouble(currentTokenValue)); break; case TOK_INTEGER: prop = new NumberProperty(Int32.Parse(currentTokenValue)); break; case TOK_PERCENT: double pcval = ParseDouble( currentTokenValue.Substring(0, currentTokenValue.Length - 1)) / 100.0; IPercentBase pcBase = this.propInfo.GetPercentBase(); if (pcBase != null) { if (pcBase.GetDimension() == 0) { prop = new NumberProperty(pcval * pcBase.GetBaseValue()); } else if (pcBase.GetDimension() == 1) { prop = new LengthProperty(new PercentLength(pcval, pcBase)); } else { throw new PropertyException("Illegal percent dimension value"); } } else { prop = new NumberProperty(pcval); } break; case TOK_NUMERIC: int numLen = currentTokenValue.Length - currentUnitLength; string unitPart = currentTokenValue.Substring(numLen); double numPart = ParseDouble(currentTokenValue.Substring(0, numLen)); Length length = null; if (unitPart.Equals(RELUNIT)) { length = new FixedLength(numPart, propInfo.currentFontSize()); } else { length = new FixedLength(numPart, unitPart); } if (length == null) { throw new PropertyException("unrecognized unit name: " + currentTokenValue); } else { prop = new LengthProperty(length); } break; case TOK_COLORSPEC: prop = new ColorTypeProperty(new ColorType(currentTokenValue)); break; case TOK_FUNCTION_LPAR: { IFunction function = (IFunction)functionTable[currentTokenValue]; if (function == null) { throw new PropertyException("no such function: " + currentTokenValue); } next(); propInfo.pushFunction(function); prop = function.Eval(parseArgs(function.NumArgs), propInfo); propInfo.popFunction(); return prop; } default: throw new PropertyException("syntax error"); } next(); return prop; } private Property[] parseArgs(int nbArgs) { Property[] args = new Property[nbArgs]; Property prop; int i = 0; if (currentToken == TOK_RPAR) { next(); } else { while (true) { prop = parseAdditiveExpr(); if (i < nbArgs) { args[i++] = prop; } if (currentToken != TOK_COMMA) { break; } next(); } expectRpar(); } if (nbArgs != i) { throw new PropertyException("Wrong number of args for function"); } return args; } private Property evalAddition(Numeric op1, Numeric op2) { if (op1 == null || op2 == null) { throw new PropertyException("Non numeric operand in addition"); } return new NumericProperty(op1.add(op2)); } private Property evalSubtraction(Numeric op1, Numeric op2) { if (op1 == null || op2 == null) { throw new PropertyException("Non numeric operand in subtraction"); } return new NumericProperty(op1.subtract(op2)); } private Property evalNegate(Numeric op) { if (op == null) { throw new PropertyException("Non numeric operand to unary minus"); } return new NumericProperty(op.multiply(negOne)); } private Property evalMultiply(Numeric op1, Numeric op2) { if (op1 == null || op2 == null) { throw new PropertyException("Non numeric operand in multiplication"); } return new NumericProperty(op1.multiply(op2)); } private Property evalDivide(Numeric op1, Numeric op2) { if (op1 == null || op2 == null) { throw new PropertyException("Non numeric operand in division"); } return new NumericProperty(op1.divide(op2)); } private Property evalModulo(Number op1, Number op2) { if (op1 == null || op2 == null) { throw new PropertyException("Non number operand to modulo"); } return new NumberProperty(op1.DoubleValue() % op2.DoubleValue()); } private double ParseDouble(string s) { return Double.Parse(s, CultureInfo.InvariantCulture.NumberFormat); } } }
// This file was created automatically, do not modify the contents of this file. // ReSharper disable InvalidXmlDocComment // ReSharper disable InconsistentNaming // ReSharper disable CheckNamespace // ReSharper disable MemberCanBePrivate.Global using System; using System.Runtime.InteropServices; // Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Engine\Classes\GameFramework\GameState.h:16 namespace UnrealEngine { [ManageType("ManageGameState")] public partial class ManageGameState : AGameState, IManageWrapper { public ManageGameState(IntPtr adress) : base(adress) { } #region DLLInmport [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGameState_DefaultTimer(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGameState_HandleLeavingMap(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGameState_HandleMatchHasEnded(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGameState_HandleMatchHasStarted(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGameState_HandleMatchIsWaitingToStart(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGameState_OnRep_ElapsedTime(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGameState_OnRep_MatchState(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGameState_HandleBeginPlay(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGameState_OnRep_GameModeClass(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGameState_OnRep_ReplicatedHasBegunPlay(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGameState_OnRep_ReplicatedWorldTimeSeconds(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGameState_OnRep_SpectatorClass(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGameState_ReceivedGameModeClass(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGameState_ReceivedSpectatorClass(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGameState_SeamlessTravelTransitionCheckpoint(IntPtr self, bool bToTransitionMap); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGameState_UpdateServerTimeSeconds(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGameState_BeginPlay(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGameState_ClearCrossLevelReferences(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGameState_Destroyed(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGameState_ForceNetRelevant(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGameState_ForceNetUpdate(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGameState_GatherCurrentMovement(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGameState_InvalidateLightingCacheDetailed(IntPtr self, bool bTranslationOnly); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGameState_K2_DestroyActor(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGameState_LifeSpanExpired(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGameState_MarkComponentsAsPendingKill(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGameState_NotifyActorBeginCursorOver(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGameState_NotifyActorEndCursorOver(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGameState_OnRep_AttachmentReplication(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGameState_OnRep_Instigator(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGameState_OnRep_Owner(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGameState_OnRep_ReplicatedMovement(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGameState_OnRep_ReplicateMovement(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGameState_OnReplicationPausedChanged(IntPtr self, bool bIsReplicationPaused); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGameState_OutsideWorldBounds(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGameState_PostActorCreated(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGameState_PostInitializeComponents(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGameState_PostNetInit(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGameState_PostNetReceiveLocationAndRotation(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGameState_PostNetReceivePhysicState(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGameState_PostNetReceiveRole(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGameState_PostRegisterAllComponents(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGameState_PostUnregisterAllComponents(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGameState_PreInitializeComponents(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGameState_PreRegisterAllComponents(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGameState_PrestreamTextures(IntPtr self, float seconds, bool bEnableStreaming, int cinematicTextureGroups); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGameState_RegisterActorTickFunctions(IntPtr self, bool bRegister); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGameState_RegisterAllComponents(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGameState_ReregisterAllComponents(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGameState_RerunConstructionScripts(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGameState_Reset(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGameState_RewindForReplay(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGameState_SetActorHiddenInGame(IntPtr self, bool bNewHidden); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGameState_SetLifeSpan(IntPtr self, float inLifespan); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGameState_SetReplicateMovement(IntPtr self, bool bInReplicateMovement); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGameState_TearOff(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGameState_TeleportSucceeded(IntPtr self, bool bIsATest); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGameState_Tick(IntPtr self, float deltaSeconds); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGameState_TornOff(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGameState_UnregisterAllComponents(IntPtr self, bool bForReregister); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGameState_BeginDestroy(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGameState_FinishDestroy(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGameState_MarkAsEditorOnlySubobject(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGameState_PostCDOContruct(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGameState_PostEditImport(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGameState_PostInitProperties(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGameState_PostLoad(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGameState_PostNetReceive(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGameState_PostRepNotifies(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGameState_PostSaveRoot(IntPtr self, bool bCleanupIsRequired); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGameState_PreDestroyFromReplication(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGameState_PreNetReceive(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGameState_ShutdownAfterError(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGameState_CreateCluster(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGameState_OnClusterMarkedAsPendingKill(IntPtr self); #endregion #region Methods /// <summary> /// Called periodically, overridden by subclasses /// </summary> public override void DefaultTimer() => E__Supper__AGameState_DefaultTimer(this); /// <summary> /// Called when the match transitions to LeavingMap /// </summary> protected override void HandleLeavingMap() => E__Supper__AGameState_HandleLeavingMap(this); /// <summary> /// Called when the map transitions to WaitingPostMatch /// </summary> protected override void HandleMatchHasEnded() => E__Supper__AGameState_HandleMatchHasEnded(this); /// <summary> /// Called when the state transitions to InProgress /// </summary> protected override void HandleMatchHasStarted() => E__Supper__AGameState_HandleMatchHasStarted(this); /// <summary> /// Called when the state transitions to WaitingToStart /// </summary> protected override void HandleMatchIsWaitingToStart() => E__Supper__AGameState_HandleMatchIsWaitingToStart(this); public override void OnRep_ElapsedTime() => E__Supper__AGameState_OnRep_ElapsedTime(this); public override void OnRep_MatchState() => E__Supper__AGameState_OnRep_MatchState(this); /// <summary> /// Called by game mode to set the started play bool /// </summary> public override void HandleBeginPlay() => E__Supper__AGameState_HandleBeginPlay(this); protected override void OnRep_GameModeClass() => E__Supper__AGameState_OnRep_GameModeClass(this); protected override void OnRep_ReplicatedHasBegunPlay() => E__Supper__AGameState_OnRep_ReplicatedHasBegunPlay(this); protected override void OnRep_ReplicatedWorldTimeSeconds() => E__Supper__AGameState_OnRep_ReplicatedWorldTimeSeconds(this); protected override void OnRep_SpectatorClass() => E__Supper__AGameState_OnRep_SpectatorClass(this); /// <summary> /// Called when the GameClass property is set (at startup for the server, after the variable has been replicated on clients) /// </summary> public override void ReceivedGameModeClass() => E__Supper__AGameState_ReceivedGameModeClass(this); /// <summary> /// Called when the SpectatorClass property is set (at startup for the server, after the variable has been replicated on clients) /// </summary> public override void ReceivedSpectatorClass() => E__Supper__AGameState_ReceivedSpectatorClass(this); /// <summary> /// Called during seamless travel transition twice (once when the transition map is loaded, once when destination map is loaded) /// </summary> public override void SeamlessTravelTransitionCheckpoint(bool bToTransitionMap) => E__Supper__AGameState_SeamlessTravelTransitionCheckpoint(this, bToTransitionMap); /// <summary> /// Called periodically to update ReplicatedWorldTimeSeconds /// </summary> protected override void UpdateServerTimeSeconds() => E__Supper__AGameState_UpdateServerTimeSeconds(this); /// <summary> /// Overridable native event for when play begins for this actor. /// </summary> protected override void BeginPlay() => E__Supper__AGameState_BeginPlay(this); /// <summary> /// Do anything needed to clear out cross level references; Called from ULevel::PreSave /// </summary> public override void ClearCrossLevelReferences() => E__Supper__AGameState_ClearCrossLevelReferences(this); /// <summary> /// Called when this actor is explicitly being destroyed during gameplay or in the editor, not called during level streaming or gameplay ending /// </summary> public override void Destroyed() => E__Supper__AGameState_Destroyed(this); /// <summary> /// Forces this actor to be net relevant if it is not already by default /// </summary> public override void ForceNetRelevant() => E__Supper__AGameState_ForceNetRelevant(this); /// <summary> /// Force actor to be updated to clients/demo net drivers /// </summary> public override void ForceNetUpdate() => E__Supper__AGameState_ForceNetUpdate(this); /// <summary> /// Fills ReplicatedMovement property /// </summary> public override void GatherCurrentMovement() => E__Supper__AGameState_GatherCurrentMovement(this); /// <summary> /// Invalidates anything produced by the last lighting build. /// </summary> public override void InvalidateLightingCacheDetailed(bool bTranslationOnly) => E__Supper__AGameState_InvalidateLightingCacheDetailed(this, bTranslationOnly); /// <summary> /// Destroy the actor /// </summary> public override void DestroyActor() => E__Supper__AGameState_K2_DestroyActor(this); /// <summary> /// Called when the lifespan of an actor expires (if he has one). /// </summary> public override void LifeSpanExpired() => E__Supper__AGameState_LifeSpanExpired(this); /// <summary> /// Called to mark all components as pending kill when the actor is being destroyed /// </summary> public override void MarkComponentsAsPendingKill() => E__Supper__AGameState_MarkComponentsAsPendingKill(this); /// <summary> /// Event when this actor has the mouse moved over it with the clickable interface. /// </summary> public override void NotifyActorBeginCursorOver() => E__Supper__AGameState_NotifyActorBeginCursorOver(this); /// <summary> /// Event when this actor has the mouse moved off of it with the clickable interface. /// </summary> public override void NotifyActorEndCursorOver() => E__Supper__AGameState_NotifyActorEndCursorOver(this); public override void OnRep_AttachmentReplication() => E__Supper__AGameState_OnRep_AttachmentReplication(this); public override void OnRep_Instigator() => E__Supper__AGameState_OnRep_Instigator(this); protected override void OnRep_Owner() => E__Supper__AGameState_OnRep_Owner(this); public override void OnRep_ReplicatedMovement() => E__Supper__AGameState_OnRep_ReplicatedMovement(this); public override void OnRep_ReplicateMovement() => E__Supper__AGameState_OnRep_ReplicateMovement(this); /// <summary> /// Called on the client when the replication paused value is changed /// </summary> public override void OnReplicationPausedChanged(bool bIsReplicationPaused) => E__Supper__AGameState_OnReplicationPausedChanged(this, bIsReplicationPaused); /// <summary> /// Called when the Actor is outside the hard limit on world bounds /// </summary> public override void OutsideWorldBounds() => E__Supper__AGameState_OutsideWorldBounds(this); /// <summary> /// Called when an actor is done spawning into the world (from UWorld::SpawnActor), both in the editor and during gameplay /// <para>For actors with a root component, the location and rotation will have already been set. </para> /// This is called before calling construction scripts, but after native components have been created /// </summary> public override void PostActorCreated() => E__Supper__AGameState_PostActorCreated(this); /// <summary> /// Allow actors to initialize themselves on the C++ side after all of their components have been initialized, only called during gameplay /// </summary> public override void PostInitializeComponents() => E__Supper__AGameState_PostInitializeComponents(this); /// <summary> /// Always called immediately after spawning and reading in replicated properties /// </summary> public override void PostNetInit() => E__Supper__AGameState_PostNetInit(this); /// <summary> /// Update location and rotation from ReplicatedMovement. Not called for simulated physics! /// </summary> public override void PostNetReceiveLocationAndRotation() => E__Supper__AGameState_PostNetReceiveLocationAndRotation(this); /// <summary> /// Update and smooth simulated physic state, replaces PostNetReceiveLocation() and PostNetReceiveVelocity() /// </summary> public override void PostNetReceivePhysicState() => E__Supper__AGameState_PostNetReceivePhysicState(this); /// <summary> /// Always called immediately after a new Role is received from the remote. /// </summary> public override void PostNetReceiveRole() => E__Supper__AGameState_PostNetReceiveRole(this); /// <summary> /// Called after all the components in the Components array are registered, called both in editor and during gameplay /// </summary> public override void PostRegisterAllComponents() => E__Supper__AGameState_PostRegisterAllComponents(this); /// <summary> /// Called after all currently registered components are cleared /// </summary> public override void PostUnregisterAllComponents() => E__Supper__AGameState_PostUnregisterAllComponents(this); /// <summary> /// Called right before components are initialized, only called during gameplay /// </summary> public override void PreInitializeComponents() => E__Supper__AGameState_PreInitializeComponents(this); /// <summary> /// Called before all the components in the Components array are registered, called both in editor and during gameplay /// </summary> public override void PreRegisterAllComponents() => E__Supper__AGameState_PreRegisterAllComponents(this); /// <summary> /// Calls PrestreamTextures() for all the actor's meshcomponents. /// </summary> /// <param name="seconds">Number of seconds to force all mip-levels to be resident</param> /// <param name="bEnableStreaming">Whether to start (true) or stop (false) streaming</param> /// <param name="cinematicTextureGroups">Bitfield indicating which texture groups that use extra high-resolution mips</param> public override void PrestreamTextures(float seconds, bool bEnableStreaming, int cinematicTextureGroups) => E__Supper__AGameState_PrestreamTextures(this, seconds, bEnableStreaming, cinematicTextureGroups); /// <summary> /// Virtual call chain to register all tick functions for the actor class hierarchy /// </summary> /// <param name="bRegister">true to register, false, to unregister</param> protected override void RegisterActorTickFunctions(bool bRegister) => E__Supper__AGameState_RegisterActorTickFunctions(this, bRegister); /// <summary> /// Ensure that all the components in the Components array are registered /// </summary> public override void RegisterAllComponents() => E__Supper__AGameState_RegisterAllComponents(this); /// <summary> /// Will reregister all components on this actor. Does a lot of work - should only really be used in editor, generally use UpdateComponentTransforms or MarkComponentsRenderStateDirty. /// </summary> public override void ReregisterAllComponents() => E__Supper__AGameState_ReregisterAllComponents(this); /// <summary> /// Rerun construction scripts, destroying all autogenerated components; will attempt to preserve the root component location. /// </summary> public override void RerunConstructionScripts() => E__Supper__AGameState_RerunConstructionScripts(this); /// <summary> /// Reset actor to initial state - used when restarting level without reloading. /// </summary> public override void Reset() => E__Supper__AGameState_Reset(this); /// <summary> /// Called on the actor before checkpoint data is applied during a replay. /// <para>Only called if bReplayRewindable is set. </para> /// </summary> public override void RewindForReplay() => E__Supper__AGameState_RewindForReplay(this); /// <summary> /// Sets the actor to be hidden in the game /// </summary> /// <param name="bNewHidden">Whether or not to hide the actor and all its components</param> public override void SetActorHiddenInGame(bool bNewHidden) => E__Supper__AGameState_SetActorHiddenInGame(this, bNewHidden); /// <summary> /// Set the lifespan of this actor. When it expires the object will be destroyed. If requested lifespan is 0, the timer is cleared and the actor will not be destroyed. /// </summary> public override void SetLifeSpan(float inLifespan) => E__Supper__AGameState_SetLifeSpan(this, inLifespan); /// <summary> /// Set whether this actor's movement replicates to network clients. /// </summary> /// <param name="bInReplicateMovement">Whether this Actor's movement replicates to clients.</param> public override void SetReplicateMovement(bool bInReplicateMovement) => E__Supper__AGameState_SetReplicateMovement(this, bInReplicateMovement); /// <summary> /// Networking - Server - TearOff this actor to stop replication to clients. Will set bTearOff to true. /// </summary> public override void TearOff() => E__Supper__AGameState_TearOff(this); /// <summary> /// Called from TeleportTo() when teleport succeeds /// </summary> public override void TeleportSucceeded(bool bIsATest) => E__Supper__AGameState_TeleportSucceeded(this, bIsATest); /// <summary> /// Function called every frame on this Actor. Override this function to implement custom logic to be executed every frame. /// <para>Note that Tick is disabled by default, and you will need to check PrimaryActorTick.bCanEverTick is set to true to enable it. </para> /// </summary> /// <param name="deltaSeconds">Game time elapsed during last frame modified by the time dilation</param> public override void Tick(float deltaSeconds) => E__Supper__AGameState_Tick(this, deltaSeconds); /// <summary> /// Networking - called on client when actor is torn off (bTearOff==true), meaning it's no longer replicated to clients. /// <para>@see bTearOff </para> /// </summary> public override void TornOff() => E__Supper__AGameState_TornOff(this); /// <summary> /// Unregister all currently registered components /// </summary> /// <param name="bForReregister">If true, RegisterAllComponents will be called immediately after this so some slow operations can be avoided</param> public override void UnregisterAllComponents(bool bForReregister) => E__Supper__AGameState_UnregisterAllComponents(this, bForReregister); /// <summary> /// Called before destroying the object. This is called immediately upon deciding to destroy the object, to allow the object to begin an /// <para>asynchronous cleanup process. </para> /// </summary> public override void BeginDestroy() => E__Supper__AGameState_BeginDestroy(this); /// <summary> /// Called to finish destroying the object. After UObject::FinishDestroy is called, the object's memory should no longer be accessed. /// <para>@warning Because properties are destroyed here, Super::FinishDestroy() should always be called at the end of your child class's FinishDestroy() method, rather than at the beginning. </para> /// </summary> public override void FinishDestroy() => E__Supper__AGameState_FinishDestroy(this); /// <summary> /// Called during subobject creation to mark this component as editor only, which causes it to get stripped in packaged builds /// </summary> public override void MarkAsEditorOnlySubobject() => E__Supper__AGameState_MarkAsEditorOnlySubobject(this); /// <summary> /// Called after the C++ constructor has run on the CDO for a class. This is an obscure routine used to deal with the recursion /// <para>in the construction of the default materials </para> /// </summary> public override void PostCDOContruct() => E__Supper__AGameState_PostCDOContruct(this); /// <summary> /// Called after importing property values for this object (paste, duplicate or .t3d import) /// <para>Allow the object to perform any cleanup for properties which shouldn't be duplicated or </para> /// are unsupported by the script serialization /// </summary> public override void PostEditImport() => E__Supper__AGameState_PostEditImport(this); /// <summary> /// Called after the C++ constructor and after the properties have been initialized, including those loaded from config. /// <para>This is called before any serialization or other setup has happened. </para> /// </summary> public override void PostInitProperties() => E__Supper__AGameState_PostInitProperties(this); /// <summary> /// Do any object-specific cleanup required immediately after loading an object. /// <para>This is not called for newly-created objects, and by default will always execute on the game thread. </para> /// </summary> public override void PostLoad() => E__Supper__AGameState_PostLoad(this); /// <summary> /// Called right after receiving a bunch /// </summary> public override void PostNetReceive() => E__Supper__AGameState_PostNetReceive(this); /// <summary> /// Called right after calling all OnRep notifies (called even when there are no notifies) /// </summary> public override void PostRepNotifies() => E__Supper__AGameState_PostRepNotifies(this); /// <summary> /// Called from within SavePackage on the passed in base/root object. /// <para>This function is called after the package has been saved and can perform cleanup. </para> /// </summary> /// <param name="bCleanupIsRequired">Whether PreSaveRoot dirtied state that needs to be cleaned up</param> public override void PostSaveRoot(bool bCleanupIsRequired) => E__Supper__AGameState_PostSaveRoot(this, bCleanupIsRequired); /// <summary> /// Called right before being marked for destruction due to network replication /// </summary> public override void PreDestroyFromReplication() => E__Supper__AGameState_PreDestroyFromReplication(this); /// <summary> /// Called right before receiving a bunch /// </summary> public override void PreNetReceive() => E__Supper__AGameState_PreNetReceive(this); /// <summary> /// After a critical error, perform any mission-critical cleanup, such as restoring the video mode orreleasing hardware resources. /// </summary> public override void ShutdownAfterError() => E__Supper__AGameState_ShutdownAfterError(this); /// <summary> /// Called after PostLoad to create UObject cluster /// </summary> public override void CreateCluster() => E__Supper__AGameState_CreateCluster(this); /// <summary> /// Called during Garbage Collection to perform additional cleanup when the cluster is about to be destroyed due to PendingKill flag being set on it. /// </summary> public override void OnClusterMarkedAsPendingKill() => E__Supper__AGameState_OnClusterMarkedAsPendingKill(this); #endregion public static implicit operator IntPtr(ManageGameState self) { return self?.NativePointer ?? IntPtr.Zero; } public static implicit operator ManageGameState(ObjectPointerDescription PtrDesc) { return NativeManager.GetWrapper<ManageGameState>(PtrDesc); } } }
using System; using System.Data; using System.Data.SqlClient; using System.Data.OleDb; namespace Epi.Data { /// <summary> /// A database-independent parameter that can be used with Epi Info data access queries /// </summary> public class QueryParameter : IDbDataParameter { #region Private Members private int size; private byte scale; private byte precision; private DbType dbType; private ParameterDirection direction; private bool isNullable; private string parameterName = string.Empty; private string sourceColumn = string.Empty; private DataRowVersion sourceVersion; private object parameterValue; #endregion #region Constructors /// <summary> /// Private constructor - not accessible /// </summary> private QueryParameter() { } /// <summary> /// Constructor for the class. Initializes a database parameter. /// </summary> /// <param name="paramName">Name of the parameter prefixed with a '@' symbol.</param> /// <param name="paramType">Generic type of the parameter.</param> /// <param name="paramValue">Value of the parameter.</param> public QueryParameter(string paramName, DbType paramType, object paramValue) { this.ParameterName = paramName; this.DbType = paramType; this.Value = paramValue; this.Direction = ParameterDirection.Input; this.SourceVersion = DataRowVersion.Default; } /// <summary> /// Constructor for the class. Initializes a database parameter. /// </summary> /// <param name="paramName">Name of the parameter prefixed with a '@' symbol.</param> /// <param name="paramType">Generic type of the parameter.</param> /// <param name="paramValue">Value of the parameter.</param> /// <param name="sourceCol">The name of the source column.</param> public QueryParameter(string paramName, DbType paramType,object paramValue, string sourceCol) { this.ParameterName = paramName; this.DbType = paramType; this.Value = paramValue; this.Direction = ParameterDirection.Input; this.SourceColumn = sourceCol; this.SourceVersion = DataRowVersion.Default; } /// <summary> /// Constructor for the class. Initializes a database parameter. /// </summary> /// <param name="paramName">Name of the parameter prefixed with a '@' symbol.</param> /// <param name="paramType">Generic type of the parameter.</param> /// <param name="paramValue">Value of the parameter.</param> public QueryParameter(string paramName, DbType paramType, object paramValue, int size) { this.ParameterName = paramName; this.DbType = paramType; this.Value = paramValue; this.Direction = ParameterDirection.Input; this.SourceVersion = DataRowVersion.Default; this.Size = size; } #endregion #region Public Properties /// <summary> /// Gets/sets the maximum size, in bytes, of the data within the column. /// </summary> public int Size { get { return this.size; } set { this.size = value; } } /// <summary> /// Gets/sets the number of decimal places to which the Value is resolved. /// </summary> public byte Scale { get { return this.scale; } set { this.scale = value; } } /// <summary> /// Gets/sets the maximum number of digits used to represent the Value property. /// </summary> public byte Precision { get { return this.precision; } set { this.precision = value; } } /// <summary> /// Gets/sets the DbType of the parameter. /// </summary> public System.Data.DbType DbType { get { return this.dbType; } set { this.dbType = value; } } /// <summary> /// Gets/sets a value indicating whether the parameter is input-only, output-only, bidirectional, or a stored procedure return value parameter. /// </summary> public ParameterDirection Direction { get { return this.direction; } set { this.direction = value; } } /// <summary> /// Gets/sets whether the parameter is nullable. /// </summary> public bool IsNullable { get { return this.isNullable; } set { this.isNullable = value; } } /// <summary> /// Gets/sets the name of the parameter. /// </summary> public string ParameterName { get { return this.parameterName; } set { this.parameterName = value; } } /// <summary> /// Gets/sets the name of the source column that is mapped to the DataSet and used for loading or returning the Value. /// </summary> public string SourceColumn { get { return this.sourceColumn; } set { this.sourceColumn = value; } } /// <summary> /// Gets/sets the DataRowVersion to use when loading the Value. /// </summary> public DataRowVersion SourceVersion { get { return this.sourceVersion; } set { this.sourceVersion = value; } } /// <summary> /// Gets/sets the value of the parameter. /// </summary> public object Value { get { return this.parameterValue; } set { this.parameterValue = value; } } #endregion } }
/* MIT License Copyright (c) 2017 Saied Zarrinmehr Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; using System.Runtime.InteropServices; using System.Windows.Interop; using SpatialAnalysis.Geometry; using SpatialAnalysis.CellularEnvironment; using System.Windows.Threading; using SpatialAnalysis.Miscellaneous; namespace SpatialAnalysis.Agents.Visualization.AgentTrailVisualization { /// <summary> /// Interaction logic for SetTrail.xaml /// </summary> public partial class SetTrail : Window { #region TrailParametersUpdated event definition // Create a custom routed event by first registering a RoutedEventID // This event uses the bubbling routing strategy public static readonly RoutedEvent TrailParametersUpdatedEvent = EventManager.RegisterRoutedEvent( "TrailParametersUpdated", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(SetTrail)); /// <summary> /// Called when trail parameters are updated /// </summary> public event RoutedEventHandler TrailParametersUpdated { add { AddHandler(TrailParametersUpdatedEvent, value); } remove { RemoveHandler(TrailParametersUpdatedEvent, value); } } // This method raises the TrailParametersUpdated event void raiseTrailParametersUpdatedEvent() { RoutedEventArgs newEventArgs = new RoutedEventArgs(SetTrail.TrailParametersUpdatedEvent); RaiseEvent(newEventArgs); } #endregion #region PointPerUniteOfLength Definition /// <summary> /// The point per unite of length property /// </summary> public static DependencyProperty PointPerUniteOfLengthProperty = DependencyProperty.Register("PointPerUniteOfLength", typeof(int), typeof(SetTrail), new FrameworkPropertyMetadata(5, SetTrail.PointPerUniteOfLengthPropertyChanged, SetTrail.PropertyCoerce)); /// <summary> /// Gets or sets the number of points per unite of length. /// </summary> /// <value>The length of the point per unite of.</value> public int PointPerUniteOfLength { get { return (int)GetValue(PointPerUniteOfLengthProperty); } set { SetValue(PointPerUniteOfLengthProperty, value); } } private static void PointPerUniteOfLengthPropertyChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args) { SetTrail createTrail = (SetTrail)obj; if ((int)args.NewValue != (int)args.OldValue) { createTrail.PointPerUniteOfLength = (int)args.NewValue; createTrail.raiseTrailParametersUpdatedEvent(); } } private static object PropertyCoerce(DependencyObject obj, object value) { return value; } #endregion #region TrailCurvature Definition public static DependencyProperty TrailCurvatureProperty = DependencyProperty.Register("TrailCurvature", typeof(double), typeof(SetTrail), new FrameworkPropertyMetadata(1.0d, SetTrail.TrailFreedomPropertyChanged, SetTrail.PropertyCoerce)); /// <summary> /// Gets or sets the trail freedom factor. /// </summary> /// <value>The trail freedom.</value> public double TrailCurvature { get { return (double)GetValue(TrailCurvatureProperty); } set { SetValue(TrailCurvatureProperty, value); } } private static void TrailFreedomPropertyChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args) { SetTrail createTrail = (SetTrail)obj; if ((double)args.NewValue != (double)args.OldValue) { createTrail.TrailCurvature = (double)args.NewValue; createTrail.raiseTrailParametersUpdatedEvent(); } } #endregion #region AgentsPerUniteOfLength Definition /// <summary> /// The number of agents per unite of length property /// </summary> public static DependencyProperty AgentsPerUniteOfLengthProperty = DependencyProperty.Register("AgentsPerUniteOfLength", typeof(int), typeof(SetTrail), new FrameworkPropertyMetadata(1, SetTrail.AgentsPerUniteOfLengthPropertyChanged, SetTrail.PropertyCoerce)); /// <summary> /// Gets or sets the number of subdivisions (i.e. agent locations) per unite of. /// </summary> /// <value>The length of the agents per unite of.</value> public int AgentsPerUniteOfLength { get { return (int)GetValue(AgentsPerUniteOfLengthProperty); } set { SetValue(AgentsPerUniteOfLengthProperty, value); } } private static void AgentsPerUniteOfLengthPropertyChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args) { SetTrail createTrail = (SetTrail)obj; if ((int)args.NewValue != (int)args.OldValue) { createTrail.AgentsPerUniteOfLength = (int)args.NewValue; createTrail.raiseTrailParametersUpdatedEvent(); } } #endregion private OSMDocument _host; /// <summary> /// Initializes a new instance of the <see cref="SetTrail"/> class. /// </summary> /// <param name="host">The document to which this class belongs.</param> public SetTrail(OSMDocument host) { InitializeComponent(); this._host = host; if (this._host.trailVisualization.AgentWalkingTrail != null) { this._smoothness.Value = this._host.trailVisualization.AgentWalkingTrail.Curvature; this._pointPerLengthUnite.SelectedValue = this._host.trailVisualization.AgentWalkingTrail.NumberOfPointsPerUniteOfLength; this._subdivision.SelectedValue = this._host.trailVisualization.AgentWalkingTrail.NumberOfPointsPerUniteOfLength; } this.Loaded += new RoutedEventHandler(CreateTrail_Loaded); this._closeBtm.Click += _closeBtm_Click; this._pointPerLengthUnite.SelectionChanged += _pointPerLengthUnite_SelectionChanged; this._smoothness.ValueChanged += _smoothness_ValueChanged; this._subdivision.SelectionChanged += _subdivision_SelectionChanged; } void _subdivision_SelectionChanged(object sender, SelectionChangedEventArgs e) { this.AgentsPerUniteOfLength = (int)this._subdivision.SelectedItem; } void _smoothness_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e) { if (e.NewValue != e.OldValue) { this.TrailCurvature = e.NewValue; } } void _pointPerLengthUnite_SelectionChanged(object sender, SelectionChangedEventArgs e) { this.PointPerUniteOfLength = (int)this._pointPerLengthUnite.SelectedItem; } void _closeBtm_Click(object sender, RoutedEventArgs e) { this._closeBtm.Click -= _closeBtm_Click; BindingOperations.ClearBinding(this._export, GroupBox.IsEnabledProperty); BindingOperations.ClearBinding(this._edit, GroupBox.IsEnabledProperty); this._host = null; this.Close(); } #region Hiding the close button private const int GWL_STYLE = -16; private const int WS_SYSMENU = 0x80000; [DllImport("user32.dll", SetLastError = true)] private static extern int GetWindowLong(IntPtr hWnd, int nIndex); [DllImport("user32.dll")] private static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong); #endregion void CreateTrail_Loaded(object sender, RoutedEventArgs e) { var hwnd = new WindowInteropHelper(this).Handle; SetWindowLong(hwnd, GWL_STYLE, GetWindowLong(hwnd, GWL_STYLE) & ~WS_SYSMENU); Binding bind = new Binding("WalkingTrail"); bind.Source = this._host.trailVisualization; bind.Mode = BindingMode.OneWay; bind.Converter = new ValueToBoolConverter(); this._export.SetBinding(GroupBox.IsEnabledProperty, bind); } } }
using LogicAppTemplate.Models; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; using System.IO; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace LogicAppTemplate { public class TemplateGenerator { private DeploymentTemplate template; private JObject workflowTemplateReference; private string LogicAppResourceGroup; private bool stripPassword = false; IResourceCollector resourceCollector; private string SubscriptionId; private string ResourceGroup; private string LogicApp; private string IntegrationAccountId; private bool extractIntegrationAccountArtifacts = false; private bool disabledState = false; public TemplateGenerator(string LogicApp, string SubscriptionId, string ResourceGroup, IResourceCollector resourceCollector, bool stripPassword = false, bool disabledState = false) { this.SubscriptionId = SubscriptionId; this.ResourceGroup = ResourceGroup; this.LogicApp = LogicApp; this.resourceCollector = resourceCollector; this.stripPassword = stripPassword; this.disabledState = disabledState; template = JsonConvert.DeserializeObject<DeploymentTemplate>(GetResourceContent("LogicAppTemplate.Templates.starterTemplate.json")); } private string GetResourceContent(string resourceName) { var assembly = System.Reflection.Assembly.GetExecutingAssembly(); using (Stream stream = assembly.GetManifestResourceStream(resourceName)) using (StreamReader reader = new StreamReader(stream)) { return reader.ReadToEnd(); } } public bool DiagnosticSettings { get; set; } public bool IncludeInitializeVariable { get; set; } public bool FixedFunctionAppName { get; set; } public bool GenerateHttpTriggerUrlOutput { get; set; } public bool ForceManagedIdentity { get; set; } public bool DisableConnectionsOutput { get; set; } public bool DisableTagParameters { get; set; } public bool DisableFunctionNameParameters { get; set; } public bool IncludeEvaluatedRecurrence { get; set; } public bool SkipOauthConnectionAuthorization { get; set; } public bool UseServiceBusDisplayName { get; set; } public bool OnlyParameterizeConnections = false; public async Task<JObject> GenerateTemplate() { JObject _definition = await resourceCollector.GetResource($"https://management.azure.com/subscriptions/{SubscriptionId}/resourceGroups/{ResourceGroup}/providers/Microsoft.Logic/workflows/{LogicApp}", "2016-06-01"); return await generateDefinition(_definition, !DisableConnectionsOutput); } public async Task<JObject> generateDefinition(JObject definition, bool generateConnection = true) { var rid = new AzureResourceId(definition.Value<string>("id")); LogicAppResourceGroup = rid.ResourceGroupName; //Manage Integration account if (definition["properties"]["integrationAccount"] == null) { ((JObject)template.resources[0]["properties"]).Remove("integrationAccount"); template.parameters.Remove("IntegrationAccountName"); template.parameters.Remove("IntegrationAccountResourceGroupName"); } else { template.parameters["IntegrationAccountName"]["defaultValue"] = definition["properties"]["integrationAccount"]["name"]; IntegrationAccountId = definition["properties"]["integrationAccount"].Value<string>("id"); var IntegrationAccountAzureResourceId = new AzureResourceId(IntegrationAccountId); if (IntegrationAccountAzureResourceId.ResourceGroupName.ToLower() != rid.ResourceGroupName.ToLower()) { template.parameters["IntegrationAccountResourceGroupName"]["defaultValue"] = IntegrationAccountAzureResourceId.ResourceGroupName; } } //ISE if (definition["properties"]["integrationServiceEnvironment"] == null) { ((JObject)template.resources[0]["properties"]).Remove("integrationServiceEnvironment"); template.parameters.Remove("integrationServiceEnvironmentName"); template.parameters.Remove("integrationServiceEnvironmentResourceGroupName"); } else { template.parameters["integrationServiceEnvironmentName"]["defaultValue"] = definition["properties"]["integrationServiceEnvironment"]["name"]; AzureResourceId iseId = new AzureResourceId(definition["properties"]["integrationServiceEnvironment"].Value<string>("id")); template.parameters["integrationServiceEnvironmentResourceGroupName"]["defaultValue"] = iseId.ResourceGroupName; } if (disabledState) { ((JObject)template.resources[0]["properties"]).Add("state", "Disabled"); } template.parameters["logicAppName"]["defaultValue"] = definition.Value<string>("name"); workflowTemplateReference = template.resources.Where(t => ((string)t["type"]) == "Microsoft.Logic/workflows").FirstOrDefault(); // WriteVerbose("Upgrading connectionId paramters..."); var modifiedDefinition = definition["properties"]["definition"].ToString().Replace(@"['connectionId']", @"['connectionId']"); // WriteVerbose("Removing API Host references..."); var def = JObject.Parse(modifiedDefinition); //try fixing all properties that start with before handling connections etc[ var ll = def.Value<JObject>("actions").Descendants().Where(dd => dd.Type == JTokenType.String && dd.Value<string>().StartsWith("[") && dd.Value<string>().EndsWith("]")).ToList(); for (int i = 0; i < ll.Count(); i++) { var tofix = ll[i]; var newValue = "[" + tofix.Value<string>(); if (tofix.Parent.Type == JTokenType.Property) { (tofix.Parent as JProperty).Value = newValue; } else { var parent = tofix.Parent; tofix.Remove(); parent.Add(newValue); } } workflowTemplateReference["properties"]["definition"] = handleActions(def, (JObject)definition["properties"]["parameters"]); if (definition.ContainsKey("tags")) { JToken tags = await HandleTags(definition); if (tags.HasValues) { workflowTemplateReference.Add("tags", tags); } } // Diagnostic Settings if (DiagnosticSettings) { JToken resources = await handleDiagnosticSettings(definition); ((JArray)workflowTemplateReference["resources"]).Merge(resources); } // Remove resources if empty if (((JArray)workflowTemplateReference["resources"]).Count == 0) { workflowTemplateReference.Remove("resources"); } JObject connections = (JObject)definition["properties"]["parameters"]["$connections"]; foreach (JProperty parameter in workflowTemplateReference["properties"]["definition"]["parameters"]) { if (!parameter.Name.StartsWith("$")) { var name = "param" + parameter.Name; template.parameters.Add(name, JObject.FromObject(new { type = parameter.Value["type"].Value<string>().ToLower(), defaultValue = (parameter.Value["type"].Value<string>().ToLower() == "securestring") ? string.Empty : parameter.Value["defaultValue"] })); parameter.Value["defaultValue"] = "[parameters('" + name + "')]"; } } var managedIdentity = (JObject)definition["identity"]; if (ForceManagedIdentity || (managedIdentity != null && managedIdentity.Value<string>("type") == "SystemAssigned")) { template.resources[0].Add("identity", JObject.Parse("{'type': 'SystemAssigned'}")); } else if (managedIdentity != null && managedIdentity.Value<string>("type") == "UserAssigned") { //Extract user assigned managed identity info var identities = ((JObject)managedIdentity["userAssignedIdentities"]).Properties().ToList(); var identity = new AzureResourceId(identities[0].Name); //Add ARM parameter to configure the user assigned identity template.parameters.Add(Constants.UserAssignedIdentityParameterName, JObject.FromObject(new { type = "string", defaultValue = identity.ResourceName })); //When the identity exists in a different resourcegroup add this as parameter and in the resourceId() function var identityResourceGroupAddtion = ""; if (LogicAppResourceGroup != identity.ResourceGroupName) { identityResourceGroupAddtion = $"parameters('{Constants.UserAssignedIdentityParameterName}_resourceGroup'),"; template.parameters.Add($"{Constants.UserAssignedIdentityParameterName}_resourceGroup", JObject.FromObject(new { type = "string", defaultValue = identity.ResourceGroupName })); } //Create identity object for ARM template var userAssignedIdentities = new JObject(); userAssignedIdentities.Add($"[resourceId({identityResourceGroupAddtion}'Microsoft.ManagedIdentity/userAssignedIdentities/', parameters('{Constants.UserAssignedIdentityParameterName}'))]", JObject.FromObject(new { })); var userAssignedIdentity = new JObject(); userAssignedIdentity.Add("type", "UserAssigned"); userAssignedIdentity.Add("userAssignedIdentities", userAssignedIdentities); //Add identity object to Logic App resource template.resources[0].Add("identity", userAssignedIdentity); } // WriteVerbose("Checking connections..."); if (connections == null) return JObject.FromObject(template); workflowTemplateReference["properties"]["parameters"]["$connections"] = new JObject(new JProperty("value", new JObject())); foreach (JProperty connectionProperty in connections["value"]) { string name = connectionProperty.Name; string connectionId = connectionProperty.First.Value<string>("connectionId"); string id = connectionProperty.First.Value<string>("id"); string connectionName = connectionProperty.First["connectionName"] != null ? connectionProperty.First.Value<string>("connectionName") : connectionId.Split('/').Last(); //fixes old templates where name sometimes is missing var connectionNameParam = AddTemplateParameter($"{connectionName}_name", "string", connectionName); AzureResourceId cid; // Check if id contains different parameter than connectionname var idarray = id.Split('/'); string candidate = idarray.Last(); string type = idarray[idarray.Count() - 2]; if (type.Equals("customApis")) { var idparam = AddTemplateParameter($"{connectionName}_api", "string", candidate); cid = apiIdTemplate(id, idparam); } else { cid = apiIdTemplate(id, connectionNameParam); } string concatedId = $"[concat('{cid.ToString()}')]"; workflowTemplateReference["properties"]["parameters"]["$connections"]["value"][name] = JObject.FromObject(new { id = concatedId, connectionId = $"[resourceId('Microsoft.Web/connections', parameters('{connectionNameParam}'))]", connectionName = $"[parameters('{connectionNameParam}')]" }); if (generateConnection) { //get api definition JObject apiResource = await resourceCollector.GetResource("https://management.azure.com" + id, "2016-06-01"); //get api instance data, sub,group,provider,name JObject apiResourceInstance = await resourceCollector.GetResource("https://management.azure.com" + connectionId, "2016-06-01"); //add depends on to make sure that the api connection is created before the Logic App ((JArray)workflowTemplateReference["dependsOn"]).Add($"[resourceId('Microsoft.Web/connections', parameters('{connectionNameParam}'))]"); // WriteVerbose($"Generating connection resource for {connectionName}...."); var connectionTemplate = generateConnectionTemplate(apiResource, apiResourceInstance, connectionName, concatedId, connectionNameParam); template.resources.Insert(1, connectionTemplate); } } // WriteVerbose("Finalizing Template..."); return JObject.FromObject(template); } private async Task<JToken> handleDiagnosticSettings(JObject definition) { JArray result = new JArray(); // Get diagnostic settings JObject resources = await resourceCollector.GetResource("https://management.azure.com" + definition.Value<string>("id") + "/providers/microsoft.insights/diagnosticSettings", "2021-05-01-preview"); foreach (JObject resourceProperty in resources["value"]) { string dsName = AddTemplateParameter(Constants.DsName, "string", resourceProperty["name"]); Match m = Regex.Match((string)resourceProperty["properties"]["workspaceId"], "resourceGroups/(.*)/providers/Microsoft.OperationalInsights/workspaces/(.*)", RegexOptions.IgnoreCase); string dsResourceGroup = AddTemplateParameter(Constants.DsResourceGroup, "string", m.Groups[1].Value); string dsWorkspaceId = AddTemplateParameter(Constants.DsWorkspaceName, "string", m.Groups[2].Value); string dsLogsEnabled = AddTemplateParameter(Constants.DsLogsEnabled, "bool", resourceProperty["properties"]["logs"][0]["enabled"]); string dsLogsRetentionPolicyEnabled = AddTemplateParameter(Constants.DsLogsRetentionPolicyEnabled, "bool", resourceProperty["properties"]["logs"][0]["retentionPolicy"]["enabled"]); string dsLogsRetentionPolicyDays = AddTemplateParameter(Constants.DsLogsRetentionPolicyDays, "int", resourceProperty["properties"]["logs"][0]["retentionPolicy"]["days"]); string dsMetricsEnabled = AddTemplateParameter(Constants.DsMetricsEnabled, "bool", resourceProperty["properties"]["metrics"][0]["enabled"]); string dsMetricsRetentionPolicyEnabled = AddTemplateParameter(Constants.DsMetricsRetentionPolicyEnabled, "bool", resourceProperty["properties"]["metrics"][0]["retentionPolicy"]["enabled"]); string dsMetricsRetentionPolicyDays = AddTemplateParameter(Constants.DsMetricsRetentionPolicyDays, "int", resourceProperty["properties"]["metrics"][0]["retentionPolicy"]["days"]); DiagnosticSettingsTemplate resource = new DiagnosticSettingsTemplate(dsName); resource.dependsOn.Add("[parameters('logicAppName')]"); result.Add(JObject.FromObject(resource)); } return result; } private AzureResourceId apiIdTemplate(string apiId, string connectionNameParameter) { var rid = new AzureResourceId(apiId); rid.SubscriptionId = "',subscription().subscriptionId,'"; if (apiId.Contains("/managedApis/")) { rid.ReplaceValueAfter("locations", "',parameters('logicAppLocation'),'"); } else { if (apiId.Contains("customApis")) { rid.ReplaceValueAfter("customApis", "',parameters('" + connectionNameParameter + "'),'"); } string resourcegroupValue = LogicAppResourceGroup == rid.ResourceGroupName ? "[resourceGroup().name]" : rid.ResourceGroupName; string resourcegroupParameterName = AddTemplateParameter(apiId.Split('/').Last() + "-ResourceGroup", "string", resourcegroupValue); rid.ResourceGroupName = $"',parameters('{resourcegroupParameterName}'),'"; } return rid; } private JToken handleActions(JObject definition, JObject parameters) { foreach (JProperty action in definition["actions"]) { var type = action.Value.SelectToken("type").Value<string>().ToLower(); //if workflow fix so links are dynamic. if (type == "workflow") { var curr = ((JObject)definition["actions"][action.Name]["inputs"]["host"]["workflow"]).Value<string>("id"); var wid = new AzureResourceId(curr); string resourcegroupValue = LogicAppResourceGroup == wid.ResourceGroupName ? "[resourceGroup().name]" : wid.ResourceGroupName; string resourcegroupParameterName = AddTemplateParameter(action.Name + "-ResourceGroup", "string", resourcegroupValue); string wokflowParameterName = AddTemplateParameter(action.Name + "-LogicAppName", "string", wid.ResourceName); string workflowid = $"[concat('/subscriptions/',subscription().subscriptionId,'/resourceGroups/',parameters('{resourcegroupParameterName}'),'/providers/Microsoft.Logic/workflows/',parameters('{wokflowParameterName}'))]"; definition["actions"][action.Name]["inputs"]["host"]["workflow"]["id"] = workflowid; } else if (type == "initializevariable" && IncludeInitializeVariable && definition["actions"][action.Name]["inputs"]["variables"][0]["value"] != null) { var variableType = definition["actions"][action.Name]["inputs"]["variables"][0]["type"]; string paramType = string.Empty; //missing securestring & secureObject switch (variableType.Value<string>()) { case "Array": case "Object": case "String": paramType = variableType.Value<string>().ToLower(); break; case "Boolean": paramType = "bool"; break; case "Float": paramType = "string"; break; case "Integer": paramType = "int"; break; default: paramType = "string"; break; } //Arrays and Objects can't be expressions if (definition["actions"][action.Name]["inputs"]["variables"][0]["value"].Type != JTokenType.Array && definition["actions"][action.Name]["inputs"]["variables"][0]["value"].Type != JTokenType.Object) { //If variable is an expression OR float, we need to change the type of the parameter to string if (definition["actions"][action.Name]["inputs"]["variables"][0].Value<string>("value").StartsWith("@") || variableType.Value<string>() == "Float") { definition["actions"][action.Name]["inputs"]["variables"][0]["value"] = "[parameters('" + AddTemplateParameter(action.Name + "-Value", "string", ((JObject)definition["actions"][action.Name]["inputs"]["variables"][0]).Value<string>("value")) + "')]"; } else { //Same as the one from in the outer if sentence definition["actions"][action.Name]["inputs"]["variables"][0]["value"] = "[parameters('" + AddTemplateParameter(action.Name + "-Value", paramType, definition["actions"][action.Name]["inputs"]["variables"][0]["value"]) + "')]"; } } else { definition["actions"][action.Name]["inputs"]["variables"][0]["value"] = "[parameters('" + AddTemplateParameter(action.Name + "-Value", paramType, definition["actions"][action.Name]["inputs"]["variables"][0]["value"]) + "')]"; } } else if (type == "apimanagement") { var apiId = ((JObject)definition["actions"][action.Name]["inputs"]["api"]).Value<string>("id"); var aaid = new AzureResourceId(apiId); aaid.SubscriptionId = "',subscription().subscriptionId,'"; aaid.ResourceGroupName = "', parameters('" + AddTemplateParameter("apimResourceGroup", "string", aaid.ResourceGroupName) + "'),'"; aaid.ReplaceValueAfter("service", "', parameters('" + AddTemplateParameter("apimInstanceName", "string", aaid.ValueAfter("service")) + "'),'"); aaid.ReplaceValueAfter("apis", "', parameters('" + AddTemplateParameter($"api_{aaid.ValueAfter("apis")}_name", "string", aaid.ValueAfter("apis")) + "'),'"); apiId = "[concat('" + aaid.ToString() + "')]"; definition["actions"][action.Name]["inputs"]["api"]["id"] = apiId; //handle subscriptionkey if not parematrized var subkey = ((JObject)definition["actions"][action.Name]["inputs"]).Value<string>("subscriptionKey"); if (subkey != null && !Regex.Match(subkey, @"parameters\('(.*)'\)").Success) { definition["actions"][action.Name]["inputs"]["subscriptionKey"] = "[parameters('" + AddTemplateParameter("apimSubscriptionKey", "string", subkey) + "')]"; } } else if (type == "if") { definition["actions"][action.Name] = handleActions(definition["actions"][action.Name].ToObject<JObject>(), parameters); //else if (definition["actions"][action.Name]["else"] != null && definition["actions"][action.Name]["else"]["actions"] != null) definition["actions"][action.Name]["else"] = handleActions(definition["actions"][action.Name]["else"].ToObject<JObject>(), parameters); } else if (type == "scope" || type == "foreach" || type == "until") { definition["actions"][action.Name] = handleActions(definition["actions"][action.Name].ToObject<JObject>(), parameters); } else if (type == "switch") { //handle default if exists if (definition["actions"][action.Name]["default"] != null && definition["actions"][action.Name]["default"]["actions"] != null) definition["actions"][action.Name]["default"] = handleActions(definition["actions"][action.Name]["default"].ToObject<JObject>(), parameters); foreach (var switchcase in definition["actions"][action.Name]["cases"].Children<JProperty>()) { definition["actions"][action.Name]["cases"][switchcase.Name] = handleActions(definition["actions"][action.Name]["cases"][switchcase.Name].ToObject<JObject>(), parameters); } } else if (type == "flatfiledecoding" || type == "flatfileencoding") { definition["actions"][action.Name]["inputs"]["integrationAccount"]["schema"]["name"] = "[parameters('" + AddTemplateParameter(action.Name + "-SchemaName", "string", ((JObject)definition["actions"][action.Name]["inputs"]["integrationAccount"]["schema"]).Value<string>("name")) + "')]"; } else if (type == "xslt" || type == "liquid") { var mapname = ((JObject)definition["actions"][action.Name]["inputs"]["integrationAccount"]["map"]).Value<string>("name"); var mapParameterName = AddTemplateParameter(action.Name + "-MapName", "string", mapname); definition["actions"][action.Name]["inputs"]["integrationAccount"]["map"]["name"] = "[parameters('" + mapParameterName + "')]"; } else if (type == "http") { //only add when not parameterized yet if (!Regex.IsMatch(((JObject)definition["actions"][action.Name]["inputs"]).Value<string>("uri"), @"parameters\('.*'\)")) definition["actions"][action.Name]["inputs"]["uri"] = "[parameters('" + AddTemplateParameter(action.Name + "-URI", "string", ((JObject)definition["actions"][action.Name]["inputs"]).Value<string>("uri")) + "')]"; var authenticationObj = (JObject)definition["actions"][action.Name]["inputs"]["authentication"]; if (authenticationObj != null) { var authType = authenticationObj.Value<string>("type"); if ("Basic".Equals(authType, StringComparison.CurrentCultureIgnoreCase)) { //only add when not parameterized yet if (!Regex.IsMatch(((JObject)definition["actions"][action.Name]["inputs"]["authentication"]).Value<string>("password"), @"parameters\('.*'\)")) definition["actions"][action.Name]["inputs"]["authentication"]["password"] = "[parameters('" + AddTemplateParameter(action.Name + "-Password", "string", ((JObject)definition["actions"][action.Name]["inputs"]["authentication"]).Value<string>("password")) + "')]"; //only add when not parameterized yet if (!Regex.IsMatch(((JObject)definition["actions"][action.Name]["inputs"]["authentication"]).Value<string>("username"), @"parameters\('.*'\)")) definition["actions"][action.Name]["inputs"]["authentication"]["username"] = "[parameters('" + AddTemplateParameter(action.Name + "-Username", "string", ((JObject)definition["actions"][action.Name]["inputs"]["authentication"]).Value<string>("username")) + "')]"; } else if ("ClientCertificate".Equals(authType, StringComparison.CurrentCultureIgnoreCase)) { definition["actions"][action.Name]["inputs"]["authentication"]["password"] = "[parameters('" + AddTemplateParameter(action.Name + "-Password", "string", ((JObject)definition["actions"][action.Name]["inputs"]["authentication"]).Value<string>("password")) + "')]"; definition["actions"][action.Name]["inputs"]["authentication"]["pfx"] = "[parameters('" + AddTemplateParameter(action.Name + "-Pfx", "string", ((JObject)definition["actions"][action.Name]["inputs"]["authentication"]).Value<string>("pfx")) + "')]"; } else if ("ActiveDirectoryOAuth".Equals(authType, StringComparison.CurrentCultureIgnoreCase)) { //only add when not parameterized yet if (!Regex.IsMatch(((JObject)definition["actions"][action.Name]["inputs"]["authentication"]).Value<string>("audience"), @"parameters\('.*'\)")) definition["actions"][action.Name]["inputs"]["authentication"]["audience"] = "[parameters('" + AddTemplateParameter(action.Name + "-Audience", "string", ((JObject)definition["actions"][action.Name]["inputs"]["authentication"]).Value<string>("audience")) + "')]"; definition["actions"][action.Name]["inputs"]["authentication"]["authority"] = "[parameters('" + AddTemplateParameter(action.Name + "-Authority", "string", (((JObject)definition["actions"][action.Name]["inputs"]["authentication"]).Value<string>("authority")) ?? "") + "')]"; definition["actions"][action.Name]["inputs"]["authentication"]["clientId"] = "[parameters('" + AddTemplateParameter(action.Name + "-ClientId", "string", ((JObject)definition["actions"][action.Name]["inputs"]["authentication"]).Value<string>("clientId")) + "')]"; definition["actions"][action.Name]["inputs"]["authentication"]["secret"] = "[parameters('" + AddTemplateParameter(action.Name + "-Secret", "string", ((JObject)definition["actions"][action.Name]["inputs"]["authentication"]).Value<string>("secret")) + "')]"; definition["actions"][action.Name]["inputs"]["authentication"]["tenant"] = "[parameters('" + AddTemplateParameter(action.Name + "-Tenant", "string", ((JObject)definition["actions"][action.Name]["inputs"]["authentication"]).Value<string>("tenant")) + "')]"; } else if ("Raw".Equals(authType, StringComparison.CurrentCultureIgnoreCase)) { definition["actions"][action.Name]["inputs"]["authentication"]["value"] = "[parameters('" + AddTemplateParameter(action.Name + "-Raw", "string", ((JObject)definition["actions"][action.Name]["inputs"]["authentication"]).Value<string>("value")) + "')]"; } else if ("ManagedServiceIdentity".Equals(authType, StringComparison.CurrentCultureIgnoreCase)) { var msiAudience = ((JObject)definition["actions"][action.Name]["inputs"]["authentication"]).Value<string>("audience"); //only add when not parameterized yet //audience is not mandatory! if (msiAudience != null && !Regex.IsMatch(msiAudience, @"parameters\('.*'\)")) { definition["actions"][action.Name]["inputs"]["authentication"]["audience"] = "[parameters('" + AddTemplateParameter(action.Name + "-Audience", "string", msiAudience) + "')]"; } if (definition["actions"][action.Name]["inputs"]["authentication"]["identity"] != null) { //When the identity exists in a different resourcegroup add this as parameter and in the resourceId() function var identityResource = new AzureResourceId(definition["actions"][action.Name]["inputs"]["authentication"]["identity"].Value<string>()); var identityResourceGroupAddtion = ""; if (LogicAppResourceGroup != identityResource.ResourceGroupName) { identityResourceGroupAddtion = $"parameters('{Constants.UserAssignedIdentityParameterName}_resourceGroup'),"; //template.parameters.Add($"{Constants.UserAssignedIdentityParameterName}_resourceGroup", JObject.FromObject(new { type = "string", defaultValue = identityResource.ResourceGroupName })); } //User Assigned Identity definition["actions"][action.Name]["inputs"]["authentication"]["identity"] = $"[resourceId({identityResourceGroupAddtion}'Microsoft.ManagedIdentity/userAssignedIdentities/', parameters('{Constants.UserAssignedIdentityParameterName}'))]"; } } } } else if (type == "function") { var curr = ((JObject)definition["actions"][action.Name]["inputs"]["function"]).Value<string>("id"); var faid = new AzureResourceId(curr); var resourcegroupValue = LogicAppResourceGroup == faid.ResourceGroupName ? "[resourceGroup().name]" : faid.ResourceGroupName; faid.SubscriptionId = "',subscription().subscriptionId,'"; faid.ResourceGroupName = "',parameters('" + AddTemplateParameter((FixedFunctionAppName ? "FunctionApp-" : action.Name + "-") + "ResourceGroup", "string", resourcegroupValue) + "'),'"; faid.ReplaceValueAfter("sites", "',parameters('" + AddTemplateParameter((FixedFunctionAppName ? "" : action.Name + "-") + "FunctionApp", "string", faid.ValueAfter("sites")) + "'),'"); if (DisableFunctionNameParameters) { faid.ReplaceValueAfter("functions", faid.ValueAfter("functions") + "'"); } else { faid.ReplaceValueAfter("functions", "',parameters('" + AddTemplateParameter((FixedFunctionAppName ? "" : action.Name + "-") + "FunctionName", "string", faid.ValueAfter("functions")) + "')"); } definition["actions"][action.Name]["inputs"]["function"]["id"] = "[concat('" + faid.ToString() + ")]"; } else { var api = action.Value.SelectToken("inputs.host.api"); if (api != null) ((JObject)definition["actions"][action.Name]["inputs"]["host"]).Remove("api"); //get the type: //handle connection var connection = action.Value.SelectToken("inputs.host.connection"); if (connection != null) { var connectioname = definition["actions"][action.Name]["inputs"]["host"]["connection"].Value<string>("name"); var getConnectionNameType = this.GetConnectionTypeName(connection, parameters); switch (getConnectionNameType) { case "filesystem": { var newValue = AddParameterForMetadataBase64((JObject)action.Value, action.Name + "-folderPath", action.Value["inputs"].Value<string>("path")); action.Value["inputs"]["path"] = newValue; break; } case "azuretables": { var inputs = action.Value.Value<JObject>("inputs"); var path = inputs.Value<string>("path"); var m = Regex.Match(path, @"/Tables/@{encodeURIComponent\('(.*)'\)"); if (m.Groups.Count > 1) { var tablename = m.Groups[1].Value; var param = AddTemplateParameter(action.Name + "-tablename", "string", tablename); inputs["path"] = "[concat('" + path.Replace($"'{tablename}'", $"', parameters('__apostrophe'), parameters('{param}'), parameters('__apostrophe'), '") + "')]"; AddTemplateParameter("__apostrophe", "string", "'"); } break; } case "dynamicsax": { var inputs = action.Value.Value<JObject>("inputs"); var path = inputs.Value<string>("path").Replace("'", "''"); var pathsubsets = path.Split('/'); var dataset = pathsubsets[2]; var m = Regex.Match(dataset, @"\(''(.*)''\)"); if (m.Groups.Count > 1) { var datasetName = m.Groups[1].Value; var param = AddTemplateParameter(action.Name + "-instance", "string", datasetName); inputs["path"] = "[concat('" + path.Replace($"''{datasetName}''", $"', parameters('__apostrophe'), parameters('{param}'), parameters('__apostrophe'), '") + "')]"; AddTemplateParameter("__apostrophe", "string", "'"); } break; } case "commondataservice": case "dynamicscrmonline": { var inputs = action.Value.Value<JObject>("inputs"); var path = inputs.Value<string>("path").Replace("'", "''"); var pathsubsets = Regex.Split(path, "(?<!/)/(?!/)"); var dataset = ""; var datasetIndex = Array.FindIndex(pathsubsets, pathsubset => pathsubset == "datasets") + 1; if (datasetIndex < pathsubsets.Length) { dataset = pathsubsets[datasetIndex]; } var m = Regex.Match(dataset, @"\(''(.*)''\)"); if (m.Groups.Count > 1) { var datasetName = m.Groups[1].Value; var param = AddTemplateParameter(action.Name + "-environment", "string", datasetName); inputs["path"] = "[concat('" + path.Replace($"''{datasetName}''", $"', parameters('__apostrophe'), parameters('{param}'), parameters('__apostrophe'), '") + "')]"; AddTemplateParameter("__apostrophe", "string", "'"); } break; } case "azureblob": { var newValue = AddParameterForMetadataBase64((JObject)action.Value, action.Name + "-path", action.Value["inputs"].Value<string>("path")); action.Value["inputs"]["path"] = newValue; break; } case "azurequeues": { var inputs = action.Value.Value<JObject>("inputs"); var path = inputs.Value<string>("path"); var m = Regex.Match(path, @"/@{encodeURIComponent\('(.*)'\)"); if (m.Groups.Count > 1) { var queuename = m.Groups[1].Value; var param = AddTemplateParameter(action.Name + "-queuename", "string", queuename); inputs["path"] = "[concat('" + path.Replace("'", "''").Replace($"'{queuename}'", $"'', parameters('{param}'), ''") + "')]"; } break; } case "azuredatafactory": { AddTemplateParameter("__apostrophe", "string", "'"); var path = action.Value["inputs"].Value<string>("path"); var splittedPath = path.Split('/'); splittedPath[2] = "@{encodeURIComponent(', parameters('__apostrophe'),subscription().subscriptionId, parameters('__apostrophe'),')}"; var rgMatch = Regex.Match(splittedPath[4], "('(?<name>.*)')"); var rgName = rgMatch.Groups["name"].Value; AddTemplateParameter("__apostrophe", "string", "'"); splittedPath[4] = "@{encodeURIComponent(', parameters('__apostrophe'),parameters('" + AddTemplateParameter(action.Name + "_ADF__ResourceGroup", "string", rgName) + "'), parameters('__apostrophe'),')}"; var adfMatch = Regex.Match(splittedPath[8], "('(?<name>.*)')"); var adfName = adfMatch.Groups["name"].Value; splittedPath[8] = "@{encodeURIComponent(', parameters('__apostrophe'),parameters('" + AddTemplateParameter(action.Name + "_ADF__Instance", "string", adfName) + "'), parameters('__apostrophe'),')}"; var pipelineMatch = Regex.Match(splittedPath[10], "('(?<name>.*)')"); var pipelineName = pipelineMatch.Groups["name"].Value; splittedPath[10] = "@{encodeURIComponent(', parameters('__apostrophe'),parameters('" + AddTemplateParameter(action.Name + "_ADF__Pipeline", "string", pipelineName) + "'), parameters('__apostrophe'),')}"; //"/subscriptions/@{encodeURIComponent('04a4ca35-9cb5-4652-b245-f1782aa43b25')}/resourcegroups/@{encodeURIComponent('azne-per-adf-dev02-rg')}/providers/Microsoft.DataFactory/factories/@{encodeURIComponent('azne-per-adf-dev02')}/pipelines/@{encodeURIComponent('INT159-FinancialData-Cognos')}/CreateRun", //replace for gui action.Value["inputs"]["path"] = "[concat('" + string.Join("/", splittedPath) + "')]"; break; } } } } } //when in if statements triggers is not there if (definition["triggers"] != null) { foreach (JProperty trigger in definition["triggers"]) { //handle api var api = trigger.Value.SelectToken("inputs.host.api"); if (api != null) ((JObject)definition["triggers"][trigger.Name]["inputs"]["host"]).Remove("api"); //handle connection var connection = trigger.Value.SelectToken("inputs.host.connection"); if (connection != null) { var getConnectionNameType = this.GetConnectionTypeName(connection, parameters); switch (getConnectionNameType) { case "filesystem": { try { var newValue = AddParameterForMetadataBase64((JObject)trigger.Value, trigger.Name + "-folderPath", trigger.Value["inputs"]["queries"].Value<string>("folderId")); trigger.Value["inputs"]["queries"]["folderId"] = newValue; } catch (FormatException ex) { //folderid is not a valid base64 so we are skipping it for now /*var path = ((JProperty)meta.First).Value.ToString(); var param = AddTemplateParameter(trigger.Name + "-folderPath","string",path); meta[((JProperty)meta.First).Name] = $"[parameters('{param}')]";*/ } break; } case "dynamicsax": { var inputs = trigger.Value.Value<JObject>("inputs"); var path = inputs.Value<string>("path").Replace("'", "''"); var pathsubsets = path.Split('/'); var dataset = pathsubsets[2]; var m = Regex.Match(dataset, @"\(''(.*)''\)"); if (m.Groups.Count > 1) { var datasetName = m.Groups[1].Value; var param = AddTemplateParameter(trigger.Name + "-instance", "string", datasetName); inputs["path"] = "[concat('" + path.Replace($"''{datasetName}''", $"', parameters('__apostrophe'), parameters('{param}'), parameters('__apostrophe'), '") + "')]"; AddTemplateParameter("__apostrophe", "string", "'"); } break; } case "commondataservice": case "dynamicscrmonline": { var inputs = trigger.Value.Value<JObject>("inputs"); var path = inputs.Value<string>("path").Replace("'", "''"); var pathsubsets = Regex.Split(path, "(?<!/)/(?!/)"); var dataset = ""; var datasetIndex = Array.FindIndex(pathsubsets, pathsubset => pathsubset == "datasets") + 1; if (datasetIndex < pathsubsets.Length) { dataset = pathsubsets[datasetIndex]; } var m = Regex.Match(dataset, @"\(''(.*)''\)"); if (m.Groups.Count > 1) { var datasetName = m.Groups[1].Value; var param = AddTemplateParameter(trigger.Name + "-environment", "string", datasetName); inputs["path"] = "[concat('" + path.Replace($"''{datasetName}''", $"', parameters('__apostrophe'), parameters('{param}'), parameters('__apostrophe'), '") + "')]"; AddTemplateParameter("__apostrophe", "string", "'"); } break; } case "azureeventgrid": { var ri = new AzureResourceId(trigger.Value["inputs"]["body"]["properties"].Value<string>("topic")); AddTemplateParameter("__apostrophe", "string", "'"); var path = trigger.Value["inputs"].Value<string>("path"); path = path.Replace("'", "', parameters('__apostrophe'),'"); //replace for gui trigger.Value["inputs"]["path"] = "[concat('" + path.Replace($"'{ri.SubscriptionId}'", $"subscription().subscriptionId") + "')]"; ri.SubscriptionId = "',subscription().subscriptionId,'"; ri.ResourceGroupName = "',parameters('" + AddTemplateParameter(ri.ResourceName + "_ResourceGroup", "string", ri.ResourceGroupName) + "'),'"; ri.ResourceName = "',parameters('" + AddTemplateParameter(ri.ResourceName + "_Name", "string", ri.ResourceName) + "')"; //replace for topic trigger.Value["inputs"]["body"]["properties"]["topic"] = "[concat('" + ri.ToString() + ")]"; break; } } } //promote parameters for reccurence settings var recurrence = trigger.Value.SelectToken("recurrence"); if (recurrence != null) { definition["triggers"][trigger.Name]["recurrence"]["frequency"] = "[parameters('" + this.AddTemplateParameter(trigger.Name + "Frequency", "string", recurrence.Value<string>("frequency")) + "')]"; definition["triggers"][trigger.Name]["recurrence"]["interval"] = "[parameters('" + this.AddTemplateParameter(trigger.Name + "Interval", "int", new JProperty("defaultValue", recurrence.Value<int>("interval"))) + "')]"; if (recurrence["startTime"] != null) { string value = recurrence.Value<string>("startTime"); DateTime date; if (DateTime.TryParse(value, out date)) { value = date.ToString("O"); } definition["triggers"][trigger.Name]["recurrence"]["startTime"] = "[parameters('" + this.AddTemplateParameter(trigger.Name + "StartTime", "string", value) + "')]"; } if (recurrence["timeZone"] != null) { definition["triggers"][trigger.Name]["recurrence"]["timeZone"] = "[parameters('" + this.AddTemplateParameter(trigger.Name + "TimeZone", "string", recurrence.Value<string>("timeZone")) + "')]"; } if (recurrence["schedule"] != null) { definition["triggers"][trigger.Name]["recurrence"]["schedule"] = "[parameters('" + this.AddTemplateParameter(trigger.Name + "Schedule", "Object", new JProperty("defaultValue", recurrence["schedule"])) + "')]"; } } if (!IncludeEvaluatedRecurrence) { //remove the evaluatedRecurrence, we don't need it in the source var evaluatedRecurrence = trigger.Value.SelectToken("evaluatedRecurrence"); if (evaluatedRecurrence != null) { ((JObject)definition["triggers"][trigger.Name]).Remove("evaluatedRecurrence"); } } // http trigger if (trigger.Value.Value<string>("type") == "Request" && trigger.Value.Value<string>("kind") == "Http") { if (this.GenerateHttpTriggerUrlOutput) { JObject outputValue = JObject.FromObject(new { type = "string", value = $"[listCallbackURL(concat(resourceId(resourceGroup().name,'Microsoft.Logic/workflows/', parameters('logicAppName')), '/triggers/{trigger.Name}'), '2016-06-01').value]" }); this.template.outputs.Add("httpTriggerUrl", outputValue); } } } } return definition; } private string AddParameterForMetadataBase64(JObject action, string parametername, string currentValue) { var meta = action.Value<JObject>("metadata"); if (meta == null) return currentValue; var inputs = action.Value<JObject>("inputs"); var base64string = ""; if (meta.Children().Count() == 1) { base64string = ((JProperty)meta.First).Name; } else { foreach (var property in meta.Children<JProperty>()) { if (currentValue.Contains(property.Name)) { base64string = property.Name; break; } } } var param = AddTemplateParameter(parametername, "string", Base64Decode(base64string)); meta.RemoveAll(); meta.Add("[base64(parameters('" + param + "'))]", JToken.Parse("\"[parameters('" + param + "')]\"")); if (currentValue == base64string) { return $"[base64(parameters('{param}'))]"; } var replaced = currentValue.Replace("'", "''").Replace($"{base64string}", $"', base64(parameters('{param}')), '"); var newValue = $"[concat('{replaced}')]"; //AddTemplateParameter("__apostrophe", "string", "'"); return newValue; } private string Base64Decode(string base64string) { return Encoding.UTF8.GetString(Convert.FromBase64String(base64string)); } private string GetConnectionTypeName(JToken ConnectionToken, JObject parameters) { //try to find the connection and understand special handling var name = ConnectionToken.Value<string>("name"); if (name != null && name.StartsWith("@parameters('$connections')")) { var match = Regex.Match(name, @"@parameters\('\$connections'\)\['(?<connectionname>\w*)'"); if (match.Success) { var path = "$connections.value." + match.Groups["connectionname"].Value; var paramConnection = parameters.SelectToken(path); if (paramConnection != null) { //if filesystem the path is base64 necoded and need to be set as parameter var id = paramConnection.Value<string>("id"); if (!string.IsNullOrEmpty(id)) return id.Split('/').Last(); } } } return null; } private string AddTemplateParameter(string paramname, string type, string defaultvalue) { return AddTemplateParameter(paramname, type, new JProperty("defaultValue", defaultvalue)); } private string AddTemplateParameter(string paramname, string type, object defaultvalue) { return AddTemplateParameter(paramname, type, new JProperty("defaultValue", defaultvalue)); } private string AddTemplateParameter(string paramname, string type, JProperty defaultvalue) { if (this.stripPassword && (paramname.EndsWith("Username", StringComparison.InvariantCultureIgnoreCase) || paramname.EndsWith("Password", StringComparison.InvariantCultureIgnoreCase))) { defaultvalue.Value = "*Stripped*"; } string realParameterName = paramname; JObject param = new JObject(); param.Add("type", JToken.FromObject(type)); param.Add(defaultvalue); if (template.parameters[paramname] == null) { template.parameters.Add(paramname, param); } else { if (!template.parameters[paramname].Value<string>("defaultValue").Equals(defaultvalue.Value.ToString())) { foreach (var p in template.parameters) { if (p.Key.StartsWith(paramname)) { for (int i = 2; i < 100; i++) { realParameterName = paramname + i.ToString(); if (template.parameters[realParameterName] == null) { template.parameters.Add(realParameterName, param); return realParameterName; } } } } } } return realParameterName; } public JObject generateConnectionTemplate(JObject connectionResource, JObject connectionInstance, string connectionName, string concatedId, string connectionNameParam) { //create template var connectionTemplate = new Models.ConnectionTemplate(connectionNameParam, concatedId); //displayName connectionTemplate.properties.displayName = $"[parameters('{AddTemplateParameter(connectionName + "_displayName", "string", (string)connectionInstance["properties"]["displayName"])}')]"; JObject connectionParameters = new JObject(); bool useGateway = connectionInstance["properties"]?["parameterValueSet"]?["values"]?["gateway"] != null || connectionInstance["properties"]?["nonSecretParameterValues"]?["gateway"] != null; if (useGateway == false) { useGateway = connectionInstance["properties"]?["nonSecretParameterValues"]?["gateway"] != null; } var instanceResourceId = new AzureResourceId(connectionInstance.Value<string>("id")); //add all parameters if (connectionResource["properties"]["connectionParameters"] != null) { foreach (JProperty parameter in connectionResource["properties"]["connectionParameters"]) { if ((string)(parameter.Value)["type"] != "oauthSetting") { //we are not handling parameter gatewaySetting if ((string)parameter.Value["type"] == "gatewaySetting") continue; if (parameter.Value["uiDefinition"]["constraints"]["capability"] != null) { var match = parameter.Value["uiDefinition"]["constraints"]["capability"].FirstOrDefault(cc => (string)cc == "gateway" && useGateway || (string)cc == "cloud" && !useGateway); if (match == null) continue; } if (OnlyParameterizeConnections == false && (parameter.Name == "accessKey" && concatedId.EndsWith("/azureblob')]")) || parameter.Name == "sharedkey" && concatedId.EndsWith("/azuretables')]")) { //handle different resourceGroups connectionParameters.Add(parameter.Name, $"[listKeys(resourceId(parameters('{AddTemplateParameter(connectionName + "_resourceGroupName", "string", instanceResourceId.ResourceGroupName)}'),'Microsoft.Storage/storageAccounts', parameters('{connectionName}_accountName')), '2018-02-01').keys[0].value]"); } else if (OnlyParameterizeConnections == false && (parameter.Name == "sharedkey" && concatedId.EndsWith("/azurequeues')]"))) { connectionParameters.Add(parameter.Name, $"[listKeys(resourceId(parameters('{AddTemplateParameter(connectionName + "_resourceGroupName", "string", instanceResourceId.ResourceGroupName)}'),'Microsoft.Storage/storageAccounts', parameters('{connectionName}_storageaccount')), '2018-02-01').keys[0].value]"); } else if (OnlyParameterizeConnections == false && concatedId.EndsWith("/servicebus')]")) { var serviceBus_displayName = (string)connectionInstance["properties"]?["displayName"]; if (string.IsNullOrEmpty(serviceBus_displayName) || !UseServiceBusDisplayName) { serviceBus_displayName = "servicebus"; } var namespace_param = AddTemplateParameter($"{serviceBus_displayName}_namespace_name", "string", "REPLACE__servicebus_namespace"); var sb_resource_group_param = AddTemplateParameter($"{serviceBus_displayName}_resourceGroupName", "string", "REPLACE__servicebus_rg"); var servicebus_auth_name_param = AddTemplateParameter($"servicebus_accessKey_name", "string", "RootManageSharedAccessKey"); connectionParameters.Add(parameter.Name, $"[listkeys(resourceId(parameters('{sb_resource_group_param}'),'Microsoft.ServiceBus/namespaces/authorizationRules', parameters('{namespace_param}'), parameters('{servicebus_auth_name_param}')), '2017-04-01').primaryConnectionString]"); } else if (OnlyParameterizeConnections == false && concatedId.EndsWith("/azureeventgridpublish')]")) { var url = connectionInstance["properties"]["nonSecretParameterValues"].Value<string>("endpoint"); var location = connectionInstance.Value<string>("location"); url = url.Replace("https://", ""); var site = url.Substring(0, url.IndexOf(".")); var param = AddTemplateParameter($"{connectionInstance.Value<string>("name")}_instancename", "string", site); if (parameter.Name == "endpoint") { connectionParameters.Add(parameter.Name, $"[reference(resourceId(parameters('{AddTemplateParameter(connectionName + "_resourceGroupName", "string", instanceResourceId.ResourceGroupName)}'),'Microsoft.EventGrid/topics',parameters('{param}')),'2018-01-01').endpoint]"); } else if (parameter.Name == "api_key") { connectionParameters.Add(parameter.Name, $"[listKeys(resourceId(parameters('{AddTemplateParameter(connectionName + "_resourceGroupName", "string", instanceResourceId.ResourceGroupName)}'),'Microsoft.EventGrid/topics',parameters('{param}')),'2018-01-01').key1]"); } } //check for the existence of token:TenantId to determine the connectoins uses Oauth else if (SkipOauthConnectionAuthorization && parameter.Name.Equals("token:TenantId")) { //skip because otherwise authenticated connection has to be authenticated again. } else { //todo check this! object parameterValue = null; if (parameter.Name.Equals("token:TenantId")) { parameterValue = "[subscription().tenantId]"; } //check for hidden constraint do not skip token parameters for client credential services like eventgrid else if (!parameter.Name.StartsWith("token:") && (parameter.Value["uiDefinition"]["constraints"]["hidden"]?.Value<bool>() ?? false)) { continue; } else if (connectionInstance["properties"]["nonSecretParameterValues"] != null) { parameterValue = connectionInstance["properties"]["nonSecretParameterValues"][parameter.Name]; } else if (concatedId.EndsWith("/managedApis/sql')]") && parameter.Name == "authType") { var parameterName = connectionInstance["properties"]["parameterValueSet"]?["name"].Value<string>(); parameterValue = (parameterName == "windowsAuthentication") ? "windows" : "basic"; } else { parameterValue = connectionInstance["properties"]["parameterValueSet"]?["values"]?[parameter.Name]?["value"]; } var addedparam = AddTemplateParameter($"{connectionName}_{parameter.Name}", (string)(parameter.Value)["type"], parameterValue); connectionParameters.Add(parameter.Name, $"[parameters('{addedparam}')]"); //If has an enum if (parameter.Value["allowedValues"] != null) { var array = new JArray(); foreach (var allowedValue in parameter.Value["allowedValues"]) { array.Add(allowedValue["value"].Value<string>().Replace("none", "anonymous")); } template.parameters[addedparam]["allowedValues"] = array; if (parameter.Value["allowedValues"].Count() == 1) { template.parameters[addedparam]["defaultValue"] = parameter.Value["allowedValues"][0]["value"].Value<string>().Replace("none", "anonymous"); } } if (parameter.Value["uiDefinition"]["description"] != null) { //add meta data template.parameters[addedparam]["metadata"] = new JObject(); template.parameters[addedparam]["metadata"]["description"] = parameter.Value["uiDefinition"]["description"]; } } } } } if (useGateway) { string currentvalue = ""; if (connectionInstance["properties"]["nonSecretParameterValues"] != null) { currentvalue = (string)connectionInstance["properties"]["nonSecretParameterValues"]["gateway"]["id"]; } else if (connectionInstance["properties"]["parameterValueSet"]["values"]["gateway"]["value"].HasValues) { currentvalue = (string)connectionInstance["properties"]["parameterValueSet"]["values"]["gateway"]["value"]["id"]; } var rid = new AzureResourceId(currentvalue); var gatewayname = AddTemplateParameter($"{connectionName}_gatewayname", "string", rid.ResourceName); var resourcegroup = AddTemplateParameter($"{connectionName}_gatewayresourcegroup", "string", rid.ResourceGroupName); var gatewayobject = new JObject(); gatewayobject["id"] = $"[concat('/subscriptions/',subscription().subscriptionId,'/resourceGroups/',parameters('{resourcegroup}'),'/providers/Microsoft.Web/connectionGateways/',parameters('{gatewayname}'))]"; connectionParameters.Add("gateway", gatewayobject); useGateway = true; } //only fill connectionParameters when source not empty, otherwise saved credentials will be lost. if (connectionParameters.HasValues) connectionTemplate.properties.parameterValues = connectionParameters; return JObject.FromObject(connectionTemplate); } private async Task<JObject> HandleTags(JObject definition) { JObject result = new JObject(); foreach (var property in definition["tags"].ToObject<JObject>().Properties()) { if (DisableTagParameters) { result.Add(property.Name, property.Value.ToString()); } else { var parm = AddTemplateParameter(property.Name + "_Tag", "string", property.Value.ToString()); result.Add(property.Name, $"[parameters('{parm}')]"); } } return result; } public DeploymentTemplate GetTemplate() { return template; } } }
// 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.Diagnostics; using System.Net; using System.Runtime.InteropServices; using System.Threading; using Microsoft.Win32; namespace System.Net.Sockets { // BaseOverlappedAsyncResult // // This class is used to track state for async Socket operations such as the BeginSend, BeginSendTo, // BeginReceive, BeginReceiveFrom, BeginSendFile, and BeginAccept calls. internal partial class BaseOverlappedAsyncResult : ContextAwareResult { private int _cleanupCount; private SafeNativeOverlapped _nativeOverlapped; // The WinNT Completion Port callback. private static unsafe readonly IOCompletionCallback s_ioCallback = new IOCompletionCallback(CompletionPortCallback); internal BaseOverlappedAsyncResult(Socket socket, Object asyncState, AsyncCallback asyncCallback) : base(socket, asyncState, asyncCallback) { _cleanupCount = 1; if (NetEventSource.IsEnabled) NetEventSource.Info(this, socket); } // SetUnmanagedStructures // // This needs to be called for overlapped IO to function properly. // // Fills in overlapped Structures used in an async overlapped Winsock call. // These calls are outside the runtime and are unmanaged code, so we need // to prepare specific structures and ints that lie in unmanaged memory // since the overlapped calls may complete asynchronously. internal void SetUnmanagedStructures(object objectsToPin) { Socket s = (Socket)AsyncObject; // Bind the Win32 Socket Handle to the ThreadPool Debug.Assert(s != null, "m_CurrentSocket is null"); Debug.Assert(s.SafeHandle != null, "m_CurrentSocket.SafeHandle is null"); if (s.SafeHandle.IsInvalid) { throw new ObjectDisposedException(s.GetType().FullName); } ThreadPoolBoundHandle boundHandle = s.GetOrAllocateThreadPoolBoundHandle(); unsafe { NativeOverlapped* overlapped = boundHandle.AllocateNativeOverlapped(s_ioCallback, this, objectsToPin); _nativeOverlapped = new SafeNativeOverlapped(s.SafeHandle, overlapped); } if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"{boundHandle}::AllocateNativeOverlapped. return={_nativeOverlapped}"); } private static unsafe void CompletionPortCallback(uint errorCode, uint numBytes, NativeOverlapped* nativeOverlapped) { #if DEBUG DebugThreadTracking.SetThreadSource(ThreadKinds.CompletionPort); using (DebugThreadTracking.SetThreadKind(ThreadKinds.System)) { #endif BaseOverlappedAsyncResult asyncResult = (BaseOverlappedAsyncResult)ThreadPoolBoundHandle.GetNativeOverlappedState(nativeOverlapped); if (asyncResult.InternalPeekCompleted) { NetEventSource.Fail(null, $"asyncResult.IsCompleted: {asyncResult}"); } if (NetEventSource.IsEnabled) NetEventSource.Info(null, $"errorCode:{errorCode} numBytes:{numBytes} nativeOverlapped:{(IntPtr)nativeOverlapped}"); // Complete the IO and invoke the user's callback. SocketError socketError = (SocketError)errorCode; if (socketError != SocketError.Success && socketError != SocketError.OperationAborted) { // There are cases where passed errorCode does not reflect the details of the underlined socket error. // "So as of today, the key is the difference between WSAECONNRESET and ConnectionAborted, // .e.g remote party or network causing the connection reset or something on the local host (e.g. closesocket // or receiving data after shutdown (SD_RECV)). With Winsock/TCP stack rewrite in longhorn, there may // be other differences as well." Socket socket = asyncResult.AsyncObject as Socket; if (socket == null) { socketError = SocketError.NotSocket; } else if (socket.CleanedUp) { socketError = SocketError.OperationAborted; } else { try { // The async IO completed with a failure. // Here we need to call WSAGetOverlappedResult() just so GetLastSocketError() will return the correct error. SocketFlags ignore; bool success = Interop.Winsock.WSAGetOverlappedResult( socket.SafeHandle, asyncResult._nativeOverlapped, out numBytes, false, out ignore); if (!success) { socketError = SocketPal.GetLastSocketError(); } if (success) { NetEventSource.Fail(asyncResult, $"Unexpectedly succeeded. errorCode:{errorCode} numBytes:{numBytes}"); } } catch (ObjectDisposedException) { // CleanedUp check above does not always work since this code is subject to race conditions socketError = SocketError.OperationAborted; } } } // Set results and invoke callback asyncResult.CompletionCallback((int)numBytes, socketError); #if DEBUG } #endif } // Called either synchronously from SocketPal async routines or asynchronously via CompletionPortCallback above. private void CompletionCallback(int numBytes, SocketError socketError) { ReleaseUnmanagedStructures(); ErrorCode = (int)socketError; InvokeCallback(PostCompletion(numBytes)); } // The following property returns the Win32 unsafe pointer to // whichever Overlapped structure we're using for IO. internal SafeHandle OverlappedHandle { get { // On WinNT we need to use (due to the current implementation) // an Overlapped object in order to bind the socket to the // ThreadPool's completion port, so return the native handle return _nativeOverlapped == null ? SafeNativeOverlapped.Zero : _nativeOverlapped; } } // Check the result of the overlapped operation. // Handle synchronous success by completing the asyncResult here. // Handle synchronous failure by cleaning up and returning a SocketError. internal SocketError ProcessOverlappedResult(bool success, int bytesTransferred) { if (success) { // Synchronous success. Socket socket = (Socket)AsyncObject; if (socket.SafeHandle.SkipCompletionPortOnSuccess) { // The socket handle is configured to skip completion on success, // so we can complete this asyncResult right now. CompletionCallback(bytesTransferred, SocketError.Success); return SocketError.Success; } // Socket handle is going to post a completion to the completion port (may have done so already). // Return pending and we will continue in the completion port callback. return SocketError.IOPending; } // Get the socket error (which may be IOPending) SocketError errorCode = SocketPal.GetLastSocketError(); if (errorCode == SocketError.IOPending) { // Operation is pending. // We will continue when the completion arrives (may have already at this point). return SocketError.IOPending; } // Synchronous failure. // Release overlapped and pinned structures. ReleaseUnmanagedStructures(); return errorCode; } internal void ReleaseUnmanagedStructures() { if (Interlocked.Decrement(ref _cleanupCount) == 0) { ForceReleaseUnmanagedStructures(); } } protected override void Cleanup() { base.Cleanup(); // If we get all the way to here and it's still not cleaned up... if (_cleanupCount > 0 && Interlocked.Exchange(ref _cleanupCount, 0) > 0) { ForceReleaseUnmanagedStructures(); } } // Utility cleanup routine. Frees the overlapped structure. // This should be overridden to free pinned and unmanaged memory in the subclass. // It needs to also be invoked from the subclass. protected virtual void ForceReleaseUnmanagedStructures() { // Free the unmanaged memory if allocated. if (NetEventSource.IsEnabled) NetEventSource.Enter(this); _nativeOverlapped.Dispose(); _nativeOverlapped = null; GC.SuppressFinalize(this); } } }
// Copyright (C) 2014 dot42 // // Original filename: Javax.Security.Cert.cs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #pragma warning disable 1717 namespace Javax.Security.Cert { /// <summary> /// <para>Abstract class to represent identity certificates. It represents a way to verify the binding of a Principal and its public key. Examples are X.509, PGP, and SDSI. </para><para>Note: This package is provided only for compatibility reasons. It contains a simplified version of the java.security.cert package that was previously used by JSSE (Java SSL package). All applications that do not have to be compatible with older versions of JSSE (that is before Java SDK 1.5) should only use java.security.cert. </para> /// </summary> /// <java-name> /// javax/security/cert/Certificate /// </java-name> [Dot42.DexImport("javax/security/cert/Certificate", AccessFlags = 1057)] public abstract partial class Certificate /* scope: __dot42__ */ { /// <summary> /// <para>Creates a new <c> Certificate </c> . </para> /// </summary> [Dot42.DexImport("<init>", "()V", AccessFlags = 1)] public Certificate() /* MethodBuilder.Create */ { } /// <summary> /// <para>Compares the argument to this Certificate. If both have the same bytes they are assumed to be equal.</para><para><para>hashCode </para></para> /// </summary> /// <returns> /// <para><code>true</code> if <c> obj </c> is the same as this <c> Certificate </c> , <code>false</code> otherwise </para> /// </returns> /// <java-name> /// equals /// </java-name> [Dot42.DexImport("equals", "(Ljava/lang/Object;)Z", AccessFlags = 1)] public override bool Equals(object obj) /* MethodBuilder.Create */ { return default(bool); } /// <summary> /// <para>Returns an integer hash code for the receiver. Any two objects which return <code>true</code> when passed to <code>equals</code> must answer the same value for this method.</para><para><para>equals </para></para> /// </summary> /// <returns> /// <para>the receiver's hash </para> /// </returns> /// <java-name> /// hashCode /// </java-name> [Dot42.DexImport("hashCode", "()I", AccessFlags = 1)] public override int GetHashCode() /* MethodBuilder.Create */ { return default(int); } /// <summary> /// <para>Returns the encoded representation for this certificate.</para><para></para> /// </summary> /// <returns> /// <para>the encoded representation for this certificate. </para> /// </returns> /// <java-name> /// getEncoded /// </java-name> [Dot42.DexImport("getEncoded", "()[B", AccessFlags = 1025)] public abstract sbyte[] JavaGetEncoded() /* MethodBuilder.Create */ ; /// <summary> /// <para>Returns the encoded representation for this certificate.</para><para></para> /// </summary> /// <returns> /// <para>the encoded representation for this certificate. </para> /// </returns> /// <java-name> /// getEncoded /// </java-name> [Dot42.DexImport("getEncoded", "()[B", AccessFlags = 1025, IgnoreFromJava = true)] public abstract byte[] GetEncoded() /* MethodBuilder.Create */ ; /// <summary> /// <para>Verifies that this certificate was signed with the given public key.</para><para></para> /// </summary> /// <java-name> /// verify /// </java-name> [Dot42.DexImport("verify", "(Ljava/security/PublicKey;)V", AccessFlags = 1025)] public abstract void Verify(global::Java.Security.IPublicKey key) /* MethodBuilder.Create */ ; /// <summary> /// <para>Verifies that this certificate was signed with the given public key. Uses the signature algorithm given by the provider.</para><para></para> /// </summary> /// <java-name> /// verify /// </java-name> [Dot42.DexImport("verify", "(Ljava/security/PublicKey;Ljava/lang/String;)V", AccessFlags = 1025)] public abstract void Verify(global::Java.Security.IPublicKey key, string sigProvider) /* MethodBuilder.Create */ ; /// <summary> /// <para>Returns a string containing a concise, human-readable description of the receiver.</para><para></para> /// </summary> /// <returns> /// <para>a printable representation for the receiver. </para> /// </returns> /// <java-name> /// toString /// </java-name> [Dot42.DexImport("toString", "()Ljava/lang/String;", AccessFlags = 1025)] public override string ToString() /* MethodBuilder.Create */ { return default(string); } /// <summary> /// <para>Returns the public key corresponding to this certificate.</para><para></para> /// </summary> /// <returns> /// <para>the public key corresponding to this certificate. </para> /// </returns> /// <java-name> /// getPublicKey /// </java-name> [Dot42.DexImport("getPublicKey", "()Ljava/security/PublicKey;", AccessFlags = 1025)] public abstract global::Java.Security.IPublicKey GetPublicKey() /* MethodBuilder.Create */ ; /// <summary> /// <para>Returns the encoded representation for this certificate.</para><para></para> /// </summary> /// <returns> /// <para>the encoded representation for this certificate. </para> /// </returns> /// <java-name> /// getEncoded /// </java-name> public byte[] Encoded { [Dot42.DexImport("getEncoded", "()[B", AccessFlags = 1025, IgnoreFromJava = true)] get{ return GetEncoded(); } } /// <summary> /// <para>Returns the public key corresponding to this certificate.</para><para></para> /// </summary> /// <returns> /// <para>the public key corresponding to this certificate. </para> /// </returns> /// <java-name> /// getPublicKey /// </java-name> public global::Java.Security.IPublicKey PublicKey { [Dot42.DexImport("getPublicKey", "()Ljava/security/PublicKey;", AccessFlags = 1025)] get{ return GetPublicKey(); } } } /// <summary> /// <para>The base class for all <c> Certificate </c> related exceptions. </para><para>Note: This package is provided only for compatibility reasons. It contains a simplified version of the java.security.cert package that was previously used by JSSE (Java SSL package). All applications that do not have to be compatible with older versions of JSSE (that is before Java SDK 1.5) should only use java.security.cert. </para> /// </summary> /// <java-name> /// javax/security/cert/CertificateException /// </java-name> [Dot42.DexImport("javax/security/cert/CertificateException", AccessFlags = 33)] public partial class CertificateException : global::System.Exception /* scope: __dot42__ */ { /// <summary> /// <para>Creates a new <c> CertificateException </c> with the specified message.</para><para></para> /// </summary> [Dot42.DexImport("<init>", "(Ljava/lang/String;)V", AccessFlags = 1)] public CertificateException(string msg) /* MethodBuilder.Create */ { } /// <summary> /// <para>Creates a new <c> CertificateException </c> . </para> /// </summary> [Dot42.DexImport("<init>", "()V", AccessFlags = 1)] public CertificateException() /* MethodBuilder.Create */ { } } /// <summary> /// <para>The exception that is thrown when a <c> Certificate </c> has expired. </para><para>Note: This package is provided only for compatibility reasons. It contains a simplified version of the java.security.cert package that was previously used by JSSE (Java SSL package). All applications that do not have to be compatible with older versions of JSSE (that is before Java SDK 1.5) should only use java.security.cert. </para> /// </summary> /// <java-name> /// javax/security/cert/CertificateExpiredException /// </java-name> [Dot42.DexImport("javax/security/cert/CertificateExpiredException", AccessFlags = 33)] public partial class CertificateExpiredException : global::Javax.Security.Cert.CertificateException /* scope: __dot42__ */ { /// <summary> /// <para>Creates a new <c> CertificateExpiredException </c> with the specified message.</para><para></para> /// </summary> [Dot42.DexImport("<init>", "(Ljava/lang/String;)V", AccessFlags = 1)] public CertificateExpiredException(string msg) /* MethodBuilder.Create */ { } /// <summary> /// <para>Creates a new <c> CertificateExpiredException </c> . </para> /// </summary> [Dot42.DexImport("<init>", "()V", AccessFlags = 1)] public CertificateExpiredException() /* MethodBuilder.Create */ { } } /// <summary> /// <para>The exception that is thrown when a <c> Certificate </c> is not yet valid. </para><para>Note: This package is provided only for compatibility reasons. It contains a simplified version of the java.security.cert package that was previously used by JSSE (Java SSL package). All applications that do not have to be compatible with older versions of JSSE (that is before Java SDK 1.5) should only use java.security.cert. </para> /// </summary> /// <java-name> /// javax/security/cert/CertificateNotYetValidException /// </java-name> [Dot42.DexImport("javax/security/cert/CertificateNotYetValidException", AccessFlags = 33)] public partial class CertificateNotYetValidException : global::Javax.Security.Cert.CertificateException /* scope: __dot42__ */ { /// <summary> /// <para>Creates a new <c> CertificateNotYetValidException </c> with the specified message.</para><para></para> /// </summary> [Dot42.DexImport("<init>", "(Ljava/lang/String;)V", AccessFlags = 1)] public CertificateNotYetValidException(string msg) /* MethodBuilder.Create */ { } /// <summary> /// <para>Creates a new <c> CertificateNotYetValidException </c> . </para> /// </summary> [Dot42.DexImport("<init>", "()V", AccessFlags = 1)] public CertificateNotYetValidException() /* MethodBuilder.Create */ { } } /// <summary> /// <para>Abstract base class for X.509 certificates. </para><para>This represents a standard way for accessing the attributes of X.509 v1 certificates. </para><para>Note: This package is provided only for compatibility reasons. It contains a simplified version of the java.security.cert package that was previously used by JSSE (Java SSL package). All applications that do not have to be compatible with older versions of JSSE (that is before Java SDK 1.5) should only use java.security.cert. </para> /// </summary> /// <java-name> /// javax/security/cert/X509Certificate /// </java-name> [Dot42.DexImport("javax/security/cert/X509Certificate", AccessFlags = 1057)] public abstract partial class X509Certificate : global::Javax.Security.Cert.Certificate /* scope: __dot42__ */ { /// <summary> /// <para>Creates a new <c> X509Certificate </c> . </para> /// </summary> [Dot42.DexImport("<init>", "()V", AccessFlags = 1)] public X509Certificate() /* MethodBuilder.Create */ { } /// <summary> /// <para>Creates a new <c> X509Certificate </c> and initializes it from the specified input stream.</para><para></para> /// </summary> /// <returns> /// <para>the certificate initialized from the specified input stream </para> /// </returns> /// <java-name> /// getInstance /// </java-name> [Dot42.DexImport("getInstance", "(Ljava/io/InputStream;)Ljavax/security/cert/X509Certificate;", AccessFlags = 25)] public static global::Javax.Security.Cert.X509Certificate GetInstance(global::Java.Io.InputStream inStream) /* MethodBuilder.Create */ { return default(global::Javax.Security.Cert.X509Certificate); } /// <summary> /// <para>Creates a new <c> X509Certificate </c> and initializes it from the specified input stream.</para><para></para> /// </summary> /// <returns> /// <para>the certificate initialized from the specified input stream </para> /// </returns> /// <java-name> /// getInstance /// </java-name> [Dot42.DexImport("getInstance", "([B)Ljavax/security/cert/X509Certificate;", AccessFlags = 25)] public static global::Javax.Security.Cert.X509Certificate GetInstance(sbyte[] inStream) /* MethodBuilder.Create */ { return default(global::Javax.Security.Cert.X509Certificate); } /// <summary> /// <para>Creates a new <c> X509Certificate </c> and initializes it from the specified input stream.</para><para></para> /// </summary> /// <returns> /// <para>the certificate initialized from the specified input stream </para> /// </returns> /// <java-name> /// getInstance /// </java-name> [Dot42.DexImport("getInstance", "([B)Ljavax/security/cert/X509Certificate;", AccessFlags = 25, IgnoreFromJava = true)] public static global::Javax.Security.Cert.X509Certificate GetInstance(byte[] inStream) /* MethodBuilder.Create */ { return default(global::Javax.Security.Cert.X509Certificate); } /// <summary> /// <para>Checks whether the certificate is currently valid. </para><para>The validity defined in ASN.1:</para><para><pre> /// validity Validity /// /// Validity ::= SEQUENCE { /// notBefore CertificateValidityDate, /// notAfter CertificateValidityDate } /// /// CertificateValidityDate ::= CHOICE { /// utcTime UTCTime, /// generalTime GeneralizedTime } /// </pre></para><para></para> /// </summary> /// <java-name> /// checkValidity /// </java-name> [Dot42.DexImport("checkValidity", "()V", AccessFlags = 1025)] public abstract void CheckValidity() /* MethodBuilder.Create */ ; /// <summary> /// <para>Checks whether the certificate is valid at the specified date.</para><para><para>checkValidity() </para></para> /// </summary> /// <java-name> /// checkValidity /// </java-name> [Dot42.DexImport("checkValidity", "(Ljava/util/Date;)V", AccessFlags = 1025)] public abstract void CheckValidity(global::Java.Util.Date date) /* MethodBuilder.Create */ ; /// <summary> /// <para>Returns the certificates <c> version </c> (version number). </para><para>The version defined is ASN.1:</para><para><pre> /// Version ::= INTEGER { v1(0), v2(1), v3(2) } /// </pre></para><para></para> /// </summary> /// <returns> /// <para>the version number. </para> /// </returns> /// <java-name> /// getVersion /// </java-name> [Dot42.DexImport("getVersion", "()I", AccessFlags = 1025)] public abstract int GetVersion() /* MethodBuilder.Create */ ; /// <summary> /// <para>Returns the <c> serialNumber </c> of the certificate. </para><para>The ASN.1 definition of <c> serialNumber </c> :</para><para><pre> /// CertificateSerialNumber ::= INTEGER /// </pre></para><para></para> /// </summary> /// <returns> /// <para>the serial number. </para> /// </returns> /// <java-name> /// getSerialNumber /// </java-name> [Dot42.DexImport("getSerialNumber", "()Ljava/math/BigInteger;", AccessFlags = 1025)] public abstract global::Java.Math.BigInteger GetSerialNumber() /* MethodBuilder.Create */ ; /// <summary> /// <para>Returns the <c> issuer </c> (issuer distinguished name) as an implementation specific <c> Principal </c> object. </para><para>The ASN.1 definition of <c> issuer </c> :</para><para><pre> /// issuer Name /// /// Name ::= CHOICE { /// RDNSequence } /// /// RDNSequence ::= SEQUENCE OF RelativeDistinguishedName /// /// RelativeDistinguishedName ::= SET OF AttributeTypeAndValue /// /// AttributeTypeAndValue ::= SEQUENCE { /// type AttributeType, /// value AttributeValue } /// /// AttributeType ::= OBJECT IDENTIFIER /// /// AttributeValue ::= ANY DEFINED BY AttributeType /// </pre></para><para></para> /// </summary> /// <returns> /// <para>the <c> issuer </c> as an implementation specific <c> Principal </c> . </para> /// </returns> /// <java-name> /// getIssuerDN /// </java-name> [Dot42.DexImport("getIssuerDN", "()Ljava/security/Principal;", AccessFlags = 1025)] public abstract global::Java.Security.IPrincipal GetIssuerDN() /* MethodBuilder.Create */ ; /// <summary> /// <para>Returns the <c> subject </c> (subject distinguished name) as an implementation specific <c> Principal </c> object. </para><para>The ASN.1 definition of <c> subject </c> :</para><para><pre> /// subject Name /// /// Name ::= CHOICE { /// RDNSequence } /// /// RDNSequence ::= SEQUENCE OF RelativeDistinguishedName /// /// RelativeDistinguishedName ::= SET OF AttributeTypeAndValue /// /// AttributeTypeAndValue ::= SEQUENCE { /// type AttributeType, /// value AttributeValue } /// /// AttributeType ::= OBJECT IDENTIFIER /// /// AttributeValue ::= ANY DEFINED BY AttributeType /// </pre></para><para></para> /// </summary> /// <returns> /// <para>the <c> subject </c> (subject distinguished name). </para> /// </returns> /// <java-name> /// getSubjectDN /// </java-name> [Dot42.DexImport("getSubjectDN", "()Ljava/security/Principal;", AccessFlags = 1025)] public abstract global::Java.Security.IPrincipal GetSubjectDN() /* MethodBuilder.Create */ ; /// <summary> /// <para>Returns the <c> notBefore </c> date from the validity period of the certificate.</para><para></para> /// </summary> /// <returns> /// <para>the start of the validity period. </para> /// </returns> /// <java-name> /// getNotBefore /// </java-name> [Dot42.DexImport("getNotBefore", "()Ljava/util/Date;", AccessFlags = 1025)] public abstract global::Java.Util.Date GetNotBefore() /* MethodBuilder.Create */ ; /// <summary> /// <para>Returns the <c> notAfter </c> date of the validity period of the certificate.</para><para></para> /// </summary> /// <returns> /// <para>the end of the validity period. </para> /// </returns> /// <java-name> /// getNotAfter /// </java-name> [Dot42.DexImport("getNotAfter", "()Ljava/util/Date;", AccessFlags = 1025)] public abstract global::Java.Util.Date GetNotAfter() /* MethodBuilder.Create */ ; /// <summary> /// <para>Returns the name of the algorithm for the certificate signature.</para><para></para> /// </summary> /// <returns> /// <para>the signature algorithm name. </para> /// </returns> /// <java-name> /// getSigAlgName /// </java-name> [Dot42.DexImport("getSigAlgName", "()Ljava/lang/String;", AccessFlags = 1025)] public abstract string GetSigAlgName() /* MethodBuilder.Create */ ; /// <summary> /// <para>Returns the OID of the signature algorithm from the certificate.</para><para></para> /// </summary> /// <returns> /// <para>the OID of the signature algorithm. </para> /// </returns> /// <java-name> /// getSigAlgOID /// </java-name> [Dot42.DexImport("getSigAlgOID", "()Ljava/lang/String;", AccessFlags = 1025)] public abstract string GetSigAlgOID() /* MethodBuilder.Create */ ; /// <summary> /// <para>Returns the parameters of the signature algorithm in DER-encoded format.</para><para></para> /// </summary> /// <returns> /// <para>the parameters of the signature algorithm, or null if none are used. </para> /// </returns> /// <java-name> /// getSigAlgParams /// </java-name> [Dot42.DexImport("getSigAlgParams", "()[B", AccessFlags = 1025)] public abstract sbyte[] JavaGetSigAlgParams() /* MethodBuilder.Create */ ; /// <summary> /// <para>Returns the parameters of the signature algorithm in DER-encoded format.</para><para></para> /// </summary> /// <returns> /// <para>the parameters of the signature algorithm, or null if none are used. </para> /// </returns> /// <java-name> /// getSigAlgParams /// </java-name> [Dot42.DexImport("getSigAlgParams", "()[B", AccessFlags = 1025, IgnoreFromJava = true)] public abstract byte[] GetSigAlgParams() /* MethodBuilder.Create */ ; /// <summary> /// <para>Returns the certificates <c> version </c> (version number). </para><para>The version defined is ASN.1:</para><para><pre> /// Version ::= INTEGER { v1(0), v2(1), v3(2) } /// </pre></para><para></para> /// </summary> /// <returns> /// <para>the version number. </para> /// </returns> /// <java-name> /// getVersion /// </java-name> public int Version { [Dot42.DexImport("getVersion", "()I", AccessFlags = 1025)] get{ return GetVersion(); } } /// <summary> /// <para>Returns the <c> serialNumber </c> of the certificate. </para><para>The ASN.1 definition of <c> serialNumber </c> :</para><para><pre> /// CertificateSerialNumber ::= INTEGER /// </pre></para><para></para> /// </summary> /// <returns> /// <para>the serial number. </para> /// </returns> /// <java-name> /// getSerialNumber /// </java-name> public global::Java.Math.BigInteger SerialNumber { [Dot42.DexImport("getSerialNumber", "()Ljava/math/BigInteger;", AccessFlags = 1025)] get{ return GetSerialNumber(); } } /// <summary> /// <para>Returns the <c> issuer </c> (issuer distinguished name) as an implementation specific <c> Principal </c> object. </para><para>The ASN.1 definition of <c> issuer </c> :</para><para><pre> /// issuer Name /// /// Name ::= CHOICE { /// RDNSequence } /// /// RDNSequence ::= SEQUENCE OF RelativeDistinguishedName /// /// RelativeDistinguishedName ::= SET OF AttributeTypeAndValue /// /// AttributeTypeAndValue ::= SEQUENCE { /// type AttributeType, /// value AttributeValue } /// /// AttributeType ::= OBJECT IDENTIFIER /// /// AttributeValue ::= ANY DEFINED BY AttributeType /// </pre></para><para></para> /// </summary> /// <returns> /// <para>the <c> issuer </c> as an implementation specific <c> Principal </c> . </para> /// </returns> /// <java-name> /// getIssuerDN /// </java-name> public global::Java.Security.IPrincipal IssuerDN { [Dot42.DexImport("getIssuerDN", "()Ljava/security/Principal;", AccessFlags = 1025)] get{ return GetIssuerDN(); } } /// <summary> /// <para>Returns the <c> subject </c> (subject distinguished name) as an implementation specific <c> Principal </c> object. </para><para>The ASN.1 definition of <c> subject </c> :</para><para><pre> /// subject Name /// /// Name ::= CHOICE { /// RDNSequence } /// /// RDNSequence ::= SEQUENCE OF RelativeDistinguishedName /// /// RelativeDistinguishedName ::= SET OF AttributeTypeAndValue /// /// AttributeTypeAndValue ::= SEQUENCE { /// type AttributeType, /// value AttributeValue } /// /// AttributeType ::= OBJECT IDENTIFIER /// /// AttributeValue ::= ANY DEFINED BY AttributeType /// </pre></para><para></para> /// </summary> /// <returns> /// <para>the <c> subject </c> (subject distinguished name). </para> /// </returns> /// <java-name> /// getSubjectDN /// </java-name> public global::Java.Security.IPrincipal SubjectDN { [Dot42.DexImport("getSubjectDN", "()Ljava/security/Principal;", AccessFlags = 1025)] get{ return GetSubjectDN(); } } /// <summary> /// <para>Returns the <c> notBefore </c> date from the validity period of the certificate.</para><para></para> /// </summary> /// <returns> /// <para>the start of the validity period. </para> /// </returns> /// <java-name> /// getNotBefore /// </java-name> public global::Java.Util.Date NotBefore { [Dot42.DexImport("getNotBefore", "()Ljava/util/Date;", AccessFlags = 1025)] get{ return GetNotBefore(); } } /// <summary> /// <para>Returns the <c> notAfter </c> date of the validity period of the certificate.</para><para></para> /// </summary> /// <returns> /// <para>the end of the validity period. </para> /// </returns> /// <java-name> /// getNotAfter /// </java-name> public global::Java.Util.Date NotAfter { [Dot42.DexImport("getNotAfter", "()Ljava/util/Date;", AccessFlags = 1025)] get{ return GetNotAfter(); } } /// <summary> /// <para>Returns the name of the algorithm for the certificate signature.</para><para></para> /// </summary> /// <returns> /// <para>the signature algorithm name. </para> /// </returns> /// <java-name> /// getSigAlgName /// </java-name> public string SigAlgName { [Dot42.DexImport("getSigAlgName", "()Ljava/lang/String;", AccessFlags = 1025)] get{ return GetSigAlgName(); } } /// <summary> /// <para>Returns the OID of the signature algorithm from the certificate.</para><para></para> /// </summary> /// <returns> /// <para>the OID of the signature algorithm. </para> /// </returns> /// <java-name> /// getSigAlgOID /// </java-name> public string SigAlgOID { [Dot42.DexImport("getSigAlgOID", "()Ljava/lang/String;", AccessFlags = 1025)] get{ return GetSigAlgOID(); } } /// <summary> /// <para>Returns the parameters of the signature algorithm in DER-encoded format.</para><para></para> /// </summary> /// <returns> /// <para>the parameters of the signature algorithm, or null if none are used. </para> /// </returns> /// <java-name> /// getSigAlgParams /// </java-name> public byte[] SigAlgParams { [Dot42.DexImport("getSigAlgParams", "()[B", AccessFlags = 1025, IgnoreFromJava = true)] get{ return GetSigAlgParams(); } } } /// <summary> /// <para>The exception that is thrown when an error occurs while a <c> Certificate </c> is being encoded. </para><para>Note: This package is provided only for compatibility reasons. It contains a simplified version of the java.security.cert package that was previously used by JSSE (Java SSL package). All applications that do not have to be compatible with older versions of JSSE (that is before Java SDK 1.5) should only use java.security.cert. </para> /// </summary> /// <java-name> /// javax/security/cert/CertificateEncodingException /// </java-name> [Dot42.DexImport("javax/security/cert/CertificateEncodingException", AccessFlags = 33)] public partial class CertificateEncodingException : global::Javax.Security.Cert.CertificateException /* scope: __dot42__ */ { /// <summary> /// <para>Creates a new <c> CertificateEncodingException </c> with the specified message.</para><para></para> /// </summary> [Dot42.DexImport("<init>", "(Ljava/lang/String;)V", AccessFlags = 1)] public CertificateEncodingException(string msg) /* MethodBuilder.Create */ { } /// <summary> /// <para>Creates a new <c> CertificateEncodingException </c> . </para> /// </summary> [Dot42.DexImport("<init>", "()V", AccessFlags = 1)] public CertificateEncodingException() /* MethodBuilder.Create */ { } } /// <summary> /// <para>The exception that is thrown when a <c> Certificate </c> can not be parsed. </para><para>Note: This package is provided only for compatibility reasons. It contains a simplified version of the java.security.cert package that was previously used by JSSE (Java SSL package). All applications that do not have to be compatible with older versions of JSSE (that is before Java SDK 1.5) should only use java.security.cert. </para> /// </summary> /// <java-name> /// javax/security/cert/CertificateParsingException /// </java-name> [Dot42.DexImport("javax/security/cert/CertificateParsingException", AccessFlags = 33)] public partial class CertificateParsingException : global::Javax.Security.Cert.CertificateException /* scope: __dot42__ */ { /// <summary> /// <para>Creates a new <c> CertificateParsingException </c> with the specified message.</para><para></para> /// </summary> [Dot42.DexImport("<init>", "(Ljava/lang/String;)V", AccessFlags = 1)] public CertificateParsingException(string msg) /* MethodBuilder.Create */ { } /// <summary> /// <para>Creates a new <c> CertificateParsingException </c> . </para> /// </summary> [Dot42.DexImport("<init>", "()V", AccessFlags = 1)] public CertificateParsingException() /* MethodBuilder.Create */ { } } }
using System; using System.Diagnostics; using System.IO; using System.Linq; namespace Orleans.TestingHost.Utils { /// <summary> /// A wrapper on Azure Storage Emulator. /// </summary> /// <remarks>It might be tricky to implement this as a <see cref="IDisposable">IDisposable</see>, isolated, autonomous instance, /// see at <see href="http://azure.microsoft.com/en-us/documentation/articles/storage-use-emulator/">Use the Azure Storage Emulator for Development and Testing</see> /// for pointers.</remarks> public static class StorageEmulator { /// <summary> /// The storage emulator process name. One way to enumerate running process names is /// Get-Process | Format-Table Id, ProcessName -autosize. If there were multiple storage emulator /// processes running, they would named WASTOR~1, WASTOR~2, ... WASTOR~n. /// </summary> private static readonly string[] storageEmulatorProcessNames = new[] { "AzureStorageEmulator", // newest "Windows Azure Storage Emulator Service", // >= 2.7 "WAStorageEmulator", // < 2.7 }; //The file names aren't the same as process names. private static readonly string[] storageEmulatorFilenames = new[] { "AzureStorageEmulator.exe", // >= 2.7 "WAStorageEmulator.exe", // < 2.7 }; /// <summary> /// Is the storage emulator already started. /// </summary> /// <returns><see langword="true" /> if this instance is started; otherwise, <see langword="false" />.</returns> public static bool IsStarted() { return GetStorageEmulatorProcess(); } /// <summary> /// Checks if the storage emulator exists, i.e. is installed. /// </summary> /// <value><see langword="true" /> if the storage emulator exists; otherwise, <see langword="false" />.</value> public static bool Exists { get { return GetStorageEmulatorPath() != null; } } /// <summary> /// Storage Emulator help. /// </summary> /// <returns>Storage emulator help.</returns> public static string Help() { if (!IsStarted()) return "Error happened. Has StorageEmulator.Start() been called?"; try { //This process handle returns immediately. using(var process = Process.Start(CreateProcessArguments("help"))) { process.WaitForExit(); var help = string.Empty; while(!process.StandardOutput.EndOfStream) { help += process.StandardOutput.ReadLine(); } return help; } } catch (Exception exc) { return exc.ToString(); } } /// <summary> /// Tries to start the storage emulator. /// </summary> /// <returns><see langword="true"/> if the process was started successfully; <see langword="false"/> otherwise.</returns> public static bool TryStart() { if (!StorageEmulator.Exists) return false; return Start(); } /// <summary> /// Starts the storage emulator if not already started. /// </summary> /// <returns><see langword="true"/> if the process was started successfully; <see langword="false"/> otherwise.</returns> public static bool Start() { if (IsStarted()) return true; try { //This process handle returns immediately. using(var process = Process.Start(CreateProcessArguments("start"))) { if (process == null) return false; process.WaitForExit(); return process.ExitCode == 0; } } catch { return false; } } /// <summary> /// Stops the storage emulator if started. /// </summary> /// <returns><see langword="true"/> if the process was stopped successfully or was already stopped; <see langword="false"/> otherwise.</returns> public static bool Stop() { if (!IsStarted()) return false; try { //This process handle returns immediately. using(var process = Process.Start(CreateProcessArguments("stop"))) { process.WaitForExit(); return process.ExitCode == 0; } } catch { return false; } } /// <summary> /// Creates a new <see cref="ProcessStartInfo">ProcessStartInfo</see> to be used as an argument /// to other operations in this class. /// </summary> /// <param name="arguments">The arguments.</param> /// <returns>A new <see cref="ProcessStartInfo"/> that has the given arguments.</returns> private static ProcessStartInfo CreateProcessArguments(string arguments) { #pragma warning disable CA1416 // Validate platform compatibility return new ProcessStartInfo(GetStorageEmulatorPath()) { WindowStyle = ProcessWindowStyle.Hidden, ErrorDialog = true, LoadUserProfile = true, CreateNoWindow = true, UseShellExecute = false, RedirectStandardOutput = true, RedirectStandardError = true, Arguments = arguments }; #pragma warning restore CA1416 } /// <summary> /// Queries the storage emulator process from the system. /// </summary> /// <returns><see langword="true" /> if the storage emulator process was found, <see langword="false" /> otherwise.</returns> private static bool GetStorageEmulatorProcess() { foreach (var name in storageEmulatorProcessNames) { var ps = Process.GetProcessesByName(name); if (ps.Length != 0) { foreach (var p in ps) p.Dispose(); return true; } } return false; } /// <summary> /// Returns a full path to the storage emulator executable, including the executable name and file extension. /// </summary> /// <returns>A full path to the storage emulator executable, or null if not found.</returns> private static string GetStorageEmulatorPath() { //Try to take the newest known emulator path. If it does not exist, try an older one. string exeBasePath = Path.Combine(GetProgramFilesBasePath(), @"Microsoft SDKs\Azure\Storage Emulator\"); return storageEmulatorFilenames .Select(filename => Path.Combine(exeBasePath, filename)) .FirstOrDefault(File.Exists); } /// <summary> /// Determines the Program Files base directory. /// </summary> /// <returns>The Program files base directory.</returns> private static string GetProgramFilesBasePath() { return Environment.Is64BitOperatingSystem ? Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86) : Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles); } } }