context
stringlengths
2.52k
185k
gt
stringclasses
1 value
using System; using System.Collections.Generic; using System.ComponentModel; using bv.model.BLToolkit; using bv.winclient.BasePanel; using bv.winclient.Core; using bv.winclient.Layout; using eidss.model.Core; using eidss.model.Reports.AZ; using eidss.model.Reports.Common; using eidss.model.Reports.OperationContext; using EIDSS.Reports.BaseControls.Filters; using EIDSS.Reports.BaseControls.Keeper; using EIDSS.Reports.BaseControls.Report; using EIDSS.Reports.Parameterized.Human.AJ.Reports; namespace EIDSS.Reports.Parameterized.Human.AJ.Keepers { public sealed partial class ComparativeTwoYearsAZReportKeeper : BaseReportKeeper { private readonly ComponentResourceManager m_Resources = new ComponentResourceManager(typeof (ComparativeTwoYearsAZReportKeeper)); private List<ItemWrapper> m_CounterCollection; public ComparativeTwoYearsAZReportKeeper() : base(new Dictionary<string, string>()) { ReportType = typeof (ComparativeTwoYearsAZReport); InitializeComponent(); using (ContextKeeper.CreateNewContext(ContextValue.ReportFilterLoading)) { SetMandatory(); Year2SpinEdit.Value = DateTime.Now.Year; Year1SpinEdit.Value = DateTime.Now.Year - 1; CounterLookUp.EditValue = CounterCollection[0]; } m_HasLoad = true; } #region Properties [Browsable(false)] private int Year1Param { get { return (int) Year1SpinEdit.Value; } } [Browsable(false)] private int Year2Param { get { return (int) Year2SpinEdit.Value; } } [Browsable(false)] private long? OrganizationIdParam { get { return OrganizationFilter.EditValueId > 0 ? (long?) OrganizationFilter.EditValueId : null; } } [Browsable(false)] private long? RegionIdParam { get { return regionFilter.RegionId > 0 ? (long?) regionFilter.RegionId : null; } } [Browsable(false)] private long? RayonIdParam { get { return rayonFilter.RayonId > 0 ? (long?) rayonFilter.RayonId : null; } } [Browsable(false)] private long? DiagnosisIdParam { get { return diagnosisFilter.EditValueId > 0 ? (long?) diagnosisFilter.EditValueId : null; } } [Browsable(false)] private int CounterParam { get { return (CounterLookUp.EditValue == null) ? -1 : ((ItemWrapper) CounterLookUp.EditValue).Number; } } private List<ItemWrapper> CounterCollection { get { return m_CounterCollection ?? (m_CounterCollection = FilterHelper.GetWinCounterList()); } } #endregion protected override BaseReport GenerateReport(DbManagerProxy manager) { if (WinUtils.IsComponentInDesignMode(this)) { return new BaseReport(); } var model = new ComparativeTwoYearsSurrogateModel(CurrentCulture.ShortName, Year1Param, Year2Param, CounterParam, DiagnosisIdParam, diagnosisFilter.SelectedText, RegionIdParam, RayonIdParam, regionFilter.SelectedText, rayonFilter.SelectedText, OrganizationIdParam, OrganizationFilter.SelectedText, Convert.ToInt64(EidssUserContext.User.OrganizationID), EidssUserContext.User.ForbiddenPersonalDataGroups, UseArchive); var reportAz = (ComparativeTwoYearsAZReport) CreateReportObject(); reportAz.SetParameters(manager, model); return reportAz; } protected internal override void ApplyResources(DbManagerProxy manager) { try { IsResourceLoading = true; m_HasLoad = false; base.ApplyResources(manager); m_CounterCollection = null; ApplyLookupResources(CounterLookUp, CounterCollection, CounterParam, CounterLabel.Text); m_Resources.ApplyResources(StartYearLabel, "StartYearLabel"); m_Resources.ApplyResources(EndYearLabel, "EndYearLabel"); m_Resources.ApplyResources(CounterLabel, "CounterLabel"); //m_Resources.ApplyResources(OrganizationFilter, "OrganizationFilter"); OrganizationFilter.DefineBinding(); //m_Resources.ApplyResources(diagnosisFilter, "diagnosisFilter"); diagnosisFilter.DefineBinding(); regionFilter.DefineBinding(); rayonFilter.DefineBinding(); if (ContextKeeper.ContainsContext(ContextValue.ReportKeeperFirstLoading)) { LocationHelper.SetDefaultFilters(manager, ContextKeeper, regionFilter, rayonFilter); } } finally { m_HasLoad = true; IsResourceLoading = false; } } private void CorrectYearRange() { if (Year2Param <= Year1Param) { if (!ContextKeeper.ContainsContext(ContextValue.ReportFilterLoading)) { if (!BaseFormManager.IsReportsServiceRunning && !BaseFormManager.IsAvrServiceRunning) { ErrorForm.ShowWarning("msgComparativeReportCorrectYear", "Year 1 shall be greater than Year 2"); } } using (ContextKeeper.CreateNewContext(ContextValue.ReportFilterLoading)) { Year1SpinEdit.EditValue = Year2Param - 1; } } } private void SetMandatory() { BaseFilter.SetLookupMandatory(CounterLookUp); LayoutCorrector.SetStyleController(Year1SpinEdit, LayoutCorrector.MandatoryStyleController); LayoutCorrector.SetStyleController(Year2SpinEdit, LayoutCorrector.MandatoryStyleController); } private void seYear1_EditValueChanged(object sender, EventArgs e) { CorrectYearRange(); } private void seYear2_EditValueChanged(object sender, EventArgs e) { CorrectYearRange(); } private void CounterLookUp_EditValueChanged(object sender, EventArgs e) { } private void regionFilter_ValueChanged(object sender, SingleFilterEventArgs e) { using (ContextKeeper.CreateNewContext(ContextValue.ReportFilterResetting)) { OrganizationFilter.Enabled = !RegionIdParam.HasValue && !RayonIdParam.HasValue; LocationHelper.RegionFilterValueChanged(regionFilter, rayonFilter, e); } } private void rayonFilter_ValueChanged(object sender, SingleFilterEventArgs e) { using (ContextKeeper.CreateNewContext(ContextValue.ReportFilterResetting)) { OrganizationFilter.Enabled = !RegionIdParam.HasValue && !RayonIdParam.HasValue; LocationHelper.RayonFilterValueChanged(regionFilter, rayonFilter, e); } } private void OrganizationFilter_ValueChanged(object sender, SingleFilterEventArgs e) { bool hasOrg = OrganizationIdParam.HasValue; regionFilter.Enabled = !hasOrg; rayonFilter.Enabled = !hasOrg; } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.Text; using Lucene.Net.Analysis; using Lucene.Net.Documents; using Lucene.Net.Search; using Lucene.Net.Index; using Lucene.Net.QueryParsers; using Lucene.Net.Store; namespace Lucene.Net.Search.Vectorhighlight { /// <summary> /// <c>FieldTermStack</c> is a stack that keeps query terms in the specified field /// of the document to be highlighted. /// </summary> public class FieldTermStack { private String fieldName; public LinkedList<TermInfo> termList = new LinkedList<TermInfo>(); public static void Main(String[] args) { Analyzer analyzer = new WhitespaceAnalyzer(); QueryParser parser = new QueryParser(Util.Version.LUCENE_CURRENT, "f", analyzer); Query query = parser.Parse("a x:b"); FieldQuery fieldQuery = new FieldQuery(query, true, false); Directory dir = new RAMDirectory(); IndexWriter writer = new IndexWriter(dir, analyzer, IndexWriter.MaxFieldLength.LIMITED); Document doc = new Document(); doc.Add(new Field("f", "a a a b b c a b b c d e f", Field.Store.YES, Field.Index.ANALYZED, Field.TermVector.WITH_POSITIONS_OFFSETS)); doc.Add(new Field("f", "b a b a f", Field.Store.YES, Field.Index.ANALYZED, Field.TermVector.WITH_POSITIONS_OFFSETS)); writer.AddDocument(doc); writer.Close(); IndexReader reader = IndexReader.Open(dir,true); FieldTermStack ftl = new FieldTermStack(reader, 0, "f", fieldQuery); reader.Close(); } /// <summary> /// a constructor. /// </summary> /// <param name="reader">IndexReader of the index</param> /// <param name="docId">document id to be highlighted</param> /// <param name="fieldName">field of the document to be highlighted</param> /// <param name="fieldQuery">FieldQuery object</param> #if LUCENENET_350 //Lucene.Net specific code. See https://issues.apache.org/jira/browse/LUCENENET-350 public FieldTermStack(IndexReader reader, int docId, String fieldName, FieldQuery fieldQuery) { this.fieldName = fieldName; List<string> termSet = fieldQuery.getTermSet(fieldName); // just return to make null snippet if un-matched fieldName specified when fieldMatch == true if (termSet == null) return; //TermFreqVector tfv = reader.GetTermFreqVector(docId, fieldName); VectorHighlightMapper tfv = new VectorHighlightMapper(termSet); reader.GetTermFreqVector(docId, fieldName, tfv); if (tfv.Size==0) return; // just return to make null snippets string[] terms = tfv.GetTerms(); foreach (String term in terms) { if (!StringUtils.AnyTermMatch(termSet, term)) continue; int index = tfv.IndexOf(term); TermVectorOffsetInfo[] tvois = tfv.GetOffsets(index); if (tvois == null) return; // just return to make null snippets int[] poss = tfv.GetTermPositions(index); if (poss == null) return; // just return to make null snippets for (int i = 0; i < tvois.Length; i++) termList.AddLast(new TermInfo(term, tvois[i].StartOffset, tvois[i].EndOffset, poss[i])); } // sort by position //Collections.sort(termList); Sort(termList); } #else //Original Port public FieldTermStack(IndexReader reader, int docId, String fieldName, FieldQuery fieldQuery) { this.fieldName = fieldName; TermFreqVector tfv = reader.GetTermFreqVector(docId, fieldName); if (tfv == null) return; // just return to make null snippets TermPositionVector tpv = null; try { tpv = (TermPositionVector)tfv; } catch (InvalidCastException e) { return; // just return to make null snippets } List<String> termSet = fieldQuery.getTermSet(fieldName); // just return to make null snippet if un-matched fieldName specified when fieldMatch == true if (termSet == null) return; foreach (String term in tpv.GetTerms()) { if (!termSet.Contains(term)) continue; int index = tpv.IndexOf(term); TermVectorOffsetInfo[] tvois = tpv.GetOffsets(index); if (tvois == null) return; // just return to make null snippets int[] poss = tpv.GetTermPositions(index); if (poss == null) return; // just return to make null snippets for (int i = 0; i < tvois.Length; i++) termList.AddLast(new TermInfo(term, tvois[i].GetStartOffset(), tvois[i].GetEndOffset(), poss[i])); } // sort by position //Collections.sort(termList); Sort(termList); } #endif void Sort(LinkedList<TermInfo> linkList) { TermInfo[] arr = new TermInfo[linkList.Count]; linkList.CopyTo(arr, 0); Array.Sort(arr, new Comparison<TermInfo>(PosComparer)); linkList.Clear(); foreach (TermInfo t in arr) linkList.AddLast(t); } int PosComparer(TermInfo t1,TermInfo t2) { return t1.Position - t2.Position; } /// <summary> /// /// </summary> /// <value> field name </value> public string FieldName { get { return fieldName; } } /// <summary> /// /// </summary> /// <returns>the top TermInfo object of the stack</returns> public TermInfo Pop() { if (termList.Count == 0) return null; LinkedListNode<TermInfo> top = termList.First; termList.RemoveFirst(); return top.Value; } /// <summary> /// /// </summary> /// <param name="termInfo">the TermInfo object to be put on the top of the stack</param> public void Push(TermInfo termInfo) { // termList.push( termInfo ); // avoid Java 1.6 feature termList.AddFirst(termInfo); } /// <summary> /// to know whether the stack is empty /// </summary> /// <returns>true if the stack is empty, false if not</returns> public bool IsEmpty() { return termList == null || termList.Count == 0; } public class TermInfo : IComparable<TermInfo> { String text; int startOffset; int endOffset; int position; public TermInfo(String text, int startOffset, int endOffset, int position) { this.text = text; this.startOffset = startOffset; this.endOffset = endOffset; this.position = position; } public string Text { get { return text; } } public int StartOffset { get { return startOffset; } } public int EndOffset { get { return endOffset; } } public int Position { get { return position; } } public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append(text).Append('(').Append(startOffset).Append(',').Append(endOffset).Append(',').Append(position).Append(')'); return sb.ToString(); } public int CompareTo(TermInfo o) { return (this.position - o.position); } } } }
// 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.Reflection; using System.Diagnostics.Contracts; using System.IO; using System.Runtime.Versioning; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Security; using System.Threading; #if FEATURE_HOST_ASSEMBLY_RESOLVER namespace System.Runtime.Loader { [System.Security.SecuritySafeCritical] public abstract class AssemblyLoadContext { [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private static extern bool OverrideDefaultAssemblyLoadContextForCurrentDomain(IntPtr ptrNativeAssemblyLoadContext); [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private static extern bool CanUseAppPathAssemblyLoadContextInCurrentDomain(); [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private static extern IntPtr InitializeAssemblyLoadContext(IntPtr ptrAssemblyLoadContext, bool fRepresentsTPALoadContext); [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private static extern IntPtr LoadFromAssemblyName(IntPtr ptrNativeAssemblyLoadContext, bool fRepresentsTPALoadContext); [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private static extern IntPtr LoadFromStream(IntPtr ptrNativeAssemblyLoadContext, IntPtr ptrAssemblyArray, int iAssemblyArrayLen, IntPtr ptrSymbols, int iSymbolArrayLen, ObjectHandleOnStack retAssembly); #if FEATURE_MULTICOREJIT [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] internal static extern void InternalSetProfileRoot(string directoryPath); [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] internal static extern void InternalStartProfile(string profile, IntPtr ptrNativeAssemblyLoadContext); #endif // FEATURE_MULTICOREJIT protected AssemblyLoadContext() { // Initialize the ALC representing non-TPA LoadContext InitializeLoadContext(false); } internal AssemblyLoadContext(bool fRepresentsTPALoadContext) { // Initialize the ALC representing TPA LoadContext InitializeLoadContext(fRepresentsTPALoadContext); } [System.Security.SecuritySafeCritical] void InitializeLoadContext(bool fRepresentsTPALoadContext) { // Initialize the VM side of AssemblyLoadContext if not already done. GCHandle gchALC = GCHandle.Alloc(this); IntPtr ptrALC = GCHandle.ToIntPtr(gchALC); m_pNativeAssemblyLoadContext = InitializeAssemblyLoadContext(ptrALC, fRepresentsTPALoadContext); // Initialize event handlers to be null by default Resolving = null; Unloading = null; // Since unloading an AssemblyLoadContext is not yet implemented, this is a temporary solution to raise the // Unloading event on process exit. Register for the current AppDomain's ProcessExit event, and the handler will in // turn raise the Unloading event. AppDomain.CurrentDomain.ProcessExit += OnProcessExit; } [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private static extern void LoadFromPath(IntPtr ptrNativeAssemblyLoadContext, string ilPath, string niPath, ObjectHandleOnStack retAssembly); [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private static extern void GetLoadedAssembliesInternal(ObjectHandleOnStack assemblies); public static Assembly[] GetLoadedAssemblies() { Assembly[] assemblies = null; GetLoadedAssembliesInternal(JitHelpers.GetObjectHandleOnStack(ref assemblies)); return assemblies; } // These are helpers that can be used by AssemblyLoadContext derivations. // They are used to load assemblies in DefaultContext. public Assembly LoadFromAssemblyPath(string assemblyPath) { if (assemblyPath == null) { throw new ArgumentNullException("assemblyPath"); } if (Path.IsRelative(assemblyPath)) { throw new ArgumentException( Environment.GetResourceString("Argument_AbsolutePathRequired"), "assemblyPath"); } RuntimeAssembly loadedAssembly = null; LoadFromPath(m_pNativeAssemblyLoadContext, assemblyPath, null, JitHelpers.GetObjectHandleOnStack(ref loadedAssembly)); return loadedAssembly; } public Assembly LoadFromNativeImagePath(string nativeImagePath, string assemblyPath) { if (nativeImagePath == null) { throw new ArgumentNullException("nativeImagePath"); } if (Path.IsRelative(nativeImagePath)) { throw new ArgumentException( Environment.GetResourceString("Argument_AbsolutePathRequired"), "nativeImagePath"); } if (assemblyPath != null && Path.IsRelative(assemblyPath)) { throw new ArgumentException(Environment.GetResourceString("Argument_AbsolutePathRequired"), "assemblyPath"); } // Basic validation has succeeded - lets try to load the NI image. // Ask LoadFile to load the specified assembly in the DefaultContext RuntimeAssembly loadedAssembly = null; LoadFromPath(m_pNativeAssemblyLoadContext, assemblyPath, nativeImagePath, JitHelpers.GetObjectHandleOnStack(ref loadedAssembly)); return loadedAssembly; } public Assembly LoadFromStream(Stream assembly) { return LoadFromStream(assembly, null); } public Assembly LoadFromStream(Stream assembly, Stream assemblySymbols) { if (assembly == null) { throw new ArgumentNullException("assembly"); } int iAssemblyStreamLength = (int)assembly.Length; int iSymbolLength = 0; // Allocate the byte[] to hold the assembly byte[] arrAssembly = new byte[iAssemblyStreamLength]; // Copy the assembly to the byte array assembly.Read(arrAssembly, 0, iAssemblyStreamLength); // Get the symbol stream in byte[] if provided byte[] arrSymbols = null; if (assemblySymbols != null) { iSymbolLength = (int)assemblySymbols.Length; arrSymbols = new byte[iSymbolLength]; assemblySymbols.Read(arrSymbols, 0, iSymbolLength); } RuntimeAssembly loadedAssembly = null; unsafe { fixed(byte *ptrAssembly = arrAssembly, ptrSymbols = arrSymbols) { LoadFromStream(m_pNativeAssemblyLoadContext, new IntPtr(ptrAssembly), iAssemblyStreamLength, new IntPtr(ptrSymbols), iSymbolLength, JitHelpers.GetObjectHandleOnStack(ref loadedAssembly)); } } return loadedAssembly; } // Custom AssemblyLoadContext implementations can override this // method to perform custom processing and use one of the protected // helpers above to load the assembly. protected abstract Assembly Load(AssemblyName assemblyName); // This method is invoked by the VM when using the host-provided assembly load context // implementation. private static Assembly Resolve(IntPtr gchManagedAssemblyLoadContext, AssemblyName assemblyName) { AssemblyLoadContext context = (AssemblyLoadContext)(GCHandle.FromIntPtr(gchManagedAssemblyLoadContext).Target); return context.ResolveUsingLoad(assemblyName); } // This method is invoked by the VM to resolve an assembly reference using the Resolving event // after trying assembly resolution via Load override and TPA load context without success. private static Assembly ResolveUsingResolvingEvent(IntPtr gchManagedAssemblyLoadContext, AssemblyName assemblyName) { AssemblyLoadContext context = (AssemblyLoadContext)(GCHandle.FromIntPtr(gchManagedAssemblyLoadContext).Target); // Invoke the AssemblyResolve event callbacks if wired up return context.ResolveUsingEvent(assemblyName); } private Assembly GetFirstResolvedAssembly(AssemblyName assemblyName) { Assembly resolvedAssembly = null; Func<AssemblyLoadContext, AssemblyName, Assembly> assemblyResolveHandler = Resolving; if (assemblyResolveHandler != null) { // Loop through the event subscribers and return the first non-null Assembly instance Delegate [] arrSubscribers = assemblyResolveHandler.GetInvocationList(); for(int i = 0; i < arrSubscribers.Length; i++) { resolvedAssembly = ((Func<AssemblyLoadContext, AssemblyName, Assembly>)arrSubscribers[i])(this, assemblyName); if (resolvedAssembly != null) { break; } } } return resolvedAssembly; } private Assembly ValidateAssemblyNameWithSimpleName(Assembly assembly, string requestedSimpleName) { // Get the name of the loaded assembly string loadedSimpleName = null; // Derived type's Load implementation is expected to use one of the LoadFrom* methods to get the assembly // which is a RuntimeAssembly instance. However, since Assembly type can be used build any other artifact (e.g. AssemblyBuilder), // we need to check for RuntimeAssembly. RuntimeAssembly rtLoadedAssembly = assembly as RuntimeAssembly; if (rtLoadedAssembly != null) { loadedSimpleName = rtLoadedAssembly.GetSimpleName(); } // The simple names should match at the very least if (String.IsNullOrEmpty(loadedSimpleName) || (!requestedSimpleName.Equals(loadedSimpleName, StringComparison.InvariantCultureIgnoreCase))) throw new InvalidOperationException(Environment.GetResourceString("Argument_CustomAssemblyLoadContextRequestedNameMismatch")); return assembly; } private Assembly ResolveUsingLoad(AssemblyName assemblyName) { string simpleName = assemblyName.Name; Assembly assembly = Load(assemblyName); if (assembly != null) { assembly = ValidateAssemblyNameWithSimpleName(assembly, simpleName); } return assembly; } private Assembly ResolveUsingEvent(AssemblyName assemblyName) { string simpleName = assemblyName.Name; // Invoke the AssemblyResolve event callbacks if wired up Assembly assembly = GetFirstResolvedAssembly(assemblyName); if (assembly != null) { assembly = ValidateAssemblyNameWithSimpleName(assembly, simpleName); } // Since attempt to resolve the assembly via Resolving event is the last option, // throw an exception if we do not find any assembly. if (assembly == null) { throw new FileNotFoundException(Environment.GetResourceString("IO.FileLoad"), simpleName); } return assembly; } public Assembly LoadFromAssemblyName(AssemblyName assemblyName) { // Attempt to load the assembly, using the same ordering as static load, in the current load context. Assembly loadedAssembly = Assembly.Load(assemblyName, m_pNativeAssemblyLoadContext); return loadedAssembly; } [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private static extern IntPtr InternalLoadUnmanagedDllFromPath(string unmanagedDllPath); // This method provides a way for overriders of LoadUnmanagedDll() to load an unmanaged DLL from a specific path in a // platform-independent way. The DLL is loaded with default load flags. protected IntPtr LoadUnmanagedDllFromPath(string unmanagedDllPath) { if (unmanagedDllPath == null) { throw new ArgumentNullException("unmanagedDllPath"); } if (unmanagedDllPath.Length == 0) { throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"), "unmanagedDllPath"); } if (Path.IsRelative(unmanagedDllPath)) { throw new ArgumentException(Environment.GetResourceString("Argument_AbsolutePathRequired"), "unmanagedDllPath"); } return InternalLoadUnmanagedDllFromPath(unmanagedDllPath); } // Custom AssemblyLoadContext implementations can override this // method to perform the load of unmanaged native dll // This function needs to return the HMODULE of the dll it loads protected virtual IntPtr LoadUnmanagedDll(String unmanagedDllName) { //defer to default coreclr policy of loading unmanaged dll return IntPtr.Zero; } // This method is invoked by the VM when using the host-provided assembly load context // implementation. private static IntPtr ResolveUnmanagedDll(String unmanagedDllName, IntPtr gchManagedAssemblyLoadContext) { AssemblyLoadContext context = (AssemblyLoadContext)(GCHandle.FromIntPtr(gchManagedAssemblyLoadContext).Target); return context.LoadUnmanagedDll(unmanagedDllName); } public static AssemblyLoadContext Default { get { if (s_DefaultAssemblyLoadContext == null) { // Try to initialize the default assembly load context with apppath one if we are allowed to if (AssemblyLoadContext.CanUseAppPathAssemblyLoadContextInCurrentDomain()) { // Synchronize access to initializing Default ALC lock(s_initLock) { if (s_DefaultAssemblyLoadContext == null) { s_DefaultAssemblyLoadContext = new AppPathAssemblyLoadContext(); } } } } return s_DefaultAssemblyLoadContext; } } // This will be used to set the AssemblyLoadContext for DefaultContext, for the AppDomain, // by a host. Once set, the runtime will invoke the LoadFromAssemblyName method against it to perform // assembly loads for the DefaultContext. // // This method will throw if the Default AssemblyLoadContext is already set or the Binding model is already locked. public static void InitializeDefaultContext(AssemblyLoadContext context) { if (context == null) { throw new ArgumentNullException("context"); } // Try to override the default assembly load context if (!AssemblyLoadContext.OverrideDefaultAssemblyLoadContextForCurrentDomain(context.m_pNativeAssemblyLoadContext)) { throw new InvalidOperationException(Environment.GetResourceString("AppDomain_BindingModelIsLocked")); } // Update the managed side as well. s_DefaultAssemblyLoadContext = context; } // This call opens and closes the file, but does not add the // assembly to the domain. [MethodImplAttribute(MethodImplOptions.InternalCall)] static internal extern AssemblyName nGetFileInformation(String s); // Helper to return AssemblyName corresponding to the path of an IL assembly public static AssemblyName GetAssemblyName(string assemblyPath) { if (assemblyPath == null) { throw new ArgumentNullException("assemblyPath"); } String fullPath = Path.GetFullPathInternal(assemblyPath); return nGetFileInformation(fullPath); } [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private static extern IntPtr GetLoadContextForAssembly(RuntimeAssembly assembly); // Returns the load context in which the specified assembly has been loaded public static AssemblyLoadContext GetLoadContext(Assembly assembly) { if (assembly == null) { throw new ArgumentNullException("assembly"); } AssemblyLoadContext loadContextForAssembly = null; RuntimeAssembly rtAsm = assembly as RuntimeAssembly; // We only support looking up load context for runtime assemblies. if (rtAsm != null) { IntPtr ptrAssemblyLoadContext = GetLoadContextForAssembly(rtAsm); if (ptrAssemblyLoadContext == IntPtr.Zero) { // If the load context is returned null, then the assembly was bound using the TPA binder // and we shall return reference to the active "Default" binder - which could be the TPA binder // or an overridden CLRPrivBinderAssemblyLoadContext instance. loadContextForAssembly = AssemblyLoadContext.Default; } else { loadContextForAssembly = (AssemblyLoadContext)(GCHandle.FromIntPtr(ptrAssemblyLoadContext).Target); } } return loadContextForAssembly; } // Set the root directory path for profile optimization. public void SetProfileOptimizationRoot(string directoryPath) { #if FEATURE_MULTICOREJIT InternalSetProfileRoot(directoryPath); #endif // FEATURE_MULTICOREJIT } // Start profile optimization for the specified profile name. public void StartProfileOptimization(string profile) { #if FEATURE_MULTICOREJIT InternalStartProfile(profile, m_pNativeAssemblyLoadContext); #endif // FEATURE_MULTICOREJI } private void OnProcessExit(object sender, EventArgs e) { var unloading = Unloading; if (unloading != null) { unloading(this); } } public event Func<AssemblyLoadContext, AssemblyName, Assembly> Resolving; public event Action<AssemblyLoadContext> Unloading; // Contains the reference to VM's representation of the AssemblyLoadContext private IntPtr m_pNativeAssemblyLoadContext; // Each AppDomain contains the reference to its AssemblyLoadContext instance, if one is // specified by the host. By having the field as a static, we are // making it an AppDomain-wide field. private static volatile AssemblyLoadContext s_DefaultAssemblyLoadContext; // Synchronization primitive for controlling initialization of Default load context private static readonly object s_initLock = new Object(); // Occurs when an Assembly is loaded public static event AssemblyLoadEventHandler AssemblyLoad { add { AppDomain.CurrentDomain.AssemblyLoad += value; } remove { AppDomain.CurrentDomain.AssemblyLoad -= value; } } // Occurs when resolution of type fails public static event ResolveEventHandler TypeResolve { add { AppDomain.CurrentDomain.TypeResolve += value; } remove { AppDomain.CurrentDomain.TypeResolve -= value; } } // Occurs when resolution of resource fails public static event ResolveEventHandler ResourceResolve { add { AppDomain.CurrentDomain.ResourceResolve += value; } remove { AppDomain.CurrentDomain.ResourceResolve -= value; } } } [System.Security.SecuritySafeCritical] class AppPathAssemblyLoadContext : AssemblyLoadContext { internal AppPathAssemblyLoadContext() : base(true) { } [System.Security.SecuritySafeCritical] protected override Assembly Load(AssemblyName assemblyName) { // We were loading an assembly into TPA ALC that was not found on TPA list. As a result we are here. // Returning null will result in the AssemblyResolve event subscribers to be invoked to help resolve the assembly. return null; } } [System.Security.SecuritySafeCritical] internal class FileLoadAssemblyLoadContext : AssemblyLoadContext { internal FileLoadAssemblyLoadContext() : base(false) { } [System.Security.SecuritySafeCritical] protected override Assembly Load(AssemblyName assemblyName) { return null; } } } #endif // FEATURE_HOST_ASSEMBLY_RESOLVER
using System; using Microsoft.SPOT; using WS2811; using Microsoft.SPOT.Hardware; using System.Threading; namespace SpiderStarTunesBT { class StarLEDs { WS2811Led MyWS2811Strip; public StarLEDs() { int NumberOfLeds = 32; // Modify here the led number of your strip ! // Initialize the strip : here using SPI2 and 800Khz model and using the linear human perceived luminosity PWM conversion factor of 2.25 MyWS2811Strip = new WS2811Led(NumberOfLeds, SPI.SPI_module.SPI1, WS2811Led.WS2811Speed.S800KHZ, 2.25); //ringsSolid(); //rotateLines(); //rings(1); } // set up LED arrangement functions: void setCenterLED(byte red, byte green, byte blue, bool clear = false) { if (clear) MyWS2811Strip.Clear(); MyWS2811Strip.Set(3, red, green, blue); MyWS2811Strip.Transmit(); } void setRing1LEDs(byte red, byte green, byte blue, bool clear = false) { if (clear) MyWS2811Strip.Clear(); MyWS2811Strip.Set(2, red, green, blue); MyWS2811Strip.Set(4, red, green, blue); MyWS2811Strip.Set(7, red, green, blue); MyWS2811Strip.Set(10, red, green, blue); MyWS2811Strip.Set(13, red, green, blue); MyWS2811Strip.Set(16, red, green, blue); MyWS2811Strip.Transmit(); } void setRing2LEDs(byte red, byte green, byte blue, bool clear = false) { if (clear) MyWS2811Strip.Clear(); MyWS2811Strip.Set(1, red, green, blue); MyWS2811Strip.Set(5, red, green, blue); MyWS2811Strip.Set(8, red, green, blue); MyWS2811Strip.Set(11, red, green, blue); MyWS2811Strip.Set(14, red, green, blue); MyWS2811Strip.Set(17, red, green, blue); MyWS2811Strip.Transmit(); } void setRing3LEDs(byte red, byte green, byte blue, bool clear = false) { if (clear) MyWS2811Strip.Clear(); MyWS2811Strip.Set(0, red, green, blue); MyWS2811Strip.Set(6, red, green, blue); MyWS2811Strip.Set(9, red, green, blue); MyWS2811Strip.Set(12, red, green, blue); MyWS2811Strip.Set(15, red, green, blue); MyWS2811Strip.Set(18, red, green, blue); MyWS2811Strip.Transmit(); } void setVerticalLEDs(byte red, byte green, byte blue, bool clear = false) { if (clear) MyWS2811Strip.Clear(); MyWS2811Strip.Set(0, red, green, blue); MyWS2811Strip.Set(1, red, green, blue); MyWS2811Strip.Set(2, red, green, blue); MyWS2811Strip.Set(3, red, green, blue); MyWS2811Strip.Set(4, red, green, blue); MyWS2811Strip.Set(5, red, green, blue); MyWS2811Strip.Set(6, red, green, blue); MyWS2811Strip.Transmit(); } void setSWtoNELEDs(byte red, byte green, byte blue, bool clear = false) { if (clear) MyWS2811Strip.Clear(); MyWS2811Strip.Set(3, red, green, blue); MyWS2811Strip.Set(7, red, green, blue); MyWS2811Strip.Set(8, red, green, blue); MyWS2811Strip.Set(9, red, green, blue); MyWS2811Strip.Set(13, red, green, blue); MyWS2811Strip.Set(14, red, green, blue); MyWS2811Strip.Set(15, red, green, blue); MyWS2811Strip.Transmit(); } void setNWtoSELEDs(byte red, byte green, byte blue, bool clear = false) { if (clear) MyWS2811Strip.Clear(); MyWS2811Strip.Set(3, red, green, blue); MyWS2811Strip.Set(10, red, green, blue); MyWS2811Strip.Set(11, red, green, blue); MyWS2811Strip.Set(12, red, green, blue); MyWS2811Strip.Set(16, red, green, blue); MyWS2811Strip.Set(17, red, green, blue); MyWS2811Strip.Set(18, red, green, blue); MyWS2811Strip.Transmit(); } public void clear() { MyWS2811Strip.Clear(); MyWS2811Strip.Transmit(); } public void chaseRedGreen() { clear(); for (int i = 0; i < 190; i++) { byte r = 0; byte g = 0; byte b = 0; if (i % 19 == 0) { clear(); } if (i % 2 == 0) { g = 255; } else { r = 255; } if (i > 0) { MyWS2811Strip.Shift(); } MyWS2811Strip.Set(0, r, g, b); MyWS2811Strip.Transmit(); Thread.Sleep(200); } clear(); } public void fadeInOut() { clear(); for (int i = 0; i < 10; i++) { byte r = 0; byte g = 0; byte b = 0; byte red = 0; byte green = 0; byte blue = 0; if (i % 2 == 0) { green = 255; } else { red = 255; } // fade in for (double p = 0.05; p < 1; p = p + 0.05) { r = (byte)(red * p); g = (byte)(green * p); b = (byte)(blue * p); setCenterLED(r, g, b); setRing1LEDs(r, g, b); setRing2LEDs(r, g, b); setRing3LEDs(r, g, b); Thread.Sleep(50); } // fade out for (double p = 1; p > 0; p = p - 0.05) { r = (byte)(red * p); g = (byte)(green * p); b = (byte)(blue * p); setCenterLED(r, g, b); setRing1LEDs(r, g, b); setRing2LEDs(r, g, b); setRing3LEDs(r, g, b); Thread.Sleep(50); } clear(); } } public void randomRedGreenPixels() { clear(); Random rnd = new Random(); for (int i = 0; i < 250; i++) { byte r = 0; byte g = 0; byte b = 0; int pixelToBlink = 0; pixelToBlink = rnd.Next(19); if (i % 2 == 0) { g = 255; } else { clear(); r = 255; } if (i % 3 == 0) { r = 255; g = 255; b = 255; } MyWS2811Strip.Set(pixelToBlink, r, g, b); MyWS2811Strip.Transmit(); Thread.Sleep(50); } clear(); } public void rings() { clear(); for (int i = 0; i < 12; i++) { byte r = 0; byte g = 0; byte b = 0; if (i % 2 == 0) { g = 255; } else { r = 255; } setCenterLED(r, g, b, true); Thread.Sleep(150); setRing1LEDs(r, g, b, true); Thread.Sleep(150); setRing2LEDs(r, g, b, true); Thread.Sleep(150); setRing3LEDs(r, g, b, true); Thread.Sleep(150); clear(); } } public void ringsIn() { clear(); for (int i = 0; i < 12; i++) { byte r = 0; byte g = 0; byte b = 0; if (i % 2 == 0) { g = 255; } else { r = 255; } setRing3LEDs(r, g, b, true); Thread.Sleep(150); setRing2LEDs(r, g, b, true); Thread.Sleep(150); setRing1LEDs(r, g, b, true); Thread.Sleep(150); setCenterLED(r, g, b, true); Thread.Sleep(150); clear(); } } public void ringsSolid() { clear(); for (int i = 0; i < 12; i++) { byte r = 0; byte g = 0; byte b = 0; if (i % 2 == 0) { g = 255; } else { r = 255; } setCenterLED(r, g, b); Thread.Sleep(250); setRing1LEDs(r, g, b); Thread.Sleep(250); setRing2LEDs(r, g, b); Thread.Sleep(250); setRing3LEDs(r, g, b); Thread.Sleep(250); clear(); } } public void ringsSolidIn() { clear(); for (int i = 0; i < 12; i++) { byte r = 0; byte g = 0; byte b = 0; if (i % 2 == 0) { g = 255; } else { r = 255; } setRing3LEDs(r, g, b); Thread.Sleep(250); setRing2LEDs(r, g, b); Thread.Sleep(250); setRing1LEDs(r, g, b); Thread.Sleep(250); setCenterLED(r, g, b); Thread.Sleep(250); clear(); } } public void rotateLines() { clear(); for (int i = 0; i < 12; i++) { byte r = 0; byte g = 0; byte b = 0; if (i % 2 == 0) { g = 255; } else { r = 255; } setVerticalLEDs(r, g, b, true); Thread.Sleep(100); setSWtoNELEDs(r, g, b, true); Thread.Sleep(100); setNWtoSELEDs(r, g, b, true); Thread.Sleep(100); clear(); } //if (NextPattern > 0) // startNextPattern(NextPattern); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 0.12.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.AcceptanceTestsBodyNumber { using System; using System.Collections.Generic; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Models; /// <summary> /// Number operations. /// </summary> public partial interface INumber { /// <summary> /// Get null Number value /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<double?>> GetNullWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get invalid float Number value /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<double?>> GetInvalidFloatWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get invalid double Number value /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<double?>> GetInvalidDoubleWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get invalid decimal Number value /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<decimal?>> GetInvalidDecimalWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Put big float value 3.402823e+20 /// </summary> /// <param name='numberBody'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> PutBigFloatWithHttpMessagesAsync(double? numberBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get big float value 3.402823e+20 /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<double?>> GetBigFloatWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Put big double value 2.5976931e+101 /// </summary> /// <param name='numberBody'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> PutBigDoubleWithHttpMessagesAsync(double? numberBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get big double value 2.5976931e+101 /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<double?>> GetBigDoubleWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Put big double value 99999999.99 /// </summary> /// <param name='numberBody'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> PutBigDoublePositiveDecimalWithHttpMessagesAsync(double? numberBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get big double value 99999999.99 /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<double?>> GetBigDoublePositiveDecimalWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Put big double value -99999999.99 /// </summary> /// <param name='numberBody'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> PutBigDoubleNegativeDecimalWithHttpMessagesAsync(double? numberBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get big double value -99999999.99 /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<double?>> GetBigDoubleNegativeDecimalWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Put big decimal value 2.5976931e+101 /// </summary> /// <param name='numberBody'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> PutBigDecimalWithHttpMessagesAsync(decimal? numberBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get big decimal value 2.5976931e+101 /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<decimal?>> GetBigDecimalWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Put big decimal value 99999999.99 /// </summary> /// <param name='numberBody'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> PutBigDecimalPositiveDecimalWithHttpMessagesAsync(decimal? numberBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get big decimal value 99999999.99 /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<decimal?>> GetBigDecimalPositiveDecimalWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Put big decimal value -99999999.99 /// </summary> /// <param name='numberBody'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> PutBigDecimalNegativeDecimalWithHttpMessagesAsync(decimal? numberBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get big decimal value -99999999.99 /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<decimal?>> GetBigDecimalNegativeDecimalWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Put small float value 3.402823e-20 /// </summary> /// <param name='numberBody'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> PutSmallFloatWithHttpMessagesAsync(double? numberBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get big double value 3.402823e-20 /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<double?>> GetSmallFloatWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Put small double value 2.5976931e-101 /// </summary> /// <param name='numberBody'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> PutSmallDoubleWithHttpMessagesAsync(double? numberBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get big double value 2.5976931e-101 /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<double?>> GetSmallDoubleWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Put small decimal value 2.5976931e-101 /// </summary> /// <param name='numberBody'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> PutSmallDecimalWithHttpMessagesAsync(decimal? numberBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get small decimal value 2.5976931e-101 /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<decimal?>> GetSmallDecimalWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Class: UnmanagedMemoryStream ** ** <OWNER>[....]</OWNER> ** ** Purpose: Create a stream over unmanaged memory, mostly ** useful for memory-mapped files. ** ** Date: October 20, 2000 (made public August 4, 2003) ** ===========================================================*/ using System; using System.Runtime; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Security; using System.Security.Permissions; using System.Threading; using System.Diagnostics.Contracts; #if !FEATURE_PAL && FEATURE_ASYNC_IO || MONO using System.Threading.Tasks; #endif // !FEATURE_PAL && FEATURE_ASYNC_IO namespace System.IO { /* * This class is used to access a contiguous block of memory, likely outside * the GC heap (or pinned in place in the GC heap, but a MemoryStream may * make more sense in those cases). It's great if you have a pointer and * a length for a section of memory mapped in by someone else and you don't * want to copy this into the GC heap. UnmanagedMemoryStream assumes these * two things: * * 1) All the memory in the specified block is readable or writable, * depending on the values you pass to the constructor. * 2) The lifetime of the block of memory is at least as long as the lifetime * of the UnmanagedMemoryStream. * 3) You clean up the memory when appropriate. The UnmanagedMemoryStream * currently will do NOTHING to free this memory. * 4) All calls to Write and WriteByte may not be threadsafe currently. * * It may become necessary to add in some sort of * DeallocationMode enum, specifying whether we unmap a section of memory, * call free, run a user-provided delegate to free the memory, etc etc. * We'll suggest user write a subclass of UnmanagedMemoryStream that uses * a SafeHandle subclass to hold onto the memory. * Check for problems when using this in the negative parts of a * process's address space. We may need to use unsigned longs internally * and change the overflow detection logic. * * -----SECURITY MODEL AND SILVERLIGHT----- * A few key notes about exposing UMS in silverlight: * 1. No ctors are exposed to transparent code. This version of UMS only * supports byte* (not SafeBuffer). Therefore, framework code can create * a UMS and hand it to transparent code. Transparent code can use most * operations on a UMS, but not operations that directly expose a * pointer. * * 2. Scope of "unsafe" and non-CLS compliant operations reduced: The * Whidbey version of this class has CLSCompliant(false) at the class * level and unsafe modifiers at the method level. These were reduced to * only where the unsafe operation is performed -- i.e. immediately * around the pointer manipulation. Note that this brings UMS in line * with recent changes in pu/clr to support SafeBuffer. * * 3. Currently, the only caller that creates a UMS is ResourceManager, * which creates read-only UMSs, and therefore operations that can * change the length will throw because write isn't supported. A * conservative option would be to formalize the concept that _only_ * read-only UMSs can be creates, and enforce this by making WriteX and * SetLength SecurityCritical. However, this is a violation of * security inheritance rules, so we must keep these safe. The * following notes make this acceptable for future use. * a. a race condition in WriteX that could have allowed a thread to * read from unzeroed memory was fixed * b. memory region cannot be expanded beyond _capacity; in other * words, a UMS creator is saying a writeable UMS is safe to * write to anywhere in the memory range up to _capacity, specified * in the ctor. Even if the caller doesn't specify a capacity, then * length is used as the capacity. */ public class UnmanagedMemoryStream : Stream { // private const long UnmanagedMemStreamMaxLength = Int64.MaxValue; [System.Security.SecurityCritical] // auto-generated private SafeBuffer _buffer; [SecurityCritical] private unsafe byte* _mem; private long _length; private long _capacity; private long _position; private long _offset; private FileAccess _access; internal bool _isOpen; #if !FEATURE_PAL && FEATURE_ASYNC_IO || MONO [NonSerialized] private Task<Int32> _lastReadTask; // The last successful task returned from ReadAsync #endif // FEATURE_PAL && FEATURE_ASYNC_IO // Needed for subclasses that need to map a file, etc. [System.Security.SecuritySafeCritical] // auto-generated protected UnmanagedMemoryStream() { unsafe { _mem = null; } _isOpen = false; } [System.Security.SecuritySafeCritical] // auto-generated public UnmanagedMemoryStream(SafeBuffer buffer, long offset, long length) { Initialize(buffer, offset, length, FileAccess.Read, false); } [System.Security.SecuritySafeCritical] // auto-generated public UnmanagedMemoryStream(SafeBuffer buffer, long offset, long length, FileAccess access) { Initialize(buffer, offset, length, access, false); } // We must create one of these without doing a security check. This // class is created while security is trying to start up. Plus, doing // a Demand from Assembly.GetManifestResourceStream isn't useful. [System.Security.SecurityCritical] // auto-generated internal UnmanagedMemoryStream(SafeBuffer buffer, long offset, long length, FileAccess access, bool skipSecurityCheck) { Initialize(buffer, offset, length, access, skipSecurityCheck); } [System.Security.SecuritySafeCritical] // auto-generated protected void Initialize(SafeBuffer buffer, long offset, long length, FileAccess access) { Initialize(buffer, offset, length, access, false); } [System.Security.SecurityCritical] // auto-generated internal void Initialize(SafeBuffer buffer, long offset, long length, FileAccess access, bool skipSecurityCheck) { if (buffer == null) { throw new ArgumentNullException("buffer"); } if (offset < 0) { throw new ArgumentOutOfRangeException("offset", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); } if (length < 0) { throw new ArgumentOutOfRangeException("length", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); } if (buffer.ByteLength < (ulong)(offset + length)) { throw new ArgumentException(Environment.GetResourceString("Argument_InvalidSafeBufferOffLen")); } if (access < FileAccess.Read || access > FileAccess.ReadWrite) { throw new ArgumentOutOfRangeException("access"); } Contract.EndContractBlock(); if (_isOpen) { throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_CalledTwice")); } #if !DISABLE_CAS_USE if (!skipSecurityCheck) { #pragma warning disable 618 new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Demand(); #pragma warning restore 618 } #endif // check for wraparound unsafe { byte* pointer = null; RuntimeHelpers.PrepareConstrainedRegions(); try { buffer.AcquirePointer(ref pointer); if ( (pointer + offset + length) < pointer) { throw new ArgumentException(Environment.GetResourceString("ArgumentOutOfRange_UnmanagedMemStreamWrapAround")); } } finally { if (pointer != null) { buffer.ReleasePointer(); } } } _offset = offset; _buffer = buffer; _length = length; _capacity = length; _access = access; _isOpen = true; } [System.Security.SecurityCritical] // auto-generated [CLSCompliant(false)] public unsafe UnmanagedMemoryStream(byte* pointer, long length) { Initialize(pointer, length, length, FileAccess.Read, false); } [System.Security.SecurityCritical] // auto-generated [CLSCompliant(false)] public unsafe UnmanagedMemoryStream(byte* pointer, long length, long capacity, FileAccess access) { Initialize(pointer, length, capacity, access, false); } // We must create one of these without doing a security check. This // class is created while security is trying to start up. Plus, doing // a Demand from Assembly.GetManifestResourceStream isn't useful. [System.Security.SecurityCritical] // auto-generated internal unsafe UnmanagedMemoryStream(byte* pointer, long length, long capacity, FileAccess access, bool skipSecurityCheck) { Initialize(pointer, length, capacity, access, skipSecurityCheck); } [System.Security.SecurityCritical] // auto-generated [CLSCompliant(false)] protected unsafe void Initialize(byte* pointer, long length, long capacity, FileAccess access) { Initialize(pointer, length, capacity, access, false); } [System.Security.SecurityCritical] // auto-generated internal unsafe void Initialize(byte* pointer, long length, long capacity, FileAccess access, bool skipSecurityCheck) { if (pointer == null) throw new ArgumentNullException("pointer"); if (length < 0 || capacity < 0) throw new ArgumentOutOfRangeException((length < 0) ? "length" : "capacity", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (length > capacity) throw new ArgumentOutOfRangeException("length", Environment.GetResourceString("ArgumentOutOfRange_LengthGreaterThanCapacity")); Contract.EndContractBlock(); // Check for wraparound. if (((byte*) ((long)pointer + capacity)) < pointer) throw new ArgumentOutOfRangeException("capacity", Environment.GetResourceString("ArgumentOutOfRange_UnmanagedMemStreamWrapAround")); if (access < FileAccess.Read || access > FileAccess.ReadWrite) throw new ArgumentOutOfRangeException("access", Environment.GetResourceString("ArgumentOutOfRange_Enum")); if (_isOpen) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_CalledTwice")); #if !DISABLE_CAS_USE if (!skipSecurityCheck) #pragma warning disable 618 new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Demand(); #pragma warning restore 618 #endif _mem = pointer; _offset = 0; _length = length; _capacity = capacity; _access = access; _isOpen = true; } public override bool CanRead { [Pure] get { return _isOpen && (_access & FileAccess.Read) != 0; } } public override bool CanSeek { [Pure] get { return _isOpen; } } public override bool CanWrite { [Pure] get { return _isOpen && (_access & FileAccess.Write) != 0; } } [System.Security.SecuritySafeCritical] // auto-generated protected override void Dispose(bool disposing) { _isOpen = false; unsafe { _mem = null; } // Stream allocates WaitHandles for async calls. So for correctness // call base.Dispose(disposing) for better perf, avoiding waiting // for the finalizers to run on those types. base.Dispose(disposing); } public override void Flush() { if (!_isOpen) __Error.StreamIsClosed(); } #if !FEATURE_PAL && FEATURE_ASYNC_IO || MONO [HostProtection(ExternalThreading=true)] [ComVisible(false)] public override Task FlushAsync(CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) return Task.FromCancellation(cancellationToken); try { Flush(); return Task.CompletedTask; } catch(Exception ex) { return Task.FromException(ex); } } #endif // !FEATURE_PAL && FEATURE_ASYNC_IO public override long Length { get { if (!_isOpen) __Error.StreamIsClosed(); return Interlocked.Read(ref _length); } } public long Capacity { get { if (!_isOpen) __Error.StreamIsClosed(); return _capacity; } } public override long Position { get { if (!CanSeek) __Error.StreamIsClosed(); Contract.EndContractBlock(); return Interlocked.Read(ref _position); } [System.Security.SecuritySafeCritical] // auto-generated set { if (value < 0) throw new ArgumentOutOfRangeException("value", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); Contract.EndContractBlock(); if (!CanSeek) __Error.StreamIsClosed(); #if WIN32 unsafe { // On 32 bit machines, ensure we don't wrap around. if (value > (long) Int32.MaxValue || _mem + value < _mem) throw new ArgumentOutOfRangeException("value", Environment.GetResourceString("ArgumentOutOfRange_StreamLength")); } #endif Interlocked.Exchange(ref _position, value); } } [CLSCompliant(false)] public unsafe byte* PositionPointer { [System.Security.SecurityCritical] // auto-generated_required get { if (_buffer != null) { throw new NotSupportedException(Environment.GetResourceString("NotSupported_UmsSafeBuffer")); } // Use a temp to avoid a race long pos = Interlocked.Read(ref _position); if (pos > _capacity) throw new IndexOutOfRangeException(Environment.GetResourceString("IndexOutOfRange_UMSPosition")); byte * ptr = _mem + pos; if (!_isOpen) __Error.StreamIsClosed(); return ptr; } [System.Security.SecurityCritical] // auto-generated_required set { if (_buffer != null) throw new NotSupportedException(Environment.GetResourceString("NotSupported_UmsSafeBuffer")); if (!_isOpen) __Error.StreamIsClosed(); // Note: subtracting pointers returns an Int64. Working around // to avoid hitting compiler warning CS0652 on this line. if (new IntPtr(value - _mem).ToInt64() > UnmanagedMemStreamMaxLength) throw new ArgumentOutOfRangeException("offset", Environment.GetResourceString("ArgumentOutOfRange_UnmanagedMemStreamLength")); if (value < _mem) throw new IOException(Environment.GetResourceString("IO.IO_SeekBeforeBegin")); Interlocked.Exchange(ref _position, value - _mem); } } internal unsafe byte* Pointer { [System.Security.SecurityCritical] // auto-generated get { if (_buffer != null) throw new NotSupportedException(Environment.GetResourceString("NotSupported_UmsSafeBuffer")); return _mem; } } [System.Security.SecuritySafeCritical] // auto-generated public override int Read([In, Out] byte[] buffer, int offset, int count) { if (buffer==null) throw new ArgumentNullException("buffer", Environment.GetResourceString("ArgumentNull_Buffer")); if (offset < 0) throw new ArgumentOutOfRangeException("offset", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (count < 0) throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (buffer.Length - offset < count) throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen")); Contract.EndContractBlock(); // Keep this in [....] with contract validation in ReadAsync if (!_isOpen) __Error.StreamIsClosed(); if (!CanRead) __Error.ReadNotSupported(); // Use a local variable to avoid a race where another thread // changes our position after we decide we can read some bytes. long pos = Interlocked.Read(ref _position); long len = Interlocked.Read(ref _length); long n = len - pos; if (n > count) n = count; if (n <= 0) return 0; int nInt = (int) n; // Safe because n <= count, which is an Int32 if (nInt < 0) nInt = 0; // _position could be beyond EOF Contract.Assert(pos + nInt >= 0, "_position + n >= 0"); // len is less than 2^63 -1. if (_buffer != null) { unsafe { byte* pointer = null; RuntimeHelpers.PrepareConstrainedRegions(); try { _buffer.AcquirePointer(ref pointer); Buffer.Memcpy(buffer, offset, pointer + pos + _offset, 0, nInt); } finally { if (pointer != null) { _buffer.ReleasePointer(); } } } } else { unsafe { Buffer.Memcpy(buffer, offset, _mem + pos, 0, nInt); } } Interlocked.Exchange(ref _position, pos + n); return nInt; } #if !FEATURE_PAL && FEATURE_ASYNC_IO || MONO [HostProtection(ExternalThreading = true)] [ComVisible(false)] public override Task<Int32> ReadAsync(Byte[] buffer, Int32 offset, Int32 count, CancellationToken cancellationToken) { if (buffer==null) throw new ArgumentNullException("buffer", Environment.GetResourceString("ArgumentNull_Buffer")); if (offset < 0) throw new ArgumentOutOfRangeException("offset", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (count < 0) throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (buffer.Length - offset < count) throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen")); Contract.EndContractBlock(); // contract validation copied from Read(...) if (cancellationToken.IsCancellationRequested) return Task.FromCancellation<Int32>(cancellationToken); try { Int32 n = Read(buffer, offset, count); Task<Int32> t = _lastReadTask; return (t != null && t.Result == n) ? t : (_lastReadTask = Task.FromResult<Int32>(n)); } catch (Exception ex) { Contract.Assert(! (ex is OperationCanceledException)); return Task.FromException<Int32>(ex); } } #endif // !FEATURE_PAL && FEATURE_ASYNC_IO [System.Security.SecuritySafeCritical] // auto-generated public override int ReadByte() { if (!_isOpen) __Error.StreamIsClosed(); if (!CanRead) __Error.ReadNotSupported(); long pos = Interlocked.Read(ref _position); // Use a local to avoid a race condition long len = Interlocked.Read(ref _length); if (pos >= len) return -1; Interlocked.Exchange(ref _position, pos + 1); int result; if (_buffer != null) { unsafe { byte* pointer = null; RuntimeHelpers.PrepareConstrainedRegions(); try { _buffer.AcquirePointer(ref pointer); result = *(pointer + pos + _offset); } finally { if (pointer != null) { _buffer.ReleasePointer(); } } } } else { unsafe { result = _mem[pos]; } } return result; } public override long Seek(long offset, SeekOrigin loc) { if (!_isOpen) __Error.StreamIsClosed(); if (offset > UnmanagedMemStreamMaxLength) throw new ArgumentOutOfRangeException("offset", Environment.GetResourceString("ArgumentOutOfRange_UnmanagedMemStreamLength")); switch(loc) { case SeekOrigin.Begin: if (offset < 0) throw new IOException(Environment.GetResourceString("IO.IO_SeekBeforeBegin")); Interlocked.Exchange(ref _position, offset); break; case SeekOrigin.Current: long pos = Interlocked.Read(ref _position); if (offset + pos < 0) throw new IOException(Environment.GetResourceString("IO.IO_SeekBeforeBegin")); Interlocked.Exchange(ref _position, offset + pos); break; case SeekOrigin.End: long len = Interlocked.Read(ref _length); if (len + offset < 0) throw new IOException(Environment.GetResourceString("IO.IO_SeekBeforeBegin")); Interlocked.Exchange(ref _position, len + offset); break; default: throw new ArgumentException(Environment.GetResourceString("Argument_InvalidSeekOrigin")); } long finalPos = Interlocked.Read(ref _position); Contract.Assert(finalPos >= 0, "_position >= 0"); return finalPos; } [System.Security.SecuritySafeCritical] // auto-generated public override void SetLength(long value) { if (value < 0) throw new ArgumentOutOfRangeException("length", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); Contract.EndContractBlock(); if (_buffer != null) throw new NotSupportedException(Environment.GetResourceString("NotSupported_UmsSafeBuffer")); if (!_isOpen) __Error.StreamIsClosed(); if (!CanWrite) __Error.WriteNotSupported(); if (value > _capacity) throw new IOException(Environment.GetResourceString("IO.IO_FixedCapacity")); long pos = Interlocked.Read(ref _position); long len = Interlocked.Read(ref _length); if (value > len) { unsafe { Buffer.ZeroMemory(_mem+len, value-len); } } Interlocked.Exchange(ref _length, value); if (pos > value) { Interlocked.Exchange(ref _position, value); } } [System.Security.SecuritySafeCritical] // auto-generated public override void Write(byte[] buffer, int offset, int count) { if (buffer==null) throw new ArgumentNullException("buffer", Environment.GetResourceString("ArgumentNull_Buffer")); if (offset < 0) throw new ArgumentOutOfRangeException("offset", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (count < 0) throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (buffer.Length - offset < count) throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen")); Contract.EndContractBlock(); // Keep contract validation in [....] with WriteAsync(..) if (!_isOpen) __Error.StreamIsClosed(); if (!CanWrite) __Error.WriteNotSupported(); long pos = Interlocked.Read(ref _position); // Use a local to avoid a race condition long len = Interlocked.Read(ref _length); long n = pos + count; // Check for overflow if (n < 0) throw new IOException(Environment.GetResourceString("IO.IO_StreamTooLong")); if (n > _capacity) { throw new NotSupportedException(Environment.GetResourceString("IO.IO_FixedCapacity")); } if (_buffer == null) { // Check to see whether we are now expanding the stream and must // zero any memory in the middle. if (pos > len) { unsafe { Buffer.ZeroMemory(_mem+len, pos-len); } } // set length after zeroing memory to avoid race condition of accessing unzeroed memory if (n > len) { Interlocked.Exchange(ref _length, n); } } if (_buffer != null) { long bytesLeft = _capacity - pos; if (bytesLeft < count) { throw new ArgumentException(Environment.GetResourceString("Arg_BufferTooSmall")); } unsafe { byte* pointer = null; RuntimeHelpers.PrepareConstrainedRegions(); try { _buffer.AcquirePointer(ref pointer); Buffer.Memcpy(pointer + pos + _offset, 0, buffer, offset, count); } finally { if (pointer != null) { _buffer.ReleasePointer(); } } } } else { unsafe { Buffer.Memcpy(_mem + pos, 0, buffer, offset, count); } } Interlocked.Exchange(ref _position, n); return; } #if !FEATURE_PAL && FEATURE_ASYNC_IO || MONO [HostProtection(ExternalThreading = true)] [ComVisible(false)] public override Task WriteAsync(Byte[] buffer, Int32 offset, Int32 count, CancellationToken cancellationToken) { if (buffer==null) throw new ArgumentNullException("buffer", Environment.GetResourceString("ArgumentNull_Buffer")); if (offset < 0) throw new ArgumentOutOfRangeException("offset", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (count < 0) throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (buffer.Length - offset < count) throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen")); Contract.EndContractBlock(); // contract validation copied from Write(..) if (cancellationToken.IsCancellationRequested) return Task.FromCancellation(cancellationToken); try { Write(buffer, offset, count); return Task.CompletedTask; } catch (Exception ex) { Contract.Assert(! (ex is OperationCanceledException)); return Task.FromException<Int32>(ex); } } #endif // !FEATURE_PAL && FEATURE_ASYNC_IO [System.Security.SecuritySafeCritical] // auto-generated public override void WriteByte(byte value) { if (!_isOpen) __Error.StreamIsClosed(); if (!CanWrite) __Error.WriteNotSupported(); long pos = Interlocked.Read(ref _position); // Use a local to avoid a race condition long len = Interlocked.Read(ref _length); long n = pos + 1; if (pos >= len) { // Check for overflow if (n < 0) throw new IOException(Environment.GetResourceString("IO.IO_StreamTooLong")); if (n > _capacity) throw new NotSupportedException(Environment.GetResourceString("IO.IO_FixedCapacity")); // Check to see whether we are now expanding the stream and must // zero any memory in the middle. // don't do if created from SafeBuffer if (_buffer == null) { if (pos > len) { unsafe { Buffer.ZeroMemory(_mem+len, pos-len); } } // set length after zeroing memory to avoid race condition of accessing unzeroed memory Interlocked.Exchange(ref _length, n); } } if (_buffer != null) { unsafe { byte* pointer = null; RuntimeHelpers.PrepareConstrainedRegions(); try { _buffer.AcquirePointer(ref pointer); *(pointer + pos + _offset) = value; } finally { if (pointer != null) { _buffer.ReleasePointer(); } } } } else { unsafe { _mem[pos] = value; } } Interlocked.Exchange(ref _position, n); } } }
/* * Swaggy Jenkins * * Jenkins API clients generated from Swagger / Open API specification * * The version of the OpenAPI document: 1.1.2-pre.0 * Contact: blah@cliffano.com * Generated by: https://openapi-generator.tech */ using System; using System.Linq; using System.Text; using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.Runtime.Serialization; using Newtonsoft.Json; using Org.OpenAPITools.Converters; namespace Org.OpenAPITools.Models { /// <summary> /// /// </summary> [DataContract] public partial class PipelineImpl : IEquatable<PipelineImpl> { /// <summary> /// Gets or Sets Class /// </summary> [DataMember(Name="_class", EmitDefaultValue=false)] public string Class { get; set; } /// <summary> /// Gets or Sets DisplayName /// </summary> [DataMember(Name="displayName", EmitDefaultValue=false)] public string DisplayName { get; set; } /// <summary> /// Gets or Sets EstimatedDurationInMillis /// </summary> [DataMember(Name="estimatedDurationInMillis", EmitDefaultValue=false)] public int EstimatedDurationInMillis { get; set; } /// <summary> /// Gets or Sets FullName /// </summary> [DataMember(Name="fullName", EmitDefaultValue=false)] public string FullName { get; set; } /// <summary> /// Gets or Sets LatestRun /// </summary> [DataMember(Name="latestRun", EmitDefaultValue=false)] public string LatestRun { get; set; } /// <summary> /// Gets or Sets Name /// </summary> [DataMember(Name="name", EmitDefaultValue=false)] public string Name { get; set; } /// <summary> /// Gets or Sets Organization /// </summary> [DataMember(Name="organization", EmitDefaultValue=false)] public string Organization { get; set; } /// <summary> /// Gets or Sets WeatherScore /// </summary> [DataMember(Name="weatherScore", EmitDefaultValue=false)] public int WeatherScore { get; set; } /// <summary> /// Gets or Sets Links /// </summary> [DataMember(Name="_links", EmitDefaultValue=false)] public PipelineImpllinks Links { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class PipelineImpl {\n"); sb.Append(" Class: ").Append(Class).Append("\n"); sb.Append(" DisplayName: ").Append(DisplayName).Append("\n"); sb.Append(" EstimatedDurationInMillis: ").Append(EstimatedDurationInMillis).Append("\n"); sb.Append(" FullName: ").Append(FullName).Append("\n"); sb.Append(" LatestRun: ").Append(LatestRun).Append("\n"); sb.Append(" Name: ").Append(Name).Append("\n"); sb.Append(" Organization: ").Append(Organization).Append("\n"); sb.Append(" WeatherScore: ").Append(WeatherScore).Append("\n"); sb.Append(" Links: ").Append(Links).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="obj">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object obj) { if (obj is null) return false; if (ReferenceEquals(this, obj)) return true; return obj.GetType() == GetType() && Equals((PipelineImpl)obj); } /// <summary> /// Returns true if PipelineImpl instances are equal /// </summary> /// <param name="other">Instance of PipelineImpl to be compared</param> /// <returns>Boolean</returns> public bool Equals(PipelineImpl other) { if (other is null) return false; if (ReferenceEquals(this, other)) return true; return ( Class == other.Class || Class != null && Class.Equals(other.Class) ) && ( DisplayName == other.DisplayName || DisplayName != null && DisplayName.Equals(other.DisplayName) ) && ( EstimatedDurationInMillis == other.EstimatedDurationInMillis || EstimatedDurationInMillis.Equals(other.EstimatedDurationInMillis) ) && ( FullName == other.FullName || FullName != null && FullName.Equals(other.FullName) ) && ( LatestRun == other.LatestRun || LatestRun != null && LatestRun.Equals(other.LatestRun) ) && ( Name == other.Name || Name != null && Name.Equals(other.Name) ) && ( Organization == other.Organization || Organization != null && Organization.Equals(other.Organization) ) && ( WeatherScore == other.WeatherScore || WeatherScore.Equals(other.WeatherScore) ) && ( Links == other.Links || Links != null && Links.Equals(other.Links) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { var hashCode = 41; // Suitable nullity checks etc, of course :) if (Class != null) hashCode = hashCode * 59 + Class.GetHashCode(); if (DisplayName != null) hashCode = hashCode * 59 + DisplayName.GetHashCode(); hashCode = hashCode * 59 + EstimatedDurationInMillis.GetHashCode(); if (FullName != null) hashCode = hashCode * 59 + FullName.GetHashCode(); if (LatestRun != null) hashCode = hashCode * 59 + LatestRun.GetHashCode(); if (Name != null) hashCode = hashCode * 59 + Name.GetHashCode(); if (Organization != null) hashCode = hashCode * 59 + Organization.GetHashCode(); hashCode = hashCode * 59 + WeatherScore.GetHashCode(); if (Links != null) hashCode = hashCode * 59 + Links.GetHashCode(); return hashCode; } } #region Operators #pragma warning disable 1591 public static bool operator ==(PipelineImpl left, PipelineImpl right) { return Equals(left, right); } public static bool operator !=(PipelineImpl left, PipelineImpl right) { return !Equals(left, right); } #pragma warning restore 1591 #endregion Operators } }
using System; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel; using System.Linq; using Csla; using Invoices.DataAccess; namespace Invoices.Business { /// <summary> /// ProductTypeUpdatedByRootList (read only list).<br/> /// This is a generated base class of <see cref="ProductTypeUpdatedByRootList"/> business object. /// This class is a root collection. /// </summary> /// <remarks> /// The items of the collection are <see cref="ProductTypeUpdatedByRootInfo"/> objects. /// Updated by ProductTypeEdit /// </remarks> [Serializable] #if WINFORMS public partial class ProductTypeUpdatedByRootList : ReadOnlyBindingListBase<ProductTypeUpdatedByRootList, ProductTypeUpdatedByRootInfo> #else public partial class ProductTypeUpdatedByRootList : ReadOnlyListBase<ProductTypeUpdatedByRootList, ProductTypeUpdatedByRootInfo> #endif { #region Event handler properties [NotUndoable] private static bool _singleInstanceSavedHandler = true; /// <summary> /// Gets or sets a value indicating whether only a single instance should handle the Saved event. /// </summary> /// <value> /// <c>true</c> if only a single instance should handle the Saved event; otherwise, <c>false</c>. /// </value> public static bool SingleInstanceSavedHandler { get { return _singleInstanceSavedHandler; } set { _singleInstanceSavedHandler = value; } } #endregion #region Collection Business Methods /// <summary> /// Determines whether a <see cref="ProductTypeUpdatedByRootInfo"/> item is in the collection. /// </summary> /// <param name="productTypeId">The ProductTypeId of the item to search for.</param> /// <returns><c>true</c> if the ProductTypeUpdatedByRootInfo is a collection item; otherwise, <c>false</c>.</returns> public bool Contains(int productTypeId) { foreach (var productTypeUpdatedByRootInfo in this) { if (productTypeUpdatedByRootInfo.ProductTypeId == productTypeId) { return true; } } return false; } #endregion #region Factory Methods /// <summary> /// Factory method. Loads a <see cref="ProductTypeUpdatedByRootList"/> collection. /// </summary> /// <returns>A reference to the fetched <see cref="ProductTypeUpdatedByRootList"/> collection.</returns> public static ProductTypeUpdatedByRootList GetProductTypeUpdatedByRootList() { return DataPortal.Fetch<ProductTypeUpdatedByRootList>(); } /// <summary> /// Factory method. Asynchronously loads a <see cref="ProductTypeUpdatedByRootList"/> collection. /// </summary> /// <param name="callback">The completion callback method.</param> public static void GetProductTypeUpdatedByRootList(EventHandler<DataPortalResult<ProductTypeUpdatedByRootList>> callback) { DataPortal.BeginFetch<ProductTypeUpdatedByRootList>(callback); } #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="ProductTypeUpdatedByRootList"/> class. /// </summary> /// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public ProductTypeUpdatedByRootList() { // Use factory methods and do not use direct creation. ProductTypeEditSaved.Register(this); var rlce = RaiseListChangedEvents; RaiseListChangedEvents = false; AllowNew = false; AllowEdit = false; AllowRemove = false; RaiseListChangedEvents = rlce; } #endregion #region Saved Event Handler /// <summary> /// Handle Saved events of <see cref="ProductTypeEdit"/> to update the list of <see cref="ProductTypeUpdatedByRootInfo"/> objects. /// </summary> /// <param name="sender">The sender of the event.</param> /// <param name="e">The <see cref="Csla.Core.SavedEventArgs"/> instance containing the event data.</param> internal void ProductTypeEditSavedHandler(object sender, Csla.Core.SavedEventArgs e) { var obj = (ProductTypeEdit)e.NewObject; if (((ProductTypeEdit)sender).IsNew) { IsReadOnly = false; var rlce = RaiseListChangedEvents; RaiseListChangedEvents = true; Add(ProductTypeUpdatedByRootInfo.LoadInfo(obj)); RaiseListChangedEvents = rlce; IsReadOnly = true; } else if (((ProductTypeEdit)sender).IsDeleted) { for (int index = 0; index < this.Count; index++) { var child = this[index]; if (child.ProductTypeId == obj.ProductTypeId) { IsReadOnly = false; var rlce = RaiseListChangedEvents; RaiseListChangedEvents = true; this.RemoveItem(index); RaiseListChangedEvents = rlce; IsReadOnly = true; break; } } } else { for (int index = 0; index < this.Count; index++) { var child = this[index]; if (child.ProductTypeId == obj.ProductTypeId) { child.UpdatePropertiesOnSaved(obj); #if !WINFORMS var notifyCollectionChangedEventArgs = new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Replace, child, child, index); OnCollectionChanged(notifyCollectionChangedEventArgs); #else var listChangedEventArgs = new ListChangedEventArgs(ListChangedType.ItemChanged, index); OnListChanged(listChangedEventArgs); #endif break; } } } } #endregion #region Data Access /// <summary> /// Loads a <see cref="ProductTypeUpdatedByRootList"/> collection from the database. /// </summary> protected void DataPortal_Fetch() { var args = new DataPortalHookArgs(); OnFetchPre(args); using (var dalManager = DalFactoryInvoices.GetManager()) { var dal = dalManager.GetProvider<IProductTypeUpdatedByRootListDal>(); var data = dal.Fetch(); Fetch(data); } OnFetchPost(args); } /// <summary> /// Loads all <see cref="ProductTypeUpdatedByRootList"/> collection items from the given list of ProductTypeUpdatedByRootInfoDto. /// </summary> /// <param name="data">The list of <see cref="ProductTypeUpdatedByRootInfoDto"/>.</param> private void Fetch(List<ProductTypeUpdatedByRootInfoDto> data) { IsReadOnly = false; var rlce = RaiseListChangedEvents; RaiseListChangedEvents = false; foreach (var dto in data) { Add(DataPortal.FetchChild<ProductTypeUpdatedByRootInfo>(dto)); } RaiseListChangedEvents = rlce; IsReadOnly = true; } #endregion #region DataPortal Hooks /// <summary> /// Occurs after setting query parameters and before the fetch operation. /// </summary> partial void OnFetchPre(DataPortalHookArgs args); /// <summary> /// Occurs after the fetch operation (object or collection is fully loaded and set up). /// </summary> partial void OnFetchPost(DataPortalHookArgs args); #endregion #region ProductTypeEditSaved nested class // TODO: edit "ProductTypeUpdatedByRootList.cs", uncomment the "OnDeserialized" method and add the following line: // TODO: ProductTypeEditSaved.Register(this); /// <summary> /// Nested class to manage the Saved events of <see cref="ProductTypeEdit"/> /// to update the list of <see cref="ProductTypeUpdatedByRootInfo"/> objects. /// </summary> private static class ProductTypeEditSaved { private static List<WeakReference> _references; private static bool Found(object obj) { return _references.Any(reference => Equals(reference.Target, obj)); } /// <summary> /// Registers a ProductTypeUpdatedByRootList instance to handle Saved events. /// to update the list of <see cref="ProductTypeUpdatedByRootInfo"/> objects. /// </summary> /// <param name="obj">The ProductTypeUpdatedByRootList instance.</param> public static void Register(ProductTypeUpdatedByRootList obj) { var mustRegister = _references == null; if (mustRegister) _references = new List<WeakReference>(); if (ProductTypeUpdatedByRootList.SingleInstanceSavedHandler) _references.Clear(); if (!Found(obj)) _references.Add(new WeakReference(obj)); if (mustRegister) ProductTypeEdit.ProductTypeEditSaved += ProductTypeEditSavedHandler; } /// <summary> /// Handles Saved events of <see cref="ProductTypeEdit"/>. /// </summary> /// <param name="sender">The sender of the event.</param> /// <param name="e">The <see cref="Csla.Core.SavedEventArgs"/> instance containing the event data.</param> public static void ProductTypeEditSavedHandler(object sender, Csla.Core.SavedEventArgs e) { foreach (var reference in _references) { if (reference.IsAlive) ((ProductTypeUpdatedByRootList) reference.Target).ProductTypeEditSavedHandler(sender, e); } } /// <summary> /// Removes event handling and clears all registered ProductTypeUpdatedByRootList instances. /// </summary> public static void Unregister() { ProductTypeEdit.ProductTypeEditSaved -= ProductTypeEditSavedHandler; _references = null; } } #endregion } }
using System; using System.Collections.Generic; using Content.Server.Atmos.Monitor.Components; using Content.Server.Atmos.Piping.Components; using Content.Server.DeviceNetwork; using Content.Server.DeviceNetwork.Components; using Content.Server.DeviceNetwork.Systems; using Content.Server.Popups; using Content.Server.Power.Components; using Content.Server.WireHacking; using Content.Shared.Access.Components; using Content.Shared.Access.Systems; using Content.Shared.Atmos; using Content.Shared.Atmos.Monitor; using Content.Shared.Atmos.Monitor.Components; using Content.Shared.Interaction; using Content.Shared.Popups; using Robust.Server.GameObjects; using Robust.Shared.GameObjects; using Robust.Shared.IoC; using Robust.Shared.Localization; using Robust.Shared.Player; namespace Content.Server.Atmos.Monitor.Systems { // AirAlarm system - specific for atmos devices, rather than // atmos monitors. // // oh boy, message passing! // // Commands should always be sent into packet's Command // data key. In response, a packet will be transmitted // with the response type as its command, and the // response data in its data key. public sealed class AirAlarmSystem : EntitySystem { [Dependency] private readonly DeviceNetworkSystem _deviceNet = default!; [Dependency] private readonly AtmosMonitorSystem _atmosMonitorSystem = default!; [Dependency] private readonly UserInterfaceSystem _uiSystem = default!; [Dependency] private readonly AccessReaderSystem _accessSystem = default!; [Dependency] private readonly PopupSystem _popup = default!; [Dependency] private readonly SharedInteractionSystem _interactionSystem = default!; #region Device Network API public const int Freq = AtmosMonitorSystem.AtmosMonitorApcFreq; /// <summary> /// Command to set device data within the air alarm's network. /// </summary> public const string AirAlarmSetData = "air_alarm_set_device_data"; /// <summary> /// Command to request a sync from devices in an air alarm's network. /// </summary> public const string AirAlarmSyncCmd = "air_alarm_sync_devices"; /// <summary> /// Command to set an air alarm's mode. /// </summary> public const string AirAlarmSetMode = "air_alarm_set_mode"; // -- Packet Data -- /// <summary> /// Data response to an AirAlarmSetData command. /// </summary> public const string AirAlarmSetDataStatus = "air_alarm_set_device_data_status"; /// <summary> /// Data response to an AirAlarmSync command. Contains /// IAtmosDeviceData in this system's implementation. /// </summary> public const string AirAlarmSyncData = "air_alarm_device_sync_data"; // -- API -- /// <summary> /// Set the data for an air alarm managed device. /// </summary> /// <param name="address">The address of the device.</param> /// <param name="data">The data to send to the device.</param> public void SetData(EntityUid uid, string address, IAtmosDeviceData data) { if (EntityManager.TryGetComponent(uid, out AtmosMonitorComponent monitor) && !monitor.NetEnabled) return; var payload = new NetworkPayload { [DeviceNetworkConstants.Command] = AirAlarmSetData, // [AirAlarmTypeData] = type, [AirAlarmSetData] = data }; _deviceNet.QueuePacket(uid, address, Freq, payload); } /// <summary> /// Broadcast a sync packet to an air alarm's local network. /// </summary> public void SyncAllDevices(EntityUid uid) { if (EntityManager.TryGetComponent(uid, out AtmosMonitorComponent monitor) && !monitor.NetEnabled) return; var payload = new NetworkPayload { [DeviceNetworkConstants.Command] = AirAlarmSyncCmd }; _deviceNet.QueuePacket(uid, string.Empty, Freq, payload, true); } /// <summary> /// Send a sync packet to a specific device from an air alarm. /// </summary> /// <param name="address">The address of the device.</param> public void SyncDevice(EntityUid uid, string address) { if (EntityManager.TryGetComponent(uid, out AtmosMonitorComponent monitor) && !monitor.NetEnabled) return; var payload = new NetworkPayload { [DeviceNetworkConstants.Command] = AirAlarmSyncCmd }; _deviceNet.QueuePacket(uid, address, Freq, payload); } /// <summary> /// Sync this air alarm's mode with the rest of the network. /// </summary> /// <param name="mode">The mode to sync with the rest of the network.</param> public void SyncMode(EntityUid uid, AirAlarmMode mode) { if (EntityManager.TryGetComponent(uid, out AtmosMonitorComponent monitor) && !monitor.NetEnabled) return; var payload = new NetworkPayload { [DeviceNetworkConstants.Command] = AirAlarmSetMode, [AirAlarmSetMode] = mode }; _deviceNet.QueuePacket(uid, string.Empty, Freq, payload, true); } #endregion #region Events public override void Initialize() { SubscribeLocalEvent<AirAlarmComponent, PacketSentEvent>(OnPacketRecv); SubscribeLocalEvent<AirAlarmComponent, AtmosDeviceUpdateEvent>(OnAtmosUpdate); SubscribeLocalEvent<AirAlarmComponent, AtmosMonitorAlarmEvent>(OnAtmosAlarm); SubscribeLocalEvent<AirAlarmComponent, PowerChangedEvent>(OnPowerChanged); SubscribeLocalEvent<AirAlarmComponent, AirAlarmResyncAllDevicesMessage>(OnResyncAll); SubscribeLocalEvent<AirAlarmComponent, AirAlarmUpdateAlarmModeMessage>(OnUpdateAlarmMode); SubscribeLocalEvent<AirAlarmComponent, AirAlarmUpdateAlarmThresholdMessage>(OnUpdateThreshold); SubscribeLocalEvent<AirAlarmComponent, AirAlarmUpdateDeviceDataMessage>(OnUpdateDeviceData); SubscribeLocalEvent<AirAlarmComponent, BoundUIClosedEvent>(OnClose); SubscribeLocalEvent<AirAlarmComponent, ComponentShutdown>(OnShutdown); SubscribeLocalEvent<AirAlarmComponent, InteractHandEvent>(OnInteract); } private void OnPowerChanged(EntityUid uid, AirAlarmComponent component, PowerChangedEvent args) { if (!args.Powered) { ForceCloseAllInterfaces(uid); component.CurrentModeUpdater = null; component.DeviceData.Clear(); } } private void OnClose(EntityUid uid, AirAlarmComponent component, BoundUIClosedEvent args) { component.ActivePlayers.Remove(args.Session.UserId); if (component.ActivePlayers.Count == 0) RemoveActiveInterface(uid); } private void OnShutdown(EntityUid uid, AirAlarmComponent component, ComponentShutdown args) { _activeUserInterfaces.Remove(uid); } private void OnInteract(EntityUid uid, AirAlarmComponent component, InteractHandEvent args) { if (!_interactionSystem.InRangeUnobstructed(args.User, args.Target)) return; if (!EntityManager.TryGetComponent(args.User, out ActorComponent? actor)) return; if (EntityManager.TryGetComponent(uid, out WiresComponent wire) && wire.IsPanelOpen) { args.Handled = false; return; } if (EntityManager.TryGetComponent(uid, out ApcPowerReceiverComponent recv) && !recv.Powered) return; _uiSystem.GetUiOrNull(component.Owner, SharedAirAlarmInterfaceKey.Key)?.Open(actor.PlayerSession); component.ActivePlayers.Add(actor.PlayerSession.UserId); AddActiveInterface(uid); SendAddress(uid); SendAlarmMode(uid); SendThresholds(uid); SyncAllDevices(uid); SendAirData(uid); } private void OnResyncAll(EntityUid uid, AirAlarmComponent component, AirAlarmResyncAllDevicesMessage args) { if (AccessCheck(uid, args.Session.AttachedEntity, component)) { component.DeviceData.Clear(); SyncAllDevices(uid); } } private void OnUpdateAlarmMode(EntityUid uid, AirAlarmComponent component, AirAlarmUpdateAlarmModeMessage args) { string addr = string.Empty; if (EntityManager.TryGetComponent(uid, out DeviceNetworkComponent netConn)) addr = netConn.Address; if (AccessCheck(uid, args.Session.AttachedEntity, component)) SetMode(uid, addr, args.Mode, true, false); else SendAlarmMode(uid); } private void OnUpdateThreshold(EntityUid uid, AirAlarmComponent component, AirAlarmUpdateAlarmThresholdMessage args) { if (AccessCheck(uid, args.Session.AttachedEntity, component)) SetThreshold(uid, args.Threshold, args.Type, args.Gas); else SendThresholds(uid); } private void OnUpdateDeviceData(EntityUid uid, AirAlarmComponent component, AirAlarmUpdateDeviceDataMessage args) { if (AccessCheck(uid, args.Session.AttachedEntity, component)) SetDeviceData(uid, args.Address, args.Data); else SyncDevice(uid, args.Address); } private bool AccessCheck(EntityUid uid, EntityUid? user, AirAlarmComponent? component = null) { if (!Resolve(uid, ref component)) return false; if (!EntityManager.TryGetComponent(uid, out AccessReaderComponent reader) || user == null) return false; if (!_accessSystem.IsAllowed(reader, user.Value) && !component.FullAccess) { _popup.PopupEntity(Loc.GetString("air-alarm-ui-access-denied"), user.Value, Filter.Entities(user.Value)); return false; } return true; } private void OnAtmosAlarm(EntityUid uid, AirAlarmComponent component, AtmosMonitorAlarmEvent args) { if (component.ActivePlayers.Count != 0) { SyncAllDevices(uid); SendAirData(uid); } string addr = string.Empty; if (EntityManager.TryGetComponent(uid, out DeviceNetworkComponent netConn)) addr = netConn.Address; if (args.HighestNetworkType == AtmosMonitorAlarmType.Danger) { SetMode(uid, addr, AirAlarmMode.None, true); // set mode to off to mimic the vents/scrubbers being turned off // update UI // // no, the mode isn't processed here - it's literally just // set to what mimics 'off' } else if (args.HighestNetworkType == AtmosMonitorAlarmType.Normal) { // if the mode is still set to off, set it to filtering instead // alternatively, set it to the last saved mode // // no, this still doesn't execute the mode SetMode(uid, addr, AirAlarmMode.Filtering, true); } } #endregion #region Air Alarm Settings /// <summary> /// Set a threshold on an air alarm. /// </summary> /// <param name="threshold">New threshold data.</param> public void SetThreshold(EntityUid uid, AtmosAlarmThreshold threshold, AtmosMonitorThresholdType type, Gas? gas = null, AirAlarmComponent? controller = null) { if (!Resolve(uid, ref controller)) return; _atmosMonitorSystem.SetThreshold(uid, type, threshold, gas); // TODO: Use BUI states instead... _uiSystem.TrySendUiMessage(uid, SharedAirAlarmInterfaceKey.Key, new AirAlarmUpdateAlarmThresholdMessage(type, threshold, gas)); } /// <summary> /// Set an air alarm's mode. /// </summary> /// <param name="origin">The origin address of this mode set. Used for network sync.</param> /// <param name="mode">The mode to set the alarm to.</param> /// <param name="sync">Whether to sync this mode change to the network or not. Defaults to false.</param> /// <param name="uiOnly">Whether this change is for the UI only, or if it changes the air alarm's operating mode. Defaults to true.</param> public void SetMode(EntityUid uid, string origin, AirAlarmMode mode, bool sync = false, bool uiOnly = true, AirAlarmComponent? controller = null) { if (!Resolve(uid, ref controller)) return; controller.CurrentMode = mode; // setting it to UI only maans we don't have // to deal with the issue of not-single-owner // alarm mode executors if (!uiOnly) { var newMode = AirAlarmModeFactory.ModeToExecutor(mode); if (newMode != null) { newMode.Execute(uid); if (newMode is IAirAlarmModeUpdate updatedMode) { controller.CurrentModeUpdater = updatedMode; controller.CurrentModeUpdater.NetOwner = origin; } else if (controller.CurrentModeUpdater != null) controller.CurrentModeUpdater = null; } } // only one air alarm in a network can use an air alarm mode // that updates, so even if it's a ui-only change, // we have to invalidte the last mode's updater and // remove it because otherwise it'll execute a now // invalid mode else if (controller.CurrentModeUpdater != null && controller.CurrentModeUpdater.NetOwner != origin) controller.CurrentModeUpdater = null; // controller.SendMessage(new AirAlarmUpdateAlarmModeMessage(mode)); // TODO: Use BUI states instead... _uiSystem.TrySendUiMessage(uid, SharedAirAlarmInterfaceKey.Key, new AirAlarmUpdateAlarmModeMessage(mode)); // setting sync deals with the issue of air alarms // in the same network needing to have the same mode // as other alarms if (sync) SyncMode(uid, mode); } /// <summary> /// Sets device data. Practically a wrapper around the packet sending function, SetData. /// </summary> /// <param name="address">The address to send the new data to.</param> /// <param name="devData">The device data to be sent.</param> public void SetDeviceData(EntityUid uid, string address, IAtmosDeviceData devData, AirAlarmComponent? controller = null) { if (!Resolve(uid, ref controller)) return; devData.Dirty = true; SetData(uid, address, devData); } private void OnPacketRecv(EntityUid uid, AirAlarmComponent controller, PacketSentEvent args) { if (!args.Data.TryGetValue(DeviceNetworkConstants.Command, out string? cmd)) return; switch (cmd) { case AirAlarmSyncData: if (!args.Data.TryGetValue(AirAlarmSyncData, out IAtmosDeviceData? data) || data == null || !controller.CanSync) break; // Save into component. // Sync data to interface. // _airAlarmDataSystem.UpdateDeviceData(uid, args.SenderAddress, data); // _uiSystem.TrySendUiMessage(uid, SharedAirAlarmInterfaceKey.Key, new AirAlarmUpdateDeviceDataMessage(args.SenderAddress, data)); if (HasComp<WiresComponent>(uid)) controller.UpdateWires(); if (!controller.DeviceData.TryAdd(args.SenderAddress, data)) controller.DeviceData[args.SenderAddress] = data; return; case AirAlarmSetDataStatus: if (!args.Data.TryGetValue(AirAlarmSetDataStatus, out bool dataStatus)) break; // Sync data to interface. // This should say if the result // failed, or succeeded. Don't save it.l SyncDevice(uid, args.SenderAddress); return; case AirAlarmSetMode: if (!args.Data.TryGetValue(AirAlarmSetMode, out AirAlarmMode alarmMode)) break; SetMode(uid, args.SenderAddress, alarmMode); return; } } #endregion #region UI // List of active user interfaces. private HashSet<EntityUid> _activeUserInterfaces = new(); /// <summary> /// Adds an active interface to be updated. /// </summary> public void AddActiveInterface(EntityUid uid) => _activeUserInterfaces.Add(uid); /// <summary> /// Removes an active interface from the system update loop. /// </summary> public void RemoveActiveInterface(EntityUid uid) => _activeUserInterfaces.Remove(uid); /// <summary> /// Force closes all interfaces currently open related to this air alarm. /// </summary> public void ForceCloseAllInterfaces(EntityUid uid) => _uiSystem.TryCloseAll(uid, SharedAirAlarmInterfaceKey.Key); private void SendAddress(EntityUid uid, DeviceNetworkComponent? netConn = null) { if (!Resolve(uid, ref netConn)) return; // TODO: Use BUI states instead... _uiSystem.TrySendUiMessage(uid, SharedAirAlarmInterfaceKey.Key, new AirAlarmSetAddressMessage(netConn.Address)); } /// <summary> /// Update an interface's air data. This is all the 'hot' data /// that an air alarm contains server-side. Updated with a whopping 8 /// delay automatically once a UI is in the loop. /// </summary> public void SendAirData(EntityUid uid, AirAlarmComponent? alarm = null, AtmosMonitorComponent? monitor = null, ApcPowerReceiverComponent? power = null) { if (!Resolve(uid, ref alarm, ref monitor, ref power)) return; if (!power.Powered) return; if (monitor.TileGas != null) { var gases = new Dictionary<Gas, float>(); foreach (var gas in Enum.GetValues<Gas>()) gases.Add(gas, monitor.TileGas.GetMoles(gas)); var airData = new AirAlarmAirData(monitor.TileGas.Pressure, monitor.TileGas.Temperature, monitor.TileGas.TotalMoles, monitor.LastAlarmState, gases); // TODO: Use BUI states instead... _uiSystem.TrySendUiMessage(uid, SharedAirAlarmInterfaceKey.Key, new AirAlarmUpdateAirDataMessage(airData)); } } /// <summary> /// Send an air alarm mode to any open interface related to an air alarm. /// </summary> public void SendAlarmMode(EntityUid uid, AtmosMonitorComponent? monitor = null, ApcPowerReceiverComponent? power = null, AirAlarmComponent? controller = null) { if (!Resolve(uid, ref monitor, ref power, ref controller) || !power.Powered) return; // TODO: Use BUI states instead... _uiSystem.TrySendUiMessage(uid, SharedAirAlarmInterfaceKey.Key, new AirAlarmUpdateAlarmModeMessage(controller.CurrentMode)); } /// <summary> /// Send all thresholds to any open interface related to a given air alarm. /// </summary> public void SendThresholds(EntityUid uid, AtmosMonitorComponent? monitor = null, ApcPowerReceiverComponent? power = null, AirAlarmComponent? controller = null) { if (!Resolve(uid, ref monitor, ref power, ref controller) || !power.Powered) return; if (monitor.PressureThreshold == null && monitor.TemperatureThreshold == null && monitor.GasThresholds == null) return; // TODO: Use BUI states instead... if (monitor.PressureThreshold != null) { _uiSystem.TrySendUiMessage(uid, SharedAirAlarmInterfaceKey.Key, new AirAlarmUpdateAlarmThresholdMessage(AtmosMonitorThresholdType.Pressure, monitor.PressureThreshold)); } if (monitor.TemperatureThreshold != null) { _uiSystem.TrySendUiMessage(uid, SharedAirAlarmInterfaceKey.Key, new AirAlarmUpdateAlarmThresholdMessage(AtmosMonitorThresholdType.Temperature, monitor.TemperatureThreshold)); } if (monitor.GasThresholds != null) { foreach (var (gas, threshold) in monitor.GasThresholds) _uiSystem.TrySendUiMessage(uid, SharedAirAlarmInterfaceKey.Key, new AirAlarmUpdateAlarmThresholdMessage(AtmosMonitorThresholdType.Gas, threshold, gas)); } } public void OnAtmosUpdate(EntityUid uid, AirAlarmComponent alarm, AtmosDeviceUpdateEvent args) { if (alarm.CurrentModeUpdater != null) alarm.CurrentModeUpdater.Update(uid); } private const float _delay = 8f; private float _timer = 0f; public override void Update(float frameTime) { _timer += frameTime; if (_timer >= _delay) { _timer = 0f; foreach (var uid in _activeUserInterfaces) { // TODO: Awful idea, use BUI states instead... SendAirData(uid); _uiSystem.TrySetUiState(uid, SharedAirAlarmInterfaceKey.Key, new AirAlarmUIState()); } } } #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 PhoneManagementSystem.WebApi.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) 2014-2015 Kendar.org // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, // modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software // is furnished to do so, subject to the following conditions: // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS // BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF // OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // =========================================================== #if NOT_YET using System; using System.Collections.Generic; using System.Security.Cryptography; using System.Text; using System.Threading; using HttpServer.Headers; using HttpServer.Logging; using HttpServer.Tools; namespace HttpServer.Authentication { /// <summary> /// Implements HTTP Digest authentication. It's more secure than Basic auth since password is /// encrypted with a "key" from the server. /// </summary> /// <remarks> /// Keep in mind that the password is encrypted with MD5. Use a combination of SSL and digest auth to be secure. /// </remarks> public class DigestAuthentication : IAuthenticator { private readonly IUserProvider _userProvider; static readonly Dictionary<string, DateTime> _nonces = new Dictionary<string, DateTime>(); private static Timer _timer; private readonly ILogger _logger = LogFactory.CreateLogger(typeof (DigestAuthentication)); /// <summary> /// Initializes a new instance of the <see cref="DigestAuthentication"/> class. /// </summary> /// <param name="userProvider">Supplies users during authentication process.</param> public DigestAuthentication(IUserProvider userProvider) { _userProvider = userProvider; } /// <summary> /// Used by test classes to be able to use hardcoded values /// </summary> public static bool DisableNonceCheck; /// <summary> /// Gets authentication scheme name /// </summary> public string Name { get { return "digest"; } } /// <summary> /// An authentication response have been received from the web browser. /// Check if it's correct /// </summary> /// <param name="header">Contents from the Authorization header</param> /// <param name="realm">Realm that should be authenticated</param> /// <param name="httpVerb">GET/POST/PUT/DELETE etc.</param> /// <returns> /// Authentication object that is stored for the request. A user class or something like that. /// </returns> /// <exception cref="ArgumentException">if authenticationHeader is invalid</exception> /// <exception cref="ArgumentNullException">If any of the parameters is empty or null.</exception> public IAuthenticationUser Authenticate(AuthorizationHeader header, string realm, string httpVerb) { if (header == null) throw new ArgumentNullException("header"); lock (_nonces) { if (_timer == null) _timer = new Timer(ManageNonces, null, 15000, 15000); } if (!header.Scheme.Equals("digest", StringComparison.OrdinalIgnoreCase)) return null; var parameters = HeaderParameterCollection.Parse(new StringReader(header.Data), ','); if (!IsValidNonce(parameters["nonce"]) && !DisableNonceCheck) return null; // request authentication information string username = parameters["username"]; var user = _userProvider.Lookup(username, realm); if (user == null) return null; // Encode authentication info string HA1 = string.IsNullOrEmpty(user.HA1) ? GetHA1(realm, username, user.Password) : user.HA1; // encode challenge info string A2 = String.Format("{0}:{1}", httpVerb, parameters["uri"]); string HA2 = GetMD5HashBinHex2(A2); string hashedDigest = Encrypt(HA1, HA2, parameters["qop"], parameters["nonce"], parameters["nc"], parameters["cnonce"]); //validate if (parameters["response"] == hashedDigest) return user; return null; } /// <summary> /// Gets authenticator scheme /// </summary> /// <value></value> /// <example> /// digest /// </example> public string Scheme { get { return "digest"; } } /// <summary> /// Encrypts parameters into a Digest string /// </summary> /// <param name="realm">Realm that the user want to log into.</param> /// <param name="userName">User logging in</param> /// <param name="password">Users password.</param> /// <param name="method">HTTP method.</param> /// <param name="uri">Uri/domain that generated the login prompt.</param> /// <param name="qop">Quality of Protection.</param> /// <param name="nonce">"Number used ONCE"</param> /// <param name="nc">Hexadecimal request counter.</param> /// <param name="cnonce">"Client Number used ONCE"</param> /// <returns>Digest encrypted string</returns> public static string Encrypt(string realm, string userName, string password, string method, string uri, string qop, string nonce, string nc, string cnonce) { string HA1 = GetHA1(realm, userName, password); string A2 = String.Format("{0}:{1}", method, uri); string HA2 = GetMD5HashBinHex2(A2); string unhashedDigest; if (qop != null) { unhashedDigest = String.Format("{0}:{1}:{2}:{3}:{4}:{5}", HA1, nonce, nc, cnonce, qop, HA2); } else { unhashedDigest = String.Format("{0}:{1}:{2}", HA1, nonce, HA2); } return GetMD5HashBinHex2(unhashedDigest); } public static string GetHA1(string realm, string userName, string password) { return GetMD5HashBinHex2(String.Format("{0}:{1}:{2}", userName, realm, password)); } /// <summary> /// /// </summary> /// <param name="ha1">Md5 hex encoded "userName:realm:password", without the quotes.</param> /// <param name="ha2">Md5 hex encoded "method:uri", without the quotes</param> /// <param name="qop">Quality of Protection</param> /// <param name="nonce">"Number used ONCE"</param> /// <param name="nc">Hexadecimal request counter.</param> /// <param name="cnonce">Client number used once</param> /// <returns></returns> protected virtual string Encrypt(string ha1, string ha2, string qop, string nonce, string nc, string cnonce) { string unhashedDigest; if (qop != null) { unhashedDigest = String.Format("{0}:{1}:{2}:{3}:{4}:{5}", ha1, nonce, nc, cnonce, qop, ha2); } else { unhashedDigest = String.Format("{0}:{1}:{2}", ha1, nonce, ha2); } return GetMD5HashBinHex2(unhashedDigest); } private void ManageNonces(object state) { try { lock (_nonces) { foreach (KeyValuePair<string, DateTime> pair in _nonces) { if (pair.Value >= DateTime.Now) continue; _nonces.Remove(pair.Key); return; } } } catch(Exception err) { _logger.Error("Failed to manage nonces.", err); } } /// <summary> /// Create a authentication challenge. /// </summary> /// <param name="realm">Realm that the user should authenticate in</param> /// <returns>A correct auth request.</returns> /// <exception cref="ArgumentNullException">If realm is empty or null.</exception> public IHeader CreateChallenge(string realm) { string nonce = GetCurrentNonce(); StringBuilder challenge = new StringBuilder("Digest realm=\""); challenge.Append(realm); challenge.Append("\""); challenge.Append(", nonce=\""); challenge.Append(nonce); challenge.Append("\""); challenge.Append(", opaque=\"" + Guid.NewGuid().ToString().Replace("-", string.Empty) + "\""); challenge.Append(", stale="); /*if (options.Length > 0) challenge.Append((bool)options[0] ? "true" : "false"); else*/ challenge.Append("false"); challenge.Append(", algorithm=MD5"); challenge.Append(", qop=auth"); return new StringHeader("WWW-Authenticate", challenge.ToString()); } /// <summary> /// Gets the current nonce. /// </summary> /// <returns></returns> protected virtual string GetCurrentNonce() { string nonce = Guid.NewGuid().ToString().Replace("-", string.Empty); lock (_nonces) _nonces.Add(nonce, DateTime.Now.AddSeconds(30)); return nonce; } /// <summary> /// Gets the Md5 hash bin hex2. /// </summary> /// <param name="toBeHashed">To be hashed.</param> /// <returns></returns> public static string GetMD5HashBinHex2(string toBeHashed) { MD5 md5 = new MD5CryptoServiceProvider(); byte[] result = md5.ComputeHash(Encoding.Default.GetBytes(toBeHashed)); StringBuilder sb = new StringBuilder(); foreach (byte b in result) sb.Append(b.ToString("x2")); return sb.ToString(); } /// <summary> /// determines if the nonce is valid or has expired. /// </summary> /// <param name="nonce">nonce value (check wikipedia for info)</param> /// <returns><c>true</c> if the nonce has not expired.</returns> protected virtual bool IsValidNonce(string nonce) { lock (_nonces) { if (_nonces.ContainsKey(nonce)) { if (_nonces[nonce] < DateTime.Now) { _nonces.Remove(nonce); return false; } return true; } } return false; } } } #endif
namespace Microsoft.Protocols.TestSuites.MS_SITESS { using System; using System.Threading; using Microsoft.Protocols.TestSuites.Common; using Microsoft.Protocols.TestTools; using Microsoft.VisualStudio.TestTools.UnitTesting; /// <summary> /// The partial test class containing test case definitions related to GetUpdatedFormDigest and GetUpdatedFormDigestInformation operations. /// </summary> [TestClass] public class S03_GetUpdatedFormDigest : TestClassBase { /// <summary> /// An instance of protocol adapter class. /// </summary> private IMS_SITESSAdapter sitessAdapter; /// <summary> /// An instance of SUT control adapter class. /// </summary> private IMS_SITESSSUTControlAdapter sutAdapter; #region Test Suite Initialization & Cleanup /// <summary> /// Test Suite Initialization. /// </summary> /// <param name="testContext">The test context.</param> [ClassInitialize] public static void ClassInitialize(TestContext testContext) { TestClassBase.Initialize(testContext); } /// <summary> /// Test Suite Cleanup. /// </summary> [ClassCleanup] public static void ClassCleanup() { TestClassBase.Cleanup(); } #endregion #region Test Cases #region Scenario 3 GetUpdatedFormDigest /// <summary> /// This test case is designed to verify the GetUpdatedFormDigest operation. /// </summary> [TestCategory("MSSITESS"), TestMethod()] public void MSSITESS_S03_TC01_GetUpdatedFormDigest() { Site.Assume.IsTrue(Common.IsRequirementEnabled(5361, this.Site), @"Test is executed only when R5361Enabled is set to true."); #region Variables string currentFormDigest = string.Empty; string newFormDigest = string.Empty; int formDigestTimeout = int.Parse(Common.GetConfigurationPropertyValue(Constants.ExpireTimePeriodBySecond, this.Site)); string formDigestValid = null; string formDigestExpired = null; string formDigestReNewed = null; string webPageUrl = Common.GetConfigurationPropertyValue(Constants.WebPageUrl, this.Site); #endregion Variables // Initialize the web service with an authenticated account. this.sitessAdapter.InitializeWebService(UserAuthenticationOption.Authenticated); // Invoke the GetUpdatedFormDigest operation. currentFormDigest = this.sitessAdapter.GetUpdatedFormDigest(); formDigestValid = this.sutAdapter.PostWebForm(currentFormDigest, webPageUrl); Site.Assert.IsTrue(formDigestValid.Contains(Constants.PostWebFormResponse), "digest accept"); // This sleep is just to wait for security validation returned by the server to expire and add 10 s for buffer, not wait for the server to complete operation or return response. Thread.Sleep((1000 * formDigestTimeout) + 10000); formDigestExpired = this.sutAdapter.PostWebForm(currentFormDigest, webPageUrl); if (Common.GetConfigurationPropertyValue(Constants.SutVersion, this.Site) == Constants.SharePointFoundation2013 || Common.GetConfigurationPropertyValue(Constants.SutVersion, this.Site) == Constants.SharePointFoundation2013SP1 || Common.GetConfigurationPropertyValue(Constants.SutVersion, this.Site) == Constants.SharePointServer2013 || Common.GetConfigurationPropertyValue(Constants.SutVersion,this.Site) == Constants.SharePointServer2016 || Common.GetConfigurationPropertyValue(Constants.SutVersion, this.Site) == Constants.SharePointServer2019) { Site.Assert.IsTrue(formDigestExpired.Contains(Constants.TimeOutInformationForSP2013AndSP2016), "digest expired"); } else { Site.Assert.IsTrue(formDigestExpired.Contains(Constants.TimeOutInformationForSP2007AndSP2010), "digest expired"); } // Invoke the GetUpdatedFormDigest operation again, the returned security validation is expected to be different with the last one. newFormDigest = this.sitessAdapter.GetUpdatedFormDigest(); formDigestReNewed = this.sutAdapter.PostWebForm(newFormDigest, webPageUrl); Site.Assert.IsTrue(formDigestReNewed.Contains(Constants.PostWebFormResponse), "New digest accept"); #region Capture requirements // If the validation token changed, the following requirement can be captured. Site.Log.Add(LogEntryKind.Debug, "Verify MS-SITESS_R192"); // Verify MS-SITESS requirement: MS-SITESS_R192 Site.CaptureRequirementIfAreNotEqual<string>( currentFormDigest, newFormDigest, 192, @"[In GetUpdatedFormDigest] In this case [when the client request an updated security validation] the server MUST return a new security validation to the client."); // If code can run to here, it means that Microsoft Windows SharePoint Services 3.0 and above support method GetUpdatedFormDigest. Site.Log.Add(LogEntryKind.Debug, "Verify MS-SITESS_R5361, Microsoft Windows SharePoint Services 3.0 and above support method GetUpdatedFormDigest."); // Verify MS-SITESS requirement: MS-SITESS_R5361 Site.CaptureRequirement( 5361, @"[In Appendix B: Product Behavior] <9> Section 3.1.4.6: Implementation does support this operation [GetUpdatedFormDigest].(Windows SharePoint Services 3.0 and above follow this behavior.)"); #endregion Capture requirements } /// <summary> /// This test case is designed to verify the GetUpdatedFormDigestInformation operation. /// </summary> [TestCategory("MSSITESS"), TestMethod()] public void MSSITESS_S03_TC02_GetUpdatedFormDigestInformation() { Site.Assume.IsTrue(Common.IsRequirementEnabled(5381, this.Site), @"Test is executed only when R5381Enabled is set to true."); string webPageUrl = Common.GetConfigurationPropertyValue(Constants.WebPageUrl, this.Site); FormDigestInformation currentInfo = new FormDigestInformation(); FormDigestInformation newInfo = new FormDigestInformation(); string urlStr = string.Empty; int formDigestTimeout = int.Parse(Common.GetConfigurationPropertyValue(Constants.ExpireTimePeriodBySecond, this.Site)); string currentSite = Common.GetConfigurationPropertyValue(Constants.SiteCollectionUrl, this.Site); // Initialize the web service with an authenticated account. this.sitessAdapter.InitializeWebService(UserAuthenticationOption.Authenticated); // Invoke the GetUpdatedFormDigestInformation operation. currentInfo = this.sitessAdapter.GetUpdatedFormDigestInformation(urlStr); var formDigestValid = this.sutAdapter.PostWebForm(currentInfo.DigestValue, webPageUrl); Site.Assert.IsTrue(formDigestValid.Contains(Constants.PostWebFormResponse), "digest accept"); // If the DigestValue is the valid security validation token, R500 can be captured. Site.Log.Add(LogEntryKind.Debug, "Verify MS-SITESS_R500, the DigestValue is {0}.", currentInfo.DigestValue); // Verify MS-SITESS requirement: MS-SITESS_R500 Site.CaptureRequirement( 500, @"[In FormDigestInformation] DigestValue: Security validation token generated by the protocol server."); // This sleep is just to wait for security validation returned by the server to expire and add 10 s for buffer, not wait for the server to complete operation or return response. Thread.Sleep((1000 * formDigestTimeout) + 10000); var formDigestExpired = this.sutAdapter.PostWebForm(currentInfo.DigestValue, webPageUrl); if (Common.GetConfigurationPropertyValue(Constants.SutVersion, this.Site) == Constants.SharePointFoundation2013 || Common.GetConfigurationPropertyValue(Constants.SutVersion, this.Site) == Constants.SharePointFoundation2013SP1 || Common.GetConfigurationPropertyValue(Constants.SutVersion, this.Site) == Constants.SharePointServer2013 || Common.GetConfigurationPropertyValue(Constants.SutVersion, this.Site) == Constants.SharePointServer2016 || Common.GetConfigurationPropertyValue(Constants.SutVersion, this.Site) == Constants.SharePointServer2019) { Site.Assert.IsTrue(formDigestExpired.Contains(Constants.TimeOutInformationForSP2013AndSP2016), "digest expired"); } else { Site.Assert.IsTrue(formDigestExpired.Contains(Constants.TimeOutInformationForSP2007AndSP2010), "digest expired"); } // If the security validation token do expire after specified timeout seconds, R501 can be captured. Site.Log.Add(LogEntryKind.Debug, "Verify MS-SITESS_R501, the TimeoutSeconds is {0}.", currentInfo.TimeoutSeconds); // Verify MS-SITESS requirement: MS-SITESS_R501 Site.CaptureRequirement( 501, @"[In FormDigestInformation] TimeoutSeconds: The time in seconds in which the security validation token will expire after the protocol server generates the security validation token server."); // Invoke the GetUpdatedFormDigestInformation operation again, the returned security validation is expected to be different with the last one. newInfo = this.sitessAdapter.GetUpdatedFormDigestInformation(urlStr); var formDigestReNewed = this.sutAdapter.PostWebForm(newInfo.DigestValue, webPageUrl); Site.Assert.IsTrue(formDigestReNewed.Contains(Constants.PostWebFormResponse), "New digest accept"); FormDigestInformation nullInfo = this.sitessAdapter.GetUpdatedFormDigestInformation(null); string expectUrl = currentSite.TrimEnd('/'); string actualUrl = nullInfo.WebFullUrl.TrimEnd('/'); bool isVerifyR550 = expectUrl.Equals(actualUrl, StringComparison.CurrentCultureIgnoreCase); #region Capture requirements // If the url is the current requested site, R550 can be captured. Site.Log.Add(LogEntryKind.Debug, "Verify MS-SITESS_R550, the actual URL is {0}.", actualUrl); // Verify MS-SITESS requirement: MS-SITESS_R550 Site.CaptureRequirementIfIsTrue( isVerifyR550, 550, @"[In GetUpdatedFormDigestInformation] [url:] If this element is omitted altogether, the protocol server MUST return the FormDigestInformation of the current requested site (2)."); #endregion Capture requirements FormDigestInformation emptyInfo = this.sitessAdapter.GetUpdatedFormDigestInformation(urlStr); #region Capture requirements expectUrl = currentSite.TrimEnd('/'); actualUrl = emptyInfo.WebFullUrl.TrimEnd('/'); bool isVerifyR551 = expectUrl.Equals(actualUrl, StringComparison.CurrentCultureIgnoreCase); // If the url is the current requested site, R551 can be captured. Site.Log.Add(LogEntryKind.Debug, "Verify MS-SITESS_R551, the actual URL is {0}.", actualUrl); // Verify MS-SITESS requirement: MS-SITESS_R551 Site.CaptureRequirementIfIsTrue( isVerifyR551, 551, @"[In GetUpdatedFormDigestInformation] [url:] If this element is included as an empty string, the protocol server MUST return the FormDigestInformation of the current requested site (2)."); #endregion Capture requirements urlStr = Common.GetConfigurationPropertyValue(Constants.SiteCollectionUrl, this.Site); FormDigestInformation otherInfo = this.sitessAdapter.GetUpdatedFormDigestInformation(urlStr); #region Capture requirements expectUrl = urlStr.TrimEnd('/'); actualUrl = otherInfo.WebFullUrl.TrimEnd('/'); bool isVerifyR405 = expectUrl.Equals(actualUrl, StringComparison.CurrentCultureIgnoreCase); // If the url is a requested site, R405 can be captured. Site.Log.Add(LogEntryKind.Debug, "Verify MS-SITESS_R405, the actual URL is {0}.", actualUrl); // Verify MS-SITESS requirement: MS-SITESS_R405 Site.CaptureRequirementIfIsTrue( isVerifyR405, 405, @"[In GetUpdatedFormDigestInformation] [url:] Otherwise[If this element is neither omitted altogether nor included as an empty string], the protocol server MUST return the FormDigestInformation of the site that contains the page specified by this element."); // If code can run to here, it means that Microsoft SharePoint Foundation 2010 and above support method GetUpdatedFormDigestInformation. Site.Log.Add(LogEntryKind.Debug, "Verify MS-SITESS_R5381, Microsoft SharePoint Foundation 2010 and above support method GetUpdatedFormDigestInformation."); // Verify MS-SITESS requirement: MS-SITESS_R5381 Site.CaptureRequirement( 5381, @"[In Appendix B: Product Behavior] Implementation does support this method [GetUpdatedFormDigestInformation]. (Microsoft SharePoint Foundation 2010 and above follow this behavior.)"); #endregion Capture requirements } #endregion Scenario 3 GetUpdatedFormDigest #endregion Test Cases #region Test Case Initialization & Cleanup /// <summary> /// Test Case Initialization. /// </summary> [TestInitialize] public void TestCaseInitialize() { this.sitessAdapter = Site.GetAdapter<IMS_SITESSAdapter>(); Common.CheckCommonProperties(this.Site, true); this.sutAdapter = Site.GetAdapter<IMS_SITESSSUTControlAdapter>(); // Since the default value of the form digest timeout is too long to wait, change it to a smaller value. int formDigestTimeout = int.Parse(Common.GetConfigurationPropertyValue(Constants.ExpireTimePeriodBySecond, this.Site)); int temp = this.sutAdapter.SetFormDigestTimeout(formDigestTimeout); Site.Assert.AreEqual<int>(formDigestTimeout, temp, "The digest timeout value should be set to the input value."); } /// <summary> /// Test Case Cleanup. /// </summary> [TestCleanup] public void TestCaseCleanup() { // Set the form digest timeout value to default value on the server. int defaultFormDigestTimeout = int.Parse(Common.GetConfigurationPropertyValue(Constants.DefaultExpireTimePeriod, this.Site)); int temp = this.sutAdapter.SetFormDigestTimeout(defaultFormDigestTimeout); Site.Assert.AreEqual<int>(defaultFormDigestTimeout, temp, "The digest timeout value should be set to the input value."); this.sitessAdapter.Reset(); this.sutAdapter.Reset(); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using Internal.IL; using Internal.Runtime; using Internal.Text; using Internal.TypeSystem; using Debug = System.Diagnostics.Debug; using GenericVariance = Internal.Runtime.GenericVariance; namespace ILCompiler.DependencyAnalysis { /// <summary> /// Given a type, EETypeNode writes an EEType data structure in the format expected by the runtime. /// /// Format of an EEType: /// /// Field Size | Contents /// ----------------+----------------------------------- /// UInt16 | Component Size. For arrays this is the element type size, for strings it is 2 (.NET uses /// | UTF16 character encoding), for generic type definitions it is the number of generic parameters, /// | and 0 for all other types. /// | /// UInt16 | EETypeKind (Normal, Array, Pointer type). Flags for: IsValueType, IsCrossModule, HasPointers, /// | HasOptionalFields, IsInterface, IsGeneric. Top 5 bits are used for enum CorElementType to /// | record whether it's back by an Int32, Int16 etc /// | /// Uint32 | Base size. /// | /// [Pointer Size] | Related type. Base type for regular types. Element type for arrays / pointer types. /// | /// UInt16 | Number of VTable slots (X) /// | /// UInt16 | Number of interfaces implemented by type (Y) /// | /// UInt32 | Hash code /// | /// [Pointer Size] | Pointer to containing TypeManager indirection cell /// | /// X * [Ptr Size] | VTable entries (optional) /// | /// Y * [Ptr Size] | Pointers to interface map data structures (optional) /// | /// [Pointer Size] | Pointer to finalizer method (optional) /// | /// [Pointer Size] | Pointer to optional fields (optional) /// | /// [Pointer Size] | Pointer to the generic type argument of a Nullable&lt;T&gt; (optional) /// | /// [Pointer Size] | Pointer to the generic type definition EEType (optional) /// | /// [Pointer Size] | Pointer to the generic argument and variance info (optional) /// </summary> public partial class EETypeNode : ObjectNode, IExportableSymbolNode, IEETypeNode, ISymbolDefinitionNode { protected TypeDesc _type; internal EETypeOptionalFieldsBuilder _optionalFieldsBuilder = new EETypeOptionalFieldsBuilder(); internal EETypeOptionalFieldsNode _optionalFieldsNode; public EETypeNode(NodeFactory factory, TypeDesc type) { if (type.IsCanonicalDefinitionType(CanonicalFormKind.Any)) Debug.Assert(this is CanonicalDefinitionEETypeNode); else if (type.IsCanonicalSubtype(CanonicalFormKind.Any)) Debug.Assert((this is CanonicalEETypeNode) || (this is NecessaryCanonicalEETypeNode)); Debug.Assert(!type.IsRuntimeDeterminedSubtype); _type = type; _optionalFieldsNode = new EETypeOptionalFieldsNode(this); // Note: The fact that you can't create invalid EETypeNode is used from many places that grab // an EETypeNode from the factory with the sole purpose of making sure the validation has run // and that the result of the positive validation is "cached" (by the presence of an EETypeNode). CheckCanGenerateEEType(factory, type); } protected override string GetName(NodeFactory factory) => this.GetMangledName(factory.NameMangler); public override bool ShouldSkipEmittingObjectNode(NodeFactory factory) { // If there is a constructed version of this node in the graph, emit that instead if (ConstructedEETypeNode.CreationAllowed(_type)) return factory.ConstructedTypeSymbol(_type).Marked; return false; } public override ObjectNode NodeForLinkage(NodeFactory factory) { return (ObjectNode)factory.NecessaryTypeSymbol(_type); } public virtual bool IsExported(NodeFactory factory) => factory.CompilationModuleGroup.ExportsType(Type); public TypeDesc Type => _type; public override ObjectNodeSection Section { get { if (_type.Context.Target.IsWindows) return ObjectNodeSection.ReadOnlyDataSection; else return ObjectNodeSection.DataSection; } } public int MinimumObjectSize => _type.Context.Target.PointerSize * 3; protected virtual bool EmitVirtualSlotsAndInterfaces => false; internal bool HasOptionalFields { get { return _optionalFieldsBuilder.IsAtLeastOneFieldUsed(); } } internal byte[] GetOptionalFieldsData(NodeFactory factory) { return _optionalFieldsBuilder.GetBytes(); } public override bool StaticDependenciesAreComputed => true; public void SetDispatchMapIndex(int index) { _optionalFieldsBuilder.SetFieldValue(EETypeOptionalFieldTag.DispatchMap, checked((uint)index)); } public static string GetMangledName(TypeDesc type, NameMangler nameMangler) { return nameMangler.NodeMangler.EEType(type); } public virtual void AppendMangledName(NameMangler nameMangler, Utf8StringBuilder sb) { sb.Append(nameMangler.NodeMangler.EEType(_type)); } int ISymbolNode.Offset => 0; int ISymbolDefinitionNode.Offset => GCDescSize; public override bool IsShareable => IsTypeNodeShareable(_type); public static bool IsTypeNodeShareable(TypeDesc type) { return type.IsParameterizedType || type.IsFunctionPointer || type is InstantiatedType; } protected override DependencyList ComputeNonRelocationBasedDependencies(NodeFactory factory) { DependencyList dependencies = new DependencyList(); // Include the optional fields by default. We don't know if optional fields will be needed until // all of the interface usage has been stabilized. If we end up not needing it, the EEType node will not // generate any relocs to it, and the optional fields node will instruct the object writer to skip // emitting it. dependencies.Add(new DependencyListEntry(_optionalFieldsNode, "Optional fields")); // Dependencies of the StaticsInfoHashTable and the ReflectionFieldAccessMap if (_type is MetadataType && !_type.IsCanonicalSubtype(CanonicalFormKind.Any)) { MetadataType metadataType = (MetadataType)_type; // NOTE: The StaticsInfoHashtable entries need to reference the gc and non-gc static nodes through an indirection cell. // The StaticsInfoHashtable entries only exist for static fields on generic types. if (metadataType.GCStaticFieldSize.AsInt > 0) { ISymbolNode gcStatics = factory.TypeGCStaticsSymbol(metadataType); if (_type.HasInstantiation) { dependencies.Add(factory.Indirection(gcStatics), "GC statics indirection for StaticsInfoHashtable"); } else { // TODO: https://github.com/dotnet/corert/issues/3224 // Reflection static field bases handling is here because in the current reflection model we reflection-enable // all fields of types that are compiled. Ideally the list of reflection enabled fields should be known before // we even start the compilation process (with the static bases being compilation roots like any other). dependencies.Add(gcStatics, "GC statics for ReflectionFieldMap entry"); } } if (metadataType.NonGCStaticFieldSize.AsInt > 0) { ISymbolNode nonGCStatic = factory.TypeNonGCStaticsSymbol(metadataType); if (_type.HasInstantiation) { // The entry in the StaticsInfoHashtable points at the beginning of the static fields data, rather than the cctor // context offset. nonGCStatic = factory.Indirection(nonGCStatic); dependencies.Add(nonGCStatic, "Non-GC statics indirection for StaticsInfoHashtable"); } else { // TODO: https://github.com/dotnet/corert/issues/3224 // Reflection static field bases handling is here because in the current reflection model we reflection-enable // all fields of types that are compiled. Ideally the list of reflection enabled fields should be known before // we even start the compilation process (with the static bases being compilation roots like any other). dependencies.Add(nonGCStatic, "Non-GC statics for ReflectionFieldMap entry"); } } // TODO: TLS dependencies } return dependencies; } public override ObjectData GetData(NodeFactory factory, bool relocsOnly) { ObjectDataBuilder objData = new ObjectDataBuilder(factory, relocsOnly); objData.RequireInitialPointerAlignment(); objData.AddSymbol(this); ComputeOptionalEETypeFields(factory, relocsOnly); OutputGCDesc(ref objData); OutputComponentSize(ref objData); OutputFlags(factory, ref objData); OutputBaseSize(ref objData); OutputRelatedType(factory, ref objData); // Number of vtable slots will be only known later. Reseve the bytes for it. var vtableSlotCountReservation = objData.ReserveShort(); // Number of interfaces will only be known later. Reserve the bytes for it. var interfaceCountReservation = objData.ReserveShort(); objData.EmitInt(_type.GetHashCode()); objData.EmitPointerReloc(factory.TypeManagerIndirection); if (EmitVirtualSlotsAndInterfaces) { // Emit VTable Debug.Assert(objData.CountBytes - ((ISymbolDefinitionNode)this).Offset == GetVTableOffset(objData.TargetPointerSize)); SlotCounter virtualSlotCounter = SlotCounter.BeginCounting(ref /* readonly */ objData); OutputVirtualSlots(factory, ref objData, _type, _type, relocsOnly); // Update slot count int numberOfVtableSlots = virtualSlotCounter.CountSlots(ref /* readonly */ objData); objData.EmitShort(vtableSlotCountReservation, checked((short)numberOfVtableSlots)); // Emit interface map SlotCounter interfaceSlotCounter = SlotCounter.BeginCounting(ref /* readonly */ objData); OutputInterfaceMap(factory, ref objData); // Update slot count int numberOfInterfaceSlots = interfaceSlotCounter.CountSlots(ref /* readonly */ objData); objData.EmitShort(interfaceCountReservation, checked((short)numberOfInterfaceSlots)); } else { // If we're not emitting any slots, the number of slots is zero. objData.EmitShort(vtableSlotCountReservation, 0); objData.EmitShort(interfaceCountReservation, 0); } OutputFinalizerMethod(factory, ref objData); OutputOptionalFields(factory, ref objData); OutputNullableTypeParameter(factory, ref objData); OutputGenericInstantiationDetails(factory, ref objData); return objData.ToObjectData(); } /// <summary> /// Returns the offset within an EEType of the beginning of VTable entries /// </summary> /// <param name="pointerSize">The size of a pointer in bytes in the target architecture</param> public static int GetVTableOffset(int pointerSize) { return 16 + 2 * pointerSize; } protected virtual int GCDescSize => 0; protected virtual void OutputGCDesc(ref ObjectDataBuilder builder) { // Non-constructed EETypeNodes get no GC Desc Debug.Assert(GCDescSize == 0); } private void OutputComponentSize(ref ObjectDataBuilder objData) { if (_type.IsArray) { int elementSize = ((ArrayType)_type).ElementType.GetElementSize().AsInt; // We validated that this will fit the short when the node was constructed. No need for nice messages. objData.EmitShort((short)checked((ushort)elementSize)); } else if (_type.IsString) { objData.EmitShort(StringComponentSize.Value); } else { objData.EmitShort(0); } } private void OutputFlags(NodeFactory factory, ref ObjectDataBuilder objData) { UInt16 flags = EETypeBuilderHelpers.ComputeFlags(_type); if (_type.GetTypeDefinition() == factory.ArrayOfTEnumeratorType) { // Generic array enumerators use special variance rules recognized by the runtime flags |= (UInt16)EETypeFlags.GenericVarianceFlag; } if (factory.TypeSystemContext.IsGenericArrayInterfaceType(_type)) { // Runtime casting logic relies on all interface types implemented on arrays // to have the variant flag set (even if all the arguments are non-variant). // This supports e.g. casting uint[] to ICollection<int> flags |= (UInt16)EETypeFlags.GenericVarianceFlag; } ISymbolNode relatedTypeNode = GetRelatedTypeNode(factory); // If the related type (base type / array element type / pointee type) is not part of this compilation group, and // the output binaries will be multi-file (not multiple object files linked together), indicate to the runtime // that it should indirect through the import address table if (relatedTypeNode != null && relatedTypeNode.RepresentsIndirectionCell) { flags |= (UInt16)EETypeFlags.RelatedTypeViaIATFlag; } if (HasOptionalFields) { flags |= (UInt16)EETypeFlags.OptionalFieldsFlag; } objData.EmitShort((short)flags); } protected virtual void OutputBaseSize(ref ObjectDataBuilder objData) { int pointerSize = _type.Context.Target.PointerSize; int objectSize; if (_type.IsDefType) { objectSize = pointerSize + ((DefType)_type).InstanceByteCount.AsInt; // +pointerSize for SyncBlock if (_type.IsValueType) objectSize += pointerSize; // + EETypePtr field inherited from System.Object } else if (_type.IsArray) { objectSize = 3 * pointerSize; // SyncBlock + EETypePtr + Length if (_type.IsMdArray) objectSize += 2 * sizeof(int) * ((ArrayType)_type).Rank; } else if (_type.IsPointer) { // These never get boxed and don't have a base size. Use a sentinel value recognized by the runtime. objData.EmitInt(ParameterizedTypeShapeConstants.Pointer); return; } else if (_type.IsByRef) { // These never get boxed and don't have a base size. Use a sentinel value recognized by the runtime. objData.EmitInt(ParameterizedTypeShapeConstants.ByRef); return; } else throw new NotImplementedException(); objectSize = AlignmentHelper.AlignUp(objectSize, pointerSize); objectSize = Math.Max(MinimumObjectSize, objectSize); if (_type.IsString) { // If this is a string, throw away objectSize we computed so far. Strings are special. // SyncBlock + EETypePtr + length + firstChar objectSize = 2 * pointerSize + sizeof(int) + sizeof(char); } objData.EmitInt(objectSize); } protected static TypeDesc GetFullCanonicalTypeForCanonicalType(TypeDesc type) { if (type.IsCanonicalSubtype(CanonicalFormKind.Specific)) { return type.ConvertToCanonForm(CanonicalFormKind.Specific); } else if (type.IsCanonicalSubtype(CanonicalFormKind.Universal)) { return type.ConvertToCanonForm(CanonicalFormKind.Universal); } else { return type; } } protected virtual ISymbolNode GetBaseTypeNode(NodeFactory factory) { return _type.BaseType != null ? factory.NecessaryTypeSymbol(_type.BaseType) : null; } private ISymbolNode GetRelatedTypeNode(NodeFactory factory) { ISymbolNode relatedTypeNode = null; if (_type.IsArray || _type.IsPointer || _type.IsByRef) { var parameterType = ((ParameterizedType)_type).ParameterType; relatedTypeNode = factory.NecessaryTypeSymbol(parameterType); } else { TypeDesc baseType = _type.BaseType; if (baseType != null) { relatedTypeNode = GetBaseTypeNode(factory); } } return relatedTypeNode; } protected virtual void OutputRelatedType(NodeFactory factory, ref ObjectDataBuilder objData) { ISymbolNode relatedTypeNode = GetRelatedTypeNode(factory); if (relatedTypeNode != null) { objData.EmitPointerReloc(relatedTypeNode); } else { objData.EmitZeroPointer(); } } protected virtual void OutputVirtualSlots(NodeFactory factory, ref ObjectDataBuilder objData, TypeDesc implType, TypeDesc declType, bool relocsOnly) { Debug.Assert(EmitVirtualSlotsAndInterfaces); declType = declType.GetClosestDefType(); var baseType = declType.BaseType; if (baseType != null) OutputVirtualSlots(factory, ref objData, implType, baseType, relocsOnly); // The generic dictionary pointer occupies the first slot of each type vtable slice if (declType.HasGenericDictionarySlot()) { // Note: Canonical type instantiations always have a generic dictionary vtable slot, but it's empty // TODO: emit the correction dictionary slot for interfaces (needed when we start supporting static methods on interfaces) if (declType.IsInterface || declType.IsCanonicalSubtype(CanonicalFormKind.Any)) objData.EmitZeroPointer(); else objData.EmitPointerReloc(factory.TypeGenericDictionary(declType)); } // It's only okay to touch the actual list of slots if we're in the final emission phase // or the vtable is not built lazily. if (relocsOnly && !factory.CompilationModuleGroup.ShouldProduceFullVTable(declType)) return; // Actual vtable slots follow IReadOnlyList<MethodDesc> virtualSlots = factory.VTable(declType).Slots; for (int i = 0; i < virtualSlots.Count; i++) { MethodDesc declMethod = virtualSlots[i]; // No generic virtual methods can appear in the vtable! Debug.Assert(!declMethod.HasInstantiation); MethodDesc implMethod = implType.GetClosestDefType().FindVirtualFunctionTargetMethodOnObjectType(declMethod); if (!implMethod.IsAbstract) { MethodDesc canonImplMethod = implMethod.GetCanonMethodTarget(CanonicalFormKind.Specific); objData.EmitPointerReloc(factory.MethodEntrypoint(canonImplMethod, implMethod.OwningType.IsValueType)); } else { objData.EmitZeroPointer(); } } } protected virtual void OutputInterfaceMap(NodeFactory factory, ref ObjectDataBuilder objData) { Debug.Assert(EmitVirtualSlotsAndInterfaces); foreach (var itf in _type.RuntimeInterfaces) { objData.EmitPointerRelocOrIndirectionReference(factory.NecessaryTypeSymbol(itf)); } } private void OutputFinalizerMethod(NodeFactory factory, ref ObjectDataBuilder objData) { MethodDesc finalizerMethod = _type.GetFinalizer(); if (finalizerMethod != null) { MethodDesc canonFinalizerMethod = finalizerMethod.GetCanonMethodTarget(CanonicalFormKind.Specific); objData.EmitPointerReloc(factory.MethodEntrypoint(canonFinalizerMethod)); } } private void OutputOptionalFields(NodeFactory factory, ref ObjectDataBuilder objData) { if (HasOptionalFields) { objData.EmitPointerReloc(_optionalFieldsNode); } } private void OutputNullableTypeParameter(NodeFactory factory, ref ObjectDataBuilder objData) { if (_type.IsNullable) { objData.EmitPointerReloc(factory.NecessaryTypeSymbol(_type.Instantiation[0])); } } private void OutputGenericInstantiationDetails(NodeFactory factory, ref ObjectDataBuilder objData) { if (_type.HasInstantiation && !_type.IsTypeDefinition) { objData.EmitPointerRelocOrIndirectionReference(factory.NecessaryTypeSymbol(_type.GetTypeDefinition())); GenericCompositionDetails details; if (_type.GetTypeDefinition() == factory.ArrayOfTEnumeratorType) { // Generic array enumerators use special variance rules recognized by the runtime details = new GenericCompositionDetails(_type.Instantiation, new[] { GenericVariance.ArrayCovariant }); } else if (factory.TypeSystemContext.IsGenericArrayInterfaceType(_type)) { // Runtime casting logic relies on all interface types implemented on arrays // to have the variant flag set (even if all the arguments are non-variant). // This supports e.g. casting uint[] to ICollection<int> details = new GenericCompositionDetails(_type, forceVarianceInfo: true); } else details = new GenericCompositionDetails(_type); objData.EmitPointerReloc(factory.GenericComposition(details)); } } /// <summary> /// Populate the OptionalFieldsRuntimeBuilder if any optional fields are required. /// </summary> protected internal virtual void ComputeOptionalEETypeFields(NodeFactory factory, bool relocsOnly) { ComputeRareFlags(factory); ComputeNullableValueOffset(); if (!relocsOnly) ComputeICastableVirtualMethodSlots(factory); ComputeValueTypeFieldPadding(); } void ComputeRareFlags(NodeFactory factory) { uint flags = 0; MetadataType metadataType = _type as MetadataType; if (_type.IsNullable) { flags |= (uint)EETypeRareFlags.IsNullableFlag; // If the nullable type is not part of this compilation group, and // the output binaries will be multi-file (not multiple object files linked together), indicate to the runtime // that it should indirect through the import address table if (factory.NecessaryTypeSymbol(_type.Instantiation[0]).RepresentsIndirectionCell) flags |= (uint)EETypeRareFlags.NullableTypeViaIATFlag; } if (factory.TypeSystemContext.HasLazyStaticConstructor(_type)) { flags |= (uint)EETypeRareFlags.HasCctorFlag; } if (EETypeBuilderHelpers.ComputeRequiresAlign8(_type)) { flags |= (uint)EETypeRareFlags.RequiresAlign8Flag; } if (metadataType != null && metadataType.IsHfa) { flags |= (uint)EETypeRareFlags.IsHFAFlag; } foreach (DefType itf in _type.RuntimeInterfaces) { if (itf == factory.ICastableInterface) { flags |= (uint)EETypeRareFlags.ICastableFlag; break; } } if (metadataType != null && !_type.IsInterface && metadataType.IsAbstract) { flags |= (uint)EETypeRareFlags.IsAbstractClassFlag; } if (metadataType != null && metadataType.IsByRefLike) { flags |= (uint)EETypeRareFlags.IsByRefLikeFlag; } if (flags != 0) { _optionalFieldsBuilder.SetFieldValue(EETypeOptionalFieldTag.RareFlags, flags); } } /// <summary> /// To support boxing / unboxing, the offset of the value field of a Nullable type is recorded on the EEType. /// This is variable according to the alignment requirements of the Nullable&lt;T&gt; type parameter. /// </summary> void ComputeNullableValueOffset() { if (!_type.IsNullable) return; if (!_type.Instantiation[0].IsCanonicalSubtype(CanonicalFormKind.Universal)) { var field = _type.GetKnownField("value"); // In the definition of Nullable<T>, the first field should be the boolean representing "hasValue" Debug.Assert(field.Offset.AsInt > 0); // The contract with the runtime states the Nullable value offset is stored with the boolean "hasValue" size subtracted // to get a small encoding size win. _optionalFieldsBuilder.SetFieldValue(EETypeOptionalFieldTag.NullableValueOffset, (uint)field.Offset.AsInt - 1); } } /// <summary> /// ICastable is a special interface whose two methods are not invoked using regular interface dispatch. /// Instead, their VTable slots are recorded on the EEType of an object implementing ICastable and are /// called directly. /// </summary> protected virtual void ComputeICastableVirtualMethodSlots(NodeFactory factory) { if (_type.IsInterface || !EmitVirtualSlotsAndInterfaces) return; foreach (DefType itf in _type.RuntimeInterfaces) { if (itf == factory.ICastableInterface) { MethodDesc isInstDecl = itf.GetKnownMethod("IsInstanceOfInterface", null); MethodDesc getImplTypeDecl = itf.GetKnownMethod("GetImplType", null); MethodDesc isInstMethodImpl = _type.ResolveInterfaceMethodTarget(isInstDecl); MethodDesc getImplTypeMethodImpl = _type.ResolveInterfaceMethodTarget(getImplTypeDecl); int isInstMethodSlot = VirtualMethodSlotHelper.GetVirtualMethodSlot(factory, isInstMethodImpl); int getImplTypeMethodSlot = VirtualMethodSlotHelper.GetVirtualMethodSlot(factory, getImplTypeMethodImpl); Debug.Assert(isInstMethodSlot != -1 && getImplTypeMethodSlot != -1); _optionalFieldsBuilder.SetFieldValue(EETypeOptionalFieldTag.ICastableIsInstSlot, (uint)isInstMethodSlot); _optionalFieldsBuilder.SetFieldValue(EETypeOptionalFieldTag.ICastableGetImplTypeSlot, (uint)getImplTypeMethodSlot); } } } protected virtual void ComputeValueTypeFieldPadding() { // All objects that can have appreciable which can be derived from size compute ValueTypeFieldPadding. // Unfortunately, the name ValueTypeFieldPadding is now wrong to avoid integration conflicts. // Interfaces, sealed types, and non-DefTypes cannot be derived from if (_type.IsInterface || !_type.IsDefType || (_type.IsSealed() && !_type.IsValueType)) return; DefType defType = _type as DefType; Debug.Assert(defType != null); uint valueTypeFieldPadding = checked((uint)(defType.InstanceByteCount.AsInt - defType.InstanceByteCountUnaligned.AsInt)); uint valueTypeFieldPaddingEncoded = EETypeBuilderHelpers.ComputeValueTypeFieldPaddingFieldValue(valueTypeFieldPadding, (uint)defType.InstanceFieldAlignment.AsInt); if (valueTypeFieldPaddingEncoded != 0) { _optionalFieldsBuilder.SetFieldValue(EETypeOptionalFieldTag.ValueTypeFieldPadding, valueTypeFieldPaddingEncoded); } } protected override void OnMarked(NodeFactory context) { if (!context.IsCppCodegenTemporaryWorkaround) { Debug.Assert(_type.IsTypeDefinition || !_type.HasSameTypeDefinition(context.ArrayOfTClass), "Asking for Array<T> EEType"); } } /// <summary> /// Validates that it will be possible to create an EEType for '<paramref name="type"/>'. /// </summary> public static void CheckCanGenerateEEType(NodeFactory factory, TypeDesc type) { // Don't validate generic definitons if (type.IsGenericDefinition) { return; } // System.__Canon or System.__UniversalCanon if(type.IsCanonicalDefinitionType(CanonicalFormKind.Any)) { return; } // It must be possible to create an EEType for the base type of this type TypeDesc baseType = type.BaseType; if (baseType != null) { // Make sure EEType can be created for this. factory.NecessaryTypeSymbol(GetFullCanonicalTypeForCanonicalType(baseType)); } // We need EETypes for interfaces foreach (var intf in type.RuntimeInterfaces) { // Make sure EEType can be created for this. factory.NecessaryTypeSymbol(GetFullCanonicalTypeForCanonicalType(intf)); } // Validate classes, structs, enums, interfaces, and delegates DefType defType = type as DefType; if (defType != null) { // Ensure we can compute the type layout defType.ComputeInstanceLayout(InstanceLayoutKind.TypeAndFields); // // The fact that we generated an EEType means that someone can call RuntimeHelpers.RunClassConstructor. // We need to make sure this is possible. // if (factory.TypeSystemContext.HasLazyStaticConstructor(defType)) { defType.ComputeStaticFieldLayout(StaticLayoutKind.StaticRegionSizesAndFields); } // Make sure instantiation length matches the expectation // TODO: it might be more resonable for the type system to enforce this (also for methods) if (defType.Instantiation.Length != defType.GetTypeDefinition().Instantiation.Length) { throw new TypeSystemException.TypeLoadException(ExceptionStringID.ClassLoadGeneral, type); } foreach (TypeDesc typeArg in defType.Instantiation) { // ByRefs, pointers, function pointers, and System.Void are never valid instantiation arguments if (typeArg.IsByRef || typeArg.IsPointer || typeArg.IsFunctionPointer || typeArg.IsVoid || (typeArg.IsValueType && ((DefType)typeArg).IsByRefLike)) { throw new TypeSystemException.TypeLoadException(ExceptionStringID.ClassLoadGeneral, type); } // TODO: validate constraints } // Check the type doesn't have bogus MethodImpls or overrides and we can get the finalizer. defType.GetFinalizer(); } // Validate parameterized types ParameterizedType parameterizedType = type as ParameterizedType; if (parameterizedType != null) { TypeDesc parameterType = parameterizedType.ParameterType; // Make sure EEType can be created for this. factory.NecessaryTypeSymbol(parameterType); if (parameterizedType.IsArray) { if (parameterType.IsFunctionPointer) { // Arrays of function pointers are not currently supported throw new TypeSystemException.TypeLoadException(ExceptionStringID.ClassLoadGeneral, type); } int elementSize = parameterType.GetElementSize().AsInt; if (elementSize >= ushort.MaxValue) { // Element size over 64k can't be encoded in the GCDesc throw new TypeSystemException.TypeLoadException(ExceptionStringID.ClassLoadValueClassTooLarge, parameterType); } if (((ArrayType)parameterizedType).Rank > 32) { throw new TypeSystemException.TypeLoadException(ExceptionStringID.ClassLoadRankTooLarge, type); } if ((parameterType.IsDefType) && ((DefType)parameterType).IsByRefLike) { // Arrays of byref-like types are not allowed throw new TypeSystemException.TypeLoadException(ExceptionStringID.ClassLoadGeneral, type); } } // Validate we're not constructing a type over a ByRef if (parameterType.IsByRef) { // CLR compat note: "ldtoken int32&&" will actually fail with a message about int32&; "ldtoken int32&[]" // will fail with a message about being unable to create an array of int32&. This is a middle ground. throw new TypeSystemException.TypeLoadException(ExceptionStringID.ClassLoadGeneral, type); } // It might seem reasonable to disallow array of void, but the CLR doesn't prevent that too hard. // E.g. "newarr void" will fail, but "newarr void[]" or "ldtoken void[]" will succeed. } // Function pointer EETypes are not currently supported if (type.IsFunctionPointer) { throw new TypeSystemException.TypeLoadException(ExceptionStringID.ClassLoadGeneral, type); } } private struct SlotCounter { private int _startBytes; public static SlotCounter BeginCounting(ref /* readonly */ ObjectDataBuilder builder) => new SlotCounter { _startBytes = builder.CountBytes }; public int CountSlots(ref /* readonly */ ObjectDataBuilder builder) { int bytesEmitted = builder.CountBytes - _startBytes; Debug.Assert(bytesEmitted % builder.TargetPointerSize == 0); return bytesEmitted / builder.TargetPointerSize; } } } }
using UnityEngine; using System.Collections.Generic; using System.IO; [System.Serializable] public class MegaPCVert { public int[] indices; public Vector3[] points; } public enum MegaInterpMethod { None, Linear, Bez, } public enum MegaBlendAnimMode { Replace, Additive, } [AddComponentMenu("Modifiers/Point Cache")] public class MegaPointCache : MegaModifier { public float time = 0.0f; public bool animated = false; public float speed = 1.0f; public float maxtime = 1.0f; public MegaRepeatMode LoopMode = MegaRepeatMode.PingPong; public MegaInterpMethod interpMethod = MegaInterpMethod.Linear; public MegaPCVert[] Verts; public float weight = 1.0f; public bool framedelay = true; public MegaBlendAnimMode blendMode = MegaBlendAnimMode.Additive; // local space int numPoints; // Number of points per sample float startFrame; // Corresponds to the UI value of the same name. float sampleRate; // Corresponds to the UI value of the same name. int numSamples; // Defines how many samples are stored in the file. float t; float alpha = 0.0f; float dalpha = 0.0f; int sindex; int sindex1; public bool showmapping = false; public float mappingSize = 0.001f; public int mapStart = 0; public int mapEnd = 0; public bool havemapping = false; public float scl = 1.0f; public bool flipyz = false; public bool negx = false; public bool negz = false; public float adjustscl = 1.0f; public Vector3 adjustoff = Vector3.zero; public override string ModName() { return "Point Cache"; } public override string GetHelpURL() { return "?page_id=1335"; } void LinearAbs(MegaModifiers mc, int start, int end) { for ( int i = start; i < end; i++ ) { Vector3 p = Verts[i].points[sindex]; Vector3 p1 = Verts[i].points[sindex1]; p.x = p.x + ((p1.x - p.x) * dalpha); p.y = p.y + ((p1.y - p.y) * dalpha); p.z = p.z + ((p1.z - p.z) * dalpha); for ( int v = 0; v < Verts[i].indices.Length; v++ ) sverts[Verts[i].indices[v]] = p; } } void LinearAbsWeighted(MegaModifiers mc, int start, int end) { for ( int i = start; i < end; i++ ) { Vector3 p = Verts[i].points[sindex]; Vector3 p1 = Verts[i].points[sindex1]; p.x = p.x + ((p1.x - p.x) * dalpha); p.y = p.y + ((p1.y - p.y) * dalpha); p.z = p.z + ((p1.z - p.z) * dalpha); float w = mc.selection[Verts[i].indices[0]]; //[wc]; p1 = verts[Verts[i].indices[0]]; p = p1 + ((p - p1) * w); for ( int v = 0; v < Verts[i].indices.Length; v++ ) sverts[Verts[i].indices[v]] = p; } } void LinearRel(MegaModifiers mc, int start, int end) { for ( int i = start; i < end; i++ ) { int ix = Verts[i].indices[0]; Vector3 basep = mc.verts[ix]; Vector3 p = Verts[i].points[sindex]; Vector3 p1 = Verts[i].points[sindex1]; p.x += (((p1.x - p.x) * dalpha) - basep.x); // * weight; //mc.verts[ix].x; p.y += (((p1.y - p.y) * dalpha) - basep.y); // * weight; //mc.verts[ix].y; p.z += (((p1.z - p.z) * dalpha) - basep.z); // * weight; //mc.verts[ix].z; p1 = verts[Verts[i].indices[0]]; p.x = p1.x + (p.x * weight); p.y = p1.y + (p.y * weight); p.z = p1.z + (p.z * weight); for ( int v = 0; v < Verts[i].indices.Length; v++ ) { int idx = Verts[i].indices[v]; sverts[idx] = p; } } } void LinearRelWeighted(MegaModifiers mc, int start, int end) { for ( int i = start; i < end; i++ ) { int ix = Verts[i].indices[0]; Vector3 basep = verts[ix]; Vector3 p = Verts[i].points[sindex]; Vector3 p1 = Verts[i].points[sindex1]; p.x += (((p1.x - p.x) * dalpha) - basep.x); // * weight; //mc.verts[ix].x; p.y += (((p1.y - p.y) * dalpha) - basep.y); // * weight; //mc.verts[ix].y; p.z += (((p1.z - p.z) * dalpha) - basep.z); // * weight; //mc.verts[ix].z; float w = mc.selection[Verts[i].indices[0]] * weight; //[wc]; p1 = verts[Verts[i].indices[0]]; p.x = p1.x + (p.x * w); p.y = p1.y + (p.y * w); p.z = p1.z + (p.z * w); for ( int v = 0; v < Verts[i].indices.Length; v++ ) { int idx = Verts[i].indices[v]; sverts[idx] = p; } } } void NoInterpAbs(MegaModifiers mc, int start, int end) { for ( int i = start; i < end; i++ ) { Vector3 p = Verts[i].points[sindex]; for ( int v = 0; v < Verts[i].indices.Length; v++ ) sverts[Verts[i].indices[v]] = p; } } void NoInterpAbsWeighted(MegaModifiers mc, int start, int end) { for ( int i = start; i < end; i++ ) { Vector3 p = Verts[i].points[sindex]; float w = mc.selection[Verts[i].indices[0]] * weight; //[wc]; Vector3 p1 = verts[Verts[i].indices[0]]; p = p1 + ((p - p1) * w); for ( int v = 0; v < Verts[i].indices.Length; v++ ) sverts[Verts[i].indices[v]] = p; } } void NoInterpRel(MegaModifiers mc, int start, int end) { for ( int i = start; i < end; i++ ) { int ix = Verts[i].indices[0]; Vector3 p = Verts[i].points[sindex] - verts[ix]; Vector3 p1 = verts[Verts[i].indices[0]]; p.x = p1.x + (p.x * weight); p.y = p1.y + (p.y * weight); p.z = p1.z + (p.z * weight); for ( int v = 0; v < Verts[i].indices.Length; v++ ) { int idx = Verts[i].indices[v]; sverts[idx] = p; } } } void NoInterpRelWeighted(MegaModifiers mc, int start, int end) { for ( int i = start; i < end; i++ ) { int ix = Verts[i].indices[0]; Vector3 p = Verts[i].points[sindex] - verts[ix]; float w = mc.selection[Verts[i].indices[0]] * weight; //[wc]; Vector3 p1 = verts[Verts[i].indices[0]]; p = p1 + ((p - p1) * w); for ( int v = 0; v < Verts[i].indices.Length; v++ ) { int idx = Verts[i].indices[v]; sverts[idx] = p; } } } bool skipframe = true; // TODO: Option to lerp or even bez, depends on how many samples public override void Modify(MegaModifiers mc) { if ( Verts != null ) { switch ( interpMethod ) { case MegaInterpMethod.Linear: switch ( blendMode ) { case MegaBlendAnimMode.Additive: LinearRel(mc, 0, Verts.Length); break; case MegaBlendAnimMode.Replace: LinearAbs(mc, 0, Verts.Length); break; } break; case MegaInterpMethod.Bez: switch ( blendMode ) { case MegaBlendAnimMode.Additive: LinearRel(mc, 0, Verts.Length); break; case MegaBlendAnimMode.Replace: LinearAbs(mc, 0, Verts.Length); break; } break; case MegaInterpMethod.None: switch ( blendMode ) { case MegaBlendAnimMode.Additive: NoInterpRel(mc, 0, Verts.Length); break; case MegaBlendAnimMode.Replace: NoInterpAbs(mc, 0, Verts.Length); break; } break; } } else { for ( int i = 0; i < verts.Length; i++ ) sverts[i] = verts[i]; } } public void ModifyInstance(MegaModifiers mc, float itime) { if ( Verts != null ) { switch ( LoopMode ) { case MegaRepeatMode.Loop: t = Mathf.Repeat(itime, maxtime); break; case MegaRepeatMode.PingPong: t = Mathf.PingPong(itime, maxtime); break; case MegaRepeatMode.Clamp: t = Mathf.Clamp(itime, 0.0f, maxtime); break; } alpha = t / maxtime; float val = (float)(Verts[0].points.Length - 1) * alpha; sindex = (int)val; dalpha = val - sindex; if ( sindex == Verts[0].points.Length - 1 ) { sindex1 = sindex; dalpha = 0.0f; } else sindex1 = sindex + 1; switch ( interpMethod ) { case MegaInterpMethod.Linear: switch ( blendMode ) { case MegaBlendAnimMode.Additive: LinearRel(mc, 0, Verts.Length); break; case MegaBlendAnimMode.Replace: LinearAbs(mc, 0, Verts.Length); break; } break; case MegaInterpMethod.Bez: switch ( blendMode ) { case MegaBlendAnimMode.Additive: LinearRel(mc, 0, Verts.Length); break; case MegaBlendAnimMode.Replace: LinearAbs(mc, 0, Verts.Length); break; } break; case MegaInterpMethod.None: switch ( blendMode ) { case MegaBlendAnimMode.Additive: NoInterpRel(mc, 0, Verts.Length); break; case MegaBlendAnimMode.Replace: NoInterpAbs(mc, 0, Verts.Length); break; } break; } } else { for ( int i = 0; i < verts.Length; i++ ) sverts[i] = verts[i]; } } public void SetAnim(float _t) { time = _t; t = _t; skipframe = true; } public override bool ModLateUpdate(MegaModContext mc) { if ( !Prepare(mc) ) return false; if ( animated ) //&& !lateanimupdate ) { if ( framedelay && skipframe ) skipframe = false; else { if ( Application.isPlaying ) time += Time.deltaTime * speed; } } switch ( LoopMode ) { case MegaRepeatMode.Loop: t = Mathf.Repeat(time, maxtime); break; case MegaRepeatMode.PingPong: t = Mathf.PingPong(time, maxtime); break; case MegaRepeatMode.Clamp: t = Mathf.Clamp(time, 0.0f, maxtime); break; } alpha = t / maxtime; float val = (float)(Verts[0].points.Length - 1) * alpha; sindex = (int)val; dalpha = val - sindex; if ( sindex == Verts[0].points.Length - 1 ) { sindex1 = sindex; dalpha = 0.0f; } else sindex1 = sindex + 1; return true; } public override bool Prepare(MegaModContext mc) { if ( Verts != null && Verts.Length > 0 && Verts[0].indices != null && Verts[0].indices.Length > 0 ) return true; return false; } public override void DoWork(MegaModifiers mc, int index, int start, int end, int cores) { ModifyCompressedMT(mc, index, cores); } public void ModifyCompressedMT(MegaModifiers mc, int tindex, int cores) { if ( Verts != null ) { int step = Verts.Length / cores; int startvert = (tindex * step); int endvert = startvert + step; if ( tindex == cores - 1 ) endvert = Verts.Length; switch ( interpMethod ) { case MegaInterpMethod.Linear: switch ( blendMode ) { case MegaBlendAnimMode.Additive: LinearRel(mc, startvert, endvert); break; case MegaBlendAnimMode.Replace: LinearAbs(mc, startvert, endvert); break; } break; case MegaInterpMethod.Bez: switch ( blendMode ) { case MegaBlendAnimMode.Additive: LinearRel(mc, startvert, endvert); break; case MegaBlendAnimMode.Replace: LinearAbs(mc, startvert, endvert); break; } break; case MegaInterpMethod.None: switch ( blendMode ) { case MegaBlendAnimMode.Additive: NoInterpRel(mc, startvert, endvert); break; case MegaBlendAnimMode.Replace: NoInterpAbs(mc, startvert, endvert); break; } break; } } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.IO; using System.Xml; using AMS.Profile; namespace NewAshAIO { public partial class NoteSheets : Form { //private String gId; private List<Sheet> sheets; private TabPage PSelected; private TabPage SourceTab; public NoteSheets() { InitializeComponent(); sheets = new List<Sheet>(); } public TabPage GetTabPageFromXY(int x,int y) { for(int i = 0;i<SheetSelection.TabPages.Count;i++) if(SheetSelection.GetTabRect(i).Contains(x, y)) return SheetSelection.TabPages[i]; return null; } private void CreateSheet(Sheet data) { TabPage newTab = new TabPage(); newTab.Tag = data; NotePage noteData = new NotePage(newTab, this); noteData.Location = new Point(0, 0); noteData.Size = newTab.Size; noteData.Anchor = AnchorStyles.Bottom | AnchorStyles.Top | AnchorStyles.Right | AnchorStyles.Left; newTab.Controls.Add(noteData); UpdateTitle(newTab); SheetSelection.TabPages.Add(newTab); } private List<Sheet> ImportSheet(String filename) { List<Sheet> sheets = new List<Sheet>(); Xml ImportFile = new Xml(filename); try { ImportFile.RootName = "notesheet"; string[] sheetsecs = ImportFile.GetSectionNames(); String name, content; foreach (String sheetname in sheetsecs) { name = ImportFile.GetValue(sheetname, "name", "[Noname]"); content = ImportFile.GetValue(sheetname, "content", ""); sheets.Add(new Sheet(name, content)); } } finally { } return sheets; } public void Show(String gameID) { char delim = Path.DirectorySeparatorChar; /*if (gameID.Length >= 3) { gId = gameID.Substring(0, 3); } else { gId = "SYSMENU"; }*/ Text = "Notepad"; if (!Directory.Exists("notes")) Directory.CreateDirectory("notes"); PSelected = null; SheetSelection.TabPages.Clear(); List<Sheet> sheets = null; if (File.Exists("notes.xml")) try { sheets = ImportSheet("notes.xml"); } catch { sheets = new List<Sheet>(); } else sheets = new List<Sheet>(); if (sheets.Count==0) sheets.Add(new Sheet("Default sheet")); for (int i = 0; i < sheets.Count; i++) { CreateSheet(sheets[i]); } SheetSelection.SelectedIndex = 0; base.Show(); } public void UpdateTitle(TabPage page) { Sheet sheet = (Sheet)page.Tag; string title = sheet.title; page.ToolTipText = title; if (title.Length > 25) title = title.Substring(0, 22) + "..."; page.Text = title; } void SheetSelection_SelectedIndexChanged(object sender, EventArgs e) { PSelected = SheetSelection.SelectedTab; if (PSelected == null) { return; } } public void DeleteSheet(TabPage selected) { if (selected == null) return; if (SheetSelection.TabPages.Count == 1) { MessageBox.Show("You must have at least one sheet!"); return; } int index = SheetSelection.TabPages.IndexOf(selected); Sheet sheet = (Sheet)selected.Tag; if (sheet.content == "" || MessageBox.Show("Are you sure you want to delete the current sheet: " + sheet.title + " ?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes) { //sheets.RemoveAt(index); SheetSelection.TabPages.RemoveAt(index); if(index > 0) index--; if(SheetSelection.TabPages.Count == 0) { PSelected = null; } else { PSelected = SheetSelection.TabPages[index]; SheetSelection.SelectedTab = PSelected; } } } private void NoteSheetsFormClosing(object sender, FormClosingEventArgs e) { char delim = Path.DirectorySeparatorChar; String filename = "notes.xml"; if (File.Exists(filename)) File.Delete(filename); Xml ExportFile = new Xml(filename); try { ExportFile.RootName = "notesheet"; String secname; int pagecount = SheetSelection.TabPages.Count; for (int i = 0; i < pagecount; i++) { Sheet sheet = (Sheet)SheetSelection.TabPages[i].Tag; secname = "sheet" + (i + 1).ToString(); ExportFile.SetValue(secname, "name", sheet.title); ExportFile.SetValue(secname, "content", sheet.content); } } finally { e.Cancel = true; Hide(); } } private void NoteSheets_FormClosing(object sender, FormClosingEventArgs e) { char delim = Path.DirectorySeparatorChar; String filename = "notes.xml"; if (File.Exists(filename)) File.Delete(filename); Xml ExportFile = new Xml(filename); try { ExportFile.RootName = "notesheet"; String secname; int pagecount = SheetSelection.TabPages.Count; for (int i = 0; i < pagecount; i++) { Sheet sheet = (Sheet)SheetSelection.TabPages[i].Tag; secname = "sheet" + (i + 1).ToString(); ExportFile.SetValue(secname, "name", sheet.title); ExportFile.SetValue(secname, "content", sheet.content); } } finally { e.Cancel = true; Hide(); } } void SheetSelectionMouseUp(object sender, MouseEventArgs e) { if(e.Button == MouseButtons.Left && SourceTab != null) { SuspendLayout(); TabPage currTabPage = GetTabPageFromXY(e.X, e.Y); if (currTabPage != null && !currTabPage.Equals(SourceTab)) { SourceTab.SuspendLayout(); if (SheetSelection.TabPages.IndexOf(currTabPage) < SheetSelection.TabPages.IndexOf(SourceTab)) { SheetSelection.TabPages.Remove(SourceTab); SheetSelection.TabPages.Insert(SheetSelection.TabPages.IndexOf(currTabPage), SourceTab); SheetSelection.SelectedTab = SourceTab; } else if (SheetSelection.TabPages.IndexOf(currTabPage) > SheetSelection.TabPages.IndexOf(SourceTab)) { SheetSelection.TabPages.Remove(SourceTab); SheetSelection.TabPages.Insert(SheetSelection.TabPages.IndexOf(currTabPage) + 1, SourceTab); SheetSelection.SelectedTab = SourceTab; } SourceTab.ResumeLayout(); } } ResumeLayout(); SourceTab = null; Cursor = Cursors.Default; } void SheetSelection_MouseUp(object sender, MouseEventArgs e) { if(e.Button == MouseButtons.Left && SourceTab != null) { SuspendLayout(); TabPage currTabPage = GetTabPageFromXY(e.X, e.Y); if (currTabPage != null && !currTabPage.Equals(SourceTab)) { SourceTab.SuspendLayout(); if (SheetSelection.TabPages.IndexOf(currTabPage) < SheetSelection.TabPages.IndexOf(SourceTab)) { SheetSelection.TabPages.Remove(SourceTab); SheetSelection.TabPages.Insert(SheetSelection.TabPages.IndexOf(currTabPage), SourceTab); SheetSelection.SelectedTab = SourceTab; } else if (SheetSelection.TabPages.IndexOf(currTabPage) > SheetSelection.TabPages.IndexOf(SourceTab)) { SheetSelection.TabPages.Remove(SourceTab); SheetSelection.TabPages.Insert(SheetSelection.TabPages.IndexOf(currTabPage) + 1, SourceTab); SheetSelection.SelectedTab = SourceTab; } SourceTab.ResumeLayout(); } } ResumeLayout(); SourceTab = null; Cursor = Cursors.Default; } void SheetSelectionMouseMove(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Left && SourceTab != null) { TabPage HoveredTabPage = GetTabPageFromXY(e.X, e.Y); if (HoveredTabPage != null) { Rectangle Rect = SheetSelection.GetTabRect(SheetSelection.TabPages.IndexOf(HoveredTabPage)); if (SheetSelection.TabPages.IndexOf(HoveredTabPage) < SheetSelection.TabPages.IndexOf(SourceTab)) { Cursor = Cursors.Hand; if(HoveredTabPage == SheetSelection.TabPages[0]) /*''ArrowForm.Location = Me.PointToScreen(New Point(Rect.Left - 5, _ ''((Rect.Top + Rect.Height) _ '' - ArrowForm.Height)))*/ {} else //The same as above here but this is index 0 += 1 /* ''ArrowForm.Location = Me.PointToScreen(New Point(Rect.Left - 2, _ ''((Rect.Top + Rect.Height) _ ''- ArrowForm.Height)))*/ {} } else if (SheetSelection.TabPages.IndexOf(HoveredTabPage) > SheetSelection.TabPages.IndexOf(SourceTab)) { Cursor = Cursors.Hand; //Custom cursor image } else Cursor = Cursors.Default; } else Cursor = Cursors.Default; } } void SheetSelection_MouseMove(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Left && SourceTab != null) { TabPage HoveredTabPage = GetTabPageFromXY(e.X, e.Y); if (HoveredTabPage != null) { Rectangle Rect = SheetSelection.GetTabRect(SheetSelection.TabPages.IndexOf(HoveredTabPage)); if (SheetSelection.TabPages.IndexOf(HoveredTabPage) < SheetSelection.TabPages.IndexOf(SourceTab)) { Cursor = Cursors.Hand; if(HoveredTabPage == SheetSelection.TabPages[0]) /*''ArrowForm.Location = Me.PointToScreen(New Point(Rect.Left - 5, _ ''((Rect.Top + Rect.Height) _ '' - ArrowForm.Height)))*/ {} else //The same as above here but this is index 0 += 1 /* ''ArrowForm.Location = Me.PointToScreen(New Point(Rect.Left - 2, _ ''((Rect.Top + Rect.Height) _ ''- ArrowForm.Height)))*/ {} } else if (SheetSelection.TabPages.IndexOf(HoveredTabPage) > SheetSelection.TabPages.IndexOf(SourceTab)) { Cursor = Cursors.Hand; //Custom cursor image } else Cursor = Cursors.Default; } else Cursor = Cursors.Default; } } void SheetSelectionMouseDown(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Left && SheetSelection.SelectedTab != null && !SheetSelection.GetTabRect(SheetSelection.SelectedIndex).IsEmpty) SourceTab = SheetSelection.SelectedTab; } void SheetSelection_MouseDown(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Left && SheetSelection.SelectedTab != null && !SheetSelection.GetTabRect(SheetSelection.SelectedIndex).IsEmpty) SourceTab = SheetSelection.SelectedTab; } void WhatsthisClick(object sender, EventArgs e) { MessageBox.Show("This is where you can keep notes while using AshAIO."); } void NoteSheetsLoad(object sender, EventArgs e) { this.Icon = Icon.ExtractAssociatedIcon(System.Reflection.Assembly.GetEntryAssembly().Location); } void AddSheetClick(object sender, EventArgs e) { int cnt = SheetSelection.TabPages.Count + 1; Sheet nsheet = new Sheet("New sheet " + cnt.ToString()); //sheets.Add(nsheet); CreateSheet(nsheet); PSelected = SheetSelection.TabPages[SheetSelection.TabPages.Count - 1]; SheetSelection.SelectedTab = PSelected; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.Azure.AcceptanceTestsAzureSpecials { using Azure; using Microsoft.Rest; using Microsoft.Rest.Azure; using Microsoft.Rest.Azure.OData; 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> /// OdataOperations operations. /// </summary> internal partial class OdataOperations : IServiceOperations<AutoRestAzureSpecialParametersTestClient>, IOdataOperations { /// <summary> /// Initializes a new instance of the OdataOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal OdataOperations(AutoRestAzureSpecialParametersTestClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the AutoRestAzureSpecialParametersTestClient /// </summary> public AutoRestAzureSpecialParametersTestClient Client { get; private set; } /// <summary> /// Specify filter parameter with value '$filter=id gt 5 and name eq /// 'foo'&amp;$orderby=id&amp;$top=10' /// </summary> /// <param name='odataQuery'> /// OData parameters to apply to the operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse> GetWithFilterWithHttpMessagesAsync(ODataQuery<OdataFilter> odataQuery = default(ODataQuery<OdataFilter>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("odataQuery", odataQuery); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetWithFilter", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "azurespecials/odata/filter").ToString(); List<string> _queryParameters = new List<string>(); if (odataQuery != null) { var _odataFilter = odataQuery.ToString(); if (!string.IsNullOrEmpty(_odataFilter)) { _queryParameters.Add(_odataFilter); } } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.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); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_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; } } }
// <copyright file="DefaultSqlConnection.Crud.cs" company="Berkeleybross"> // Copyright (c) Berkeleybross. All rights reserved. // </copyright> namespace PeregrineDb.Databases { using System; using System.Collections.Generic; using System.Data; using System.Diagnostics.CodeAnalysis; using Pagination; using PeregrineDb.SqlCommands; using PeregrineDb.Utils; public partial class DefaultSqlConnection { public int Count<TEntity>(string conditions = null, object parameters = null, int? commandTimeout = null) { var command = this.commandFactory.MakeCountCommand<TEntity>(conditions, parameters); return this.ExecuteScalar<int>(command.CommandText, command.Parameters, CommandType.Text, commandTimeout); } public int Count<TEntity>(object conditions, int? commandTimeout = null) { var command = this.commandFactory.MakeCountCommand<TEntity>(conditions); return this.ExecuteScalar<int>(command.CommandText, command.Parameters, CommandType.Text, commandTimeout); } public bool Exists<TEntity>(string conditions, object parameters, int? commandTimeout = null) { return this.Count<TEntity>(conditions, parameters, commandTimeout) > 0; } public bool Exists<TEntity>(object conditions, int? commandTimeout = null) { return this.Count<TEntity>(conditions, commandTimeout) > 0; } public TEntity Find<TEntity>(object id, int? commandTimeout = null) { var command = this.commandFactory.MakeFindCommand<TEntity>(id); return this.QueryFirstOrDefault<TEntity>(command.CommandText, command.Parameters, CommandType.Text, commandTimeout); } public TEntity Get<TEntity>(object id, int? commandTimeout = null) where TEntity : class { return this.Find<TEntity>(id, commandTimeout) ?? throw new InvalidOperationException($"An entity with id {id} was not found"); } public TEntity FindFirst<TEntity>(string orderBy, string conditions, object parameters, int? commandTimeout = null) { var command = this.commandFactory.MakeGetFirstNCommand<TEntity>(1, conditions, parameters, orderBy); return this.QueryFirstOrDefault<TEntity>(command.CommandText, command.Parameters, CommandType.Text, commandTimeout); } public TEntity FindFirst<TEntity>(string orderBy, object conditions, int? commandTimeout = null) { var command = this.commandFactory.MakeGetFirstNCommand<TEntity>(1, conditions, orderBy); return this.QueryFirstOrDefault<TEntity>(command.CommandText, command.Parameters, CommandType.Text, commandTimeout); } public TEntity GetFirst<TEntity>(string orderBy, string conditions, object parameters, int? commandTimeout = null) where TEntity : class { var result = this.FindFirst<TEntity>(orderBy, conditions, parameters, commandTimeout); return result ?? throw new InvalidOperationException($"No entity matching {conditions} was found"); } public TEntity GetFirst<TEntity>(string orderBy, object conditions, int? commandTimeout = null) where TEntity : class { var command = this.commandFactory.MakeGetFirstNCommand<TEntity>(1, conditions, orderBy); return this.QueryFirst<TEntity>(command.CommandText, command.Parameters, CommandType.Text, commandTimeout); } public TEntity FindSingle<TEntity>(string conditions, object parameters, int? commandTimeout = null) { var command = this.commandFactory.MakeGetFirstNCommand<TEntity>(2, conditions, parameters, null); return this.QuerySingleOrDefault<TEntity>(command.CommandText, command.Parameters, CommandType.Text, commandTimeout); } public TEntity FindSingle<TEntity>(object conditions, int? commandTimeout = null) { var command = this.commandFactory.MakeGetFirstNCommand<TEntity>(2, conditions, null); return this.QuerySingleOrDefault<TEntity>(command.CommandText, command.Parameters, CommandType.Text, commandTimeout); } public TEntity GetSingle<TEntity>(string conditions, object parameters, int? commandTimeout = null) where TEntity : class { var command = this.commandFactory.MakeGetFirstNCommand<TEntity>(2, conditions, parameters, null); return this.QuerySingle<TEntity>(command.CommandText, command.Parameters, CommandType.Text, commandTimeout); } public TEntity GetSingle<TEntity>(object conditions, int? commandTimeout = null) where TEntity : class { var command = this.commandFactory.MakeGetFirstNCommand<TEntity>(2, conditions, null); return this.QuerySingle<TEntity>(command.CommandText, command.Parameters, CommandType.Text, commandTimeout); } public IReadOnlyList<TEntity> GetRange<TEntity>(string conditions, object parameters, int? commandTimeout = null) { var command = this.commandFactory.MakeGetRangeCommand<TEntity>(conditions, parameters); return this.Query<TEntity>(command.CommandText, command.Parameters, CommandType.Text, commandTimeout); } public IReadOnlyList<TEntity> GetRange<TEntity>(object conditions, int? commandTimeout = null) { var command = this.commandFactory.MakeGetRangeCommand<TEntity>(conditions); return this.Query<TEntity>(command.CommandText, command.Parameters, CommandType.Text, commandTimeout); } public IReadOnlyList<TEntity> GetTop<TEntity>(int count, string orderBy, string conditions, object parameters, int? commandTimeout = null) { Ensure.NotNullOrWhiteSpace(orderBy, nameof(orderBy)); var command = this.commandFactory.MakeGetFirstNCommand<TEntity>(count, conditions, parameters, orderBy); return this.Query<TEntity>(command.CommandText, command.Parameters, CommandType.Text, commandTimeout); } public IReadOnlyList<TEntity> GetTop<TEntity>(int count, string orderBy, object conditions, int? commandTimeout = null) { Ensure.NotNullOrWhiteSpace(orderBy, nameof(orderBy)); var command = this.commandFactory.MakeGetFirstNCommand<TEntity>(count, conditions, orderBy); return this.Query<TEntity>(command.CommandText, command.Parameters, CommandType.Text, commandTimeout); } public PagedList<TEntity> GetPage<TEntity>(IPageBuilder pageBuilder, string orderBy, string conditions, object parameters, int? commandTimeout = null) { var totalNumberOfItems = this.Count<TEntity>(conditions, parameters, commandTimeout); var page = pageBuilder.GetCurrentPage(totalNumberOfItems); if (page.IsEmpty) { return PagedList<TEntity>.Empty(totalNumberOfItems, page); } var pageCommand = this.commandFactory.MakeGetPageCommand<TEntity>(page, conditions, parameters, orderBy); var items = this.Query<TEntity>(pageCommand.CommandText, pageCommand.Parameters, CommandType.Text, commandTimeout); return PagedList<TEntity>.Create(totalNumberOfItems, page, items); } public PagedList<TEntity> GetPage<TEntity>(IPageBuilder pageBuilder, string orderBy, object conditions, int? commandTimeout = null) { var totalNumberOfItems = this.Count<TEntity>(conditions, commandTimeout); var page = pageBuilder.GetCurrentPage(totalNumberOfItems); if (page.IsEmpty) { return PagedList<TEntity>.Empty(totalNumberOfItems, page); } var pageCommand = this.commandFactory.MakeGetPageCommand<TEntity>(page, conditions, orderBy); var items = this.Query<TEntity>(pageCommand.CommandText, pageCommand.Parameters, CommandType.Text, commandTimeout); return PagedList<TEntity>.Create(totalNumberOfItems, page, items); } public IReadOnlyList<TEntity> GetAll<TEntity>(int? commandTimeout = null) { var command = this.commandFactory.MakeGetRangeCommand<TEntity>(null, null); return this.Query<TEntity>(command.CommandText, command.Parameters, CommandType.Text, commandTimeout); } public void Insert(object entity, int? commandTimeout = null, bool? verifyAffectedRowCount = null) { var command = this.commandFactory.MakeInsertCommand(entity); var result = this.Execute(command.CommandText, command.Parameters, CommandType.Text, commandTimeout); if (this.Config.ShouldVerifyAffectedRowCount(verifyAffectedRowCount)) { result.ExpectingAffectedRowCountToBe(1); } } public TPrimaryKey Insert<TPrimaryKey>(object entity, int? commandTimeout = null) { Ensure.NotNull(entity, nameof(entity)); var command = this.commandFactory.MakeInsertReturningPrimaryKeyCommand<TPrimaryKey>(entity); return this.ExecuteScalar<TPrimaryKey>(command.CommandText, command.Parameters, CommandType.Text, commandTimeout); } public CommandResult InsertRange<TEntity>(IEnumerable<TEntity> entities, int? commandTimeout = null) { var command = this.commandFactory.MakeInsertRangeCommand(entities); return this.ExecuteMultiple(command.CommandText, command.Parameters, CommandType.Text, commandTimeout); } [SuppressMessage("ReSharper", "PossibleMultipleEnumeration", Justification = "Ensure doesn't enumerate")] public void InsertRange<TEntity, TPrimaryKey>(IEnumerable<TEntity> entities, Action<TEntity, TPrimaryKey> setPrimaryKey, int? commandTimeout = null) { Ensure.NotNull(setPrimaryKey, nameof(setPrimaryKey)); Ensure.NotNull(entities, nameof(entities)); foreach (var entity in entities) { var command = this.commandFactory.MakeInsertReturningPrimaryKeyCommand<TPrimaryKey>(entity); var id = this.ExecuteScalar<TPrimaryKey>(command.CommandText, command.Parameters, CommandType.Text, commandTimeout); setPrimaryKey(entity, id); } } public void Update<TEntity>(TEntity entity, int? commandTimeout = null, bool? verifyAffectedRowCount = null) where TEntity : class { var command = this.commandFactory.MakeUpdateCommand(entity); var result = this.Execute(command.CommandText, command.Parameters, CommandType.Text, commandTimeout); if (this.Config.ShouldVerifyAffectedRowCount(verifyAffectedRowCount)) { result.ExpectingAffectedRowCountToBe(1); } } public CommandResult UpdateRange<TEntity>(IEnumerable<TEntity> entities, int? commandTimeout = null) where TEntity : class { var command = this.commandFactory.MakeUpdateRangeCommand(entities); return this.ExecuteMultiple(command.CommandText, command.Parameters, CommandType.Text, commandTimeout); } public void Delete<TEntity>(TEntity entity, int? commandTimeout = null, bool? verifyAffectedRowCount = null) where TEntity : class { var command = this.commandFactory.MakeDeleteCommand(entity); var result = this.Execute(command.CommandText, command.Parameters, CommandType.Text, commandTimeout); if (this.Config.ShouldVerifyAffectedRowCount(verifyAffectedRowCount)) { result.ExpectingAffectedRowCountToBe(1); } } public void Delete<TEntity>(object id, int? commandTimeout = null, bool? verifyAffectedRowCount = null) { var command = this.commandFactory.MakeDeleteByPrimaryKeyCommand<TEntity>(id); var result = this.Execute(command.CommandText, command.Parameters, CommandType.Text, commandTimeout); if (this.Config.ShouldVerifyAffectedRowCount(verifyAffectedRowCount)) { result.ExpectingAffectedRowCountToBe(1); } } public CommandResult DeleteRange<TEntity>(string conditions, object parameters, int? commandTimeout = null) { var command = this.commandFactory.MakeDeleteRangeCommand<TEntity>(conditions, parameters); return this.Execute(command.CommandText, command.Parameters, CommandType.Text, commandTimeout); } public CommandResult DeleteRange<TEntity>(object conditions, int? commandTimeout = null) { var command = this.commandFactory.MakeDeleteRangeCommand<TEntity>(conditions); return this.Execute(command.CommandText, command.Parameters, CommandType.Text, commandTimeout); } public CommandResult DeleteAll<TEntity>(int? commandTimeout = null) { var command = this.commandFactory.MakeDeleteAllCommand<TEntity>(); return this.Execute(command.CommandText, command.Parameters, CommandType.Text, commandTimeout); } } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for details. using System; using System.IO; using System.Threading; using System.Windows.Forms; using OpenLiveWriter.CoreServices.Threading; namespace OpenLiveWriter.CoreServices.Diagnostics { public class FileLogger : IDisposable { private readonly object bufferLock = new object(); private LogEntry head; private LogEntry tail; private bool canceled = false; /// <summary> /// The log file name. /// </summary> private readonly string logFileName; /// <summary> /// The name the log file should be moved to when it gets too big. /// </summary> private readonly string archiveLogFileName; private readonly int logFileSizeThreshold; public FileLogger(string logFileName) : this(logFileName, null, null) { } public FileLogger(string logFileName, string archiveLogFileName, int? logFileSizeThreshold) { this.logFileName = logFileName; this.archiveLogFileName = archiveLogFileName; this.logFileSizeThreshold = logFileSizeThreshold ?? int.MaxValue; Thread t = ThreadHelper.NewThread(WriteEntriesThreadStart, "Logging", false, false, true); t.Priority = ThreadPriority.BelowNormal; t.Start(); } public void Dispose() { lock (bufferLock) { canceled = true; Monitor.Pulse(bufferLock); } GC.SuppressFinalize(this); } public void AddEntry(object entry) { LogEntry logEntry = new LogEntry(entry); lock (bufferLock) { if (head == null) head = logEntry; if (tail != null) tail.Next = logEntry; tail = logEntry; Monitor.Pulse(bufferLock); } } /// <summary> /// Block until the logger contains no entries /// and is done writing buffered entries /// </summary> public void Flush() { while (true) { lock (bufferLock) { if (canceled) throw new InvalidOperationException("Can't flush a disposed FileLogger"); if (head == null && !writesPending) { return; } Monitor.Pulse(bufferLock); } Thread.Sleep(10); } } private bool writesPending = false; #if DEBUG private bool loggingFailed = false; #endif private void WriteEntriesThreadStart() { FileInfo fileInfo = new FileInfo(logFileName); for (;;) { LogEntry localHead; lock (bufferLock) { writesPending = false; while (head == null && !canceled) { Monitor.Wait(bufferLock); } localHead = head; head = null; tail = null; if (localHead == null && canceled) return; writesPending = true; } try { // If file is larger than a preset threshold, delete // the existing archive file if present and rename the // file to the archive file. if (archiveLogFileName != null) { fileInfo.Refresh(); // make file info flush its internal data cache if (fileInfo.Length > logFileSizeThreshold) { File.Delete(archiveLogFileName); File.Move(logFileName, archiveLogFileName); } } } catch { // no big deal... maybe we'll have better luck next time. } try { // Try to write the message. Incrementally back off, waiting for the file to // become available. (The first backoff is 0ms intentionally -- to give up our // scheduling quantum -- allowing another thread to run. Subsequent backoffs // increase linearly at 5ms intervals.) for (int i = 0; ; i++) { try { // Get a stream writer on the file. using (StreamWriter streamWriter = File.AppendText(logFileName)) { for (LogEntry le = localHead; le != null; le = le.Next) { // Attempt to write the entry. streamWriter.Write(le.Value.ToString()); } } break; // writes succeeded, don't try again } catch { // Sleep. Back off linearly, but not more than 2s. Thread.Sleep(Math.Min(i * 5, 2000)); } } } catch (Exception e) { object foo = e; // This should never happen, but if it does, we can't very well log about it. #if DEBUG if (!loggingFailed) MessageBox.Show("Logging failed!\n\n" + e.ToString(), ApplicationEnvironment.ProductNameQualified); loggingFailed = true; #endif } } } private class LogEntry { public readonly object Value; public LogEntry Next; public LogEntry(object value) { Value = value; } } } public class CsvLogEntry { private string[] words; public CsvLogEntry(params string[] words) { this.words = words; } public override string ToString() { string[] escaped = new string[words.Length]; for (int i = 0; i < escaped.Length; i++) escaped[i] = '"' + (words[i] ?? "").Replace("\"", "\"\"") + '"'; return StringHelper.Join(escaped, ",") + "\r\n"; } } }
using UnityEngine; using System; using System.Collections; using System.Collections.Generic; using System.IO; /* The MIT License (MIT) Copyright (c) 2014 Brad Nelson and Play-Em 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. */ // AnimationToPNG is based on Twinfox and bitbutter's Render Particle to Animated Texture Scripts, // this script will render out an animation that is played when "Play" is pressed in the editor. /* Basically this is a script you can attach to any gameobject in the scene, but you have to reference a Black Camera and White Camera both of which should be set to orthographic, but this script should have it covered. There is a prefab called AnimationToPNG which should include everything needed to run the script. If you have Unity Pro, you can use Render Texture, which can accurately render the transparent background for your animations easily in full resolution of the camera. Just check the box for the variable "useRenderTexture" to use RenderTextures instead. If you are using Unity Free, then leave this unchecked and you will have a split area using half of the screen width to render the animations. You can change the "animationName" to a string of your choice for a prefix for the output file names, if it is left empty then no filename will be added. The destination folder is relative to the Project Folder root, so you can change the string to a folder name of your choice and it will be created. If it already exists, it will simply create a new folder with a number incremented as to how many of those named folders exist. Choose how many frames per second the animation will run by changing the "frameRate" variable, and how many frames of the animation you wish to capture by changing the "framesToCapture" variable. Once "Play" is pressed in the Unity Editor, it should output all the animation frames to PNGs output in the folder you have chosen, and will stop capturing after the number of frames you wish to capture is completed. */ public class AnimationToPNG : MonoBehaviour { // Animation Name to be the prefix for the output filenames public string animationName = ""; // Default folder name where you want the animations to be output public string folder = "PNG_Animations"; // Framerate at which you want to play the animation public int frameRate = 25; // How many frames you want to capture during the animation public int framesToCapture = 25; // White Camera private Camera whiteCam; // Black Camera private Camera blackCam; // Pixels to World Unit size public float pixelsToWorldUnit = 74.48275862068966f; // If you have Unity Pro you can use a RenderTexture which will render the full camera width, otherwise it will only render half private bool useRenderTexture = false; private int videoframe = 0; // how many frames we've rendered private float originaltimescaleTime; // track the original time scale so we can freeze the animation between frames private string realFolder = ""; // real folder where the output files will be private bool done = false; // is the capturing finished? private bool readyToCapture = false; // Make sure all the camera setup is complete before capturing private float cameraSize; // Size of the orthographic camera established from the current screen resolution and the pixels to world unit private Texture2D texb; // black camera texture private Texture2D texw; // white camera texture private Texture2D outputtex; // final output texture private RenderTexture blackCamRenderTexture; // black camera render texure private RenderTexture whiteCamRenderTexture; // white camera render texure public void Start () { useRenderTexture = Application.HasProLicense(); // Set the playback framerate! // (real time doesn't influence time anymore) Time.captureFramerate = frameRate; // Create a folder that doesn't exist yet. Append number if necessary. realFolder = folder; int count = 1; while (Directory.Exists(realFolder)) { realFolder = folder + count; count++; } // Create the folder Directory.CreateDirectory(realFolder); originaltimescaleTime = Time.timeScale; // Force orthographic camera to render out sprites per pixel size designated by pixels to world unit cameraSize = Screen.width / ((( Screen.width / Screen.height ) * 2 ) * pixelsToWorldUnit ); GameObject bc = new GameObject("Black Camera"); bc.transform.localPosition = new Vector3(0, 0, -1); blackCam = bc.AddComponent<Camera>(); blackCam.backgroundColor = Color.black; blackCam.orthographic = true; blackCam.orthographicSize = cameraSize; blackCam.tag = "MainCamera"; GameObject wc = new GameObject("White Camera"); wc.transform.localPosition = new Vector3(0, 0, -1); whiteCam = wc.AddComponent<Camera>(); whiteCam.backgroundColor = Color.white; whiteCam.orthographic = true; whiteCam.orthographicSize = cameraSize; // If not using a Render Texture then set the cameras to split the screen to ensure we have an accurate image with alpha if (!useRenderTexture){ // Change the camera rects to have split on screen to capture the animation properly blackCam.rect = new Rect(0.0f, 0.0f, 0.5f, 1.0f); whiteCam.rect = new Rect(0.5f, 0.0f, 0.5f, 1.0f); } // Cameras are set ready to capture! readyToCapture = true; } void Update() { // If the capturing is not done and the cameras are set, then Capture the animation if(!done && readyToCapture){ StartCoroutine(Capture()); } } void LateUpdate() { // When we are all done capturing, clean up all the textures and RenderTextures from the scene if (done) { DestroyImmediate(texb); DestroyImmediate(texw); DestroyImmediate(outputtex); if (useRenderTexture) { //Clean Up whiteCam.targetTexture = null; RenderTexture.active = null; DestroyImmediate(whiteCamRenderTexture); blackCam.targetTexture = null; RenderTexture.active = null; DestroyImmediate(blackCamRenderTexture); } } } IEnumerator Capture () { if(videoframe < framesToCapture) { // name is "realFolder/animationName0000.png" // string name = realFolder + "/" + animationName + Time.frameCount.ToString("0000") + ".png"; string filename = String.Format("{0}/" + animationName + "{1:D04}.png", realFolder, Time.frameCount); // Stop time Time.timeScale = 0; // Yield to next frame and then start the rendering yield return new WaitForEndOfFrame(); // If we are using a render texture to make the animation frames then set up the camera render textures if (useRenderTexture){ //Initialize and render textures blackCamRenderTexture = new RenderTexture(Screen.width,Screen.height,24, RenderTextureFormat.ARGB32); whiteCamRenderTexture = new RenderTexture(Screen.width,Screen.height,24, RenderTextureFormat.ARGB32); blackCam.targetTexture = blackCamRenderTexture; blackCam.Render(); RenderTexture.active = blackCamRenderTexture; texb = GetTex2D(true); //Now do it for Alpha Camera whiteCam.targetTexture = whiteCamRenderTexture; whiteCam.Render(); RenderTexture.active = whiteCamRenderTexture; texw = GetTex2D(true); } // If not using render textures then simply get the images from both cameras else { // store 'black background' image texb = GetTex2D(true); // store 'white background' image texw = GetTex2D(false); } // If we have both textures then create final output texture if (texw && texb) { int width = Screen.width; int height = Screen.height; // If we are not using a render texture then the width will only be half the screen if (!useRenderTexture){ width = width / 2; } outputtex = new Texture2D(width, height, TextureFormat.ARGB32, false); // Create Alpha from the difference between black and white camera renders for (int y = 0; y < outputtex.height; ++y) { // each row for (int x = 0; x < outputtex.width; ++x) { // each column float alpha; if (useRenderTexture){ alpha = texw.GetPixel(x, y).r - texb.GetPixel(x, y).r; } else { alpha = texb.GetPixel(x + width, y).r - texb.GetPixel(x, y).r; } alpha = 1.0f - alpha; Color color; if(alpha == 0) { color = Color.clear; } else { color = texb.GetPixel(x, y) / alpha; } color.a = alpha; outputtex.SetPixel(x, y, color); } } // Encode the resulting output texture to a byte array then write to the file byte[] pngShot = outputtex.EncodeToPNG(); #if !UNITY_WEBPLAYER File.WriteAllBytes(filename, pngShot); #endif // Reset the time scale, then move on to the next frame. Time.timeScale = originaltimescaleTime; videoframe++; } // Debug.Log("Frame " + name + " " + videoframe); } else { Debug.Log("Complete! " + videoframe + " videoframes rendered (0 indexed)"); done = true; } } // Get the texture from the screen, render all or only half of the camera private Texture2D GetTex2D(bool renderAll) { // Create a texture the size of the screen, RGB24 format int width = Screen.width; int height = Screen.height; if (!renderAll) { width = width / 2; } Texture2D tex = new Texture2D(width, height, TextureFormat.ARGB32, false); // Read screen contents into the texture tex.ReadPixels(new Rect(0, 0, width, height), 0, 0); tex.Apply(); return tex; } }
using System; using System.Collections; using System.Linq; using UnityEngine; using UnityWeld.Binding.Exceptions; using UnityWeld.Binding.Internal; namespace UnityWeld.Binding { /// <summary> /// Binds a property in the view-model that is a collection and instantiates copies /// of template objects to bind to the items of the collection. /// /// Creates and destroys child objects when items are added and removed from a /// collection that implements INotifyCollectionChanged, like ObservableList. /// </summary> [HelpURL("https://github.com/Real-Serious-Games/Unity-Weld")] public class CollectionBinding : AbstractTemplateSelector { /// <summary> /// Collection that we have bound to. /// </summary> private IEnumerable viewModelCollectionValue; public override void Connect() { Disconnect(); string propertyName; object newViewModel; ParseViewModelEndPointReference( ViewModelPropertyName, out propertyName, out newViewModel ); viewModel = newViewModel; viewModelPropertyWatcher = new PropertyWatcher( newViewModel, propertyName, NotifyPropertyChanged_PropertyChanged ); BindCollection(); } public override void Disconnect() { UnbindCollection(); if (viewModelPropertyWatcher != null) { viewModelPropertyWatcher.Dispose(); viewModelPropertyWatcher = null; } viewModel = null; } private void NotifyPropertyChanged_PropertyChanged() { RebindCollection(); } private void Collection_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { switch (e.Action) { case NotifyCollectionChangedAction.Add: // Add items that were added to the bound collection. if (e.NewItems != null) { var list = viewModelCollectionValue as IList; foreach (var item in e.NewItems) { int index; if (list == null) { // Default to adding the new object at the last index. index = transform.childCount; } else { index = list.IndexOf(item); } InstantiateTemplate(item, index); } } break; case NotifyCollectionChangedAction.Remove: // TODO: respect item order // Remove items that have been deleted. if (e.OldItems != null) { foreach (var item in e.OldItems) { DestroyTemplate(item); } } break; case NotifyCollectionChangedAction.Reset: DestroyAllTemplates(); break; default: throw new ArgumentOutOfRangeException(); } } /// <summary> /// Bind to the view model collection so we can monitor it for changes. /// </summary> private void BindCollection() { // Bind view model. var viewModelType = viewModel.GetType(); string propertyName; string viewModelName; ParseEndPointReference( ViewModelPropertyName, out propertyName, out viewModelName ); var viewModelCollectionProperty = viewModelType.GetProperty(propertyName); if (viewModelCollectionProperty == null) { throw new MemberNotFoundException( "Expected property " + ViewModelPropertyName + ", but it wasn't found on type " + viewModelType + "." ); } // Get value from view model. var viewModelValue = viewModelCollectionProperty.GetValue(viewModel, null); if (viewModelValue == null) { throw new PropertyNullException( "Cannot bind to null property in view: " + ViewModelPropertyName ); } if (!(viewModelValue is IEnumerable)) { throw new InvalidTypeException( "Property " + ViewModelPropertyName + " is not a collection and cannot be used to bind collections." ); } viewModelCollectionValue = (IEnumerable)viewModelValue; // Generate children var collectionAsList = viewModelCollectionValue.Cast<object>().ToList(); for (var index = 0; index < collectionAsList.Count; index++) { InstantiateTemplate(collectionAsList[index], index); } // Subscribe to collection changed events. var collectionChanged = viewModelCollectionValue as INotifyCollectionChanged; if (collectionChanged != null) { collectionChanged.CollectionChanged += Collection_CollectionChanged; } } /// <summary> /// Unbind from the collection, stop monitoring it for changes. /// </summary> private void UnbindCollection() { DestroyAllTemplates(); // Unsubscribe from collection changed events. if (viewModelCollectionValue != null) { var collectionChanged = viewModelCollectionValue as INotifyCollectionChanged; if (collectionChanged != null) { collectionChanged.CollectionChanged -= Collection_CollectionChanged; } viewModelCollectionValue = null; } } /// <summary> /// Rebind to the collection when it has changed on the view-model. /// </summary> private void RebindCollection() { UnbindCollection(); BindCollection(); } } }
//#define GSOLVER_LOG //#define ALWAYS_CHECK_THRESHOLD #define AGGREGATE_CONSTANTS using System; using AutoDiff; using AD=AutoDiff; using System.IO; using System.Text; using Castor; using System.Collections.Generic; namespace Alica.Reasoner { public class GSolver { protected class RpropResult : IComparable<RpropResult> { public double[] initialValue; public double[] finalValue; public double initialUtil; public double finalUtil; public bool aborted; public int CompareTo (RpropResult other) { return (this.finalUtil > other.finalUtil)?-1:1; } public double DistanceTraveled() { double ret = 0; for(int i=0; i<initialValue.Length; i++) { ret+= (initialValue[i]-finalValue[i])*(initialValue[i]-finalValue[i]); } return Math.Sqrt(ret); } public double DistanceTraveledNormed(double[] ranges) { double ret = 0; for(int i=0; i<initialValue.Length; i++) { ret+= (initialValue[i]-finalValue[i])*(initialValue[i]-finalValue[i])/(ranges[i]*ranges[i]); } return Math.Sqrt(ret); } } public long Runs {get; private set;} public long FEvals {get; private set;} public long MaxFEvals {get; set;} double initialStepSize = 0.005; public double RPropConvergenceStepSize {get; private set;} internal double utilitySignificanceThreshold = 1E-22; Random rand; int dim; double[,] limits; double[] ranges; double[] rpropStepWidth; double[] rpropStepConvergenceThreshold; double utilityThreshold; ulong maxSolveTime; //double[][] seeds; AD.ICompiledTerm term; StreamWriter sw; List<RpropResult> rResults; protected static int fcounter =0; //Configuration: protected bool seedWithUtilOptimum; public GSolver () { AD.Term.SetAnd(AD.Term.AndType.and); AD.Term.SetOr(AD.Term.OrType.max); this.rand = new Random(); this.rResults = new List<RpropResult>(); this.seedWithUtilOptimum = true; this.MaxFEvals = SystemConfig.LocalInstance["Alica"].GetInt("Alica","CSPSolving","MaxFunctionEvaluations"); this.maxSolveTime = ((ulong)SystemConfig.LocalInstance["Alica"].GetInt("Alica","CSPSolving","MaxSolveTime"))*1000000; RPropConvergenceStepSize = 1E-2; } protected void InitLog() { string logFile = "/tmp/test"+(fcounter++)+".dbg"; FileStream file = new FileStream(logFile, FileMode.Create); this.sw = new StreamWriter(file); sw.AutoFlush = true; } protected void Log(double util, double[] val) { sw.Write(util); sw.Write("\t"); for(int i=0; i <dim; i++) { sw.Write(val[i]); sw.Write("\t"); } sw.WriteLine(); } protected void LogStep() { sw.WriteLine(); sw.WriteLine(); } protected void CloseLog() { if (sw != null) { sw.Close(); sw=null; } } public double[] Solve(AD.Term equation, AD.Variable[] args, double[,] limits, out double util) { return Solve(equation,args,limits,null,Double.MaxValue, out util); } public bool SolveSimple(AD.Term equation, AD.Variable[] args, double[,] limits) { return SolveSimple(equation,args,limits,null); } public double[] Solve(AD.Term equation, AD.Variable[] args, double[,] limits, double[][] seeds,double sufficientUtility, out double util) { this.FEvals = 0; this.Runs = 0; util = 0; this.utilityThreshold = sufficientUtility; #if (GSOLVER_LOG) InitLog(); #endif rResults.Clear(); ulong begin = RosCS.RosSharp.Now(); this.dim = args.Length; this.limits = limits; this.ranges = new double[dim]; for(int i=0; i<dim; i++) { this.ranges[i] = (this.limits[i,1]-this.limits[i,0]); } #if AGGREGATE_CONSTANTS equation = equation.AggregateConstants(); #endif term = AD.TermUtils.Compile(equation,args); AD.ConstraintUtility cu = (AD.ConstraintUtility) equation; bool utilIsConstant =(cu.Utility is AD.Constant); if (utilIsConstant) this.utilityThreshold = 0.75; bool constraintIsConstant = (cu.Constraint is AD.Constant); if (constraintIsConstant) { if(((AD.Constant)cu.Constraint).Value < 0.25) { util = ((AD.Constant)cu.Constraint).Value; double[] ret = new double[dim]; for(int i=0; i<dim; i++) { ret[i] = this.ranges[i]/2.0+this.limits[i,0]; } return ret; } } //Optimize given seeds this.rpropStepWidth = new double[dim]; this.rpropStepConvergenceThreshold = new double[dim]; if (seeds != null) { this.Runs++; //Run with prefered cached seed RpropResult rpfirst = RPropLoop(seeds[0],true); if (rpfirst.finalUtil > this.utilityThreshold) { util = rpfirst.finalUtil; //Console.WriteLine("FEvals: {0}",this.FEvals); return rpfirst.finalValue; } rResults.Add(rpfirst); //run with seeds of all other agends for(int i=1; i<seeds.Length; i++) { if (begin + this.maxSolveTime < RosCS.RosSharp.Now() || this.FEvals > this.MaxFEvals) { break; //do not check any further seeds } this.Runs++; RpropResult rp = RPropLoop(seeds[i],false); if (rp.finalUtil > this.utilityThreshold) { util = rp.finalUtil; //Console.WriteLine("FEvals: {0}",this.FEvals); return rp.finalValue; } rResults.Add(rp); } } //Here: Ignore all constraints search optimum if (begin + this.maxSolveTime > RosCS.RosSharp.Now() && this.FEvals < this.MaxFEvals) { //if time allows, do an unconstrained run if(!constraintIsConstant && !utilIsConstant && seedWithUtilOptimum) { AD.ICompiledTerm curProb = term; term = AD.TermUtils.Compile(((AD.ConstraintUtility)equation).Utility,args); this.Runs++; double[] utilitySeed = RPropLoop(null).finalValue; term = curProb; //Take result and search with constraints RpropResult ru = RPropLoop(utilitySeed,false); /*if (ru.finalUtil > this.utilityThreshold) { util = ru.finalUtil; return ru.finalValue; }*/ rResults.Add(ru); } } do { //Do runs until termination criteria, running out of time, or too many function evaluations this.Runs++; RpropResult rp = RPropLoop(null,false); if(rp.finalUtil > this.utilityThreshold) { util = rp.finalUtil; //Console.WriteLine("FEvals: {0}",this.FEvals); return rp.finalValue; } rResults.Add(rp); } while(begin + this.maxSolveTime > RosCS.RosSharp.Now() && this.FEvals < this.MaxFEvals); //return best result int resIdx = 0; RpropResult res = rResults[0]; for(int i=1; i< rResults.Count; i++) { if (Double.IsNaN(res.finalUtil) || rResults[i].finalUtil > res.finalUtil) { if (resIdx == 0 && seeds!=null && !Double.IsNaN(res.finalUtil)) { if (rResults[i].finalUtil - res.finalUtil > utilitySignificanceThreshold && rResults[i].finalUtil > 0.75) { res = rResults[i]; resIdx = i; } } else { res = rResults[i]; resIdx = i; } } } //Console.WriteLine("ResultIndex: {0} Delta {1}",resIdx,res.finalUtil-rResults[0].finalUtil); #if (GSOLVER_LOG) CloseLog(); #endif // Console.Write("Found: "); // for(int i=0; i<dim; i++) { // Console.Write("{0}\t",res.finalValue[i]); // } // Console.WriteLine(); // //Console.WriteLine("Runs: {0} FEvals: {1}",this.Runs,this.FEvals); util = res.finalUtil; return res.finalValue; } public bool SolveSimple(AD.Term equation, AD.Variable[] args, double[,] limits, double[][] seeds) { rResults.Clear(); this.dim = args.Length; this.limits = limits; this.ranges = new double[dim]; for(int i=0; i<dim; i++) { this.ranges[i] = (this.limits[i,1]-this.limits[i,0]); } equation = equation.AggregateConstants(); term = AD.TermUtils.Compile(equation,args); this.rpropStepWidth = new double[dim]; this.rpropStepConvergenceThreshold = new double[dim]; if (seeds != null) { for(int i=0; i<seeds.Length; i++) { RpropResult r = RPropLoopSimple(seeds[i]); rResults.Add(r); if (r.finalUtil > 0.75) return true; } } int runs = 2*dim - (seeds==null?0:seeds.Length); for(int i=0; i<runs; i++) { RpropResult r = RPropLoopSimple(null); rResults.Add(r); if (r.finalUtil > 0.75) return true; } int adit = 0; while(!EvalResults() && adit++ < 20) { RpropResult r = RPropLoopSimple(null); rResults.Add(r); if(r.finalUtil > 0.75) return true; } if (adit > 20) { Console.WriteLine("Failed to satisfy heuristic!"); } return false; } public double[] SolveTest(AD.Term equation, AD.Variable[] args, double[,] limits) { #if (GSOLVER_LOG) InitLog(); #endif rResults.Clear(); double[] res = null; this.dim = args.Length; this.limits = limits; this.ranges = new double[dim]; for(int i=0; i<dim; i++) { this.ranges[i] = (this.limits[i,1]-this.limits[i,0]); } term = AD.TermUtils.Compile(equation,args); this.rpropStepWidth = new double[dim]; this.rpropStepConvergenceThreshold = new double[dim]; this.Runs = 0; this.FEvals = 0; //int runs = 1000000; while(true) { this.Runs++; //RpropResult r = RPropLoopSimple(null); RpropResult r = RPropLoop(null,false); //Console.WriteLine("Run: {0} Util: {1}",i,r.finalUtil); /*for(int k=0; k<dim; k++) { Console.Write("{0}\t",r.finalValue[k]); } Console.WriteLine();*/ if (r.finalUtil > 0.75) { res = r.finalValue; break; } } #if (GSOLVER_LOG) CloseLog(); #endif return res; } public double[] SolveTest(AD.Term equation, AD.Variable[] args, double[,] limits,int maxRuns, out bool found) { #if (GSOLVER_LOG) InitLog(); #endif found = false; rResults.Clear(); double[] res = null; this.dim = args.Length; this.limits = limits; this.ranges = new double[dim]; for(int i=0; i<dim; i++) { this.ranges[i] = (this.limits[i,1]-this.limits[i,0]); } term = AD.TermUtils.Compile(equation,args); this.rpropStepWidth = new double[dim]; this.rpropStepConvergenceThreshold = new double[dim]; this.Runs = 0; this.FEvals = 0; while(this.Runs < maxRuns) { this.Runs++; //RpropResult r = RPropLoopSimple(null); RpropResult r = RPropLoop(null,false); //Console.WriteLine("Run: {0} Util: {1}",i,r.finalUtil); /*for(int k=0; k<dim; k++) { Console.Write("{0}\t",r.finalValue[k]); } Console.WriteLine();*/ if (r.finalUtil > 0.75) { res = r.finalValue; found = true; break; } } #if (GSOLVER_LOG) CloseLog(); #endif return res; } protected double[] InitialPointFromSeed(RpropResult res, double[] seed) { Tuple<double[],double> tup; res.initialValue = new double[dim]; res.finalValue = new double[dim]; for(int i=0; i<dim; i++) { if (Double.IsNaN(seed[i])) { res.initialValue[i] = rand.NextDouble()*ranges[i]+limits[i,0]; } else { res.initialValue[i] = Math.Min(Math.Max(seed[i],limits[i,0]),limits[i,1]); } } tup = term.Differentiate(res.initialValue); res.initialUtil = tup.Item2; res.finalUtil = tup.Item2; Buffer.BlockCopy(res.initialValue,0,res.finalValue,0,sizeof(double)*dim); return tup.Item1; } protected double[] InitialPoint(RpropResult res) { Tuple<double[],double> tup; bool found = true; res.initialValue = new double[dim]; res.finalValue = new double[dim]; do { for(int i=0; i<dim; i++) { //double range = limits[i,1]-limits[i,0]; res.initialValue[i] = rand.NextDouble()*ranges[i]+limits[i,0]; } this.FEvals++; tup = term.Differentiate(res.initialValue); for(int i=0; i<dim; i++) { if (Double.IsNaN(tup.Item1[i])) { //Console.WriteLine("NaN in Gradient, retrying"); found = false; break; } else found = true; } } while(!found); res.initialUtil = tup.Item2; res.finalUtil = tup.Item2; Buffer.BlockCopy(res.initialValue,0,res.finalValue,0,sizeof(double)*dim); return tup.Item1; } protected RpropResult RPropLoop(double[] seed) { return RPropLoop(seed,false); } protected RpropResult RPropLoop(double[] seed, bool precise) { //Console.WriteLine("RpropLoop"); InitialStepSize(); double[] curGradient; RpropResult ret = new RpropResult(); if(seed != null) { curGradient = InitialPointFromSeed(ret,seed); } else { curGradient = InitialPoint(ret); } double curUtil = ret.initialUtil; double[] formerGradient = new double[dim]; double[] curValue = new double[dim]; Tuple<double[],double> tup; Buffer.BlockCopy(ret.initialValue,0,curValue,0,sizeof(double)*dim); formerGradient = curGradient; //Buffer.BlockCopy(curGradient,0,formerGradient,0,sizeof(double)*dim); int itcounter = 0; int badcounter = 0; /*Console.WriteLine("Initial Sol:"); for(int i=0; i<dim;i++) { Console.Write("{0} ",curValue[i]); } Console.WriteLine(); Console.WriteLine("Initial Util: {0}",curUtil); */ #if (GSOLVER_LOG) Log(curUtil,curValue); #endif int maxIter = 60; int maxBad = 30; double minStep = 1E-11; if(precise) { maxIter = 120; //110 maxBad = 60; //60 minStep = 1E-15;//15 } int convergendDims = 0; while(itcounter++ < maxIter && badcounter < maxBad) { //Console.WriteLine("Iteration {0}",itcounter); //Console.WriteLine("Val: "); /*if (curUtil < 0.5 && rand.NextDouble()< 0.05) { //JUMP! //Console.WriteLine("JUMPING!"); for (int i=0; i<dim; i++) { curValue[i] += curGradient[i]; if (curValue[i] > limits[i,1]) curValue[i] = limits[i,1]; else if (curValue[i] < limits[i,0]) curValue[i] = limits[i,0]; } InitialStepSize(); } else {*/ convergendDims = 0; for(int i=0; i<dim; i++) { if (curGradient[i] * formerGradient[i] > 0) rpropStepWidth[i] *= 1.3; else if (curGradient[i] * formerGradient[i] < 0) rpropStepWidth[i] *= 0.5; rpropStepWidth[i] = Math.Max(minStep,rpropStepWidth[i]); //rpropStepWidth[i] = Math.Max(0.000001,rpropStepWidth[i]); if (curGradient[i] > 0) curValue[i] += rpropStepWidth[i]; else if (curGradient[i] < 0) curValue[i] -= rpropStepWidth[i]; if (curValue[i] > limits[i,1]) curValue[i] = limits[i,1]; else if (curValue[i] < limits[i,0]) curValue[i] = limits[i,0]; //Console.Write("{0}\t",curValue[i]); if(rpropStepWidth[i] < rpropStepConvergenceThreshold[i]) { ++convergendDims; } } //Abort if all dimensions are converged if(!precise && convergendDims>=dim) { if (curUtil > ret.finalUtil) { ret.finalUtil = curUtil; Buffer.BlockCopy(curValue,0,ret.finalValue,0,sizeof(double)*dim); } return ret; } //} //Console.WriteLine(); this.FEvals++; tup = term.Differentiate(curValue); bool allZero = true; //Console.WriteLine("Grad: "); for(int i=0; i < dim; i++) { if (Double.IsNaN(tup.Item1[i])) { //Console.Error.WriteLine("NaN in gradient, aborting!"); ret.aborted=true; #if (GSOLVER_LOG) LogStep(); #endif return ret; } allZero &= (tup.Item1[i]==0); //Console.Write("{0}\t",tup.Item1[i]); } //Console.WriteLine(); curUtil = tup.Item2; formerGradient = curGradient; curGradient = tup.Item1; #if (GSOLVER_LOG) Log(curUtil,curValue); #endif //Console.WriteLine("CurUtil: {0} Final {1}",curUtil,ret.finalUtil); if (curUtil > ret.finalUtil) { badcounter = 0;//Math.Max(0,badcounter-1); //if (curUtil-ret.finalUtil < 0.00000000000001) { //Console.WriteLine("not better"); // badcounter++; //} else { //badcounter = 0; //} ret.finalUtil = curUtil; Buffer.BlockCopy(curValue,0,ret.finalValue,0,sizeof(double)*dim); //ret.finalValue = curValue; #if (ALWAYS_CHECK_THRESHOLD) if(curUtil > utilityThreshold) return ret; #endif } else { //if (curUtil < ret.finalUtil || curUtil > 0) badcounter++; badcounter++; } if (allZero) { //Console.WriteLine("All Zero!"); /*Console.WriteLine("Util {0}",curUtil); Console.Write("Vals: "); for(int i=0; i < dim; i++) { Console.Write("{0}\t",curValue[i]); } Console.WriteLine();*/ ret.aborted = false; #if (GSOLVER_LOG) LogStep(); #endif return ret; } } #if (GSOLVER_LOG) LogStep(); #endif ret.aborted = false; return ret; } protected RpropResult RPropLoopSimple(double[] seed) { InitialStepSize(); double[] curGradient; RpropResult ret = new RpropResult(); if(seed != null) { curGradient = InitialPointFromSeed(ret,seed); } else { curGradient = InitialPoint(ret); } double curUtil = ret.initialUtil; if (ret.initialUtil > 0.75) { return ret; } double[] formerGradient = new double[dim]; double[] curValue = new double[dim]; Tuple<double[],double> tup; Buffer.BlockCopy(ret.initialValue,0,curValue,0,sizeof(double)*dim); formerGradient = curGradient; //Buffer.BlockCopy(curGradient,0,formerGradient,0,sizeof(double)*dim); int itcounter = 0; int badcounter = 0; //Log(curUtil,curValue); while(itcounter++ < 40 && badcounter < 6) { for(int i=0; i<dim; i++) { if (curGradient[i] * formerGradient[i] > 0) rpropStepWidth[i] *= 1.3; else if (curGradient[i] * formerGradient[i] < 0) rpropStepWidth[i] *= 0.5; rpropStepWidth[i] = Math.Max(0.0001,rpropStepWidth[i]); if (curGradient[i] > 0) curValue[i] += rpropStepWidth[i]; else if (curGradient[i] < 0) curValue[i] -= rpropStepWidth[i]; if (curValue[i] > limits[i,1]) curValue[i] = limits[i,1]; else if (curValue[i] < limits[i,0]) curValue[i] = limits[i,0]; } tup = term.Differentiate(curValue); bool allZero = true; for(int i=0; i < dim; i++) { if (Double.IsNaN(tup.Item1[i])) { Console.WriteLine("NaN in gradient, aborting!"); ret.aborted=false;//true; //HACK! return ret; } allZero &= (tup.Item1[i]==0); } curUtil = tup.Item2; formerGradient = curGradient; curGradient = tup.Item1; //Log(curUtil,curValue); //Console.WriteLine("CurUtil: {0} Final {1}",curUtil,ret.finalUtil); if (curUtil > ret.finalUtil) { badcounter = 0; ret.finalUtil = curUtil; Buffer.BlockCopy(curValue,0,ret.finalValue,0,sizeof(double)*dim); if (curUtil > 0.75) return ret; } else { badcounter++; } if (allZero) { //Console.WriteLine("All Zero!"); ret.aborted = false; return ret; } } ret.aborted = false; return ret; } protected void InitialStepSize() { for(int i=0; i<this.dim; i++) { //double range = this.limits[i,1]-this.limits[i,0]; this.rpropStepWidth[i] = initialStepSize*ranges[i]; this.rpropStepConvergenceThreshold[i] = rpropStepWidth[i]*this.RPropConvergenceStepSize; } } protected bool EvalResults() { /* * TODO: Compare Average Distance between start and end point to * Average distance between any two arbitrary points. * * Latter one can be found in http://www.math.uni-muenster.de/reine/u/burgstal/d18.pdf : * maxDist = sqrt(dim) * avgDist <= 1 / sqrt(6) * sqrt((1+2*sqrt(1-3/(5*dim)))/3) * maxDist * * aprox: (http://www.jstor.org/pss/1427094) * * avgDist = sqrt(dim/3) * (1 - 1/(10*k) - 13/(280*k^2) - 101/ (2800*k^3) - 37533 / (1232000 k^4) * O(sqrt(k)) (?) * */ int count = this.rResults.Count; //Console.WriteLine("Eval"); /* double maxDist = Math.Sqrt(dim); double avgDist = 1 / Math.Sqrt(6) * Math.Sqrt((1+2*Math.Sqrt(1-3/(5*dim)))/3) * maxDist; double allDist = 0; for(int i=0; i<count; i++) { if (rResults[i].aborted) { abortedCount++; } else { allDist += rResults[i].DistanceTraveledNormed(this.ranges); } } double avgDistTraveled = allDist / (count-abortedCount); Console.WriteLine("Traveled: {0} Expected: {1}",avgDistTraveled,avgDist); */ //if (avgDistTraveled < 0.66* avgDist) return false; int abortedCount = 0; //double[] midValue = new double[dim]; double[] midInitValue = new double[dim]; //double[] valueDev = new double[dim]; double[] valueInitDev = new double[dim]; //double midUtil =0; for(int i=0; i<count; i++) { if (rResults[i].aborted) { abortedCount++; } else { //midUtil += rResults[i].finalUtil; for(int j=0; j<dim; j++) { //midValue[j] += rResults[i].finalValue[j]; midInitValue[j] += rResults[i].initialValue[j]; } } } if (count-abortedCount < dim) return false; for(int j=0; j<dim; j++) { //midValue[j] /= (count-abortedCount); midInitValue[j] /= (count-abortedCount); } for(int i=0; i<count; i++) { if (rResults[i].aborted) continue; for (int j=0; j<dim; j++) { //valueDev[j] += Math.Pow((rResults[i].finalValue[j]-midValue[j])/ranges[j],2); valueInitDev[j] += Math.Pow((rResults[i].initialValue[j]-midInitValue[j])/ranges[j],2); } } for(int j=0; j<dim; j++) { //if (valueDev[j] > valueInitDev[j]) return false; //valueDev[j] /= (count-abortedCount); valueInitDev[j] /= (count-abortedCount); //if (Math.Sqrt(valueInitDev[j]) < 0.22) return false; if (valueInitDev[j] < 0.0441) return false; } Console.WriteLine("Runs: {0} Aborted: {1}",count,abortedCount); /*Console.WriteLine("Final Std Deviation: "); for(int j=0; j<dim; j++) { Console.Write("{0}\t",Math.Sqrt(valueDev[j])); } Console.WriteLine(); Console.WriteLine("Initial Std Deviation: "); for(int j=0; j<dim; j++) { Console.Write("{0}\t",Math.Sqrt(valueInitDev[j])); } Console.WriteLine(); */ /*for(int j=0; j<dim; j++) { if (valueDev[j] > valueInitDev[j]) return false; }*/ return true; } } }
/// This code was generated by /// \ / _ _ _| _ _ /// | (_)\/(_)(_|\/| |(/_ v1.0.0 /// / / using System; using System.Collections.Generic; using Twilio.Base; using Twilio.Converters; namespace Twilio.Rest.Preview.Sync.Service.SyncMap { /// <summary> /// PLEASE NOTE that this class contains preview products that are subject to change. Use them with caution. If you /// currently do not have developer preview access, please contact help@twilio.com. /// /// FetchSyncMapItemOptions /// </summary> public class FetchSyncMapItemOptions : IOptions<SyncMapItemResource> { /// <summary> /// The service_sid /// </summary> public string PathServiceSid { get; } /// <summary> /// The map_sid /// </summary> public string PathMapSid { get; } /// <summary> /// The key /// </summary> public string PathKey { get; } /// <summary> /// Construct a new FetchSyncMapItemOptions /// </summary> /// <param name="pathServiceSid"> The service_sid </param> /// <param name="pathMapSid"> The map_sid </param> /// <param name="pathKey"> The key </param> public FetchSyncMapItemOptions(string pathServiceSid, string pathMapSid, string pathKey) { PathServiceSid = pathServiceSid; PathMapSid = pathMapSid; PathKey = pathKey; } /// <summary> /// Generate the necessary parameters /// </summary> public List<KeyValuePair<string, string>> GetParams() { var p = new List<KeyValuePair<string, string>>(); return p; } } /// <summary> /// PLEASE NOTE that this class contains preview products that are subject to change. Use them with caution. If you /// currently do not have developer preview access, please contact help@twilio.com. /// /// DeleteSyncMapItemOptions /// </summary> public class DeleteSyncMapItemOptions : IOptions<SyncMapItemResource> { /// <summary> /// The service_sid /// </summary> public string PathServiceSid { get; } /// <summary> /// The map_sid /// </summary> public string PathMapSid { get; } /// <summary> /// The key /// </summary> public string PathKey { get; } /// <summary> /// The If-Match HTTP request header /// </summary> public string IfMatch { get; set; } /// <summary> /// Construct a new DeleteSyncMapItemOptions /// </summary> /// <param name="pathServiceSid"> The service_sid </param> /// <param name="pathMapSid"> The map_sid </param> /// <param name="pathKey"> The key </param> public DeleteSyncMapItemOptions(string pathServiceSid, string pathMapSid, string pathKey) { PathServiceSid = pathServiceSid; PathMapSid = pathMapSid; PathKey = pathKey; } /// <summary> /// Generate the necessary parameters /// </summary> public List<KeyValuePair<string, string>> GetParams() { var p = new List<KeyValuePair<string, string>>(); return p; } /// <summary> /// Generate the necessary header parameters /// </summary> public List<KeyValuePair<string, string>> GetHeaderParams() { var p = new List<KeyValuePair<string, string>>(); if (IfMatch != null) { p.Add(new KeyValuePair<string, string>("If-Match", IfMatch)); } return p; } } /// <summary> /// PLEASE NOTE that this class contains preview products that are subject to change. Use them with caution. If you /// currently do not have developer preview access, please contact help@twilio.com. /// /// CreateSyncMapItemOptions /// </summary> public class CreateSyncMapItemOptions : IOptions<SyncMapItemResource> { /// <summary> /// The service_sid /// </summary> public string PathServiceSid { get; } /// <summary> /// The map_sid /// </summary> public string PathMapSid { get; } /// <summary> /// The key /// </summary> public string Key { get; } /// <summary> /// The data /// </summary> public object Data { get; } /// <summary> /// Construct a new CreateSyncMapItemOptions /// </summary> /// <param name="pathServiceSid"> The service_sid </param> /// <param name="pathMapSid"> The map_sid </param> /// <param name="key"> The key </param> /// <param name="data"> The data </param> public CreateSyncMapItemOptions(string pathServiceSid, string pathMapSid, string key, object data) { PathServiceSid = pathServiceSid; PathMapSid = pathMapSid; Key = key; Data = data; } /// <summary> /// Generate the necessary parameters /// </summary> public List<KeyValuePair<string, string>> GetParams() { var p = new List<KeyValuePair<string, string>>(); if (Key != null) { p.Add(new KeyValuePair<string, string>("Key", Key)); } if (Data != null) { p.Add(new KeyValuePair<string, string>("Data", Serializers.JsonObject(Data))); } return p; } } /// <summary> /// PLEASE NOTE that this class contains preview products that are subject to change. Use them with caution. If you /// currently do not have developer preview access, please contact help@twilio.com. /// /// ReadSyncMapItemOptions /// </summary> public class ReadSyncMapItemOptions : ReadOptions<SyncMapItemResource> { /// <summary> /// The service_sid /// </summary> public string PathServiceSid { get; } /// <summary> /// The map_sid /// </summary> public string PathMapSid { get; } /// <summary> /// The order /// </summary> public SyncMapItemResource.QueryResultOrderEnum Order { get; set; } /// <summary> /// The from /// </summary> public string From { get; set; } /// <summary> /// The bounds /// </summary> public SyncMapItemResource.QueryFromBoundTypeEnum Bounds { get; set; } /// <summary> /// Construct a new ReadSyncMapItemOptions /// </summary> /// <param name="pathServiceSid"> The service_sid </param> /// <param name="pathMapSid"> The map_sid </param> public ReadSyncMapItemOptions(string pathServiceSid, string pathMapSid) { PathServiceSid = pathServiceSid; PathMapSid = pathMapSid; } /// <summary> /// Generate the necessary parameters /// </summary> public override List<KeyValuePair<string, string>> GetParams() { var p = new List<KeyValuePair<string, string>>(); if (Order != null) { p.Add(new KeyValuePair<string, string>("Order", Order.ToString())); } if (From != null) { p.Add(new KeyValuePair<string, string>("From", From)); } if (Bounds != null) { p.Add(new KeyValuePair<string, string>("Bounds", Bounds.ToString())); } if (PageSize != null) { p.Add(new KeyValuePair<string, string>("PageSize", PageSize.ToString())); } return p; } } /// <summary> /// PLEASE NOTE that this class contains preview products that are subject to change. Use them with caution. If you /// currently do not have developer preview access, please contact help@twilio.com. /// /// UpdateSyncMapItemOptions /// </summary> public class UpdateSyncMapItemOptions : IOptions<SyncMapItemResource> { /// <summary> /// The service_sid /// </summary> public string PathServiceSid { get; } /// <summary> /// The map_sid /// </summary> public string PathMapSid { get; } /// <summary> /// The key /// </summary> public string PathKey { get; } /// <summary> /// The data /// </summary> public object Data { get; } /// <summary> /// The If-Match HTTP request header /// </summary> public string IfMatch { get; set; } /// <summary> /// Construct a new UpdateSyncMapItemOptions /// </summary> /// <param name="pathServiceSid"> The service_sid </param> /// <param name="pathMapSid"> The map_sid </param> /// <param name="pathKey"> The key </param> /// <param name="data"> The data </param> public UpdateSyncMapItemOptions(string pathServiceSid, string pathMapSid, string pathKey, object data) { PathServiceSid = pathServiceSid; PathMapSid = pathMapSid; PathKey = pathKey; Data = data; } /// <summary> /// Generate the necessary parameters /// </summary> public List<KeyValuePair<string, string>> GetParams() { var p = new List<KeyValuePair<string, string>>(); if (Data != null) { p.Add(new KeyValuePair<string, string>("Data", Serializers.JsonObject(Data))); } return p; } /// <summary> /// Generate the necessary header parameters /// </summary> public List<KeyValuePair<string, string>> GetHeaderParams() { var p = new List<KeyValuePair<string, string>>(); if (IfMatch != null) { p.Add(new KeyValuePair<string, string>("If-Match", IfMatch)); } return p; } } }
using System.Globalization; using System.Net; using System.Reactive; using System.Reactive.Disposables; using System.Reactive.Linq; using System.Text.RegularExpressions; using Autofac; using AutoMapper; using Miningcore.Banning; using Miningcore.Blockchain; using Miningcore.Configuration; using Miningcore.Extensions; using Miningcore.Messaging; using Miningcore.Nicehash; using Miningcore.Nicehash.API; using Miningcore.Notifications.Messages; using Miningcore.Persistence; using Miningcore.Persistence.Repositories; using Miningcore.Stratum; using Miningcore.Time; using Miningcore.Util; using Miningcore.VarDiff; using Newtonsoft.Json; using NLog; using Contract = Miningcore.Contracts.Contract; // ReSharper disable InconsistentlySynchronizedField namespace Miningcore.Mining; public abstract class PoolBase : StratumServer, IMiningPool { protected PoolBase(IComponentContext ctx, JsonSerializerSettings serializerSettings, IConnectionFactory cf, IStatsRepository statsRepo, IMapper mapper, IMasterClock clock, IMessageBus messageBus, NicehashService nicehashService) : base(ctx, messageBus, clock) { Contract.RequiresNonNull(ctx, nameof(ctx)); Contract.RequiresNonNull(serializerSettings, nameof(serializerSettings)); Contract.RequiresNonNull(cf, nameof(cf)); Contract.RequiresNonNull(statsRepo, nameof(statsRepo)); Contract.RequiresNonNull(mapper, nameof(mapper)); Contract.RequiresNonNull(clock, nameof(clock)); Contract.RequiresNonNull(messageBus, nameof(messageBus)); Contract.RequiresNonNull(nicehashService, nameof(nicehashService)); this.serializerSettings = serializerSettings; this.cf = cf; this.statsRepo = statsRepo; this.mapper = mapper; this.nicehashService = nicehashService; } protected PoolStats poolStats = new(); protected readonly JsonSerializerSettings serializerSettings; protected readonly IConnectionFactory cf; protected readonly IStatsRepository statsRepo; protected readonly IMapper mapper; protected readonly NicehashService nicehashService; protected readonly CompositeDisposable disposables = new(); protected BlockchainStats blockchainStats; protected static readonly TimeSpan maxShareAge = TimeSpan.FromSeconds(6); protected static readonly TimeSpan loginFailureBanTimeout = TimeSpan.FromSeconds(10); protected static readonly Regex regexStaticDiff = new(@";?d=(\d*(\.\d+)?)", RegexOptions.Compiled); protected const string PasswordControlVarsSeparator = ";"; protected readonly Dictionary<PoolEndpoint, VarDiffManager> varDiffManagers = new(); protected abstract Task SetupJobManager(CancellationToken ct); protected abstract WorkerContextBase CreateWorkerContext(); protected double? GetStaticDiffFromPassparts(string[] parts) { if(parts == null || parts.Length == 0) return null; foreach(var part in parts) { var m = regexStaticDiff.Match(part); if(m.Success) { var str = m.Groups[1].Value.Trim(); if(double.TryParse(str, NumberStyles.Float, CultureInfo.InvariantCulture, out var diff) && !double.IsNaN(diff) && !double.IsInfinity(diff)) return diff; } } return null; } protected override void OnConnect(StratumConnection connection, IPEndPoint ipEndPoint) { var context = CreateWorkerContext(); var poolEndpoint = poolConfig.Ports[ipEndPoint.Port]; context.Init(poolConfig, poolEndpoint.Difficulty, poolConfig.EnableInternalStratum == true ? poolEndpoint.VarDiff : null, clock); connection.SetContext(context); // varDiff setup if(context.VarDiff != null) { lock(context.VarDiff) { StartVarDiffIdleUpdate(connection, poolEndpoint); } } // expect miner to establish communication within a certain time EnsureNoZombieClient(connection); } private void EnsureNoZombieClient(StratumConnection connection) { Observable.Timer(clock.Now.AddSeconds(10)) .TakeUntil(connection.Terminated) .Where(_ => connection.IsAlive) .Subscribe(_ => { try { if(connection.LastReceive == null) { logger.Info(() => $"[{connection.ConnectionId}] Booting zombie-worker (post-connect silence)"); CloseConnection(connection); } } catch(Exception ex) { logger.Error(ex); } }, ex => { logger.Error(ex, nameof(EnsureNoZombieClient)); }); } #region VarDiff protected async Task UpdateVarDiffAsync(StratumConnection connection, bool isIdleUpdate = false) { var context = connection.ContextAs<WorkerContextBase>(); if(context.VarDiff != null) { logger.Debug(() => $"[{connection.ConnectionId}] Updating VarDiff" + (isIdleUpdate ? " [idle]" : string.Empty)); // get or create manager VarDiffManager varDiffManager; var poolEndpoint = poolConfig.Ports[connection.LocalEndpoint.Port]; lock(varDiffManagers) { if(!varDiffManagers.TryGetValue(poolEndpoint, out varDiffManager)) { varDiffManager = new VarDiffManager(poolEndpoint.VarDiff, clock); varDiffManagers[poolEndpoint] = varDiffManager; } } double? newDiff = null; lock(context.VarDiff) { StartVarDiffIdleUpdate(connection, poolEndpoint); // update it newDiff = varDiffManager.Update(context.VarDiff, context.Difficulty, isIdleUpdate); } if(newDiff != null) { logger.Info(() => $"[{connection.ConnectionId}] VarDiff update to {Math.Round(newDiff.Value, 3)}"); await OnVarDiffUpdateAsync(connection, newDiff.Value); } } } /// <summary> /// Wire interval based vardiff updates for client /// WARNING: Assumes to be invoked with lock held on context.VarDiff /// </summary> private void StartVarDiffIdleUpdate(StratumConnection connection, PoolEndpoint poolEndpoint) { // Check Every Target Time as we adjust the diff to meet target // Diff may not be changed, only be changed when avg is out of the range. // Diff must be dropped once changed. Will not affect reject rate. var shareReceived = messageBus.Listen<StratumShare>() .Where(x => x.Share.PoolId == poolConfig.Id && x.Connection == connection) .Select(_ => Unit.Default) .Take(1); var timeout = poolEndpoint.VarDiff.TargetTime; Observable.Timer(TimeSpan.FromSeconds(timeout)) .TakeUntil(Observable.Merge(shareReceived, connection.Terminated)) .Where(_ => connection.IsAlive) .Select(x => Observable.FromAsync(() => UpdateVarDiffAsync(connection, true))) .Concat() .Subscribe(_ => { }, ex => { logger.Debug(ex, nameof(StartVarDiffIdleUpdate)); }); } protected virtual Task OnVarDiffUpdateAsync(StratumConnection connection, double newDiff) { var context = connection.ContextAs<WorkerContextBase>(); context.EnqueueNewDifficulty(newDiff); return Task.FromResult(true); } #endregion // VarDiff protected bool CloseIfDead(StratumConnection connection, WorkerContextBase context) { var lastActivityAgo = clock.Now - context.LastActivity; if(poolConfig.ClientConnectionTimeout > 0 && lastActivityAgo.TotalSeconds > poolConfig.ClientConnectionTimeout) { logger.Info(() => $"[[{connection.ConnectionId}] Booting zombie-worker (idle-timeout exceeded)"); CloseConnection(connection); return true; } return false; } protected void SetupBanning(ClusterConfig clusterConfig) { if(poolConfig.Banning?.Enabled == true) { var managerType = clusterConfig.Banning?.Manager ?? BanManagerKind.Integrated; banManager = ctx.ResolveKeyed<IBanManager>(managerType); } } protected virtual async Task InitStatsAsync() { if(clusterConfig.ShareRelay == null) await LoadStatsAsync(); } private async Task LoadStatsAsync() { try { logger.Debug(() => "Loading pool stats"); var stats = await cf.Run(con => statsRepo.GetLastPoolStatsAsync(con, poolConfig.Id)); if(stats != null) { poolStats = mapper.Map<PoolStats>(stats); blockchainStats = mapper.Map<BlockchainStats>(stats); } } catch(Exception ex) { logger.Warn(ex, () => "Unable to load pool stats"); } } protected void ConsiderBan(StratumConnection connection, WorkerContextBase context, PoolShareBasedBanningConfig config) { var totalShares = context.Stats.ValidShares + context.Stats.InvalidShares; if(totalShares > config.CheckThreshold) { var ratioBad = (double) context.Stats.InvalidShares / totalShares; if(ratioBad < config.InvalidPercent / 100.0) { // reset stats context.Stats.ValidShares = 0; context.Stats.InvalidShares = 0; } else { if(poolConfig.Banning?.Enabled == true && (clusterConfig.Banning?.BanOnInvalidShares.HasValue == false || clusterConfig.Banning?.BanOnInvalidShares == true)) { logger.Info(() => $"[{connection.ConnectionId}] Banning worker for {config.Time} sec: {Math.Floor(ratioBad * 100)}% of the last {totalShares} shares were invalid"); banManager.Ban(connection.RemoteEndpoint.Address, TimeSpan.FromSeconds(config.Time)); CloseConnection(connection); } } } } protected virtual async Task<double?> GetNicehashStaticMinDiff(StratumConnection connection, string userAgent, string coinName, string algoName) { if(userAgent.Contains(NicehashConstants.NicehashUA, StringComparison.OrdinalIgnoreCase) && clusterConfig.Nicehash?.EnableAutoDiff == true) { return await nicehashService.GetStaticDiff(coinName, algoName, CancellationToken.None); } return null; } private StratumEndpoint PoolEndpoint2IPEndpoint(int port, PoolEndpoint pep) { var listenAddress = IPAddress.Parse("127.0.0.1"); if(!string.IsNullOrEmpty(pep.ListenAddress)) listenAddress = pep.ListenAddress != "*" ? IPAddress.Parse(pep.ListenAddress) : IPAddress.Any; return new StratumEndpoint(new IPEndPoint(listenAddress, port), pep); } private void OutputPoolInfo() { var msg = $@" Mining Pool: {poolConfig.Id} Coin Type: {poolConfig.Template.Symbol} [{poolConfig.Template.Symbol}] Network Connected: {blockchainStats.NetworkType} Detected Reward Type: {blockchainStats.RewardType} Current Block Height: {blockchainStats.BlockHeight} Current Connect Peers: {blockchainStats.ConnectedPeers} Network Difficulty: {blockchainStats.NetworkDifficulty} Network Hash Rate: {FormatUtil.FormatHashrate(blockchainStats.NetworkHashrate)} Stratum Port(s): {(poolConfig.Ports?.Any() == true ? string.Join(", ", poolConfig.Ports.Keys) : string.Empty)} Pool Fee: {(poolConfig.RewardRecipients?.Any() == true ? poolConfig.RewardRecipients.Where(x => x.Type != "dev").Sum(x => x.Percentage) : 0)}% "; logger.Info(() => msg); } #region API-Surface public PoolConfig Config => poolConfig; public PoolStats PoolStats => poolStats; public BlockchainStats NetworkStats => blockchainStats; public virtual void Configure(PoolConfig poolConfig, ClusterConfig clusterConfig) { Contract.RequiresNonNull(poolConfig, nameof(poolConfig)); Contract.RequiresNonNull(clusterConfig, nameof(clusterConfig)); logger = LogUtil.GetPoolScopedLogger(typeof(PoolBase), poolConfig); this.poolConfig = poolConfig; this.clusterConfig = clusterConfig; } public abstract double HashrateFromShares(double shares, double interval); public abstract double ShareMultiplier { get; } public virtual async Task RunAsync(CancellationToken ct) { Contract.RequiresNonNull(poolConfig, nameof(poolConfig)); logger.Info(() => "Starting Pool ..."); try { SetupBanning(clusterConfig); await SetupJobManager(ct); await InitStatsAsync(); logger.Info(() => "Pool Online"); OutputPoolInfo(); messageBus.NotifyPoolStatus(this, PoolStatus.Online); if(poolConfig.EnableInternalStratum == true) { var ipEndpoints = poolConfig.Ports.Keys .Select(port => PoolEndpoint2IPEndpoint(port, poolConfig.Ports[port])) .ToArray(); await RunAsync(ct, ipEndpoints); } } catch(PoolStartupAbortException) { // just forward these throw; } catch(TaskCanceledException) { // just forward these throw; } catch(Exception ex) { logger.Error(ex); throw; } } #endregion // API-Surface }
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 openCaseMaster.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) 2004-2021 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen // // 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 Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Text; using NLog.Internal; namespace NLog.Targets { /// <summary> /// Default class for serialization of values to JSON format. /// </summary> public class DefaultJsonSerializer : IJsonConverter { private readonly ObjectReflectionCache _objectReflectionCache; private readonly MruCache<Enum, string> _enumCache = new MruCache<Enum, string>(2000); private const int MaxJsonLength = 512 * 1024; private static readonly IEqualityComparer<object> _referenceEqualsComparer = SingleItemOptimizedHashSet<object>.ReferenceEqualityComparer.Default; private static JsonSerializeOptions DefaultSerializerOptions = new JsonSerializeOptions(); private static JsonSerializeOptions DefaultExceptionSerializerOptions = new JsonSerializeOptions() { SanitizeDictionaryKeys = true }; /// <summary> /// Singleton instance of the serializer. /// </summary> [Obsolete("Instead use LogFactory.ServiceRepository.ResolveInstance(typeof(IJsonConverter)). Marked obsolete on NLog 5.0")] public static DefaultJsonSerializer Instance { get; } = new DefaultJsonSerializer(null); /// <summary> /// Private. Use <see cref="Instance"/> /// </summary> internal DefaultJsonSerializer(IServiceProvider serviceProvider) { _objectReflectionCache = new ObjectReflectionCache(serviceProvider); } /// <summary> /// Returns a serialization of an object into JSON format. /// </summary> /// <param name="value">The object to serialize to JSON.</param> /// <returns>Serialized value.</returns> public string SerializeObject(object value) { return SerializeObject(value, DefaultSerializerOptions); } /// <summary> /// Returns a serialization of an object into JSON format. /// </summary> /// <param name="value">The object to serialize to JSON.</param> /// <param name="options">serialisation options</param> /// <returns>Serialized value.</returns> public string SerializeObject(object value, JsonSerializeOptions options) { if (value is null) { return "null"; } else if (value is string str) { for (int i = 0; i < str.Length; ++i) { if (RequiresJsonEscape(str[i], options)) { StringBuilder sb = new StringBuilder(str.Length + 4); sb.Append('"'); AppendStringEscape(sb, str, options); sb.Append('"'); return sb.ToString(); } } return QuoteValue(str); } else { IConvertible convertibleValue = value as IConvertible; TypeCode objTypeCode = convertibleValue?.GetTypeCode() ?? TypeCode.Object; if (objTypeCode != TypeCode.Object && objTypeCode != TypeCode.Char) { Enum enumValue; if (!options.EnumAsInteger && IsNumericTypeCode(objTypeCode, false) && (enumValue = value as Enum) != null) { return QuoteValue(EnumAsString(enumValue)); } else { string xmlStr = XmlHelper.XmlConvertToString(convertibleValue, objTypeCode); if (SkipQuotes(convertibleValue, objTypeCode)) { return xmlStr; } else { return QuoteValue(xmlStr); } } } else { StringBuilder sb = new StringBuilder(); if (!SerializeObject(value, sb, options)) { return null; } return sb.ToString(); } } } /// <summary> /// Serialization of the object in JSON format to the destination StringBuilder /// </summary> /// <param name="value">The object to serialize to JSON.</param> /// <param name="destination">Write the resulting JSON to this destination.</param> /// <returns>Object serialized successfully (true/false).</returns> public bool SerializeObject(object value, StringBuilder destination) { return SerializeObject(value, destination, DefaultSerializerOptions); } /// <summary> /// Serialization of the object in JSON format to the destination StringBuilder /// </summary> /// <param name="value">The object to serialize to JSON.</param> /// <param name="destination">Write the resulting JSON to this destination.</param> /// <param name="options">serialisation options</param> /// <returns>Object serialized successfully (true/false).</returns> public bool SerializeObject(object value, StringBuilder destination, JsonSerializeOptions options) { return SerializeObject(value, destination, options, default(SingleItemOptimizedHashSet<object>), 0); } /// <summary> /// Serialization of the object in JSON format to the destination StringBuilder /// </summary> /// <param name="value">The object to serialize to JSON.</param> /// <param name="destination">Write the resulting JSON to this destination.</param> /// <param name="options">serialisation options</param> /// <param name="objectsInPath">The objects in path (Avoid cyclic reference loop).</param> /// <param name="depth">The current depth (level) of recursion.</param> /// <returns>Object serialized successfully (true/false).</returns> private bool SerializeObject(object value, StringBuilder destination, JsonSerializeOptions options, SingleItemOptimizedHashSet<object> objectsInPath, int depth) { int originalLength = destination.Length; try { if (SerializeSimpleObjectValue(value, destination, options)) { return true; } return SerializeObjectWithReflection(value, destination, options, ref objectsInPath, depth); } catch { destination.Length = originalLength; return false; } } private bool SerializeObjectWithReflection(object value, StringBuilder destination, JsonSerializeOptions options, ref SingleItemOptimizedHashSet<object> objectsInPath, int depth) { int originalLength = destination.Length; if (originalLength > MaxJsonLength) { return false; } if (objectsInPath.Contains(value)) { return false; } if (value is IDictionary dict) { using (StartCollectionScope(ref objectsInPath, dict)) { SerializeDictionaryObject(dict, destination, options, objectsInPath, depth); return true; } } if (value is IEnumerable enumerable) { if (_objectReflectionCache.TryLookupExpandoObject(value, out var objectPropertyList)) { return SerializeObjectPropertyList(value, ref objectPropertyList, destination, options, ref objectsInPath, depth); } else { using (StartCollectionScope(ref objectsInPath, value)) { SerializeCollectionObject(enumerable, destination, options, objectsInPath, depth); return true; } } } else { var objectPropertyList = _objectReflectionCache.LookupObjectProperties(value); return SerializeObjectPropertyList(value, ref objectPropertyList, destination, options, ref objectsInPath, depth); } } private bool SerializeSimpleObjectValue(object value, StringBuilder destination, JsonSerializeOptions options, bool forceToString = false) { var convertibleValue = value as IConvertible; var objTypeCode = convertibleValue?.GetTypeCode() ?? (value is null ? TypeCode.Empty : TypeCode.Object); if (objTypeCode != TypeCode.Object) { SerializeSimpleTypeCodeValue(convertibleValue, objTypeCode, destination, options, forceToString); return true; } if (value is DateTimeOffset dateTimeOffset) { QuoteValue(destination, dateTimeOffset.ToString("yyyy-MM-dd HH:mm:ss zzz", CultureInfo.InvariantCulture)); return true; } if (value is IFormattable formattable) { SerializeWithFormatProvider(formattable, destination, options); return true; } return false; // Not simple } private static SingleItemOptimizedHashSet<object>.SingleItemScopedInsert StartCollectionScope(ref SingleItemOptimizedHashSet<object> objectsInPath, object value) { return new SingleItemOptimizedHashSet<object>.SingleItemScopedInsert(value, ref objectsInPath, true, _referenceEqualsComparer); } private void SerializeWithFormatProvider(IFormattable formattable, StringBuilder destination, JsonSerializeOptions options) { var str = formattable.ToString(null, CultureInfo.InvariantCulture); destination.Append('"'); AppendStringEscape(destination, str, options); destination.Append('"'); } private void SerializeDictionaryObject(IDictionary dictionary, StringBuilder destination, JsonSerializeOptions options, SingleItemOptimizedHashSet<object> objectsInPath, int depth) { bool first = true; int nextDepth = objectsInPath.Count <= 1 ? depth : (depth + 1); if (nextDepth > options.MaxRecursionLimit) { destination.Append("{}"); return; } destination.Append('{'); foreach (var item in new DictionaryEntryEnumerable(dictionary)) { var originalLength = destination.Length; if (originalLength > MaxJsonLength) { break; } if (!first) { destination.Append(','); } var itemKey = item.Key; if (!SerializeObjectAsString(itemKey, destination, options)) { destination.Length = originalLength; continue; } if (options.SanitizeDictionaryKeys) { int keyEndIndex = destination.Length - 1; int keyStartIndex = originalLength + (first ? 0 : 1) + 1; if (!SanitizeDictionaryKey(destination, keyStartIndex, keyEndIndex - keyStartIndex)) { destination.Length = originalLength; // Empty keys are not allowed continue; } } destination.Append(':'); //only serialize, if key and value are serialized without error (e.g. due to reference loop) var itemValue = item.Value; if (!SerializeObject(itemValue, destination, options, objectsInPath, nextDepth)) { destination.Length = originalLength; } else { first = false; } } destination.Append('}'); } private static bool SanitizeDictionaryKey(StringBuilder destination, int keyStartIndex, int keyLength) { if (keyLength == 0) { return false; // Empty keys are not allowed } int keyEndIndex = keyStartIndex + keyLength; for (int i = keyStartIndex; i < keyEndIndex; ++i) { char keyChar = destination[i]; if (keyChar == '_' || char.IsLetterOrDigit(keyChar)) continue; destination[i] = '_'; } return true; } private void SerializeCollectionObject(IEnumerable value, StringBuilder destination, JsonSerializeOptions options, SingleItemOptimizedHashSet<object> objectsInPath, int depth) { bool first = true; int nextDepth = objectsInPath.Count <= 1 ? depth : (depth + 1); // Allow serialization of list-items if (nextDepth > options.MaxRecursionLimit) { destination.Append("[]"); return; } int originalLength; destination.Append('['); foreach (var val in value) { originalLength = destination.Length; if (originalLength > MaxJsonLength) { break; } if (!first) { destination.Append(','); } if (!SerializeObject(val, destination, options, objectsInPath, nextDepth)) { destination.Length = originalLength; } else { first = false; } } destination.Append(']'); } private bool SerializeObjectPropertyList(object value, ref ObjectReflectionCache.ObjectPropertyList objectPropertyList, StringBuilder destination, JsonSerializeOptions options, ref SingleItemOptimizedHashSet<object> objectsInPath, int depth) { if (objectPropertyList.IsSimpleValue) { value = objectPropertyList.ObjectValue; if (SerializeSimpleObjectValue(value, destination, options)) { return true; } } else if (depth < options.MaxRecursionLimit) { if (ReferenceEquals(options, DefaultSerializerOptions) && value is Exception) { // Exceptions are seldom under control, and can include random Data-Dictionary-keys, so we sanitize by default options = DefaultExceptionSerializerOptions; } using (new SingleItemOptimizedHashSet<object>.SingleItemScopedInsert(value, ref objectsInPath, false, _referenceEqualsComparer)) { return SerializeObjectProperties(objectPropertyList, destination, options, objectsInPath, depth); } } return SerializeObjectAsString(value, destination, options); } private void SerializeSimpleTypeCodeValue(IConvertible value, TypeCode objTypeCode, StringBuilder destination, JsonSerializeOptions options, bool forceToString = false) { if (objTypeCode == TypeCode.Empty || value is null) { destination.Append(forceToString ? "\"\"" : "null"); } else if (objTypeCode == TypeCode.String || objTypeCode == TypeCode.Char) { destination.Append('"'); AppendStringEscape(destination, value.ToString(), options); destination.Append('"'); } else { SerializeSimpleTypeCodeValueNoEscape(value, objTypeCode, destination, options, forceToString); } } private void SerializeSimpleTypeCodeValueNoEscape(IConvertible value, TypeCode objTypeCode, StringBuilder destination, JsonSerializeOptions options, bool forceToString) { if (IsNumericTypeCode(objTypeCode, false)) { if (!options.EnumAsInteger && value is Enum enumValue) { QuoteValue(destination, EnumAsString(enumValue)); } else { SerializeNumericValue(value, objTypeCode, destination, forceToString); } } else if (objTypeCode == TypeCode.DateTime) { destination.Append('"'); destination.AppendXmlDateTimeRoundTrip(value.ToDateTime(CultureInfo.InvariantCulture)); destination.Append('"'); } else if (IsNumericTypeCode(objTypeCode, true) && SkipQuotes(value, objTypeCode)) { SerializeNumericValue(value, objTypeCode, destination, forceToString); } else { string str = XmlHelper.XmlConvertToString(value, objTypeCode); if (!forceToString && !string.IsNullOrEmpty(str) && SkipQuotes(value, objTypeCode)) { destination.Append(str); } else { QuoteValue(destination, str); } } } private void SerializeNumericValue(IConvertible value, TypeCode objTypeCode, StringBuilder destination, bool forceToString) { if (forceToString) destination.Append('"'); destination.AppendNumericInvariant(value, objTypeCode); if (forceToString) destination.Append('"'); } private static string QuoteValue(string value) { return string.Concat("\"", value, "\""); } private static void QuoteValue(StringBuilder destination, string value) { destination.Append('"'); destination.Append(value); destination.Append('"'); } private string EnumAsString(Enum value) { string textValue; if (!_enumCache.TryGetValue(value, out textValue)) { textValue = Convert.ToString(value, CultureInfo.InvariantCulture); _enumCache.TryAddValue(value, textValue); } return textValue; } /// <summary> /// No quotes needed for this type? /// </summary> private static bool SkipQuotes(IConvertible value, TypeCode objTypeCode) { switch (objTypeCode) { case TypeCode.String: return false; case TypeCode.Char: return false; case TypeCode.DateTime: return false; case TypeCode.Empty: return true; case TypeCode.Boolean: return true; case TypeCode.Decimal: return true; case TypeCode.Double: { double dblValue = value.ToDouble(CultureInfo.InvariantCulture); return !double.IsNaN(dblValue) && !double.IsInfinity(dblValue); } case TypeCode.Single: { float floatValue = value.ToSingle(CultureInfo.InvariantCulture); return !float.IsNaN(floatValue) && !float.IsInfinity(floatValue); } default: return IsNumericTypeCode(objTypeCode, false); } } /// <summary> /// Checks the object <see cref="TypeCode" /> if it is numeric /// </summary> /// <param name="objTypeCode">TypeCode for the object</param> /// <param name="includeDecimals">Accept fractional types as numeric type.</param> /// <returns></returns> private static bool IsNumericTypeCode(TypeCode objTypeCode, bool includeDecimals) { switch (objTypeCode) { case TypeCode.Byte: case TypeCode.SByte: case TypeCode.Int16: case TypeCode.Int32: case TypeCode.Int64: case TypeCode.UInt16: case TypeCode.UInt32: case TypeCode.UInt64: return true; case TypeCode.Single: case TypeCode.Double: case TypeCode.Decimal: return includeDecimals; } return false; } /// <summary> /// Checks input string if it needs JSON escaping, and makes necessary conversion /// </summary> /// <param name="destination">Destination Builder</param> /// <param name="text">Input string</param> /// <param name="options">all options</param> /// <returns>JSON escaped string</returns> private static void AppendStringEscape(StringBuilder destination, string text, JsonSerializeOptions options) { AppendStringEscape(destination, text, options.EscapeUnicode, options.EscapeForwardSlash); } /// <summary> /// Checks input string if it needs JSON escaping, and makes necessary conversion /// </summary> /// <param name="destination">Destination Builder</param> /// <param name="text">Input string</param> /// <param name="escapeUnicode">Should non-ascii characters be encoded</param> /// <param name="escapeForwardSlash"></param> /// <returns>JSON escaped string</returns> internal static void AppendStringEscape(StringBuilder destination, string text, bool escapeUnicode, bool escapeForwardSlash) { if (string.IsNullOrEmpty(text)) return; StringBuilder sb = null; for (int i = 0; i < text.Length; ++i) { char ch = text[i]; if (!RequiresJsonEscape(ch, escapeUnicode, escapeForwardSlash)) { sb?.Append(ch); continue; } else if (sb is null) { sb = destination; sb.Append(text, 0, i); } switch (ch) { case '"': sb.Append("\\\""); break; case '\\': sb.Append("\\\\"); break; case '\b': sb.Append("\\b"); break; case '/': if (escapeForwardSlash) { sb.Append("\\/"); } else { sb.Append(ch); } break; case '\r': sb.Append("\\r"); break; case '\n': sb.Append("\\n"); break; case '\f': sb.Append("\\f"); break; case '\t': sb.Append("\\t"); break; default: if (EscapeChar(ch, escapeUnicode)) { sb.AppendFormat(CultureInfo.InvariantCulture, "\\u{0:x4}", (int)ch); } else { sb.Append(ch); } break; } } if (sb is null) destination.Append(text); // Faster to make single Append } internal static void PerformJsonEscapeWhenNeeded(StringBuilder builder, int startPos, bool escapeUnicode, bool escapeForwardSlash) { for (int i = startPos; i < builder.Length; ++i) { if (RequiresJsonEscape(builder[i], escapeUnicode, escapeForwardSlash)) { var str = builder.ToString(startPos, builder.Length - startPos); builder.Length = startPos; Targets.DefaultJsonSerializer.AppendStringEscape(builder, str, escapeUnicode, escapeForwardSlash); break; } } } internal static bool RequiresJsonEscape(char ch, JsonSerializeOptions options) { return RequiresJsonEscape(ch, options.EscapeUnicode, options.EscapeForwardSlash); } internal static bool RequiresJsonEscape(char ch, bool escapeUnicode, bool escapeForwardSlash) { if (!EscapeChar(ch, escapeUnicode)) { switch (ch) { case '/': return escapeForwardSlash; case '"': case '\\': return true; default: return false; } } return true; } private static bool EscapeChar(char ch, bool escapeUnicode) { if (ch < 32) return true; else return escapeUnicode && ch > 127; } private bool SerializeObjectProperties(ObjectReflectionCache.ObjectPropertyList objectPropertyList, StringBuilder destination, JsonSerializeOptions options, SingleItemOptimizedHashSet<object> objectsInPath, int depth) { destination.Append('{'); bool first = true; foreach (var propertyValue in objectPropertyList) { var originalLength = destination.Length; try { if (!propertyValue.HasNameAndValue) continue; if (!first) { destination.Append(", "); } QuoteValue(destination, propertyValue.Name); destination.Append(':'); var objTypeCode = propertyValue.TypeCode; if (objTypeCode != TypeCode.Object) { SerializeSimpleTypeCodeValue((IConvertible)propertyValue.Value, objTypeCode, destination, options); first = false; } else { if (!SerializeObject(propertyValue.Value, destination, options, objectsInPath, depth + 1)) { destination.Length = originalLength; } else { first = false; } } } catch { // skip single property destination.Length = originalLength; } } destination.Append('}'); return true; } private bool SerializeObjectAsString(object value, StringBuilder destination, JsonSerializeOptions options) { var originalLength = destination.Length; try { if (SerializeSimpleObjectValue(value, destination, options, true)) { return true; } var str = Convert.ToString(value, CultureInfo.InvariantCulture); destination.Append('"'); AppendStringEscape(destination, str, options); destination.Append('"'); return true; } catch { // skip bad object destination.Length = originalLength; return false; } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Data.Entity; using System.Data.Entity.Infrastructure; using System.Diagnostics; using System.Linq; using System.Reactive.Disposables; using System.Reactive.Linq; using System.Reactive.Subjects; using System.Runtime.Serialization; using System.Threading; using System.Threading.Tasks; using Microsoft.Its.Domain.Serialization; using Microsoft.Its.Recipes; using Unit = System.Reactive.Unit; using log = Its.Log.Lite.Log; namespace Microsoft.Its.Domain.Sql { /// <summary> /// Updates read models based on events after they have been added to an event store. /// </summary> /// <typeparam name="TDbContext">The type of the database context where read models are to be updated.</typeparam> public class ReadModelCatchup<TDbContext> : IDisposable where TDbContext : DbContext, new() { private readonly List<object> projectors; private readonly CompositeDisposable disposables; private MatchEvent[] matchEvents; /// <summary> /// Provides a method for specifying how <see cref="DbContext" /> instances are created for use by instances of <see cref="ReadModelCatchup{TDbContext}" />. /// </summary> public Func<DbContext> CreateReadModelDbContext = () => new TDbContext(); /// <summary> /// Provides a method for specifying how the EventStoreDbContext instances are created for use by instance of <see cref="ReadModelCatchup{TBdContext}" /> /// </summary> public Func<EventStoreDbContext> CreateEventStoreDbContext = () => new EventStoreDbContext(); internal async Task<EventStoreDbContext> CreateOpenEventStoreDbContext() { var context = CreateEventStoreDbContext(); var dbConnection = ((IObjectContextAdapter) context).ObjectContext.Connection; await dbConnection.OpenAsync(); return context; } private readonly CancellationDisposable cancellationDisposable; private readonly InProcessEventBus bus; private readonly ISubject<ReadModelCatchupStatus> progress = new Subject<ReadModelCatchupStatus>(); private int running; private List<ReadModelInfo> unsubscribedReadModelInfos; private List<ReadModelInfo> subscribedReadModelInfos; private string lockResourceName; /// <summary> /// Initializes the <see cref="ReadModelCatchup{TDbContext}"/> class. /// </summary> static ReadModelCatchup() { ReadModelUpdate.ConfigureUnitOfWork(); } /// <summary> /// Initializes a new instance of the <see cref="ReadModelCatchup{TDbContext}"/> class. /// </summary> /// <param name="projectors">The projectors to be updated as new events are added to the event store.</param> /// <exception cref="System.ArgumentException">You must specify at least one projector.</exception> public ReadModelCatchup(params object[] projectors) { if (!projectors.OrEmpty().Any()) { throw new ArgumentException("You must specify at least one projector."); } this.projectors = new List<object>(projectors); EnsureProjectorNamesAreDistinct(); cancellationDisposable = new CancellationDisposable(); disposables = new CompositeDisposable { cancellationDisposable, Disposable.Create(() => progress.OnCompleted()) }; bus = new InProcessEventBus(new Subject<IEvent>()); disposables.Add(bus.ReportErrorsToDatabase(() => CreateReadModelDbContext())); disposables.Add(bus); Sensors.ReadModelDbContexts.GetOrAdd(typeof (TDbContext).Name, CreateReadModelDbContext); } /// <summary> /// Gets the event bus used to publish events to the subscribed projectors. /// </summary> public IEventBus EventBus { get { return bus; } } /// <summary> /// Gets the event handlers that the catchup is running /// </summary> public IEnumerable<object> EventHandlers { get { return projectors.ToArray(); } } /// <summary> /// Gets or sets the name of the catchup. /// </summary> /// <remarks>Catchups having the same name and updating the same database will not run in parallel. In order to have catchups that run in parallel for the same database, they should be given different names.</remarks> public string Name { get; set; } /// <summary> /// Gets an observable sequence showing the catchup's progress. /// </summary> public IObservable<ReadModelCatchupStatus> Progress { get { return progress; } } /// <summary> /// Specifies the lowest id of the events to be caught up. /// </summary> public long StartAtEventId { get; set; } /// <summary> /// Runs a single catchup operation, which will catch up the subscribed projectors through the latest recorded event. /// </summary> /// <remarks>This method will return immediately without performing any updates if another catchup is currently in progress for the same read model database.</remarks> public async Task<ReadModelCatchupResult> Run() { // perform a re-entrancy check so that multiple catchups do not try to run concurrently if (Interlocked.CompareExchange(ref running, 1, 0) != 0) { Debug.WriteLine(string.Format("Catchup {0}: ReadModelCatchup already in progress. Skipping.", Name), ToString()); return ReadModelCatchupResult.CatchupAlreadyInProgress; } EnsureInitialized(); long eventsProcessed = 0; var stopwatch = new Stopwatch(); // iterate over the events in order try { using (var query = new ExclusiveEventStoreCatchupQuery( await CreateOpenEventStoreDbContext(), lockResourceName, GetStartingId, matchEvents)) { ReportStatus(new ReadModelCatchupStatus { BatchCount = query.ExpectedNumberOfEvents, NumberOfEventsProcessed = eventsProcessed, CurrentEventId = query.StartAtId, CatchupName = Name }); Debug.WriteLine(new { query }); if (query.ExpectedNumberOfEvents == 0) { return ReadModelCatchupResult.CatchupRanButNoNewEvents; } Debug.WriteLine(string.Format("Catchup {0}: Beginning replay of {1} events", Name, query.ExpectedNumberOfEvents)); stopwatch.Start(); eventsProcessed = await StreamEventsToProjections(query); } } catch (Exception exception) { // TODO: (Run) this should probably throw Debug.WriteLine(string.Format("Catchup {0}: Read model catchup failed after {1}ms at {2} events.\n{3}", Name, stopwatch.ElapsedMilliseconds, eventsProcessed, exception)); } finally { // reset the re-entrancy flag running = 0; Debug.WriteLine(string.Format("Catchup {0}: Catchup batch done.", Name)); } stopwatch.Stop(); if (eventsProcessed > 0) { Debug.WriteLine( "Catchup {0}: {1} events projected in {2}ms ({3}ms/event)", Name, eventsProcessed, stopwatch.ElapsedMilliseconds, (stopwatch.ElapsedMilliseconds/eventsProcessed)); } return ReadModelCatchupResult.CatchupRanAndHandledNewEvents; } private async Task<long> StreamEventsToProjections(ExclusiveEventStoreCatchupQuery query) { long eventsProcessed = 0; foreach (var storedEvent in query.Events) { eventsProcessed++; IncludeReadModelsNeeding(storedEvent); if (cancellationDisposable.IsDisposed) { break; } IEvent @event = null; var now = Clock.Now(); try { // update projectors @event = storedEvent.ToDomainEvent(); if (@event != null) { using (var work = CreateUnitOfWork(@event)) { await bus.PublishAsync(@event); var infos = work.Resource<DbContext>().Set<ReadModelInfo>(); subscribedReadModelInfos.ForEach(i => { var eventsRemaining = query.ExpectedNumberOfEvents - eventsProcessed; infos.Attach(i); i.LastUpdated = now; i.CurrentAsOfEventId = storedEvent.Id; i.LatencyInMilliseconds = (now - @event.Timestamp).TotalMilliseconds; i.BatchRemainingEvents = eventsRemaining; if (eventsProcessed == 1) { i.BatchStartTime = now; i.BatchTotalEvents = query.ExpectedNumberOfEvents; } if (i.InitialCatchupStartTime == null) { i.InitialCatchupStartTime = now; i.InitialCatchupEvents = query.ExpectedNumberOfEvents; } if (eventsRemaining == 0 && i.InitialCatchupEndTime == null) { i.InitialCatchupEndTime = now; } }); work.VoteCommit(); } } else { throw new SerializationException(string.Format( "Deserialization: Event type '{0}.{1}' not found", storedEvent.StreamName, storedEvent.Type)); } } catch (Exception ex) { var error = @event == null ? SerializationError(ex, storedEvent) : new Domain.EventHandlingError(ex, @event: @event); ReadModelUpdate.ReportFailure( error, () => CreateReadModelDbContext()); } var status = new ReadModelCatchupStatus { BatchCount = query.ExpectedNumberOfEvents, NumberOfEventsProcessed = eventsProcessed, CurrentEventId = storedEvent.Id, EventTimestamp = storedEvent.Timestamp, StatusTimeStamp = now, CatchupName = Name }; if (status.IsEndOfBatch) { // reset the re-entrancy flag running = 0; query.Dispose(); } ReportStatus(status); } return eventsProcessed; } private void IncludeReadModelsNeeding(StorableEvent storedEvent) { if (unsubscribedReadModelInfos.Count > 0) { foreach (var readmodelInfo in unsubscribedReadModelInfos.ToArray()) { if (storedEvent.Id >= readmodelInfo.CurrentAsOfEventId + 1) { var handler = projectors.Single(p => ReadModelInfo.NameForProjector(p) == readmodelInfo.Name); disposables.Add(bus.Subscribe(handler)); unsubscribedReadModelInfos.Remove(readmodelInfo); subscribedReadModelInfos.Add(readmodelInfo); } } } } private void ReportStatus(ReadModelCatchupStatus status) { try { progress.OnNext(status); } catch (Exception exception) { Debug.WriteLine(string.Format("Catchup {0}: Exception while reporting status @ {1}: {2}", Name, status, exception)); } } private long GetStartingId() { var readModelInfos = subscribedReadModelInfos.Concat(unsubscribedReadModelInfos).ToArray(); using (var db = CreateReadModelDbContext()) { foreach (var readModelInfo in readModelInfos) { db.Set<ReadModelInfo>().Attach(readModelInfo); } db.ChangeTracker.Entries<ReadModelInfo>().ForEach(e => e.Reload()); } var existingReadModelInfosCount = readModelInfos.Length; long startAtId = 0; if (GetProjectorNames().Count() == existingReadModelInfosCount) { // if all of the read models have been previously updated, we don't have to start at event 0 startAtId = readModelInfos.Min(i => i.CurrentAsOfEventId) + 1; } return Math.Max(startAtId, StartAtEventId); } private static Domain.EventHandlingError SerializationError(Exception ex, StorableEvent e) { var error = new EventHandlingDeserializationError( ex, e.Body, e.AggregateId, e.SequenceNumber, e.Timestamp, e.Actor, e.StreamName, e.Type); error.Metadata.AbsoluteSequenceNumber = e.Id; return error; } private UnitOfWork<ReadModelUpdate> CreateUnitOfWork( IEvent @event) { return new UnitOfWork<ReadModelUpdate>() .AddResource(@event) .EnsureDbContextIsInitialized(() => CreateReadModelDbContext()); } /// <summary> /// Runs a single catchup operation each time the source observable produces a queryable of events. /// </summary> /// <param name="events">The events.</param> public void RunWhen(IObservable<Unit> events) { disposables.Add(events.Subscribe(es => Run().Wait())); } private void EnsureInitialized() { if (subscribedReadModelInfos != null) { return; } // figure out which event types we will need to query matchEvents = projectors.SelectMany(p => p.MatchesEvents()) .Distinct() .Select(m => { if (m.Type == "Scheduled") { return new MatchEvent(m.StreamName, "*"); } return m; }) .ToArray(); Debug.WriteLine(string.Format("Catchup {0}: Subscribing to event types: {1}", Name, matchEvents.Select(m => m.ToString()).ToJson())); using (var db = CreateReadModelDbContext()) { EnsureLockResourceNameIsInitialized(db); var existingReadModelInfoNames = GetProjectorNames(); var existingReadModelInfos = db.Set<ReadModelInfo>() .OrderBy(i => i.Name) .Where(i => existingReadModelInfoNames.Contains(i.Name)) .ToList(); unsubscribedReadModelInfos = new List<ReadModelInfo>(existingReadModelInfos); subscribedReadModelInfos = new List<ReadModelInfo>(); // create ReadModelInfo entries for any projectors that don't already have them foreach (var projector in projectors.Where(p => !unsubscribedReadModelInfos.Select(i => i.Name).Contains(ReadModelInfo.NameForProjector(p)))) { var readModelInfo = new ReadModelInfo { Name = ReadModelInfo.NameForProjector(projector) }; db.Set<ReadModelInfo>().Add(readModelInfo); unsubscribedReadModelInfos.Add(readModelInfo); } db.SaveChanges(); } } private void EnsureLockResourceNameIsInitialized(DbContext db) { if (string.IsNullOrEmpty(lockResourceName)) { lockResourceName = db.Database.Connection.Database + Name.IfNotNullOrEmptyOrWhitespace() .Then(n => ":" + n) .ElseDefault(); } } /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> public void Dispose() { disposables.Dispose(); } private void EnsureProjectorNamesAreDistinct() { var names = GetProjectorNames(); if (names.Distinct().Count() != names.Count()) { throw new ArgumentException("Duplicate read model names:\n" + names.Where(n => names.Count(nn => nn == n) > 1) .Distinct() .ToDelimitedString("\n")); } } private string[] GetProjectorNames() { return projectors .Select(ReadModelInfo.NameForProjector) .OrderBy(name => name) .ToArray(); } } }
//----------------------------------------------------------------------- // <copyright file="GraphBalanceSpec.cs" company="Akka.NET Project"> // Copyright (C) 2015-2016 Lightbend Inc. <http://www.lightbend.com> // Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net> // </copyright> //----------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Akka.Streams.Dsl; using Akka.Streams.TestKit; using Akka.Streams.TestKit.Tests; using FluentAssertions; using Reactive.Streams; using Xunit; // ReSharper disable InvokeAsExtensionMethod namespace Akka.Streams.Tests.Dsl { public class GraphBalanceSpec : AkkaSpec { private ActorMaterializer Materializer { get; } public GraphBalanceSpec() { var settings = ActorMaterializerSettings.Create(Sys).WithInputBuffer(2, 16); Materializer = ActorMaterializer.Create(Sys, settings); } [Fact] public void A_Balance_must_balance_between_subscribers_which_signal_demand() { this.AssertAllStagesStopped(() => { var c1 = TestSubscriber.CreateManualProbe<int>(this); var c2 = TestSubscriber.CreateManualProbe<int>(this); RunnableGraph.FromGraph(GraphDsl.Create(b => { var balance = b.Add(new Balance<int>(2)); var source = Source.From(Enumerable.Range(1, 3)); b.From(source).To(balance.In); b.From(balance.Out(0)).To(Sink.FromSubscriber(c1)); b.From(balance.Out(1)).To(Sink.FromSubscriber(c2)); return ClosedShape.Instance; })).Run(Materializer); var sub1 = c1.ExpectSubscription(); var sub2 = c2.ExpectSubscription(); sub1.Request(1); c1.ExpectNext(1).ExpectNoMsg(TimeSpan.FromMilliseconds(100)); sub2.Request(2); c2.ExpectNext(2, 3); c1.ExpectComplete(); c2.ExpectComplete(); }, Materializer); } [Fact] public void A_Balance_must_support_waiting_for_demand_from_all_downstream_subscriptions() { this.AssertAllStagesStopped(() => { var s1 = TestSubscriber.CreateManualProbe<int>(this); var p2 = RunnableGraph.FromGraph(GraphDsl.Create(Sink.AsPublisher<int>(false), (b, p2Sink) => { var balance = b.Add(new Balance<int>(2, true)); var source = Source.From(Enumerable.Range(1, 3)).MapMaterializedValue<IPublisher<int>>(_ => null); b.From(source).To(balance.In); b.From(balance.Out(0)).To(Sink.FromSubscriber(s1).MapMaterializedValue<IPublisher<int>>(_ => null)); b.From(balance.Out(1)).To(p2Sink); return ClosedShape.Instance; })).Run(Materializer); var sub1 = s1.ExpectSubscription(); sub1.Request(1); s1.ExpectNoMsg(TimeSpan.FromMilliseconds(200)); var s2 = TestSubscriber.CreateManualProbe<int>(this); p2.Subscribe(s2); var sub2 = s2.ExpectSubscription(); // still no demand from s2 s2.ExpectNoMsg(TimeSpan.FromMilliseconds(200)); sub2.Request(2); s1.ExpectNext(1); s2.ExpectNext(2, 3); s1.ExpectComplete(); s2.ExpectComplete(); }, Materializer); } [Fact(Skip = "Racy")] public void A_Balance_must_support_waiting_for_demand_from_all_non_cancelled_downstream_subscriptions() { this.AssertAllStagesStopped(() => { var s1 = TestSubscriber.CreateManualProbe<int>(this); var t = RunnableGraph.FromGraph(GraphDsl.Create(Sink.AsPublisher<int>(false), Sink.AsPublisher<int>(false), Keep.Both, (b, p2Sink, p3Sink) => { var balance = b.Add(new Balance<int>(3, true)); var source = Source.From(Enumerable.Range(1, 3)) .MapMaterializedValue<Tuple<IPublisher<int>, IPublisher<int>>>(_ => null); b.From(source).To(balance.In); b.From(balance.Out(0)) .To( Sink.FromSubscriber(s1) .MapMaterializedValue<Tuple<IPublisher<int>, IPublisher<int>>>(_ => null)); b.From(balance.Out(1)).To(p2Sink); b.From(balance.Out(2)).To(p3Sink); return ClosedShape.Instance; })).Run(Materializer); var p2 = t.Item1; var p3 = t.Item2; var sub1 = s1.ExpectSubscription(); sub1.Request(1); var s2 = TestSubscriber.CreateManualProbe<int>(this); p2.Subscribe(s2); var sub2 = s2.ExpectSubscription(); var s3 = TestSubscriber.CreateManualProbe<int>(this); p3.Subscribe(s3); var sub3 = s3.ExpectSubscription(); sub2.Request(2); s1.ExpectNoMsg(TimeSpan.FromMilliseconds(200)); sub3.Cancel(); s1.ExpectNext(1); s2.ExpectNext(2, 3); s1.ExpectComplete(); s2.ExpectComplete(); }, Materializer); } [Fact] public void A_Balance_must_work_with_1_way_balance() { this.AssertAllStagesStopped(() => { var task = Source.FromGraph(GraphDsl.Create(b => { var balance = b.Add(new Balance<int>(1)); var source = b.Add(Source.From(Enumerable.Range(1, 3))); b.From(source).To(balance.In); return new SourceShape<int>(balance.Out(0)); })).RunAggregate(new List<int>(), (list, i) => { list.Add(i); return list; }, Materializer); task.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue(); task.Result.ShouldAllBeEquivalentTo(new[] {1, 2, 3}); }, Materializer); } [Fact] public void A_Balance_must_work_with_5_way_balance() { this.AssertAllStagesStopped(() => { var sink = Sink.First<IEnumerable<int>>(); var t = RunnableGraph.FromGraph(GraphDsl.Create(sink, sink, sink, sink, sink, Tuple.Create, (b, s1, s2, s3, s4, s5) => { var balance = b.Add(new Balance<int>(5, true)); var source = Source.From(Enumerable.Range(0, 15)).MapMaterializedValue<Tuple<Task<IEnumerable<int>>, Task<IEnumerable<int>>, Task<IEnumerable<int>>, Task<IEnumerable<int>>, Task<IEnumerable<int>>>>(_=> null); b.From(source).To(balance.In); b.From(balance.Out(0)).Via(Flow.Create<int>().Grouped(15)).To(s1); b.From(balance.Out(1)).Via(Flow.Create<int>().Grouped(15)).To(s2); b.From(balance.Out(2)).Via(Flow.Create<int>().Grouped(15)).To(s3); b.From(balance.Out(3)).Via(Flow.Create<int>().Grouped(15)).To(s4); b.From(balance.Out(4)).Via(Flow.Create<int>().Grouped(15)).To(s5); return ClosedShape.Instance; })).Run(Materializer); var task = Task.WhenAll(t.Item1, t.Item2, t.Item3, t.Item4, t.Item5); task.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue(); task.Result.SelectMany(l=>l).ShouldAllBeEquivalentTo(Enumerable.Range(0, 15)); }, Materializer); } [Fact] public void A_Balance_must_balance_between_all_three_outputs() { this.AssertAllStagesStopped(() => { const int numElementsForSink = 10000; var outputs = Sink.Aggregate<int, int>(0, (sum, i) => sum + i); var t = RunnableGraph.FromGraph(GraphDsl.Create(outputs, outputs, outputs, Tuple.Create, (b, o1, o2, o3) => { var balance = b.Add(new Balance<int>(3, true)); var source = Source.Repeat(1) .Take(numElementsForSink*3) .MapMaterializedValue<Tuple<Task<int>, Task<int>, Task<int>>>(_ => null); b.From(source).To(balance.In); b.From(balance.Out(0)).To(o1); b.From(balance.Out(1)).To(o2); b.From(balance.Out(2)).To(o3); return ClosedShape.Instance; })).Run(Materializer); var task = Task.WhenAll(t.Item1, t.Item2, t.Item3); task.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue(); task.Result.Should().NotContain(0); task.Result.Sum().Should().Be(numElementsForSink*3); }, Materializer); } [Fact] public void A_Balance_must_fairly_balance_between_three_outputs() { this.AssertAllStagesStopped(() => { var probe = this.SinkProbe<int>(); var t = RunnableGraph.FromGraph(GraphDsl.Create(probe, probe, probe, Tuple.Create, (b, o1, o2, o3) => { var balance = b.Add(new Balance<int>(3)); var source = Source.From(Enumerable.Range(1,7)) .MapMaterializedValue<Tuple<TestSubscriber.Probe<int>, TestSubscriber.Probe<int>, TestSubscriber.Probe<int>>>(_ => null); b.From(source).To(balance.In); b.From(balance.Out(0)).To(o1); b.From(balance.Out(1)).To(o2); b.From(balance.Out(2)).To(o3); return ClosedShape.Instance; })).Run(Materializer); var p1 = t.Item1; var p2 = t.Item2; var p3 = t.Item3; p1.RequestNext(1); p2.RequestNext(2); p3.RequestNext(3); p2.RequestNext(4); p1.RequestNext(5); p3.RequestNext(6); p1.RequestNext(7); p1.ExpectComplete(); p2.ExpectComplete(); p3.ExpectComplete(); }, Materializer); } [Fact] public void A_Balance_must_produce_to_second_even_though_first_cancels() { this.AssertAllStagesStopped(() => { var c1 = TestSubscriber.CreateManualProbe<int>(this); var c2 = TestSubscriber.CreateManualProbe<int>(this); RunnableGraph.FromGraph(GraphDsl.Create(b => { var balance = b.Add(new Balance<int>(2)); var source = Source.From(Enumerable.Range(1, 3)); b.From(source).To(balance.In); b.From(balance.Out(0)).To(Sink.FromSubscriber(c1)); b.From(balance.Out(1)).To(Sink.FromSubscriber(c2)); return ClosedShape.Instance; })).Run(Materializer); var sub1 = c1.ExpectSubscription(); sub1.Cancel(); var sub2 = c2.ExpectSubscription(); sub2.Request(3); c2.ExpectNext(1, 2, 3); c2.ExpectComplete(); }, Materializer); } [Fact] public void A_Balance_must_produce_to_first_even_though_second_cancels() { this.AssertAllStagesStopped(() => { var c1 = TestSubscriber.CreateManualProbe<int>(this); var c2 = TestSubscriber.CreateManualProbe<int>(this); RunnableGraph.FromGraph(GraphDsl.Create(b => { var balance = b.Add(new Balance<int>(2)); var source = Source.From(Enumerable.Range(1, 3)); b.From(source).To(balance.In); b.From(balance.Out(0)).To(Sink.FromSubscriber(c1)); b.From(balance.Out(1)).To(Sink.FromSubscriber(c2)); return ClosedShape.Instance; })).Run(Materializer); var sub1 = c1.ExpectSubscription(); var sub2 = c2.ExpectSubscription(); sub2.Cancel(); sub1.Request(3); c1.ExpectNext(1, 2, 3); c1.ExpectComplete(); }, Materializer); } [Fact] public void A_Balance_must_cancel_upstream_when_downstream_cancel() { this.AssertAllStagesStopped(() => { var p1 = TestPublisher.CreateManualProbe<int>(this); var c1 = TestSubscriber.CreateManualProbe<int>(this); var c2 = TestSubscriber.CreateManualProbe<int>(this); RunnableGraph.FromGraph(GraphDsl.Create(b => { var balance = b.Add(new Balance<int>(2)); var source = Source.FromPublisher(p1.Publisher); b.From(source).To(balance.In); b.From(balance.Out(0)).To(Sink.FromSubscriber(c1)); b.From(balance.Out(1)).To(Sink.FromSubscriber(c2)); return ClosedShape.Instance; })).Run(Materializer); var bsub = p1.ExpectSubscription(); var sub1 = c1.ExpectSubscription(); var sub2 = c2.ExpectSubscription(); sub1.Request(1); p1.ExpectRequest(bsub, 16); bsub.SendNext(1); c1.ExpectNext(1); sub2.Request(1); bsub.SendNext(2); c2.ExpectNext(2); sub1.Cancel(); sub2.Cancel(); bsub.ExpectCancellation(); }, Materializer); } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Description; using BGB.WebAPI.Areas.HelpPage.ModelDescriptions; using BGB.WebAPI.Areas.HelpPage.Models; namespace BGB.WebAPI.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } // Example: // [TypeConverter(typeof(PointConverter))] // public class Point // { // public Point(int x, int y) // { // X = x; // Y = y; // } // public int X { get; set; } // public int Y { get; set; } // } // Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection. // // public class Point // { // public int X { get; set; } // public int Y { get; set; } // } // Regular complex class Point will have properties X and Y added to UriParameters collection. if (complexTypeDescription != null && !IsBindableWithTypeConverter(parameterType)) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static bool IsBindableWithTypeConverter(Type parameterType) { if (parameterType == null) { return false; } return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string)); } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
// Copyright 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! namespace Google.Cloud.Debugger.V2.Snippets { using Google.Api.Gax; using Google.Api.Gax.Grpc; using apis = Google.Cloud.Debugger.V2; using Google.Protobuf; 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; /// <summary>Generated snippets</summary> public class GeneratedDebugger2ClientSnippets { /// <summary>Snippet for SetBreakpointAsync</summary> public async Task SetBreakpointAsync() { // Snippet: SetBreakpointAsync(string,Breakpoint,string,CallSettings) // Additional: SetBreakpointAsync(string,Breakpoint,string,CancellationToken) // Create client Debugger2Client debugger2Client = await Debugger2Client.CreateAsync(); // Initialize request argument(s) string debuggeeId = ""; Breakpoint breakpoint = new Breakpoint(); string clientVersion = ""; // Make the request SetBreakpointResponse response = await debugger2Client.SetBreakpointAsync(debuggeeId, breakpoint, clientVersion); // End snippet } /// <summary>Snippet for SetBreakpoint</summary> public void SetBreakpoint() { // Snippet: SetBreakpoint(string,Breakpoint,string,CallSettings) // Create client Debugger2Client debugger2Client = Debugger2Client.Create(); // Initialize request argument(s) string debuggeeId = ""; Breakpoint breakpoint = new Breakpoint(); string clientVersion = ""; // Make the request SetBreakpointResponse response = debugger2Client.SetBreakpoint(debuggeeId, breakpoint, clientVersion); // End snippet } /// <summary>Snippet for SetBreakpointAsync</summary> public async Task SetBreakpointAsync_RequestObject() { // Snippet: SetBreakpointAsync(SetBreakpointRequest,CallSettings) // Additional: SetBreakpointAsync(SetBreakpointRequest,CancellationToken) // Create client Debugger2Client debugger2Client = await Debugger2Client.CreateAsync(); // Initialize request argument(s) SetBreakpointRequest request = new SetBreakpointRequest { DebuggeeId = "", Breakpoint = new Breakpoint(), ClientVersion = "", }; // Make the request SetBreakpointResponse response = await debugger2Client.SetBreakpointAsync(request); // End snippet } /// <summary>Snippet for SetBreakpoint</summary> public void SetBreakpoint_RequestObject() { // Snippet: SetBreakpoint(SetBreakpointRequest,CallSettings) // Create client Debugger2Client debugger2Client = Debugger2Client.Create(); // Initialize request argument(s) SetBreakpointRequest request = new SetBreakpointRequest { DebuggeeId = "", Breakpoint = new Breakpoint(), ClientVersion = "", }; // Make the request SetBreakpointResponse response = debugger2Client.SetBreakpoint(request); // End snippet } /// <summary>Snippet for GetBreakpointAsync</summary> public async Task GetBreakpointAsync() { // Snippet: GetBreakpointAsync(string,string,string,CallSettings) // Additional: GetBreakpointAsync(string,string,string,CancellationToken) // Create client Debugger2Client debugger2Client = await Debugger2Client.CreateAsync(); // Initialize request argument(s) string debuggeeId = ""; string breakpointId = ""; string clientVersion = ""; // Make the request GetBreakpointResponse response = await debugger2Client.GetBreakpointAsync(debuggeeId, breakpointId, clientVersion); // End snippet } /// <summary>Snippet for GetBreakpoint</summary> public void GetBreakpoint() { // Snippet: GetBreakpoint(string,string,string,CallSettings) // Create client Debugger2Client debugger2Client = Debugger2Client.Create(); // Initialize request argument(s) string debuggeeId = ""; string breakpointId = ""; string clientVersion = ""; // Make the request GetBreakpointResponse response = debugger2Client.GetBreakpoint(debuggeeId, breakpointId, clientVersion); // End snippet } /// <summary>Snippet for GetBreakpointAsync</summary> public async Task GetBreakpointAsync_RequestObject() { // Snippet: GetBreakpointAsync(GetBreakpointRequest,CallSettings) // Additional: GetBreakpointAsync(GetBreakpointRequest,CancellationToken) // Create client Debugger2Client debugger2Client = await Debugger2Client.CreateAsync(); // Initialize request argument(s) GetBreakpointRequest request = new GetBreakpointRequest { DebuggeeId = "", BreakpointId = "", ClientVersion = "", }; // Make the request GetBreakpointResponse response = await debugger2Client.GetBreakpointAsync(request); // End snippet } /// <summary>Snippet for GetBreakpoint</summary> public void GetBreakpoint_RequestObject() { // Snippet: GetBreakpoint(GetBreakpointRequest,CallSettings) // Create client Debugger2Client debugger2Client = Debugger2Client.Create(); // Initialize request argument(s) GetBreakpointRequest request = new GetBreakpointRequest { DebuggeeId = "", BreakpointId = "", ClientVersion = "", }; // Make the request GetBreakpointResponse response = debugger2Client.GetBreakpoint(request); // End snippet } /// <summary>Snippet for DeleteBreakpointAsync</summary> public async Task DeleteBreakpointAsync() { // Snippet: DeleteBreakpointAsync(string,string,string,CallSettings) // Additional: DeleteBreakpointAsync(string,string,string,CancellationToken) // Create client Debugger2Client debugger2Client = await Debugger2Client.CreateAsync(); // Initialize request argument(s) string debuggeeId = ""; string breakpointId = ""; string clientVersion = ""; // Make the request await debugger2Client.DeleteBreakpointAsync(debuggeeId, breakpointId, clientVersion); // End snippet } /// <summary>Snippet for DeleteBreakpoint</summary> public void DeleteBreakpoint() { // Snippet: DeleteBreakpoint(string,string,string,CallSettings) // Create client Debugger2Client debugger2Client = Debugger2Client.Create(); // Initialize request argument(s) string debuggeeId = ""; string breakpointId = ""; string clientVersion = ""; // Make the request debugger2Client.DeleteBreakpoint(debuggeeId, breakpointId, clientVersion); // End snippet } /// <summary>Snippet for DeleteBreakpointAsync</summary> public async Task DeleteBreakpointAsync_RequestObject() { // Snippet: DeleteBreakpointAsync(DeleteBreakpointRequest,CallSettings) // Additional: DeleteBreakpointAsync(DeleteBreakpointRequest,CancellationToken) // Create client Debugger2Client debugger2Client = await Debugger2Client.CreateAsync(); // Initialize request argument(s) DeleteBreakpointRequest request = new DeleteBreakpointRequest { DebuggeeId = "", BreakpointId = "", ClientVersion = "", }; // Make the request await debugger2Client.DeleteBreakpointAsync(request); // End snippet } /// <summary>Snippet for DeleteBreakpoint</summary> public void DeleteBreakpoint_RequestObject() { // Snippet: DeleteBreakpoint(DeleteBreakpointRequest,CallSettings) // Create client Debugger2Client debugger2Client = Debugger2Client.Create(); // Initialize request argument(s) DeleteBreakpointRequest request = new DeleteBreakpointRequest { DebuggeeId = "", BreakpointId = "", ClientVersion = "", }; // Make the request debugger2Client.DeleteBreakpoint(request); // End snippet } /// <summary>Snippet for ListBreakpointsAsync</summary> public async Task ListBreakpointsAsync() { // Snippet: ListBreakpointsAsync(string,string,CallSettings) // Additional: ListBreakpointsAsync(string,string,CancellationToken) // Create client Debugger2Client debugger2Client = await Debugger2Client.CreateAsync(); // Initialize request argument(s) string debuggeeId = ""; string clientVersion = ""; // Make the request ListBreakpointsResponse response = await debugger2Client.ListBreakpointsAsync(debuggeeId, clientVersion); // End snippet } /// <summary>Snippet for ListBreakpoints</summary> public void ListBreakpoints() { // Snippet: ListBreakpoints(string,string,CallSettings) // Create client Debugger2Client debugger2Client = Debugger2Client.Create(); // Initialize request argument(s) string debuggeeId = ""; string clientVersion = ""; // Make the request ListBreakpointsResponse response = debugger2Client.ListBreakpoints(debuggeeId, clientVersion); // End snippet } /// <summary>Snippet for ListBreakpointsAsync</summary> public async Task ListBreakpointsAsync_RequestObject() { // Snippet: ListBreakpointsAsync(ListBreakpointsRequest,CallSettings) // Additional: ListBreakpointsAsync(ListBreakpointsRequest,CancellationToken) // Create client Debugger2Client debugger2Client = await Debugger2Client.CreateAsync(); // Initialize request argument(s) ListBreakpointsRequest request = new ListBreakpointsRequest { DebuggeeId = "", ClientVersion = "", }; // Make the request ListBreakpointsResponse response = await debugger2Client.ListBreakpointsAsync(request); // End snippet } /// <summary>Snippet for ListBreakpoints</summary> public void ListBreakpoints_RequestObject() { // Snippet: ListBreakpoints(ListBreakpointsRequest,CallSettings) // Create client Debugger2Client debugger2Client = Debugger2Client.Create(); // Initialize request argument(s) ListBreakpointsRequest request = new ListBreakpointsRequest { DebuggeeId = "", ClientVersion = "", }; // Make the request ListBreakpointsResponse response = debugger2Client.ListBreakpoints(request); // End snippet } /// <summary>Snippet for ListDebuggeesAsync</summary> public async Task ListDebuggeesAsync() { // Snippet: ListDebuggeesAsync(string,string,CallSettings) // Additional: ListDebuggeesAsync(string,string,CancellationToken) // Create client Debugger2Client debugger2Client = await Debugger2Client.CreateAsync(); // Initialize request argument(s) string project = ""; string clientVersion = ""; // Make the request ListDebuggeesResponse response = await debugger2Client.ListDebuggeesAsync(project, clientVersion); // End snippet } /// <summary>Snippet for ListDebuggees</summary> public void ListDebuggees() { // Snippet: ListDebuggees(string,string,CallSettings) // Create client Debugger2Client debugger2Client = Debugger2Client.Create(); // Initialize request argument(s) string project = ""; string clientVersion = ""; // Make the request ListDebuggeesResponse response = debugger2Client.ListDebuggees(project, clientVersion); // End snippet } /// <summary>Snippet for ListDebuggeesAsync</summary> public async Task ListDebuggeesAsync_RequestObject() { // Snippet: ListDebuggeesAsync(ListDebuggeesRequest,CallSettings) // Additional: ListDebuggeesAsync(ListDebuggeesRequest,CancellationToken) // Create client Debugger2Client debugger2Client = await Debugger2Client.CreateAsync(); // Initialize request argument(s) ListDebuggeesRequest request = new ListDebuggeesRequest { Project = "", ClientVersion = "", }; // Make the request ListDebuggeesResponse response = await debugger2Client.ListDebuggeesAsync(request); // End snippet } /// <summary>Snippet for ListDebuggees</summary> public void ListDebuggees_RequestObject() { // Snippet: ListDebuggees(ListDebuggeesRequest,CallSettings) // Create client Debugger2Client debugger2Client = Debugger2Client.Create(); // Initialize request argument(s) ListDebuggeesRequest request = new ListDebuggeesRequest { Project = "", ClientVersion = "", }; // Make the request ListDebuggeesResponse response = debugger2Client.ListDebuggees(request); // End snippet } } }
/* * Guid.cs - Implementation of the "System.Guid" class. * * Copyright (C) 2001 Southern Storm Software, Pty Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ namespace System { #if !ECMA_COMPAT using System.Runtime.CompilerServices; using System.Text; public struct Guid : IFormattable, IComparable { // The empty GUID. public static readonly Guid Empty; // Internal state. private int a__; private short b__, c__; private byte d__, e__, f__, g__, h__, i__, j__, k__; // Create a new GUID, initialized to a unique random value. [MethodImpl(MethodImplOptions.InternalCall)] extern public static Guid NewGuid(); // Helper methods for Guid parsing. private static int GetHex(String g, ref int posn, int length, int digits) { int value = 0; char ch; while(digits > 0) { if(posn >= length) { throw new FormatException(_("Format_GuidValue")); } ch = g[posn++]; if(ch >= '0' && ch <= '9') { value = value * 16 + (int)(ch - '0'); } else if(ch >= 'A' && ch <= 'F') { value = value * 16 + (int)(ch - 'A' + 10); } else if(ch >= 'a' && ch <= 'f') { value = value * 16 + (int)(ch - 'a' + 10); } else { throw new FormatException(_("Format_GuidValue")); } --digits; } return value; } private static int GetVarHex(String g, ref int posn, int length, int digits) { int value = 0; char ch; bool sawDigit = false; if((length - posn) <= 2 || g[posn] != '0' || (g[posn + 1] != 'x' && g[posn + 1] != 'X')) { throw new FormatException(_("Format_GuidValue")); } posn += 2; for(;;) { if(posn >= length) { break; } ch = g[posn++]; if(ch >= '0' && ch <= '9') { value = value * 16 + (int)(ch - '0'); } else if(ch >= 'A' && ch <= 'F') { value = value * 16 + (int)(ch - 'A' + 10); } else if(ch >= 'a' && ch <= 'f') { value = value * 16 + (int)(ch - 'a' + 10); } else { --posn; break; } sawDigit = true; --digits; if(digits < 0) { throw new FormatException(_("Format_GuidValue")); } } if(!sawDigit) { throw new FormatException(_("Format_GuidValue")); } return value; } private static void GetChar(String g, ref int posn, int length, char ch) { if(posn >= length || g[posn] != ch) { throw new FormatException(_("Format_GuidValue")); } ++posn; } // Constructors. public Guid(String g) { if(g == null) { throw new ArgumentNullException("g"); } int posn = 0; int length = g.Length; if(g[0] == '{') { ++posn; } if((length - posn) >= 2 && g[posn] == '0' && (g[posn + 1] == 'x' || g[posn + 1] == 'X')) { if(posn == 0) { throw new FormatException(_("Format_GuidValue")); } a__ = (int)GetVarHex(g, ref posn, length, 8); GetChar(g, ref posn, length, ','); b__ = (short)GetVarHex(g, ref posn, length, 4); GetChar(g, ref posn, length, ','); c__ = (short)GetVarHex(g, ref posn, length, 4); GetChar(g, ref posn, length, ','); GetChar(g, ref posn, length, '{'); d__ = (byte)GetVarHex(g, ref posn, length, 2); if(posn < length && g[posn] == '}') { // The byte values must be individually bracketed. GetChar(g, ref posn, length, '}'); GetChar(g, ref posn, length, ','); GetChar(g, ref posn, length, '{'); e__ = (byte)GetVarHex(g, ref posn, length, 2); GetChar(g, ref posn, length, '}'); GetChar(g, ref posn, length, ','); GetChar(g, ref posn, length, '{'); f__ = (byte)GetVarHex(g, ref posn, length, 2); GetChar(g, ref posn, length, '}'); GetChar(g, ref posn, length, ','); GetChar(g, ref posn, length, '{'); g__ = (byte)GetVarHex(g, ref posn, length, 2); GetChar(g, ref posn, length, '}'); GetChar(g, ref posn, length, ','); GetChar(g, ref posn, length, '{'); h__ = (byte)GetVarHex(g, ref posn, length, 2); GetChar(g, ref posn, length, '}'); GetChar(g, ref posn, length, ','); GetChar(g, ref posn, length, '{'); i__ = (byte)GetVarHex(g, ref posn, length, 2); GetChar(g, ref posn, length, '}'); GetChar(g, ref posn, length, ','); GetChar(g, ref posn, length, '{'); j__ = (byte)GetVarHex(g, ref posn, length, 2); GetChar(g, ref posn, length, '}'); GetChar(g, ref posn, length, ','); GetChar(g, ref posn, length, '{'); k__ = (byte)GetVarHex(g, ref posn, length, 2); GetChar(g, ref posn, length, '}'); } else { // The byte values are not individually bracketed. GetChar(g, ref posn, length, ','); e__ = (byte)GetVarHex(g, ref posn, length, 2); GetChar(g, ref posn, length, ','); f__ = (byte)GetVarHex(g, ref posn, length, 2); GetChar(g, ref posn, length, ','); g__ = (byte)GetVarHex(g, ref posn, length, 2); GetChar(g, ref posn, length, ','); h__ = (byte)GetVarHex(g, ref posn, length, 2); GetChar(g, ref posn, length, ','); i__ = (byte)GetVarHex(g, ref posn, length, 2); GetChar(g, ref posn, length, ','); j__ = (byte)GetVarHex(g, ref posn, length, 2); GetChar(g, ref posn, length, ','); k__ = (byte)GetVarHex(g, ref posn, length, 2); GetChar(g, ref posn, length, '}'); } } else { a__ = (int)GetHex(g, ref posn, length, 8); GetChar(g, ref posn, length, '-'); b__ = (short)GetHex(g, ref posn, length, 4); GetChar(g, ref posn, length, '-'); c__ = (short)GetHex(g, ref posn, length, 4); GetChar(g, ref posn, length, '-'); d__ = (byte)GetHex(g, ref posn, length, 2); e__ = (byte)GetHex(g, ref posn, length, 2); GetChar(g, ref posn, length, '-'); f__ = (byte)GetHex(g, ref posn, length, 2); g__ = (byte)GetHex(g, ref posn, length, 2); h__ = (byte)GetHex(g, ref posn, length, 2); i__ = (byte)GetHex(g, ref posn, length, 2); j__ = (byte)GetHex(g, ref posn, length, 2); k__ = (byte)GetHex(g, ref posn, length, 2); } if(g[0] == '{') { if(posn >= length || g[posn] != '}') { throw new FormatException(_("Format_GuidValue")); } ++posn; } if(posn != length) { throw new FormatException(_("Format_GuidValue")); } } public Guid(byte[] b) { if(b == null) { throw new ArgumentNullException("b"); } if(b.Length != 16) { throw new ArgumentException(_("Arg_GuidArray16")); } a__ = ((int)(b[0])) | (((int)(b[1])) << 8) | (((int)(b[2])) << 16) | (((int)(b[3])) << 24); b__ = (short)(((int)(b[4])) | (((int)(b[5])) << 8)); c__ = (short)(((int)(b[6])) | (((int)(b[7])) << 8)); d__ = b[8]; e__ = b[9]; f__ = b[10]; g__ = b[11]; h__ = b[12]; i__ = b[13]; j__ = b[14]; k__ = b[15]; } public Guid(int a, short b, short c, byte[] d) { if(d == null) { throw new ArgumentNullException("d"); } if(d.Length != 8) { throw new ArgumentException(_("Arg_GuidArray8")); } a__ = a; b__ = b; c__ = c; d__ = d[0]; e__ = d[1]; f__ = d[2]; g__ = d[3]; h__ = d[4]; i__ = d[5]; j__ = d[6]; k__ = d[7]; } public Guid(int a, short b, short c, byte d, byte e, byte f, byte g, byte h, byte i, byte j, byte k) { a__ = a; b__ = b; c__ = c; d__ = d; e__ = e; f__ = f; g__ = g; h__ = h; i__ = i; j__ = j; k__ = k; } [CLSCompliant(false)] public Guid(uint a, ushort b, ushort c, byte d, byte e, byte f, byte g, byte h, byte i, byte j, byte k) { a__ = unchecked((int)a); b__ = unchecked((short)b); c__ = unchecked((short)c); d__ = d; e__ = e; f__ = f; g__ = g; h__ = h; i__ = i; j__ = j; k__ = k; } // Implement the IComparable interface. public int CompareTo(Object value) { if(value != null) { if(!(value is Guid)) { throw new ArgumentException(_("Arg_MustBeGuid")); } Guid temp = (Guid)value; if(((uint)a__) < ((uint)(temp.a__))) { return -1; } else if(((uint)a__) > ((uint)(temp.a__))) { return 1; } if(((ushort)b__) < ((ushort)(temp.b__))) { return -1; } else if(((ushort)b__) > ((ushort)(temp.b__))) { return 1; } if(((ushort)c__) < ((ushort)(temp.c__))) { return -1; } else if(((ushort)c__) > ((ushort)(temp.c__))) { return 1; } if(d__ < temp.d__) { return -1; } else if(d__ > temp.d__) { return 1; } if(e__ < temp.e__) { return -1; } else if(e__ > temp.e__) { return 1; } if(f__ < temp.f__) { return -1; } else if(f__ > temp.f__) { return 1; } if(g__ < temp.g__) { return -1; } else if(g__ > temp.g__) { return 1; } if(h__ < temp.h__) { return -1; } else if(h__ > temp.h__) { return 1; } if(i__ < temp.i__) { return -1; } else if(i__ > temp.i__) { return 1; } if(j__ < temp.j__) { return -1; } else if(j__ > temp.j__) { return 1; } if(k__ < temp.k__) { return -1; } else if(k__ > temp.k__) { return 1; } return 0; } else { return 1; } } // Determine if two Guid objects are equal. public override bool Equals(Object obj) { if(obj is Guid) { Guid temp = (Guid)obj; return (a__ == temp.a__ && b__ == temp.b__ && c__ == temp.c__ && d__ == temp.d__ && e__ == temp.e__ && f__ == temp.f__ && g__ == temp.g__ && h__ == temp.h__ && i__ == temp.i__ && j__ == temp.j__ && k__ == temp.k__); } else { return false; } } // Get a hash code for this Guid object. public override int GetHashCode() { return (a__ ^ ((((int)b__) << 16) | (int)(ushort)c__) ^ ((((int)f__) << 24) | k__)); } // Convert this Guid into a byte array. public byte[] ToByteArray() { byte[] bytes = new byte [16]; bytes[0] = (byte)(a__); bytes[1] = (byte)(a__ >> 8); bytes[2] = (byte)(a__ >> 16); bytes[3] = (byte)(a__ >> 24); bytes[4] = (byte)(b__); bytes[5] = (byte)(b__ >> 8); bytes[6] = (byte)(c__); bytes[7] = (byte)(c__ >> 8); bytes[8] = d__; bytes[9] = e__; bytes[10] = f__; bytes[11] = g__; bytes[12] = h__; bytes[13] = i__; bytes[14] = j__; bytes[15] = k__; return bytes; } // Add the hex representation of an integer to a string builder. private static void AddHex(StringBuilder builder, int value, int digits) { int hexdig; while(digits > 0) { --digits; hexdig = ((value >> (digits * 4)) & 0x0F); if(hexdig < 10) { builder.Append((char)('0' + hexdig)); } else { builder.Append((char)('a' + hexdig - 10)); } } } // Convert this Guid into a string. public override String ToString() { return ToString("D", null); } public String ToString(String format) { return ToString(format, null); } public String ToString(String format, IFormatProvider provider) { String start, end, sep; if(format == "B" || format == "b") { start = "{"; end = "}"; sep = "-"; } else if(format == null || format == "" || format == "D" || format == "d") { start = ""; end = ""; sep = "-"; } else if(format == "N" || format == "n") { start = ""; end = ""; sep = ""; } else if(format == "P" || format == "p") { start = "("; end = ")"; sep = "-"; } else { throw new FormatException(_("Format_Guid")); } StringBuilder builder = new StringBuilder(38); builder.Append(start); AddHex(builder, a__, 8); builder.Append(sep); AddHex(builder, b__, 4); builder.Append(sep); AddHex(builder, c__, 4); builder.Append(sep); AddHex(builder, d__, 2); AddHex(builder, e__, 2); builder.Append(sep); AddHex(builder, f__, 2); AddHex(builder, g__, 2); AddHex(builder, h__, 2); AddHex(builder, i__, 2); AddHex(builder, j__, 2); AddHex(builder, k__, 2); builder.Append(end); return builder.ToString(); } // Operators. public static bool operator==(Guid a, Guid b) { return (a.a__ == b.a__ && a.b__ == b.b__ && a.c__ == b.c__ && a.d__ == b.d__ && a.e__ == b.e__ && a.f__ == b.f__ && a.g__ == b.g__ && a.h__ == b.h__ && a.i__ == b.i__ && a.j__ == b.j__ && a.k__ == b.k__); } public static bool operator!=(Guid a, Guid b) { return (a.a__ != b.a__ || a.b__ != b.b__ || a.c__ != b.c__ || a.d__ != b.d__ || a.e__ != b.e__ || a.f__ != b.f__ || a.g__ != b.g__ || a.h__ != b.h__ || a.i__ != b.i__ || a.j__ != b.j__ || a.k__ != b.k__); } }; // struct Guid #endif // !ECMA_COMPAT }; // namespace System
namespace System { using Text; // A Version object contains four hierarchical numeric components: major, minor, // build and revision. Build and revision may be unspecified, which is represented // internally as a -1. By definition, an unspecified component matches anything // (both unspecified and specified), and an unspecified component is "less than" any // specified component. [Bridge.Convention(Member = Bridge.ConventionMember.Field | Bridge.ConventionMember.Method, Notation = Bridge.Notation.CamelCase)] public sealed class Version : ICloneable, IComparable<Version>, IEquatable<Version> { // AssemblyName depends on the order staying the same private int _Major; private int _Minor; private int _Build = -1; private int _Revision = -1; private static readonly char SeparatorsArray = '.'; public Version(int major, int minor, int build, int revision) { if (major < 0) throw new ArgumentOutOfRangeException("major", "Cannot be < 0"); if (minor < 0) throw new ArgumentOutOfRangeException("minor", "Cannot be < 0"); if (build < 0) throw new ArgumentOutOfRangeException("build", "Cannot be < 0"); if (revision < 0) throw new ArgumentOutOfRangeException("revision", "Cannot be < 0"); _Major = major; _Minor = minor; _Build = build; _Revision = revision; } public Version(int major, int minor, int build) { if (major < 0) throw new ArgumentOutOfRangeException("major", "Cannot be < 0"); if (minor < 0) throw new ArgumentOutOfRangeException("minor", "Cannot be < 0"); if (build < 0) throw new ArgumentOutOfRangeException("build", "Cannot be < 0"); _Major = major; _Minor = minor; _Build = build; } public Version(int major, int minor) { if (major < 0) throw new ArgumentOutOfRangeException("major", "Cannot be < 0"); if (minor < 0) throw new ArgumentOutOfRangeException("minor", "Cannot be < 0"); _Major = major; _Minor = minor; } public Version(String version) { Version v = Version.Parse(version); _Major = v.Major; _Minor = v.Minor; _Build = v.Build; _Revision = v.Revision; } public Version() { _Major = 0; _Minor = 0; } // Properties for setting and getting version numbers public int Major { get { return _Major; } } public int Minor { get { return _Minor; } } public int Build { get { return _Build; } } public int Revision { get { return _Revision; } } public short MajorRevision { get { return (short)(_Revision >> 16); } } public short MinorRevision { get { return (short)(_Revision & 0xFFFF); } } public Object Clone() { Version v = new Version(); v._Major = _Major; v._Minor = _Minor; v._Build = _Build; v._Revision = _Revision; return (v); } public int CompareTo(Object version) { if (version == null) { return 1; } Version v = version as Version; if (v == null) { throw new ArgumentException("version should be of System.Version type"); } if (this._Major != v._Major) if (this._Major > v._Major) return 1; else return -1; if (this._Minor != v._Minor) if (this._Minor > v._Minor) return 1; else return -1; if (this._Build != v._Build) if (this._Build > v._Build) return 1; else return -1; if (this._Revision != v._Revision) if (this._Revision > v._Revision) return 1; else return -1; return 0; } public int CompareTo(Version value) { if (value == null) return 1; if (this._Major != value._Major) if (this._Major > value._Major) return 1; else return -1; if (this._Minor != value._Minor) if (this._Minor > value._Minor) return 1; else return -1; if (this._Build != value._Build) if (this._Build > value._Build) return 1; else return -1; if (this._Revision != value._Revision) if (this._Revision > value._Revision) return 1; else return -1; return 0; } public override bool Equals(Object obj) { return Equals(obj as Version); } public bool Equals(Version obj) { if (obj == null) return false; // check that major, minor, build & revision numbers match if ((this._Major != obj._Major) || (this._Minor != obj._Minor) || (this._Build != obj._Build) || (this._Revision != obj._Revision)) return false; return true; } public override int GetHashCode() { // Let's assume that most version numbers will be pretty small and just // OR some lower order bits together. int accumulator = 0; accumulator |= (this._Major & 0x0000000F) << 28; accumulator |= (this._Minor & 0x000000FF) << 20; accumulator |= (this._Build & 0x000000FF) << 12; accumulator |= (this._Revision & 0x00000FFF); return accumulator; } public override String ToString() { if (_Build == -1) return (ToString(2)); if (_Revision == -1) return (ToString(3)); return (ToString(4)); } public String ToString(int fieldCount) { StringBuilder sb; switch (fieldCount) { case 0: return (String.Empty); case 1: return (_Major.ToString()); case 2: sb = new StringBuilder(); AppendPositiveNumber(_Major, sb); sb.Append('.'); AppendPositiveNumber(_Minor, sb); return sb.ToString(); default: if (_Build == -1) throw new ArgumentException("Build should be > 0 if fieldCount > 2", "fieldCount"); if (fieldCount == 3) { sb = new StringBuilder(); AppendPositiveNumber(_Major, sb); sb.Append('.'); AppendPositiveNumber(_Minor, sb); sb.Append('.'); AppendPositiveNumber(_Build, sb); return sb.ToString(); } if (_Revision == -1) throw new ArgumentException("Revision should be > 0 if fieldCount > 3", "fieldCount"); if (fieldCount == 4) { sb = new StringBuilder(); AppendPositiveNumber(_Major, sb); sb.Append('.'); AppendPositiveNumber(_Minor, sb); sb.Append('.'); AppendPositiveNumber(_Build, sb); sb.Append('.'); AppendPositiveNumber(_Revision, sb); return sb.ToString(); } throw new ArgumentException("Should be < 5", "fieldCount"); } } private const int ZERO_CHAR_VALUE = (int)'0'; private static void AppendPositiveNumber(int num, StringBuilder sb) { int index = sb.Length; int reminder; do { reminder = num % 10; num = num / 10; sb.Insert(index, (char)(ZERO_CHAR_VALUE + reminder)); } while (num > 0); } public static Version Parse(string input) { if (input == null) { throw new ArgumentNullException("input"); } VersionResult r = new VersionResult(); r.Init("input", true); if (!TryParseVersion(input, ref r)) { throw r.GetVersionParseException(); } return r.m_parsedVersion; } public static bool TryParse(string input, out Version result) { VersionResult r = new VersionResult(); r.Init("input", false); bool b = TryParseVersion(input, ref r); result = r.m_parsedVersion; return b; } private static bool TryParseVersion(string version, ref VersionResult result) { int major, minor, build, revision; if ((Object)version == null) { result.SetFailure(ParseFailureKind.ArgumentNullException); return false; } String[] parsedComponents = version.Split(SeparatorsArray); int parsedComponentsLength = parsedComponents.Length; if ((parsedComponentsLength < 2) || (parsedComponentsLength > 4)) { result.SetFailure(ParseFailureKind.ArgumentException); return false; } if (!TryParseComponent(parsedComponents[0], "version", ref result, out major)) { return false; } if (!TryParseComponent(parsedComponents[1], "version", ref result, out minor)) { return false; } parsedComponentsLength -= 2; if (parsedComponentsLength > 0) { if (!TryParseComponent(parsedComponents[2], "build", ref result, out build)) { return false; } parsedComponentsLength--; if (parsedComponentsLength > 0) { if (!TryParseComponent(parsedComponents[3], "revision", ref result, out revision)) { return false; } else { result.m_parsedVersion = new Version(major, minor, build, revision); } } else { result.m_parsedVersion = new Version(major, minor, build); } } else { result.m_parsedVersion = new Version(major, minor); } return true; } private static bool TryParseComponent(string component, string componentName, ref VersionResult result, out int parsedComponent) { if (!Int32.TryParse(component, out parsedComponent)) { result.SetFailure(ParseFailureKind.FormatException, component); return false; } if (parsedComponent < 0) { result.SetFailure(ParseFailureKind.ArgumentOutOfRangeException, componentName); return false; } return true; } public static bool operator ==(Version v1, Version v2) { if (Object.ReferenceEquals(v1, null)) { return Object.ReferenceEquals(v2, null); } return v1.Equals(v2); } public static bool operator !=(Version v1, Version v2) { return !(v1 == v2); } public static bool operator <(Version v1, Version v2) { if ((Object)v1 == null) throw new ArgumentNullException("v1"); return (v1.CompareTo(v2) < 0); } public static bool operator <=(Version v1, Version v2) { if ((Object)v1 == null) throw new ArgumentNullException("v1"); return (v1.CompareTo(v2) <= 0); } public static bool operator >(Version v1, Version v2) { return (v2 < v1); } public static bool operator >=(Version v1, Version v2) { return (v2 <= v1); } internal enum ParseFailureKind { ArgumentNullException, ArgumentException, ArgumentOutOfRangeException, FormatException } internal struct VersionResult { internal Version m_parsedVersion; internal ParseFailureKind m_failure; internal string m_exceptionArgument; internal string m_argumentName; internal bool m_canThrow; internal void Init(string argumentName, bool canThrow) { m_canThrow = canThrow; m_argumentName = argumentName; } internal void SetFailure(ParseFailureKind failure) { SetFailure(failure, String.Empty); } internal void SetFailure(ParseFailureKind failure, string argument) { m_failure = failure; m_exceptionArgument = argument; if (m_canThrow) { throw GetVersionParseException(); } } internal Exception GetVersionParseException() { switch (m_failure) { case ParseFailureKind.ArgumentNullException: return new ArgumentNullException(m_argumentName); case ParseFailureKind.ArgumentException: return new ArgumentException("VersionString"); case ParseFailureKind.ArgumentOutOfRangeException: return new ArgumentOutOfRangeException(m_exceptionArgument, "Cannot be < 0"); case ParseFailureKind.FormatException: // Regenerate the FormatException as would be thrown by Int32.Parse() try { Int32.Parse(m_exceptionArgument); } catch (FormatException e) { return e; } catch (OverflowException e) { return e; } return new FormatException("InvalidString"); default: return new ArgumentException("VersionString"); } } } } }
/* * 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.Events { using System; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using Apache.Ignite.Core.Binary; using Apache.Ignite.Core.Cluster; using Apache.Ignite.Core.Common; using Apache.Ignite.Core.Impl.Binary; /// <summary> /// Base event implementation. /// </summary> public abstract class EventBase : IEvent, IEquatable<EventBase> { /** */ private readonly IgniteGuid _id; /** */ private readonly long _localOrder; /** */ private readonly IClusterNode _node; /** */ private readonly string _message; /** */ private readonly int _type; /** */ private readonly string _name; /** */ private readonly DateTime _timestamp; /// <summary> /// Initializes a new instance of the <see cref="EventBase"/> class. /// </summary> /// <param name="r">The reader to read data from.</param> [SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods")] protected EventBase(IBinaryRawReader r) { Debug.Assert(r != null); _id = r.ReadObject<IgniteGuid>(); _localOrder = r.ReadLong(); _node = ReadNode(r); _message = r.ReadString(); _type = r.ReadInt(); _name = r.ReadString(); var timestamp = r.ReadTimestamp(); Debug.Assert(timestamp.HasValue); _timestamp = timestamp.Value; } /// <summary> /// Gets globally unique ID of this event. /// </summary> public IgniteGuid Id { get { return _id; } } /// <summary> /// Gets locally unique ID that is atomically incremented for each event. Unlike global <see cref="Id" /> /// this local ID can be used for ordering events on this node. /// <para /> /// Note that for performance considerations Ignite doesn't order events globally. /// </summary> public long LocalOrder { get { return _localOrder; } } /// <summary> /// Node where event occurred and was recorded. /// </summary> public IClusterNode Node { get { return _node; } } /// <summary> /// Gets optional message for this event. /// </summary> public string Message { get { return _message; } } /// <summary> /// Gets type of this event. All system event types are defined in <see cref="EventType" /> /// </summary> public int Type { get { return _type; } } /// <summary> /// Gets name of this event. /// </summary> public string Name { get { return _name; } } /// <summary> /// Gets event timestamp. Timestamp is local to the node on which this event was produced. /// Note that more than one event can be generated with the same timestamp. /// For ordering purposes use <see cref="LocalOrder" /> instead. /// </summary> public DateTime Timestamp { get { return _timestamp; } } /// <summary> /// Gets shortened version of ToString result. /// </summary> public virtual string ToShortString() { return ToString(); } /// <summary> /// Determines whether the specified object is equal to this instance. /// </summary> /// <param name="other">The object to compare with this instance.</param> /// <returns> /// <c>true</c> if the specified object is equal to this instance; otherwise, <c>false</c>. /// </returns> public bool Equals(EventBase other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; return _id.Equals(other._id); } /// <summary> /// Determines whether the specified object is equal to this instance. /// </summary> /// <param name="obj">The object to compare with this instance.</param> /// <returns> /// <c>true</c> if the specified object is equal to this instance; otherwise, <c>false</c>. /// </returns> public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; if (obj.GetType() != GetType()) return false; return Equals((EventBase) obj); } /// <summary> /// Returns a hash code for this instance. /// </summary> /// <returns> /// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table. /// </returns> public override int GetHashCode() { return _id.GetHashCode(); } /// <summary> /// Returns a <see cref="string" /> that represents this instance. /// </summary> /// <returns> /// A <see cref="string" /> that represents this instance. /// </returns> public override string ToString() { return string.Format(CultureInfo.InvariantCulture, "{0} [Name={1}, Type={2}, Timestamp={3}, Message={4}]", GetType().Name, Name, Type, Timestamp, Message); } /// <summary> /// Reads a node from stream. /// </summary> /// <param name="reader">Reader.</param> /// <returns>Node or null.</returns> [SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods")] protected static IClusterNode ReadNode(IBinaryRawReader reader) { return ((BinaryReader)reader).Marshaller.Ignite.GetNode(reader.ReadGuid()); } } }
// Licensed to the .NET Foundation under one or more agreements. // See the LICENSE file in the project root for more information. // // System.Drawing.PrinterSettings.cs // // Authors: // Dennis Hayes (dennish@Raytek.com) // Herve Poussineau (hpoussineau@fr.st) // Andreas Nahr (ClassDevelopment@A-SoftTech.com) // // (C) 2002 Ximian, Inc // Copyright (C) 2004,2006 Novell, Inc (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System.Runtime.InteropServices; using System.Collections; using System.Collections.Specialized; using System.ComponentModel; using System.Drawing.Imaging; namespace System.Drawing.Printing { [Serializable] public class PrinterSettings : ICloneable { private string printer_name; private string print_filename; private short copies; private int maximum_page; private int minimum_page; private int from_page; private int to_page; private bool collate; private PrintRange print_range; internal int maximum_copies; internal bool can_duplex; internal bool supports_color; internal int landscape_angle; private bool print_tofile; internal PrinterSettings.PrinterResolutionCollection printer_resolutions; internal PrinterSettings.PaperSizeCollection paper_sizes; internal PrinterSettings.PaperSourceCollection paper_sources; private PageSettings default_pagesettings; private Duplex duplex; internal bool is_plotter; private PrintingServices printing_services; internal NameValueCollection printer_capabilities; // this stores a list of all the printer options. Used only in cups, but might come in handy on win too. public PrinterSettings() : this(SysPrn.CreatePrintingService()) { } internal PrinterSettings(PrintingServices printing_services) { this.printing_services = printing_services; printer_name = printing_services.DefaultPrinter; ResetToDefaults(); printing_services.LoadPrinterSettings(printer_name, this); } private void ResetToDefaults() { printer_resolutions = null; paper_sizes = null; paper_sources = null; default_pagesettings = null; maximum_page = 9999; copies = 1; collate = true; } //properties public bool CanDuplex { get { return can_duplex; } } public bool Collate { get { return collate; } set { collate = value; } } public short Copies { get { return copies; } set { if (value < 0) throw new ArgumentException("The value of the Copies property is less than zero."); copies = value; } } public PageSettings DefaultPageSettings { get { if (default_pagesettings == null) { default_pagesettings = new PageSettings(this, SupportsColor, false, // Real defaults are set by LoadPrinterSettings new PaperSize("A4", 827, 1169), new PaperSource(PaperSourceKind.FormSource, "Tray"), new PrinterResolution(PrinterResolutionKind.Medium, 200, 200)); } return default_pagesettings; } } public Duplex Duplex { get { return this.duplex; } set { this.duplex = value; } } public int FromPage { get { return from_page; } set { if (value < 0) throw new ArgumentException("The value of the FromPage property is less than zero"); from_page = value; } } public static PrinterSettings.StringCollection InstalledPrinters { get { return SysPrn.GlobalService.InstalledPrinters; } } public bool IsDefaultPrinter { get { return (printer_name == printing_services.DefaultPrinter); } } public bool IsPlotter { get { return is_plotter; } } public bool IsValid { get { return printing_services.IsPrinterValid(this.printer_name); } } public int LandscapeAngle { get { return landscape_angle; } } public int MaximumCopies { get { return maximum_copies; } } public int MaximumPage { get { return maximum_page; } set { // This not documented but behaves like MinimumPage if (value < 0) throw new ArgumentException("The value of the MaximumPage property is less than zero"); maximum_page = value; } } public int MinimumPage { get { return minimum_page; } set { if (value < 0) throw new ArgumentException("The value of the MaximumPage property is less than zero"); minimum_page = value; } } public PrinterSettings.PaperSizeCollection PaperSizes { get { if (!this.IsValid) throw new InvalidPrinterException(this); return paper_sizes; } } public PrinterSettings.PaperSourceCollection PaperSources { get { if (!this.IsValid) throw new InvalidPrinterException(this); return paper_sources; } } public string PrintFileName { get { return print_filename; } set { print_filename = value; } } public string PrinterName { get { return printer_name; } set { if (printer_name == value) return; printer_name = value; printing_services.LoadPrinterSettings(printer_name, this); } } public PrinterSettings.PrinterResolutionCollection PrinterResolutions { get { if (!this.IsValid) throw new InvalidPrinterException(this); if (printer_resolutions == null) { printer_resolutions = new PrinterSettings.PrinterResolutionCollection(new PrinterResolution[] { }); printing_services.LoadPrinterResolutions(printer_name, this); } return printer_resolutions; } } public PrintRange PrintRange { get { return print_range; } set { if (value != PrintRange.AllPages && value != PrintRange.Selection && value != PrintRange.SomePages) throw new InvalidEnumArgumentException("The value of the PrintRange property is not one of the PrintRange values"); print_range = value; } } public bool PrintToFile { get { return print_tofile; } set { print_tofile = value; } } public bool SupportsColor { get { return supports_color; } } public int ToPage { get { return to_page; } set { if (value < 0) throw new ArgumentException("The value of the ToPage property is less than zero"); to_page = value; } } internal NameValueCollection PrinterCapabilities { get { if (this.printer_capabilities == null) this.printer_capabilities = new NameValueCollection(); return this.printer_capabilities; } } //methods public object Clone() { PrinterSettings ps = new PrinterSettings(printing_services); return ps; } [MonoTODO("PrinterSettings.CreateMeasurementGraphics")] public Graphics CreateMeasurementGraphics() { throw new NotImplementedException(); } [MonoTODO("PrinterSettings.CreateMeasurementGraphics")] public Graphics CreateMeasurementGraphics(bool honorOriginAtMargins) { throw new NotImplementedException(); } [MonoTODO("PrinterSettings.CreateMeasurementGraphics")] public Graphics CreateMeasurementGraphics(PageSettings pageSettings) { throw new NotImplementedException(); } [MonoTODO("PrinterSettings.CreateMeasurementGraphics")] public Graphics CreateMeasurementGraphics(PageSettings pageSettings, bool honorOriginAtMargins) { throw new NotImplementedException(); } [MonoTODO("PrinterSettings.GetHdevmode")] public IntPtr GetHdevmode() { throw new NotImplementedException(); } [MonoTODO("PrinterSettings.GetHdevmode")] public IntPtr GetHdevmode(PageSettings pageSettings) { throw new NotImplementedException(); } [MonoTODO("PrinterSettings.GetHdevname")] public IntPtr GetHdevnames() { throw new NotImplementedException(); } [MonoTODO("IsDirectPrintingSupported")] public bool IsDirectPrintingSupported(Image image) { throw new NotImplementedException(); } [MonoTODO("IsDirectPrintingSupported")] public bool IsDirectPrintingSupported(ImageFormat imageFormat) { throw new NotImplementedException(); } [MonoTODO("PrinterSettings.SetHdevmode")] public void SetHdevmode(IntPtr hdevmode) { throw new NotImplementedException(); } [MonoTODO("PrinterSettings.SetHdevnames")] public void SetHdevnames(IntPtr hdevnames) { throw new NotImplementedException(); } public override string ToString() { return "Printer [PrinterSettings " + printer_name + " Copies=" + copies + " Collate=" + collate + " Duplex=" + can_duplex + " FromPage=" + from_page + " LandscapeAngle=" + landscape_angle + " MaximumCopies=" + maximum_copies + " OutputPort=" + " ToPage=" + to_page + "]"; } // Public subclasses #region Public Subclasses public class PaperSourceCollection : ICollection, IEnumerable { ArrayList _PaperSources = new ArrayList(); public PaperSourceCollection(PaperSource[] array) { foreach (PaperSource ps in array) _PaperSources.Add(ps); } public int Count { get { return _PaperSources.Count; } } int ICollection.Count { get { return _PaperSources.Count; } } bool ICollection.IsSynchronized { get { return false; } } object ICollection.SyncRoot { get { return this; } } [EditorBrowsable(EditorBrowsableState.Never)] public int Add(PaperSource paperSource) { return _PaperSources.Add(paperSource); } public void CopyTo(PaperSource[] paperSources, int index) { throw new NotImplementedException(); } public virtual PaperSource this[int index] { get { return _PaperSources[index] as PaperSource; } } IEnumerator IEnumerable.GetEnumerator() { return _PaperSources.GetEnumerator(); } public IEnumerator GetEnumerator() { return _PaperSources.GetEnumerator(); } void ICollection.CopyTo(Array array, int index) { _PaperSources.CopyTo(array, index); } internal void Clear() { _PaperSources.Clear(); } } public class PaperSizeCollection : ICollection, IEnumerable { ArrayList _PaperSizes = new ArrayList(); public PaperSizeCollection(PaperSize[] array) { foreach (PaperSize ps in array) _PaperSizes.Add(ps); } public int Count { get { return _PaperSizes.Count; } } int ICollection.Count { get { return _PaperSizes.Count; } } bool ICollection.IsSynchronized { get { return false; } } object ICollection.SyncRoot { get { return this; } } [EditorBrowsable(EditorBrowsableState.Never)] public int Add(PaperSize paperSize) { return _PaperSizes.Add(paperSize); } public void CopyTo(PaperSize[] paperSizes, int index) { throw new NotImplementedException(); } public virtual PaperSize this[int index] { get { return _PaperSizes[index] as PaperSize; } } IEnumerator IEnumerable.GetEnumerator() { return _PaperSizes.GetEnumerator(); } public IEnumerator GetEnumerator() { return _PaperSizes.GetEnumerator(); } void ICollection.CopyTo(Array array, int index) { _PaperSizes.CopyTo(array, index); } internal void Clear() { _PaperSizes.Clear(); } } public class PrinterResolutionCollection : ICollection, IEnumerable { ArrayList _PrinterResolutions = new ArrayList(); public PrinterResolutionCollection(PrinterResolution[] array) { foreach (PrinterResolution pr in array) _PrinterResolutions.Add(pr); } public int Count { get { return _PrinterResolutions.Count; } } int ICollection.Count { get { return _PrinterResolutions.Count; } } bool ICollection.IsSynchronized { get { return false; } } object ICollection.SyncRoot { get { return this; } } [EditorBrowsable(EditorBrowsableState.Never)] public int Add(PrinterResolution printerResolution) { return _PrinterResolutions.Add(printerResolution); } public void CopyTo(PrinterResolution[] printerResolutions, int index) { throw new NotImplementedException(); } public virtual PrinterResolution this[int index] { get { return _PrinterResolutions[index] as PrinterResolution; } } IEnumerator IEnumerable.GetEnumerator() { return _PrinterResolutions.GetEnumerator(); } public IEnumerator GetEnumerator() { return _PrinterResolutions.GetEnumerator(); } void ICollection.CopyTo(Array array, int index) { _PrinterResolutions.CopyTo(array, index); } internal void Clear() { _PrinterResolutions.Clear(); } } public class StringCollection : ICollection, IEnumerable { ArrayList _Strings = new ArrayList(); public StringCollection(string[] array) { foreach (string s in array) _Strings.Add(s); } public int Count { get { return _Strings.Count; } } int ICollection.Count { get { return _Strings.Count; } } bool ICollection.IsSynchronized { get { return false; } } object ICollection.SyncRoot { get { return this; } } public virtual string this[int index] { get { return _Strings[index] as string; } } [EditorBrowsable(EditorBrowsableState.Never)] public int Add(string value) { return _Strings.Add(value); } public void CopyTo(string[] strings, int index) { throw new NotImplementedException(); } IEnumerator IEnumerable.GetEnumerator() { return _Strings.GetEnumerator(); } public IEnumerator GetEnumerator() { return _Strings.GetEnumerator(); } void ICollection.CopyTo(Array array, int index) { _Strings.CopyTo(array, index); } } #endregion /* void GetPrintDialogInfo (string printer_name, ref string port, ref string type, ref string status, ref string comment) { printing_services.GetPrintDialogInfo (printer_name, ref port, ref type, ref status, ref comment); } */ } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Text; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { public class CSharpCommandLineParser : CommandLineParser { public static CSharpCommandLineParser Default { get; } = new CSharpCommandLineParser(); internal static CSharpCommandLineParser ScriptRunner { get; } = new CSharpCommandLineParser(isScriptRunner: true); internal CSharpCommandLineParser(bool isScriptRunner = false) : base(CSharp.MessageProvider.Instance, isScriptRunner) { } protected override string RegularFileExtension { get { return ".cs"; } } protected override string ScriptFileExtension { get { return ".csx"; } } internal sealed override CommandLineArguments CommonParse(IEnumerable<string> args, string baseDirectory, string sdkDirectoryOpt, string additionalReferenceDirectories) { return Parse(args, baseDirectory, sdkDirectoryOpt, additionalReferenceDirectories); } /// <summary> /// Parses a command line. /// </summary> /// <param name="args">A collection of strings representing the command line arguments.</param> /// <param name="baseDirectory">The base directory used for qualifying file locations.</param> /// <param name="sdkDirectory">The directory to search for mscorlib, or null if not available.</param> /// <param name="additionalReferenceDirectories">A string representing additional reference paths.</param> /// <returns>a commandlinearguments object representing the parsed command line.</returns> public new CSharpCommandLineArguments Parse(IEnumerable<string> args, string baseDirectory, string sdkDirectory, string additionalReferenceDirectories = null) { List<Diagnostic> diagnostics = new List<Diagnostic>(); List<string> flattenedArgs = new List<string>(); List<string> scriptArgs = IsScriptRunner ? new List<string>() : null; FlattenArgs(args, diagnostics, flattenedArgs, scriptArgs, baseDirectory); string appConfigPath = null; bool displayLogo = true; bool displayHelp = false; bool optimize = false; bool checkOverflow = false; bool allowUnsafe = false; bool concurrentBuild = true; bool deterministic = false; // TODO(5431): Enable deterministic mode by default bool emitPdb = false; DebugInformationFormat debugInformationFormat = DebugInformationFormat.Pdb; bool debugPlus = false; string pdbPath = null; bool noStdLib = IsScriptRunner; // don't add mscorlib from sdk dir when running scripts string outputDirectory = baseDirectory; ImmutableArray<KeyValuePair<string, string>> pathMap = ImmutableArray<KeyValuePair<string, string>>.Empty; string outputFileName = null; string documentationPath = null; string errorLogPath = null; bool parseDocumentationComments = false; //Don't just null check documentationFileName because we want to do this even if the file name is invalid. bool utf8output = false; OutputKind outputKind = OutputKind.ConsoleApplication; SubsystemVersion subsystemVersion = SubsystemVersion.None; LanguageVersion languageVersion = CSharpParseOptions.Default.LanguageVersion; string mainTypeName = null; string win32ManifestFile = null; string win32ResourceFile = null; string win32IconFile = null; bool noWin32Manifest = false; Platform platform = Platform.AnyCpu; ulong baseAddress = 0; int fileAlignment = 0; bool? delaySignSetting = null; string keyFileSetting = null; string keyContainerSetting = null; List<ResourceDescription> managedResources = new List<ResourceDescription>(); List<CommandLineSourceFile> sourceFiles = new List<CommandLineSourceFile>(); List<CommandLineSourceFile> additionalFiles = new List<CommandLineSourceFile>(); bool sourceFilesSpecified = false; bool resourcesOrModulesSpecified = false; Encoding codepage = null; var checksumAlgorithm = SourceHashAlgorithm.Sha1; var defines = ArrayBuilder<string>.GetInstance(); List<CommandLineReference> metadataReferences = new List<CommandLineReference>(); List<CommandLineAnalyzerReference> analyzers = new List<CommandLineAnalyzerReference>(); List<string> libPaths = new List<string>(); List<string> sourcePaths = new List<string>(); List<string> keyFileSearchPaths = new List<string>(); List<string> usings = new List<string>(); var generalDiagnosticOption = ReportDiagnostic.Default; var diagnosticOptions = new Dictionary<string, ReportDiagnostic>(); var noWarns = new Dictionary<string, ReportDiagnostic>(); var warnAsErrors = new Dictionary<string, ReportDiagnostic>(); int warningLevel = 4; bool highEntropyVA = false; bool printFullPaths = false; string moduleAssemblyName = null; string moduleName = null; List<string> features = new List<string>(); string runtimeMetadataVersion = null; bool errorEndLocation = false; bool reportAnalyzer = false; CultureInfo preferredUILang = null; string touchedFilesPath = null; var sqmSessionGuid = Guid.Empty; bool optionsEnded = false; bool interactiveMode = false; bool publicSign = false; // Process ruleset files first so that diagnostic severity settings specified on the command line via // /nowarn and /warnaserror can override diagnostic severity settings specified in the ruleset file. if (!IsScriptRunner) { foreach (string arg in flattenedArgs) { string name, value; if (TryParseOption(arg, out name, out value) && (name == "ruleset")) { var unquoted = RemoveQuotesAndSlashes(value); if (string.IsNullOrEmpty(unquoted)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<text>", name); } else { generalDiagnosticOption = GetDiagnosticOptionsFromRulesetFile(diagnosticOptions, diagnostics, unquoted, baseDirectory); } } } } foreach (string arg in flattenedArgs) { Debug.Assert(optionsEnded || !arg.StartsWith("@", StringComparison.Ordinal)); string name, value; if (optionsEnded || !TryParseOption(arg, out name, out value)) { sourceFiles.AddRange(ParseFileArgument(arg, baseDirectory, diagnostics)); if (sourceFiles.Count > 0) { sourceFilesSpecified = true; } continue; } switch (name) { case "?": case "help": displayHelp = true; continue; case "r": case "reference": metadataReferences.AddRange(ParseAssemblyReferences(arg, value, diagnostics, embedInteropTypes: false)); continue; case "features": if (value == null) { features.Clear(); } else { features.Add(value); } continue; case "lib": case "libpath": case "libpaths": ParseAndResolveReferencePaths(name, value, baseDirectory, libPaths, MessageID.IDS_LIB_OPTION, diagnostics); continue; #if DEBUG case "attachdebugger": Debugger.Launch(); continue; #endif } if (IsScriptRunner) { switch (name) { case "-": // csi -- script.csx if (value != null) break; // Indicates that the remaining arguments should not be treated as options. optionsEnded = true; continue; case "i": case "i+": if (value != null) break; interactiveMode = true; continue; case "i-": if (value != null) break; interactiveMode = false; continue; case "loadpath": case "loadpaths": ParseAndResolveReferencePaths(name, value, baseDirectory, sourcePaths, MessageID.IDS_REFERENCEPATH_OPTION, diagnostics); continue; case "u": case "using": case "usings": case "import": case "imports": usings.AddRange(ParseUsings(arg, value, diagnostics)); continue; } } else { switch (name) { case "a": case "analyzer": analyzers.AddRange(ParseAnalyzers(arg, value, diagnostics)); continue; case "d": case "define": if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<text>", arg); continue; } IEnumerable<Diagnostic> defineDiagnostics; defines.AddRange(ParseConditionalCompilationSymbols(RemoveQuotesAndSlashes(value), out defineDiagnostics)); diagnostics.AddRange(defineDiagnostics); continue; case "codepage": if (value == null) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<text>", name); continue; } var encoding = TryParseEncodingName(value); if (encoding == null) { AddDiagnostic(diagnostics, ErrorCode.FTL_BadCodepage, value); continue; } codepage = encoding; continue; case "checksumalgorithm": if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<text>", name); continue; } var newChecksumAlgorithm = TryParseHashAlgorithmName(value); if (newChecksumAlgorithm == SourceHashAlgorithm.None) { AddDiagnostic(diagnostics, ErrorCode.FTL_BadChecksumAlgorithm, value); continue; } checksumAlgorithm = newChecksumAlgorithm; continue; case "checked": case "checked+": if (value != null) { break; } checkOverflow = true; continue; case "checked-": if (value != null) break; checkOverflow = false; continue; case "noconfig": // It is already handled (see CommonCommandLineCompiler.cs). continue; case "sqmsessionguid": if (value == null) { AddDiagnostic(diagnostics, ErrorCode.ERR_MissingGuidForOption, "<text>", name); } else { if (!Guid.TryParse(value, out sqmSessionGuid)) { AddDiagnostic(diagnostics, ErrorCode.ERR_InvalidFormatForGuidForOption, value, name); } } continue; case "preferreduilang": value = RemoveQuotesAndSlashes(value); if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<text>", arg); continue; } try { preferredUILang = new CultureInfo(value); if (CorLightup.Desktop.IsUserCustomCulture(preferredUILang) ?? false) { // Do not use user custom cultures. preferredUILang = null; } } catch (CultureNotFoundException) { } if (preferredUILang == null) { AddDiagnostic(diagnostics, ErrorCode.WRN_BadUILang, value); } continue; case "out": if (string.IsNullOrWhiteSpace(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg); } else { ParseOutputFile(value, diagnostics, baseDirectory, out outputFileName, out outputDirectory); } continue; case "t": case "target": if (value == null) { break; // force 'unrecognized option' } if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.FTL_InvalidTarget); } else { outputKind = ParseTarget(value, diagnostics); } continue; case "moduleassemblyname": value = value != null ? value.Unquote() : null; if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<text>", arg); } else if (!MetadataHelpers.IsValidAssemblyOrModuleName(value)) { // Dev11 C# doesn't check the name (VB does) AddDiagnostic(diagnostics, ErrorCode.ERR_InvalidAssemblyName, "<text>", arg); } else { moduleAssemblyName = value; } continue; case "modulename": var unquotedModuleName = RemoveQuotesAndSlashes(value); if (string.IsNullOrEmpty(unquotedModuleName)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), "modulename"); continue; } else { moduleName = unquotedModuleName; } continue; case "platform": if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<string>", arg); } else { platform = ParsePlatform(value, diagnostics); } continue; case "recurse": value = RemoveQuotesAndSlashes(value); if (value == null) { break; // force 'unrecognized option' } else if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg); } else { int before = sourceFiles.Count; sourceFiles.AddRange(ParseRecurseArgument(value, baseDirectory, diagnostics)); if (sourceFiles.Count > before) { sourceFilesSpecified = true; } } continue; case "doc": parseDocumentationComments = true; if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), arg); continue; } string unquoted = RemoveQuotesAndSlashes(value); if (string.IsNullOrEmpty(unquoted)) { // CONSIDER: This diagnostic exactly matches dev11, but it would be simpler (and more consistent with /out) // if we just let the next case handle /doc:"". AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), "/doc:"); // Different argument. } else { documentationPath = ParseGenericPathToFile(unquoted, diagnostics, baseDirectory); } continue; case "addmodule": if (value == null) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), "/addmodule:"); } else if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg); } else { // NOTE(tomat): Dev10 used to report CS1541: ERR_CantIncludeDirectory if the path was a directory. // Since we now support /referencePaths option we would need to search them to see if the resolved path is a directory. // An error will be reported by the assembly manager anyways. metadataReferences.AddRange(ParseSeparatedPaths(value).Select(path => new CommandLineReference(path, MetadataReferenceProperties.Module))); resourcesOrModulesSpecified = true; } continue; case "l": case "link": metadataReferences.AddRange(ParseAssemblyReferences(arg, value, diagnostics, embedInteropTypes: true)); continue; case "win32res": win32ResourceFile = GetWin32Setting(arg, value, diagnostics); continue; case "win32icon": win32IconFile = GetWin32Setting(arg, value, diagnostics); continue; case "win32manifest": win32ManifestFile = GetWin32Setting(arg, value, diagnostics); noWin32Manifest = false; continue; case "nowin32manifest": noWin32Manifest = true; win32ManifestFile = null; continue; case "res": case "resource": if (value == null) { break; // Dev11 reports unrecognized option } var embeddedResource = ParseResourceDescription(arg, value, baseDirectory, diagnostics, embedded: true); if (embeddedResource != null) { managedResources.Add(embeddedResource); resourcesOrModulesSpecified = true; } continue; case "linkres": case "linkresource": if (value == null) { break; // Dev11 reports unrecognized option } var linkedResource = ParseResourceDescription(arg, value, baseDirectory, diagnostics, embedded: false); if (linkedResource != null) { managedResources.Add(linkedResource); resourcesOrModulesSpecified = true; } continue; case "debug": emitPdb = true; // unused, parsed for backward compat only if (value != null) { if (value.IsEmpty()) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), name); continue; } switch (value.ToLower()) { case "full": case "pdbonly": debugInformationFormat = DebugInformationFormat.Pdb; break; case "portable": debugInformationFormat = DebugInformationFormat.PortablePdb; break; case "embedded": debugInformationFormat = DebugInformationFormat.Embedded; break; default: AddDiagnostic(diagnostics, ErrorCode.ERR_BadDebugType, value); break; } } continue; case "debug+": //guard against "debug+:xx" if (value != null) break; emitPdb = true; debugPlus = true; continue; case "debug-": if (value != null) break; emitPdb = false; debugPlus = false; continue; case "o": case "optimize": case "o+": case "optimize+": if (value != null) break; optimize = true; continue; case "o-": case "optimize-": if (value != null) break; optimize = false; continue; case "deterministic": case "deterministic+": if (value != null) break; deterministic = true; continue; case "deterministic-": if (value != null) break; deterministic = false; continue; case "p": case "parallel": case "p+": case "parallel+": if (value != null) break; concurrentBuild = true; continue; case "p-": case "parallel-": if (value != null) break; concurrentBuild = false; continue; case "warnaserror": case "warnaserror+": if (value == null) { generalDiagnosticOption = ReportDiagnostic.Error; // Reset specific warnaserror options (since last /warnaserror flag on the command line always wins), // and bump warnings to errors. warnAsErrors.Clear(); foreach (var key in diagnosticOptions.Keys) { if (diagnosticOptions[key] == ReportDiagnostic.Warn) { warnAsErrors[key] = ReportDiagnostic.Error; } } continue; } if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsNumber, name); } else { AddWarnings(warnAsErrors, ReportDiagnostic.Error, ParseWarnings(value)); } continue; case "warnaserror-": if (value == null) { generalDiagnosticOption = ReportDiagnostic.Default; // Clear specific warnaserror options (since last /warnaserror flag on the command line always wins). warnAsErrors.Clear(); continue; } if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsNumber, name); } else { foreach (var id in ParseWarnings(value)) { ReportDiagnostic ruleSetValue; if (diagnosticOptions.TryGetValue(id, out ruleSetValue)) { warnAsErrors[id] = ruleSetValue; } else { warnAsErrors[id] = ReportDiagnostic.Default; } } } continue; case "w": case "warn": if (value == null) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsNumber, name); continue; } int newWarningLevel; if (string.IsNullOrEmpty(value) || !int.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out newWarningLevel)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsNumber, name); } else if (newWarningLevel < 0 || newWarningLevel > 4) { AddDiagnostic(diagnostics, ErrorCode.ERR_BadWarningLevel, name); } else { warningLevel = newWarningLevel; } continue; case "nowarn": if (value == null) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsNumber, name); continue; } if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsNumber, name); } else { AddWarnings(noWarns, ReportDiagnostic.Suppress, ParseWarnings(value)); } continue; case "unsafe": case "unsafe+": if (value != null) break; allowUnsafe = true; continue; case "unsafe-": if (value != null) break; allowUnsafe = false; continue; case "langversion": if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), "/langversion:"); } else if (!TryParseLanguageVersion(value, CSharpParseOptions.Default.LanguageVersion, out languageVersion)) { AddDiagnostic(diagnostics, ErrorCode.ERR_BadCompatMode, value); } continue; case "delaysign": case "delaysign+": if (value != null) { break; } delaySignSetting = true; continue; case "delaysign-": if (value != null) { break; } delaySignSetting = false; continue; case "publicsign": case "publicsign+": if (value != null) { break; } publicSign = true; continue; case "publicsign-": if (value != null) { break; } publicSign = false; continue; case "keyfile": if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, "keyfile"); } else { keyFileSetting = RemoveQuotesAndSlashes(value); } // NOTE: Dev11/VB also clears "keycontainer", see also: // // MSDN: In case both /keyfile and /keycontainer are specified (either by command line option or by // MSDN: custom attribute) in the same compilation, the compiler will first try the key container. // MSDN: If that succeeds, then the assembly is signed with the information in the key container. // MSDN: If the compiler does not find the key container, it will try the file specified with /keyfile. // MSDN: If that succeeds, the assembly is signed with the information in the key file and the key // MSDN: information will be installed in the key container (similar to sn -i) so that on the next // MSDN: compilation, the key container will be valid. continue; case "keycontainer": if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), "keycontainer"); } else { keyContainerSetting = value; } // NOTE: Dev11/VB also clears "keyfile", see also: // // MSDN: In case both /keyfile and /keycontainer are specified (either by command line option or by // MSDN: custom attribute) in the same compilation, the compiler will first try the key container. // MSDN: If that succeeds, then the assembly is signed with the information in the key container. // MSDN: If the compiler does not find the key container, it will try the file specified with /keyfile. // MSDN: If that succeeds, the assembly is signed with the information in the key file and the key // MSDN: information will be installed in the key container (similar to sn -i) so that on the next // MSDN: compilation, the key container will be valid. continue; case "highentropyva": case "highentropyva+": if (value != null) break; highEntropyVA = true; continue; case "highentropyva-": if (value != null) break; highEntropyVA = false; continue; case "nologo": displayLogo = false; continue; case "baseaddress": value = RemoveQuotesAndSlashes(value); ulong newBaseAddress; if (string.IsNullOrEmpty(value) || !TryParseUInt64(value, out newBaseAddress)) { if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsNumber, name); } else { AddDiagnostic(diagnostics, ErrorCode.ERR_BadBaseNumber, value); } } else { baseAddress = newBaseAddress; } continue; case "subsystemversion": if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), "subsystemversion"); continue; } // It seems VS 2012 just silently corrects invalid values and suppresses the error message SubsystemVersion version = SubsystemVersion.None; if (SubsystemVersion.TryParse(value, out version)) { subsystemVersion = version; } else { AddDiagnostic(diagnostics, ErrorCode.ERR_InvalidSubsystemVersion, value); } continue; case "touchedfiles": unquoted = RemoveQuotesAndSlashes(value); if (string.IsNullOrEmpty(unquoted)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), "touchedfiles"); continue; } else { touchedFilesPath = unquoted; } continue; case "bugreport": UnimplementedSwitch(diagnostics, name); continue; case "utf8output": if (value != null) break; utf8output = true; continue; case "m": case "main": // Remove any quotes for consistent behavior as MSBuild can return quoted or // unquoted main. unquoted = RemoveQuotesAndSlashes(value); if (string.IsNullOrEmpty(unquoted)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<text>", name); continue; } mainTypeName = unquoted; continue; case "fullpaths": if (value != null) break; printFullPaths = true; continue; case "pathmap": // "/pathmap:K1=V1,K2=V2..." { if (value == null) break; pathMap = pathMap.Concat(ParsePathMap(value, diagnostics)); } continue; case "filealign": value = RemoveQuotesAndSlashes(value); ushort newAlignment; if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsNumber, name); } else if (!TryParseUInt16(value, out newAlignment)) { AddDiagnostic(diagnostics, ErrorCode.ERR_InvalidFileAlignment, value); } else if (!CompilationOptions.IsValidFileAlignment(newAlignment)) { AddDiagnostic(diagnostics, ErrorCode.ERR_InvalidFileAlignment, value); } else { fileAlignment = newAlignment; } continue; case "pdb": if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg); } else { pdbPath = ParsePdbPath(value, diagnostics, baseDirectory); } continue; case "errorendlocation": errorEndLocation = true; continue; case "reportanalyzer": reportAnalyzer = true; continue; case "nostdlib": case "nostdlib+": if (value != null) break; noStdLib = true; continue; case "nostdlib-": if (value != null) break; noStdLib = false; continue; case "errorreport": continue; case "errorlog": unquoted = RemoveQuotesAndSlashes(value); if (string.IsNullOrEmpty(unquoted)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, ":<file>", RemoveQuotesAndSlashes(arg)); } else { errorLogPath = ParseGenericPathToFile(unquoted, diagnostics, baseDirectory); } continue; case "appconfig": unquoted = RemoveQuotesAndSlashes(value); if (string.IsNullOrEmpty(unquoted)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, ":<text>", RemoveQuotesAndSlashes(arg)); } else { appConfigPath = ParseGenericPathToFile(unquoted, diagnostics, baseDirectory); } continue; case "runtimemetadataversion": unquoted = RemoveQuotesAndSlashes(value); if (string.IsNullOrEmpty(unquoted)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<text>", name); continue; } runtimeMetadataVersion = unquoted; continue; case "ruleset": // The ruleset arg has already been processed in a separate pass above. continue; case "additionalfile": if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<file list>", name); continue; } additionalFiles.AddRange(ParseAdditionalFileArgument(value, baseDirectory, diagnostics)); continue; } } AddDiagnostic(diagnostics, ErrorCode.ERR_BadSwitch, arg); } foreach (var o in warnAsErrors) { diagnosticOptions[o.Key] = o.Value; } // Specific nowarn options always override specific warnaserror options. foreach (var o in noWarns) { diagnosticOptions[o.Key] = o.Value; } if (!IsScriptRunner && !sourceFilesSpecified && (outputKind.IsNetModule() || !resourcesOrModulesSpecified)) { AddDiagnostic(diagnostics, diagnosticOptions, ErrorCode.WRN_NoSources); } if (!noStdLib && sdkDirectory != null) { metadataReferences.Insert(0, new CommandLineReference(Path.Combine(sdkDirectory, "mscorlib.dll"), MetadataReferenceProperties.Assembly)); } if (!platform.Requires64Bit()) { if (baseAddress > uint.MaxValue - 0x8000) { AddDiagnostic(diagnostics, ErrorCode.ERR_BadBaseNumber, string.Format("0x{0:X}", baseAddress)); baseAddress = 0; } } // add additional reference paths if specified if (!string.IsNullOrWhiteSpace(additionalReferenceDirectories)) { ParseAndResolveReferencePaths(null, additionalReferenceDirectories, baseDirectory, libPaths, MessageID.IDS_LIB_ENV, diagnostics); } ImmutableArray<string> referencePaths = BuildSearchPaths(sdkDirectory, libPaths); ValidateWin32Settings(win32ResourceFile, win32IconFile, win32ManifestFile, outputKind, diagnostics); // Dev11 searches for the key file in the current directory and assembly output directory. // We always look to base directory and then examine the search paths. keyFileSearchPaths.Add(baseDirectory); if (baseDirectory != outputDirectory) { keyFileSearchPaths.Add(outputDirectory); } // Public sign doesn't use the legacy search path settings if (publicSign && !string.IsNullOrWhiteSpace(keyFileSetting)) { keyFileSetting = ParseGenericPathToFile(keyFileSetting, diagnostics, baseDirectory); } var parsedFeatures = CompilerOptionParseUtilities.ParseFeatures(features); string compilationName; GetCompilationAndModuleNames(diagnostics, outputKind, sourceFiles, sourceFilesSpecified, moduleAssemblyName, ref outputFileName, ref moduleName, out compilationName); var parseOptions = new CSharpParseOptions ( languageVersion: languageVersion, preprocessorSymbols: defines.ToImmutableAndFree(), documentationMode: parseDocumentationComments ? DocumentationMode.Diagnose : DocumentationMode.None, kind: SourceCodeKind.Regular, features: parsedFeatures ); var scriptParseOptions = parseOptions.WithKind(SourceCodeKind.Script); // We want to report diagnostics with source suppression in the error log file. // However, these diagnostics won't be reported on the command line. var reportSuppressedDiagnostics = errorLogPath != null; var options = new CSharpCompilationOptions ( outputKind: outputKind, moduleName: moduleName, mainTypeName: mainTypeName, scriptClassName: WellKnownMemberNames.DefaultScriptClassName, usings: usings, optimizationLevel: optimize ? OptimizationLevel.Release : OptimizationLevel.Debug, checkOverflow: checkOverflow, allowUnsafe: allowUnsafe, deterministic: deterministic, concurrentBuild: concurrentBuild, cryptoKeyContainer: keyContainerSetting, cryptoKeyFile: keyFileSetting, delaySign: delaySignSetting, platform: platform, generalDiagnosticOption: generalDiagnosticOption, warningLevel: warningLevel, specificDiagnosticOptions: diagnosticOptions, reportSuppressedDiagnostics: reportSuppressedDiagnostics, publicSign: publicSign ); if (debugPlus) { options = options.WithDebugPlusMode(debugPlus); } var emitOptions = new EmitOptions ( metadataOnly: false, debugInformationFormat: debugInformationFormat, pdbFilePath: null, // to be determined later outputNameOverride: null, // to be determined later baseAddress: baseAddress, highEntropyVirtualAddressSpace: highEntropyVA, fileAlignment: fileAlignment, subsystemVersion: subsystemVersion, runtimeMetadataVersion: runtimeMetadataVersion ); // add option incompatibility errors if any diagnostics.AddRange(options.Errors); return new CSharpCommandLineArguments { IsScriptRunner = IsScriptRunner, InteractiveMode = interactiveMode || IsScriptRunner && sourceFiles.Count == 0, BaseDirectory = baseDirectory, PathMap = pathMap, Errors = diagnostics.AsImmutable(), Utf8Output = utf8output, CompilationName = compilationName, OutputFileName = outputFileName, PdbPath = pdbPath, EmitPdb = emitPdb, OutputDirectory = outputDirectory, DocumentationPath = documentationPath, ErrorLogPath = errorLogPath, AppConfigPath = appConfigPath, SourceFiles = sourceFiles.AsImmutable(), Encoding = codepage, ChecksumAlgorithm = checksumAlgorithm, MetadataReferences = metadataReferences.AsImmutable(), AnalyzerReferences = analyzers.AsImmutable(), AdditionalFiles = additionalFiles.AsImmutable(), ReferencePaths = referencePaths, SourcePaths = sourcePaths.AsImmutable(), KeyFileSearchPaths = keyFileSearchPaths.AsImmutable(), Win32ResourceFile = win32ResourceFile, Win32Icon = win32IconFile, Win32Manifest = win32ManifestFile, NoWin32Manifest = noWin32Manifest, DisplayLogo = displayLogo, DisplayHelp = displayHelp, ManifestResources = managedResources.AsImmutable(), CompilationOptions = options, ParseOptions = IsScriptRunner ? scriptParseOptions : parseOptions, EmitOptions = emitOptions, ScriptArguments = scriptArgs.AsImmutableOrEmpty(), TouchedFilesPath = touchedFilesPath, PrintFullPaths = printFullPaths, ShouldIncludeErrorEndLocation = errorEndLocation, PreferredUILang = preferredUILang, SqmSessionGuid = sqmSessionGuid, ReportAnalyzer = reportAnalyzer }; } private static void ParseAndResolveReferencePaths(string switchName, string switchValue, string baseDirectory, List<string> builder, MessageID origin, List<Diagnostic> diagnostics) { if (string.IsNullOrEmpty(switchValue)) { Debug.Assert(!string.IsNullOrEmpty(switchName)); AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_PathList.Localize(), switchName); return; } foreach (string path in ParseSeparatedPaths(switchValue)) { string resolvedPath = FileUtilities.ResolveRelativePath(path, baseDirectory); if (resolvedPath == null) { AddDiagnostic(diagnostics, ErrorCode.WRN_InvalidSearchPathDir, path, origin.Localize(), MessageID.IDS_DirectoryHasInvalidPath.Localize()); } else if (!PortableShim.Directory.Exists(resolvedPath)) { AddDiagnostic(diagnostics, ErrorCode.WRN_InvalidSearchPathDir, path, origin.Localize(), MessageID.IDS_DirectoryDoesNotExist.Localize()); } else { builder.Add(resolvedPath); } } } private static string GetWin32Setting(string arg, string value, List<Diagnostic> diagnostics) { if (value == null) { AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg); } else { string noQuotes = RemoveQuotesAndSlashes(value); if (string.IsNullOrWhiteSpace(noQuotes)) { AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg); } else { return noQuotes; } } return null; } private void GetCompilationAndModuleNames( List<Diagnostic> diagnostics, OutputKind outputKind, List<CommandLineSourceFile> sourceFiles, bool sourceFilesSpecified, string moduleAssemblyName, ref string outputFileName, ref string moduleName, out string compilationName) { string simpleName; if (outputFileName == null) { // In C#, if the output file name isn't specified explicitly, then executables take their // names from the files containing their entrypoints and libraries derive their names from // their first input files. if (!IsScriptRunner && !sourceFilesSpecified) { AddDiagnostic(diagnostics, ErrorCode.ERR_OutputNeedsName); simpleName = null; } else if (outputKind.IsApplication()) { simpleName = null; } else { simpleName = PathUtilities.RemoveExtension(PathUtilities.GetFileName(sourceFiles.FirstOrDefault().Path)); outputFileName = simpleName + outputKind.GetDefaultExtension(); if (simpleName.Length == 0 && !outputKind.IsNetModule()) { AddDiagnostic(diagnostics, ErrorCode.FTL_InputFileNameTooLong, outputFileName); outputFileName = simpleName = null; } } } else { simpleName = PathUtilities.RemoveExtension(outputFileName); if (simpleName.Length == 0) { AddDiagnostic(diagnostics, ErrorCode.FTL_InputFileNameTooLong, outputFileName); outputFileName = simpleName = null; } } if (outputKind.IsNetModule()) { Debug.Assert(!IsScriptRunner); compilationName = moduleAssemblyName; } else { if (moduleAssemblyName != null) { AddDiagnostic(diagnostics, ErrorCode.ERR_AssemblyNameOnNonModule); } compilationName = simpleName; } if (moduleName == null) { moduleName = outputFileName; } } private static ImmutableArray<string> BuildSearchPaths(string sdkDirectoryOpt, List<string> libPaths) { var builder = ArrayBuilder<string>.GetInstance(); // Match how Dev11 builds the list of search paths // see PCWSTR LangCompiler::GetSearchPath() // current folder first -- base directory is searched by default // Add SDK directory if it is available if (sdkDirectoryOpt != null) { builder.Add(sdkDirectoryOpt); } // libpath builder.AddRange(libPaths); return builder.ToImmutableAndFree(); } public static IEnumerable<string> ParseConditionalCompilationSymbols(string value, out IEnumerable<Diagnostic> diagnostics) { Diagnostic myDiagnostic = null; value = value.TrimEnd(null); // Allow a trailing semicolon or comma in the options if (!value.IsEmpty() && (value.Last() == ';' || value.Last() == ',')) { value = value.Substring(0, value.Length - 1); } string[] values = value.Split(new char[] { ';', ',' } /*, StringSplitOptions.RemoveEmptyEntries*/); var defines = new ArrayBuilder<string>(values.Length); foreach (string id in values) { string trimmedId = id.Trim(); if (SyntaxFacts.IsValidIdentifier(trimmedId)) { defines.Add(trimmedId); } else if (myDiagnostic == null) { myDiagnostic = Diagnostic.Create(CSharp.MessageProvider.Instance, (int)ErrorCode.WRN_DefineIdentifierRequired, trimmedId); } } diagnostics = myDiagnostic == null ? SpecializedCollections.EmptyEnumerable<Diagnostic>() : SpecializedCollections.SingletonEnumerable(myDiagnostic); return defines.AsEnumerable(); } private static Platform ParsePlatform(string value, IList<Diagnostic> diagnostics) { switch (value.ToLowerInvariant()) { case "x86": return Platform.X86; case "x64": return Platform.X64; case "itanium": return Platform.Itanium; case "anycpu": return Platform.AnyCpu; case "anycpu32bitpreferred": return Platform.AnyCpu32BitPreferred; case "arm": return Platform.Arm; default: AddDiagnostic(diagnostics, ErrorCode.ERR_BadPlatformType, value); return Platform.AnyCpu; } } private static OutputKind ParseTarget(string value, IList<Diagnostic> diagnostics) { switch (value.ToLowerInvariant()) { case "exe": return OutputKind.ConsoleApplication; case "winexe": return OutputKind.WindowsApplication; case "library": return OutputKind.DynamicallyLinkedLibrary; case "module": return OutputKind.NetModule; case "appcontainerexe": return OutputKind.WindowsRuntimeApplication; case "winmdobj": return OutputKind.WindowsRuntimeMetadata; default: AddDiagnostic(diagnostics, ErrorCode.FTL_InvalidTarget); return OutputKind.ConsoleApplication; } } private static IEnumerable<string> ParseUsings(string arg, string value, IList<Diagnostic> diagnostics) { if (value.Length == 0) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Namespace1.Localize(), arg); yield break; } foreach (var u in value.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries)) { yield return u; } } private IEnumerable<CommandLineAnalyzerReference> ParseAnalyzers(string arg, string value, List<Diagnostic> diagnostics) { if (value == null) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), arg); yield break; } else if (value.Length == 0) { AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg); yield break; } List<string> paths = ParseSeparatedPaths(value).Where((path) => !string.IsNullOrWhiteSpace(path)).ToList(); foreach (string path in paths) { yield return new CommandLineAnalyzerReference(path); } } private IEnumerable<CommandLineReference> ParseAssemblyReferences(string arg, string value, IList<Diagnostic> diagnostics, bool embedInteropTypes) { if (value == null) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), arg); yield break; } else if (value.Length == 0) { AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg); yield break; } // /r:"reference" // /r:alias=reference // /r:alias="reference" // /r:reference;reference // /r:"path;containing;semicolons" // /r:"unterminated_quotes // /r:"quotes"in"the"middle // /r:alias=reference;reference ... error 2034 // /r:nonidf=reference ... error 1679 int eqlOrQuote = value.IndexOfAny(new[] { '"', '=' }); string alias; if (eqlOrQuote >= 0 && value[eqlOrQuote] == '=') { alias = value.Substring(0, eqlOrQuote); value = value.Substring(eqlOrQuote + 1); if (!SyntaxFacts.IsValidIdentifier(alias)) { AddDiagnostic(diagnostics, ErrorCode.ERR_BadExternIdentifier, alias); yield break; } } else { alias = null; } List<string> paths = ParseSeparatedPaths(value).Where((path) => !string.IsNullOrWhiteSpace(path)).ToList(); if (alias != null) { if (paths.Count > 1) { AddDiagnostic(diagnostics, ErrorCode.ERR_OneAliasPerReference, value); yield break; } if (paths.Count == 0) { AddDiagnostic(diagnostics, ErrorCode.ERR_AliasMissingFile, alias); yield break; } } foreach (string path in paths) { // NOTE(tomat): Dev10 used to report CS1541: ERR_CantIncludeDirectory if the path was a directory. // Since we now support /referencePaths option we would need to search them to see if the resolved path is a directory. var aliases = (alias != null) ? ImmutableArray.Create(alias) : ImmutableArray<string>.Empty; var properties = new MetadataReferenceProperties(MetadataImageKind.Assembly, aliases, embedInteropTypes); yield return new CommandLineReference(path, properties); } } private static void ValidateWin32Settings(string win32ResourceFile, string win32IconResourceFile, string win32ManifestFile, OutputKind outputKind, IList<Diagnostic> diagnostics) { if (win32ResourceFile != null) { if (win32IconResourceFile != null) { AddDiagnostic(diagnostics, ErrorCode.ERR_CantHaveWin32ResAndIcon); } if (win32ManifestFile != null) { AddDiagnostic(diagnostics, ErrorCode.ERR_CantHaveWin32ResAndManifest); } } if (outputKind.IsNetModule() && win32ManifestFile != null) { AddDiagnostic(diagnostics, ErrorCode.WRN_CantHaveManifestForModule); } } internal static ResourceDescription ParseResourceDescription( string arg, string resourceDescriptor, string baseDirectory, IList<Diagnostic> diagnostics, bool embedded) { string filePath; string fullPath; string fileName; string resourceName; string accessibility; ParseResourceDescription( resourceDescriptor, baseDirectory, false, out filePath, out fullPath, out fileName, out resourceName, out accessibility); bool isPublic; if (accessibility == null) { // If no accessibility is given, we default to "public". // NOTE: Dev10 distinguishes between null and empty/whitespace-only. isPublic = true; } else if (string.Equals(accessibility, "public", StringComparison.OrdinalIgnoreCase)) { isPublic = true; } else if (string.Equals(accessibility, "private", StringComparison.OrdinalIgnoreCase)) { isPublic = false; } else { AddDiagnostic(diagnostics, ErrorCode.ERR_BadResourceVis, accessibility); return null; } if (string.IsNullOrEmpty(filePath)) { AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg); return null; } if (fullPath == null || string.IsNullOrWhiteSpace(fileName) || fileName.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0) { AddDiagnostic(diagnostics, ErrorCode.FTL_InputFileNameTooLong, filePath); return null; } Func<Stream> dataProvider = () => { // Use FileShare.ReadWrite because the file could be opened by the current process. // For example, it is an XML doc file produced by the build. return PortableShim.FileStream.Create(fullPath, PortableShim.FileMode.Open, PortableShim.FileAccess.Read, PortableShim.FileShare.ReadWrite); }; return new ResourceDescription(resourceName, fileName, dataProvider, isPublic, embedded, checkArgs: false); } private static bool TryParseLanguageVersion(string str, LanguageVersion defaultVersion, out LanguageVersion version) { if (str == null) { version = defaultVersion; return true; } switch (str.ToLowerInvariant()) { case "iso-1": version = LanguageVersion.CSharp1; return true; case "iso-2": version = LanguageVersion.CSharp2; return true; case "default": version = defaultVersion; return true; default: int versionNumber; if (int.TryParse(str, NumberStyles.None, CultureInfo.InvariantCulture, out versionNumber) && ((LanguageVersion)versionNumber).IsValid()) { version = (LanguageVersion)versionNumber; return true; } version = defaultVersion; return false; } } private static IEnumerable<string> ParseWarnings(string value) { value = value.Unquote(); string[] values = value.Split(new char[] { ',', ';', ' ' }, StringSplitOptions.RemoveEmptyEntries); foreach (string id in values) { ushort number; if (ushort.TryParse(id, NumberStyles.Integer, CultureInfo.InvariantCulture, out number) && ErrorFacts.IsWarning((ErrorCode)number)) { // The id refers to a compiler warning. yield return CSharp.MessageProvider.Instance.GetIdForErrorCode(number); } else { // Previous versions of the compiler used to report a warning (CS1691) // whenever an unrecognized warning code was supplied in /nowarn or // /warnaserror. We no longer generate a warning in such cases. // Instead we assume that the unrecognized id refers to a custom diagnostic. yield return id; } } } private static void AddWarnings(Dictionary<string, ReportDiagnostic> d, ReportDiagnostic kind, IEnumerable<string> items) { foreach (var id in items) { ReportDiagnostic existing; if (d.TryGetValue(id, out existing)) { // Rewrite the existing value with the latest one unless it is for /nowarn. if (existing != ReportDiagnostic.Suppress) d[id] = kind; } else { d.Add(id, kind); } } } private static void UnimplementedSwitch(IList<Diagnostic> diagnostics, string switchName) { AddDiagnostic(diagnostics, ErrorCode.WRN_UnimplementedCommandLineSwitch, "/" + switchName); } internal override void GenerateErrorForNoFilesFoundInRecurse(string path, IList<Diagnostic> diagnostics) { // no error in csc.exe } private static void AddDiagnostic(IList<Diagnostic> diagnostics, ErrorCode errorCode) { diagnostics.Add(Diagnostic.Create(CSharp.MessageProvider.Instance, (int)errorCode)); } private static void AddDiagnostic(IList<Diagnostic> diagnostics, ErrorCode errorCode, params object[] arguments) { diagnostics.Add(Diagnostic.Create(CSharp.MessageProvider.Instance, (int)errorCode, arguments)); } /// <summary> /// Diagnostic for the errorCode added if the warningOptions does not mention suppressed for the errorCode. /// </summary> private static void AddDiagnostic(IList<Diagnostic> diagnostics, Dictionary<string, ReportDiagnostic> warningOptions, ErrorCode errorCode, params object[] arguments) { int code = (int)errorCode; ReportDiagnostic value; warningOptions.TryGetValue(CSharp.MessageProvider.Instance.GetIdForErrorCode(code), out value); if (value != ReportDiagnostic.Suppress) { AddDiagnostic(diagnostics, errorCode, arguments); } } } }
using System; using System.Linq; using System.Linq.Expressions; using Signum.Entities; using Signum.Utilities; using Signum.Engine.Maps; using Signum.Utilities.DataStructures; using System.Collections.ObjectModel; namespace Signum.Engine.Linq { internal class EntityCompleter : DbExpressionVisitor { readonly QueryBinder binder; ImmutableStack<Type> previousTypes = ImmutableStack<Type>.Empty; public EntityCompleter(QueryBinder binder) { this.binder = binder; } public static Expression Complete(Expression source, QueryBinder binder) { EntityCompleter pc = new EntityCompleter(binder); var result = pc.Visit(source); var expandedResul = QueryJoinExpander.ExpandJoins(result, binder, cleanRequests: true); return expandedResul; } protected internal override Expression VisitLiteReference(LiteReferenceExpression lite) { if (lite.EagerEntity) return base.VisitLiteReference(lite); var id = lite.Reference is ImplementedByAllExpression || lite.Reference is ImplementedByExpression && ((ImplementedByExpression)lite.Reference).Implementations.Select(imp=>imp.Value.ExternalId.ValueType.Nullify()).Distinct().Count() > 1 ? (Expression)binder.GetIdString(lite.Reference) : (Expression)binder.GetId(lite.Reference); var typeId = binder.GetEntityType(lite.Reference); var toStr = LiteToString(lite, typeId); return new LiteValueExpression(lite.Type, typeId, id, toStr); } private Expression? LiteToString(LiteReferenceExpression lite, Expression typeId) { if (lite.CustomToStr != null) return Visit(lite.CustomToStr); if (lite.Reference is ImplementedByAllExpression) return null; if (lite.LazyToStr) return null; if (IsCacheable(typeId)) return null; if (lite.Reference is EntityExpression entityExp) { if (entityExp.AvoidExpandOnRetrieving) return null; return binder.BindMethodCall(Expression.Call(entityExp, EntityExpression.ToStringMethod)); } if (lite.Reference is ImplementedByExpression ibe) { if (ibe.Implementations.Any(imp => imp.Value.AvoidExpandOnRetrieving)) return null; return ibe.Implementations.Values.Select(ee => new When(SmartEqualizer.NotEqualNullable(ee.ExternalId, QueryBinder.NullId(ee.ExternalId.ValueType)), binder.BindMethodCall(Expression.Call(ee, EntityExpression.ToStringMethod))) ).ToCondition(typeof(string)); } return binder.BindMethodCall(Expression.Call(lite.Reference, EntityExpression.ToStringMethod)); } private bool IsCacheable(Expression newTypeId) { if (newTypeId is TypeEntityExpression tfie) return IsCached(tfie.TypeValue); if (newTypeId is TypeImplementedByExpression tibe) return tibe.TypeImplementations.All(t => IsCached(t.Key)); return false; } protected internal override Expression VisitEntity(EntityExpression ee) { if (previousTypes.Contains(ee.Type) || IsCached(ee.Type) || ee.AvoidExpandOnRetrieving) { ee = new EntityExpression(ee.Type, ee.ExternalId, null, null, null, null, null /*ee.SystemPeriod TODO*/ , ee.AvoidExpandOnRetrieving); } else ee = binder.Completed(ee); previousTypes = previousTypes.Push(ee.Type); var bindings = VisitBindings(ee.Bindings!); var mixins = Visit(ee.Mixins, VisitMixinEntity); var id = (PrimaryKeyExpression)Visit(ee.ExternalId); var result = new EntityExpression(ee.Type, id, ee.ExternalPeriod, ee.TableAlias, bindings, mixins, ee.TablePeriod, ee.AvoidExpandOnRetrieving); previousTypes = previousTypes.Pop(); return result; } private ReadOnlyCollection<FieldBinding> VisitBindings(ReadOnlyCollection<FieldBinding> bindings) { return bindings.Select(b => { var newB = Visit(b.Binding); if (newB != null) return new FieldBinding(b.FieldInfo, newB); return null; }).NotNull().ToReadOnly(); } protected internal override Expression VisitEmbeddedEntity(EmbeddedEntityExpression eee) { var bindings = VisitBindings(eee.Bindings); var hasValue = Visit(eee.HasValue); if (eee.Bindings != bindings || eee.HasValue != hasValue) { return new EmbeddedEntityExpression(eee.Type, hasValue, bindings, eee.FieldEmbedded, eee.ViewTable); } return eee; } protected internal override MixinEntityExpression VisitMixinEntity(MixinEntityExpression me) { var bindings = VisitBindings(me.Bindings); if (me.Bindings != bindings) { return new MixinEntityExpression(me.Type, bindings, me.MainEntityAlias, me.FieldMixin); } return me; } private bool IsCached(Type type) { var cc = Schema.Current.CacheController(type); if (cc != null && cc.Enabled) { cc.Load(); /*just to force cache before executing the query*/ return true; } return false; } protected internal override Expression VisitMList(MListExpression ml) { var proj = binder.MListProjection(ml, withRowId: true); var newProj = (ProjectionExpression)this.Visit(proj); return new MListProjectionExpression(ml.Type, newProj); } protected internal override Expression VisitAdditionalField(AdditionalFieldExpression afe) { var exp = binder.BindAdditionalField(afe, entityCompleter: true); var newEx = this.Visit(exp); if (newEx is ProjectionExpression newProj && newProj.Projector.Type.IsInstantiationOf(typeof(MList<>.RowIdElement))) return new MListProjectionExpression(afe.Type, newProj); return newEx; } protected internal override Expression VisitProjection(ProjectionExpression proj) { Expression projector; SelectExpression select = proj.Select; using (binder.SetCurrentSource(proj.Select)) projector = this.Visit(proj.Projector); Alias alias = binder.aliasGenerator.NextSelectAlias(); ProjectedColumns pc = ColumnProjector.ProjectColumns(projector, alias); projector = pc.Projector; select = new SelectExpression(alias, false, null, pc.Columns, select, null, null, null, 0); if (projector != proj.Projector) return new ProjectionExpression(select, projector, proj.UniqueFunction, proj.Type); return proj; } } }
using YAF.Lucene.Net.Support; using System.Diagnostics; namespace YAF.Lucene.Net.Codecs.Lucene41 { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using IndexInput = YAF.Lucene.Net.Store.IndexInput; /// <summary> /// Implements the skip list reader for block postings format /// that stores positions and payloads. /// <para/> /// Although this skipper uses MultiLevelSkipListReader as an interface, /// its definition of skip position will be a little different. /// <para/> /// For example, when skipInterval = blockSize = 3, df = 2*skipInterval = 6, /// <para/> /// 0 1 2 3 4 5 /// d d d d d d (posting list) /// ^ ^ (skip point in MultiLeveSkipWriter) /// ^ (skip point in Lucene41SkipWriter) /// <para/> /// In this case, MultiLevelSkipListReader will use the last document as a skip point, /// while Lucene41SkipReader should assume no skip point will comes. /// <para/> /// If we use the interface directly in Lucene41SkipReader, it may silly try to read /// another skip data after the only skip point is loaded. /// <para/> /// To illustrate this, we can call skipTo(d[5]), since skip point d[3] has smaller docId, /// and numSkipped+blockSize== df, the MultiLevelSkipListReader will assume the skip list /// isn't exhausted yet, and try to load a non-existed skip point /// <para/> /// Therefore, we'll trim df before passing it to the interface. see <see cref="Trim(int)"/>. /// </summary> internal sealed class Lucene41SkipReader : MultiLevelSkipListReader { // private boolean DEBUG = Lucene41PostingsReader.DEBUG; private readonly int blockSize; private long[] docPointer; private long[] posPointer; private long[] payPointer; private int[] posBufferUpto; private int[] payloadByteUpto; private long lastPosPointer; private long lastPayPointer; private int lastPayloadByteUpto; private long lastDocPointer; private int lastPosBufferUpto; public Lucene41SkipReader(IndexInput skipStream, int maxSkipLevels, int blockSize, bool hasPos, bool hasOffsets, bool hasPayloads) : base(skipStream, maxSkipLevels, blockSize, 8) { this.blockSize = blockSize; docPointer = new long[maxSkipLevels]; if (hasPos) { posPointer = new long[maxSkipLevels]; posBufferUpto = new int[maxSkipLevels]; if (hasPayloads) { payloadByteUpto = new int[maxSkipLevels]; } else { payloadByteUpto = null; } if (hasOffsets || hasPayloads) { payPointer = new long[maxSkipLevels]; } else { payPointer = null; } } else { posPointer = null; } } /// <summary> /// Trim original docFreq to tell skipReader read proper number of skip points. /// <para/> /// Since our definition in Lucene41Skip* is a little different from MultiLevelSkip* /// this trimmed docFreq will prevent skipReader from: /// 1. silly reading a non-existed skip point after the last block boundary /// 2. moving into the vInt block /// </summary> internal int Trim(int df) { return df % blockSize == 0 ? df - 1 : df; } public void Init(long skipPointer, long docBasePointer, long posBasePointer, long payBasePointer, int df) { base.Init(skipPointer, Trim(df)); lastDocPointer = docBasePointer; lastPosPointer = posBasePointer; lastPayPointer = payBasePointer; Arrays.Fill(docPointer, docBasePointer); if (posPointer != null) { Arrays.Fill(posPointer, posBasePointer); if (payPointer != null) { Arrays.Fill(payPointer, payBasePointer); } } else { Debug.Assert(posBasePointer == 0); } } /// <summary> /// Returns the doc pointer of the doc to which the last call of /// <seealso cref="MultiLevelSkipListReader.SkipTo(int)"/> has skipped. /// </summary> public long DocPointer { get { return lastDocPointer; } } public long PosPointer { get { return lastPosPointer; } } public int PosBufferUpto { get { return lastPosBufferUpto; } } public long PayPointer { get { return lastPayPointer; } } public int PayloadByteUpto { get { return lastPayloadByteUpto; } } public int NextSkipDoc { get { return m_skipDoc[0]; } } protected override void SeekChild(int level) { base.SeekChild(level); // if (DEBUG) { // System.out.println("seekChild level=" + level); // } docPointer[level] = lastDocPointer; if (posPointer != null) { posPointer[level] = lastPosPointer; posBufferUpto[level] = lastPosBufferUpto; if (payloadByteUpto != null) { payloadByteUpto[level] = lastPayloadByteUpto; } if (payPointer != null) { payPointer[level] = lastPayPointer; } } } protected override void SetLastSkipData(int level) { base.SetLastSkipData(level); lastDocPointer = docPointer[level]; // if (DEBUG) { // System.out.println("setLastSkipData level=" + value); // System.out.println(" lastDocPointer=" + lastDocPointer); // } if (posPointer != null) { lastPosPointer = posPointer[level]; lastPosBufferUpto = posBufferUpto[level]; // if (DEBUG) { // System.out.println(" lastPosPointer=" + lastPosPointer + " lastPosBUfferUpto=" + lastPosBufferUpto); // } if (payPointer != null) { lastPayPointer = payPointer[level]; } if (payloadByteUpto != null) { lastPayloadByteUpto = payloadByteUpto[level]; } } } protected override int ReadSkipData(int level, IndexInput skipStream) { // if (DEBUG) { // System.out.println("readSkipData level=" + level); // } int delta = skipStream.ReadVInt32(); // if (DEBUG) { // System.out.println(" delta=" + delta); // } docPointer[level] += skipStream.ReadVInt32(); // if (DEBUG) { // System.out.println(" docFP=" + docPointer[level]); // } if (posPointer != null) { posPointer[level] += skipStream.ReadVInt32(); // if (DEBUG) { // System.out.println(" posFP=" + posPointer[level]); // } posBufferUpto[level] = skipStream.ReadVInt32(); // if (DEBUG) { // System.out.println(" posBufferUpto=" + posBufferUpto[level]); // } if (payloadByteUpto != null) { payloadByteUpto[level] = skipStream.ReadVInt32(); } if (payPointer != null) { payPointer[level] += skipStream.ReadVInt32(); } } return delta; } } }
// DescriptorCollection.cs // Copyright (C) 2004 Mike Krueger // // This program is free software. It is dual licensed under GNU GPL and GNU LGPL. // See COPYING_GPL.txt and COPYING_LGPL.txt for details. // using System; using System.Collections; namespace ICSharpCode.USBlib { /// <summary> /// A collection that stores <see cref='Descriptor'/> objects. /// </summary> [Serializable()] public class DescriptorCollection : CollectionBase { /// <summary> /// Initializes a new instance of <see cref='DescriptorCollection'/>. /// </summary> public DescriptorCollection() { } /// <summary> /// Initializes a new instance of <see cref='DescriptorCollection'/> based on another <see cref='DescriptorCollection'/>. /// </summary> /// <param name='val'> /// A <see cref='DescriptorCollection'/> from which the contents are copied /// </param> public DescriptorCollection(DescriptorCollection val) { this.AddRange(val); } /// <summary> /// Initializes a new instance of <see cref='DescriptorCollection'/> containing any array of <see cref='Descriptor'/> objects. /// </summary> /// <param name='val'> /// A array of <see cref='Descriptor'/> objects with which to intialize the collection /// </param> public DescriptorCollection(Descriptor[] val) { this.AddRange(val); } /// <summary> /// Represents the entry at the specified index of the <see cref='Descriptor'/>. /// </summary> /// <param name='index'>The zero-based index of the entry to locate in the collection.</param> /// <value>The entry at the specified index of the collection.</value> /// <exception cref='ArgumentOutOfRangeException'><paramref name='index'/> is outside the valid range of indexes for the collection.</exception> public Descriptor this[int index] { get { return ((Descriptor)(List[index])); } set { List[index] = value; } } /// <summary> /// Adds a <see cref='Descriptor'/> with the specified value to the /// <see cref='DescriptorCollection'/>. /// </summary> /// <param name='val'>The <see cref='Descriptor'/> to add.</param> /// <returns>The index at which the new element was inserted.</returns> /// <seealso cref='DescriptorCollection.AddRange'/> public int Add(Descriptor val) { return List.Add(val); } /// <summary> /// Copies the elements of an array to the end of the <see cref='DescriptorCollection'/>. /// </summary> /// <param name='val'> /// An array of type <see cref='Descriptor'/> containing the objects to add to the collection. /// </param> /// <seealso cref='DescriptorCollection.Add'/> public void AddRange(Descriptor[] val) { for (int i = 0; i < val.Length; i++) { this.Add(val[i]); } } /// <summary> /// Adds the contents of another <see cref='DescriptorCollection'/> to the end of the collection. /// </summary> /// <param name='val'> /// A <see cref='DescriptorCollection'/> containing the objects to add to the collection. /// </param> /// <seealso cref='DescriptorCollection.Add'/> public void AddRange(DescriptorCollection val) { for (int i = 0; i < val.Count; i++) { this.Add(val[i]); } } /// <summary> /// Gets a value indicating whether the /// <see cref='DescriptorCollection'/> contains the specified <see cref='Descriptor'/>. /// </summary> /// <param name='val'>The <see cref='Descriptor'/> to locate.</param> /// <returns> /// <see langword='true'/> if the <see cref='Descriptor'/> is contained in the collection; /// otherwise, <see langword='false'/>. /// </returns> /// <seealso cref='DescriptorCollection.IndexOf'/> public bool Contains(Descriptor val) { return List.Contains(val); } /// <summary> /// Copies the <see cref='DescriptorCollection'/> values to a one-dimensional <see cref='Array'/> instance at the /// specified index. /// </summary> /// <param name='array'>The one-dimensional <see cref='Array'/> that is the destination of the values copied from <see cref='DescriptorCollection'/>.</param> /// <param name='index'>The index in <paramref name='array'/> where copying begins.</param> /// <exception cref='ArgumentException'> /// <para><paramref name='array'/> is multidimensional.</para> /// <para>-or-</para> /// <para>The number of elements in the <see cref='DescriptorCollection'/> is greater than /// the available space between <paramref name='arrayIndex'/> and the end of /// <paramref name='array'/>.</para> /// </exception> /// <exception cref='ArgumentNullException'><paramref name='array'/> is <see langword='null'/>. </exception> /// <exception cref='ArgumentOutOfRangeException'><paramref name='arrayIndex'/> is less than <paramref name='array'/>'s lowbound. </exception> /// <seealso cref='Array'/> public void CopyTo(Descriptor[] array, int index) { List.CopyTo(array, index); } /// <summary> /// Returns the index of a <see cref='Descriptor'/> in /// the <see cref='DescriptorCollection'/>. /// </summary> /// <param name='val'>The <see cref='Descriptor'/> to locate.</param> /// <returns> /// The index of the <see cref='Descriptor'/> of <paramref name='val'/> in the /// <see cref='DescriptorCollection'/>, if found; otherwise, -1. /// </returns> /// <seealso cref='DescriptorCollection.Contains'/> public int IndexOf(Descriptor val) { return List.IndexOf(val); } /// <summary> /// Inserts a <see cref='Descriptor'/> into the <see cref='DescriptorCollection'/> at the specified index. /// </summary> /// <param name='index'>The zero-based index where <paramref name='val'/> should be inserted.</param> /// <param name='val'>The <see cref='Descriptor'/> to insert.</param> /// <seealso cref='DescriptorCollection.Add'/> public void Insert(int index, Descriptor val) { List.Insert(index, val); } /// <summary> /// Returns an enumerator that can iterate through the <see cref='DescriptorCollection'/>. /// </summary> /// <seealso cref='IEnumerator'/> public new DescriptorEnumerator GetEnumerator() { return new DescriptorEnumerator(this); } /// <summary> /// Removes a specific <see cref='Descriptor'/> from the <see cref='DescriptorCollection'/>. /// </summary> /// <param name='val'>The <see cref='Descriptor'/> to remove from the <see cref='DescriptorCollection'/>.</param> /// <exception cref='ArgumentException'><paramref name='val'/> is not found in the Collection.</exception> public void Remove(Descriptor val) { List.Remove(val); } /// <summary> /// Enumerator that can iterate through a DescriptorCollection. /// </summary> /// <seealso cref='IEnumerator'/> /// <seealso cref='DescriptorCollection'/> /// <seealso cref='Descriptor'/> public class DescriptorEnumerator : IEnumerator { IEnumerator baseEnumerator; IEnumerable temp; /// <summary> /// Initializes a new instance of <see cref='DescriptorEnumerator'/>. /// </summary> public DescriptorEnumerator(DescriptorCollection mappings) { this.temp = ((IEnumerable)(mappings)); this.baseEnumerator = temp.GetEnumerator(); } /// <summary> /// Gets the current <see cref='Descriptor'/> in the <seealso cref='DescriptorCollection'/>. /// </summary> public Descriptor Current { get { return ((Descriptor)(baseEnumerator.Current)); } } object IEnumerator.Current { get { return baseEnumerator.Current; } } /// <summary> /// Advances the enumerator to the next <see cref='Descriptor'/> of the <see cref='DescriptorCollection'/>. /// </summary> public bool MoveNext() { return baseEnumerator.MoveNext(); } /// <summary> /// Sets the enumerator to its initial position, which is before the first element in the <see cref='DescriptorCollection'/>. /// </summary> public void Reset() { baseEnumerator.Reset(); } } } }
// *********************************************************************** // Copyright (c) 2012-2015 Charlie Poole // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** using System; using System.Reflection; using NUnit.Framework.Compatibility; using NUnit.Framework.Interfaces; namespace NUnit.Framework.Internal { /// <summary> /// The Test abstract class represents a test within the framework. /// </summary> public abstract class Test : ITest, IComparable { #region Fields /// <summary> /// Static value to seed ids. It's started at 1000 so any /// uninitialized ids will stand out. /// </summary> private static int _nextID = 1000; /// <summary> /// The SetUp methods. /// </summary> protected MethodInfo[] setUpMethods; /// <summary> /// The teardown methods /// </summary> protected MethodInfo[] tearDownMethods; #endregion #region Construction /// <summary> /// Constructs a test given its name /// </summary> /// <param name="name">The name of the test</param> protected Test( string name ) { Guard.ArgumentNotNullOrEmpty(name, "name"); Initialize(name); } /// <summary> /// Constructs a test given the path through the /// test hierarchy to its parent and a name. /// </summary> /// <param name="pathName">The parent tests full name</param> /// <param name="name">The name of the test</param> protected Test( string pathName, string name ) { Guard.ArgumentNotNullOrEmpty(pathName, "pathName"); Initialize(name); FullName = pathName + "." + name; } /// <summary> /// TODO: Documentation needed for constructor /// </summary> /// <param name="typeInfo"></param> protected Test(ITypeInfo typeInfo) { Initialize(typeInfo.GetDisplayName()); string nspace = typeInfo.Namespace; if (nspace != null && nspace != "") FullName = nspace + "." + Name; TypeInfo = typeInfo; } /// <summary> /// Construct a test from a MethodInfo /// </summary> /// <param name="method"></param> protected Test(IMethodInfo method) { Initialize(method.Name); Method = method; TypeInfo = method.TypeInfo; FullName = method.TypeInfo.FullName + "." + Name; } private void Initialize(string name) { FullName = Name = name; Id = GetNextId(); Properties = new PropertyBag(); RunState = RunState.Runnable; } private static string GetNextId() { return IdPrefix + unchecked(_nextID++); } #endregion #region ITest Members /// <summary> /// Gets or sets the id of the test /// </summary> /// <value></value> public string Id { get; set; } /// <summary> /// Gets or sets the name of the test /// </summary> public string Name { get; set; } /// <summary> /// Gets or sets the fully qualified name of the test /// </summary> /// <value></value> public string FullName { get; set; } /// <summary> /// Gets the name of the class containing this test. Returns /// null if the test is not associated with a class. /// </summary> public string ClassName { get { if (TypeInfo == null) return null; return TypeInfo.IsGenericType ? TypeInfo.GetGenericTypeDefinition().FullName : TypeInfo.FullName; } } /// <summary> /// Gets the name of the method implementing this test. /// Returns null if the test is not implemented as a method. /// </summary> public virtual string MethodName { get { return null; } } /// <summary> /// Gets the TypeInfo of the fixture used in running this test /// or null if no fixture type is associated with it. /// </summary> public ITypeInfo TypeInfo { get; private set; } /// <summary> /// Gets a MethodInfo for the method implementing this test. /// Returns null if the test is not implemented as a method. /// </summary> public IMethodInfo Method { get; set; } // public setter needed by NUnitTestCaseBuilder /// <summary> /// Whether or not the test should be run /// </summary> public RunState RunState { get; set; } /// <summary> /// Gets the name used for the top-level element in the /// XML representation of this test /// </summary> public abstract string XmlElementName { get; } /// <summary> /// Gets a string representing the type of test. Used as an attribute /// value in the XML representation of a test and has no other /// function in the framework. /// </summary> public virtual string TestType { get { return this.GetType().Name; } } /// <summary> /// Gets a count of test cases represented by /// or contained under this test. /// </summary> public virtual int TestCaseCount { get { return 1; } } /// <summary> /// Gets the properties for this test /// </summary> public IPropertyBag Properties { get; private set; } /// <summary> /// Returns true if this is a TestSuite /// </summary> public bool IsSuite { get { return this is TestSuite; } } /// <summary> /// Gets a bool indicating whether the current test /// has any descendant tests. /// </summary> public abstract bool HasChildren { get; } /// <summary> /// Gets the parent as a Test object. /// Used by the core to set the parent. /// </summary> public ITest Parent { get; set; } /// <summary> /// Gets this test's child tests /// </summary> /// <value>A list of child tests</value> public abstract System.Collections.Generic.IList<ITest> Tests { get; } /// <summary> /// Gets or sets a fixture object for running this test. /// </summary> public virtual object Fixture { get; set; } #endregion #region Other Public Properties /// <summary> /// Static prefix used for ids in this AppDomain. /// Set by FrameworkController. /// </summary> public static string IdPrefix { get; set; } /// <summary> /// Gets or Sets the Int value representing the seed for the RandomGenerator /// </summary> /// <value></value> public int Seed { get; set; } #endregion #region Internal Properties internal bool RequiresThread { get; set; } internal bool IsAsynchronous { get; set; } #endregion #region Other Public Methods /// <summary> /// Creates a TestResult for this test. /// </summary> /// <returns>A TestResult suitable for this type of test.</returns> public abstract TestResult MakeTestResult(); #if PORTABLE /// <summary> /// Modify a newly constructed test by applying any of NUnit's common /// attributes, based on a supplied ICustomAttributeProvider, which is /// usually the reflection element from which the test was constructed, /// but may not be in some instances. The attributes retrieved are /// saved for use in subsequent operations. /// </summary> /// <param name="provider">An object deriving from MemberInfo</param> public void ApplyAttributesToTest(MemberInfo provider) { foreach (IApplyToTest iApply in provider.GetAttributes<IApplyToTest>(true)) iApply.ApplyToTest(this); } /// <summary> /// Modify a newly constructed test by applying any of NUnit's common /// attributes, based on a supplied ICustomAttributeProvider, which is /// usually the reflection element from which the test was constructed, /// but may not be in some instances. The attributes retrieved are /// saved for use in subsequent operations. /// </summary> /// <param name="provider">An object deriving from MemberInfo</param> public void ApplyAttributesToTest(Assembly provider) { foreach (IApplyToTest iApply in provider.GetAttributes<IApplyToTest>()) iApply.ApplyToTest(this); } #else /// <summary> /// Modify a newly constructed test by applying any of NUnit's common /// attributes, based on a supplied ICustomAttributeProvider, which is /// usually the reflection element from which the test was constructed, /// but may not be in some instances. The attributes retrieved are /// saved for use in subsequent operations. /// </summary> /// <param name="provider">An object implementing ICustomAttributeProvider</param> public void ApplyAttributesToTest(ICustomAttributeProvider provider) { foreach (IApplyToTest iApply in provider.GetCustomAttributes(typeof(IApplyToTest), true)) iApply.ApplyToTest(this); } #endif #endregion #region Protected Methods /// <summary> /// Add standard attributes and members to a test node. /// </summary> /// <param name="thisNode"></param> /// <param name="recursive"></param> protected void PopulateTestNode(TNode thisNode, bool recursive) { thisNode.AddAttribute("id", this.Id.ToString()); thisNode.AddAttribute("name", this.Name); thisNode.AddAttribute("fullname", this.FullName); if (this.MethodName != null) thisNode.AddAttribute("methodname", this.MethodName); if (this.ClassName != null) thisNode.AddAttribute("classname", this.ClassName); thisNode.AddAttribute("runstate", this.RunState.ToString()); if (Properties.Keys.Count > 0) Properties.AddToXml(thisNode, recursive); } #endregion #region IXmlNodeBuilder Members /// <summary> /// Returns the Xml representation of the test /// </summary> /// <param name="recursive">If true, include child tests recursively</param> /// <returns></returns> public TNode ToXml(bool recursive) { return AddToXml(new TNode("dummy"), recursive); } /// <summary> /// Returns an XmlNode representing the current result after /// adding it as a child of the supplied parent node. /// </summary> /// <param name="parentNode">The parent node.</param> /// <param name="recursive">If true, descendant results are included</param> /// <returns></returns> public abstract TNode AddToXml(TNode parentNode, bool recursive); #endregion #region IComparable Members /// <summary> /// Compares this test to another test for sorting purposes /// </summary> /// <param name="obj">The other test</param> /// <returns>Value of -1, 0 or +1 depending on whether the current test is less than, equal to or greater than the other test</returns> public int CompareTo(object obj) { Test other = obj as Test; if (other == null) return -1; return this.FullName.CompareTo(other.FullName); } #endregion } }
/* Copyright (c) 2006 Tomas Matousek. The use and distribution terms for this software are contained in the file named License.txt, which can be found in the root of the Phalanger distribution. By using this software in any fashion, you are agreeing to be bound by the terms of this license. You must not remove this notice from this software. TODO: filter - see url_scanner_ex.c session starts rewriter (session.use_trans_sid) url_rewriter.tags */ using System; using System.Web; using System.Net; using System.Text; using System.Text.RegularExpressions; using System.Collections; using System.Collections.Generic; using PHP.Core; using System.Diagnostics; namespace PHP.Library { public sealed class UrlRewriter { #region Construction and Properties private UrlRewriter() { } private Dictionary<string, string> Variables { get { if (_variables == null) _variables = new Dictionary<string, string>(); return _variables; } } private Dictionary<string, string> _variables; // GENERICS private PhpCallback filterCallback; private PhpCallback/*!*/ GetOrCreateFilterCallback(ScriptContext/*!*/ context) { if (filterCallback == null) filterCallback = new PhpCallback(new RoutineDelegate(Filter), context); return filterCallback; } #endregion #region object #endregion #region Filter /// <summary> /// Tags parser, modifies the specified elements in the HTML code. /// </summary> private class TagsUrlRewriter: UrlRewriterTagsParser { public TagsUrlRewriter(UrlRewriter rewriter) { this.rewriter = rewriter; } private readonly UrlRewriter rewriter; Regex protocolPattern = new Regex(@"^[a-zA-Z]+:(\\|//).*", RegexOptions.Compiled); protected override void OnTagAttribute(string tagName, ref string attributeName, ref string attributeValue, ref char attributeValueQuote) { string[] attrs; if (ScriptContext.CurrentContext.Config.Session.UrlRewriterTags.TryGetValue(tagName.ToLower(), out attrs)) { for (int i = 0; i < attrs.Length; i++) { if (string.Equals(attrs[i], attributeName, StringComparison.InvariantCultureIgnoreCase)) { if (protocolPattern.IsMatch(attributeValue)) return; // the URL must NOT be an absolute URL (not start with the protocol name) // modify attribute value if (attributeValue.Contains("?")) attributeValue += "&"; else attributeValue += "?"; bool bFirst = true; foreach (KeyValuePair<string, string> item in rewriter.Variables) { if (bFirst) bFirst = false; else attributeValue += "&"; attributeValue += item.Key + "=" + item.Value; } return; } } } } protected override void OnTagElement(string tagName, ref string tagString) { // modify the "form" element const string strFormTag = "form"; if ( string.Compare(tagName, strFormTag, StringComparison.InvariantCultureIgnoreCase) == 0 && ScriptContext.CurrentContext.Config.Session.UrlRewriterTags.ContainsKey(strFormTag) ) { foreach (KeyValuePair<string, string> item in rewriter.Variables) tagString += string.Format("<input type=\"hidden\" name=\"{0}\" value=\"{1}\" />", item.Key, item.Value); } } } private TagsUrlRewriter parser; private TagsUrlRewriter.ParserState parserState = new TagsUrlRewriter.ParserState(); private object Filter(object instance, PhpStack/*!*/ stack) { StringBuilder result = new StringBuilder(); Debug.Assert(stack.ArgCount >= 1, "Called by output buffering, so should be ok"); string data = PhpVariable.AsString(stack.PeekValueUnchecked(1)); stack.RemoveFrame(); // parse the text if (parser == null) parser = new TagsUrlRewriter(this); return parser.ParseHtml(parserState, data); } #endregion #region output_add_rewrite_var, output_reset_rewrite_vars [ImplementsFunction("output_add_rewrite_var")] public static bool AddRewriteVariable(string name, string value) { if (String.IsNullOrEmpty(name)) { PhpException.InvalidArgument("name", LibResources.GetString("arg:null_or_empty")); return false; } ScriptContext context = ScriptContext.CurrentContext; UrlRewriter rewriter = context.Properties.GetOrCreateProperty(() => new UrlRewriter()); BufferedOutput output = context.BufferedOutput; // some output flush output.Flush(); rewriter.Variables[name] = value; // start UrlRewriter filtering if not yet if (output.FindLevelByFilter( rewriter.filterCallback ) < 0) { // create new output buffer level (URL-Rewriter is not started yet) int Level = output.IncreaseLevel(); output.SetFilter(rewriter.GetOrCreateFilterCallback(context), Level); output.SetLevelName(Level, "URL-Rewriter"); } context.IsOutputBuffered = true; // turn on output buffering if not yet return true; } [ImplementsFunction("output_reset_rewrite_vars")] public static bool ResetRewriteVariables() { /*PhpException.FunctionNotSupported(); return false;*/ ScriptContext context = ScriptContext.CurrentContext; UrlRewriter rewriter; if (context.Properties.TryGetProperty<UrlRewriter>(out rewriter) == false) return false; BufferedOutput output = context.BufferedOutput; if (output.Level == 0 || output.GetFilter() != rewriter.filterCallback) return false; // some output flush output.Flush(); rewriter.Variables.Clear(); output.DecreaseLevel(false); if (output.Level == 0) context.IsOutputBuffered = 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 Gnx.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 2010-2014 Google // 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 Google.OrTools.ConstraintSolver { using System; using System.Collections.Generic; public partial class Solver : IDisposable { public IntVar[] MakeIntVarArray(int count, long min, long max) { IntVar[] array = new IntVar[count]; for (int i = 0; i < count; ++i) { array[i] = MakeIntVar(min, max); } return array; } public IntVar[] MakeIntVarArray(int count, long min, long max, string name) { IntVar[] array = new IntVar[count]; for (int i = 0; i < count; ++i) { string var_name = name + i; array[i] = MakeIntVar(min, max, var_name); } return array; } public IntVar[] MakeIntVarArray(int count, long[] values) { IntVar[] array = new IntVar[count]; for (int i = 0; i < count; ++i) { array[i] = MakeIntVar(values); } return array; } public IntVar[] MakeIntVarArray(int count, long[] values, string name) { IntVar[] array = new IntVar[count]; for (int i = 0; i < count; ++i) { string var_name = name + i; array[i] = MakeIntVar(values, var_name); } return array; } public IntVar[] MakeIntVarArray(int count, int[] values) { IntVar[] array = new IntVar[count]; for (int i = 0; i < count; ++i) { array[i] = MakeIntVar(values); } return array; } public IntVar[] MakeIntVarArray(int count, int[] values, string name) { IntVar[] array = new IntVar[count]; for (int i = 0; i < count; ++i) { string var_name = name + i; array[i] = MakeIntVar(values, var_name); } return array; } public IntVar[] MakeBoolVarArray(int count) { IntVar[] array = new IntVar[count]; for (int i = 0; i < count; ++i) { array[i] = MakeBoolVar(); } return array; } public IntVar[] MakeBoolVarArray(int count, string name) { IntVar[] array = new IntVar[count]; for (int i = 0; i < count; ++i) { string var_name = name + i; array[i] = MakeBoolVar(var_name); } return array; } public IntVar[,] MakeIntVarMatrix(int rows, int cols, long min, long max) { IntVar[,] array = new IntVar[rows, cols]; for (int i = 0; i < rows; ++i) { for (int j = 0; j < cols; ++j) { array[i,j] = MakeIntVar(min, max); } } return array; } public IntVar[,] MakeIntVarMatrix(int rows, int cols, long min, long max, string name) { IntVar[,] array = new IntVar[rows, cols]; for (int i = 0; i < rows; ++i) { for (int j = 0; j < cols; ++j) { string var_name = name + "["+ i + ", " + j +"]"; array[i,j] = MakeIntVar(min, max, var_name); } } return array; } public IntVar[,] MakeIntVarMatrix(int rows, int cols, long[] values) { IntVar[,] array = new IntVar[rows, cols]; for (int i = 0; i < rows; ++i) { for (int j = 0; j < cols; ++j) { array[i,j] = MakeIntVar(values); } } return array; } public IntVar[,] MakeIntVarMatrix(int rows, int cols, long[] values, string name) { IntVar[,] array = new IntVar[rows, cols]; for (int i = 0; i < rows; ++i) { for (int j = 0; j < cols; ++j) { string var_name = name + "["+ i + ", " + j +"]"; array[i,j] = MakeIntVar(values, var_name); } } return array; } public IntVar[,] MakeIntVarMatrix(int rows, int cols, int[] values) { IntVar[,] array = new IntVar[rows, cols]; for (int i = 0; i < rows; ++i) { for (int j = 0; j < cols; ++j) { array[i,j] = MakeIntVar(values); } } return array; } public IntVar[,] MakeIntVarMatrix(int rows, int cols, int[] values, string name) { IntVar[,] array = new IntVar[rows, cols]; for (int i = 0; i < rows; ++i) { for (int j = 0; j < cols; ++j) { string var_name = name + "["+ i + ", " + j +"]"; array[i,j] = MakeIntVar(values, var_name); } } return array; } public IntVar[,] MakeBoolVarMatrix(int rows, int cols) { IntVar[,] array = new IntVar[rows, cols]; for (int i = 0; i < rows; ++i) { for (int j = 0; j < cols; ++j) { array[i,j] = MakeBoolVar(); } } return array; } public IntVar[,] MakeBoolVarMatrix(int rows, int cols, string name) { IntVar[,] array = new IntVar[rows, cols]; for (int i = 0; i < rows; ++i) { for (int j = 0; j < cols; ++j) { string var_name = name + "["+ i + ", " + j +"]"; array[i,j] = MakeBoolVar(var_name); } } return array; } public IntervalVar[] MakeFixedDurationIntervalVarArray(int count, long start_min, long start_max, long duration, bool optional) { IntervalVar[] array = new IntervalVar[count]; for (int i = 0; i < count; ++i) { array[i] = MakeFixedDurationIntervalVar(start_min, start_max, duration, optional, ""); } return array; } public IntervalVar[] MakeFixedDurationIntervalVarArray(int count, long start_min, long start_max, long duration, bool optional, string name) { IntervalVar[] array = new IntervalVar[count]; for (int i = 0; i < count; ++i) { array[i] = MakeFixedDurationIntervalVar(start_min, start_max, duration, optional, name + i); } return array; } public IntervalVar[] MakeFixedDurationIntervalVarArray(int count, long[] start_min, long[] start_max, long[] duration, bool optional, string name) { IntervalVar[] array = new IntervalVar[count]; for (int i = 0; i < count; ++i) { array[i] = MakeFixedDurationIntervalVar(start_min[i], start_max[i], duration[i], optional, name + i); } return array; } public IntervalVar[] MakeFixedDurationIntervalVarArray(int count, int[] start_min, int[] start_max, int[] duration, bool optional, string name) { IntervalVar[] array = new IntervalVar[count]; for (int i = 0; i < count; ++i) { array[i] = MakeFixedDurationIntervalVar(start_min[i], start_max[i], duration[i], optional, name + i); } return array; } public IntervalVar[] MakeFixedDurationIntervalVarArray(IntVar[] starts, int[] durations, string name) { int count = starts.Length; IntervalVar[] array = new IntervalVar[count]; for (int i = 0; i < count; ++i) { array[i] = MakeFixedDurationIntervalVar(starts[i], durations[i], name + i); } return array; } public IntervalVar[] MakeFixedDurationIntervalVarArray(IntVar[] starts, long[] durations, string name) { int count = starts.Length; IntervalVar[] array = new IntervalVar[count]; for (int i = 0; i < count; ++i) { array[i] = MakeFixedDurationIntervalVar(starts[i], durations[i], name + i); } return array; } public void NewSearch(DecisionBuilder db) { pinned_decision_builder_ = db; pinned_search_monitors_.Clear(); NewSearchAux(db); } public void NewSearch(DecisionBuilder db, SearchMonitor sm1) { pinned_decision_builder_ = db; pinned_search_monitors_.Clear(); pinned_search_monitors_.Add(sm1); NewSearchAux(db, sm1); } public void NewSearch(DecisionBuilder db, SearchMonitor sm1, SearchMonitor sm2) { pinned_decision_builder_ = db; pinned_search_monitors_.Clear(); pinned_search_monitors_.Add(sm1); pinned_search_monitors_.Add(sm2); NewSearchAux(db, sm1, sm2); } public void NewSearch(DecisionBuilder db, SearchMonitor sm1, SearchMonitor sm2, SearchMonitor sm3) { pinned_decision_builder_ = db; pinned_search_monitors_.Clear(); pinned_search_monitors_.Add(sm1); pinned_search_monitors_.Add(sm2); pinned_search_monitors_.Add(sm3); NewSearchAux(db, sm1, sm2, sm3); } public void NewSearch(DecisionBuilder db, SearchMonitor sm1, SearchMonitor sm2, SearchMonitor sm3, SearchMonitor sm4) { pinned_decision_builder_ = db; pinned_search_monitors_.Clear(); pinned_search_monitors_.Add(sm1); pinned_search_monitors_.Add(sm2); pinned_search_monitors_.Add(sm3); pinned_search_monitors_.Add(sm4); NewSearchAux(db, sm1, sm2, sm3, sm4); } public void NewSearch(DecisionBuilder db, SearchMonitor[] monitors) { pinned_decision_builder_ = db; pinned_search_monitors_.Clear(); pinned_search_monitors_.AddRange(monitors); NewSearchAux(db, monitors); } public void EndSearch() { pinned_decision_builder_ = null; pinned_search_monitors_.Clear(); EndSearchAux(); } private System.Collections.Generic.List<SearchMonitor> pinned_search_monitors_ = new System.Collections.Generic.List<SearchMonitor>(); private DecisionBuilder pinned_decision_builder_; } public partial class IntExpr : PropagationBaseObject { public static IntExpr operator+(IntExpr a, IntExpr b) { return a.solver().MakeSum(a, b); } public static IntExpr operator+(IntExpr a, long v) { return a.solver().MakeSum(a, v); } public static IntExpr operator+(long v, IntExpr a) { return a.solver().MakeSum(a, v); } public static IntExpr operator-(IntExpr a, IntExpr b) { return a.solver().MakeDifference(a, b); } public static IntExpr operator-(IntExpr a, long v) { return a.solver().MakeSum(a, -v); } public static IntExpr operator-(long v, IntExpr a) { return a.solver().MakeDifference(v, a); } public static IntExpr operator*(IntExpr a, IntExpr b) { return a.solver().MakeProd(a, b); } public static IntExpr operator*(IntExpr a, long v) { return a.solver().MakeProd(a, v); } public static IntExpr operator*(long v, IntExpr a) { return a.solver().MakeProd(a, v); } public static IntExpr operator/(IntExpr a, long v) { return a.solver().MakeDiv(a, v); } public static IntExpr operator%(IntExpr a, long v) { return a.solver().MakeModulo(a, v); } public static IntExpr operator-(IntExpr a) { return a.solver().MakeOpposite(a); } public IntExpr Abs() { return this.solver().MakeAbs(this); } public IntExpr Square() { return this.solver().MakeSquare(this); } public static IntExprEquality operator ==(IntExpr a, IntExpr b) { return new IntExprEquality(a, b, true); } public static IntExprEquality operator !=(IntExpr a, IntExpr b) { return new IntExprEquality(a, b, false); } public static WrappedConstraint operator ==(IntExpr a, long v) { return new WrappedConstraint(a.solver().MakeEquality(a, v)); } public static WrappedConstraint operator !=(IntExpr a, long v) { return new WrappedConstraint(a.solver().MakeNonEquality(a.Var(), v)); } public static WrappedConstraint operator >=(IntExpr a, long v) { return new WrappedConstraint(a.solver().MakeGreaterOrEqual(a, v)); } public static WrappedConstraint operator >(IntExpr a, long v) { return new WrappedConstraint(a.solver().MakeGreater(a, v)); } public static WrappedConstraint operator <=(IntExpr a, long v) { return new WrappedConstraint(a.solver().MakeLessOrEqual(a, v)); } public static WrappedConstraint operator <(IntExpr a, long v) { return new WrappedConstraint(a.solver().MakeLess(a, v)); } public static WrappedConstraint operator >=(IntExpr a, IntExpr b) { return new WrappedConstraint(a.solver().MakeGreaterOrEqual(a.Var(), b.Var())); } public static WrappedConstraint operator >(IntExpr a, IntExpr b) { return new WrappedConstraint(a.solver().MakeGreater(a.Var(), b.Var())); } public static WrappedConstraint operator <=(IntExpr a, IntExpr b) { return new WrappedConstraint(a.solver().MakeLessOrEqual(a.Var(), b.Var())); } public static WrappedConstraint operator <(IntExpr a, IntExpr b) { return new WrappedConstraint(a.solver().MakeLess(a.Var(), b.Var())); } } public partial class Constraint : PropagationBaseObject, IConstraintWithStatus { public static implicit operator IntVar(Constraint eq) { return eq.Var(); } public static implicit operator IntExpr(Constraint eq) { return eq.Var(); } public static IntExpr operator+(Constraint a, Constraint b) { return a.solver().MakeSum(a.Var(), b.Var()); } public static IntExpr operator+(Constraint a, long v) { return a.solver().MakeSum(a.Var(), v); } public static IntExpr operator+(long v, Constraint a) { return a.solver().MakeSum(a.Var(), v); } public static IntExpr operator-(Constraint a, Constraint b) { return a.solver().MakeDifference(a.Var(), b.Var()); } public static IntExpr operator-(Constraint a, long v) { return a.solver().MakeSum(a.Var(), -v); } public static IntExpr operator-(long v, Constraint a) { return a.solver().MakeDifference(v, a.Var()); } public static IntExpr operator*(Constraint a, Constraint b) { return a.solver().MakeProd(a.Var(), b.Var()); } public static IntExpr operator*(Constraint a, long v) { return a.solver().MakeProd(a.Var(), v); } public static IntExpr operator*(long v, Constraint a) { return a.solver().MakeProd(a.Var(), v); } public static IntExpr operator/(Constraint a, long v) { return a.solver().MakeDiv(a.Var(), v); } public static IntExpr operator-(Constraint a) { return a.solver().MakeOpposite(a.Var()); } public IntExpr Abs() { return this.solver().MakeAbs(this.Var()); } public IntExpr Square() { return this.solver().MakeSquare(this.Var()); } public static WrappedConstraint operator ==(Constraint a, long v) { return new WrappedConstraint(a.solver().MakeEquality(a.Var(), v)); } public static WrappedConstraint operator ==(long v, Constraint a) { return new WrappedConstraint(a.solver().MakeEquality(a.Var(), v)); } public static WrappedConstraint operator !=(Constraint a, long v) { return new WrappedConstraint(a.solver().MakeNonEquality(a.Var(), v)); } public static WrappedConstraint operator !=(long v, Constraint a) { return new WrappedConstraint(a.solver().MakeNonEquality(a.Var(), v)); } public static WrappedConstraint operator >=(Constraint a, long v) { return new WrappedConstraint(a.solver().MakeGreaterOrEqual(a.Var(), v)); } public static WrappedConstraint operator >=(long v, Constraint a) { return new WrappedConstraint(a.solver().MakeLessOrEqual(a.Var(), v)); } public static WrappedConstraint operator >(Constraint a, long v) { return new WrappedConstraint(a.solver().MakeGreater(a.Var(), v)); } public static WrappedConstraint operator >(long v, Constraint a) { return new WrappedConstraint(a.solver().MakeLess(a.Var(), v)); } public static WrappedConstraint operator <=(Constraint a, long v) { return new WrappedConstraint(a.solver().MakeLessOrEqual(a.Var(), v)); } public static WrappedConstraint operator <=(long v, Constraint a) { return new WrappedConstraint(a.solver().MakeGreaterOrEqual(a.Var(), v)); } public static WrappedConstraint operator <(Constraint a, long v) { return new WrappedConstraint(a.solver().MakeLess(a.Var(), v)); } public static WrappedConstraint operator <(long v, Constraint a) { return new WrappedConstraint(a.solver().MakeGreater(a.Var(), v)); } public static WrappedConstraint operator >=(Constraint a, Constraint b) { return new WrappedConstraint(a.solver().MakeGreaterOrEqual(a.Var(), b.Var())); } public static WrappedConstraint operator >(Constraint a, Constraint b) { return new WrappedConstraint(a.solver().MakeGreater(a.Var(), b.Var())); } public static WrappedConstraint operator <=(Constraint a, Constraint b) { return new WrappedConstraint(a.solver().MakeLessOrEqual(a.Var(), b.Var())); } public static WrappedConstraint operator <(Constraint a, Constraint b) { return new WrappedConstraint(a.solver().MakeLess(a.Var(), b.Var())); } public static ConstraintEquality operator ==(Constraint a, Constraint b) { return new ConstraintEquality(a, b, true); } public static ConstraintEquality operator !=(Constraint a, Constraint b) { return new ConstraintEquality(a, b, false); } } } // namespace Google.OrTools.ConstraintSolver
// Copyright (c) The Avalonia Project. All rights reserved. // Licensed under the MIT license. See licence.md file in the project root for full license information. using Avalonia.Controls.Primitives; using Avalonia.Input; using Avalonia.LogicalTree; using Moq; using Xunit; namespace Avalonia.Controls.UnitTests { public class VirtualizingStackPanelTests { public class Vertical { [Fact] public void Measure_Invokes_Controller_UpdateControls() { var target = (IVirtualizingPanel)new VirtualizingStackPanel(); var controller = new Mock<IVirtualizingController>(); target.Controller = controller.Object; target.Measure(new Size(100, 100)); controller.Verify(x => x.UpdateControls(), Times.Once()); } [Fact] public void Measure_Invokes_Controller_UpdateControls_If_AvailableSize_Changes() { var target = (IVirtualizingPanel)new VirtualizingStackPanel(); var controller = new Mock<IVirtualizingController>(); target.Controller = controller.Object; target.Measure(new Size(100, 100)); target.InvalidateMeasure(); target.Measure(new Size(100, 100)); target.InvalidateMeasure(); target.Measure(new Size(100, 101)); controller.Verify(x => x.UpdateControls(), Times.Exactly(2)); } [Fact] public void Measure_Does_Not_Invoke_Controller_UpdateControls_If_AvailableSize_Is_The_Same() { var target = (IVirtualizingPanel)new VirtualizingStackPanel(); var controller = new Mock<IVirtualizingController>(); target.Controller = controller.Object; target.Measure(new Size(100, 100)); target.InvalidateMeasure(); target.Measure(new Size(100, 100)); controller.Verify(x => x.UpdateControls(), Times.Once()); } [Fact] public void Measure_Invokes_Controller_UpdateControls_If_AvailableSize_Is_The_Same_After_ForceInvalidateMeasure() { var target = (IVirtualizingPanel)new VirtualizingStackPanel(); var controller = new Mock<IVirtualizingController>(); target.Controller = controller.Object; target.Measure(new Size(100, 100)); target.ForceInvalidateMeasure(); target.Measure(new Size(100, 100)); controller.Verify(x => x.UpdateControls(), Times.Exactly(2)); } [Fact] public void Arrange_Invokes_Controller_UpdateControls() { var target = (IVirtualizingPanel)new VirtualizingStackPanel(); var controller = new Mock<IVirtualizingController>(); target.Controller = controller.Object; target.Measure(new Size(100, 100)); target.Arrange(new Rect(0, 0, 110, 110)); controller.Verify(x => x.UpdateControls(), Times.Exactly(2)); } [Fact] public void Reports_IsFull_False_Until_Measure_Height_Is_Reached() { var target = (IVirtualizingPanel)new VirtualizingStackPanel(); target.Measure(new Size(100, 100)); Assert.Equal(new Size(0, 0), target.DesiredSize); Assert.Equal(new Size(0, 0), target.Bounds.Size); Assert.False(target.IsFull); Assert.Equal(0, target.OverflowCount); target.Children.Add(new Canvas { Width = 50, Height = 50 }); Assert.False(target.IsFull); Assert.Equal(0, target.OverflowCount); target.Children.Add(new Canvas { Width = 50, Height = 50 }); Assert.True(target.IsFull); Assert.Equal(0, target.OverflowCount); } [Fact] public void Reports_Overflow_After_Arrange() { var target = (IVirtualizingPanel)new VirtualizingStackPanel(); target.Measure(new Size(100, 100)); target.Arrange(new Rect(target.DesiredSize)); Assert.Equal(new Size(0, 0), target.Bounds.Size); target.Children.Add(new Canvas { Width = 50, Height = 50 }); target.Children.Add(new Canvas { Width = 50, Height = 50 }); target.Children.Add(new Canvas { Width = 50, Height = 50 }); target.Children.Add(new Canvas { Width = 50, Height = 50 }); Assert.Equal(0, target.OverflowCount); target.Measure(new Size(100, 100)); target.Arrange(new Rect(target.DesiredSize)); Assert.Equal(2, target.OverflowCount); } [Fact] public void Reports_Correct_Overflow_During_Arrange() { var target = (IVirtualizingPanel)new VirtualizingStackPanel(); var controller = new Mock<IVirtualizingController>(); var called = false; target.Children.Add(new Canvas { Width = 50, Height = 50 }); target.Children.Add(new Canvas { Width = 50, Height = 52 }); target.Measure(new Size(100, 100)); controller.Setup(x => x.UpdateControls()).Callback(() => { Assert.Equal(2, target.PixelOverflow); Assert.Equal(0, target.OverflowCount); called = true; }); target.Controller = controller.Object; target.Arrange(new Rect(target.DesiredSize)); Assert.True(called); } [Fact] public void Reports_PixelOverflow_After_Arrange() { var target = (IVirtualizingPanel)new VirtualizingStackPanel(); target.Children.Add(new Canvas { Width = 50, Height = 50 }); target.Children.Add(new Canvas { Width = 50, Height = 52 }); target.Measure(new Size(100, 100)); target.Arrange(new Rect(target.DesiredSize)); Assert.Equal(2, target.PixelOverflow); } [Fact] public void Reports_PixelOverflow_After_Arrange_Smaller_Than_Measure() { var target = (IVirtualizingPanel)new VirtualizingStackPanel(); target.Children.Add(new Canvas { Width = 50, Height = 50 }); target.Children.Add(new Canvas { Width = 50, Height = 52 }); target.Measure(new Size(100, 100)); target.Arrange(new Rect(0, 0, 50, 50)); Assert.Equal(52, target.PixelOverflow); } [Fact] public void Reports_PixelOverflow_With_PixelOffset() { var target = (IVirtualizingPanel)new VirtualizingStackPanel(); target.Children.Add(new Canvas { Width = 50, Height = 50 }); target.Children.Add(new Canvas { Width = 50, Height = 52 }); target.PixelOffset = 2; target.Measure(new Size(100, 100)); target.Arrange(new Rect(target.DesiredSize)); Assert.Equal(2, target.PixelOverflow); } [Fact] public void PixelOffset_Can_Be_More_Than_Child_Without_Affecting_IsFull() { var target = (IVirtualizingPanel)new VirtualizingStackPanel(); target.Children.Add(new Canvas { Width = 50, Height = 50 }); target.Children.Add(new Canvas { Width = 50, Height = 52 }); target.PixelOffset = 55; target.Measure(new Size(100, 100)); target.Arrange(new Rect(target.DesiredSize)); Assert.Equal(55, target.PixelOffset); Assert.Equal(2, target.PixelOverflow); Assert.True(target.IsFull); } [Fact] public void Passes_Navigation_Request_To_ILogicalScrollable_Parent() { var presenter = new Mock<ILogical>().As<IControl>(); var scrollable = presenter.As<ILogicalScrollable>(); var target = (IVirtualizingPanel)new VirtualizingStackPanel(); var from = new Canvas(); scrollable.Setup(x => x.IsLogicalScrollEnabled).Returns(true); ((ISetLogicalParent)target).SetParent(presenter.Object); ((INavigableContainer)target).GetControl(NavigationDirection.Next, from, false); scrollable.Verify(x => x.GetControlInDirection(NavigationDirection.Next, from)); } } } }
namespace RefExplorer.Gui { partial class MainForm { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MainForm)); this.toolStripContainer1 = new System.Windows.Forms.ToolStripContainer(); this.tabControl = new System.Windows.Forms.TabControl(); this.entryPointsPage = new System.Windows.Forms.TabPage(); this.inputFilesControl = new RefExplorer.Gui.InputFilesControl(); this.optionsPage = new System.Windows.Forms.TabPage(); this.ShowPInvoke = new System.Windows.Forms.CheckBox(); this.doNotExploreBox = new System.Windows.Forms.TextBox(); this.excludeBox = new System.Windows.Forms.TextBox(); this.label2 = new System.Windows.Forms.Label(); this.label1 = new System.Windows.Forms.Label(); this.graphPage = new System.Windows.Forms.TabPage(); this.webBrowser = new RefExplorer.Gui.MyBrowser(); this.menuStrip1 = new System.Windows.Forms.MenuStrip(); this.fileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.openMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.saveMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator3 = new System.Windows.Forms.ToolStripSeparator(); this.printToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.exportToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator2 = new System.Windows.Forms.ToolStripSeparator(); this.exitToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.viewToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.refreshToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.helpToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.infoToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStrip = new System.Windows.Forms.ToolStrip(); this.exportButton = new System.Windows.Forms.ToolStripButton(); this.printButton = new System.Windows.Forms.ToolStripButton(); this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator(); this.zoomComboBox = new System.Windows.Forms.ToolStripComboBox(); this.toolStripLabel1 = new System.Windows.Forms.ToolStripLabel(); this.openFileDialog = new System.Windows.Forms.OpenFileDialog(); this.saveFileDialog = new System.Windows.Forms.SaveFileDialog(); this.defaultsButton = new System.Windows.Forms.Button(); this.toolStripContainer1.ContentPanel.SuspendLayout(); this.toolStripContainer1.TopToolStripPanel.SuspendLayout(); this.toolStripContainer1.SuspendLayout(); this.tabControl.SuspendLayout(); this.entryPointsPage.SuspendLayout(); this.optionsPage.SuspendLayout(); this.graphPage.SuspendLayout(); this.menuStrip1.SuspendLayout(); this.toolStrip.SuspendLayout(); this.SuspendLayout(); // // toolStripContainer1 // // // toolStripContainer1.ContentPanel // this.toolStripContainer1.ContentPanel.Controls.Add(this.tabControl); this.toolStripContainer1.ContentPanel.Size = new System.Drawing.Size(910, 426); this.toolStripContainer1.Dock = System.Windows.Forms.DockStyle.Fill; this.toolStripContainer1.Location = new System.Drawing.Point(0, 0); this.toolStripContainer1.Name = "toolStripContainer1"; this.toolStripContainer1.Size = new System.Drawing.Size(910, 475); this.toolStripContainer1.TabIndex = 0; this.toolStripContainer1.Text = "toolStripContainer1"; // // toolStripContainer1.TopToolStripPanel // this.toolStripContainer1.TopToolStripPanel.Controls.Add(this.menuStrip1); this.toolStripContainer1.TopToolStripPanel.Controls.Add(this.toolStrip); // // tabControl // this.tabControl.Controls.Add(this.entryPointsPage); this.tabControl.Controls.Add(this.optionsPage); this.tabControl.Controls.Add(this.graphPage); this.tabControl.Dock = System.Windows.Forms.DockStyle.Fill; this.tabControl.Location = new System.Drawing.Point(0, 0); this.tabControl.Name = "tabControl"; this.tabControl.SelectedIndex = 0; this.tabControl.Size = new System.Drawing.Size(910, 426); this.tabControl.TabIndex = 1; this.tabControl.SelectedIndexChanged += new System.EventHandler(this.tabControl_SelectedIndexChanged); // // entryPointsPage // this.entryPointsPage.Controls.Add(this.inputFilesControl); this.entryPointsPage.Location = new System.Drawing.Point(4, 22); this.entryPointsPage.Name = "entryPointsPage"; this.entryPointsPage.Size = new System.Drawing.Size(902, 400); this.entryPointsPage.TabIndex = 2; this.entryPointsPage.Text = "Entry Points"; this.entryPointsPage.UseVisualStyleBackColor = true; // // inputFilesControl // this.inputFilesControl.Dock = System.Windows.Forms.DockStyle.Fill; this.inputFilesControl.IsDirty = false; this.inputFilesControl.Location = new System.Drawing.Point(0, 0); this.inputFilesControl.Name = "inputFilesControl"; this.inputFilesControl.Size = new System.Drawing.Size(902, 400); this.inputFilesControl.TabIndex = 0; // // optionsPage // this.optionsPage.AutoScroll = true; this.optionsPage.Controls.Add(this.defaultsButton); this.optionsPage.Controls.Add(this.ShowPInvoke); this.optionsPage.Controls.Add(this.doNotExploreBox); this.optionsPage.Controls.Add(this.excludeBox); this.optionsPage.Controls.Add(this.label2); this.optionsPage.Controls.Add(this.label1); this.optionsPage.Location = new System.Drawing.Point(4, 22); this.optionsPage.Name = "optionsPage"; this.optionsPage.Padding = new System.Windows.Forms.Padding(3); this.optionsPage.Size = new System.Drawing.Size(902, 400); this.optionsPage.TabIndex = 1; this.optionsPage.Text = "Options"; this.optionsPage.UseVisualStyleBackColor = true; // // ShowPInvoke // this.ShowPInvoke.AutoSize = true; this.ShowPInvoke.Location = new System.Drawing.Point(11, 174); this.ShowPInvoke.Name = "ShowPInvoke"; this.ShowPInvoke.Size = new System.Drawing.Size(232, 17); this.ShowPInvoke.TabIndex = 7; this.ShowPInvoke.Text = "Show references to native DLLs (P/Invoke)"; this.ShowPInvoke.UseVisualStyleBackColor = true; this.ShowPInvoke.CheckedChanged += new System.EventHandler(this.ShowPInvoke_CheckedChanged); // // doNotExploreBox // this.doNotExploreBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.doNotExploreBox.Location = new System.Drawing.Point(11, 107); this.doNotExploreBox.Multiline = true; this.doNotExploreBox.Name = "doNotExploreBox"; this.doNotExploreBox.Size = new System.Drawing.Size(883, 51); this.doNotExploreBox.TabIndex = 6; this.doNotExploreBox.Text = "Microsoft.*;System;System.*"; this.doNotExploreBox.TextChanged += new System.EventHandler(this.OptionTextChanged); // // excludeBox // this.excludeBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.excludeBox.Location = new System.Drawing.Point(11, 25); this.excludeBox.Multiline = true; this.excludeBox.Name = "excludeBox"; this.excludeBox.Size = new System.Drawing.Size(883, 51); this.excludeBox.TabIndex = 5; this.excludeBox.Text = "mscorlib"; this.excludeBox.TextChanged += new System.EventHandler(this.OptionTextChanged); // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(8, 91); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(265, 13); this.label2.TabIndex = 4; this.label2.Text = "Do not explore references of (semicolon separated list):"; // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(8, 9); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(256, 13); this.label1.TabIndex = 2; this.label1.Text = "Do not show references to (semicolon separated list):"; // // graphPage // this.graphPage.Controls.Add(this.webBrowser); this.graphPage.Location = new System.Drawing.Point(4, 22); this.graphPage.Name = "graphPage"; this.graphPage.Padding = new System.Windows.Forms.Padding(3); this.graphPage.Size = new System.Drawing.Size(902, 398); this.graphPage.TabIndex = 0; this.graphPage.Text = "Graph"; this.graphPage.UseVisualStyleBackColor = true; // // webBrowser // this.webBrowser.Dock = System.Windows.Forms.DockStyle.Fill; this.webBrowser.IsWebBrowserContextMenuEnabled = false; this.webBrowser.Location = new System.Drawing.Point(3, 3); this.webBrowser.MinimumSize = new System.Drawing.Size(20, 20); this.webBrowser.Name = "webBrowser"; this.webBrowser.Size = new System.Drawing.Size(896, 392); this.webBrowser.TabIndex = 1; this.webBrowser.Navigating += new System.Windows.Forms.WebBrowserNavigatingEventHandler(this.webBrowser_Navigating); // // menuStrip1 // this.menuStrip1.Dock = System.Windows.Forms.DockStyle.None; this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.fileToolStripMenuItem, this.viewToolStripMenuItem, this.helpToolStripMenuItem}); this.menuStrip1.Location = new System.Drawing.Point(0, 0); this.menuStrip1.Name = "menuStrip1"; this.menuStrip1.Size = new System.Drawing.Size(910, 24); this.menuStrip1.TabIndex = 2; this.menuStrip1.Text = "menuStrip1"; // // fileToolStripMenuItem // this.fileToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.openMenuItem, this.saveMenuItem, this.toolStripSeparator3, this.printToolStripMenuItem, this.exportToolStripMenuItem, this.toolStripSeparator2, this.exitToolStripMenuItem}); this.fileToolStripMenuItem.Name = "fileToolStripMenuItem"; this.fileToolStripMenuItem.Size = new System.Drawing.Size(37, 20); this.fileToolStripMenuItem.Text = "&File"; // // openMenuItem // this.openMenuItem.Name = "openMenuItem"; this.openMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.O))); this.openMenuItem.Size = new System.Drawing.Size(195, 22); this.openMenuItem.Text = "&Open Project..."; this.openMenuItem.Visible = false; this.openMenuItem.Click += new System.EventHandler(this.openMenuItem_Click); // // saveMenuItem // this.saveMenuItem.Name = "saveMenuItem"; this.saveMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.S))); this.saveMenuItem.Size = new System.Drawing.Size(195, 22); this.saveMenuItem.Text = "&Save Project..."; this.saveMenuItem.Visible = false; this.saveMenuItem.Click += new System.EventHandler(this.saveMenuItem_Click); // // toolStripSeparator3 // this.toolStripSeparator3.Name = "toolStripSeparator3"; this.toolStripSeparator3.Size = new System.Drawing.Size(192, 6); this.toolStripSeparator3.Visible = false; // // printToolStripMenuItem // this.printToolStripMenuItem.Name = "printToolStripMenuItem"; this.printToolStripMenuItem.ShortcutKeyDisplayString = "Ctrl+P"; this.printToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.P))); this.printToolStripMenuItem.Size = new System.Drawing.Size(195, 22); this.printToolStripMenuItem.Text = "&Print..."; this.printToolStripMenuItem.Click += new System.EventHandler(this.printButton_Click); // // exportToolStripMenuItem // this.exportToolStripMenuItem.Name = "exportToolStripMenuItem"; this.exportToolStripMenuItem.ShortcutKeyDisplayString = "Ctrl+E"; this.exportToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.E))); this.exportToolStripMenuItem.Size = new System.Drawing.Size(195, 22); this.exportToolStripMenuItem.Text = "E&xport..."; this.exportToolStripMenuItem.Click += new System.EventHandler(this.exportButton_Click); // // toolStripSeparator2 // this.toolStripSeparator2.Name = "toolStripSeparator2"; this.toolStripSeparator2.Size = new System.Drawing.Size(192, 6); // // exitToolStripMenuItem // this.exitToolStripMenuItem.Name = "exitToolStripMenuItem"; this.exitToolStripMenuItem.ShortcutKeyDisplayString = "Ctrl+Alt+F4"; this.exitToolStripMenuItem.Size = new System.Drawing.Size(195, 22); this.exitToolStripMenuItem.Text = "&Exit"; this.exitToolStripMenuItem.Click += new System.EventHandler(this.exitToolStripMenuItem_Click); // // viewToolStripMenuItem // this.viewToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.refreshToolStripMenuItem}); this.viewToolStripMenuItem.Name = "viewToolStripMenuItem"; this.viewToolStripMenuItem.Size = new System.Drawing.Size(44, 20); this.viewToolStripMenuItem.Text = "&View"; // // refreshToolStripMenuItem // this.refreshToolStripMenuItem.Name = "refreshToolStripMenuItem"; this.refreshToolStripMenuItem.ShortcutKeys = System.Windows.Forms.Keys.F5; this.refreshToolStripMenuItem.Size = new System.Drawing.Size(132, 22); this.refreshToolStripMenuItem.Text = "&Refresh"; this.refreshToolStripMenuItem.Click += new System.EventHandler(this.refreshButton_Click); // // helpToolStripMenuItem // this.helpToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.infoToolStripMenuItem}); this.helpToolStripMenuItem.Name = "helpToolStripMenuItem"; this.helpToolStripMenuItem.Size = new System.Drawing.Size(44, 20); this.helpToolStripMenuItem.Text = "&Help"; // // infoToolStripMenuItem // this.infoToolStripMenuItem.Name = "infoToolStripMenuItem"; this.infoToolStripMenuItem.Size = new System.Drawing.Size(95, 22); this.infoToolStripMenuItem.Text = "&Info"; this.infoToolStripMenuItem.Click += new System.EventHandler(this.infoToolStripMenuItem_Click); // // toolStrip // this.toolStrip.Dock = System.Windows.Forms.DockStyle.None; this.toolStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.exportButton, this.printButton, this.toolStripSeparator1, this.zoomComboBox, this.toolStripLabel1}); this.toolStrip.Location = new System.Drawing.Point(0, 24); this.toolStrip.Name = "toolStrip"; this.toolStrip.Size = new System.Drawing.Size(910, 25); this.toolStrip.Stretch = true; this.toolStrip.TabIndex = 1; // // exportButton // this.exportButton.Image = ((System.Drawing.Image)(resources.GetObject("exportButton.Image"))); this.exportButton.ImageTransparentColor = System.Drawing.Color.Magenta; this.exportButton.Name = "exportButton"; this.exportButton.Size = new System.Drawing.Size(60, 22); this.exportButton.Text = "Export"; this.exportButton.ToolTipText = "Export (Ctrl+E)"; this.exportButton.Click += new System.EventHandler(this.exportButton_Click); // // printButton // this.printButton.Image = ((System.Drawing.Image)(resources.GetObject("printButton.Image"))); this.printButton.ImageTransparentColor = System.Drawing.Color.Black; this.printButton.Name = "printButton"; this.printButton.Size = new System.Drawing.Size(52, 22); this.printButton.Text = "Print"; this.printButton.ToolTipText = "Print (Ctrl+P)"; this.printButton.Click += new System.EventHandler(this.printButton_Click); // // toolStripSeparator1 // this.toolStripSeparator1.Name = "toolStripSeparator1"; this.toolStripSeparator1.Size = new System.Drawing.Size(6, 25); // // zoomComboBox // this.zoomComboBox.Alignment = System.Windows.Forms.ToolStripItemAlignment.Right; this.zoomComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.zoomComboBox.DropDownWidth = 75; this.zoomComboBox.Items.AddRange(new object[] { "150%", "125%", "100%", "75%", "50%", "25%"}); this.zoomComboBox.Name = "zoomComboBox"; this.zoomComboBox.Size = new System.Drawing.Size(75, 25); this.zoomComboBox.DropDownClosed += new System.EventHandler(this.zoomComboBox_DropDownClosed); // // toolStripLabel1 // this.toolStripLabel1.Alignment = System.Windows.Forms.ToolStripItemAlignment.Right; this.toolStripLabel1.Name = "toolStripLabel1"; this.toolStripLabel1.Size = new System.Drawing.Size(42, 22); this.toolStripLabel1.Text = "Zoom:"; // // openFileDialog // this.openFileDialog.FileName = "myProject.reproj"; this.openFileDialog.Filter = "RefExplorer files|*.reproj"; this.openFileDialog.Title = "Open Project"; // // saveFileDialog // this.saveFileDialog.Filter = "RefExplorer files|*.reproj"; this.saveFileDialog.Title = "Save Project"; // // defaultsButton // this.defaultsButton.Location = new System.Drawing.Point(11, 207); this.defaultsButton.Name = "defaultsButton"; this.defaultsButton.Size = new System.Drawing.Size(102, 23); this.defaultsButton.TabIndex = 8; this.defaultsButton.Text = "&Load Defaults"; this.defaultsButton.UseVisualStyleBackColor = true; this.defaultsButton.Click += new System.EventHandler(this.defaultsButton_Click); // // MainForm // this.AllowDrop = true; this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(910, 475); this.Controls.Add(this.toolStripContainer1); this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.MainMenuStrip = this.menuStrip1; this.Name = "MainForm"; this.Text = ".NET Reference Explorer"; this.DragDrop += new System.Windows.Forms.DragEventHandler(this.Form1_DragDrop); this.DragEnter += new System.Windows.Forms.DragEventHandler(this.Form1_DragEnter); this.toolStripContainer1.ContentPanel.ResumeLayout(false); this.toolStripContainer1.TopToolStripPanel.ResumeLayout(false); this.toolStripContainer1.TopToolStripPanel.PerformLayout(); this.toolStripContainer1.ResumeLayout(false); this.toolStripContainer1.PerformLayout(); this.tabControl.ResumeLayout(false); this.entryPointsPage.ResumeLayout(false); this.optionsPage.ResumeLayout(false); this.optionsPage.PerformLayout(); this.graphPage.ResumeLayout(false); this.menuStrip1.ResumeLayout(false); this.menuStrip1.PerformLayout(); this.toolStrip.ResumeLayout(false); this.toolStrip.PerformLayout(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.ToolStripContainer toolStripContainer1; private System.Windows.Forms.ToolStrip toolStrip; private System.Windows.Forms.ToolStripButton exportButton; private System.Windows.Forms.ToolStripButton printButton; private System.Windows.Forms.TabControl tabControl; private System.Windows.Forms.TabPage graphPage; private MyBrowser webBrowser; private System.Windows.Forms.TabPage optionsPage; private System.Windows.Forms.Label label1; private System.Windows.Forms.MenuStrip menuStrip1; private System.Windows.Forms.ToolStripMenuItem fileToolStripMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripSeparator2; private System.Windows.Forms.ToolStripMenuItem exitToolStripMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripSeparator3; private System.Windows.Forms.ToolStripMenuItem printToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem exportToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem helpToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem infoToolStripMenuItem; private System.Windows.Forms.Label label2; private System.Windows.Forms.TextBox excludeBox; private System.Windows.Forms.TextBox doNotExploreBox; private System.Windows.Forms.TabPage entryPointsPage; private InputFilesControl inputFilesControl; private System.Windows.Forms.ToolStripMenuItem openMenuItem; private System.Windows.Forms.ToolStripMenuItem saveMenuItem; private System.Windows.Forms.ToolStripMenuItem viewToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem refreshToolStripMenuItem; private System.Windows.Forms.OpenFileDialog openFileDialog; private System.Windows.Forms.SaveFileDialog saveFileDialog; private System.Windows.Forms.ToolStripSeparator toolStripSeparator1; private System.Windows.Forms.ToolStripComboBox zoomComboBox; private System.Windows.Forms.ToolStripLabel toolStripLabel1; private System.Windows.Forms.CheckBox ShowPInvoke; private System.Windows.Forms.Button defaultsButton; } }
// 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. ////////////////////////////////////////////////////////// // L-1-7-1.cs - Beta1 Layout Test - RDawson // // Tests layout of classes using 1-deep nesting in // the same assembly and module (checking access from a // class in the same family). // // See ReadMe.txt in the same project as this source for // further details about these tests. // using System; class L171{ public static int Main(){ int mi_RetCode; mi_RetCode = Test(); if(mi_RetCode == 100) Console.WriteLine("Pass"); else Console.WriteLine("FAIL"); return mi_RetCode; } public static int Test(){ int mi_RetCode = 100; B.ClsB bc = new B.ClsB(); A.ClsA ac = new A.ClsA(); B b = new B(); if(Test_Nested(bc) != 100) mi_RetCode = 0; if(Test_Nested(ac) != 100) mi_RetCode = 0; //@csharp - C# simply won't compile non-related private/family/protected access if(Test_Nested(b.ClsAPubInst) != 100) mi_RetCode = 0; if(Test_Nested(B.ClsAPubStat) != 100) mi_RetCode = 0; if(Test_Nested(b.ClsBPubInst) != 100) mi_RetCode = 0; if(Test_Nested(b.ClsBAsmInst) != 100) mi_RetCode = 0; if(Test_Nested(b.ClsBFoaInst) != 100) mi_RetCode = 0; if(Test_Nested(B.ClsBPubStat) != 100) mi_RetCode = 0; return mi_RetCode; } public static int Test_Nested(A.ClsA ac){ int mi_RetCode = 100; ///////////////////////////////// // Test instance field access ac.NestFldAPubInst = 100; if(ac.NestFldAPubInst != 100) mi_RetCode = 0; ///////////////////////////////// // Test static field access A.ClsA.NestFldAPubStat = 100; if(A.ClsA.NestFldAPubStat != 100) mi_RetCode = 0; ///////////////////////////////// // Test instance MethAod access if(ac.NestMethAPubInst() != 100) mi_RetCode = 0; ///////////////////////////////// // Test static MethAod access if(A.ClsA.NestMethAPubStat() != 100) mi_RetCode = 0; ///////////////////////////////// // Test virtual MethAod access if(ac.NestMethAPubVirt() != 100) mi_RetCode = 0; //////////////////////////////////////////// // Test access from within the nested class if(ac.Test() != 100) mi_RetCode = 0; return mi_RetCode; } public static int Test_Nested(B.ClsB bc){ int mi_RetCode = 100; ///////////////////////////////// // Test instance field access bc.NestFldBPubInst = 100; if(bc.NestFldBPubInst != 100) mi_RetCode = 0; bc.NestFldBAsmInst = 100; if(bc.NestFldBAsmInst != 100) mi_RetCode = 0; bc.NestFldBFoaInst = 100; if(bc.NestFldBFoaInst != 100) mi_RetCode = 0; ///////////////////////////////// // Test static field access B.ClsB.NestFldBPubStat = 100; if(B.ClsB.NestFldBPubStat != 100) mi_RetCode = 0; B.ClsB.NestFldBAsmStat = 100; if(B.ClsB.NestFldBAsmStat != 100) mi_RetCode = 0; B.ClsB.NestFldBFoaStat = 100; if(B.ClsB.NestFldBFoaStat != 100) mi_RetCode = 0; ///////////////////////////////// // Test instance method access if(bc.NestMethBPubInst() != 100) mi_RetCode = 0; if(bc.NestMethBAsmInst() != 100) mi_RetCode = 0; if(bc.NestMethBFoaInst() != 100) mi_RetCode = 0; ///////////////////////////////// // Test static method access if(B.ClsB.NestMethBPubStat() != 100) mi_RetCode = 0; if(B.ClsB.NestMethBAsmStat() != 100) mi_RetCode = 0; if(B.ClsB.NestMethBFoaStat() != 100) mi_RetCode = 0; ///////////////////////////////// // Test virtual method access if(bc.NestMethBPubVirt() != 100) mi_RetCode = 0; if(bc.NestMethBAsmVirt() != 100) mi_RetCode = 0; if(bc.NestMethBFoaVirt() != 100) mi_RetCode = 0; //////////////////////////////////////////// // Test access from within the nested class if(bc.Test() != 100) mi_RetCode = 0; return mi_RetCode; } } class B : A{ public int Test(){ A a = new A(); int mi_RetCode = 100; ///////////////////////////////// // Test nested class access if(Test_Nested(ClsAPubInst) != 100) mi_RetCode = 0; if(Test_Nested(ClsAFamInst) != 100) mi_RetCode = 0; if(Test_Nested(ClsAFoaInst) != 100) mi_RetCode = 0; if(Test_Nested(ClsAPubStat) != 100) mi_RetCode = 0; if(Test_Nested(ClsBPubInst) != 100) mi_RetCode = 0; if(Test_Nested(ClsBPrivInst) != 100) mi_RetCode = 0; if(Test_Nested(ClsBFamInst) != 100) mi_RetCode = 0; if(Test_Nested(ClsBAsmInst) != 100) mi_RetCode = 0; if(Test_Nested(ClsBFoaInst) != 100) mi_RetCode = 0; if(Test_Nested(ClsBPubStat) != 100) mi_RetCode = 0; if(Test_Nested(ClsBPrivStat) != 100) mi_RetCode = 0; return mi_RetCode; } public int Test_Nested(ClsA Nested_Cls){ int mi_RetCode = 100; ///////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////// // ACCESS NESTED FIELDS/MEMBERS ///////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////// ///////////////////////////////// // Test instance field access Nested_Cls.NestFldAPubInst = 100; if(Nested_Cls.NestFldAPubInst != 100) mi_RetCode = 0; ///////////////////////////////// // Test static field access A.ClsA.NestFldAPubStat = 100; if(A.ClsA.NestFldAPubStat != 100) mi_RetCode = 0; ///////////////////////////////// // Test instance MethAod access if(Nested_Cls.NestMethAPubInst() != 100) mi_RetCode = 0; ///////////////////////////////// // Test static MethAod access if(A.ClsA.NestMethAPubStat() != 100) mi_RetCode = 0; ///////////////////////////////// // Test virtual MethAod access if(Nested_Cls.NestMethAPubVirt() != 100) mi_RetCode = 0; //@csharp - @todo - @bugbug - This is coded poorly in L-1-7-3 and L-1-8-3, we should be able to access assembly and famorassem members, but because of they way it's coded that's illegal according to C#, fix this up //////////////////////////////////////////// // Test access from within the nested class if(Nested_Cls.Test() != 100) mi_RetCode = 0; return mi_RetCode; } public static int Test_Nested(ClsB Nested_Cls){ int mi_RetCode = 100; ///////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////// // ACCESS NESTED FIELDS/MEMBERS ///////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////// ///////////////////////////////// // Test instance field access Nested_Cls.NestFldBPubInst = 100; if(Nested_Cls.NestFldBPubInst != 100) mi_RetCode = 0; Nested_Cls.NestFldBAsmInst = 100; if(Nested_Cls.NestFldBAsmInst != 100) mi_RetCode = 0; Nested_Cls.NestFldBFoaInst = 100; if(Nested_Cls.NestFldBFoaInst != 100) mi_RetCode = 0; ///////////////////////////////// // Test static field access B.ClsB.NestFldBPubStat = 100; if(B.ClsB.NestFldBPubStat != 100) mi_RetCode = 0; B.ClsB.NestFldBAsmStat = 100; if(B.ClsB.NestFldBAsmStat != 100) mi_RetCode = 0; B.ClsB.NestFldBFoaStat = 100; if(B.ClsB.NestFldBFoaStat != 100) mi_RetCode = 0; ///////////////////////////////// // Test instance MethBod access if(Nested_Cls.NestMethBPubInst() != 100) mi_RetCode = 0; if(Nested_Cls.NestMethBAsmInst() != 100) mi_RetCode = 0; if(Nested_Cls.NestMethBFoaInst() != 100) mi_RetCode = 0; ///////////////////////////////// // Test static MethBod access if(B.ClsB.NestMethBPubStat() != 100) mi_RetCode = 0; if(B.ClsB.NestMethBAsmStat() != 100) mi_RetCode = 0; if(B.ClsB.NestMethBFoaStat() != 100) mi_RetCode = 0; ///////////////////////////////// // Test virtual MethBod access if(Nested_Cls.NestMethBPubVirt() != 100) mi_RetCode = 0; if(Nested_Cls.NestMethBAsmVirt() != 100) mi_RetCode = 0; if(Nested_Cls.NestMethBFoaVirt() != 100) mi_RetCode = 0; //////////////////////////////////////////// // Test access from within the nested class if(Nested_Cls.Test() != 100) mi_RetCode = 0; return mi_RetCode; } ////////////////////////////// // Instance Fields public int FldBPubInst; private int FldBPrivInst; protected int FldBFamInst; //Translates to "family" internal int FldBAsmInst; //Translates to "assembly" protected internal int FldBFoaInst; //Translates to "famorassem" ////////////////////////////// // Static Fields public static int FldBPubStat; private static int FldBPrivStat; protected static int FldBFamStat; //family internal static int FldBAsmStat; //assembly protected internal static int FldBFoaStat; //famorassem ////////////////////////////////////// // Instance fields for nested classes public ClsB ClsBPubInst = new ClsB(); private ClsB ClsBPrivInst = new ClsB(); protected ClsB ClsBFamInst = new ClsB(); internal ClsB ClsBAsmInst = new ClsB(); protected internal ClsB ClsBFoaInst = new ClsB(); ///////////////////////////////////// // Static fields of nested classes public static ClsB ClsBPubStat = new ClsB(); private static ClsB ClsBPrivStat = new ClsB(); ////////////////////////////// // Instance MethBods public int MethBPubInst(){ Console.WriteLine("B::MethBPubInst()"); return 100; } private int MethBPrivInst(){ Console.WriteLine("B::MethBPrivInst()"); return 100; } protected int MethBFamInst(){ Console.WriteLine("B::MethBFamInst()"); return 100; } internal int MethBAsmInst(){ Console.WriteLine("B::MethBAsmInst()"); return 100; } protected internal int MethBFoaInst(){ Console.WriteLine("B::MethBFoaInst()"); return 100; } ////////////////////////////// // Static MethBods public static int MethBPubStat(){ Console.WriteLine("B::MethBPubStat()"); return 100; } private static int MethBPrivStat(){ Console.WriteLine("B::MethBPrivStat()"); return 100; } protected static int MethBFamStat(){ Console.WriteLine("B::MethBFamStat()"); return 100; } internal static int MethBAsmStat(){ Console.WriteLine("B::MethBAsmStat()"); return 100; } protected internal static int MethBFoaStat(){ Console.WriteLine("B::MethBFoaStat()"); return 100; } ////////////////////////////// // Virtual Instance MethBods public virtual int MethBPubVirt(){ Console.WriteLine("B::MethBPubVirt()"); return 100; } //@csharp - Note that C# won't compile an illegal private virtual function //So there is no negative testing MethBPrivVirt() here. protected virtual int MethBFamVirt(){ Console.WriteLine("B::MethBFamVirt()"); return 100; } internal virtual int MethBAsmVirt(){ Console.WriteLine("B::MethBAsmVirt()"); return 100; } protected internal virtual int MethBFoaVirt(){ Console.WriteLine("B::MethBFoaVirt()"); return 100; } public class ClsB{ public int Test(){ int mi_RetCode = 100; ///////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////// // ACCESS ENCLOSING FIELDS/MEMBERS ///////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////// //@csharp - C# will not allow nested classes to access non-static members of their enclosing classes ///////////////////////////////// // Test static field access FldBPubStat = 100; if(FldBPubStat != 100) mi_RetCode = 0; FldBFamStat = 100; if(FldBFamStat != 100) mi_RetCode = 0; FldBAsmStat = 100; if(FldBAsmStat != 100) mi_RetCode = 0; FldBFoaStat = 100; if(FldBFoaStat != 100) mi_RetCode = 0; ///////////////////////////////// // Test static method access if(MethBPubStat() != 100) mi_RetCode = 0; if(MethBFamStat() != 100) mi_RetCode = 0; if(MethBAsmStat() != 100) mi_RetCode = 0; if(MethBFoaStat() != 100) mi_RetCode = 0; ///////////////////////////////// // Test static field access FldAPubStat = 100; if(FldAPubStat != 100) mi_RetCode = 0; FldAFamStat = 100; if(FldAFamStat != 100) mi_RetCode = 0; FldAFoaStat = 100; if(FldAFoaStat != 100) mi_RetCode = 0; ///////////////////////////////// // Test static method access if(MethAPubStat() != 100) mi_RetCode = 0; if(MethAFamStat() != 100) mi_RetCode = 0; if(MethAFoaStat() != 100) mi_RetCode = 0; //////////////////////////////////////////// // Test access from within the nested class if(ClsAPubStat.Test() != 100) mi_RetCode = 0; return mi_RetCode; } ////////////////////////////// // Instance Fields public int NestFldBPubInst; private int NestFldBPrivInst; protected int NestFldBFamInst; //Translates to "family" internal int NestFldBAsmInst; //Translates to "assembly" protected internal int NestFldBFoaInst; //Translates to "famorassem" ////////////////////////////// // Static Fields public static int NestFldBPubStat; private static int NestFldBPrivStat; protected static int NestFldBFamStat; //family internal static int NestFldBAsmStat; //assembly protected internal static int NestFldBFoaStat; //famorassem ////////////////////////////// // Instance NestMethods public int NestMethBPubInst(){ Console.WriteLine("B::NestMethBPubInst()"); return 100; } private int NestMethBPrivInst(){ Console.WriteLine("B::NestMethBPrivInst()"); return 100; } protected int NestMethBFamInst(){ Console.WriteLine("B::NestMethBFamInst()"); return 100; } internal int NestMethBAsmInst(){ Console.WriteLine("B::NestMethBAsmInst()"); return 100; } protected internal int NestMethBFoaInst(){ Console.WriteLine("B::NestMethBFoaInst()"); return 100; } ////////////////////////////// // Static NestMethBods public static int NestMethBPubStat(){ Console.WriteLine("B::NestMethBPubStat()"); return 100; } private static int NestMethBPrivStat(){ Console.WriteLine("B::NestMethBPrivStat()"); return 100; } protected static int NestMethBFamStat(){ Console.WriteLine("B::NestMethBFamStat()"); return 100; } internal static int NestMethBAsmStat(){ Console.WriteLine("B::NestMethBAsmStat()"); return 100; } protected internal static int NestMethBFoaStat(){ Console.WriteLine("B::NestMethBFoaStat()"); return 100; } ////////////////////////////// // Virtual Instance NestMethods public virtual int NestMethBPubVirt(){ Console.WriteLine("B::NestMethBPubVirt()"); return 100; } //@csharp - Note that C# won't compile an illegal private virtual function //So there is no negative testing NestMethBPrivVirt() here. protected virtual int NestMethBFamVirt(){ Console.WriteLine("B::NestMethBFamVirt()"); return 100; } internal virtual int NestMethBAsmVirt(){ Console.WriteLine("B::NestMethBAsmVirt()"); return 100; } protected internal virtual int NestMethBFoaVirt(){ Console.WriteLine("B::NestMethBFoaVirt()"); return 100; } } }
using UnityEngine; namespace Pathfinding.Util { /** Transforms to and from world space to a 2D movement plane. * The transformation is guaranteed to be purely a rotation * so no scale or offset is used. This interface is primarily * used to make it easier to write movement scripts which can * handle movement both in the XZ plane and in the XY plane. * * \see #Pathfinding.Util.GraphTransform */ public interface IMovementPlane { Vector2 ToPlane (Vector3 p); Vector2 ToPlane (Vector3 p, out float elevation); Vector3 ToWorld (Vector2 p, float elevation = 0); } /** Generic 3D coordinate transformation */ public interface ITransform { Vector3 Transform (Vector3 position); Vector3 InverseTransform (Vector3 position); } /** Defines a transformation from graph space to world space. * This is essentially just a simple wrapper around a matrix, but it has several utilities that are useful. */ public class GraphTransform : IMovementPlane, ITransform { /** True if this transform is the identity transform (i.e it does not do anything) */ public readonly bool identity; /** True if this transform is a pure translation without any scaling or rotation */ public readonly bool onlyTranslational; readonly bool isXY; readonly bool isXZ; readonly Matrix4x4 matrix; readonly Matrix4x4 inverseMatrix; readonly Vector3 up; readonly Vector3 translation; readonly Int3 i3translation; readonly Quaternion rotation; readonly Quaternion inverseRotation; public static readonly GraphTransform identityTransform = new GraphTransform(Matrix4x4.identity); public GraphTransform (Matrix4x4 matrix) { this.matrix = matrix; inverseMatrix = matrix.inverse; identity = matrix.isIdentity; onlyTranslational = MatrixIsTranslational(matrix); up = matrix.MultiplyVector(Vector3.up).normalized; translation = matrix.MultiplyPoint3x4(Vector3.zero); i3translation = (Int3)translation; // Extract the rotation from the matrix. This is only correct if the matrix has no skew, but we only // want to use it for the movement plane so as long as the Up axis is parpendicular to the Forward // axis everything should be ok. In fact the only case in the project when all three axes are not // perpendicular is when hexagon or isometric grid graphs are used, but in those cases only the // X and Z axes are not perpendicular. rotation = Quaternion.LookRotation(TransformVector(Vector3.forward), TransformVector(Vector3.up)); inverseRotation = Quaternion.Inverse(rotation); // Some short circuiting code for the movement plane calculations isXY = rotation == Quaternion.Euler(-90, 0, 0); isXZ = rotation == Quaternion.Euler(0, 0, 0); } public Vector3 WorldUpAtGraphPosition (Vector3 point) { return up; } static bool MatrixIsTranslational (Matrix4x4 matrix) { return matrix.GetColumn(0) == new Vector4(1, 0, 0, 0) && matrix.GetColumn(1) == new Vector4(0, 1, 0, 0) && matrix.GetColumn(2) == new Vector4(0, 0, 1, 0) && matrix.m33 == 1; } public Vector3 Transform (Vector3 point) { if (onlyTranslational) return point + translation; return matrix.MultiplyPoint3x4(point); } public Vector3 TransformVector (Vector3 point) { if (onlyTranslational) return point; return matrix.MultiplyVector(point); } public void Transform (Int3[] arr) { if (onlyTranslational) { for (int i = arr.Length - 1; i >= 0; i--) arr[i] += i3translation; } else { for (int i = arr.Length - 1; i >= 0; i--) arr[i] = (Int3)matrix.MultiplyPoint3x4((Vector3)arr[i]); } } public void Transform (Vector3[] arr) { if (onlyTranslational) { for (int i = arr.Length - 1; i >= 0; i--) arr[i] += translation; } else { for (int i = arr.Length - 1; i >= 0; i--) arr[i] = matrix.MultiplyPoint3x4(arr[i]); } } public Vector3 InverseTransform (Vector3 point) { if (onlyTranslational) return point - translation; return inverseMatrix.MultiplyPoint3x4(point); } public Int3 InverseTransform (Int3 point) { if (onlyTranslational) return point - i3translation; return (Int3)inverseMatrix.MultiplyPoint3x4((Vector3)point); } public void InverseTransform (Int3[] arr) { for (int i = arr.Length - 1; i >= 0; i--) arr[i] = (Int3)inverseMatrix.MultiplyPoint3x4((Vector3)arr[i]); } public static GraphTransform operator * (GraphTransform lhs, Matrix4x4 rhs) { return new GraphTransform(lhs.matrix * rhs); } public static GraphTransform operator * (Matrix4x4 lhs, GraphTransform rhs) { return new GraphTransform(lhs * rhs.matrix); } public Bounds Transform (Bounds bounds) { if (onlyTranslational) return new Bounds(bounds.center + translation, bounds.size); var corners = ArrayPool<Vector3>.Claim(8); var extents = bounds.extents; corners[0] = Transform(bounds.center + new Vector3(extents.x, extents.y, extents.z)); corners[1] = Transform(bounds.center + new Vector3(extents.x, extents.y, -extents.z)); corners[2] = Transform(bounds.center + new Vector3(extents.x, -extents.y, extents.z)); corners[3] = Transform(bounds.center + new Vector3(extents.x, -extents.y, -extents.z)); corners[4] = Transform(bounds.center + new Vector3(-extents.x, extents.y, extents.z)); corners[5] = Transform(bounds.center + new Vector3(-extents.x, extents.y, -extents.z)); corners[6] = Transform(bounds.center + new Vector3(-extents.x, -extents.y, extents.z)); corners[7] = Transform(bounds.center + new Vector3(-extents.x, -extents.y, -extents.z)); var min = corners[0]; var max = corners[0]; for (int i = 1; i < 8; i++) { min = Vector3.Min(min, corners[i]); max = Vector3.Max(max, corners[i]); } ArrayPool<Vector3>.Release(ref corners); return new Bounds((min+max)*0.5f, max - min); } public Bounds InverseTransform (Bounds bounds) { if (onlyTranslational) return new Bounds(bounds.center - translation, bounds.size); var corners = ArrayPool<Vector3>.Claim(8); var extents = bounds.extents; corners[0] = InverseTransform(bounds.center + new Vector3(extents.x, extents.y, extents.z)); corners[1] = InverseTransform(bounds.center + new Vector3(extents.x, extents.y, -extents.z)); corners[2] = InverseTransform(bounds.center + new Vector3(extents.x, -extents.y, extents.z)); corners[3] = InverseTransform(bounds.center + new Vector3(extents.x, -extents.y, -extents.z)); corners[4] = InverseTransform(bounds.center + new Vector3(-extents.x, extents.y, extents.z)); corners[5] = InverseTransform(bounds.center + new Vector3(-extents.x, extents.y, -extents.z)); corners[6] = InverseTransform(bounds.center + new Vector3(-extents.x, -extents.y, extents.z)); corners[7] = InverseTransform(bounds.center + new Vector3(-extents.x, -extents.y, -extents.z)); var min = corners[0]; var max = corners[0]; for (int i = 1; i < 8; i++) { min = Vector3.Min(min, corners[i]); max = Vector3.Max(max, corners[i]); } ArrayPool<Vector3>.Release(ref corners); return new Bounds((min+max)*0.5f, max - min); } #region IMovementPlane implementation /** Transforms from world space to the 'ground' plane of the graph. * The transformation is purely a rotation so no scale or offset is used. * * For a graph rotated with the rotation (-90, 0, 0) this will transform * a coordinate (x,y,z) to (x,y). For a graph with the rotation (0,0,0) * this will tranform a coordinate (x,y,z) to (x,z). More generally for * a graph with a quaternion rotation R this will transform a vector V * to R * V (i.e rotate the vector V using the rotation R). */ Vector2 IMovementPlane.ToPlane (Vector3 point) { // These special cases cover most graph orientations used in practice. // Having them here improves performance in those cases by a factor of // 2.5 without impacting the generic case in any significant way. if (isXY) return new Vector2(point.x, point.y); if (!isXZ) point = inverseRotation * point; return new Vector2(point.x, point.z); } /** Transforms from world space to the 'ground' plane of the graph. * The transformation is purely a rotation so no scale or offset is used. */ Vector2 IMovementPlane.ToPlane (Vector3 point, out float elevation) { if (!isXZ) point = inverseRotation * point; elevation = point.y; return new Vector2(point.x, point.z); } /** Transforms from the 'ground' plane of the graph to world space. * The transformation is purely a rotation so no scale or offset is used. */ Vector3 IMovementPlane.ToWorld (Vector2 point, float elevation) { return rotation * new Vector3(point.x, elevation, point.y); } #endregion } }
//----------------------------------------------------------------------------- // Torque // Copyright GarageGames, LLC 2011 //----------------------------------------------------------------------------- // The master server is declared with the server defaults, which is // loaded on both clients & dedicated servers. If the server mod // is not loaded on a client, then the master must be defined. // $pref::Master[0] = "2:master.garagegames.com:28002"; $pref::Player::Name = "Visitor"; $pref::Player::defaultFov = 75; $pref::Player::zoomSpeed = 0; $pref::Net::LagThreshold = 400; $pref::Net::Port = 28000; $pref::HudMessageLogSize = 40; $pref::ChatHudLength = 1; $pref::Input::LinkMouseSensitivity = 1; // DInput keyboard, mouse, and joystick prefs $pref::Input::KeyboardEnabled = 1; $pref::Input::MouseEnabled = 1; $pref::Input::JoystickEnabled = 0; $pref::Input::KeyboardTurnSpeed = 0.1; $sceneLighting::cacheSize = 20000; $sceneLighting::purgeMethod = "lastCreated"; $sceneLighting::cacheLighting = 1; $pref::Video::displayDevice = "D3D9"; $pref::Video::disableVerticalSync = 1; $pref::Video::mode = "1024 768 false 32 60 4"; $pref::Video::defaultFenceCount = 0; $pref::Video::screenShotSession = 0; $pref::Video::screenShotFormat = "PNG"; $pref::Video::disableNormalmapping = false; $pref::Video::disablePixSpecular = false; $pref::Video::disableCubemapping = false; /// $pref::Video::disableParallaxMapping = false; // Console-friendly defaults if($platform $= "xenon") { // Save some fillrate on the X360, and take advantage of the HW scaling $pref::Video::Resolution = "1152 640"; $pref::Video::mode = $pref::Video::Resolution SPC "true 32 60 0"; $pref::Video::fullScreen = 1; } /// This is the path used by ShaderGen to cache procedural /// shaders. If left blank ShaderGen will only cache shaders /// to memory and not to disk. $shaderGen::cachePath = "shaders/procedural"; /// The perfered light manager to use at startup. If blank /// or if the selected one doesn't work on this platfom it /// will try the defaults below. $pref::lightManager = ""; /// This is the default list of light managers ordered from /// most to least desirable for initialization. $lightManager::defaults = "Advanced Lighting" NL "Basic Lighting"; /// A scale to apply to the camera view distance /// typically used for tuning performance. $pref::camera::distanceScale = 1.0; /// Causes the system to do a one time autodetect /// of an SFX provider and device at startup if the /// provider is unset. $pref::SFX::autoDetect = true; /// The sound provider to select at startup. Typically /// this is DirectSound, OpenAL, or XACT. There is also /// a special Null provider which acts normally, but /// plays no sound. $pref::SFX::provider = ""; /// The sound device to select from the provider. Each /// provider may have several different devices. $pref::SFX::device = "OpenAL"; /// If true the device will try to use hardware buffers /// and sound mixing. If not it will use software. $pref::SFX::useHardware = false; /// If you have a software device you have a /// choice of how many software buffers to /// allow at any one time. More buffers cost /// more CPU time to process and mix. $pref::SFX::maxSoftwareBuffers = 16; /// This is the playback frequency for the primary /// sound buffer used for mixing. Although most /// providers will reformat on the fly, for best /// quality and performance match your sound files /// to this setting. $pref::SFX::frequency = 44100; /// This is the playback bitrate for the primary /// sound buffer used for mixing. Although most /// providers will reformat on the fly, for best /// quality and performance match your sound files /// to this setting. $pref::SFX::bitrate = 32; /// The overall system volume at startup. Note that /// you can only scale volume down, volume does not /// get louder than 1. $pref::SFX::masterVolume = 0.8; /// The startup sound channel volumes. These are /// used to control the overall volume of different /// classes of sounds. $pref::SFX::channelVolume1 = 1; $pref::SFX::channelVolume2 = 1; $pref::SFX::channelVolume3 = 1; $pref::SFX::channelVolume4 = 1; $pref::SFX::channelVolume5 = 1; $pref::SFX::channelVolume6 = 1; $pref::SFX::channelVolume7 = 1; $pref::SFX::channelVolume8 = 1; $pref::PostEffect::PreferedHDRFormat = "GFXFormatR8G8B8A8"; /// This is an scalar which can be used to reduce the /// reflection textures on all objects to save fillrate. $pref::Reflect::refractTexScale = 1.0; /// This is the total frame in milliseconds to budget for /// reflection rendering. If your CPU bound and have alot /// of smaller reflection surfaces try reducing this time. $pref::Reflect::frameLimitMS = 10; /// Set true to force all water objects to use static cubemap reflections. $pref::Water::disableTrueReflections = false; // A global LOD scalar which can reduce the overall density of placed GroundCover. $pref::GroundCover::densityScale = 1.0; /// An overall scaler on the lod switching between DTS models. /// Smaller numbers makes the lod switch sooner. $pref::TS::detailAdjust = 1.0; /// $pref::Decals::enabled = true; /// $pref::Decals::lifeTimeScale = "1"; /// The number of mipmap levels to drop on loaded textures /// to reduce video memory usage. /// /// It will skip any textures that have been defined as not /// allowing down scaling. /// $pref::Video::textureReductionLevel = 0; /// $pref::Shadows::textureScalar = 1.0; /// $pref::Shadows::disable = false; /// Sets the shadow filtering mode. /// /// None - Disables filtering. /// /// SoftShadow - Does a simple soft shadow /// /// SoftShadowHighQuality /// $pref::Shadows::filterMode = "SoftShadow"; /// $pref::Video::defaultAnisotropy = 1; /// Radius in meters around the camera that ForestItems are affected by wind. /// Note that a very large number with a large number of items is not cheap. $pref::windEffectRadius = 25; /// AutoDetect graphics quality levels the next startup. $pref::Video::autoDetect = 1; //----------------------------------------------------------------------------- // Graphics Quality Groups //----------------------------------------------------------------------------- // The graphics quality groups are used by the options dialog to // control the state of the $prefs. You should overload these in // your game specific defaults.cs file if they need to be changed. if ( isObject( MeshQualityGroup ) ) MeshQualityGroup.delete(); if ( isObject( TextureQualityGroup ) ) TextureQualityGroup.delete(); if ( isObject( LightingQualityGroup ) ) LightingQualityGroup.delete(); if ( isObject( ShaderQualityGroup ) ) ShaderQualityGroup.delete(); new SimGroup( MeshQualityGroup ) { new ArrayObject( [Lowest] ) { class = "GraphicsQualityLevel"; caseSensitive = true; key["$pref::TS::detailAdjust"] = 0.5; key["$pref::TS::skipRenderDLs"] = 1; key["$pref::Terrain::lodScale"] = 2.0; key["$pref::decalMgr::enabled"] = false; key["$pref::GroundCover::densityScale"] = 0.5; }; new ArrayObject( [Low] ) { class = "GraphicsQualityLevel"; caseSensitive = true; key["$pref::TS::detailAdjust"] = 0.75; key["$pref::TS::skipRenderDLs"] = 0; key["$pref::Terrain::lodScale"] = 1.5; key["$pref::decalMgr::enabled"] = true; key["$pref::GroundCover::densityScale"] = 0.75; }; new ArrayObject( [Normal] ) { class = "GraphicsQualityLevel"; caseSensitive = true; key["$pref::TS::detailAdjust"] = 1.0; key["$pref::TS::skipRenderDLs"] = 0; key["$pref::Terrain::lodScale"] = 1.0; key["$pref::decalMgr::enabled"] = true; key["$pref::GroundCover::densityScale"] = 1.0; }; new ArrayObject( [High] ) { class = "GraphicsQualityLevel"; caseSensitive = true; key["$pref::TS::detailAdjust"] = 1.5; key["$pref::TS::skipRenderDLs"] = 0; key["$pref::Terrain::lodScale"] = 0.75; key["$pref::decalMgr::enabled"] = true; key["$pref::GroundCover::densityScale"] = 1.0; }; }; new SimGroup( TextureQualityGroup ) { new ArrayObject( [Lowest] ) { class = "GraphicsQualityLevel"; caseSensitive = true; key["$pref::Video::textureReductionLevel"] = 2; key["$pref::Reflect::refractTexScale"] = 0.5; key["$pref::Terrain::detailScale"] = 0.5; }; new ArrayObject( [Low] ) { class = "GraphicsQualityLevel"; caseSensitive = true; key["$pref::Video::textureReductionLevel"] = 1; key["$pref::Reflect::refractTexScale"] = 0.75; key["$pref::Terrain::detailScale"] = 0.75; }; new ArrayObject( [Normal] ) { class = "GraphicsQualityLevel"; caseSensitive = true; key["$pref::Video::textureReductionLevel"] = 0; key["$pref::Reflect::refractTexScale"] = 1; key["$pref::Terrain::detailScale"] = 1; }; new ArrayObject( [High] ) { class = "GraphicsQualityLevel"; caseSensitive = true; key["$pref::Video::textureReductionLevel"] = 0; key["$pref::Reflect::refractTexScale"] = 1.25; key["$pref::Terrain::detailScale"] = 1.5; }; }; function TextureQualityGroup::onApply( %this, %level ) { // Note that this can be a slow operation. reloadTextures(); } new SimGroup( LightingQualityGroup ) { new ArrayObject( [Lowest] ) { class = "GraphicsQualityLevel"; caseSensitive = true; key["$pref::lightManager"] = "Basic Lighting"; key["$pref::Shadows::disable"] = false; key["$pref::Shadows::textureScalar"] = 0.5; key["$pref::Shadows::filterMode"] = "None"; }; new ArrayObject( [Low] ) { class = "GraphicsQualityLevel"; caseSensitive = true; key["$pref::lightManager"] = "Advanced Lighting"; key["$pref::Shadows::disable"] = false; key["$pref::Shadows::textureScalar"] = 0.5; key["$pref::Shadows::filterMode"] = "SoftShadow"; }; new ArrayObject( [Normal] ) { class = "GraphicsQualityLevel"; caseSensitive = true; key["$pref::lightManager"] = "Advanced Lighting"; key["$pref::Shadows::disable"] = false; key["$pref::Shadows::textureScalar"] = 1.0; key["$pref::Shadows::filterMode"] = "SoftShadowHighQuality"; }; new ArrayObject( [High] ) { class = "GraphicsQualityLevel"; caseSensitive = true; key["$pref::lightManager"] = "Advanced Lighting"; key["$pref::Shadows::disable"] = false; key["$pref::Shadows::textureScalar"] = 2.0; key["$pref::Shadows::filterMode"] = "SoftShadowHighQuality"; }; }; function LightingQualityGroup::onApply( %this, %level ) { // Set the light manager. This should do nothing // if its already set or if its not compatible. setLightManager( $pref::lightManager ); } // TODO: Reduce shader complexity of water and the scatter sky here! new SimGroup( ShaderQualityGroup ) { new ArrayObject( [Lowest] ) { class = "GraphicsQualityLevel"; caseSensitive = true; key["$pref::Video::disablePixSpecular"] = true; key["$pref::Video::disableNormalmapping"] = true; key["$pref::Video::disableParallaxMapping"] = true; key["$pref::Water::disableTrueReflections"] = true; }; new ArrayObject( [Low] ) { class = "GraphicsQualityLevel"; caseSensitive = true; key["$pref::Video::disablePixSpecular"] = false; key["$pref::Video::disableNormalmapping"] = false; key["$pref::Video::disableParallaxMapping"] = true; key["$pref::Water::disableTrueReflections"] = true; }; new ArrayObject( [Normal] ) { class = "GraphicsQualityLevel"; caseSensitive = true; key["$pref::Video::disablePixSpecular"] = false; key["$pref::Video::disableNormalmapping"] = false; key["$pref::Video::disableParallaxMapping"] = false; key["$pref::Water::disableTrueReflections"] = false; }; new ArrayObject( [High] ) { class = "GraphicsQualityLevel"; caseSensitive = true; key["$pref::Video::disablePixSpecular"] = false; key["$pref::Video::disableNormalmapping"] = false; key["$pref::Video::disableParallaxMapping"] = false; key["$pref::Water::disableTrueReflections"] = false; }; }; function GraphicsQualityAutodetect() { $pref::Video::autoDetect = false; %shaderVer = getPixelShaderVersion(); %intel = ( strstr( strupr( getDisplayDeviceInformation() ), "INTEL" ) != -1 ) ? true : false; %videoMem = GFXCardProfilerAPI::getVideoMemoryMB(); return GraphicsQualityAutodetect_Apply( %shaderVer, %intel, %videoMem ); } function GraphicsQualityAutodetect_Apply( %shaderVer, %intel, %videoMem ) { if ( %shaderVer < 2.0 ) { return "Your video card does not meet the minimum requirment of shader model 2.0."; } if ( %shaderVer < 3.0 || %intel ) { // Allow specular and normals for 2.0a and 2.0b if ( %shaderVer > 2.0 ) { MeshQualityGroup-->Lowest.apply(); TextureQualityGroup-->Lowest.apply(); LightingQualityGroup-->Lowest.apply(); ShaderQualityGroup-->Low.apply(); } else { MeshQualityGroup-->Lowest.apply(); TextureQualityGroup-->Lowest.apply(); LightingQualityGroup-->Lowest.apply(); ShaderQualityGroup-->Lowest.apply(); } } else { if ( %videoMem > 1000 ) { MeshQualityGroup-->High.apply(); TextureQualityGroup-->High.apply(); LightingQualityGroup-->High.apply(); ShaderQualityGroup-->High.apply(); } else if ( %videoMem > 400 || %videoMem == 0 ) { MeshQualityGroup-->Normal.apply(); TextureQualityGroup-->Normal.apply(); LightingQualityGroup-->Normal.apply(); ShaderQualityGroup-->Normal.apply(); if ( %videoMem == 0 ) return "Torque was unable to detect available video memory. Applying 'Normal' quality."; } else { MeshQualityGroup-->Low.apply(); TextureQualityGroup-->Low.apply(); LightingQualityGroup-->Low.apply(); ShaderQualityGroup-->Low.apply(); } } return "Graphics quality settings have been auto detected."; }
using Microsoft.IdentityModel.S2S.Protocols.OAuth2; using Microsoft.IdentityModel.Tokens; using Microsoft.SharePoint.Client; using System; using System.Net; using System.Security.Principal; using System.Web; using System.Web.Configuration; namespace Core.AppEvents.HandlerDelegationWeb { /// <summary> /// Encapsulates all the information from SharePoint. /// </summary> public abstract class SharePointContext { public const string SPHostUrlKey = "SPHostUrl"; public const string SPAppWebUrlKey = "SPAppWebUrl"; public const string SPLanguageKey = "SPLanguage"; public const string SPClientTagKey = "SPClientTag"; public const string SPProductNumberKey = "SPProductNumber"; protected static readonly TimeSpan AccessTokenLifetimeTolerance = TimeSpan.FromMinutes(5.0); private readonly Uri spHostUrl; private readonly Uri spAppWebUrl; private readonly string spLanguage; private readonly string spClientTag; private readonly string spProductNumber; // <AccessTokenString, UtcExpiresOn> protected Tuple<string, DateTime> userAccessTokenForSPHost; protected Tuple<string, DateTime> userAccessTokenForSPAppWeb; protected Tuple<string, DateTime> appOnlyAccessTokenForSPHost; protected Tuple<string, DateTime> appOnlyAccessTokenForSPAppWeb; /// <summary> /// Gets the SharePoint host url from QueryString of the specified HTTP request. /// </summary> /// <param name="httpRequest">The specified HTTP request.</param> /// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns> public static Uri GetSPHostUrl(HttpRequestBase httpRequest) { if (httpRequest == null) { throw new ArgumentNullException("httpRequest"); } string spHostUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SPHostUrlKey]); Uri spHostUrl; if (Uri.TryCreate(spHostUrlString, UriKind.Absolute, out spHostUrl) && (spHostUrl.Scheme == Uri.UriSchemeHttp || spHostUrl.Scheme == Uri.UriSchemeHttps)) { return spHostUrl; } return null; } /// <summary> /// Gets the SharePoint host url from QueryString of the specified HTTP request. /// </summary> /// <param name="httpRequest">The specified HTTP request.</param> /// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns> public static Uri GetSPHostUrl(HttpRequest httpRequest) { return GetSPHostUrl(new HttpRequestWrapper(httpRequest)); } /// <summary> /// The SharePoint host url. /// </summary> public Uri SPHostUrl { get { return this.spHostUrl; } } /// <summary> /// The SharePoint app web url. /// </summary> public Uri SPAppWebUrl { get { return this.spAppWebUrl; } } /// <summary> /// The SharePoint language. /// </summary> public string SPLanguage { get { return this.spLanguage; } } /// <summary> /// The SharePoint client tag. /// </summary> public string SPClientTag { get { return this.spClientTag; } } /// <summary> /// The SharePoint product number. /// </summary> public string SPProductNumber { get { return this.spProductNumber; } } /// <summary> /// The user access token for the SharePoint host. /// </summary> public abstract string UserAccessTokenForSPHost { get; } /// <summary> /// The user access token for the SharePoint app web. /// </summary> public abstract string UserAccessTokenForSPAppWeb { get; } /// <summary> /// The app only access token for the SharePoint host. /// </summary> public abstract string AppOnlyAccessTokenForSPHost { get; } /// <summary> /// The app only access token for the SharePoint app web. /// </summary> public abstract string AppOnlyAccessTokenForSPAppWeb { get; } /// <summary> /// Constructor. /// </summary> /// <param name="spHostUrl">The SharePoint host url.</param> /// <param name="spAppWebUrl">The SharePoint app web url.</param> /// <param name="spLanguage">The SharePoint language.</param> /// <param name="spClientTag">The SharePoint client tag.</param> /// <param name="spProductNumber">The SharePoint product number.</param> protected SharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber) { if (spHostUrl == null) { throw new ArgumentNullException("spHostUrl"); } if (string.IsNullOrEmpty(spLanguage)) { throw new ArgumentNullException("spLanguage"); } if (string.IsNullOrEmpty(spClientTag)) { throw new ArgumentNullException("spClientTag"); } if (string.IsNullOrEmpty(spProductNumber)) { throw new ArgumentNullException("spProductNumber"); } this.spHostUrl = spHostUrl; this.spAppWebUrl = spAppWebUrl; this.spLanguage = spLanguage; this.spClientTag = spClientTag; this.spProductNumber = spProductNumber; } /// <summary> /// Creates a user ClientContext for the SharePoint host. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateUserClientContextForSPHost() { return CreateClientContext(this.SPHostUrl, this.UserAccessTokenForSPHost); } /// <summary> /// Creates a user ClientContext for the SharePoint app web. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateUserClientContextForSPAppWeb() { return CreateClientContext(this.SPAppWebUrl, this.UserAccessTokenForSPAppWeb); } /// <summary> /// Creates app only ClientContext for the SharePoint host. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateAppOnlyClientContextForSPHost() { return CreateClientContext(this.SPHostUrl, this.AppOnlyAccessTokenForSPHost); } /// <summary> /// Creates an app only ClientContext for the SharePoint app web. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateAppOnlyClientContextForSPAppWeb() { return CreateClientContext(this.SPAppWebUrl, this.AppOnlyAccessTokenForSPAppWeb); } /// <summary> /// Gets the database connection string from SharePoint for autohosted app. /// </summary> /// <returns>The database connection string. Returns <c>null</c> if the app is not autohosted or there is no database.</returns> public string GetDatabaseConnectionString() { string dbConnectionString = null; using (ClientContext clientContext = CreateAppOnlyClientContextForSPHost()) { if (clientContext != null) { var result = AppInstance.RetrieveAppDatabaseConnectionString(clientContext); clientContext.ExecuteQuery(); dbConnectionString = result.Value; } } if (dbConnectionString == null) { const string LocalDBInstanceForDebuggingKey = "LocalDBInstanceForDebugging"; var dbConnectionStringSettings = WebConfigurationManager.ConnectionStrings[LocalDBInstanceForDebuggingKey]; dbConnectionString = dbConnectionStringSettings != null ? dbConnectionStringSettings.ConnectionString : null; } return dbConnectionString; } /// <summary> /// Determines if the specified access token is valid. /// It considers an access token as not valid if it is null, or it has expired. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <returns>True if the access token is valid.</returns> protected static bool IsAccessTokenValid(Tuple<string, DateTime> accessToken) { return accessToken != null && !string.IsNullOrEmpty(accessToken.Item1) && accessToken.Item2 > DateTime.UtcNow; } /// <summary> /// Creates a ClientContext with the specified SharePoint site url and the access token. /// </summary> /// <param name="spSiteUrl">The site url.</param> /// <param name="accessToken">The access token.</param> /// <returns>A ClientContext instance.</returns> private static ClientContext CreateClientContext(Uri spSiteUrl, string accessToken) { if (spSiteUrl != null && !string.IsNullOrEmpty(accessToken)) { return TokenHelper.GetClientContextWithAccessToken(spSiteUrl.AbsoluteUri, accessToken); } return null; } } /// <summary> /// Redirection status. /// </summary> public enum RedirectionStatus { Ok, ShouldRedirect, CanNotRedirect } /// <summary> /// Provides SharePointContext instances. /// </summary> public abstract class SharePointContextProvider { private static SharePointContextProvider current; /// <summary> /// The current SharePointContextProvider instance. /// </summary> public static SharePointContextProvider Current { get { return SharePointContextProvider.current; } } /// <summary> /// Initializes the default SharePointContextProvider instance. /// </summary> static SharePointContextProvider() { if (!TokenHelper.IsHighTrustApp()) { SharePointContextProvider.current = new SharePointAcsContextProvider(); } else { SharePointContextProvider.current = new SharePointHighTrustContextProvider(); } } /// <summary> /// Registers the specified SharePointContextProvider instance as current. /// It should be called by Application_Start() in Global.asax. /// </summary> /// <param name="provider">The SharePointContextProvider to be set as current.</param> public static void Register(SharePointContextProvider provider) { if (provider == null) { throw new ArgumentNullException("provider"); } SharePointContextProvider.current = provider; } /// <summary> /// Checks if it is necessary to redirect to SharePoint for user to authenticate. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param> /// <returns>Redirection status.</returns> public static RedirectionStatus CheckRedirectionStatus(HttpContextBase httpContext, out Uri redirectUrl) { if (httpContext == null) { throw new ArgumentNullException("httpContext"); } redirectUrl = null; if (SharePointContextProvider.Current.GetSharePointContext(httpContext) != null) { return RedirectionStatus.Ok; } const string SPHasRedirectedToSharePointKey = "SPHasRedirectedToSharePoint"; if (!string.IsNullOrEmpty(httpContext.Request.QueryString[SPHasRedirectedToSharePointKey])) { return RedirectionStatus.CanNotRedirect; } Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); if (spHostUrl == null) { return RedirectionStatus.CanNotRedirect; } if (StringComparer.OrdinalIgnoreCase.Equals(httpContext.Request.HttpMethod, "POST")) { return RedirectionStatus.CanNotRedirect; } Uri requestUrl = httpContext.Request.Url; var queryNameValueCollection = HttpUtility.ParseQueryString(requestUrl.Query); // Removes the values that are included in {StandardTokens}, as {StandardTokens} will be inserted at the beginning of the query string. queryNameValueCollection.Remove(SharePointContext.SPHostUrlKey); queryNameValueCollection.Remove(SharePointContext.SPAppWebUrlKey); queryNameValueCollection.Remove(SharePointContext.SPLanguageKey); queryNameValueCollection.Remove(SharePointContext.SPClientTagKey); queryNameValueCollection.Remove(SharePointContext.SPProductNumberKey); // Adds SPHasRedirectedToSharePoint=1. queryNameValueCollection.Add(SPHasRedirectedToSharePointKey, "1"); UriBuilder returnUrlBuilder = new UriBuilder(requestUrl); returnUrlBuilder.Query = queryNameValueCollection.ToString(); // Inserts StandardTokens. const string StandardTokens = "{StandardTokens}"; string returnUrlString = returnUrlBuilder.Uri.AbsoluteUri; returnUrlString = returnUrlString.Insert(returnUrlString.IndexOf("?") + 1, StandardTokens + "&"); // Constructs redirect url. string redirectUrlString = TokenHelper.GetAppContextTokenRequestUrl(spHostUrl.AbsoluteUri, Uri.EscapeDataString(returnUrlString)); redirectUrl = new Uri(redirectUrlString, UriKind.Absolute); return RedirectionStatus.ShouldRedirect; } /// <summary> /// Checks if it is necessary to redirect to SharePoint for user to authenticate. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param> /// <returns>Redirection status.</returns> public static RedirectionStatus CheckRedirectionStatus(HttpContext httpContext, out Uri redirectUrl) { return CheckRedirectionStatus(new HttpContextWrapper(httpContext), out redirectUrl); } /// <summary> /// Creates a SharePointContext instance with the specified HTTP request. /// </summary> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> public SharePointContext CreateSharePointContext(HttpRequestBase httpRequest) { if (httpRequest == null) { throw new ArgumentNullException("httpRequest"); } // SPHostUrl Uri spHostUrl = SharePointContext.GetSPHostUrl(httpRequest); if (spHostUrl == null) { return null; } // SPAppWebUrl string spAppWebUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SharePointContext.SPAppWebUrlKey]); Uri spAppWebUrl; if (!Uri.TryCreate(spAppWebUrlString, UriKind.Absolute, out spAppWebUrl) || !(spAppWebUrl.Scheme == Uri.UriSchemeHttp || spAppWebUrl.Scheme == Uri.UriSchemeHttps)) { spAppWebUrl = null; } // SPLanguage string spLanguage = httpRequest.QueryString[SharePointContext.SPLanguageKey]; if (string.IsNullOrEmpty(spLanguage)) { return null; } // SPClientTag string spClientTag = httpRequest.QueryString[SharePointContext.SPClientTagKey]; if (string.IsNullOrEmpty(spClientTag)) { return null; } // SPProductNumber string spProductNumber = httpRequest.QueryString[SharePointContext.SPProductNumberKey]; if (string.IsNullOrEmpty(spProductNumber)) { return null; } return CreateSharePointContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, httpRequest); } /// <summary> /// Creates a SharePointContext instance with the specified HTTP request. /// </summary> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> public SharePointContext CreateSharePointContext(HttpRequest httpRequest) { return CreateSharePointContext(new HttpRequestWrapper(httpRequest)); } /// <summary> /// Gets a SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns> public SharePointContext GetSharePointContext(HttpContextBase httpContext) { if (httpContext == null) { throw new ArgumentNullException("httpContext"); } Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); if (spHostUrl == null) { return null; } SharePointContext spContext = LoadSharePointContext(httpContext); if (spContext == null || !ValidateSharePointContext(spContext, httpContext)) { spContext = CreateSharePointContext(httpContext.Request); if (spContext != null) { SaveSharePointContext(spContext, httpContext); } } return spContext; } /// <summary> /// Gets a SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns> public SharePointContext GetSharePointContext(HttpContext httpContext) { return GetSharePointContext(new HttpContextWrapper(httpContext)); } /// <summary> /// Creates a SharePointContext instance. /// </summary> /// <param name="spHostUrl">The SharePoint host url.</param> /// <param name="spAppWebUrl">The SharePoint app web url.</param> /// <param name="spLanguage">The SharePoint language.</param> /// <param name="spClientTag">The SharePoint client tag.</param> /// <param name="spProductNumber">The SharePoint product number.</param> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> protected abstract SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest); /// <summary> /// Validates if the given SharePointContext can be used with the specified HTTP context. /// </summary> /// <param name="spContext">The SharePointContext.</param> /// <param name="httpContext">The HTTP context.</param> /// <returns>True if the given SharePointContext can be used with the specified HTTP context.</returns> protected abstract bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext); /// <summary> /// Loads the SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found.</returns> protected abstract SharePointContext LoadSharePointContext(HttpContextBase httpContext); /// <summary> /// Saves the specified SharePointContext instance associated with the specified HTTP context. /// <c>null</c> is accepted for clearing the SharePointContext instance associated with the HTTP context. /// </summary> /// <param name="spContext">The SharePointContext instance to be saved, or <c>null</c>.</param> /// <param name="httpContext">The HTTP context.</param> protected abstract void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext); } #region ACS /// <summary> /// Encapsulates all the information from SharePoint in ACS mode. /// </summary> public class SharePointAcsContext : SharePointContext { private readonly string contextToken; private readonly SharePointContextToken contextTokenObj; /// <summary> /// The context token. /// </summary> public string ContextToken { get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextToken : null; } } /// <summary> /// The context token's "CacheKey" claim. /// </summary> public string CacheKey { get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.CacheKey : null; } } /// <summary> /// The context token's "refreshtoken" claim. /// </summary> public string RefreshToken { get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.RefreshToken : null; } } public override string UserAccessTokenForSPHost { get { return GetAccessTokenString(ref this.userAccessTokenForSPHost, () => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPHostUrl.Authority)); } } public override string UserAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb, () => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPAppWebUrl.Authority)); } } public override string AppOnlyAccessTokenForSPHost { get { return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost, () => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPHostUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPHostUrl))); } } public override string AppOnlyAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb, () => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPAppWebUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPAppWebUrl))); } } public SharePointAcsContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, string contextToken, SharePointContextToken contextTokenObj) : base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber) { if (string.IsNullOrEmpty(contextToken)) { throw new ArgumentNullException("contextToken"); } if (contextTokenObj == null) { throw new ArgumentNullException("contextTokenObj"); } this.contextToken = contextToken; this.contextTokenObj = contextTokenObj; } /// <summary> /// Ensures the access token is valid and returns it. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> /// <returns>The access token string.</returns> private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler) { RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler); return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null; } /// <summary> /// Renews the access token if it is not valid. /// </summary> /// <param name="accessToken">The access token to renew.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler) { if (IsAccessTokenValid(accessToken)) { return; } try { OAuth2AccessTokenResponse oAuth2AccessTokenResponse = tokenRenewalHandler(); DateTime expiresOn = oAuth2AccessTokenResponse.ExpiresOn; if ((expiresOn - oAuth2AccessTokenResponse.NotBefore) > AccessTokenLifetimeTolerance) { // Make the access token get renewed a bit earlier than the time when it expires // so that the calls to SharePoint with it will have enough time to complete successfully. expiresOn -= AccessTokenLifetimeTolerance; } accessToken = Tuple.Create(oAuth2AccessTokenResponse.AccessToken, expiresOn); } catch (WebException) { } } } /// <summary> /// Default provider for SharePointAcsContext. /// </summary> public class SharePointAcsContextProvider : SharePointContextProvider { private const string SPContextKey = "SPContext"; private const string SPCacheKeyKey = "SPCacheKey"; protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest) { string contextTokenString = TokenHelper.GetContextTokenFromRequest(httpRequest); if (string.IsNullOrEmpty(contextTokenString)) { return null; } SharePointContextToken contextToken = null; try { contextToken = TokenHelper.ReadAndValidateContextToken(contextTokenString, httpRequest.Url.Authority); } catch (WebException) { return null; } catch (AudienceUriValidationFailedException) { return null; } return new SharePointAcsContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, contextTokenString, contextToken); } protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointAcsContext spAcsContext = spContext as SharePointAcsContext; if (spAcsContext != null) { Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); string contextToken = TokenHelper.GetContextTokenFromRequest(httpContext.Request); HttpCookie spCacheKeyCookie = httpContext.Request.Cookies[SPCacheKeyKey]; string spCacheKey = spCacheKeyCookie != null ? spCacheKeyCookie.Value : null; return spHostUrl == spAcsContext.SPHostUrl && !string.IsNullOrEmpty(spAcsContext.CacheKey) && spCacheKey == spAcsContext.CacheKey && !string.IsNullOrEmpty(spAcsContext.ContextToken) && (string.IsNullOrEmpty(contextToken) || contextToken == spAcsContext.ContextToken); } return false; } protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext) { return httpContext.Session[SPContextKey] as SharePointAcsContext; } protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointAcsContext spAcsContext = spContext as SharePointAcsContext; if (spAcsContext != null) { HttpCookie spCacheKeyCookie = new HttpCookie(SPCacheKeyKey) { Value = spAcsContext.CacheKey, Secure = true, HttpOnly = true }; httpContext.Response.AppendCookie(spCacheKeyCookie); } httpContext.Session[SPContextKey] = spAcsContext; } } #endregion ACS #region HighTrust /// <summary> /// Encapsulates all the information from SharePoint in HighTrust mode. /// </summary> public class SharePointHighTrustContext : SharePointContext { private readonly WindowsIdentity logonUserIdentity; /// <summary> /// The Windows identity for the current user. /// </summary> public WindowsIdentity LogonUserIdentity { get { return this.logonUserIdentity; } } public override string UserAccessTokenForSPHost { get { return GetAccessTokenString(ref this.userAccessTokenForSPHost, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, this.LogonUserIdentity)); } } public override string UserAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, this.LogonUserIdentity)); } } public override string AppOnlyAccessTokenForSPHost { get { return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, null)); } } public override string AppOnlyAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, null)); } } public SharePointHighTrustContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, WindowsIdentity logonUserIdentity) : base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber) { if (logonUserIdentity == null) { throw new ArgumentNullException("logonUserIdentity"); } this.logonUserIdentity = logonUserIdentity; } /// <summary> /// Ensures the access token is valid and returns it. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> /// <returns>The access token string.</returns> private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler) { RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler); return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null; } /// <summary> /// Renews the access token if it is not valid. /// </summary> /// <param name="accessToken">The access token to renew.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler) { if (IsAccessTokenValid(accessToken)) { return; } DateTime expiresOn = DateTime.UtcNow.Add(TokenHelper.HighTrustAccessTokenLifetime); if (TokenHelper.HighTrustAccessTokenLifetime > AccessTokenLifetimeTolerance) { // Make the access token get renewed a bit earlier than the time when it expires // so that the calls to SharePoint with it will have enough time to complete successfully. expiresOn -= AccessTokenLifetimeTolerance; } accessToken = Tuple.Create(tokenRenewalHandler(), expiresOn); } } /// <summary> /// Default provider for SharePointHighTrustContext. /// </summary> public class SharePointHighTrustContextProvider : SharePointContextProvider { private const string SPContextKey = "SPContext"; protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest) { WindowsIdentity logonUserIdentity = httpRequest.LogonUserIdentity; if (logonUserIdentity == null || !logonUserIdentity.IsAuthenticated || logonUserIdentity.IsGuest || logonUserIdentity.User == null) { return null; } return new SharePointHighTrustContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, logonUserIdentity); } protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointHighTrustContext spHighTrustContext = spContext as SharePointHighTrustContext; if (spHighTrustContext != null) { Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); WindowsIdentity logonUserIdentity = httpContext.Request.LogonUserIdentity; return spHostUrl == spHighTrustContext.SPHostUrl && logonUserIdentity != null && logonUserIdentity.IsAuthenticated && !logonUserIdentity.IsGuest && logonUserIdentity.User == spHighTrustContext.LogonUserIdentity.User; } return false; } protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext) { return httpContext.Session[SPContextKey] as SharePointHighTrustContext; } protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { httpContext.Session[SPContextKey] = spContext as SharePointHighTrustContext; } } #endregion HighTrust }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace System.Net.Http { public partial class ByteArrayContent : System.Net.Http.HttpContent { public ByteArrayContent(byte[] content) { } public ByteArrayContent(byte[] content, int offset, int count) { } protected override System.Threading.Tasks.Task<System.IO.Stream> CreateContentReadStreamAsync() { throw null; } protected override System.Threading.Tasks.Task SerializeToStreamAsync(System.IO.Stream stream, System.Net.TransportContext context) { throw null; } protected internal override bool TryComputeLength(out long length) { length = default(long); throw null; } } public enum ClientCertificateOption { Automatic = 1, Manual = 0, } public abstract partial class DelegatingHandler : System.Net.Http.HttpMessageHandler { protected DelegatingHandler() { } protected DelegatingHandler(System.Net.Http.HttpMessageHandler innerHandler) { } public System.Net.Http.HttpMessageHandler InnerHandler { get { throw null; } set { } } protected override void Dispose(bool disposing) { } protected internal override System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> SendAsync(System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) { throw null; } } public partial class FormUrlEncodedContent : System.Net.Http.ByteArrayContent { public FormUrlEncodedContent(System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<string, string>> nameValueCollection) : base (default(byte[])) { } } public partial class HttpClient : System.Net.Http.HttpMessageInvoker { public HttpClient() : base (default(System.Net.Http.HttpMessageHandler)) { } public HttpClient(System.Net.Http.HttpMessageHandler handler) : base (default(System.Net.Http.HttpMessageHandler)) { } public HttpClient(System.Net.Http.HttpMessageHandler handler, bool disposeHandler) : base (default(System.Net.Http.HttpMessageHandler)) { } public System.Uri BaseAddress { get { throw null; } set { } } public System.Net.Http.Headers.HttpRequestHeaders DefaultRequestHeaders { get { throw null; } } public long MaxResponseContentBufferSize { get { throw null; } set { } } public System.TimeSpan Timeout { get { throw null; } set { } } public void CancelPendingRequests() { } public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> DeleteAsync(string requestUri) { throw null; } public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> DeleteAsync(string requestUri, System.Threading.CancellationToken cancellationToken) { throw null; } public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> DeleteAsync(System.Uri requestUri) { throw null; } public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> DeleteAsync(System.Uri requestUri, System.Threading.CancellationToken cancellationToken) { throw null; } protected override void Dispose(bool disposing) { } public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> GetAsync(string requestUri) { throw null; } public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> GetAsync(string requestUri, System.Net.Http.HttpCompletionOption completionOption) { throw null; } public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> GetAsync(string requestUri, System.Net.Http.HttpCompletionOption completionOption, System.Threading.CancellationToken cancellationToken) { throw null; } public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> GetAsync(string requestUri, System.Threading.CancellationToken cancellationToken) { throw null; } public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> GetAsync(System.Uri requestUri) { throw null; } public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> GetAsync(System.Uri requestUri, System.Net.Http.HttpCompletionOption completionOption) { throw null; } public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> GetAsync(System.Uri requestUri, System.Net.Http.HttpCompletionOption completionOption, System.Threading.CancellationToken cancellationToken) { throw null; } public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> GetAsync(System.Uri requestUri, System.Threading.CancellationToken cancellationToken) { throw null; } public System.Threading.Tasks.Task<byte[]> GetByteArrayAsync(string requestUri) { throw null; } public System.Threading.Tasks.Task<byte[]> GetByteArrayAsync(System.Uri requestUri) { throw null; } public System.Threading.Tasks.Task<System.IO.Stream> GetStreamAsync(string requestUri) { throw null; } public System.Threading.Tasks.Task<System.IO.Stream> GetStreamAsync(System.Uri requestUri) { throw null; } public System.Threading.Tasks.Task<string> GetStringAsync(string requestUri) { throw null; } public System.Threading.Tasks.Task<string> GetStringAsync(System.Uri requestUri) { throw null; } public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> PostAsync(string requestUri, System.Net.Http.HttpContent content) { throw null; } public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> PostAsync(string requestUri, System.Net.Http.HttpContent content, System.Threading.CancellationToken cancellationToken) { throw null; } public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> PostAsync(System.Uri requestUri, System.Net.Http.HttpContent content) { throw null; } public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> PostAsync(System.Uri requestUri, System.Net.Http.HttpContent content, System.Threading.CancellationToken cancellationToken) { throw null; } public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> PutAsync(string requestUri, System.Net.Http.HttpContent content) { throw null; } public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> PutAsync(string requestUri, System.Net.Http.HttpContent content, System.Threading.CancellationToken cancellationToken) { throw null; } public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> PutAsync(System.Uri requestUri, System.Net.Http.HttpContent content) { throw null; } public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> PutAsync(System.Uri requestUri, System.Net.Http.HttpContent content, System.Threading.CancellationToken cancellationToken) { throw null; } public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> SendAsync(System.Net.Http.HttpRequestMessage request) { throw null; } public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> SendAsync(System.Net.Http.HttpRequestMessage request, System.Net.Http.HttpCompletionOption completionOption) { throw null; } public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> SendAsync(System.Net.Http.HttpRequestMessage request, System.Net.Http.HttpCompletionOption completionOption, System.Threading.CancellationToken cancellationToken) { throw null; } public override System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> SendAsync(System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) { throw null; } } public partial class HttpClientHandler : System.Net.Http.HttpMessageHandler { public HttpClientHandler() { } public bool AllowAutoRedirect { get { throw null; } set { } } public System.Net.DecompressionMethods AutomaticDecompression { get { throw null; } set { } } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public bool CheckCertificateRevocationList { get { throw null; } set { } } public System.Net.Http.ClientCertificateOption ClientCertificateOptions { get { throw null; } set { } } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public System.Security.Cryptography.X509Certificates.X509CertificateCollection ClientCertificates { get; } public System.Net.CookieContainer CookieContainer { get { throw null; } set { } } public System.Net.ICredentials Credentials { get { throw null; } set { } } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public System.Net.ICredentials DefaultProxyCredentials { get { throw null; } set { } } public int MaxAutomaticRedirections { get { throw null; } set { } } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public int MaxConnectionsPerServer { get { throw null; } set { } } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public int MaxResponseHeadersLength { get { throw null; } set { } } public long MaxRequestContentBufferSize { get { throw null; } set { } } public bool PreAuthenticate { get { throw null; } set { } } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public System.Collections.Generic.IDictionary<string, object> Properties { get { throw null; } } public System.Net.IWebProxy Proxy { get { throw null; } set { } } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public System.Func<System.Net.Http.HttpRequestMessage, System.Security.Cryptography.X509Certificates.X509Certificate2, System.Security.Cryptography.X509Certificates.X509Chain, System.Net.Security.SslPolicyErrors, bool> ServerCertificateCustomValidationCallback { get { throw null; } set { } } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public System.Security.Authentication.SslProtocols SslProtocols { get { throw null; } set { } } public virtual bool SupportsAutomaticDecompression { get { throw null; } } public virtual bool SupportsProxy { get { throw null; } } public virtual bool SupportsRedirectConfiguration { get { throw null; } } public bool UseCookies { get { throw null; } set { } } public bool UseDefaultCredentials { get { throw null; } set { } } public bool UseProxy { get { throw null; } set { } } protected override void Dispose(bool disposing) { } protected internal override System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> SendAsync(System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) { throw null; } } public enum HttpCompletionOption { ResponseContentRead = 0, ResponseHeadersRead = 1, } public abstract partial class HttpContent : System.IDisposable { protected HttpContent() { } public System.Net.Http.Headers.HttpContentHeaders Headers { get { throw null; } } public System.Threading.Tasks.Task CopyToAsync(System.IO.Stream stream) { throw null; } public System.Threading.Tasks.Task CopyToAsync(System.IO.Stream stream, System.Net.TransportContext context) { throw null; } protected virtual System.Threading.Tasks.Task<System.IO.Stream> CreateContentReadStreamAsync() { throw null; } public void Dispose() { } protected virtual void Dispose(bool disposing) { } public System.Threading.Tasks.Task LoadIntoBufferAsync() { throw null; } public System.Threading.Tasks.Task LoadIntoBufferAsync(long maxBufferSize) { throw null; } public System.Threading.Tasks.Task<byte[]> ReadAsByteArrayAsync() { throw null; } public System.Threading.Tasks.Task<System.IO.Stream> ReadAsStreamAsync() { throw null; } public System.Threading.Tasks.Task<string> ReadAsStringAsync() { throw null; } protected abstract System.Threading.Tasks.Task SerializeToStreamAsync(System.IO.Stream stream, System.Net.TransportContext context); protected internal abstract bool TryComputeLength(out long length); } public abstract partial class HttpMessageHandler : System.IDisposable { protected HttpMessageHandler() { } public void Dispose() { } protected virtual void Dispose(bool disposing) { } protected internal abstract System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> SendAsync(System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken); } public partial class HttpMessageInvoker : System.IDisposable { public HttpMessageInvoker(System.Net.Http.HttpMessageHandler handler) { } public HttpMessageInvoker(System.Net.Http.HttpMessageHandler handler, bool disposeHandler) { } public void Dispose() { } protected virtual void Dispose(bool disposing) { } public virtual System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> SendAsync(System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) { throw null; } } public partial class HttpMethod : System.IEquatable<System.Net.Http.HttpMethod> { public HttpMethod(string method) { } public static System.Net.Http.HttpMethod Delete { get { throw null; } } public static System.Net.Http.HttpMethod Get { get { throw null; } } public static System.Net.Http.HttpMethod Head { get { throw null; } } public string Method { get { throw null; } } public static System.Net.Http.HttpMethod Options { get { throw null; } } public static System.Net.Http.HttpMethod Post { get { throw null; } } public static System.Net.Http.HttpMethod Put { get { throw null; } } public static System.Net.Http.HttpMethod Trace { get { throw null; } } public bool Equals(System.Net.Http.HttpMethod other) { throw null; } public override bool Equals(object obj) { throw null; } public override int GetHashCode() { throw null; } public static bool operator ==(System.Net.Http.HttpMethod left, System.Net.Http.HttpMethod right) { throw null; } public static bool operator !=(System.Net.Http.HttpMethod left, System.Net.Http.HttpMethod right) { throw null; } public override string ToString() { throw null; } } public partial class HttpRequestException : System.Exception { public HttpRequestException() { } public HttpRequestException(string message) { } public HttpRequestException(string message, System.Exception inner) { } } public partial class HttpRequestMessage : System.IDisposable { public HttpRequestMessage() { } public HttpRequestMessage(System.Net.Http.HttpMethod method, string requestUri) { } public HttpRequestMessage(System.Net.Http.HttpMethod method, System.Uri requestUri) { } public System.Net.Http.HttpContent Content { get { throw null; } set { } } public System.Net.Http.Headers.HttpRequestHeaders Headers { get { throw null; } } public System.Net.Http.HttpMethod Method { get { throw null; } set { } } public System.Collections.Generic.IDictionary<string, object> Properties { get { throw null; } } public System.Uri RequestUri { get { throw null; } set { } } public System.Version Version { get { throw null; } set { } } public void Dispose() { } protected virtual void Dispose(bool disposing) { } public override string ToString() { throw null; } } public partial class HttpResponseMessage : System.IDisposable { public HttpResponseMessage() { } public HttpResponseMessage(System.Net.HttpStatusCode statusCode) { } public System.Net.Http.HttpContent Content { get { throw null; } set { } } public System.Net.Http.Headers.HttpResponseHeaders Headers { get { throw null; } } public bool IsSuccessStatusCode { get { throw null; } } public string ReasonPhrase { get { throw null; } set { } } public System.Net.Http.HttpRequestMessage RequestMessage { get { throw null; } set { } } public System.Net.HttpStatusCode StatusCode { get { throw null; } set { } } public System.Version Version { get { throw null; } set { } } public void Dispose() { } protected virtual void Dispose(bool disposing) { } public System.Net.Http.HttpResponseMessage EnsureSuccessStatusCode() { throw null; } public override string ToString() { throw null; } } public abstract partial class MessageProcessingHandler : System.Net.Http.DelegatingHandler { protected MessageProcessingHandler() { } protected MessageProcessingHandler(System.Net.Http.HttpMessageHandler innerHandler) { } protected abstract System.Net.Http.HttpRequestMessage ProcessRequest(System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken); protected abstract System.Net.Http.HttpResponseMessage ProcessResponse(System.Net.Http.HttpResponseMessage response, System.Threading.CancellationToken cancellationToken); protected internal sealed override System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> SendAsync(System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) { throw null; } } public partial class MultipartContent : System.Net.Http.HttpContent, System.Collections.Generic.IEnumerable<System.Net.Http.HttpContent>, System.Collections.IEnumerable { public MultipartContent() { } public MultipartContent(string subtype) { } public MultipartContent(string subtype, string boundary) { } public virtual void Add(System.Net.Http.HttpContent content) { } protected override void Dispose(bool disposing) { } public System.Collections.Generic.IEnumerator<System.Net.Http.HttpContent> GetEnumerator() { throw null; } protected override System.Threading.Tasks.Task SerializeToStreamAsync(System.IO.Stream stream, System.Net.TransportContext context) { throw null; } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; } protected internal override bool TryComputeLength(out long length) { length = default(long); throw null; } } public partial class MultipartFormDataContent : System.Net.Http.MultipartContent { public MultipartFormDataContent() { } public MultipartFormDataContent(string boundary) { } public override void Add(System.Net.Http.HttpContent content) { } public void Add(System.Net.Http.HttpContent content, string name) { } public void Add(System.Net.Http.HttpContent content, string name, string fileName) { } } public partial class StreamContent : System.Net.Http.HttpContent { public StreamContent(System.IO.Stream content) { } public StreamContent(System.IO.Stream content, int bufferSize) { } protected override System.Threading.Tasks.Task<System.IO.Stream> CreateContentReadStreamAsync() { throw null; } protected override void Dispose(bool disposing) { } protected override System.Threading.Tasks.Task SerializeToStreamAsync(System.IO.Stream stream, System.Net.TransportContext context) { throw null; } protected internal override bool TryComputeLength(out long length) { length = default(long); throw null; } } public partial class StringContent : System.Net.Http.ByteArrayContent { public StringContent(string content) : base (default(byte[])) { } public StringContent(string content, System.Text.Encoding encoding) : base (default(byte[])) { } public StringContent(string content, System.Text.Encoding encoding, string mediaType) : base (default(byte[])) { } } }
#if !UNITY_EDITOR_OSX || MAC_FORCE_TESTS using System.Runtime.InteropServices; using UnityEngine; using NUnit.Framework; using UnityEditor.VFX.UI; using UnityEngine.Experimental.VFX; using UnityEngine.TestTools; namespace UnityEditor.VFX.Test { [TestFixture] class VFXConverterTests { public struct Conversion { public object value; public System.Type targetType; public object expectedResult; public override string ToString() { return string.Format("Convert {0} to type {1} is {2}", value == null ? (object)"null" : value, targetType.UserFriendlyName(), expectedResult == null ? (object)"null" : expectedResult); } } static Conversion[] s_Conversions; static Conversion[] s_FailingConversions; static Conversion[] conversions { get { BuildValueSources(); return s_Conversions; } } static Conversion[] failingConversions { get { BuildValueSources(); return s_FailingConversions; } } [OneTimeTearDown] public void TearDown() { } static void BuildValueSources() { if (s_Conversions == null) { s_Conversions = new Conversion[] { // Vector3 new Conversion {value = new Vector3(1, 2, 3), targetType = typeof(Vector2), expectedResult = new Vector2(1, 2)}, new Conversion {value = new Vector3(1, 2, 3), targetType = typeof(Vector3), expectedResult = new Vector3(1, 2, 3)}, new Conversion { value = new Vector3(1, 2, 3), targetType = typeof(Vector4), expectedResult = new Vector4(1, 2, 3, 0) }, new Conversion {value = new Vector3(1, 2, 3), targetType = typeof(float), expectedResult = 1.0f}, new Conversion {value = new Vector3(1, 2, 3), targetType = typeof(int), expectedResult = 1}, new Conversion {value = new Vector3(1, 2, 3), targetType = typeof(uint), expectedResult = 1u}, new Conversion { value = new Vector3(0.1f, 0.2f, 0.3f), targetType = typeof(Color), expectedResult = new Color(0.1f, 0.2f, 0.3f) }, // Vector2 new Conversion {value = new Vector2(1, 2), targetType = typeof(Vector2), expectedResult = new Vector2(1, 2)}, new Conversion {value = new Vector2(1, 2), targetType = typeof(Vector3), expectedResult = new Vector3(1, 2, 0)}, new Conversion {value = new Vector2(1, 2), targetType = typeof(Vector4), expectedResult = new Vector4(1, 2, 0, 0)}, new Conversion {value = new Vector2(1, 2), targetType = typeof(float), expectedResult = 1.0f}, new Conversion {value = new Vector2(1, 2), targetType = typeof(int), expectedResult = 1}, new Conversion {value = new Vector2(1, 2), targetType = typeof(uint), expectedResult = 1u}, new Conversion { value = new Vector2(0.1f, 0.2f), targetType = typeof(Color), expectedResult = new Color(0.1f, 0.2f, 0.0f) }, // Vector4 new Conversion {value = new Vector4(1, 2, 3, 4), targetType = typeof(Vector2), expectedResult = new Vector2(1, 2)}, new Conversion { value = new Vector4(1, 2, 3, 4), targetType = typeof(Vector3), expectedResult = new Vector3(1, 2, 3) }, new Conversion { value = new Vector4(1, 2, 3, 4), targetType = typeof(Vector4), expectedResult = new Vector4(1, 2, 3, 4) }, new Conversion {value = new Vector4(1, 2, 3, 4), targetType = typeof(float), expectedResult = 1.0f}, new Conversion {value = new Vector4(1, 2, 3, 4), targetType = typeof(int), expectedResult = 1}, new Conversion {value = new Vector4(1, 2, 3, 4), targetType = typeof(uint), expectedResult = 1u}, new Conversion { value = new Vector4(0.1f, 0.2f, 0.3f, 0.4f), targetType = typeof(Color), expectedResult = new Color(0.1f, 0.2f, 0.3f, 0.4f) }, // Color new Conversion { value = new Color(0.1f, 0.2f, 0.3f, 0.4f), targetType = typeof(Vector2), expectedResult = new Vector2(0.1f, 0.2f) }, new Conversion { value = new Color(0.1f, 0.2f, 0.3f, 0.4f), targetType = typeof(Vector3), expectedResult = new Vector3(0.1f, 0.2f, 0.3f) }, new Conversion { value = new Color(0.1f, 0.2f, 0.3f, 0.4f), targetType = typeof(Vector4), expectedResult = new Vector4(0.1f, 0.2f, 0.3f, 0.4f) }, new Conversion {value = new Color(0.1f, 0.2f, 0.3f, 0.4f), targetType = typeof(float), expectedResult = 0.4f}, new Conversion { value = new Color(0.1f, 0.2f, 0.3f, 0.4f), targetType = typeof(Color), expectedResult = new Color(0.1f, 0.2f, 0.3f, 0.4f) }, new Conversion {value = 1.1f, targetType = typeof(int), expectedResult = 1}, new Conversion {value = 1.1f, targetType = typeof(uint), expectedResult = 1u}, new Conversion {value = -1.1f, targetType = typeof(uint), expectedResult = 0u}, new Conversion {value = (uint)int.MaxValue + 2u, targetType = typeof(int), expectedResult = 0}, new Conversion { value = (uint)int.MaxValue + 2u, targetType = typeof(uint), expectedResult = (uint)int.MaxValue + 2u }, new Conversion {value = null, targetType = typeof(uint), expectedResult = null}, new Conversion {value = null, targetType = typeof(Texture2D), expectedResult = null}, new Conversion {value = null, targetType = typeof(Vector3), expectedResult = null}, new Conversion {value = new Vector3(1, 2, 3), targetType = typeof(DirectionType), expectedResult = new DirectionType() { direction = new Vector3(1, 2, 3) } }, new Conversion {value = new Vector3(4, 5, 6), targetType = typeof(Vector), expectedResult = new Vector() { vector = new Vector3(4, 5, 6) } }, new Conversion {value = new Vector3(7, 8, 9), targetType = typeof(Position), expectedResult = new Position() { position = new Vector3(7, 8, 9) } }, new Conversion {value = new DirectionType() { direction = new Vector3(1, 2, 3) }, targetType = typeof(Vector3), expectedResult = new Vector3(1, 2, 3) }, new Conversion {value = new Vector() { vector = new Vector3(4, 5, 6) }, targetType = typeof(Vector3), expectedResult = new Vector3(4, 5, 6) }, new Conversion {value = new Position() { position = new Vector3(7, 8, 9) }, targetType = typeof(Vector3), expectedResult = new Vector3(7, 8, 9) }, new Conversion {value = 3, targetType = typeof(VFXValueType), expectedResult = VFXValueType.Float3}, new Conversion {value = 3u, targetType = typeof(VFXValueType), expectedResult = VFXValueType.Float3}, new Conversion {value = VFXValueType.Float3, targetType = typeof(int), expectedResult = 3}, new Conversion {value = VFXValueType.Float3, targetType = typeof(uint), expectedResult = 3u} }; s_FailingConversions = new Conversion[] { new Conversion { value = Matrix4x4.TRS(new Vector3(1, 2, 3), Quaternion.Euler(10, 20, 30), new Vector3(4, 5, 6)), targetType = typeof(float), expectedResult = null }, }; } } [Test] public void SimpleConvertTest([ValueSource("conversions")] Conversion conversion) { Assert.AreEqual(conversion.expectedResult, VFXConverter.ConvertTo(conversion.value, conversion.targetType)); } //TEMP disable LogAssert.Expect, still failing running on katana #if _ENABLE_LOG_EXCEPT_TEST [Test] public void FailingConvertTest([ValueSource("failingConversions")] Conversion conversion) { LogAssert.Expect(LogType.Error, string.Format("Cannot cast from {0} to {1}", conversion.value.GetType(), conversion.targetType)); Assert.IsNull(VFXConverter.ConvertTo(conversion.value, conversion.targetType)); } #endif [Test] public void MatrixToTransformTest() { Matrix4x4 value = Matrix4x4.TRS(new Vector3(1, 2, 3), Quaternion.Euler(10, 20, 30), new Vector3(4, 5, 6)); Transform transform = VFXConverter.ConvertTo<Transform>(value); float epsilon = 0.00001f; Assert.AreEqual(transform.position.x, 1, epsilon); Assert.AreEqual(transform.position.y, 2, epsilon); Assert.AreEqual(transform.position.z, 3, epsilon); Assert.AreEqual(transform.angles.x, 10, epsilon); Assert.AreEqual(transform.angles.y, 20, epsilon); Assert.AreEqual(transform.angles.z, 30, epsilon); Assert.AreEqual(transform.scale.x, 4, epsilon); Assert.AreEqual(transform.scale.y, 5, epsilon); Assert.AreEqual(transform.scale.z, 6, epsilon); } } } #endif
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 Mepham.Forum.Api.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; } } }
#region License /* ********************************************************************************** * Copyright (c) Roman Ivantsov * This source code is subject to terms and conditions of the MIT License * for Irony. A copy of the license can be found in the License.txt file * at the root of this distribution. * By using this source code in any fashion, you are agreeing to be bound by the terms of the * MIT License. * You must not remove this notice from this software. * **********************************************************************************/ #endregion //Authors: Roman Ivantsov - initial implementation and some later edits // Philipp Serr - implementation of advanced features for c#, python, VB using System; using System.Collections.Generic; using System.Globalization; using System.Text; using System.Diagnostics; using Irony.Ast; namespace Irony.Parsing { using BigInteger = System.Numerics.BigInteger; //Microsoft.Scripting.Math.BigInteger; using Complex64 = System.Numerics.Complex; using Irony.Ast; // Microsoft.Scripting.Math.Complex64; [Flags] public enum NumberOptions { None = 0, Default = None, AllowStartEndDot = 0x01, //python : http://docs.python.org/ref/floating.html IntOnly = 0x02, NoDotAfterInt = 0x04, //for use with IntOnly flag; essentially tells terminal to avoid matching integer if // it is followed by dot (or exp symbol) - leave to another terminal that will handle float numbers AllowSign = 0x08, DisableQuickParse = 0x10, AllowLetterAfter = 0x20, // allow number be followed by a letter or underscore; by default this flag is not set, so "3a" would not be // recognized as number followed by an identifier AllowUnderscore = 0x40, // Ruby allows underscore inside number: 1_234 //The following should be used with base-identifying prefixes Binary = 0x0100, //e.g. GNU GCC C Extension supports binary number literals Octal = 0x0200, Hex = 0x0400, } public class NumberLiteral : CompoundTerminalBase { //Flags for internal use public enum NumberFlagsInternal : short { HasDot = 0x1000, HasExp = 0x2000, } //nested helper class public class ExponentsTable : Dictionary<char, TypeCode> { } #region Public Consts //currently using TypeCodes for identifying numeric types public const TypeCode TypeCodeBigInt = (TypeCode)30; public const TypeCode TypeCodeImaginary = (TypeCode)31; #endregion #region constructors and initialization public NumberLiteral(string name) : this(name, NumberOptions.Default) { } public NumberLiteral(string name, NumberOptions options, Type astNodeType) : this(name, options) { base.AstConfig.NodeType = astNodeType; } public NumberLiteral(string name, NumberOptions options, AstNodeCreator astNodeCreator) : this(name, options) { base.AstConfig.NodeCreator = astNodeCreator; } public NumberLiteral(string name, NumberOptions options) : base(name) { this.Options = options; base.SetFlag(TermFlags.IsLiteral); } public void AddPrefix(string prefix, NumberOptions options) { this.PrefixFlags.Add(prefix, (short)options); this.Prefixes.Add(prefix); } public void AddExponentSymbols(string symbols, TypeCode floatType) { foreach (var exp in symbols) { this._exponentsTable[exp] = floatType; } } #endregion #region Public fields/properties: ExponentSymbols, Suffixes public NumberOptions Options; public char DecimalSeparator = '.'; //Default types are assigned to literals without suffixes; first matching type used public TypeCode[] DefaultIntTypes = new TypeCode[] { TypeCode.Int32 }; public TypeCode DefaultFloatType = TypeCode.Double; private ExponentsTable _exponentsTable = new ExponentsTable(); public bool IsSet(NumberOptions option) { return (this.Options & option) != 0; } #endregion #region Private fields: _quickParseTerminators #endregion #region overrides public override void Init(GrammarData grammarData) { base.Init(grammarData); //Default Exponent symbols if table is empty if (this._exponentsTable.Count == 0 && !this.IsSet(NumberOptions.IntOnly)) { this._exponentsTable['e'] = this.DefaultFloatType; this._exponentsTable['E'] = this.DefaultFloatType; } if (this.EditorInfo == null) { this.EditorInfo = new TokenEditorInfo(TokenType.Literal, TokenColor.Number, TokenTriggers.None); } } public override IList<string> GetFirsts() { StringList result = new StringList(); result.AddRange(base.Prefixes); //we assume that prefix is always optional, so number can always start with plain digit result.AddRange(new string[] { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" }); // Python float numbers can start with a dot if (this.IsSet(NumberOptions.AllowStartEndDot)) { result.Add(this.DecimalSeparator.ToString()); } if (this.IsSet(NumberOptions.AllowSign)) { result.AddRange(new string[] { "-", "+" }); } return result; } //Most numbers in source programs are just one-digit instances of 0, 1, 2, and maybe others until 9 // so we try to do a quick parse for these, without starting the whole general process protected override Token QuickParse(ParsingContext context, ISourceStream source) { if (this.IsSet(NumberOptions.DisableQuickParse)) { return null; } char current = source.PreviewChar; //it must be a digit followed by a whitespace or delimiter if (!char.IsDigit(current)) { return null; } if (!this.Grammar.IsWhitespaceOrDelimiter(source.NextPreviewChar)) { return null; } int iValue = current - '0'; object value = null; switch (this.DefaultIntTypes[0]) { case TypeCode.Int32: value = iValue; break; case TypeCode.UInt32: value = (UInt32)iValue; break; case TypeCode.Byte: value = (byte)iValue; break; case TypeCode.SByte: value = (sbyte)iValue; break; case TypeCode.Int16: value = (Int16)iValue; break; case TypeCode.UInt16: value = (UInt16)iValue; break; default: return null; } source.PreviewPosition++; return source.CreateToken(this.OutputTerminal, value); } protected override void InitDetails(ParsingContext context, CompoundTokenDetails details) { base.InitDetails(context, details); details.Flags = (short)this.Options; } protected override void ReadPrefix(ISourceStream source, CompoundTokenDetails details) { //check that is not a 0 followed by dot; //this may happen in Python for number "0.123" - we can mistakenly take "0" as octal prefix if (source.PreviewChar == '0' && source.NextPreviewChar == '.') { return; } base.ReadPrefix(source, details); }//method protected override bool ReadBody(ISourceStream source, CompoundTokenDetails details) { //remember start - it may be different from source.TokenStart, we may have skipped prefix int start = source.PreviewPosition; char current = source.PreviewChar; if (this.IsSet(NumberOptions.AllowSign) && (current == '-' || current == '+')) { details.Sign = current.ToString(); source.PreviewPosition++; } //Figure out digits set string digits = this.GetDigits(details); bool isDecimal = !details.IsSet((short)(NumberOptions.Binary | NumberOptions.Octal | NumberOptions.Hex)); bool allowFloat = !this.IsSet(NumberOptions.IntOnly); bool foundDigits = false; while (!source.EOF()) { current = source.PreviewChar; //1. If it is a digit, just continue going; the same for '_' if it is allowed if (digits.IndexOf(current) >= 0 || this.IsSet(NumberOptions.AllowUnderscore) && current == '_') { source.PreviewPosition++; foundDigits = true; continue; } //2. Check if it is a dot in float number bool isDot = current == this.DecimalSeparator; if (allowFloat && isDot) { //If we had seen already a dot or exponent, don't accept this one; bool hasDotOrExp = details.IsSet((short)(NumberFlagsInternal.HasDot | NumberFlagsInternal.HasExp)); if (hasDotOrExp) { break; //from while loop } //In python number literals (NumberAllowPointFloat) a point can be the first and last character, //We accept dot only if it is followed by a digit if (digits.IndexOf(source.NextPreviewChar) < 0 && !this.IsSet(NumberOptions.AllowStartEndDot)) { break; //from while loop } details.Flags |= (int)NumberFlagsInternal.HasDot; source.PreviewPosition++; continue; } //3. Check if it is int number followed by dot or exp symbol bool isExpSymbol = (details.ExponentSymbol == null) && this._exponentsTable.ContainsKey(current); if (!allowFloat && foundDigits && (isDot || isExpSymbol)) { //If no partial float allowed then return false - it is not integer, let float terminal recognize it as float if (this.IsSet(NumberOptions.NoDotAfterInt)) { return false; } //otherwise break, it is integer and we're done reading digits break; } //4. Only for decimals - check if it is (the first) exponent symbol if (allowFloat && isDecimal && isExpSymbol) { char next = source.NextPreviewChar; bool nextIsSign = next == '-' || next == '+'; bool nextIsDigit = digits.IndexOf(next) >= 0; if (!nextIsSign && !nextIsDigit) { break; //Exponent should be followed by either sign or digit } //ok, we've got real exponent details.ExponentSymbol = current.ToString(); //remember the exp char details.Flags |= (int)NumberFlagsInternal.HasExp; source.PreviewPosition++; if (nextIsSign) { source.PreviewPosition++; //skip +/- explicitly so we don't have to deal with them on the next iteration } continue; } //4. It is something else (not digit, not dot or exponent) - we're done break; //from while loop }//while int end = source.PreviewPosition; if (!foundDigits) { return false; } details.Body = source.Text.Substring(start, end - start); return true; } protected internal override void OnValidateToken(ParsingContext context) { if (!this.IsSet(NumberOptions.AllowLetterAfter)) { var current = context.Source.PreviewChar; if (char.IsLetter(current) || current == '_') { context.CurrentToken = context.CreateErrorToken(Resources.ErrNoLetterAfterNum); // "Number cannot be followed by a letter." } } base.OnValidateToken(context); } protected override bool ConvertValue(CompoundTokenDetails details) { if (String.IsNullOrEmpty(details.Body)) { details.Error = Resources.ErrInvNumber; // "Invalid number."; return false; } this.AssignTypeCodes(details); //check for underscore if (this.IsSet(NumberOptions.AllowUnderscore) && details.Body.Contains("_")) { details.Body = details.Body.Replace("_", string.Empty); } //Try quick paths switch (details.TypeCodes[0]) { case TypeCode.Int32: if (this.QuickConvertToInt32(details)) { return true; } break; case TypeCode.Double: if (this.QuickConvertToDouble(details)) { return true; } break; } //Go full cycle details.Value = null; foreach (TypeCode typeCode in details.TypeCodes) { switch (typeCode) { case TypeCode.Single: case TypeCode.Double: case TypeCode.Decimal: case TypeCodeImaginary: return this.ConvertToFloat(typeCode, details); case TypeCode.SByte: case TypeCode.Byte: case TypeCode.Int16: case TypeCode.UInt16: case TypeCode.Int32: case TypeCode.UInt32: case TypeCode.Int64: case TypeCode.UInt64: if (details.Value == null) { //if it is not done yet this.TryConvertToLong(details, typeCode == TypeCode.UInt64); //try to convert to Long/Ulong and place the result into details.Value field; } if (this.TryCastToIntegerType(typeCode, details)) { //now try to cast the ULong value to the target type return true; } break; case TypeCodeBigInt: if (this.ConvertToBigInteger(details)) { return true; } break; }//switch } return false; }//method private void AssignTypeCodes(CompoundTokenDetails details) { //Type could be assigned when we read suffix; if so, just exit if (details.TypeCodes != null) { return; } //Decide on float types var hasDot = details.IsSet((short)(NumberFlagsInternal.HasDot)); var hasExp = details.IsSet((short)(NumberFlagsInternal.HasExp)); var isFloat = (hasDot || hasExp); if (!isFloat) { details.TypeCodes = this.DefaultIntTypes; return; } //so we have a float. If we have exponent symbol then use it to select type if (hasExp) { TypeCode code; if (this._exponentsTable.TryGetValue(details.ExponentSymbol[0], out code)) { details.TypeCodes = new TypeCode[] { code }; return; } }//if hasExp //Finally assign default float type details.TypeCodes = new TypeCode[] { this.DefaultFloatType }; } #endregion #region private utilities private bool QuickConvertToInt32(CompoundTokenDetails details) { int radix = this.GetRadix(details); if (radix == 10 && details.Body.Length > 10) { return false; //10 digits is maximum for int32; int32.MaxValue = 2 147 483 647 } try { //workaround for .Net FX bug: http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=278448 int iValue = 0; if (radix == 10) { iValue = Convert.ToInt32(details.Body, CultureInfo.InvariantCulture); } else { iValue = Convert.ToInt32(details.Body, radix); } details.Value = iValue; return true; } catch { return false; } }//method private bool QuickConvertToDouble(CompoundTokenDetails details) { if (details.IsSet((short)(NumberOptions.Binary | NumberOptions.Octal | NumberOptions.Hex))) { return false; } if (details.IsSet((short)(NumberFlagsInternal.HasExp))) { return false; } if (this.DecimalSeparator != '.') { return false; } double dvalue; if (!double.TryParse(details.Body, NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out dvalue)) { return false; } details.Value = dvalue; return true; } private bool ConvertToFloat(TypeCode typeCode, CompoundTokenDetails details) { //only decimal numbers can be fractions if (details.IsSet((short)(NumberOptions.Binary | NumberOptions.Octal | NumberOptions.Hex))) { details.Error = Resources.ErrInvNumber; // "Invalid number."; return false; } string body = details.Body; //Some languages allow exp symbols other than E. Check if it is the case, and change it to E // - otherwise .NET conversion methods may fail if (details.IsSet((short)NumberFlagsInternal.HasExp) && details.ExponentSymbol.ToUpper() != "E") { body = body.Replace(details.ExponentSymbol, "E"); } //'.' decimal seperator required by invariant culture if (details.IsSet((short)NumberFlagsInternal.HasDot) && this.DecimalSeparator != '.') { body = body.Replace(this.DecimalSeparator, '.'); } switch (typeCode) { case TypeCode.Double: case TypeCodeImaginary: double dValue; if (!Double.TryParse(body, NumberStyles.Float, CultureInfo.InvariantCulture, out dValue)) { return false; } if (typeCode == TypeCodeImaginary) { details.Value = new Complex64(0, dValue); } else { details.Value = dValue; } return true; case TypeCode.Single: float fValue; if (!Single.TryParse(body, NumberStyles.Float, CultureInfo.InvariantCulture, out fValue)) { return false; } details.Value = fValue; return true; case TypeCode.Decimal: decimal decValue; if (!Decimal.TryParse(body, NumberStyles.Float, CultureInfo.InvariantCulture, out decValue)) { return false; } details.Value = decValue; return true; }//switch return false; } private bool TryCastToIntegerType(TypeCode typeCode, CompoundTokenDetails details) { if (details.Value == null) { return false; } try { if (typeCode != TypeCode.UInt64) { details.Value = Convert.ChangeType(details.Value, typeCode, CultureInfo.InvariantCulture); } return true; } catch (Exception) { details.Error = string.Format(Resources.ErrCannotConvertValueToType, details.Value, typeCode.ToString()); return false; } }//method private bool TryConvertToLong(CompoundTokenDetails details, bool useULong) { try { int radix = this.GetRadix(details); //workaround for .Net FX bug: http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=278448 if (radix == 10) { if (useULong) { details.Value = Convert.ToUInt64(details.Body, CultureInfo.InvariantCulture); } else { details.Value = Convert.ToInt64(details.Body, CultureInfo.InvariantCulture); } } else if (useULong) { details.Value = Convert.ToUInt64(details.Body, radix); } else { details.Value = Convert.ToInt64(details.Body, radix); } return true; } catch (OverflowException) { details.Error = string.Format(Resources.ErrCannotConvertValueToType, details.Value, TypeCode.Int64.ToString()); return false; } } private bool ConvertToBigInteger(CompoundTokenDetails details) { //ignore leading zeros and sign details.Body = details.Body.TrimStart('+').TrimStart('-').TrimStart('0'); if (string.IsNullOrEmpty(details.Body)) { details.Body = "0"; } int bodyLength = details.Body.Length; int radix = this.GetRadix(details); int wordLength = this.GetSafeWordLength(details); int sectionCount = this.GetSectionCount(bodyLength, wordLength); ulong[] numberSections = new ulong[sectionCount]; //big endian try { int startIndex = details.Body.Length - wordLength; for (int sectionIndex = sectionCount - 1; sectionIndex >= 0; sectionIndex--) { if (startIndex < 0) { wordLength += startIndex; startIndex = 0; } //workaround for .Net FX bug: http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=278448 if (radix == 10) { numberSections[sectionIndex] = Convert.ToUInt64(details.Body.Substring(startIndex, wordLength)); } else { numberSections[sectionIndex] = Convert.ToUInt64(details.Body.Substring(startIndex, wordLength), radix); } startIndex -= wordLength; } } catch { details.Error = Resources.ErrInvNumber;// "Invalid number."; return false; } //produce big integer ulong safeWordRadix = this.GetSafeWordRadix(details); BigInteger bigIntegerValue = numberSections[0]; for (int i = 1; i < sectionCount; i++) { bigIntegerValue = checked(bigIntegerValue * safeWordRadix + numberSections[i]); } if (details.Sign == "-") { bigIntegerValue = -bigIntegerValue; } details.Value = bigIntegerValue; return true; } private int GetRadix(CompoundTokenDetails details) { if (details.IsSet((short)NumberOptions.Hex)) { return 16; } if (details.IsSet((short)NumberOptions.Octal)) { return 8; } if (details.IsSet((short)NumberOptions.Binary)) { return 2; } return 10; } private string GetDigits(CompoundTokenDetails details) { if (details.IsSet((short)NumberOptions.Hex)) { return Strings.HexDigits; } if (details.IsSet((short)NumberOptions.Octal)) { return Strings.OctalDigits; } if (details.IsSet((short)NumberOptions.Binary)) { return Strings.BinaryDigits; } return Strings.DecimalDigits; } private int GetSafeWordLength(CompoundTokenDetails details) { if (details.IsSet((short)NumberOptions.Hex)) { return 15; } if (details.IsSet((short)NumberOptions.Octal)) { return 21; //maxWordLength 22 } if (details.IsSet((short)NumberOptions.Binary)) { return 63; } return 19; //maxWordLength 20 } private int GetSectionCount(int stringLength, int safeWordLength) { int quotient = stringLength / safeWordLength; int remainder = stringLength - quotient * safeWordLength; return remainder == 0 ? quotient : quotient + 1; } //radix^safeWordLength private ulong GetSafeWordRadix(CompoundTokenDetails details) { if (details.IsSet((short)NumberOptions.Hex)) { return 1152921504606846976; } if (details.IsSet((short)NumberOptions.Octal)) { return 9223372036854775808; } if (details.IsSet((short)NumberOptions.Binary)) { return 9223372036854775808; } return 10000000000000000000; } private static bool IsIntegerCode(TypeCode code) { return (code >= TypeCode.SByte && code <= TypeCode.UInt64); } #endregion }//class }
using Microsoft.CSharp; using Mono.Cecil; using System; using System.CodeDom; using System.Collections.Generic; using System.Linq; using Mono.Collections.Generic; namespace PublicApiGenerator { static class CecilEx { public static IEnumerable<IMemberDefinition> GetMembers(this TypeDefinition type) { return type.Fields.Cast<IMemberDefinition>() .Concat(type.Methods) .Concat(type.Properties) .Concat(type.Events); } public static bool IsUnsafeSignatureType(this TypeReference typeReference) { while (true) { if (typeReference.IsPointer) return true; if (typeReference.IsArray || typeReference.IsByReference) { typeReference = typeReference.GetElementType(); continue; } return false; } } public static bool IsVolatile(this TypeReference typeReference) { return typeReference is RequiredModifierType modType && modType.ModifierType.FullName == "System.Runtime.CompilerServices.IsVolatile"; } public static bool IsUnmanaged(this TypeReference typeReference) { return typeReference is RequiredModifierType modType && modType.ModifierType.FullName == "System.Runtime.InteropServices.UnmanagedType"; } public static bool IsExtensionMethod(this ICustomAttributeProvider method) { return method.CustomAttributes.Any(a => a.AttributeType.FullName == "System.Runtime.CompilerServices.ExtensionAttribute"); } public static bool IsDelegate(this TypeDefinition publicType) { return publicType.BaseType != null && publicType.BaseType.FullName == "System.MulticastDelegate"; } public static bool IsCompilerGenerated(this IMemberDefinition m) { return m.CustomAttributes.Any(a => a.AttributeType.FullName == "System.Runtime.CompilerServices.CompilerGeneratedAttribute"); } public static MemberAttributes CombineAccessorAttributes(MemberAttributes first, MemberAttributes second) { MemberAttributes access = 0; var firstAccess = first & MemberAttributes.AccessMask; var secondAccess = second & MemberAttributes.AccessMask; if (firstAccess == MemberAttributes.Public || secondAccess == MemberAttributes.Public) access = MemberAttributes.Public; else if (firstAccess == MemberAttributes.Family || secondAccess == MemberAttributes.Family) access = MemberAttributes.Family; else if (firstAccess == MemberAttributes.FamilyAndAssembly || secondAccess == MemberAttributes.FamilyAndAssembly) access = MemberAttributes.FamilyAndAssembly; else if (firstAccess == MemberAttributes.FamilyOrAssembly || secondAccess == MemberAttributes.FamilyOrAssembly) access = MemberAttributes.FamilyOrAssembly; else if (firstAccess == MemberAttributes.Assembly || secondAccess == MemberAttributes.Assembly) access = MemberAttributes.Assembly; else if (firstAccess == MemberAttributes.Private || secondAccess == MemberAttributes.Private) access = MemberAttributes.Private; // Scope should be the same for getter and setter. If one isn't specified, it'll be 0 var firstScope = first & MemberAttributes.ScopeMask; var secondScope = second & MemberAttributes.ScopeMask; var scope = (MemberAttributes)Math.Max((int)firstScope, (int)secondScope); // Vtable should be the same for getter and setter. If one isn't specified, it'll be 0 var firstVtable = first & MemberAttributes.VTableMask; var secondVtable = second & MemberAttributes.VTableMask; var vtable = (MemberAttributes)Math.Max((int)firstVtable, (int)secondVtable); return access | scope | vtable; } public static MemberAttributes GetMethodAttributes(this MethodDefinition method) { MemberAttributes access = 0; if (method.IsFamily || method.IsFamilyOrAssembly) access = MemberAttributes.Family; if (method.IsPublic) access = MemberAttributes.Public; if (method.IsAssembly) access = MemberAttributes.Assembly; MemberAttributes scope = 0; if (method.IsStatic) scope |= MemberAttributes.Static; if (method.IsFinal || !method.IsVirtual) scope |= MemberAttributes.Final; if (method.IsAbstract) scope |= MemberAttributes.Abstract; if (method.IsVirtual && !method.IsNewSlot) scope |= MemberAttributes.Override; MemberAttributes vtable = 0; if (IsHidingMethod(method)) vtable = MemberAttributes.New; return access | scope | vtable; } static bool IsHidingMethod(MethodDefinition method) { var typeDefinition = method.DeclaringType; // If we're an interface, just try and find any method with the same signature // in any of the interfaces that we implement if (typeDefinition.IsInterface) { var interfaceMethods = from @interfaceReference in typeDefinition.Interfaces let interfaceDefinition = interfaceReference.InterfaceType.Resolve() where interfaceDefinition != null select interfaceDefinition.Methods; return interfaceMethods.Any(ms => MetadataResolver.GetMethod(ms, method) != null); } // If we're not an interface, find a base method that isn't virtual return !method.IsVirtual && GetBaseTypes(typeDefinition).Any(d => MetadataResolver.GetMethod(d.Methods, method) != null); } static IEnumerable<TypeDefinition> GetBaseTypes(TypeDefinition type) { var baseType = type.BaseType; while (baseType != null) { var definition = baseType.Resolve(); if (definition == null) yield break; yield return definition; baseType = baseType.DeclaringType; } } public static CodeTypeReference MakeReadonly(this CodeTypeReference typeReference) => ModifyCodeTypeReference(typeReference, "readonly"); public static CodeTypeReference MakeUnsafe(this CodeTypeReference typeReference) => ModifyCodeTypeReference(typeReference, "unsafe"); public static CodeTypeReference MakeVolatile(this CodeTypeReference typeReference) => ModifyCodeTypeReference(typeReference, "volatile"); public static CodeTypeReference MakeThis(this CodeTypeReference typeReference) => ModifyCodeTypeReference(typeReference, "this"); public static CodeTypeReference MakeReturn(this CodeTypeReference typeReference) => ModifyCodeTypeReference(typeReference, "return:"); public static CodeTypeReference MakeGet(this CodeTypeReference typeReference) => ModifyCodeTypeReference(typeReference, "get:"); public static CodeTypeReference MakeSet(this CodeTypeReference typeReference) => ModifyCodeTypeReference(typeReference, "set:"); public static CodeTypeReference MakeIn(this CodeTypeReference typeReference) => ModifyCodeTypeReference(typeReference, "in"); static CodeTypeReference ModifyCodeTypeReference(CodeTypeReference typeReference, string modifier) { using (var provider = new CSharpCodeProvider()) { if (typeReference.TypeArguments.Count == 0) // For types without generic arguments we resolve the output type directly to turn System.String into string return new CodeTypeReference(modifier + " " + provider.GetTypeOutput(typeReference)); else // For types with generic types the BaseType is GenericType`<Arity>. Then we cannot resolve the output type and need to pass on the BaseType // to avoid falling into hardcoded assumptions in CodeTypeReference that cuts of the type after the 4th comma. i.ex. readonly Func<string, string, string, string> // works but readonly Func<string, string, string, string, string> would turn into readonly Func<string return new CodeTypeReference(modifier + " " + typeReference.BaseType, typeReference.TypeArguments.Cast<CodeTypeReference>().ToArray()); } } internal static bool? IsNew<TDefinition>(this TDefinition methodDefinition, Func<TypeDefinition, Collection<TDefinition>?> selector, Func<TDefinition, bool> predicate) where TDefinition : IMemberDefinition { bool? isNew = null; var baseType = methodDefinition.DeclaringType.BaseType; while (baseType is TypeDefinition typeDef) { isNew = selector(typeDef).Any(predicate); if (isNew is true) { break; } baseType = typeDef.BaseType; } return isNew; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Xunit; namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.conversion.conversion001.conversion001 { // <Title> Compound operator in conversion.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> // <Expects Status=success></Expects> // <Code> public class Base1 { public int field; } public class Base2 { public int field; } public class TestClass { public int field; public static implicit operator TestClass(Base2 p1) { return new TestClass() { field = p1.field } ; } public static Base2 operator |(TestClass p1, Base1 p2) { return new Base2() { field = (p1.field | p2.field) } ; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] ars) { TestClass l = new TestClass() { field = 8 } ; Base1 r = new Base1() { field = 2 } ; dynamic d0 = l; d0 |= r; dynamic d1 = l; dynamic d2 = r; d1 |= d2; l |= d2; if (d0.field == 10 && d1.field == 10 && l.field == 10) return 0; return 1; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.conversion.conversion002.conversion002 { // <Title> Compound operator in conversion.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> // <Expects Status=success></Expects> // <Code> public class Base1 { public int field; } public class Base2 { public int field; } public class TestClass { public int field; public static explicit operator TestClass(Base2 p1) { return new TestClass() { field = p1.field } ; } public static Base2 operator |(TestClass p1, Base1 p2) { return new Base2() { field = (p1.field | p2.field) } ; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] ars) { TestClass l = new TestClass() { field = 8 } ; Base1 r = new Base1() { field = 2 } ; int flag = 0; dynamic d0 = l; try { d0 |= r; } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e) { if (ErrorVerifier.Verify(ErrorMessageId.NoImplicitConvCast, e.Message, "Base2", "TestClass")) { flag++; } } dynamic d1 = l; dynamic d2 = r; try { d1 |= d2; } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e) { if (ErrorVerifier.Verify(ErrorMessageId.NoImplicitConvCast, e.Message, "Base2", "TestClass")) { flag++; } } try { l |= d2; } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e) { if (ErrorVerifier.Verify(ErrorMessageId.NoImplicitConvCast, e.Message, "Base2", "TestClass")) { flag++; } } if (flag == 0) return 0; return 1; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.conversion.conversion003.conversion003 { // <Title> Compound operator in conversion.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> // <Expects Status=success></Expects> // <Code> public class Test { public int field; public static implicit operator Test(string p1) { return new Test() { field = 10 } ; } public static Test operator +(Test p1, Test p2) { return new Test() { field = (p1.field + p2.field) } ; } [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] ars) { dynamic d0 = new Test() { field = 2 } ; d0 += ""; dynamic d1 = new Test() { field = 2 } ; d1 += "A"; Test d2 = new Test() { field = 2 } ; dynamic t2 = ""; d2 += t2; dynamic d3 = new Test() { field = 2 } ; dynamic t3 = string.Empty; d3 += t3; if (d0.field == 12 && d1.field == 12 && d2.field == 12 && d3.field == 12) return 0; return 1; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.conversion.conversion005.conversion005 { // <Title> Compound operator in conversion.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> // <Expects Status=success></Expects> // <Code> public class Base1 { public int field; } public struct Base2 { public int field; } public struct TestStruct { public int field; public static explicit operator TestStruct(Base2 p1) { return new TestStruct() { field = p1.field } ; } public static Base2 operator *(TestStruct p1, Base1 p2) { return new Base2() { field = (p1.field * 2) } ; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] ars) { TestStruct l = new TestStruct() { field = 8 } ; Base1 r = new Base1() { field = 2 } ; int flag = 0; dynamic d0 = l; try { d0 *= r; } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e) { if (ErrorVerifier.Verify(ErrorMessageId.NoImplicitConvCast, e.Message, "Base2", "TestStruct")) { flag++; } } dynamic d1 = l; try { d1 *= null; } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e) { if (ErrorVerifier.Verify(ErrorMessageId.NoImplicitConvCast, e.Message, "Base2", "TestStruct")) { flag++; } } dynamic d2 = l; dynamic d3 = r; try { d2 *= d3; } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e) { if (ErrorVerifier.Verify(ErrorMessageId.NoImplicitConvCast, e.Message, "Base2", "TestStruct")) { flag++; } } try { l *= d3; } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e) { if (ErrorVerifier.Verify(ErrorMessageId.NoImplicitConvCast, e.Message, "Base2", "TestStruct")) { flag++; } } if (flag == 0) return 0; return 1; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.conversion.conversion006.conversion006 { // <Title> Compound operator in conversion(negative).</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> // <Expects Status=success></Expects> // <Code> public class Base1 { public int field; } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] ars) { Test l = new Test(); Base1 r = new Base1() { field = 2 } ; try { dynamic d0 = l; d0 *= r; } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e) { if (ErrorVerifier.Verify(ErrorMessageId.BadBinaryOps, e.Message, "*=", "Test", "Base1")) return 0; } return 1; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.conversion.conversion007.conversion007 { // <Title> Compound operator in conversion.</Title> // <Description> // Compound operators (d += 10) is Expanding to (d = d + 10), it turns out this does match // the semantics of the equivalent static production. // In the static context, (t += 10) will result of type Test, but in dynamic, the result is type int. // </Description> // <RelatedBugs></RelatedBugs> // <Expects Status=success></Expects> // <Code> public class TestClass { [Fact] public void RunTest() { Test.DynamicCSharpRunTest(); } } public class Test { private int _f1 = 10; public Test() { } public Test(int p1) { _f1 = p1; } public static implicit operator Test(int p1) { return new Test(p1); } public static int operator +(Test t, int p1) { return t._f1 + p1; } public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic d = new Test(); if ((((d += 10).GetType()) == typeof(int)) && (d.GetType() == typeof(int))) { return 0; } return 1; } } //</Code> }
/* * 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 log4net; using Nini.Config; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Services.Interfaces; namespace OpenSim.Region.CoreModules.Avatar.Dialog { public class DialogModule : IRegionModule, IDialogModule { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); protected Scene m_scene; public void Initialise(Scene scene, IConfigSource source) { m_scene = scene; m_scene.RegisterModuleInterface<IDialogModule>(this); m_scene.AddCommand( this, "alert", "alert <first> <last> <message>", "Send an alert to a user", HandleAlertConsoleCommand); m_scene.AddCommand( this, "alert general", "alert [general] <message>", "Send an alert to everyone", "If keyword 'general' is omitted, then <message> must be surrounded by quotation marks.", HandleAlertConsoleCommand); } public void PostInitialise() {} public void Close() {} public string Name { get { return "Dialog Module"; } } public bool IsSharedModule { get { return false; } } public void SendAlertToUser(IClientAPI client, string message) { SendAlertToUser(client, message, false); } public void SendAlertToUser(IClientAPI client, string message, bool modal) { client.SendAgentAlertMessage(message, modal); } public void SendAlertToUser(UUID agentID, string message) { SendAlertToUser(agentID, message, false); } public void SendAlertToUser(UUID agentID, string message, bool modal) { ScenePresence sp = m_scene.GetScenePresence(agentID); if (sp != null) sp.ControllingClient.SendAgentAlertMessage(message, modal); } public void SendAlertToUser(string firstName, string lastName, string message, bool modal) { ScenePresence presence = m_scene.GetScenePresence(firstName, lastName); if (presence != null) presence.ControllingClient.SendAgentAlertMessage(message, modal); } public void SendGeneralAlert(string message) { m_scene.ForEachScenePresence(delegate(ScenePresence presence) { if (!presence.IsChildAgent) presence.ControllingClient.SendAlertMessage(message); }); } public void SendDialogToUser( UUID avatarID, string objectName, UUID objectID, UUID ownerID, string message, UUID textureID, int ch, string[] buttonlabels) { UserAccount account = m_scene.UserAccountService.GetUserAccount(m_scene.RegionInfo.ScopeID, ownerID); string ownerFirstName, ownerLastName; if (account != null) { ownerFirstName = account.FirstName; ownerLastName = account.LastName; } else { ownerFirstName = "(unknown"; ownerLastName = "user)"; } ScenePresence sp = m_scene.GetScenePresence(avatarID); if (sp != null) sp.ControllingClient.SendDialog(objectName, objectID, ownerFirstName, ownerLastName, message, textureID, ch, buttonlabels); } public void SendUrlToUser( UUID avatarID, string objectName, UUID objectID, UUID ownerID, bool groupOwned, string message, string url) { ScenePresence sp = m_scene.GetScenePresence(avatarID); if (sp != null) sp.ControllingClient.SendLoadURL(objectName, objectID, ownerID, groupOwned, message, url); } public void SendTextBoxToUser(UUID avatarid, string message, int chatChannel, string name, UUID objectid, UUID ownerid) { UserAccount account = m_scene.UserAccountService.GetUserAccount(m_scene.RegionInfo.ScopeID, ownerid); string ownerFirstName, ownerLastName; if (account != null) { ownerFirstName = account.FirstName; ownerLastName = account.LastName; } else { ownerFirstName = "(unknown"; ownerLastName = "user)"; } ScenePresence sp = m_scene.GetScenePresence(avatarid); if (sp != null) sp.ControllingClient.SendTextBoxRequest(message, chatChannel, name, ownerFirstName, ownerLastName, objectid); } public void SendNotificationToUsersInRegion( UUID fromAvatarID, string fromAvatarName, string message) { m_scene.ForEachScenePresence(delegate(ScenePresence presence) { if (!presence.IsChildAgent) presence.ControllingClient.SendBlueBoxMessage(fromAvatarID, fromAvatarName, message); }); } /// <summary> /// Handle an alert command from the console. /// </summary> /// <param name="module"></param> /// <param name="cmdparams"></param> public void HandleAlertConsoleCommand(string module, string[] cmdparams) { if (m_scene.ConsoleScene() != null && m_scene.ConsoleScene() != m_scene) return; bool isGeneral = false; string firstName = string.Empty; string lastName = string.Empty; string message = string.Empty; if (cmdparams.Length > 1) { firstName = cmdparams[1]; isGeneral = firstName.ToLower().Equals("general"); } if (cmdparams.Length == 2 && !isGeneral) { // alert "message" message = cmdparams[1]; isGeneral = true; } else if (cmdparams.Length > 2 && isGeneral) { // alert general <message> message = CombineParams(cmdparams, 2); } else if (cmdparams.Length > 3) { // alert <first> <last> <message> lastName = cmdparams[2]; message = CombineParams(cmdparams, 3); } else { OpenSim.Framework.Console.MainConsole.Instance.Output( "Usage: alert \"message\" | alert general <message> | alert <first> <last> <message>"); return; } if (isGeneral) { m_log.InfoFormat( "[DIALOG]: Sending general alert in region {0} with message {1}", m_scene.RegionInfo.RegionName, message); SendGeneralAlert(message); } else { m_log.InfoFormat( "[DIALOG]: Sending alert in region {0} to {1} {2} with message {3}", m_scene.RegionInfo.RegionName, firstName, lastName, message); SendAlertToUser(firstName, lastName, message, false); } } private string CombineParams(string[] commandParams, int pos) { string result = string.Empty; for (int i = pos; i < commandParams.Length; i++) { result += commandParams[i] + " "; } 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. /*============================================================ ** ** ** ** Purpose: The boolean class serves as a wrapper for the primitive ** type boolean. ** ** ===========================================================*/ using System; using System.Globalization; using System.Diagnostics.Contracts; namespace System { // The Boolean class provides the // object representation of the boolean primitive type. [Serializable] [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public struct Boolean : IComparable, IComparable<Boolean>, IEquatable<Boolean>, IConvertible { // // Member Variables // private 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(); } // 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 Boolean)) { return false; } return (m_value == ((Boolean)obj).m_value); } public bool Equals(Boolean 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 Boolean)) { throw new ArgumentException(SR.Arg_MustBeBoolean); } if (m_value == ((Boolean)obj).m_value) { return 0; } else if (m_value == false) { return -1; } return 1; } public int CompareTo(Boolean value) { if (m_value == value) { return 0; } else if (m_value == false) { return -1; } return 1; } // // Static Methods // // Determines whether a String represents true or false. // public static Boolean Parse(String value) { if (value == null) throw new ArgumentNullException(nameof(value)); Contract.EndContractBlock(); Boolean result = false; if (!TryParse(value, out result)) { throw new FormatException(SR.Format_BadBoolean); } else { return result; } } // Determines whether a String represents true or false. // public static Boolean TryParse(String value, out Boolean result) { result = false; if (value == null) { return false; } // For perf reasons, let's first see if they're equal, then do the // trim to get rid of white space, and check again. if (TrueLiteral.Equals(value, StringComparison.OrdinalIgnoreCase)) { result = true; return true; } if (FalseLiteral.Equals(value, StringComparison.OrdinalIgnoreCase)) { result = false; return true; } // Special case: Trim whitespace as well as null characters. value = TrimWhiteSpaceAndNull(value); if (TrueLiteral.Equals(value, StringComparison.OrdinalIgnoreCase)) { result = true; return true; } if (FalseLiteral.Equals(value, StringComparison.OrdinalIgnoreCase)) { result = false; return true; } return false; } private static String TrimWhiteSpaceAndNull(String value) { int start = 0; int end = value.Length - 1; char nullChar = (char)0x0000; while (start < value.Length) { if (!Char.IsWhiteSpace(value[start]) && value[start] != nullChar) { break; } start++; } while (end >= start) { if (!Char.IsWhiteSpace(value[end]) && value[end] != nullChar) { break; } end--; } return value.Substring(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(String.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(String.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.Net.Sockets; using System.Net.Test.Common; using Xunit; using Xunit.Abstractions; namespace System.Net.NetworkInformation.Tests { [PlatformSpecific(PlatformID.Windows)] public class IPInterfacePropertiesTest_Windows { private readonly ITestOutputHelper _log; public IPInterfacePropertiesTest_Windows() { _log = TestLogging.GetInstance(); } [Fact] public void IPInfoTest_AccessAllProperties_NoErrors() { foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces()) { _log.WriteLine("Nic: " + nic.Name); _log.WriteLine("- Supports IPv4: " + nic.Supports(NetworkInterfaceComponent.IPv4)); _log.WriteLine("- Supports IPv6: " + nic.Supports(NetworkInterfaceComponent.IPv6)); IPInterfaceProperties ipProperties = nic.GetIPProperties(); Assert.NotNull(ipProperties); Assert.NotNull(ipProperties.AnycastAddresses); _log.WriteLine("- Anycast Addresses: " + ipProperties.AnycastAddresses.Count); foreach (IPAddressInformation anyAddr in ipProperties.AnycastAddresses) { _log.WriteLine("-- " + anyAddr.Address.ToString()); _log.WriteLine("--- Dns Eligible: " + anyAddr.IsDnsEligible); _log.WriteLine("--- Transient: " + anyAddr.IsTransient); } Assert.NotNull(ipProperties.DhcpServerAddresses); _log.WriteLine("- Dhcp Server Addresses: " + ipProperties.DhcpServerAddresses.Count); foreach (IPAddress dhcp in ipProperties.DhcpServerAddresses) { _log.WriteLine("-- " + dhcp.ToString()); } Assert.NotNull(ipProperties.DnsAddresses); _log.WriteLine("- Dns Addresses: " + ipProperties.DnsAddresses.Count); foreach (IPAddress dns in ipProperties.DnsAddresses) { _log.WriteLine("-- " + dns.ToString()); } Assert.NotNull(ipProperties.DnsSuffix); _log.WriteLine("- Dns Suffix: " + ipProperties.DnsSuffix); Assert.NotNull(ipProperties.GatewayAddresses); _log.WriteLine("- Gateway Addresses: " + ipProperties.GatewayAddresses.Count); foreach (GatewayIPAddressInformation gateway in ipProperties.GatewayAddresses) { _log.WriteLine("-- " + gateway.Address.ToString()); } _log.WriteLine("- Dns Enabled: " + ipProperties.IsDnsEnabled); _log.WriteLine("- Dynamic Dns Enabled: " + ipProperties.IsDynamicDnsEnabled); Assert.NotNull(ipProperties.MulticastAddresses); _log.WriteLine("- Multicast Addresses: " + ipProperties.MulticastAddresses.Count); foreach (IPAddressInformation multi in ipProperties.MulticastAddresses) { _log.WriteLine("-- " + multi.Address.ToString()); _log.WriteLine("--- Dns Eligible: " + multi.IsDnsEligible); _log.WriteLine("--- Transient: " + multi.IsTransient); } Assert.NotNull(ipProperties.UnicastAddresses); _log.WriteLine("- Unicast Addresses: " + ipProperties.UnicastAddresses.Count); foreach (UnicastIPAddressInformation uni in ipProperties.UnicastAddresses) { _log.WriteLine("-- " + uni.Address.ToString()); _log.WriteLine("--- Preferred Lifetime: " + uni.AddressPreferredLifetime); _log.WriteLine("--- Valid Lifetime: " + uni.AddressValidLifetime); _log.WriteLine("--- Dhcp lease Lifetime: " + uni.DhcpLeaseLifetime); _log.WriteLine("--- Duplicate Address Detection State: " + uni.DuplicateAddressDetectionState); Assert.NotNull(uni.IPv4Mask); _log.WriteLine("--- IPv4 Mask: " + uni.IPv4Mask); _log.WriteLine("--- Dns Eligible: " + uni.IsDnsEligible); _log.WriteLine("--- Transient: " + uni.IsTransient); _log.WriteLine("--- Prefix Origin: " + uni.PrefixOrigin); _log.WriteLine("--- Suffix Origin: " + uni.SuffixOrigin); // Prefix Length _log.WriteLine("--- Prefix Length: " + uni.PrefixLength); Assert.NotEqual(0, uni.PrefixLength); } Assert.NotNull(ipProperties.WinsServersAddresses); _log.WriteLine("- Wins Addresses: " + ipProperties.WinsServersAddresses.Count); foreach (IPAddress wins in ipProperties.WinsServersAddresses) { _log.WriteLine("-- " + wins.ToString()); } } } [Fact] public void IPInfoTest_AccessAllIPv4Properties_NoErrors() { foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces()) { _log.WriteLine("Nic: " + nic.Name); IPInterfaceProperties ipProperties = nic.GetIPProperties(); _log.WriteLine("IPv4 Properties:"); if (!nic.Supports(NetworkInterfaceComponent.IPv4)) { var nie = Assert.Throws<NetworkInformationException>(() => ipProperties.GetIPv4Properties()); Assert.Equal(SocketError.ProtocolNotSupported, (SocketError)nie.ErrorCode); continue; } IPv4InterfaceProperties ipv4Properties = ipProperties.GetIPv4Properties(); _log.WriteLine("Index: " + ipv4Properties.Index); _log.WriteLine("IsAutomaticPrivateAddressingActive: " + ipv4Properties.IsAutomaticPrivateAddressingActive); _log.WriteLine("IsAutomaticPrivateAddressingEnabled: " + ipv4Properties.IsAutomaticPrivateAddressingEnabled); _log.WriteLine("IsDhcpEnabled: " + ipv4Properties.IsDhcpEnabled); _log.WriteLine("IsForwardingEnabled: " + ipv4Properties.IsForwardingEnabled); _log.WriteLine("Mtu: " + ipv4Properties.Mtu); _log.WriteLine("UsesWins: " + ipv4Properties.UsesWins); } } [Fact] public void IPInfoTest_AccessAllIPv6Properties_NoErrors() { foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces()) { _log.WriteLine("Nic: " + nic.Name); IPInterfaceProperties ipProperties = nic.GetIPProperties(); _log.WriteLine("IPv6 Properties:"); if (!nic.Supports(NetworkInterfaceComponent.IPv6)) { var nie = Assert.Throws<NetworkInformationException>(() => ipProperties.GetIPv6Properties()); Assert.Equal(SocketError.ProtocolNotSupported, (SocketError)nie.ErrorCode); continue; } IPv6InterfaceProperties ipv6Properties = ipProperties.GetIPv6Properties(); if (ipv6Properties == null) { _log.WriteLine("IPv6Properties is null"); continue; } _log.WriteLine("Index: " + ipv6Properties.Index); _log.WriteLine("Mtu: " + ipv6Properties.Mtu); _log.WriteLine("ScopeID: " + ipv6Properties.GetScopeId(ScopeLevel.Link)); } } [Fact] [Trait("IPv6", "true")] public void IPv6ScopeId_GetLinkLevel_MatchesIndex() { Assert.True(Capability.IPv6Support()); foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces()) { IPInterfaceProperties ipProperties = nic.GetIPProperties(); if (!nic.Supports(NetworkInterfaceComponent.IPv6)) { continue; } IPv6InterfaceProperties ipv6Properties = ipProperties.GetIPv6Properties(); // This is not officially guaranteed by Windows, but it's what gets used. Assert.Equal(ipv6Properties.Index, ipv6Properties.GetScopeId(ScopeLevel.Link)); } } [Fact] [Trait("IPv6", "true")] public void IPv6ScopeId_AccessAllValues_Success() { Assert.True(Capability.IPv6Support()); foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces()) { _log.WriteLine("Nic: " + nic.Name); if (!nic.Supports(NetworkInterfaceComponent.IPv6)) { continue; } IPInterfaceProperties ipProperties = nic.GetIPProperties(); _log.WriteLine("- IPv6 Scope levels:"); IPv6InterfaceProperties ipv6Properties = ipProperties.GetIPv6Properties(); Array values = Enum.GetValues(typeof(ScopeLevel)); foreach (ScopeLevel level in values) { _log.WriteLine("-- Level: " + level + "; " + ipv6Properties.GetScopeId(level)); } } } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.EditAndContinue; using Microsoft.CodeAnalysis.Editor.Implementation.EditAndContinue; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Notification; using Microsoft.CodeAnalysis.Text; using Microsoft.DiaSymReader; using Microsoft.VisualStudio.ComponentModelHost; using Microsoft.VisualStudio.Editor; using Microsoft.VisualStudio.LanguageServices.Implementation.EditAndContinue.Interop; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem; using Microsoft.VisualStudio.LanguageServices.Utilities; using Roslyn.Utilities; using ShellInterop = Microsoft.VisualStudio.Shell.Interop; using VsTextSpan = Microsoft.VisualStudio.TextManager.Interop.TextSpan; using VsThreading = Microsoft.VisualStudio.Threading; using Document = Microsoft.CodeAnalysis.Document; using Microsoft.CodeAnalysis.Debugging; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem.Interop; using Microsoft.VisualStudio.Shell.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.EditAndContinue { internal sealed class VsENCRebuildableProjectImpl { private readonly AbstractProject _vsProject; // number of projects that are in the debug state: private static int s_debugStateProjectCount; // number of projects that are in the break state: private static int s_breakStateProjectCount; // projects that entered the break state: private static readonly List<KeyValuePair<ProjectId, ProjectReadOnlyReason>> s_breakStateEnteredProjects = new List<KeyValuePair<ProjectId, ProjectReadOnlyReason>>(); // active statements of projects that entered the break state: private static readonly List<VsActiveStatement> s_pendingActiveStatements = new List<VsActiveStatement>(); private static VsReadOnlyDocumentTracker s_readOnlyDocumentTracker; internal static readonly TraceLog log = new TraceLog(2048, "EnC"); private static Solution s_breakStateEntrySolution; private static EncDebuggingSessionInfo s_encDebuggingSessionInfo; private readonly IEditAndContinueWorkspaceService _encService; private readonly IActiveStatementTrackingService _trackingService; private readonly EditAndContinueDiagnosticUpdateSource _diagnosticProvider; private readonly IDebugEncNotify _debugEncNotify; private readonly INotificationService _notifications; private readonly IVsEditorAdaptersFactoryService _editorAdaptersFactoryService; #region Per Project State private bool _changesApplied; // maps VS Active Statement Id, which is unique within this project, to our id private Dictionary<uint, ActiveStatementId> _activeStatementIds; private ProjectAnalysisSummary _lastEditSessionSummary = ProjectAnalysisSummary.NoChanges; private HashSet<uint> _activeMethods; private List<VsExceptionRegion> _exceptionRegions; private EmitBaseline _committedBaseline; private EmitBaseline _pendingBaseline; private Project _projectBeingEmitted; private ImmutableArray<DocumentId> _documentsWithEmitError = ImmutableArray<DocumentId>.Empty; /// <summary> /// Initialized when the project switches to debug state. /// Null if the project has no output file or we can't read the MVID. /// </summary> private ModuleMetadata _metadata; private ISymUnmanagedReader3 _pdbReader; private IntPtr _pdbReaderObjAsStream; #endregion private bool IsDebuggable { get { return _metadata != null; } } internal VsENCRebuildableProjectImpl(AbstractProject project) { _vsProject = project; _encService = _vsProject.Workspace.Services.GetService<IEditAndContinueWorkspaceService>(); _trackingService = _vsProject.Workspace.Services.GetService<IActiveStatementTrackingService>(); _notifications = _vsProject.Workspace.Services.GetService<INotificationService>(); _debugEncNotify = (IDebugEncNotify)project.ServiceProvider.GetService(typeof(ShellInterop.SVsShellDebugger)); var componentModel = (IComponentModel)project.ServiceProvider.GetService(typeof(SComponentModel)); _diagnosticProvider = componentModel.GetService<EditAndContinueDiagnosticUpdateSource>(); _editorAdaptersFactoryService = componentModel.GetService<IVsEditorAdaptersFactoryService>(); Debug.Assert(_encService != null); Debug.Assert(_trackingService != null); Debug.Assert(_diagnosticProvider != null); Debug.Assert(_editorAdaptersFactoryService != null); } // called from an edit filter if an edit of a read-only buffer is attempted: internal bool OnEdit(DocumentId documentId) { if (_encService.IsProjectReadOnly(documentId.ProjectId, out var sessionReason, out var projectReason)) { OnReadOnlyDocumentEditAttempt(documentId, sessionReason, projectReason); return true; } return false; } private void OnReadOnlyDocumentEditAttempt( DocumentId documentId, SessionReadOnlyReason sessionReason, ProjectReadOnlyReason projectReason) { if (sessionReason == SessionReadOnlyReason.StoppedAtException) { _debugEncNotify.NotifyEncEditAttemptedAtInvalidStopState(); return; } var visualStudioWorkspace = _vsProject.Workspace as VisualStudioWorkspaceImpl; var hostProject = visualStudioWorkspace?.GetHostProject(documentId.ProjectId) as AbstractProject; if (hostProject?.EditAndContinueImplOpt?._metadata != null) { _debugEncNotify.NotifyEncEditDisallowedByProject(hostProject.Hierarchy); return; } // NotifyEncEditDisallowedByProject is broken if the project isn't built at the time the debugging starts (debugger bug 877586). // TODO: localize messages https://github.com/dotnet/roslyn/issues/16656 string message; if (sessionReason == SessionReadOnlyReason.Running) { message = "Changes are not allowed while code is running."; } else { Debug.Assert(sessionReason == SessionReadOnlyReason.None); switch (projectReason) { case ProjectReadOnlyReason.MetadataNotAvailable: // TODO: Remove once https://github.com/dotnet/roslyn/issues/16657 is addressed bool deferredLoad = (_vsProject.ServiceProvider.GetService(typeof(SVsSolution)) as IVsSolution7)?.IsSolutionLoadDeferred() == true; if (deferredLoad) { message = "Changes are not allowed if the project wasn't loaded and built when debugging started." + Environment.NewLine + Environment.NewLine + "'Lightweight solution load' is enabled for the current solution. " + "Disable it to ensure that all projects are loaded when debugging starts."; s_encDebuggingSessionInfo?.LogReadOnlyEditAttemptedProjectNotBuiltOrLoaded(); } else { message = "Changes are not allowed if the project wasn't built when debugging started."; } break; case ProjectReadOnlyReason.NotLoaded: message = "Changes are not allowed if the assembly has not been loaded."; break; default: throw ExceptionUtilities.UnexpectedValue(projectReason); } } _notifications.SendNotification(message, title: FeaturesResources.Edit_and_Continue1, severity: NotificationSeverity.Error); } /// <summary> /// Since we can't await asynchronous operations we need to wait for them to complete. /// The default SynchronizationContext.Wait pumps messages giving the debugger a chance to /// reenter our EnC implementation. To avoid that we use a specialized SynchronizationContext /// that doesn't pump messages. We need to make sure though that the async methods we wait for /// don't dispatch to foreground thread, otherwise we would end up in a deadlock. /// </summary> private static VsThreading.SpecializedSyncContext NonReentrantContext { get { return VsThreading.ThreadingTools.Apply(VsThreading.NoMessagePumpSyncContext.Default); } } public bool HasCustomMetadataEmitter() { return true; } /// <summary> /// Invoked when the debugger transitions from Design mode to Run mode or Break mode. /// </summary> public int StartDebuggingPE() { try { log.Write("Enter Debug Mode: project '{0}'", _vsProject.DisplayName); // EnC service is global (per solution), but the debugger calls this for each project. // Avoid starting the debug session if it has already been started. if (_encService.DebuggingSession == null) { Debug.Assert(s_debugStateProjectCount == 0); Debug.Assert(s_breakStateProjectCount == 0); Debug.Assert(s_breakStateEnteredProjects.Count == 0); _encService.OnBeforeDebuggingStateChanged(DebuggingState.Design, DebuggingState.Run); _encService.StartDebuggingSession(_vsProject.Workspace.CurrentSolution); s_encDebuggingSessionInfo = new EncDebuggingSessionInfo(); s_readOnlyDocumentTracker = new VsReadOnlyDocumentTracker(_encService, _editorAdaptersFactoryService, _vsProject); } string outputPath = _vsProject.ObjOutputPath; // The project doesn't produce a debuggable binary or we can't read it. // Continue on since the debugger ignores HResults and we need to handle subsequent calls. if (outputPath != null) { try { InjectFault_MvidRead(); _metadata = ModuleMetadata.CreateFromStream(new FileStream(outputPath, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete)); _metadata.GetModuleVersionId(); } catch (FileNotFoundException) { // If the project isn't referenced by the project being debugged it might not be built. // In that case EnC is never allowed for the project, and thus we can assume the project hasn't entered debug state. log.Write("StartDebuggingPE: '{0}' metadata file not found: '{1}'", _vsProject.DisplayName, outputPath); _metadata = null; } catch (Exception e) { log.Write("StartDebuggingPE: error reading MVID of '{0}' ('{1}'): {2}", _vsProject.DisplayName, outputPath, e.Message); _metadata = null; var descriptor = new DiagnosticDescriptor("Metadata", "Metadata", ServicesVSResources.Error_while_reading_0_colon_1, DiagnosticCategory.EditAndContinue, DiagnosticSeverity.Error, isEnabledByDefault: true, customTags: DiagnosticCustomTags.EditAndContinue); _diagnosticProvider.ReportDiagnostics( new EncErrorId(_encService.DebuggingSession, EditAndContinueDiagnosticUpdateSource.DebuggerErrorId), _encService.DebuggingSession.InitialSolution, _vsProject.Id, new[] { Diagnostic.Create(descriptor, Location.None, outputPath, e.Message) }); } } else { log.Write("StartDebuggingPE: project has no output path '{0}'", _vsProject.DisplayName); _metadata = null; } if (_metadata != null) { // The debugger doesn't call EnterBreakStateOnPE for projects that don't have MVID. // However a project that's initially not loaded (but it might be in future) enters // both the debug and break states. s_debugStateProjectCount++; } _activeMethods = new HashSet<uint>(); _exceptionRegions = new List<VsExceptionRegion>(); _activeStatementIds = new Dictionary<uint, ActiveStatementId>(); // The HResult is ignored by the debugger. return VSConstants.S_OK; } catch (Exception e) when (FatalError.ReportWithoutCrash(e)) { return VSConstants.E_FAIL; } } public int StopDebuggingPE() { try { log.Write("Exit Debug Mode: project '{0}'", _vsProject.DisplayName); Debug.Assert(s_breakStateEnteredProjects.Count == 0); // Clear the solution stored while projects were entering break mode. // It should be cleared as soon as all tracked projects enter the break mode // but if the entering break mode fails for some projects we should avoid leaking the solution. Debug.Assert(s_breakStateEntrySolution == null); s_breakStateEntrySolution = null; // EnC service is global (per solution), but the debugger calls this for each project. // Avoid ending the debug session if it has already been ended. if (_encService.DebuggingSession != null) { _encService.OnBeforeDebuggingStateChanged(DebuggingState.Run, DebuggingState.Design); _encService.EndDebuggingSession(); LogEncSession(); s_encDebuggingSessionInfo = null; s_readOnlyDocumentTracker.Dispose(); s_readOnlyDocumentTracker = null; } if (_metadata != null) { _metadata.Dispose(); _metadata = null; s_debugStateProjectCount--; } else { // an error might have been reported: var errorId = new EncErrorId(_encService.DebuggingSession, EditAndContinueDiagnosticUpdateSource.DebuggerErrorId); _diagnosticProvider.ClearDiagnostics(errorId, _vsProject.Workspace.CurrentSolution, _vsProject.Id, documentIdOpt: null); } _activeMethods = null; _exceptionRegions = null; _committedBaseline = null; _activeStatementIds = null; _projectBeingEmitted = null; Debug.Assert(_pdbReaderObjAsStream == IntPtr.Zero || _pdbReader == null); if (_pdbReader != null) { if (Marshal.IsComObject(_pdbReader)) { Marshal.ReleaseComObject(_pdbReader); } _pdbReader = null; } // The HResult is ignored by the debugger. return VSConstants.S_OK; } catch (Exception e) when (FatalError.ReportWithoutCrash(e)) { return VSConstants.E_FAIL; } } private static void LogEncSession() { var sessionId = DebugLogMessage.GetNextId(); Logger.Log(FunctionId.Debugging_EncSession, DebugLogMessage.Create(sessionId, s_encDebuggingSessionInfo)); foreach (var editSession in s_encDebuggingSessionInfo.EditSessions) { var editSessionId = DebugLogMessage.GetNextId(); Logger.Log(FunctionId.Debugging_EncSession_EditSession, DebugLogMessage.Create(sessionId, editSessionId, editSession)); if (editSession.EmitDeltaErrorIds != null) { foreach (var error in editSession.EmitDeltaErrorIds) { Logger.Log(FunctionId.Debugging_EncSession_EditSession_EmitDeltaErrorId, DebugLogMessage.Create(sessionId, editSessionId, error)); } } foreach (var rudeEdit in editSession.RudeEdits) { Logger.Log(FunctionId.Debugging_EncSession_EditSession_RudeEdit, DebugLogMessage.Create(sessionId, editSessionId, rudeEdit, blocking: editSession.HadRudeEdits)); } } } /// <summary> /// Get MVID and file name of the project's output file. /// </summary> /// <remarks> /// The MVID is used by the debugger to identify modules loaded into debuggee that correspond to this project. /// The path seems to be unused. /// /// The output file path might be different from the path of the module loaded into the process. /// For example, the binary produced by the C# compiler is stores in obj directory, /// and then copied to bin directory from which it is loaded to the debuggee. /// /// The binary produced by the compiler can also be rewritten by post-processing tools. /// The debugger assumes that the MVID of the compiler's output file at the time we start debugging session /// is the same as the MVID of the module loaded into debuggee. The original MVID might be different though. /// </remarks> public int GetPEidentity(Guid[] pMVID, string[] pbstrPEName) { Debug.Assert(_encService.DebuggingSession != null); if (_metadata == null) { return VSConstants.E_FAIL; } if (pMVID != null && pMVID.Length != 0) { pMVID[0] = _metadata.GetModuleVersionId(); } if (pbstrPEName != null && pbstrPEName.Length != 0) { var outputPath = _vsProject.ObjOutputPath; Debug.Assert(outputPath != null); pbstrPEName[0] = Path.GetFileName(outputPath); } return VSConstants.S_OK; } /// <summary> /// Called by the debugger when entering a Break state. /// </summary> /// <param name="encBreakReason">Reason for transition to Break state.</param> /// <param name="pActiveStatements">Statements active when the debuggee is stopped.</param> /// <param name="cActiveStatements">Length of <paramref name="pActiveStatements"/>.</param> public int EnterBreakStateOnPE(Interop.ENC_BREAKSTATE_REASON encBreakReason, ShellInterop.ENC_ACTIVE_STATEMENT[] pActiveStatements, uint cActiveStatements) { try { using (NonReentrantContext) { log.Write("Enter {2}Break Mode: project '{0}', AS#: {1}", _vsProject.DisplayName, pActiveStatements != null ? pActiveStatements.Length : -1, encBreakReason == ENC_BREAKSTATE_REASON.ENC_BREAK_EXCEPTION ? "Exception " : ""); Debug.Assert(cActiveStatements == (pActiveStatements != null ? pActiveStatements.Length : 0)); Debug.Assert(s_breakStateProjectCount < s_debugStateProjectCount); Debug.Assert(s_breakStateProjectCount > 0 || _exceptionRegions.Count == 0); Debug.Assert(s_breakStateProjectCount == s_breakStateEnteredProjects.Count); Debug.Assert(IsDebuggable); if (s_breakStateEntrySolution == null) { _encService.OnBeforeDebuggingStateChanged(DebuggingState.Run, DebuggingState.Break); s_breakStateEntrySolution = _vsProject.Workspace.CurrentSolution; // TODO: This is a workaround for a debugger bug in which not all projects exit the break state. // Reset the project count. s_breakStateProjectCount = 0; } ProjectReadOnlyReason state; if (pActiveStatements != null) { AddActiveStatements(s_breakStateEntrySolution, pActiveStatements); state = ProjectReadOnlyReason.None; } else { // unfortunately the debugger doesn't provide details: state = ProjectReadOnlyReason.NotLoaded; } // If pActiveStatements is null the EnC Manager failed to retrieve the module corresponding // to the project in the debuggee. We won't include such projects in the edit session. s_breakStateEnteredProjects.Add(KeyValuePair.Create(_vsProject.Id, state)); s_breakStateProjectCount++; // EnC service is global, but the debugger calls this for each project. // Avoid starting the edit session until all projects enter break state. if (s_breakStateEnteredProjects.Count == s_debugStateProjectCount) { Debug.Assert(_encService.EditSession == null); Debug.Assert(s_pendingActiveStatements.TrueForAll(s => s.Owner._activeStatementIds.Count == 0)); var byDocument = new Dictionary<DocumentId, ImmutableArray<ActiveStatementSpan>>(); // note: fills in activeStatementIds of projects that own the active statements: GroupActiveStatements(s_pendingActiveStatements, byDocument); // When stopped at exception: All documents are read-only, but the files might be changed outside of VS. // So we start an edit session as usual and report a rude edit for all changes we see. bool stoppedAtException = encBreakReason == ENC_BREAKSTATE_REASON.ENC_BREAK_EXCEPTION; var projectStates = ImmutableDictionary.CreateRange(s_breakStateEnteredProjects); _encService.StartEditSession(s_breakStateEntrySolution, byDocument, projectStates, stoppedAtException); _trackingService.StartTracking(_encService.EditSession); s_readOnlyDocumentTracker.UpdateWorkspaceDocuments(); // When tracking is started the tagger is notified and the active statements are highlighted. // Add the handler that notifies the debugger *after* that initial tagger notification, // so that it's not triggered unless an actual change in leaf AS occurs. _trackingService.TrackingSpansChanged += TrackingSpansChanged; } } // The debugger ignores the result. return VSConstants.S_OK; } catch (Exception e) when (FatalError.ReportWithoutCrash(e)) { return VSConstants.E_FAIL; } finally { // TODO: This is a workaround for a debugger bug. // Ensure that the state gets reset even if if `GroupActiveStatements` throws an exception. if (s_breakStateEnteredProjects.Count == s_debugStateProjectCount) { // we don't need these anymore: s_pendingActiveStatements.Clear(); s_breakStateEnteredProjects.Clear(); s_breakStateEntrySolution = null; } } } private void TrackingSpansChanged(bool leafChanged) { //log.Write("Tracking spans changed: {0}", leafChanged); //if (leafChanged) //{ // // fire and forget: // Application.Current.Dispatcher.InvokeAsync(() => // { // log.Write("Notifying debugger of active statement change."); // var debugNotify = (IDebugEncNotify)_vsProject.ServiceProvider.GetService(typeof(ShellInterop.SVsShellDebugger)); // debugNotify.NotifyEncUpdateCurrentStatement(); // }); //} } private struct VsActiveStatement { public readonly DocumentId DocumentId; public readonly uint StatementId; public readonly ActiveStatementSpan Span; public readonly VsENCRebuildableProjectImpl Owner; public VsActiveStatement(VsENCRebuildableProjectImpl owner, uint statementId, DocumentId documentId, ActiveStatementSpan span) { this.Owner = owner; this.StatementId = statementId; this.DocumentId = documentId; this.Span = span; } } private struct VsExceptionRegion { public readonly uint ActiveStatementId; public readonly int Ordinal; public readonly uint MethodToken; public readonly LinePositionSpan Span; public VsExceptionRegion(uint activeStatementId, int ordinal, uint methodToken, LinePositionSpan span) { this.ActiveStatementId = activeStatementId; this.Span = span; this.MethodToken = methodToken; this.Ordinal = ordinal; } } // See InternalApis\vsl\inc\encbuild.idl private const int TEXT_POSITION_ACTIVE_STATEMENT = 1; private void AddActiveStatements(Solution solution, ShellInterop.ENC_ACTIVE_STATEMENT[] vsActiveStatements) { Debug.Assert(_activeMethods.Count == 0); Debug.Assert(_exceptionRegions.Count == 0); foreach (var vsActiveStatement in vsActiveStatements) { log.DebugWrite("+AS[{0}]: {1} {2} {3} {4} '{5}'", unchecked((int)vsActiveStatement.id), vsActiveStatement.tsPosition.iStartLine, vsActiveStatement.tsPosition.iStartIndex, vsActiveStatement.tsPosition.iEndLine, vsActiveStatement.tsPosition.iEndIndex, vsActiveStatement.filename); // TODO (tomat): // Active statement is in user hidden code. The only information that we have from the debugger // is the method token. We don't need to track the statement (it's not in user code anyways), // but we should probably track the list of such methods in order to preserve their local variables. // Not sure what's exactly the scenario here, perhaps modifying async method/iterator? // Dev12 just ignores these. if (vsActiveStatement.posType != TEXT_POSITION_ACTIVE_STATEMENT) { continue; } var flags = (ActiveStatementFlags)vsActiveStatement.ASINFO; // Finds a document id in the solution with the specified file path. DocumentId documentId = solution.GetDocumentIdsWithFilePath(vsActiveStatement.filename) .Where(dId => dId.ProjectId == _vsProject.Id).SingleOrDefault(); if (documentId != null) { var document = solution.GetDocument(documentId); Debug.Assert(document != null); SourceText source = document.GetTextAsync(default(CancellationToken)).Result; LinePositionSpan lineSpan = vsActiveStatement.tsPosition.ToLinePositionSpan(); // If the PDB is out of sync with the source we might get bad spans. var sourceLines = source.Lines; if (lineSpan.End.Line >= sourceLines.Count || sourceLines.GetPosition(lineSpan.End) > sourceLines[sourceLines.Count - 1].EndIncludingLineBreak) { log.Write("AS out of bounds (line count is {0})", source.Lines.Count); continue; } SyntaxNode syntaxRoot = document.GetSyntaxRootAsync(default(CancellationToken)).Result; var analyzer = document.Project.LanguageServices.GetService<IEditAndContinueAnalyzer>(); s_pendingActiveStatements.Add(new VsActiveStatement( this, vsActiveStatement.id, document.Id, new ActiveStatementSpan(flags, lineSpan))); bool isLeaf = (flags & ActiveStatementFlags.LeafFrame) != 0; var ehRegions = analyzer.GetExceptionRegions(source, syntaxRoot, lineSpan, isLeaf); for (int i = 0; i < ehRegions.Length; i++) { _exceptionRegions.Add(new VsExceptionRegion( vsActiveStatement.id, i, vsActiveStatement.methodToken, ehRegions[i])); } } _activeMethods.Add(vsActiveStatement.methodToken); } } private static void GroupActiveStatements( IEnumerable<VsActiveStatement> activeStatements, Dictionary<DocumentId, ImmutableArray<ActiveStatementSpan>> byDocument) { var spans = new List<ActiveStatementSpan>(); foreach (var grouping in activeStatements.GroupBy(s => s.DocumentId)) { var documentId = grouping.Key; foreach (var activeStatement in grouping.OrderBy(s => s.Span.Span.Start)) { int ordinal = spans.Count; // register vsid with the project that owns the active statement: activeStatement.Owner._activeStatementIds.Add(activeStatement.StatementId, new ActiveStatementId(documentId, ordinal)); spans.Add(activeStatement.Span); } byDocument.Add(documentId, spans.AsImmutable()); spans.Clear(); } } /// <summary> /// Returns the number of exception regions around current active statements. /// This is called when the project is entering a break right after /// <see cref="EnterBreakStateOnPE"/> and prior to <see cref="GetExceptionSpans"/>. /// </summary> /// <remarks> /// Called by EnC manager. /// </remarks> public int GetExceptionSpanCount(out uint pcExceptionSpan) { pcExceptionSpan = (uint)_exceptionRegions.Count; return VSConstants.S_OK; } /// <summary> /// Returns information about exception handlers in the source. /// </summary> /// <remarks> /// Called by EnC manager. /// </remarks> public int GetExceptionSpans(uint celt, ShellInterop.ENC_EXCEPTION_SPAN[] rgelt, ref uint pceltFetched) { Debug.Assert(celt == rgelt.Length); Debug.Assert(celt == _exceptionRegions.Count); for (int i = 0; i < _exceptionRegions.Count; i++) { rgelt[i] = new ShellInterop.ENC_EXCEPTION_SPAN() { id = (uint)i, methodToken = _exceptionRegions[i].MethodToken, tsPosition = _exceptionRegions[i].Span.ToVsTextSpan() }; } pceltFetched = celt; return VSConstants.S_OK; } /// <summary> /// Called by the debugger whenever it needs to determine a position of an active statement. /// E.g. the user clicks on a frame in a call stack. /// </summary> /// <remarks> /// Called when applying change, when setting current IP, a notification is received from /// <see cref="IDebugEncNotify.NotifyEncUpdateCurrentStatement"/>, etc. /// In addition this API is exposed on IDebugENC2 COM interface so it can be used anytime by other components. /// </remarks> public int GetCurrentActiveStatementPosition(uint vsId, VsTextSpan[] ptsNewPosition) { try { using (NonReentrantContext) { Debug.Assert(IsDebuggable); var session = _encService.EditSession; var ids = _activeStatementIds; // Can be called anytime, even outside of an edit/debug session. // We might not have an active statement available if PDB got out of sync with the source. if (session == null || ids == null || !ids.TryGetValue(vsId, out var id)) { log.Write("GetCurrentActiveStatementPosition failed for AS {0}.", unchecked((int)vsId)); return VSConstants.E_FAIL; } Document document = _vsProject.Workspace.CurrentSolution.GetDocument(id.DocumentId); SourceText text = document.GetTextAsync(default(CancellationToken)).Result; LinePositionSpan lineSpan; // Try to get spans from the tracking service first. // We might get an imprecise result if the document analysis hasn't been finished yet and // the active statement has structurally changed, but that's ok. The user won't see an updated tag // for the statement until the analysis finishes anyways. if (_trackingService.TryGetSpan(id, text, out var span) && span.Length > 0) { lineSpan = text.Lines.GetLinePositionSpan(span); } else { var activeSpans = session.GetDocumentAnalysis(document).GetValue(default(CancellationToken)).ActiveStatements; if (activeSpans.IsDefault) { // The document has syntax errors and the tracking span is gone. log.Write("Position not available for AS {0} due to syntax errors", unchecked((int)vsId)); return VSConstants.E_FAIL; } lineSpan = activeSpans[id.Ordinal]; } ptsNewPosition[0] = lineSpan.ToVsTextSpan(); log.DebugWrite("AS position: {0} ({1},{2})-({3},{4}) {5}", unchecked((int)vsId), lineSpan.Start.Line, lineSpan.Start.Character, lineSpan.End.Line, lineSpan.End.Character, (int)session.BaseActiveStatements[id.DocumentId][id.Ordinal].Flags); return VSConstants.S_OK; } } catch (Exception e) when (FatalError.ReportWithoutCrash(e)) { return VSConstants.E_FAIL; } } /// <summary> /// Returns the state of the changes made to the source. /// The EnC manager calls this to determine whether there are any changes to the source /// and if so whether there are any rude edits. /// </summary> public int GetENCBuildState(ShellInterop.ENC_BUILD_STATE[] pENCBuildState) { try { using (NonReentrantContext) { Debug.Assert(pENCBuildState != null && pENCBuildState.Length == 1); // GetENCBuildState is called outside of edit session (at least) in following cases: // 1) when the debugger is determining whether a source file checksum matches the one in PDB. // 2) when the debugger is setting the next statement and a change is pending // See CDebugger::SetNextStatement(CTextPos* pTextPos, bool WarnOnFunctionChange): // // pENC2->ExitBreakState(); // >>> hr = GetCodeContextOfPosition(pTextPos, &pCodeContext, &pProgram, true, true); // pENC2->EnterBreakState(m_pSession, GetEncBreakReason()); // // The debugger seem to expect ENC_NOT_MODIFIED in these cases, otherwise errors occur. if (_changesApplied || _encService.EditSession == null) { _lastEditSessionSummary = ProjectAnalysisSummary.NoChanges; } else { // Fetch the latest snapshot of the project and get an analysis summary for any changes // made since the break mode was entered. var currentProject = _vsProject.Workspace.CurrentSolution.GetProject(_vsProject.Id); if (currentProject == null) { // If the project has yet to be loaded into the solution (which may be the case, // since they are loaded on-demand), then it stands to reason that it has not yet // been modified. // TODO (https://github.com/dotnet/roslyn/issues/1204): this check should be unnecessary. _lastEditSessionSummary = ProjectAnalysisSummary.NoChanges; log.Write("Project '{0}' has not yet been loaded into the solution", _vsProject.DisplayName); } else { _projectBeingEmitted = currentProject; _lastEditSessionSummary = GetProjectAnalysisSummary(_projectBeingEmitted); } _encService.EditSession.LogBuildState(_lastEditSessionSummary); } switch (_lastEditSessionSummary) { case ProjectAnalysisSummary.NoChanges: pENCBuildState[0] = ShellInterop.ENC_BUILD_STATE.ENC_NOT_MODIFIED; break; case ProjectAnalysisSummary.CompilationErrors: pENCBuildState[0] = ShellInterop.ENC_BUILD_STATE.ENC_COMPILE_ERRORS; break; case ProjectAnalysisSummary.RudeEdits: pENCBuildState[0] = ShellInterop.ENC_BUILD_STATE.ENC_NONCONTINUABLE_ERRORS; break; case ProjectAnalysisSummary.ValidChanges: case ProjectAnalysisSummary.ValidInsignificantChanges: // The debugger doesn't distinguish between these two. pENCBuildState[0] = ShellInterop.ENC_BUILD_STATE.ENC_APPLY_READY; break; default: throw ExceptionUtilities.UnexpectedValue(_lastEditSessionSummary); } log.Write("EnC state of '{0}' queried: {1}{2}", _vsProject.DisplayName, EncStateToString(pENCBuildState[0]), _encService.EditSession != null ? "" : " (no session)"); return VSConstants.S_OK; } } catch (Exception e) when (FatalError.ReportWithoutCrash(e)) { return VSConstants.E_FAIL; } } private static string EncStateToString(ENC_BUILD_STATE state) { switch (state) { case ENC_BUILD_STATE.ENC_NOT_MODIFIED: return "ENC_NOT_MODIFIED"; case ENC_BUILD_STATE.ENC_NONCONTINUABLE_ERRORS: return "ENC_NONCONTINUABLE_ERRORS"; case ENC_BUILD_STATE.ENC_COMPILE_ERRORS: return "ENC_COMPILE_ERRORS"; case ENC_BUILD_STATE.ENC_APPLY_READY: return "ENC_APPLY_READY"; default: return state.ToString(); } } private ProjectAnalysisSummary GetProjectAnalysisSummary(Project project) { if (!IsDebuggable) { return ProjectAnalysisSummary.NoChanges; } var cancellationToken = default(CancellationToken); return _encService.EditSession.GetProjectAnalysisSummaryAsync(project, cancellationToken).Result; } public int ExitBreakStateOnPE() { try { using (NonReentrantContext) { // The debugger calls Exit without previously calling Enter if the project's MVID isn't available. if (!IsDebuggable) { return VSConstants.S_OK; } log.Write("Exit Break Mode: project '{0}'", _vsProject.DisplayName); // EnC service is global, but the debugger calls this for each project. // Avoid ending the edit session if it has already been ended. if (_encService.EditSession != null) { Debug.Assert(s_breakStateProjectCount == s_debugStateProjectCount); _encService.OnBeforeDebuggingStateChanged(DebuggingState.Break, DebuggingState.Run); _encService.EditSession.LogEditSession(s_encDebuggingSessionInfo); _encService.EndEditSession(); _trackingService.EndTracking(); s_readOnlyDocumentTracker.UpdateWorkspaceDocuments(); _trackingService.TrackingSpansChanged -= TrackingSpansChanged; } _exceptionRegions.Clear(); _activeMethods.Clear(); _activeStatementIds.Clear(); s_breakStateProjectCount--; Debug.Assert(s_breakStateProjectCount >= 0); _changesApplied = false; _diagnosticProvider.ClearDiagnostics( new EncErrorId(_encService.DebuggingSession, EditAndContinueDiagnosticUpdateSource.EmitErrorId), _vsProject.Workspace.CurrentSolution, _vsProject.Id, _documentsWithEmitError); _documentsWithEmitError = ImmutableArray<DocumentId>.Empty; } // HResult ignored by the debugger return VSConstants.S_OK; } catch (Exception e) when (FatalError.ReportWithoutCrash(e)) { return VSConstants.E_FAIL; } } public unsafe int BuildForEnc(object pUpdatePE) { try { log.Write("Applying changes to {0}", _vsProject.DisplayName); Debug.Assert(_encService.EditSession != null); Debug.Assert(!_encService.EditSession.StoppedAtException); // Non-debuggable project has no changes. Debug.Assert(IsDebuggable); if (_changesApplied) { log.Write("Changes already applied to {0}, can't apply again", _vsProject.DisplayName); throw ExceptionUtilities.Unreachable; } // The debugger always calls GetENCBuildState right before BuildForEnc. Debug.Assert(_projectBeingEmitted != null); Debug.Assert(_lastEditSessionSummary == GetProjectAnalysisSummary(_projectBeingEmitted)); // The debugger should have called GetENCBuildState before calling BuildForEnc. // Unfortunately, there is no way how to tell the debugger that the changes were not significant, // so we'll to emit an empty delta. See bug 839558. Debug.Assert(_lastEditSessionSummary == ProjectAnalysisSummary.ValidInsignificantChanges || _lastEditSessionSummary == ProjectAnalysisSummary.ValidChanges); var updater = (IDebugUpdateInMemoryPE2)pUpdatePE; if (_committedBaseline == null) { var hr = MarshalPdbReader(updater, out _pdbReaderObjAsStream, out _pdbReader); if (hr != VSConstants.S_OK) { return hr; } _committedBaseline = EmitBaseline.CreateInitialBaseline(_metadata, GetBaselineEncDebugInfo); } // ISymUnmanagedReader can only be accessed from an MTA thread, // so dispatch it to one of thread pool threads, which are MTA. var emitTask = Task.Factory.SafeStartNew(EmitProjectDelta, CancellationToken.None, TaskScheduler.Default); Deltas delta; using (NonReentrantContext) { delta = emitTask.Result; if (delta == null) { // Non-fatal Watson has already been reported by the emit task return VSConstants.E_FAIL; } } var errorId = new EncErrorId(_encService.DebuggingSession, EditAndContinueDiagnosticUpdateSource.EmitErrorId); // Clear diagnostics, in case the project was built before and failed due to errors. _diagnosticProvider.ClearDiagnostics(errorId, _projectBeingEmitted.Solution, _vsProject.Id, _documentsWithEmitError); if (!delta.EmitResult.Success) { var errors = delta.EmitResult.Diagnostics.Where(d => d.Severity == DiagnosticSeverity.Error); _documentsWithEmitError = _diagnosticProvider.ReportDiagnostics(errorId, _projectBeingEmitted.Solution, _vsProject.Id, errors); _encService.EditSession.LogEmitProjectDeltaErrors(errors.Select(e => e.Id)); return VSConstants.E_FAIL; } _documentsWithEmitError = ImmutableArray<DocumentId>.Empty; SetFileUpdates(updater, delta.LineEdits); updater.SetDeltaIL(delta.IL.Value, (uint)delta.IL.Value.Length); updater.SetDeltaPdb(SymUnmanagedStreamFactory.CreateStream(delta.Pdb.Stream)); updater.SetRemapMethods(delta.Pdb.UpdatedMethods, (uint)delta.Pdb.UpdatedMethods.Length); updater.SetDeltaMetadata(delta.Metadata.Bytes, (uint)delta.Metadata.Bytes.Length); _pendingBaseline = delta.EmitResult.Baseline; #if DEBUG fixed (byte* deltaMetadataPtr = &delta.Metadata.Bytes[0]) { var reader = new System.Reflection.Metadata.MetadataReader(deltaMetadataPtr, delta.Metadata.Bytes.Length); var moduleDef = reader.GetModuleDefinition(); log.DebugWrite("Gen {0}: MVID={1}, BaseId={2}, EncId={3}", moduleDef.Generation, reader.GetGuid(moduleDef.Mvid).ToString(), reader.GetGuid(moduleDef.BaseGenerationId).ToString(), reader.GetGuid(moduleDef.GenerationId).ToString()); } #endif return VSConstants.S_OK; } catch (Exception e) when (FatalError.ReportWithoutCrash(e)) { return VSConstants.E_FAIL; } } private unsafe void SetFileUpdates( IDebugUpdateInMemoryPE2 updater, List<KeyValuePair<DocumentId, ImmutableArray<LineChange>>> edits) { int totalEditCount = edits.Sum(e => e.Value.Length); if (totalEditCount == 0) { return; } var lineUpdates = new LINEUPDATE[totalEditCount]; fixed (LINEUPDATE* lineUpdatesPtr = lineUpdates) { int index = 0; var fileUpdates = new FILEUPDATE[edits.Count]; for (int f = 0; f < fileUpdates.Length; f++) { var documentId = edits[f].Key; var deltas = edits[f].Value; fileUpdates[f].FileName = _vsProject.GetDocumentOrAdditionalDocument(documentId).FilePath; fileUpdates[f].LineUpdateCount = (uint)deltas.Length; fileUpdates[f].LineUpdates = (IntPtr)(lineUpdatesPtr + index); for (int l = 0; l < deltas.Length; l++) { lineUpdates[index + l].Line = (uint)deltas[l].OldLine; lineUpdates[index + l].UpdatedLine = (uint)deltas[l].NewLine; } index += deltas.Length; } // The updater makes a copy of all data, we can release the buffer after the call. updater.SetFileUpdates(fileUpdates, (uint)fileUpdates.Length); } } private Deltas EmitProjectDelta() { Debug.Assert(Thread.CurrentThread.GetApartmentState() == ApartmentState.MTA); var emitTask = _encService.EditSession.EmitProjectDeltaAsync(_projectBeingEmitted, _committedBaseline, default(CancellationToken)); return emitTask.Result; } /// <summary> /// Returns EnC debug information for initial version of the specified method. /// </summary> /// <exception cref="InvalidDataException">The debug information data is corrupt or can't be retrieved from the debugger.</exception> private EditAndContinueMethodDebugInformation GetBaselineEncDebugInfo(MethodDefinitionHandle methodHandle) { Debug.Assert(Thread.CurrentThread.GetApartmentState() == ApartmentState.MTA); InitializePdbReader(); return GetEditAndContinueMethodDebugInfo(_pdbReader, methodHandle); } private void InitializePdbReader() { Debug.Assert(Thread.CurrentThread.GetApartmentState() == ApartmentState.MTA); if (_pdbReader == null) { // Unmarshal the symbol reader (being marshalled cross thread from STA -> MTA). Debug.Assert(_pdbReaderObjAsStream != IntPtr.Zero); var exception = Marshal.GetExceptionForHR(NativeMethods.GetObjectForStream(_pdbReaderObjAsStream, out object pdbReaderObjMta)); if (exception != null) { // likely a bug in the compiler/debugger FatalError.ReportWithoutCrash(exception); throw new InvalidDataException(exception.Message, exception); } _pdbReaderObjAsStream = IntPtr.Zero; _pdbReader = (ISymUnmanagedReader3)pdbReaderObjMta; } } private static EditAndContinueMethodDebugInformation GetEditAndContinueMethodDebugInfo(ISymUnmanagedReader3 symReader, MethodDefinitionHandle methodHandle) { return TryGetPortableEncDebugInfo(symReader, methodHandle, out var info) ? info : GetNativeEncDebugInfo(symReader, methodHandle); } private static unsafe bool TryGetPortableEncDebugInfo(ISymUnmanagedReader symReader, MethodDefinitionHandle methodHandle, out EditAndContinueMethodDebugInformation info) { if (!(symReader is ISymUnmanagedReader5 symReader5)) { info = default(EditAndContinueMethodDebugInformation); return false; } int hr = symReader5.GetPortableDebugMetadataByVersion(version: 1, metadata: out byte* metadata, size: out int size); Marshal.ThrowExceptionForHR(hr); if (hr != 0) { info = default(EditAndContinueMethodDebugInformation); return false; } var pdbReader = new System.Reflection.Metadata.MetadataReader(metadata, size); ImmutableArray<byte> GetCdiBytes(Guid kind) => TryGetCustomDebugInformation(pdbReader, methodHandle, kind, out var cdi) ? pdbReader.GetBlobContent(cdi.Value) : default(ImmutableArray<byte>); info = EditAndContinueMethodDebugInformation.Create( compressedSlotMap: GetCdiBytes(PortableCustomDebugInfoKinds.EncLocalSlotMap), compressedLambdaMap: GetCdiBytes(PortableCustomDebugInfoKinds.EncLambdaAndClosureMap)); return true; } /// <exception cref="BadImageFormatException">Invalid data format.</exception> private static bool TryGetCustomDebugInformation(System.Reflection.Metadata.MetadataReader reader, EntityHandle handle, Guid kind, out CustomDebugInformation customDebugInfo) { bool foundAny = false; customDebugInfo = default(CustomDebugInformation); foreach (var infoHandle in reader.GetCustomDebugInformation(handle)) { var info = reader.GetCustomDebugInformation(infoHandle); var id = reader.GetGuid(info.Kind); if (id == kind) { if (foundAny) { throw new BadImageFormatException(); } customDebugInfo = info; foundAny = true; } } return foundAny; } private static EditAndContinueMethodDebugInformation GetNativeEncDebugInfo(ISymUnmanagedReader3 symReader, MethodDefinitionHandle methodHandle) { int methodToken = MetadataTokens.GetToken(methodHandle); byte[] debugInfo; try { debugInfo = symReader.GetCustomDebugInfo(methodToken, methodVersion: 1); } catch (ArgumentOutOfRangeException) { // Sometimes the debugger returns the HRESULT for ArgumentOutOfRangeException, rather than E_FAIL, // for methods without custom debug info (https://github.com/dotnet/roslyn/issues/4138). debugInfo = null; } catch (Exception e) when (FatalError.ReportWithoutCrash(e)) // likely a bug in the compiler/debugger { throw new InvalidDataException(e.Message, e); } try { ImmutableArray<byte> localSlots, lambdaMap; if (debugInfo != null) { localSlots = CustomDebugInfoReader.TryGetCustomDebugInfoRecord(debugInfo, CustomDebugInfoKind.EditAndContinueLocalSlotMap); lambdaMap = CustomDebugInfoReader.TryGetCustomDebugInfoRecord(debugInfo, CustomDebugInfoKind.EditAndContinueLambdaMap); } else { localSlots = lambdaMap = default(ImmutableArray<byte>); } return EditAndContinueMethodDebugInformation.Create(localSlots, lambdaMap); } catch (InvalidOperationException e) when (FatalError.ReportWithoutCrash(e)) // likely a bug in the compiler/debugger { // TODO: CustomDebugInfoReader should throw InvalidDataException throw new InvalidDataException(e.Message, e); } } public int EncApplySucceeded(int hrApplyResult) { try { log.Write("Change applied to {0}", _vsProject.DisplayName); Debug.Assert(IsDebuggable); Debug.Assert(_encService.EditSession != null); Debug.Assert(!_encService.EditSession.StoppedAtException); Debug.Assert(_pendingBaseline != null); // Since now on until exiting the break state, we consider the changes applied and the project state should be NoChanges. _changesApplied = true; _committedBaseline = _pendingBaseline; _pendingBaseline = null; return VSConstants.S_OK; } catch (Exception e) when (FatalError.ReportWithoutCrash(e)) { return VSConstants.E_FAIL; } } /// <summary> /// Called when changes are being applied. /// </summary> /// <param name="exceptionRegionId"> /// The value of <see cref="ShellInterop.ENC_EXCEPTION_SPAN.id"/>. /// Set by <see cref="GetExceptionSpans(uint, ShellInterop.ENC_EXCEPTION_SPAN[], ref uint)"/> to the index into <see cref="_exceptionRegions"/>. /// </param> /// <param name="ptsNewPosition">Output value holder.</param> public int GetCurrentExceptionSpanPosition(uint exceptionRegionId, VsTextSpan[] ptsNewPosition) { try { using (NonReentrantContext) { Debug.Assert(IsDebuggable); Debug.Assert(_encService.EditSession != null); Debug.Assert(!_encService.EditSession.StoppedAtException); Debug.Assert(ptsNewPosition.Length == 1); var exceptionRegion = _exceptionRegions[(int)exceptionRegionId]; var session = _encService.EditSession; var asid = _activeStatementIds[exceptionRegion.ActiveStatementId]; var document = _projectBeingEmitted.GetDocument(asid.DocumentId); var analysis = session.GetDocumentAnalysis(document).GetValue(default(CancellationToken)); var regions = analysis.ExceptionRegions; // the method shouldn't be called in presence of errors: Debug.Assert(!analysis.HasChangesAndErrors); Debug.Assert(!regions.IsDefault); // Absence of rude edits guarantees that the exception regions around AS haven't semantically changed. // Only their spans might have changed. ptsNewPosition[0] = regions[asid.Ordinal][exceptionRegion.Ordinal].ToVsTextSpan(); } return VSConstants.S_OK; } catch (Exception e) when (FatalError.ReportWithoutCrash(e)) { return VSConstants.E_FAIL; } } private static int MarshalPdbReader(IDebugUpdateInMemoryPE2 updater, out IntPtr pdbReaderPointer, out ISymUnmanagedReader3 managedSymReader) { // ISymUnmanagedReader can only be accessed from an MTA thread, however, we need // fetch the IUnknown instance (call IENCSymbolReaderProvider.GetSymbolReader) here // in the STA. To further complicate things, we need to return synchronously from // this method. Waiting for the MTA thread to complete so we can return synchronously // blocks the STA thread, so we need to make sure the CLR doesn't try to marshal // ISymUnmanagedReader calls made in an MTA back to the STA for execution (if this // happens we'll be deadlocked). We'll use CoMarshalInterThreadInterfaceInStream to // achieve this. First, we'll marshal the object in a Stream and pass a Stream pointer // over to the MTA. In the MTA, we'll get the Stream from the pointer and unmarshal // the object. The reader object was originally created on an MTA thread, and the // instance we retrieved in the STA was a proxy. When we unmarshal the Stream in the // MTA, it "unwraps" the proxy, allowing us to directly call the implementation. // Another way to achieve this would be for the symbol reader to implement IAgileObject, // but the symbol reader we use today does not. If that changes, we should consider // removing this marshal/unmarshal code. updater.GetENCDebugInfo(out IENCDebugInfo debugInfo); var symbolReaderProvider = (IENCSymbolReaderProvider)debugInfo; symbolReaderProvider.GetSymbolReader(out object pdbReaderObjSta); if (Marshal.IsComObject(pdbReaderObjSta)) { int hr = NativeMethods.GetStreamForObject(pdbReaderObjSta, out pdbReaderPointer); Marshal.ReleaseComObject(pdbReaderObjSta); managedSymReader = null; return hr; } else { pdbReaderPointer = IntPtr.Zero; managedSymReader = (ISymUnmanagedReader3)pdbReaderObjSta; return 0; } } #region Testing #if DEBUG // Fault injection: // If set we'll fail to read MVID of specified projects to test error reporting. internal static ImmutableArray<string> InjectMvidReadingFailure; private void InjectFault_MvidRead() { if (!InjectMvidReadingFailure.IsDefault && InjectMvidReadingFailure.Contains(_vsProject.DisplayName)) { throw new IOException("Fault injection"); } } #else [Conditional("DEBUG")] private void InjectFault_MvidRead() { } #endif #endregion } }
using System; using System.Collections.Generic; using Android.Runtime; namespace Com.Tencent.Mapsdk.Raster.Model { // Metadata.xml XPath class reference: path="/api/package[@name='com.tencent.mapsdk.raster.model']/class[@name='Polyline']" [global::Android.Runtime.Register ("com/tencent/mapsdk/raster/model/Polyline", DoNotGenerateAcw=true)] public partial class Polyline : global::Java.Lang.Object { internal static IntPtr java_class_handle; internal static IntPtr class_ref { get { return JNIEnv.FindClass ("com/tencent/mapsdk/raster/model/Polyline", ref java_class_handle); } } protected override IntPtr ThresholdClass { get { return class_ref; } } protected override global::System.Type ThresholdType { get { return typeof (Polyline); } } protected Polyline (IntPtr javaReference, JniHandleOwnership transfer) : base (javaReference, transfer) {} static Delegate cb_getColor; #pragma warning disable 0169 static Delegate GetGetColorHandler () { if (cb_getColor == null) cb_getColor = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, int>) n_GetColor); return cb_getColor; } static int n_GetColor (IntPtr jnienv, IntPtr native__this) { global::Com.Tencent.Mapsdk.Raster.Model.Polyline __this = global::Java.Lang.Object.GetObject<global::Com.Tencent.Mapsdk.Raster.Model.Polyline> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); return __this.Color; } #pragma warning restore 0169 static Delegate cb_setColor_I; #pragma warning disable 0169 static Delegate GetSetColor_IHandler () { if (cb_setColor_I == null) cb_setColor_I = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, int>) n_SetColor_I); return cb_setColor_I; } static void n_SetColor_I (IntPtr jnienv, IntPtr native__this, int p0) { global::Com.Tencent.Mapsdk.Raster.Model.Polyline __this = global::Java.Lang.Object.GetObject<global::Com.Tencent.Mapsdk.Raster.Model.Polyline> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); __this.Color = p0; } #pragma warning restore 0169 static IntPtr id_getColor; static IntPtr id_setColor_I; public virtual int Color { // Metadata.xml XPath method reference: path="/api/package[@name='com.tencent.mapsdk.raster.model']/class[@name='Polyline']/method[@name='getColor' and count(parameter)=0]" [Register ("getColor", "()I", "GetGetColorHandler")] get { if (id_getColor == IntPtr.Zero) id_getColor = JNIEnv.GetMethodID (class_ref, "getColor", "()I"); if (GetType () == ThresholdType) return JNIEnv.CallIntMethod (Handle, id_getColor); else return JNIEnv.CallNonvirtualIntMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "getColor", "()I")); } // Metadata.xml XPath method reference: path="/api/package[@name='com.tencent.mapsdk.raster.model']/class[@name='Polyline']/method[@name='setColor' and count(parameter)=1 and parameter[1][@type='int']]" [Register ("setColor", "(I)V", "GetSetColor_IHandler")] set { if (id_setColor_I == IntPtr.Zero) id_setColor_I = JNIEnv.GetMethodID (class_ref, "setColor", "(I)V"); if (GetType () == ThresholdType) JNIEnv.CallVoidMethod (Handle, id_setColor_I, new JValue (value)); else JNIEnv.CallNonvirtualVoidMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "setColor", "(I)V"), new JValue (value)); } } static Delegate cb_isDottedLine; #pragma warning disable 0169 static Delegate GetIsDottedLineHandler () { if (cb_isDottedLine == null) cb_isDottedLine = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, bool>) n_IsDottedLine); return cb_isDottedLine; } static bool n_IsDottedLine (IntPtr jnienv, IntPtr native__this) { global::Com.Tencent.Mapsdk.Raster.Model.Polyline __this = global::Java.Lang.Object.GetObject<global::Com.Tencent.Mapsdk.Raster.Model.Polyline> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); return __this.DottedLine; } #pragma warning restore 0169 static Delegate cb_setDottedLine_Z; #pragma warning disable 0169 static Delegate GetSetDottedLine_ZHandler () { if (cb_setDottedLine_Z == null) cb_setDottedLine_Z = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, bool>) n_SetDottedLine_Z); return cb_setDottedLine_Z; } static void n_SetDottedLine_Z (IntPtr jnienv, IntPtr native__this, bool p0) { global::Com.Tencent.Mapsdk.Raster.Model.Polyline __this = global::Java.Lang.Object.GetObject<global::Com.Tencent.Mapsdk.Raster.Model.Polyline> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); __this.DottedLine = p0; } #pragma warning restore 0169 static IntPtr id_isDottedLine; static IntPtr id_setDottedLine_Z; public virtual bool DottedLine { // Metadata.xml XPath method reference: path="/api/package[@name='com.tencent.mapsdk.raster.model']/class[@name='Polyline']/method[@name='isDottedLine' and count(parameter)=0]" [Register ("isDottedLine", "()Z", "GetIsDottedLineHandler")] get { if (id_isDottedLine == IntPtr.Zero) id_isDottedLine = JNIEnv.GetMethodID (class_ref, "isDottedLine", "()Z"); if (GetType () == ThresholdType) return JNIEnv.CallBooleanMethod (Handle, id_isDottedLine); else return JNIEnv.CallNonvirtualBooleanMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "isDottedLine", "()Z")); } // Metadata.xml XPath method reference: path="/api/package[@name='com.tencent.mapsdk.raster.model']/class[@name='Polyline']/method[@name='setDottedLine' and count(parameter)=1 and parameter[1][@type='boolean']]" [Register ("setDottedLine", "(Z)V", "GetSetDottedLine_ZHandler")] set { if (id_setDottedLine_Z == IntPtr.Zero) id_setDottedLine_Z = JNIEnv.GetMethodID (class_ref, "setDottedLine", "(Z)V"); if (GetType () == ThresholdType) JNIEnv.CallVoidMethod (Handle, id_setDottedLine_Z, new JValue (value)); else JNIEnv.CallNonvirtualVoidMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "setDottedLine", "(Z)V"), new JValue (value)); } } static Delegate cb_isGeodesic; #pragma warning disable 0169 static Delegate GetIsGeodesicHandler () { if (cb_isGeodesic == null) cb_isGeodesic = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, bool>) n_IsGeodesic); return cb_isGeodesic; } static bool n_IsGeodesic (IntPtr jnienv, IntPtr native__this) { global::Com.Tencent.Mapsdk.Raster.Model.Polyline __this = global::Java.Lang.Object.GetObject<global::Com.Tencent.Mapsdk.Raster.Model.Polyline> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); return __this.Geodesic; } #pragma warning restore 0169 static Delegate cb_setGeodesic_Z; #pragma warning disable 0169 static Delegate GetSetGeodesic_ZHandler () { if (cb_setGeodesic_Z == null) cb_setGeodesic_Z = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, bool>) n_SetGeodesic_Z); return cb_setGeodesic_Z; } static void n_SetGeodesic_Z (IntPtr jnienv, IntPtr native__this, bool p0) { global::Com.Tencent.Mapsdk.Raster.Model.Polyline __this = global::Java.Lang.Object.GetObject<global::Com.Tencent.Mapsdk.Raster.Model.Polyline> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); __this.Geodesic = p0; } #pragma warning restore 0169 static IntPtr id_isGeodesic; static IntPtr id_setGeodesic_Z; public virtual bool Geodesic { // Metadata.xml XPath method reference: path="/api/package[@name='com.tencent.mapsdk.raster.model']/class[@name='Polyline']/method[@name='isGeodesic' and count(parameter)=0]" [Register ("isGeodesic", "()Z", "GetIsGeodesicHandler")] get { if (id_isGeodesic == IntPtr.Zero) id_isGeodesic = JNIEnv.GetMethodID (class_ref, "isGeodesic", "()Z"); if (GetType () == ThresholdType) return JNIEnv.CallBooleanMethod (Handle, id_isGeodesic); else return JNIEnv.CallNonvirtualBooleanMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "isGeodesic", "()Z")); } // Metadata.xml XPath method reference: path="/api/package[@name='com.tencent.mapsdk.raster.model']/class[@name='Polyline']/method[@name='setGeodesic' and count(parameter)=1 and parameter[1][@type='boolean']]" [Register ("setGeodesic", "(Z)V", "GetSetGeodesic_ZHandler")] set { if (id_setGeodesic_Z == IntPtr.Zero) id_setGeodesic_Z = JNIEnv.GetMethodID (class_ref, "setGeodesic", "(Z)V"); if (GetType () == ThresholdType) JNIEnv.CallVoidMethod (Handle, id_setGeodesic_Z, new JValue (value)); else JNIEnv.CallNonvirtualVoidMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "setGeodesic", "(Z)V"), new JValue (value)); } } static Delegate cb_getId; #pragma warning disable 0169 static Delegate GetGetIdHandler () { if (cb_getId == null) cb_getId = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, IntPtr>) n_GetId); return cb_getId; } static IntPtr n_GetId (IntPtr jnienv, IntPtr native__this) { global::Com.Tencent.Mapsdk.Raster.Model.Polyline __this = global::Java.Lang.Object.GetObject<global::Com.Tencent.Mapsdk.Raster.Model.Polyline> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); return JNIEnv.NewString (__this.Id); } #pragma warning restore 0169 static IntPtr id_getId; public virtual string Id { // Metadata.xml XPath method reference: path="/api/package[@name='com.tencent.mapsdk.raster.model']/class[@name='Polyline']/method[@name='getId' and count(parameter)=0]" [Register ("getId", "()Ljava/lang/String;", "GetGetIdHandler")] get { if (id_getId == IntPtr.Zero) id_getId = JNIEnv.GetMethodID (class_ref, "getId", "()Ljava/lang/String;"); if (GetType () == ThresholdType) return JNIEnv.GetString (JNIEnv.CallObjectMethod (Handle, id_getId), JniHandleOwnership.TransferLocalRef); else return JNIEnv.GetString (JNIEnv.CallNonvirtualObjectMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "getId", "()Ljava/lang/String;")), JniHandleOwnership.TransferLocalRef); } } static Delegate cb_getPoints; #pragma warning disable 0169 static Delegate GetGetPointsHandler () { if (cb_getPoints == null) cb_getPoints = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, IntPtr>) n_GetPoints); return cb_getPoints; } static IntPtr n_GetPoints (IntPtr jnienv, IntPtr native__this) { global::Com.Tencent.Mapsdk.Raster.Model.Polyline __this = global::Java.Lang.Object.GetObject<global::Com.Tencent.Mapsdk.Raster.Model.Polyline> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); return global::Android.Runtime.JavaList<global::Com.Tencent.Mapsdk.Raster.Model.LatLng>.ToLocalJniHandle (__this.Points); } #pragma warning restore 0169 static Delegate cb_setPoints_Ljava_util_List_; #pragma warning disable 0169 static Delegate GetSetPoints_Ljava_util_List_Handler () { if (cb_setPoints_Ljava_util_List_ == null) cb_setPoints_Ljava_util_List_ = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, IntPtr>) n_SetPoints_Ljava_util_List_); return cb_setPoints_Ljava_util_List_; } static void n_SetPoints_Ljava_util_List_ (IntPtr jnienv, IntPtr native__this, IntPtr native_p0) { global::Com.Tencent.Mapsdk.Raster.Model.Polyline __this = global::Java.Lang.Object.GetObject<global::Com.Tencent.Mapsdk.Raster.Model.Polyline> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); System.Collections.Generic.IList<Com.Tencent.Mapsdk.Raster.Model.LatLng> p0 = global::Android.Runtime.JavaList<global::Com.Tencent.Mapsdk.Raster.Model.LatLng>.FromJniHandle (native_p0, JniHandleOwnership.DoNotTransfer); __this.Points = p0; } #pragma warning restore 0169 static IntPtr id_getPoints; static IntPtr id_setPoints_Ljava_util_List_; public virtual global::System.Collections.Generic.IList<global::Com.Tencent.Mapsdk.Raster.Model.LatLng> Points { // Metadata.xml XPath method reference: path="/api/package[@name='com.tencent.mapsdk.raster.model']/class[@name='Polyline']/method[@name='getPoints' and count(parameter)=0]" [Register ("getPoints", "()Ljava/util/List;", "GetGetPointsHandler")] get { if (id_getPoints == IntPtr.Zero) id_getPoints = JNIEnv.GetMethodID (class_ref, "getPoints", "()Ljava/util/List;"); if (GetType () == ThresholdType) return global::Android.Runtime.JavaList<global::Com.Tencent.Mapsdk.Raster.Model.LatLng>.FromJniHandle (JNIEnv.CallObjectMethod (Handle, id_getPoints), JniHandleOwnership.TransferLocalRef); else return global::Android.Runtime.JavaList<global::Com.Tencent.Mapsdk.Raster.Model.LatLng>.FromJniHandle (JNIEnv.CallNonvirtualObjectMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "getPoints", "()Ljava/util/List;")), JniHandleOwnership.TransferLocalRef); } // Metadata.xml XPath method reference: path="/api/package[@name='com.tencent.mapsdk.raster.model']/class[@name='Polyline']/method[@name='setPoints' and count(parameter)=1 and parameter[1][@type='java.util.List']]" [Register ("setPoints", "(Ljava/util/List;)V", "GetSetPoints_Ljava_util_List_Handler")] set { if (id_setPoints_Ljava_util_List_ == IntPtr.Zero) id_setPoints_Ljava_util_List_ = JNIEnv.GetMethodID (class_ref, "setPoints", "(Ljava/util/List;)V"); IntPtr native_value = global::Android.Runtime.JavaList<global::Com.Tencent.Mapsdk.Raster.Model.LatLng>.ToLocalJniHandle (value); if (GetType () == ThresholdType) JNIEnv.CallVoidMethod (Handle, id_setPoints_Ljava_util_List_, new JValue (native_value)); else JNIEnv.CallNonvirtualVoidMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "setPoints", "(Ljava/util/List;)V"), new JValue (native_value)); JNIEnv.DeleteLocalRef (native_value); } } static Delegate cb_isVisible; #pragma warning disable 0169 static Delegate GetIsVisibleHandler () { if (cb_isVisible == null) cb_isVisible = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, bool>) n_IsVisible); return cb_isVisible; } static bool n_IsVisible (IntPtr jnienv, IntPtr native__this) { global::Com.Tencent.Mapsdk.Raster.Model.Polyline __this = global::Java.Lang.Object.GetObject<global::Com.Tencent.Mapsdk.Raster.Model.Polyline> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); return __this.Visible; } #pragma warning restore 0169 static Delegate cb_setVisible_Z; #pragma warning disable 0169 static Delegate GetSetVisible_ZHandler () { if (cb_setVisible_Z == null) cb_setVisible_Z = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, bool>) n_SetVisible_Z); return cb_setVisible_Z; } static void n_SetVisible_Z (IntPtr jnienv, IntPtr native__this, bool p0) { global::Com.Tencent.Mapsdk.Raster.Model.Polyline __this = global::Java.Lang.Object.GetObject<global::Com.Tencent.Mapsdk.Raster.Model.Polyline> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); __this.Visible = p0; } #pragma warning restore 0169 static IntPtr id_isVisible; static IntPtr id_setVisible_Z; public virtual bool Visible { // Metadata.xml XPath method reference: path="/api/package[@name='com.tencent.mapsdk.raster.model']/class[@name='Polyline']/method[@name='isVisible' and count(parameter)=0]" [Register ("isVisible", "()Z", "GetIsVisibleHandler")] get { if (id_isVisible == IntPtr.Zero) id_isVisible = JNIEnv.GetMethodID (class_ref, "isVisible", "()Z"); if (GetType () == ThresholdType) return JNIEnv.CallBooleanMethod (Handle, id_isVisible); else return JNIEnv.CallNonvirtualBooleanMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "isVisible", "()Z")); } // Metadata.xml XPath method reference: path="/api/package[@name='com.tencent.mapsdk.raster.model']/class[@name='Polyline']/method[@name='setVisible' and count(parameter)=1 and parameter[1][@type='boolean']]" [Register ("setVisible", "(Z)V", "GetSetVisible_ZHandler")] set { if (id_setVisible_Z == IntPtr.Zero) id_setVisible_Z = JNIEnv.GetMethodID (class_ref, "setVisible", "(Z)V"); if (GetType () == ThresholdType) JNIEnv.CallVoidMethod (Handle, id_setVisible_Z, new JValue (value)); else JNIEnv.CallNonvirtualVoidMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "setVisible", "(Z)V"), new JValue (value)); } } static Delegate cb_getWidth; #pragma warning disable 0169 static Delegate GetGetWidthHandler () { if (cb_getWidth == null) cb_getWidth = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, float>) n_GetWidth); return cb_getWidth; } static float n_GetWidth (IntPtr jnienv, IntPtr native__this) { global::Com.Tencent.Mapsdk.Raster.Model.Polyline __this = global::Java.Lang.Object.GetObject<global::Com.Tencent.Mapsdk.Raster.Model.Polyline> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); return __this.Width; } #pragma warning restore 0169 static Delegate cb_setWidth_F; #pragma warning disable 0169 static Delegate GetSetWidth_FHandler () { if (cb_setWidth_F == null) cb_setWidth_F = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, float>) n_SetWidth_F); return cb_setWidth_F; } static void n_SetWidth_F (IntPtr jnienv, IntPtr native__this, float p0) { global::Com.Tencent.Mapsdk.Raster.Model.Polyline __this = global::Java.Lang.Object.GetObject<global::Com.Tencent.Mapsdk.Raster.Model.Polyline> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); __this.Width = p0; } #pragma warning restore 0169 static IntPtr id_getWidth; static IntPtr id_setWidth_F; public virtual float Width { // Metadata.xml XPath method reference: path="/api/package[@name='com.tencent.mapsdk.raster.model']/class[@name='Polyline']/method[@name='getWidth' and count(parameter)=0]" [Register ("getWidth", "()F", "GetGetWidthHandler")] get { if (id_getWidth == IntPtr.Zero) id_getWidth = JNIEnv.GetMethodID (class_ref, "getWidth", "()F"); if (GetType () == ThresholdType) return JNIEnv.CallFloatMethod (Handle, id_getWidth); else return JNIEnv.CallNonvirtualFloatMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "getWidth", "()F")); } // Metadata.xml XPath method reference: path="/api/package[@name='com.tencent.mapsdk.raster.model']/class[@name='Polyline']/method[@name='setWidth' and count(parameter)=1 and parameter[1][@type='float']]" [Register ("setWidth", "(F)V", "GetSetWidth_FHandler")] set { if (id_setWidth_F == IntPtr.Zero) id_setWidth_F = JNIEnv.GetMethodID (class_ref, "setWidth", "(F)V"); if (GetType () == ThresholdType) JNIEnv.CallVoidMethod (Handle, id_setWidth_F, new JValue (value)); else JNIEnv.CallNonvirtualVoidMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "setWidth", "(F)V"), new JValue (value)); } } static Delegate cb_getZIndex; #pragma warning disable 0169 static Delegate GetGetZIndexHandler () { if (cb_getZIndex == null) cb_getZIndex = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, float>) n_GetZIndex); return cb_getZIndex; } static float n_GetZIndex (IntPtr jnienv, IntPtr native__this) { global::Com.Tencent.Mapsdk.Raster.Model.Polyline __this = global::Java.Lang.Object.GetObject<global::Com.Tencent.Mapsdk.Raster.Model.Polyline> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); return __this.ZIndex; } #pragma warning restore 0169 static Delegate cb_setZIndex_F; #pragma warning disable 0169 static Delegate GetSetZIndex_FHandler () { if (cb_setZIndex_F == null) cb_setZIndex_F = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, float>) n_SetZIndex_F); return cb_setZIndex_F; } static void n_SetZIndex_F (IntPtr jnienv, IntPtr native__this, float p0) { global::Com.Tencent.Mapsdk.Raster.Model.Polyline __this = global::Java.Lang.Object.GetObject<global::Com.Tencent.Mapsdk.Raster.Model.Polyline> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); __this.ZIndex = p0; } #pragma warning restore 0169 static IntPtr id_getZIndex; static IntPtr id_setZIndex_F; public virtual float ZIndex { // Metadata.xml XPath method reference: path="/api/package[@name='com.tencent.mapsdk.raster.model']/class[@name='Polyline']/method[@name='getZIndex' and count(parameter)=0]" [Register ("getZIndex", "()F", "GetGetZIndexHandler")] get { if (id_getZIndex == IntPtr.Zero) id_getZIndex = JNIEnv.GetMethodID (class_ref, "getZIndex", "()F"); if (GetType () == ThresholdType) return JNIEnv.CallFloatMethod (Handle, id_getZIndex); else return JNIEnv.CallNonvirtualFloatMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "getZIndex", "()F")); } // Metadata.xml XPath method reference: path="/api/package[@name='com.tencent.mapsdk.raster.model']/class[@name='Polyline']/method[@name='setZIndex' and count(parameter)=1 and parameter[1][@type='float']]" [Register ("setZIndex", "(F)V", "GetSetZIndex_FHandler")] set { if (id_setZIndex_F == IntPtr.Zero) id_setZIndex_F = JNIEnv.GetMethodID (class_ref, "setZIndex", "(F)V"); if (GetType () == ThresholdType) JNIEnv.CallVoidMethod (Handle, id_setZIndex_F, new JValue (value)); else JNIEnv.CallNonvirtualVoidMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "setZIndex", "(F)V"), new JValue (value)); } } static IntPtr id_equals_Ljava_lang_Object_; // Metadata.xml XPath method reference: path="/api/package[@name='com.tencent.mapsdk.raster.model']/class[@name='Polyline']/method[@name='equals' and count(parameter)=1 and parameter[1][@type='java.lang.Object']]" [Register ("equals", "(Ljava/lang/Object;)Z", "")] public override sealed bool Equals (global::Java.Lang.Object p0) { if (id_equals_Ljava_lang_Object_ == IntPtr.Zero) id_equals_Ljava_lang_Object_ = JNIEnv.GetMethodID (class_ref, "equals", "(Ljava/lang/Object;)Z"); bool __ret = JNIEnv.CallBooleanMethod (Handle, id_equals_Ljava_lang_Object_, new JValue (p0)); return __ret; } static IntPtr id_hashCode; // Metadata.xml XPath method reference: path="/api/package[@name='com.tencent.mapsdk.raster.model']/class[@name='Polyline']/method[@name='hashCode' and count(parameter)=0]" [Register ("hashCode", "()I", "")] public override sealed int GetHashCode () { if (id_hashCode == IntPtr.Zero) id_hashCode = JNIEnv.GetMethodID (class_ref, "hashCode", "()I"); return JNIEnv.CallIntMethod (Handle, id_hashCode); } static Delegate cb_remove; #pragma warning disable 0169 static Delegate GetRemoveHandler () { if (cb_remove == null) cb_remove = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr>) n_Remove); return cb_remove; } static void n_Remove (IntPtr jnienv, IntPtr native__this) { global::Com.Tencent.Mapsdk.Raster.Model.Polyline __this = global::Java.Lang.Object.GetObject<global::Com.Tencent.Mapsdk.Raster.Model.Polyline> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); __this.Remove (); } #pragma warning restore 0169 static IntPtr id_remove; // Metadata.xml XPath method reference: path="/api/package[@name='com.tencent.mapsdk.raster.model']/class[@name='Polyline']/method[@name='remove' and count(parameter)=0]" [Register ("remove", "()V", "GetRemoveHandler")] public virtual void Remove () { if (id_remove == IntPtr.Zero) id_remove = JNIEnv.GetMethodID (class_ref, "remove", "()V"); if (GetType () == ThresholdType) JNIEnv.CallVoidMethod (Handle, id_remove); else JNIEnv.CallNonvirtualVoidMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "remove", "()V")); } } }
#define AWSSDK_UNITY // // Copyright 2014-2015 Amazon.com, // Inc. or its affiliates. All Rights Reserved. // // Licensed under the Amazon Software License (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/asl/ // // or in the "license" file accompanying this file. This file is // distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, 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.Globalization; using System.IO; using System.Linq; using System.Text; using Amazon.Runtime; using Amazon.Runtime.Internal.Util; using System.Reflection; namespace Amazon.Util { /// <summary> /// This class defines utilities and constants that can be used by /// all the client libraries of the SDK. /// </summary> public static partial class AWSSDKUtils { #region Internal Constants internal const string DefaultRegion = "us-east-1"; internal const string DefaultGovRegion = "us-gov-west-1"; internal const string SDKVersionNumber = "2.0.0.0"; internal const int DefaultMaxRetry = 3; private const int DefaultConnectionLimit = 50; private const int DefaultMaxIdleTime = 50 * 1000; // 50 seconds public static readonly DateTime EPOCH_START = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); public const int DefaultBufferSize = 8192; // Default value of progress update interval for streaming is 100KB. public const long DefaultProgressUpdateInterval = 102400; internal static Dictionary<int, string> RFCEncodingSchemes = new Dictionary<int, string> { { 3986, ValidUrlCharacters }, { 1738, ValidUrlCharactersRFC1738 } }; #endregion #region Public Constants /// <summary> /// The user agent string header /// </summary> public const string UserAgentHeader = "User-Agent"; /// <summary> /// The Set of accepted and valid Url characters per RFC3986. /// Characters outside of this set will be encoded. /// </summary> public const string ValidUrlCharacters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.~"; /// <summary> /// The Set of accepted and valid Url characters per RFC1738. /// Characters outside of this set will be encoded. /// </summary> public const string ValidUrlCharactersRFC1738 = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_."; /// <summary> /// The set of accepted and valid Url path characters per RFC3986. /// </summary> private static string ValidPathCharacters = DetermineValidPathCharacters(); // Checks which path characters should not be encoded // This set will be different for .NET 4 and .NET 4.5, as // per http://msdn.microsoft.com/en-us/library/hh367887%28v=vs.110%29.aspx private static string DetermineValidPathCharacters() { const string basePathCharacters = "/:'()!*[]"; var sb = new StringBuilder(); foreach (var c in basePathCharacters) { var escaped = Uri.EscapeUriString(c.ToString()); if (escaped.Length == 1 && escaped[0] == c) sb.Append(c); } return sb.ToString(); } /// <summary> /// The string representing Url Encoded Content in HTTP requests /// </summary> public const string UrlEncodedContent = "application/x-www-form-urlencoded; charset=utf-8"; /// <summary> /// The GMT Date Format string. Used when parsing date objects /// </summary> public const string GMTDateFormat = "ddd, dd MMM yyyy HH:mm:ss \\G\\M\\T"; /// <summary> /// The ISO8601Date Format string. Used when parsing date objects /// </summary> public const string ISO8601DateFormat = "yyyy-MM-dd\\THH:mm:ss.fff\\Z"; /// <summary> /// The ISO8601Date Format string. Used when parsing date objects /// </summary> public const string ISO8601DateFormatNoMS = "yyyy-MM-dd\\THH:mm:ss\\Z"; /// <summary> /// The ISO8601 Basic date/time format string. Used when parsing date objects /// </summary> public const string ISO8601BasicDateTimeFormat = "yyyyMMddTHHmmssZ"; /// <summary> /// The ISO8601 basic date format. Used during AWS4 signature computation. /// </summary> public const string ISO8601BasicDateFormat = "yyyyMMdd"; /// <summary> /// The RFC822Date Format string. Used when parsing date objects /// </summary> public const string RFC822DateFormat = "ddd, dd MMM yyyy HH:mm:ss \\G\\M\\T"; #endregion #region UserAgent static string _versionNumber; static string _sdkUserAgent; static string _customData; /// <summary> /// The AWS SDK User Agent /// </summary> public static string SDKUserAgent { get { return _sdkUserAgent; } } static AWSSDKUtils() { BuildUserAgentString(); } public static void SetUserAgent(string productName, string versionNumber) { SetUserAgent(productName, versionNumber, null); } public static void SetUserAgent(string productName, string versionNumber, string customData) { _userAgentBaseName = productName; _versionNumber = versionNumber; _customData = customData; BuildUserAgentString(); } static void BuildUserAgentString() { if (_versionNumber == null) { _versionNumber = SDKVersionNumber; } _sdkUserAgent = string.Format(CultureInfo.InvariantCulture, "{0}/{1} .NET Runtime/{2} .NET Framework/{3} OS/{4} {5}", _userAgentBaseName, _versionNumber, DetermineRuntime(), DetermineFramework(), DetermineOSVersion(), _customData).Trim(); } #endregion #region Internal Methods /// <summary> /// Returns an extension of a path. /// This has the same behavior as System.IO.Path.GetExtension, but does not /// check the path for invalid characters. /// </summary> /// <param name="path"></param> /// <returns></returns> public static string GetExtension(string path) { if (path == null) return null; int length = path.Length; int index = length; while (--index >= 0) { char ch = path[index]; if (ch == '.') { if (index != length - 1) return path.Substring(index, length - index); else return string.Empty; } else if (IsPathSeparator(ch)) break; } return string.Empty; } // Checks if the character is one \ / : private static bool IsPathSeparator(char ch) { return (ch == '\\' || ch == '/' || ch == ':'); } /* * Determines the string to be signed based on the input parameters for * AWS Signature Version 2 */ internal static string CalculateStringToSignV2(IDictionary<string, string> parameters, string serviceUrl) { StringBuilder data = new StringBuilder("POST\n", 512); IDictionary<string, string> sorted = new SortedDictionary<string, string>(parameters, StringComparer.Ordinal); Uri endpoint = new Uri(serviceUrl); data.Append(endpoint.Host); data.Append("\n"); string uri = endpoint.AbsolutePath; if (uri == null || uri.Length == 0) { uri = "/"; } data.Append(AWSSDKUtils.UrlEncode(uri, true)); data.Append("\n"); foreach (KeyValuePair<string, string> pair in sorted) { if (pair.Value != null) { data.Append(AWSSDKUtils.UrlEncode(pair.Key, false)); data.Append("="); data.Append(AWSSDKUtils.UrlEncode(pair.Value, false)); data.Append("&"); } } string result = data.ToString(); return result.Remove(result.Length - 1); } /** * Convert Dictionary of paremeters to Url encoded query string */ internal static string GetParametersAsString(IDictionary<string, string> parameters) { string[] keys = new string[parameters.Keys.Count]; parameters.Keys.CopyTo(keys, 0); Array.Sort<string>(keys); StringBuilder data = new StringBuilder(512); foreach (string key in keys) { string value = parameters[key]; if (value != null) { data.Append(key); data.Append('='); data.Append(AWSSDKUtils.UrlEncode(value, false)); data.Append('&'); } } string result = data.ToString(); if (result.Length == 0) return string.Empty; return result.Remove(result.Length - 1); } /// <summary> /// Returns a new string created by joining each of the strings in the /// specified list together, with a comma between them. /// </summary> /// <parma name="strings">The list of strings to join into a single, comma delimited /// string list.</parma> /// <returns> A new string created by joining each of the strings in the /// specified list together, with a comma between strings.</returns> public static String Join(List<String> strings) { StringBuilder result = new StringBuilder(); Boolean first = true; foreach (String s in strings) { if (!first) result.Append(", "); result.Append(s); first = false; } return result.ToString(); } /// <summary> /// Attempt to infer the region for a service request based on the endpoint /// </summary> /// <param name="url">Endpoint to the service to be called</param> /// <returns> /// Region parsed from the endpoint; DefaultRegion (or DefaultGovRegion) /// if it cannot be determined/is not explicit /// </returns> public static string DetermineRegion(string url) { int delimIndex = url.IndexOf("//", StringComparison.Ordinal); if (delimIndex >= 0) url = url.Substring(delimIndex + 2); if(url.EndsWith("/", StringComparison.Ordinal)) url = url.Substring(0, url.Length - 1); int awsIndex = url.IndexOf(".amazonaws.com", StringComparison.Ordinal); if (awsIndex < 0) return DefaultRegion; string serviceAndRegion = url.Substring(0, awsIndex); int cloudSearchIndex = url.IndexOf(".cloudsearch.amazonaws.com", StringComparison.Ordinal); if (cloudSearchIndex > 0) serviceAndRegion = url.Substring(0, cloudSearchIndex); int queueIndex = serviceAndRegion.IndexOf("queue", StringComparison.Ordinal); if (queueIndex == 0) return DefaultRegion; if (queueIndex > 0) return serviceAndRegion.Substring(0, queueIndex - 1); char separator; if (serviceAndRegion.StartsWith("s3-", StringComparison.Ordinal)) separator = '-'; else separator = '.'; int separatorIndex = serviceAndRegion.IndexOf(separator); if (separatorIndex == -1) return DefaultRegion; string region = serviceAndRegion.Substring(separatorIndex + 1); if (region.Equals("external-1")) return RegionEndpoint.USEast1.SystemName; if (string.Equals(region, "us-gov", StringComparison.Ordinal)) return DefaultGovRegion; return region; } /// <summary> /// Attempt to infer the service name for a request (in short form, eg 'iam') from the /// service endpoint. /// </summary> /// <param name="url">Endpoint to the service to be called</param> /// <returns> /// Short-form name of the service parsed from the endpoint; empty string if it cannot /// be determined /// </returns> public static string DetermineService(string url) { int delimIndex = url.IndexOf("//", StringComparison.Ordinal); if (delimIndex >= 0) url = url.Substring(delimIndex + 2); string[] urlParts = url.Split(new char[] {'.'}, StringSplitOptions.RemoveEmptyEntries); if (urlParts == null || urlParts.Length == 0) return string.Empty; string servicePart = urlParts[0]; int hyphenated = servicePart.IndexOf('-'); string service; if (hyphenated < 0) { service = servicePart; } else { service = servicePart.Substring(0, hyphenated); } // Check for SQS : return "sqs" incase service is determined to be "queue" as per the URL. if (service.Equals("queue")) { return "sqs"; } else { return service; } } /// <summary> /// Utility method for converting Unix epoch seconds to DateTime structure. /// </summary> /// <param name="seconds">The number of seconds since January 1, 1970.</param> /// <returns>Converted DateTime structure</returns> public static DateTime ConvertFromUnixEpochSeconds(int seconds) { return new DateTime(seconds * 10000000L + EPOCH_START.Ticks, DateTimeKind.Utc).ToLocalTime(); } public static int ConvertToUnixEpochSeconds(DateTime dateTime) { return (int)ConvertToUnixEpochMilliSeconds(dateTime); } public static double ConvertToUnixEpochMilliSeconds(DateTime dateTime) { TimeSpan ts = new TimeSpan(dateTime.ToUniversalTime().Ticks - EPOCH_START.Ticks); double milli = Math.Round(ts.TotalMilliseconds, 0) / 1000.0; return milli; } /// <summary> /// Helper function to format a byte array into string /// </summary> /// <param name="data">The data blob to process</param> /// <param name="lowercase">If true, returns hex digits in lower case form</param> /// <returns>String version of the data</returns> internal static string ToHex(byte[] data, bool lowercase) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < data.Length; i++) { sb.Append(data[i].ToString(lowercase ? "x2" : "X2", CultureInfo.InvariantCulture)); } return sb.ToString(); } /// <summary> /// Calls a specific EventHandler in a background thread /// </summary> /// <param name="handler"></param> /// <param name="args"></param> /// <param name="sender"></param> public static void InvokeInBackground<T>(EventHandler<T> handler, T args, object sender) where T : EventArgs { if (handler == null) return; var list = handler.GetInvocationList(); foreach (var call in list) { var eventHandler = ((EventHandler<T>)call); if (eventHandler != null) { Dispatcher.Dispatch(() => eventHandler(sender, args)); } } } private static BackgroundInvoker _dispatcher; private static BackgroundInvoker Dispatcher { get { if (_dispatcher == null) { _dispatcher = new BackgroundInvoker(); } return _dispatcher; } } /// <summary> /// Parses a query string of a URL and returns the parameters as a string-to-string dictionary. /// </summary> /// <param name="url"></param> /// <returns></returns> public static Dictionary<string, string> ParseQueryParameters(string url) { Dictionary<string, string> parameters = new Dictionary<string, string>(); if (!string.IsNullOrEmpty(url)) { int queryIndex = url.IndexOf('?'); if (queryIndex >= 0) { string queryString = url.Substring(queryIndex + 1); string[] kvps = queryString.Split(new char[] { '&' }, StringSplitOptions.None); foreach (string kvp in kvps) { if (string.IsNullOrEmpty(kvp)) continue; string[] nameValuePair = kvp.Split(new char[] { '=' }, 2); string name = nameValuePair[0]; string value = nameValuePair.Length == 1 ? null : nameValuePair[1]; parameters[name] = value; } } } return parameters; } internal static bool AreEqual(object[] itemsA, object[] itemsB) { if (itemsA == null || itemsB == null) return (itemsA == itemsB); if (itemsA.Length != itemsB.Length) return false; var length = itemsA.Length; for (int i = 0; i < length; i++) { var a = itemsA[i]; var b = itemsB[i]; if (!AreEqual(a, b)) return false; } return true; } internal static bool AreEqual(object a, object b) { if (a == null || b == null) return (a == b); if (object.ReferenceEquals(a, b)) return true; return (a.Equals(b)); } /// <summary> /// Utility method for converting a string to a MemoryStream. /// </summary> /// <param name="s"></param> /// <returns></returns> public static MemoryStream GenerateMemoryStreamFromString(string s) { MemoryStream stream = new MemoryStream(); StreamWriter writer = new StreamWriter(stream); writer.Write(s); writer.Flush(); stream.Position = 0; return stream; } /// <summary> /// Utility method for copy the contents of the source stream to the destination stream. /// </summary> /// <param name="source"></param> /// <param name="destination"></param> /// <param name="bufferSize"></param> public static void CopyStream(Stream source, Stream destination, int bufferSize = 8192) { if (source == null) throw new ArgumentNullException("source"); if (destination == null) throw new ArgumentNullException("destination"); if (bufferSize <= 0) throw new ArgumentOutOfRangeException("bufferSize"); byte[] array = new byte[bufferSize]; int count; while ((count = source.Read(array, 0, array.Length)) != 0) { destination.Write(array, 0, count); } } #endregion #region Public Methods and Properties /// <summary> /// Formats the current date as a GMT timestamp /// </summary> /// <returns>A GMT formatted string representation /// of the current date and time /// </returns> public static string FormattedCurrentTimestampGMT { get { DateTime dateTime = AWSSDKUtils.CorrectedUtcNow; DateTime formatted = new DateTime( dateTime.Year, dateTime.Month, dateTime.Day, dateTime.Hour, dateTime.Minute, dateTime.Second, dateTime.Millisecond, DateTimeKind.Local ); return formatted.ToString( GMTDateFormat, CultureInfo.InvariantCulture ); } } /// <summary> /// Formats the current date as ISO 8601 timestamp /// </summary> /// <returns>An ISO 8601 formatted string representation /// of the current date and time /// </returns> public static string FormattedCurrentTimestampISO8601 { get { return GetFormattedTimestampISO8601(0); } } /// <summary> /// Gets the ISO8601 formatted timestamp that is minutesFromNow /// in the future. /// </summary> /// <param name="minutesFromNow">The number of minutes from the current instant /// for which the timestamp is needed.</param> /// <returns>The ISO8601 formatted future timestamp.</returns> public static string GetFormattedTimestampISO8601(int minutesFromNow) { DateTime dateTime = AWSSDKUtils.CorrectedUtcNow.AddMinutes(minutesFromNow); DateTime formatted = new DateTime( dateTime.Year, dateTime.Month, dateTime.Day, dateTime.Hour, dateTime.Minute, dateTime.Second, dateTime.Millisecond, DateTimeKind.Local ); return formatted.ToString( AWSSDKUtils.ISO8601DateFormat, CultureInfo.InvariantCulture ); } /// <summary> /// Formats the current date as ISO 8601 timestamp /// </summary> /// <returns>An ISO 8601 formatted string representation /// of the current date and time /// </returns> public static string FormattedCurrentTimestampRFC822 { get { return GetFormattedTimestampRFC822(0); } } /// <summary> /// Gets the RFC822 formatted timestamp that is minutesFromNow /// in the future. /// </summary> /// <param name="minutesFromNow">The number of minutes from the current instant /// for which the timestamp is needed.</param> /// <returns>The ISO8601 formatted future timestamp.</returns> public static string GetFormattedTimestampRFC822(int minutesFromNow) { DateTime dateTime = AWSSDKUtils.CorrectedUtcNow.AddMinutes(minutesFromNow); DateTime formatted = new DateTime( dateTime.Year, dateTime.Month, dateTime.Day, dateTime.Hour, dateTime.Minute, dateTime.Second, dateTime.Millisecond, DateTimeKind.Local ); return formatted.ToString( AWSSDKUtils.RFC822DateFormat, CultureInfo.InvariantCulture ); } /// <summary> /// URL encodes a string per RFC3986. If the path property is specified, /// the accepted path characters {/+:} are not encoded. /// </summary> /// <param name="data">The string to encode</param> /// <param name="path">Whether the string is a URL path or not</param> /// <returns>The encoded string</returns> public static string UrlEncode(string data, bool path) { return UrlEncode(3986, data, path); } /// <summary> /// URL encodes a string per the specified RFC. If the path property is specified, /// the accepted path characters {/+:} are not encoded. /// </summary> /// <param name="rfcNumber">RFC number determing safe characters</param> /// <param name="data">The string to encode</param> /// <param name="path">Whether the string is a URL path or not</param> /// <returns>The encoded string</returns> /// <remarks> /// Currently recognised RFC versions are 1738 (Dec '94) and 3986 (Jan '05). /// If the specified RFC is not recognised, 3986 is used by default. /// </remarks> public static string UrlEncode(int rfcNumber, string data, bool path) { StringBuilder encoded = new StringBuilder(data.Length * 2); string validUrlCharacters; if (!RFCEncodingSchemes.TryGetValue(rfcNumber, out validUrlCharacters)) validUrlCharacters = ValidUrlCharacters; string unreservedChars = String.Concat(validUrlCharacters, (path ? ValidPathCharacters : "")); foreach (char symbol in System.Text.Encoding.UTF8.GetBytes(data)) { if (unreservedChars.IndexOf(symbol) != -1) { encoded.Append(symbol); } else { encoded.Append("%").Append(string.Format(CultureInfo.InvariantCulture, "{0:X2}", (int)symbol)); } } return encoded.ToString(); } public static void Sleep(TimeSpan ts) { Sleep((int)ts.TotalMilliseconds); } /// <summary> /// Convert bytes to a hex string /// </summary> /// <param name="value">Bytes to convert.</param> /// <returns>Hexadecimal string representing the byte array.</returns> public static string BytesToHexString(byte[] value) { string hex = BitConverter.ToString(value); hex = hex.Replace("-", string.Empty); return hex; } /// <summary> /// Convert a hex string to bytes /// </summary> /// <param name="hex">Hexadecimal string</param> /// <returns>Byte array corresponding to the hex string.</returns> public static byte[] HexStringToBytes(string hex) { if (string.IsNullOrEmpty(hex) || hex.Length % 2 == 1) throw new ArgumentOutOfRangeException("hex"); int count = 0; byte[] buffer = new byte[hex.Length / 2]; for (int i = 0; i < hex.Length; i += 2) { string sub = hex.Substring(i, 2); byte b = Convert.ToByte(sub, 16); buffer[count] = b; count++; } return buffer; } /// <summary> /// Returns DateTime.UtcNow + ClockOffset when /// <seealso cref="AWSConfigs.CorrectForClockSkew"/> is true. /// This value should be used when constructing requests, as it /// will represent accurate time w.r.t. AWS servers. /// </summary> public static DateTime CorrectedUtcNow { get { var now = DateTime.UtcNow; if (AWSConfigs.CorrectForClockSkew) now += AWSConfigs.ClockOffset; return now; } } #endregion #region unity utils #if AWSSDK_UNITY /// <summary> /// Determines if Unity scripting backend is IL2CPP. /// </summary> /// <returns><c>true</c>If scripting backend is IL2CPP; otherwise, <c>false</c>.</returns> internal static bool IsIL2CPP { get{ Type type = Type.GetType("Mono.Runtime"); if (type != null) { MethodInfo displayName = type.GetMethod("GetDisplayName", BindingFlags.NonPublic | BindingFlags.Static); if (displayName != null) { string name = null; try { name = displayName.Invoke(null, null).ToString(); } catch(Exception) { return false; } if(name != null && name.ToUpper().Contains("IL2CPP")) { return true; } } } return false; } } #endif #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.ComponentModel; using System.IO; using System.Linq; using System.Net; using System.Runtime.InteropServices; using System.Security; using System.Text; using System.Threading; using Xunit; using Xunit.NetCore.Extensions; namespace System.Diagnostics.Tests { public partial class ProcessTests : ProcessTestBase { private class FinalizingProcess : Process { public static volatile bool WasFinalized; public static void CreateAndRelease() { new FinalizingProcess(); } protected override void Dispose(bool disposing) { if (!disposing) { WasFinalized = true; } base.Dispose(disposing); } } private void SetAndCheckBasePriority(ProcessPriorityClass exPriorityClass, int priority) { _process.PriorityClass = exPriorityClass; _process.Refresh(); Assert.Equal(priority, _process.BasePriority); } private void AssertNonZeroWindowsZeroUnix(long value) { if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { Assert.NotEqual(0, value); } else { Assert.Equal(0, value); } } [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))] [PlatformSpecific(TestPlatforms.Windows)] // Expected behavior varies on Windows and Unix public void TestBasePriorityOnWindows() { CreateDefaultProcess(); ProcessPriorityClass originalPriority = _process.PriorityClass; Assert.Equal(ProcessPriorityClass.Normal, originalPriority); try { // We are not checking for RealTime case here, as RealTime priority process can // preempt the threads of all other processes, including operating system processes // performing important tasks, which may cause the machine to be unresponsive. //SetAndCheckBasePriority(ProcessPriorityClass.RealTime, 24); SetAndCheckBasePriority(ProcessPriorityClass.High, 13); SetAndCheckBasePriority(ProcessPriorityClass.Idle, 4); SetAndCheckBasePriority(ProcessPriorityClass.Normal, 8); } finally { _process.PriorityClass = originalPriority; } } [Theory] [InlineData(true)] [InlineData(false)] [InlineData(null)] public void TestEnableRaiseEvents(bool? enable) { bool exitedInvoked = false; Process p = CreateProcessLong(); if (enable.HasValue) { p.EnableRaisingEvents = enable.Value; } p.Exited += delegate { exitedInvoked = true; }; StartSleepKillWait(p); if (enable.GetValueOrDefault()) { // There's no guarantee that the Exited callback will be invoked by // the time Process.WaitForExit completes, though it's extremely likely. // There could be a race condition where WaitForExit is returning from // its wait and sees that the callback is already running asynchronously, // at which point it returns to the caller even if the callback hasn't // entirely completed. As such, we spin until the value is set. Assert.True(SpinWait.SpinUntil(() => exitedInvoked, WaitInMS)); } else { Assert.False(exitedInvoked); } } [Fact] public void TestExitCode() { { Process p = CreateProcess(); p.Start(); Assert.True(p.WaitForExit(WaitInMS)); Assert.Equal(SuccessExitCode, p.ExitCode); } { Process p = CreateProcessLong(); StartSleepKillWait(p); Assert.NotEqual(0, p.ExitCode); } } [Fact] public void TestExitTime() { // ExitTime resolution on some platforms is less accurate than our DateTime.UtcNow resolution, so // we subtract ms from the begin time to account for it. DateTime timeBeforeProcessStart = DateTime.UtcNow.AddMilliseconds(-25); Process p = CreateProcessLong(); p.Start(); Assert.Throws<InvalidOperationException>(() => p.ExitTime); p.Kill(); Assert.True(p.WaitForExit(WaitInMS)); Assert.True(p.ExitTime.ToUniversalTime() >= timeBeforeProcessStart, $@"TestExitTime is incorrect. " + $@"TimeBeforeStart {timeBeforeProcessStart} Ticks={timeBeforeProcessStart.Ticks}, " + $@"ExitTime={p.ExitTime}, Ticks={p.ExitTime.Ticks}, " + $@"ExitTimeUniversal {p.ExitTime.ToUniversalTime()} Ticks={p.ExitTime.ToUniversalTime().Ticks}, " + $@"NowUniversal {DateTime.Now.ToUniversalTime()} Ticks={DateTime.Now.Ticks}"); } [Fact] public void StartTime_GetNotStarted_ThrowsInvalidOperationException() { var process = new Process(); Assert.Throws<InvalidOperationException>(() => process.StartTime); } [Fact] public void TestId() { CreateDefaultProcess(); if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { Assert.Equal(_process.Id, Interop.GetProcessId(_process.SafeHandle)); } else { IEnumerable<int> testProcessIds = Process.GetProcessesByName(HostRunnerName).Select(p => p.Id); Assert.Contains(_process.Id, testProcessIds); } } [Fact] public void TestHasExited() { { Process p = CreateProcess(); p.Start(); Assert.True(p.WaitForExit(WaitInMS)); Assert.True(p.HasExited, "TestHasExited001 failed"); } { Process p = CreateProcessLong(); p.Start(); try { Assert.False(p.HasExited, "TestHasExited002 failed"); } finally { p.Kill(); Assert.True(p.WaitForExit(WaitInMS)); } Assert.True(p.HasExited, "TestHasExited003 failed"); } } [Fact] public void HasExited_GetNotStarted_ThrowsInvalidOperationException() { var process = new Process(); Assert.Throws<InvalidOperationException>(() => process.HasExited); } [Fact] public void Kill_NotStarted_ThrowsInvalidOperationException() { var process = new Process(); Assert.Throws<InvalidOperationException>(() => process.Kill()); } [Fact] public void TestMachineName() { CreateDefaultProcess(); // Checking that the MachineName returns some value. Assert.NotNull(_process.MachineName); } [Fact] public void MachineName_GetNotStarted_ThrowsInvalidOperationException() { var process = new Process(); Assert.Throws<InvalidOperationException>(() => process.MachineName); } [Fact] public void TestMainModuleOnNonOSX() { Process p = Process.GetCurrentProcess(); Assert.True(p.Modules.Count > 0); Assert.Equal(HostRunnerName, p.MainModule.ModuleName); Assert.EndsWith(HostRunnerName, p.MainModule.FileName); Assert.Equal(string.Format("System.Diagnostics.ProcessModule ({0})", HostRunnerName), p.MainModule.ToString()); } [Fact] public void TestMaxWorkingSet() { CreateDefaultProcess(); using (Process p = Process.GetCurrentProcess()) { Assert.True((long)p.MaxWorkingSet > 0); Assert.True((long)p.MinWorkingSet >= 0); } if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) return; // doesn't support getting/setting working set for other processes long curValue = (long)_process.MaxWorkingSet; Assert.True(curValue >= 0); if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { try { _process.MaxWorkingSet = (IntPtr)((int)curValue + 1024); IntPtr min, max; uint flags; Interop.GetProcessWorkingSetSizeEx(_process.SafeHandle, out min, out max, out flags); curValue = (int)max; _process.Refresh(); Assert.Equal(curValue, (int)_process.MaxWorkingSet); } finally { _process.MaxWorkingSet = (IntPtr)curValue; } } } [Fact] [PlatformSpecific(~TestPlatforms.OSX)] // Getting MaxWorkingSet is not supported on OSX. public void MaxWorkingSet_GetNotStarted_ThrowsInvalidOperationException() { var process = new Process(); Assert.Throws<InvalidOperationException>(() => process.MaxWorkingSet); } [Fact] [PlatformSpecific(TestPlatforms.OSX)] public void MaxValueWorkingSet_GetSetMacos_ThrowsPlatformSupportedException() { var process = new Process(); Assert.Throws<PlatformNotSupportedException>(() => process.MaxWorkingSet); Assert.Throws<PlatformNotSupportedException>(() => process.MaxWorkingSet = (IntPtr)1); } [Fact] public void TestMinWorkingSet() { CreateDefaultProcess(); using (Process p = Process.GetCurrentProcess()) { Assert.True((long)p.MaxWorkingSet > 0); Assert.True((long)p.MinWorkingSet >= 0); } if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) return; // doesn't support getting/setting working set for other processes long curValue = (long)_process.MinWorkingSet; Assert.True(curValue >= 0); if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { try { _process.MinWorkingSet = (IntPtr)((int)curValue - 1024); IntPtr min, max; uint flags; Interop.GetProcessWorkingSetSizeEx(_process.SafeHandle, out min, out max, out flags); curValue = (int)min; _process.Refresh(); Assert.Equal(curValue, (int)_process.MinWorkingSet); } finally { _process.MinWorkingSet = (IntPtr)curValue; } } } [Fact] [PlatformSpecific(~TestPlatforms.OSX)] // Getting MinWorkingSet is not supported on OSX. public void MinWorkingSet_GetNotStarted_ThrowsInvalidOperationException() { var process = new Process(); Assert.Throws<InvalidOperationException>(() => process.MinWorkingSet); } [Fact] [PlatformSpecific(TestPlatforms.OSX)] public void MinWorkingSet_GetMacos_ThrowsPlatformSupportedException() { var process = new Process(); Assert.Throws<PlatformNotSupportedException>(() => process.MinWorkingSet); } [Fact] public void TestModules() { ProcessModuleCollection moduleCollection = Process.GetCurrentProcess().Modules; foreach (ProcessModule pModule in moduleCollection) { // Validated that we can get a value for each of the following. Assert.NotNull(pModule); Assert.NotNull(pModule.FileName); Assert.NotNull(pModule.ModuleName); // Just make sure these don't throw IntPtr baseAddr = pModule.BaseAddress; IntPtr entryAddr = pModule.EntryPointAddress; int memSize = pModule.ModuleMemorySize; } } [Fact] public void TestNonpagedSystemMemorySize64() { CreateDefaultProcess(); AssertNonZeroWindowsZeroUnix(_process.NonpagedSystemMemorySize64); } [Fact] public void NonpagedSystemMemorySize64_GetNotStarted_ThrowsInvalidOperationException() { var process = new Process(); Assert.Throws<InvalidOperationException>(() => process.NonpagedSystemMemorySize64); } [Fact] public void TestPagedMemorySize64() { CreateDefaultProcess(); AssertNonZeroWindowsZeroUnix(_process.PagedMemorySize64); } [Fact] public void PagedMemorySize64_GetNotStarted_ThrowsInvalidOperationException() { var process = new Process(); Assert.Throws<InvalidOperationException>(() => process.PagedMemorySize64); } [Fact] public void TestPagedSystemMemorySize64() { CreateDefaultProcess(); AssertNonZeroWindowsZeroUnix(_process.PagedSystemMemorySize64); } [Fact] public void PagedSystemMemorySize64_GetNotStarted_ThrowsInvalidOperationException() { var process = new Process(); Assert.Throws<InvalidOperationException>(() => process.PagedSystemMemorySize64); } [Fact] public void TestPeakPagedMemorySize64() { CreateDefaultProcess(); AssertNonZeroWindowsZeroUnix(_process.PeakPagedMemorySize64); } [Fact] public void PeakPagedMemorySize64_GetNotStarted_ThrowsInvalidOperationException() { var process = new Process(); Assert.Throws<InvalidOperationException>(() => process.PeakPagedMemorySize64); } [Fact] public void TestPeakVirtualMemorySize64() { CreateDefaultProcess(); AssertNonZeroWindowsZeroUnix(_process.PeakVirtualMemorySize64); } [Fact] public void PeakVirtualMemorySize64_GetNotStarted_ThrowsInvalidOperationException() { var process = new Process(); Assert.Throws<InvalidOperationException>(() => process.PeakVirtualMemorySize64); } [Fact] public void TestPeakWorkingSet64() { CreateDefaultProcess(); AssertNonZeroWindowsZeroUnix(_process.PeakWorkingSet64); } [Fact] public void PeakWorkingSet64_GetNotStarted_ThrowsInvalidOperationException() { var process = new Process(); Assert.Throws<InvalidOperationException>(() => process.PeakWorkingSet64); } [Fact] public void TestPrivateMemorySize64() { CreateDefaultProcess(); AssertNonZeroWindowsZeroUnix(_process.PrivateMemorySize64); } [Fact] public void PrivateMemorySize64_GetNotStarted_ThrowsInvalidOperationException() { var process = new Process(); Assert.Throws<InvalidOperationException>(() => process.PrivateMemorySize64); } [Fact] public void TestVirtualMemorySize64() { CreateDefaultProcess(); Assert.True(_process.VirtualMemorySize64 > 0); } [Fact] public void VirtualMemorySize64_GetNotStarted_ThrowsInvalidOperationException() { var process = new Process(); Assert.Throws<InvalidOperationException>(() => process.VirtualMemorySize64); } [Fact] public void TestWorkingSet64() { CreateDefaultProcess(); if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { // resident memory can be 0 on OSX. Assert.True(_process.WorkingSet64 >= 0); return; } Assert.True(_process.WorkingSet64 > 0); } [Fact] public void WorkingSet64_GetNotStarted_ThrowsInvalidOperationException() { var process = new Process(); Assert.Throws<InvalidOperationException>(() => process.WorkingSet64); } [Fact] public void TestProcessorTime() { CreateDefaultProcess(); Assert.True(_process.UserProcessorTime.TotalSeconds >= 0); Assert.True(_process.PrivilegedProcessorTime.TotalSeconds >= 0); double processorTimeBeforeSpin = Process.GetCurrentProcess().TotalProcessorTime.TotalSeconds; double processorTimeAtHalfSpin = 0; // Perform loop to occupy cpu, takes less than a second. int i = int.MaxValue / 16; while (i > 0) { i--; if (i == int.MaxValue / 32) processorTimeAtHalfSpin = Process.GetCurrentProcess().TotalProcessorTime.TotalSeconds; } Assert.InRange(processorTimeAtHalfSpin, processorTimeBeforeSpin, Process.GetCurrentProcess().TotalProcessorTime.TotalSeconds); } [Fact] public void UserProcessorTime_GetNotStarted_ThrowsInvalidOperationException() { var process = new Process(); Assert.Throws<InvalidOperationException>(() => process.UserProcessorTime); } [Fact] public void PriviledgedProcessorTime_GetNotStarted_ThrowsInvalidOperationException() { var process = new Process(); Assert.Throws<InvalidOperationException>(() => process.PrivilegedProcessorTime); } [Fact] public void TotalProcessorTime_GetNotStarted_ThrowsInvalidOperationException() { var process = new Process(); Assert.Throws<InvalidOperationException>(() => process.TotalProcessorTime); } [Fact] public void TestProcessStartTime() { TimeSpan allowedWindow = TimeSpan.FromSeconds(3); DateTime testStartTime = DateTime.UtcNow; using (var remote = RemoteInvoke(() => { Console.Write(Process.GetCurrentProcess().StartTime.ToUniversalTime()); return SuccessExitCode; }, new RemoteInvokeOptions { StartInfo = new ProcessStartInfo { RedirectStandardOutput = true } })) { Assert.Equal(remote.Process.StartTime, remote.Process.StartTime); DateTime remoteStartTime = DateTime.Parse(remote.Process.StandardOutput.ReadToEnd()); DateTime curTime = DateTime.UtcNow; Assert.InRange(remoteStartTime, testStartTime - allowedWindow, curTime + allowedWindow); } } [Fact] public void ExitTime_GetNotStarted_ThrowsInvalidOperationException() { var process = new Process(); Assert.Throws<InvalidOperationException>(() => process.ExitTime); } [Fact] [PlatformSpecific(~TestPlatforms.OSX)] // getting/setting affinity not supported on OSX public void TestProcessorAffinity() { CreateDefaultProcess(); IntPtr curProcessorAffinity = _process.ProcessorAffinity; try { _process.ProcessorAffinity = new IntPtr(0x1); Assert.Equal(new IntPtr(0x1), _process.ProcessorAffinity); } finally { _process.ProcessorAffinity = curProcessorAffinity; Assert.Equal(curProcessorAffinity, _process.ProcessorAffinity); } } [Fact] public void TestPriorityBoostEnabled() { CreateDefaultProcess(); bool isPriorityBoostEnabled = _process.PriorityBoostEnabled; try { _process.PriorityBoostEnabled = true; Assert.True(_process.PriorityBoostEnabled, "TestPriorityBoostEnabled001 failed"); _process.PriorityBoostEnabled = false; Assert.False(_process.PriorityBoostEnabled, "TestPriorityBoostEnabled002 failed"); } finally { _process.PriorityBoostEnabled = isPriorityBoostEnabled; } } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // PriorityBoostEnabled is a no-op on Unix. public void PriorityBoostEnabled_GetNotStarted_ThrowsInvalidOperationException() { var process = new Process(); Assert.Throws<InvalidOperationException>(() => process.PriorityBoostEnabled); Assert.Throws<InvalidOperationException>(() => process.PriorityBoostEnabled = true); } [Fact, PlatformSpecific(TestPlatforms.Windows)] // Expected behavior varies on Windows and Unix public void TestPriorityClassWindows() { CreateDefaultProcess(); ProcessPriorityClass priorityClass = _process.PriorityClass; try { _process.PriorityClass = ProcessPriorityClass.High; Assert.Equal(_process.PriorityClass, ProcessPriorityClass.High); _process.PriorityClass = ProcessPriorityClass.Normal; Assert.Equal(_process.PriorityClass, ProcessPriorityClass.Normal); } finally { _process.PriorityClass = priorityClass; } } [Theory] [InlineData((ProcessPriorityClass)0)] [InlineData(ProcessPriorityClass.Normal | ProcessPriorityClass.Idle)] public void TestInvalidPriorityClass(ProcessPriorityClass priorityClass) { var process = new Process(); Assert.Throws<InvalidEnumArgumentException>(() => process.PriorityClass = priorityClass); } [Fact] public void PriorityClass_GetNotStarted_ThrowsInvalidOperationException() { var process = new Process(); Assert.Throws<InvalidOperationException>(() => process.PriorityClass); } [Fact] public void TestProcessName() { CreateDefaultProcess(); // Processes are not hosted by dotnet in the full .NET Framework. string expected = PlatformDetection.IsFullFramework || PlatformDetection.IsNetNative ? TestConsoleApp : HostRunner; Assert.Equal(Path.GetFileNameWithoutExtension(_process.ProcessName), Path.GetFileNameWithoutExtension(expected), StringComparer.OrdinalIgnoreCase); } [Fact] public void ProcessName_GetNotStarted_ThrowsInvalidOperationException() { var process = new Process(); Assert.Throws<InvalidOperationException>(() => process.ProcessName); } [Fact] public void TestSafeHandle() { CreateDefaultProcess(); Assert.False(_process.SafeHandle.IsInvalid); } [Fact] public void SafeHandle_GetNotStarted_ThrowsInvalidOperationException() { var process = new Process(); Assert.Throws<InvalidOperationException>(() => process.SafeHandle); } [Fact] public void TestSessionId() { CreateDefaultProcess(); uint sessionId; #if TargetsWindows Interop.ProcessIdToSessionId((uint)_process.Id, out sessionId); #else sessionId = (uint)Interop.getsid(_process.Id); #endif Assert.Equal(sessionId, (uint)_process.SessionId); } [Fact] public void SessionId_GetNotStarted_ThrowsInvalidOperationException() { var process = new Process(); Assert.Throws<InvalidOperationException>(() => process.SessionId); } [Fact] public void TestGetCurrentProcess() { Process current = Process.GetCurrentProcess(); Assert.NotNull(current); int currentProcessId = #if TargetsWindows Interop.GetCurrentProcessId(); #else Interop.getpid(); #endif Assert.Equal(currentProcessId, current.Id); } [Fact] public void TestGetProcessById() { CreateDefaultProcess(); Process p = Process.GetProcessById(_process.Id); Assert.Equal(_process.Id, p.Id); Assert.Equal(_process.ProcessName, p.ProcessName); } [Fact] public void TestGetProcesses() { Process currentProcess = Process.GetCurrentProcess(); // Get all the processes running on the machine, and check if the current process is one of them. var foundCurrentProcess = (from p in Process.GetProcesses() where (p.Id == currentProcess.Id) && (p.ProcessName.Equals(currentProcess.ProcessName)) select p).Any(); Assert.True(foundCurrentProcess, "TestGetProcesses001 failed"); foundCurrentProcess = (from p in Process.GetProcesses(currentProcess.MachineName) where (p.Id == currentProcess.Id) && (p.ProcessName.Equals(currentProcess.ProcessName)) select p).Any(); Assert.True(foundCurrentProcess, "TestGetProcesses002 failed"); } [Fact] public void GetProcesseses_NullMachineName_ThrowsArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("machineName", () => Process.GetProcesses(null)); } [Fact] public void GetProcesses_EmptyMachineName_ThrowsArgumentException() { Assert.Throws<ArgumentException>(null, () => Process.GetProcesses("")); } [Fact] public void GetProcessesByName_ProcessName_ReturnsExpected() { // Get the current process using its name Process currentProcess = Process.GetCurrentProcess(); Process[] processes = Process.GetProcessesByName(currentProcess.ProcessName); Assert.NotEmpty(processes); Assert.All(processes, process => Assert.Equal(".", process.MachineName)); } public static IEnumerable<object[]> MachineName_TestData() { string currentProcessName = Process.GetCurrentProcess().MachineName; yield return new object[] { currentProcessName }; yield return new object[] { "." }; yield return new object[] { Dns.GetHostName() }; } public static IEnumerable<object[]> MachineName_Remote_TestData() { yield return new object[] { Guid.NewGuid().ToString("N") }; yield return new object[] { "\\" + Guid.NewGuid().ToString("N") }; } [Theory] [MemberData(nameof(MachineName_TestData))] public void GetProcessesByName_ProcessNameMachineName_ReturnsExpected(string machineName) { Process currentProcess = Process.GetCurrentProcess(); Process[] processes = Process.GetProcessesByName(currentProcess.ProcessName, machineName); Assert.NotEmpty(processes); Assert.All(processes, process => Assert.Equal(machineName, process.MachineName)); } [MemberData(nameof(MachineName_Remote_TestData))] [PlatformSpecific(TestPlatforms.Windows)] // Accessing processes on remote machines is only supported on Windows. public void GetProcessesByName_RemoteMachineNameWindows_ReturnsExpected(string machineName) { try { GetProcessesByName_ProcessNameMachineName_ReturnsExpected(machineName); } catch (InvalidOperationException) { // As we can't detect reliably if performance counters are enabled // we let possible InvalidOperationExceptions pass silently. } } [Fact] public void GetProcessesByName_NoSuchProcess_ReturnsEmpty() { string processName = Guid.NewGuid().ToString("N"); Assert.Empty(Process.GetProcessesByName(processName)); } [Fact] public void GetProcessesByName_NullMachineName_ThrowsArgumentNullException() { Process currentProcess = Process.GetCurrentProcess(); AssertExtensions.Throws<ArgumentNullException>("machineName", () => Process.GetProcessesByName(currentProcess.ProcessName, null)); } [Fact] public void GetProcessesByName_EmptyMachineName_ThrowsArgumentException() { Process currentProcess = Process.GetCurrentProcess(); Assert.Throws<ArgumentException>(null, () => Process.GetProcessesByName(currentProcess.ProcessName, "")); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // Behavior differs on Windows and Unix [ActiveIssue("https://github.com/dotnet/corefx/issues/18212", TargetFrameworkMonikers.UapAot)] public void TestProcessOnRemoteMachineWindows() { Process currentProccess = Process.GetCurrentProcess(); void TestRemoteProccess(Process remoteProcess) { Assert.Equal(currentProccess.Id, remoteProcess.Id); Assert.Equal(currentProccess.BasePriority, remoteProcess.BasePriority); Assert.Equal(currentProccess.EnableRaisingEvents, remoteProcess.EnableRaisingEvents); Assert.Equal("127.0.0.1", remoteProcess.MachineName); // This property throws exception only on remote processes. Assert.Throws<NotSupportedException>(() => remoteProcess.MainModule); } try { TestRemoteProccess(Process.GetProcessById(currentProccess.Id, "127.0.0.1")); TestRemoteProccess(Process.GetProcessesByName(currentProccess.ProcessName, "127.0.0.1").Where(p => p.Id == currentProccess.Id).Single()); } catch (InvalidOperationException) { // As we can't detect reliably if performance counters are enabled // we let possible InvalidOperationExceptions pass silently. } } [Fact] public void StartInfo_GetFileName_ReturnsExpected() { Process process = CreateProcessLong(); process.Start(); // Processes are not hosted by dotnet in the full .NET Framework. string expectedFileName = PlatformDetection.IsFullFramework || PlatformDetection.IsNetNative ? TestConsoleApp : HostRunner; Assert.Equal(expectedFileName, process.StartInfo.FileName); process.Kill(); Assert.True(process.WaitForExit(WaitInMS)); } [Fact] public void StartInfo_SetOnRunningProcess_ThrowsInvalidOperationException() { Process process = CreateProcessLong(); process.Start(); // .NET Core fixes a bug where Process.StartInfo for a unrelated process would // return information about the current process, not the unrelated process. // See https://github.com/dotnet/corefx/issues/1100. if (PlatformDetection.IsFullFramework) { var startInfo = new ProcessStartInfo(); process.StartInfo = startInfo; Assert.Equal(startInfo, process.StartInfo); } else { Assert.Throws<InvalidOperationException>(() => process.StartInfo = new ProcessStartInfo()); } process.Kill(); Assert.True(process.WaitForExit(WaitInMS)); } [Fact] public void StartInfo_SetGet_ReturnsExpected() { var process = new Process() { StartInfo = new ProcessStartInfo(TestConsoleApp) }; Assert.Equal(TestConsoleApp, process.StartInfo.FileName); } [Fact] public void StartInfo_SetNull_ThrowsArgumentNullException() { var process = new Process(); Assert.Throws<ArgumentNullException>(() => process.StartInfo = null); } [Fact] public void StartInfo_GetOnRunningProcess_ThrowsInvalidOperationException() { Process process = Process.GetCurrentProcess(); // .NET Core fixes a bug where Process.StartInfo for an unrelated process would // return information about the current process, not the unrelated process. // See https://github.com/dotnet/corefx/issues/1100. if (PlatformDetection.IsFullFramework) { Assert.NotNull(process.StartInfo); } else { Assert.Throws<InvalidOperationException>(() => process.StartInfo); } } [Theory] [InlineData(@"""abc"" d e", @"abc,d,e")] [InlineData(@"""abc"" d e", @"abc,d,e")] [InlineData("\"abc\"\t\td\te", @"abc,d,e")] [InlineData(@"a\\b d""e f""g h", @"a\\b,de fg,h")] [InlineData(@"\ \\ \\\", @"\,\\,\\\")] [InlineData(@"a\\\""b c d", @"a\""b,c,d")] [InlineData(@"a\\\\""b c"" d e", @"a\\b c,d,e")] [InlineData(@"a""b c""d e""f g""h i""j k""l", @"ab cd,ef gh,ij kl")] [InlineData(@"a b c""def", @"a,b,cdef")] [InlineData(@"""\a\"" \\""\\\ b c", @"\a"" \\\\,b,c")] public void TestArgumentParsing(string inputArguments, string expectedArgv) { using (var handle = RemoteInvokeRaw((Func<string, string, string, int>)ConcatThreeArguments, inputArguments, new RemoteInvokeOptions { Start = true, StartInfo = new ProcessStartInfo { RedirectStandardOutput = true } })) { Assert.Equal(expectedArgv, handle.Process.StandardOutput.ReadToEnd()); } } [Fact] public void StandardInput_GetNotRedirected_ThrowsInvalidOperationException() { var process = new Process(); Assert.Throws<InvalidOperationException>(() => process.StandardInput); } private static int ConcatThreeArguments(string one, string two, string three) { Console.Write(string.Join(",", one, two, three)); return SuccessExitCode; } // [Fact] // uncomment for diagnostic purposes to list processes to console public void TestDiagnosticsWithConsoleWriteLine() { foreach (var p in Process.GetProcesses().OrderBy(p => p.Id)) { Console.WriteLine("{0} : \"{1}\" (Threads: {2})", p.Id, p.ProcessName, p.Threads.Count); p.Dispose(); } } [Fact] public void CanBeFinalized() { FinalizingProcess.CreateAndRelease(); GC.Collect(); GC.WaitForPendingFinalizers(); Assert.True(FinalizingProcess.WasFinalized); } [Theory] [InlineData(false)] [InlineData(true)] public void TestStartWithMissingFile(bool fullPath) { string path = Guid.NewGuid().ToString("N"); if (fullPath) { path = Path.GetFullPath(path); Assert.True(Path.IsPathRooted(path)); } else { Assert.False(Path.IsPathRooted(path)); } Assert.False(File.Exists(path)); Win32Exception e = Assert.Throws<Win32Exception>(() => Process.Start(path)); Assert.NotEqual(0, e.NativeErrorCode); } [Fact] public void Start_NullStartInfo_ThrowsArgumentNullExceptionException() { AssertExtensions.Throws<ArgumentNullException>("startInfo", () => Process.Start((ProcessStartInfo)null)); } [Fact] public void Start_EmptyFileName_ThrowsInvalidOperationException() { var process = new Process(); Assert.Throws<InvalidOperationException>(() => process.Start()); } [Fact] public void Start_HasStandardOutputEncodingNonRedirected_ThrowsInvalidOperationException() { var process = new Process { StartInfo = new ProcessStartInfo { FileName = "FileName", RedirectStandardOutput = false, StandardOutputEncoding = Encoding.UTF8 } }; Assert.Throws<InvalidOperationException>(() => process.Start()); } [Fact] public void Start_HasStandardErrorEncodingNonRedirected_ThrowsInvalidOperationException() { var process = new Process { StartInfo = new ProcessStartInfo { FileName = "FileName", RedirectStandardError = false, StandardErrorEncoding = Encoding.UTF8 } }; Assert.Throws<InvalidOperationException>(() => process.Start()); } [Fact] public void Start_Disposed_ThrowsObjectDisposedException() { var process = new Process(); process.StartInfo.FileName = "Nothing"; process.Dispose(); Assert.Throws<ObjectDisposedException>(() => process.Start()); } [Fact] [PlatformSpecific(TestPlatforms.Linux | TestPlatforms.Windows)] // Expected process HandleCounts differs on OSX public void TestHandleCount() { using (Process p = Process.GetCurrentProcess()) { Assert.True(p.HandleCount > 0); } } [Fact] [PlatformSpecific(TestPlatforms.OSX)] // Expected process HandleCounts differs on OSX public void TestHandleCount_OSX() { using (Process p = Process.GetCurrentProcess()) { Assert.Equal(0, p.HandleCount); } } [Fact] [PlatformSpecific(TestPlatforms.Linux | TestPlatforms.Windows)] // Expected process HandleCounts differs on OSX [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Handle count change is not reliable, but seems less robust on NETFX")] public void HandleCountChanges() { RemoteInvoke(() => { Process p = Process.GetCurrentProcess(); int handleCount = p.HandleCount; using (var fs1 = File.Open(GetTestFilePath(), FileMode.OpenOrCreate)) using (var fs2 = File.Open(GetTestFilePath(), FileMode.OpenOrCreate)) using (var fs3 = File.Open(GetTestFilePath(), FileMode.OpenOrCreate)) { p.Refresh(); int secondHandleCount = p.HandleCount; Assert.True(handleCount < secondHandleCount); handleCount = secondHandleCount; } p.Refresh(); int thirdHandleCount = p.HandleCount; Assert.True(thirdHandleCount < handleCount); return SuccessExitCode; }).Dispose(); } [Fact] public void HandleCount_GetNotStarted_ThrowsInvalidOperationException() { var process = new Process(); Assert.Throws<InvalidOperationException>(() => process.HandleCount); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // MainWindowHandle is not supported on Unix. public void MainWindowHandle_NoWindow_ReturnsEmptyHandle() { CreateDefaultProcess(); Assert.Equal(IntPtr.Zero, _process.MainWindowHandle); Assert.Equal(_process.MainWindowHandle, _process.MainWindowHandle); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] [SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "HWND not available")] public void MainWindowHandle_GetNotStarted_ThrowsInvalidOperationException() { var process = new Process(); Assert.Throws<InvalidOperationException>(() => process.MainWindowHandle); } [Fact] public void MainWindowTitle_NoWindow_ReturnsEmpty() { CreateDefaultProcess(); Assert.Empty(_process.MainWindowTitle); Assert.Same(_process.MainWindowTitle, _process.MainWindowTitle); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // MainWindowTitle is a no-op and always returns string.Empty on Unix. [SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "HWND not available")] public void MainWindowTitle_GetNotStarted_ThrowsInvalidOperationException() { var process = new Process(); Assert.Throws<InvalidOperationException>(() => process.MainWindowTitle); } [Fact] public void CloseMainWindow_NoWindow_ReturnsFalse() { CreateDefaultProcess(); Assert.False(_process.CloseMainWindow()); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // CloseMainWindow is a no-op and always returns false on Unix. public void CloseMainWindow_NotStarted_ThrowsInvalidOperationException() { var process = new Process(); Assert.Throws<InvalidOperationException>(() => process.CloseMainWindow()); } [PlatformSpecific(TestPlatforms.Windows)] // Needs to get the process Id from OS [Fact] public void TestRespondingWindows() { using (Process p = Process.GetCurrentProcess()) { Assert.True(p.Responding); } } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // Responding always returns true on Unix. [SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "HWND not available")] public void Responding_GetNotStarted_ThrowsInvalidOperationException() { var process = new Process(); Assert.Throws<InvalidOperationException>(() => process.Responding); } [Fact] public void TestNonpagedSystemMemorySize() { CreateDefaultProcess(); #pragma warning disable 0618 AssertNonZeroWindowsZeroUnix(_process.NonpagedSystemMemorySize); #pragma warning restore 0618 } [Fact] public void NonpagedSystemMemorySize_GetNotStarted_ThrowsInvalidOperationException() { var process = new Process(); #pragma warning disable 0618 Assert.Throws<InvalidOperationException>(() => process.NonpagedSystemMemorySize); #pragma warning restore 0618 } [Fact] public void TestPagedMemorySize() { CreateDefaultProcess(); #pragma warning disable 0618 AssertNonZeroWindowsZeroUnix(_process.PagedMemorySize); #pragma warning restore 0618 } [Fact] public void PagedMemorySize_GetNotStarted_ThrowsInvalidOperationException() { var process = new Process(); #pragma warning disable 0618 Assert.Throws<InvalidOperationException>(() => process.PagedMemorySize); #pragma warning restore 0618 } [Fact] public void TestPagedSystemMemorySize() { CreateDefaultProcess(); #pragma warning disable 0618 AssertNonZeroWindowsZeroUnix(_process.PagedSystemMemorySize); #pragma warning restore 0618 } [Fact] public void PagedSystemMemorySize_GetNotStarted_ThrowsInvalidOperationException() { var process = new Process(); #pragma warning disable 0618 Assert.Throws<InvalidOperationException>(() => process.PagedSystemMemorySize); #pragma warning restore 0618 } [Fact] public void TestPeakPagedMemorySize() { CreateDefaultProcess(); #pragma warning disable 0618 AssertNonZeroWindowsZeroUnix(_process.PeakPagedMemorySize); #pragma warning restore 0618 } [Fact] public void PeakPagedMemorySize_GetNotStarted_ThrowsInvalidOperationException() { var process = new Process(); #pragma warning disable 0618 Assert.Throws<InvalidOperationException>(() => process.PeakPagedMemorySize); #pragma warning restore 0618 } [Fact] public void TestPeakVirtualMemorySize() { CreateDefaultProcess(); #pragma warning disable 0618 AssertNonZeroWindowsZeroUnix(_process.PeakVirtualMemorySize); #pragma warning restore 0618 } [Fact] public void PeakVirtualMemorySize_GetNotStarted_ThrowsInvalidOperationException() { var process = new Process(); #pragma warning disable 0618 Assert.Throws<InvalidOperationException>(() => process.PeakVirtualMemorySize); #pragma warning restore 0618 } [Fact] public void TestPeakWorkingSet() { CreateDefaultProcess(); #pragma warning disable 0618 AssertNonZeroWindowsZeroUnix(_process.PeakWorkingSet); #pragma warning restore 0618 } [Fact] public void PeakWorkingSet_GetNotStarted_ThrowsInvalidOperationException() { var process = new Process(); #pragma warning disable 0618 Assert.Throws<InvalidOperationException>(() => process.PeakWorkingSet); #pragma warning restore 0618 } [Fact] public void TestPrivateMemorySize() { CreateDefaultProcess(); #pragma warning disable 0618 AssertNonZeroWindowsZeroUnix(_process.PrivateMemorySize); #pragma warning restore 0618 } [Fact] public void PrivateMemorySize_GetNotStarted_ThrowsInvalidOperationException() { var process = new Process(); #pragma warning disable 0618 Assert.Throws<InvalidOperationException>(() => process.PrivateMemorySize); #pragma warning restore 0618 } [Fact] public void TestVirtualMemorySize() { CreateDefaultProcess(); #pragma warning disable 0618 Assert.Equal(unchecked((int)_process.VirtualMemorySize64), _process.VirtualMemorySize); #pragma warning restore 0618 } [Fact] public void VirtualMemorySize_GetNotStarted_ThrowsInvalidOperationException() { var process = new Process(); #pragma warning disable 0618 Assert.Throws<InvalidOperationException>(() => process.VirtualMemorySize); #pragma warning restore 0618 } [Fact] public void TestWorkingSet() { CreateDefaultProcess(); if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { // resident memory can be 0 on OSX. #pragma warning disable 0618 Assert.True(_process.WorkingSet >= 0); #pragma warning restore 0618 return; } #pragma warning disable 0618 Assert.True(_process.WorkingSet > 0); #pragma warning restore 0618 } [Fact] public void WorkingSet_GetNotStarted_ThrowsInvalidOperationException() { var process = new Process(); #pragma warning disable 0618 Assert.Throws<InvalidOperationException>(() => process.WorkingSet); #pragma warning restore 0618 } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // Starting process with authentication not supported on Unix public void Process_StartInvalidNamesTest() { Assert.Throws<InvalidOperationException>(() => Process.Start(null, "userName", new SecureString(), "thisDomain")); Assert.Throws<InvalidOperationException>(() => Process.Start(string.Empty, "userName", new SecureString(), "thisDomain")); Assert.Throws<Win32Exception>(() => Process.Start("exe", string.Empty, new SecureString(), "thisDomain")); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // Starting process with authentication not supported on Unix public void Process_StartWithInvalidUserNamePassword() { SecureString password = AsSecureString("Value"); Assert.Throws<Win32Exception>(() => Process.Start(GetCurrentProcessName(), "userName", password, "thisDomain")); Assert.Throws<Win32Exception>(() => Process.Start(GetCurrentProcessName(), Environment.UserName, password, Environment.UserDomainName)); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // Starting process with authentication not supported on Unix public void Process_StartTest() { string currentProcessName = GetCurrentProcessName(); string userName = string.Empty; string domain = "thisDomain"; SecureString password = AsSecureString("Value"); Process p = Process.Start(currentProcessName, userName, password, domain); Assert.NotNull(p); Assert.Equal(currentProcessName, p.StartInfo.FileName); Assert.Equal(userName, p.StartInfo.UserName); Assert.Same(password, p.StartInfo.Password); Assert.Equal(domain, p.StartInfo.Domain); Assert.True(p.WaitForExit(WaitInMS)); password.Dispose(); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // Starting process with authentication not supported on Unix public void Process_StartWithArgumentsTest() { string currentProcessName = GetCurrentProcessName(); string userName = string.Empty; string domain = Environment.UserDomainName; string arguments = "-xml testResults.xml"; SecureString password = AsSecureString("Value"); Process p = Process.Start(currentProcessName, arguments, userName, password, domain); Assert.NotNull(p); Assert.Equal(currentProcessName, p.StartInfo.FileName); Assert.Equal(arguments, p.StartInfo.Arguments); Assert.Equal(userName, p.StartInfo.UserName); Assert.Same(password, p.StartInfo.Password); Assert.Equal(domain, p.StartInfo.Domain); p.Kill(); password.Dispose(); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // Starting process with authentication not supported on Unix public void Process_StartWithDuplicatePassword() { var startInfo = new ProcessStartInfo() { FileName = "exe", UserName = "dummyUser", PasswordInClearText = "Value", Password = AsSecureString("Value"), UseShellExecute = false }; var process = new Process() { StartInfo = startInfo }; Assert.Throws<ArgumentException>(null, () => process.Start()); } private string GetCurrentProcessName() { return $"{Process.GetCurrentProcess().ProcessName}.exe"; } private SecureString AsSecureString(string str) { SecureString secureString = new SecureString(); foreach (var ch in str) { secureString.AppendChar(ch); } return secureString; } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Drawing; using System.Drawing.Drawing2D; using System.Security.Permissions; using System.Windows.Forms; using System.Windows.Forms.VisualStyles; using System.Collections; using System.Drawing.Design; using Aga.Controls.Tree.NodeControls; using System.Drawing.Imaging; using System.Diagnostics; namespace Aga.Controls.Tree { public partial class TreeViewAdv : Control { private const int LeftMargin = 7; internal const int ItemDragSensivity = 4; private readonly int _columnHeaderHeight; private const int DividerWidth = 9; private Pen _linePen; private Pen _markPen; private bool _suspendUpdate; private bool _needFullUpdate; private bool _fireSelectionEvent; private NodePlusMinus _plusMinus; private Control _currentEditor; private EditableControl _currentEditorOwner; private ToolTip _toolTip; private Timer _dragTimer; private IRowLayout _rowLayout; private DrawContext _measureContext; private TreeColumn _hotColumn = null; #region Public Events [Category("Action")] public event ItemDragEventHandler ItemDrag; private void OnItemDrag(MouseButtons buttons, object item) { if (ItemDrag != null) ItemDrag(this, new ItemDragEventArgs(buttons, item)); } [Category("Behavior")] public event EventHandler<TreeNodeAdvMouseEventArgs> NodeMouseDoubleClick; private void OnNodeMouseDoubleClick(TreeNodeAdvMouseEventArgs args) { if (NodeMouseDoubleClick != null) NodeMouseDoubleClick(this, args); } [Category("Behavior")] public event EventHandler<TreeColumnEventArgs> ColumnWidthChanged; internal void OnColumnWidthChanged(TreeColumn column) { if (ColumnWidthChanged != null) ColumnWidthChanged(this, new TreeColumnEventArgs(column)); } [Category("Behavior")] public event EventHandler<TreeColumnEventArgs> ColumnReordered; internal void OnColumnReordered(TreeColumn column) { if (ColumnReordered != null) ColumnReordered(this, new TreeColumnEventArgs(column)); } [Category("Behavior")] public event EventHandler<TreeColumnEventArgs> ColumnClicked; internal void OnColumnClicked(TreeColumn column) { if (ColumnClicked != null) ColumnClicked(this, new TreeColumnEventArgs(column)); } [Category("Behavior")] public event EventHandler SelectionChanged; internal void OnSelectionChanged() { if (SuspendSelectionEvent) _fireSelectionEvent = true; else { _fireSelectionEvent = false; if (SelectionChanged != null) SelectionChanged(this, EventArgs.Empty); } } [Category("Behavior")] public event EventHandler<TreeViewAdvEventArgs> Collapsing; internal void OnCollapsing(TreeNodeAdv node) { if (Collapsing != null) Collapsing(this, new TreeViewAdvEventArgs(node)); } [Category("Behavior")] public event EventHandler<TreeViewAdvEventArgs> Collapsed; internal void OnCollapsed(TreeNodeAdv node) { if (Collapsed != null) Collapsed(this, new TreeViewAdvEventArgs(node)); } [Category("Behavior")] public event EventHandler<TreeViewAdvEventArgs> Expanding; internal void OnExpanding(TreeNodeAdv node) { if (Expanding != null) Expanding(this, new TreeViewAdvEventArgs(node)); } [Category("Behavior")] public event EventHandler<TreeViewAdvEventArgs> Expanded; internal void OnExpanded(TreeNodeAdv node) { ListView t; if (Expanded != null) Expanded(this, new TreeViewAdvEventArgs(node)); } #endregion public TreeViewAdv() { InitializeComponent(); SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint | ControlStyles.OptimizedDoubleBuffer | ControlStyles.ResizeRedraw | ControlStyles.Selectable , true); if (Application.RenderWithVisualStyles) _columnHeaderHeight = 20; else _columnHeaderHeight = 17; BorderStyle = BorderStyle.Fixed3D; _hScrollBar.Height = SystemInformation.HorizontalScrollBarHeight; _vScrollBar.Width = SystemInformation.VerticalScrollBarWidth; _rowLayout = new FixedRowHeightLayout(this, RowHeight); _rowMap = new List<TreeNodeAdv>(); _selection = new List<TreeNodeAdv>(); _readonlySelection = new ReadOnlyCollection<TreeNodeAdv>(_selection); _columns = new TreeColumnCollection(this); _toolTip = new ToolTip(); _dragTimer = new Timer(); _dragTimer.Interval = 100; _dragTimer.Tick += new EventHandler(DragTimerTick); _measureContext = new DrawContext(); _measureContext.Font = Font; _measureContext.Graphics = Graphics.FromImage(new Bitmap(1, 1)); Input = new NormalInputState(this); Search = new IncrementalSearch(); CreateNodes(); CreatePens(); ArrangeControls(); _plusMinus = new NodePlusMinus(); _controls = new NodeControlsCollection(this); } #region Public Methods public TreePath GetPath(TreeNodeAdv node) { if (node == _root) return TreePath.Empty; else { Stack<object> stack = new Stack<object>(); while (node != _root && node != null) { stack.Push(node.Tag); node = node.Parent; } return new TreePath(stack.ToArray()); } } public TreeNodeAdv GetNodeAt(Point point) { NodeControlInfo info = GetNodeControlInfoAt(point); return info.Node; } public NodeControlInfo GetNodeControlInfoAt(Point point) { if (point.X < 0 || point.Y < 0) return NodeControlInfo.Empty; int row = _rowLayout.GetRowAt(point); if (row < RowCount && row >= 0) return GetNodeControlInfoAt(_rowMap[row], point); else return NodeControlInfo.Empty; } public void BeginUpdate() { _suspendUpdate = true; } public void EndUpdate() { _suspendUpdate = false; if (_needFullUpdate) FullUpdate(); else UpdateView(); } public void ExpandAll() { BeginUpdate(); SetIsExpanded(_root, true); EndUpdate(); } public void CollapseAll() { BeginUpdate(); SetIsExpanded(_root, false); EndUpdate(); } /// <summary> /// Expand all parent nodes, andd scroll to the specified node /// </summary> public void EnsureVisible(TreeNodeAdv node) { if (node == null) throw new ArgumentNullException("node"); if (!IsMyNode(node)) throw new ArgumentException(); TreeNodeAdv parent = node.Parent; while (parent != _root) { parent.IsExpanded = true; parent = parent.Parent; } ScrollTo(node); } /// <summary> /// Make node visible, scroll if needed. All parent nodes of the specified node must be expanded /// </summary> /// <param name="node"></param> public void ScrollTo(TreeNodeAdv node) { if (node == null) throw new ArgumentNullException("node"); if (!IsMyNode(node)) throw new ArgumentException(); if (node.Row < 0) CreateRowMap(); int row = -1; if (node.Row < FirstVisibleRow) row = node.Row; else { int pageStart = _rowLayout.GetRowBounds(FirstVisibleRow).Top; int rowBottom = _rowLayout.GetRowBounds(node.Row).Bottom; if (rowBottom > pageStart + DisplayRectangle.Height - ColumnHeaderHeight) row = _rowLayout.GetFirstRow(node.Row); } if (row >= _vScrollBar.Minimum && row <= _vScrollBar.Maximum) _vScrollBar.Value = row; } public void ClearSelection() { while (Selection.Count > 0) Selection[0].IsSelected = false; } #endregion protected override void OnSizeChanged(EventArgs e) { ArrangeControls(); SafeUpdateScrollBars(); base.OnSizeChanged(e); } private void ArrangeControls() { int hBarSize = _hScrollBar.Height; int vBarSize = _vScrollBar.Width; Rectangle clientRect = ClientRectangle; _hScrollBar.SetBounds(clientRect.X, clientRect.Bottom - hBarSize, clientRect.Width - vBarSize, hBarSize); _vScrollBar.SetBounds(clientRect.Right - vBarSize, clientRect.Y, vBarSize, clientRect.Height - hBarSize); } private void SafeUpdateScrollBars() { if (InvokeRequired) Invoke(new MethodInvoker(UpdateScrollBars)); else UpdateScrollBars(); } private void UpdateScrollBars() { UpdateVScrollBar(); UpdateHScrollBar(); UpdateVScrollBar(); UpdateHScrollBar(); _hScrollBar.Width = DisplayRectangle.Width; _vScrollBar.Height = DisplayRectangle.Height; } private void UpdateHScrollBar() { _hScrollBar.Maximum = ContentWidth; _hScrollBar.LargeChange = Math.Max(DisplayRectangle.Width, 0); _hScrollBar.SmallChange = 5; _hScrollBar.Visible = _hScrollBar.LargeChange < _hScrollBar.Maximum; _hScrollBar.Value = Math.Min(_hScrollBar.Value, _hScrollBar.Maximum - _hScrollBar.LargeChange + 1); } private void UpdateVScrollBar() { _vScrollBar.Maximum = Math.Max(RowCount - 1, 0); _vScrollBar.LargeChange = _rowLayout.PageRowCount; _vScrollBar.Visible = (RowCount > 0) && (_vScrollBar.LargeChange <= _vScrollBar.Maximum); _vScrollBar.Value = Math.Min(_vScrollBar.Value, _vScrollBar.Maximum - _vScrollBar.LargeChange + 1); } protected override CreateParams CreateParams { [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode)] get { CreateParams res = base.CreateParams; switch (BorderStyle) { case BorderStyle.FixedSingle: res.Style |= 0x800000; break; case BorderStyle.Fixed3D: res.ExStyle |= 0x200; break; } return res; } } protected override void OnGotFocus(EventArgs e) { HideEditor(); UpdateView(); ChangeInput(); base.OnGotFocus(e); } protected override void OnLeave(EventArgs e) { HideEditor(); UpdateView(); base.OnLeave(e); } protected override void OnFontChanged(EventArgs e) { base.OnFontChanged(e); _measureContext.Font = Font; _rowLayout.ClearCache(); FullUpdate(); } internal IEnumerable<NodeControlInfo> GetNodeControls(TreeNodeAdv node) { if (node == null) yield break; Rectangle rowRect = _rowLayout.GetRowBounds(node.Row); int y = rowRect.Y; int x = (node.Level - 1) * _indent + LeftMargin; int width = 0; Rectangle rect = Rectangle.Empty; if (ShowPlusMinus) { width = _plusMinus.MeasureSize(node, _measureContext).Width; rect = new Rectangle(x, y, width, rowRect.Height); if (HeaderStyle != ColumnHeaderStyle.None && Columns.Count > 0 && Columns[0].Width < rect.Right) rect.Width = Columns[0].Width - x; yield return new NodeControlInfo(_plusMinus, rect, node); x += (width + 1); } if (HeaderStyle == ColumnHeaderStyle.None) { foreach (NodeControl c in NodeControls) { width = c.MeasureSize(node, _measureContext).Width; rect = new Rectangle(x, y, width, rowRect.Height); x += (width + 1); yield return new NodeControlInfo(c, rect, node); } } else { int right = 0; foreach (TreeColumn col in Columns) { if (col.IsVisible) { right += col.Width; for (int i = 0; i < NodeControls.Count; i++) { NodeControl nc = NodeControls[i]; if (nc.ParentColumn == col) { bool isLastControl = true; for (int k = i + 1; k < NodeControls.Count; k++) if (NodeControls[k].ParentColumn == col) { isLastControl = false; break; } width = right - x; if (!isLastControl) width = nc.MeasureSize(node, _measureContext).Width; int maxWidth = Math.Max(0, right - x); rect = new Rectangle(x, y, Math.Min(maxWidth, width), rowRect.Height); x += (width + 1); yield return new NodeControlInfo(nc, rect, node); } } x = right; } } } } internal static double Dist(Point p1, Point p2) { return Math.Sqrt(Math.Pow(p1.X - p2.X, 2) + Math.Pow(p1.Y - p2.Y, 2)); } internal void FullUpdate() { _rowLayout.ClearCache(); CreateRowMap(); SafeUpdateScrollBars(); UpdateView(); _needFullUpdate = false; } internal void UpdateView() { if (!_suspendUpdate) Invalidate(false); } internal void UpdateHeaders() { Invalidate(new Rectangle(0,0, Width, ColumnHeaderHeight)); } internal void UpdateColumns() { FullUpdate(); } private void CreateNodes() { Selection.Clear(); SelectionStart = null; _root = new TreeNodeAdv(this, null); _root.IsExpanded = true; if (_root.Nodes.Count > 0) CurrentNode = _root.Nodes[0]; else CurrentNode = null; } internal void ReadChilds(TreeNodeAdv parentNode) { if (!parentNode.IsLeaf) { parentNode.IsExpandedOnce = true; List<TreeNodeAdv> oldNodes = new List<TreeNodeAdv>(parentNode.Nodes); parentNode.Nodes.Clear(); if (Model != null) { IEnumerable items = Model.GetChildren(GetPath(parentNode)); if (items != null) foreach (object obj in items) { bool found = false; if (obj != null) { for (int i = 0; i < oldNodes.Count; i++) if (obj == oldNodes[i].Tag) { AddNode(parentNode, -1, oldNodes[i]); oldNodes.RemoveAt(i); found = true; break; } } if (!found) AddNewNode(parentNode, obj, -1); } } } } private void AddNewNode(TreeNodeAdv parent, object tag, int index) { TreeNodeAdv node = new TreeNodeAdv(this, tag); AddNode(parent, index, node); } private void AddNode(TreeNodeAdv parent, int index, TreeNodeAdv node) { if (index >= 0 && index < parent.Nodes.Count) parent.Nodes.Insert(index, node); else parent.Nodes.Add(node); node.IsLeaf = Model.IsLeaf(GetPath(node)); if (node.IsLeaf) node.Nodes.Clear(); if (!LoadOnDemand || node.IsExpandedOnce) ReadChilds(node); } private void CreateRowMap() { _rowMap.Clear(); int row = 0; _contentWidth = 0; foreach (TreeNodeAdv node in VisibleNodes) { node.Row = row; _rowMap.Add(node); if (HeaderStyle == ColumnHeaderStyle.None) { Rectangle rect = GetNodeBounds(node); _contentWidth = Math.Max(_contentWidth, rect.Right); } row++; } if (HeaderStyle != ColumnHeaderStyle.None) { _contentWidth = 0; foreach (TreeColumn col in _columns) if (col.IsVisible) _contentWidth += col.Width; } } private NodeControlInfo GetNodeControlInfoAt(TreeNodeAdv node, Point point) { Rectangle rect = _rowLayout.GetRowBounds(FirstVisibleRow); point.Y += (rect.Y - ColumnHeaderHeight); point.X += OffsetX; foreach (NodeControlInfo info in GetNodeControls(node)) if (info.Bounds.Contains(point)) return info; return NodeControlInfo.Empty; } private Rectangle GetNodeBounds(TreeNodeAdv node) { Rectangle res = Rectangle.Empty; foreach (NodeControlInfo info in GetNodeControls(node)) { if (res == Rectangle.Empty) res = info.Bounds; else res = Rectangle.Union(res, info.Bounds); } return res; } private void _vScrollBar_ValueChanged(object sender, EventArgs e) { FirstVisibleRow = _vScrollBar.Value; } private void _hScrollBar_ValueChanged(object sender, EventArgs e) { OffsetX = _hScrollBar.Value; } private void SetIsExpanded(TreeNodeAdv root, bool value) { foreach (TreeNodeAdv node in root.Nodes) { node.IsExpanded = value; SetIsExpanded(node, value); } } internal void SmartFullUpdate() { if (_suspendUpdate) _needFullUpdate = true; else FullUpdate(); } internal bool IsMyNode(TreeNodeAdv node) { if (node == null) return false; if (node.Tree != this) return false; while (node.Parent != null) node = node.Parent; return node == _root; } private void UpdateSelection() { bool flag = false; if (!IsMyNode(CurrentNode)) CurrentNode = null; if (!IsMyNode(_selectionStart)) _selectionStart = null; for (int i = Selection.Count - 1; i >= 0; i--) if (!IsMyNode(Selection[i])) { flag = true; Selection.RemoveAt(i); } if (flag) OnSelectionChanged(); } internal void ChangeColumnWidth(TreeColumn column) { if (!(_input is ResizeColumnState)) { FullUpdate(); OnColumnWidthChanged(column); } } #region Editor public void DisplayEditor(Control control, EditableControl owner) { if (control == null || owner == null) throw new ArgumentNullException(); if (CurrentNode != null) { HideEditor(); _currentEditor = control; _currentEditorOwner = owner; UpdateEditorBounds(); UpdateView(); control.Parent = this; control.Focus(); owner.UpdateEditor(control); } } public void UpdateEditorBounds() { if (_currentEditor != null) { EditorContext context = new EditorContext(); context.Owner = _currentEditorOwner; context.CurrentNode = CurrentNode; context.Editor = _currentEditor; context.DrawContext = _measureContext; SetEditorBounds(context); } } public void HideEditor() { if (_currentEditorOwner != null) { _currentEditorOwner.HideEditor(_currentEditor); _currentEditor = null; _currentEditorOwner = null; } } private void SetEditorBounds(EditorContext context) { foreach (NodeControlInfo info in GetNodeControls(context.CurrentNode)) { if (context.Owner == info.Control && info.Control is EditableControl) { Point p = info.Bounds.Location; p.X -= OffsetX; p.Y -= (_rowLayout.GetRowBounds(FirstVisibleRow).Y - ColumnHeaderHeight); int width = DisplayRectangle.Width - p.X; if (HeaderStyle != ColumnHeaderStyle.None && info.Control.ParentColumn != null && Columns.Contains(info.Control.ParentColumn)) { Rectangle rect = GetColumnBounds(info.Control.ParentColumn.Index); width = rect.Right - OffsetX - p.X; } context.Bounds = new Rectangle(p.X, p.Y, width, info.Bounds.Height); ((EditableControl)info.Control).SetEditorBounds(context); return; } } } private Rectangle GetColumnBounds(int column) { int x = 0; for (int i = 0; i < Columns.Count; i++) { if (Columns[i].IsVisible) { if (i < column) x += Columns[i].Width; else return new Rectangle(x, 0, Columns[i].Width, 0); } } return Rectangle.Empty; } #endregion #region ModelEvents private void BindModelEvents() { _model.NodesChanged += new EventHandler<TreeModelEventArgs>(_model_NodesChanged); _model.NodesInserted += new EventHandler<TreeModelEventArgs>(_model_NodesInserted); _model.NodesRemoved += new EventHandler<TreeModelEventArgs>(_model_NodesRemoved); _model.StructureChanged += new EventHandler<TreePathEventArgs>(_model_StructureChanged); } private void UnbindModelEvents() { _model.NodesChanged -= new EventHandler<TreeModelEventArgs>(_model_NodesChanged); _model.NodesInserted -= new EventHandler<TreeModelEventArgs>(_model_NodesInserted); _model.NodesRemoved -= new EventHandler<TreeModelEventArgs>(_model_NodesRemoved); _model.StructureChanged -= new EventHandler<TreePathEventArgs>(_model_StructureChanged); } private void _model_StructureChanged(object sender, TreePathEventArgs e) { if (e.Path == null) throw new ArgumentNullException(); TreeNodeAdv node = FindNode(e.Path); if (node != null) { ReadChilds(node); UpdateSelection(); SmartFullUpdate(); } else throw new ArgumentException("Path not found"); } private void _model_NodesRemoved(object sender, TreeModelEventArgs e) { TreeNodeAdv parent = FindNode(e.Path); if (parent != null) { if (e.Indices != null) { List<int> list = new List<int>(e.Indices); list.Sort(); for (int n = list.Count - 1; n >= 0; n--) { int index = list[n]; if (index >= 0 && index <= parent.Nodes.Count) parent.Nodes.RemoveAt(index); else throw new ArgumentOutOfRangeException("Index out of range"); } } else { for (int i = parent.Nodes.Count - 1; i >= 0; i--) { for (int n = 0; n < e.Children.Length; n++) if (parent.Nodes[i].Tag == e.Children[n]) { parent.Nodes.RemoveAt(i); break; } } } } UpdateSelection(); SmartFullUpdate(); } private void _model_NodesInserted(object sender, TreeModelEventArgs e) { if (e.Indices == null) throw new ArgumentNullException("Indices"); TreeNodeAdv parent = FindNode(e.Path); if (parent != null) { for (int i = 0; i < e.Children.Length; i++) AddNewNode(parent, e.Children[i], e.Indices[i]); } SmartFullUpdate(); } private void _model_NodesChanged(object sender, TreeModelEventArgs e) { TreeNodeAdv parent = FindNode(e.Path); if (parent != null) { if (e.Indices != null) { foreach (int index in e.Indices) { if (index >= 0 && index < parent.Nodes.Count) { TreeNodeAdv node = parent.Nodes[index]; Rectangle rect = GetNodeBounds(node); _contentWidth = Math.Max(_contentWidth, rect.Right); } else throw new ArgumentOutOfRangeException("Index out of range"); } } else { foreach (TreeNodeAdv node in parent.Nodes) { foreach (object obj in e.Children) if (node.Tag == obj) { Rectangle rect = GetNodeBounds(node); _contentWidth = Math.Max(_contentWidth, rect.Right); } } } } _rowLayout.ClearCache(); SafeUpdateScrollBars(); UpdateView(); } public TreeNodeAdv FindNode(TreePath path) { if (path.IsEmpty()) return _root; else return FindNode(_root, path, 0); } private TreeNodeAdv FindNode(TreeNodeAdv root, TreePath path, int level) { foreach (TreeNodeAdv node in root.Nodes) if (node.Tag == path.FullPath[level]) { if (level == path.FullPath.Length - 1) return node; else return FindNode(node, path, level + 1); } return null; } #endregion } }
using System; /// <summary> /// FromBase64CharArray(System.Char[],System.Int32,System.Int32) /// </summary> public class ConvertFromBase64CharArray { #region Public Methods public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = NegTest1() && retVal; retVal = NegTest2() && retVal; retVal = NegTest2b() && retVal; retVal = NegTest3() && retVal; retVal = NegTest4() && retVal; return retVal; } #region Positive Test Cases public bool PosTest1() { bool retVal = true; // Add your scenario description here TestLibrary.TestFramework.BeginScenario("PosTest1: Verify method FromBase64CharArray ."); try { byte[] byteArray1 = new byte[256]; byte[] byteArray2 = new byte[256]; char[] charArray = new char[352]; int charArrayLength; for (int x = 0; x < byteArray1.Length; x++) byteArray1[x] = (byte)x; charArrayLength = Convert.ToBase64CharArray( byteArray1, 0, byteArray1.Length, charArray, 0); byteArray2 = Convert.FromBase64CharArray(charArray, 0, charArrayLength); if (!ArraysAreEqual(byteArray1,byteArray2)) { TestLibrary.TestFramework.LogError("001.1", "Method ChangeType Err."); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("001.2", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } #endregion #region Nagetive Test Cases public bool NegTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest1: inArray is a null reference."); try { byte[] byteArray1 = new byte[256]; byte[] byteArray2 = new byte[256]; char[] charArray = new char[352]; int charArrayLength; for (int x = 0; x < byteArray1.Length; x++) byteArray1[x] = (byte)x; charArrayLength = Convert.ToBase64CharArray( byteArray1, 0, byteArray1.Length, charArray, 0); charArray = null; byteArray2 = Convert.FromBase64CharArray(charArray, 0, charArrayLength); TestLibrary.TestFramework.LogError("101.1", "ArgumentNullException is not thrown."); retVal = false; } catch (ArgumentNullException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("101.2", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } public bool NegTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest2: offset is less than 0."); try { byte[] byteArray1 = new byte[256]; byte[] byteArray2 = new byte[256]; char[] charArray = new char[352]; int charArrayLength; for (int x = 0; x < byteArray1.Length; x++) byteArray1[x] = (byte)x; charArrayLength = Convert.ToBase64CharArray( byteArray1, 0, byteArray1.Length, charArray, 0); byteArray2 = Convert.FromBase64CharArray(charArray, -1, charArrayLength); TestLibrary.TestFramework.LogError("102.1", "ArgumentOutOfRangeException is not thrown."); retVal = false; } catch (ArgumentOutOfRangeException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("102.2", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } public bool NegTest2b() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest2b: length is less than 0."); try { byte[] byteArray1 = new byte[256]; byte[] byteArray2 = new byte[256]; char[] charArray = new char[352]; int charArrayLength; for (int x = 0; x < byteArray1.Length; x++) byteArray1[x] = (byte)x; charArrayLength = Convert.ToBase64CharArray( byteArray1, 0, byteArray1.Length, charArray, 0); byteArray2 = Convert.FromBase64CharArray(charArray, 0, -1); TestLibrary.TestFramework.LogError("102.1", "ArgumentOutOfRangeException is not thrown."); retVal = false; } catch (ArgumentOutOfRangeException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("102.2", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } public bool NegTest3() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest3: offset plus length indicates a position not within inArray."); try { byte[] byteArray1 = new byte[256]; byte[] byteArray2 = new byte[256]; char[] charArray = new char[352]; int charArrayLength; for (int x = 0; x < byteArray1.Length; x++) byteArray1[x] = (byte)x; charArrayLength = Convert.ToBase64CharArray( byteArray1, 0, byteArray1.Length, charArray, 0); byteArray2 = Convert.FromBase64CharArray(charArray, 0, charArrayLength + 10); TestLibrary.TestFramework.LogError("103.1", "ArgumentOutOfRangeException is not thrown."); retVal = false; } catch (ArgumentOutOfRangeException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("103.2", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } public bool NegTest4() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest4: The format of inArray is invalid. inArray contains a non-base 64 "+ "character, more than two padding characters, or a non-white space character "+ "among the padding characters."); try { byte[] byteArray1 = new byte[256]; byte[] byteArray2 = new byte[256]; char[] charArray = new char[352]; int charArrayLength; for (int x = 0; x < byteArray1.Length; x++) byteArray1[x] = (byte)x; charArrayLength = Convert.ToBase64CharArray( byteArray1, 0, byteArray1.Length, charArray, 0); charArray = new char[352 + 1]; byteArray2 = Convert.FromBase64CharArray(charArray, 0, charArrayLength); TestLibrary.TestFramework.LogError("104.1", "FormatException is not thrown."); retVal = false; } catch (FormatException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("104.2", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } #endregion #endregion public static int Main() { ConvertFromBase64CharArray test = new ConvertFromBase64CharArray(); TestLibrary.TestFramework.BeginTestCase("ConvertFromBase64CharArray"); if (test.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } #region Private Method private bool ArraysAreEqual(byte[] a1, byte[] a2) { if (a1.Length != a2.Length) return false; for (int i = 0; i < a1.Length; i++) if (a1[i] != a2[i]) return false; return true; } #endregion }
//--------------------------------------------------------------------- // <copyright file="AtomValueUtils.cs" company="Microsoft"> // Copyright (C) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information. // </copyright> //--------------------------------------------------------------------- namespace Microsoft.OData.Core { #region Namespaces using System; using System.Diagnostics; using System.Xml; using Microsoft.OData.Edm; using Microsoft.OData.Core.Atom; using Microsoft.OData.Core.Metadata; using Microsoft.OData.Edm.Library; #endregion Namespaces /// <summary> /// Utility methods around writing of ATOM values. /// </summary> internal static class AtomValueUtils { /// <summary>The characters that are considered to be whitespace by XmlConvert.</summary> private static readonly char[] XmlWhitespaceChars = new char[] { ' ', '\t', '\n', '\r' }; /// <summary> /// Converts the given value to the ATOM string representation /// and uses the writer to write it. /// </summary> /// <param name="writer">The writer to write the stringified value.</param> /// <param name="value">The value to be written.</param> internal static void WritePrimitiveValue(XmlWriter writer, object value) { Debug.Assert(value != null, "value != null"); if (!PrimitiveConverter.Instance.TryWriteAtom(value, writer)) { string result = ConvertPrimitiveToString(value); ODataAtomWriterUtils.WriteString(writer, result); } } /// <summary>Converts the specified value to a serializable string in ATOM format, or throws an exception if the value cannot be converted.</summary> /// <param name="value">Non-null value to convert.</param> /// <returns>The specified value converted to an ATOM string.</returns> internal static string ConvertPrimitiveToString(object value) { string result; if (!TryConvertPrimitiveToString(value, out result)) { throw new ODataException(Strings.AtomValueUtils_CannotConvertValueToAtomPrimitive(value.GetType().FullName)); } return result; } /// <summary> /// Reads a string value of an XML element and gets TypeName from model's EdmEnumTypeReference. /// </summary> /// <param name="reader">The XML reader to read the value from.</param> /// <param name="enumTypeReference">The enum rype reference.</param> /// <returns>An ODataEnumValue</returns> internal static ODataEnumValue ReadEnumValue(XmlReader reader, IEdmEnumTypeReference enumTypeReference) { Debug.Assert(reader != null, "reader != null"); // skip the validation on value or type name. string stringValue = reader.ReadElementContentValue(); string typeName = (enumTypeReference != null) ? enumTypeReference.ODataFullName() : null; return new ODataEnumValue(stringValue, typeName); } /// <summary> /// Reads a value of an XML element and converts it to the target primitive value. /// </summary> /// <param name="reader">The XML reader to read the value from.</param> /// <param name="primitiveTypeReference">The primitive type reference to convert the value to.</param> /// <returns>The primitive value read.</returns> /// <remarks>This method does not read null values, it only reads the actual element value (not its attributes).</remarks> /// <remarks> /// Pre-Condition: XmlNodeType.Element - the element to read the value for. /// XmlNodeType.Attribute - an attribute on the element to read the value for. /// Post-Condition: XmlNodeType.Element - the element was empty. /// XmlNodeType.EndElement - the element had some value. /// </remarks> internal static object ReadPrimitiveValue(XmlReader reader, IEdmPrimitiveTypeReference primitiveTypeReference) { Debug.Assert(reader != null, "reader != null"); object spatialValue; if (!PrimitiveConverter.Instance.TryTokenizeFromXml(reader, EdmLibraryExtensions.GetPrimitiveClrType(primitiveTypeReference), out spatialValue)) { string stringValue = reader.ReadElementContentValue(); return ConvertStringToPrimitive(stringValue, primitiveTypeReference); } return spatialValue; } /// <summary> /// Converts a given <see cref="AtomTextConstructKind"/> to a string appropriate for Atom format. /// </summary> /// <param name="textConstructKind">The text construct kind to convert.</param> /// <returns>The string version of the text construct format in Atom format.</returns> internal static string ToString(AtomTextConstructKind textConstructKind) { switch (textConstructKind) { case AtomTextConstructKind.Text: return AtomConstants.AtomTextConstructTextKind; case AtomTextConstructKind.Html: return AtomConstants.AtomTextConstructHtmlKind; case AtomTextConstructKind.Xhtml: return AtomConstants.AtomTextConstructXHtmlKind; default: throw new ODataException(Strings.General_InternalError(InternalErrorCodes.ODataAtomConvert_ToString)); } } /// <summary>Converts the specified value to a serializable string in ATOM format.</summary> /// <param name="value">Non-null value to convert.</param> /// <param name="result">The specified value converted to an ATOM string.</param> /// <returns>boolean value indicating conversion successful conversion</returns> internal static bool TryConvertPrimitiveToString(object value, out string result) { Debug.Assert(value != null, "value != null"); result = null; TypeCode typeCode = PlatformHelper.GetTypeCode(value.GetType()); switch (typeCode) { case TypeCode.Boolean: result = ODataAtomConvert.ToString((bool)value); break; case TypeCode.Byte: result = ODataAtomConvert.ToString((byte)value); break; case TypeCode.Decimal: result = ODataAtomConvert.ToString((decimal)value); break; case TypeCode.Double: result = ODataAtomConvert.ToString((double)value); break; case TypeCode.Int16: result = ODataAtomConvert.ToString((Int16)value); break; case TypeCode.Int32: result = ODataAtomConvert.ToString((Int32)value); break; case TypeCode.Int64: result = ODataAtomConvert.ToString((Int64)value); break; case TypeCode.SByte: result = ODataAtomConvert.ToString((SByte)value); break; case TypeCode.String: result = (string)value; break; case TypeCode.Single: result = ODataAtomConvert.ToString((Single)value); break; default: byte[] bytes = value as byte[]; if (bytes != null) { result = ODataAtomConvert.ToString(bytes); break; } if (value is DateTimeOffset) { result = ODataAtomConvert.ToString((DateTimeOffset)value); break; } if (value is Guid) { result = ODataAtomConvert.ToString((Guid)value); break; } if (value is TimeSpan) { // Edm.Duration result = ODataAtomConvert.ToString((TimeSpan)value); break; } if (value is Date) { // Edm.Date result = ODataAtomConvert.ToString((Date)value); break; } if (value is TimeOfDay) { // Edm.TimeOfDay result = ODataAtomConvert.ToString((TimeOfDay)value); break; } return false; } Debug.Assert(result != null, "result != null"); return true; } /// <summary> /// Converts a string to a primitive value. /// </summary> /// <param name="text">The string text to convert.</param> /// <param name="targetTypeReference">Type to convert the string to.</param> /// <returns>The value converted to the target type.</returns> /// <remarks>This method does not convert null value.</remarks> [System.Diagnostics.CodeAnalysis.SuppressMessage("DataWeb.Usage", "AC0014", Justification = "Throws every time")] internal static object ConvertStringToPrimitive(string text, IEdmPrimitiveTypeReference targetTypeReference) { Debug.Assert(text != null, "text != null"); Debug.Assert(targetTypeReference != null, "targetTypeReference != null"); try { EdmPrimitiveTypeKind primitiveKind = targetTypeReference.PrimitiveKind(); switch (primitiveKind) { case EdmPrimitiveTypeKind.Binary: return Convert.FromBase64String(text); case EdmPrimitiveTypeKind.Boolean: return ConvertXmlBooleanValue(text); case EdmPrimitiveTypeKind.Byte: return XmlConvert.ToByte(text); case EdmPrimitiveTypeKind.DateTimeOffset: return PlatformHelper.ConvertStringToDateTimeOffset(text); case EdmPrimitiveTypeKind.Decimal: return XmlConvert.ToDecimal(text); case EdmPrimitiveTypeKind.Double: return XmlConvert.ToDouble(text); case EdmPrimitiveTypeKind.Guid: return new Guid(text); case EdmPrimitiveTypeKind.Int16: return XmlConvert.ToInt16(text); case EdmPrimitiveTypeKind.Int32: return XmlConvert.ToInt32(text); case EdmPrimitiveTypeKind.Int64: return XmlConvert.ToInt64(text); case EdmPrimitiveTypeKind.SByte: return XmlConvert.ToSByte(text); case EdmPrimitiveTypeKind.Single: return XmlConvert.ToSingle(text); case EdmPrimitiveTypeKind.String: return text; case EdmPrimitiveTypeKind.Duration: return EdmValueParser.ParseDuration(text); case EdmPrimitiveTypeKind.Date: return PlatformHelper.ConvertStringToDate(text); case EdmPrimitiveTypeKind.TimeOfDay: return PlatformHelper.ConvertStringToTimeOfDay(text); case EdmPrimitiveTypeKind.Stream: case EdmPrimitiveTypeKind.None: case EdmPrimitiveTypeKind.Geography: case EdmPrimitiveTypeKind.GeographyCollection: case EdmPrimitiveTypeKind.GeographyPoint: case EdmPrimitiveTypeKind.GeographyLineString: case EdmPrimitiveTypeKind.GeographyPolygon: case EdmPrimitiveTypeKind.GeometryCollection: case EdmPrimitiveTypeKind.GeographyMultiPolygon: case EdmPrimitiveTypeKind.GeographyMultiLineString: case EdmPrimitiveTypeKind.GeographyMultiPoint: case EdmPrimitiveTypeKind.Geometry: case EdmPrimitiveTypeKind.GeometryPoint: case EdmPrimitiveTypeKind.GeometryLineString: case EdmPrimitiveTypeKind.GeometryPolygon: case EdmPrimitiveTypeKind.GeometryMultiPolygon: case EdmPrimitiveTypeKind.GeometryMultiLineString: case EdmPrimitiveTypeKind.GeometryMultiPoint: default: // Note that Astoria supports XElement and Binary as well, but they are serialized as string or byte[] // and the metadata will actually talk about string and byte[] as well. Astoria will perform the conversion if necessary. throw new ODataException(Strings.General_InternalError(InternalErrorCodes.AtomValueUtils_ConvertStringToPrimitive)); } } catch (Exception e) { if (!ExceptionUtils.IsCatchableExceptionType(e)) { throw; } throw ReaderValidationUtils.GetPrimitiveTypeConversionException(targetTypeReference, e, text); } } /// <summary> /// Reimplementation of XmlConvert.ToBoolean that accepts 'True' and 'False' in addition /// to 'true' and 'false'. /// </summary> /// <param name="text">The string value read from the Xml reader.</param> /// <returns>The converted boolean value.</returns> private static bool ConvertXmlBooleanValue(string text) { text = text.Trim(XmlWhitespaceChars); switch (text) { case "true": case "True": case "1": return true; case "false": case "False": case "0": return false; default: // We know that this will throw; call XmlConvert for the appropriate error message. return XmlConvert.ToBoolean(text); } } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Azure.Management.Compute; using Microsoft.Azure.Management.Compute.Models; using Microsoft.Azure.Management.Network; using Microsoft.Azure.Management.Network.Models; using Microsoft.Azure.Management.ResourceManager; using Microsoft.Azure.Management.ResourceManager.Models; using Microsoft.Azure.Management.Storage; using Microsoft.Azure.Management.Storage.Models; using Microsoft.Rest.Azure; using Microsoft.Rest.ClientRuntime.Azure.TestFramework; using Newtonsoft.Json.Linq; using Xunit; using CM = Microsoft.Azure.Management.Compute.Models; namespace Compute.Tests { public class VMScaleSetTestsBase : VMTestBase { protected VirtualMachineScaleSetExtension GetTestVMSSVMExtension( string name = "vmssext01", string publisher = "Microsoft.Compute", string type = "VMAccessAgent", string version = "2.0", bool autoUpdateMinorVersion = true, bool? enableAutomaticUpgrade = null, bool? suppressFailures = null) { var vmExtension = new VirtualMachineScaleSetExtension { Name = name, Publisher = publisher, Type1 = type, TypeHandlerVersion = version, AutoUpgradeMinorVersion = autoUpdateMinorVersion, Settings = "{}", ProtectedSettings = "{}", EnableAutomaticUpgrade = enableAutomaticUpgrade, SuppressFailures = suppressFailures }; return vmExtension; } protected VirtualMachineScaleSetExtension GetVmssServiceFabricExtension() { VirtualMachineScaleSetExtension sfExtension = new VirtualMachineScaleSetExtension { Name = "vmsssfext01", Publisher = "Microsoft.Azure.ServiceFabric", Type1 = "ServiceFabricNode", TypeHandlerVersion = "1.0", AutoUpgradeMinorVersion = true, Settings = "{}", ProtectedSettings = "{}" }; return sfExtension; } protected VirtualMachineScaleSetExtension GetAzureDiskEncryptionExtension() { // NOTE: Replace dummy values for AAD credentials and KeyVault urls below by running DiskEncryptionPreRequisites.ps1. // There is no ARM client implemented for key-vault in swagger test framework yet. These changes need to go sooner to // unblock powershell cmdlets/API for disk encryption on scale set. So recorded this test by creating required resources // in prod and replaced them with dummy value before check-in. // // Follow below steps to run this test again: // Step 1: Execute DiskEncryptionPreRequisites.ps1. Use same subscription and region as you are running test in. // Step 2: Replace aadClientId, aadClientSecret, keyVaultUrl, and keyVaultId values below with the values returned // by above PS script // Step 3: Run test and record session // Step 4: Delete KeyVault, AAD app created by above PS script // Step 5: Replace values for AAD credentials and KeyVault urls by dummy values before check-in string aadClientId = Guid.NewGuid().ToString(); string aadClientSecret = Guid.NewGuid().ToString(); string keyVaultUrl = "https://adetestkv1.vault.azure.net/"; string keyVaultId = "/subscriptions/d0d8594d-65c5-481c-9a58-fea6f203f1e2/resourceGroups/adetest/providers/Microsoft.KeyVault/vaults/adetestkv1"; string settings = string.Format("\"AADClientID\": \"{0}\", \"KeyVaultURL\": \"{1}\", \"KeyEncryptionKeyURL\": \"\", \"KeyVaultResourceId\":\"{2}\", \"KekVaultResourceId\": \"\", \"KeyEncryptionAlgorithm\": \"{3}\", \"VolumeType\": \"{4}\", \"EncryptionOperation\": \"{5}\"", aadClientId, keyVaultUrl, keyVaultId, "", "All", "DisableEncryption"); string protectedSettings = string.Format("\"AADClientSecret\": \"{0}\"", aadClientSecret); var vmExtension = new VirtualMachineScaleSetExtension { Name = "adeext1", Publisher = "Microsoft.Azure.Security", Type1 = "ADETest", TypeHandlerVersion = "2.0", Settings = new JRaw("{ " + settings + " }"), ProtectedSettings = new JRaw("{ " + protectedSettings + " }") }; return vmExtension; } protected VirtualMachineScaleSet CreateDefaultVMScaleSetInput( string rgName, string storageAccountName, ImageReference imageRef, string subnetId, bool hasManagedDisks = false, string healthProbeId = null, string loadBalancerBackendPoolId = null, IList<string> zones = null, int? osDiskSizeInGB = null, string machineSizeType = null, bool? enableUltraSSD = false, string diskEncryptionSetId = null, AutomaticRepairsPolicy automaticRepairsPolicy = null, DiagnosticsProfile bootDiagnosticsProfile = null, int? faultDomainCount = null, int? capacity = null) { // Generate Container name to hold disk VHds string containerName = TestUtilities.GenerateName(TestPrefix); var vhdContainer = "https://" + storageAccountName + ".blob.core.windows.net/" + containerName; var vmssName = TestUtilities.GenerateName("vmss"); bool createOSDisk = !hasManagedDisks || osDiskSizeInGB != null; string vmSize = zones == null ? VirtualMachineSizeTypes.StandardA1V2 : VirtualMachineSizeTypes.StandardA1V2; var vmScaleSet = new VirtualMachineScaleSet() { Location = m_location, Tags = new Dictionary<string, string>() { { "RG", "rg" }, { "testTag", "1" } }, Sku = new CM.Sku() { Capacity = capacity ?? 2, Name = machineSizeType == null ? vmSize : machineSizeType }, Zones = zones, Overprovision = false, UpgradePolicy = new UpgradePolicy() { Mode = UpgradeMode.Automatic }, VirtualMachineProfile = new VirtualMachineScaleSetVMProfile() { StorageProfile = new VirtualMachineScaleSetStorageProfile() { ImageReference = imageRef, OsDisk = !createOSDisk ? null : new VirtualMachineScaleSetOSDisk { Caching = CachingTypes.None, CreateOption = DiskCreateOptionTypes.FromImage, Name = hasManagedDisks ? null : "test", VhdContainers = hasManagedDisks ? null : new List<string>{ vhdContainer }, DiskSizeGB = osDiskSizeInGB, ManagedDisk = diskEncryptionSetId == null ? null: new VirtualMachineScaleSetManagedDiskParameters() { StorageAccountType = StorageAccountTypes.StandardLRS, DiskEncryptionSet = new DiskEncryptionSetParameters() { Id = diskEncryptionSetId } } }, DataDisks = !hasManagedDisks ? null : new List<VirtualMachineScaleSetDataDisk> { new VirtualMachineScaleSetDataDisk { Lun = 1, CreateOption = DiskCreateOptionTypes.Empty, DiskSizeGB = 128, ManagedDisk = diskEncryptionSetId == null ? null: new VirtualMachineScaleSetManagedDiskParameters() { StorageAccountType = StorageAccountTypes.StandardLRS, DiskEncryptionSet = new DiskEncryptionSetParameters() { Id = diskEncryptionSetId } } } } }, OsProfile = new VirtualMachineScaleSetOSProfile() { ComputerNamePrefix = "test", AdminUsername = "Foo12", AdminPassword = PLACEHOLDER, CustomData = Convert.ToBase64String(Encoding.UTF8.GetBytes("Custom data")) }, NetworkProfile = new VirtualMachineScaleSetNetworkProfile() { HealthProbe = healthProbeId == null ? null : new ApiEntityReference { Id = healthProbeId }, NetworkInterfaceConfigurations = new List<VirtualMachineScaleSetNetworkConfiguration>() { new VirtualMachineScaleSetNetworkConfiguration() { Name = TestUtilities.GenerateName("vmsstestnetconfig"), Primary = true, IpConfigurations = new List<VirtualMachineScaleSetIPConfiguration> { new VirtualMachineScaleSetIPConfiguration() { Name = TestUtilities.GenerateName("vmsstestnetconfig"), Subnet = new Microsoft.Azure.Management.Compute.Models.ApiEntityReference() { Id = subnetId }, LoadBalancerBackendAddressPools = (loadBalancerBackendPoolId != null) ? new List<Microsoft.Azure.Management.Compute.Models.SubResource> { new Microsoft.Azure.Management.Compute.Models.SubResource(loadBalancerBackendPoolId) } : null, ApplicationGatewayBackendAddressPools = new List<Microsoft.Azure.Management.Compute.Models.SubResource>(), } } } } }, ExtensionProfile = new VirtualMachineScaleSetExtensionProfile(), }, AutomaticRepairsPolicy = automaticRepairsPolicy }; if (bootDiagnosticsProfile != null) { vmScaleSet.VirtualMachineProfile.DiagnosticsProfile = bootDiagnosticsProfile; } if (faultDomainCount != null) { vmScaleSet.PlatformFaultDomainCount = faultDomainCount; } if (enableUltraSSD == true) { vmScaleSet.AdditionalCapabilities = new AdditionalCapabilities { UltraSSDEnabled = true }; VirtualMachineScaleSetOSDisk osDisk = vmScaleSet.VirtualMachineProfile.StorageProfile.OsDisk; osDisk.ManagedDisk = osDisk.ManagedDisk ?? new VirtualMachineScaleSetManagedDiskParameters(); osDisk.ManagedDisk.StorageAccountType = StorageAccountTypes.PremiumLRS; foreach (VirtualMachineScaleSetDataDisk dataDisk in vmScaleSet.VirtualMachineProfile.StorageProfile.DataDisks) { dataDisk.ManagedDisk = dataDisk.ManagedDisk ?? new VirtualMachineScaleSetManagedDiskParameters(); dataDisk.ManagedDisk.StorageAccountType = StorageAccountTypes.UltraSSDLRS; } } return vmScaleSet; } public VirtualMachineScaleSet CreateVMScaleSet_NoAsyncTracking( string rgName, string vmssName, StorageAccount storageAccount, ImageReference imageRef, out VirtualMachineScaleSet inputVMScaleSet, VirtualMachineScaleSetExtensionProfile extensionProfile = null, Action<VirtualMachineScaleSet> vmScaleSetCustomizer = null, bool createWithPublicIpAddress = false, bool createWithManagedDisks = false, bool hasDiffDisks = false, bool createWithHealthProbe = false, Subnet subnet = null, IList<string> zones = null, int? osDiskSizeInGB = null, string ppgId = null, string machineSizeType = null, bool? enableUltraSSD = false, string diskEncryptionSetId = null, AutomaticRepairsPolicy automaticRepairsPolicy = null, bool? encryptionAtHostEnabled = null, bool singlePlacementGroup = true, DiagnosticsProfile bootDiagnosticsProfile = null, int? faultDomainCount = null, int? capacity = null, string dedicatedHostGroupReferenceId = null, string dedicatedHostGroupName = null, string dedicatedHostName = null, string userData = null, string capacityReservationGroupReferenceId = null) { try { var createOrUpdateResponse = CreateVMScaleSetAndGetOperationResponse(rgName, vmssName, storageAccount, imageRef, out inputVMScaleSet, extensionProfile, vmScaleSetCustomizer, createWithPublicIpAddress, createWithManagedDisks, hasDiffDisks, createWithHealthProbe, subnet, zones, osDiskSizeInGB, ppgId: ppgId, machineSizeType: machineSizeType, enableUltraSSD: enableUltraSSD, diskEncryptionSetId: diskEncryptionSetId, automaticRepairsPolicy: automaticRepairsPolicy, encryptionAtHostEnabled: encryptionAtHostEnabled, singlePlacementGroup: singlePlacementGroup, bootDiagnosticsProfile: bootDiagnosticsProfile, faultDomainCount: faultDomainCount, capacity: capacity, dedicatedHostGroupReferenceId: dedicatedHostGroupReferenceId, dedicatedHostGroupName: dedicatedHostGroupName, dedicatedHostName: dedicatedHostName, userData: userData, capacityReservationGroupReferenceId: capacityReservationGroupReferenceId); var getResponse = m_CrpClient.VirtualMachineScaleSets.Get(rgName, vmssName); return getResponse; } catch { // TODO: It is better to issue Delete and forget. m_ResourcesClient.ResourceGroups.Delete(rgName); throw; } } protected VirtualMachineScaleSet CreateVMScaleSet( string rgName, string vmssName, StorageAccount storageAccount, ImageReference imageRef, out VirtualMachineScaleSet inputVMScaleSet, VirtualMachineScaleSetExtensionProfile extensionProfile = null, Action<VirtualMachineScaleSet> vmScaleSetCustomizer = null, bool createWithPublicIpAddress = false, bool createWithManagedDisks = false) { try { var createOrUpdateResponse = CreateVMScaleSetAndGetOperationResponse( rgName, vmssName, storageAccount, imageRef, out inputVMScaleSet, extensionProfile, vmScaleSetCustomizer, createWithPublicIpAddress, createWithManagedDisks); var lroResponse = m_CrpClient.VirtualMachineScaleSets.CreateOrUpdate(rgName, inputVMScaleSet.Name, inputVMScaleSet); var getResponse = m_CrpClient.VirtualMachineScaleSets.Get(rgName, inputVMScaleSet.Name); return getResponse; } catch { m_ResourcesClient.ResourceGroups.Delete(rgName); throw; } } protected void UpdateVMScaleSet(string rgName, string vmssName, VirtualMachineScaleSet inputVMScaleSet) { var createOrUpdateResponse = m_CrpClient.VirtualMachineScaleSets.CreateOrUpdate(rgName, vmssName, inputVMScaleSet); } // This method is used to Update VM Scale Set but it internally calls PATCH verb instead of PUT. // PATCH verb is more relaxed and does not puts constraint to specify full parameters. protected void PatchVMScaleSet(string rgName, string vmssName, VirtualMachineScaleSetUpdate inputVMScaleSet) { var patchResponse = m_CrpClient.VirtualMachineScaleSets.Update(rgName, vmssName, inputVMScaleSet); } private VirtualMachineScaleSet CreateVMScaleSetAndGetOperationResponse( string rgName, string vmssName, StorageAccount storageAccount, ImageReference imageRef, out VirtualMachineScaleSet inputVMScaleSet, VirtualMachineScaleSetExtensionProfile extensionProfile = null, Action<VirtualMachineScaleSet> vmScaleSetCustomizer = null, bool createWithPublicIpAddress = false, bool createWithManagedDisks = false, bool hasDiffDisks = false, bool createWithHealthProbe = false, Subnet subnet = null, IList<string> zones = null, int? osDiskSizeInGB = null, string ppgId = null, string machineSizeType = null, bool? enableUltraSSD = false, string diskEncryptionSetId = null, AutomaticRepairsPolicy automaticRepairsPolicy = null, bool? encryptionAtHostEnabled = null, bool singlePlacementGroup = true, DiagnosticsProfile bootDiagnosticsProfile = null, int? faultDomainCount = null, int? capacity = null, string dedicatedHostGroupReferenceId = null, string dedicatedHostGroupName = null, string dedicatedHostName = null, string userData = null, string capacityReservationGroupReferenceId = null) { // Create the resource Group, it might have been already created during StorageAccount creation. var resourceGroup = m_ResourcesClient.ResourceGroups.CreateOrUpdate( rgName, new ResourceGroup { Location = m_location }); var getPublicIpAddressResponse = createWithPublicIpAddress ? null : CreatePublicIP(rgName); var subnetResponse = subnet ?? CreateVNET(rgName); var nicResponse = CreateNIC( rgName, subnetResponse, getPublicIpAddressResponse != null ? getPublicIpAddressResponse.IpAddress : null); var loadBalancer = (getPublicIpAddressResponse != null && createWithHealthProbe) ? CreatePublicLoadBalancerWithProbe(rgName, getPublicIpAddressResponse) : null; Assert.True(createWithManagedDisks || storageAccount != null); inputVMScaleSet = CreateDefaultVMScaleSetInput(rgName, storageAccount?.Name, imageRef, subnetResponse.Id, hasManagedDisks:createWithManagedDisks, healthProbeId: loadBalancer?.Probes?.FirstOrDefault()?.Id, loadBalancerBackendPoolId: loadBalancer?.BackendAddressPools?.FirstOrDefault()?.Id, zones: zones, osDiskSizeInGB: osDiskSizeInGB, machineSizeType: machineSizeType, enableUltraSSD: enableUltraSSD, diskEncryptionSetId: diskEncryptionSetId, automaticRepairsPolicy: automaticRepairsPolicy, bootDiagnosticsProfile: bootDiagnosticsProfile, faultDomainCount: faultDomainCount, capacity: capacity); if (vmScaleSetCustomizer != null) { vmScaleSetCustomizer(inputVMScaleSet); } if (encryptionAtHostEnabled != null) { inputVMScaleSet.VirtualMachineProfile.SecurityProfile = new SecurityProfile { EncryptionAtHost = encryptionAtHostEnabled.Value }; } inputVMScaleSet.VirtualMachineProfile.UserData = userData; if (hasDiffDisks) { VirtualMachineScaleSetOSDisk osDisk = new VirtualMachineScaleSetOSDisk(); osDisk.Caching = CachingTypes.ReadOnly; osDisk.CreateOption = DiskCreateOptionTypes.FromImage; osDisk.DiffDiskSettings = new DiffDiskSettings { Option = DiffDiskOptions.Local, Placement = DiffDiskPlacement.CacheDisk }; inputVMScaleSet.VirtualMachineProfile.StorageProfile.OsDisk = osDisk; } inputVMScaleSet.VirtualMachineProfile.ExtensionProfile = extensionProfile; if (ppgId != null) { inputVMScaleSet.ProximityPlacementGroup = new Microsoft.Azure.Management.Compute.Models.SubResource() { Id = ppgId }; } if (dedicatedHostGroupReferenceId != null) { CreateDedicatedHostGroup(rgName, dedicatedHostGroupName, availabilityZone: null); CreateDedicatedHost(rgName, dedicatedHostGroupName, dedicatedHostName, "DSv3-Type1"); inputVMScaleSet.HostGroup = new CM.SubResource() { Id = dedicatedHostGroupReferenceId }; } if (!string.IsNullOrEmpty(capacityReservationGroupReferenceId)) { inputVMScaleSet.VirtualMachineProfile.CapacityReservation = new CapacityReservationProfile { CapacityReservationGroup = new CM.SubResource { Id = capacityReservationGroupReferenceId } }; } inputVMScaleSet.SinglePlacementGroup = singlePlacementGroup ? (bool?) null : false; VirtualMachineScaleSet createOrUpdateResponse = null; try { createOrUpdateResponse = m_CrpClient.VirtualMachineScaleSets.CreateOrUpdate(rgName, vmssName, inputVMScaleSet); Assert.True(createOrUpdateResponse.Name == vmssName); Assert.True(createOrUpdateResponse.Location.ToLower() == inputVMScaleSet.Location.ToLower().Replace(" ", "")); } catch (CloudException e) { if (e.Message.Contains("the allotted time")) { createOrUpdateResponse = m_CrpClient.VirtualMachineScaleSets.Get(rgName, vmssName); } else { throw; } } ValidateVMScaleSet(inputVMScaleSet, createOrUpdateResponse, createWithManagedDisks, ppgId: ppgId, dedicatedHostGroupReferenceId: dedicatedHostGroupReferenceId); return createOrUpdateResponse; } protected void ValidateVMScaleSetInstanceView(VirtualMachineScaleSet vmScaleSet, VirtualMachineScaleSetInstanceView vmScaleSetInstanceView) { Assert.NotNull(vmScaleSetInstanceView.Statuses); Assert.NotNull(vmScaleSetInstanceView); if (vmScaleSet.VirtualMachineProfile.ExtensionProfile != null) { Assert.NotNull(vmScaleSetInstanceView.Extensions); int instancesCount = vmScaleSetInstanceView.Extensions.First().StatusesSummary.Sum(t => t.Count.Value); Assert.True(instancesCount == vmScaleSet.Sku.Capacity); } } protected void ValidateVMScaleSet(VirtualMachineScaleSet vmScaleSet, VirtualMachineScaleSet vmScaleSetOut, bool hasManagedDisks = false, string ppgId = null, string dedicatedHostGroupReferenceId = null) { Assert.True(!string.IsNullOrEmpty(vmScaleSetOut.ProvisioningState)); Assert.True(vmScaleSetOut.Sku.Name == vmScaleSet.Sku.Name); Assert.NotNull(vmScaleSetOut.VirtualMachineProfile.StorageProfile.OsDisk); if (vmScaleSet.VirtualMachineProfile.StorageProfile.OsDisk?.DiskSizeGB != null) { Assert.NotNull(vmScaleSetOut.VirtualMachineProfile.StorageProfile.OsDisk.DiskSizeGB); Assert.Equal(vmScaleSet.VirtualMachineProfile.StorageProfile.OsDisk.DiskSizeGB, vmScaleSetOut.VirtualMachineProfile.StorageProfile.OsDisk.DiskSizeGB); } if (!hasManagedDisks) { Assert.True(vmScaleSetOut.VirtualMachineProfile.StorageProfile.OsDisk.Name == vmScaleSet.VirtualMachineProfile.StorageProfile.OsDisk.Name); if (vmScaleSet.VirtualMachineProfile.StorageProfile.OsDisk.Image != null) { Assert.True(vmScaleSetOut.VirtualMachineProfile.StorageProfile.OsDisk.Image.Uri == vmScaleSet.VirtualMachineProfile.StorageProfile.OsDisk.Image.Uri); } Assert.True(vmScaleSetOut.VirtualMachineProfile.StorageProfile.OsDisk.Caching == vmScaleSet.VirtualMachineProfile.StorageProfile.OsDisk.Caching); } else { Assert.NotNull(vmScaleSetOut.VirtualMachineProfile.StorageProfile.OsDisk.ManagedDisk); if (vmScaleSet.VirtualMachineProfile.StorageProfile.OsDisk != null) { VirtualMachineScaleSetOSDisk osDisk = vmScaleSet.VirtualMachineProfile.StorageProfile.OsDisk; VirtualMachineScaleSetOSDisk osDiskOut = vmScaleSetOut.VirtualMachineProfile.StorageProfile.OsDisk; if (osDisk.Caching != null) { Assert.True(osDisk.Caching == osDiskOut.Caching); } else { Assert.NotNull(osDiskOut.Caching); } if(osDisk.DiffDiskSettings != null) { Assert.True(osDisk.DiffDiskSettings.Option == osDiskOut.DiffDiskSettings.Option); } Assert.NotNull(osDiskOut.ManagedDisk); if (osDisk.ManagedDisk != null && osDisk.ManagedDisk.StorageAccountType != null) { Assert.True(osDisk.ManagedDisk.StorageAccountType == osDiskOut.ManagedDisk.StorageAccountType); } else { Assert.NotNull(osDiskOut.ManagedDisk.StorageAccountType); } if (osDisk.Name != null) { Assert.Equal(osDiskOut.Name, osDisk.Name); } Assert.True(osDiskOut.CreateOption == DiskCreateOptionTypes.FromImage); } if (vmScaleSet.VirtualMachineProfile.StorageProfile.DataDisks != null && vmScaleSet.VirtualMachineProfile.StorageProfile.DataDisks.Count > 0) { Assert.Equal( vmScaleSet.VirtualMachineProfile.StorageProfile.DataDisks.Count, vmScaleSetOut.VirtualMachineProfile.StorageProfile.DataDisks.Count); foreach (VirtualMachineScaleSetDataDisk dataDisk in vmScaleSet.VirtualMachineProfile.StorageProfile.DataDisks) { VirtualMachineScaleSetDataDisk matchingDataDisk = vmScaleSetOut.VirtualMachineProfile.StorageProfile.DataDisks.FirstOrDefault(disk => disk.Lun == dataDisk.Lun); Assert.NotNull(matchingDataDisk); if (dataDisk.Caching != null) { Assert.True(dataDisk.Caching == matchingDataDisk.Caching); } else { Assert.NotNull(matchingDataDisk.Caching); } if (dataDisk.ManagedDisk != null && dataDisk.ManagedDisk.StorageAccountType != null) { Assert.True(dataDisk.ManagedDisk.StorageAccountType == matchingDataDisk.ManagedDisk.StorageAccountType); } else { Assert.NotNull(matchingDataDisk.ManagedDisk.StorageAccountType); } if (dataDisk.Name != null) { Assert.Equal(dataDisk.Name, matchingDataDisk.Name); } Assert.True(dataDisk.CreateOption == matchingDataDisk.CreateOption); } } } if (vmScaleSet.UpgradePolicy?.AutomaticOSUpgradePolicy != null) { bool expectedDisableAutomaticRollbackValue = vmScaleSet.UpgradePolicy.AutomaticOSUpgradePolicy.DisableAutomaticRollback ?? false; Assert.True(vmScaleSetOut.UpgradePolicy.AutomaticOSUpgradePolicy.DisableAutomaticRollback == expectedDisableAutomaticRollbackValue); bool expectedEnableAutomaticOSUpgradeValue = vmScaleSet.UpgradePolicy.AutomaticOSUpgradePolicy.EnableAutomaticOSUpgrade ?? false; Assert.True(vmScaleSetOut.UpgradePolicy.AutomaticOSUpgradePolicy.EnableAutomaticOSUpgrade == expectedEnableAutomaticOSUpgradeValue); } if (vmScaleSet.AutomaticRepairsPolicy != null) { bool expectedAutomaticRepairsEnabledValue = vmScaleSet.AutomaticRepairsPolicy.Enabled ?? false; Assert.True(vmScaleSetOut.AutomaticRepairsPolicy.Enabled == expectedAutomaticRepairsEnabledValue); string expectedAutomaticRepairsGracePeriodValue = vmScaleSet.AutomaticRepairsPolicy.GracePeriod ?? "PT10M"; Assert.Equal(vmScaleSetOut.AutomaticRepairsPolicy.GracePeriod, expectedAutomaticRepairsGracePeriodValue, ignoreCase: true); } if (vmScaleSet.VirtualMachineProfile.OsProfile.Secrets != null && vmScaleSet.VirtualMachineProfile.OsProfile.Secrets.Any()) { foreach (var secret in vmScaleSet.VirtualMachineProfile.OsProfile.Secrets) { Assert.NotNull(secret.VaultCertificates); var secretOut = vmScaleSetOut.VirtualMachineProfile.OsProfile.Secrets.FirstOrDefault(s => string.Equals(secret.SourceVault.Id, s.SourceVault.Id)); Assert.NotNull(secretOut); // Disabling resharper null-ref check as it doesn't seem to understand the not-null assert above. // ReSharper disable PossibleNullReferenceException Assert.NotNull(secretOut.VaultCertificates); var VaultCertComparer = new VaultCertComparer(); Assert.True(secretOut.VaultCertificates.SequenceEqual(secret.VaultCertificates, VaultCertComparer)); // ReSharper enable PossibleNullReferenceException } } if (vmScaleSet.VirtualMachineProfile.ExtensionProfile != null && vmScaleSet.VirtualMachineProfile.ExtensionProfile.Extensions.Any()) { foreach (var vmExtension in vmScaleSet.VirtualMachineProfile.ExtensionProfile.Extensions) { var vmExt = vmScaleSetOut.VirtualMachineProfile.ExtensionProfile.Extensions.FirstOrDefault(s => String.Compare(s.Name, vmExtension.Name, StringComparison.OrdinalIgnoreCase) == 0); Assert.NotNull(vmExt); } } if (vmScaleSet.VirtualMachineProfile.NetworkProfile != null) { if (vmScaleSet.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations != null && vmScaleSet.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations.Count > 0) { Assert.NotNull(vmScaleSetOut.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations); Assert.Equal( vmScaleSetOut.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations.Count, vmScaleSet.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations.Count); foreach (var nicconfig in vmScaleSet.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations) { var outnicconfig = vmScaleSetOut.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations.First( nc => string.Equals(nc.Name, nicconfig.Name, StringComparison.OrdinalIgnoreCase)); Assert.NotNull(outnicconfig); CompareVmssNicConfig(nicconfig, outnicconfig); } } } else { Assert.True((vmScaleSetOut.VirtualMachineProfile.NetworkProfile == null) || (vmScaleSetOut.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations.Count == 0)); } if(vmScaleSet.Zones != null) { Assert.True(vmScaleSet.Zones.SequenceEqual(vmScaleSetOut.Zones), "Zones don't match"); if(vmScaleSet.ZoneBalance.HasValue) { Assert.Equal(vmScaleSet.ZoneBalance, vmScaleSetOut.ZoneBalance); } else { if (vmScaleSet.Zones.Count > 1) { Assert.True(vmScaleSetOut.ZoneBalance.HasValue); } else { Assert.False(vmScaleSetOut.ZoneBalance.HasValue); } } if (vmScaleSet.PlatformFaultDomainCount.HasValue) { Assert.Equal(vmScaleSet.PlatformFaultDomainCount, vmScaleSetOut.PlatformFaultDomainCount); } else { Assert.True(vmScaleSetOut.PlatformFaultDomainCount.HasValue); } } else { Assert.Null(vmScaleSetOut.Zones); Assert.Null(vmScaleSetOut.ZoneBalance); } if(ppgId != null) { Assert.Equal(ppgId, vmScaleSetOut.ProximityPlacementGroup.Id, StringComparer.OrdinalIgnoreCase); } if (dedicatedHostGroupReferenceId != null) { Assert.Equal(dedicatedHostGroupReferenceId, vmScaleSetOut.HostGroup.Id, StringComparer.OrdinalIgnoreCase); } if(vmScaleSet.ScaleInPolicy?.ForceDeletion != null) { Assert.Equal(vmScaleSet.ScaleInPolicy.ForceDeletion, vmScaleSetOut.ScaleInPolicy.ForceDeletion); } } protected void CompareVmssNicConfig(VirtualMachineScaleSetNetworkConfiguration nicconfig, VirtualMachineScaleSetNetworkConfiguration outnicconfig) { if (nicconfig.IpConfigurations != null && nicconfig.IpConfigurations.Count > 0) { Assert.NotNull(outnicconfig.IpConfigurations); Assert.Equal(nicconfig.IpConfigurations.Count, outnicconfig.IpConfigurations.Count); foreach (var ipconfig in nicconfig.IpConfigurations) { var outipconfig = outnicconfig.IpConfigurations.First( ic => string.Equals(ic.Name, ipconfig.Name, StringComparison.OrdinalIgnoreCase)); Assert.NotNull(outipconfig); CompareIpConfigApplicationGatewayPools(ipconfig, outipconfig); } } else { Assert.True((outnicconfig.IpConfigurations == null) || (outnicconfig.IpConfigurations.Count == 0)); } } protected void CompareIpConfigApplicationGatewayPools(VirtualMachineScaleSetIPConfiguration ipconfig, VirtualMachineScaleSetIPConfiguration outipconfig) { if (ipconfig.ApplicationGatewayBackendAddressPools != null && ipconfig.ApplicationGatewayBackendAddressPools.Count > 0) { Assert.NotNull(outipconfig.ApplicationGatewayBackendAddressPools); Assert.Equal(ipconfig.ApplicationGatewayBackendAddressPools.Count, outipconfig.ApplicationGatewayBackendAddressPools.Count); foreach (var pool in ipconfig.ApplicationGatewayBackendAddressPools) { var outPool = outipconfig.ApplicationGatewayBackendAddressPools.First( p => string.Equals(p.Id, pool.Id, StringComparison.OrdinalIgnoreCase)); Assert.NotNull(outPool); } } else { Assert.True((outipconfig.ApplicationGatewayBackendAddressPools == null) || (outipconfig.ApplicationGatewayBackendAddressPools.Count == 0)); } } } }
namespace Microsoft.Protocols.TestSuites.MS_ASHTTP { using System; using System.Collections.Generic; using Microsoft.Protocols.TestSuites.Common; using Microsoft.Protocols.TestTools; using Microsoft.VisualStudio.TestTools.UnitTesting; using Response = Microsoft.Protocols.TestSuites.Common.Response; /// <summary> /// This scenario is designed to test HTTP POST commands with positive response. /// </summary> [TestClass] public class S01_HTTPPOSTPositive : TestSuiteBase { #region Class initialize and clean up /// <summary> /// Initialize the class. /// </summary> /// <param name="testContext">VSTS test context.</param> [ClassInitialize] public static void ClassInitialize(TestContext testContext) { TestClassBase.Initialize(testContext); } /// <summary> /// Clear the class. /// </summary> [ClassCleanup] public static void ClassCleanup() { TestClassBase.Cleanup(); } #endregion #region Test cases /// <summary> /// This test case is intended to validate the Content-Type response header. /// </summary> [TestCategory("MSASHTTP"), TestMethod()] public void MSASHTTP_S01_TC01_VerifyContentTypeResponseHeader() { #region Synchronize the collection hierarchy via FolderSync command. FolderSyncResponse folderSyncResponse = this.CallFolderSyncCommand(); Site.Assert.IsNotNull(folderSyncResponse.Headers["Content-Type"], "The Content-Type header should not be null."); #endregion // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASHTTP_R219"); // Verify MS-ASHTTP requirement: MS-ASHTTP_R219 // If the content type is WBXML, this requirement can be captured. Site.CaptureRequirementIfAreEqual<string>( "application/vnd.ms-sync.wbxml", folderSyncResponse.Headers["Content-Type"], 219, @"[In Content-Type] If the response body is WBXML, the value of this [Content-Type] header MUST be ""application/vnd.ms-sync.wbxml""."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASHTTP_R229"); // Verify MS-ASHTTP requirement: MS-ASHTTP_R229 // If the content type is WBXML, this requirement can be captured. Site.CaptureRequirementIfAreEqual<string>( "application/vnd.ms-sync.wbxml", folderSyncResponse.Headers["Content-Type"], 229, @"[In Response Body] The response body [except the Autodiscover command], if any, is in WBXML."); } /// <summary> /// This test case is intended to validate the Content-Encoding response header. /// </summary> [TestCategory("MSASHTTP"), TestMethod()] public void MSASHTTP_S01_TC02_VerifyContentEncodingResponseHeader() { #region Call FolderSync command without setting AcceptEncoding header. FolderSyncResponse folderSyncResponse = this.CallFolderSyncCommand(); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASHTTP_R412"); // Verify MS-ASHTTP requirement: MS-ASHTTP_R412 // If the Content-Encoding header doesn't exist, this requirement can be captured. Site.CaptureRequirementIfIsFalse( folderSyncResponse.Headers.ToString().Contains("Content-Encoding"), 412, @"[In Response Headers] [[Header] Content-Encoding [is] required when the content is compressed ;] otherwise, this header [Content-Encoding] is not included."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASHTTP_R215"); // Verify MS-ASHTTP requirement: MS-ASHTTP_R215 // If the Content-Encoding header doesn't exist, this requirement can be captured. Site.CaptureRequirementIfIsFalse( folderSyncResponse.Headers.ToString().Contains("Content-Encoding"), 215, @"[In Content-Encoding] Otherwise [if the response body is not compressed], it [Content-Encoding header] is omitted."); #endregion #region Call ConfigureRequestPrefixFields to set the AcceptEncoding header to "gzip". IDictionary<HTTPPOSTRequestPrefixField, string> requestPrefix = new Dictionary<HTTPPOSTRequestPrefixField, string>(); requestPrefix.Add(HTTPPOSTRequestPrefixField.AcceptEncoding, "gzip"); this.HTTPAdapter.ConfigureRequestPrefixFields(requestPrefix); #endregion #region Call FolderSync command. folderSyncResponse = this.LoopCallFolderSyncCommand(); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASHTTP_R197"); // Verify MS-ASHTTP requirement: MS-ASHTTP_R197 // If the Content-Encoding header is gzip, this requirement can be captured. Site.CaptureRequirementIfAreEqual<string>( "gzip", folderSyncResponse.Headers["Content-Encoding"], 197, @"[In Response Headers] [Header] Content-Encoding [is] required when the content is compressed [; otherwise, this header [Content-Encoding] is not included]."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASHTTP_R214"); // Verify MS-ASHTTP requirement: MS-ASHTTP_R214 // If the Content-Encoding header is gzip, this requirement can be captured. Site.CaptureRequirementIfAreEqual<string>( "gzip", folderSyncResponse.Headers["Content-Encoding"], 214, @"[In Content-Encoding] This [Content-Encoding] header is required if the response body is compressed."); #endregion } /// <summary> /// This test case is intended to validate the AttachmentName command parameter with Base64 encoding query value type. /// </summary> [TestCategory("MSASHTTP"), TestMethod()] public void MSASHTTP_S01_TC03_CommandParameter_AttachmentName_Base64() { Site.Assume.AreNotEqual<string>("14.0", Common.GetConfigurationPropertyValue("ActiveSyncProtocolVersion", this.Site), "The GetAttachment command is not supported when the MS-ASProtocolVersion header is set to 14.0. MS-ASProtocolVersion header value is determined using Common PTFConfig property named ActiveSyncProtocolVersion."); Site.Assume.AreNotEqual<string>("14.1", Common.GetConfigurationPropertyValue("ActiveSyncProtocolVersion", this.Site), "The GetAttachment command is not supported when the MS-ASProtocolVersion header is set to 14.1. MS-ASProtocolVersion header value is determined using Common PTFConfig property named ActiveSyncProtocolVersion."); Site.Assume.AreNotEqual<string>("16.0", Common.GetConfigurationPropertyValue("ActiveSyncProtocolVersion", this.Site), "The GetAttachment command is not supported when the MS-ASProtocolVersion header is set to 16.0. MS-ASProtocolVersion header value is determined using Common PTFConfig property named ActiveSyncProtocolVersion."); Site.Assume.AreNotEqual<string>("16.1", Common.GetConfigurationPropertyValue("ActiveSyncProtocolVersion", this.Site), "The GetAttachment command is not supported when the MS-ASProtocolVersion header is set to 16.1. MS-ASProtocolVersion header value is determined using Common PTFConfig property named ActiveSyncProtocolVersion."); this.VerifyGetAttachmentsCommandParameter(QueryValueType.Base64); } /// <summary> /// This test case is intended to validate the AttachmentName command parameter with Plain Text query value type. /// </summary> [TestCategory("MSASHTTP"), TestMethod()] public void MSASHTTP_S01_TC04_CommandParameter_AttachmentName_PlainText() { Site.Assume.AreNotEqual<string>("14.0", Common.GetConfigurationPropertyValue("ActiveSyncProtocolVersion", this.Site), "The GetAttachment command is not supported when the MS-ASProtocolVersion header is set to 14.0. MS-ASProtocolVersion header value is determined using Common PTFConfig property named ActiveSyncProtocolVersion."); Site.Assume.AreNotEqual<string>("14.1", Common.GetConfigurationPropertyValue("ActiveSyncProtocolVersion", this.Site), "The GetAttachment command is not supported when the MS-ASProtocolVersion header is set to 14.1. MS-ASProtocolVersion header value is determined using Common PTFConfig property named ActiveSyncProtocolVersion."); Site.Assume.AreNotEqual<string>("16.0", Common.GetConfigurationPropertyValue("ActiveSyncProtocolVersion", this.Site), "The GetAttachment command is not supported when the MS-ASProtocolVersion header is set to 16.0. MS-ASProtocolVersion header value is determined using Common PTFConfig property named ActiveSyncProtocolVersion."); Site.Assume.AreNotEqual<string>("16.1", Common.GetConfigurationPropertyValue("ActiveSyncProtocolVersion", this.Site), "The GetAttachment command is not supported when the MS-ASProtocolVersion header is set to 16.1. MS-ASProtocolVersion header value is determined using Common PTFConfig property named ActiveSyncProtocolVersion."); SendStringResponse getAttachmentResponse = this.VerifyGetAttachmentsCommandParameter(QueryValueType.PlainText); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASHTTP_R115"); // Verify MS-ASHTTP requirement: MS-ASHTTP_R115 // The GetAttachment command executes successfully when the AttachmentName command parameter is set, so this requirement can be captured. Site.CaptureRequirement( 115, @"[In Command-Specific URI Parameters] [Parameter] AttachmentName [is used by] GetAttachment."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASHTTP_R487"); // Verify MS-ASHTTP requirement: MS-ASHTTP_R487 // The GetAttachment command executes successfully when the AttachmentName command parameter is set, so this requirement can be captured. Site.CaptureRequirement( 487, @"[In Command-Specific URI Parameters] [Parameter] AttachmentName [is described as] A string that specifies the name of the attachment file to be retrieved. "); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASHTTP_R230"); // Verify MS-ASHTTP requirement: MS-ASHTTP_R230 // The GetAttachment command response has no xml body, so this requirement can be captured. Site.CaptureRequirementIfIsFalse( this.IsXml(getAttachmentResponse.ResponseDataXML), 230, @"[In Response Body] Three commands have no XML body in certain contexts: GetAttachment, [Sync, and Ping]."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASHTTP_R490"); // Verify MS-ASHTTP requirement: MS-ASHTTP_R490 // The GetAttachment command was executed successfully, so this requirement can be captured. Site.CaptureRequirement( 490, @"[In Command Codes] [Command] GetAttachment retrieves an e-mail attachment from the server."); } /// <summary> /// This test case is intended to validate the SaveInSent, CollectionId and ItemId command parameters with Base64 encoding query value type. /// </summary> [TestCategory("MSASHTTP"), TestMethod()] public void MSASHTTP_S01_TC05_CommandParameter_SaveInSent_Base64() { this.VerifySaveInSentCommandParameter(QueryValueType.Base64, "1", "1", "1"); } /// <summary> /// This test case is intended to validate the SaveInSent, CollectionId and ItemId command parameters with Plain Text query value type. /// </summary> [TestCategory("MSASHTTP"), TestMethod()] public void MSASHTTP_S01_TC06_CommandParameter_SaveInSent_PlainText() { this.VerifySaveInSentCommandParameter(QueryValueType.PlainText, "T", "F", null); } /// <summary> /// This test case is intended to validate the LongId command parameter with Base64 encoding query value type. /// </summary> [TestCategory("MSASHTTP"), TestMethod()] public void MSASHTTP_S01_TC07_CommandParameter_LongId_Base64() { this.VerifyLongIdCommandParameter(QueryValueType.Base64); } /// <summary> /// This test case is intended to validate the LongId command parameter with Plain Text query value type. /// </summary> [TestCategory("MSASHTTP"), TestMethod()] public void MSASHTTP_S01_TC08_CommandParameter_LongId_PlainText() { this.VerifyLongIdCommandParameter(QueryValueType.PlainText); } /// <summary> /// This test case is intended to validate the Occurrence command parameter with Base64 encoding query value type. /// </summary> [TestCategory("MSASHTTP"), TestMethod()] public void MSASHTTP_S01_TC09_CommandParameter_Occurrence_Base64() { #region User3 calls SendMail to send a meeting request to User2. IDictionary<HTTPPOSTRequestPrefixField, string> requestPrefix = new Dictionary<HTTPPOSTRequestPrefixField, string>(); string sendMailSubject = Common.GenerateResourceName(this.Site, "SendMail"); string smartForwardSubject = Common.GenerateResourceName(this.Site, "SmartForward"); // Call ConfigureRequestPrefixFields to change the QueryValueType to Base64. requestPrefix.Add(HTTPPOSTRequestPrefixField.QueryValueType, QueryValueType.Base64.ToString()); this.HTTPAdapter.ConfigureRequestPrefixFields(requestPrefix); // Switch the current user to user3 and synchronize the collection hierarchy. this.SwitchUser(this.UserThreeInformation, true); // Call SendMail command to send the meeting request to User2. this.SendMeetingRequest(sendMailSubject); #endregion #region User2 calls MeetingResponse command to accept the received meeting request and forward it to User1. // Call ConfigureRequestPrefixFields to switch the credential to User2 and synchronize the collection hierarchy. this.SwitchUser(this.UserTwoInformation, true); // Call Sync command to get the ServerId of the received meeting request. string itemServerId = this.LoopToSyncItem(this.UserTwoInformation.InboxCollectionId, sendMailSubject, true); // Add the received item to the item collection of User2. CreatedItems inboxItemForUserTwo = new CreatedItems { CollectionId = this.UserTwoInformation.InboxCollectionId }; inboxItemForUserTwo.ItemSubject.Add(sendMailSubject); this.UserTwoInformation.UserCreatedItems.Add(inboxItemForUserTwo); // Check the calendar item if is exist. string calendarItemServerId = this.LoopToSyncItem(this.UserTwoInformation.CalendarCollectionId, sendMailSubject, true); CreatedItems calendarItemForUserTwo = new CreatedItems { CollectionId = this.UserTwoInformation.CalendarCollectionId }; calendarItemForUserTwo.ItemSubject.Add(sendMailSubject); this.UserTwoInformation.UserCreatedItems.Add(calendarItemForUserTwo); // Call MeetingResponse command to accept the received meeting request. this.CallMeetingResponseCommand(this.UserTwoInformation.InboxCollectionId, itemServerId); // The accepted meeting request will be moved to Delete Items folder. itemServerId = this.LoopToSyncItem(this.UserTwoInformation.DeletedItemsCollectionId, sendMailSubject, true); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASHTTP_R432"); // Verify MS-ASHTTP requirement: MS-ASHTTP_R432 // MeetingResponse command is executed successfully, so this requirement can be captured. Site.CaptureRequirementIfIsNotNull( itemServerId, 432, @"[In Command Codes] [Command] MeetingResponse [is] used to accept [, tentatively accept , or decline] a meeting request in the user's Inbox folder."); // Remove the inboxItemForUserTwo object from the clean up list since it has been moved to Delete Items folder. this.UserTwoInformation.UserCreatedItems.Remove(inboxItemForUserTwo); this.AddCreatedItemToCollection("User2", this.UserTwoInformation.DeletedItemsCollectionId, sendMailSubject); // Call SmartForward command to forward the meeting to User1 string startTime = (string)this.GetElementValueFromSyncResponse(this.UserTwoInformation.CalendarCollectionId, calendarItemServerId, Response.ItemsChoiceType8.StartTime); string occurrence = TestSuiteHelper.ConvertInstanceIdFormat(startTime); string userOneMailboxAddress = Common.GetMailAddress(this.UserOneInformation.UserName, this.UserOneInformation.UserDomain); string userTwoMailboxAddress = Common.GetMailAddress(this.UserTwoInformation.UserName, this.UserTwoInformation.UserDomain); this.CallSmartForwardCommand(userTwoMailboxAddress, userOneMailboxAddress, itemServerId, smartForwardSubject, null, null, occurrence); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASHTTP_R513"); // Verify MS-ASHTTP requirement: MS-ASHTTP_R513 // SmartForward command executed successfully with setting Occurrence command parameter, so this requirement can be captured. Site.CaptureRequirement( 513, @"[In Command-Specific URI Parameters] [Parameter] Occurrence [is described as] A string that specifies the ID of a particular occurrence in a recurring meeting."); this.AddCreatedItemToCollection("User3", this.UserThreeInformation.DeletedItemsCollectionId, "Meeting Forward Notification: " + smartForwardSubject); #endregion #region User1 gets the forwarded meeting request // Call ConfigureRequestPrefixFields to switch the credential to User1 and synchronize the collection hierarchy. this.SwitchUser(this.UserOneInformation, true); this.AddCreatedItemToCollection("User1", this.UserOneInformation.InboxCollectionId, smartForwardSubject); this.AddCreatedItemToCollection("User1", this.UserOneInformation.CalendarCollectionId, smartForwardSubject); // Call Sync command to get the ServerId of the received meeting request. this.LoopToSyncItem(this.UserOneInformation.InboxCollectionId, smartForwardSubject, true); // Call Sync command to get the ServerId of the calendar item. this.LoopToSyncItem(this.UserOneInformation.CalendarCollectionId, smartForwardSubject, true); #endregion #region User3 gets the Meeting Forward Notification email in the Deleted Items folder. // Call ConfigureRequestPrefixFields to switch the credential to User3 and synchronize the collection hierarchy. this.SwitchUser(this.UserThreeInformation, false); // Call Sync command to get the ServerId of the received meeting request and the notification email. this.LoopToSyncItem(this.UserThreeInformation.DeletedItemsCollectionId, "Meeting Forward Notification: " + smartForwardSubject, true); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASHTTP_R119"); // Verify MS-ASHTTP requirement: MS-ASHTTP_R119 // SmartForward command executed successfully with setting Occurrence command parameter, so this requirement can be captured. Site.CaptureRequirement( 119, @"[In Command-Specific URI Parameters] [Parameter] Occurrence [is used by] SmartForward."); #endregion #region Reset the query value type. requestPrefix[HTTPPOSTRequestPrefixField.QueryValueType] = Common.GetConfigurationPropertyValue("HeaderEncodingType", this.Site); HTTPAdapter.ConfigureRequestPrefixFields(requestPrefix); #endregion } /// <summary> /// This test case is intended to validate the Occurrence command parameter with Plain Text query value type. /// </summary> [TestCategory("MSASHTTP"), TestMethod()] public void MSASHTTP_S01_TC10_CommandParameter_Occurrence_PlainText() { #region User3 calls SendMail to send a meeting request to User2 IDictionary<HTTPPOSTRequestPrefixField, string> requestPrefix = new Dictionary<HTTPPOSTRequestPrefixField, string>(); string sendMailSubject = Common.GenerateResourceName(this.Site, "SendMail"); string smartReplySubject = Common.GenerateResourceName(this.Site, "SmartReply"); // Call ConfigureRequestPrefixFields to change the QueryValueType. requestPrefix.Add(HTTPPOSTRequestPrefixField.QueryValueType, QueryValueType.PlainText.ToString()); this.HTTPAdapter.ConfigureRequestPrefixFields(requestPrefix); // Switch the current user to user3 and synchronize the collection hierarchy. this.SwitchUser(this.UserThreeInformation, true); // Call SendMail command to send the meeting request to User2. this.SendMeetingRequest(sendMailSubject); #endregion #region User2 calls SmartReply command to reply the request to User3 with Occurrence command parameter // Call ConfigureRequestPrefixFields to switch the credential to User2 and synchronize the collection hierarchy. this.SwitchUser(this.UserTwoInformation, true); // Call Sync command to get the ServerId of the received meeting request. string itemServerId = this.LoopToSyncItem(this.UserTwoInformation.InboxCollectionId, sendMailSubject, true); // Add the received item to the item collection of User2. CreatedItems inboxItemForUserTwo = new CreatedItems { CollectionId = this.UserTwoInformation.InboxCollectionId }; inboxItemForUserTwo.ItemSubject.Add(sendMailSubject); this.UserTwoInformation.UserCreatedItems.Add(inboxItemForUserTwo); // Call Sync command to get the ServerId of the calendar item. string calendarItemServerId = this.LoopToSyncItem(this.UserTwoInformation.CalendarCollectionId, sendMailSubject, true); CreatedItems calendarItemForUserTwo = new CreatedItems { CollectionId = this.UserTwoInformation.CalendarCollectionId }; calendarItemForUserTwo.ItemSubject.Add(sendMailSubject); this.UserTwoInformation.UserCreatedItems.Add(calendarItemForUserTwo); // Call SmartReply command with the Occurrence command parameter. string startTime = (string)this.GetElementValueFromSyncResponse(this.UserTwoInformation.CalendarCollectionId, calendarItemServerId, Response.ItemsChoiceType8.StartTime); string occurrence = TestSuiteHelper.ConvertInstanceIdFormat(startTime); string userTwoMailboxAddress = Common.GetMailAddress(this.UserTwoInformation.UserName, this.UserTwoInformation.UserDomain); string userThreeMailboxAddress = Common.GetMailAddress(this.UserThreeInformation.UserName, this.UserThreeInformation.UserDomain); this.CallSmartReplyCommand(userTwoMailboxAddress, userThreeMailboxAddress, itemServerId, smartReplySubject, null, null, occurrence); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASHTTP_R513"); // Verify MS-ASHTTP requirement: MS-ASHTTP_R513 // SmartReply command executed successfully with setting Occurrence command parameter, so this requirement can be captured. Site.CaptureRequirement( 513, @"[In Command-Specific URI Parameters] [Parameter] Occurrence [is described as] A string that specifies the ID of a particular occurrence in a recurring meeting."); #endregion #region User3 gets the reply mail // Call ConfigureRequestPrefixFields to switch the credential to User3 and synchronize the collection hierarchy. this.SwitchUser(this.UserThreeInformation, false); // Call Sync command to get the ServerId of the received the reply. this.LoopToSyncItem(this.UserThreeInformation.InboxCollectionId, smartReplySubject, true); this.AddCreatedItemToCollection("User3", this.UserThreeInformation.InboxCollectionId, smartReplySubject); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASHTTP_R529"); // Verify MS-ASHTTP requirement: MS-ASHTTP_R529 // SmartReply command executed successfully with setting Occurrence command parameter, so this requirement can be captured. Site.CaptureRequirement( 529, @"[In Command-Specific URI Parameters] [Parameter] Occurrence [is used by] SmartReply."); #endregion #region Reset the query value type and user credential. requestPrefix[HTTPPOSTRequestPrefixField.QueryValueType] = Common.GetConfigurationPropertyValue("HeaderEncodingType", this.Site); HTTPAdapter.ConfigureRequestPrefixFields(requestPrefix); this.SwitchUser(this.UserOneInformation, false); #endregion } /// <summary> /// This test case is intended to validate the FolderSync, FolderCreate, FolderUpdate and FolderDelete command codes. /// </summary> [TestCategory("MSASHTTP"), TestMethod()] public void MSASHTTP_S01_TC11_CommandCode_FolderRelatedCommands() { string folderNameToCreate = Common.GenerateResourceName(this.Site, "CreatedFolder"); string folderNameToUpdate = Common.GenerateResourceName(this.Site, "UpdatedFolder"); #region Call FolderSync command to synchronize the folder hierarchy. FolderSyncResponse folderSyncResponse = this.CallFolderSyncCommand(); #endregion #region Call FolderCreate command to create a sub folder under Inbox folder. FolderCreateResponse folderCreateResponse = this.CallFolderCreateCommand(folderSyncResponse.ResponseData.SyncKey, folderNameToCreate, Common.GetDefaultFolderServerId(folderSyncResponse, FolderType.Inbox, Site)); #endregion #region Call FolderSync command to synchronize the folder hierarchy. folderSyncResponse = this.CallFolderSyncCommand(); // Get the created folder name using the ServerId returned in FolderSync response. string createdFolderName = this.GetFolderFromFolderSyncResponse(folderSyncResponse, folderCreateResponse.ResponseData.ServerId, "DisplayName"); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASHTTP_R493"); // Verify MS-ASHTTP requirement: MS-ASHTTP_R493 // The created folder could be got in FolderSync response, so this requirement can be captured. Site.CaptureRequirementIfAreEqual<string>( folderNameToCreate, createdFolderName, 493, @"[In Command Codes] [Command] FolderCreate creates an e-mail, [calendar, or contacts folder] on the server."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASHTTP_R491"); // Verify MS-ASHTTP requirement: MS-ASHTTP_R491 // R493 is captured, so this requirement can be captured directly. Site.CaptureRequirement( 491, @"[In Command Codes] [Command] FolderSync synchronizes the folder hierarchy."); // Call the Sync command with latest SyncKey without change in folder. SyncStore syncResponse = this.CallSyncCommand(folderCreateResponse.ResponseData.ServerId); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASHTTP_R482"); // Verify MS-ASHTTP requirement: MS-ASHTTP_R482 // If response is not in xml, this requirement can be captured. Site.CaptureRequirementIfIsNull( syncResponse.SyncKey, 482, @"[In Response Body] Three commands have no XML body in certain contexts: [GetAttachment,] Sync [, and Ping]."); #endregion #region Call FolderUpdate command to update the name of the created folder to a new folder name and move the created folder to SentItems folder. this.CallFolderUpdateCommand(folderSyncResponse.ResponseData.SyncKey, folderCreateResponse.ResponseData.ServerId, folderNameToUpdate, Common.GetDefaultFolderServerId(folderSyncResponse, FolderType.SentItems, this.Site)); #endregion #region Call FolderSync command to synchronize the folder hierarchy. folderSyncResponse = this.CallFolderSyncCommand(); // Get the updated folder name using the ServerId returned in FolderSync response. string updatedFolderName = this.GetFolderFromFolderSyncResponse(folderSyncResponse, folderCreateResponse.ResponseData.ServerId, "DisplayName"); string updatedParentId = this.GetFolderFromFolderSyncResponse(folderSyncResponse, folderCreateResponse.ResponseData.ServerId, "ParentId"); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASHTTP_R431"); // Verify MS-ASHTTP requirement: MS-ASHTTP_R431 // The folder name is updated to the specified name, so this requirement can be captured. Site.CaptureRequirementIfAreEqual<string>( folderNameToUpdate, updatedFolderName, 431, @"[In Command Codes] [Command] FolderUpdate is used to rename folders."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASHTTP_R68"); // Verify MS-ASHTTP requirement: MS-ASHTTP_R68 // The folder has been moved to the new created folder, so this requirement can be captured. Site.CaptureRequirementIfAreEqual<string>( Common.GetDefaultFolderServerId(folderSyncResponse, FolderType.SentItems, this.Site), updatedParentId, 68, @"[In Command Codes] [Command] FolderUpdate moves a folder from one location to another on the server."); #endregion #region Call FolderDelete to delete the folder from the server. this.CallFolderDeleteCommand(folderSyncResponse.ResponseData.SyncKey, folderCreateResponse.ResponseData.ServerId); #endregion #region Call FolderSync command to synchronize the folder hierarchy. folderSyncResponse = this.CallFolderSyncCommand(); // Get the created folder name using the ServerId returned in FolderSync response. updatedFolderName = this.GetFolderFromFolderSyncResponse(folderSyncResponse, folderCreateResponse.ResponseData.ServerId, "DisplayName"); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASHTTP_R496"); // Verify MS-ASHTTP requirement: MS-ASHTTP_R496 // The folder with the specified ServerId could not be got, so this requirement can be captured. Site.CaptureRequirementIfIsNull( updatedFolderName, 496, @"[In Command Codes] [Command] FolderDelete deletes a folder from the server."); #endregion } /// <summary> /// This test case is intended to validate the Ping, MoveItems, GetItemEstimate and ItemOperations command codes. /// </summary> [TestCategory("MSASHTTP"), TestMethod()] public void MSASHTTP_S01_TC12_CommandCode_ItemRelatedCommands() { #region Call ConfigureRequestPrefixFields to change the query value type to Base64. IDictionary<HTTPPOSTRequestPrefixField, string> requestPrefix = new Dictionary<HTTPPOSTRequestPrefixField, string>(); requestPrefix.Add(HTTPPOSTRequestPrefixField.QueryValueType, QueryValueType.Base64.ToString()); this.HTTPAdapter.ConfigureRequestPrefixFields(requestPrefix); #endregion #region Call SendMail command to send email to User2. string sendMailSubject = Common.GenerateResourceName(Site, "SendMail"); string folderNameToCreate = Common.GenerateResourceName(Site, "CreatedFolder"); string userOneMailboxAddress = Common.GetMailAddress(this.UserOneInformation.UserName, this.UserOneInformation.UserDomain); string userTwoMailboxAddress = Common.GetMailAddress(this.UserTwoInformation.UserName, this.UserTwoInformation.UserDomain); // Call SendMail command to send email to User2. this.CallSendMailCommand(userOneMailboxAddress, userTwoMailboxAddress, sendMailSubject, null); #endregion #region Call Ping command for changes that would require the client to resynchronize. // Switch the user to User2 and synchronize the collection hierarchy. this.SwitchUser(this.UserTwoInformation, true); // Call FolderSync command to synchronize the collection hierarchy. FolderSyncResponse folderSyncResponse = this.CallFolderSyncCommand(); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASHTTP_R428"); // Verify MS-ASHTTP requirement: MS-ASHTTP_R428 // The received email could not be got by FolderSync command, so this requirement can be captured. Site.CaptureRequirementIfIsFalse( folderSyncResponse.ResponseDataXML.Contains(sendMailSubject), 428, @"[In Command Codes] But [command] FolderSync does not synchronize the items in the folders."); // Call Ping command for changes of Inbox folder. PingResponse pingResponse = this.CallPingCommand(this.UserTwoInformation.InboxCollectionId); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASHTTP_R504"); // Verify MS-ASHTTP requirement: MS-ASHTTP_R504 // The Status of the Ping command is 2 which means this folder needs to be synced, so this requirement can be captured. Site.CaptureRequirementIfAreEqual<string>( "2", pingResponse.ResponseData.Status.ToString(), 504, @"[In Command Codes] [Command] Ping requests that the server monitor specified folders for changes that would require the client to resynchronize."); #endregion #region Get the ServerId of the received email. // Call Sync command to get the ServerId of the received email. string receivedItemServerId = this.LoopToSyncItem(this.UserTwoInformation.InboxCollectionId, sendMailSubject, true); #endregion #region Call FolderCreate command to create a sub folder under Inbox folder. FolderCreateResponse folderCreateResponse = this.CallFolderCreateCommand(folderSyncResponse.ResponseData.SyncKey, folderNameToCreate, this.UserTwoInformation.InboxCollectionId); // Get the ServerId of the created folder. string createdFolder = folderCreateResponse.ResponseData.ServerId; #endregion #region Move the received email from Inbox folder to the created folder. this.CallMoveItemsCommand(receivedItemServerId, this.UserTwoInformation.InboxCollectionId, createdFolder); #endregion #region Get the moved email in the created folder. // Call Sync command to get the received email. receivedItemServerId = this.LoopToSyncItem(createdFolder, sendMailSubject, true); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASHTTP_R499"); // Verify MS-ASHTTP requirement: MS-ASHTTP_R499 // The moved email could be got in the new created folder, so this requirement can be captured. Site.CaptureRequirementIfIsNotNull( receivedItemServerId, 499, @"[In Command Codes] [Command] MoveItems moves items from one folder to another."); #endregion #region Call ItemOperation command to fetch the email in Sent Items folder with AcceptMultiPart command parameter. SendStringResponse itemOperationResponse = this.CallItemOperationsCommand(createdFolder, receivedItemServerId, true); Site.Assert.IsNotNull(itemOperationResponse.Headers["Content-Type"], "The Content-Type header should not be null."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASHTTP_R94"); // Verify MS-ASHTTP requirement: MS-ASHTTP_R94 // The content is in multipart, so this requirement can be captured. Site.CaptureRequirementIfAreEqual<string>( "application/vnd.ms-sync.multipart", itemOperationResponse.Headers["Content-Type"], 94, @"[In Command Parameters] [When flag] AcceptMultiPart [value is] 0x02, [the meaning is] setting this flag [AcceptMultiPart] to instruct the server to return the requested item in multipart format."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASHTTP_R95"); // Verify MS-ASHTTP requirement: MS-ASHTTP_R95 // R94 can be captured, so this requirement can be captured directly. Site.CaptureRequirement( 95, @"[In Command Parameters] [When flag] AcceptMultiPart [value is] 0x02, [it is] valid for ItemOperations."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASHTTP_R534"); // Verify MS-ASHTTP requirement: MS-ASHTTP_R534 // R94 can be captured, so this requirement can be captured directly. Site.CaptureRequirement( 534, @"[In Command Parameters] [Parameter] Options [ is used by] ItemOperations."); #endregion #region Call FolderDelete to delete a folder from the server. this.CallFolderDeleteCommand(folderCreateResponse.ResponseData.SyncKey, createdFolder); #endregion #region Reset the query value type and user credential. requestPrefix[HTTPPOSTRequestPrefixField.QueryValueType] = Common.GetConfigurationPropertyValue("HeaderEncodingType", this.Site); this.HTTPAdapter.ConfigureRequestPrefixFields(requestPrefix); this.SwitchUser(this.UserOneInformation, false); #endregion } /// <summary> /// This test case is intended to validate the ResolveRecipients and Settings command codes. /// </summary> [TestCategory("MSASHTTP"), TestMethod()] public void MSASHTTP_S01_TC13_CommandCode_UserRelatedCommands() { #region Call ResolveRecipients command. object[] items = new object[] { Common.GetConfigurationPropertyValue("User1Name", Site) }; ResolveRecipientsRequest resolveRecipientsRequest = Common.CreateResolveRecipientsRequest(items); SendStringResponse resolveRecipientsResponse = HTTPAdapter.HTTPPOST(CommandName.ResolveRecipients, null, resolveRecipientsRequest.GetRequestDataSerializedXML()); // Check the command is executed successfully. this.CheckResponseStatus(resolveRecipientsResponse.ResponseDataXML); #endregion #region Call Settings command. SettingsRequest settingsRequest = Common.CreateSettingsRequest(); SendStringResponse settingsResponse = HTTPAdapter.HTTPPOST(CommandName.Settings, null, settingsRequest.GetRequestDataSerializedXML()); // Check the command is executed successfully. this.CheckResponseStatus(settingsResponse.ResponseDataXML); #endregion } /// <summary> /// This test case is intended to validate the ValidateCert command code. /// </summary> [TestCategory("MSASHTTP"), TestMethod()] public void MSASHTTP_S01_TC14_CommandCode_ValidateCert() { #region Call ValidateCert command. ValidateCertRequest validateCertRequest = Common.CreateValidateCertRequest(); SendStringResponse validateCertResponse = HTTPAdapter.HTTPPOST(CommandName.ValidateCert, null, validateCertRequest.GetRequestDataSerializedXML()); // Check the command is executed successfully. this.CheckResponseStatus(validateCertResponse.ResponseDataXML); #endregion } #endregion #region Private methods /// <summary> /// Loop to call FolderSync command and get the response till FolderSync Response's Content-Encoding header is gzip. /// </summary> /// <returns>The response of FolderSync command.</returns> private FolderSyncResponse LoopCallFolderSyncCommand() { #region Loop to call FolderSync int counter = 0; int waitTime = int.Parse(Common.GetConfigurationPropertyValue("WaitTime", Site)); int upperBound = int.Parse(Common.GetConfigurationPropertyValue("RetryCount", Site)); FolderSyncResponse folderSyncResponse = this.CallFolderSyncCommand(); while (counter < upperBound && !folderSyncResponse.Headers.ToString().Contains("Content-Encoding")) { System.Threading.Thread.Sleep(waitTime); folderSyncResponse = this.CallFolderSyncCommand(); counter++; } #endregion #region Call ConfigureRequestPrefixFields to reset the AcceptEncoding header. IDictionary<HTTPPOSTRequestPrefixField, string> requestPrefix = new Dictionary<HTTPPOSTRequestPrefixField, string>(); requestPrefix[HTTPPOSTRequestPrefixField.AcceptEncoding] = null; this.HTTPAdapter.ConfigureRequestPrefixFields(requestPrefix); #endregion #region Return FolderSync response Site.Assert.IsNotNull(folderSyncResponse.Headers["Content-Encoding"], "The Content-Encoding header should exist in the response headers after retry {0} times", counter); return folderSyncResponse; #endregion } #endregion } }
using System; using System.Collections.Generic; using System.IO; using System.Text; namespace Aardvark.Base { #region IXml Interfaces public interface IXml { void WriteTo(StreamWriter writer, int indent = 0); } public interface IXmlText { Text GetText(); } public interface IXmlItemProperty { XmlItem XmlItem { get; set; } } public interface IXmlDocProperty { XmlDoc XmlDoc { get; set; } } #endregion #region XmlAtt public struct XmlAtt : IXml { public Symbol Key; public Text Value; public XmlAtt(Symbol key, string value) { Key = key; Value = value.ToText(); } public XmlAtt(Text key, Text value) { Key = Symbol.Create(key.ToString()); Value = value; } public void WriteTo(StreamWriter writer, int indent = 0) { writer.Write(Key.ToString()); writer.Write("=\""); writer.Write(Value.ToString()); writer.Write('"'); } } #endregion #region XmlItem public class XmlItem : IXml { public Symbol Name; public List<XmlAtt> AttList; public List<IXml> SubList; #region Constructors public XmlItem() : this(default(Symbol)) { } public XmlItem(Symbol name, params XmlAtt[] atts) { Name = name; AttList = new List<XmlAtt>(atts); SubList = new List<IXml>(); } public XmlItem(Symbol name, string str) : this(name, str.ToText()) { } public XmlItem(Symbol name, Text text) : this(name) { SubList.Add(new XmlDirectText(text)); } public XmlItem(Symbol name, object obj) : this(name, obj.ToString()) { } public XmlItem(Symbol name, IXml xmlItem, params IXml[] xmlItems) : this(name) { Add(xmlItem); foreach (var item in xmlItems) Add(item); } #endregion #region Properties public void Add(XmlAtt att) { AttList.Add(att); } public int Count { get { return SubList.Count; } } public IXml this[int index] { get { return SubList[index]; } set { SubList[index] = value; } } #endregion #region Query Methods public int SubCount<T>() where T : class { int count = 0; foreach (var xml in SubList) if (xml is T) ++count; return count; } public Text Attribute(Symbol symbol) { foreach (var att in AttList) if (att.Key == symbol) return att.Value; return default(Text); } public T FirstSub<T>() where T : class { T item; if (NextSubIndex(out item) < 0) return null; return item; } public T FirstSub<T>(out int index) where T : class { T item; if ((index = NextSubIndex(out item)) < 0) return null; return item; } public T NextSub<T>(ref int index) where T : class { T item; if ((index = NextSubIndex(out item, index)) < 0) return null; return item; } public XmlItem FirstSubItemWithName(string name) { return FirstSubItemWithName(Symbol.Create(name)); } public XmlItem FirstSubItemWithName(Symbol name) { return FirstSub<XmlItem>(i => i.Name == name); } public T FirstSub<T>(Func<T, bool> predicate) where T : class { T item; int index; if ((index = NextSubIndex(out item)) < 0) return null; while (!predicate(item)) { if ((index = NextSubIndex(out item, index)) < 0) return null; } return item; } public XmlItem FirstSubItemWithName(string name, out int index) { return FirstSubItemWithName(Symbol.Create(name), out index); } public XmlItem FirstSubItemWithName(Symbol name, out int index) { return FirstSub<XmlItem>(i => i.Name == name, out index); } public T FirstSub<T>(Func<T, bool> predicate, out int index) where T : class { T item; if ((index = NextSubIndex(out item)) < 0) return null; while (!predicate(item)) { if ((index = NextSubIndex(out item, index)) < 0) return null; } return item; } public XmlItem NextSubItemWithName(string name, ref int index) { return NextSubItemWithName(Symbol.Create(name), ref index); } public XmlItem NextSubItemWithName(Symbol name, ref int index) { return NextSub<XmlItem>(i => i.Name == name, ref index); } public IEnumerable<XmlItem> SubItemsWithName(Symbol name) { XmlItem item; int index = -1; while ((item = NextSub<XmlItem>(i => i.Name == name, ref index)) != null) yield return item; } public T NextSub<T>(Func<T, bool> predicate, ref int index) where T : class { T item; do { if ((index = NextSubIndex(out item, index)) < 0) return null; } while (!predicate(item)); return item; } public XmlItem RequiredSubItemWithName(string name) { return RequiredSubItemWithName(Symbol.Create(name)); } public string RequiredSubItemStringOnlyWithName(Symbol name) { return RequiredSubItemWithName(name).RequiredOnlySubString; } public XmlItem RequiredSubItemWithName(Symbol name) { return RequiredSub<XmlItem>(i => i.Name == name); } public T RequiredSub<T>(Func<T, bool> predicate) where T : class { int index = -1; T item; do { if ((index = NextSubIndex(out item, index)) < 0) throw new ArgumentException(); } while (!predicate(item)); return item; } public XmlItem SubItemWithName(string name) { return SubItemWithName(Symbol.Create(name)); } public XmlItem SubItemWithName(Symbol name) { return Sub<XmlItem>(i => i.Name == name); } public T Sub<T>(Func<T, bool> predicate) where T : class { int index = -1; T item; do { if ((index = NextSubIndex(out item, index)) < 0) return null; } while (!predicate(item)); return item; } public XmlItem RequiredSubItemWithName(string name, out int index) { return RequiredSubItemWithName(Symbol.Create(name), out index); } public XmlItem RequiredSubItemWithName(Symbol name, out int index) { return RequiredSub<XmlItem>(i => i.Name == name, out index); } public T RequiredSub<T>(Func<T, bool> predicate, out int index) where T : class { index = -1; T item; do { if ((index = NextSubIndex(out item, index)) < 0) throw new ArgumentException(); } while (!predicate(item)); return item; } public XmlItem SubItemWithName(string name, out int index) { return SubItemWithName(Symbol.Create(name), out index); } public XmlItem SubItemWithName(Symbol name, out int index) { return Sub<XmlItem>(i => i.Name == name, out index); } public T Sub<T>(Func<T, bool> predicate, out int index) where T : class { index = -1; T item; do { if ((index = NextSubIndex(out item, index)) < 0) return null; } while (!predicate(item)); return item; } #endregion #region Required Sub public string RequiredOnlySubString { get { return RequiredOnlySubText.ToString(); } } public Text RequiredOnlySubText { get { var text = RequiredOnlySub<IXmlText>(); return text.GetText(); } } public T RequiredOnlySub<T>() where T : class { if (SubList.Count != 1) throw new ArgumentException(); var sub = SubList[0] as T; if (sub == null) throw new ArgumentException(); return sub; } #endregion #region SubNodes by Index public int NextSubIndex<T>(int i = -1) where T : class { ++i; for (int c = SubList.Count; i < c; i++) if (SubList[i] is T) return i; return -1; } public int NextSubIndex<T>(out T item, int i = -1) where T : class { ++i; for (int c = SubList.Count; i < c; i++) { var node = SubList[i] as T; if (node != null) { item = node; return i; } } item = default(T); return -1; } #endregion #region Manipulation Methods public void Add(Text text) { SubList.Add(new XmlDirectText(text)); } public void Add(IXml node) { if (node != null) SubList.Add(node); } public IXml Remove() { var last = SubList.Count - 1; var xml = SubList[last]; SubList.RemoveAt(last); return xml; } #endregion #region IXml Members public void WriteTo(StreamWriter writer, int indent = 0) { var name = Name.ToString(); var subItemCount = SubCount<XmlItem>(); if (indent > 0) for (int i = 0; i < indent; i++) writer.Write(" "); writer.Write('<'); writer.Write(name); if (AttList.Count > 0) foreach (var att in AttList) { writer.Write(' '); att.WriteTo(writer); } if (SubList.Count == 0) { if (AttList.Count > 0) writer.WriteLine(" />"); else writer.WriteLine("/>"); } else { writer.Write('>'); if (subItemCount == 0) { foreach (var xml in SubList) xml.WriteTo(writer); } else { writer.WriteLine(); foreach (var xml in SubList) xml.WriteTo(writer, indent + 1); if (indent > 0) for (int i = 0; i < indent; i++) writer.Write(" "); } writer.Write("</"); writer.Write(name); writer.WriteLine('>'); } } #endregion } #endregion #region XmlDirectText public class XmlDirectText : IXml, IXmlText { public Text Text; #region Constructors public XmlDirectText(Text text) { Text = text; } public XmlDirectText(string str) : this(str.ToText()) { } #endregion #region IXml Members public void WriteTo(StreamWriter writer, int indent = 0) { if (indent == 0) writer.Write(Text.ToString()); else if (Text.SkipWhiteSpace() < Text.Count) { for (int i = 0; i < indent; i++) writer.Write(" "); writer.Write(Text.ToString()); writer.WriteLine(); } } #endregion #region IXmlText Members public Text GetText() { return Text; } #endregion } #endregion #region XmlLazyText public class XmlLazyText : IXml, IXmlText { public Action<StreamWriter> WriteAct; public XmlLazyText(Action<StreamWriter> writeAct) { WriteAct = writeAct; } #region IXml Members public void WriteTo(StreamWriter writer, int indent = 0) { if (indent > 0) for (int i = 0; i < indent; i++) writer.Write(" "); WriteAct(writer); if (indent > 0) writer.WriteLine(); } #endregion #region IXmlText Members public Text GetText() { var stream = new MemoryStream(); WriteAct(new StreamWriter(stream)); return new StreamReader(stream).ReadToEnd().ToText(); } #endregion } #endregion #region XmlDoc public class XmlDoc : XmlItem, IXml { #region Constructor public XmlDoc(string version = null, string encoding = null) : base(XmlSymbol) { if (version != null) Add(new XmlAtt("version", version)); if (encoding != null) Add(new XmlAtt("encoding", encoding)); } public XmlDoc(XmlItem item, string version = null, string encoding = null) : this(version, encoding) { Add(item); } #endregion #region Constants public static readonly Symbol XmlSymbol = Symbol.Create("xml"); #endregion #region IO public void SaveTo(string filePath) { using (var streamWriter = new StreamWriter(filePath)) WriteTo(streamWriter, 0); } public static XmlDoc LoadFrom(string filePath) { return LoadFrom(filePath, Encoding.Default); } public static XmlDoc LoadFrom(string filePath, Encoding encoding) { var fileString = File.ReadAllText(filePath, encoding); var parser = new XmlParser(); var doc = new XmlDoc(); try { parser.Parse(fileString, doc); } catch (ParserException<XmlParser> e) { Console.WriteLine("(line {0}, col {1}): {2}", e.Parser.UserLine, e.Parser.UserColumn, e.Message); } return doc; } #endregion #region IXml Members public new void WriteTo(StreamWriter writer, int indent = 0) { if (AttList.Count > 0) { writer.Write("<?xml"); foreach (var att in AttList) { writer.Write(' '); att.WriteTo(writer); } writer.WriteLine("?>"); } foreach (var xml in SubList) { var text = xml as XmlDirectText; if (text != null && text.Text.IsWhiteSpace) continue; xml.WriteTo(writer, indent); } } #endregion } #endregion #region XmlParser public class XmlParser : TextParser<XmlParser> { public bool SeenName; public bool SeenSlash; public bool PreserveWhiteSpace; public bool SimpleNames; public char Separator; public void Parse(string text, XmlItem node) { SeenName = false; SeenSlash = false; PreserveWhiteSpace = true; SimpleNames = true; Separator = ':'; Parse(new Text(text), this, TextState, node); } /// <summary> /// A parser state is initialized with an array of cases which /// represent the state transitions. A state transition is chosen if /// its specified regular expression is the first one (closest to the /// current position) that matches. The specified function is /// performed when the transition is chosen, and the function needs /// to return the next state. If the 'null' state is returned, or the /// whole input is consumed, the parsing function that performs all /// transitions terminates. Since recursive descent also calls this /// parsing function, returning the 'null' state also signals return /// from recursive descent. /// </summary> public static readonly State<XmlParser, XmlItem> TextState = new State<XmlParser, XmlItem>(new[] { new Case<XmlParser, XmlItem>(@"<\?xml", (p, n) => { if (!(n is XmlDoc)) { p.Skip(1); throw new ParserException<XmlParser>(p, "illegal character"); } p.Skip(); p.SeenName = true; p.SeenSlash = false; return TagState; }), new Case<XmlParser, XmlItem>(@"<!DOCTYPE", (p, n) => { n.Add(p.GetToEndOf('>')); return TextState; }), new Case<XmlParser, XmlItem>(@"<!--", (p, n) => { p.SkipToEndOf("-->"); return TextState; }), new Case<XmlParser, XmlItem>(@"<", (p, n) => { p.Skip(); p.SeenName = p.SeenSlash = false; return TagState; }), new Case<XmlParser, XmlItem>(@"&", (p, n) => { n.Add(p.GetToEndOf(';')); return TextState; }), }, // If the following action is specified, all cases are search // operations that skip text which is supplied to the action. // In the Xml case, this is used to add the text between xml // tags to the node. (p, n, t) => { if (p.PreserveWhiteSpace || !t.IsWhiteSpace) n.Add(t); } ); public static readonly Rx SymbolRx = new Rx(@"[A-Za-z_][0-9A-Za-z_]*"); public static readonly State<XmlParser, XmlItem> TagState = new State<XmlParser, XmlItem>(new[] { new Case<XmlParser, XmlItem>(SymbolRx, (p, n) => { var namePos = p.Pos; Text nameText; if (p.SimpleNames) nameText = p.Get(); else { p.Skip(); while (p.TrySkip(p.Separator)) p.Skip(SymbolRx); nameText = p.GetFrom(namePos); } if (p.EndOfText) throw new ParserException<XmlParser>(p, "end of file after tag name"); var name = Symbol.Create(nameText.ToString()); if (p.SeenName) // its an attribute { if (namePos != p.LastWhiteSpace) { p.Pos = namePos; // adjust for error msg throw new ParserException<XmlParser>(p, "missing required whitespace"); } p.SkipWhiteSpace(); if (!p.TryGet('=')) throw new ParserException<XmlParser>(p, "tag attribute missing '='"); p.SkipWhiteSpace(); var quote = p.Peek; if (quote != '"' && quote != '\'') throw new ParserException<XmlParser>(p, "tag attribute not quoted"); p.Skip(1); // skip quote var value = p.GetToStartOf(quote); p.Skip(); // skip quote n.AttList.Add(new XmlAtt(nameText, value)); return TagState; } p.SeenName = true; if (n.Name == null) { n.Name = name; return TagState; } if (p.SeenSlash) { if (name != n.Name) throw new ParserException<XmlParser>(p, "ending tag does not match"); return TagState; } var subNode = new XmlItem(name); // node to parse into Parse(p, TagState, subNode); // recurse to parse xml-tree n.Add(subNode); // add parsed node return TextState; }), new Case<XmlParser, XmlItem>(@"\?>", (p, n) => { if (!(n is XmlDoc)) throw new ParserException<XmlParser>(p, "illegal character"); p.Skip(); return TextState; }), new Case<XmlParser, XmlItem>(@">", (p, n) => { if (p.SeenSlash) { if (!p.SeenName) throw new ParserException<XmlParser>(p, "ending tag without name"); p.Skip(); return null; // no next state == recursion end } p.Skip(); return TextState; }), new Case<XmlParser, XmlItem>(@"/", (p, n) => { if (p.SeenSlash) throw new ParserException<XmlParser>(p, "second slash in tag"); p.SeenSlash = true; p.Skip(); return TagState; }), // If a state has a default case, all cases represent // non-searching patterns, that need to match at the // start of the non-consumed input. If non of the other // cases match at this point, the default case is taken. // In the xml case the state inside tags is non-searching, // and its default case handles white space and illegal // chraracters insided tags. new Case<XmlParser, XmlItem>((p, n) => // default used for eating white space { p.SkipWhiteSpaceAndCheckProgress(); return TagState; }), }); } #endregion }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations { public class VarKeywordRecommenderTests : RecommenderTests { private readonly VarKeywordRecommender _recommender = new VarKeywordRecommender(); public VarKeywordRecommenderTests() { this.keywordText = "var"; this.RecommendKeywordsAsync = (position, context) => _recommender.RecommendKeywordsAsync(position, context, CancellationToken.None); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAtRoot_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterClass_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"class C { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalStatement_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"System.Console.WriteLine(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalVariableDeclaration_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"int i = 0; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInUsingAlias() { await VerifyAbsenceAsync( @"using Foo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterStackAlloc() { await VerifyAbsenceAsync( @"class C { int* foo = stackalloc $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInFixedStatement() { await VerifyAbsenceAsync(AddInsideMethod( @"fixed ($$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInDelegateReturnType() { await VerifyAbsenceAsync( @"public delegate $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInCastType() { await VerifyAbsenceAsync(AddInsideMethod( @"var str = (($$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInCastType2() { await VerifyAbsenceAsync(AddInsideMethod( @"var str = (($$)items) as string;")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestEmptyStatement() { await VerifyKeywordAsync(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestBeforeStatement() { await VerifyKeywordAsync(AddInsideMethod( @"$$ return true;")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterStatement() { await VerifyKeywordAsync(AddInsideMethod( @"return true; $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterBlock() { await VerifyKeywordAsync(AddInsideMethod( @"if (true) { } $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterLock() { await VerifyAbsenceAsync(AddInsideMethod( @"lock $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterLock2() { await VerifyAbsenceAsync(AddInsideMethod( @"lock ($$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterLock3() { await VerifyAbsenceAsync(AddInsideMethod( @"lock (l$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInClass() { await VerifyAbsenceAsync(@"class C { $$ }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInFor() { await VerifyKeywordAsync(AddInsideMethod( @"for ($$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInFor() { await VerifyAbsenceAsync(AddInsideMethod( @"for (var $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInFor2() { await VerifyKeywordAsync(AddInsideMethod( @"for ($$;")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInFor3() { await VerifyKeywordAsync(AddInsideMethod( @"for ($$;;")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterVar() { await VerifyAbsenceAsync(AddInsideMethod( @"var $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInForEach() { await VerifyKeywordAsync(AddInsideMethod( @"foreach ($$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInForEach() { await VerifyAbsenceAsync(AddInsideMethod( @"foreach (var $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInUsing() { await VerifyKeywordAsync(AddInsideMethod( @"using ($$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInUsing() { await VerifyAbsenceAsync(AddInsideMethod( @"using (var $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterConstLocal() { await VerifyKeywordAsync(AddInsideMethod( @"const $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterConstField() { await VerifyAbsenceAsync( @"class C { const $$"); } } }
/*This code is managed under the Apache v2 license. To see an overview: http://www.tldrlegal.com/license/apache-license-2.0-(apache-2.0) Author: Robert Gawdzik www.github.com/rgawdzik/ THIS CODE HAS NO FORM OF ANY WARRANTY, AND IS CONSIDERED AS-IS. */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Paradox.Game.Classes.Ships; namespace Paradox.Game.Classes.Cameras { public class Camera { #region Class-Level Properties and Variables //Spectator Variables private const int SpectatorChange = 600; private int _spectatorTime; private int _followShip; private int _cameraSpeed; //Camera Matrices public Matrix View { get; set; } public Matrix Projection { get; set; } public Quaternion CameraRotation { get; set; } //For a Cockpit View, CameraRotation is not used. /* To create a view matrix, you need to have the following properties: * cameraPosition = position of the camera * cameraTarget = coordinate of what the camera is looking at. * cameraUpVector = Vector indicating which direction is up. */ public Vector3 CameraPosition; public Vector3 CameraDirection { get; set; } public Vector3 CameraUp { get; set; } public Vector3 CameraFollowPosition { get; set; } private Vector3 _defaultCameraUp; private Random _randomVar; public float CameraShakeIntensity; #endregion #region Constructors public Camera(GraphicsDevice device, Vector3 cameraFollowPosition) { CameraRotation = Quaternion.Identity; View = Matrix.Identity; DefaultProjectionMatrix(device); //Sets the Projection Matrix to the default params. CameraFollowPosition = cameraFollowPosition; SetDefaultCameraUp(); CameraUp = _defaultCameraUp; _randomVar = new Random(); CameraShakeIntensity = 0f; } public Camera(GraphicsDevice device, Vector3 cameraFollowPosition, Vector3 defaultCameraUp) { CameraRotation = Quaternion.Identity; View = Matrix.Identity; DefaultProjectionMatrix(device); //Sets the Projection Matrix to the default params. CameraFollowPosition = cameraFollowPosition; _defaultCameraUp = defaultCameraUp; _randomVar = new Random(); CameraShakeIntensity = 0; } public Camera(float FieldOfView, float AspectRatio, float NearPlaneDistance, float FarPlaneDistance, Vector3 cameraFollowPosition, Vector3 defaultCameraUp) { CameraRotation = Quaternion.Identity; View = Matrix.Identity; Projection = Matrix.CreatePerspectiveFieldOfView(FieldOfView, AspectRatio, NearPlaneDistance, FarPlaneDistance); CameraFollowPosition = cameraFollowPosition; _defaultCameraUp = defaultCameraUp; } #endregion #region Update Object Method(s) //This Update tells the Camera to follow an object, a chase view camera update. public void Update(Vector3 objectPosition, Quaternion objectRotation) { CameraRotation = Quaternion.Lerp(CameraRotation, objectRotation, 0.12f); //Adds Camera Delay. CameraPosition = CameraFollowPosition; //Resets the CameraPosition to default values. CameraPosition = Vector3.Transform(CameraPosition, Matrix.CreateFromQuaternion(CameraRotation)); //Transforms the Camera Position according to the object rotation and the previous camera rotation (delay) CameraPosition += objectPosition; //Repositions the camera to the object position. CameraUp = _defaultCameraUp; CameraUp = Vector3.Transform(CameraUp, Matrix.CreateFromQuaternion(CameraRotation)); //Modifies the Up Vector according to the Camera Rotation. View = Matrix.CreateLookAt(CameraPosition, CameraShakeProjection(objectPosition, CameraShakeIntensity), CameraUp); } //This Update tells the Camera that it is in Cockpit view. public void Update(Quaternion cameraRotation, Vector3 objectPosition) //The Camera Rotation is provided, most likely by Mouse Input Params. This allows the camera to point to any area as the player pleases. { CameraRotation = cameraRotation; CameraPosition = CameraFollowPosition; CameraPosition = Vector3.Transform(CameraPosition, Matrix.CreateFromQuaternion(CameraRotation)); //Transforms the Camera Position according to the Camera Rotation. CameraPosition += objectPosition; //Repositions the camera to the object position. CameraUp = _defaultCameraUp; CameraUp = Vector3.Transform(CameraUp, Matrix.CreateFromQuaternion(CameraRotation)); //Modifies the Up Vector according to the Camera Rotation. View = Matrix.CreateLookAt(CameraPosition, objectPosition, CameraUp); } /// <summary> /// Creates a camera that Randomly spectates different Friends. /// </summary> /// <param name="EnemyList"></param> public void SpectatorUpdate(List<Friend> FriendList) { _spectatorTime++; //The time to start spectating another ship has occured. if (_spectatorTime >= SpectatorChange) { _followShip = _randomVar.Next(FriendList.Count); _cameraSpeed += _randomVar.Next(-20, 20); _spectatorTime = 0; } //The Ship has been destroyed, let's get another one to follow. if (_followShip >= FriendList.Count) { _followShip = _randomVar.Next(FriendList.Count); } CameraRotation = FollowShip(FriendList[_followShip].ShipPosition, 0.2f); CameraPosition = CameraFollowPosition; //Resets the CameraPosition to default values. CameraPosition = Vector3.Transform(CameraPosition, Matrix.CreateFromQuaternion(CameraRotation)); //Transforms the Camera Position according to the object rotation and the previous camera rotation (delay) CameraPosition += FriendList[_followShip].ShipPosition;//Repositions the camera to the object position. //CameraPosition = Vector3.Lerp(CameraPosition, CameraPosition + FriendList[_followShip].ShipPosition, 0.2f) ; //Moves the camera in a random speed. CameraPosition.X += _cameraSpeed; CameraPosition.Y += _cameraSpeed; CameraPosition.Z += _cameraSpeed; //Increments the camera speed. _cameraSpeed += _cameraSpeed; CameraUp = _defaultCameraUp; CameraUp = Vector3.Transform(CameraUp, Matrix.CreateFromQuaternion(CameraRotation)); //Modifies the Up Vector according to the Camera Rotation. View = Matrix.CreateLookAt(CameraPosition, FriendList[_followShip].ShipPosition, CameraUp); } #endregion #region Helper Methods private void DefaultProjectionMatrix(GraphicsDevice device) { //Sets the Projection Matrix to the default params. Projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4, device.Viewport.AspectRatio, 0.2f, 3300f); //Previously 2400f } private void SetCameraFollowPosition(Vector3 cameraFollowPosition) { CameraFollowPosition = cameraFollowPosition; } public Quaternion FollowShip(Vector3 position, float lerpValue) { Vector3 desiredDirection = Vector3.Normalize(CameraPosition - position); Quaternion ShipDirection = Quaternion.CreateFromRotationMatrix(Matrix.CreateWorld(CameraPosition, desiredDirection, CameraUp)); return Quaternion.Lerp(CameraRotation, ShipDirection, lerpValue); } private void SetDefaultCameraUp() { _defaultCameraUp = new Vector3(0, 1, 0); } private Vector3 CameraShakeProjection(Vector3 objectFollowPosition, float intesity) { return new Vector3((float)Math.Sin(_randomVar.Next(-30, 30) * intesity) + objectFollowPosition.X, (float)Math.Sin(_randomVar.Next(-30, 30) * intesity) + objectFollowPosition.Y, objectFollowPosition.Z); //The Z axis should not even be a variable. } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace Microsoft.Tools.ServiceModel.SvcUtil.XmlSerializer { using System; using System.ServiceModel.Channels; using System.ServiceModel.Description; using System.IO; using System.Collections.Generic; using System.Collections.ObjectModel; using System.CodeDom.Compiler; using System.ServiceModel; using System.Runtime.Serialization; using System.Text; using System.Reflection; using System.Globalization; internal static class ToolConsole { #if DEBUG private static bool s_debug = false; #endif #if DEBUG internal static void SetOptions(bool debug) { ToolConsole.s_debug = debug; } #endif internal static void WriteLine(string str, int indent) { ToolStringBuilder toolStringBuilder = new ToolStringBuilder(indent); toolStringBuilder.WriteParagraph(str); } internal static void WriteLine(string str) { Console.WriteLine(str); } internal static void WriteLine() { Console.WriteLine(); } internal static void WriteError(string errMsg) { WriteError(errMsg, SR.Format(SR.Error)); } private static void WriteError(Exception e) { WriteError(e, SR.Format(SR.Error)); } internal static void WriteUnexpectedError(Exception e) { WriteError(SR.Format(SR.ErrUnexpectedError)); WriteError(e); } internal static void WriteUnexpectedError(string errMsg) { WriteError(SR.Format(SR.ErrUnexpectedError)); if (!string.IsNullOrEmpty(errMsg)) WriteError(errMsg); } internal static void WriteToolError(ToolArgumentException ae) { WriteError(ae); ToolConsole.WriteLine(SR.Format(SR.MoreHelp, Options.Abbr.Help)); } internal static void WriteToolError(ToolRuntimeException re) { WriteError(re); } internal static void WriteWarning(string message) { Console.Error.Write(SR.Format(SR.Warning)); Console.Error.WriteLine(message); Console.Error.WriteLine(); } private static void WriteError(string errMsg, string prefix) { Console.Error.Write(prefix); Console.Error.WriteLine(errMsg); Console.Error.WriteLine(); } internal static void WriteError(Exception e, string prefix) { #if DEBUG if (s_debug) { ToolConsole.WriteLine(); WriteError(e.ToString(), prefix); return; } #endif WriteError(e.Message, prefix); while (e.InnerException != null) { if (e.Message != e.InnerException.Message) { WriteError(e.InnerException.Message, " "); } e = e.InnerException; } } internal static void WriteHeader() { // Using CommonResStrings.WcfTrademarkForCmdLine for the trademark: the proper resource for command line tools. ToolConsole.WriteLine(SR.Format(SR.Logo, SR.WcfTrademarkForCmdLine, ThisAssembly.InformationalVersion, SR.CopyrightForCmdLine)); } internal static void WriteHelpText() { HelpGenerator.WriteUsage(); ToolConsole.WriteLine(); ToolConsole.WriteLine(); HelpGenerator.WriteCommonOptionsHelp(); ToolConsole.WriteLine(); ToolConsole.WriteLine(); HelpGenerator.WriteXmlSerializerTypeGenerationHelp(); ToolConsole.WriteLine(); ToolConsole.WriteLine(); HelpGenerator.WriteExamples(); ToolConsole.WriteLine(); ToolConsole.WriteLine(); } private static class HelpGenerator { private static ToolStringBuilder s_exampleBuilder = new ToolStringBuilder(4); static HelpGenerator() { } // beforefieldInit internal static void WriteUsage() { ToolConsole.WriteLine(SR.Format(SR.HelpUsage1)); ToolConsole.WriteLine(); ToolConsole.WriteLine(SR.Format(SR.HelpUsage6)); } internal static void WriteXmlSerializerTypeGenerationHelp() { HelpCategory helpCategory = new HelpCategory(SR.Format(SR.HelpXmlSerializerTypeGenerationCategory)); helpCategory.Description = SR.Format(SR.HelpXmlSerializerTypeGenerationDescription, ThisAssembly.Title); helpCategory.Syntax = SR.Format(SR.HelpXmlSerializerTypeGenerationSyntax, ThisAssembly.Title, SR.Format(SR.HelpInputAssemblyPath)); helpCategory.Inputs = new ArgumentInfo[1]; helpCategory.Inputs[0] = ArgumentInfo.CreateInputHelpInfo(SR.Format(SR.HelpInputAssemblyPath)); helpCategory.Inputs[0].HelpText = SR.Format(SR.HelpXmlSerializerTypeGenerationSyntaxInput1); helpCategory.Options = new ArgumentInfo[3]; helpCategory.Options[0] = ArgumentInfo.CreateParameterHelpInfo(Options.Cmd.Reference, SR.Format(SR.ParametersReference)); helpCategory.Options[0].HelpText = SR.Format(SR.HelpXmlSerializerTypeGenerationSyntaxInput2, Options.Abbr.Reference); helpCategory.Options[1] = ArgumentInfo.CreateParameterHelpInfo(Options.Cmd.ExcludeType, SR.Format(SR.ParametersExcludeType)); helpCategory.Options[1].HelpText = SR.Format(SR.HelpXmlSerializerTypeGenerationSyntaxInput3, Options.Abbr.ExcludeType); helpCategory.Options[2] = ArgumentInfo.CreateParameterHelpInfo(Options.Cmd.Out, SR.Format(SR.ParametersOut)); helpCategory.Options[2].HelpText = SR.Format(SR.HelpXmlSerializerTypeGenerationSyntaxInput4, Options.Abbr.Out); helpCategory.WriteHelp(); } internal static void WriteCommonOptionsHelp() { HelpCategory helpCategory = new HelpCategory(SR.Format(SR.HelpCommonOptionsCategory)); var options = new List<ArgumentInfo>(); ArgumentInfo option; option = ArgumentInfo.CreateParameterHelpInfo(Options.Cmd.Directory, SR.Format(SR.ParametersDirectory)); option.HelpText = SR.Format(SR.HelpDirectory, Options.Abbr.Directory); options.Add(option); option = ArgumentInfo.CreateFlagHelpInfo(Options.Cmd.NoLogo); option.HelpText = SR.Format(SR.HelpNologo); options.Add(option); option = ArgumentInfo.CreateFlagHelpInfo(Options.Cmd.Help); option.HelpText = SR.Format(SR.HelpHelp, Options.Abbr.Help); options.Add(option); helpCategory.Options = options.ToArray(); helpCategory.WriteHelp(); } internal static void WriteCodeGenerationHelp() { HelpCategory helpCategory = new HelpCategory(SR.Format(SR.HelpCodeGenerationCategory)); helpCategory.Description = SR.Format(SR.HelpCodeGenerationDescription, ThisAssembly.Title); helpCategory.Syntax = SR.Format(SR.HelpCodeGenerationSyntax, ThisAssembly.Title, Options.Abbr.Target, Options.Targets.Code, SR.Format(SR.HelpInputMetadataDocumentPath), SR.Format(SR.HelpInputUrl), SR.Format(SR.HelpInputEpr)); helpCategory.Inputs = new ArgumentInfo[3]; helpCategory.Inputs[0] = ArgumentInfo.CreateInputHelpInfo(SR.Format(SR.HelpInputMetadataDocumentPath)); helpCategory.Inputs[0].HelpText = SR.Format(SR.HelpCodeGenerationSyntaxInput1); helpCategory.Inputs[1] = ArgumentInfo.CreateInputHelpInfo(SR.Format(SR.HelpInputUrl)); helpCategory.Inputs[1].HelpText = SR.Format(SR.HelpCodeGenerationSyntaxInput2); helpCategory.Inputs[2] = ArgumentInfo.CreateInputHelpInfo(SR.Format(SR.HelpInputEpr)); helpCategory.Inputs[2].HelpText = SR.Format(SR.HelpCodeGenerationSyntaxInput3); helpCategory.Options = new ArgumentInfo[26]; helpCategory.Options[0] = ArgumentInfo.CreateParameterHelpInfo(Options.Cmd.Out, SR.Format(SR.ParametersOut)); helpCategory.Options[0].HelpText = SR.Format(SR.HelpOut, Options.Abbr.Out); helpCategory.Options[1] = ArgumentInfo.CreateParameterHelpInfo(Options.Cmd.Namespace, SR.Format(SR.ParametersNamespace)); helpCategory.Options[1].HelpText = SR.Format(SR.HelpNamespace, Options.Abbr.Namespace); helpCategory.Options[2] = ArgumentInfo.CreateParameterHelpInfo(Options.Cmd.Reference, SR.Format(SR.ParametersReference)); helpCategory.Options[2].BeginGroup = true; helpCategory.Options[2].HelpText = SR.Format(SR.HelpReferenceCodeGeneration, Options.Abbr.Reference); helpCategory.Options[3] = ArgumentInfo.CreateParameterHelpInfo(Options.Cmd.CollectionType, SR.Format(SR.ParametersCollectionType)); helpCategory.Options[3].HelpText = SR.Format(SR.HelpCollectionType, Options.Abbr.CollectionType); helpCategory.Options[4] = ArgumentInfo.CreateParameterHelpInfo(Options.Cmd.ExcludeType, SR.Format(SR.ParametersExcludeType)); helpCategory.Options[4].HelpText = SR.Format(SR.HelpExcludeTypeCodeGeneration, Options.Abbr.ExcludeType); helpCategory.Options[5] = ArgumentInfo.CreateFlagHelpInfo(Options.Cmd.Nostdlib); helpCategory.Options[5].HelpText = SR.Format(SR.HelpNostdlib); helpCategory.WriteHelp(); } internal static void WriteExamples() { HelpCategory helpCategory = new HelpCategory(SR.Format(SR.HelpExamples)); helpCategory.WriteHelp(); WriteExample(SR.HelpExamples1, SR.HelpExamples2); } private static void WriteExample(string syntax, string explanation) { ToolConsole.WriteLine(string.Format(CultureInfo.InvariantCulture, " {0}", syntax)); s_exampleBuilder.WriteParagraph(string.Format(CultureInfo.InvariantCulture, " {0}", explanation)); ToolConsole.WriteLine(); } private class ArgumentInfo { private const string argHelpPrefix = " "; private const string argHelpSeperator = " - "; internal static ArgumentInfo CreateInputHelpInfo(string input) { ArgumentInfo argInfo = new ArgumentInfo(); argInfo._name = input; return argInfo; } internal static ArgumentInfo CreateFlagHelpInfo(string option) { ArgumentInfo argInfo = new ArgumentInfo(); argInfo._name = String.Format(CultureInfo.InvariantCulture, "/{0}", option); return argInfo; } internal static ArgumentInfo CreateParameterHelpInfo(string option, string optionUse) { ArgumentInfo argInfo = new ArgumentInfo(); argInfo._name = String.Format(CultureInfo.InvariantCulture, "/{0}:{1}", option, optionUse); return argInfo; } private bool _beginGroup; private string _name; private string _helpText; public bool BeginGroup { get { return _beginGroup; } set { _beginGroup = value; } } public string Name { get { return _name; } } public string HelpText { set { _helpText = value; } } private string GenerateHelp(string pattern) { return string.Format(CultureInfo.InvariantCulture, pattern, _name, _helpText); } private static int CalculateMaxNameLength(ArgumentInfo[] arguments) { int maxNameLength = 0; foreach (ArgumentInfo argument in arguments) { if (argument.Name.Length > maxNameLength) { maxNameLength = argument.Name.Length; } } return maxNameLength; } public static void WriteArguments(ArgumentInfo[] arguments) { int maxArgumentLength = CalculateMaxNameLength(arguments); int helpTextIndent = argHelpPrefix.Length + maxArgumentLength + argHelpSeperator.Length; string helpPattern = argHelpPrefix + "{0, -" + maxArgumentLength + "}" + argHelpSeperator + "{1}"; ToolStringBuilder builder = new ToolStringBuilder(helpTextIndent); foreach (ArgumentInfo argument in arguments) { if (argument.BeginGroup) ToolConsole.WriteLine(); string optionHelp = argument.GenerateHelp(helpPattern); builder.WriteParagraph(optionHelp); } } } private class HelpCategory { static HelpCategory() { try { bool junk = Console.CursorVisible; if (Console.WindowWidth > 75) s_nameMidpoint = Console.WindowWidth / 3; else s_nameMidpoint = 25; } catch { s_nameMidpoint = 25; } } private static ToolStringBuilder s_categoryBuilder = new ToolStringBuilder(4); private static int s_nameMidpoint; private int _nameStart; private string _name; private string _description = null; private string _syntax = null; private ArgumentInfo[] _options; private ArgumentInfo[] _inputs; public HelpCategory(string name) { Tool.Assert(name != null, "Name should never be null"); _name = name; _nameStart = s_nameMidpoint - (name.Length / 2); } public string Description { set { _description = value; } } public string Syntax { set { _syntax = value; } } public ArgumentInfo[] Options { get { return _options; } set { _options = value; } } public ArgumentInfo[] Inputs { get { return _inputs; } set { _inputs = value; } } public void WriteHelp() { int start = s_nameMidpoint; ToolConsole.WriteLine(new string(' ', _nameStart) + _name); ToolConsole.WriteLine(); if (_description != null) { s_categoryBuilder.WriteParagraph(_description); ToolConsole.WriteLine(); } if (_syntax != null) { s_categoryBuilder.WriteParagraph(_syntax); ToolConsole.WriteLine(); } if (_inputs != null) { ArgumentInfo.WriteArguments(_inputs); ToolConsole.WriteLine(); } if (_options != null) { ToolConsole.WriteLine(SR.Format(SR.HelpOptions)); ToolConsole.WriteLine(); ArgumentInfo.WriteArguments(_options); ToolConsole.WriteLine(); } } } } private class ToolStringBuilder { private int _indentLength; private int _cursorLeft; private int _lineWidth; private StringBuilder _stringBuilder; public ToolStringBuilder(int indentLength) { _indentLength = indentLength; } private void Reset() { _stringBuilder = new StringBuilder(); _cursorLeft = GetConsoleCursorLeft(); _lineWidth = GetBufferWidth(); } public void WriteParagraph(string text) { this.Reset(); this.AppendParagraph(text); ToolConsole.WriteLine(_stringBuilder.ToString()); _stringBuilder = null; } private void AppendParagraph(string text) { Tool.Assert(_stringBuilder != null, "stringBuilder cannot be null"); int index = 0; while (index < text.Length) { this.AppendWord(text, ref index); this.AppendWhitespace(text, ref index); } } private void AppendWord(string text, ref int index) { // If we're at the beginning of a new line we should indent. if ((_cursorLeft == 0) && (index != 0)) AppendIndent(); int wordLength = FindWordLength(text, index); // Now that we know how long the string is we can: // 1. print it on the current line if we have enough space // 2. print it on the next line if we don't have space // on the current line and it will fit on the next line // 3. print whatever will fit on the current line // and overflow to the next line. if (wordLength < this.HangingLineWidth) { if (wordLength > this.BufferWidth) { this.AppendLineBreak(); this.AppendIndent(); } _stringBuilder.Append(text, index, wordLength); _cursorLeft += wordLength; } else { AppendWithOverflow(text, ref index, ref wordLength); } index += wordLength; } private void AppendWithOverflow(string test, ref int start, ref int wordLength) { do { _stringBuilder.Append(test, start, this.BufferWidth); start += this.BufferWidth; wordLength -= this.BufferWidth; this.AppendLineBreak(); if (wordLength > 0) this.AppendIndent(); } while (wordLength > this.BufferWidth); if (wordLength > 0) { _stringBuilder.Append(test, start, wordLength); _cursorLeft += wordLength; } } private void AppendWhitespace(string text, ref int index) { while ((index < text.Length) && char.IsWhiteSpace(text[index])) { if (BufferWidth == 0) { this.AppendLineBreak(); } // For each whitespace character: // 1. If we're at a newline character we insert // a new line and reset the cursor. // 2. If the whitespace character is at the beginning of a new // line, we insert an indent instead of the whitespace // 3. Insert the whitespace if (AtNewLine(text, index)) { this.AppendLineBreak(); index += Environment.NewLine.Length; } else if (_cursorLeft == 0 && index != 0) { AppendIndent(); index++; } else { _stringBuilder.Append(text[index]); index++; _cursorLeft++; } } } private void AppendIndent() { _stringBuilder.Append(' ', _indentLength); _cursorLeft += _indentLength; } private void AppendLineBreak() { if (BufferWidth != 0) _stringBuilder.AppendLine(); _cursorLeft = 0; } private int BufferWidth { get { return _lineWidth - _cursorLeft; } } private int HangingLineWidth { get { return _lineWidth - _indentLength; } } private static int FindWordLength(string text, int index) { for (int end = index; end < text.Length; end++) { if (char.IsWhiteSpace(text[end])) return end - index; } return text.Length - index; } private static bool AtNewLine(string text, int index) { if ((index + Environment.NewLine.Length) > text.Length) { return false; } for (int i = 0; i < Environment.NewLine.Length; i++) { if (Environment.NewLine[i] != text[index + i]) { return false; } } return true; } private static int GetConsoleCursorLeft() { try { return Console.CursorLeft; } catch { return 0; } } private static int GetBufferWidth() { try { bool junk = Console.CursorVisible; return Console.BufferWidth; } catch { return int.MaxValue; } } } } }
namespace Nancy { using System; using System.Collections.Generic; using System.ComponentModel; using System.IO; using Nancy.ModelBinding; using Nancy.Responses.Negotiation; using Nancy.Routing; using Nancy.Session; using Nancy.Validation; using Nancy.ViewEngines; /// <summary> /// Basic class containing the functionality for defining routes and actions in Nancy. /// </summary> public abstract class NancyModule : INancyModule, IHideObjectMembers { private readonly List<Route> routes; /// <summary> /// Initializes a new instance of the <see cref="NancyModule"/> class. /// </summary> protected NancyModule() : this(String.Empty) { } /// <summary> /// Initializes a new instance of the <see cref="NancyModule"/> class. /// </summary> /// <param name="modulePath">A <see cref="string"/> containing the root relative path that all paths in the module will be a subset of.</param> protected NancyModule(string modulePath) { this.After = new AfterPipeline(); this.Before = new BeforePipeline(); this.OnError = new ErrorPipeline(); this.ModulePath = modulePath; this.routes = new List<Route>(); } /// <summary> /// Non-model specific data for rendering in the response /// </summary> public dynamic ViewBag { get { return this.Context == null ? null : this.Context.ViewBag; } } /// <summary> /// Gets <see cref="RouteBuilder"/> for declaring actions for DELETE requests. /// </summary> /// <value>A <see cref="RouteBuilder"/> instance.</value> public RouteBuilder Delete { get { return new RouteBuilder("DELETE", this); } } /// <summary> /// Gets <see cref="RouteBuilder"/> for declaring actions for GET requests. /// </summary> /// <value>A <see cref="RouteBuilder"/> instance.</value> /// <remarks>These actions will also be used when a HEAD request is recieved.</remarks> public RouteBuilder Get { get { return new RouteBuilder("GET", this); } } /// <summary> /// Gets <see cref="RouteBuilder"/> for declaring actions for OPTIONS requests. /// </summary> /// <value>A <see cref="RouteBuilder"/> instance.</value> public RouteBuilder Options { get { return new RouteBuilder("OPTIONS", this); } } /// <summary> /// Gets <see cref="RouteBuilder"/> for declaring actions for PATCH requests. /// </summary> /// <value>A <see cref="RouteBuilder"/> instance.</value> public RouteBuilder Patch { get { return new RouteBuilder("PATCH", this); } } /// <summary> /// Gets <see cref="RouteBuilder"/> for declaring actions for POST requests. /// </summary> /// <value>A <see cref="RouteBuilder"/> instance.</value> public RouteBuilder Post { get { return new RouteBuilder("POST", this); } } /// <summary> /// Gets <see cref="RouteBuilder"/> for declaring actions for PUT requests. /// </summary> /// <value>A <see cref="RouteBuilder"/> instance.</value> public RouteBuilder Put { get { return new RouteBuilder("PUT", this); } } /// <summary> /// Get the root path of the routes in the current module. /// </summary> /// <value> /// A <see cref="T:System.String" /> containing the root path of the module or <see langword="null" /> /// if no root path should be used.</value><remarks>All routes will be relative to this root path. /// </remarks> public string ModulePath { get; private set; } /// <summary> /// Gets all declared routes by the module. /// </summary> /// <value>A <see cref="IEnumerable{T}"/> instance, containing all <see cref="Route"/> instances declared by the module.</value> public virtual IEnumerable<Route> Routes { get { return this.routes.AsReadOnly(); } } /// <summary> /// Gets the current session. /// </summary> public ISession Session { get { return this.Request.Session; } } /// <summary> /// Renders a view from inside a route handler. /// </summary> /// <value>A <see cref="ViewRenderer"/> instance that is used to determin which view that should be rendered.</value> public ViewRenderer View { get { return new ViewRenderer(this); } } public Negotiator Negotiate { get { return new Negotiator(this.Context); } } /// <summary> /// Gets or sets the validator locator. /// </summary> public IModelValidatorLocator ValidatorLocator { get; set; } /// <summary> /// Gets or sets an <see cref="Request"/> instance that represents the current request. /// </summary> /// <value>An <see cref="Request"/> instance.</value> public virtual Request Request { get { return this.Context.Request; } set { this.Context.Request = value; } } /// <summary> /// The extension point for accessing the view engines in Nancy. /// </summary><value>An <see cref="T:Nancy.ViewEngines.IViewFactory" /> instance.</value> /// <remarks>This is automatically set by Nancy at runtime.</remarks> public IViewFactory ViewFactory { get; set; } /// <summary><para> /// The post-request hook /// </para><para> /// The post-request hook is called after the response is created by the route execution. /// It can be used to rewrite the response or add/remove items from the context. /// </para> /// <remarks>This is automatically set by Nancy at runtime.</remarks> /// </summary> public AfterPipeline After { get; set; } /// <summary><para> /// The pre-request hook /// </para><para> /// The PreRequest hook is called prior to executing a route. If any item in the /// pre-request pipeline returns a response then the route is not executed and the /// response is returned. /// </para> /// <remarks>This is automatically set by Nancy at runtime.</remarks> /// </summary> public BeforePipeline Before { get; set; } /// <summary><para> /// The error hook /// </para><para> /// The error hook is called if an exception is thrown at any time during executing /// the PreRequest hook, a route and the PostRequest hook. It can be used to set /// the response and/or finish any ongoing tasks (close database session, etc). /// </para> /// <remarks>This is automatically set by Nancy at runtime.</remarks> /// </summary> public ErrorPipeline OnError { get; set; } /// <summary> /// Gets or sets the current Nancy context /// </summary> /// <value>A <see cref="T:Nancy.NancyContext" /> instance.</value> /// <remarks>This is automatically set by Nancy at runtime.</remarks> public NancyContext Context { get; set; } /// <summary> /// An extension point for adding support for formatting response contents. /// </summary><value>This property will always return <see langword="null" /> because it acts as an extension point.</value><remarks>Extension methods to this property should always return <see cref="P:Nancy.NancyModuleBase.Response" /> or one of the types that can implicitly be types into a <see cref="P:Nancy.NancyModuleBase.Response" />.</remarks> public IResponseFormatter Response { get; set; } /// <summary> /// Gets or sets the model binder locator /// </summary> public IModelBinderLocator ModelBinderLocator { get; set; } /// <summary> /// Gets or sets the model validation result /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] public virtual ModelValidationResult ModelValidationResult { get { return this.Context == null ? null : this.Context.ModelValidationResult; } set { if (this.Context != null) { this.Context.ModelValidationResult = value; } } } /// <summary> /// Helper class for configuring a route handler in a module. /// </summary> public class RouteBuilder : IHideObjectMembers { private readonly string method; private readonly NancyModule parentModule; /// <summary> /// Initializes a new instance of the <see cref="RouteBuilder"/> class. /// </summary> /// <param name="method">The HTTP request method that the route should be available for.</param> /// <param name="parentModule">The <see cref="INancyModule"/> that the route is being configured for.</param> public RouteBuilder(string method, NancyModule parentModule) { this.method = method; this.parentModule = parentModule; } /// <summary> /// Defines a Nancy route for the specified <paramref name="path"/>. /// </summary> /// <value>A delegate that is used to invoke the route.</value> public Func<dynamic, dynamic> this[string path] { set { this.AddRoute(path, null, value); } } /// <summary> /// Defines a Nancy route for the specified <paramref name="path"/> and <paramref name="condition"/>. /// </summary> /// <value>A delegate that is used to invoke the route.</value> public Func<dynamic, dynamic> this[string path, Func<NancyContext, bool> condition] { set { this.AddRoute(path, condition, value); } } protected void AddRoute(string path, Func<NancyContext, bool> condition, Func<dynamic, dynamic> value) { var fullPath = String.Concat(this.parentModule.ModulePath, path); this.parentModule.routes.Add(new Route(this.method, fullPath, condition, value)); } } /// <summary> /// Helper class for rendering a view from a route handler. /// </summary> public class ViewRenderer : IHideObjectMembers { private readonly INancyModule module; /// <summary> /// Initializes a new instance of the <see cref="ViewRenderer"/> class. /// </summary> /// <param name="module">The <see cref="INancyModule"/> instance that is rendering the view.</param> public ViewRenderer(INancyModule module) { this.module = module; } /// <summary> /// Renders the view with its name resolved from the model type, and model defined by the <paramref name="model"/> parameter. /// </summary> /// <param name="model">The model that should be passed into the view.</param> /// <returns>A delegate that can be invoked with the <see cref="Stream"/> that the view should be rendered to.</returns> /// <remarks>The view name is model.GetType().Name with any Model suffix removed.</remarks> public Negotiator this[dynamic model] { get { return this.GetNegotiator(null, model); } } /// <summary> /// Renders the view with the name defined by the <paramref name="viewName"/> parameter. /// </summary> /// <param name="viewName">The name of the view to render.</param> /// <returns>A delegate that can be invoked with the <see cref="Stream"/> that the view should be rendered to.</returns> /// <remarks>The extension in the view name is optional. If it is omitted, then Nancy will try to resolve which of the available engines that should be used to render the view.</remarks> public Negotiator this[string viewName] { get { return this.GetNegotiator(viewName, null); } } /// <summary> /// Renders the view with the name and model defined by the <paramref name="viewName"/> and <paramref name="model"/> parameters. /// </summary> /// <param name="viewName">The name of the view to render.</param> /// <param name="model">The model that should be passed into the view.</param> /// <returns>A delegate that can be invoked with the <see cref="Stream"/> that the view should be rendered to.</returns> /// <remarks>The extension in the view name is optional. If it is omitted, then Nancy will try to resolve which of the available engines that should be used to render the view.</remarks> public Negotiator this[string viewName, dynamic model] { get { return this.GetNegotiator(viewName, model); } } private Negotiator GetNegotiator(string viewName, object model) { var negotiationContext = this.module.Context.NegotiationContext; negotiationContext.ViewName = viewName; negotiationContext.DefaultModel = model; negotiationContext.PermissableMediaRanges.Clear(); negotiationContext.PermissableMediaRanges.Add("text/html"); return new Negotiator(this.module.Context); } } } }
/* * Copyright 2007 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using NUnit.Framework; namespace ZXing.Client.Result.Test { /// <summary> /// Tests <see cref="AddressBookParsedResult" />. /// /// <author>Sean Owen</author> /// </summary> [TestFixture] public sealed class AddressBookParsedResultTestCase { [Test] public void testAddressBookDocomo() { doTest("MECARD:N:Sean Owen;;", null, new String[] { "Sean Owen" }, null, null, null, null, null, null, null, null, null); doTest("MECARD:NOTE:ZXing Team;N:Sean Owen;URL:google.com;EMAIL:srowen@example.org;;", null, new String[] { "Sean Owen" }, null, null, new String[] { "srowen@example.org" }, null, null, null, new String[] { "google.com" }, null, "ZXing Team"); } [Test] public void testAddressBookAU() { doTest("MEMORY:foo\r\nNAME1:Sean\r\nTEL1:+12125551212\r\n", null, new String[] { "Sean" }, null, null, null, new String[] { "+12125551212" }, null, null, null, null, "foo"); } [Test] public void testVCard() { doTest("BEGIN:VCARD\r\nADR;HOME:123 Main St\r\nVERSION:2.1\r\nN:Owen;Sean\r\nEND:VCARD", null, new String[] { "Sean Owen" }, null, new String[] { "123 Main St" }, null, null, null, null, null, null, null); } [Test] public void testVCardFullN() { doTest("BEGIN:VCARD\r\nVERSION:2.1\r\nN:Owen;Sean;T;Mr.;Esq.\r\nEND:VCARD", null, new String[] { "Mr. Sean T Owen Esq." }, null, null, null, null, null, null, null, null, null); } [Test] public void testVCardFullN2() { doTest("BEGIN:VCARD\r\nVERSION:2.1\r\nN:Owen;Sean;;;\r\nEND:VCARD", null, new String[] { "Sean Owen" }, null, null, null, null, null, null, null, null, null); } [Test] public void testVCardFullN3() { doTest("BEGIN:VCARD\r\nVERSION:2.1\r\nN:;Sean;;;\r\nEND:VCARD", null, new String[] { "Sean" }, null, null, null, null, null, null, null, null, null); } [Test] public void testVCardCaseInsensitive() { doTest("begin:vcard\r\nadr;HOME:123 Main St\r\nVersion:2.1\r\nn:Owen;Sean\r\nEND:VCARD", null, new String[] { "Sean Owen" }, null, new String[] { "123 Main St" }, null, null, null, null, null, null, null); } [Test] public void testEscapedVCard() { doTest("BEGIN:VCARD\r\nADR;HOME:123\\;\\\\ Main\\, St\\nHome\r\nVERSION:2.1\r\nN:Owen;Sean\r\nEND:VCARD", null, new String[] { "Sean Owen" }, null, new String[] { "123;\\ Main, St\nHome" }, null, null, null, null, null, null, null); } [Test] public void testBizcard() { doTest("BIZCARD:N:Sean;X:Owen;C:Google;A:123 Main St;M:+12125551212;E:srowen@example.org;", null, new String[] { "Sean Owen" }, null, new String[] { "123 Main St" }, new String[] { "srowen@example.org" }, new String[] { "+12125551212" }, null, "Google", null, null, null); } [Test] public void testSeveralAddresses() { doTest("MECARD:N:Foo Bar;ORG:Company;TEL:5555555555;EMAIL:foo.bar@xyz.com;ADR:City, 10001;" + "ADR:City, 10001;NOTE:This is the memo.;;", null, new String[] { "Foo Bar" }, null, new String[] { "City, 10001", "City, 10001" }, new String[] { "foo.bar@xyz.com" }, new String[] { "5555555555" }, null, "Company", null, null, "This is the memo."); } [Test] public void testQuotedPrintable() { doTest("BEGIN:VCARD\r\nADR;HOME;CHARSET=UTF-8;ENCODING=QUOTED-PRINTABLE:;;" + "=38=38=20=4C=79=6E=62=72=6F=6F=6B=0D=0A=43=\r\n" + "=4F=20=36=39=39=\r\n" + "=39=39;;;\r\nEND:VCARD", null, null, null, new String[] { "88 Lynbrook\r\nCO 69999" }, null, null, null, null, null, null, null); } [Test] public void testVCardEscape() { doTest("BEGIN:VCARD\r\nNOTE:foo\\nbar\r\nEND:VCARD", null, null, null, null, null, null, null, null, null, null, "foo\nbar"); doTest("BEGIN:VCARD\r\nNOTE:foo\\;bar\r\nEND:VCARD", null, null, null, null, null, null, null, null, null, null, "foo;bar"); doTest("BEGIN:VCARD\r\nNOTE:foo\\\\bar\r\nEND:VCARD", null, null, null, null, null, null, null, null, null, null, "foo\\bar"); doTest("BEGIN:VCARD\r\nNOTE:foo\\,bar\r\nEND:VCARD", null, null, null, null, null, null, null, null, null, null, "foo,bar"); } [Test] public void testVCardValueURI() { doTest("BEGIN:VCARD\r\nTEL;VALUE=uri:tel:+1-555-555-1212\r\nEND:VCARD", null, null, null, null, null, new String[] { "+1-555-555-1212" }, new String[] { null }, null, null, null, null); doTest("BEGIN:VCARD\r\nN;VALUE=text:Owen;Sean\r\nEND:VCARD", null, new String[] { "Sean Owen" }, null, null, null, null, null, null, null, null, null); } [Test] public void testVCardTypes() { doTest("BEGIN:VCARD\r\nTEL;HOME:\r\nTEL;WORK:10\r\nTEL:20\r\nTEL;CELL:30\r\nEND:VCARD", null, null, null, null, null, new String[] {"10", "20", "30"}, new String[] {"WORK", "", "CELL"}, null, null, null, null); } private static void doTest(String contents, String title, String[] names, String pronunciation, String[] addresses, String[] emails, String[] phoneNumbers, String[] phoneTypes, String org, String[] urls, String birthday, String note) { ZXing.Result fakeResult = new ZXing.Result(contents, null, null, BarcodeFormat.QR_CODE); ParsedResult result = ResultParser.parseResult(fakeResult); Assert.AreEqual(ParsedResultType.ADDRESSBOOK, result.Type); AddressBookParsedResult addressResult = (AddressBookParsedResult)result; Assert.AreEqual(title, addressResult.Title); Assert.IsTrue(AreEqual(names, addressResult.Names)); Assert.AreEqual(pronunciation, addressResult.Pronunciation); Assert.IsTrue(AreEqual(addresses, addressResult.Addresses)); Assert.IsTrue(AreEqual(emails, addressResult.Emails)); Assert.IsTrue(AreEqual(phoneNumbers, addressResult.PhoneNumbers)); Assert.AreEqual(phoneTypes, addressResult.PhoneTypes); Assert.AreEqual(org, addressResult.Org); Assert.IsTrue(AreEqual(urls, addressResult.URLs)); Assert.AreEqual(birthday, addressResult.Birthday); Assert.AreEqual(note, addressResult.Note); } internal static bool AreEqual<T>(IList<T> left, IList<T> right) { if (left == null) return right == null; if (right == null) return false; if (left.Count != right.Count) return false; foreach (var leftItem in left) { var found = false; foreach (var rightItem in right) { if (Equals(rightItem, leftItem)) { found = true; break; } } if (!found) return false; } foreach (var rightItem in right) { var found = false; foreach (var leftItem in left) { if (Equals(rightItem, leftItem)) { found = true; break; } } if (!found) return false; } return true; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Globalization; using System.ComponentModel; namespace System.Net.Security { // // The class does the real work in authentication and // user data encryption with NEGO SSPI package. // // This is part of the NegotiateStream PAL. // internal static partial class NegotiateStreamPal { internal static int QueryMaxTokenSize(string package) { return SSPIWrapper.GetVerifyPackageInfo(GlobalSSPI.SSPIAuth, package, true).MaxToken; } internal static SafeFreeCredentials AcquireDefaultCredential(string package, bool isServer) { return SSPIWrapper.AcquireDefaultCredential( GlobalSSPI.SSPIAuth, package, (isServer ? Interop.SspiCli.CredentialUse.SECPKG_CRED_INBOUND : Interop.SspiCli.CredentialUse.SECPKG_CRED_OUTBOUND)); } internal static unsafe SafeFreeCredentials AcquireCredentialsHandle(string package, bool isServer, NetworkCredential credential) { SafeSspiAuthDataHandle authData = null; try { Interop.SECURITY_STATUS result = Interop.SspiCli.SspiEncodeStringsAsAuthIdentity( credential.UserName, credential.Domain, credential.Password, out authData); if (result != Interop.SECURITY_STATUS.OK) { if (NetEventSource.IsEnabled) NetEventSource.Error(null, SR.Format(SR.net_log_operation_failed_with_error, nameof(Interop.SspiCli.SspiEncodeStringsAsAuthIdentity), $"0x{(int)result:X}")); throw new Win32Exception((int)result); } return SSPIWrapper.AcquireCredentialsHandle(GlobalSSPI.SSPIAuth, package, (isServer ? Interop.SspiCli.CredentialUse.SECPKG_CRED_INBOUND : Interop.SspiCli.CredentialUse.SECPKG_CRED_OUTBOUND), ref authData); } finally { if (authData != null) { authData.Dispose(); } } } internal static string QueryContextClientSpecifiedSpn(SafeDeleteContext securityContext) { return SSPIWrapper.QueryContextAttributes(GlobalSSPI.SSPIAuth, securityContext, Interop.SspiCli.ContextAttribute.SECPKG_ATTR_CLIENT_SPECIFIED_TARGET) as string; } internal static string QueryContextAuthenticationPackage(SafeDeleteContext securityContext) { var negotiationInfoClass = SSPIWrapper.QueryContextAttributes(GlobalSSPI.SSPIAuth, securityContext, Interop.SspiCli.ContextAttribute.SECPKG_ATTR_NEGOTIATION_INFO) as NegotiationInfoClass; return negotiationInfoClass?.AuthenticationPackage; } internal static SecurityStatusPal InitializeSecurityContext( SafeFreeCredentials credentialsHandle, ref SafeDeleteContext securityContext, string spn, ContextFlagsPal requestedContextFlags, SecurityBuffer[] inSecurityBufferArray, SecurityBuffer outSecurityBuffer, ref ContextFlagsPal contextFlags) { Interop.SspiCli.ContextFlags outContextFlags = Interop.SspiCli.ContextFlags.Zero; Interop.SECURITY_STATUS winStatus = (Interop.SECURITY_STATUS)SSPIWrapper.InitializeSecurityContext( GlobalSSPI.SSPIAuth, credentialsHandle, ref securityContext, spn, ContextFlagsAdapterPal.GetInteropFromContextFlagsPal(requestedContextFlags), Interop.SspiCli.Endianness.SECURITY_NETWORK_DREP, inSecurityBufferArray, outSecurityBuffer, ref outContextFlags); contextFlags = ContextFlagsAdapterPal.GetContextFlagsPalFromInterop(outContextFlags); return SecurityStatusAdapterPal.GetSecurityStatusPalFromInterop(winStatus); } internal static SecurityStatusPal CompleteAuthToken( ref SafeDeleteContext securityContext, SecurityBuffer[] inSecurityBufferArray) { Interop.SECURITY_STATUS winStatus = (Interop.SECURITY_STATUS)SSPIWrapper.CompleteAuthToken( GlobalSSPI.SSPIAuth, ref securityContext, inSecurityBufferArray); return SecurityStatusAdapterPal.GetSecurityStatusPalFromInterop(winStatus); } internal static SecurityStatusPal AcceptSecurityContext( SafeFreeCredentials credentialsHandle, ref SafeDeleteContext securityContext, ContextFlagsPal requestedContextFlags, SecurityBuffer[] inSecurityBufferArray, SecurityBuffer outSecurityBuffer, ref ContextFlagsPal contextFlags) { Interop.SspiCli.ContextFlags outContextFlags = Interop.SspiCli.ContextFlags.Zero; Interop.SECURITY_STATUS winStatus = (Interop.SECURITY_STATUS)SSPIWrapper.AcceptSecurityContext( GlobalSSPI.SSPIAuth, credentialsHandle, ref securityContext, ContextFlagsAdapterPal.GetInteropFromContextFlagsPal(requestedContextFlags), Interop.SspiCli.Endianness.SECURITY_NETWORK_DREP, inSecurityBufferArray, outSecurityBuffer, ref outContextFlags); contextFlags = ContextFlagsAdapterPal.GetContextFlagsPalFromInterop(outContextFlags); return SecurityStatusAdapterPal.GetSecurityStatusPalFromInterop(winStatus); } internal static Win32Exception CreateExceptionFromError(SecurityStatusPal statusCode) { return new Win32Exception((int)SecurityStatusAdapterPal.GetInteropFromSecurityStatusPal(statusCode)); } internal static int VerifySignature(SafeDeleteContext securityContext, byte[] buffer, int offset, int count) { // validate offset within length if (offset < 0 || offset > (buffer == null ? 0 : buffer.Length)) { NetEventSource.Info("Argument 'offset' out of range."); throw new ArgumentOutOfRangeException(nameof(offset)); } // validate count within offset and end of buffer if (count < 0 || count > (buffer == null ? 0 : buffer.Length - offset)) { NetEventSource.Info("Argument 'count' out of range."); throw new ArgumentOutOfRangeException(nameof(count)); } // setup security buffers for ssp call // one points at signed data // two will receive payload if signature is valid SecurityBuffer[] securityBuffer = new SecurityBuffer[2]; securityBuffer[0] = new SecurityBuffer(buffer, offset, count, SecurityBufferType.SECBUFFER_STREAM); securityBuffer[1] = new SecurityBuffer(0, SecurityBufferType.SECBUFFER_DATA); // call SSP function int errorCode = SSPIWrapper.VerifySignature( GlobalSSPI.SSPIAuth, securityContext, securityBuffer, 0); // throw if error if (errorCode != 0) { NetEventSource.Info($"VerifySignature threw error: {errorCode.ToString("x", NumberFormatInfo.InvariantInfo)}"); throw new Win32Exception(errorCode); } // not sure why this is here - retained from Encrypt code above if (securityBuffer[1].type != SecurityBufferType.SECBUFFER_DATA) throw new InternalException(); // return validated payload size return securityBuffer[1].size; } internal static int MakeSignature(SafeDeleteContext securityContext, byte[] buffer, int offset, int count, ref byte[] output) { SecPkgContext_Sizes sizes = SSPIWrapper.QueryContextAttributes( GlobalSSPI.SSPIAuth, securityContext, Interop.SspiCli.ContextAttribute.SECPKG_ATTR_SIZES ) as SecPkgContext_Sizes; // alloc new output buffer if not supplied or too small int resultSize = count + sizes.cbMaxSignature; if (output == null || output.Length < resultSize) { output = new byte[resultSize]; } // make a copy of user data for in-place encryption Buffer.BlockCopy(buffer, offset, output, sizes.cbMaxSignature, count); // setup security buffers for ssp call SecurityBuffer[] securityBuffer = new SecurityBuffer[2]; securityBuffer[0] = new SecurityBuffer(output, 0, sizes.cbMaxSignature, SecurityBufferType.SECBUFFER_TOKEN); securityBuffer[1] = new SecurityBuffer(output, sizes.cbMaxSignature, count, SecurityBufferType.SECBUFFER_DATA); // call SSP Function int errorCode = SSPIWrapper.MakeSignature(GlobalSSPI.SSPIAuth, securityContext, securityBuffer, 0); // throw if error if (errorCode != 0) { NetEventSource.Info($"MakeSignature threw error: {errorCode.ToString("x", NumberFormatInfo.InvariantInfo)}"); throw new Win32Exception(errorCode); } // return signed size return securityBuffer[0].size + securityBuffer[1].size; } } }
/* Copyright 2010 Google Inc Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Text; using Google.Apis.Discovery; using Google.Apis.Json; using Google.Apis.Requests; using Google.Apis.Testing; using Google.Apis.Util; using Newtonsoft.Json; using NUnit.Framework; using System.Linq; namespace Google.Apis.Tests.Apis.Discovery { /// <summary> /// Test for the "BaseService" class. /// </summary> [TestFixture] public class BaseServiceTest { private class ConcreteClass : BaseService { public ConcreteClass(JsonDictionary js) : base(ServiceFactory.Default, js, new ConcreteFactoryParameters()) { } public new string ServerUrl { get { return base.ServerUrl; } set { base.ServerUrl = value; } } public new string BasePath { get { return base.BasePath; } set { base.BasePath = value; } } #region Nested type: ConcreteFactoryParameters private class ConcreteFactoryParameters : FactoryParameters { public ConcreteFactoryParameters() : base("http://test/", "testService/") {} } #endregion } /// <summary> /// A Json schema for testing serialization/deserialization. /// </summary> internal class MockJsonSchema : IDirectResponseSchema { [JsonProperty("kind")] public string Kind { get; set; } [JsonProperty("longUrl")] public string LongURL { get; set; } [JsonProperty("status")] public string Status { get; set; } public RequestError Error { get; set; } public string ETag { get; set; } } #region Test Helper methods private void CheckDeserializationResults(MockJsonSchema result) { Assert.NotNull(result); Assert.That(result.Kind, Is.EqualTo("urlshortener#url")); Assert.That(result.LongURL, Is.EqualTo("http://google.com/")); Assert.That(result.Status, Is.Null); } private IService CreateService(DiscoveryVersion version) { return version == DiscoveryVersion.Version_0_3 ? CreateLegacyV03Service() : CreateV1Service(); } private IService CreateV1Service() { var dict = new JsonDictionary(); dict.Add("name", "TestName"); dict.Add("version", "v1"); return new ConcreteClass(dict); } private IService CreateLegacyV03Service() { var dict = new JsonDictionary(); dict.Add("name", "TestName"); dict.Add("version", "v1"); dict.Add("features", new[] { Features.LegacyDataResponse.GetStringValue() }); return new ConcreteClass(dict); } #endregion /// <summary> /// This tests the v0.3 Deserialization of the BaseService. /// </summary> [Test] public void TestDeserializationV0_3() { const string ResponseV0_3 = @"{ ""data"" : { ""kind"": ""urlshortener#url"", ""longUrl"": ""http://google.com/"", } }"; IService impl = CreateLegacyV03Service(); // Check that the default serializer is set. Assert.IsInstanceOf<NewtonsoftJsonSerializer>(impl.Serializer); // Check that the response is decoded correctly. var stream = new MemoryStream(Encoding.Default.GetBytes(ResponseV0_3)); var response = new MockResponse() { Stream = stream }; CheckDeserializationResults(impl.DeserializeResponse<MockJsonSchema>(response)); } /// <summary> /// This tests the v1 Deserialization of the BaseService. /// </summary> [Test] public void TestDeserializationV1() { const string ResponseV1 = @"{""kind"":""urlshortener#url"",""longUrl"":""http://google.com/""}"; IService impl = CreateV1Service(); // Check that the default serializer is set Assert.IsInstanceOf<NewtonsoftJsonSerializer>(impl.Serializer); // Check that the response is decoded correctly var stream = new MemoryStream(Encoding.Default.GetBytes(ResponseV1)); CheckDeserializationResults( impl.DeserializeResponse<MockJsonSchema>(new MockResponse() { Stream = stream })); } /// <summary> /// Confirms that the serializer won't do anything if a string is the requested response type. /// </summary> [Test] public void TestDeserializationString() { const string ResponseV1 = @"{""kind"":""urlshortener#url"",""longUrl"":""http://google.com/""}"; IService impl = CreateV1Service(); // Check that the response is decoded correctly var stream = new MemoryStream(Encoding.Default.GetBytes(ResponseV1)); string result = impl.DeserializeResponse<string>(new MockResponse() { Stream = stream }); Assert.AreEqual(ResponseV1, result); } /// <summary> /// Tests the deserialization for server error responses. /// </summary> [Test] public void TestErrorDeserialization( [Values(DiscoveryVersion.Version_0_3, DiscoveryVersion.Version_1_0)] DiscoveryVersion version) { const string ErrorResponse = @"{ ""error"": { ""errors"": [ { ""domain"": ""global"", ""reason"": ""required"", ""message"": ""Required"", ""locationType"": ""parameter"", ""location"": ""resource.longUrl"" } ], ""code"": 400, ""message"": ""Required"" } }"; IService impl = CreateService(version); using (var stream = new MemoryStream(Encoding.Default.GetBytes(ErrorResponse))) { // Verify that the response is decoded correctly. GoogleApiException ex = Assert.Throws<GoogleApiException>(() => { impl.DeserializeResponse<MockJsonSchema>(new MockResponse() { Stream = stream }); }); // Check that the contents of the error json was translated into the exception object. // We cannot compare the entire exception as it depends on the implementation and might change. Assert.That(ex.ToString(), Contains.Substring("resource.longUrl")); } using (var stream = new MemoryStream(Encoding.Default.GetBytes(ErrorResponse))) { RequestError error = impl.DeserializeError(new MockResponse() { Stream = stream }); Assert.AreEqual(400, error.Code); Assert.AreEqual("Required", error.Message); Assert.AreEqual(1, error.Errors.Count); } } /// <summary> /// This tests the "Features" extension of services. /// </summary> [Test] public void TestFeaturesV1() { IService impl = CreateV1Service(); Assert.NotNull(impl.Features); Assert.IsFalse(impl.HasFeature(Features.LegacyDataResponse)); } /// <summary> /// This test is designed to test the "Features" extension of services. /// </summary> [Test] public void TestFeaturesV03() { IService impl = CreateLegacyV03Service(); Assert.NotNull(impl.Features); Assert.IsTrue(impl.HasFeature(Features.LegacyDataResponse)); } /// <summary> /// This test confirms that the BaseService will not crash on non-existent, optional fields /// within the JSON document. /// </summary> [Test] public void TestNoThrowOnFieldsMissing() { IService impl = CreateV1Service(); Assert.AreEqual("v1", impl.Version); Assert.IsNull(impl.Id); Assert.IsNotNull(impl.Labels); MoreAsserts.IsEmpty(impl.Labels); Assert.AreEqual("TestName", impl.Name); Assert.IsNull(impl.Protocol); Assert.IsNull(impl.Title); } /// <summary> /// Tests if serialization works. /// </summary> [Test] public void TestSerializationV0_3() { const string ResponseV0_3 = "{\"data\":{\"kind\":\"urlshortener#url\",\"longUrl\":\"http://google.com/\"}}"; MockJsonSchema schema = new MockJsonSchema(); schema.Kind = "urlshortener#url"; schema.LongURL = "http://google.com/"; IService impl = CreateLegacyV03Service(); // Check if a response is serialized correctly string result = impl.SerializeRequest(schema); Assert.AreEqual(ResponseV0_3, result); } /// <summary> /// Tests if serialization works. /// </summary> [Test] public void TestSerializationV1() { const string ResponseV1 = @"{""kind"":""urlshortener#url"",""longUrl"":""http://google.com/""}"; MockJsonSchema schema = new MockJsonSchema(); schema.Kind = "urlshortener#url"; schema.LongURL = "http://google.com/"; IService impl = CreateV1Service(); // Check if a response is serialized correctly string result = impl.SerializeRequest(schema); Assert.AreEqual(ResponseV1, result); } /// <summary> /// The test targets the more basic properties of the BaseService. /// It should ensure that all properties return the values assigned to them within the JSON document. /// </summary> [Test] public void TestSimpleGetters() { var dict = new JsonDictionary(); dict.Add("name", "TestName"); dict.Add("version", "v1"); dict.Add("description", "Test Description"); dict.Add("documentationLink", "https://www.google.com/"); dict.Add("features", new List<object>{ "feature1", "feature2" }); dict.Add("labels", new List<object>{ "label1", "label2" }); dict.Add("id", "TestId"); dict.Add("title", "Test API"); IService impl = new ConcreteClass(dict); Assert.AreEqual("Test Description", impl.Description); Assert.AreEqual("https://www.google.com/", impl.DocumentationLink); MoreAsserts.ContentsEqualAndInOrder(new List<string> { "feature1", "feature2" }, impl.Features); MoreAsserts.ContentsEqualAndInOrder(new List<string> { "label1", "label2" }, impl.Labels); Assert.AreEqual("TestId", impl.Id); Assert.AreEqual("Test API", impl.Title); } /// <summary> /// Confirms that OAuth2 scopes can be parsed correctly. /// </summary> [Test] public void TestOAuth2Scopes() { var scopes = new JsonDictionary(); scopes.Add("https://www.example.com/auth/one", new Scope() { ID = "https://www.example.com/auth/one" }); scopes.Add("https://www.example.com/auth/two", new Scope() { ID = "https://www.example.com/auth/two" }); var oauth2 = new JsonDictionary() { { "scopes", scopes } }; var auth = new JsonDictionary() { { "oauth2", oauth2 } }; var dict = new JsonDictionary() { { "auth", auth }, { "name", "TestName" }, { "version", "v1" } }; IService impl = new ConcreteClass(dict); Assert.IsNotNull(impl.Scopes); Assert.AreEqual(2, impl.Scopes.Count); Assert.IsTrue(impl.Scopes.ContainsKey("https://www.example.com/auth/one")); Assert.IsTrue(impl.Scopes.ContainsKey("https://www.example.com/auth/two")); } /// <summary> /// Test that the Parameters property is initialized. /// </summary> [Test] public void TestCommonParameters() { const string testJson = @"{ 'fields': { 'type': 'string', 'description': 'Selector specifying which fields to include in a partial response.', 'location': 'query' }, 'prettyPrint': { 'type': 'boolean', 'description': 'Returns response with indentations and line breaks.', 'default': 'true', 'location': 'query' }, }"; var paramDict = Google.Apis.Json.JsonReader.Parse(testJson.Replace('\'', '\"')) as JsonDictionary; var dict = new JsonDictionary() { { "parameters", paramDict}, { "name", "TestName" }, { "version", "v1" } }; var impl = new ConcreteClass(dict); Assert.That(impl.Parameters.Count, Is.EqualTo(2)); Assert.That(impl.Parameters.Keys, Is.EquivalentTo(new string[] { "fields", "prettyPrint" })); var prettyPrint = impl.Parameters["prettyPrint"]; Assert.That(prettyPrint.Description, Is.EqualTo("Returns response with indentations and line breaks.")); Assert.That(prettyPrint.ValueType, Is.EqualTo("boolean")); } /// <summary> /// Test a service with empty parameters. /// </summary> [Test] public void TestCommonParametersEmpty() { var paramDict = new JsonDictionary(); var dict = new JsonDictionary() { { "parameters", paramDict }, { "name", "TestName" }, { "version", "v1" } }; var impl = new ConcreteClass(dict); Assert.That(impl.Parameters, Is.Not.Null); Assert.That(impl.Parameters.Count, Is.EqualTo(0)); } /// <summary> /// Test a service with no parameters /// </summary> [Test] public void TestCommonParametersMissing() { var paramDict = new JsonDictionary(); var dict = new JsonDictionary() { { "name", "TestName" }, { "version", "v1" } }; var impl = new ConcreteClass(dict); Assert.That(impl.Parameters, Is.Not.Null); Assert.That(impl.Parameters.Count, Is.EqualTo(0)); } /// <summary> /// Confirms that methods, which are directly on the service, are supported /// </summary> [Test] public void TestMethodsOnService() { var testMethod = new JsonDictionary(); testMethod.Add("id", "service.testMethod"); testMethod.Add("path", "service/testMethod"); testMethod.Add("httpMethod", "GET"); var methods = new JsonDictionary() { { "testMethod", testMethod } }; var dict = new JsonDictionary() { { "methods", methods }, { "name", "TestName" }, { "version", "v1" } }; IService impl = new ConcreteClass(dict); Assert.IsNotNull(impl.Methods); Assert.AreEqual(1, impl.Methods.Count); Assert.AreEqual("testMethod", impl.Methods["testMethod"].Name); } /// <summary> /// Tests the BaseResource.GetResource method. /// </summary> [Test] public void TestGetResource() { var container = CreateV1Service(); container.Resources.Clear(); // Create json. var subJson = new JsonDictionary(); subJson.Add("resources", new JsonDictionary { { "Grandchild", new JsonDictionary() } }); var topJson = new JsonDictionary(); topJson.Add("resources", new JsonDictionary { { "Sub", subJson } }); // Create the resource hierachy. var topResource = ServiceFactory.Default.CreateResource("Top", topJson); var subResource = topResource.Resources["Sub"]; var grandchildResource = subResource.Resources["Grandchild"]; container.Resources.Add("Top", topResource); // Check the generated full name. Assert.AreEqual(container.Methods, BaseService.GetResource(container, "").Methods); Assert.AreEqual(topResource, BaseService.GetResource(container, "Top")); Assert.AreEqual(subResource, BaseService.GetResource(container, "Top.Sub")); Assert.AreEqual(grandchildResource, BaseService.GetResource(container, "Top.Sub.Grandchild")); } [Test] public void TestBaseUri() { ConcreteClass instance = (ConcreteClass)CreateV1Service(); instance.BasePath = "/test/"; instance.ServerUrl = "https://www.test.value/"; Assert.AreEqual("https://www.test.value/test/", instance.BaseUri.ToString()); instance.BasePath = "test/"; instance.ServerUrl = "https://www.test.value/"; Assert.AreEqual("https://www.test.value/test/", instance.BaseUri.ToString()); instance.BasePath = "/test/"; instance.ServerUrl = "https://www.test.value"; Assert.AreEqual("https://www.test.value/test/", instance.BaseUri.ToString()); instance.BasePath = "test/"; instance.ServerUrl = "https://www.test.value"; Assert.AreEqual("https://www.test.value/test/", instance.BaseUri.ToString()); // Mono's Uri class strips double forward slashes so this test will not work. // Only run for MS.Net if ( Google.Apis.Util.Utilities.IsMonoRuntime() == false) { instance.BasePath = "//test/"; instance.ServerUrl = "https://www.test.value"; Assert.AreEqual("https://www.test.value//test/", instance.BaseUri.ToString()); instance.BasePath = "//test/"; instance.ServerUrl = "https://www.test.value/"; Assert.AreEqual("https://www.test.value//test/", instance.BaseUri.ToString()); instance.BasePath = "test/"; instance.ServerUrl = "https://www.test.value//"; Assert.AreEqual("https://www.test.value//test/", instance.BaseUri.ToString()); instance.BasePath = "/test//"; instance.ServerUrl = "https://www.test.value/"; Assert.AreEqual("https://www.test.value/test//", instance.BaseUri.ToString()); } } [Test] public void RemoveAnnotations() { string json = @" { 'schemas': { 'Event': { 'id': 'Event', 'type': 'object', 'properties': { 'description': { 'type': 'string', 'description': 'Description of the event. Optional.' }, 'end': { '$ref': 'EventDateTime', 'description': 'The (exclusive) end time of the event. For a recurring event, this is the end time of the first instance.', 'annotations': { 'required': [ 'calendar.events.import', 'calendar.events.insert', 'calendar.events.update' ] } }, } } } }"; JsonDictionary js = Google.Apis.Json.JsonReader.Parse(json) as JsonDictionary; var end = AssertNode(js, "schemas", "Event", "properties", "end"); Assert.That(end.Count, Is.EqualTo(3)); Assert.That(end.ContainsKey("annotations"), Is.True); BaseService.RemoveAnnotations(js, 0); Assert.That(end.Count, Is.EqualTo(2)); Assert.That(end.ContainsKey("annotations"), Is.False); } private JsonDictionary AssertNode(JsonDictionary dict, params string[] nodes) { JsonDictionary cur = dict; for(int i=0;i<nodes.Length;i++) { Assert.That(cur.ContainsKey(nodes[i])); Assert.That(cur[nodes[i]], Is.TypeOf(typeof(JsonDictionary))); cur = cur[nodes[i]] as JsonDictionary; } return cur; } } }
// 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: For writing text to streams in a particular ** encoding. ** ** ===========================================================*/ using System; using System.Text; using System.Threading; using System.Globalization; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Security.Permissions; using System.Runtime.Serialization; using System.Diagnostics.Contracts; using System.Runtime.InteropServices; using System.Threading.Tasks; namespace System.IO { // This class implements a TextWriter for writing characters to a Stream. // This is designed for character output in a particular Encoding, // whereas the Stream class is designed for byte input and output. // [Serializable] [ComVisible(true)] public class StreamWriter : TextWriter { // For UTF-8, the values of 1K for the default buffer size and 4K for the // file stream buffer size are reasonable & give very reasonable // performance for in terms of construction time for the StreamWriter and // write perf. Note that for UTF-8, we end up allocating a 4K byte buffer, // which means we take advantage of adaptive buffering code. // The performance using UnicodeEncoding is acceptable. internal const int DefaultBufferSize = 1024; // char[] private const int DefaultFileStreamBufferSize = 4096; private const int MinBufferSize = 128; private const Int32 DontCopyOnWriteLineThreshold = 512; // Bit bucket - Null has no backing store. Non closable. public new static readonly StreamWriter Null = new StreamWriter(Stream.Null, new UTF8Encoding(false, true), MinBufferSize, true); private Stream stream; private Encoding encoding; private Encoder encoder; private byte[] byteBuffer; private char[] charBuffer; private int charPos; private int charLen; private bool autoFlush; private bool haveWrittenPreamble; private bool closable; #if MDA_SUPPORTED [NonSerialized] // For StreamWriterBufferedDataLost MDA private MdaHelper mdaHelper; #endif // We don't guarantee thread safety on StreamWriter, but we should at // least prevent users from trying to write anything while an Async // write from the same thread is in progress. [NonSerialized] private volatile Task _asyncWriteTask; private void CheckAsyncTaskInProgress() { // We are not locking the access to _asyncWriteTask because this is not meant to guarantee thread safety. // We are simply trying to deter calling any Write APIs while an async Write from the same thread is in progress. Task t = _asyncWriteTask; if (t != null && !t.IsCompleted) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_AsyncIOInProgress")); } // The high level goal is to be tolerant of encoding errors when we read and very strict // when we write. Hence, default StreamWriter encoding will throw on encoding error. // Note: when StreamWriter throws on invalid encoding chars (for ex, high surrogate character // D800-DBFF without a following low surrogate character DC00-DFFF), it will cause the // internal StreamWriter's state to be irrecoverable as it would have buffered the // illegal chars and any subsequent call to Flush() would hit the encoding error again. // Even Close() will hit the exception as it would try to flush the unwritten data. // Maybe we can add a DiscardBufferedData() method to get out of such situation (like // StreamReader though for different reason). Either way, the buffered data will be lost! private static volatile Encoding _UTF8NoBOM; internal static Encoding UTF8NoBOM { [FriendAccessAllowed] get { if (_UTF8NoBOM == null) { // No need for double lock - we just want to avoid extra // allocations in the common case. UTF8Encoding noBOM = new UTF8Encoding(false, true); Thread.MemoryBarrier(); _UTF8NoBOM = noBOM; } return _UTF8NoBOM; } } internal StreamWriter(): base(null) { // Ask for CurrentCulture all the time } public StreamWriter(Stream stream) : this(stream, UTF8NoBOM, DefaultBufferSize, false) { } public StreamWriter(Stream stream, Encoding encoding) : this(stream, encoding, DefaultBufferSize, false) { } // Creates a new StreamWriter for the given stream. The // character encoding is set by encoding and the buffer size, // in number of 16-bit characters, is set by bufferSize. // public StreamWriter(Stream stream, Encoding encoding, int bufferSize) : this(stream, encoding, bufferSize, false) { } public StreamWriter(Stream stream, Encoding encoding, int bufferSize, bool leaveOpen) : base(null) // Ask for CurrentCulture all the time { if (stream == null || encoding == null) throw new ArgumentNullException((stream == null ? "stream" : "encoding")); if (!stream.CanWrite) throw new ArgumentException(Environment.GetResourceString("Argument_StreamNotWritable")); if (bufferSize <= 0) throw new ArgumentOutOfRangeException("bufferSize", Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum")); Contract.EndContractBlock(); Init(stream, encoding, bufferSize, leaveOpen); } public StreamWriter(String path) : this(path, false, UTF8NoBOM, DefaultBufferSize) { } public StreamWriter(String path, bool append) : this(path, append, UTF8NoBOM, DefaultBufferSize) { } public StreamWriter(String path, bool append, Encoding encoding) : this(path, append, encoding, DefaultBufferSize) { } [System.Security.SecuritySafeCritical] public StreamWriter(String path, bool append, Encoding encoding, int bufferSize): this(path, append, encoding, bufferSize, true) { } [System.Security.SecurityCritical] internal StreamWriter(String path, bool append, Encoding encoding, int bufferSize, bool checkHost) : base(null) { // Ask for CurrentCulture all the time if (path == null) throw new ArgumentNullException("path"); if (encoding == null) throw new ArgumentNullException("encoding"); if (path.Length == 0) throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath")); if (bufferSize <= 0) throw new ArgumentOutOfRangeException("bufferSize", Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum")); Contract.EndContractBlock(); Stream stream = CreateFile(path, append, checkHost); Init(stream, encoding, bufferSize, false); } [System.Security.SecuritySafeCritical] private void Init(Stream streamArg, Encoding encodingArg, int bufferSize, bool shouldLeaveOpen) { this.stream = streamArg; this.encoding = encodingArg; this.encoder = encoding.GetEncoder(); if (bufferSize < MinBufferSize) bufferSize = MinBufferSize; charBuffer = new char[bufferSize]; byteBuffer = new byte[encoding.GetMaxByteCount(bufferSize)]; charLen = bufferSize; // If we're appending to a Stream that already has data, don't write // the preamble. if (stream.CanSeek && stream.Position > 0) haveWrittenPreamble = true; closable = !shouldLeaveOpen; #if MDA_SUPPORTED if (Mda.StreamWriterBufferedDataLost.Enabled) { String callstack = null; if (Mda.StreamWriterBufferedDataLost.CaptureAllocatedCallStack) callstack = Environment.GetStackTrace(null, false); mdaHelper = new MdaHelper(this, callstack); } #endif } [System.Security.SecurityCritical] private static Stream CreateFile(String path, bool append, bool checkHost) { FileMode mode = append? FileMode.Append: FileMode.Create; FileStream f = new FileStream(path, mode, FileAccess.Write, FileShare.Read, DefaultFileStreamBufferSize, FileOptions.SequentialScan, Path.GetFileName(path), false, false, checkHost); return f; } public override void Close() { Dispose(true); GC.SuppressFinalize(this); } protected override void Dispose(bool disposing) { try { // We need to flush any buffered data if we are being closed/disposed. // Also, we never close the handles for stdout & friends. So we can safely // write any buffered data to those streams even during finalization, which // is generally the right thing to do. if (stream != null) { // Note: flush on the underlying stream can throw (ex., low disk space) if (disposing || (LeaveOpen && stream is __ConsoleStream)) { CheckAsyncTaskInProgress(); Flush(true, true); #if MDA_SUPPORTED // Disable buffered data loss mda if (mdaHelper != null) GC.SuppressFinalize(mdaHelper); #endif } } } finally { // Dispose of our resources if this StreamWriter is closable. // Note: Console.Out and other such non closable streamwriters should be left alone if (!LeaveOpen && stream != null) { try { // Attempt to close the stream even if there was an IO error from Flushing. // Note that Stream.Close() can potentially throw here (may or may not be // due to the same Flush error). In this case, we still need to ensure // cleaning up internal resources, hence the finally block. if (disposing) stream.Close(); } finally { stream = null; byteBuffer = null; charBuffer = null; encoding = null; encoder = null; charLen = 0; base.Dispose(disposing); } } } } public override void Flush() { CheckAsyncTaskInProgress(); Flush(true, true); } private void Flush(bool flushStream, bool flushEncoder) { // flushEncoder should be true at the end of the file and if // the user explicitly calls Flush (though not if AutoFlush is true). // This is required to flush any dangling characters from our UTF-7 // and UTF-8 encoders. if (stream == null) __Error.WriterClosed(); // Perf boost for Flush on non-dirty writers. if (charPos==0 && (!flushStream && !flushEncoder)) return; if (!haveWrittenPreamble) { haveWrittenPreamble = true; byte[] preamble = encoding.GetPreamble(); if (preamble.Length > 0) stream.Write(preamble, 0, preamble.Length); } int count = encoder.GetBytes(charBuffer, 0, charPos, byteBuffer, 0, flushEncoder); charPos = 0; if (count > 0) stream.Write(byteBuffer, 0, count); // By definition, calling Flush should flush the stream, but this is // only necessary if we passed in true for flushStream. The Web // Services guys have some perf tests where flushing needlessly hurts. if (flushStream) stream.Flush(); } public virtual bool AutoFlush { get { return autoFlush; } set { CheckAsyncTaskInProgress(); autoFlush = value; if (value) Flush(true, false); } } public virtual Stream BaseStream { get { return stream; } } internal bool LeaveOpen { get { return !closable; } } internal bool HaveWrittenPreamble { set { haveWrittenPreamble= value; } } public override Encoding Encoding { get { return encoding; } } public override void Write(char value) { CheckAsyncTaskInProgress(); if (charPos == charLen) Flush(false, false); charBuffer[charPos] = value; charPos++; if (autoFlush) Flush(true, false); } public override void Write(char[] buffer) { // This may be faster than the one with the index & count since it // has to do less argument checking. if (buffer==null) return; CheckAsyncTaskInProgress(); int index = 0; int count = buffer.Length; while (count > 0) { if (charPos == charLen) Flush(false, false); int n = charLen - charPos; if (n > count) n = count; Contract.Assert(n > 0, "StreamWriter::Write(char[]) isn't making progress! This is most likely a race condition in user code."); Buffer.InternalBlockCopy(buffer, index * sizeof(char), charBuffer, charPos * sizeof(char), n * sizeof(char)); charPos += n; index += n; count -= n; } if (autoFlush) Flush(true, false); } public override void Write(char[] buffer, int index, int count) { if (buffer==null) throw new ArgumentNullException("buffer", Environment.GetResourceString("ArgumentNull_Buffer")); if (index < 0) throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (count < 0) throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (buffer.Length - index < count) throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen")); Contract.EndContractBlock(); CheckAsyncTaskInProgress(); while (count > 0) { if (charPos == charLen) Flush(false, false); int n = charLen - charPos; if (n > count) n = count; Contract.Assert(n > 0, "StreamWriter::Write(char[], int, int) isn't making progress! This is most likely a race condition in user code."); Buffer.InternalBlockCopy(buffer, index * sizeof(char), charBuffer, charPos * sizeof(char), n * sizeof(char)); charPos += n; index += n; count -= n; } if (autoFlush) Flush(true, false); } public override void Write(String value) { if (value != null) { CheckAsyncTaskInProgress(); int count = value.Length; int index = 0; while (count > 0) { if (charPos == charLen) Flush(false, false); int n = charLen - charPos; if (n > count) n = count; Contract.Assert(n > 0, "StreamWriter::Write(String) isn't making progress! This is most likely a race condition in user code."); value.CopyTo(index, charBuffer, charPos, n); charPos += n; index += n; count -= n; } if (autoFlush) Flush(true, false); } } #region Task based Async APIs [HostProtection(ExternalThreading = true)] [ComVisible(false)] public override Task WriteAsync(char value) { // If we have been inherited into a subclass, the following implementation could be incorrect // since it does not call through to Write() which a subclass might have overriden. // To be safe we will only use this implementation in cases where we know it is safe to do so, // and delegate to our base class (which will call into Write) when we are not sure. if (this.GetType() != typeof(StreamWriter)) return base.WriteAsync(value); if (stream == null) __Error.WriterClosed(); CheckAsyncTaskInProgress(); Task task = WriteAsyncInternal(this, value, charBuffer, charPos, charLen, CoreNewLine, autoFlush, appendNewLine: false); _asyncWriteTask = task; return task; } // We pass in private instance fields of this MarshalByRefObject-derived type as local params // to ensure performant access inside the state machine that corresponds this async method. // Fields that are written to must be assigned at the end of the method *and* before instance invocations. private static async Task WriteAsyncInternal(StreamWriter _this, Char value, Char[] charBuffer, Int32 charPos, Int32 charLen, Char[] coreNewLine, bool autoFlush, bool appendNewLine) { if (charPos == charLen) { await _this.FlushAsyncInternal(false, false, charBuffer, charPos).ConfigureAwait(false); Contract.Assert(_this.charPos == 0); charPos = 0; } charBuffer[charPos] = value; charPos++; if (appendNewLine) { for (Int32 i = 0; i < coreNewLine.Length; i++) // Expect 2 iterations, no point calling BlockCopy { if (charPos == charLen) { await _this.FlushAsyncInternal(false, false, charBuffer, charPos).ConfigureAwait(false); Contract.Assert(_this.charPos == 0); charPos = 0; } charBuffer[charPos] = coreNewLine[i]; charPos++; } } if (autoFlush) { await _this.FlushAsyncInternal(true, false, charBuffer, charPos).ConfigureAwait(false); Contract.Assert(_this.charPos == 0); charPos = 0; } _this.CharPos_Prop = charPos; } [HostProtection(ExternalThreading = true)] [ComVisible(false)] public override Task WriteAsync(String value) { // If we have been inherited into a subclass, the following implementation could be incorrect // since it does not call through to Write() which a subclass might have overriden. // To be safe we will only use this implementation in cases where we know it is safe to do so, // and delegate to our base class (which will call into Write) when we are not sure. if (this.GetType() != typeof(StreamWriter)) return base.WriteAsync(value); if (value != null) { if (stream == null) __Error.WriterClosed(); CheckAsyncTaskInProgress(); Task task = WriteAsyncInternal(this, value, charBuffer, charPos, charLen, CoreNewLine, autoFlush, appendNewLine: false); _asyncWriteTask = task; return task; } else { return Task.CompletedTask; } } // We pass in private instance fields of this MarshalByRefObject-derived type as local params // to ensure performant access inside the state machine that corresponds this async method. // Fields that are written to must be assigned at the end of the method *and* before instance invocations. private static async Task WriteAsyncInternal(StreamWriter _this, String value, Char[] charBuffer, Int32 charPos, Int32 charLen, Char[] coreNewLine, bool autoFlush, bool appendNewLine) { Contract.Requires(value != null); int count = value.Length; int index = 0; while (count > 0) { if (charPos == charLen) { await _this.FlushAsyncInternal(false, false, charBuffer, charPos).ConfigureAwait(false); Contract.Assert(_this.charPos == 0); charPos = 0; } int n = charLen - charPos; if (n > count) n = count; Contract.Assert(n > 0, "StreamWriter::Write(String) isn't making progress! This is most likely a race condition in user code."); value.CopyTo(index, charBuffer, charPos, n); charPos += n; index += n; count -= n; } if (appendNewLine) { for (Int32 i = 0; i < coreNewLine.Length; i++) // Expect 2 iterations, no point calling BlockCopy { if (charPos == charLen) { await _this.FlushAsyncInternal(false, false, charBuffer, charPos).ConfigureAwait(false); Contract.Assert(_this.charPos == 0); charPos = 0; } charBuffer[charPos] = coreNewLine[i]; charPos++; } } if (autoFlush) { await _this.FlushAsyncInternal(true, false, charBuffer, charPos).ConfigureAwait(false); Contract.Assert(_this.charPos == 0); charPos = 0; } _this.CharPos_Prop = charPos; } [HostProtection(ExternalThreading = true)] [ComVisible(false)] public override Task WriteAsync(char[] buffer, int index, int count) { if (buffer==null) throw new ArgumentNullException("buffer", Environment.GetResourceString("ArgumentNull_Buffer")); if (index < 0) throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (count < 0) throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (buffer.Length - index < count) throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen")); Contract.EndContractBlock(); // If we have been inherited into a subclass, the following implementation could be incorrect // since it does not call through to Write() which a subclass might have overriden. // To be safe we will only use this implementation in cases where we know it is safe to do so, // and delegate to our base class (which will call into Write) when we are not sure. if (this.GetType() != typeof(StreamWriter)) return base.WriteAsync(buffer, index, count); if (stream == null) __Error.WriterClosed(); CheckAsyncTaskInProgress(); Task task = WriteAsyncInternal(this, buffer, index, count, charBuffer, charPos, charLen, CoreNewLine, autoFlush, appendNewLine: false); _asyncWriteTask = task; return task; } // We pass in private instance fields of this MarshalByRefObject-derived type as local params // to ensure performant access inside the state machine that corresponds this async method. // Fields that are written to must be assigned at the end of the method *and* before instance invocations. private static async Task WriteAsyncInternal(StreamWriter _this, Char[] buffer, Int32 index, Int32 count, Char[] charBuffer, Int32 charPos, Int32 charLen, Char[] coreNewLine, bool autoFlush, bool appendNewLine) { Contract.Requires(count == 0 || (count > 0 && buffer != null)); Contract.Requires(index >= 0); Contract.Requires(count >= 0); Contract.Requires(buffer == null || (buffer != null && buffer.Length - index >= count)); while (count > 0) { if (charPos == charLen) { await _this.FlushAsyncInternal(false, false, charBuffer, charPos).ConfigureAwait(false); Contract.Assert(_this.charPos == 0); charPos = 0; } int n = charLen - charPos; if (n > count) n = count; Contract.Assert(n > 0, "StreamWriter::Write(char[], int, int) isn't making progress! This is most likely a race condition in user code."); Buffer.InternalBlockCopy(buffer, index * sizeof(char), charBuffer, charPos * sizeof(char), n * sizeof(char)); charPos += n; index += n; count -= n; } if (appendNewLine) { for (Int32 i = 0; i < coreNewLine.Length; i++) // Expect 2 iterations, no point calling BlockCopy { if (charPos == charLen) { await _this.FlushAsyncInternal(false, false, charBuffer, charPos).ConfigureAwait(false); Contract.Assert(_this.charPos == 0); charPos = 0; } charBuffer[charPos] = coreNewLine[i]; charPos++; } } if (autoFlush) { await _this.FlushAsyncInternal(true, false, charBuffer, charPos).ConfigureAwait(false); Contract.Assert(_this.charPos == 0); charPos = 0; } _this.CharPos_Prop = charPos; } [HostProtection(ExternalThreading = true)] [ComVisible(false)] public override Task WriteLineAsync() { // If we have been inherited into a subclass, the following implementation could be incorrect // since it does not call through to Write() which a subclass might have overriden. // To be safe we will only use this implementation in cases where we know it is safe to do so, // and delegate to our base class (which will call into Write) when we are not sure. if (this.GetType() != typeof(StreamWriter)) return base.WriteLineAsync(); if (stream == null) __Error.WriterClosed(); CheckAsyncTaskInProgress(); Task task = WriteAsyncInternal(this, null, 0, 0, charBuffer, charPos, charLen, CoreNewLine, autoFlush, appendNewLine: true); _asyncWriteTask = task; return task; } [HostProtection(ExternalThreading = true)] [ComVisible(false)] public override Task WriteLineAsync(char value) { // If we have been inherited into a subclass, the following implementation could be incorrect // since it does not call through to Write() which a subclass might have overriden. // To be safe we will only use this implementation in cases where we know it is safe to do so, // and delegate to our base class (which will call into Write) when we are not sure. if (this.GetType() != typeof(StreamWriter)) return base.WriteLineAsync(value); if (stream == null) __Error.WriterClosed(); CheckAsyncTaskInProgress(); Task task = WriteAsyncInternal(this, value, charBuffer, charPos, charLen, CoreNewLine, autoFlush, appendNewLine: true); _asyncWriteTask = task; return task; } [HostProtection(ExternalThreading = true)] [ComVisible(false)] public override Task WriteLineAsync(String value) { // If we have been inherited into a subclass, the following implementation could be incorrect // since it does not call through to Write() which a subclass might have overriden. // To be safe we will only use this implementation in cases where we know it is safe to do so, // and delegate to our base class (which will call into Write) when we are not sure. if (this.GetType() != typeof(StreamWriter)) return base.WriteLineAsync(value); if (stream == null) __Error.WriterClosed(); CheckAsyncTaskInProgress(); Task task = WriteAsyncInternal(this, value, charBuffer, charPos, charLen, CoreNewLine, autoFlush, appendNewLine: true); _asyncWriteTask = task; return task; } [HostProtection(ExternalThreading = true)] [ComVisible(false)] public override Task WriteLineAsync(char[] buffer, int index, int count) { if (buffer==null) throw new ArgumentNullException("buffer", Environment.GetResourceString("ArgumentNull_Buffer")); if (index < 0) throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (count < 0) throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (buffer.Length - index < count) throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen")); Contract.EndContractBlock(); // If we have been inherited into a subclass, the following implementation could be incorrect // since it does not call through to Write() which a subclass might have overriden. // To be safe we will only use this implementation in cases where we know it is safe to do so, // and delegate to our base class (which will call into Write) when we are not sure. if (this.GetType() != typeof(StreamWriter)) return base.WriteLineAsync(buffer, index, count); if (stream == null) __Error.WriterClosed(); CheckAsyncTaskInProgress(); Task task = WriteAsyncInternal(this, buffer, index, count, charBuffer, charPos, charLen, CoreNewLine, autoFlush, appendNewLine: true); _asyncWriteTask = task; return task; } [HostProtection(ExternalThreading = true)] [ComVisible(false)] public override Task FlushAsync() { // If we have been inherited into a subclass, the following implementation could be incorrect // since it does not call through to Flush() which a subclass might have overriden. To be safe // we will only use this implementation in cases where we know it is safe to do so, // and delegate to our base class (which will call into Flush) when we are not sure. if (this.GetType() != typeof(StreamWriter)) return base.FlushAsync(); // flushEncoder should be true at the end of the file and if // the user explicitly calls Flush (though not if AutoFlush is true). // This is required to flush any dangling characters from our UTF-7 // and UTF-8 encoders. if (stream == null) __Error.WriterClosed(); CheckAsyncTaskInProgress(); Task task = FlushAsyncInternal(true, true, charBuffer, charPos); _asyncWriteTask = task; return task; } private Int32 CharPos_Prop { set { this.charPos = value; } } private bool HaveWrittenPreamble_Prop { set { this.haveWrittenPreamble = value; } } private Task FlushAsyncInternal(bool flushStream, bool flushEncoder, Char[] sCharBuffer, Int32 sCharPos) { // Perf boost for Flush on non-dirty writers. if (sCharPos == 0 && !flushStream && !flushEncoder) return Task.CompletedTask; Task flushTask = FlushAsyncInternal(this, flushStream, flushEncoder, sCharBuffer, sCharPos, this.haveWrittenPreamble, this.encoding, this.encoder, this.byteBuffer, this.stream); this.charPos = 0; return flushTask; } // We pass in private instance fields of this MarshalByRefObject-derived type as local params // to ensure performant access inside the state machine that corresponds this async method. private static async Task FlushAsyncInternal(StreamWriter _this, bool flushStream, bool flushEncoder, Char[] charBuffer, Int32 charPos, bool haveWrittenPreamble, Encoding encoding, Encoder encoder, Byte[] byteBuffer, Stream stream) { if (!haveWrittenPreamble) { _this.HaveWrittenPreamble_Prop = true; byte[] preamble = encoding.GetPreamble(); if (preamble.Length > 0) await stream.WriteAsync(preamble, 0, preamble.Length).ConfigureAwait(false); } int count = encoder.GetBytes(charBuffer, 0, charPos, byteBuffer, 0, flushEncoder); if (count > 0) await stream.WriteAsync(byteBuffer, 0, count).ConfigureAwait(false); // By definition, calling Flush should flush the stream, but this is // only necessary if we passed in true for flushStream. The Web // Services guys have some perf tests where flushing needlessly hurts. if (flushStream) await stream.FlushAsync().ConfigureAwait(false); } #endregion #if MDA_SUPPORTED // StreamWriterBufferedDataLost MDA // Instead of adding a finalizer to StreamWriter for detecting buffered data loss // (ie, when the user forgets to call Close/Flush on the StreamWriter), we will // have a separate object with normal finalization semantics that maintains a // back pointer to this StreamWriter and alerts about any data loss private sealed class MdaHelper { private StreamWriter streamWriter; private String allocatedCallstack; // captures the callstack when this streamwriter was allocated internal MdaHelper(StreamWriter sw, String cs) { streamWriter = sw; allocatedCallstack = cs; } // Finalizer ~MdaHelper() { // Make sure people closed this StreamWriter, exclude StreamWriter::Null. if (streamWriter.charPos != 0 && streamWriter.stream != null && streamWriter.stream != Stream.Null) { String fileName = (streamWriter.stream is FileStream) ? ((FileStream)streamWriter.stream).NameInternal : "<unknown>"; String callStack = allocatedCallstack; if (callStack == null) callStack = Environment.GetResourceString("IO_StreamWriterBufferedDataLostCaptureAllocatedFromCallstackNotEnabled"); String message = Environment.GetResourceString("IO_StreamWriterBufferedDataLost", streamWriter.stream.GetType().FullName, fileName, callStack); Mda.StreamWriterBufferedDataLost.ReportError(message); } } } // class MdaHelper #endif // MDA_SUPPORTED } // class StreamWriter } // namespace
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // // ConcatQueryOperator.cs // // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using System.Collections.Generic; using System.Diagnostics; using System.Threading; namespace System.Linq.Parallel { /// <summary> /// Concatenates one data source with another. Order preservation is used to ensure /// the output is actually a concatenation -- i.e. one after the other. The only /// special synchronization required is to find the largest index N in the first data /// source so that the indices of elements in the second data source can be offset /// by adding N+1. This makes it appear to the order preservation infrastructure as /// though all elements in the second came after all elements in the first, which is /// precisely what we want. /// </summary> /// <typeparam name="TSource"></typeparam> internal sealed class ConcatQueryOperator<TSource> : BinaryQueryOperator<TSource, TSource, TSource> { private readonly bool _prematureMergeLeft = false; // Whether to prematurely merge the left data source private readonly bool _prematureMergeRight = false; // Whether to prematurely merge the right data source //--------------------------------------------------------------------------------------- // Initializes a new concatenation operator. // // Arguments: // child - the child whose data we will reverse // internal ConcatQueryOperator(ParallelQuery<TSource> firstChild, ParallelQuery<TSource> secondChild) : base(firstChild, secondChild) { Debug.Assert(firstChild != null, "first child data source cannot be null"); Debug.Assert(secondChild != null, "second child data source cannot be null"); _outputOrdered = LeftChild.OutputOrdered || RightChild.OutputOrdered; _prematureMergeLeft = LeftChild.OrdinalIndexState.IsWorseThan(OrdinalIndexState.Increasing); _prematureMergeRight = RightChild.OrdinalIndexState.IsWorseThan(OrdinalIndexState.Increasing); if ((LeftChild.OrdinalIndexState == OrdinalIndexState.Indexable) && (RightChild.OrdinalIndexState == OrdinalIndexState.Indexable)) { SetOrdinalIndex(OrdinalIndexState.Indexable); } else { SetOrdinalIndex( ExchangeUtilities.Worse(OrdinalIndexState.Increasing, ExchangeUtilities.Worse(LeftChild.OrdinalIndexState, RightChild.OrdinalIndexState))); } } //--------------------------------------------------------------------------------------- // Just opens the current operator, including opening the child and wrapping it with // partitions as needed. // internal override QueryResults<TSource> Open(QuerySettings settings, bool preferStriping) { // We just open the children operators. QueryResults<TSource> leftChildResults = LeftChild.Open(settings, preferStriping); QueryResults<TSource> rightChildResults = RightChild.Open(settings, preferStriping); return ConcatQueryOperatorResults.NewResults(leftChildResults, rightChildResults, this, settings, preferStriping); } public override void WrapPartitionedStream<TLeftKey, TRightKey>( PartitionedStream<TSource, TLeftKey> leftStream, PartitionedStream<TSource, TRightKey> rightStream, IPartitionedStreamRecipient<TSource> outputRecipient, bool preferStriping, QuerySettings settings) { // Prematurely merge the left results, if necessary if (_prematureMergeLeft) { ListQueryResults<TSource> leftStreamResults = ExecuteAndCollectResults(leftStream, leftStream.PartitionCount, LeftChild.OutputOrdered, preferStriping, settings); PartitionedStream<TSource, int> leftStreamInc = leftStreamResults.GetPartitionedStream(); WrapHelper<int, TRightKey>(leftStreamInc, rightStream, outputRecipient, settings, preferStriping); } else { Debug.Assert(!ExchangeUtilities.IsWorseThan(leftStream.OrdinalIndexState, OrdinalIndexState.Increasing)); WrapHelper<TLeftKey, TRightKey>(leftStream, rightStream, outputRecipient, settings, preferStriping); } } private void WrapHelper<TLeftKey, TRightKey>( PartitionedStream<TSource, TLeftKey> leftStreamInc, PartitionedStream<TSource, TRightKey> rightStream, IPartitionedStreamRecipient<TSource> outputRecipient, QuerySettings settings, bool preferStriping) { // Prematurely merge the right results, if necessary if (_prematureMergeRight) { ListQueryResults<TSource> rightStreamResults = ExecuteAndCollectResults(rightStream, leftStreamInc.PartitionCount, LeftChild.OutputOrdered, preferStriping, settings); PartitionedStream<TSource, int> rightStreamInc = rightStreamResults.GetPartitionedStream(); WrapHelper2<TLeftKey, int>(leftStreamInc, rightStreamInc, outputRecipient); } else { Debug.Assert(!ExchangeUtilities.IsWorseThan(rightStream.OrdinalIndexState, OrdinalIndexState.Increasing)); WrapHelper2<TLeftKey, TRightKey>(leftStreamInc, rightStream, outputRecipient); } } private void WrapHelper2<TLeftKey, TRightKey>( PartitionedStream<TSource, TLeftKey> leftStreamInc, PartitionedStream<TSource, TRightKey> rightStreamInc, IPartitionedStreamRecipient<TSource> outputRecipient) { int partitionCount = leftStreamInc.PartitionCount; // Generate the shared data. IComparer<ConcatKey<TLeftKey, TRightKey>> comparer = ConcatKey<TLeftKey, TRightKey>.MakeComparer( leftStreamInc.KeyComparer, rightStreamInc.KeyComparer); var outputStream = new PartitionedStream<TSource, ConcatKey<TLeftKey, TRightKey>>(partitionCount, comparer, OrdinalIndexState); for (int i = 0; i < partitionCount; i++) { outputStream[i] = new ConcatQueryOperatorEnumerator<TLeftKey, TRightKey>(leftStreamInc[i], rightStreamInc[i]); } outputRecipient.Receive(outputStream); } //--------------------------------------------------------------------------------------- // Returns an enumerable that represents the query executing sequentially. // internal override IEnumerable<TSource> AsSequentialQuery(CancellationToken token) { return LeftChild.AsSequentialQuery(token).Concat(RightChild.AsSequentialQuery(token)); } //--------------------------------------------------------------------------------------- // Whether this operator performs a premature merge that would not be performed in // a similar sequential operation (i.e., in LINQ to Objects). // internal override bool LimitsParallelism { get { return false; } } //--------------------------------------------------------------------------------------- // The enumerator type responsible for concatenating two data sources. // private sealed class ConcatQueryOperatorEnumerator<TLeftKey, TRightKey> : QueryOperatorEnumerator<TSource, ConcatKey<TLeftKey, TRightKey>> { private readonly QueryOperatorEnumerator<TSource, TLeftKey> _firstSource; // The first data source to enumerate. private readonly QueryOperatorEnumerator<TSource, TRightKey> _secondSource; // The second data source to enumerate. private bool _begunSecond; // Whether this partition has begun enumerating the second source yet. //--------------------------------------------------------------------------------------- // Instantiates a new select enumerator. // internal ConcatQueryOperatorEnumerator( QueryOperatorEnumerator<TSource, TLeftKey> firstSource, QueryOperatorEnumerator<TSource, TRightKey> secondSource) { Debug.Assert(firstSource != null); Debug.Assert(secondSource != null); _firstSource = firstSource; _secondSource = secondSource; } //--------------------------------------------------------------------------------------- // MoveNext advances to the next element in the output. While the first data source has // elements, this consists of just advancing through it. After this, all partitions must // synchronize at a barrier and publish the maximum index N. Finally, all partitions can // move on to the second data source, adding N+1 to indices in order to get the correct // index offset. // internal override bool MoveNext(ref TSource currentElement, ref ConcatKey<TLeftKey, TRightKey> currentKey) { Debug.Assert(_firstSource != null); Debug.Assert(_secondSource != null); // If we are still enumerating the first source, fetch the next item. if (!_begunSecond) { // If elements remain, just return true and continue enumerating the left. TLeftKey leftKey = default(TLeftKey); if (_firstSource.MoveNext(ref currentElement, ref leftKey)) { currentKey = ConcatKey<TLeftKey, TRightKey>.MakeLeft(leftKey); return true; } _begunSecond = true; } // Now either move on to, or continue, enumerating the right data source. TRightKey rightKey = default(TRightKey); if (_secondSource.MoveNext(ref currentElement, ref rightKey)) { currentKey = ConcatKey<TLeftKey, TRightKey>.MakeRight(rightKey); return true; } return false; } protected override void Dispose(bool disposing) { _firstSource.Dispose(); _secondSource.Dispose(); } } //----------------------------------------------------------------------------------- // Query results for a Concat operator. The results are indexable if the child // results were indexable. // private class ConcatQueryOperatorResults : BinaryQueryOperatorResults { private readonly int _leftChildCount; // The number of elements in the left child result set private readonly int _rightChildCount; // The number of elements in the right child result set public static QueryResults<TSource> NewResults( QueryResults<TSource> leftChildQueryResults, QueryResults<TSource> rightChildQueryResults, ConcatQueryOperator<TSource> op, QuerySettings settings, bool preferStriping) { if (leftChildQueryResults.IsIndexible && rightChildQueryResults.IsIndexible) { return new ConcatQueryOperatorResults( leftChildQueryResults, rightChildQueryResults, op, settings, preferStriping); } else { return new BinaryQueryOperatorResults( leftChildQueryResults, rightChildQueryResults, op, settings, preferStriping); } } private ConcatQueryOperatorResults( QueryResults<TSource> leftChildQueryResults, QueryResults<TSource> rightChildQueryResults, ConcatQueryOperator<TSource> concatOp, QuerySettings settings, bool preferStriping) : base(leftChildQueryResults, rightChildQueryResults, concatOp, settings, preferStriping) { Debug.Assert(leftChildQueryResults.IsIndexible && rightChildQueryResults.IsIndexible); _leftChildCount = leftChildQueryResults.ElementsCount; _rightChildCount = rightChildQueryResults.ElementsCount; } internal override bool IsIndexible { get { return true; } } internal override int ElementsCount { get { Debug.Assert(_leftChildCount >= 0 && _rightChildCount >= 0); return _leftChildCount + _rightChildCount; } } internal override TSource GetElement(int index) { if (index < _leftChildCount) { return _leftChildQueryResults.GetElement(index); } else { return _rightChildQueryResults.GetElement(index - _leftChildCount); } } } } //--------------------------------------------------------------------------------------- // ConcatKey represents an ordering key for the Concat operator. It knows whether the // element it is associated with is from the left source or the right source, and also // the elements ordering key. // internal struct ConcatKey<TLeftKey, TRightKey> { private readonly TLeftKey _leftKey; private readonly TRightKey _rightKey; private readonly bool _isLeft; private ConcatKey(TLeftKey leftKey, TRightKey rightKey, bool isLeft) { _leftKey = leftKey; _rightKey = rightKey; _isLeft = isLeft; } internal static ConcatKey<TLeftKey, TRightKey> MakeLeft(TLeftKey leftKey) { return new ConcatKey<TLeftKey, TRightKey>(leftKey, default(TRightKey), isLeft: true); } internal static ConcatKey<TLeftKey, TRightKey> MakeRight(TRightKey rightKey) { return new ConcatKey<TLeftKey, TRightKey>(default(TLeftKey), rightKey, isLeft: false); } internal static IComparer<ConcatKey<TLeftKey, TRightKey>> MakeComparer( IComparer<TLeftKey> leftComparer, IComparer<TRightKey> rightComparer) { return new ConcatKeyComparer(leftComparer, rightComparer); } //--------------------------------------------------------------------------------------- // ConcatKeyComparer compares ConcatKeys, so that elements from the left source come // before elements from the right source, and elements within each source are ordered // according to the corresponding order key. // private class ConcatKeyComparer : IComparer<ConcatKey<TLeftKey, TRightKey>> { private readonly IComparer<TLeftKey> _leftComparer; private readonly IComparer<TRightKey> _rightComparer; internal ConcatKeyComparer(IComparer<TLeftKey> leftComparer, IComparer<TRightKey> rightComparer) { _leftComparer = leftComparer; _rightComparer = rightComparer; } public int Compare(ConcatKey<TLeftKey, TRightKey> x, ConcatKey<TLeftKey, TRightKey> y) { // If one element is from the left source and the other not, the element from the left source // comes earlier. if (x._isLeft != y._isLeft) { return x._isLeft ? -1 : 1; } // Elements are from the same source (left or right). Compare the corresponding keys. if (x._isLeft) { return _leftComparer.Compare(x._leftKey, y._leftKey); } return _rightComparer.Compare(x._rightKey, y._rightKey); } } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.Azure; using Microsoft.Azure.Management.DataFactories; using Microsoft.Azure.Management.DataFactories.Models; namespace Microsoft.Azure.Management.DataFactories { public static partial class GatewayOperationsExtensions { /// <summary> /// Create or update a data factory gateway. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.DataFactories.IGatewayOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The resource group name of the data factory. /// </param> /// <param name='dataFactoryName'> /// Required. A unique data factory instance name. /// </param> /// <param name='parameters'> /// Required. The parameters required to create or update a data /// factory gateway. /// </param> /// <returns> /// The create or update data factory gateway operation response. /// </returns> public static GatewayCreateOrUpdateResponse BeginCreateOrUpdate(this IGatewayOperations operations, string resourceGroupName, string dataFactoryName, GatewayCreateOrUpdateParameters parameters) { return Task.Factory.StartNew((object s) => { return ((IGatewayOperations)s).BeginCreateOrUpdateAsync(resourceGroupName, dataFactoryName, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Create or update a data factory gateway. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.DataFactories.IGatewayOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The resource group name of the data factory. /// </param> /// <param name='dataFactoryName'> /// Required. A unique data factory instance name. /// </param> /// <param name='parameters'> /// Required. The parameters required to create or update a data /// factory gateway. /// </param> /// <returns> /// The create or update data factory gateway operation response. /// </returns> public static Task<GatewayCreateOrUpdateResponse> BeginCreateOrUpdateAsync(this IGatewayOperations operations, string resourceGroupName, string dataFactoryName, GatewayCreateOrUpdateParameters parameters) { return operations.BeginCreateOrUpdateAsync(resourceGroupName, dataFactoryName, parameters, CancellationToken.None); } /// <summary> /// Delete a data factory gateway. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.DataFactories.IGatewayOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The resource group name of the data factory. /// </param> /// <param name='dataFactoryName'> /// Required. A unique data factory instance name. /// </param> /// <param name='gatewayName'> /// Required. Name of the gateway to delete. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static LongRunningOperationResponse BeginDelete(this IGatewayOperations operations, string resourceGroupName, string dataFactoryName, string gatewayName) { return Task.Factory.StartNew((object s) => { return ((IGatewayOperations)s).BeginDeleteAsync(resourceGroupName, dataFactoryName, gatewayName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Delete a data factory gateway. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.DataFactories.IGatewayOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The resource group name of the data factory. /// </param> /// <param name='dataFactoryName'> /// Required. A unique data factory instance name. /// </param> /// <param name='gatewayName'> /// Required. Name of the gateway to delete. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static Task<LongRunningOperationResponse> BeginDeleteAsync(this IGatewayOperations operations, string resourceGroupName, string dataFactoryName, string gatewayName) { return operations.BeginDeleteAsync(resourceGroupName, dataFactoryName, gatewayName, CancellationToken.None); } /// <summary> /// Create or update a data factory gateway. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.DataFactories.IGatewayOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The resource group name of the data factory. /// </param> /// <param name='dataFactoryName'> /// Required. A unique data factory instance name. /// </param> /// <param name='parameters'> /// Required. The parameters required to create or update a data /// factory gateway. /// </param> /// <returns> /// The create or update data factory gateway operation response. /// </returns> public static GatewayCreateOrUpdateResponse CreateOrUpdate(this IGatewayOperations operations, string resourceGroupName, string dataFactoryName, GatewayCreateOrUpdateParameters parameters) { return Task.Factory.StartNew((object s) => { return ((IGatewayOperations)s).CreateOrUpdateAsync(resourceGroupName, dataFactoryName, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Create or update a data factory gateway. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.DataFactories.IGatewayOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The resource group name of the data factory. /// </param> /// <param name='dataFactoryName'> /// Required. A unique data factory instance name. /// </param> /// <param name='parameters'> /// Required. The parameters required to create or update a data /// factory gateway. /// </param> /// <returns> /// The create or update data factory gateway operation response. /// </returns> public static Task<GatewayCreateOrUpdateResponse> CreateOrUpdateAsync(this IGatewayOperations operations, string resourceGroupName, string dataFactoryName, GatewayCreateOrUpdateParameters parameters) { return operations.CreateOrUpdateAsync(resourceGroupName, dataFactoryName, parameters, CancellationToken.None); } /// <summary> /// Delete a data factory gateway. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.DataFactories.IGatewayOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The resource group name of the data factory. /// </param> /// <param name='dataFactoryName'> /// Required. A unique data factory instance name. /// </param> /// <param name='gatewayName'> /// Required. Name of the gateway to delete. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static AzureOperationResponse Delete(this IGatewayOperations operations, string resourceGroupName, string dataFactoryName, string gatewayName) { return Task.Factory.StartNew((object s) => { return ((IGatewayOperations)s).DeleteAsync(resourceGroupName, dataFactoryName, gatewayName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Delete a data factory gateway. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.DataFactories.IGatewayOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The resource group name of the data factory. /// </param> /// <param name='dataFactoryName'> /// Required. A unique data factory instance name. /// </param> /// <param name='gatewayName'> /// Required. Name of the gateway to delete. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static Task<AzureOperationResponse> DeleteAsync(this IGatewayOperations operations, string resourceGroupName, string dataFactoryName, string gatewayName) { return operations.DeleteAsync(resourceGroupName, dataFactoryName, gatewayName, CancellationToken.None); } /// <summary> /// Gets a data factory gateway. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.DataFactories.IGatewayOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The resource group name of the data factory. /// </param> /// <param name='dataFactoryName'> /// Required. A unique data factory instance name. /// </param> /// <param name='gatewayName'> /// Required. Name of the gateway to get. /// </param> /// <returns> /// The Get data factory gateway operation response. /// </returns> public static GatewayGetResponse Get(this IGatewayOperations operations, string resourceGroupName, string dataFactoryName, string gatewayName) { return Task.Factory.StartNew((object s) => { return ((IGatewayOperations)s).GetAsync(resourceGroupName, dataFactoryName, gatewayName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets a data factory gateway. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.DataFactories.IGatewayOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The resource group name of the data factory. /// </param> /// <param name='dataFactoryName'> /// Required. A unique data factory instance name. /// </param> /// <param name='gatewayName'> /// Required. Name of the gateway to get. /// </param> /// <returns> /// The Get data factory gateway operation response. /// </returns> public static Task<GatewayGetResponse> GetAsync(this IGatewayOperations operations, string resourceGroupName, string dataFactoryName, string gatewayName) { return operations.GetAsync(resourceGroupName, dataFactoryName, gatewayName, CancellationToken.None); } /// <summary> /// The Get Operation Status operation returns the status of the /// specified operation. After calling an asynchronous operation, you /// can call Get Operation Status to determine whether the operation /// has succeeded, failed, or is still in progress. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.DataFactories.IGatewayOperations. /// </param> /// <param name='operationStatusLink'> /// Required. Location value returned by the Begin operation. /// </param> /// <returns> /// The create or update data factory gateway operation response. /// </returns> public static GatewayCreateOrUpdateResponse GetCreateOrUpdateStatus(this IGatewayOperations operations, string operationStatusLink) { return Task.Factory.StartNew((object s) => { return ((IGatewayOperations)s).GetCreateOrUpdateStatusAsync(operationStatusLink); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The Get Operation Status operation returns the status of the /// specified operation. After calling an asynchronous operation, you /// can call Get Operation Status to determine whether the operation /// has succeeded, failed, or is still in progress. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.DataFactories.IGatewayOperations. /// </param> /// <param name='operationStatusLink'> /// Required. Location value returned by the Begin operation. /// </param> /// <returns> /// The create or update data factory gateway operation response. /// </returns> public static Task<GatewayCreateOrUpdateResponse> GetCreateOrUpdateStatusAsync(this IGatewayOperations operations, string operationStatusLink) { return operations.GetCreateOrUpdateStatusAsync(operationStatusLink, CancellationToken.None); } /// <summary> /// List all gateways under a data factory. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.DataFactories.IGatewayOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The resource group name of the data factory. /// </param> /// <param name='dataFactoryName'> /// Required. A unique data factory instance name. /// </param> /// <returns> /// The List data factory gateways operation response. /// </returns> public static GatewayListResponse List(this IGatewayOperations operations, string resourceGroupName, string dataFactoryName) { return Task.Factory.StartNew((object s) => { return ((IGatewayOperations)s).ListAsync(resourceGroupName, dataFactoryName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// List all gateways under a data factory. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.DataFactories.IGatewayOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The resource group name of the data factory. /// </param> /// <param name='dataFactoryName'> /// Required. A unique data factory instance name. /// </param> /// <returns> /// The List data factory gateways operation response. /// </returns> public static Task<GatewayListResponse> ListAsync(this IGatewayOperations operations, string resourceGroupName, string dataFactoryName) { return operations.ListAsync(resourceGroupName, dataFactoryName, CancellationToken.None); } /// <summary> /// Regenerate gateway key. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.DataFactories.IGatewayOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The resource group name of the data factory. /// </param> /// <param name='dataFactoryName'> /// Required. A unique data factory instance name. /// </param> /// <param name='gatewayName'> /// Required. The name of the gateway to regenerate key. /// </param> /// <returns> /// The regenerate gateway key operation response. /// </returns> public static GatewayRegenerateKeyResponse RegenerateKey(this IGatewayOperations operations, string resourceGroupName, string dataFactoryName, string gatewayName) { return Task.Factory.StartNew((object s) => { return ((IGatewayOperations)s).RegenerateKeyAsync(resourceGroupName, dataFactoryName, gatewayName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Regenerate gateway key. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.DataFactories.IGatewayOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The resource group name of the data factory. /// </param> /// <param name='dataFactoryName'> /// Required. A unique data factory instance name. /// </param> /// <param name='gatewayName'> /// Required. The name of the gateway to regenerate key. /// </param> /// <returns> /// The regenerate gateway key operation response. /// </returns> public static Task<GatewayRegenerateKeyResponse> RegenerateKeyAsync(this IGatewayOperations operations, string resourceGroupName, string dataFactoryName, string gatewayName) { return operations.RegenerateKeyAsync(resourceGroupName, dataFactoryName, gatewayName, CancellationToken.None); } /// <summary> /// Retrieve gateway connection information. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.DataFactories.IGatewayOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The resource group name of the data factory. /// </param> /// <param name='dataFactoryName'> /// Required. A unique data factory instance name. /// </param> /// <param name='gatewayName'> /// Required. Name of the gateway. /// </param> /// <returns> /// The retrieve gateway connection information operation response. /// </returns> public static GatewayConnectionInfoRetrieveResponse RetrieveConnectionInfo(this IGatewayOperations operations, string resourceGroupName, string dataFactoryName, string gatewayName) { return Task.Factory.StartNew((object s) => { return ((IGatewayOperations)s).RetrieveConnectionInfoAsync(resourceGroupName, dataFactoryName, gatewayName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Retrieve gateway connection information. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.DataFactories.IGatewayOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The resource group name of the data factory. /// </param> /// <param name='dataFactoryName'> /// Required. A unique data factory instance name. /// </param> /// <param name='gatewayName'> /// Required. Name of the gateway. /// </param> /// <returns> /// The retrieve gateway connection information operation response. /// </returns> public static Task<GatewayConnectionInfoRetrieveResponse> RetrieveConnectionInfoAsync(this IGatewayOperations operations, string resourceGroupName, string dataFactoryName, string gatewayName) { return operations.RetrieveConnectionInfoAsync(resourceGroupName, dataFactoryName, gatewayName, CancellationToken.None); } /// <summary> /// Update a data factory gateway. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.DataFactories.IGatewayOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The resource group name of the data factory. /// </param> /// <param name='dataFactoryName'> /// Required. A unique data factory instance name. /// </param> /// <param name='parameters'> /// Required. The parameters required to create or update a data /// factory gateway. /// </param> /// <returns> /// The create or update data factory gateway operation response. /// </returns> public static GatewayCreateOrUpdateResponse Update(this IGatewayOperations operations, string resourceGroupName, string dataFactoryName, GatewayCreateOrUpdateParameters parameters) { return Task.Factory.StartNew((object s) => { return ((IGatewayOperations)s).UpdateAsync(resourceGroupName, dataFactoryName, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Update a data factory gateway. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.DataFactories.IGatewayOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The resource group name of the data factory. /// </param> /// <param name='dataFactoryName'> /// Required. A unique data factory instance name. /// </param> /// <param name='parameters'> /// Required. The parameters required to create or update a data /// factory gateway. /// </param> /// <returns> /// The create or update data factory gateway operation response. /// </returns> public static Task<GatewayCreateOrUpdateResponse> UpdateAsync(this IGatewayOperations operations, string resourceGroupName, string dataFactoryName, GatewayCreateOrUpdateParameters parameters) { return operations.UpdateAsync(resourceGroupName, dataFactoryName, parameters, CancellationToken.None); } } }
// 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.Collections; using System.Collections.Generic; using System.Globalization; using System.DirectoryServices; using System.Text.RegularExpressions; namespace System.DirectoryServices.AccountManagement { #pragma warning disable 618 // Have not migrated to v4 transparency yet [System.Security.SecurityCritical(System.Security.SecurityCriticalScope.Everything)] #pragma warning restore 618 internal class SAMQuerySet : ResultSet { // We will iterate over all principals under ctxBase, returning only those which are in the list of types and which // satisfy ALL the matching properties. internal SAMQuerySet( List<string> schemaTypes, DirectoryEntries entries, DirectoryEntry ctxBase, int sizeLimit, SAMStoreCtx storeCtx, SAMMatcher samMatcher) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMQuerySet", "SAMQuerySet: creating for path={0}, sizelimit={1}", ctxBase.Path, sizeLimit); _schemaTypes = schemaTypes; _entries = entries; _sizeLimit = sizeLimit; // -1 == no limit _storeCtx = storeCtx; _ctxBase = ctxBase; _matcher = samMatcher; _enumerator = _entries.GetEnumerator(); } // Return the principal we're positioned at as a Principal object. // Need to use our StoreCtx's GetAsPrincipal to convert the native object to a Principal override internal object CurrentAsPrincipal { get { GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMQuerySet", "CurrentAsPrincipal"); // Since this class is only used internally, none of our code should be even calling this // if MoveNext returned false, or before calling MoveNext. Debug.Assert(_endReached == false && _current != null); return SAMUtils.DirectoryEntryAsPrincipal(_current, _storeCtx); } } // Advance the enumerator to the next principal in the result set, pulling in additional pages // of results (or ranges of attribute values) as needed. // Returns true if successful, false if no more results to return. override internal bool MoveNext() { GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMQuerySet", "Entering MoveNext"); Debug.Assert(_enumerator != null); bool needToRetry = false; bool f; // Have we exceeded the requested size limit? if ((_sizeLimit != -1) && (_resultsReturned >= _sizeLimit)) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMQuerySet", "MoveNext: exceeded sizelimit, ret={0}, limit={1}", _resultsReturned, _sizeLimit); _endReached = true; } // End was reached previously. Nothing more to do. if (_endReached) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMQuerySet", "MoveNext: endReached"); return false; } // Pull the next result. We may have to repeat this several times // until we find a result that matches the user's filter. do { f = _enumerator.MoveNext(); needToRetry = false; if (f) { DirectoryEntry entry = (DirectoryEntry)_enumerator.Current; // Does it match the user's properties? // // We'd like to use DirectoryEntries.SchemaFilter rather than calling // IsOfCorrectType here, but SchemaFilter has a bug // where multiple DirectoryEntries all share the same SchemaFilter --- // which would create multithreading issues for us. if (IsOfCorrectType(entry) && _matcher.Matches(entry)) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMQuerySet", "MoveNext: found a match on {0}", entry.Path); // Yes. It's our new current object _current = entry; _resultsReturned++; } else { // No. Retry. needToRetry = true; } } } while (needToRetry); if (!f) { /* // One more to try: the root object if (IsOfCorrectType(this.ctxBase) && this.matcher.Matches(this.ctxBase)) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMQuerySet", "MoveNext: found a match on root {0}", this.ctxBase); this.current = this.ctxBase; this.resultsReturned++; f = true; } else { endReached = true; } * */ } return f; } private bool IsOfCorrectType(DirectoryEntry de) { // Is the object in question one of the desired types? foreach (string schemaType in _schemaTypes) { if (SAMUtils.IsOfObjectClass(de, schemaType)) return true; } return false; } // Resets the enumerator to before the first result in the set. This potentially can be an expensive // operation, e.g., if doing a paged search, may need to re-retrieve the first page of results. // As a special case, if the ResultSet is already at the very beginning, this is guaranteed to be // a no-op. override internal void Reset() { GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMQuerySet", "Reset"); // if current == null, we're already at the beginning if (_current != null) { _endReached = false; _current = null; if (_enumerator != null) _enumerator.Reset(); _resultsReturned = 0; } } // // Private fields // private SAMStoreCtx _storeCtx; private DirectoryEntry _ctxBase; private DirectoryEntries _entries; private IEnumerator _enumerator = null; // the enumerator for "entries" private DirectoryEntry _current = null; // the DirectoryEntry that we're currently positioned at // Filter parameters private int _sizeLimit; // -1 == no limit private List<string> _schemaTypes; private SAMMatcher _matcher; // Count of number of results returned so far private int _resultsReturned = 0; // Have we run out of entries? private bool _endReached = false; } internal abstract class SAMMatcher { abstract internal bool Matches(DirectoryEntry de); } // // The matcher routines for query-by-example support // #pragma warning disable 618 // Have not migrated to v4 transparency yet [System.Security.SecurityCritical(System.Security.SecurityCriticalScope.Everything)] #pragma warning restore 618 internal class QbeMatcher : SAMMatcher { private QbeFilterDescription _propertiesToMatch; internal QbeMatcher(QbeFilterDescription propertiesToMatch) { _propertiesToMatch = propertiesToMatch; } // // Static constructor: used for initializing static tables // static QbeMatcher() { // // Load the filterPropertiesTable // s_filterPropertiesTable = new Hashtable(); for (int i = 0; i < s_filterPropertiesTableRaw.GetLength(0); i++) { Type qbeType = s_filterPropertiesTableRaw[i, 0] as Type; string winNTPropertyName = s_filterPropertiesTableRaw[i, 1] as string; MatcherDelegate f = s_filterPropertiesTableRaw[i, 2] as MatcherDelegate; Debug.Assert(qbeType != null); Debug.Assert(winNTPropertyName != null); Debug.Assert(f != null); // There should only be one entry per QBE type Debug.Assert(s_filterPropertiesTable[qbeType] == null); FilterPropertyTableEntry entry = new FilterPropertyTableEntry(); entry.winNTPropertyName = winNTPropertyName; entry.matcher = f; s_filterPropertiesTable[qbeType] = entry; } } internal override bool Matches(DirectoryEntry de) { // If it has no SID, it's not a security principal, and we're not interested in it. // (In reg-SAM, computers don't have accounts and therefore don't have SIDs, but ADSI // creates fake Computer objects for them. In LSAM, computers CAN have accounts, and thus // SIDs). if (de.Properties["objectSid"] == null || de.Properties["objectSid"].Count == 0) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMQuerySet", "SamMatcher: Matches: skipping no-SID {0}", de.Path); return false; } // Try to match each specified property in turn foreach (FilterBase filter in _propertiesToMatch.FiltersToApply) { FilterPropertyTableEntry entry = (FilterPropertyTableEntry)s_filterPropertiesTable[filter.GetType()]; if (entry == null) { // Must be a property we don't support throw new NotSupportedException( String.Format( CultureInfo.CurrentCulture, StringResources.StoreCtxUnsupportedPropertyForQuery, PropertyNamesExternal.GetExternalForm(filter.PropertyName))); } if (!entry.matcher(filter, entry.winNTPropertyName, de)) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMQuerySet", "SamMatcher: Matches: no match {0}", de.Path); return false; } } // All tests pass --- it's a match GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMQuerySet", "SamMatcher: Matches: match {0}", de.Path); return true; } // We only list properties we support filtering on in this table. At run-time, if we detect they set a // property that's not listed here, we throw an exception. private static object[,] s_filterPropertiesTableRaw = { // QbeType WinNT Property Matcher {typeof(DescriptionFilter), "Description", new MatcherDelegate(StringMatcher)}, {typeof(DisplayNameFilter), "FullName", new MatcherDelegate(StringMatcher)}, {typeof(SidFilter), "objectSid", new MatcherDelegate(SidMatcher)}, {typeof(SamAccountNameFilter), "Name", new MatcherDelegate(SamAccountNameMatcher)}, {typeof(AuthPrincEnabledFilter), "UserFlags", new MatcherDelegate(UserFlagsMatcher)}, {typeof(PermittedWorkstationFilter), "LoginWorkstations", new MatcherDelegate(MultiStringMatcher)}, {typeof(PermittedLogonTimesFilter), "LoginHours", new MatcherDelegate(BinaryMatcher)}, {typeof(ExpirationDateFilter), "AccountExpirationDate", new MatcherDelegate(ExpirationDateMatcher)}, {typeof(SmartcardLogonRequiredFilter), "UserFlags", new MatcherDelegate(UserFlagsMatcher)}, {typeof(DelegationPermittedFilter), "UserFlags", new MatcherDelegate(UserFlagsMatcher)}, {typeof(HomeDirectoryFilter), "HomeDirectory", new MatcherDelegate(StringMatcher)}, {typeof(HomeDriveFilter), "HomeDirDrive", new MatcherDelegate(StringMatcher)}, {typeof(ScriptPathFilter), "LoginScript", new MatcherDelegate(StringMatcher)}, {typeof(PasswordNotRequiredFilter), "UserFlags", new MatcherDelegate(UserFlagsMatcher)}, {typeof(PasswordNeverExpiresFilter), "UserFlags", new MatcherDelegate(UserFlagsMatcher)}, {typeof(CannotChangePasswordFilter), "UserFlags", new MatcherDelegate(UserFlagsMatcher)}, {typeof(AllowReversiblePasswordEncryptionFilter), "UserFlags", new MatcherDelegate(UserFlagsMatcher)}, {typeof(GroupScopeFilter), "groupType", new MatcherDelegate(GroupTypeMatcher)}, {typeof(ExpiredAccountFilter), "AccountExpirationDate", new MatcherDelegate(DateTimeMatcher)}, {typeof(LastLogonTimeFilter), "LastLogin", new MatcherDelegate(DateTimeMatcher)}, {typeof(PasswordSetTimeFilter), "PasswordAge", new MatcherDelegate(DateTimeMatcher)}, {typeof(BadLogonCountFilter), "BadPasswordAttempts", new MatcherDelegate(IntMatcher)}, }; private static Hashtable s_filterPropertiesTable = null; private class FilterPropertyTableEntry { internal string winNTPropertyName; internal MatcherDelegate matcher; } // // Conversion routines // private static bool WildcardStringMatch(FilterBase filter, string wildcardFilter, string property) { // Build a Regex that matches valueToMatch, and store it on the Filter (so that we don't have // to have the CLR constantly reparse the regex string). // Ideally, we'd like to use a compiled Regex (RegexOptions.Compiled) for performance, // but the CLR cannot release generated MSIL. Thus, our memory usage would grow without bound // each time a query was performed. Regex regex = filter.Extra as Regex; if (regex == null) { regex = new Regex(SAMUtils.PAPIQueryToRegexString(wildcardFilter), RegexOptions.Singleline); filter.Extra = regex; } Match match = regex.Match(property); return match.Success; } // returns true if specified WinNT property's value matches filter.Value private delegate bool MatcherDelegate(FilterBase filter, string winNTPropertyName, DirectoryEntry de); private static bool DateTimeMatcher(FilterBase filter, string winNTPropertyName, DirectoryEntry de) { QbeMatchType valueToMatch = (QbeMatchType)filter.Value; if (null == valueToMatch.Value) { if ((de.Properties.Contains(winNTPropertyName) == false) || (de.Properties[winNTPropertyName].Count == 0) || (de.Properties[winNTPropertyName].Value == null)) return true; } else { Debug.Assert(valueToMatch.Value is DateTime); if (de.Properties.Contains(winNTPropertyName) && (de.Properties[winNTPropertyName].Value != null)) { DateTime value; if (winNTPropertyName == "PasswordAge") { PropertyValueCollection values = de.Properties["PasswordAge"]; if (values.Count != 0) { Debug.Assert(values.Count == 1); Debug.Assert(values[0] is Int32); int secondsLapsed = (int)values[0]; value = DateTime.UtcNow - new TimeSpan(0, 0, secondsLapsed); } else { // If we don't have a passwordAge then this item will never match. return false; } } else { value = (DateTime)de.Properties[winNTPropertyName].Value; } int comparisonResult = DateTime.Compare(value, (DateTime)valueToMatch.Value); bool result = true; switch (valueToMatch.Match) { case MatchType.Equals: result = comparisonResult == 0; break; case MatchType.NotEquals: result = comparisonResult != 0; break; case MatchType.GreaterThan: result = comparisonResult > 0; break; case MatchType.GreaterThanOrEquals: result = comparisonResult >= 0; break; case MatchType.LessThan: result = comparisonResult < 0; break; case MatchType.LessThanOrEquals: result = comparisonResult <= 0; break; default: result = false; break; } return result; } } return false; } private static bool StringMatcher(FilterBase filter, string winNTPropertyName, DirectoryEntry de) { string valueToMatch = (string)filter.Value; if (valueToMatch == null) { if ((de.Properties.Contains(winNTPropertyName) == false) || (de.Properties[winNTPropertyName].Count == 0) || (((string)de.Properties[winNTPropertyName].Value).Length == 0)) return true; } else { if (de.Properties.Contains(winNTPropertyName)) { string value = (string)de.Properties[winNTPropertyName].Value; if (value != null) { return WildcardStringMatch(filter, valueToMatch, value); } } } return false; } private static bool IntMatcher(FilterBase filter, string winNTPropertyName, DirectoryEntry de) { QbeMatchType valueToMatch = (QbeMatchType)filter.Value; bool result = false; if (null == valueToMatch.Value) { if ((de.Properties.Contains(winNTPropertyName) == false) || (de.Properties[winNTPropertyName].Count == 0) || (de.Properties[winNTPropertyName].Value == null)) result = true; } else { if (de.Properties.Contains(winNTPropertyName)) { int value = (int)de.Properties[winNTPropertyName].Value; int comparisonValue = (int)valueToMatch.Value; switch (valueToMatch.Match) { case MatchType.Equals: result = (value == comparisonValue); break; case MatchType.NotEquals: result = (value != comparisonValue); break; case MatchType.GreaterThan: result = (value > comparisonValue); break; case MatchType.GreaterThanOrEquals: result = (value >= comparisonValue); break; case MatchType.LessThan: result = (value < comparisonValue); break; case MatchType.LessThanOrEquals: result = (value <= comparisonValue); break; default: result = false; break; } } } return result; } private static bool SamAccountNameMatcher(FilterBase filter, string winNTPropertyName, DirectoryEntry de) { string samToMatch = (string)filter.Value; int index = samToMatch.IndexOf('\\'); if (index == samToMatch.Length - 1) throw new InvalidOperationException(StringResources.StoreCtxNT4IdentityClaimWrongForm); string samAccountName = (index != -1) ? samToMatch.Substring(index + 1) : // +1 to skip the '/' samToMatch; if (de.Properties["Name"].Count > 0 && de.Properties["Name"].Value != null) { return WildcardStringMatch(filter, samAccountName, (string)de.Properties["Name"].Value); /* return (String.Compare(((string)de.Properties["Name"].Value), samAccountName, true, // acct names are not case-sensitive CultureInfo.InvariantCulture) == 0); */ } return false; } private static bool SidMatcher(FilterBase filter, string winNTPropertyName, DirectoryEntry de) { byte[] sidToMatch = Utils.StringToByteArray((string)filter.Value); if (sidToMatch == null) throw new InvalidOperationException(StringResources.StoreCtxSecurityIdentityClaimBadFormat); if (de.Properties["objectSid"].Count > 0 && de.Properties["objectSid"].Value != null) { return Utils.AreBytesEqual(sidToMatch, (byte[])de.Properties["objectSid"].Value); } return false; } private static bool UserFlagsMatcher(FilterBase filter, string winNTPropertyName, DirectoryEntry de) { Debug.Assert(winNTPropertyName == "UserFlags"); bool valueToMatch = (bool)filter.Value; // If it doesn't contain the property, it certainly can't match the user's value if (!de.Properties.Contains(winNTPropertyName) || de.Properties[winNTPropertyName].Count == 0) return false; int value = (int)de.Properties[winNTPropertyName].Value; switch (filter.PropertyName) { // We want to return true iff both value and valueToMatch are true, or both are false // (i.e., NOT XOR) case AuthPrincEnabledFilter.PropertyNameStatic: // UF_ACCOUNTDISABLE // Note that the logic is inverted on this one. We expose "Enabled", // but SAM stores it as "Disabled". return (((value & 0x0002) != 0) ^ valueToMatch); case SmartcardLogonRequiredFilter.PropertyNameStatic: // UF_SMARTCARD_REQUIRED return !(((value & 0x40000) != 0) ^ valueToMatch); case DelegationPermittedFilter.PropertyNameStatic: // UF_NOT_DELEGATED // Note that the logic is inverted on this one. That's because we expose // "delegation allowed", but AD represents it as the inverse, "delegation NOT allowed" return (((value & 0x100000) != 0) ^ valueToMatch); case PasswordNotRequiredFilter.PropertyNameStatic: // UF_PASSWD_NOTREQD return !(((value & 0x0020) != 0) ^ valueToMatch); case PasswordNeverExpiresFilter.PropertyNameStatic: // UF_DONT_EXPIRE_PASSWD return !(((value & 0x10000) != 0) ^ valueToMatch); case CannotChangePasswordFilter.PropertyNameStatic: // UF_PASSWD_CANT_CHANGE return !(((value & 0x0040) != 0) ^ valueToMatch); case AllowReversiblePasswordEncryptionFilter.PropertyNameStatic: // UF_ENCRYPTED_TEXT_PASSWORD_ALLOWED return !(((value & 0x0080) != 0) ^ valueToMatch); default: Debug.Fail("SAMQuerySet.UserFlagsMatcher: fell off end looking for " + filter.PropertyName); return false; } } private static bool MultiStringMatcher(FilterBase filter, string winNTPropertyName, DirectoryEntry de) { string valueToMatch = (string)filter.Value; if (valueToMatch == null) { if ((de.Properties.Contains(winNTPropertyName) == false) || (de.Properties[winNTPropertyName].Count == 0) || (((string)de.Properties[winNTPropertyName].Value).Length == 0)) return true; } else { if (de.Properties.Contains(winNTPropertyName) && (de.Properties[winNTPropertyName].Count != 0)) { foreach (string value in de.Properties[winNTPropertyName]) { if (value != null) { return WildcardStringMatch(filter, valueToMatch, value); } } } } return false; } private static bool BinaryMatcher(FilterBase filter, string winNTPropertyName, DirectoryEntry de) { byte[] valueToMatch = (byte[])filter.Value; if (valueToMatch == null) { if ((de.Properties.Contains(winNTPropertyName) == false) || (de.Properties[winNTPropertyName].Count == 0) || (de.Properties[winNTPropertyName].Value == null)) return true; } else { if (de.Properties.Contains(winNTPropertyName)) { byte[] value = (byte[])de.Properties[winNTPropertyName].Value; if ((value != null) && Utils.AreBytesEqual(value, valueToMatch)) return true; } } return false; } private static bool ExpirationDateMatcher(FilterBase filter, string winNTPropertyName, DirectoryEntry de) { Debug.Assert(filter is ExpirationDateFilter); Debug.Assert(winNTPropertyName == "AccountExpirationDate"); Nullable<DateTime> valueToCompare = (Nullable<DateTime>)filter.Value; if (!valueToCompare.HasValue) { if ((de.Properties.Contains(winNTPropertyName) == false) || (de.Properties[winNTPropertyName].Count == 0) || (de.Properties[winNTPropertyName].Value == null)) return true; } else { if (de.Properties.Contains(winNTPropertyName) && (de.Properties[winNTPropertyName].Value != null)) { DateTime value = (DateTime)de.Properties[winNTPropertyName].Value; if (value.Equals(valueToCompare.Value)) return true; } } return false; } private static bool GroupTypeMatcher(FilterBase filter, string winNTPropertyName, DirectoryEntry de) { Debug.Assert(winNTPropertyName == "groupType"); Debug.Assert(filter is GroupScopeFilter); GroupScope valueToMatch = (GroupScope)filter.Value; // All SAM local machine groups are local groups if (valueToMatch == GroupScope.Local) return true; else return false; } } // // The matcher routines for FindBy* support // #pragma warning disable 618 // Have not migrated to v4 transparency yet [System.Security.SecurityCritical(System.Security.SecurityCriticalScope.Everything)] #pragma warning restore 618 internal class FindByDateMatcher : SAMMatcher { internal enum DateProperty { LogonTime, PasswordSetTime, AccountExpirationTime } private DateProperty _propertyToMatch; private MatchType _matchType; private DateTime _valueToMatch; internal FindByDateMatcher(DateProperty property, MatchType matchType, DateTime value) { _propertyToMatch = property; _matchType = matchType; _valueToMatch = value; } internal override bool Matches(DirectoryEntry de) { // If it has no SID, it's not a security principal, and we're not interested in it. // (In reg-SAM, computers don't have accounts and therefore don't have SIDs, but ADSI // creates fake Computer objects for them. In LSAM, computers CAN have accounts, and thus // SIDs). if (de.Properties["objectSid"] == null || de.Properties["objectSid"].Count == 0) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMQuerySet", "FindByDateMatcher: Matches: skipping no-SID {0}", de.Path); return false; } switch (_propertyToMatch) { case DateProperty.LogonTime: return MatchOnLogonTime(de); case DateProperty.PasswordSetTime: return MatchOnPasswordSetTime(de); case DateProperty.AccountExpirationTime: return MatchOnAccountExpirationTime(de); default: Debug.Fail("FindByDateMatcher.Matches: Fell off end looking for propertyToMatch=" + _propertyToMatch.ToString()); return false; } } private bool MatchOnLogonTime(DirectoryEntry de) { PropertyValueCollection values = de.Properties["LastLogin"]; Nullable<DateTime> storeValue = null; // Get the logon time from the DirectoryEntry if (values.Count > 0) { Debug.Assert(values.Count == 1); storeValue = (Nullable<DateTime>)values[0]; } return TestForMatch(storeValue); } private bool MatchOnAccountExpirationTime(DirectoryEntry de) { PropertyValueCollection values = de.Properties["AccountExpirationDate"]; Nullable<DateTime> storeValue = null; // Get the expiration date from the DirectoryEntry if (values.Count > 0) { Debug.Assert(values.Count == 1); storeValue = (Nullable<DateTime>)values[0]; } return TestForMatch(storeValue); } private bool MatchOnPasswordSetTime(DirectoryEntry de) { PropertyValueCollection values = de.Properties["PasswordAge"]; Nullable<DateTime> storeValue = null; if (values.Count != 0) { Debug.Assert(values.Count == 1); Debug.Assert(values[0] is Int32); int secondsLapsed = (int)values[0]; storeValue = DateTime.UtcNow - new TimeSpan(0, 0, secondsLapsed); } return TestForMatch(storeValue); } private bool TestForMatch(Nullable<DateTime> nullableStoreValue) { // If the store object doesn't have the property set, then the only // way it could match is if they asked for a not-equals test // (if the store object doesn't have a value, then it certainly doesn't match // whatever value they specified) if (!nullableStoreValue.HasValue) return (_matchType == MatchType.NotEquals) ? true : false; Debug.Assert(nullableStoreValue.HasValue); DateTime storeValue = nullableStoreValue.Value; switch (_matchType) { case MatchType.Equals: return (storeValue == _valueToMatch); case MatchType.NotEquals: return (storeValue != _valueToMatch); case MatchType.GreaterThan: return (storeValue > _valueToMatch); case MatchType.GreaterThanOrEquals: return (storeValue >= _valueToMatch); case MatchType.LessThan: return (storeValue < _valueToMatch); case MatchType.LessThanOrEquals: return (storeValue <= _valueToMatch); default: Debug.Fail("FindByDateMatcher.TestForMatch: Fell off end looking for matchType=" + _matchType.ToString()); return false; } } } #pragma warning disable 618 // Have not migrated to v4 transparency yet [System.Security.SecurityCritical(System.Security.SecurityCriticalScope.Everything)] #pragma warning restore 618 internal class GroupMemberMatcher : SAMMatcher { private byte[] _memberSidToMatch; internal GroupMemberMatcher(byte[] memberSidToMatch) { Debug.Assert(memberSidToMatch != null); Debug.Assert(memberSidToMatch.Length != 0); _memberSidToMatch = memberSidToMatch; } internal override bool Matches(DirectoryEntry groupDE) { // If it has no SID, it's not a security principal, and we're not interested in it. // (In reg-SAM, computers don't have accounts and therefore don't have SIDs, but ADSI // creates fake Computer objects for them. In LSAM, computers CAN have accounts, and thus // SIDs). if (groupDE.Properties["objectSid"] == null || groupDE.Properties["objectSid"].Count == 0) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMQuerySet", "GroupMemberMatcher: Matches: skipping no-SID group={0}", groupDE.Path); return false; } // Enumerate the members of the group, looking for a match UnsafeNativeMethods.IADsGroup iADsGroup = (UnsafeNativeMethods.IADsGroup)groupDE.NativeObject; UnsafeNativeMethods.IADsMembers iADsMembers = iADsGroup.Members(); foreach (UnsafeNativeMethods.IADs nativeMember in ((IEnumerable)iADsMembers)) { // Wrap the DirectoryEntry around the native ADSI object // (which already has the correct credentials) DirectoryEntry memberDE = new DirectoryEntry(nativeMember); // No SID --> not interesting if (memberDE.Properties["objectSid"] == null || memberDE.Properties["objectSid"].Count == 0) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMQuerySet", "GroupMemberMatcher: Matches: skipping member no-SID member={0}", memberDE.Path); continue; } byte[] memberSid = (byte[])memberDE.Properties["objectSid"].Value; // Did we find a matching member in the group? if (Utils.AreBytesEqual(memberSid, _memberSidToMatch)) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMQuerySet", "GroupMemberMatcher: Matches: match member={0}, group={1)", memberDE.Path, groupDE.Path); return true; } } // We tried all the members in the group and didn't get a match on any GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMQuerySet", "SamMatcher: Matches: no match, group={0}", groupDE.Path); return false; } } } //#endif // PAPI_REGSAM
#region Apache License // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion using System; using System.Collections; #if !NETCF using System.Runtime.Serialization; using System.Xml; #endif namespace Ctrip.Util { /// <summary> /// String keyed object map that is read only. /// </summary> /// <remarks> /// <para> /// This collection is readonly and cannot be modified. /// </para> /// <para> /// While this collection is serializable only member /// objects that are serializable will /// be serialized along with this collection. /// </para> /// </remarks> /// <author>Nicko Cadell</author> /// <author>Gert Driesen</author> #if NETCF public class ReadOnlyPropertiesDictionary : IDictionary #else [Serializable] public class ReadOnlyPropertiesDictionary : ISerializable, IDictionary #endif { #region Private Instance Fields /// <summary> /// The Hashtable used to store the properties data /// </summary> private Hashtable m_hashtable = new Hashtable(); #endregion Private Instance Fields #region Public Instance Constructors /// <summary> /// Constructor /// </summary> /// <remarks> /// <para> /// Initializes a new instance of the <see cref="ReadOnlyPropertiesDictionary" /> class. /// </para> /// </remarks> public ReadOnlyPropertiesDictionary() { } /// <summary> /// Copy Constructor /// </summary> /// <param name="propertiesDictionary">properties to copy</param> /// <remarks> /// <para> /// Initializes a new instance of the <see cref="ReadOnlyPropertiesDictionary" /> class. /// </para> /// </remarks> public ReadOnlyPropertiesDictionary(ReadOnlyPropertiesDictionary propertiesDictionary) { foreach(DictionaryEntry entry in propertiesDictionary) { InnerHashtable.Add(entry.Key, entry.Value); } } #endregion Public Instance Constructors #region Private Instance Constructors #if !NETCF /// <summary> /// Deserialization constructor /// </summary> /// <param name="info">The <see cref="SerializationInfo" /> that holds the serialized object data.</param> /// <param name="context">The <see cref="StreamingContext" /> that contains contextual information about the source or destination.</param> /// <remarks> /// <para> /// Initializes a new instance of the <see cref="ReadOnlyPropertiesDictionary" /> class /// with serialized data. /// </para> /// </remarks> protected ReadOnlyPropertiesDictionary(SerializationInfo info, StreamingContext context) { foreach(SerializationEntry entry in info) { // The keys are stored as Xml encoded names InnerHashtable[XmlConvert.DecodeName(entry.Name)] = entry.Value; } } #endif #endregion Protected Instance Constructors #region Public Instance Properties /// <summary> /// Gets the key names. /// </summary> /// <returns>An array of all the keys.</returns> /// <remarks> /// <para> /// Gets the key names. /// </para> /// </remarks> public string[] GetKeys() { string[] keys = new String[InnerHashtable.Count]; InnerHashtable.Keys.CopyTo(keys, 0); return keys; } /// <summary> /// Gets or sets the value of the property with the specified key. /// </summary> /// <value> /// The value of the property with the specified key. /// </value> /// <param name="key">The key of the property to get or set.</param> /// <remarks> /// <para> /// The property value will only be serialized if it is serializable. /// If it cannot be serialized it will be silently ignored if /// a serialization operation is performed. /// </para> /// </remarks> public virtual object this[string key] { get { return InnerHashtable[key]; } set { throw new NotSupportedException("This is a Read Only Dictionary and can not be modified"); } } #endregion Public Instance Properties #region Public Instance Methods /// <summary> /// Test if the dictionary contains a specified key /// </summary> /// <param name="key">the key to look for</param> /// <returns>true if the dictionary contains the specified key</returns> /// <remarks> /// <para> /// Test if the dictionary contains a specified key /// </para> /// </remarks> public bool Contains(string key) { return InnerHashtable.Contains(key); } #endregion /// <summary> /// The hashtable used to store the properties /// </summary> /// <value> /// The internal collection used to store the properties /// </value> /// <remarks> /// <para> /// The hashtable used to store the properties /// </para> /// </remarks> protected Hashtable InnerHashtable { get { return m_hashtable; } } #region Implementation of ISerializable #if !NETCF /// <summary> /// Serializes this object into the <see cref="SerializationInfo" /> provided. /// </summary> /// <param name="info">The <see cref="SerializationInfo" /> to populate with data.</param> /// <param name="context">The destination for this serialization.</param> /// <remarks> /// <para> /// Serializes this object into the <see cref="SerializationInfo" /> provided. /// </para> /// </remarks> #if NET_4_0 [System.Security.SecurityCritical] #else [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.Demand, SerializationFormatter=true)] #endif public virtual void GetObjectData(SerializationInfo info, StreamingContext context) { foreach(DictionaryEntry entry in InnerHashtable) { string entryKey = entry.Key as string; object entryValue = entry.Value; // If value is serializable then we add it to the list if (entryKey != null && entryValue != null && entryValue.GetType().IsSerializable) { // Store the keys as an Xml encoded local name as it may contain colons (':') // which are NOT escaped by the Xml Serialization framework. // This must be a bug in the serialization framework as we cannot be expected // to know the implementation details of all the possible transport layers. info.AddValue(XmlConvert.EncodeLocalName(entryKey), entryValue); } } } #endif #endregion Implementation of ISerializable #region Implementation of IDictionary /// <summary> /// See <see cref="IDictionary.GetEnumerator"/> /// </summary> IDictionaryEnumerator IDictionary.GetEnumerator() { return InnerHashtable.GetEnumerator(); } /// <summary> /// See <see cref="IDictionary.Remove"/> /// </summary> /// <param name="key"></param> void IDictionary.Remove(object key) { throw new NotSupportedException("This is a Read Only Dictionary and can not be modified"); } /// <summary> /// See <see cref="IDictionary.Contains"/> /// </summary> /// <param name="key"></param> /// <returns></returns> bool IDictionary.Contains(object key) { return InnerHashtable.Contains(key); } /// <summary> /// Remove all properties from the properties collection /// </summary> public virtual void Clear() { throw new NotSupportedException("This is a Read Only Dictionary and can not be modified"); } /// <summary> /// See <see cref="IDictionary.Add"/> /// </summary> /// <param name="key"></param> /// <param name="value"></param> void IDictionary.Add(object key, object value) { throw new NotSupportedException("This is a Read Only Dictionary and can not be modified"); } /// <summary> /// See <see cref="IDictionary.IsReadOnly"/> /// </summary> bool IDictionary.IsReadOnly { get { return true; } } /// <summary> /// See <see cref="IDictionary.this[object]"/> /// </summary> object IDictionary.this[object key] { get { if (!(key is string)) throw new ArgumentException("key must be a string"); return InnerHashtable[key]; } set { throw new NotSupportedException("This is a Read Only Dictionary and can not be modified"); } } /// <summary> /// See <see cref="IDictionary.Values"/> /// </summary> ICollection IDictionary.Values { get { return InnerHashtable.Values; } } /// <summary> /// See <see cref="IDictionary.Keys"/> /// </summary> ICollection IDictionary.Keys { get { return InnerHashtable.Keys; } } /// <summary> /// See <see cref="IDictionary.IsFixedSize"/> /// </summary> bool IDictionary.IsFixedSize { get { return InnerHashtable.IsFixedSize; } } #endregion #region Implementation of ICollection /// <summary> /// See <see cref="ICollection.CopyTo"/> /// </summary> /// <param name="array"></param> /// <param name="index"></param> void ICollection.CopyTo(Array array, int index) { InnerHashtable.CopyTo(array, index); } /// <summary> /// See <see cref="ICollection.IsSynchronized"/> /// </summary> bool ICollection.IsSynchronized { get { return InnerHashtable.IsSynchronized; } } /// <summary> /// The number of properties in this collection /// </summary> public int Count { get { return InnerHashtable.Count; } } /// <summary> /// See <see cref="ICollection.SyncRoot"/> /// </summary> object ICollection.SyncRoot { get { return InnerHashtable.SyncRoot; } } #endregion #region Implementation of IEnumerable /// <summary> /// See <see cref="IEnumerable.GetEnumerator"/> /// </summary> IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable)InnerHashtable).GetEnumerator(); } #endregion } }
// Copyright 2014 The Rector & Visitors of the University of Virginia // // 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 Xamarin.Forms; using SensusService.Exceptions; using SensusUI.UiProperties; using Newtonsoft.Json; using System.Threading; using System.Collections.Generic; using System.Linq; using SensusService; using Xamarin; namespace SensusUI.Inputs { public abstract class Input { private string _name; private string _id; private string _groupId; private string _labelText; private int _labelFontSize; private View _view; private bool _displayNumber; private bool _complete; private bool _needsToBeStored; private double? _latitude; private double? _longitude; private DateTimeOffset? _locationUpdateTimestamp; private bool _required; private bool _viewed; private DateTimeOffset? _completionTimestamp; private List<InputDisplayCondition> _displayConditions; private Color? _backgroundColor; private Thickness? _padding; private bool _frame; private List<InputCompletionRecord> _completionRecords; [EntryStringUiProperty("Name:", true, 0)] public string Name { get{ return _name; } set{ _name = value; } } public string Id { get { return _id; } set { _id = value; } } public string GroupId { get { return _groupId; } set { _groupId = value; } } [EntryStringUiProperty("Label Text:", true, 1)] public string LabelText { get { return _labelText; } set { _labelText = value; } } public int LabelFontSize { get { return _labelFontSize; } set { _labelFontSize = value; } } public bool DisplayNumber { get { return _displayNumber; } set { _displayNumber = value; } } [JsonIgnore] public abstract object Value { get; } /// <summary> /// Gets or sets a value indicating whether the user has interacted with this <see cref="SensusUI.Inputs.Input"/>, /// leaving it in a state of completion. Contrast with Valid, which merely indicates that the /// state of the input will not prevent the user from moving through an input request (e.g., in the case /// of inputs that are not required). /// </summary> /// <value><c>true</c> if complete; otherwise, <c>false</c>.</value> [JsonIgnore] public bool Complete { get { return _complete; } protected set { _complete = value; DateTimeOffset timestamp = DateTimeOffset.UtcNow; object inputValue = null; _completionTimestamp = null; if (_complete) { _completionTimestamp = timestamp; // get a deep copy of the value. some inputs have list values, and simply using the list reference wouldn't track the history, since the most up-to-date list would be used for all history values. inputValue = JsonConvert.DeserializeObject<object>(JsonConvert.SerializeObject(Value, SensusServiceHelper.JSON_SERIALIZER_SETTINGS), SensusServiceHelper.JSON_SERIALIZER_SETTINGS); } if (StoreCompletionRecords) _completionRecords.Add(new InputCompletionRecord(timestamp, inputValue)); } } /// <summary> /// Gets a value indicating whether this <see cref="SensusUI.Inputs.Input"/> is valid. A valid input is one that /// is complete, one that has been viewed but is not required, or one that isn't displayed. In short, it is an /// input state that should not prevent the user from proceeding through an input request. /// </summary> /// <value><c>true</c> if valid; otherwise, <c>false</c>.</value> [JsonIgnore] public bool Valid { get { return _complete || _viewed && !_required || !Display; } } public bool NeedsToBeStored { get { return _needsToBeStored; } set { _needsToBeStored = value; } } public double? Latitude { get { return _latitude; } set { _latitude = value; } } public double? Longitude { get { return _longitude; } set { _longitude = value; } } public DateTimeOffset? LocationUpdateTimestamp { get { return _locationUpdateTimestamp; } set { _locationUpdateTimestamp = value; } } [JsonIgnore] public abstract bool Enabled { get; set; } [JsonIgnore] public abstract string DefaultName { get; } [OnOffUiProperty(null, true, 5)] public bool Required { get { return _required; } set { _required = value; } } public bool Viewed { get { return _viewed; } set { _viewed = value; } } [JsonIgnore] public DateTimeOffset? CompletionTimestamp { get { return _completionTimestamp; } } public List<InputDisplayCondition> DisplayConditions { get { return _displayConditions; } } public Color? BackgroundColor { get { return _backgroundColor; } set { _backgroundColor = value; } } public Thickness? Padding { get { return _padding; } set { _padding = value; } } public bool Frame { get { return _frame; } set { _frame = value; } } public List<InputCompletionRecord> CompletionRecords { get { return _completionRecords; } } public virtual bool StoreCompletionRecords { get { return true; } } [JsonIgnore] public bool Display { get { List<InputDisplayCondition> conjuncts = _displayConditions.Where(displayCondition => displayCondition.Conjunctive).ToList(); if (conjuncts.Count > 0 && conjuncts.Any(displayCondition => !displayCondition.Satisfied)) return false; List<InputDisplayCondition> disjuncts = _displayConditions.Where(displayCondition => !displayCondition.Conjunctive).ToList(); if (disjuncts.Count > 0 && disjuncts.All(displayCondition => !displayCondition.Satisfied)) return false; return true; } } public Input() { _name = DefaultName; _id = Guid.NewGuid().ToString(); _displayNumber = true; _complete = false; _needsToBeStored = true; _required = true; _viewed = false; _completionTimestamp = null; _labelFontSize = 20; _displayConditions = new List<InputDisplayCondition>(); _backgroundColor = null; _padding = null; _frame = true; _completionRecords = new List<InputCompletionRecord>(); } public Input(string labelText) : this() { _labelText = labelText; } public Input(string labelText, int labelFontSize) : this(labelText) { _labelFontSize = labelFontSize; } public Input(string name, string labelText) : this(labelText) { _name = name; } protected Label CreateLabel(int index) { return new Label { Text = GetLabelText(index), FontSize = _labelFontSize // set the style ID on the label so that we can retrieve it when unit testing #if UNIT_TESTING , StyleId = Name + " Label" #endif }; } protected string GetLabelText(int index) { return string.IsNullOrWhiteSpace(_labelText) ? "" : (_required ? "*" : "") + (index > 0 && _displayNumber ? index + ") " : "") + _labelText; } public virtual View GetView(int index) { return _view; } protected virtual void SetView(View value) { ContentView viewContainer = new ContentView { Content = value }; if (_backgroundColor != null) viewContainer.BackgroundColor = _backgroundColor.GetValueOrDefault(); if (_padding != null) viewContainer.Padding = _padding.GetValueOrDefault(); _view = viewContainer; } public void Reset() { _view = null; _complete = false; _needsToBeStored = true; _latitude = null; _longitude = null; _locationUpdateTimestamp = null; _viewed = false; _completionTimestamp = null; _backgroundColor = null; _padding = null; } public virtual bool ValueMatches(object conditionValue, bool conjunctive) { // if either is null, both must be null to be equal if (Value == null || conditionValue == null) return Value == null && conditionValue == null; // if they're of the same type, compare else if (Value.GetType().Equals(conditionValue.GetType())) return Value.Equals(conditionValue); else { // this should never happen try { Insights.Report(new Exception("Called Input.ValueMatches with conditionValue of type " + conditionValue.GetType() + ". Comparing with value of type " + Value.GetType() + "."), Insights.Severity.Critical); } catch (Exception) { } return false; } } public override string ToString() { return _name + (_name == DefaultName ? "" : " -- " + DefaultName) + (_required ? "*" : ""); } public Input Copy() { Input copy = JsonConvert.DeserializeObject<Input>(JsonConvert.SerializeObject(this, SensusServiceHelper.JSON_SERIALIZER_SETTINGS), SensusServiceHelper.JSON_SERIALIZER_SETTINGS); copy.Reset(); return copy; } } }
// 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. // ------------------------------------------------------------------------------ // Changes to this file must follow the http://aka.ms/api-review process. // ------------------------------------------------------------------------------ namespace System.Collections.Concurrent { public partial class BlockingCollection<T> : System.Collections.Generic.IEnumerable<T>, System.Collections.Generic.IReadOnlyCollection<T>, System.Collections.ICollection, System.Collections.IEnumerable, System.IDisposable { public BlockingCollection() { } public BlockingCollection(System.Collections.Concurrent.IProducerConsumerCollection<T> collection) { } public BlockingCollection(System.Collections.Concurrent.IProducerConsumerCollection<T> collection, int boundedCapacity) { } public BlockingCollection(int boundedCapacity) { } public int BoundedCapacity { get { throw null; } } public int Count { get { throw null; } } public bool IsAddingCompleted { get { throw null; } } public bool IsCompleted { get { throw null; } } bool System.Collections.ICollection.IsSynchronized { get { throw null; } } object System.Collections.ICollection.SyncRoot { get { throw null; } } public void Add(T item) { } public void Add(T item, System.Threading.CancellationToken cancellationToken) { } public static int AddToAny(System.Collections.Concurrent.BlockingCollection<T>[] collections, T item) { throw null; } public static int AddToAny(System.Collections.Concurrent.BlockingCollection<T>[] collections, T item, System.Threading.CancellationToken cancellationToken) { throw null; } public void CompleteAdding() { } public void CopyTo(T[] array, int index) { } public void Dispose() { } protected virtual void Dispose(bool disposing) { } public System.Collections.Generic.IEnumerable<T> GetConsumingEnumerable() { throw null; } public System.Collections.Generic.IEnumerable<T> GetConsumingEnumerable(System.Threading.CancellationToken cancellationToken) { throw null; } System.Collections.Generic.IEnumerator<T> System.Collections.Generic.IEnumerable<T>.GetEnumerator() { throw null; } void System.Collections.ICollection.CopyTo(System.Array array, int index) { } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; } public T Take() { throw null; } public T Take(System.Threading.CancellationToken cancellationToken) { throw null; } public static int TakeFromAny(System.Collections.Concurrent.BlockingCollection<T>[] collections, [System.Diagnostics.CodeAnalysis.MaybeNullAttribute] out T item) { throw null; } public static int TakeFromAny(System.Collections.Concurrent.BlockingCollection<T>[] collections, [System.Diagnostics.CodeAnalysis.MaybeNullAttribute] out T item, System.Threading.CancellationToken cancellationToken) { throw null; } public T[] ToArray() { throw null; } public bool TryAdd(T item) { throw null; } public bool TryAdd(T item, int millisecondsTimeout) { throw null; } public bool TryAdd(T item, int millisecondsTimeout, System.Threading.CancellationToken cancellationToken) { throw null; } public bool TryAdd(T item, System.TimeSpan timeout) { throw null; } public static int TryAddToAny(System.Collections.Concurrent.BlockingCollection<T>[] collections, T item) { throw null; } public static int TryAddToAny(System.Collections.Concurrent.BlockingCollection<T>[] collections, T item, int millisecondsTimeout) { throw null; } public static int TryAddToAny(System.Collections.Concurrent.BlockingCollection<T>[] collections, T item, int millisecondsTimeout, System.Threading.CancellationToken cancellationToken) { throw null; } public static int TryAddToAny(System.Collections.Concurrent.BlockingCollection<T>[] collections, T item, System.TimeSpan timeout) { throw null; } public bool TryTake([System.Diagnostics.CodeAnalysis.MaybeNullWhenAttribute(false)] out T item) { throw null; } public bool TryTake([System.Diagnostics.CodeAnalysis.MaybeNullWhenAttribute(false)] out T item, int millisecondsTimeout) { throw null; } public bool TryTake([System.Diagnostics.CodeAnalysis.MaybeNullWhenAttribute(false)] out T item, int millisecondsTimeout, System.Threading.CancellationToken cancellationToken) { throw null; } public bool TryTake([System.Diagnostics.CodeAnalysis.MaybeNullWhenAttribute(false)] out T item, System.TimeSpan timeout) { throw null; } public static int TryTakeFromAny(System.Collections.Concurrent.BlockingCollection<T>[] collections, [System.Diagnostics.CodeAnalysis.MaybeNullAttribute] out T item) { throw null; } public static int TryTakeFromAny(System.Collections.Concurrent.BlockingCollection<T>[] collections, [System.Diagnostics.CodeAnalysis.MaybeNullAttribute] out T item, int millisecondsTimeout) { throw null; } public static int TryTakeFromAny(System.Collections.Concurrent.BlockingCollection<T>[] collections, [System.Diagnostics.CodeAnalysis.MaybeNullAttribute] out T item, int millisecondsTimeout, System.Threading.CancellationToken cancellationToken) { throw null; } public static int TryTakeFromAny(System.Collections.Concurrent.BlockingCollection<T>[] collections, [System.Diagnostics.CodeAnalysis.MaybeNullAttribute] out T item, System.TimeSpan timeout) { throw null; } } public partial class ConcurrentBag<T> : System.Collections.Concurrent.IProducerConsumerCollection<T>, System.Collections.Generic.IEnumerable<T>, System.Collections.Generic.IReadOnlyCollection<T>, System.Collections.ICollection, System.Collections.IEnumerable { public ConcurrentBag() { } public ConcurrentBag(System.Collections.Generic.IEnumerable<T> collection) { } public int Count { get { throw null; } } public bool IsEmpty { get { throw null; } } bool System.Collections.ICollection.IsSynchronized { get { throw null; } } object System.Collections.ICollection.SyncRoot { get { throw null; } } public void Add(T item) { } public void Clear() { } public void CopyTo(T[] array, int index) { } public System.Collections.Generic.IEnumerator<T> GetEnumerator() { throw null; } bool System.Collections.Concurrent.IProducerConsumerCollection<T>.TryAdd(T item) { throw null; } void System.Collections.ICollection.CopyTo(System.Array array, int index) { } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; } public T[] ToArray() { throw null; } public bool TryPeek([System.Diagnostics.CodeAnalysis.MaybeNullWhenAttribute(false)] out T result) { throw null; } public bool TryTake([System.Diagnostics.CodeAnalysis.MaybeNullWhenAttribute(false)] out T result) { throw null; } } public partial class ConcurrentDictionary<TKey, TValue> : System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey, TValue>>, System.Collections.Generic.IDictionary<TKey, TValue>, System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<TKey, TValue>>, System.Collections.Generic.IReadOnlyCollection<System.Collections.Generic.KeyValuePair<TKey, TValue>>, System.Collections.Generic.IReadOnlyDictionary<TKey, TValue>, System.Collections.ICollection, System.Collections.IDictionary, System.Collections.IEnumerable where TKey : notnull { public ConcurrentDictionary() { } public ConcurrentDictionary(System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<TKey, TValue>> collection) { } public ConcurrentDictionary(System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<TKey, TValue>> collection, System.Collections.Generic.IEqualityComparer<TKey>? comparer) { } public ConcurrentDictionary(System.Collections.Generic.IEqualityComparer<TKey>? comparer) { } public ConcurrentDictionary(int concurrencyLevel, System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<TKey, TValue>> collection, System.Collections.Generic.IEqualityComparer<TKey>? comparer) { } public ConcurrentDictionary(int concurrencyLevel, int capacity) { } public ConcurrentDictionary(int concurrencyLevel, int capacity, System.Collections.Generic.IEqualityComparer<TKey>? comparer) { } public int Count { get { throw null; } } public bool IsEmpty { get { throw null; } } public TValue this[TKey key] { get { throw null; } set { } } public System.Collections.Generic.ICollection<TKey> Keys { get { throw null; } } bool System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey, TValue>>.IsReadOnly { get { throw null; } } System.Collections.Generic.IEnumerable<TKey> System.Collections.Generic.IReadOnlyDictionary<TKey, TValue>.Keys { get { throw null; } } System.Collections.Generic.IEnumerable<TValue> System.Collections.Generic.IReadOnlyDictionary<TKey, TValue>.Values { get { throw null; } } bool System.Collections.ICollection.IsSynchronized { get { throw null; } } object System.Collections.ICollection.SyncRoot { get { throw null; } } bool System.Collections.IDictionary.IsFixedSize { get { throw null; } } bool System.Collections.IDictionary.IsReadOnly { get { throw null; } } object? System.Collections.IDictionary.this[object key] { get { throw null; } set { } } System.Collections.ICollection System.Collections.IDictionary.Keys { get { throw null; } } System.Collections.ICollection System.Collections.IDictionary.Values { get { throw null; } } public System.Collections.Generic.ICollection<TValue> Values { get { throw null; } } public TValue AddOrUpdate(TKey key, System.Func<TKey, TValue> addValueFactory, System.Func<TKey, TValue, TValue> updateValueFactory) { throw null; } public TValue AddOrUpdate(TKey key, TValue addValue, System.Func<TKey, TValue, TValue> updateValueFactory) { throw null; } public TValue AddOrUpdate<TArg>(TKey key, System.Func<TKey, TArg, TValue> addValueFactory, System.Func<TKey, TValue, TArg, TValue> updateValueFactory, TArg factoryArgument) { throw null; } public void Clear() { } public bool ContainsKey(TKey key) { throw null; } public System.Collections.Generic.IEnumerator<System.Collections.Generic.KeyValuePair<TKey, TValue>> GetEnumerator() { throw null; } public TValue GetOrAdd(TKey key, System.Func<TKey, TValue> valueFactory) { throw null; } public TValue GetOrAdd(TKey key, TValue value) { throw null; } public TValue GetOrAdd<TArg>(TKey key, System.Func<TKey, TArg, TValue> valueFactory, TArg factoryArgument) { throw null; } void System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey, TValue>>.Add(System.Collections.Generic.KeyValuePair<TKey, TValue> keyValuePair) { } bool System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey, TValue>>.Contains(System.Collections.Generic.KeyValuePair<TKey, TValue> keyValuePair) { throw null; } void System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey, TValue>>.CopyTo(System.Collections.Generic.KeyValuePair<TKey, TValue>[] array, int index) { } bool System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey, TValue>>.Remove(System.Collections.Generic.KeyValuePair<TKey, TValue> keyValuePair) { throw null; } void System.Collections.Generic.IDictionary<TKey, TValue>.Add(TKey key, TValue value) { } bool System.Collections.Generic.IDictionary<TKey, TValue>.Remove(TKey key) { throw null; } void System.Collections.ICollection.CopyTo(System.Array array, int index) { } void System.Collections.IDictionary.Add(object key, object? value) { } bool System.Collections.IDictionary.Contains(object key) { throw null; } System.Collections.IDictionaryEnumerator System.Collections.IDictionary.GetEnumerator() { throw null; } void System.Collections.IDictionary.Remove(object key) { } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; } public System.Collections.Generic.KeyValuePair<TKey, TValue>[] ToArray() { throw null; } public bool TryAdd(TKey key, TValue value) { throw null; } public bool TryGetValue(TKey key, [System.Diagnostics.CodeAnalysis.MaybeNullWhenAttribute(false)] out TValue value) { throw null; } public bool TryRemove(TKey key, [System.Diagnostics.CodeAnalysis.MaybeNullWhenAttribute(false)] out TValue value) { throw null; } public bool TryUpdate(TKey key, TValue newValue, TValue comparisonValue) { throw null; } } public partial class ConcurrentQueue<T> : System.Collections.Concurrent.IProducerConsumerCollection<T>, System.Collections.Generic.IEnumerable<T>, System.Collections.Generic.IReadOnlyCollection<T>, System.Collections.ICollection, System.Collections.IEnumerable { public ConcurrentQueue() { } public ConcurrentQueue(System.Collections.Generic.IEnumerable<T> collection) { } public int Count { get { throw null; } } public bool IsEmpty { get { throw null; } } bool System.Collections.ICollection.IsSynchronized { get { throw null; } } object System.Collections.ICollection.SyncRoot { get { throw null; } } public void Clear() { } public void CopyTo(T[] array, int index) { } public void Enqueue(T item) { } public System.Collections.Generic.IEnumerator<T> GetEnumerator() { throw null; } bool System.Collections.Concurrent.IProducerConsumerCollection<T>.TryAdd(T item) { throw null; } bool System.Collections.Concurrent.IProducerConsumerCollection<T>.TryTake(out T item) { throw null; } void System.Collections.ICollection.CopyTo(System.Array array, int index) { } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; } public T[] ToArray() { throw null; } public bool TryDequeue([System.Diagnostics.CodeAnalysis.MaybeNullWhenAttribute(false)] out T result) { throw null; } public bool TryPeek([System.Diagnostics.CodeAnalysis.MaybeNullWhenAttribute(false)] out T result) { throw null; } } public partial class ConcurrentStack<T> : System.Collections.Concurrent.IProducerConsumerCollection<T>, System.Collections.Generic.IEnumerable<T>, System.Collections.Generic.IReadOnlyCollection<T>, System.Collections.ICollection, System.Collections.IEnumerable { public ConcurrentStack() { } public ConcurrentStack(System.Collections.Generic.IEnumerable<T> collection) { } public int Count { get { throw null; } } public bool IsEmpty { get { throw null; } } bool System.Collections.ICollection.IsSynchronized { get { throw null; } } object System.Collections.ICollection.SyncRoot { get { throw null; } } public void Clear() { } public void CopyTo(T[] array, int index) { } public System.Collections.Generic.IEnumerator<T> GetEnumerator() { throw null; } public void Push(T item) { } public void PushRange(T[] items) { } public void PushRange(T[] items, int startIndex, int count) { } bool System.Collections.Concurrent.IProducerConsumerCollection<T>.TryAdd(T item) { throw null; } bool System.Collections.Concurrent.IProducerConsumerCollection<T>.TryTake(out T item) { throw null; } void System.Collections.ICollection.CopyTo(System.Array array, int index) { } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; } public T[] ToArray() { throw null; } public bool TryPeek([System.Diagnostics.CodeAnalysis.MaybeNullWhenAttribute(false)] out T result) { throw null; } public bool TryPop([System.Diagnostics.CodeAnalysis.MaybeNullWhenAttribute(false)] out T result) { throw null; } public int TryPopRange(T[] items) { throw null; } public int TryPopRange(T[] items, int startIndex, int count) { throw null; } } [System.FlagsAttribute] public enum EnumerablePartitionerOptions { None = 0, NoBuffering = 1, } public partial interface IProducerConsumerCollection<T> : System.Collections.Generic.IEnumerable<T>, System.Collections.ICollection, System.Collections.IEnumerable { void CopyTo(T[] array, int index); T[] ToArray(); bool TryAdd(T item); bool TryTake([System.Diagnostics.CodeAnalysis.MaybeNullWhenAttribute(false)] out T item); } public abstract partial class OrderablePartitioner<TSource> : System.Collections.Concurrent.Partitioner<TSource> { protected OrderablePartitioner(bool keysOrderedInEachPartition, bool keysOrderedAcrossPartitions, bool keysNormalized) { } public bool KeysNormalized { get { throw null; } } public bool KeysOrderedAcrossPartitions { get { throw null; } } public bool KeysOrderedInEachPartition { get { throw null; } } public override System.Collections.Generic.IEnumerable<TSource> GetDynamicPartitions() { throw null; } public virtual System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<long, TSource>> GetOrderableDynamicPartitions() { throw null; } public abstract System.Collections.Generic.IList<System.Collections.Generic.IEnumerator<System.Collections.Generic.KeyValuePair<long, TSource>>> GetOrderablePartitions(int partitionCount); public override System.Collections.Generic.IList<System.Collections.Generic.IEnumerator<TSource>> GetPartitions(int partitionCount) { throw null; } } public static partial class Partitioner { public static System.Collections.Concurrent.OrderablePartitioner<System.Tuple<int, int>> Create(int fromInclusive, int toExclusive) { throw null; } public static System.Collections.Concurrent.OrderablePartitioner<System.Tuple<int, int>> Create(int fromInclusive, int toExclusive, int rangeSize) { throw null; } public static System.Collections.Concurrent.OrderablePartitioner<System.Tuple<long, long>> Create(long fromInclusive, long toExclusive) { throw null; } public static System.Collections.Concurrent.OrderablePartitioner<System.Tuple<long, long>> Create(long fromInclusive, long toExclusive, long rangeSize) { throw null; } public static System.Collections.Concurrent.OrderablePartitioner<TSource> Create<TSource>(System.Collections.Generic.IEnumerable<TSource> source) { throw null; } public static System.Collections.Concurrent.OrderablePartitioner<TSource> Create<TSource>(System.Collections.Generic.IEnumerable<TSource> source, System.Collections.Concurrent.EnumerablePartitionerOptions partitionerOptions) { throw null; } public static System.Collections.Concurrent.OrderablePartitioner<TSource> Create<TSource>(System.Collections.Generic.IList<TSource> list, bool loadBalance) { throw null; } public static System.Collections.Concurrent.OrderablePartitioner<TSource> Create<TSource>(TSource[] array, bool loadBalance) { throw null; } } public abstract partial class Partitioner<TSource> { protected Partitioner() { } public virtual bool SupportsDynamicPartitions { get { throw null; } } public virtual System.Collections.Generic.IEnumerable<TSource> GetDynamicPartitions() { throw null; } public abstract System.Collections.Generic.IList<System.Collections.Generic.IEnumerator<TSource>> GetPartitions(int partitionCount); } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Newtonsoft.Json; using StackExchange.Redis; using StackExchange.Redis.Extensions.Core.Configuration; namespace Aqovia.Utilities.SagaMachine.StatePersistance { public class RedisKeyValueStore : IKeyValueStore, IDisposable { private const double DefaultLockExpiryTime = 30000; private readonly RedisCachingSectionHandler _redisConfiguration; private readonly ConnectionMultiplexer _redis; public RedisKeyValueStore() { _redisConfiguration = RedisCachingSectionHandler.GetConfig(); var configurationOptions = new ConfigurationOptions { ConnectTimeout = _redisConfiguration.ConnectTimeout, Ssl = _redisConfiguration.Ssl, Password = Environment.ExpandEnvironmentVariables(_redisConfiguration.Password).Trim() }; foreach (RedisHost redisHost in _redisConfiguration.RedisHosts) { configurationOptions.EndPoints.Add( Environment.ExpandEnvironmentVariables(redisHost.Host).Trim(), redisHost.CachePort ); } _redis = ConnectionMultiplexer.Connect(configurationOptions); } public RedisKeyValueStore(string connectionString) { _redis = ConnectionMultiplexer.Connect(connectionString); } private IDatabase GetDatabase() { var db = _redisConfiguration == null ? _redis.GetDatabase() : _redis.GetDatabase(_redisConfiguration.Database); return db; } public HashedValue<T> GetValue<T>(string key) { IDatabase db = GetDatabase(); ITransaction trans; Task<RedisValue> result; string currentHash; do { currentHash = db.HashGet(key, "hash"); trans = db.CreateTransaction(); trans.AddCondition(Condition.HashEqual(key, "hash", currentHash)); result = trans.HashGetAsync(key, "value"); } while (!trans.Execute()); return new HashedValue<T> { Value = ((string)result.Result) != null ? JsonConvert.DeserializeObject<T>(result.Result) : default(T), Hash = currentHash }; } public bool TrySetValue<T>(string key, T value, string oldHash) { IDatabase db = GetDatabase(); if (string.IsNullOrEmpty(oldHash)) {//We are creating a new entry Guid hashGuid = Guid.NewGuid(); var trans = db.CreateTransaction(); trans.AddCondition(Condition.KeyNotExists(key)); trans.HashSetAsync(key, "value", JsonConvert.SerializeObject(value)); trans.HashSetAsync(key, "hash", hashGuid.ToString()); return trans.Execute(); } else {//try and update instead Guid newHashGuid = Guid.NewGuid(); var trans = db.CreateTransaction(); trans.AddCondition(Condition.HashEqual(key, "hash", oldHash)); trans.HashSetAsync(key, "value", JsonConvert.SerializeObject(value)); trans.HashSetAsync(key, "hash", newHashGuid.ToString()); return trans.Execute(); } } public bool Remove(string key, string oldHash) { IDatabase db = GetDatabase(); var trans = db.CreateTransaction(); trans.AddCondition(Condition.HashEqual(key, "hash", oldHash)); trans.KeyDeleteAsync(key); return trans.Execute(); } public TimeSpan Ping() { IDatabase db = GetDatabase(); return db.Ping(); } public void Remove(string key) { IDatabase db = GetDatabase(); db.KeyDelete(key); } /// <summary> /// Request lock against key value element /// Lock lifespan 500 milliseconds /// </summary> /// <param name="key"></param> /// <param name="lockToken"></param> /// <returns></returns> public async Task<bool> TakeLockWithDefaultExpiryTime(string key, Guid lockToken) { return await TakeLock(key, lockToken, DefaultLockExpiryTime); } /// <summary> /// Request lock against key value element /// Lock has lifespan specified in milliseconds /// </summary> /// <param name="key"></param> /// <param name="lockToken"></param> /// <param name="milliseconds"></param> /// <returns></returns> public async Task<bool> TakeLock(string key, Guid lockToken, double milliseconds) { var maxNumberOfAttempts = 3; var currentRetry = 0; var db = GetDatabase(); while(true) { currentRetry++; try { var redisLockKey = string.Format("lock_{0}", key); var trans = db.CreateTransaction(); trans.AddCondition(Condition.KeyNotExists(redisLockKey)); var acquireLockTask = trans.LockTakeAsync(redisLockKey, lockToken.ToString(), TimeSpan.MaxValue).ConfigureAwait(false); var setExpiryTimeTask = trans.KeyExpireAsync(redisLockKey, TimeSpan.FromMilliseconds(milliseconds)).ConfigureAwait(false); /* This is added to workaround bug discovered in the Redis client. Remove this line if bug resolved. Detail can be found here: https://github.com/StackExchange/StackExchange.Redis/issues/415 */ trans.Execute(); var hasLock = await acquireLockTask; var hasSucceedToSetExpiryTime = await setExpiryTimeTask; if (!hasSucceedToSetExpiryTime) { // Note: this should never happen, however to be safe we handle this very improbable case throw new Exception(string.Format("Unable to set expiry time for Redis key \"{0}\". Key needs to be removed manually from Redis.", redisLockKey)); } if (currentRetry > maxNumberOfAttempts) { return hasLock; } if (hasLock) { return true; } } catch (TaskCanceledException) { // LockTakeAsync throws a TaskCanceledException when it fails to acquire the lock // If failed then retry based on the logic in the error detection strategy // Determine whether to retry the operation, as well as how // long to wait, based on the retry strategy. if (currentRetry > maxNumberOfAttempts) { return false; } } // Wait to retry the operation. // Consider calculating an exponential delay here and // using a strategy best suited for the operation and fault. await Task.Delay(((int)Math.Pow(3, currentRetry)) * 500).ConfigureAwait(false); } } public async Task<bool> ReleaseLock(string key, Guid lockToken) { var db = GetDatabase(); var redisLockKey = string.Format("lock_{0}", key); return await db.LockReleaseAsync(redisLockKey, lockToken.ToString()).ConfigureAwait(false); } public void Dispose() { _redis.Close(); } } }
using Kitware.VTK; using System; // input file is C:\VTK\Graphics\Testing\Tcl\multipleIso.tcl // output file is AVmultipleIso.cs /// <summary> /// The testing class derived from AVmultipleIso /// </summary> public class AVmultipleIsoClass { /// <summary> /// The main entry method called by the CSharp driver /// </summary> /// <param name="argv"></param> public static void AVmultipleIso(String [] argv) { //Prefix Content is: "" // get the interactor ui[] //# Graphics stuff[] // Create the RenderWindow, Renderer and both Actors[] //[] ren1 = vtkRenderer.New(); renWin = vtkRenderWindow.New(); renWin.AddRenderer((vtkRenderer)ren1); iren = new vtkRenderWindowInteractor(); iren.SetRenderWindow((vtkRenderWindow)renWin); pl3d = new vtkPLOT3DReader(); pl3d.SetXYZFileName((string)"" + (VTK_DATA_ROOT.ToString()) + "/Data/combxyz.bin"); pl3d.SetQFileName((string)"" + (VTK_DATA_ROOT.ToString()) + "/Data/combq.bin"); pl3d.SetScalarFunctionNumber((int)100); pl3d.SetVectorFunctionNumber((int)202); pl3d.Update(); range = pl3d.GetOutput().GetPointData().GetScalars().GetRange(); min = (double)(lindex(range,0)); max = (double)(lindex(range,1)); value = (min+max)/2.0; cf = new vtkContourFilter(); cf.SetInputConnection((vtkAlgorithmOutput)pl3d.GetOutputPort()); cf.SetValue((int)0,(double)value); cf.UseScalarTreeOn(); numberOfContours = 5; epsilon = (double)(max-min)/(double)(numberOfContours*10); min = min+epsilon; max = max-epsilon; i = 1; while((i) <= numberOfContours) { cf.SetValue((int)0,(double)min+((i-1)/(double)(numberOfContours-1))*(max-min)); cf.Update(); pd[i] = new vtkPolyData(); pd[i].CopyStructure((vtkDataSet)cf.GetOutput()); pd[i].GetPointData().DeepCopy((vtkFieldData)cf.GetOutput().GetPointData()); mapper[i] = vtkPolyDataMapper.New(); mapper[i].SetInput((vtkPolyData)pd[i]); mapper[i].SetScalarRange((double)((vtkDataSet)pl3d.GetOutput()).GetPointData().GetScalars().GetRange()[0], (double)((vtkDataSet)pl3d.GetOutput()).GetPointData().GetScalars().GetRange()[1]); actor[i] = new vtkActor(); actor[i].AddPosition((double)0,(double)i*12,(double)0); actor[i].SetMapper((vtkMapper)mapper[i]); ren1.AddActor((vtkProp)actor[i]); i = i + 1; } // Add the actors to the renderer, set the background and size[] //[] ren1.SetBackground((double).3,(double).3,(double).3); renWin.SetSize((int)450,(int)150); cam1 = ren1.GetActiveCamera(); ren1.GetActiveCamera().SetPosition((double)-36.3762,(double)32.3855,(double)51.3652); ren1.GetActiveCamera().SetFocalPoint((double)8.255,(double)33.3861,(double)29.7687); ren1.GetActiveCamera().SetViewAngle((double)30); ren1.GetActiveCamera().SetViewUp((double)0,(double)0,(double)1); ren1.ResetCameraClippingRange(); iren.Initialize(); // render the image[] //[] // prevent the tk window from showing up then start the event loop[] //deleteAllVTKObjects(); } static string VTK_DATA_ROOT; static int threshold; static vtkRenderer ren1; static vtkRenderWindow renWin; static vtkRenderWindowInteractor iren; static vtkPLOT3DReader pl3d; static double[] range; static double min; static double max; static double value; static vtkContourFilter cf; static int numberOfContours; static double epsilon; static int i; static vtkPolyData[] pd = new vtkPolyData[100]; static vtkPolyDataMapper[] mapper = new vtkPolyDataMapper[100]; static vtkActor[] actor = new vtkActor[100]; static vtkCamera cam1; /// <summary> /// Returns the variable in the index [i] of the System.Array [arr] /// </summary> /// <param name="arr"></param> /// <param name="i"></param> public static Object lindex(System.Array arr, int i) { return arr.GetValue(i); } /// <summary> /// Returns the variable in the index [index] of the array [arr] /// </summary> /// <param name="arr"></param> /// <param name="index"></param> public static double lindex(IntPtr arr, int index) { double[] destination = new double[index + 1]; System.Runtime.InteropServices.Marshal.Copy(arr, destination, 0, index + 1); return destination[index]; } /// <summary> /// Returns the variable in the index [index] of the vtkLookupTable [arr] /// </summary> /// <param name="arr"></param> /// <param name="index"></param> public static long lindex(vtkLookupTable arr, double index) { return arr.GetIndex(index); } /// <summary> /// Returns the substring ([index], [index]+1) in the string [arr] /// </summary> /// <param name="arr"></param> /// <param name="index"></param> public static int lindex(String arr, int index) { string[] str = arr.Split(new char[]{' '}); return System.Int32.Parse(str[index]); } /// <summary> /// Returns the index [index] in the int array [arr] /// </summary> /// <param name="arr"></param> /// <param name="index"></param> public static int lindex(int[] arr, int index) { return arr[index]; } /// <summary> /// Returns the index [index] in the float array [arr] /// </summary> /// <param name="arr"></param> /// <param name="index"></param> public static float lindex(float[] arr, int index) { return arr[index]; } /// <summary> /// Returns the index [index] in the double array [arr] /// </summary> /// <param name="arr"></param> /// <param name="index"></param> public static double lindex(double[] arr, int index) { return arr[index]; } ///<summary> A Get Method for Static Variables </summary> public static string GetVTK_DATA_ROOT() { return VTK_DATA_ROOT; } ///<summary> A Set Method for Static Variables </summary> public static void SetVTK_DATA_ROOT(string toSet) { VTK_DATA_ROOT = toSet; } ///<summary> A Get Method for Static Variables </summary> public static int Getthreshold() { return threshold; } ///<summary> A Set Method for Static Variables </summary> public static void Setthreshold(int toSet) { threshold = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkRenderer Getren1() { return ren1; } ///<summary> A Set Method for Static Variables </summary> public static void Setren1(vtkRenderer toSet) { ren1 = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkRenderWindow GetrenWin() { return renWin; } ///<summary> A Set Method for Static Variables </summary> public static void SetrenWin(vtkRenderWindow toSet) { renWin = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkRenderWindowInteractor Getiren() { return iren; } ///<summary> A Set Method for Static Variables </summary> public static void Setiren(vtkRenderWindowInteractor toSet) { iren = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkPLOT3DReader Getpl3d() { return pl3d; } ///<summary> A Set Method for Static Variables </summary> public static void Setpl3d(vtkPLOT3DReader toSet) { pl3d = toSet; } ///<summary> A Get Method for Static Variables </summary> public static double[] Getrange() { return range; } ///<summary> A Set Method for Static Variables </summary> public static void Setrange(double[] toSet) { range = toSet; } ///<summary> A Get Method for Static Variables </summary> public static double Getmin() { return min; } ///<summary> A Set Method for Static Variables </summary> public static void Setmin(double toSet) { min = toSet; } ///<summary> A Get Method for Static Variables </summary> public static double Getmax() { return max; } ///<summary> A Set Method for Static Variables </summary> public static void Setmax(double toSet) { max = toSet; } ///<summary> A Get Method for Static Variables </summary> public static double Getvalue() { return value; } ///<summary> A Set Method for Static Variables </summary> public static void Setvalue(double toSet) { value = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkContourFilter Getcf() { return cf; } ///<summary> A Set Method for Static Variables </summary> public static void Setcf(vtkContourFilter toSet) { cf = toSet; } ///<summary> A Get Method for Static Variables </summary> public static int GetnumberOfContours() { return numberOfContours; } ///<summary> A Set Method for Static Variables </summary> public static void SetnumberOfContours(int toSet) { numberOfContours = toSet; } ///<summary> A Get Method for Static Variables </summary> public static double Getepsilon() { return epsilon; } ///<summary> A Set Method for Static Variables </summary> public static void Setepsilon(double toSet) { epsilon = toSet; } ///<summary> A Get Method for Static Variables </summary> public static int Geti() { return i; } ///<summary> A Set Method for Static Variables </summary> public static void Seti(int toSet) { i = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkPolyData[] Getpd() { return pd; } ///<summary> A Set Method for Static Variables </summary> public static void Setpd(vtkPolyData[] toSet) { pd = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkPolyDataMapper[] Getmapper() { return mapper; } ///<summary> A Set Method for Static Variables </summary> public static void Setmapper(vtkPolyDataMapper[] toSet) { mapper = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkActor[] Getactor() { return actor; } ///<summary> A Set Method for Static Variables </summary> public static void Setactor(vtkActor[] toSet) { actor = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkCamera Getcam1() { return cam1; } ///<summary> A Set Method for Static Variables </summary> public static void Setcam1(vtkCamera toSet) { cam1 = toSet; } ///<summary>Deletes all static objects created</summary> public static void deleteAllVTKObjects() { //clean up vtk objects if(ren1!= null){ren1.Dispose();} if(renWin!= null){renWin.Dispose();} if(iren!= null){iren.Dispose();} if(pl3d!= null){pl3d.Dispose();} if(cf!= null){cf.Dispose();} if(cam1!= null){cam1.Dispose();} } } //--- end of script --//
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gagvr = Google.Ads.GoogleAds.V8.Resources; using gax = Google.Api.Gax; using gaxgrpc = Google.Api.Gax.Grpc; using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore; using proto = Google.Protobuf; using grpccore = Grpc.Core; using grpcinter = Grpc.Core.Interceptors; using sys = System; using scg = System.Collections.Generic; using sco = System.Collections.ObjectModel; using st = System.Threading; using stt = System.Threading.Tasks; namespace Google.Ads.GoogleAds.V8.Services { /// <summary>Settings for <see cref="ClickViewServiceClient"/> instances.</summary> public sealed partial class ClickViewServiceSettings : gaxgrpc::ServiceSettingsBase { /// <summary>Get a new instance of the default <see cref="ClickViewServiceSettings"/>.</summary> /// <returns>A new instance of the default <see cref="ClickViewServiceSettings"/>.</returns> public static ClickViewServiceSettings GetDefault() => new ClickViewServiceSettings(); /// <summary>Constructs a new <see cref="ClickViewServiceSettings"/> object with default settings.</summary> public ClickViewServiceSettings() { } private ClickViewServiceSettings(ClickViewServiceSettings existing) : base(existing) { gax::GaxPreconditions.CheckNotNull(existing, nameof(existing)); GetClickViewSettings = existing.GetClickViewSettings; OnCopy(existing); } partial void OnCopy(ClickViewServiceSettings existing); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>ClickViewServiceClient.GetClickView</c> and <c>ClickViewServiceClient.GetClickViewAsync</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 GetClickViewSettings { 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="ClickViewServiceSettings"/> object.</returns> public ClickViewServiceSettings Clone() => new ClickViewServiceSettings(this); } /// <summary> /// Builder class for <see cref="ClickViewServiceClient"/> to provide simple configuration of credentials, endpoint /// etc. /// </summary> internal sealed partial class ClickViewServiceClientBuilder : gaxgrpc::ClientBuilderBase<ClickViewServiceClient> { /// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary> public ClickViewServiceSettings Settings { get; set; } /// <summary>Creates a new builder with default settings.</summary> public ClickViewServiceClientBuilder() { UseJwtAccessWithScopes = ClickViewServiceClient.UseJwtAccessWithScopes; } partial void InterceptBuild(ref ClickViewServiceClient client); partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<ClickViewServiceClient> task); /// <summary>Builds the resulting client.</summary> public override ClickViewServiceClient Build() { ClickViewServiceClient client = null; InterceptBuild(ref client); return client ?? BuildImpl(); } /// <summary>Builds the resulting client asynchronously.</summary> public override stt::Task<ClickViewServiceClient> BuildAsync(st::CancellationToken cancellationToken = default) { stt::Task<ClickViewServiceClient> task = null; InterceptBuildAsync(cancellationToken, ref task); return task ?? BuildAsyncImpl(cancellationToken); } private ClickViewServiceClient BuildImpl() { Validate(); grpccore::CallInvoker callInvoker = CreateCallInvoker(); return ClickViewServiceClient.Create(callInvoker, Settings); } private async stt::Task<ClickViewServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken) { Validate(); grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false); return ClickViewServiceClient.Create(callInvoker, Settings); } /// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary> protected override string GetDefaultEndpoint() => ClickViewServiceClient.DefaultEndpoint; /// <summary> /// Returns the default scopes for this builder type, used if no scopes are otherwise specified. /// </summary> protected override scg::IReadOnlyList<string> GetDefaultScopes() => ClickViewServiceClient.DefaultScopes; /// <summary>Returns the channel pool to use when no other options are specified.</summary> protected override gaxgrpc::ChannelPool GetChannelPool() => ClickViewServiceClient.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>ClickViewService client wrapper, for convenient use.</summary> /// <remarks> /// Service to fetch click views. /// </remarks> public abstract partial class ClickViewServiceClient { /// <summary> /// The default endpoint for the ClickViewService 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 ClickViewService scopes.</summary> /// <remarks> /// The default ClickViewService 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="ClickViewServiceClient"/> using the default credentials, endpoint and /// settings. To specify custom credentials or other settings, use <see cref="ClickViewServiceClientBuilder"/>. /// </summary> /// <param name="cancellationToken"> /// The <see cref="st::CancellationToken"/> to use while creating the client. /// </param> /// <returns>The task representing the created <see cref="ClickViewServiceClient"/>.</returns> public static stt::Task<ClickViewServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) => new ClickViewServiceClientBuilder().BuildAsync(cancellationToken); /// <summary> /// Synchronously creates a <see cref="ClickViewServiceClient"/> using the default credentials, endpoint and /// settings. To specify custom credentials or other settings, use <see cref="ClickViewServiceClientBuilder"/>. /// </summary> /// <returns>The created <see cref="ClickViewServiceClient"/>.</returns> public static ClickViewServiceClient Create() => new ClickViewServiceClientBuilder().Build(); /// <summary> /// Creates a <see cref="ClickViewServiceClient"/> 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="ClickViewServiceSettings"/>.</param> /// <returns>The created <see cref="ClickViewServiceClient"/>.</returns> internal static ClickViewServiceClient Create(grpccore::CallInvoker callInvoker, ClickViewServiceSettings settings = null) { gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker)); grpcinter::Interceptor interceptor = settings?.Interceptor; if (interceptor != null) { callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor); } ClickViewService.ClickViewServiceClient grpcClient = new ClickViewService.ClickViewServiceClient(callInvoker); return new ClickViewServiceClientImpl(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 ClickViewService client</summary> public virtual ClickViewService.ClickViewServiceClient GrpcClient => throw new sys::NotImplementedException(); /// <summary> /// Returns the requested click view in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual gagvr::ClickView GetClickView(GetClickViewRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Returns the requested click view in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::ClickView> GetClickViewAsync(GetClickViewRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Returns the requested click view in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::ClickView> GetClickViewAsync(GetClickViewRequest request, st::CancellationToken cancellationToken) => GetClickViewAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Returns the requested click view in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the click view to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual gagvr::ClickView GetClickView(string resourceName, gaxgrpc::CallSettings callSettings = null) => GetClickView(new GetClickViewRequest { ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested click view in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the click view to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::ClickView> GetClickViewAsync(string resourceName, gaxgrpc::CallSettings callSettings = null) => GetClickViewAsync(new GetClickViewRequest { ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested click view in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the click view to fetch. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::ClickView> GetClickViewAsync(string resourceName, st::CancellationToken cancellationToken) => GetClickViewAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Returns the requested click view in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the click view to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual gagvr::ClickView GetClickView(gagvr::ClickViewName resourceName, gaxgrpc::CallSettings callSettings = null) => GetClickView(new GetClickViewRequest { ResourceNameAsClickViewName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested click view in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the click view to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::ClickView> GetClickViewAsync(gagvr::ClickViewName resourceName, gaxgrpc::CallSettings callSettings = null) => GetClickViewAsync(new GetClickViewRequest { ResourceNameAsClickViewName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested click view in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the click view to fetch. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::ClickView> GetClickViewAsync(gagvr::ClickViewName resourceName, st::CancellationToken cancellationToken) => GetClickViewAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); } /// <summary>ClickViewService client wrapper implementation, for convenient use.</summary> /// <remarks> /// Service to fetch click views. /// </remarks> public sealed partial class ClickViewServiceClientImpl : ClickViewServiceClient { private readonly gaxgrpc::ApiCall<GetClickViewRequest, gagvr::ClickView> _callGetClickView; /// <summary> /// Constructs a client wrapper for the ClickViewService service, with the specified gRPC client and settings. /// </summary> /// <param name="grpcClient">The underlying gRPC client.</param> /// <param name="settings">The base <see cref="ClickViewServiceSettings"/> used within this client.</param> public ClickViewServiceClientImpl(ClickViewService.ClickViewServiceClient grpcClient, ClickViewServiceSettings settings) { GrpcClient = grpcClient; ClickViewServiceSettings effectiveSettings = settings ?? ClickViewServiceSettings.GetDefault(); gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings); _callGetClickView = clientHelper.BuildApiCall<GetClickViewRequest, gagvr::ClickView>(grpcClient.GetClickViewAsync, grpcClient.GetClickView, effectiveSettings.GetClickViewSettings).WithGoogleRequestParam("resource_name", request => request.ResourceName); Modify_ApiCall(ref _callGetClickView); Modify_GetClickViewApiCall(ref _callGetClickView); 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_GetClickViewApiCall(ref gaxgrpc::ApiCall<GetClickViewRequest, gagvr::ClickView> call); partial void OnConstruction(ClickViewService.ClickViewServiceClient grpcClient, ClickViewServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper); /// <summary>The underlying gRPC ClickViewService client</summary> public override ClickViewService.ClickViewServiceClient GrpcClient { get; } partial void Modify_GetClickViewRequest(ref GetClickViewRequest request, ref gaxgrpc::CallSettings settings); /// <summary> /// Returns the requested click view in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public override gagvr::ClickView GetClickView(GetClickViewRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_GetClickViewRequest(ref request, ref callSettings); return _callGetClickView.Sync(request, callSettings); } /// <summary> /// Returns the requested click view in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public override stt::Task<gagvr::ClickView> GetClickViewAsync(GetClickViewRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_GetClickViewRequest(ref request, ref callSettings); return _callGetClickView.Async(request, callSettings); } } }
using EPiServer.Commerce.Catalog.ContentTypes; using EPiServer.Commerce.Catalog.Linking; using EPiServer.Commerce.Marketing; using EPiServer.Commerce.Order; using EPiServer.Reference.Commerce.Site.Features.AddressBook.Services; using EPiServer.Reference.Commerce.Site.Features.Cart.Extensions; using EPiServer.Reference.Commerce.Site.Features.Cart.ViewModels; using EPiServer.Reference.Commerce.Site.Features.Market.Services; using EPiServer.Reference.Commerce.Site.Features.Product.Services; using EPiServer.Reference.Commerce.Site.Features.Shared.Models; using EPiServer.Reference.Commerce.Site.Features.Shared.Services; using EPiServer.Reference.Commerce.Site.Infrastructure.Facades; using EPiServer.ServiceLocation; using EPiServer.Tracking.Commerce; using EPiServer.Tracking.Commerce.Data; using Mediachase.Commerce; using Mediachase.Commerce.Catalog; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace EPiServer.Reference.Commerce.Site.Features.Cart.Services { [ServiceConfiguration(typeof(ICartService), Lifecycle = ServiceInstanceScope.Singleton)] public class CartService : ICartService { private readonly IProductService _productService; private readonly IPricingService _pricingService; private readonly IOrderGroupFactory _orderGroupFactory; private readonly CustomerContextFacade _customerContext; private readonly IInventoryProcessor _inventoryProcessor; private readonly IPromotionEngine _promotionEngine; private readonly IOrderRepository _orderRepository; private readonly IAddressBookService _addressBookService; private readonly ICurrentMarket _currentMarket; private readonly ICurrencyService _currencyService; private readonly ReferenceConverter _referenceConverter; private readonly IContentLoader _contentLoader; private readonly IRelationRepository _relationRepository; private readonly OrderValidationService _orderValidationService; public CartService( IProductService productService, IPricingService pricingService, IOrderGroupFactory orderGroupFactory, CustomerContextFacade customerContext, IInventoryProcessor inventoryProcessor, IOrderRepository orderRepository, IPromotionEngine promotionEngine, IAddressBookService addressBookService, ICurrentMarket currentMarket, ICurrencyService currencyService, ReferenceConverter referenceConverter, IContentLoader contentLoader, IRelationRepository relationRepository, OrderValidationService orderValidationService) { _productService = productService; _pricingService = pricingService; _orderGroupFactory = orderGroupFactory; _customerContext = customerContext; _inventoryProcessor = inventoryProcessor; _promotionEngine = promotionEngine; _orderRepository = orderRepository; _addressBookService = addressBookService; _currentMarket = currentMarket; _currencyService = currencyService; _referenceConverter = referenceConverter; _contentLoader = contentLoader; _relationRepository = relationRepository; _orderValidationService = orderValidationService; } public CartChangeData ChangeCartItem(ICart cart, int shipmentId, string code, decimal quantity, string size, string newSize, string displayName) { CartChangeData cartChange = null; if (quantity > 0) { if (size == newSize) { // Custom cart change type: quantityChanged. cartChange = new CartChangeData("quantityChanged", code); cartChange.SetChange("oldQuantity", cart.GetAllLineItems().FirstOrDefault(x => x.Code == code).Quantity); ChangeQuantity(cart, shipmentId, code, quantity); return cartChange; } // Custom cart change type: variantChanged. cartChange = new CartChangeData("variantChanged", code); cartChange.SetChange("oldSize", size); cartChange.SetChange("oldCode", code); cartChange.SetChange("oldPrice", cart.GetAllLineItems().FirstOrDefault(x => x.Code == code).PlacedPrice); var newCode = _productService.GetSiblingVariantCodeBySize(code, newSize); UpdateLineItemSku(cart, shipmentId, code, newCode, quantity, displayName); return cartChange; } RemoveLineItem(cart, shipmentId, code); cartChange = new CartChangeData(CartChangeType.ItemRemoved, code); return cartChange; } public IDictionary<ILineItem, IList<ValidationIssue>> ValidateCart(ICart cart) { return _orderValidationService.ValidateOrder(cart); } public string DefaultCartName => "Default"; public string DefaultWishListName => "WishList"; public void RecreateLineItemsBasedOnShipments(ICart cart, IEnumerable<CartItemViewModel> cartItems, IEnumerable<AddressModel> addresses) { var form = cart.GetFirstForm(); var items = cartItems .GroupBy(x => new { x.AddressId, x.Code, x.DisplayName, x.IsGift }) .Select(x => new { Code = x.Key.Code, DisplayName = x.Key.DisplayName, AddressId = x.Key.AddressId, Quantity = x.Count(), IsGift = x.Key.IsGift }); foreach (var shipment in form.Shipments) { shipment.LineItems.Clear(); } form.Shipments.Clear(); foreach (var address in addresses) { var shipment = cart.CreateShipment(_orderGroupFactory); form.Shipments.Add(shipment); shipment.ShippingAddress = _addressBookService.ConvertToAddress(address, cart); foreach (var item in items.Where(x => x.AddressId == address.AddressId)) { var lineItem = cart.CreateLineItem(item.Code, _orderGroupFactory); lineItem.DisplayName = item.DisplayName; lineItem.IsGift = item.IsGift; lineItem.Quantity = item.Quantity; shipment.LineItems.Add(lineItem); } } ValidateCart(cart); } public void MergeShipments(ICart cart) { if (cart == null || !cart.GetAllLineItems().Any()) { return; } var form = cart.GetFirstForm(); var keptShipment = cart.GetFirstShipment(); var removedShipments = form.Shipments.Skip(1).ToList(); var movedLineItems = removedShipments.SelectMany(x => x.LineItems).ToList(); removedShipments.ForEach(x => x.LineItems.Clear()); removedShipments.ForEach(x => cart.GetFirstForm().Shipments.Remove(x)); foreach (var item in movedLineItems) { var existingLineItem = keptShipment.LineItems.SingleOrDefault(x => x.Code == item.Code); if (existingLineItem != null) { existingLineItem.Quantity += item.Quantity; continue; } keptShipment.LineItems.Add(item); } ValidateCart(cart); } public void UpdateShippingMethod(ICart cart, int shipmentId, Guid shippingMethodId) { var shipment = cart.GetFirstForm().Shipments.First(x => x.ShipmentId == shipmentId); shipment.ShippingMethodId = shippingMethodId; ValidateCart(cart); } public AddToCartResult AddToCart(ICart cart, string code, decimal quantity) { var result = new AddToCartResult(); var contentLink = _referenceConverter.GetContentLink(code); var entryContent = _contentLoader.Get<EntryContentBase>(contentLink); if (entryContent is BundleContent) { foreach (var relation in _relationRepository.GetChildren<BundleEntry>(contentLink)) { var entry = _contentLoader.Get<EntryContentBase>(relation.Child); var recursiveResult = AddToCart(cart, entry.Code, relation.Quantity ?? 1); if (recursiveResult.EntriesAddedToCart) { result.EntriesAddedToCart = true; } foreach (var message in recursiveResult.ValidationMessages) { result.ValidationMessages.Add(message); } } return result; } var lineItem = cart.GetAllLineItems().FirstOrDefault(x => x.Code == code && !x.IsGift); if (lineItem == null) { lineItem = AddNewLineItem(cart, code, quantity, entryContent.DisplayName); } else { var shipment = cart.GetFirstShipment(); cart.UpdateLineItemQuantity(shipment, lineItem, lineItem.Quantity + quantity); } var validationIssues = ValidateCart(cart); AddValidationMessagesToResult(result, lineItem, validationIssues); return result; } public void SetCartCurrency(ICart cart, Currency currency) { if (currency.IsEmpty || currency == cart.Currency) { return; } cart.Currency = currency; foreach (var lineItem in cart.GetAllLineItems()) { // If there is an item which has no price in the new currency, a NullReference exception will be thrown. // Mixing currencies in cart is not allowed. // It's up to site's managers to ensure that all items have prices in allowed currency. lineItem.PlacedPrice = _pricingService.GetPrice(lineItem.Code, cart.MarketId, currency).UnitPrice.Amount; } ValidateCart(cart); } public IDictionary<ILineItem, IList<ValidationIssue>> RequestInventory(ICart cart) { var validationIssues = new Dictionary<ILineItem, IList<ValidationIssue>>(); cart.AdjustInventoryOrRemoveLineItems((item, issue) => validationIssues.AddValidationIssues(item, issue), _inventoryProcessor); return validationIssues; } public ICart LoadCart(string name) { var cart = _orderRepository.LoadCart<ICart>(_customerContext.CurrentContactId, name, _currentMarket); if (cart != null) { SetCartCurrency(cart, _currencyService.GetCurrentCurrency()); var validationIssues = ValidateCart(cart); // After validate, if there is any change in cart, saving cart. if (validationIssues.Any()) { _orderRepository.Save(cart); } } return cart; } public ICart LoadOrCreateCart(string name) { var cart = _orderRepository.LoadOrCreateCart<ICart>(_customerContext.CurrentContactId, name, _currentMarket); if (cart != null) { SetCartCurrency(cart, _currencyService.GetCurrentCurrency()); } return cart; } public bool AddCouponCode(ICart cart, string couponCode) { var couponCodes = cart.GetFirstForm().CouponCodes; if (couponCodes.Any(c => c.Equals(couponCode, StringComparison.OrdinalIgnoreCase))) { return false; } couponCodes.Add(couponCode); var rewardDescriptions = ApplyDiscounts(cart); var appliedCoupons = rewardDescriptions .Where(r => r.AppliedCoupon != null) .Select(r => r.AppliedCoupon); var couponApplied = appliedCoupons.Any(c => c.Equals(couponCode, StringComparison.OrdinalIgnoreCase)); if (!couponApplied) { couponCodes.Remove(couponCode); } return couponApplied; } public void RemoveCouponCode(ICart cart, string couponCode) { cart.GetFirstForm().CouponCodes.Remove(couponCode); ApplyDiscounts(cart); } public IEnumerable<RewardDescription> ApplyDiscounts(ICart cart) { return cart.ApplyDiscounts(_promotionEngine, new PromotionEngineSettings()); } private void RemoveLineItem(ICart cart, int shipmentId, string code) { // Gets the shipment for shipment id or for wish list shipment id as a parameter is always equal zero (wish list). var shipment = cart.GetFirstForm().Shipments.First(s => s.ShipmentId == shipmentId || shipmentId == 0); var lineItem = shipment.LineItems.FirstOrDefault(l => l.Code == code); if (lineItem != null) { shipment.LineItems.Remove(lineItem); } if (!shipment.LineItems.Any()) { cart.GetFirstForm().Shipments.Remove(shipment); } ValidateCart(cart); } private static void AddValidationMessagesToResult(AddToCartResult result, ILineItem lineItem, IDictionary<ILineItem, IList<ValidationIssue>> validationIssues) { foreach (var validationIssue in validationIssues) { var warning = new StringBuilder(); warning.Append($"Line Item with code {lineItem.Code} "); validationIssue.Value.Aggregate(warning, (current, issue) => current.Append(issue).Append(", ")); result.ValidationMessages.Add(warning.ToString().TrimEnd(',', ' ')); } if (!validationIssues.HasItemBeenRemoved(lineItem)) { result.EntriesAddedToCart = true; } } private void UpdateLineItemSku(ICart cart, int shipmentId, string oldCode, string newCode, decimal quantity, string displayName) { RemoveLineItem(cart, shipmentId, oldCode); // Merge same sku's. var newLineItem = GetFirstLineItem(cart, newCode); if (newLineItem != null) { var shipment = cart.GetFirstForm().Shipments.First(s => s.ShipmentId == shipmentId || shipmentId == 0); cart.UpdateLineItemQuantity(shipment, newLineItem, newLineItem.Quantity + quantity); } else { AddNewLineItem(cart, newCode, quantity, displayName); } ValidateCart(cart); } private ILineItem AddNewLineItem(ICart cart, string newCode, decimal quantity, string displayName) { var newLineItem = cart.CreateLineItem(newCode, _orderGroupFactory); newLineItem.Quantity = quantity; newLineItem.DisplayName = displayName; cart.AddLineItem(newLineItem, _orderGroupFactory); var price = _pricingService.GetPrice(newCode); if (price != null) { newLineItem.PlacedPrice = price.UnitPrice.Amount; } return newLineItem; } private void ChangeQuantity(ICart cart, int shipmentId, string code, decimal quantity) { var shipment = cart.GetFirstForm().Shipments.First(s => s.ShipmentId == shipmentId); var lineItem = shipment.LineItems.FirstOrDefault(x => x.Code == code); if (lineItem == null) { return; } cart.UpdateLineItemQuantity(shipment, lineItem, quantity); ValidateCart(cart); } private ILineItem GetFirstLineItem(IOrderGroup cart, string code) { return cart.GetAllLineItems().FirstOrDefault(x => x.Code == code); } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using FarseerPhysics.Collision; using FarseerPhysics.Collision.Shapes; using FarseerPhysics.Common; using FarseerPhysics.Controllers; using FarseerPhysics.Dynamics; using FarseerPhysics.Dynamics.Contacts; using FarseerPhysics.Dynamics.Joints; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.Graphics; using Cocos2D; namespace FarseerPhysics.DebugViews { /// <summary> /// A debug view that works in XNA. /// A debug view shows you what happens inside the physics engine. You can view /// bodies, joints, fixtures and more. /// </summary> public class DebugViewXNA : DebugView, IDisposable { //Drawing private CCPrimitiveBatch _customPrimitiveBatch; private CCPrimitiveBatch _basicPrimitiveBatch; private CCPrimitiveBatch _primitiveBatch; private SpriteBatch _batch; private SpriteFont _font; private GraphicsDevice _device; private Vector2[] _tempVertices = new Vector2[Settings.MaxPolygonVertices]; private List<StringData> _stringData; private Matrix _localProjection; private Matrix _localView; //Shapes public Color DefaultShapeColor = new Color(0.9f, 0.7f, 0.7f); public Color InactiveShapeColor = new Color(0.5f, 0.5f, 0.3f); public Color KinematicShapeColor = new Color(0.5f, 0.5f, 0.9f); public Color SleepingShapeColor = new Color(0.6f, 0.6f, 0.6f); public Color StaticShapeColor = new Color(0.5f, 0.9f, 0.5f); public Color TextColor = Color.White; //Contacts private int _pointCount; private const int MaxContactPoints = 2048; private ContactPoint[] _points = new ContactPoint[MaxContactPoints]; //Debug panel #if XBOX || OUYA public Vector2 DebugPanelPosition = new Vector2(55, 100); #else public Vector2 DebugPanelPosition = new Vector2(40, 100); #endif private int _max; private int _avg; private int _min; //Performance graph public bool AdaptiveLimits = true; public int ValuesToGraph = 500; public int MinimumValue; public int MaximumValue = 1000; private List<float> _graphValues = new List<float>(); #if XBOX || OUYA public Rectangle PerformancePanelBounds = new Rectangle(265, 100, 200, 100); #else public Rectangle PerformancePanelBounds = new Rectangle(250, 100, 200, 100); #endif private Vector2[] _background = new Vector2[4]; public bool Enabled = true; #if XBOX || WINDOWS_PHONE || OUYA public const int CircleSegments = 16; #else public const int CircleSegments = 32; #endif public DebugViewXNA(World world) : base(world) { world.ContactManager.PreSolve += PreSolve; //Default flags AppendFlags(DebugViewFlags.Shape); AppendFlags(DebugViewFlags.Controllers); AppendFlags(DebugViewFlags.Joint); } public void BeginCustomDraw() { if (!_customPrimitiveBatch.IsReady()) { _customPrimitiveBatch.Begin(); } _primitiveBatch = _customPrimitiveBatch; } public void EndCustomDraw() { //_primitiveBatch.End(); } #region IDisposable Members public void Dispose() { World.ContactManager.PreSolve -= PreSolve; } #endregion private void PreSolve(Contact contact, ref Manifold oldManifold) { if ((Flags & DebugViewFlags.ContactPoints) == DebugViewFlags.ContactPoints) { Manifold manifold = contact.Manifold; if (manifold.PointCount == 0) { return; } Fixture fixtureA = contact.FixtureA; FixedArray2<PointState> state1, state2; Collision.Collision.GetPointStates(out state1, out state2, ref oldManifold, ref manifold); FixedArray2<Vector2> points; Vector2 normal; contact.GetWorldManifold(out normal, out points); for (int i = 0; i < manifold.PointCount && _pointCount < MaxContactPoints; ++i) { if (fixtureA == null) { _points[i] = new ContactPoint(); } _points[_pointCount] = new ContactPoint() {Position = points[i], Normal = normal, State = state2[i]}; ++_pointCount; } } } /// <summary> /// Call this to draw shapes and other debug draw data. /// </summary> private void DrawDebugData() { if ((Flags & DebugViewFlags.Shape) == DebugViewFlags.Shape) { foreach (Body b in World.BodyList) { Transform xf; b.GetTransform(out xf); foreach (Fixture f in b.FixtureList) { if (b.Enabled == false) { DrawShape(f, xf, InactiveShapeColor); } else if (b.BodyType == BodyType.Static) { DrawShape(f, xf, StaticShapeColor); } else if (b.BodyType == BodyType.Kinematic) { DrawShape(f, xf, KinematicShapeColor); } else if (b.Awake == false) { DrawShape(f, xf, SleepingShapeColor); } else { DrawShape(f, xf, DefaultShapeColor); } } } } if ((Flags & DebugViewFlags.ContactPoints) == DebugViewFlags.ContactPoints) { const float axisScale = 0.3f; for (int i = 0; i < _pointCount; ++i) { ContactPoint point = _points[i]; if (point.State == PointState.Add) { // Add DrawPoint(point.Position, 0.1f, new Color(0.3f, 0.95f, 0.3f)); } else if (point.State == PointState.Persist) { // Persist DrawPoint(point.Position, 0.1f, new Color(0.3f, 0.3f, 0.95f)); } if ((Flags & DebugViewFlags.ContactNormals) == DebugViewFlags.ContactNormals) { Vector2 p1 = point.Position; Vector2 p2 = p1 + axisScale * point.Normal; DrawSegment(p1, p2, new Color(0.4f, 0.9f, 0.4f)); } } _pointCount = 0; } if ((Flags & DebugViewFlags.PolygonPoints) == DebugViewFlags.PolygonPoints) { foreach (Body body in World.BodyList) { foreach (Fixture f in body.FixtureList) { PolygonShape polygon = f.Shape as PolygonShape; if (polygon != null) { Transform xf; body.GetTransform(out xf); for (int i = 0; i < polygon.Vertices.Count; i++) { Vector2 tmp = MathUtils.Multiply(ref xf, polygon.Vertices[i]); DrawPoint(tmp, 0.1f, Color.Red); } } } } } if ((Flags & DebugViewFlags.Joint) == DebugViewFlags.Joint) { foreach (Joint j in World.JointList) { DrawJoint(j); } } if ((Flags & DebugViewFlags.Pair) == DebugViewFlags.Pair) { Color color = new Color(0.3f, 0.9f, 0.9f); for (int i = 0; i < World.ContactManager.ContactList.Count; i++) { Contact c = World.ContactManager.ContactList[i]; Fixture fixtureA = c.FixtureA; Fixture fixtureB = c.FixtureB; AABB aabbA; fixtureA.GetAABB(out aabbA, 0); AABB aabbB; fixtureB.GetAABB(out aabbB, 0); Vector2 cA = aabbA.Center; Vector2 cB = aabbB.Center; DrawSegment(cA, cB, color); } } if ((Flags & DebugViewFlags.AABB) == DebugViewFlags.AABB) { Color color = new Color(0.9f, 0.3f, 0.9f); IBroadPhase bp = World.ContactManager.BroadPhase; foreach (Body b in World.BodyList) { if (b.Enabled == false) { continue; } foreach (Fixture f in b.FixtureList) { for (int t = 0; t < f.ProxyCount; ++t) { FixtureProxy proxy = f.Proxies[t]; AABB aabb; bp.GetFatAABB(proxy.ProxyId, out aabb); DrawAABB(ref aabb, color); } } } } if ((Flags & DebugViewFlags.CenterOfMass) == DebugViewFlags.CenterOfMass) { foreach (Body b in World.BodyList) { Transform xf; b.GetTransform(out xf); xf.Position = b.WorldCenter; DrawTransform(ref xf); } } if ((Flags & DebugViewFlags.Controllers) == DebugViewFlags.Controllers) { for (int i = 0; i < World.ControllerList.Count; i++) { Controller controller = World.ControllerList[i]; BuoyancyController buoyancy = controller as BuoyancyController; if (buoyancy != null) { AABB container = buoyancy.Container; DrawAABB(ref container, Color.LightBlue); } } } if ((Flags & DebugViewFlags.DebugPanel) == DebugViewFlags.DebugPanel) { DrawDebugPanel(); } } private void DrawPerformanceGraph() { _graphValues.Add(World.UpdateTime); if (_graphValues.Count > ValuesToGraph + 1) _graphValues.RemoveAt(0); float x = PerformancePanelBounds.X; float deltaX = PerformancePanelBounds.Width / (float)ValuesToGraph; float yScale = PerformancePanelBounds.Bottom - (float)PerformancePanelBounds.Top; // we must have at least 2 values to start rendering if (_graphValues.Count > 2) { _max = (int)_graphValues.Max(); _avg = (int)_graphValues.Average(); _min = (int)_graphValues.Min(); if (AdaptiveLimits) { MaximumValue = _max; MinimumValue = 0; } // start at last value (newest value added) // continue until no values are left for (int i = _graphValues.Count - 1; i > 0; i--) { float y1 = PerformancePanelBounds.Bottom - ((_graphValues[i] / (MaximumValue - MinimumValue)) * yScale); float y2 = PerformancePanelBounds.Bottom - ((_graphValues[i - 1] / (MaximumValue - MinimumValue)) * yScale); Vector2 x1 = new Vector2(MathHelper.Clamp(x, PerformancePanelBounds.Left, PerformancePanelBounds.Right), MathHelper.Clamp(y1, PerformancePanelBounds.Top, PerformancePanelBounds.Bottom)); Vector2 x2 = new Vector2( MathHelper.Clamp(x + deltaX, PerformancePanelBounds.Left, PerformancePanelBounds.Right), MathHelper.Clamp(y2, PerformancePanelBounds.Top, PerformancePanelBounds.Bottom)); DrawSegment(x1, x2, Color.LightGreen); x += deltaX; } } DrawString(PerformancePanelBounds.Right + 10, PerformancePanelBounds.Top, "Max: " + _max); DrawString(PerformancePanelBounds.Right + 10, PerformancePanelBounds.Center.Y - 7, "Avg: " + _avg); DrawString(PerformancePanelBounds.Right + 10, PerformancePanelBounds.Bottom - 15, "Min: " + _min); //Draw background. _background[0] = new Vector2(PerformancePanelBounds.X, PerformancePanelBounds.Y); _background[1] = new Vector2(PerformancePanelBounds.X, PerformancePanelBounds.Y + PerformancePanelBounds.Height); _background[2] = new Vector2(PerformancePanelBounds.X + PerformancePanelBounds.Width, PerformancePanelBounds.Y + PerformancePanelBounds.Height); _background[3] = new Vector2(PerformancePanelBounds.X + PerformancePanelBounds.Width, PerformancePanelBounds.Y); DrawSolidPolygon(_background, 4, Color.DarkGray, true); } private void DrawDebugPanel() { int fixtures = 0; for (int i = 0; i < World.BodyList.Count; i++) { fixtures += World.BodyList[i].FixtureList.Count; } int x = (int)DebugPanelPosition.X; int y = (int)DebugPanelPosition.Y; DrawString(x, y, "Objects:" + "\n- Bodies: " + World.BodyList.Count + "\n- Fixtures: " + fixtures + "\n- Contacts: " + World.ContactList.Count + "\n- Joints: " + World.JointList.Count + "\n- Controllers: " + World.ControllerList.Count + "\n- Proxies: " + World.ProxyCount); DrawString(x + 110, y, "Update time:" + "\n- Body: " + World.SolveUpdateTime + "\n- Contact: " + World.ContactsUpdateTime + "\n- CCD: " + World.ContinuousPhysicsTime + "\n- Joint: " + World.Island.JointUpdateTime + "\n- Controller: " + World.ControllersUpdateTime + "\n- Total: " + World.UpdateTime); } public void DrawAABB(ref AABB aabb, Color color) { Vector2[] verts = new Vector2[4]; verts[0] = new Vector2(aabb.LowerBound.X, aabb.LowerBound.Y); verts[1] = new Vector2(aabb.UpperBound.X, aabb.LowerBound.Y); verts[2] = new Vector2(aabb.UpperBound.X, aabb.UpperBound.Y); verts[3] = new Vector2(aabb.LowerBound.X, aabb.UpperBound.Y); DrawPolygon(verts, 4, color); } private void DrawJoint(Joint joint) { if (!joint.Enabled) return; Body b1 = joint.BodyA; Body b2 = joint.BodyB; Transform xf1, xf2; b1.GetTransform(out xf1); Vector2 x2 = Vector2.Zero; // WIP David if (!joint.IsFixedType()) { b2.GetTransform(out xf2); x2 = xf2.Position; } Vector2 p1 = joint.WorldAnchorA; Vector2 p2 = joint.WorldAnchorB; Vector2 x1 = xf1.Position; Color color = new Color(0.5f, 0.8f, 0.8f); switch (joint.JointType) { case JointType.Distance: DrawSegment(p1, p2, color); break; case JointType.Pulley: PulleyJoint pulley = (PulleyJoint)joint; Vector2 s1 = pulley.GroundAnchorA; Vector2 s2 = pulley.GroundAnchorB; DrawSegment(s1, p1, color); DrawSegment(s2, p2, color); DrawSegment(s1, s2, color); break; case JointType.FixedMouse: DrawPoint(p1, 0.5f, new Color(0.0f, 1.0f, 0.0f)); DrawSegment(p1, p2, new Color(0.8f, 0.8f, 0.8f)); break; case JointType.Revolute: //DrawSegment(x2, p1, color); DrawSegment(p2, p1, color); DrawSolidCircle(p2, 0.1f, Vector2.Zero, Color.Red); DrawSolidCircle(p1, 0.1f, Vector2.Zero, Color.Blue); break; case JointType.FixedAngle: //Should not draw anything. break; case JointType.FixedRevolute: DrawSegment(x1, p1, color); DrawSolidCircle(p1, 0.1f, Vector2.Zero, Color.Pink); break; case JointType.FixedLine: DrawSegment(x1, p1, color); DrawSegment(p1, p2, color); break; case JointType.FixedDistance: DrawSegment(x1, p1, color); DrawSegment(p1, p2, color); break; case JointType.FixedPrismatic: DrawSegment(x1, p1, color); DrawSegment(p1, p2, color); break; case JointType.Gear: DrawSegment(x1, x2, color); break; //case JointType.Weld: // break; default: DrawSegment(x1, p1, color); DrawSegment(p1, p2, color); DrawSegment(x2, p2, color); break; } } public void DrawShape(Fixture fixture, Transform xf, Color color) { switch (fixture.ShapeType) { case ShapeType.Circle: { CircleShape circle = (CircleShape)fixture.Shape; Vector2 center = MathUtils.Multiply(ref xf, circle.Position); float radius = circle.Radius; Vector2 axis = xf.R.Col1; DrawSolidCircle(center, radius, axis, color); } break; case ShapeType.Polygon: { PolygonShape poly = (PolygonShape)fixture.Shape; int vertexCount = poly.Vertices.Count; Debug.Assert(vertexCount <= Settings.MaxPolygonVertices); for (int i = 0; i < vertexCount; ++i) { _tempVertices[i] = MathUtils.Multiply(ref xf, poly.Vertices[i]); } DrawSolidPolygon(_tempVertices, vertexCount, color); } break; case ShapeType.Edge: { EdgeShape edge = (EdgeShape)fixture.Shape; Vector2 v1 = MathUtils.Multiply(ref xf, edge.Vertex1); Vector2 v2 = MathUtils.Multiply(ref xf, edge.Vertex2); DrawSegment(v1, v2, color); } break; case ShapeType.Loop: { LoopShape loop = (LoopShape)fixture.Shape; int count = loop.Vertices.Count; Vector2 v1 = MathUtils.Multiply(ref xf, loop.Vertices[count - 1]); DrawCircle(v1, 0.05f, color); for (int i = 0; i < count; ++i) { Vector2 v2 = MathUtils.Multiply(ref xf, loop.Vertices[i]); DrawSegment(v1, v2, color); v1 = v2; } } break; } } public override void DrawPolygon(Vector2[] vertices, int count, float red, float green, float blue) { DrawPolygon(vertices, count, new Color(red, green, blue)); } public void DrawPolygon(Vector2[] vertices, int count, Color color) { if (!_primitiveBatch.IsReady()) { throw new InvalidOperationException("BeginCustomDraw must be called before drawing anything."); } for (int i = 0; i < count - 1; i++) { _primitiveBatch.AddVertex(ref vertices[i], color, PrimitiveType.LineList); _primitiveBatch.AddVertex(ref vertices[i + 1], color, PrimitiveType.LineList); } _primitiveBatch.AddVertex(ref vertices[count - 1], color, PrimitiveType.LineList); _primitiveBatch.AddVertex(ref vertices[0], color, PrimitiveType.LineList); } public override void DrawSolidPolygon(Vector2[] vertices, int count, float red, float green, float blue) { DrawSolidPolygon(vertices, count, new Color(red, green, blue), true); } public void DrawSolidPolygon(Vector2[] vertices, int count, Color color) { DrawSolidPolygon(vertices, count, color, true); } public void DrawSolidPolygon(Vector2[] vertices, int count, Color color, bool outline) { if (!_primitiveBatch.IsReady()) { throw new InvalidOperationException("BeginCustomDraw must be called before drawing anything."); } if (count == 2) { DrawPolygon(vertices, count, color); return; } Color colorFill = color * (outline ? 0.5f : 1.0f); for (int i = 1; i < count - 1; i++) { _primitiveBatch.AddVertex(ref vertices[0], colorFill, PrimitiveType.TriangleList); _primitiveBatch.AddVertex(ref vertices[i], colorFill, PrimitiveType.TriangleList); _primitiveBatch.AddVertex(ref vertices[i + 1], colorFill, PrimitiveType.TriangleList); } if (outline) { DrawPolygon(vertices, count, color); } } public override void DrawCircle(Vector2 center, float radius, float red, float green, float blue) { DrawCircle(center, radius, new Color(red, green, blue)); } public void DrawCircle(Vector2 center, float radius, Color color) { if (!_primitiveBatch.IsReady()) { throw new InvalidOperationException("BeginCustomDraw must be called before drawing anything."); } const double increment = Math.PI * 2.0 / CircleSegments; double theta = 0.0; for (int i = 0, count = CircleSegments; i < count; i++) { Vector2 v1 = center + radius * new Vector2((float)Math.Cos(theta), (float)Math.Sin(theta)); Vector2 v2 = center + radius * new Vector2((float)Math.Cos(theta + increment), (float)Math.Sin(theta + increment)); _primitiveBatch.AddVertex(ref v1, color, PrimitiveType.LineList); _primitiveBatch.AddVertex(ref v2, color, PrimitiveType.LineList); theta += increment; } } public override void DrawSolidCircle(Vector2 center, float radius, Vector2 axis, float red, float green, float blue) { DrawSolidCircle(center, radius, axis, new Color(red, green, blue)); } public void DrawSolidCircle(Vector2 center, float radius, Vector2 axis, Color color) { if (!_primitiveBatch.IsReady()) { throw new InvalidOperationException("BeginCustomDraw must be called before drawing anything."); } const double increment = Math.PI * 2.0 / CircleSegments; double theta = 0.0; Color colorFill = color * 0.5f; Vector2 v0 = center + radius * new Vector2((float)Math.Cos(theta), (float)Math.Sin(theta)); theta += increment; for (int i = 1; i < CircleSegments - 1; i++) { Vector2 v1 = center + radius * new Vector2((float)Math.Cos(theta), (float)Math.Sin(theta)); Vector2 v2 = center + radius * new Vector2((float)Math.Cos(theta + increment), (float)Math.Sin(theta + increment)); _primitiveBatch.AddVertex(ref v0, colorFill, PrimitiveType.TriangleList); _primitiveBatch.AddVertex(ref v1, colorFill, PrimitiveType.TriangleList); _primitiveBatch.AddVertex(ref v2, colorFill, PrimitiveType.TriangleList); theta += increment; } DrawCircle(center, radius, color); DrawSegment(center, center + axis * radius, color); } public override void DrawSegment(Vector2 start, Vector2 end, float red, float green, float blue) { DrawSegment(start, end, new Color(red, green, blue)); } public void DrawSegment(Vector2 start, Vector2 end, Color color) { if (!_primitiveBatch.IsReady()) { throw new InvalidOperationException("BeginCustomDraw must be called before drawing anything."); } _primitiveBatch.AddVertex(ref start, color, PrimitiveType.LineList); _primitiveBatch.AddVertex(ref end, color, PrimitiveType.LineList); } public override void DrawTransform(ref Transform transform) { const float axisScale = 0.4f; Vector2 p1 = transform.Position; Vector2 p2 = p1 + axisScale * transform.R.Col1; DrawSegment(p1, p2, Color.Red); p2 = p1 + axisScale * transform.R.Col2; DrawSegment(p1, p2, Color.Green); } public void DrawPoint(Vector2 p, float size, Color color) { Vector2[] verts = new Vector2[4]; float hs = size / 2.0f; verts[0] = p + new Vector2(-hs, -hs); verts[1] = p + new Vector2(hs, -hs); verts[2] = p + new Vector2(hs, hs); verts[3] = p + new Vector2(-hs, hs); DrawSolidPolygon(verts, 4, color, true); } public void DrawString(int x, int y, string s, params object[] args) { _stringData.Add(new StringData(x, y, s, args, TextColor)); } public void DrawArrow(Vector2 start, Vector2 end, float length, float width, bool drawStartIndicator, Color color) { // Draw connection segment between start- and end-point DrawSegment(start, end, color); // Precalculate halfwidth float halfWidth = width / 2; // Create directional reference Vector2 rotation = (start - end); rotation.Normalize(); // Calculate angle of directional vector float angle = (float)Math.Atan2(rotation.X, -rotation.Y); // Create matrix for rotation Matrix rotMatrix = Matrix.CreateRotationZ(angle); // Create translation matrix for end-point Matrix endMatrix = Matrix.CreateTranslation(end.X, end.Y, 0); // Setup arrow end shape Vector2[] verts = new Vector2[3]; verts[0] = new Vector2(0, 0); verts[1] = new Vector2(-halfWidth, -length); verts[2] = new Vector2(halfWidth, -length); // Rotate end shape Vector2.Transform(verts, ref rotMatrix, verts); // Translate end shape Vector2.Transform(verts, ref endMatrix, verts); // Draw arrow end shape DrawSolidPolygon(verts, 3, color, false); if (drawStartIndicator) { // Create translation matrix for start Matrix startMatrix = Matrix.CreateTranslation(start.X, start.Y, 0); // Setup arrow start shape Vector2[] baseVerts = new Vector2[4]; baseVerts[0] = new Vector2(-halfWidth, length / 4); baseVerts[1] = new Vector2(halfWidth, length / 4); baseVerts[2] = new Vector2(halfWidth, 0); baseVerts[3] = new Vector2(-halfWidth, 0); // Rotate start shape Vector2.Transform(baseVerts, ref rotMatrix, baseVerts); // Translate start shape Vector2.Transform(baseVerts, ref startMatrix, baseVerts); // Draw start shape DrawSolidPolygon(baseVerts, 4, color, false); } } public void RenderDebugData() { if (!Enabled) { return; } //Nothing is enabled - don't draw the debug view. if (Flags == 0) return; _device.RasterizerState = RasterizerState.CullNone; _device.DepthStencilState = DepthStencilState.Default; if (_customPrimitiveBatch.IsReady()) { _customPrimitiveBatch.UpdateMatrix(); _customPrimitiveBatch.End(); } _primitiveBatch = _basicPrimitiveBatch; _primitiveBatch.Begin(); DrawDebugData(); _primitiveBatch.End(); if ((Flags & DebugViewFlags.PerformanceGraph) == DebugViewFlags.PerformanceGraph) { _primitiveBatch.Begin(); DrawPerformanceGraph(); _primitiveBatch.End(); } // begin the sprite batch effect _batch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend); // draw any strings we have for (int i = 0; i < _stringData.Count; i++) { _batch.DrawString(_font, string.Format(_stringData[i].S, _stringData[i].Args), new Vector2(_stringData[i].X + 1f, _stringData[i].Y + 1f), Color.Black); _batch.DrawString(_font, string.Format(_stringData[i].S, _stringData[i].Args), new Vector2(_stringData[i].X, _stringData[i].Y), _stringData[i].Color); } // end the sprite batch effect _batch.End(); _stringData.Clear(); } public void LoadContent(GraphicsDevice device, ContentManager content) { // Create a new SpriteBatch, which can be used to draw textures. _device = device; _batch = new SpriteBatch(_device); _customPrimitiveBatch = new CCPrimitiveBatch(_device, 5000); _basicPrimitiveBatch = new CCPrimitiveBatch(_device, 5000); _font = content.Load<SpriteFont>("fonts/debugfont"); _stringData = new List<StringData>(); _localProjection = Matrix.CreateOrthographicOffCenter(0f, _device.Viewport.Width, _device.Viewport.Height, 0f, 0f, 1f); _localView = Matrix.Identity; } #region Nested type: ContactPoint private struct ContactPoint { public Vector2 Normal; public Vector2 Position; public PointState State; } #endregion #region Nested type: StringData private struct StringData { public object[] Args; public Color Color; public string S; public int X, Y; public StringData(int x, int y, string s, object[] args, Color color) { X = x; Y = y; S = s; Args = args; Color = color; } } #endregion } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using System.Reflection.PortableExecutable; using System.Text; using System.Threading; using Microsoft.CodeAnalysis; using EmitContext = Microsoft.CodeAnalysis.Emit.EmitContext; namespace Microsoft.Cci { internal sealed class PeWritingException : Exception { public PeWritingException(Exception inner) : base(inner.Message, inner) { } } internal static class PeWriter { public static bool WritePeToStream( EmitContext context, CommonMessageProvider messageProvider, Func<Stream> getPeStream, Func<Stream> getPortablePdbStreamOpt, PdbWriter nativePdbWriterOpt, string pdbPathOpt, bool allowMissingMethodBodies, bool isDeterministic, CancellationToken cancellationToken) { // If PDB writer is given, we have to have PDB path. Debug.Assert(nativePdbWriterOpt == null || pdbPathOpt != null); var mdWriter = FullMetadataWriter.Create(context, messageProvider, allowMissingMethodBodies, isDeterministic, getPortablePdbStreamOpt != null, cancellationToken); var properties = context.Module.Properties; nativePdbWriterOpt?.SetMetadataEmitter(mdWriter); // Since we are producing a full assembly, we should not have a module version ID // imposed ahead-of time. Instead we will compute a deterministic module version ID // based on the contents of the generated stream. Debug.Assert(properties.PersistentIdentifier == default(Guid)); var ilBuilder = new BlobBuilder(32 * 1024); var mappedFieldDataBuilder = new BlobBuilder(); var managedResourceBuilder = new BlobBuilder(1024); Blob mvidFixup, mvidStringFixup; mdWriter.BuildMetadataAndIL( nativePdbWriterOpt, ilBuilder, mappedFieldDataBuilder, managedResourceBuilder, out mvidFixup, out mvidStringFixup); MethodDefinitionHandle entryPointHandle; MethodDefinitionHandle debugEntryPointHandle; mdWriter.GetEntryPoints(out entryPointHandle, out debugEntryPointHandle); if (!debugEntryPointHandle.IsNil) { nativePdbWriterOpt?.SetEntryPoint((uint)MetadataTokens.GetToken(debugEntryPointHandle)); } if (nativePdbWriterOpt != null) { var assembly = mdWriter.Module.AsAssembly; if (assembly != null && assembly.Kind == OutputKind.WindowsRuntimeMetadata) { // Dev12: If compiling to winmdobj, we need to add to PDB source spans of // all types and members for better error reporting by WinMDExp. nativePdbWriterOpt.WriteDefinitionLocations(mdWriter.Module.GetSymbolToLocationMap()); } else { #if DEBUG // validate that all definitions are writable // if same scenario would happen in an winmdobj project nativePdbWriterOpt.AssertAllDefinitionsHaveTokens(mdWriter.Module.GetSymbolToLocationMap()); #endif } } Stream peStream = getPeStream(); if (peStream == null) { return false; } BlobContentId pdbContentId = nativePdbWriterOpt?.GetContentId() ?? default(BlobContentId); // the writer shall not be used after this point for writing: nativePdbWriterOpt = null; ushort portablePdbVersion = 0; var metadataRootBuilder = mdWriter.GetRootBuilder(); var peHeaderBuilder = new PEHeaderBuilder( machine: properties.Machine, sectionAlignment: properties.SectionAlignment, fileAlignment: properties.FileAlignment, imageBase: properties.BaseAddress, majorLinkerVersion: properties.LinkerMajorVersion, minorLinkerVersion: properties.LinkerMinorVersion, majorOperatingSystemVersion: 4, minorOperatingSystemVersion: 0, majorImageVersion: 0, minorImageVersion: 0, majorSubsystemVersion: properties.MajorSubsystemVersion, minorSubsystemVersion: properties.MinorSubsystemVersion, subsystem: properties.Subsystem, dllCharacteristics: properties.DllCharacteristics, imageCharacteristics: properties.ImageCharacteristics, sizeOfStackReserve: properties.SizeOfStackReserve, sizeOfStackCommit: properties.SizeOfStackCommit, sizeOfHeapReserve: properties.SizeOfHeapReserve, sizeOfHeapCommit: properties.SizeOfHeapCommit); var deterministicIdProvider = isDeterministic ? new Func<IEnumerable<Blob>, BlobContentId>(content => BlobContentId.FromHash(CryptographicHashProvider.ComputeSha1(content))) : null; if (mdWriter.EmitStandaloneDebugMetadata) { Debug.Assert(getPortablePdbStreamOpt != null); var portablePdbBlob = new BlobBuilder(); var portablePdbBuilder = mdWriter.GetPortablePdbBuilder(metadataRootBuilder.Sizes, debugEntryPointHandle, deterministicIdProvider); pdbContentId = portablePdbBuilder.Serialize(portablePdbBlob); portablePdbVersion = portablePdbBuilder.FormatVersion; // write to Portable PDB stream: Stream portablePdbStream = getPortablePdbStreamOpt(); if (portablePdbStream != null) { portablePdbBlob.WriteContentTo(portablePdbStream); } } DebugDirectoryBuilder debugDirectoryBuilder; if (pdbPathOpt != null || isDeterministic) { debugDirectoryBuilder = new DebugDirectoryBuilder(); if (pdbPathOpt != null) { string paddedPath = isDeterministic ? pdbPathOpt : PadPdbPath(pdbPathOpt); debugDirectoryBuilder.AddCodeViewEntry(paddedPath, pdbContentId, portablePdbVersion); } if (isDeterministic) { debugDirectoryBuilder.AddReproducibleEntry(); } } else { debugDirectoryBuilder = null; } var peBuilder = new ManagedPEBuilder( peHeaderBuilder, metadataRootBuilder, ilBuilder, mappedFieldDataBuilder, managedResourceBuilder, CreateNativeResourceSectionSerializer(context.Module), debugDirectoryBuilder, CalculateStrongNameSignatureSize(context.Module), entryPointHandle, properties.CorFlags, deterministicIdProvider); var peBlob = new BlobBuilder(); BlobContentId peContentId; peBuilder.Serialize(peBlob, out peContentId); PatchModuleVersionIds(mvidFixup, mvidStringFixup, peContentId.Guid); try { peBlob.WriteContentTo(peStream); } catch (Exception e) when (!(e is OperationCanceledException)) { throw new PeWritingException(e); } return true; } private static void PatchModuleVersionIds(Blob guidFixup, Blob stringFixup, Guid mvid) { if (!guidFixup.IsDefault) { var writer = new BlobWriter(guidFixup); writer.WriteGuid(mvid); Debug.Assert(writer.RemainingBytes == 0); } if (!stringFixup.IsDefault) { var writer = new BlobWriter(stringFixup); writer.WriteUserString(mvid.ToString()); Debug.Assert(writer.RemainingBytes == 0); } } // Padding: We pad the path to this minimal size to // allow some tools to patch the path without the need to rewrite the entire image. // This is a workaround put in place until these tools are retired. private static string PadPdbPath(string path) { const int minLength = 260; return path + new string('\0', Math.Max(0, minLength - Encoding.UTF8.GetByteCount(path) - 1)); } private static ResourceSectionBuilder CreateNativeResourceSectionSerializer(IModule module) { // Win32 resources are supplied to the compiler in one of two forms, .RES (the output of the resource compiler), // or .OBJ (the output of running cvtres.exe on a .RES file). A .RES file is parsed and processed into // a set of objects implementing IWin32Resources. These are then ordered and the final image form is constructed // and written to the resource section. Resources in .OBJ form are already very close to their final output // form. Rather than reading them and parsing them into a set of objects similar to those produced by // processing a .RES file, we process them like the native linker would, copy the relevant sections from // the .OBJ into our output and apply some fixups. var nativeResourceSectionOpt = module.Win32ResourceSection; if (nativeResourceSectionOpt != null) { return new ResourceSectionBuilderFromObj(nativeResourceSectionOpt); } var nativeResourcesOpt = module.Win32Resources; if (nativeResourcesOpt?.Any() == true) { return new ResourceSectionBuilderFromResources(nativeResourcesOpt); } return null; } private class ResourceSectionBuilderFromObj : ResourceSectionBuilder { private readonly ResourceSection _resourceSection; public ResourceSectionBuilderFromObj(ResourceSection resourceSection) { Debug.Assert(resourceSection != null); _resourceSection = resourceSection; } protected override void Serialize(BlobBuilder builder, SectionLocation location) { NativeResourceWriter.SerializeWin32Resources(builder, _resourceSection, location.RelativeVirtualAddress); } } private class ResourceSectionBuilderFromResources : ResourceSectionBuilder { private readonly IEnumerable<IWin32Resource> _resources; public ResourceSectionBuilderFromResources(IEnumerable<IWin32Resource> resources) { Debug.Assert(resources.Any()); _resources = resources; } protected override void Serialize(BlobBuilder builder, SectionLocation location) { NativeResourceWriter.SerializeWin32Resources(builder, _resources, location.RelativeVirtualAddress); } } private static int CalculateStrongNameSignatureSize(IModule module) { IAssembly assembly = module.AsAssembly; if (assembly == null) { return 0; } // EDMAURER the count of characters divided by two because the each pair of characters will turn in to one byte. int keySize = (assembly.SignatureKey == null) ? 0 : assembly.SignatureKey.Length / 2; if (keySize == 0) { keySize = assembly.PublicKey.Length; } if (keySize == 0) { return 0; } return (keySize < 128 + 32) ? 128 : keySize - 32; } } }
// 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.Collections.ObjectModel; using System.Globalization; using System.Xml; using System.Xml.Serialization; using System.Diagnostics.CodeAnalysis; using System.Xml.Schema; using System.ServiceModel.Channels; using System.Diagnostics; namespace System.ServiceModel.Syndication { [XmlRoot(ElementName = Atom10Constants.FeedTag, Namespace = Atom10Constants.Atom10Namespace)] public class Atom10FeedFormatter : SyndicationFeedFormatter, IXmlSerializable { internal const string XmlNs = "http://www.w3.org/XML/1998/namespace"; internal const string XmlNsNs = "http://www.w3.org/2000/xmlns/"; private static readonly XmlQualifiedName s_atom10Href = new XmlQualifiedName(Atom10Constants.HrefTag, string.Empty); private static readonly XmlQualifiedName s_atom10Label = new XmlQualifiedName(Atom10Constants.LabelTag, string.Empty); private static readonly XmlQualifiedName s_atom10Length = new XmlQualifiedName(Atom10Constants.LengthTag, string.Empty); private static readonly XmlQualifiedName s_atom10Relative = new XmlQualifiedName(Atom10Constants.RelativeTag, string.Empty); private static readonly XmlQualifiedName s_atom10Scheme = new XmlQualifiedName(Atom10Constants.SchemeTag, string.Empty); private static readonly XmlQualifiedName s_atom10Term = new XmlQualifiedName(Atom10Constants.TermTag, string.Empty); private static readonly XmlQualifiedName s_atom10Title = new XmlQualifiedName(Atom10Constants.TitleTag, string.Empty); private static readonly XmlQualifiedName s_atom10Type = new XmlQualifiedName(Atom10Constants.TypeTag, string.Empty); private static readonly UriGenerator s_idGenerator = new UriGenerator(); private const string Rfc3339LocalDateTimeFormat = "yyyy-MM-ddTHH:mm:sszzz"; private const string Rfc3339UTCDateTimeFormat = "yyyy-MM-ddTHH:mm:ssZ"; private readonly int _maxExtensionSize; public Atom10FeedFormatter() : this(typeof(SyndicationFeed)) { } public Atom10FeedFormatter(Type feedTypeToCreate) : base() { if (feedTypeToCreate == null) { throw new ArgumentNullException(nameof(feedTypeToCreate)); } if (!typeof(SyndicationFeed).IsAssignableFrom(feedTypeToCreate)) { throw new ArgumentException(SR.Format(SR.InvalidObjectTypePassed, nameof(feedTypeToCreate), nameof(SyndicationFeed)), nameof(feedTypeToCreate)); } _maxExtensionSize = int.MaxValue; FeedType = feedTypeToCreate; } public Atom10FeedFormatter(SyndicationFeed feedToWrite) : base(feedToWrite) { // No need to check that the parameter passed is valid - it is checked by the c'tor of the base class _maxExtensionSize = int.MaxValue; FeedType = feedToWrite.GetType(); } internal override TryParseDateTimeCallback GetDefaultDateTimeParser() { return DateTimeHelper.DefaultAtom10DateTimeParser; } public bool PreserveAttributeExtensions { get; set; } = true; public bool PreserveElementExtensions { get; set; } = true; public override string Version => SyndicationVersions.Atom10; protected Type FeedType { get; } public override bool CanRead(XmlReader reader) { if (reader == null) { throw new ArgumentNullException(nameof(reader)); } return reader.IsStartElement(Atom10Constants.FeedTag, Atom10Constants.Atom10Namespace); } [SuppressMessage("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes", Justification = "The IXmlSerializable implementation is only for exposing under WCF DataContractSerializer. The funcionality is exposed to derived class through the ReadFrom\\WriteTo methods")] XmlSchema IXmlSerializable.GetSchema() => null; [SuppressMessage("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes", Justification = "The IXmlSerializable implementation is only for exposing under WCF DataContractSerializer. The funcionality is exposed to derived class through the ReadFrom\\WriteTo methods")] void IXmlSerializable.ReadXml(XmlReader reader) { if (reader == null) { throw new ArgumentNullException(nameof(reader)); } ReadFeed(reader); } [SuppressMessage("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes", Justification = "The IXmlSerializable implementation is only for exposing under WCF DataContractSerializer. The funcionality is exposed to derived class through the ReadFrom\\WriteTo methods")] void IXmlSerializable.WriteXml(XmlWriter writer) { if (writer == null) { throw new ArgumentNullException(nameof(writer)); } WriteFeed(writer); } public override void ReadFrom(XmlReader reader) { if (!CanRead(reader)) { throw new XmlException(SR.Format(SR.UnknownFeedXml, reader.LocalName, reader.NamespaceURI)); } ReadFeed(reader); } public override void WriteTo(XmlWriter writer) { if (writer == null) { throw new ArgumentNullException(nameof(writer)); } writer.WriteStartElement(Atom10Constants.FeedTag, Atom10Constants.Atom10Namespace); WriteFeed(writer); writer.WriteEndElement(); } internal static void ReadCategory(XmlReader reader, SyndicationCategory category, string version, bool preserveAttributeExtensions, bool preserveElementExtensions, int maxExtensionSize) { MoveToStartElement(reader); bool isEmpty = reader.IsEmptyElement; if (reader.HasAttributes) { while (reader.MoveToNextAttribute()) { if (reader.LocalName == Atom10Constants.TermTag && reader.NamespaceURI == string.Empty) { category.Name = reader.Value; } else if (reader.LocalName == Atom10Constants.SchemeTag && reader.NamespaceURI == string.Empty) { category.Scheme = reader.Value; } else if (reader.LocalName == Atom10Constants.LabelTag && reader.NamespaceURI == string.Empty) { category.Label = reader.Value; } else { string ns = reader.NamespaceURI; string name = reader.LocalName; if (FeedUtils.IsXmlns(name, ns)) { continue; } string val = reader.Value; if (!TryParseAttribute(name, ns, val, category, version)) { if (preserveAttributeExtensions) { category.AttributeExtensions.Add(new XmlQualifiedName(name, ns), val); } } } } } if (!isEmpty) { reader.ReadStartElement(); XmlBuffer buffer = null; XmlDictionaryWriter extWriter = null; try { while (reader.IsStartElement()) { if (TryParseElement(reader, category, version)) { continue; } else if (!preserveElementExtensions) { reader.Skip(); } else { CreateBufferIfRequiredAndWriteNode(ref buffer, ref extWriter, reader, maxExtensionSize); } } LoadElementExtensions(buffer, extWriter, category); } finally { extWriter?.Dispose(); } reader.ReadEndElement(); } else { reader.ReadStartElement(); } } internal static TextSyndicationContent ReadTextContentFrom(XmlReader reader, string context, bool preserveAttributeExtensions) { string type = reader.GetAttribute(Atom10Constants.TypeTag); return ReadTextContentFromHelper(reader, type, context, preserveAttributeExtensions); } internal static void WriteCategory(XmlWriter writer, SyndicationCategory category, string version) { writer.WriteStartElement(Atom10Constants.CategoryTag, Atom10Constants.Atom10Namespace); WriteAttributeExtensions(writer, category, version); string categoryName = category.Name ?? string.Empty; if (!category.AttributeExtensions.ContainsKey(s_atom10Term)) { writer.WriteAttributeString(Atom10Constants.TermTag, categoryName); } if (!string.IsNullOrEmpty(category.Label) && !category.AttributeExtensions.ContainsKey(s_atom10Label)) { writer.WriteAttributeString(Atom10Constants.LabelTag, category.Label); } if (!string.IsNullOrEmpty(category.Scheme) && !category.AttributeExtensions.ContainsKey(s_atom10Scheme)) { writer.WriteAttributeString(Atom10Constants.SchemeTag, category.Scheme); } WriteElementExtensions(writer, category, version); writer.WriteEndElement(); } internal void ReadItemFrom(XmlReader reader, SyndicationItem result) { ReadItemFrom(reader, result, null); } internal bool TryParseFeedElementFrom(XmlReader reader, SyndicationFeed result) { if (reader.IsStartElement(Atom10Constants.AuthorTag, Atom10Constants.Atom10Namespace)) { result.Authors.Add(ReadPersonFrom(reader, result)); } else if (reader.IsStartElement(Atom10Constants.CategoryTag, Atom10Constants.Atom10Namespace)) { result.Categories.Add(ReadCategoryFrom(reader, result)); } else if (reader.IsStartElement(Atom10Constants.ContributorTag, Atom10Constants.Atom10Namespace)) { result.Contributors.Add(ReadPersonFrom(reader, result)); } else if (reader.IsStartElement(Atom10Constants.GeneratorTag, Atom10Constants.Atom10Namespace)) { result.Generator = reader.ReadElementString(); } else if (reader.IsStartElement(Atom10Constants.IdTag, Atom10Constants.Atom10Namespace)) { result.Id = reader.ReadElementString(); } else if (reader.IsStartElement(Atom10Constants.LinkTag, Atom10Constants.Atom10Namespace)) { result.Links.Add(ReadLinkFrom(reader, result)); } else if (reader.IsStartElement(Atom10Constants.LogoTag, Atom10Constants.Atom10Namespace)) { result.ImageUrl = UriFromString(reader.ReadElementString(), UriKind.RelativeOrAbsolute, Atom10Constants.LogoTag, Atom10Constants.Atom10Namespace, reader); } else if (reader.IsStartElement(Atom10Constants.RightsTag, Atom10Constants.Atom10Namespace)) { result.Copyright = ReadTextContentFrom(reader, "//atom:feed/atom:rights[@type]"); } else if (reader.IsStartElement(Atom10Constants.SubtitleTag, Atom10Constants.Atom10Namespace)) { result.Description = ReadTextContentFrom(reader, "//atom:feed/atom:subtitle[@type]"); } else if (reader.IsStartElement(Atom10Constants.TitleTag, Atom10Constants.Atom10Namespace)) { result.Title = ReadTextContentFrom(reader, "//atom:feed/atom:title[@type]"); } else if (reader.IsStartElement(Atom10Constants.UpdatedTag, Atom10Constants.Atom10Namespace)) { reader.ReadStartElement(); string dtoString = reader.ReadString(); try { result.LastUpdatedTime = DateFromString(dtoString, reader); } catch (XmlException e) { result.LastUpdatedTimeException = e; } reader.ReadEndElement(); } else { return false; } return true; } internal bool TryParseItemElementFrom(XmlReader reader, SyndicationItem result) { if (reader.IsStartElement(Atom10Constants.AuthorTag, Atom10Constants.Atom10Namespace)) { result.Authors.Add(ReadPersonFrom(reader, result)); } else if (reader.IsStartElement(Atom10Constants.CategoryTag, Atom10Constants.Atom10Namespace)) { result.Categories.Add(ReadCategoryFrom(reader, result)); } else if (reader.IsStartElement(Atom10Constants.ContentTag, Atom10Constants.Atom10Namespace)) { result.Content = ReadContentFrom(reader, result); } else if (reader.IsStartElement(Atom10Constants.ContributorTag, Atom10Constants.Atom10Namespace)) { result.Contributors.Add(ReadPersonFrom(reader, result)); } else if (reader.IsStartElement(Atom10Constants.IdTag, Atom10Constants.Atom10Namespace)) { result.Id = reader.ReadElementString(); } else if (reader.IsStartElement(Atom10Constants.LinkTag, Atom10Constants.Atom10Namespace)) { result.Links.Add(ReadLinkFrom(reader, result)); } else if (reader.IsStartElement(Atom10Constants.PublishedTag, Atom10Constants.Atom10Namespace)) { reader.ReadStartElement(); string dtoString = reader.ReadString(); try { result.PublishDate = DateFromString(dtoString, reader); } catch (XmlException e) { result.PublishDateException = e; } reader.ReadEndElement(); } else if (reader.IsStartElement(Atom10Constants.RightsTag, Atom10Constants.Atom10Namespace)) { result.Copyright = ReadTextContentFrom(reader, "//atom:feed/atom:entry/atom:rights[@type]"); } else if (reader.IsStartElement(Atom10Constants.SourceFeedTag, Atom10Constants.Atom10Namespace)) { reader.ReadStartElement(); result.SourceFeed = ReadFeedFrom(reader, new SyndicationFeed(), true); // isSourceFeed reader.ReadEndElement(); } else if (reader.IsStartElement(Atom10Constants.SummaryTag, Atom10Constants.Atom10Namespace)) { result.Summary = ReadTextContentFrom(reader, "//atom:feed/atom:entry/atom:summary[@type]"); } else if (reader.IsStartElement(Atom10Constants.TitleTag, Atom10Constants.Atom10Namespace)) { result.Title = ReadTextContentFrom(reader, "//atom:feed/atom:entry/atom:title[@type]"); } else if (reader.IsStartElement(Atom10Constants.UpdatedTag, Atom10Constants.Atom10Namespace)) { reader.ReadStartElement(); string dtoString = reader.ReadString(); try { result.LastUpdatedTime = DateFromString(dtoString, reader); } catch (XmlException e) { result.LastUpdatedTimeException = e; } reader.ReadEndElement(); } else { return false; } return true; } internal void WriteContentTo(XmlWriter writer, string elementName, SyndicationContent content) { if (content != null) { content.WriteTo(writer, elementName, Atom10Constants.Atom10Namespace); } } internal void WriteElement(XmlWriter writer, string elementName, string value) { if (value != null) { writer.WriteElementString(elementName, Atom10Constants.Atom10Namespace, value); } } internal void WriteFeedAuthorsTo(XmlWriter writer, Collection<SyndicationPerson> authors) { for (int i = 0; i < authors.Count; ++i) { SyndicationPerson p = authors[i]; WritePersonTo(writer, p, Atom10Constants.AuthorTag); } } internal void WriteFeedContributorsTo(XmlWriter writer, Collection<SyndicationPerson> contributors) { for (int i = 0; i < contributors.Count; ++i) { SyndicationPerson p = contributors[i]; WritePersonTo(writer, p, Atom10Constants.ContributorTag); } } internal void WriteFeedLastUpdatedTimeTo(XmlWriter writer, DateTimeOffset lastUpdatedTime, bool isRequired) { if (lastUpdatedTime == DateTimeOffset.MinValue && isRequired) { lastUpdatedTime = DateTimeOffset.UtcNow; } if (lastUpdatedTime != DateTimeOffset.MinValue) { WriteElement(writer, Atom10Constants.UpdatedTag, AsString(lastUpdatedTime)); } } internal void WriteItemAuthorsTo(XmlWriter writer, Collection<SyndicationPerson> authors) { for (int i = 0; i < authors.Count; ++i) { SyndicationPerson p = authors[i]; WritePersonTo(writer, p, Atom10Constants.AuthorTag); } } internal void WriteItemContents(XmlWriter dictWriter, SyndicationItem item) { WriteItemContents(dictWriter, item, null); } internal void WriteItemContributorsTo(XmlWriter writer, Collection<SyndicationPerson> contributors) { for (int i = 0; i < contributors.Count; ++i) { SyndicationPerson p = contributors[i]; WritePersonTo(writer, p, Atom10Constants.ContributorTag); } } internal void WriteItemLastUpdatedTimeTo(XmlWriter writer, DateTimeOffset lastUpdatedTime) { if (lastUpdatedTime == DateTimeOffset.MinValue) { lastUpdatedTime = DateTimeOffset.UtcNow; } writer.WriteElementString(Atom10Constants.UpdatedTag, Atom10Constants.Atom10Namespace, AsString(lastUpdatedTime)); } internal void WriteLink(XmlWriter writer, SyndicationLink link, Uri baseUri) { writer.WriteStartElement(Atom10Constants.LinkTag, Atom10Constants.Atom10Namespace); Uri baseUriToWrite = FeedUtils.GetBaseUriToWrite(baseUri, link.BaseUri); if (baseUriToWrite != null) { writer.WriteAttributeString("xml", "base", XmlNs, FeedUtils.GetUriString(baseUriToWrite)); } link.WriteAttributeExtensions(writer, SyndicationVersions.Atom10); if (!string.IsNullOrEmpty(link.RelationshipType) && !link.AttributeExtensions.ContainsKey(s_atom10Relative)) { writer.WriteAttributeString(Atom10Constants.RelativeTag, link.RelationshipType); } if (!string.IsNullOrEmpty(link.MediaType) && !link.AttributeExtensions.ContainsKey(s_atom10Type)) { writer.WriteAttributeString(Atom10Constants.TypeTag, link.MediaType); } if (!string.IsNullOrEmpty(link.Title) && !link.AttributeExtensions.ContainsKey(s_atom10Title)) { writer.WriteAttributeString(Atom10Constants.TitleTag, link.Title); } if (link.Length != 0 && !link.AttributeExtensions.ContainsKey(s_atom10Length)) { writer.WriteAttributeString(Atom10Constants.LengthTag, Convert.ToString(link.Length, CultureInfo.InvariantCulture)); } if (!link.AttributeExtensions.ContainsKey(s_atom10Href)) { writer.WriteAttributeString(Atom10Constants.HrefTag, FeedUtils.GetUriString(link.Uri)); } link.WriteElementExtensions(writer, SyndicationVersions.Atom10); writer.WriteEndElement(); } protected override SyndicationFeed CreateFeedInstance() => CreateFeedInstance(FeedType); protected virtual SyndicationItem ReadItem(XmlReader reader, SyndicationFeed feed) { if (feed == null) { throw new ArgumentNullException(nameof(feed)); } if (reader == null) { throw new ArgumentNullException(nameof(reader)); } SyndicationItem item = CreateItem(feed); ReadItemFrom(reader, item, feed.BaseUri); return item; } [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", MessageId = "2#", Justification = "The out parameter is needed to enable implementations that read in items from the stream on demand")] protected virtual IEnumerable<SyndicationItem> ReadItems(XmlReader reader, SyndicationFeed feed, out bool areAllItemsRead) { if (feed == null) { throw new ArgumentNullException(nameof(feed)); } if (reader == null) { throw new ArgumentNullException(nameof(reader)); } NullNotAllowedCollection<SyndicationItem> items = new NullNotAllowedCollection<SyndicationItem>(); while (reader.IsStartElement(Atom10Constants.EntryTag, Atom10Constants.Atom10Namespace)) { items.Add(ReadItem(reader, feed)); } areAllItemsRead = true; return items; } protected virtual void WriteItem(XmlWriter writer, SyndicationItem item, Uri feedBaseUri) { writer.WriteStartElement(Atom10Constants.EntryTag, Atom10Constants.Atom10Namespace); WriteItemContents(writer, item, feedBaseUri); writer.WriteEndElement(); } protected virtual void WriteItems(XmlWriter writer, IEnumerable<SyndicationItem> items, Uri feedBaseUri) { if (items == null) { return; } foreach (SyndicationItem item in items) { WriteItem(writer, item, feedBaseUri); } } private static TextSyndicationContent ReadTextContentFromHelper(XmlReader reader, string type, string context, bool preserveAttributeExtensions) { if (string.IsNullOrEmpty(type)) { type = Atom10Constants.PlaintextType; } TextSyndicationContentKind kind; switch (type) { case Atom10Constants.PlaintextType: kind = TextSyndicationContentKind.Plaintext; break; case Atom10Constants.HtmlType: kind = TextSyndicationContentKind.Html; break; case Atom10Constants.XHtmlType: kind = TextSyndicationContentKind.XHtml; break; default: throw new XmlException(FeedUtils.AddLineInfo(reader, SR.Format(SR.Atom10SpecRequiresTextConstruct, context, type))); } Dictionary<XmlQualifiedName, string> attrs = null; if (reader.HasAttributes) { while (reader.MoveToNextAttribute()) { if (reader.LocalName == Atom10Constants.TypeTag && reader.NamespaceURI == string.Empty) { continue; } string ns = reader.NamespaceURI; string name = reader.LocalName; if (FeedUtils.IsXmlns(name, ns)) { continue; } if (preserveAttributeExtensions) { string value = reader.Value; if (attrs == null) { attrs = new Dictionary<XmlQualifiedName, string>(); } attrs.Add(new XmlQualifiedName(name, ns), value); } } } reader.MoveToElement(); string localName = reader.LocalName; string nameSpace = reader.NamespaceURI; string val = (kind == TextSyndicationContentKind.XHtml) ? reader.ReadInnerXml() : reader.ReadElementString(); TextSyndicationContent result = new TextSyndicationContent(val, kind); if (attrs != null) { foreach (XmlQualifiedName attr in attrs.Keys) { Debug.Assert(!FeedUtils.IsXmlns(attr.Name, attr.Namespace), "XML namespace attributes should not be added to the list." ); result.AttributeExtensions.Add(attr, attrs[attr]); } } return result; } private string AsString(DateTimeOffset dateTime) { if (dateTime.Offset == TimeSpan.Zero) { return dateTime.ToUniversalTime().ToString(Rfc3339UTCDateTimeFormat, CultureInfo.InvariantCulture); } else { return dateTime.ToString(Rfc3339LocalDateTimeFormat, CultureInfo.InvariantCulture); } } private void ReadCategory(XmlReader reader, SyndicationCategory category) { ReadCategory(reader, category, Version, PreserveAttributeExtensions, PreserveElementExtensions, _maxExtensionSize); } private SyndicationCategory ReadCategoryFrom(XmlReader reader, SyndicationFeed feed) { SyndicationCategory result = CreateCategory(feed); ReadCategory(reader, result); return result; } private SyndicationCategory ReadCategoryFrom(XmlReader reader, SyndicationItem item) { SyndicationCategory result = CreateCategory(item); ReadCategory(reader, result); return result; } private SyndicationContent ReadContentFrom(XmlReader reader, SyndicationItem item) { MoveToStartElement(reader); string type = reader.GetAttribute(Atom10Constants.TypeTag, string.Empty); if (TryParseContent(reader, item, type, Version, out SyndicationContent result)) { return result; } if (string.IsNullOrEmpty(type)) { type = Atom10Constants.PlaintextType; } string src = reader.GetAttribute(Atom10Constants.SourceTag, string.Empty); if (string.IsNullOrEmpty(src) && type != Atom10Constants.PlaintextType && type != Atom10Constants.HtmlType && type != Atom10Constants.XHtmlType) { return new XmlSyndicationContent(reader); } if (!string.IsNullOrEmpty(src)) { result = new UrlSyndicationContent(UriFromString(src, UriKind.RelativeOrAbsolute, Atom10Constants.ContentTag, Atom10Constants.Atom10Namespace, reader), type); bool isEmpty = reader.IsEmptyElement; if (reader.HasAttributes) { while (reader.MoveToNextAttribute()) { if (reader.LocalName == Atom10Constants.TypeTag && reader.NamespaceURI == string.Empty) { continue; } else if (reader.LocalName == Atom10Constants.SourceTag && reader.NamespaceURI == string.Empty) { continue; } else if (!FeedUtils.IsXmlns(reader.LocalName, reader.NamespaceURI)) { if (PreserveAttributeExtensions) { result.AttributeExtensions.Add(new XmlQualifiedName(reader.LocalName, reader.NamespaceURI), reader.Value); } } } } reader.ReadStartElement(); if (!isEmpty) { reader.ReadEndElement(); } return result; } else { return ReadTextContentFromHelper(reader, type, "//atom:feed/atom:entry/atom:content[@type]", PreserveAttributeExtensions); } } private void ReadFeed(XmlReader reader) { SetFeed(CreateFeedInstance()); ReadFeedFrom(reader, Feed, false); } private SyndicationFeed ReadFeedFrom(XmlReader reader, SyndicationFeed result, bool isSourceFeed) { reader.MoveToContent(); try { bool elementIsEmpty = false; if (!isSourceFeed) { MoveToStartElement(reader); elementIsEmpty = reader.IsEmptyElement; if (reader.HasAttributes) { while (reader.MoveToNextAttribute()) { if (reader.LocalName == "lang" && reader.NamespaceURI == XmlNs) { result.Language = reader.Value; } else if (reader.LocalName == "base" && reader.NamespaceURI == XmlNs) { result.BaseUri = FeedUtils.CombineXmlBase(result.BaseUri, reader.Value); } else { string ns = reader.NamespaceURI; string name = reader.LocalName; if (FeedUtils.IsXmlns(name, ns) || FeedUtils.IsXmlSchemaType(name, ns)) { continue; } string val = reader.Value; if (!TryParseAttribute(name, ns, val, result, Version)) { if (PreserveAttributeExtensions) { result.AttributeExtensions.Add(new XmlQualifiedName(reader.LocalName, reader.NamespaceURI), reader.Value); } } } } } reader.ReadStartElement(); } XmlBuffer buffer = null; XmlDictionaryWriter extWriter = null; bool areAllItemsRead = true; NullNotAllowedCollection<SyndicationItem> feedItems = null; if (!elementIsEmpty) { try { while (reader.IsStartElement()) { if (TryParseFeedElementFrom(reader, result)) { // nothing, we parsed something, great } else if (reader.IsStartElement(Atom10Constants.EntryTag, Atom10Constants.Atom10Namespace) && !isSourceFeed) { feedItems = feedItems ?? new NullNotAllowedCollection<SyndicationItem>(); IEnumerable<SyndicationItem> items = ReadItems(reader, result, out areAllItemsRead); foreach(SyndicationItem item in items) { feedItems.Add(item); } // if the derived class is reading the items lazily, then stop reading from the stream if (!areAllItemsRead) { break; } } else { if (!TryParseElement(reader, result, Version)) { if (PreserveElementExtensions) { CreateBufferIfRequiredAndWriteNode(ref buffer, ref extWriter, reader, _maxExtensionSize); } else { reader.Skip(); } } } } if (feedItems != null) { result.Items = feedItems; } LoadElementExtensions(buffer, extWriter, result); } finally { if (extWriter != null) { ((IDisposable)extWriter).Dispose(); } } } if (!isSourceFeed && areAllItemsRead) { reader.ReadEndElement(); // feed } } catch (FormatException e) { throw new XmlException(FeedUtils.AddLineInfo(reader, SR.ErrorParsingFeed), e); } catch (ArgumentException e) { throw new XmlException(FeedUtils.AddLineInfo(reader, SR.ErrorParsingFeed), e); } return result; } private void ReadItemFrom(XmlReader reader, SyndicationItem result, Uri feedBaseUri) { try { result.BaseUri = feedBaseUri; MoveToStartElement(reader); bool isEmpty = reader.IsEmptyElement; if (reader.HasAttributes) { while (reader.MoveToNextAttribute()) { string ns = reader.NamespaceURI; string name = reader.LocalName; if (name == "base" && ns == XmlNs) { result.BaseUri = FeedUtils.CombineXmlBase(result.BaseUri, reader.Value); continue; } if (FeedUtils.IsXmlns(name, ns) || FeedUtils.IsXmlSchemaType(name, ns)) { continue; } string val = reader.Value; if (!TryParseAttribute(name, ns, val, result, Version)) { if (PreserveAttributeExtensions) { result.AttributeExtensions.Add(new XmlQualifiedName(reader.LocalName, reader.NamespaceURI), reader.Value); } } } } reader.ReadStartElement(); if (!isEmpty) { XmlBuffer buffer = null; XmlDictionaryWriter extWriter = null; try { while (reader.IsStartElement()) { if (TryParseItemElementFrom(reader, result)) { // nothing, we parsed something, great } else { if (!TryParseElement(reader, result, Version)) { if (PreserveElementExtensions) { CreateBufferIfRequiredAndWriteNode(ref buffer, ref extWriter, reader, _maxExtensionSize); } else { reader.Skip(); } } } } LoadElementExtensions(buffer, extWriter, result); } finally { extWriter?.Dispose(); } reader.ReadEndElement(); // item } } catch (FormatException e) { throw new XmlException(FeedUtils.AddLineInfo(reader, SR.ErrorParsingItem), e); } catch (ArgumentException e) { throw new XmlException(FeedUtils.AddLineInfo(reader, SR.ErrorParsingItem), e); } } private void ReadLink(XmlReader reader, SyndicationLink link, Uri baseUri) { bool isEmpty = reader.IsEmptyElement; string mediaType = null; string relationship = null; string title = null; string lengthStr = null; string val = null; link.BaseUri = baseUri; if (reader.HasAttributes) { while (reader.MoveToNextAttribute()) { if (reader.LocalName == "base" && reader.NamespaceURI == XmlNs) { link.BaseUri = FeedUtils.CombineXmlBase(link.BaseUri, reader.Value); } else if (reader.LocalName == Atom10Constants.TypeTag && reader.NamespaceURI == string.Empty) { mediaType = reader.Value; } else if (reader.LocalName == Atom10Constants.RelativeTag && reader.NamespaceURI == string.Empty) { relationship = reader.Value; } else if (reader.LocalName == Atom10Constants.TitleTag && reader.NamespaceURI == string.Empty) { title = reader.Value; } else if (reader.LocalName == Atom10Constants.LengthTag && reader.NamespaceURI == string.Empty) { lengthStr = reader.Value; } else if (reader.LocalName == Atom10Constants.HrefTag && reader.NamespaceURI == string.Empty) { val = reader.Value; } else if (!FeedUtils.IsXmlns(reader.LocalName, reader.NamespaceURI)) { if (PreserveAttributeExtensions) { link.AttributeExtensions.Add(new XmlQualifiedName(reader.LocalName, reader.NamespaceURI), reader.Value); } } } } long length = 0; if (!string.IsNullOrEmpty(lengthStr)) { length = Convert.ToInt64(lengthStr, CultureInfo.InvariantCulture.NumberFormat); } reader.ReadStartElement(); if (!isEmpty) { XmlBuffer buffer = null; XmlDictionaryWriter extWriter = null; try { while (reader.IsStartElement()) { if (TryParseElement(reader, link, Version)) { continue; } else if (!PreserveElementExtensions) { reader.Skip(); } else { CreateBufferIfRequiredAndWriteNode(ref buffer, ref extWriter, reader, _maxExtensionSize); } } LoadElementExtensions(buffer, extWriter, link); } finally { extWriter?.Dispose(); } reader.ReadEndElement(); } link.Length = length; link.MediaType = mediaType; link.RelationshipType = relationship; link.Title = title; link.Uri = (val != null) ? UriFromString(val, UriKind.RelativeOrAbsolute, Atom10Constants.LinkTag, Atom10Constants.Atom10Namespace, reader) : null; } private SyndicationLink ReadLinkFrom(XmlReader reader, SyndicationFeed feed) { SyndicationLink result = CreateLink(feed); ReadLink(reader, result, feed.BaseUri); return result; } private SyndicationLink ReadLinkFrom(XmlReader reader, SyndicationItem item) { SyndicationLink result = CreateLink(item); ReadLink(reader, result, item.BaseUri); return result; } private SyndicationPerson ReadPersonFrom(XmlReader reader, SyndicationFeed feed) { SyndicationPerson result = CreatePerson(feed); ReadPersonFrom(reader, result); return result; } private SyndicationPerson ReadPersonFrom(XmlReader reader, SyndicationItem item) { SyndicationPerson result = CreatePerson(item); ReadPersonFrom(reader, result); return result; } private void ReadPersonFrom(XmlReader reader, SyndicationPerson result) { bool isEmpty = reader.IsEmptyElement; if (reader.HasAttributes) { while (reader.MoveToNextAttribute()) { string ns = reader.NamespaceURI; string name = reader.LocalName; if (FeedUtils.IsXmlns(name, ns)) { continue; } string val = reader.Value; if (!TryParseAttribute(name, ns, val, result, Version)) { if (PreserveAttributeExtensions) { result.AttributeExtensions.Add(new XmlQualifiedName(reader.LocalName, reader.NamespaceURI), reader.Value); } } } } reader.ReadStartElement(); if (!isEmpty) { XmlBuffer buffer = null; XmlDictionaryWriter extWriter = null; try { while (reader.IsStartElement()) { if (reader.IsStartElement(Atom10Constants.NameTag, Atom10Constants.Atom10Namespace)) { result.Name = reader.ReadElementString(); } else if (reader.IsStartElement(Atom10Constants.UriTag, Atom10Constants.Atom10Namespace)) { result.Uri = reader.ReadElementString(); } else if (reader.IsStartElement(Atom10Constants.EmailTag, Atom10Constants.Atom10Namespace)) { result.Email = reader.ReadElementString(); } else { if (!TryParseElement(reader, result, Version)) { if (PreserveElementExtensions) { CreateBufferIfRequiredAndWriteNode(ref buffer, ref extWriter, reader, _maxExtensionSize); } else { reader.Skip(); } } } } LoadElementExtensions(buffer, extWriter, result); } finally { extWriter?.Dispose(); } reader.ReadEndElement(); } } private TextSyndicationContent ReadTextContentFrom(XmlReader reader, string context) { return ReadTextContentFrom(reader, context, PreserveAttributeExtensions); } private void WriteCategoriesTo(XmlWriter writer, Collection<SyndicationCategory> categories) { for (int i = 0; i < categories.Count; ++i) { WriteCategory(writer, categories[i], Version); } } private void WriteFeed(XmlWriter writer) { if (Feed == null) { throw new InvalidOperationException(SR.FeedFormatterDoesNotHaveFeed); } WriteFeedTo(writer, Feed, isSourceFeed: false); } private void WriteFeedTo(XmlWriter writer, SyndicationFeed feed, bool isSourceFeed) { if (!isSourceFeed) { if (!string.IsNullOrEmpty(feed.Language)) { writer.WriteAttributeString("xml", "lang", XmlNs, feed.Language); } if (feed.BaseUri != null) { writer.WriteAttributeString("xml", "base", XmlNs, FeedUtils.GetUriString(feed.BaseUri)); } WriteAttributeExtensions(writer, feed, Version); } bool isElementRequired = !isSourceFeed; TextSyndicationContent title = feed.Title; if (isElementRequired) { title = title ?? new TextSyndicationContent(string.Empty); } WriteContentTo(writer, Atom10Constants.TitleTag, title); WriteContentTo(writer, Atom10Constants.SubtitleTag, feed.Description); string id = feed.Id; if (isElementRequired) { id = id ?? s_idGenerator.Next(); } WriteElement(writer, Atom10Constants.IdTag, id); WriteContentTo(writer, Atom10Constants.RightsTag, feed.Copyright); WriteFeedLastUpdatedTimeTo(writer, feed.LastUpdatedTime, isElementRequired); WriteCategoriesTo(writer, feed.Categories); if (feed.ImageUrl != null) { WriteElement(writer, Atom10Constants.LogoTag, feed.ImageUrl.ToString()); } WriteFeedAuthorsTo(writer, feed.Authors); WriteFeedContributorsTo(writer, feed.Contributors); WriteElement(writer, Atom10Constants.GeneratorTag, feed.Generator); for (int i = 0; i < feed.Links.Count; ++i) { WriteLink(writer, feed.Links[i], feed.BaseUri); } WriteElementExtensions(writer, feed, Version); if (!isSourceFeed) { WriteItems(writer, feed.Items, feed.BaseUri); } } private void WriteItemContents(XmlWriter dictWriter, SyndicationItem item, Uri feedBaseUri) { Uri baseUriToWrite = FeedUtils.GetBaseUriToWrite(feedBaseUri, item.BaseUri); if (baseUriToWrite != null) { dictWriter.WriteAttributeString("xml", "base", XmlNs, FeedUtils.GetUriString(baseUriToWrite)); } WriteAttributeExtensions(dictWriter, item, Version); string id = item.Id ?? s_idGenerator.Next(); WriteElement(dictWriter, Atom10Constants.IdTag, id); TextSyndicationContent title = item.Title ?? new TextSyndicationContent(string.Empty); WriteContentTo(dictWriter, Atom10Constants.TitleTag, title); WriteContentTo(dictWriter, Atom10Constants.SummaryTag, item.Summary); if (item.PublishDate != DateTimeOffset.MinValue) { dictWriter.WriteElementString(Atom10Constants.PublishedTag, Atom10Constants.Atom10Namespace, AsString(item.PublishDate)); } WriteItemLastUpdatedTimeTo(dictWriter, item.LastUpdatedTime); WriteItemAuthorsTo(dictWriter, item.Authors); WriteItemContributorsTo(dictWriter, item.Contributors); for (int i = 0; i < item.Links.Count; ++i) { WriteLink(dictWriter, item.Links[i], item.BaseUri); } WriteCategoriesTo(dictWriter, item.Categories); WriteContentTo(dictWriter, Atom10Constants.ContentTag, item.Content); WriteContentTo(dictWriter, Atom10Constants.RightsTag, item.Copyright); if (item.SourceFeed != null) { dictWriter.WriteStartElement(Atom10Constants.SourceFeedTag, Atom10Constants.Atom10Namespace); WriteFeedTo(dictWriter, item.SourceFeed, isSourceFeed: true); dictWriter.WriteEndElement(); } WriteElementExtensions(dictWriter, item, Version); } private void WritePersonTo(XmlWriter writer, SyndicationPerson p, string elementName) { writer.WriteStartElement(elementName, Atom10Constants.Atom10Namespace); WriteAttributeExtensions(writer, p, Version); WriteElement(writer, Atom10Constants.NameTag, p.Name); if (!string.IsNullOrEmpty(p.Uri)) { writer.WriteElementString(Atom10Constants.UriTag, Atom10Constants.Atom10Namespace, p.Uri); } if (!string.IsNullOrEmpty(p.Email)) { writer.WriteElementString(Atom10Constants.EmailTag, Atom10Constants.Atom10Namespace, p.Email); } WriteElementExtensions(writer, p, Version); writer.WriteEndElement(); } } [XmlRoot(ElementName = Atom10Constants.FeedTag, Namespace = Atom10Constants.Atom10Namespace)] public class Atom10FeedFormatter<TSyndicationFeed> : Atom10FeedFormatter where TSyndicationFeed : SyndicationFeed, new() { public Atom10FeedFormatter() : base(typeof(TSyndicationFeed)) { } public Atom10FeedFormatter(TSyndicationFeed feedToWrite) : base(feedToWrite) { } protected override SyndicationFeed CreateFeedInstance() => new TSyndicationFeed(); } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Microsoft.Tools.Transformer.CodeModel; using System; using System.Xml; namespace ModelFileToCCI2 { public abstract class ModelReader { public void RecursivelyReadBlock(XmlReader reader, object parentObj, bool include) { while (reader.Read() && (reader.NodeType != XmlNodeType.EndElement)) { XmlParseAssert(reader.IsStartElement()); switch (reader.Name) { case XmlKeywords.Elements.Xml: { XmlParseAssert(include); XmlParseAssert(parentObj is ModelElement); RecursivelyReadBlock(reader, parentObj, true); break; } case XmlKeywords.Elements.ThinModel: { XmlParseAssert(include); XmlParseAssert(parentObj is ModelElement); RecursivelyReadBlock(reader, parentObj, true); break; } case XmlKeywords.Elements.Assembly: { XmlParseAssert(include); XmlParseAssert(parentObj is ModelElement); XmlParseAssert(reader.AttributeCount > 0); string assemblyName = reader.GetAttribute(XmlKeywords.Attributes.Name); XmlParseAssert(assemblyName != null); string includeStatusString = reader.GetAttribute(XmlKeywords.Attributes.IncludeStatus); IncludeStatus includeStatus = IncludeStatus.Inherit; if (includeStatusString != null) includeStatus = XmlKeywords.ParseIncludeStatus(includeStatusString); string platform = reader.GetAttribute(XmlKeywords.Attributes.Platform); string architecture = reader.GetAttribute(XmlKeywords.Attributes.Architecture); string flavor = reader.GetAttribute(XmlKeywords.Attributes.Flavor); string condition = reader.GetAttribute(XmlKeywords.Attributes.Condition); bool included = IncludeBuild(platform, architecture, flavor, condition); AssemblyElement assembly = null; if (included) assembly = CreateAssemblyElement((ModelElement)parentObj, assemblyName, includeStatus); if (!reader.IsEmptyElement) RecursivelyReadBlock(reader, assembly, included); break; } case XmlKeywords.Elements.Type: { TypeElement type = null; bool included = false; if (include) { XmlParseAssert(parentObj is AssemblyElement); XmlParseAssert(reader.AttributeCount > 0); string fullyQualifiedTypeName = reader.GetAttribute(XmlKeywords.Attributes.Name); XmlParseAssert(fullyQualifiedTypeName != null); AssemblyElement declaringAssembly = (AssemblyElement)parentObj; IncludeStatus includeStatus = declaringAssembly.IncludeStatus; string includeStatusString = reader.GetAttribute(XmlKeywords.Attributes.IncludeStatus); if (includeStatusString != null) includeStatus = XmlKeywords.ParseIncludeStatus(includeStatusString); SecurityTransparencyStatus securityTransparencyStatus = SecurityTransparencyStatus.Transparent; string securityTransparencyStatusString = reader.GetAttribute(XmlKeywords.Attributes.SecurityTransparencyStatus); if (securityTransparencyStatusString != null) securityTransparencyStatus = XmlKeywords.ParseSecurityTransparencyStatus(securityTransparencyStatusString); string visibilityOverrideString = reader.GetAttribute(XmlKeywords.Attributes.VisibilityOverride); VisibilityOverride visibilityOverride = XmlKeywords.ParseVisibilityOverride(visibilityOverrideString); string platform = reader.GetAttribute(XmlKeywords.Attributes.Platform); string architecture = reader.GetAttribute(XmlKeywords.Attributes.Architecture); string flavor = reader.GetAttribute(XmlKeywords.Attributes.Flavor); string condition = reader.GetAttribute(XmlKeywords.Attributes.Condition); included = IncludeBuild(platform, architecture, flavor, condition); if (included) type = CreateTypeElement(declaringAssembly, fullyQualifiedTypeName, includeStatus, visibilityOverride, securityTransparencyStatus); } if (!reader.IsEmptyElement) RecursivelyReadBlock(reader, type, included); break; } case XmlKeywords.Elements.TypeForwarder: { TypeForwarderElement type = null; bool included = false; if (include) { XmlParseAssert(parentObj is AssemblyElement); XmlParseAssert(reader.AttributeCount > 1); string assemblyName = reader.GetAttribute(XmlKeywords.Attributes.AssemblyName); string typeName = reader.GetAttribute(XmlKeywords.Attributes.TypeName); XmlParseAssert(assemblyName != null); XmlParseAssert(typeName != null); AssemblyElement declaringAssembly = (AssemblyElement)parentObj; IncludeStatus includeStatus = declaringAssembly.IncludeStatus; string includeStatusString = reader.GetAttribute(XmlKeywords.Attributes.IncludeStatus); if (includeStatusString != null) includeStatus = XmlKeywords.ParseIncludeStatus(includeStatusString); string platform = reader.GetAttribute(XmlKeywords.Attributes.Platform); string architecture = reader.GetAttribute(XmlKeywords.Attributes.Architecture); string flavor = reader.GetAttribute(XmlKeywords.Attributes.Flavor); string condition = reader.GetAttribute(XmlKeywords.Attributes.Condition); included = IncludeBuild(platform, architecture, flavor, condition); if (included) type = CreateTypeForwarderElement(declaringAssembly, assemblyName, typeName, includeStatus); } if (!reader.IsEmptyElement) RecursivelyReadBlock(reader, type, included); break; } case XmlKeywords.Elements.Member: { if (include) { XmlParseAssert(parentObj is TypeElement); XmlParseAssert(reader.AttributeCount > 0); string memberName = reader.GetAttribute(XmlKeywords.Attributes.Name); XmlParseAssert(memberName != null); TypeElement declaringType = (TypeElement)parentObj; string returnType = reader.GetAttribute(XmlKeywords.Attributes.ReturnType); string memberTypeString = reader.GetAttribute(XmlKeywords.Attributes.MemberType); MemberTypes memberType = XmlKeywords.ParseMemberType(memberTypeString); XmlParseAssert(memberType != MemberTypes.Unknown); IncludeStatus includeStatus = declaringType.IncludeStatus; string includeStatusString = reader.GetAttribute(XmlKeywords.Attributes.IncludeStatus); if (includeStatusString != null) includeStatus = XmlKeywords.ParseIncludeStatus(includeStatusString); if (includeStatus == IncludeStatus.Inherit) { throw new FormatException(String.Format("Specify include status for Member \"{0}\" in Type \"{1}\"", memberName, declaringType.Key)); } XmlParseAssert(includeStatus != IncludeStatus.Inherit); // Inherited virtual members "sometimes" don't inherit transparency status (when following certain rulesets) and we don't know // inheritance or rule status here. Therefore we can't say what the transparency status is here unless it's explicitly defined. SecurityTransparencyStatus securityTransparencyStatus = SecurityTransparencyStatus.Undefined; string securityTransparencyStatusString = reader.GetAttribute(XmlKeywords.Attributes.SecurityTransparencyStatus); if (securityTransparencyStatusString != null) { securityTransparencyStatus = XmlKeywords.ParseSecurityTransparencyStatus(securityTransparencyStatusString); } string visibilityOverrideString = reader.GetAttribute(XmlKeywords.Attributes.VisibilityOverride); VisibilityOverride visibilityOverride = XmlKeywords.ParseVisibilityOverride(visibilityOverrideString); string platform = reader.GetAttribute(XmlKeywords.Attributes.Platform); string architecture = reader.GetAttribute(XmlKeywords.Attributes.Architecture); string flavor = reader.GetAttribute(XmlKeywords.Attributes.Flavor); string condition = reader.GetAttribute(XmlKeywords.Attributes.Condition); bool included = IncludeBuild(platform, architecture, flavor, condition); if (included) CreateMemberElement(declaringType, memberName, returnType, memberType, includeStatus, visibilityOverride, securityTransparencyStatus); } break; } } } } private static void XmlParseAssert(bool expressionResult) { if (!expressionResult) throw new Exception("XML parse error"); } private static void InvalidXml(string message) { throw new Exception("InvalidXml: " + message); } abstract public AssemblyElement CreateAssemblyElement(ModelElement model, string assemblyName, IncludeStatus includeStatus); abstract public TypeElement CreateTypeElement(AssemblyElement assembly, string typeName, IncludeStatus includeStatus, VisibilityOverride visibilityOverride, SecurityTransparencyStatus securityTransparencyStatus); abstract public TypeForwarderElement CreateTypeForwarderElement(AssemblyElement parent, string assemblyName, string typeName, IncludeStatus includeStatus); abstract public MemberElement CreateMemberElement(TypeElement type, string memberName, string returnType, MemberTypes memberType, IncludeStatus includeStatus, VisibilityOverride visibilityOverride, SecurityTransparencyStatus securityTransparencyStatus); abstract public bool IncludeBuild(string platform, string architecture, string flavor, string condition); } }
using MagicOnion.Utils; using MessagePack; using System; using System.Collections.Concurrent; using System.Collections.Immutable; using System.Diagnostics.CodeAnalysis; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using System.Threading.Channels; namespace MagicOnion.Server.Hubs { public class ImmutableArrayGroupRepositoryFactory : IGroupRepositoryFactory { public IGroupRepository CreateRepository(MessagePackSerializerOptions serializerOptions, IMagicOnionLogger logger) { return new ImmutableArrayGroupRepository(serializerOptions, logger); } } public class ImmutableArrayGroupRepository : IGroupRepository { MessagePackSerializerOptions serializerOptions; IMagicOnionLogger logger; readonly Func<string, IGroup> factory; ConcurrentDictionary<string, IGroup> dictionary = new ConcurrentDictionary<string, IGroup>(); public ImmutableArrayGroupRepository(MessagePackSerializerOptions serializerOptions, IMagicOnionLogger logger) { this.serializerOptions = serializerOptions; this.factory = CreateGroup; this.logger = logger; } public IGroup GetOrAdd(string groupName) { return dictionary.GetOrAdd(groupName, factory); } IGroup CreateGroup(string groupName) { return new ImmutableArrayGroup(groupName, this, serializerOptions, logger); } public bool TryGet(string groupName, [NotNullWhen(true)] out IGroup? group) { return dictionary.TryGetValue(groupName, out group); } public bool TryRemove(string groupName) { return dictionary.TryRemove(groupName, out _); } } public class ImmutableArrayGroup : IGroup { readonly object gate = new object(); readonly IGroupRepository parent; readonly MessagePackSerializerOptions serializerOptions; readonly IMagicOnionLogger logger; ImmutableArray<ServiceContext> members; IInMemoryStorage? inmemoryStorage; public string GroupName { get; } public ImmutableArrayGroup(string groupName, IGroupRepository parent, MessagePackSerializerOptions serializerOptions, IMagicOnionLogger logger) { this.GroupName = groupName; this.parent = parent; this.serializerOptions = serializerOptions; this.logger = logger; this.members = ImmutableArray<ServiceContext>.Empty; } public ValueTask<int> GetMemberCountAsync() { return new ValueTask<int>(members.Length); } public IInMemoryStorage<T> GetInMemoryStorage<T>() where T : class { lock (gate) { if (inmemoryStorage == null) { inmemoryStorage = new DefaultInMemoryStorage<T>(); } else if (!(inmemoryStorage is IInMemoryStorage<T>)) { throw new ArgumentException("already initialized inmemory-storage by another type, inmemory-storage only use single type"); } return (IInMemoryStorage<T>)inmemoryStorage; } } public ValueTask AddAsync(ServiceContext context) { lock (gate) { members = members.Add(context); } return default(ValueTask); } public ValueTask<bool> RemoveAsync(ServiceContext context) { lock (gate) { members = members.Remove(context); if (inmemoryStorage != null) { inmemoryStorage.Remove(context.ContextId); } if (members.Length == 0) { if (parent.TryRemove(GroupName)) { return new ValueTask<bool>(true); } } return new ValueTask<bool>(false); } } // broadcast: [methodId, [argument]] public Task WriteAllAsync<T>(int methodId, T value, bool fireAndForget) { var message = BuildMessage(methodId, value); var source = members; if (fireAndForget) { for (int i = 0; i < source.Length; i++) { source[i].QueueResponseStreamWrite(message); } logger.InvokeHubBroadcast(GroupName, message.Length, source.Length); return TaskEx.CompletedTask; } else { throw new NotSupportedException("The write operation must be called with Fire and Forget option"); } } public Task WriteExceptAsync<T>(int methodId, T value, Guid connectionId, bool fireAndForget) { var message = BuildMessage(methodId, value); var source = members; if (fireAndForget) { var writeCount = 0; for (int i = 0; i < source.Length; i++) { if (source[i].ContextId != connectionId) { source[i].QueueResponseStreamWrite(message); writeCount++; } } logger.InvokeHubBroadcast(GroupName, message.Length, writeCount); return TaskEx.CompletedTask; } else { throw new NotSupportedException("The write operation must be called with Fire and Forget option"); } } public Task WriteExceptAsync<T>(int methodId, T value, Guid[] connectionIds, bool fireAndForget) { var message = BuildMessage(methodId, value); var source = members; if (fireAndForget) { var writeCount = 0; for (int i = 0; i < source.Length; i++) { foreach (var item in connectionIds) { if (source[i].ContextId == item) { goto NEXT; } } source[i].QueueResponseStreamWrite(message); writeCount++; NEXT: continue; } logger.InvokeHubBroadcast(GroupName, message.Length, writeCount); return TaskEx.CompletedTask; } else { throw new NotSupportedException("The write operation must be called with Fire and Forget option"); } } public Task WriteToAsync<T>(int methodId, T value, Guid connectionId, bool fireAndForget) { var message = BuildMessage(methodId, value); var source = members; if (fireAndForget) { var writeCount = 0; for (int i = 0; i < source.Length; i++) { if (source[i].ContextId == connectionId) { source[i].QueueResponseStreamWrite(message); writeCount++; break; } } logger.InvokeHubBroadcast(GroupName, message.Length, writeCount); return TaskEx.CompletedTask; } else { throw new NotSupportedException("The write operation must be called with Fire and Forget option"); } } public Task WriteToAsync<T>(int methodId, T value, Guid[] connectionIds, bool fireAndForget) { var message = BuildMessage(methodId, value); var source = members; if (fireAndForget) { var writeCount = 0; for (int i = 0; i < source.Length; i++) { foreach (var item in connectionIds) { if (source[i].ContextId == item) { source[i].QueueResponseStreamWrite(message); writeCount++; goto NEXT; } } NEXT: continue; } logger.InvokeHubBroadcast(GroupName, message.Length, writeCount); return TaskEx.CompletedTask; } else { throw new NotSupportedException("The write operation must be called with Fire and Forget option"); } } public Task WriteExceptRawAsync(ArraySegment<byte> msg, Guid[] exceptConnectionIds, bool fireAndForget) { // oh, copy is bad but current gRPC interface only accepts byte[]... var message = new byte[msg.Count]; Array.Copy(msg.Array!, msg.Offset, message, 0, message.Length); var source = members; if (fireAndForget) { var writeCount = 0; if (exceptConnectionIds == null) { for (int i = 0; i < source.Length; i++) { source[i].QueueResponseStreamWrite(message); writeCount++; } } else { for (int i = 0; i < source.Length; i++) { foreach (var item in exceptConnectionIds) { if (source[i].ContextId == item) { goto NEXT; } } source[i].QueueResponseStreamWrite(message); writeCount++; NEXT: continue; } } logger.InvokeHubBroadcast(GroupName, message.Length, writeCount); return TaskEx.CompletedTask; } else { throw new NotSupportedException("The write operation must be called with Fire and Forget option"); } } public Task WriteToRawAsync(ArraySegment<byte> msg, Guid[] connectionIds, bool fireAndForget) { // oh, copy is bad but current gRPC interface only accepts byte[]... var message = new byte[msg.Count]; Array.Copy(msg.Array!, msg.Offset, message, 0, message.Length); var source = members; if (fireAndForget) { var writeCount = 0; if (connectionIds != null) { for (int i = 0; i < source.Length; i++) { foreach (var item in connectionIds) { if (source[i].ContextId != item) { goto NEXT; } } source[i].QueueResponseStreamWrite(message); writeCount++; NEXT: continue; } logger.InvokeHubBroadcast(GroupName, message.Length, writeCount); } return TaskEx.CompletedTask; } else { throw new NotSupportedException("The write operation must be called with Fire and Forget option"); } } byte[] BuildMessage<T>(int methodId, T value) { using (var buffer = ArrayPoolBufferWriter.RentThreadStaticWriter()) { var writer = new MessagePackWriter(buffer); writer.WriteArrayHeader(2); writer.WriteInt32(methodId); MessagePackSerializer.Serialize(ref writer, value, serializerOptions); writer.Flush(); return buffer.WrittenSpan.ToArray(); } } } }
//--------------------------------------------------------------------------- // // <copyright file="GradientStop.cs" company="Microsoft"> // Copyright (C) Microsoft Corporation. All rights reserved. // </copyright> // // This file was generated, please do not edit it directly. // // Please see http://wiki/default.aspx/Microsoft.Projects.Avalon/MilCodeGen.html for more information. // //--------------------------------------------------------------------------- using MS.Internal; using MS.Internal.KnownBoxes; using MS.Internal.Collections; using MS.Internal.PresentationCore; using MS.Utility; using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Globalization; using System.Reflection; using System.Runtime.InteropServices; using System.ComponentModel.Design.Serialization; using System.Text; using System.Windows; using System.Windows.Media; using System.Windows.Media.Effects; using System.Windows.Media.Media3D; using System.Windows.Media.Animation; using System.Windows.Media.Composition; using System.Windows.Media.Imaging; using System.Windows.Markup; using System.Windows.Media.Converters; using System.Security; using System.Security.Permissions; using SR=MS.Internal.PresentationCore.SR; using SRID=MS.Internal.PresentationCore.SRID; // These types are aliased to match the unamanaged names used in interop using BOOL = System.UInt32; using WORD = System.UInt16; using Float = System.Single; namespace System.Windows.Media { sealed partial class GradientStop : Animatable, IFormattable { #region Constructors //------------------------------------------------------ // // Constructors // //------------------------------------------------------ #endregion Constructors //------------------------------------------------------ // // Public Methods // //------------------------------------------------------ #region Public Methods /// <summary> /// Shadows inherited Clone() with a strongly typed /// version for convenience. /// </summary> public new GradientStop Clone() { return (GradientStop)base.Clone(); } /// <summary> /// Shadows inherited CloneCurrentValue() with a strongly typed /// version for convenience. /// </summary> public new GradientStop CloneCurrentValue() { return (GradientStop)base.CloneCurrentValue(); } #endregion Public Methods //------------------------------------------------------ // // Public Properties // //------------------------------------------------------ #region Public Properties /// <summary> /// Color - Color. Default value is Colors.Transparent. /// </summary> public Color Color { get { return (Color) GetValue(ColorProperty); } set { SetValueInternal(ColorProperty, value); } } /// <summary> /// Offset - double. Default value is 0.0. /// </summary> public double Offset { get { return (double) GetValue(OffsetProperty); } set { SetValueInternal(OffsetProperty, value); } } #endregion Public Properties //------------------------------------------------------ // // Protected Methods // //------------------------------------------------------ #region Protected Methods /// <summary> /// Implementation of <see cref="System.Windows.Freezable.CreateInstanceCore">Freezable.CreateInstanceCore</see>. /// </summary> /// <returns>The new Freezable.</returns> protected override Freezable CreateInstanceCore() { return new GradientStop(); } #endregion ProtectedMethods //------------------------------------------------------ // // Internal Methods // //------------------------------------------------------ #region Internal Methods #endregion Internal Methods //------------------------------------------------------ // // Internal Properties // //------------------------------------------------------ #region Internal Properties /// <summary> /// Creates a string representation of this object based on the current culture. /// </summary> /// <returns> /// A string representation of this object. /// </returns> public override string ToString() { ReadPreamble(); // Delegate to the internal method which implements all ToString calls. return ConvertToString(null /* format string */, null /* format provider */); } /// <summary> /// Creates a string representation of this object based on the IFormatProvider /// passed in. If the provider is null, the CurrentCulture is used. /// </summary> /// <returns> /// A string representation of this object. /// </returns> public string ToString(IFormatProvider provider) { ReadPreamble(); // Delegate to the internal method which implements all ToString calls. return ConvertToString(null /* format string */, provider); } /// <summary> /// Creates a string representation of this object based on the format string /// and IFormatProvider passed in. /// If the provider is null, the CurrentCulture is used. /// See the documentation for IFormattable for more information. /// </summary> /// <returns> /// A string representation of this object. /// </returns> string IFormattable.ToString(string format, IFormatProvider provider) { ReadPreamble(); // Delegate to the internal method which implements all ToString calls. return ConvertToString(format, provider); } /// <summary> /// Creates a string representation of this object based on the format string /// and IFormatProvider passed in. /// If the provider is null, the CurrentCulture is used. /// See the documentation for IFormattable for more information. /// </summary> /// <returns> /// A string representation of this object. /// </returns> internal string ConvertToString(string format, IFormatProvider provider) { // Helper to get the numeric list separator for a given culture. char separator = MS.Internal.TokenizerHelper.GetNumericListSeparator(provider); return String.Format(provider, "{1:" + format + "}{0}{2:" + format + "}", separator, Color, Offset); } #endregion Internal Properties //------------------------------------------------------ // // Dependency Properties // //------------------------------------------------------ #region Dependency Properties /// <summary> /// The DependencyProperty for the GradientStop.Color property. /// </summary> public static readonly DependencyProperty ColorProperty = RegisterProperty("Color", typeof(Color), typeof(GradientStop), Colors.Transparent, null, null, /* isIndependentlyAnimated = */ false, /* coerceValueCallback */ null); /// <summary> /// The DependencyProperty for the GradientStop.Offset property. /// </summary> public static readonly DependencyProperty OffsetProperty = RegisterProperty("Offset", typeof(double), typeof(GradientStop), 0.0, null, null, /* isIndependentlyAnimated = */ false, /* coerceValueCallback */ null); #endregion Dependency Properties //------------------------------------------------------ // // Internal Fields // //------------------------------------------------------ #region Internal Fields internal static Color s_Color = Colors.Transparent; internal const double c_Offset = 0.0; #endregion Internal Fields } }
namespace my.utils { using System; using System.Collections; using System.Text; using System.Text.RegularExpressions; /// <summary> /// This Class implements the Difference Algorithm published in /// "An O(ND) Difference Algorithm and its Variations" by Eugene Myers /// Algorithmica Vol. 1 No. 2, 1986, p 251. /// /// There are many C, Java, Lisp implementations public available but they all seem to come /// from the same source (diffutils) that is under the (unfree) GNU public License /// and cannot be reused as a sourcecode for a commercial application. /// There are very old C implementations that use other (worse) algorithms. /// Microsoft also published sourcecode of a diff-tool (windiff) that uses some tree data. /// Also, a direct transfer from a C source to C# is not easy because there is a lot of pointer /// arithmetic in the typical C solutions and i need a managed solution. /// These are the reasons why I implemented the original published algorithm from the scratch and /// make it avaliable without the GNU license limitations. /// I do not need a high performance diff tool because it is used only sometimes. /// I will do some performace tweaking when needed. /// /// The algorithm itself is comparing 2 arrays of numbers so when comparing 2 text documents /// each line is converted into a (hash) number. See DiffText(). /// /// Some chages to the original algorithm: /// The original algorithm was described using a recursive approach and comparing zero indexed arrays. /// Extracting sub-arrays and rejoining them is very performance and memory intensive so the same /// (readonly) data arrays are passed arround together with their lower and upper bounds. /// This circumstance makes the LCS and SMS functions more complicate. /// I added some code to the LCS function to get a fast response on sub-arrays that are identical, /// completely deleted or inserted. /// /// The result from a comparisation is stored in 2 arrays that flag for modified (deleted or inserted) /// lines in the 2 data arrays. These bits are then analysed to produce a array of Item objects. /// /// Further possible optimizations: /// (first rule: don't do it; second: don't do it yet) /// The arrays DataA and DataB are passed as parameters, but are never changed after the creation /// so they can be members of the class to avoid the paramter overhead. /// In SMS is a lot of boundary arithmetic in the for-D and for-k loops that can be done by increment /// and decrement of local variables. /// The DownVector and UpVector arrays are alywas created and destroyed each time the SMS gets called. /// It is possible to reuse tehm when transfering them to members of the class. /// See TODO: hints. /// /// diff.cs: A port of the algorythm to C# /// Copyright (c) by Matthias Hertel, http://www.mathertel.de /// This work is licensed under a BSD style license. See http://www.mathertel.de/License.aspx /// /// Changes: /// 2002.09.20 There was a "hang" in some situations. /// Now I undestand a little bit more of the SMS algorithm. /// There have been overlapping boxes; that where analyzed partial differently. /// One return-point is enough. /// A assertion was added in CreateDiffs when in debug-mode, that counts the number of equal (no modified) lines in both arrays. /// They must be identical. /// /// 2003.02.07 Out of bounds error in the Up/Down vector arrays in some situations. /// The two vetors are now accessed using different offsets that are adjusted using the start k-Line. /// A test case is added. /// /// 2006.03.05 Some documentation and a direct Diff entry point. /// /// 2006.03.08 Refactored the API to static methods on the Diff class to make usage simpler. /// 2006.03.10 using the standard Debug class for self-test now. /// compile with: csc /target:exe /out:diffTest.exe /d:DEBUG /d:TRACE /d:SELFTEST Diff.cs /// 2007.01.06 license agreement changed to a BSD style license. /// 2007.06.03 added the Optimize method. /// 2007.09.23 UpVector and DownVector optimization by Jan Stoklasa (). /// 2008.05.31 Adjusted the testing code that failed because of the Optimize method (not a bug in the diff algorithm). /// 2008.10.08 Fixing a test case and adding a new test case. /// </summary> public class Diff { /// <summary>details of one difference.</summary> public struct Item { /// <summary>Start Line number in Data A.</summary> public int StartA; /// <summary>Start Line number in Data B.</summary> public int StartB; /// <summary>Number of changes in Data A.</summary> public int deletedA; /// <summary>Number of changes in Data B.</summary> public int insertedB; } // Item /// <summary> /// Shortest Middle Snake Return Data /// </summary> private struct SMSRD { internal int x, y; // internal int u, v; // 2002.09.20: no need for 2 points } #region self-Test #if (SELFTEST) /// <summary> /// start a self- / box-test for some diff cases and report to the debug output. /// </summary> /// <param name="args">not used</param> /// <returns>always 0</returns> public static int Main(string[] args) { StringBuilder ret = new StringBuilder(); string a, b; System.Diagnostics.ConsoleTraceListener ctl = new System.Diagnostics.ConsoleTraceListener(false); System.Diagnostics.Debug.Listeners.Add(ctl); System.Console.WriteLine("Diff Self Test..."); // test all changes a = "a,b,c,d,e,f,g,h,i,j,k,l".Replace(',', '\n'); b = "0,1,2,3,4,5,6,7,8,9".Replace(',', '\n'); System.Diagnostics.Debug.Assert(TestHelper(Diff.DiffText(a, b, false, false, false)) == "12.10.0.0*", "all-changes test failed."); System.Diagnostics.Debug.WriteLine("all-changes test passed."); // test all same a = "a,b,c,d,e,f,g,h,i,j,k,l".Replace(',', '\n'); b = a; System.Diagnostics.Debug.Assert(TestHelper(Diff.DiffText(a, b, false, false, false)) == "", "all-same test failed."); System.Diagnostics.Debug.WriteLine("all-same test passed."); // test snake a = "a,b,c,d,e,f".Replace(',', '\n'); b = "b,c,d,e,f,x".Replace(',', '\n'); System.Diagnostics.Debug.Assert(TestHelper(Diff.DiffText(a, b, false, false, false)) == "1.0.0.0*0.1.6.5*", "snake test failed."); System.Diagnostics.Debug.WriteLine("snake test passed."); // 2002.09.20 - repro a = "c1,a,c2,b,c,d,e,g,h,i,j,c3,k,l".Replace(',', '\n'); b = "C1,a,C2,b,c,d,e,I1,e,g,h,i,j,C3,k,I2,l".Replace(',', '\n'); System.Diagnostics.Debug.Assert(TestHelper(Diff.DiffText(a, b, false, false, false)) == "1.1.0.0*1.1.2.2*0.2.7.7*1.1.11.13*0.1.13.15*", "repro20020920 test failed."); System.Diagnostics.Debug.WriteLine("repro20020920 test passed."); // 2003.02.07 - repro a = "F".Replace(',', '\n'); b = "0,F,1,2,3,4,5,6,7".Replace(',', '\n'); System.Diagnostics.Debug.Assert(TestHelper(Diff.DiffText(a, b, false, false, false)) == "0.1.0.0*0.7.1.2*", "repro20030207 test failed."); System.Diagnostics.Debug.WriteLine("repro20030207 test passed."); // Muegel - repro a = "HELLO\nWORLD"; b = "\n\nhello\n\n\n\nworld\n"; System.Diagnostics.Debug.Assert(TestHelper(Diff.DiffText(a, b, false, false, false)) == "2.8.0.0*", "repro20030409 test failed."); System.Diagnostics.Debug.WriteLine("repro20030409 test passed."); // test some differences a = "a,b,-,c,d,e,f,f".Replace(',', '\n'); b = "a,b,x,c,e,f".Replace(',', '\n'); System.Diagnostics.Debug.Assert(TestHelper(Diff.DiffText(a, b, false, false, false)) == "1.1.2.2*1.0.4.4*1.0.7.6*", "some-changes test failed."); System.Diagnostics.Debug.WriteLine("some-changes test passed."); // test one change within long chain of repeats a = "a,a,a,a,a,a,a,a,a,a".Replace(',', '\n'); b = "a,a,a,a,-,a,a,a,a,a".Replace(',', '\n'); System.Diagnostics.Debug.Assert(TestHelper(Diff.DiffText(a, b, false, false, false)) == "0.1.4.4*1.0.9.10*", "long chain of repeats test failed."); System.Diagnostics.Debug.WriteLine("End."); System.Diagnostics.Debug.Flush(); return (0); } public static string TestHelper(Item []f) { StringBuilder ret = new StringBuilder(); for (int n = 0; n < f.Length; n++) { ret.Append(f[n].deletedA.ToString() + "." + f[n].insertedB.ToString() + "." + f[n].StartA.ToString() + "." + f[n].StartB.ToString() + "*"); } // Debug.Write(5, "TestHelper", ret.ToString()); return (ret.ToString()); } #endif #endregion /// <summary> /// Find the difference in 2 texts, comparing by textlines. /// </summary> /// <param name="TextA">A-version of the text (usualy the old one)</param> /// <param name="TextB">B-version of the text (usualy the new one)</param> /// <returns>Returns a array of Items that describe the differences.</returns> public Item[] DiffText(string TextA, string TextB) { return (DiffText(TextA, TextB, false, false, false)); } // DiffText /// <summary> /// Find the difference in 2 text documents, comparing by textlines. /// The algorithm itself is comparing 2 arrays of numbers so when comparing 2 text documents /// each line is converted into a (hash) number. This hash-value is computed by storing all /// textlines into a common hashtable so i can find dublicates in there, and generating a /// new number each time a new textline is inserted. /// </summary> /// <param name="TextA">A-version of the text (usualy the old one)</param> /// <param name="TextB">B-version of the text (usualy the new one)</param> /// <param name="trimSpace">When set to true, all leading and trailing whitespace characters are stripped out before the comparation is done.</param> /// <param name="ignoreSpace">When set to true, all whitespace characters are converted to a single space character before the comparation is done.</param> /// <param name="ignoreCase">When set to true, all characters are converted to their lowercase equivivalence before the comparation is done.</param> /// <returns>Returns a array of Items that describe the differences.</returns> public static Item[] DiffText(string TextA, string TextB, bool trimSpace, bool ignoreSpace, bool ignoreCase) { // prepare the input-text and convert to comparable numbers. Hashtable h = new Hashtable(TextA.Length + TextB.Length); // The A-Version of the data (original data) to be compared. DiffData DataA = new DiffData(DiffCodes(TextA, h, trimSpace, ignoreSpace, ignoreCase)); // The B-Version of the data (modified data) to be compared. DiffData DataB = new DiffData(DiffCodes(TextB, h, trimSpace, ignoreSpace, ignoreCase)); h = null; // free up hashtable memory (maybe) int MAX = DataA.Length + DataB.Length + 1; /// vector for the (0,0) to (x,y) search int[] DownVector = new int[2 * MAX + 2]; /// vector for the (u,v) to (N,M) search int[] UpVector = new int[2 * MAX + 2]; LCS(DataA, 0, DataA.Length, DataB, 0, DataB.Length, DownVector, UpVector); Optimize(DataA); Optimize(DataB); return CreateDiffs(DataA, DataB); } // DiffText /// <summary> /// If a sequence of modified lines starts with a line that contains the same content /// as the line that appends the changes, the difference sequence is modified so that the /// appended line and not the starting line is marked as modified. /// This leads to more readable diff sequences when comparing text files. /// </summary> /// <param name="Data">A Diff data buffer containing the identified changes.</param> private static void Optimize(DiffData Data) { int StartPos, EndPos; StartPos = 0; while (StartPos < Data.Length) { while ((StartPos < Data.Length) && (Data.modified[StartPos] == false)) StartPos++; EndPos = StartPos; while ((EndPos < Data.Length) && (Data.modified[EndPos] == true)) EndPos++; if ((EndPos < Data.Length) && (Data.data[StartPos] == Data.data[EndPos])) { Data.modified[StartPos] = false; Data.modified[EndPos] = true; } else { StartPos = EndPos; } // if } // while } // Optimize /// <summary> /// Find the difference in 2 arrays of integers. /// </summary> /// <param name="ArrayA">A-version of the numbers (usualy the old one)</param> /// <param name="ArrayB">B-version of the numbers (usualy the new one)</param> /// <returns>Returns a array of Items that describe the differences.</returns> public static Item[] DiffInt(int[] ArrayA, int[] ArrayB) { // The A-Version of the data (original data) to be compared. DiffData DataA = new DiffData(ArrayA); // The B-Version of the data (modified data) to be compared. DiffData DataB = new DiffData(ArrayB); int MAX = DataA.Length + DataB.Length + 1; /// vector for the (0,0) to (x,y) search int[] DownVector = new int[2 * MAX + 2]; /// vector for the (u,v) to (N,M) search int[] UpVector = new int[2 * MAX + 2]; LCS(DataA, 0, DataA.Length, DataB, 0, DataB.Length, DownVector, UpVector); return CreateDiffs(DataA, DataB); } // Diff /// <summary> /// This function converts all textlines of the text into unique numbers for every unique textline /// so further work can work only with simple numbers. /// </summary> /// <param name="aText">the input text</param> /// <param name="h">This extern initialized hashtable is used for storing all ever used textlines.</param> /// <param name="trimSpace">ignore leading and trailing space characters</param> /// <returns>a array of integers.</returns> private static int[] DiffCodes(string aText, Hashtable h, bool trimSpace, bool ignoreSpace, bool ignoreCase) { // get all codes of the text string[] Lines; int[] Codes; int lastUsedCode = h.Count; object aCode; string s; // strip off all cr, only use lf as textline separator. aText = aText.Replace("\r", ""); Lines = aText.Split('\n'); Codes = new int[Lines.Length]; for (int i = 0; i < Lines.Length; ++i) { s = Lines[i]; if (trimSpace) s = s.Trim(); if (ignoreSpace) { s = Regex.Replace(s, "\\s+", " "); // TODO: optimization: faster blank removal. } if (ignoreCase) s = s.ToLower(); aCode = h[s]; if (aCode == null) { lastUsedCode++; h[s] = lastUsedCode; Codes[i] = lastUsedCode; } else { Codes[i] = (int)aCode; } // if } // for return (Codes); } // DiffCodes /// <summary> /// This is the algorithm to find the Shortest Middle Snake (SMS). /// </summary> /// <param name="DataA">sequence A</param> /// <param name="LowerA">lower bound of the actual range in DataA</param> /// <param name="UpperA">upper bound of the actual range in DataA (exclusive)</param> /// <param name="DataB">sequence B</param> /// <param name="LowerB">lower bound of the actual range in DataB</param> /// <param name="UpperB">upper bound of the actual range in DataB (exclusive)</param> /// <param name="DownVector">a vector for the (0,0) to (x,y) search. Passed as a parameter for speed reasons.</param> /// <param name="UpVector">a vector for the (u,v) to (N,M) search. Passed as a parameter for speed reasons.</param> /// <returns>a MiddleSnakeData record containing x,y and u,v</returns> private static SMSRD SMS(DiffData DataA, int LowerA, int UpperA, DiffData DataB, int LowerB, int UpperB, int[] DownVector, int[] UpVector) { SMSRD ret; int MAX = DataA.Length + DataB.Length + 1; int DownK = LowerA - LowerB; // the k-line to start the forward search int UpK = UpperA - UpperB; // the k-line to start the reverse search int Delta = (UpperA - LowerA) - (UpperB - LowerB); bool oddDelta = (Delta & 1) != 0; // The vectors in the publication accepts negative indexes. the vectors implemented here are 0-based // and are access using a specific offset: UpOffset UpVector and DownOffset for DownVektor int DownOffset = MAX - DownK; int UpOffset = MAX - UpK; int MaxD = ((UpperA - LowerA + UpperB - LowerB) / 2) + 1; // Debug.Write(2, "SMS", String.Format("Search the box: A[{0}-{1}] to B[{2}-{3}]", LowerA, UpperA, LowerB, UpperB)); // init vectors DownVector[DownOffset + DownK + 1] = LowerA; UpVector[UpOffset + UpK - 1] = UpperA; for (int D = 0; D <= MaxD; D++) { // Extend the forward path. for (int k = DownK - D; k <= DownK + D; k += 2) { // Debug.Write(0, "SMS", "extend forward path " + k.ToString()); // find the only or better starting point int x, y; if (k == DownK - D) { x = DownVector[DownOffset + k + 1]; // down } else { x = DownVector[DownOffset + k - 1] + 1; // a step to the right if ((k < DownK + D) && (DownVector[DownOffset + k + 1] >= x)) x = DownVector[DownOffset + k + 1]; // down } y = x - k; // find the end of the furthest reaching forward D-path in diagonal k. while ((x < UpperA) && (y < UpperB) && (DataA.data[x] == DataB.data[y])) { x++; y++; } DownVector[DownOffset + k] = x; // overlap ? if (oddDelta && (UpK - D < k) && (k < UpK + D)) { if (UpVector[UpOffset + k] <= DownVector[DownOffset + k]) { ret.x = DownVector[DownOffset + k]; ret.y = DownVector[DownOffset + k] - k; // ret.u = UpVector[UpOffset + k]; // 2002.09.20: no need for 2 points // ret.v = UpVector[UpOffset + k] - k; return (ret); } // if } // if } // for k // Extend the reverse path. for (int k = UpK - D; k <= UpK + D; k += 2) { // Debug.Write(0, "SMS", "extend reverse path " + k.ToString()); // find the only or better starting point int x, y; if (k == UpK + D) { x = UpVector[UpOffset + k - 1]; // up } else { x = UpVector[UpOffset + k + 1] - 1; // left if ((k > UpK - D) && (UpVector[UpOffset + k - 1] < x)) x = UpVector[UpOffset + k - 1]; // up } // if y = x - k; while ((x > LowerA) && (y > LowerB) && (DataA.data[x - 1] == DataB.data[y - 1])) { x--; y--; // diagonal } UpVector[UpOffset + k] = x; // overlap ? if (!oddDelta && (DownK - D <= k) && (k <= DownK + D)) { if (UpVector[UpOffset + k] <= DownVector[DownOffset + k]) { ret.x = DownVector[DownOffset + k]; ret.y = DownVector[DownOffset + k] - k; // ret.u = UpVector[UpOffset + k]; // 2002.09.20: no need for 2 points // ret.v = UpVector[UpOffset + k] - k; return (ret); } // if } // if } // for k } // for D throw new ApplicationException("the algorithm should never come here."); } // SMS /// <summary> /// This is the divide-and-conquer implementation of the longes common-subsequence (LCS) /// algorithm. /// The published algorithm passes recursively parts of the A and B sequences. /// To avoid copying these arrays the lower and upper bounds are passed while the sequences stay constant. /// </summary> /// <param name="DataA">sequence A</param> /// <param name="LowerA">lower bound of the actual range in DataA</param> /// <param name="UpperA">upper bound of the actual range in DataA (exclusive)</param> /// <param name="DataB">sequence B</param> /// <param name="LowerB">lower bound of the actual range in DataB</param> /// <param name="UpperB">upper bound of the actual range in DataB (exclusive)</param> /// <param name="DownVector">a vector for the (0,0) to (x,y) search. Passed as a parameter for speed reasons.</param> /// <param name="UpVector">a vector for the (u,v) to (N,M) search. Passed as a parameter for speed reasons.</param> private static void LCS(DiffData DataA, int LowerA, int UpperA, DiffData DataB, int LowerB, int UpperB, int[] DownVector, int[] UpVector) { // Debug.Write(2, "LCS", String.Format("Analyse the box: A[{0}-{1}] to B[{2}-{3}]", LowerA, UpperA, LowerB, UpperB)); // Fast walkthrough equal lines at the start while (LowerA < UpperA && LowerB < UpperB && DataA.data[LowerA] == DataB.data[LowerB]) { LowerA++; LowerB++; } // Fast walkthrough equal lines at the end while (LowerA < UpperA && LowerB < UpperB && DataA.data[UpperA - 1] == DataB.data[UpperB - 1]) { --UpperA; --UpperB; } if (LowerA == UpperA) { // mark as inserted lines. while (LowerB < UpperB) DataB.modified[LowerB++] = true; } else if (LowerB == UpperB) { // mark as deleted lines. while (LowerA < UpperA) DataA.modified[LowerA++] = true; } else { // Find the middle snakea and length of an optimal path for A and B SMSRD smsrd = SMS(DataA, LowerA, UpperA, DataB, LowerB, UpperB, DownVector, UpVector); // Debug.Write(2, "MiddleSnakeData", String.Format("{0},{1}", smsrd.x, smsrd.y)); // The path is from LowerX to (x,y) and (x,y) to UpperX LCS(DataA, LowerA, smsrd.x, DataB, LowerB, smsrd.y, DownVector, UpVector); LCS(DataA, smsrd.x, UpperA, DataB, smsrd.y, UpperB, DownVector, UpVector); // 2002.09.20: no need for 2 points } } // LCS() /// <summary>Scan the tables of which lines are inserted and deleted, /// producing an edit script in forward order. /// </summary> /// dynamic array private static Item[] CreateDiffs(DiffData DataA, DiffData DataB) { ArrayList a = new ArrayList(); Item aItem; Item[] result; int StartA, StartB; int LineA, LineB; LineA = 0; LineB = 0; while (LineA < DataA.Length || LineB < DataB.Length) { if ((LineA < DataA.Length) && (!DataA.modified[LineA]) && (LineB < DataB.Length) && (!DataB.modified[LineB])) { // equal lines LineA++; LineB++; } else { // maybe deleted and/or inserted lines StartA = LineA; StartB = LineB; while (LineA < DataA.Length && (LineB >= DataB.Length || DataA.modified[LineA])) // while (LineA < DataA.Length && DataA.modified[LineA]) LineA++; while (LineB < DataB.Length && (LineA >= DataA.Length || DataB.modified[LineB])) // while (LineB < DataB.Length && DataB.modified[LineB]) LineB++; if ((StartA < LineA) || (StartB < LineB)) { // store a new difference-item aItem = new Item(); aItem.StartA = StartA; aItem.StartB = StartB; aItem.deletedA = LineA - StartA; aItem.insertedB = LineB - StartB; a.Add(aItem); } // if } // if } // while result = new Item[a.Count]; a.CopyTo(result); return (result); } } // class Diff /// <summary>Data on one input file being compared. /// </summary> internal class DiffData { /// <summary>Number of elements (lines).</summary> internal int Length; /// <summary>Buffer of numbers that will be compared.</summary> internal int[] data; /// <summary> /// Array of booleans that flag for modified data. /// This is the result of the diff. /// This means deletedA in the first Data or inserted in the second Data. /// </summary> internal bool[] modified; /// <summary> /// Initialize the Diff-Data buffer. /// </summary> /// <param name="data">reference to the buffer</param> internal DiffData(int[] initData) { data = initData; Length = initData.Length; modified = new bool[Length + 2]; } // DiffData } // class DiffData } // namespace
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; namespace Lucene.Net.Search { /// <summary>An alternative to BooleanScorer that also allows a minimum number /// of optional scorers that should match. /// <br>Implements skipTo(), and has no limitations on the numbers of added scorers. /// <br>Uses ConjunctionScorer, DisjunctionScorer, ReqOptScorer and ReqExclScorer. /// </summary> class BooleanScorer2 : Scorer { private class AnonymousClassDisjunctionSumScorer : DisjunctionSumScorer { private void InitBlock(BooleanScorer2 enclosingInstance) { this.enclosingInstance = enclosingInstance; } private BooleanScorer2 enclosingInstance; public BooleanScorer2 Enclosing_Instance { get { return enclosingInstance; } } internal AnonymousClassDisjunctionSumScorer(BooleanScorer2 enclosingInstance, System.Collections.IList Param1, int Param2):base(Param1, Param2) { InitBlock(enclosingInstance); } private int lastScoredDoc = - 1; public override float Score() { if (this.Doc() >= lastScoredDoc) { lastScoredDoc = this.Doc(); Enclosing_Instance.coordinator.nrMatchers += base.nrMatchers; } return base.Score(); } } private class AnonymousClassConjunctionScorer : ConjunctionScorer { private void InitBlock(int requiredNrMatchers, BooleanScorer2 enclosingInstance) { this.requiredNrMatchers = requiredNrMatchers; this.enclosingInstance = enclosingInstance; } private int requiredNrMatchers; private BooleanScorer2 enclosingInstance; public BooleanScorer2 Enclosing_Instance { get { return enclosingInstance; } } internal AnonymousClassConjunctionScorer(int requiredNrMatchers, BooleanScorer2 enclosingInstance, Lucene.Net.Search.Similarity Param1, System.Collections.ICollection scorers) : base(Param1, scorers) { InitBlock(requiredNrMatchers, enclosingInstance); } private int lastScoredDoc = - 1; public override float Score() { if (this.Doc() >= lastScoredDoc) { lastScoredDoc = this.Doc(); Enclosing_Instance.coordinator.nrMatchers += requiredNrMatchers; } // All scorers match, so defaultSimilarity super.score() always has 1 as // the coordination factor. // Therefore the sum of the scores of the requiredScorers // is used as score. return base.Score(); } } private System.Collections.ArrayList requiredScorers = new System.Collections.ArrayList(); private System.Collections.ArrayList optionalScorers = new System.Collections.ArrayList(); private System.Collections.ArrayList prohibitedScorers = new System.Collections.ArrayList(); private class Coordinator { public Coordinator(BooleanScorer2 enclosingInstance) { InitBlock(enclosingInstance); } private void InitBlock(BooleanScorer2 enclosingInstance) { this.enclosingInstance = enclosingInstance; } private BooleanScorer2 enclosingInstance; public BooleanScorer2 Enclosing_Instance { get { return enclosingInstance; } } internal int maxCoord = 0; // to be increased for each non prohibited scorer private float[] coordFactors = null; internal virtual void Init() { // use after all scorers have been added. coordFactors = new float[maxCoord + 1]; Similarity sim = Enclosing_Instance.GetSimilarity(); for (int i = 0; i <= maxCoord; i++) { coordFactors[i] = sim.Coord(i, maxCoord); } } internal int nrMatchers; // to be increased by score() of match counting scorers. internal virtual void InitDoc() { nrMatchers = 0; } internal virtual float CoordFactor() { return coordFactors[nrMatchers]; } } private Coordinator coordinator; /// <summary>The scorer to which all scoring will be delegated, /// except for computing and using the coordination factor. /// </summary> private Scorer countingSumScorer = null; /// <summary>The number of optionalScorers that need to match (if there are any) </summary> private int minNrShouldMatch; /// <summary>Whether it is allowed to return documents out of order. /// This can accelerate the scoring of disjunction queries. /// </summary> private bool allowDocsOutOfOrder; /// <summary>Create a BooleanScorer2.</summary> /// <param name="similarity">The similarity to be used. /// </param> /// <param name="minNrShouldMatch">The minimum number of optional added scorers /// that should match during the search. /// In case no required scorers are added, /// at least one of the optional scorers will have to /// match during the search. /// </param> /// <param name="allowDocsOutOfOrder">Whether it is allowed to return documents out of order. /// This can accelerate the scoring of disjunction queries. /// </param> public BooleanScorer2(Similarity similarity, int minNrShouldMatch, bool allowDocsOutOfOrder) : base(similarity) { if (minNrShouldMatch < 0) { throw new System.ArgumentException("Minimum number of optional scorers should not be negative"); } coordinator = new Coordinator(this); this.minNrShouldMatch = minNrShouldMatch; this.allowDocsOutOfOrder = allowDocsOutOfOrder; } /// <summary>Create a BooleanScorer2. /// In no required scorers are added, /// at least one of the optional scorers will have to match during the search. /// </summary> /// <param name="similarity">The similarity to be used. /// </param> /// <param name="minNrShouldMatch">The minimum number of optional added scorers /// that should match during the search. /// In case no required scorers are added, /// at least one of the optional scorers will have to /// match during the search. /// </param> public BooleanScorer2(Similarity similarity, int minNrShouldMatch) : this(similarity, minNrShouldMatch, false) { } /// <summary>Create a BooleanScorer2. /// In no required scorers are added, /// at least one of the optional scorers will have to match during the search. /// </summary> /// <param name="similarity">The similarity to be used. /// </param> public BooleanScorer2(Similarity similarity):this(similarity, 0, false) { } public virtual void Add(Scorer scorer, bool required, bool prohibited) { if (!prohibited) { coordinator.maxCoord++; } if (required) { if (prohibited) { throw new System.ArgumentException("scorer cannot be required and prohibited"); } requiredScorers.Add(scorer); } else if (prohibited) { prohibitedScorers.Add(scorer); } else { optionalScorers.Add(scorer); } } /// <summary>Initialize the match counting scorer that sums all the /// scores. <p> /// When "counting" is used in a name it means counting the number /// of matching scorers.<br> /// When "sum" is used in a name it means score value summing /// over the matching scorers /// </summary> private void InitCountingSumScorer() { coordinator.Init(); countingSumScorer = MakeCountingSumScorer(); } /// <summary>Count a scorer as a single match. </summary> private class SingleMatchScorer : Scorer { private void InitBlock(BooleanScorer2 enclosingInstance) { this.enclosingInstance = enclosingInstance; } private BooleanScorer2 enclosingInstance; public BooleanScorer2 Enclosing_Instance { get { return enclosingInstance; } } private Scorer scorer; private int lastScoredDoc = - 1; internal SingleMatchScorer(BooleanScorer2 enclosingInstance, Scorer scorer) : base(scorer.GetSimilarity()) { InitBlock(enclosingInstance); this.scorer = scorer; } public override float Score() { if (this.Doc() >= lastScoredDoc) { lastScoredDoc = this.Doc(); Enclosing_Instance.coordinator.nrMatchers++; } return scorer.Score(); } public override int Doc() { return scorer.Doc(); } public override bool Next() { return scorer.Next(); } public override bool SkipTo(int docNr) { return scorer.SkipTo(docNr); } public override Explanation Explain(int docNr) { return scorer.Explain(docNr); } } private Scorer countingDisjunctionSumScorer(System.Collections.IList scorers, int minMrShouldMatch) // each scorer from the list counted as a single matcher { return new AnonymousClassDisjunctionSumScorer(this, scorers, minMrShouldMatch); } private static Similarity defaultSimilarity = new DefaultSimilarity(); private Scorer CountingConjunctionSumScorer(System.Collections.IList requiredScorers) { // each scorer from the list counted as a single matcher int requiredNrMatchers = requiredScorers.Count; return new AnonymousClassConjunctionScorer(requiredNrMatchers, this, defaultSimilarity, requiredScorers); } private Scorer DualConjunctionSumScorer(Scorer req1, Scorer req2) { // non counting. return new ConjunctionScorer(defaultSimilarity, new Scorer[]{req1, req2}); // All scorers match, so defaultSimilarity always has 1 as // the coordination factor. // Therefore the sum of the scores of two scorers // is used as score. } /// <summary>Returns the scorer to be used for match counting and score summing. /// Uses requiredScorers, optionalScorers and prohibitedScorers. /// </summary> private Scorer MakeCountingSumScorer() { // each scorer counted as a single matcher return (requiredScorers.Count == 0) ? MakeCountingSumScorerNoReq() : MakeCountingSumScorerSomeReq(); } private Scorer MakeCountingSumScorerNoReq() { // No required scorers if (optionalScorers.Count == 0) { return new NonMatchingScorer(); // no clauses or only prohibited clauses } else { // No required scorers. At least one optional scorer. // minNrShouldMatch optional scorers are required, but at least 1 int nrOptRequired = (minNrShouldMatch < 1) ? 1 : minNrShouldMatch; if (optionalScorers.Count < nrOptRequired) { return new NonMatchingScorer(); // fewer optional clauses than minimum (at least 1) that should match } else { // optionalScorers.size() >= nrOptRequired, no required scorers Scorer requiredCountingSumScorer = (optionalScorers.Count > nrOptRequired) ? countingDisjunctionSumScorer(optionalScorers, nrOptRequired) : ((optionalScorers.Count == 1) ? new SingleMatchScorer(this, (Scorer) optionalScorers[0]) : CountingConjunctionSumScorer(optionalScorers)); return AddProhibitedScorers(requiredCountingSumScorer); } } } private Scorer MakeCountingSumScorerSomeReq() { // At least one required scorer. if (optionalScorers.Count < minNrShouldMatch) { return new NonMatchingScorer(); // fewer optional clauses than minimum that should match } else if (optionalScorers.Count == minNrShouldMatch) { // all optional scorers also required. System.Collections.ArrayList allReq = new System.Collections.ArrayList(requiredScorers); allReq.AddRange(optionalScorers); return AddProhibitedScorers(CountingConjunctionSumScorer(allReq)); } else { // optionalScorers.size() > minNrShouldMatch, and at least one required scorer Scorer requiredCountingSumScorer = (requiredScorers.Count == 1) ? new SingleMatchScorer(this, (Scorer) requiredScorers[0]) : CountingConjunctionSumScorer(requiredScorers); if (minNrShouldMatch > 0) { // use a required disjunction scorer over the optional scorers return AddProhibitedScorers(DualConjunctionSumScorer(requiredCountingSumScorer, countingDisjunctionSumScorer(optionalScorers, minNrShouldMatch))); } else { // minNrShouldMatch == 0 return new ReqOptSumScorer(AddProhibitedScorers(requiredCountingSumScorer), ((optionalScorers.Count == 1) ? new SingleMatchScorer(this, (Scorer) optionalScorers[0]):countingDisjunctionSumScorer(optionalScorers, 1))); // require 1 in combined, optional scorer. } } } /// <summary>Returns the scorer to be used for match counting and score summing. /// Uses the given required scorer and the prohibitedScorers. /// </summary> /// <param name="requiredCountingSumScorer">A required scorer already built. /// </param> private Scorer AddProhibitedScorers(Scorer requiredCountingSumScorer) { return (prohibitedScorers.Count == 0) ? requiredCountingSumScorer : new ReqExclScorer(requiredCountingSumScorer, ((prohibitedScorers.Count == 1) ? (Scorer) prohibitedScorers[0] : new DisjunctionSumScorer(prohibitedScorers))); } /// <summary>Scores and collects all matching documents.</summary> /// <param name="hc">The collector to which all matching documents are passed through /// {@link HitCollector#Collect(int, float)}. /// <br>When this method is used the {@link #Explain(int)} method should not be used. /// </param> public override void Score(HitCollector hc) { if (allowDocsOutOfOrder && requiredScorers.Count == 0 && prohibitedScorers.Count < 32) { // fall back to BooleanScorer, scores documents somewhat out of order BooleanScorer bs = new BooleanScorer(GetSimilarity(), minNrShouldMatch); System.Collections.IEnumerator si = optionalScorers.GetEnumerator(); while (si.MoveNext()) { bs.Add((Scorer) si.Current, false, false); } si = prohibitedScorers.GetEnumerator(); while (si.MoveNext()) { bs.Add((Scorer) si.Current, false, true); } bs.Score(hc); } else { if (countingSumScorer == null) { InitCountingSumScorer(); } while (countingSumScorer.Next()) { hc.Collect(countingSumScorer.Doc(), Score()); } } } /// <summary>Expert: Collects matching documents in a range. /// <br>Note that {@link #Next()} must be called once before this method is /// called for the first time. /// </summary> /// <param name="hc">The collector to which all matching documents are passed through /// {@link HitCollector#Collect(int, float)}. /// </param> /// <param name="max">Do not score documents past this. /// </param> /// <returns> true if more matching documents may remain. /// </returns> protected internal override bool Score(HitCollector hc, int max) { // null pointer exception when next() was not called before: int docNr = countingSumScorer.Doc(); while (docNr < max) { hc.Collect(docNr, Score()); if (!countingSumScorer.Next()) { return false; } docNr = countingSumScorer.Doc(); } return true; } public override int Doc() { return countingSumScorer.Doc(); } public override bool Next() { if (countingSumScorer == null) { InitCountingSumScorer(); } return countingSumScorer.Next(); } public override float Score() { coordinator.InitDoc(); float sum = countingSumScorer.Score(); return sum * coordinator.CoordFactor(); } /// <summary>Skips to the first match beyond the current whose document number is /// greater than or equal to a given target. /// /// <p>When this method is used the {@link #Explain(int)} method should not be used. /// /// </summary> /// <param name="target">The target document number. /// </param> /// <returns> true iff there is such a match. /// </returns> public override bool SkipTo(int target) { if (countingSumScorer == null) { InitCountingSumScorer(); } return countingSumScorer.SkipTo(target); } /// <summary>Throws an UnsupportedOperationException. /// TODO: Implement an explanation of the coordination factor. /// </summary> /// <param name="doc">The document number for the explanation. /// </param> /// <throws> UnsupportedOperationException </throws> public override Explanation Explain(int doc) { throw new System.NotSupportedException(); /* How to explain the coordination factor? initCountingSumScorer(); return countingSumScorer.explain(doc); // misses coord factor. */ } } }
using System; using System.IO; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Terraria; using Terraria.ID; using Terraria.ModLoader; namespace ExampleMod.NPCs.Abomination { //ported from my tAPI mod because I'm lazy public class Abomination : ModNPC { private static int hellLayer { get { return Main.maxTilesY - 200; } } private const int sphereRadius = 300; private float attackCool { get { return npc.ai[0]; } set { npc.ai[0] = value; } } private float moveCool { get { return npc.ai[1]; } set { npc.ai[1] = value; } } private float rotationSpeed { get { return npc.ai[2]; } set { npc.ai[2] = value; } } private float captiveRotation { get { return npc.ai[3]; } set { npc.ai[3] = value; } } private int moveTime = 300; private int moveTimer = 60; internal int laserTimer = 0; internal int laser1 = -1; internal int laser2 = -1; private bool dontDamage = false; public override void SetDefaults() { npc.name = "Abomination"; npc.displayName = "The Abomination"; npc.aiStyle = -1; npc.lifeMax = 40000; npc.damage = 100; npc.defense = 55; npc.knockBackResist = 0f; npc.width = 100; npc.height = 100; Main.npcFrameCount[npc.type] = 2; npc.value = Item.buyPrice(0, 20, 0, 0); npc.npcSlots = 15f; npc.boss = true; npc.lavaImmune = true; npc.noGravity = true; npc.noTileCollide = true; npc.HitSound = SoundID.NPCHit1; npc.DeathSound = SoundID.NPCDeath1; npc.buffImmune[24] = true; music = MusicID.Boss2; } public override void ScaleExpertStats(int numPlayers, float bossLifeScale) { npc.lifeMax = (int)(npc.lifeMax * 0.625f * bossLifeScale); npc.damage = (int)(npc.damage * 0.6f); } public override void AI() { if (Main.netMode != 1 && npc.localAI[0] == 0f) { for (int k = 0; k < 5; k++) { int captive = NPC.NewNPC((int)npc.position.X, (int)npc.position.Y, mod.NPCType("CaptiveElement")); Main.npc[captive].ai[0] = npc.whoAmI; Main.npc[captive].ai[1] = k; Main.npc[captive].ai[2] = 50 * (k + 1); if (k == 2) { Main.npc[captive].damage += 20; } CaptiveElement.SetPosition(Main.npc[captive]); Main.npc[captive].netUpdate = true; } npc.netUpdate = true; npc.localAI[0] = 1f; } Player player = Main.player[npc.target]; if (!player.active || player.dead || player.position.Y < hellLayer * 16) { npc.TargetClosest(false); player = Main.player[npc.target]; if (!player.active || player.dead || player.position.Y < hellLayer * 16) { npc.velocity = new Vector2(0f, 10f); if (npc.timeLeft > 10) { npc.timeLeft = 10; } return; } } moveCool -= 1f; if (Main.netMode != 1 && moveCool <= 0f) { npc.TargetClosest(false); player = Main.player[npc.target]; double angle = Main.rand.NextDouble() * 2.0 * Math.PI; int distance = sphereRadius + Main.rand.Next(200); Vector2 moveTo = player.Center + (float)distance * new Vector2((float)Math.Cos(angle), (float)Math.Sin(angle)); moveCool = (float)moveTime + (float)Main.rand.Next(100); npc.velocity = (moveTo - npc.Center) / moveCool; rotationSpeed = (float)(Main.rand.NextDouble() + Main.rand.NextDouble()); if (rotationSpeed > 1f) { rotationSpeed = 1f + (rotationSpeed - 1f) / 2f; } if (Main.rand.Next(2) == 0) { rotationSpeed *= -1; } rotationSpeed *= 0.01f; npc.netUpdate = true; } if (Vector2.Distance(Main.player[npc.target].position, npc.position) > sphereRadius) { moveTimer--; } else { moveTimer += 3; if (moveTime >= 300 && moveTimer > 60) { moveTimer = 60; } } if (moveTimer <= 0) { moveTimer += 60; moveTime -= 3; if (moveTime < 99) { moveTime = 99; moveTimer = 0; } npc.netUpdate = true; } else if (moveTimer > 60) { moveTimer -= 60; moveTime += 3; npc.netUpdate = true; } captiveRotation += rotationSpeed; if (captiveRotation < 0f) { captiveRotation += 2f * (float)Math.PI; } if (captiveRotation >= 2f * (float)Math.PI) { captiveRotation -= 2f * (float)Math.PI; } attackCool -= 1f; if (Main.netMode != 1 && attackCool <= 0f) { attackCool = 200f + 200f * (float)npc.life / (float)npc.lifeMax + (float)Main.rand.Next(200); Vector2 delta = player.Center - npc.Center; float magnitude = (float)Math.Sqrt(delta.X * delta.X + delta.Y * delta.Y); if (magnitude > 0) { delta *= 5f / magnitude; } else { delta = new Vector2(0f, 5f); } int damage = (npc.damage - 30) / 2; if (Main.expertMode) { damage = (int)(damage / Main.expertDamage); } Projectile.NewProjectile(npc.Center.X, npc.Center.Y, delta.X, delta.Y, mod.ProjectileType("ElementBall"), damage, 3f, Main.myPlayer, BuffID.OnFire, 600f); npc.netUpdate = true; } if (Main.expertMode) { ExpertLaser(); } if (Main.rand.Next(2) == 0) { float radius = (float)Math.Sqrt(Main.rand.Next(sphereRadius * sphereRadius)); double angle = Main.rand.NextDouble() * 2.0 * Math.PI; Dust.NewDust(new Vector2(npc.Center.X + radius * (float)Math.Cos(angle), npc.Center.Y + radius * (float)Math.Sin(angle)), 0, 0, mod.DustType("Sparkle"), 0f, 0f, 0, default(Color), 1.5f); } } private void ExpertLaser() { laserTimer--; if (laserTimer <= 0 && Main.netMode != 1) { if (npc.localAI[0] == 2f) { int laser1Index; int laser2Index; if (laser1 < 0) { laser1Index = npc.whoAmI; } else { for (laser1Index = 0; laser1Index < 200; laser1Index++) { if (Main.npc[laser1Index].type == mod.NPCType("CaptiveElement") && laser1 == Main.npc[laser1Index].ai[1]) { break; } } } if (laser2 < 0) { laser2Index = npc.whoAmI; } else { for (laser2Index = 0; laser2Index < 200; laser2Index++) { if (Main.npc[laser2Index].type == mod.NPCType("CaptiveElement") && laser2 == Main.npc[laser2Index].ai[1]) { break; } } } Vector2 pos = Main.npc[laser1Index].Center; int damage = Main.npc[laser1Index].damage / 2; if (Main.expertMode) { damage = (int)(damage / Main.expertDamage); } Projectile.NewProjectile(pos.X, pos.Y, 0f, 0f, mod.ProjectileType("ElementLaser"), damage, 0f, Main.myPlayer, laser1Index, laser2Index); } else { npc.localAI[0] = 2f; } laserTimer = 500 + Main.rand.Next(100); laserTimer = 60 + laserTimer * npc.life / npc.lifeMax; laser1 = Main.rand.Next(6) - 1; laser2 = Main.rand.Next(5) - 1; if (laser2 >= laser1) { laser2++; } } } public override void SendExtraAI(BinaryWriter writer) { writer.Write((short)moveTime); writer.Write((short)moveTimer); if (Main.expertMode) { writer.Write((short)laserTimer); writer.Write((byte)(laser1 + 1)); writer.Write((byte)(laser2 + 1)); } } public override void ReceiveExtraAI(BinaryReader reader) { moveTime = reader.ReadInt16(); moveTimer = reader.ReadInt16(); if (Main.expertMode) { laserTimer = reader.ReadInt16(); laser1 = reader.ReadByte() - 1; laser2 = reader.ReadByte() - 1; } } public override void FindFrame(int frameHeight) { if (attackCool < 50f) { npc.frame.Y = frameHeight; } else { npc.frame.Y = 0; } } public override void HitEffect(int hitDirection, double damage) { for (int k = 0; k < damage / npc.lifeMax * 100.0; k++) { Dust.NewDust(npc.position, npc.width, npc.height, 5, hitDirection, -1f, 0, default(Color), 1f); } if (Main.netMode != 1 && npc.life <= 0) { Vector2 spawnAt = npc.Center + new Vector2(0f, (float)npc.height / 2f); NPC.NewNPC((int)spawnAt.X, (int)spawnAt.Y, mod.NPCType("AbominationRun")); } } public override bool PreNPCLoot() { return false; } public override void OnHitPlayer(Player player, int damage, bool crit) { if (Main.expertMode || Main.rand.Next(2) == 0) { player.AddBuff(BuffID.OnFire, 600, true); } } public override void ModifyHitByItem(Player player, Item item, ref int damage, ref float knockback, ref bool crit) { dontDamage = (player.Center - npc.Center).Length() > sphereRadius; } public override void ModifyHitByProjectile(Projectile projectile, ref int damage, ref float knockback, ref bool crit, ref int hitDirection) { Player player = Main.player[projectile.owner]; dontDamage = player.active && (player.Center - npc.Center).Length() > sphereRadius; } public override bool StrikeNPC(ref double damage, int defense, ref float knockback, int hitDirection, ref bool crit) { if (dontDamage) { damage = 0; crit = true; dontDamage = false; Main.PlaySound(npc.HitSound, npc.position); return false; } return true; } public override bool PreDraw(SpriteBatch spriteBatch, Color drawColor) { spriteBatch.Draw(mod.GetTexture("NPCs/Abomination/HolySphere"), npc.Center - Main.screenPosition, null, Color.White * (70f / 255f), 0f, new Vector2(sphereRadius, sphereRadius), 1f, SpriteEffects.None, 0f); spriteBatch.Draw(mod.GetTexture("NPCs/Abomination/HolySphereBorder"), npc.Center - Main.screenPosition, null, Color.White * 0.5f, 0f, new Vector2(sphereRadius, sphereRadius), 1f, SpriteEffects.None, 0f); if (Main.expertMode && laserTimer <= 60 && (laser1 == -1 || laser2 == -1)) { float rotation = laserTimer / 30f; if (laser1 == -1) { rotation *= -1f; } spriteBatch.Draw(mod.GetTexture("NPCs/Abomination/Rune"), npc.Center - Main.screenPosition, null, new Color(255, 10, 0), rotation, new Vector2(64, 64), 1f, SpriteEffects.None, 0f); } return true; } public override bool? DrawHealthBar(byte hbPosition, ref float scale, ref Vector2 position) { scale = 1.5f; return null; } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Text.RegularExpressions; using StructureMap; using LibGit2Sharp; using Branch = LibGit2Sharp.Branch; namespace Sep.Git.Tfs.Core { public class GitRepository : GitHelpers, IGitRepository { private readonly IContainer _container; private readonly Globals _globals; private IDictionary<string, IGitTfsRemote> _cachedRemotes; private Repository _repository; private RemoteConfigConverter _remoteConfigReader; public GitRepository(TextWriter stdout, string gitDir, IContainer container, Globals globals, RemoteConfigConverter remoteConfigReader) : base(stdout, container) { _container = container; _globals = globals; GitDir = gitDir; _repository = new LibGit2Sharp.Repository(GitDir); _remoteConfigReader = remoteConfigReader; } ~GitRepository() { if (_repository != null) _repository.Dispose(); } public GitCommit Commit(LogEntry logEntry) { var parents = logEntry.CommitParents.Select(sha => _repository.Lookup<Commit>(sha)); var commit = _repository.ObjectDatabase.CreateCommit( new Signature(logEntry.AuthorName, logEntry.AuthorEmail, logEntry.Date.ToUniversalTime()), new Signature(logEntry.CommitterName, logEntry.CommitterEmail, logEntry.Date.ToUniversalTime()), logEntry.Log, logEntry.Tree, parents, false); changesetsCache[logEntry.ChangesetId] = commit.Sha; return new GitCommit(commit); } public void UpdateRef(string gitRefName, string shaCommit, string message = null) { if (message == null) _repository.Refs.Add(gitRefName, shaCommit, allowOverwrite: true); else _repository.Refs.Add(gitRefName, shaCommit, _repository.Config.BuildSignature(DateTime.Now), message, true); } public static string ShortToLocalName(string branchName) { return "refs/heads/" + branchName; } public static string ShortToTfsRemoteName(string branchName) { return "refs/remotes/tfs/" + branchName; } public string GitDir { get; set; } public string WorkingCopyPath { get; set; } public string WorkingCopySubdir { get; set; } protected override GitProcess Start(string[] command, Action<ProcessStartInfo> initialize) { return base.Start(command, initialize.And(SetUpPaths)); } private void SetUpPaths(ProcessStartInfo gitCommand) { if (GitDir != null) gitCommand.EnvironmentVariables["GIT_DIR"] = GitDir; if (WorkingCopyPath != null) gitCommand.WorkingDirectory = WorkingCopyPath; if (WorkingCopySubdir != null) gitCommand.WorkingDirectory = Path.Combine(gitCommand.WorkingDirectory, WorkingCopySubdir); } public string GetConfig(string key) { var entry = _repository.Config.Get<string>(key); return entry == null ? null : entry.Value; } public T GetConfig<T>(string key) { return GetConfig(key, default(T)); } public T GetConfig<T>(string key, T defaultValue) { try { var entry = _repository.Config.Get<T>(key); if (entry == null) return defaultValue; return entry.Value; } catch (Exception) { return defaultValue; } } public void SetConfig(string key, string value) { _repository.Config.Set<string>(key, value, ConfigurationLevel.Local); } public IEnumerable<IGitTfsRemote> ReadAllTfsRemotes() { var remotes = GetTfsRemotes().Values; foreach (var remote in remotes) remote.EnsureTfsAuthenticated(); return remotes; } public IGitTfsRemote ReadTfsRemote(string remoteId) { if (!HasRemote(remoteId)) throw new GitTfsException("Unable to locate git-tfs remote with id = " + remoteId) .WithRecommendation("Try using `git tfs bootstrap` to auto-init TFS remotes."); var remote = GetTfsRemotes()[remoteId]; remote.EnsureTfsAuthenticated(); return remote; } private IGitTfsRemote ReadTfsRemote(string tfsUrl, string tfsRepositoryPath) { var allRemotes = GetTfsRemotes(); var matchingRemotes = allRemotes.Values.Where( remote => remote.MatchesUrlAndRepositoryPath(tfsUrl, tfsRepositoryPath)); switch (matchingRemotes.Count()) { case 0: return new DerivedGitTfsRemote(tfsUrl, tfsRepositoryPath); case 1: var remote = matchingRemotes.First(); return remote; default: Trace.WriteLine("More than one remote matched!"); goto case 1; } } public IEnumerable<string> GetGitRemoteBranches(string gitRemote) { gitRemote = gitRemote + "/"; var references = _repository.Branches.Where(b => b.IsRemote && b.Name.StartsWith(gitRemote) && !b.Name.EndsWith("/HEAD")); return references.Select(r => r.Name); } private IDictionary<string, IGitTfsRemote> GetTfsRemotes() { return _cachedRemotes ?? (_cachedRemotes = ReadTfsRemotes()); } public IGitTfsRemote CreateTfsRemote(RemoteInfo remote, string autocrlf = null, string ignorecase = null) { if (HasRemote(remote.Id)) throw new GitTfsException("A remote with id \"" + remote.Id + "\" already exists."); // The autocrlf default (as indicated by a null) is false and is set to override the system-wide setting. // When creating branches we use the empty string to indicate that we do not want to set the value at all. if (autocrlf == null) autocrlf = "false"; if (autocrlf != String.Empty) _repository.Config.Set("core.autocrlf", autocrlf); if (ignorecase != null) _repository.Config.Set("core.ignorecase", ignorecase); foreach (var entry in _remoteConfigReader.Dump(remote)) { if (entry.Value != null) { _repository.Config.Set(entry.Key, entry.Value); } else { _repository.Config.Unset(entry.Key); } } var gitTfsRemote = BuildRemote(remote); gitTfsRemote.EnsureTfsAuthenticated(); return _cachedRemotes[remote.Id] = gitTfsRemote; } public void DeleteTfsRemote(IGitTfsRemote remote) { if (remote == null) throw new GitTfsException("error: the name of the remote to delete is invalid!"); UnsetTfsRemoteConfig(remote.Id); _repository.Refs.Remove(remote.RemoteRef); } private void UnsetTfsRemoteConfig(string remoteId) { foreach (var entry in _remoteConfigReader.Delete(remoteId)) { _repository.Config.Unset(entry.Key); } _cachedRemotes = null; } public void MoveRemote(string oldRemoteName, string newRemoteName) { if (!Reference.IsValidName(ShortToLocalName(oldRemoteName))) throw new GitTfsException("error: the name of the remote to move is invalid!"); if (!Reference.IsValidName(ShortToLocalName(newRemoteName))) throw new GitTfsException("error: the new name of the remote is invalid!"); if (HasRemote(newRemoteName)) throw new GitTfsException(string.Format("error: this remote name \"{0}\" is already used!", newRemoteName)); var oldRemote = ReadTfsRemote(oldRemoteName); if(oldRemote == null) throw new GitTfsException(string.Format("error: the remote \"{0}\" doesn't exist!", oldRemoteName)); var remoteInfo = oldRemote.RemoteInfo; remoteInfo.Id = newRemoteName; CreateTfsRemote(remoteInfo); var newRemote = ReadTfsRemote(newRemoteName); _repository.Refs.Rename(oldRemote.RemoteRef, newRemote.RemoteRef); UnsetTfsRemoteConfig(oldRemoteName); } public Branch RenameBranch(string oldName, string newName) { var branch = _repository.Branches[oldName]; if (branch == null) return null; return _repository.Branches.Rename(branch, newName); } private IDictionary<string, IGitTfsRemote> ReadTfsRemotes() { // does this need to ensuretfsauthenticated? _repository.Config.Set("tfs.touch", "1"); // reload configuration, because `git tfs init` and `git tfs clone` use Process.Start to update the config, so _repository's copy is out of date. return _remoteConfigReader.Load(_repository.Config).Select(x => BuildRemote(x)).ToDictionary(x => x.Id); } private IGitTfsRemote BuildRemote(RemoteInfo remoteInfo) { return _container.With(remoteInfo).With<IGitRepository>(this).GetInstance<IGitTfsRemote>(); } public bool HasRemote(string remoteId) { return GetTfsRemotes().ContainsKey(remoteId); } public bool HasRef(string gitRef) { return _repository.Refs[gitRef] != null; } public void MoveTfsRefForwardIfNeeded(IGitTfsRemote remote) { MoveTfsRefForwardIfNeeded(remote, "HEAD"); } public void MoveTfsRefForwardIfNeeded(IGitTfsRemote remote, string @ref) { int currentMaxChangesetId = remote.MaxChangesetId; var untrackedTfsChangesets = from cs in GetLastParentTfsCommits(@ref) where cs.Remote.Id == remote.Id && cs.ChangesetId > currentMaxChangesetId orderby cs.ChangesetId select cs; foreach (var cs in untrackedTfsChangesets) { // UpdateTfsHead sets tag with TFS changeset id on each commit so we can't just update to latest remote.UpdateTfsHead(cs.GitCommit, cs.ChangesetId); } } public GitCommit GetCommit(string commitish) { return new GitCommit(_repository.Lookup<Commit>(commitish)); } public MergeResult Merge(string commitish) { var commit = _repository.Lookup<Commit>(commitish); if(commit == null) throw new GitTfsException("error: commit '"+ commitish + "' can't be found and merged into!"); return _repository.Merge(commit, _repository.Config.BuildSignature(new DateTimeOffset(DateTime.Now))); } public String GetCurrentCommit() { return _repository.Head.Commits.First().Sha; } public IEnumerable<TfsChangesetInfo> GetLastParentTfsCommits(string head) { var changesets = new List<TfsChangesetInfo>(); var commit = _repository.Lookup<Commit>(head); if (commit == null) return changesets; FindTfsParentCommits(changesets, commit); return changesets; } private void FindTfsParentCommits(List<TfsChangesetInfo> changesets, Commit commit) { var commitsToFollow = new Stack<Commit>(); commitsToFollow.Push(commit); var alreadyVisitedCommits = new HashSet<string>(); while (commitsToFollow.Any()) { commit = commitsToFollow.Pop(); alreadyVisitedCommits.Add(commit.Sha); var changesetInfo = TryParseChangesetInfo(commit.Message, commit.Sha); if (changesetInfo == null) { // If commit was not a TFS commit, continue searching all new parents of the commit // Add parents in reverse order to keep topology (main parent should be treated first!) foreach (var parent in commit.Parents.Where(x => !alreadyVisitedCommits.Contains(x.Sha)).Reverse()) commitsToFollow.Push(parent); } else { changesets.Add(changesetInfo); } } Trace.WriteLine("Commits visited count:" + alreadyVisitedCommits.Count); } public TfsChangesetInfo GetTfsChangesetById(string remoteRef, int changesetId) { var commit = FindCommitByChangesetId(changesetId, remoteRef); if (commit == null) return null; return TryParseChangesetInfo(commit.Message, commit.Sha); } public TfsChangesetInfo GetCurrentTfsCommit() { var currentCommit = _repository.Head.Commits.First(); return TryParseChangesetInfo(currentCommit.Message, currentCommit.Sha); } public TfsChangesetInfo GetTfsCommit(GitCommit commit) { return TryParseChangesetInfo(commit.Message, commit.Sha); } public TfsChangesetInfo GetTfsCommit(string sha) { return GetTfsCommit(GetCommit(sha)); } private TfsChangesetInfo TryParseChangesetInfo(string gitTfsMetaInfo, string commit) { var match = GitTfsConstants.TfsCommitInfoRegex.Match(gitTfsMetaInfo); if (match.Success) { var commitInfo = _container.GetInstance<TfsChangesetInfo>(); commitInfo.Remote = ReadTfsRemote(match.Groups["url"].Value, match.Groups["repository"].Success ? match.Groups["repository"].Value : null); commitInfo.ChangesetId = Convert.ToInt32(match.Groups["changeset"].Value); commitInfo.GitCommit = commit; return commitInfo; } return null; } public IDictionary<string, GitObject> CreateObjectsDictionary() { return new Dictionary<string, GitObject>(StringComparer.InvariantCultureIgnoreCase); } public IDictionary<string, GitObject> GetObjects(string commit, IDictionary<string, GitObject> entries) { if (commit != null) { ParseEntries(entries, _repository.Lookup<Commit>(commit).Tree, commit); } return entries; } public IDictionary<string, GitObject> GetObjects(string commit) { var entries = CreateObjectsDictionary(); return GetObjects(commit, entries); } public IGitTreeBuilder GetTreeBuilder(string commit) { if (commit == null) { return new GitTreeBuilder(_repository.ObjectDatabase); } else { return new GitTreeBuilder(_repository.ObjectDatabase, _repository.Lookup<Commit>(commit).Tree); } } public string GetCommitMessage(string head, string parentCommitish) { var message = new System.Text.StringBuilder(); foreach (Commit comm in _repository.Commits.QueryBy(new CommitFilter { Since = head, Until = parentCommitish })) { // Normalize commit message line endings to CR+LF style, so that message // would be correctly shown in TFS commit dialog. message.AppendLine(NormalizeLineEndings(comm.Message)); } return GitTfsConstants.TfsCommitInfoRegex.Replace(message.ToString(), "").Trim(' ', '\r', '\n'); } private static string NormalizeLineEndings(string input) { return string.IsNullOrEmpty(input) ? input : input.Replace("\r\n", "\n").Replace("\r", "\n").Replace("\n", "\r\n"); } private void ParseEntries(IDictionary<string, GitObject> entries, Tree treeInfo, string commit) { var treesToDescend = new Queue<Tree>(new[] {treeInfo}); while (treesToDescend.Any()) { var currentTree = treesToDescend.Dequeue(); foreach (var item in currentTree) { if (item.TargetType == TreeEntryTargetType.Tree) { treesToDescend.Enqueue((Tree)item.Target); } var path = item.Path.Replace('\\', '/'); entries[path] = new GitObject { Mode = item.Mode, Sha = item.Target.Sha, ObjectType = item.TargetType, Path = path, Commit = commit }; } } } public IEnumerable<IGitChangedFile> GetChangedFiles(string from, string to) { using (var diffOutput = CommandOutputPipe("diff-tree", "-r", "-M", "-z", from, to)) { var changes = GitChangeInfo.GetChangedFiles(diffOutput); foreach (var change in changes) { yield return BuildGitChangedFile(change); } } } private IGitChangedFile BuildGitChangedFile(GitChangeInfo change) { return change.ToGitChangedFile(_container.With((IGitRepository) this)); } public bool WorkingCopyHasUnstagedOrUncommitedChanges { get { if (IsBare) return false; return (from entry in _repository.RetrieveStatus() where entry.State != FileStatus.Ignored && entry.State != FileStatus.Untracked select entry).Any(); } } public void CopyBlob(string sha, string outputFile) { Blob blob; var destination = new FileInfo(outputFile); if (!destination.Directory.Exists) destination.Directory.Create(); if ((blob = _repository.Lookup<Blob>(sha)) != null) using (Stream stream = blob.GetContentStream()) using (var outstream = File.Create(destination.FullName)) stream.CopyTo(outstream); } public string AssertValidBranchName(string gitBranchName) { if (!Reference.IsValidName(ShortToLocalName(gitBranchName))) throw new GitTfsException("The name specified for the new git branch is not allowed. Choose another one!"); while (IsRefNameUsed(gitBranchName)) { gitBranchName = "_" + gitBranchName; } return gitBranchName; } private bool IsRefNameUsed(string gitBranchName) { var parts = gitBranchName.Split('/'); var refName = parts.First(); for (int i = 1; i <= parts.Length; i++) { if (HasRef(ShortToLocalName(refName)) || HasRef(ShortToTfsRemoteName(refName))) return true; if (i < parts.Length) refName += '/' + parts[i]; } return false; } public bool CreateBranch(string gitBranchName, string target) { Reference reference; try { reference = _repository.Refs.Add(gitBranchName, target); } catch (Exception) { return false; } return reference != null; } private readonly Dictionary<int, string> changesetsCache = new Dictionary<int, string>(); private bool cacheIsFull = false; public string FindCommitHashByChangesetId(int changesetId) { var commit = FindCommitByChangesetId(changesetId); if (commit == null) return null; return commit.Sha; } private static readonly Regex tfsIdRegex = new Regex("^git-tfs-id: .*;C([0-9]+)\r?$", RegexOptions.Multiline | RegexOptions.Compiled | RegexOptions.RightToLeft); public static bool TryParseChangesetId(string commitMessage, out int changesetId) { var match = tfsIdRegex.Match(commitMessage); if (match.Success) { changesetId = int.Parse(match.Groups[1].Value); return true; } changesetId = 0; return false; } private Commit FindCommitByChangesetId(int changesetId, string remoteRef = null) { Trace.WriteLine("Looking for changeset " + changesetId + " in git repository..."); if (remoteRef == null) { string sha; if (changesetsCache.TryGetValue(changesetId, out sha)) return _repository.Lookup<Commit>(sha); if (cacheIsFull) return null; } var reachableFromRemoteBranches = new CommitFilter { Since = _repository.Branches.Where(p => p.IsRemote), SortBy = CommitSortStrategies.Time }; if (remoteRef != null) reachableFromRemoteBranches.Since = _repository.Branches.Where(p => p.IsRemote && p.CanonicalName.EndsWith(remoteRef)); var commitsFromRemoteBranches = _repository.Commits.QueryBy(reachableFromRemoteBranches); Commit commit = null; foreach (var c in commitsFromRemoteBranches) { int id; if (TryParseChangesetId(c.Message, out id)) { changesetsCache[id] = c.Sha; if (id == changesetId) { commit = c; break; } } } if (remoteRef == null && commit == null) cacheIsFull = true; // repository fully scanned Trace.WriteLine((commit == null) ? " => Commit not found!" : " => Commit found! hash: " + commit.Sha); return commit; } public void CreateTag(string name, string sha, string comment, string Owner, string emailOwner, System.DateTime creationDate) { if (_repository.Tags[name] == null) _repository.ApplyTag(name, sha, new Signature(Owner, emailOwner, new DateTimeOffset(creationDate)), comment); } public void CreateNote(string sha, string content, string owner, string emailOwner, DateTime creationDate) { Signature author = new Signature(owner, emailOwner, creationDate); _repository.Notes.Add(new ObjectId(sha), content, author, author, "commits"); } public void ResetHard(string sha) { _repository.Reset(ResetMode.Hard, sha); } public bool IsBare { get { return _repository.Info.IsBare; } } /// <summary> /// Gets all configured "subtree" remotes which point to the same Tfs URL as the given remote. /// If the given remote is itself a subtree, an empty enumerable is returned. /// </summary> public IEnumerable<IGitTfsRemote> GetSubtrees(IGitTfsRemote owner) { //a subtree remote cannot have subtrees itself. if (owner.IsSubtree) return Enumerable.Empty<IGitTfsRemote>(); return ReadAllTfsRemotes().Where(x => x.IsSubtree && string.Equals(x.OwningRemoteId, owner.Id, StringComparison.InvariantCultureIgnoreCase)); } public void ResetRemote(IGitTfsRemote remoteToReset, string target) { _repository.Refs.UpdateTarget(remoteToReset.RemoteRef, target); } public string GetCurrentBranch() { return _repository.Head.CanonicalName; } public void GarbageCollect(bool auto, string additionalMessage) { try { if (auto) _globals.Repository.CommandNoisy("gc", "--auto"); else _globals.Repository.CommandNoisy("gc"); } catch (Exception e) { Trace.WriteLine(e); realStdout.WriteLine("Warning: `git gc` failed! " + additionalMessage); } } public bool Checkout(string commitish) { try { _repository.Checkout(commitish); return true; } catch (MergeConflictException) { return false; } } public IEnumerable<GitCommit> FindParentCommits(string @from, string to) { var commits = _repository.Commits.QueryBy( new CommitFilter() {Since = @from, Until = to, SortBy = CommitSortStrategies.Reverse, FirstParentOnly = true}) .Select(c=>new GitCommit(c)); var parent = to; foreach (var gitCommit in commits) { if(!gitCommit.Parents.Any(c=>c.Sha == parent)) return new List<GitCommit>(); parent = gitCommit.Sha; } return commits; } } }
// 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.Concurrent; using System.Collections.Generic; using Xunit; namespace System.Threading.Tasks.Tests { public static class ParallelLoopResultTests { [Fact] public static void ForPLRTests() { ParallelLoopResult plr = Parallel.For(1, 0, delegate (int i, ParallelLoopState ps) { if (i == 10) ps.Stop(); }); PLRcheck(plr, "For-Empty", true, null); plr = Parallel.For(0, 100, delegate (int i, ParallelLoopState ps) { //Thread.Sleep(20); if (i == 10) ps.Stop(); }); PLRcheck(plr, "For-Stop", false, null); plr = Parallel.For(0, 100, delegate (int i, ParallelLoopState ps) { //Thread.Sleep(20); if (i == 10) ps.Break(); }); PLRcheck(plr, "For-Break", false, 10); plr = Parallel.For(0, 100, delegate (int i, ParallelLoopState ps) { //Thread.Sleep(20); }); PLRcheck(plr, "For-Completion", true, null); } [Fact] public static void ForPLR64Tests() { ParallelLoopResult plr = Parallel.For(1L, 0L, delegate (long i, ParallelLoopState ps) { if (i == 10) ps.Stop(); }); PLRcheck(plr, "For64-Empty", true, null); plr = Parallel.For(0L, 100L, delegate (long i, ParallelLoopState ps) { //Thread.Sleep(20); if (i == 10) ps.Stop(); }); PLRcheck(plr, "For64-Stop", false, null); plr = Parallel.For(0L, 100L, delegate (long i, ParallelLoopState ps) { //Thread.Sleep(20); if (i == 10) ps.Break(); }); PLRcheck(plr, "For64-Break", false, 10); plr = Parallel.For(0L, 100L, delegate (long i, ParallelLoopState ps) { //Thread.Sleep(20); }); PLRcheck(plr, "For64-Completion", true, null); } [Fact] public static void ForEachPLRTests() { Dictionary<string, string> dict = new Dictionary<string, string>(); ParallelLoopResult plr = Parallel.ForEach(dict, delegate (KeyValuePair<string, string> kvp, ParallelLoopState ps) { if (kvp.Value.Equals("Purple")) ps.Stop(); }); PLRcheck(plr, "ForEach-Empty", true, null); dict.Add("Apple", "Red"); dict.Add("Banana", "Yellow"); dict.Add("Pear", "Green"); dict.Add("Plum", "Red"); dict.Add("Grape", "Green"); dict.Add("Cherry", "Red"); dict.Add("Carrot", "Orange"); dict.Add("Eggplant", "Purple"); plr = Parallel.ForEach(dict, delegate (KeyValuePair<string, string> kvp, ParallelLoopState ps) { if (kvp.Value.Equals("Purple")) ps.Stop(); }); PLRcheck(plr, "ForEach-Stop", false, null); plr = Parallel.ForEach(dict, delegate (KeyValuePair<string, string> kvp, ParallelLoopState ps) { if (kvp.Value.Equals("Purple")) ps.Break(); }); PLRcheck(plr, "ForEach-Break", false, 7); // right?? plr = Parallel.ForEach(dict, delegate (KeyValuePair<string, string> kvp, ParallelLoopState ps) { //if(kvp.Value.Equals("Purple")) ps.Stop(); }); PLRcheck(plr, "ForEach-Complete", true, null); } [Fact] public static void PartitionerForEachPLRTests() { // // Now try testing Partitionable, OrderablePartitionable // List<int> intlist = new List<int>(); for (int i = 0; i < 20; i++) intlist.Add(i * i); MyPartitioner<int> mp = new MyPartitioner<int>(intlist); ParallelLoopResult plr = Parallel.ForEach(mp, delegate (int item, ParallelLoopState ps) { if (item == 0) ps.Stop(); }); PLRcheck(plr, "Partitioner-ForEach-Stop", false, null); plr = Parallel.ForEach(mp, delegate (int item, ParallelLoopState ps) { }); PLRcheck(plr, "Partitioner-ForEach-Complete", true, null); } [Fact] public static void OrderablePartitionerForEachTests() { List<int> intlist = new List<int>(); for (int i = 0; i < 20; i++) intlist.Add(i * i); OrderablePartitioner<int> mop = Partitioner.Create(intlist, true); ParallelLoopResult plr = Parallel.ForEach(mop, delegate (int item, ParallelLoopState ps, long index) { if (index == 2) ps.Stop(); }); PLRcheck(plr, "OrderablePartitioner-ForEach-Stop", false, null); plr = Parallel.ForEach(mop, delegate (int item, ParallelLoopState ps, long index) { if (index == 2) ps.Break(); }); PLRcheck(plr, "OrderablePartitioner-ForEach-Break", false, 2); plr = Parallel.ForEach(mop, delegate (int item, ParallelLoopState ps, long index) { }); PLRcheck(plr, "OrderablePartitioner-ForEach-Complete", true, null); } private static void PLRcheck(ParallelLoopResult plr, string ttype, bool shouldComplete, Int32? expectedLBI) { Assert.Equal(shouldComplete, plr.IsCompleted); Assert.Equal(expectedLBI, plr.LowestBreakIteration); } // Generalized test for testing For-loop results private static void ForPLRTest( Action<int, ParallelLoopState> body, string desc, bool excExpected, bool shouldComplete, bool shouldStop, bool shouldBreak) { ForPLRTest(body, new ParallelOptions(), desc, excExpected, shouldComplete, shouldStop, shouldBreak, false); } private static void ForPLRTest( Action<int, ParallelLoopState> body, ParallelOptions parallelOptions, string desc, bool excExpected, bool shouldComplete, bool shouldStop, bool shouldBreak, bool shouldCancel) { try { ParallelLoopResult plr = Parallel.For(0, 1, parallelOptions, body); Assert.False(shouldCancel); Assert.False(excExpected); Assert.Equal(shouldComplete, plr.IsCompleted); Assert.Equal(shouldStop, plr.LowestBreakIteration == null); Assert.Equal(shouldBreak, plr.LowestBreakIteration != null); } catch (OperationCanceledException) { Assert.True(shouldCancel); } catch (AggregateException) { Assert.True(excExpected); } } // ... and a 64-bit version private static void For64PLRTest( Action<long, ParallelLoopState> body, string desc, bool excExpected, bool shouldComplete, bool shouldStop, bool shouldBreak) { For64PLRTest(body, new ParallelOptions(), desc, excExpected, shouldComplete, shouldStop, shouldBreak, false); } private static void For64PLRTest( Action<long, ParallelLoopState> body, ParallelOptions parallelOptions, string desc, bool excExpected, bool shouldComplete, bool shouldStop, bool shouldBreak, bool shouldCancel) { try { ParallelLoopResult plr = Parallel.For(0L, 1L, parallelOptions, body); Assert.False(shouldCancel); Assert.False(excExpected); Assert.Equal(shouldComplete, plr.IsCompleted); Assert.Equal(shouldStop, plr.LowestBreakIteration == null); Assert.Equal(shouldBreak, plr.LowestBreakIteration != null); } catch (OperationCanceledException) { Assert.True(shouldCancel); } catch (AggregateException) { Assert.True(excExpected); } } // Generalized test for testing ForEach-loop results private static void ForEachPLRTest( Action<KeyValuePair<int, string>, ParallelLoopState> body, string desc, bool excExpected, bool shouldComplete, bool shouldStop, bool shouldBreak) { ForEachPLRTest(body, new ParallelOptions(), desc, excExpected, shouldComplete, shouldStop, shouldBreak, false); } private static void ForEachPLRTest( Action<KeyValuePair<int, string>, ParallelLoopState> body, ParallelOptions parallelOptions, string desc, bool excExpected, bool shouldComplete, bool shouldStop, bool shouldBreak, bool shouldCancel) { Dictionary<int, string> dict = new Dictionary<int, string>(); dict.Add(1, "one"); try { ParallelLoopResult plr = Parallel.ForEach(dict, parallelOptions, body); Assert.False(shouldCancel); Assert.False(excExpected); Assert.Equal(shouldComplete, plr.IsCompleted); Assert.Equal(shouldStop, plr.LowestBreakIteration == null); Assert.Equal(shouldBreak, plr.LowestBreakIteration != null); } catch (OperationCanceledException) { Assert.True(shouldCancel); } catch (AggregateException) { Assert.True(excExpected); } } // Generalized test for testing Partitioner ForEach-loop results private static void PartitionerForEachPLRTest( Action<int, ParallelLoopState> body, string desc, bool excExpected, bool shouldComplete, bool shouldStop, bool shouldBreak) { List<int> list = new List<int>(); for (int i = 0; i < 20; i++) list.Add(i); MyPartitioner<int> mp = new MyPartitioner<int>(list); try { ParallelLoopResult plr = Parallel.ForEach(mp, body); Assert.False(excExpected); Assert.Equal(shouldComplete, plr.IsCompleted); Assert.Equal(shouldStop, plr.LowestBreakIteration == null); Assert.Equal(shouldBreak, plr.LowestBreakIteration != null); } catch (AggregateException) { Assert.True(excExpected); } } // Generalized test for testing OrderablePartitioner ForEach-loop results private static void OrderablePartitionerForEachPLRTest( Action<int, ParallelLoopState, long> body, string desc, bool excExpected, bool shouldComplete, bool shouldStop, bool shouldBreak) { List<int> list = new List<int>(); for (int i = 0; i < 20; i++) list.Add(i); OrderablePartitioner<int> mop = Partitioner.Create(list, true); try { ParallelLoopResult plr = Parallel.ForEach(mop, body); Assert.False(excExpected); Assert.Equal(shouldComplete, plr.IsCompleted); Assert.Equal(shouldStop, plr.LowestBreakIteration == null); Assert.Equal(shouldBreak, plr.LowestBreakIteration != null); } catch (AggregateException) { Assert.True(excExpected); } } // Perform tests on various combinations of Stop()/Break() [Fact] public static void SimultaneousStopBreakTests() { // // Test 32-bit Parallel.For() // ForPLRTest(delegate (int i, ParallelLoopState ps) { ps.Stop(); ps.Break(); }, "Break After Stop", true, false, false, false); ForPLRTest(delegate (int i, ParallelLoopState ps) { ps.Break(); ps.Stop(); }, "Stop After Break", true, false, false, false); CancellationTokenSource cts = new CancellationTokenSource(); ParallelOptions options = new ParallelOptions(); options.CancellationToken = cts.Token; ForPLRTest(delegate (int i, ParallelLoopState ps) { ps.Break(); cts.Cancel(); }, options, "Cancel After Break", false, false, false, false, true); cts = new CancellationTokenSource(); options = new ParallelOptions(); options.CancellationToken = cts.Token; ForPLRTest(delegate (int i, ParallelLoopState ps) { ps.Stop(); cts.Cancel(); }, options, "Cancel After Stop", false, false, false, false, true); cts = new CancellationTokenSource(); options = new ParallelOptions(); options.CancellationToken = cts.Token; ForPLRTest(delegate (int i, ParallelLoopState ps) { cts.Cancel(); ps.Stop(); }, options, "Stop After Cancel", false, false, false, false, true); cts = new CancellationTokenSource(); options = new ParallelOptions(); options.CancellationToken = cts.Token; ForPLRTest(delegate (int i, ParallelLoopState ps) { cts.Cancel(); ps.Break(); }, options, "Break After Cancel", false, false, false, false, true); ForPLRTest(delegate (int i, ParallelLoopState ps) { ps.Break(); try { ps.Stop(); } catch { } }, "Stop(caught) after Break", false, false, false, true); ForPLRTest(delegate (int i, ParallelLoopState ps) { ps.Stop(); try { ps.Break(); } catch { } }, "Break(caught) after Stop", false, false, true, false); // // Test "vanilla" Parallel.ForEach // ForEachPLRTest(delegate (KeyValuePair<int, string> kvp, ParallelLoopState ps) { ps.Break(); ps.Stop(); }, "Stop-After-Break", true, false, false, false); ForEachPLRTest(delegate (KeyValuePair<int, string> kvp, ParallelLoopState ps) { ps.Stop(); ps.Break(); }, "Break-after-Stop", true, false, false, false); cts = new CancellationTokenSource(); options = new ParallelOptions(); options.CancellationToken = cts.Token; ForEachPLRTest(delegate (KeyValuePair<int, string> kvp, ParallelLoopState ps) { ps.Break(); cts.Cancel(); }, options, "Cancel After Break", false, false, false, false, true); cts = new CancellationTokenSource(); options = new ParallelOptions(); options.CancellationToken = cts.Token; ForEachPLRTest(delegate (KeyValuePair<int, string> kvp, ParallelLoopState ps) { ps.Stop(); cts.Cancel(); }, options, "Cancel After Stop", false, false, false, false, true); cts = new CancellationTokenSource(); options = new ParallelOptions(); options.CancellationToken = cts.Token; ForEachPLRTest(delegate (KeyValuePair<int, string> kvp, ParallelLoopState ps) { cts.Cancel(); ps.Stop(); }, options, "Stop After Cancel", false, false, false, false, true); cts = new CancellationTokenSource(); options = new ParallelOptions(); options.CancellationToken = cts.Token; ForEachPLRTest(delegate (KeyValuePair<int, string> kvp, ParallelLoopState ps) { cts.Cancel(); ps.Break(); }, options, "Break After Cancel", false, false, false, false, true); ForEachPLRTest(delegate (KeyValuePair<int, string> kvp, ParallelLoopState ps) { ps.Break(); try { ps.Stop(); } catch { } }, "Stop(caught)-after-Break", false, false, false, true); ForEachPLRTest(delegate (KeyValuePair<int, string> kvp, ParallelLoopState ps) { ps.Stop(); try { ps.Break(); } catch { } }, "Break(caught)-after-Stop", false, false, true, false); // // Test Parallel.ForEach w/ Partitioner // PartitionerForEachPLRTest(delegate (int i, ParallelLoopState ps) { ps.Break(); ps.Stop(); }, "Stop-After-Break", true, false, false, false); PartitionerForEachPLRTest(delegate (int i, ParallelLoopState ps) { ps.Stop(); ps.Break(); }, "Break-after-Stop", true, false, false, false); PartitionerForEachPLRTest(delegate (int i, ParallelLoopState ps) { ps.Break(); try { ps.Stop(); } catch { } }, "Stop(caught)-after-Break", false, false, false, true); PartitionerForEachPLRTest(delegate (int i, ParallelLoopState ps) { ps.Stop(); try { ps.Break(); } catch { } }, "Break(caught)-after-Stop", false, false, true, false); // // Test Parallel.ForEach w/ OrderablePartitioner // OrderablePartitionerForEachPLRTest(delegate (int i, ParallelLoopState ps, long index) { ps.Break(); ps.Stop(); }, "Stop-After-Break", true, false, false, false); OrderablePartitionerForEachPLRTest(delegate (int i, ParallelLoopState ps, long index) { ps.Stop(); ps.Break(); }, "Break-after-Stop", true, false, false, false); OrderablePartitionerForEachPLRTest(delegate (int i, ParallelLoopState ps, long index) { ps.Break(); try { ps.Stop(); } catch { } }, "Stop(caught)-after-Break", false, false, false, true); OrderablePartitionerForEachPLRTest(delegate (int i, ParallelLoopState ps, long index) { ps.Stop(); try { ps.Break(); } catch { } }, "Break(caught)-after-Stop", false, false, true, false); // // Test 64-bit Parallel.For // For64PLRTest(delegate (long i, ParallelLoopState ps) { ps.Stop(); ps.Break(); }, "Break After Stop", true, false, false, false); For64PLRTest(delegate (long i, ParallelLoopState ps) { ps.Break(); ps.Stop(); }, "Stop After Break", true, false, false, false); cts = new CancellationTokenSource(); options = new ParallelOptions(); options.CancellationToken = cts.Token; For64PLRTest(delegate (long i, ParallelLoopState ps) { ps.Break(); cts.Cancel(); }, options, "Cancel After Break", false, false, false, false, true); cts = new CancellationTokenSource(); options = new ParallelOptions(); options.CancellationToken = cts.Token; For64PLRTest(delegate (long i, ParallelLoopState ps) { ps.Stop(); cts.Cancel(); }, options, "Cancel After Stop", false, false, false, false, true); cts = new CancellationTokenSource(); options = new ParallelOptions(); options.CancellationToken = cts.Token; For64PLRTest(delegate (long i, ParallelLoopState ps) { cts.Cancel(); ps.Stop(); }, options, "Stop after Cancel", false, false, false, false, true); cts = new CancellationTokenSource(); options = new ParallelOptions(); options.CancellationToken = cts.Token; For64PLRTest(delegate (long i, ParallelLoopState ps) { cts.Cancel(); ps.Break(); }, options, "Break after Cancel", false, false, false, false, true); For64PLRTest(delegate (long i, ParallelLoopState ps) { ps.Break(); try { ps.Stop(); } catch { } }, "Stop(caught) after Break", false, false, false, true); For64PLRTest(delegate (long i, ParallelLoopState ps) { ps.Stop(); try { ps.Break(); } catch { } }, "Break(caught) after Stop", false, false, true, false); } #region Helper Classes and Methods // // Utility class for use w/ Partitioner-style ForEach testing. // Created by Cindy Song. // public class MyPartitioner<TSource> : Partitioner<TSource> { private IList<TSource> _data; public MyPartitioner(IList<TSource> data) { _data = data; } override public IList<IEnumerator<TSource>> GetPartitions(int partitionCount) { if (partitionCount <= 0) { throw new ArgumentOutOfRangeException(nameof(partitionCount)); } IEnumerator<TSource>[] partitions = new IEnumerator<TSource>[partitionCount]; IEnumerable<KeyValuePair<long, TSource>> partitionEnumerable = Partitioner.Create(_data, true).GetOrderableDynamicPartitions(); for (int i = 0; i < partitionCount; i++) { partitions[i] = DropIndices(partitionEnumerable.GetEnumerator()); } return partitions; } override public IEnumerable<TSource> GetDynamicPartitions() { return DropIndices(Partitioner.Create(_data, true).GetOrderableDynamicPartitions()); } private static IEnumerable<TSource> DropIndices(IEnumerable<KeyValuePair<long, TSource>> source) { foreach (KeyValuePair<long, TSource> pair in source) { yield return pair.Value; } } private static IEnumerator<TSource> DropIndices(IEnumerator<KeyValuePair<long, TSource>> source) { while (source.MoveNext()) { yield return source.Current.Value; } } public override bool SupportsDynamicPartitions { get { return true; } } } #endregion } }
using System; using Content.Client.Administration.Managers; using Content.Client.Changelog; using Content.Client.CharacterInterface; using Content.Client.Chat.Managers; using Content.Client.EscapeMenu; using Content.Client.Eui; using Content.Client.Flash; using Content.Client.HUD; using Content.Client.Info; using Content.Client.Input; using Content.Client.IoC; using Content.Client.Launcher; using Content.Client.MainMenu; using Content.Client.MobState.Overlays; using Content.Client.Parallax; using Content.Client.Parallax.Managers; using Content.Client.Preferences; using Content.Client.Sandbox; using Content.Client.Screenshot; using Content.Client.Singularity; using Content.Client.StationEvents; using Content.Client.StationEvents.Managers; using Content.Client.Stylesheets; using Content.Client.Viewport; using Content.Client.Voting; using Content.Shared.Actions; using Content.Shared.Administration; using Content.Shared.Alert; using Content.Shared.AME; using Content.Shared.Cargo.Components; using Content.Shared.Chemistry.Components; using Content.Shared.Chemistry.Dispenser; using Content.Shared.Gravity; using Content.Shared.Lathe; using Content.Shared.Markers; using Content.Shared.Research.Components; using Content.Shared.VendingMachines; using Content.Shared.Wires; using Robust.Client; using Robust.Client.Graphics; using Robust.Client.Input; using Robust.Client.Player; using Robust.Client.State; using Robust.Client.UserInterface; using Robust.Shared.ContentPack; using Robust.Shared.GameObjects; using Robust.Shared.IoC; using Robust.Shared.Map; using Robust.Shared.Prototypes; using Robust.Shared.Timing; namespace Content.Client.Entry { public sealed class EntryPoint : GameClient { [Dependency] private readonly IPlayerManager _playerManager = default!; [Dependency] private readonly IBaseClient _baseClient = default!; [Dependency] private readonly IEscapeMenuOwner _escapeMenuOwner = default!; [Dependency] private readonly IGameController _gameController = default!; [Dependency] private readonly IStateManager _stateManager = default!; [Dependency] private readonly IEntityManager _entityManager = default!; public override void Init() { var factory = IoCManager.Resolve<IComponentFactory>(); var prototypes = IoCManager.Resolve<IPrototypeManager>(); factory.DoAutoRegistrations(); foreach (var ignoreName in IgnoredComponents.List) { factory.RegisterIgnore(ignoreName); } factory.RegisterClass<SharedResearchConsoleComponent>(); factory.RegisterClass<SharedLatheComponent>(); factory.RegisterClass<SharedSpawnPointComponent>(); factory.RegisterClass<SharedVendingMachineComponent>(); factory.RegisterClass<SharedWiresComponent>(); factory.RegisterClass<SharedCargoConsoleComponent>(); factory.RegisterClass<SharedReagentDispenserComponent>(); factory.RegisterClass<SharedChemMasterComponent>(); factory.RegisterClass<SharedGravityGeneratorComponent>(); factory.RegisterClass<SharedAMEControllerComponent>(); prototypes.RegisterIgnore("accent"); prototypes.RegisterIgnore("material"); prototypes.RegisterIgnore("reaction"); //Chemical reactions only needed by server. Reactions checks are server-side. prototypes.RegisterIgnore("gasReaction"); prototypes.RegisterIgnore("seed"); // Seeds prototypes are server-only. prototypes.RegisterIgnore("barSign"); prototypes.RegisterIgnore("objective"); prototypes.RegisterIgnore("holiday"); prototypes.RegisterIgnore("aiFaction"); prototypes.RegisterIgnore("gameMap"); prototypes.RegisterIgnore("behaviorSet"); prototypes.RegisterIgnore("advertisementsPack"); prototypes.RegisterIgnore("metabolizerType"); prototypes.RegisterIgnore("metabolismGroup"); prototypes.RegisterIgnore("salvageMap"); prototypes.RegisterIgnore("gamePreset"); prototypes.RegisterIgnore("gameRule"); prototypes.RegisterIgnore("worldSpell"); prototypes.RegisterIgnore("entitySpell"); prototypes.RegisterIgnore("instantSpell"); ClientContentIoC.Register(); foreach (var callback in TestingCallbacks) { var cast = (ClientModuleTestingCallbacks) callback; cast.ClientBeforeIoC?.Invoke(); } IoCManager.BuildGraph(); factory.GenerateNetIds(); IoCManager.Resolve<IClientAdminManager>().Initialize(); IoCManager.Resolve<IParallaxManager>().LoadParallax(); IoCManager.Resolve<IBaseClient>().PlayerJoinedServer += SubscribePlayerAttachmentEvents; IoCManager.Resolve<IStylesheetManager>().Initialize(); IoCManager.Resolve<IScreenshotHook>().Initialize(); IoCManager.Resolve<ChangelogManager>().Initialize(); IoCManager.Resolve<RulesManager>().Initialize(); IoCManager.Resolve<ViewportManager>().Initialize(); IoCManager.InjectDependencies(this); _escapeMenuOwner.Initialize(); _baseClient.PlayerJoinedServer += (_, _) => { IoCManager.Resolve<IMapManager>().CreateNewMapEntity(MapId.Nullspace); }; } /// <summary> /// Subscribe events to the player manager after the player manager is set up /// </summary> /// <param name="sender"></param> /// <param name="args"></param> public void SubscribePlayerAttachmentEvents(object? sender, EventArgs args) { if (_playerManager.LocalPlayer != null) { _playerManager.LocalPlayer.EntityAttached += AttachPlayerToEntity; _playerManager.LocalPlayer.EntityDetached += DetachPlayerFromEntity; } } /// <summary> /// Add the character interface master which combines all character interfaces into one window /// </summary> public void AttachPlayerToEntity(EntityAttachedEventArgs eventArgs) { // TODO This is shitcode. Move this to an entity system, FOR FUCK'S SAKE _entityManager.AddComponent<CharacterInterfaceComponent>(eventArgs.NewEntity); } /// <summary> /// Remove the character interface master from this entity now that we have detached ourselves from it /// </summary> public void DetachPlayerFromEntity(EntityDetachedEventArgs eventArgs) { // TODO This is shitcode. Move this to an entity system, FOR FUCK'S SAKE if (!_entityManager.Deleted(eventArgs.OldEntity)) { _entityManager.RemoveComponent<CharacterInterfaceComponent>(eventArgs.OldEntity); } } public override void PostInit() { base.PostInit(); // Setup key contexts var inputMan = IoCManager.Resolve<IInputManager>(); ContentContexts.SetupContexts(inputMan.Contexts); IoCManager.Resolve<IGameHud>().Initialize(); var overlayMgr = IoCManager.Resolve<IOverlayManager>(); overlayMgr.AddOverlay(new ParallaxOverlay()); overlayMgr.AddOverlay(new SingularityOverlay()); overlayMgr.AddOverlay(new CritOverlay()); //Hopefully we can cut down on this list... don't see why a death overlay needs to be instantiated here. overlayMgr.AddOverlay(new CircleMaskOverlay()); overlayMgr.AddOverlay(new FlashOverlay()); overlayMgr.AddOverlay(new RadiationPulseOverlay()); IoCManager.Resolve<IChatManager>().Initialize(); IoCManager.Resolve<IClientPreferencesManager>().Initialize(); IoCManager.Resolve<IStationEventManager>().Initialize(); IoCManager.Resolve<EuiManager>().Initialize(); IoCManager.Resolve<IVoteManager>().Initialize(); IoCManager.Resolve<IGamePrototypeLoadManager>().Initialize(); _baseClient.RunLevelChanged += (_, args) => { if (args.NewLevel == ClientRunLevel.Initialize) { SwitchToDefaultState(args.OldLevel == ClientRunLevel.Connected || args.OldLevel == ClientRunLevel.InGame); } }; // Disable engine-default viewport since we use our own custom viewport control. IoCManager.Resolve<IUserInterfaceManager>().MainViewport.Visible = false; SwitchToDefaultState(); } private void SwitchToDefaultState(bool disconnected = false) { // Fire off into state dependent on launcher or not. if (_gameController.LaunchState.FromLauncher) { _stateManager.RequestStateChange<LauncherConnecting>(); var state = (LauncherConnecting) _stateManager.CurrentState; if (disconnected) { state.SetDisconnected(); } } else { _stateManager.RequestStateChange<MainScreen>(); } } public override void Update(ModUpdateLevel level, FrameEventArgs frameEventArgs) { base.Update(level, frameEventArgs); switch (level) { case ModUpdateLevel.FramePreEngine: // TODO: Turn IChatManager into an EntitySystem and remove the line below. IoCManager.Resolve<IChatManager>().FrameUpdate(frameEventArgs); break; } } } }
// // HttpURLConnection.cs // // Author: // Lluis Sanchez Gual <lluis@novell.com> // // Copyright (c) 2010 Novell, Inc (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using System.Net; namespace Sharpen { public abstract class URLConnection { public abstract InputStream GetInputStream(); } public class HttpsURLConnection: HttpURLConnection { public HttpsURLConnection (Uri uri): base (uri) { } public HttpsURLConnection (Uri uri, Proxy p): base (uri, p) { } public void SetSSLSocketFactory (object factory) { // TODO } } public class HttpURLConnection: URLConnection { public const int HTTP_OK = 200; public const int HTTP_NOT_FOUND = 404; public const int HTTP_FORBIDDEN = 403; public const int HTTP_UNAUTHORIZED = 401; HttpWebRequest request; HttpWebResponse reqResponse; Uri url; public HttpURLConnection (Uri uri) { url = uri; request = (HttpWebRequest) HttpWebRequest.Create (uri); } public HttpURLConnection (Uri uri, Proxy p) { url = uri; request = (HttpWebRequest) HttpWebRequest.Create (uri); } HttpWebResponse Response { get { if (reqResponse == null) { try { reqResponse = (HttpWebResponse) request.GetResponse (); } catch (WebException ex) { reqResponse = (HttpWebResponse) ex.Response; if (reqResponse == null) { if (this is HttpsURLConnection) throw new WebException ("A secure connection could not be established", ex); throw; } } } return reqResponse; } } public void SetUseCaches (bool u) { if (u) request.CachePolicy = new System.Net.Cache.RequestCachePolicy (System.Net.Cache.RequestCacheLevel.Default); else request.CachePolicy = new System.Net.Cache.RequestCachePolicy (System.Net.Cache.RequestCacheLevel.BypassCache); } public void SetRequestMethod (string method) { request.Method = method; } public string GetRequestMethod () { return request.Method; } public void SetInstanceFollowRedirects (bool redirects) { request.AllowAutoRedirect = redirects; } public void SetDoOutput (bool dooutput) { // Not required? } public void SetFixedLengthStreamingMode (int len) { request.SendChunked = false; } public void SetChunkedStreamingMode (int n) { request.SendChunked = true; } public void SetRequestProperty (string key, string value) { switch (key.ToLower ()) { case "user-agent": request.UserAgent = value; break; case "content-length": request.ContentLength = long.Parse (value); break; case "content-type": request.ContentType = value; break; case "expect": request.Expect = value; break; case "referer": request.Referer = value; break; case "transfer-encoding": request.TransferEncoding = value; break; case "accept": request.Accept = value; break; default: request.Headers.Set (key, value); break; } } public string GetResponseMessage () { return Response.StatusDescription; } public void SetConnectTimeout (int ms) { if (ms == 0) ms = -1; request.Timeout = ms; } public void SetReadTimeout (int ms) { // Not available } public override InputStream GetInputStream () { return Response.GetResponseStream (); } public OutputStream GetOutputStream () { return request.GetRequestStream (); } public string GetHeaderField (string header) { return Response.GetResponseHeader (header); } public string GetContentType () { return Response.ContentType; } public int GetContentLength () { return (int) Response.ContentLength; } public int GetResponseCode () { return (int) Response.StatusCode; } public Uri GetURL () { return url; } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq.Expressions; using DesertOctopus.Utilities; using DesertOctopus.Utilities.MethodInfoHelpers; namespace DesertOctopus.Cloning { /// <summary> /// Helper class for array expression trees /// </summary> internal static class ArrayCloner { /// <summary> /// Generate an expression tree for arrays /// </summary> /// <param name="variables">Global variables for the expression tree</param> /// <param name="source">Source object</param> /// <param name="clone">Clone object</param> /// <param name="sourceType">Type of the source object</param> /// <param name="refTrackerParam">Reference tracker</param> /// <returns>Expression tree to clone arrays</returns> public static Expression GenerateArrayExpression(List<ParameterExpression> variables, ParameterExpression source, ParameterExpression clone, Type sourceType, ParameterExpression refTrackerParam) { var elementType = sourceType.GetElementType(); if (elementType.IsPrimitive || elementType.IsValueType || (elementType == typeof(string))) { return Expression.Block(Expression.Assign(clone, Expression.Convert(Expression.Call(Expression.Convert(source, typeof(Array)), ArrayMih.Clone()), sourceType)), Expression.Call(refTrackerParam, ObjectClonerReferenceTrackerMih.Track(), source, clone)); } if (elementType.IsArray) { return GenerateJaggedArray(variables, source, clone, sourceType, refTrackerParam); } else { return GenerateArrayOfKnownDimension(variables, source, clone, sourceType, elementType, refTrackerParam); } } private static Expression GenerateArrayOfKnownDimension(List<ParameterExpression> variables, ParameterExpression source, ParameterExpression clone, Type sourceType, Type elementType, ParameterExpression refTrackerParam) { var i = Expression.Parameter(typeof(int), "i"); var lengths = Expression.Parameter(typeof(int[]), "lengths"); var rank = sourceType.GetArrayRank(); variables.Add(i); variables.Add(lengths); List<Expression> notTrackedExpressions = new List<Expression>(); notTrackedExpressions.Add(Expression.IfThen(Expression.GreaterThanOrEqual(Expression.Constant(rank), Expression.Constant(255)), Expression.Throw(Expression.New(NotSupportedExceptionMih.ConstructorString(), Expression.Constant("Array with more than 255 dimensions are not supported"))))); notTrackedExpressions.Add(Expression.Assign(lengths, Expression.Call(CreateArrayMethodInfo.GetCreateArrayMethodInfo(typeof(int)), Expression.Constant(rank)))); notTrackedExpressions.AddRange(PopulateDimensionalArrayLength(source, i, lengths, rank)); notTrackedExpressions.Add(Expression.Assign(clone, Expression.Convert(Expression.Call(ArrayMih.CreateInstance(), Expression.Constant(elementType), lengths), sourceType))); notTrackedExpressions.Add(Expression.Call(refTrackerParam, ObjectClonerReferenceTrackerMih.Track(), source, clone)); notTrackedExpressions.AddRange(GenerateCopyDimensionalArray(source, clone, sourceType, variables, lengths, rank, refTrackerParam)); return ObjectCloner.GenerateNullTrackedOrUntrackedExpression(source, clone, sourceType, refTrackerParam, Expression.Block(notTrackedExpressions)); } private static IEnumerable<Expression> GenerateCopyDimensionalArray(ParameterExpression sourceArray, ParameterExpression cloneArray, Type sourceType, List<ParameterExpression> variables, ParameterExpression lengths, int rank, ParameterExpression refTrackerParam) { var elementType = sourceType.GetElementType(); var item = Expression.Parameter(elementType, "item"); var clonedItem = Expression.Parameter(elementType, "clonedItem"); var typeExpr = Expression.Parameter(typeof(Type), "typeExpr"); var indices = Expression.Parameter(typeof(int[]), "indices"); variables.Add(typeExpr); variables.Add(item); variables.Add(indices); variables.Add(clonedItem); var expressions = new List<Expression>(); expressions.Add(Expression.Assign(indices, Expression.Call(CreateArrayMethodInfo.GetCreateArrayMethodInfo(typeof(int)), Expression.Constant(rank)))); Debug.Assert(!(elementType.IsPrimitive || elementType.IsValueType || elementType == typeof(string)), "This method is not made to handle primitive types"); Expression innerExpression = Expression.Block(ClassCloner.GetCloneClassTypeExpression(refTrackerParam, item, clonedItem, elementType), Expression.Call(cloneArray, ArrayMih.SetValueRank(), Expression.Convert(clonedItem, typeof(object)), indices)); Func<int, Expression, Expression> makeArrayLoop = (loopRank, innerExpr) => { var loopRankIndex = Expression.Parameter(typeof(int), "loopRankIndex" + loopRank); variables.Add(loopRankIndex); var loopExpressions = new List<Expression>(); loopExpressions.Add(Expression.Assign(Expression.ArrayAccess(indices, Expression.Constant(loopRank)), loopRankIndex)); loopExpressions.Add(Expression.Assign(item, Expression.Convert(Expression.Call(sourceArray, ArrayMih.GetValueRank(), indices), elementType))); loopExpressions.Add(innerExpr); loopExpressions.Add(Expression.Assign(loopRankIndex, Expression.Add(loopRankIndex, Expression.Constant(1)))); var cond = Expression.LessThan(loopRankIndex, Expression.ArrayIndex(lengths, Expression.Constant(loopRank))); var loopBody = Expression.Block(loopExpressions); var breakLabel = Expression.Label("breakLabel" + loopRank); var loop = Expression.Loop(Expression.IfThenElse(cond, loopBody, Expression.Break(breakLabel)), breakLabel); return Expression.Block(Expression.Assign(loopRankIndex, Expression.Constant(0)), loop); }; for (int r = rank - 1; r >= 0; r--) { innerExpression = makeArrayLoop(r, innerExpression); } expressions.Add(innerExpression); return expressions; } private static IEnumerable<Expression> PopulateDimensionalArrayLength(ParameterExpression sourceArray, ParameterExpression i, ParameterExpression lengths, int rank) { var loopExpressions = new List<Expression>(); var expressions = new List<Expression>(); expressions.Add(Expression.Assign(i, Expression.Constant(0))); var length = Expression.Call(sourceArray, ArrayMih.GetLength(), i); loopExpressions.Add(Expression.Assign(Expression.ArrayAccess(lengths, i), length)); loopExpressions.Add(Expression.Assign(i, Expression.Add(i, Expression.Constant(1)))); var loopBody = Expression.Block(loopExpressions); var breakLabel = Expression.Label("breakLabelLength"); var cond = Expression.LessThan(i, Expression.Constant(rank)); var loop = Expression.Loop(Expression.IfThenElse(cond, loopBody, Expression.Break(breakLabel)), breakLabel); expressions.Add(loop); return expressions; } private static Expression GenerateJaggedArray(List<ParameterExpression> variables, ParameterExpression source, ParameterExpression clone, Type sourceType, ParameterExpression refTrackerParam) { var elementType = sourceType.GetElementType(); var item = Expression.Parameter(elementType, "item"); var clonedItem = Expression.Parameter(elementType, "item"); var typeExpr = Expression.Parameter(typeof(Type), "typeExpr"); var i = Expression.Parameter(typeof(int), "i"); var length = Expression.Parameter(typeof(int), "length"); variables.Add(typeExpr); variables.Add(clonedItem); variables.Add(item); variables.Add(length); variables.Add(i); var notTrackedExpressions = new List<Expression>(); notTrackedExpressions.Add(Expression.Assign(length, Expression.Property(source, "Length"))); notTrackedExpressions.Add(Expression.Assign(i, Expression.Constant(0))); notTrackedExpressions.Add(Expression.Assign(clone, Expression.Convert(Expression.New(sourceType.GetConstructor(new[] { typeof(int) }), length), sourceType))); notTrackedExpressions.Add(Expression.Call(refTrackerParam, ObjectClonerReferenceTrackerMih.Track(), source, clone)); Debug.Assert(!elementType.IsPrimitive && !elementType.IsValueType && elementType != typeof(string), "Element type cannot be a primitive type"); var loopExpressions = new List<Expression>(); loopExpressions.Add(Expression.Assign(item, Expression.Convert(Expression.Call(source, ArrayMih.GetValue(), i), elementType))); loopExpressions.Add(ClassCloner.GetCloneClassTypeExpression(refTrackerParam, item, clonedItem, elementType)); loopExpressions.Add(Expression.Call(clone, ArrayMih.SetValue(), Expression.Convert(clonedItem, typeof(object)), i)); loopExpressions.Add(Expression.Assign(i, Expression.Add(i, Expression.Constant(1)))); var cond = Expression.LessThan(i, length); var loopBody = Expression.Block(loopExpressions); var breakLabel = Expression.Label("breakLabel"); var loop = Expression.Loop(Expression.IfThenElse(cond, loopBody, Expression.Break(breakLabel)), breakLabel); notTrackedExpressions.Add(loop); return ObjectCloner.GenerateNullTrackedOrUntrackedExpression(source, clone, sourceType, refTrackerParam, Expression.Block(notTrackedExpressions)); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Microsoft.Win32.SafeHandles; using System.IO; using System.Runtime.InteropServices; using System.Security; namespace System.Threading { public sealed partial class Semaphore : WaitHandle { private const int MAX_PATH = 260; // creates a nameless semaphore object // Win32 only takes maximum count of Int32.MaxValue [SecuritySafeCritical] public Semaphore(int initialCount, int maximumCount) : this(initialCount, maximumCount, null) { } [SecurityCritical] public Semaphore(int initialCount, int maximumCount, string name) { if (initialCount < 0) { throw new ArgumentOutOfRangeException("initialCount", SR.ArgumentOutOfRange_NeedNonNegNumRequired); } if (maximumCount < 1) { throw new ArgumentOutOfRangeException("maximumCount", SR.ArgumentOutOfRange_NeedPosNum); } if (initialCount > maximumCount) { throw new ArgumentException(SR.Argument_SemaphoreInitialMaximum); } if (null != name && MAX_PATH < name.Length) { throw new ArgumentException(SR.Argument_WaitHandleNameTooLong); } SafeWaitHandle myHandle = CreateSemaphone(initialCount, maximumCount, name); if (myHandle.IsInvalid) { int errorCode = Marshal.GetLastWin32Error(); if (null != name && 0 != name.Length && Interop.mincore.Errors.ERROR_INVALID_HANDLE == errorCode) throw new WaitHandleCannotBeOpenedException(SR.Format(SR.WaitHandleCannotBeOpenedException_InvalidHandle, name)); WinIOError(); } this.SafeWaitHandle = myHandle; } [SecurityCritical] public Semaphore(int initialCount, int maximumCount, string name, out bool createdNew) { if (initialCount < 0) { throw new ArgumentOutOfRangeException("initialCount", SR.ArgumentOutOfRange_NeedNonNegNumRequired); } if (maximumCount < 1) { throw new ArgumentOutOfRangeException("maximumCount", SR.ArgumentOutOfRange_NeedNonNegNumRequired); } if (initialCount > maximumCount) { throw new ArgumentException(SR.Argument_SemaphoreInitialMaximum); } if (null != name && MAX_PATH < name.Length) { throw new ArgumentException(SR.Argument_WaitHandleNameTooLong); } SafeWaitHandle myHandle; myHandle = CreateSemaphone(initialCount, maximumCount, name); int errorCode = Marshal.GetLastWin32Error(); if (myHandle.IsInvalid) { if (null != name && 0 != name.Length && Interop.mincore.Errors.ERROR_INVALID_HANDLE == errorCode) throw new WaitHandleCannotBeOpenedException(SR.Format(SR.WaitHandleCannotBeOpenedException_InvalidHandle, name)); WinIOError(); } createdNew = errorCode != Interop.mincore.Errors.ERROR_ALREADY_EXISTS; this.SafeWaitHandle = myHandle; } [SecurityCritical] private Semaphore(SafeWaitHandle handle) { this.SafeWaitHandle = handle; } [SecurityCritical] public static Semaphore OpenExisting(string name) { Semaphore result; switch (OpenExistingWorker(name, out result)) { case OpenExistingResult.NameNotFound: throw new WaitHandleCannotBeOpenedException(); case OpenExistingResult.NameInvalid: throw new WaitHandleCannotBeOpenedException(SR.Format(SR.WaitHandleCannotBeOpenedException_InvalidHandle, name)); case OpenExistingResult.PathNotFound: throw new IOException(GetMessage(Interop.mincore.Errors.ERROR_PATH_NOT_FOUND)); default: return result; } } [SecurityCritical] public static bool TryOpenExisting(string name, out Semaphore result) { return OpenExistingWorker(name, out result) == OpenExistingResult.Success; } // This exists in WaitHandle, but is oddly ifdefed for some reason... private enum OpenExistingResult { Success, NameNotFound, PathNotFound, NameInvalid } [SecurityCritical] private static OpenExistingResult OpenExistingWorker(string name, out Semaphore result) { if (name == null) { throw new ArgumentNullException("name"); } if (name.Length == 0) { throw new ArgumentException(SR.Format(SR.InvalidNullEmptyArgument, "name")); } if (null != name && MAX_PATH < name.Length) { throw new ArgumentException(SR.Argument_WaitHandleNameTooLong); } result = null; SafeWaitHandle myHandle = OpenSemaphore(name); if (myHandle.IsInvalid) { int errorCode = Marshal.GetLastWin32Error(); if (Interop.mincore.Errors.ERROR_FILE_NOT_FOUND == errorCode || Interop.mincore.Errors.ERROR_INVALID_NAME == errorCode) return OpenExistingResult.NameNotFound; if (Interop.mincore.Errors.ERROR_PATH_NOT_FOUND == errorCode) return OpenExistingResult.PathNotFound; if (null != name && 0 != name.Length && Interop.mincore.Errors.ERROR_INVALID_HANDLE == errorCode) return OpenExistingResult.NameInvalid; //this is for passed through NativeMethods Errors WinIOError(); } result = new Semaphore(myHandle); return OpenExistingResult.Success; } public int Release() { return Release(1); } // increase the count on a semaphore, returns previous count [SecuritySafeCritical] public int Release(int releaseCount) { if (releaseCount < 1) { throw new ArgumentOutOfRangeException("releaseCount", SR.ArgumentOutOfRange_NeedNonNegNumRequired); } int previousCount; //If ReleaseSempahore returns false when the specified value would cause // the semaphore's count to exceed the maximum count set when Semaphore was created //Non-Zero return if (!ReleaseSemaphore(SafeWaitHandle, releaseCount, out previousCount)) { throw new SemaphoreFullException(); } return previousCount; } internal static void WinIOError() { int errorCode = Marshal.GetLastWin32Error(); WinIOError(errorCode, String.Empty); } internal static void WinIOError(string str) { int errorCode = Marshal.GetLastWin32Error(); WinIOError(errorCode, str); } // After calling GetLastWin32Error(), it clears the last error field, // so you must save the HResult and pass it to this method. This method // will determine the appropriate exception to throw dependent on your // error, and depending on the error, insert a string into the message // gotten from the ResourceManager. internal static void WinIOError(int errorCode, String str) { throw new IOException(GetMessage(errorCode), MakeHRFromErrorCode(errorCode)); } // Use this to translate error codes like the above into HRESULTs like // 0x80070006 for ERROR_INVALID_HANDLE internal static int MakeHRFromErrorCode(int errorCode) { return unchecked(((int)0x80070000) | errorCode); } } }
using System; using System.ComponentModel; using System.Reflection.Emit; using System.Reflection; using System.Threading; using System.Collections.Generic; /* Change history: * 20 Apr 2007 Marc Gravell Renamed */ namespace MediaBrowser.Theater.Interfaces.Reflection { sealed class HyperTypeDescriptor : CustomTypeDescriptor { private readonly PropertyDescriptorCollection propertyCollections; static readonly Dictionary<PropertyInfo, PropertyDescriptor> properties = new Dictionary<PropertyInfo, PropertyDescriptor>(); internal HyperTypeDescriptor(ICustomTypeDescriptor parent) : base(parent) { propertyCollections = WrapProperties(parent.GetProperties()); } public sealed override PropertyDescriptorCollection GetProperties(Attribute[] attributes) { return propertyCollections; } public sealed override PropertyDescriptorCollection GetProperties() { return propertyCollections; } private static PropertyDescriptorCollection WrapProperties(PropertyDescriptorCollection oldProps) { PropertyDescriptor[] newProps = new PropertyDescriptor[oldProps.Count]; int index = 0; bool changed = false; // HACK: how to identify reflection, given that the class is internal... Type wrapMe = Assembly.GetAssembly(typeof(PropertyDescriptor)).GetType("System.ComponentModel.ReflectPropertyDescriptor"); foreach (PropertyDescriptor oldProp in oldProps) { PropertyDescriptor pd = oldProp; // if it looks like reflection, try to create a bespoke descriptor if (ReferenceEquals(wrapMe, pd.GetType()) && TryCreatePropertyDescriptor(ref pd)) { changed = true; } newProps[index++] = pd; } return changed ? new PropertyDescriptorCollection(newProps, true) : oldProps; } static readonly ModuleBuilder moduleBuilder; static int counter; static HyperTypeDescriptor() { AssemblyName an = new AssemblyName("Hyper.ComponentModel.dynamic"); AssemblyBuilder ab = AppDomain.CurrentDomain.DefineDynamicAssembly(an, AssemblyBuilderAccess.Run); moduleBuilder = ab.DefineDynamicModule("Hyper.ComponentModel.dynamic.dll"); } private static bool TryCreatePropertyDescriptor(ref PropertyDescriptor descriptor) { try { PropertyInfo property = descriptor.ComponentType.GetProperty(descriptor.Name); if (property == null) return false; lock (properties) { PropertyDescriptor foundBuiltAlready; if (properties.TryGetValue(property, out foundBuiltAlready)) { descriptor = foundBuiltAlready; return true; } string name = "_c" + Interlocked.Increment(ref counter).ToString(); TypeBuilder tb = moduleBuilder.DefineType(name, TypeAttributes.Sealed | TypeAttributes.NotPublic | TypeAttributes.Class | TypeAttributes.BeforeFieldInit | TypeAttributes.AutoClass | TypeAttributes.Public, typeof(ChainingPropertyDescriptor)); // ctor calls base ConstructorBuilder cb = tb.DefineConstructor(MethodAttributes.HideBySig | MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName, CallingConventions.Standard, new Type[] { typeof(PropertyDescriptor) }); ILGenerator il = cb.GetILGenerator(); il.Emit(OpCodes.Ldarg_0); il.Emit(OpCodes.Ldarg_1); il.Emit(OpCodes.Call, typeof(ChainingPropertyDescriptor).GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, null, new Type[] { typeof(PropertyDescriptor) }, null)); il.Emit(OpCodes.Ret); MethodBuilder mb; MethodInfo baseMethod; if (property.CanRead) { // obtain the implementation that we want to override baseMethod = typeof(ChainingPropertyDescriptor).GetMethod("GetValue"); // create a new method that accepts an object and returns an object (as per the base) mb = tb.DefineMethod(baseMethod.Name, MethodAttributes.HideBySig | MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.Final, baseMethod.CallingConvention, baseMethod.ReturnType, new Type[] { typeof(object) }); // start writing IL into the method il = mb.GetILGenerator(); if (property.DeclaringType.IsValueType) { // upbox the object argument into our known (instance) struct type LocalBuilder lb = il.DeclareLocal(property.DeclaringType); il.Emit(OpCodes.Ldarg_1); il.Emit(OpCodes.Unbox_Any, property.DeclaringType); il.Emit(OpCodes.Stloc_0); il.Emit(OpCodes.Ldloca_S, lb); } else { // cast the object argument into our known class type il.Emit(OpCodes.Ldarg_1); il.Emit(OpCodes.Castclass, property.DeclaringType); } // call the "get" method il.Emit(OpCodes.Callvirt, property.GetGetMethod()); if (property.PropertyType.IsValueType) { // box it from the known (value) struct type il.Emit(OpCodes.Box, property.PropertyType); } // return the value il.Emit(OpCodes.Ret); // signal that this method should override the base tb.DefineMethodOverride(mb, baseMethod); } bool supportsChangeEvents = descriptor.SupportsChangeEvents, isReadOnly = descriptor.IsReadOnly; // override SupportsChangeEvents baseMethod = typeof(ChainingPropertyDescriptor).GetProperty("SupportsChangeEvents").GetGetMethod(); mb = tb.DefineMethod(baseMethod.Name, MethodAttributes.HideBySig | MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.Final | MethodAttributes.SpecialName, baseMethod.CallingConvention, baseMethod.ReturnType, Type.EmptyTypes); il = mb.GetILGenerator(); if (supportsChangeEvents) { il.Emit(OpCodes.Ldc_I4_1); } else { il.Emit(OpCodes.Ldc_I4_0); } il.Emit(OpCodes.Ret); tb.DefineMethodOverride(mb, baseMethod); // override IsReadOnly baseMethod = typeof(ChainingPropertyDescriptor).GetProperty("IsReadOnly").GetGetMethod(); mb = tb.DefineMethod(baseMethod.Name, MethodAttributes.HideBySig | MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.Final | MethodAttributes.SpecialName, baseMethod.CallingConvention, baseMethod.ReturnType, Type.EmptyTypes); il = mb.GetILGenerator(); if (isReadOnly) { il.Emit(OpCodes.Ldc_I4_1); } else { il.Emit(OpCodes.Ldc_I4_0); } il.Emit(OpCodes.Ret); tb.DefineMethodOverride(mb, baseMethod); /* REMOVED: PropertyType, ComponentType; actually *adds* time overriding these // override PropertyType baseMethod = typeof(ChainingPropertyDescriptor).GetProperty("PropertyType").GetGetMethod(); mb = tb.DefineMethod(baseMethod.Name, MethodAttributes.HideBySig | MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.Final | MethodAttributes.SpecialName, baseMethod.CallingConvention, baseMethod.ReturnType, Type.EmptyTypes); il = mb.GetILGenerator(); il.Emit(OpCodes.Ldtoken, descriptor.PropertyType); il.Emit(OpCodes.Call, typeof(Type).GetMethod("GetTypeFromHandle")); il.Emit(OpCodes.Ret); tb.DefineMethodOverride(mb, baseMethod); // override ComponentType baseMethod = typeof(ChainingPropertyDescriptor).GetProperty("ComponentType").GetGetMethod(); mb = tb.DefineMethod(baseMethod.Name, MethodAttributes.HideBySig | MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.Final | MethodAttributes.SpecialName, baseMethod.CallingConvention, baseMethod.ReturnType, Type.EmptyTypes); il = mb.GetILGenerator(); il.Emit(OpCodes.Ldtoken, descriptor.ComponentType); il.Emit(OpCodes.Call, typeof(Type).GetMethod("GetTypeFromHandle")); il.Emit(OpCodes.Ret); tb.DefineMethodOverride(mb, baseMethod); */ // for classes, implement write (would be lost in unbox for structs) if (!property.DeclaringType.IsValueType) { if (!isReadOnly && property.CanWrite) { // override set method baseMethod = typeof(ChainingPropertyDescriptor).GetMethod("SetValue"); mb = tb.DefineMethod(baseMethod.Name, MethodAttributes.HideBySig | MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.Final, baseMethod.CallingConvention, baseMethod.ReturnType, new Type[] { typeof(object), typeof(object) }); il = mb.GetILGenerator(); il.Emit(OpCodes.Ldarg_1); il.Emit(OpCodes.Castclass, property.DeclaringType); il.Emit(OpCodes.Ldarg_2); if (property.PropertyType.IsValueType) { il.Emit(OpCodes.Unbox_Any, property.PropertyType); } else { il.Emit(OpCodes.Castclass, property.PropertyType); } il.Emit(OpCodes.Callvirt, property.GetSetMethod()); il.Emit(OpCodes.Ret); tb.DefineMethodOverride(mb, baseMethod); } if (supportsChangeEvents) { EventInfo ei = property.DeclaringType.GetEvent(property.Name + "Changed"); if (ei != null) { baseMethod = typeof(ChainingPropertyDescriptor).GetMethod("AddValueChanged"); mb = tb.DefineMethod(baseMethod.Name, MethodAttributes.HideBySig | MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.Final | MethodAttributes.SpecialName, baseMethod.CallingConvention, baseMethod.ReturnType, new Type[] { typeof(object), typeof(EventHandler) }); il = mb.GetILGenerator(); il.Emit(OpCodes.Ldarg_1); il.Emit(OpCodes.Castclass, property.DeclaringType); il.Emit(OpCodes.Ldarg_2); il.Emit(OpCodes.Callvirt, ei.GetAddMethod()); il.Emit(OpCodes.Ret); tb.DefineMethodOverride(mb, baseMethod); baseMethod = typeof(ChainingPropertyDescriptor).GetMethod("RemoveValueChanged"); mb = tb.DefineMethod(baseMethod.Name, MethodAttributes.HideBySig | MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.Final | MethodAttributes.SpecialName, baseMethod.CallingConvention, baseMethod.ReturnType, new Type[] { typeof(object), typeof(EventHandler) }); il = mb.GetILGenerator(); il.Emit(OpCodes.Ldarg_1); il.Emit(OpCodes.Castclass, property.DeclaringType); il.Emit(OpCodes.Ldarg_2); il.Emit(OpCodes.Callvirt, ei.GetRemoveMethod()); il.Emit(OpCodes.Ret); tb.DefineMethodOverride(mb, baseMethod); } } } PropertyDescriptor newDesc = tb.CreateType().GetConstructor(new Type[] { typeof(PropertyDescriptor) }).Invoke(new object[] { descriptor }) as PropertyDescriptor; if (newDesc == null) { return false; } descriptor = newDesc; properties.Add(property, descriptor); return true; } } catch { return false; } } } }